Search is not available for this dataset
text
stringlengths
75
104k
def _get_extra(self, attrs, exclude): """Read the extra properties, taking into account an exclude list""" result = {} for key in attrs.getNames(): if key not in exclude: result[str(key)] = str(attrs[key]) return result
def _read(self, filename, field_labels=None): """Read all the requested fields Arguments: | ``filename`` -- the filename of the FCHK file | ``field_labels`` -- when given, only these fields are read """ # if fields is None, all fields are read def read_field(f): """Read a single field""" datatype = None while datatype is None: # find a sane header line line = f.readline() if line == "": return False label = line[:43].strip() if field_labels is not None: if len(field_labels) == 0: return False elif label not in field_labels: return True else: field_labels.discard(label) line = line[43:] words = line.split() if len(words) == 0: return True if words[0] == 'I': datatype = int unreadable = 0 elif words[0] == 'R': datatype = float unreadable = np.nan if len(words) == 2: try: value = datatype(words[1]) except ValueError: return True elif len(words) == 3: if words[1] != "N=": raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1])) length = int(words[2]) value = np.zeros(length, datatype) counter = 0 try: while counter < length: line = f.readline() if line == "": raise FileFormatError("Unexpected end of formatted checkpoint file %s" % filename) for word in line.split(): try: value[counter] = datatype(word) except (ValueError, OverflowError) as e: print('WARNING: could not interpret word while reading %s: %s' % (word, self.filename)) if self.ignore_errors: value[counter] = unreadable else: raise counter += 1 except ValueError: return True else: raise FileFormatError("Unexpected line in formatted checkpoint file %s\n%s" % (filename, line[:-1])) self.fields[label] = value return True self.fields = {} with open(filename, 'r') as f: self.title = f.readline()[:-1].strip() words = f.readline().split() if len(words) == 3: self.command, self.lot, self.basis = words elif len(words) == 2: self.command, self.lot = words else: raise FileFormatError('The second line of the FCHK file should contain two or three words.') while read_field(f): pass
def _analyze(self): """Convert a few elementary fields into a molecule object""" if ("Atomic numbers" in self.fields) and ("Current cartesian coordinates" in self.fields): self.molecule = Molecule( self.fields["Atomic numbers"], np.reshape(self.fields["Current cartesian coordinates"], (-1, 3)), self.title, )
def get_optimization_coordinates(self): """Return the coordinates of the geometries at each point in the optimization""" coor_array = self.fields.get("Opt point 1 Geometries") if coor_array is None: return [] else: return np.reshape(coor_array, (-1, len(self.molecule.numbers), 3))
def get_optimized_molecule(self): """Return a molecule object of the optimal geometry""" opt_coor = self.get_optimization_coordinates() if len(opt_coor) == 0: return None else: return Molecule( self.molecule.numbers, opt_coor[-1], )
def get_optimization_gradients(self): """Return the energy gradients of all geometries during an optimization""" grad_array = self.fields.get("Opt point 1 Gradient at each geome") if grad_array is None: return [] else: return np.reshape(grad_array, (-1, len(self.molecule.numbers), 3))
def get_hessian(self): """Return the hessian""" force_const = self.fields.get("Cartesian Force Constants") if force_const is None: return None N = len(self.molecule.numbers) result = np.zeros((3*N, 3*N), float) counter = 0 for row in range(3*N): result[row, :row+1] = force_const[counter:counter+row+1] result[:row+1, row] = force_const[counter:counter+row+1] counter += row + 1 return result
def copy_with(self, **kwargs): """Return a copy with (a few) changed attributes The keyword arguments are the attributes to be replaced by new values. All other attributes are copied (or referenced) from the original object. This only works if the constructor takes all (read-only) attributes as arguments. """ attrs = {} for key, descriptor in self.__class__.__dict__.items(): if isinstance(descriptor, ReadOnlyAttribute): attrs[key] = descriptor.__get__(self) for key in kwargs: if key not in attrs: raise TypeError("Unknown attribute: %s" % key) attrs.update(kwargs) return self.__class__(**attrs)
def _read(self, filename): """Internal routine that reads all data from the punch file.""" data = {} parsers = [ FirstDataParser(), CoordinateParser(), EnergyGradParser(), SkipApproxHessian(), HessianParser(), MassParser(), ] with open(filename) as f: while True: line = f.readline() if line == "": break # at each line, a parsers checks if it has to process a piece of # file. If that happens, the parser gets control over the file # and reads as many lines as it needs to collect data for some # attributes. for parser in parsers: if parser.test(line, data): parser.read(line, f, data) break self.__dict__.update(data)
def read(self, line, f, data): """See :meth:`PunchParser.read`""" self.used = True data["title"] = f.readline().strip() data["symmetry"] = f.readline().split()[0] if data["symmetry"] != "C1": raise NotImplementedError("Only C1 symmetry is supported.") symbols = [] while line != " $END \n": line = f.readline() if line[0] != " ": symbols.append(line.split()[0]) data["symbols"] = symbols
def read(self, line, f, data): """See :meth:`PunchParser.read`""" f.readline() f.readline() N = len(data["symbols"]) # if the data are already read before, just overwrite them numbers = data.get("numbers") if numbers is None: numbers = np.zeros(N, int) data["numbers"] = numbers coordinates = data.get("coordinates") if coordinates is None: coordinates = np.zeros((N,3), float) data["coordinates"] = coordinates for i in range(N): words = f.readline().split() numbers[i] = int(float(words[1])) coordinates[i,0] = float(words[2])*angstrom coordinates[i,1] = float(words[3])*angstrom coordinates[i,2] = float(words[4])*angstrom
def read(self, line, f, data): """See :meth:`PunchParser.read`""" data["energy"] = float(f.readline().split()[1]) N = len(data["symbols"]) # if the data are already read before, just overwrite them gradient = data.get("gradient") if gradient is None: gradient = np.zeros((N,3), float) data["gradient"] = gradient for i in range(N): words = f.readline().split() gradient[i,0] = float(words[2]) gradient[i,1] = float(words[3]) gradient[i,2] = float(words[4])
def read(self, line, f, data): """See :meth:`PunchParser.read`""" line = f.readline() assert(line == " $HESS\n") while line != " $END\n": line = f.readline()
def read(self, line, f, data): """See :meth:`PunchParser.read`""" assert("hessian" not in data) f.readline() N = len(data["symbols"]) hessian = np.zeros((3*N, 3*N), float) tmp = hessian.ravel() counter = 0 while True: line = f.readline() if line == " $END\n": break line = line[5:-1] for j in range(len(line)//15): tmp[counter] = float(line[j*15:(j+1)*15]) counter += 1 data["hessian"] = hessian
def read(self, line, f, data): """See :meth:`PunchParser.read`""" N = len(data["symbols"]) masses = np.zeros(N, float) counter = 0 while counter < N: words = f.readline().split() for word in words: masses[counter] = float(word)*amu counter += 1 data["masses"] = masses
def setup_hydrocarbon_ff(graph): """Create a simple ForceField object for hydrocarbons based on the graph.""" # A) Define parameters. # the bond parameters: bond_params = { (6, 1): 310*kcalmol/angstrom**2, (6, 6): 220*kcalmol/angstrom**2, } # for every (a, b), also add (b, a) for key, val in list(bond_params.items()): if key[0] != key[1]: bond_params[(key[1], key[0])] = val # the bend parameters bend_params = { (1, 6, 1): 35*kcalmol/rad**2, (1, 6, 6): 30*kcalmol/rad**2, (6, 6, 6): 60*kcalmol/rad**2, } # for every (a, b, c), also add (c, b, a) for key, val in list(bend_params.items()): if key[0] != key[2]: bend_params[(key[2], key[1], key[0])] = val # B) detect all internal coordinates and corresponding energy terms. terms = [] # bonds for i0, i1 in graph.edges: K = bond_params[(graph.numbers[i0], graph.numbers[i1])] terms.append(BondStretchTerm(K, i0, i1)) # 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]: K = bend_params[(graph.numbers[i0], graph.numbers[i1], graph.numbers[i2])] terms.append(BendAngleTerm(K, i0, i1, i2)) # C) Create and return the force field return ForceField(terms)
def add_to_hessian(self, coordinates, hessian): """Add the contributions of this energy term to the Hessian Arguments: | ``coordinates`` -- A numpy array with 3N Cartesian coordinates. | ``hessian`` -- A matrix for the full Hessian to which this energy term has to add its contribution. """ # Compute the derivatives of the bond stretch towards the two cartesian # coordinates. The bond length is computed too, but not used. q, g = self.icfn(coordinates[list(self.indexes)], 1) # Add the contribution to the Hessian (an outer product) for ja, ia in enumerate(self.indexes): # ja is 0, 1, 2, ... # ia is i0, i1, i2, ... for jb, ib in enumerate(self.indexes): contrib = 2*self.force_constant*numpy.outer(g[ja], g[jb]) hessian[3*ia:3*ia+3, 3*ib:3*ib+3] += contrib
def hessian(self, coordinates): """Compute the force-field Hessian for the given coordinates. Argument: | ``coordinates`` -- A numpy array with the Cartesian atom coordinates, with shape (N,3). Returns: | ``hessian`` -- A numpy array with the Hessian, with shape (3*N, 3*N). """ # N3 is 3 times the number of atoms. N3 = coordinates.size # Start with a zero hessian. hessian = numpy.zeros((N3,N3), float) # Add the contribution of each term. for term in self.terms: term.add_to_hessian(coordinates, hessian) return hessian
def compute_rotsym(molecule, graph, threshold=1e-3*angstrom): """Compute the rotational symmetry number Arguments: | ``molecule`` -- The molecule | ``graph`` -- The corresponding bond graph 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. """ result = 0 for match in graph.symmetries: permutation = list(j for i,j in sorted(match.forward.items())) new_coordinates = molecule.coordinates[permutation] rmsd = fit_rmsd(molecule.coordinates, new_coordinates)[2] if rmsd < threshold: result += 1 return result
def quaternion_product(quat1, quat2): """Return the quaternion product of the two arguments""" return np.array([ quat1[0]*quat2[0] - np.dot(quat1[1:], quat2[1:]), quat1[0]*quat2[1] + quat2[0]*quat1[1] + quat1[2]*quat2[3] - quat1[3]*quat2[2], quat1[0]*quat2[2] + quat2[0]*quat1[2] + quat1[3]*quat2[1] - quat1[1]*quat2[3], quat1[0]*quat2[3] + quat2[0]*quat1[3] + quat1[1]*quat2[2] - quat1[2]*quat2[1] ], float)
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)
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)
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)
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)
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
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
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
def dot(r1, r2): """Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar) """ 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.") return r1.x*r2.x + r1.y*r2.y + r1.z*r2.z
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
def _opbend_transform_mean(rs, fn_low, deriv=0): """Compute the mean of the 3 opbends """ v = 0.0 d = np.zeros((4,3), float) dd = np.zeros((4,3,4,3), float) #loop over the 3 cyclic permutations for p in np.array([[0,1,2], [2,0,1], [1,2,0]]): opbend = _opbend_transform([rs[p[0]], rs[p[1]], rs[p[2]], rs[3]], fn_low, deriv) v += opbend[0]/3 index0 = np.where(p==0)[0][0] #index0 is the index of the 0th atom (rs[0]) index1 = np.where(p==1)[0][0] index2 = np.where(p==2)[0][0] index3 = 3 if deriv>0: d[0] += opbend[1][index0]/3 d[1] += opbend[1][index1]/3 d[2] += opbend[1][index2]/3 d[3] += opbend[1][index3]/3 if deriv>1: dd[0, :, 0, :] += opbend[2][index0, :, index0, :]/3 dd[0, :, 1, :] += opbend[2][index0, :, index1, :]/3 dd[0, :, 2, :] += opbend[2][index0, :, index2, :]/3 dd[0, :, 3, :] += opbend[2][index0, :, index3, :]/3 dd[1, :, 0, :] += opbend[2][index1, :, index0, :]/3 dd[1, :, 1, :] += opbend[2][index1, :, index1, :]/3 dd[1, :, 2, :] += opbend[2][index1, :, index2, :]/3 dd[1, :, 3, :] += opbend[2][index1, :, index3, :]/3 dd[2, :, 0, :] += opbend[2][index2, :, index0, :]/3 dd[2, :, 1, :] += opbend[2][index2, :, index1, :]/3 dd[2, :, 2, :] += opbend[2][index2, :, index2, :]/3 dd[2, :, 3, :] += opbend[2][index2, :, index3, :]/3 dd[3, :, 0, :] += opbend[2][index3, :, index0, :]/3 dd[3, :, 1, :] += opbend[2][index3, :, index1, :]/3 dd[3, :, 2, :] += opbend[2][index3, :, index2, :]/3 dd[3, :, 3, :] += opbend[2][index3, :, index3, :]/3 if deriv==0: return v, elif deriv==1: return v, d elif deriv==2: return v, d, dd else: raise ValueError("deriv must be 0, 1 or 2.")
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()
def _bend_cos_low(a, b, deriv): """Similar to bend_cos, but with relative vectors""" a = Vector3(6, deriv, a, (0, 1, 2)) b = Vector3(6, deriv, b, (3, 4, 5)) a /= a.norm() b /= b.norm() return dot(a, b).results()
def _bend_angle_low(a, b, deriv): """Similar to bend_angle, but with relative vectors""" result = _bend_cos_low(a, b, deriv) return _cos_to_angle(result, deriv)
def _dihed_cos_low(a, b, c, deriv): """Similar to dihed_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)) b /= b.norm() tmp = b.copy() tmp *= dot(a, b) a -= tmp tmp = b.copy() tmp *= dot(c, b) c -= tmp a /= a.norm() c /= c.norm() return dot(a, c).results()
def _dihed_angle_low(av, bv, cv, deriv): """Similar to dihed_cos, 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)) b /= b.norm() tmp = b.copy() tmp *= dot(a, b) a -= tmp tmp = b.copy() tmp *= dot(c, b) c -= tmp a /= a.norm() c /= c.norm() result = dot(a, c).results() # avoid trobles with the gradients by either using arccos or arcsin if abs(result[0]) < 0.5: # if the cosine is far away for -1 or +1, it is safe to take the arccos # and fix the sign of the angle. sign = 1-(np.linalg.det([av, bv, cv]) > 0)*2 return _cos_to_angle(result, deriv, sign) else: # if the cosine is close to -1 or +1, it is better to compute the sine, # take the arcsin and fix the sign of the angle d = cross(b, a) side = (result[0] > 0)*2-1 # +1 means angle in range [-pi/2,pi/2] result = dot(d, c).results() return _sin_to_angle(result, deriv, side)
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()
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()
def _opbend_angle_low(a, b, c, deriv=0): """Similar to opbend_angle, but with relative vectors""" result = _opbend_cos_low(a, b, c, deriv) sign = np.sign(np.linalg.det([a, b, c])) return _cos_to_angle(result, deriv, sign)
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.")
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.")
def copy(self): """Return a deep copy""" result = Scalar(self.size, self.deriv) result.v = self.v if self.deriv > 0: result.d[:] = self.d[:] if self.deriv > 1: result.dd[:] = self.dd[:] return result
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
def inv(self): """In place invert""" self.v = 1/self.v tmp = self.v**2 if self.deriv > 1: self.dd[:] = tmp*(2*self.v*np.outer(self.d, self.d) - self.dd) if self.deriv > 0: self.d[:] = -tmp*self.d[:]
def copy(self): """Return a deep copy""" result = Vector3(self.size, self.deriv) result.x.v = self.x.v result.y.v = self.y.v result.z.v = self.z.v if self.deriv > 0: result.x.d[:] = self.x.d result.y.d[:] = self.y.d result.z.d[:] = self.z.d if self.deriv > 1: result.x.dd[:] = self.x.dd result.y.dd[:] = self.y.dd result.z.dd[:] = self.z.dd return result
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
def _get_line(self): """Get a line or raise StopIteration""" line = self._f.readline() if len(line) == 0: raise StopIteration return line
def _read_frame(self): """Read one frame""" # Read the first line, ignore the title and try to get the time. The # time field is optional. line = self._get_line() pos = line.rfind("t=") if pos >= 0: time = float(line[pos+2:])*picosecond else: time = 0.0 # Read the second line, the number of atoms must match with the first # frame. num_atoms = int(self._get_line()) if self.num_atoms is not None and self.num_atoms != num_atoms: raise ValueError("The number of atoms must be the same over the entire file.") # Read the atom lines pos = np.zeros((num_atoms, 3), np.float32) vel = np.zeros((num_atoms, 3), np.float32) for i in range(num_atoms): words = self._get_line()[22:].split() pos[i, 0] = float(words[0]) pos[i, 1] = float(words[1]) pos[i, 2] = float(words[2]) vel[i, 0] = float(words[3]) vel[i, 1] = float(words[4]) vel[i, 2] = float(words[5]) pos *= nanometer vel *= nanometer/picosecond # Read the cell line cell = np.zeros((3, 3), np.float32) words = self._get_line().split() if len(words) >= 3: cell[0, 0] = float(words[0]) cell[1, 1] = float(words[1]) cell[2, 2] = float(words[2]) if len(words) == 9: cell[1, 0] = float(words[3]) cell[2, 0] = float(words[4]) cell[0, 1] = float(words[5]) cell[2, 1] = float(words[6]) cell[0, 2] = float(words[7]) cell[1, 2] = float(words[8]) cell *= nanometer return time, pos, vel, cell
def _skip_frame(self): """Skip one frame""" self._get_line() num_atoms = int(self._get_line()) if self.num_atoms is not None and self.num_atoms != num_atoms: raise ValueError("The number of atoms must be the same over the entire file.") for i in range(num_atoms+1): self._get_line()
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
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
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
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 )
def from_molecule(cls, molecule, labels=None): """Initialize a similarity descriptor Arguments: molecule -- a Molecules object labels -- a list with integer labels used to identify atoms of the same type. When not given, the atom numbers from the molecule are used. """ if labels is None: labels = molecule.numbers return cls(molecule.distance_matrix, labels)
def from_molecular_graph(cls, molecular_graph, labels=None): """Initialize a similarity descriptor Arguments: molecular_graphs -- A MolecularGraphs object labels -- a list with integer labels used to identify atoms of the same type. When not given, the atom numbers from the molecular graph are used. """ if labels is None: labels = molecular_graph.numbers.astype(int) return cls(molecular_graph.distances, labels)
def from_coordinates(cls, coordinates, labels): """Initialize a similarity descriptor Arguments: coordinates -- a Nx3 numpy array labels -- a list with integer labels used to identify atoms of the same type """ from molmod.ext import molecules_distance_matrix distance_matrix = molecules_distance_matrix(coordinates) return cls(distance_matrix, labels)
def load_chk(filename): '''Load a checkpoint file Argument: | filename -- the file to load from The return value is a dictionary whose keys are field labels and the values can be None, string, integer, float, boolean or an array of strings, integers, booleans or floats. The file format is similar to the Gaussian fchk format, but has the extra feature that the shapes of the arrays are also stored. ''' with open(filename) as f: result = {} while True: line = f.readline() if line == '': break if len(line) < 54: raise IOError('Header lines must be at least 54 characters long.') key = line[:40].strip() kind = line[47:52].strip() value = line[53:-1] # discard newline if kind == 'str': result[key] = value elif kind == 'int': result[key] = int(value) elif kind == 'bln': result[key] = value.lower() in ['true', '1', 'yes'] elif kind == 'flt': result[key] = float(value) elif kind[3:5] == 'ar': if kind[:3] == 'str': dtype = np.dtype('U22') elif kind[:3] == 'int': dtype = int elif kind[:3] == 'bln': dtype = bool elif kind[:3] == 'flt': dtype = float else: raise IOError('Unsupported kind: %s' % kind) shape = tuple(int(i) for i in value.split(',')) array = np.zeros(shape, dtype) if array.size > 0: work = array.ravel() counter = 0 while True: short = f.readline().split() if len(short) == 0: raise IOError('Insufficient data') for s in short: if dtype == bool: work[counter] = s.lower() in ['true', '1', 'yes'] elif callable(dtype): work[counter] = dtype(s) else: work[counter] = s counter += 1 if counter == array.size: break if counter == array.size: break result[key] = array elif kind == 'none': result[key] = None else: raise IOError('Unsupported kind: %s' % kind) return result
def dump_chk(filename, data): '''Dump a checkpoint file Argument: | filename -- the file to write to | data -- a dictionary whose keys are field labels and the values can be None, string, integer, float, boolean, an array/list of strings, integers, floats or booleans. The file format is similar to the Gaussian fchk format, but has the extra feature that the shapes of the arrays are also stored. ''' with open(filename, 'w') as f: for key, value in sorted(data.items()): if not isinstance(key, str): raise TypeError('The keys must be strings.') if len(key) > 40: raise ValueError('Key strings cannot be longer than 40 characters.') if '\n' in key: raise ValueError('Key strings cannot contain newlines.') if isinstance(value, str): if len(value) > 256: raise ValueError('Only small strings are supported (256 chars).') if '\n' in value: raise ValueError('The string cannot contain new lines.') print('%40s kind=str %s' % (key.ljust(40), value), file=f) elif isinstance(value, bool): print('%40s kind=bln %s' % (key.ljust(40), value), file=f) elif isinstance(value, (int, np.integer)): print('%40s kind=int %i' % (key.ljust(40), value), file=f) elif isinstance(value, float): print('%40s kind=flt %22.15e' % (key.ljust(40), value), file=f) elif isinstance(value, np.ndarray) or isinstance(value, list) or \ isinstance(value, tuple): if isinstance(value, list) or isinstance(value, tuple): value = np.array(value) if value.dtype.fields is not None: raise TypeError('Arrays with fields are not supported.') shape_str = ','.join(str(i) for i in value.shape) if issubclass(value.dtype.type, (str, np.unicode, np.bytes_)): value = value.astype(np.unicode) for cell in value.flat: if len(cell) >= 22: raise ValueError('In case of string arrays, a string may contain at most 21 characters.') if ' ' in cell or '\n' in cell: raise ValueError('In case of string arrays, a string may not contain spaces or new lines.') print('%40s kind=strar %s' % (key.ljust(40), shape_str), file=f) format_str = '%22s' elif issubclass(value.dtype.type, np.integer): print('%40s kind=intar %s' % (key.ljust(40), shape_str), file=f) format_str = '%22i' elif issubclass(value.dtype.type, np.bool_): print('%40s kind=blnar %s' % (key.ljust(40), shape_str), file=f) format_str = '%22s' elif issubclass(value.dtype.type, float): print('%40s kind=fltar %s' % (key.ljust(40), shape_str), file=f) format_str = '%22.15e' else: raise TypeError('Numpy array type %s not supported.' % value.dtype.type) short_len = 4 short = [] for x in value.ravel(): short.append(x) if len(short) == 4: print(' '.join(format_str % s for s in short), file=f) short = [] if len(short) > 0: print(' '.join(format_str % s for s in short), file=f) elif value is None: print('%40s kind=none None' % key.ljust(40), file=f) else: raise TypeError('Type %s not supported.' % type(value))
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 = {}
def read_from_file(self, filename): """Load a PSF file""" self.clear() with open(filename) as f: # A) check the first line line = next(f) if not line.startswith("PSF"): raise FileFormatError("Error while reading: A PSF file must start with a line 'PSF'.") # B) read in all the sections, without interpreting them current_section = None sections = {} for line in f: line = line.strip() if line == "": continue elif "!N" in line: words = line.split() current_section = [] section_name = words[1][2:] if section_name.endswith(":"): section_name = section_name[:-1] sections[section_name] = current_section else: current_section.append(line) # C) interpret the supported sections # C.1) The title self.title = sections['TITLE'][0] molecules = [] numbers = [] # C.2) The atoms and molecules for line in sections['ATOM']: words = line.split() self.atom_types.append(words[5]) self.charges.append(float(words[6])) self.names.append(words[3]) molecules.append(int(words[2])) atom = periodic[words[4]] if atom is None: numbers.append(0) else: numbers.append(periodic[words[4]].number) self.molecules = np.array(molecules)-1 self.numbers = np.array(numbers) self.charges = np.array(self.charges) # C.3) The bonds section tmp = [] for line in sections['BOND']: tmp.extend(int(word) for word in line.split()) self.bonds = np.reshape(np.array(tmp), (-1, 2))-1 # C.4) The bends section tmp = [] for line in sections['THETA']: tmp.extend(int(word) for word in line.split()) self.bends = np.reshape(np.array(tmp), (-1, 3))-1 # C.5) The dihedral section tmp = [] for line in sections['PHI']: tmp.extend(int(word) for word in line.split()) self.dihedrals = np.reshape(np.array(tmp), (-1, 4))-1 # C.6) The improper section tmp = [] for line in sections['IMPHI']: tmp.extend(int(word) for word in line.split()) self.impropers = np.reshape(np.array(tmp), (-1, 4))-1
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
def dump(self, f): """Dump the data structure to a file-like object""" # header print("PSF", file=f) print(file=f) # title print(" 1 !NTITLE", file=f) print(self.title, file=f) print(file=f) # atoms print("% 7i !NATOM" % len(self.numbers), file=f) if len(self.numbers) > 0: for index, (number, atom_type, charge, name, molecule) in enumerate(zip(self.numbers, self.atom_types, self.charges, self.names, self.molecules)): atom = periodic[number] print("% 7i % 4s % 4i NAME % 6s % 6s % 8.4f % 12.6f 0" % ( index + 1, name, molecule + 1, atom.symbol, atom_type, charge, atom.mass/unified, ), file=f) print(file=f) # bonds print("% 7i !NBOND" % len(self.bonds), file=f) if len(self.bonds) > 0: tmp = [] for bond in self.bonds: tmp.extend(bond+1) if len(tmp) >= 8: print(" ".join("% 7i" % v for v in tmp[:8]), file=f) tmp = tmp[8:] if len(tmp) > 0: print(" ".join("% 7i" % v for v in tmp), file=f) print(file=f) # bends print("% 7i !NTHETA" % len(self.bends), file=f) if len(self.bends) > 0: tmp = [] for bend in self.bends: tmp.extend(bend+1) if len(tmp) >= 9: print(" " + (" ".join("% 6i" % v for v in tmp[:9])), file=f) tmp = tmp[9:] if len(tmp) > 0: print(" " + (" ".join("% 6i" % v for v in tmp)), file=f) print(file=f) # dihedrals print("% 7i !NPHI" % len(self.dihedrals), file=f) if len(self.dihedrals) > 0: tmp = [] for dihedral in self.dihedrals: tmp.extend(dihedral+1) if len(tmp) >= 8: print(" " + (" ".join("% 6i" % v for v in tmp[:8])), file=f) tmp = tmp[8:] if len(tmp) > 0: print(" " + (" ".join("% 6i" % v for v in tmp)), file=f) print(file=f) # impropers print("% 7i !NIMPHI" % len(self.impropers), file=f) if len(self.impropers) > 0: tmp = [] for improper in self.impropers: tmp.extend(improper+1) if len(tmp) >= 8: print(" " + (" ".join("% 6i" % v for v in tmp[:8])), file=f) tmp = tmp[8:] if len(tmp) > 0: print(" " + (" ".join("% 6i" % v for v in tmp)), file=f) print(file=f) # not implemented fields print(" 0 !NDON", file=f) print(file=f) print(" 0 !NNB", file=f) print(file=f) print(" 0 !NGRP", file=f) print(file=f)
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)
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)
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
def iter_halfs_bond(graph): """Select a random bond (pair of atoms) that divides the molecule in two""" for atom1, atom2 in graph.edges: try: affected_atoms1, affected_atoms2 = graph.get_halfs(atom1, atom2) yield affected_atoms1, affected_atoms2, (atom1, atom2) except GraphError: # just try again continue
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
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
def generate_manipulations( molecule, bond_stretch_factor=0.15, torsion_amplitude=np.pi, bending_amplitude=0.30 ): """Generate a (complete) set of manipulations The result can be used as input for the functions 'randomize_molecule' and 'single_random_manipulation' Arguments: molecule -- a reference geometry of the molecule, with graph attribute bond_stretch_factor -- the maximum relative change in bond length by one bond stretch manipulatio torsion_amplitude -- the maximum change a dihdral angle bending_amplitude -- the maximum change in a bending angle The return value is a list of RandomManipulation objects. They can be used to generate different random distortions of the original molecule. """ do_stretch = (bond_stretch_factor > 0) do_double_stretch = (bond_stretch_factor > 0) do_bend = (bending_amplitude > 0) do_double_bend = (bending_amplitude > 0) do_torsion = (torsion_amplitude > 0) results = [] # A) all manipulations that require one bond that cuts the molecule in half if do_stretch or do_torsion: for affected_atoms1, affected_atoms2, hinge_atoms in iter_halfs_bond(molecule.graph): if do_stretch: length = np.linalg.norm( molecule.coordinates[hinge_atoms[0]] - molecule.coordinates[hinge_atoms[1]] ) results.append(RandomStretch( affected_atoms1, length*bond_stretch_factor, hinge_atoms )) if do_torsion and len(affected_atoms1) > 1 and len(affected_atoms2) > 1: results.append(RandomTorsion( affected_atoms1, torsion_amplitude, hinge_atoms )) # B) all manipulations that require a bending angle that cuts the molecule # in two parts if do_bend: for affected_atoms, hinge_atoms in iter_halfs_bend(molecule.graph): results.append(RandomBend( affected_atoms, bending_amplitude, hinge_atoms )) # C) all manipulations that require two bonds that separate two halfs if do_double_stretch or do_double_bend: for affected_atoms1, affected_atoms2, hinge_atoms in iter_halfs_double(molecule.graph): if do_double_stretch: length1 = np.linalg.norm( molecule.coordinates[hinge_atoms[0]] - molecule.coordinates[hinge_atoms[1]] ) length2 = np.linalg.norm( molecule.coordinates[hinge_atoms[2]] - molecule.coordinates[hinge_atoms[3]] ) results.append(RandomDoubleStretch( affected_atoms1, 0.5*(length1+length2)*bond_stretch_factor, hinge_atoms )) if do_double_bend and len(affected_atoms1) > 2 and len(affected_atoms2) > 2: if hinge_atoms[0] != hinge_atoms[2]: results.append(RandomTorsion( affected_atoms1, bending_amplitude, (hinge_atoms[0], hinge_atoms[2]) )) if hinge_atoms[1] != hinge_atoms[3]: results.append(RandomTorsion( affected_atoms2, bending_amplitude, (hinge_atoms[1], hinge_atoms[3]) )) # Neglect situations where three or more cuts are required. return results
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
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
def randomize_molecule_low(molecule, manipulations): """Return a randomized copy of the molecule, without the nonbond check.""" manipulations = copy.copy(manipulations) shuffle(manipulations) coordinates = molecule.coordinates.copy() for manipulation in manipulations: manipulation.apply(coordinates) return molecule.copy_with(coordinates=coordinates)
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
def single_random_manipulation_low(molecule, manipulations): """Return a randomized copy of the molecule, without the nonbond check.""" manipulation = sample(manipulations, 1)[0] coordinates = molecule.coordinates.copy() transformation = manipulation.apply(coordinates) return molecule.copy_with(coordinates=coordinates), transformation
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
def read_from_file(cls, filename): """Construct a MolecularDistortion object from a file""" with open(filename) as f: lines = list(line for line in f if line[0] != '#') r = [] t = [] for line in lines[:3]: values = list(float(word) for word in line.split()) r.append(values[:3]) t.append(values[3]) transformation = Complete(r, t) affected_atoms = set(int(word) for word in lines[3].split()) return cls(affected_atoms, transformation)
def apply(self, coordinates): """Apply this distortion to Cartesian coordinates""" for i in self.affected_atoms: coordinates[i] = self.transformation*coordinates[i]
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)
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
def get_transformation(self, coordinates): """Construct a transformation object""" atom1, atom2 = self.hinge_atoms direction = coordinates[atom1] - coordinates[atom2] direction /= np.linalg.norm(direction) direction *= np.random.uniform(-self.max_amplitude, self.max_amplitude) result = Translation(direction) return result
def get_transformation(self, coordinates): """Construct a transformation object""" atom1, atom2 = self.hinge_atoms center = coordinates[atom1] axis = coordinates[atom1] - coordinates[atom2] axis /= np.linalg.norm(axis) angle = np.random.uniform(-self.max_amplitude, self.max_amplitude) return Complete.about_axis(center, angle, axis)
def get_transformation(self, coordinates): """Construct a transformation object""" atom1, atom2, atom3 = self.hinge_atoms center = coordinates[atom2] a = coordinates[atom1] - coordinates[atom2] b = coordinates[atom3] - coordinates[atom2] axis = np.cross(a, b) norm = np.linalg.norm(axis) if norm < 1e-5: # We suppose that atom3 is part of the affected atoms axis = random_orthonormal(a) else: axis /= np.linalg.norm(axis) angle = np.random.uniform(-self.max_amplitude, self.max_amplitude) return Complete.about_axis(center, angle, axis)
def get_transformation(self, coordinates): """Construct a transformation object""" atom1, atom2, atom3, atom4 = self.hinge_atoms a = coordinates[atom1] - coordinates[atom2] a /= np.linalg.norm(a) b = coordinates[atom3] - coordinates[atom4] b /= np.linalg.norm(b) direction = 0.5*(a+b) direction *= np.random.uniform(-self.max_amplitude, self.max_amplitude) result = Translation(direction) return result
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
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))
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
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)
def parents(self): """ Returns an simple FIFO queue with the ancestors and itself. """ q = self.__parent__.parents() q.put(self) return q
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
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()
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.")
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)
def com(self): """the center of mass of the molecule""" return (self.coordinates*self.masses.reshape((-1,1))).sum(axis=0)/self.mass
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
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)
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])
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)
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)
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)
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.")
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(":")]