text
stringlengths
81
112k
Compute the rotation matrix representated by the quaternion 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*...
Compute the cosine between two vectors The result is clipped within the range [-1, 1] 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...
Return a random unit vector of the given dimension Optional argument: size -- the number of dimensions of the unit vector [default=3] def random_unit(size=3): """Return a random unit vector of the given dimension Optional argument: size -- the number of dimensions of the unit ...
Return a random normalized vector orthogonal to the given vector 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 ...
Return a vector orthogonal to the given triangle Arguments: a, b, c -- three 3D numpy vectors 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 = n...
Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar) def dot(r1, r2): """Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar) """ if r1.size != r2.size: ...
Compute the cross product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Vector3) def cross(r1, r2): """Compute the cross product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Vector3) """ if r1.size != r2.si...
Compute the mean of the 3 opbends 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 ...
Similar to bond_length, but with a relative vector 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()
Similar to bend_cos, but with relative vectors 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()
Similar to bend_angle, but with relative vectors 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)
Similar to dihed_cos, but with relative vectors 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)...
Similar to dihed_cos, but with relative vectors 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 *= d...
Similar to opdist, but with relative vectors 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) ...
Similar to opbend_cos, but with relative vectors 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(...
Similar to opbend_angle, but with relative vectors 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)
Convert a cosine and its derivatives to an angle and its derivatives 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: factor...
Convert a sine and its derivatives to an angle and its derivatives 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 ...
Return a deep copy 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
Return the value and optionally derivative and second order derivative 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:...
In place invert 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[:]
Return a deep copy 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 ...
Return a Scalar object with the norm of this vector 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 ...
Get a line or raise StopIteration def _get_line(self): """Get a line or raise StopIteration""" line = self._f.readline() if len(line) == 0: raise StopIteration return line
Read one frame 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 ...
Skip one frame 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(...
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. def setup_ics(graph): """Make a list of internal coordinates based on the gra...
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 Jac...
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) def fill_jacobian_column(sel...
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 c...
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. def from_mo...
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 a...
Initialize a similarity descriptor Arguments: coordinates -- a Nx3 numpy array labels -- a list with integer labels used to identify atoms of the same type def from_coordinates(cls, coordinates, labels): """Initialize a similarity descriptor ...
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 t...
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 fo...
Clear the contents of the data structure 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 ...
Load a PSF file 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 mus...
Convert a molecular graph into a unique name This method is not sensitive to the order of the atoms in the graph. 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. """ ...
Dump the data structure to a file-like object 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) # a...
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 ...
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,...
Return a list of groups of atom indexes Each atom in a group belongs to the same molecule or residue. 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_ind...
Select a random bond (pair of atoms) that divides the molecule in two 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) yi...
Select randomly two consecutive bonds that divide the molecule in two 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...
Select two random non-consecutive bonds that divide the molecule in two 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]: ...
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 -- ...
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 fo...
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. def randomize_molecule(molecule...
Return a randomized copy of the molecule, without the nonbond check. 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()...
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. ...
Return a randomized copy of the molecule, without the nonbond check. 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() transformati...
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 additi...
Construct a MolecularDistortion object from a file 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]: ...
Apply this distortion to Cartesian coordinates def apply(self, coordinates): """Apply this distortion to Cartesian coordinates""" for i in self.affected_atoms: coordinates[i] = self.transformation*coordinates[i]
Write the object to a file 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 tr...
Generate, apply and return a random manipulation 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 re...
Construct a transformation object 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.ma...
Construct a transformation object 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....
Construct a transformation object 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] ...
Construct a transformation object 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] ...
Iterate over all bins surrounding the given bin 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: ...
Translate the key into the central cell This method is only applicable in case of a periodic system. 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( se...
Choose a proper grid for the binning process 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: ...
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: def par...
Returns an simple FIFO queue with the ancestors and itself. def parents(self): """ Returns an simple FIFO queue with the ancestors and itself. """ q = self.__parent__.parents() q.put(self) return q
Returns the whole URL from the base to this node. 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
If any ancestor required an authentication, this node needs it too. 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()
the atomic numbers must match 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 a...
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. ...
the center of mass of the molecule def com(self): """the center of mass of the molecule""" return (self.coordinates*self.masses.reshape((-1,1))).sum(axis=0)/self.mass
the intertia tensor of the molecule 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*...
the chemical formula of the molecule 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): ...
Set self.masses based on self.numbers and periodic table. 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])
Set self.symbols based on self.numbers and the periodic table. 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)
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 def write_to_file(self, filename): """Write the molecular geometry to a file. ...
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...
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. def compute_rots...
Get the label from the last line read 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(":")]
Skip a section def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
Read and return an entire section 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) ...
Get the next section with the given label 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()
Read a single frame from the trajectory def _read_frame(self): """Read a single frame from the trajectory""" self._secfile.get_next("Frame Number") frame = ATRJFrame() # Read the time and energy energy_lines = self._secfile.get_next("Time/Energy") energy_words = energy_l...
Generate the Cartesian coordinates of the points in a cube file *Arguemnts:* origin The cartesian coordinate for the origin of the grid. axes The 3 by 3 array with the grid spacings as rows. nrep The number of grid points along each axis. def get_cube...
Create a cube object by loading data from a file. *Arguemnts:* filename The file to load. It must contain the header with the description of the grid and the molecule. def from_file(cls, filename): '''Create a cube object by loading data from a file. ...
Write the cube to a file in the Gaussian cube format. def write_to_file(self, fn): '''Write the cube to a file in the Gaussian cube format.''' with open(fn, 'w') as f: f.write(' {}\n'.format(self.molecule.title)) f.write(' {}\n'.format(self.subtitle)) def write_grid...
Return a copy of the cube with optionally new data. def copy(self, newdata=None): '''Return a copy of the cube with optionally new data.''' if newdata is None: newdata = self.data.copy() return self.__class__( self.molecule, self.origin.copy(), self.axes.copy(), ...
Checks the constency between self.__index and self.__order def _consistent(self): """Checks the constency between self.__index and self.__order""" if len(self.__order) != sum(len(values) for values in self.__index.values()): return False import copy tmp = copy.copy(self.__or...
Add a child section or keyword 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(c...
Dump the children of the current section to a file-like object 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+' ')
Dump this section and its children to a file-like object 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" % (...
A helper method that only reads uncommented lines 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.str...
Load the children of this section from a file-like object 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_n...
Load this section from a file-like object 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(...
Dump this keyword to a file-like object 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....
Load this keyword from a file-like object 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 = word...
Set the value associated with the keyword 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
Arguments: | ``filename`` -- the filename of the input file Use as follows:: >>> if = CP2KInputFile.read_from_file("somefile.inp") >>> for section in if: ... print section.name def read_from_file(filename): """ Arguments: ...
Read and return the next time frame def _read_frame(self): """Read and return the next time frame""" pos = np.zeros((self.num_atoms, 3), float) vel = np.zeros((self.num_atoms, 3), float) for i in range(self.num_atoms): line = next(self._f) words = line.split() ...
Check the sanity of the given 4x4 transformation matrix 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 ha...
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) ...