text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Apply the rotation represented by the quaternion to the vector <END_TASK> <USER_TASK:> Description: def quaternion_rotation(quat, vector): """Apply the rotation represented by the quaternion to the vector Warning: This only works correctly for normalized quaternions. """
dp = np.dot(quat[1:], vector) cos = (2*quat[0]*quat[0] - 1) return np.array([ 2 * (quat[0] * (quat[2] * vector[2] - quat[3] * vector[1]) + quat[1] * dp) + cos * vector[0], 2 * (quat[0] * (quat[3] * vector[0] - quat[1] * vector[2]) + quat[2] * dp) + cos * vector[1], 2 * (quat[0] * (quat[1] * vector[1] - quat[2] * vector[0]) + quat[3] * dp) + cos * vector[2] ], float)
<SYSTEM_TASK:> Compute the quaternion representing the rotation given by the matrix <END_TASK> <USER_TASK:> Description: def rotation_matrix_to_quaternion(rotation_matrix): """Compute the quaternion representing the rotation given by the matrix"""
invert = (np.linalg.det(rotation_matrix) < 0) if invert: factor = -1 else: factor = 1 c2 = 0.25*(factor*np.trace(rotation_matrix) + 1) if c2 < 0: #print c2 c2 = 0.0 c = np.sqrt(c2) r2 = 0.5*(1 + factor*np.diagonal(rotation_matrix)) - c2 #print "check", r2.sum()+c2 r = np.zeros(3, float) for index, r2_comp in enumerate(r2): if r2_comp < 0: continue else: row, col = off_diagonals[index] if (rotation_matrix[row, col] - rotation_matrix[col, row] < 0): r[index] = -np.sqrt(r2_comp) else: r[index] = +np.sqrt(r2_comp) return factor, np.array([c, r[0], r[1], r[2]], float)
<SYSTEM_TASK:> Compute the rotation matrix representated by the quaternion <END_TASK> <USER_TASK:> Description: def quaternion_to_rotation_matrix(quaternion): """Compute the rotation matrix representated by the quaternion"""
c, x, y, z = quaternion return np.array([ [c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ], [2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ], [2*x*z - 2*c*y, 2*y*z + 2*c*x, c*c - x*x - y*y + z*z] ], float)
<SYSTEM_TASK:> Compute the cosine between two vectors <END_TASK> <USER_TASK:> Description: def cosine(a, b): """Compute the cosine between two vectors The result is clipped within the range [-1, 1] """
result = np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b) return np.clip(result, -1, 1)
<SYSTEM_TASK:> Return a random unit vector of the given dimension <END_TASK> <USER_TASK:> Description: def random_unit(size=3): """Return a random unit vector of the given dimension Optional argument: size -- the number of dimensions of the unit vector [default=3] """
while True: result = np.random.normal(0, 1, size) length = np.linalg.norm(result) if length > 1e-3: return result/length
<SYSTEM_TASK:> Return a random normalized vector orthogonal to the given vector <END_TASK> <USER_TASK:> Description: def random_orthonormal(normal): """Return a random normalized vector orthogonal to the given vector"""
u = normal_fns[np.argmin(np.fabs(normal))](normal) u /= np.linalg.norm(u) v = np.cross(normal, u) v /= np.linalg.norm(v) alpha = np.random.uniform(0.0, np.pi*2) return np.cos(alpha)*u + np.sin(alpha)*v
<SYSTEM_TASK:> Return a vector orthogonal to the given triangle <END_TASK> <USER_TASK:> Description: def triangle_normal(a, b, c): """Return a vector orthogonal to the given triangle Arguments: a, b, c -- three 3D numpy vectors """
normal = np.cross(a - c, b - c) norm = np.linalg.norm(normal) return normal/norm
<SYSTEM_TASK:> Compute the cross product <END_TASK> <USER_TASK:> Description: def cross(r1, r2): """Compute the cross product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Vector3) """
if r1.size != r2.size: raise ValueError("Both arguments must have the same input size.") if r1.deriv != r2.deriv: raise ValueError("Both arguments must have the same deriv.") result = Vector3(r1.size, r1.deriv) result.x = r1.y*r2.z - r1.z*r2.y result.y = r1.z*r2.x - r1.x*r2.z result.z = r1.x*r2.y - r1.y*r2.x return result
<SYSTEM_TASK:> Similar to bond_length, but with a relative vector <END_TASK> <USER_TASK:> Description: def _bond_length_low(r, deriv): """Similar to bond_length, but with a relative vector"""
r = Vector3(3, deriv, r, (0, 1, 2)) d = r.norm() return d.results()
<SYSTEM_TASK:> Similar to opdist, but with relative vectors <END_TASK> <USER_TASK:> Description: def _opdist_low(av, bv, cv, deriv): """Similar to opdist, but with relative vectors"""
a = Vector3(9, deriv, av, (0, 1, 2)) b = Vector3(9, deriv, bv, (3, 4, 5)) c = Vector3(9, deriv, cv, (6, 7, 8)) n = cross(a, b) n /= n.norm() dist = dot(c, n) return dist.results()
<SYSTEM_TASK:> Similar to opbend_cos, but with relative vectors <END_TASK> <USER_TASK:> Description: def _opbend_cos_low(a, b, c, deriv): """Similar to opbend_cos, but with relative vectors"""
a = Vector3(9, deriv, a, (0, 1, 2)) b = Vector3(9, deriv, b, (3, 4, 5)) c = Vector3(9, deriv, c, (6, 7, 8)) n = cross(a,b) n /= n.norm() c /= c.norm() temp = dot(n,c) result = temp.copy() result.v = np.sqrt(1.0-temp.v**2) if result.deriv > 0: result.d *= -temp.v result.d /= result.v if result.deriv > 1: result.dd *= -temp.v result.dd /= result.v temp2 = np.array([temp.d]).transpose()*temp.d temp2 /= result.v**3 result.dd -= temp2 return result.results()
<SYSTEM_TASK:> Convert a cosine and its derivatives to an angle and its derivatives <END_TASK> <USER_TASK:> Description: def _cos_to_angle(result, deriv, sign=1): """Convert a cosine and its derivatives to an angle and its derivatives"""
v = np.arccos(np.clip(result[0], -1, 1)) if deriv == 0: return v*sign, if abs(result[0]) >= 1: factor1 = 0 else: factor1 = -1.0/np.sqrt(1-result[0]**2) d = factor1*result[1] if deriv == 1: return v*sign, d*sign factor2 = result[0]*factor1**3 dd = factor2*np.outer(result[1], result[1]) + factor1*result[2] if deriv == 2: return v*sign, d*sign, dd*sign raise ValueError("deriv must be 0, 1 or 2.")
<SYSTEM_TASK:> Convert a sine and its derivatives to an angle and its derivatives <END_TASK> <USER_TASK:> Description: def _sin_to_angle(result, deriv, side=1): """Convert a sine and its derivatives to an angle and its derivatives"""
v = np.arcsin(np.clip(result[0], -1, 1)) sign = side if sign == -1: if v < 0: offset = -np.pi else: offset = np.pi else: offset = 0.0 if deriv == 0: return v*sign + offset, if abs(result[0]) >= 1: factor1 = 0 else: factor1 = 1.0/np.sqrt(1-result[0]**2) d = factor1*result[1] if deriv == 1: return v*sign + offset, d*sign factor2 = result[0]*factor1**3 dd = factor2*np.outer(result[1], result[1]) + factor1*result[2] if deriv == 2: return v*sign + offset, d*sign, dd*sign raise ValueError("deriv must be 0, 1 or 2.")
<SYSTEM_TASK:> Return the value and optionally derivative and second order derivative <END_TASK> <USER_TASK:> Description: def results(self): """Return the value and optionally derivative and second order derivative"""
if self.deriv == 0: return self.v, if self.deriv == 1: return self.v, self.d if self.deriv == 2: return self.v, self.d, self.dd
<SYSTEM_TASK:> Return a Scalar object with the norm of this vector <END_TASK> <USER_TASK:> Description: def norm(self): """Return a Scalar object with the norm of this vector"""
result = Scalar(self.size, self.deriv) result.v = np.sqrt(self.x.v**2 + self.y.v**2 + self.z.v**2) if self.deriv > 0: result.d += self.x.v*self.x.d result.d += self.y.v*self.y.d result.d += self.z.v*self.z.d result.d /= result.v if self.deriv > 1: result.dd += self.x.v*self.x.dd result.dd += self.y.v*self.y.dd result.dd += self.z.v*self.z.dd denom = result.v**2 result.dd += (1 - self.x.v**2/denom)*np.outer(self.x.d, self.x.d) result.dd += (1 - self.y.v**2/denom)*np.outer(self.y.d, self.y.d) result.dd += (1 - self.z.v**2/denom)*np.outer(self.z.d, self.z.d) tmp = -self.x.v*self.y.v/denom*np.outer(self.x.d, self.y.d) result.dd += tmp+tmp.transpose() tmp = -self.y.v*self.z.v/denom*np.outer(self.y.d, self.z.d) result.dd += tmp+tmp.transpose() tmp = -self.z.v*self.x.v/denom*np.outer(self.z.d, self.x.d) result.dd += tmp+tmp.transpose() result.dd /= result.v return result
<SYSTEM_TASK:> Get a line or raise StopIteration <END_TASK> <USER_TASK:> Description: def _get_line(self): """Get a line or raise StopIteration"""
line = self._f.readline() if len(line) == 0: raise StopIteration return line
<SYSTEM_TASK:> Make a list of internal coordinates based on the graph <END_TASK> <USER_TASK:> Description: def setup_ics(graph): """Make a list of internal coordinates based on the graph Argument: | ``graph`` -- A Graph instance. The list of internal coordinates will include all bond lengths, all bending angles, and all dihedral angles. """
ics = [] # A) Collect all bonds. for i0, i1 in graph.edges: ics.append(BondLength(i0, i1)) # B) Collect all bends. (see b_bending_angles.py for the explanation) for i1 in range(graph.num_vertices): n = list(graph.neighbors[i1]) for index, i0 in enumerate(n): for i2 in n[:index]: ics.append(BendingAngle(i0, i1, i2)) # C) Collect all dihedrals. for i1, i2 in graph.edges: for i0 in graph.neighbors[i1]: if i0==i2: # All four indexes must be different. continue for i3 in graph.neighbors[i2]: if i3==i1 or i3==i0: # All four indexes must be different. continue ics.append(DihedralAngle(i0, i1, i2, i3)) return ics
<SYSTEM_TASK:> Construct a Jacobian for the given internal and Cartesian coordinates <END_TASK> <USER_TASK:> Description: def compute_jacobian(ics, coordinates): """Construct a Jacobian for the given internal and Cartesian coordinates Arguments: | ``ics`` -- A list of internal coordinate objects. | ``coordinates`` -- A numpy array with Cartesian coordinates, shape=(N,3) The return value will be a numpy array with the Jacobian matrix. There will be a column for each internal coordinate, and a row for each Cartesian coordinate (3*N rows). """
N3 = coordinates.size jacobian = numpy.zeros((N3, len(ics)), float) for j, ic in enumerate(ics): # Let the ic object fill in each column of the Jacobian. ic.fill_jacobian_column(jacobian[:,j], coordinates) return jacobian
<SYSTEM_TASK:> Fill in a column of the Jacobian. <END_TASK> <USER_TASK:> Description: def fill_jacobian_column(self, jaccol, coordinates): """Fill in a column of the Jacobian. Arguments: | ``jaccol`` -- The column of Jacobian to which the result must be added. | ``coordinates`` -- A numpy array with Cartesian coordinates, shape=(N,3) """
q, g = self.icfn(coordinates[list(self.indexes)], 1) for i, j in enumerate(self.indexes): jaccol[3*j:3*j+3] += g[i] return jaccol
<SYSTEM_TASK:> Compute the similarity between two molecules based on their descriptors <END_TASK> <USER_TASK:> Description: def compute_similarity(a, b, margin=1.0, cutoff=10.0): """Compute the similarity between two molecules based on their descriptors Arguments: a -- the similarity measure of the first molecule b -- the similarity measure of the second molecule margin -- the sensitivity when comparing distances (default = 1.0) cutoff -- don't compare distances longer than the cutoff (default = 10.0 au) When comparing two distances (always between two atom pairs with identical labels), the folowing formula is used: dav = (distance1+distance2)/2 delta = abs(distance1-distance2) When the delta is within the margin and dav is below the cutoff: (1-dav/cutoff)*(cos(delta/margin/np.pi)+1)/2 and zero otherwise. The returned value is the sum of such terms over all distance pairs with matching atom types. When comparing similarities it might be useful to normalize them in some way, e.g. similarity(a, b)/(similarity(a, a)*similarity(b, b))**0.5 """
return similarity_measure( a.table_labels, a.table_distances, b.table_labels, b.table_distances, margin, cutoff )
<SYSTEM_TASK:> Clear the contents of the data structure <END_TASK> <USER_TASK:> Description: def clear(self): """Clear the contents of the data structure"""
self.title = None self.numbers = np.zeros(0, int) self.atom_types = [] # the atom_types in the second column, used to associate ff parameters self.charges = [] # ff charges self.names = [] # a name that is unique for the molecule composition and connectivity self.molecules = np.zeros(0, int) # a counter for each molecule self.bonds = np.zeros((0, 2), int) self.bends = np.zeros((0, 3), int) self.dihedrals = np.zeros((0, 4), int) self.impropers = np.zeros((0, 4), int) self.name_cache = {}
<SYSTEM_TASK:> Convert a molecular graph into a unique name <END_TASK> <USER_TASK:> Description: def _get_name(self, graph, group=None): """Convert a molecular graph into a unique name This method is not sensitive to the order of the atoms in the graph. """
if group is not None: graph = graph.get_subgraph(group, normalize=True) fingerprint = graph.fingerprint.tobytes() name = self.name_cache.get(fingerprint) if name is None: name = "NM%02i" % len(self.name_cache) self.name_cache[fingerprint] = name return name
<SYSTEM_TASK:> Add the graph of the molecule to the data structure <END_TASK> <USER_TASK:> Description: def add_molecule(self, molecule, atom_types=None, charges=None, split=True): """Add the graph of the molecule to the data structure The molecular graph is estimated from the molecular geometry based on interatomic distances. Argument: | ``molecule`` -- a Molecule instance Optional arguments: | ``atom_types`` -- a list with atom type strings | ``charges`` -- The net atom charges | ``split`` -- When True, the molecule is split into disconnected molecules [default=True] """
molecular_graph = MolecularGraph.from_geometry(molecule) self.add_molecular_graph(molecular_graph, atom_types, charges, split, molecule)
<SYSTEM_TASK:> Add the molecular graph to the data structure <END_TASK> <USER_TASK:> Description: def add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None): """Add the molecular graph to the data structure Argument: | ``molecular_graph`` -- a MolecularGraph instance Optional arguments: | ``atom_types`` -- a list with atom type strings | ``charges`` -- The net atom charges | ``split`` -- When True, the molecule is split into disconnected molecules [default=True] """
# add atom numbers and molecule indices new = len(molecular_graph.numbers) if new == 0: return prev = len(self.numbers) offset = prev self.numbers.resize(prev + new) self.numbers[-new:] = molecular_graph.numbers if atom_types is None: atom_types = [periodic[number].symbol for number in molecular_graph.numbers] self.atom_types.extend(atom_types) if charges is None: charges = [0.0]*len(molecular_graph.numbers) self.charges.extend(charges) self.molecules.resize(prev + new) # add names (autogenerated) if split: groups = molecular_graph.independent_vertices names = [self._get_name(molecular_graph, group) for group in groups] group_indices = np.zeros(new, int) for group_index, group in enumerate(groups): for index in group: group_indices[index] = group_index self.names.extend([names[group_index] for group_index in group_indices]) if prev == 0: self.molecules[:] = group_indices else: self.molecules[-new:] = self.molecules[-new]+group_indices+1 else: if prev == 0: self.molecules[-new:] = 0 else: self.molecules[-new:] = self.molecules[-new]+1 name = self._get_name(molecular_graph) self.names.extend([name]*new) self._add_graph_bonds(molecular_graph, offset, atom_types, molecule) self._add_graph_bends(molecular_graph, offset, atom_types, molecule) self._add_graph_dihedrals(molecular_graph, offset, atom_types, molecule) self._add_graph_impropers(molecular_graph, offset, atom_types, molecule)
<SYSTEM_TASK:> Return a list of groups of atom indexes <END_TASK> <USER_TASK:> Description: def get_groups(self): """Return a list of groups of atom indexes Each atom in a group belongs to the same molecule or residue. """
groups = [] for a_index, m_index in enumerate(self.molecules): if m_index >= len(groups): groups.append([a_index]) else: groups[m_index].append(a_index) return groups
<SYSTEM_TASK:> Select randomly two consecutive bonds that divide the molecule in two <END_TASK> <USER_TASK:> Description: def iter_halfs_bend(graph): """Select randomly two consecutive bonds that divide the molecule in two"""
for atom2 in range(graph.num_vertices): neighbors = list(graph.neighbors[atom2]) for index1, atom1 in enumerate(neighbors): for atom3 in neighbors[index1+1:]: try: affected_atoms = graph.get_halfs(atom2, atom1)[0] # the affected atoms never contain atom1! yield affected_atoms, (atom1, atom2, atom3) continue except GraphError: pass try: affected_atoms = graph.get_halfs(atom2, atom3)[0] # the affected atoms never contain atom3! yield affected_atoms, (atom3, atom2, atom1) except GraphError: pass
<SYSTEM_TASK:> Select two random non-consecutive bonds that divide the molecule in two <END_TASK> <USER_TASK:> Description: def iter_halfs_double(graph): """Select two random non-consecutive bonds that divide the molecule in two"""
edges = graph.edges for index1, (atom_a1, atom_b1) in enumerate(edges): for atom_a2, atom_b2 in edges[:index1]: try: affected_atoms1, affected_atoms2, hinge_atoms = graph.get_halfs_double(atom_a1, atom_b1, atom_a2, atom_b2) yield affected_atoms1, affected_atoms2, hinge_atoms except GraphError: pass
<SYSTEM_TASK:> Check whether all nonbonded atoms are well separated. <END_TASK> <USER_TASK:> Description: def check_nonbond(molecule, thresholds): """Check whether all nonbonded atoms are well separated. If a nonbond atom pair is found that has an interatomic distance below the given thresholds. The thresholds dictionary has the following format: {frozenset([atom_number1, atom_number2]): distance} When random geometries are generated for sampling the conformational space of a molecule without strong repulsive nonbonding interactions, try to underestimate the thresholds at first instance and exclude bond stretches and bending motions for the random manipuulations. Then compute the forces projected on the nonbonding distance gradients. The distance for which the absolute value of these gradients drops below 100 kJ/mol is a coarse guess of a proper threshold value. """
# check that no atoms overlap for atom1 in range(molecule.graph.num_vertices): for atom2 in range(atom1): if molecule.graph.distances[atom1, atom2] > 2: distance = np.linalg.norm(molecule.coordinates[atom1] - molecule.coordinates[atom2]) if distance < thresholds[frozenset([molecule.numbers[atom1], molecule.numbers[atom2]])]: return False return True
<SYSTEM_TASK:> Return a randomized copy of the molecule. <END_TASK> <USER_TASK:> Description: def randomize_molecule(molecule, manipulations, nonbond_thresholds, max_tries=1000): """Return a randomized copy of the molecule. If no randomized molecule can be generated that survives the nonbond check after max_tries repetitions, None is returned. In case of success, the randomized molecule is returned. The original molecule is not altered. """
for m in range(max_tries): random_molecule = randomize_molecule_low(molecule, manipulations) if check_nonbond(random_molecule, nonbond_thresholds): return random_molecule
<SYSTEM_TASK:> Apply a single random manipulation. <END_TASK> <USER_TASK:> Description: def single_random_manipulation(molecule, manipulations, nonbond_thresholds, max_tries=1000): """Apply a single random manipulation. If no randomized molecule can be generated that survives the nonbond check after max_tries repetitions, None is returned. In case of success, the randomized molecule and the corresponding transformation is returned. The original molecule is not altered. """
for m in range(max_tries): random_molecule, transformation = single_random_manipulation_low(molecule, manipulations) if check_nonbond(random_molecule, nonbond_thresholds): return random_molecule, transformation return None
<SYSTEM_TASK:> Create a random dimer. <END_TASK> <USER_TASK:> Description: def random_dimer(molecule0, molecule1, thresholds, shoot_max): """Create a random dimer. molecule0 and molecule1 are placed in one reference frame at random relative positions. Interatomic distances are above the thresholds. Initially a dimer is created where one interatomic distance approximates the threshold value. Then the molecules are given an additional separation in the range [0, shoot_max]. thresholds has the following format: {frozenset([atom_number1, atom_number2]): distance} """
# apply a random rotation to molecule1 center = np.zeros(3, float) angle = np.random.uniform(0, 2*np.pi) axis = random_unit() rotation = Complete.about_axis(center, angle, axis) cor1 = np.dot(molecule1.coordinates, rotation.r) # select a random atom in each molecule atom0 = np.random.randint(len(molecule0.numbers)) atom1 = np.random.randint(len(molecule1.numbers)) # define a translation of molecule1 that brings both atoms in overlap delta = molecule0.coordinates[atom0] - cor1[atom1] cor1 += delta # define a random direction direction = random_unit() cor1 += 1*direction # move molecule1 along this direction until all intermolecular atomic # distances are above the threshold values threshold_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float) distance_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float) for i1, n1 in enumerate(molecule0.numbers): for i2, n2 in enumerate(molecule1.numbers): threshold = thresholds.get(frozenset([n1, n2])) threshold_mat[i1, i2] = threshold**2 while True: cor1 += 0.1*direction distance_mat[:] = 0 for i in 0, 1, 2: distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2 if (distance_mat > threshold_mat).all(): break # translate over a random distance [0, shoot] along the same direction # (if necessary repeat until no overlap is found) while True: cor1 += direction*np.random.uniform(0, shoot_max) distance_mat[:] = 0 for i in 0, 1, 2: distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2 if (distance_mat > threshold_mat).all(): break # done dimer = Molecule( np.concatenate([molecule0.numbers, molecule1.numbers]), np.concatenate([molecule0.coordinates, cor1]) ) dimer.direction = direction dimer.atom0 = atom0 dimer.atom1 = atom1 return dimer
<SYSTEM_TASK:> Apply this distortion to Cartesian coordinates <END_TASK> <USER_TASK:> Description: def apply(self, coordinates): """Apply this distortion to Cartesian coordinates"""
for i in self.affected_atoms: coordinates[i] = self.transformation*coordinates[i]
<SYSTEM_TASK:> Write the object to a file <END_TASK> <USER_TASK:> Description: def write_to_file(self, filename): """Write the object to a file"""
r = self.transformation.r t = self.transformation.t with open(filename, "w") as f: print("# A (random) transformation of a part of a molecule:", file=f) print("# The translation vector is in atomic units.", file=f) print("# Rx Ry Rz T", file=f) print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[0, 0], r[0, 1], r[0, 2], t[0]), file=f) print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[1, 0], r[1, 1], r[1, 2], t[1]), file=f) print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[2, 0], r[2, 1], r[2, 2], t[2]), file=f) print("# The indexes of the affected atoms:", file=f) print(" ".join(str(i) for i in self.affected_atoms), file=f)
<SYSTEM_TASK:> Generate, apply and return a random manipulation <END_TASK> <USER_TASK:> Description: def apply(self, coordinates): """Generate, apply and return a random manipulation"""
transform = self.get_transformation(coordinates) result = MolecularDistortion(self.affected_atoms, transform) result.apply(coordinates) return result
<SYSTEM_TASK:> Iterate over all bins surrounding the given bin <END_TASK> <USER_TASK:> Description: def iter_surrounding(self, center_key): """Iterate over all bins surrounding the given bin"""
for shift in self.neighbor_indexes: key = tuple(np.add(center_key, shift).astype(int)) if self.integer_cell is not None: key = self.wrap_key(key) bin = self._bins.get(key) if bin is not None: yield key, bin
<SYSTEM_TASK:> Translate the key into the central cell <END_TASK> <USER_TASK:> Description: def wrap_key(self, key): """Translate the key into the central cell This method is only applicable in case of a periodic system. """
return tuple(np.round( self.integer_cell.shortest_vector(key) ).astype(int))
<SYSTEM_TASK:> Choose a proper grid for the binning process <END_TASK> <USER_TASK:> Description: def _setup_grid(self, cutoff, unit_cell, grid): """Choose a proper grid for the binning process"""
if grid is None: # automatically choose a decent grid if unit_cell is None: grid = cutoff/2.9 else: # The following would be faster, but it is not reliable # enough yet. #grid = unit_cell.get_optimal_subcell(cutoff/2.0) divisions = np.ceil(unit_cell.spacings/cutoff) divisions[divisions<1] = 1 grid = unit_cell/divisions if isinstance(grid, float): grid_cell = UnitCell(np.array([ [grid, 0, 0], [0, grid, 0], [0, 0, grid] ])) elif isinstance(grid, UnitCell): grid_cell = grid else: raise TypeError("Grid must be None, a float or a UnitCell instance.") if unit_cell is not None: # The columns of integer_matrix are the unit cell vectors in # fractional coordinates of the grid cell. integer_matrix = grid_cell.to_fractional(unit_cell.matrix.transpose()).transpose() if abs((integer_matrix - np.round(integer_matrix))*self.unit_cell.active).max() > 1e-6: raise ValueError("The unit cell vectors are not an integer linear combination of grid cell vectors.") integer_matrix = integer_matrix.round() integer_cell = UnitCell(integer_matrix, unit_cell.active) else: integer_cell = None return grid_cell, integer_cell
<SYSTEM_TASK:> Evaluate a python expression string containing constants <END_TASK> <USER_TASK:> Description: def parse_unit(expression): """Evaluate a python expression string containing constants Argument: | ``expression`` -- A string containing a numerical expressions including unit conversions. In addition to the variables in this module, also the following shorthands are supported: """
try: g = globals() g.update(shorthands) return float(eval(str(expression), g)) except: raise ValueError("Could not interpret '%s' as a unit or a measure." % expression)
<SYSTEM_TASK:> Returns an simple FIFO queue with the ancestors and itself. <END_TASK> <USER_TASK:> Description: def parents(self): """ Returns an simple FIFO queue with the ancestors and itself. """
q = self.__parent__.parents() q.put(self) return q
<SYSTEM_TASK:> Returns the whole URL from the base to this node. <END_TASK> <USER_TASK:> Description: def url(self): """ Returns the whole URL from the base to this node. """
path = None nodes = self.parents() while not nodes.empty(): path = urljoin(path, nodes.get().path()) return path
<SYSTEM_TASK:> If any ancestor required an authentication, this node needs it too. <END_TASK> <USER_TASK:> Description: def auth_required(self): """ If any ancestor required an authentication, this node needs it too. """
if self._auth: return self._auth, self return self.__parent__.auth_required()
<SYSTEM_TASK:> the atomic numbers must match <END_TASK> <USER_TASK:> Description: def _check_graph(self, graph): """the atomic numbers must match"""
if graph.num_vertices != self.size: raise TypeError("The number of vertices in the graph does not " "match the length of the atomic numbers array.") # In practice these are typically the same arrays using the same piece # of memory. Just checking to be sure. if (self.numbers != graph.numbers).any(): raise TypeError("The atomic numbers in the graph do not match the " "atomic numbers in the molecule.")
<SYSTEM_TASK:> Construct a molecule object read from the given file. <END_TASK> <USER_TASK:> Description: def from_file(cls, filename): """Construct a molecule object read from the given file. The file format is inferred from the extensions. Currently supported formats are: ``*.cml``, ``*.fchk``, ``*.pdb``, ``*.sdf``, ``*.xyz`` If a file contains more than one molecule, only the first one is read. Argument: | ``filename`` -- the name of the file containing the molecule Example usage:: >>> mol = Molecule.from_file("foo.xyz") """
# TODO: many different API's to load files. brrr... if filename.endswith(".cml"): from molmod.io import load_cml return load_cml(filename)[0] elif filename.endswith(".fchk"): from molmod.io import FCHKFile fchk = FCHKFile(filename, field_labels=[]) return fchk.molecule elif filename.endswith(".pdb"): from molmod.io import load_pdb return load_pdb(filename) elif filename.endswith(".sdf"): from molmod.io import SDFReader return next(SDFReader(filename)) elif filename.endswith(".xyz"): from molmod.io import XYZReader xyz_reader = XYZReader(filename) title, coordinates = next(xyz_reader) return Molecule(xyz_reader.numbers, coordinates, title, symbols=xyz_reader.symbols) else: raise ValueError("Could not determine file format for %s." % filename)
<SYSTEM_TASK:> the center of mass of the molecule <END_TASK> <USER_TASK:> Description: def com(self): """the center of mass of the molecule"""
return (self.coordinates*self.masses.reshape((-1,1))).sum(axis=0)/self.mass
<SYSTEM_TASK:> the intertia tensor of the molecule <END_TASK> <USER_TASK:> Description: def inertia_tensor(self): """the intertia tensor of the molecule"""
result = np.zeros((3,3), float) for i in range(self.size): r = self.coordinates[i] - self.com # the diagonal term result.ravel()[::4] += self.masses[i]*(r**2).sum() # the outer product term result -= self.masses[i]*np.outer(r,r) return result
<SYSTEM_TASK:> the chemical formula of the molecule <END_TASK> <USER_TASK:> Description: def chemical_formula(self): """the chemical formula of the molecule"""
counts = {} for number in self.numbers: counts[number] = counts.get(number, 0)+1 items = [] for number, count in sorted(counts.items(), reverse=True): if count == 1: items.append(periodic[number].symbol) else: items.append("%s%i" % (periodic[number].symbol, count)) return "".join(items)
<SYSTEM_TASK:> Set self.masses based on self.numbers and periodic table. <END_TASK> <USER_TASK:> Description: def set_default_masses(self): """Set self.masses based on self.numbers and periodic table."""
self.masses = np.array([periodic[n].mass for n in self.numbers])
<SYSTEM_TASK:> Set self.symbols based on self.numbers and the periodic table. <END_TASK> <USER_TASK:> Description: def set_default_symbols(self): """Set self.symbols based on self.numbers and the periodic table."""
self.symbols = tuple(periodic[n].symbol for n in self.numbers)
<SYSTEM_TASK:> Write the molecular geometry to a file. <END_TASK> <USER_TASK:> Description: def write_to_file(self, filename): """Write the molecular geometry to a file. The file format is inferred from the extensions. Currently supported formats are: ``*.xyz``, ``*.cml`` Argument: | ``filename`` -- a filename """
# TODO: give all file format writers the same API if filename.endswith('.cml'): from molmod.io import dump_cml dump_cml(filename, [self]) elif filename.endswith('.xyz'): from molmod.io import XYZWriter symbols = [] for n in self.numbers: atom = periodic[n] if atom is None: symbols.append("X") else: symbols.append(atom.symbol) xyz_writer = XYZWriter(filename, symbols) xyz_writer.dump(self.title, self.coordinates) del xyz_writer else: raise ValueError("Could not determine file format for %s." % filename)
<SYSTEM_TASK:> Compute the RMSD between two molecules. <END_TASK> <USER_TASK:> Description: def rmsd(self, other): """Compute the RMSD between two molecules. Arguments: | ``other`` -- Another molecule with the same atom numbers Return values: | ``transformation`` -- the transformation that brings 'self' into overlap with 'other' | ``other_trans`` -- the transformed coordinates of geometry 'other' | ``rmsd`` -- the rmsd of the distances between corresponding atoms in 'self' and 'other' Make sure the atoms in `self` and `other` are in the same order. Usage:: >>> print molecule1.rmsd(molecule2)[2]/angstrom """
if self.numbers.shape != other.numbers.shape or \ (self.numbers != other.numbers).all(): raise ValueError("The other molecule does not have the same numbers as this molecule.") return fit_rmsd(self.coordinates, other.coordinates)
<SYSTEM_TASK:> Compute the rotational symmetry number. <END_TASK> <USER_TASK:> Description: def compute_rotsym(self, threshold=1e-3*angstrom): """Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself. """
# Generate a graph with a more permissive threshold for bond lengths: # (is convenient in case of transition state geometries) graph = MolecularGraph.from_geometry(self, scaling=1.5) try: return compute_rotsym(self, graph, threshold) except ValueError: raise ValueError("The rotational symmetry number can only be computed when the graph is fully connected.")
<SYSTEM_TASK:> Get the label from the last line read <END_TASK> <USER_TASK:> Description: def _get_current_label(self): """Get the label from the last line read"""
if len(self._last) == 0: raise StopIteration return self._last[:self._last.find(":")]
<SYSTEM_TASK:> Read and return an entire section <END_TASK> <USER_TASK:> Description: def _read_section(self): """Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]] self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: lines.append(self._last) self._last = self._f.readline() return lines
<SYSTEM_TASK:> Get the next section with the given label <END_TASK> <USER_TASK:> Description: def get_next(self, label): """Get the next section with the given label"""
while self._get_current_label() != label: self._skip_section() return self._read_section()
<SYSTEM_TASK:> Add a child section or keyword <END_TASK> <USER_TASK:> Description: def append(self, child): """Add a child section or keyword"""
if not (isinstance(child, CP2KSection) or isinstance(child, CP2KKeyword)): raise TypeError("The child must be a CP2KSection or a CP2KKeyword, got: %s." % child) l = self.__index.setdefault(child.name, []) l.append(child) self.__order.append(child)
<SYSTEM_TASK:> Dump the children of the current section to a file-like object <END_TASK> <USER_TASK:> Description: def dump_children(self, f, indent=''): """Dump the children of the current section to a file-like object"""
for child in self.__order: child.dump(f, indent+' ')
<SYSTEM_TASK:> Dump this section and its children to a file-like object <END_TASK> <USER_TASK:> Description: def dump(self, f, indent=''): """Dump this section and its children to a file-like object"""
print(("%s&%s %s" % (indent, self.__name, self.section_parameters)).rstrip(), file=f) self.dump_children(f, indent) print("%s&END %s" % (indent, self.__name), file=f)
<SYSTEM_TASK:> A helper method that only reads uncommented lines <END_TASK> <USER_TASK:> Description: def readline(self, f): """A helper method that only reads uncommented lines"""
while True: line = f.readline() if len(line) == 0: raise EOFError line = line[:line.find('#')] line = line.strip() if len(line) > 0: return line
<SYSTEM_TASK:> Load the children of this section from a file-like object <END_TASK> <USER_TASK:> Description: def load_children(self, f): """Load the children of this section from a file-like object"""
while True: line = self.readline(f) if line[0] == '&': if line[1:].startswith("END"): check_name = line[4:].strip().upper() if check_name != self.__name: raise FileFormatError("CP2KSection end mismatch, pos=%s", f.tell()) break else: section = CP2KSection() section.load(f, line) self.append(section) else: keyword = CP2KKeyword() keyword.load(line) self.append(keyword)
<SYSTEM_TASK:> Load this section from a file-like object <END_TASK> <USER_TASK:> Description: def load(self, f, line=None): """Load this section from a file-like object"""
if line is None: # in case the file contains only a fragment of an input file, # this is useful. line = f.readlin() words = line[1:].split() self.__name = words[0].upper() self.section_parameters = " ".join(words[1:]) try: self.load_children(f) except EOFError: raise FileFormatError("Unexpected end of file, section '%s' not ended." % self.__name)
<SYSTEM_TASK:> Dump this keyword to a file-like object <END_TASK> <USER_TASK:> Description: def dump(self, f, indent=''): """Dump this keyword to a file-like object"""
if self.__unit is None: print(("%s%s %s" % (indent, self.__name, self.__value)).rstrip(), file=f) else: print(("%s%s [%s] %s" % (indent, self.__name, self.__unit, self.__value)).rstrip(), file=f)
<SYSTEM_TASK:> Load this keyword from a file-like object <END_TASK> <USER_TASK:> Description: def load(self, line): """Load this keyword from a file-like object"""
words = line.split() try: float(words[0]) self.__name = "" self.__value = " ".join(words) except ValueError: self.__name = words[0].upper() if len(words) > 2 and words[1][0]=="[" and words[1][-1]=="]": self.unit = words[1][1:-1] self.__value = " ".join(words[2:]) else: self.__value = " ".join(words[1:])
<SYSTEM_TASK:> Set the value associated with the keyword <END_TASK> <USER_TASK:> Description: def set_value(self, value): """Set the value associated with the keyword"""
if not isinstance(value, str): raise TypeError("A value must be a string, got %s." % value) self.__value = value
<SYSTEM_TASK:> Check the sanity of the given 4x4 transformation matrix <END_TASK> <USER_TASK:> Description: def check_matrix(m): """Check the sanity of the given 4x4 transformation matrix"""
if m.shape != (4, 4): raise ValueError("The argument must be a 4x4 array.") if max(abs(m[3, 0:3])) > eps: raise ValueError("The given matrix does not have correct translational part") if abs(m[3, 3] - 1.0) > eps: raise ValueError("The lower right element of the given matrix must be 1.0.")
<SYSTEM_TASK:> Compute the transformation that minimizes the RMSD between the points ras and rbs <END_TASK> <USER_TASK:> Description: def superpose(ras, rbs, weights=None): """Compute the transformation that minimizes the RMSD between the points ras and rbs Arguments: | ``ras`` -- a ``np.array`` with 3D coordinates of geometry A, shape=(N,3) | ``rbs`` -- a ``np.array`` with 3D coordinates of geometry B, shape=(N,3) Optional arguments: | ``weights`` -- a numpy array with fitting weights for each coordinate, shape=(N,) Return value: | ``transformation`` -- the transformation that brings geometry A into overlap with geometry B Each row in ras and rbs represents a 3D coordinate. Corresponding rows contain the points that are brought into overlap by the fitting procedure. The implementation is based on the Kabsch Algorithm: http://dx.doi.org/10.1107%2FS0567739476001873 """
if weights is None: ma = ras.mean(axis=0) mb = rbs.mean(axis=0) else: total_weight = weights.sum() ma = np.dot(weights, ras)/total_weight mb = np.dot(weights, rbs)/total_weight # Kabsch if weights is None: A = np.dot((rbs-mb).transpose(), ras-ma) else: weights = weights.reshape((-1, 1)) A = np.dot(((rbs-mb)*weights).transpose(), (ras-ma)*weights) v, s, wt = np.linalg.svd(A) s[:] = 1 if np.linalg.det(np.dot(v, wt)) < 0: s[2] = -1 r = np.dot(wt.T*s, v.T) return Complete(r, np.dot(r, -mb) + ma)
<SYSTEM_TASK:> Fit geometry rbs onto ras, returns more info than superpose <END_TASK> <USER_TASK:> Description: def fit_rmsd(ras, rbs, weights=None): """Fit geometry rbs onto ras, returns more info than superpose Arguments: | ``ras`` -- a numpy array with 3D coordinates of geometry A, shape=(N,3) | ``rbs`` -- a numpy array with 3D coordinates of geometry B, shape=(N,3) Optional arguments: | ``weights`` -- a numpy array with fitting weights for each coordinate, shape=(N,) Return values: | ``transformation`` -- the transformation that brings geometry A into overlap with geometry B | ``rbs_trans`` -- the transformed coordinates of geometry B | ``rmsd`` -- the rmsd of the distances between corresponding atoms in geometry A and B This is a utility routine based on the function superpose. It just computes rbs_trans and rmsd after calling superpose with the same arguments """
transformation = superpose(ras, rbs, weights) rbs_trans = transformation * rbs rmsd = compute_rmsd(ras, rbs_trans) return transformation, rbs_trans, rmsd
<SYSTEM_TASK:> Apply this translation to the given object <END_TASK> <USER_TASK:> Description: def apply_to(self, x, columns=False): """Apply this translation to the given object The argument can be several sorts of objects: * ``np.array`` with shape (3, ) * ``np.array`` with shape (N, 3) * ``np.array`` with shape (3, N), use ``columns=True`` * ``Translation`` * ``Rotation`` * ``Complete`` * ``UnitCell`` In case of arrays, the 3D vectors are translated. In case of trans- formations, a new transformation is returned that consists of this translation applied AFTER the given translation. In case of a unit cell, the original object is returned. This method is equivalent to ``self*x``. """
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns: return x + self.t.reshape((3,1)) if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns: return x + self.t elif isinstance(x, Complete): return Complete(x.r, x.t + self.t) elif isinstance(x, Translation): return Translation(x.t + self.t) elif isinstance(x, Rotation): return Complete(x.r, self.t) elif isinstance(x, UnitCell): return x else: raise ValueError("Can not apply this translation to %s" % x)
<SYSTEM_TASK:> Compare two translations <END_TASK> <USER_TASK:> Description: def compare(self, other, t_threshold=1e-3): """Compare two translations The RMSD of the translation vectors is computed. The return value is True when the RMSD is below the threshold, i.e. when the two translations are almost identical. """
return compute_rmsd(self.t, other.t) < t_threshold
<SYSTEM_TASK:> the columns must orthogonal <END_TASK> <USER_TASK:> Description: def _check_r(self, r): """the columns must orthogonal"""
if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \ abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \ abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \ np.dot(r[:, 0], r[:, 1]) > eps or \ np.dot(r[:, 1], r[:, 2]) > eps or \ np.dot(r[:, 2], r[:, 0]) > eps: raise ValueError("The rotation matrix is significantly non-orthonormal.")
<SYSTEM_TASK:> Initialize a rotation based on the properties <END_TASK> <USER_TASK:> Description: def from_properties(cls, angle, axis, invert): """Initialize a rotation based on the properties"""
norm = np.linalg.norm(axis) if norm > 0: x = axis[0] / norm y = axis[1] / norm z = axis[2] / norm c = np.cos(angle) s = np.sin(angle) r = (1-2*invert) * np.array([ [x*x*(1-c)+c , x*y*(1-c)-z*s, x*z*(1-c)+y*s], [x*y*(1-c)+z*s, y*y*(1-c)+c , y*z*(1-c)-x*s], [x*z*(1-c)-y*s, y*z*(1-c)+x*s, z*z*(1-c)+c ] ]) else: r = np.identity(3) * (1-2*invert) return cls(r)
<SYSTEM_TASK:> The 4x4 matrix representation of this rotation <END_TASK> <USER_TASK:> Description: def matrix(self): """The 4x4 matrix representation of this rotation"""
result = np.identity(4, float) result[0:3, 0:3] = self.r return result
<SYSTEM_TASK:> Apply this rotation to the given object <END_TASK> <USER_TASK:> Description: def apply_to(self, x, columns=False): """Apply this rotation to the given object The argument can be several sorts of objects: * ``np.array`` with shape (3, ) * ``np.array`` with shape (N, 3) * ``np.array`` with shape (3, N), use ``columns=True`` * ``Translation`` * ``Rotation`` * ``Complete`` * ``UnitCell`` In case of arrays, the 3D vectors are rotated. In case of trans- formations, a transformation is returned that consists of this rotation applied AFTER the given translation. In case of a unit cell, a unit cell with rotated cell vectors is returned. This method is equivalent to ``self*x``. """
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns: return np.dot(self.r, x) if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns: return np.dot(x, self.r.transpose()) elif isinstance(x, Complete): return Complete(np.dot(self.r, x.r), np.dot(self.r, x.t)) elif isinstance(x, Translation): return Complete(self.r, np.dot(self.r, x.t)) elif isinstance(x, Rotation): return Rotation(np.dot(self.r, x.r)) elif isinstance(x, UnitCell): return UnitCell(np.dot(self.r, x.matrix), x.active) else: raise ValueError("Can not apply this rotation to %s" % x)
<SYSTEM_TASK:> Compare two rotations <END_TASK> <USER_TASK:> Description: def compare(self, other, r_threshold=1e-3): """Compare two rotations The RMSD of the rotation matrices is computed. The return value is True when the RMSD is below the threshold, i.e. when the two rotations are almost identical. """
return compute_rmsd(self.r, other.r) < r_threshold
<SYSTEM_TASK:> Initialize a transformation based on the properties <END_TASK> <USER_TASK:> Description: def from_properties(cls, angle, axis, invert, translation): """Initialize a transformation based on the properties"""
rot = Rotation.from_properties(angle, axis, invert) return Complete(rot.r, translation)
<SYSTEM_TASK:> Convert the first argument into a Complete object <END_TASK> <USER_TASK:> Description: def cast(cls, c): """Convert the first argument into a Complete object"""
if isinstance(c, Complete): return c elif isinstance(c, Translation): return Complete(np.identity(3, float), c.t) elif isinstance(c, Rotation): return Complete(c.r, np.zeros(3, float))
<SYSTEM_TASK:> Create transformation that represents a rotation about an axis <END_TASK> <USER_TASK:> Description: def about_axis(cls, center, angle, axis, invert=False): """Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- When True, an inversion rotation is constructed [default=False] """
return Translation(center) * \ Rotation.from_properties(angle, axis, invert) * \ Translation(-center)
<SYSTEM_TASK:> Compare two transformations <END_TASK> <USER_TASK:> Description: def compare(self, other, t_threshold=1e-3, r_threshold=1e-3): """Compare two transformations The RMSD values of the rotation matrices and the translation vectors are computed. The return value is True when the RMSD values are below the thresholds, i.e. when the two transformations are almost identical. """
return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold
<SYSTEM_TASK:> Skip the next time frame <END_TASK> <USER_TASK:> Description: def _skip_frame(self): """Skip the next time frame"""
for line in self._f: if line == 'ITEM: ATOMS\n': break for i in range(self.num_atoms): next(self._f)
<SYSTEM_TASK:> Add an atom info object to the database <END_TASK> <USER_TASK:> Description: def _add_atom_info(self, atom_info): """Add an atom info object to the database"""
self.atoms_by_number[atom_info.number] = atom_info self.atoms_by_symbol[atom_info.symbol.lower()] = atom_info
<SYSTEM_TASK:> Extend the current cluster with data from another cluster <END_TASK> <USER_TASK:> Description: def update(self, other): """Extend the current cluster with data from another cluster"""
Cluster.update(self, other) self.rules.extend(other.rules)
<SYSTEM_TASK:> Add related items <END_TASK> <USER_TASK:> Description: def add_related(self, *objects): """Add related items The arguments can be individual items or cluster objects containing several items. When two groups of related items share one or more common members, they will be merged into one cluster. """
master = None # this will become the common cluster of all related items slaves = set([]) # set of clusters that are going to be merged in the master solitaire = set([]) # set of new items that are not yet part of a cluster for new in objects: if isinstance(new, self.cls): if master is None: master = new else: slaves.add(new) for item in new.items: existing = self.lookup.get(item) if existing is not None: slaves.add(existing) else: cluster = self.lookup.get(new) if cluster is None: #print "solitaire", new solitaire.add(new) elif master is None: #print "starting master", new master = cluster elif master != cluster: #print "in slave", new slaves.add(cluster) #else: ##nothing to do #print "new in master", new if master is None: master = self.cls([]) for slave in slaves: master.update(slave) for item in solitaire: master.add_item(item) for item in master.items: self.lookup[item] = master
<SYSTEM_TASK:> Continue reading until the next frame is reached <END_TASK> <USER_TASK:> Description: def goto_next_frame(self): """Continue reading until the next frame is reached"""
marked = False while True: line = next(self._f)[:-1] if marked and len(line) > 0 and not line.startswith(" --------"): try: step = int(line[:10]) return step, line except ValueError: pass marked = (len(line) == 131 and line == self._marker)
<SYSTEM_TASK:> Read a frame from the XYZ file <END_TASK> <USER_TASK:> Description: def _read_frame(self): """Read a frame from the XYZ file"""
size = self.read_size() title = self._f.readline()[:-1] if self.symbols is None: symbols = [] coordinates = np.zeros((size, 3), float) for counter in range(size): line = self._f.readline() if len(line) == 0: raise StopIteration words = line.split() if len(words) < 4: raise StopIteration if self.symbols is None: symbols.append(words[0]) try: coordinates[counter, 0] = float(words[1]) coordinates[counter, 1] = float(words[2]) coordinates[counter, 2] = float(words[3]) except ValueError: raise StopIteration coordinates *= self.file_unit if self.symbols is None: self.symbols = symbols return title, coordinates
<SYSTEM_TASK:> Skip a single frame from the trajectory <END_TASK> <USER_TASK:> Description: def _skip_frame(self): """Skip a single frame from the trajectory"""
size = self.read_size() for i in range(size+1): line = self._f.readline() if len(line) == 0: raise StopIteration
<SYSTEM_TASK:> Get the first molecule from the trajectory <END_TASK> <USER_TASK:> Description: def get_first_molecule(self): """Get the first molecule from the trajectory This can be useful to configure your program before handeling the actual trajectory. """
title, coordinates = self._first molecule = Molecule(self.numbers, coordinates, title, symbols=self.symbols) return molecule
<SYSTEM_TASK:> Dump a frame to the trajectory file <END_TASK> <USER_TASK:> Description: def dump(self, title, coordinates): """Dump a frame to the trajectory file Arguments: | ``title`` -- the title of the frame | ``coordinates`` -- a numpy array with coordinates in atomic units """
print("% 8i" % len(self.symbols), file=self._f) print(str(title), file=self._f) for symbol, coordinate in zip(self.symbols, coordinates): print("% 2s % 12.9f % 12.9f % 12.9f" % ((symbol, ) + tuple(coordinate/self.file_unit)), file=self._f)
<SYSTEM_TASK:> Get a molecule from the trajectory <END_TASK> <USER_TASK:> Description: def get_molecule(self, index=0): """Get a molecule from the trajectory Optional argument: | ``index`` -- The frame index [default=0] """
return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols)
<SYSTEM_TASK:> Write the trajectory to a file <END_TASK> <USER_TASK:> Description: def write_to_file(self, f, file_unit=angstrom): """Write the trajectory to a file Argument: | ``f`` -- a filename or a file-like object to write to Optional argument: | ``file_unit`` -- the unit of the values written to file [default=angstrom] """
xyz_writer = XYZWriter(f, self.symbols, file_unit=file_unit) for title, coordinates in zip(self.titles, self.geometries): xyz_writer.dump(title, coordinates)
<SYSTEM_TASK:> Check the analytical gradient using finite differences <END_TASK> <USER_TASK:> Description: def check_anagrad(fun, x0, epsilon, threshold): """Check the analytical gradient using finite differences Arguments: | ``fun`` -- the function to be tested, more info below | ``x0`` -- the reference point around which the function should be tested | ``epsilon`` -- a small scalar used for the finite differences | ``threshold`` -- the maximum acceptable difference between the analytical gradient and the gradient obtained by finite differentiation The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- the arguments of the function to be tested | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned [default=False] """
N = len(x0) f0, ana_grad = fun(x0, do_gradient=True) for i in range(N): xh = x0.copy() xh[i] += 0.5*epsilon xl = x0.copy() xl[i] -= 0.5*epsilon num_grad_comp = (fun(xh)-fun(xl))/epsilon if abs(num_grad_comp - ana_grad[i]) > threshold: raise AssertionError("Error in the analytical gradient, component %i, got %s, should be about %s" % (i, ana_grad[i], num_grad_comp))
<SYSTEM_TASK:> Check the difference between two function values using the analytical gradient <END_TASK> <USER_TASK:> Description: def check_delta(fun, x, dxs, period=None): """Check the difference between two function values using the analytical gradient Arguments: | ``fun`` -- The function to be tested, more info below. | ``x`` -- The argument vector. | ``dxs`` -- A matrix where each row is a vector of small differences to be added to the argument vector. Optional argument: | ``period`` -- If the function value is periodic, one may provide the period such that differences are computed using periodic boundary conditions. The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- The arguments of the function to be tested. | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned. [default=False] For every row in dxs, the following computation is repeated: 1) D1 = 'f(x+dx) - f(x)' is computed. 2) D2 = '0.5 (grad f(x+dx) + grad f(x)) . dx' is computed. A threshold is set to the median of the D1 set. For each case where |D1| is larger than the threshold, |D1 - D2|, should be smaller than the threshold. """
dn1s = [] dn2s = [] dnds = [] for dx in dxs: f0, grad0 = fun(x, do_gradient=True) f1, grad1 = fun(x+dx, do_gradient=True) grad = 0.5*(grad0+grad1) d1 = f1 - f0 if period is not None: d1 -= np.floor(d1/period + 0.5)*period if hasattr(d1, '__iter__'): norm = np.linalg.norm else: norm = abs d2 = np.dot(grad, dx) dn1s.append(norm(d1)) dn2s.append(norm(d2)) dnds.append(norm(d1-d2)) dn1s = np.array(dn1s) dn2s = np.array(dn2s) dnds = np.array(dnds) # Get the threshold (and mask) threshold = np.median(dn1s) mask = dn1s > threshold # Make sure that all cases for which dn1 is above the treshold, dnd is below # the threshold if not (dnds[mask] < threshold).all(): raise AssertionError(( 'The first order approximation on the difference is too wrong. The ' 'threshold is %.1e.\n\nDifferences:\n%s\n\nFirst order ' 'approximation to differences:\n%s\n\nAbsolute errors:\n%s') % (threshold, ' '.join('%.1e' % v for v in dn1s[mask]), ' '.join('%.1e' % v for v in dn2s[mask]), ' '.join('%.1e' % v for v in dnds[mask]) ))
<SYSTEM_TASK:> Compute the Hessian using the finite difference method <END_TASK> <USER_TASK:> Description: def compute_fd_hessian(fun, x0, epsilon, anagrad=True): """Compute the Hessian using the finite difference method Arguments: | ``fun`` -- the function for which the Hessian should be computed, more info below | ``x0`` -- the point at which the Hessian must be computed | ``epsilon`` -- a small scalar step size used to compute the finite differences Optional argument: | ``anagrad`` -- when True, analytical gradients are used [default=True] The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- the arguments of the function to be tested | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned [default=False] """
N = len(x0) def compute_gradient(x): if anagrad: return fun(x, do_gradient=True)[1] else: gradient = np.zeros(N, float) for i in range(N): xh = x.copy() xh[i] += 0.5*epsilon xl = x.copy() xl[i] -= 0.5*epsilon gradient[i] = (fun(xh)-fun(xl))/epsilon return gradient hessian = np.zeros((N,N), float) for i in range(N): xh = x0.copy() xh[i] += 0.5*epsilon xl = x0.copy() xl[i] -= 0.5*epsilon hessian[i] = (compute_gradient(xh) - compute_gradient(xl))/epsilon return 0.5*(hessian + hessian.transpose())
<SYSTEM_TASK:> Clip the a step within the maximum allowed range <END_TASK> <USER_TASK:> Description: def limit_step(self, step): """Clip the a step within the maximum allowed range"""
if self.qmax is None: return step else: return np.clip(step, -self.qmax, self.qmax)
<SYSTEM_TASK:> Find a bracket that does contain the minimum <END_TASK> <USER_TASK:> Description: def _bracket(self, qinit, f0, fun): """Find a bracket that does contain the minimum"""
self.num_bracket = 0 qa = qinit fa = fun(qa) counter = 0 if fa >= f0: while True: self.num_bracket += 1 #print " bracket shrink" qb, fb = qa, fa qa /= 1+phi fa = fun(qa) if qa < self.qtol: return if fa < f0: return (0, f0), (qa, fa), (qb, fb) counter += 1 if self.max_iter is not None and counter > self.max_iter: return else: self.num_bracket += 1 #print " bracket grow1" qb, fb = qa, fa qa *= (1+phi) fa = fun(qa) if fa >= fb: return (0, f0), (qb, fb), (qa, fa) while True: self.num_bracket += 1 #print " bracket grow2" qc, fc = qb, fb qb, fb = qa, fa qa = qb*(1+phi) - qc fa = fun(qa) if fa >= fb: return (qc, fc), (qb, fb), (qa, fa) counter += 1 if self.max_iter is not None and counter > self.max_iter: return
<SYSTEM_TASK:> Reduce the size of the bracket until the minimum is found <END_TASK> <USER_TASK:> Description: def _golden(self, triplet, fun): """Reduce the size of the bracket until the minimum is found"""
self.num_golden = 0 (qa, fa), (qb, fb), (qc, fc) = triplet while True: self.num_golden += 1 qd = qa + (qb-qa)*phi/(1+phi) fd = fun(qd) if fd < fb: #print "golden d" (qa, fa), (qb, fb) = (qb, fb), (qd, fd) else: #print "golden b" (qa, fa), (qc, fc) = (qd, fd), (qa, fa) if abs(qa-qb) < self.qtol: return qc, fc
<SYSTEM_TASK:> Transform the unknowns to preconditioned coordinates <END_TASK> <USER_TASK:> Description: def do(self, x_orig): """Transform the unknowns to preconditioned coordinates This method also transforms the gradient to original coordinates """
if self.scales is None: return x_orig else: return np.dot(self.rotation.transpose(), x_orig)*self.scales
<SYSTEM_TASK:> Transform the unknowns to original coordinates <END_TASK> <USER_TASK:> Description: def undo(self, x_prec): """Transform the unknowns to original coordinates This method also transforms the gradient to preconditioned coordinates """
if self.scales is None: return x_prec else: return np.dot(self.rotation, x_prec/self.scales)
<SYSTEM_TASK:> Returns the header for screen logging of the minimization <END_TASK> <USER_TASK:> Description: def get_header(self): """Returns the header for screen logging of the minimization"""
result = " " if self.step_rms is not None: result += " Step RMS" if self.step_max is not None: result += " Step MAX" if self.grad_rms is not None: result += " Grad RMS" if self.grad_max is not None: result += " Grad MAX" if self.rel_grad_rms is not None: result += " Grad/F RMS" if self.rel_grad_max is not None: result += " Grad/F MAX" return result
<SYSTEM_TASK:> Configure the 1D function for a line search <END_TASK> <USER_TASK:> Description: def configure(self, x0, axis): """Configure the 1D function for a line search Arguments: x0 -- the reference point (q=0) axis -- a unit vector in the direction of the line search """
self.x0 = x0 self.axis = axis
<SYSTEM_TASK:> Return the final solution in the original coordinates <END_TASK> <USER_TASK:> Description: def get_final(self): """Return the final solution in the original coordinates"""
if self.prec is None: return self.x else: return self.prec.undo(self.x)
<SYSTEM_TASK:> Print the header for screen logging <END_TASK> <USER_TASK:> Description: def _print_header(self): """Print the header for screen logging"""
header = " Iter Dir " if self.constraints is not None: header += ' SC CC' header += " Function" if self.convergence_condition is not None: header += self.convergence_condition.get_header() header += " Time" self._screen("-"*(len(header)), newline=True) self._screen(header, newline=True) self._screen("-"*(len(header)), newline=True)