text stringlengths 81 112k |
|---|
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:... |
The inverse translation
def inv(self):
"""The inverse translation"""
result = Translation(-self.t)
result._cache_inv = self
return result |
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``
... |
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.
def compare(self, other, t_threshold=1e-3):
"""Compare two translations
The... |
the columns must orthogonal
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 \
... |
Return a random rotation
def random(cls):
"""Return a random rotation"""
axis = random_unit()
angle = np.random.uniform(0,2*np.pi)
invert = bool(np.random.randint(0,2))
return Rotation.from_properties(angle, axis, invert) |
Initialize a rotation based on the properties
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 = ... |
Rotation properties: angle, axis, invert
def properties(self):
"""Rotation properties: angle, axis, invert"""
# determine wether an inversion rotation has been applied
invert = (np.linalg.det(self.r) < 0)
factor = {True: -1, False: 1}[invert]
# get the rotation data
# tr... |
The 4x4 matrix representation of this rotation
def matrix(self):
"""The 4x4 matrix representation of this rotation"""
result = np.identity(4, float)
result[0:3, 0:3] = self.r
return result |
The inverse rotation
def inv(self):
"""The inverse rotation"""
result = Rotation(self.r.transpose())
result._cache_inv = self
return result |
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``
* ... |
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.
def compare(self, other, r_threshold=1e-3):
"""Compare two rotations
The RMSD of th... |
Initialize a transformation based on the properties
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) |
Convert the first argument into a Complete object
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, Rotati... |
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
... |
Transformation properties: angle, axis, invert, translation
def properties(self):
"""Transformation properties: angle, axis, invert, translation"""
rot = Rotation(self.r)
angle, axis, invert = rot.properties
return angle, axis, invert, self.t |
The inverse transformation
def inv(self):
"""The inverse transformation"""
result = Complete(self.r.transpose(), np.dot(self.r.transpose(), -self.t))
result._cache_inv = self
return result |
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.
def compare(self, other, t_threshol... |
Read and return the next time frame
def _read_frame(self):
"""Read and return the next time frame"""
# Read one frame, we assume that the current file position is at the
# line 'ITEM: TIMESTEP' and that this line marks the beginning of a
# time frame.
line = next(self._f)
... |
Skip the next time frame
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) |
Add an atom info object to the database
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 |
Extend the current cluster with data from another cluster
def update(self, other):
"""Extend the current cluster with data from another cluster"""
Cluster.update(self, other)
self.rules.extend(other.rules) |
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.
def add_related(self, *objects):
"""Add related items
... |
Read a single frame from the trajectory
def _read_frame(self):
"""Read a single frame from the trajectory"""
# auxiliary read function
def read_three(msg):
"""Read three words as floating point numbers"""
line = next(self._f)
try:
return [floa... |
Continue reading until the next frame is reached
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:
... |
Read a single frame from the trajectory
def _read_frame(self):
"""Read a single frame from the trajectory"""
# optionally skip the equilibration
if self.skip_equi_period:
while True:
step, line = self.goto_next_frame()
self._counter += 1
... |
Read a frame from the XYZ file
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):
... |
Skip a single frame from the trajectory
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 |
Get the first molecule from the trajectory
This can be useful to configure your program before handeling the
actual trajectory.
def get_first_molecule(self):
"""Get the first molecule from the trajectory
This can be useful to configure your program before handeling the
... |
Dump a frame to the trajectory file
Arguments:
| ``title`` -- the title of the frame
| ``coordinates`` -- a numpy array with coordinates in atomic units
def dump(self, title, coordinates):
"""Dump a frame to the trajectory file
Arguments:
| ``titl... |
Get a molecule from the trajectory
Optional argument:
| ``index`` -- The frame index [default=0]
def get_molecule(self, index=0):
"""Get a molecule from the trajectory
Optional argument:
| ``index`` -- The frame index [default=0]
"""
return Mo... |
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]
def write_to_file(self, f, file_unit=angst... |
Efficiently test if counter is in ``xrange(*sub)``
Arguments:
| ``sub`` -- a slice object
| ``counter`` -- an integer
The function returns True if the counter is in
``xrange(sub.start, sub.stop, sub.step)``.
def slice_match(sub, counter):
"""Efficiently test if counter is ... |
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... |
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 adde... |
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... |
Update the search direction given the latest gradient and step
def update(self, gradient, step):
"""Update the search direction given the latest gradient and step"""
do_sd = self.gradient_old is None
self.gradient_old = self.gradient
self.gradient = gradient
if do_sd:
... |
Update the conjugate gradient
def _update_cg(self):
"""Update the conjugate gradient"""
beta = self._beta()
# Automatic direction reset
if beta < 0:
self.direction = -self.gradient
self.status = "SD"
else:
self.direction = self.direction * bet... |
Update the search direction given the latest gradient and step
def update(self, gradient, step):
"""Update the search direction given the latest gradient and step"""
self.old_gradient = self.gradient
self.gradient = gradient
N = len(self.gradient)
if self.inv_hessian is None:
... |
Clip the a step within the maximum allowed range
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) |
Find a bracket that does contain the minimum
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
... |
Reduce the size of the bracket until the minimum is found
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... |
Perform an update of the linear transformation
Arguments:
| ``counter`` -- the iteration counter of the minimizer
| ``f`` -- the function value at ``x_orig``
| ``x_orig`` -- the unknowns in original coordinates
| ``gradient_orig`` -- the gradient in or... |
Perform an update of the linear transformation
Arguments:
| ``counter`` -- the iteration counter of the minimizer
| ``f`` -- the function value at ``x_orig``
| ``x_orig`` -- the unknowns in original coordinates
| ``gradient_orig`` -- the gradient in or... |
Perform an update of the linear transformation
Arguments:
| ``counter`` -- the iteration counter of the minimizer
| ``f`` -- the function value at ``x_orig``
| ``x_orig`` -- the unknowns in original coordinates
| ``gradient_orig`` -- the gradient in or... |
Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates
def do(self, x_orig):
"""Transform the unknowns to preconditioned coordinates
This method also transforms the gradient to original coordinates
"""
if sel... |
Transform the unknowns to original coordinates
This method also transforms the gradient to preconditioned coordinates
def undo(self, x_prec):
"""Transform the unknowns to original coordinates
This method also transforms the gradient to preconditioned coordinates
"""
if s... |
Returns the header for screen logging of the minimization
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 M... |
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
def configure(self, x0, axis):
"""Configure the 1D function for a line search
Arguments:
x0 -- th... |
Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
def _compute_equations(self, x, verbose=False):
'''Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
... |
Take a robust, but not very efficient step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each row is one gradient.
| ``values`` -- A numpy array with t... |
Take an efficient (not always robust) step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each row is one gradient.
| ``values`` -- A numpy array with t... |
Brings unknowns to the constraints.
Arguments:
| ``x`` -- The unknowns.
def free_shake(self, x):
'''Brings unknowns to the constraints.
Arguments:
| ``x`` -- The unknowns.
'''
self.lock[:] = False
normals, values, error = self._compute_equ... |
Brings unknowns to the constraints, without increasing fun above fmax.
Arguments:
| ``x`` -- The unknowns.
| ``fun`` -- The function being minimized.
| ``fmax`` -- The highest allowed value of the function being
minimized.
The functio... |
Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is a gradient or direction, where the components
that point away from the cons... |
Return the final solution in the original coordinates
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) |
Run the iterative optimizer
def _run(self):
"""Run the iterative optimizer"""
success = self.initialize()
while success is None:
success = self.propagate()
return success |
Print the header for screen logging
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:
he... |
Print something on screen when self.verbose == True
def _screen(self, s, newline=False):
"""Print something on screen when self.verbose == True"""
if self.verbose:
if newline:
print(s)
else:
print(s, end=' ') |
Perform a line search along the current direction
def _line_opt(self):
"""Perform a line search along the current direction"""
direction = self.search_direction.direction
if self.constraints is not None:
try:
direction = self.constraints.project(self.x, direction)
... |
A map to look up the index of a edge
def edge_index(self):
"""A map to look up the index of a edge"""
return dict((edge, index) for index, edge in enumerate(self.edges)) |
A dictionary with neighbors
The dictionary will have the following form:
``{vertexX: (vertexY1, vertexY2, ...), ...}``
This means that vertexX and vertexY1 are connected etc. This also
implies that the following elements are part of the dictionary:
``{vertexY1: (v... |
The matrix with the all-pairs shortest path lenghts
def distances(self):
"""The matrix with the all-pairs shortest path lenghts"""
from molmod.ext import graphs_floyd_warshall
distances = np.zeros((self.num_vertices,)*2, dtype=int)
#distances[:] = -1 # set all -1, which is just a very b... |
Vertices that have the lowest maximum distance to any other vertex
def central_vertices(self):
"""Vertices that have the lowest maximum distance to any other vertex"""
max_distances = self.distances.max(0)
max_distances_min = max_distances[max_distances > 0].min()
return (max_distances ... |
Lists of vertices that are only interconnected within each list
This means that there is no path from a vertex in one list to a
vertex in another list. In case of a molecular graph, this would
yield the atoms that belong to individual molecules.
def independent_vertices(self):
... |
A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.)
def fingerprint(self):
"""A total graph fingerprint
The r... |
A fingerprint for each vertex
The result is invariant under permutation of the vertex indexes.
Vertices that are symmetrically equivalent will get the same
fingerprint, e.g. the hydrogens in methane would get the same
fingerprint.
def vertex_fingerprints(self):
"""A... |
A dictionary with symmetrically equivalent vertices.
def equivalent_vertices(self):
"""A dictionary with symmetrically equivalent vertices."""
level1 = {}
for i, row in enumerate(self.vertex_fingerprints):
key = row.tobytes()
l = level1.get(key)
if l is None:... |
Graph symmetries (permutations) that map the graph onto itself.
def symmetries(self):
"""Graph symmetries (permutations) that map the graph onto itself."""
symmetry_cycles = set([])
symmetries = set([])
for match in GraphSearch(EqualPattern(self))(self):
match.cycles = matc... |
The cycle representations of the graph symmetries
def symmetry_cycles(self):
"""The cycle representations of the graph symmetries"""
result = set([])
for symmetry in self.symmetries:
result.add(symmetry.cycles)
return result |
The vertices in a canonical or normalized order.
This routine will return a list of vertices in an order that does not
depend on the initial order, but only depends on the connectivity and
the return values of the function self.get_vertex_string.
Only the vertices that are ... |
Iterate over the vertices with the breadth first algorithm.
See http://en.wikipedia.org/wiki/Breadth-first_search for more info.
If not start vertex is given, the central vertex is taken.
By default, the distance to the starting vertex is also computed. If
the path to the s... |
Iterate over the edges with the breadth first convention.
We need this for the pattern matching algorithms, but a quick look at
Wikipedia did not result in a known and named algorithm.
The edges are yielded one by one, together with the distance of the
edge from the startin... |
Constructs a subgraph of the current graph
Arguments:
| ``subvertices`` -- The vertices that should be retained.
| ``normalize`` -- Whether or not the vertices should renumbered and
reduced to the given set of subvertices. When True, also the
edges a... |
Return an array with fingerprints for each vertex
def get_vertex_fingerprints(self, vertex_strings, edge_strings, num_iter=None):
"""Return an array with fingerprints for each vertex"""
import hashlib
def str2array(x):
"""convert a hash string to a numpy array of bytes"""
... |
Split the graph in two halfs by cutting the edge: vertex1-vertex2
If this is not possible (due to loops connecting both ends), a
GraphError is raised.
Returns the vertices in both halfs.
def get_halfs(self, vertex1, vertex2):
"""Split the graph in two halfs by cutting the edg... |
List all vertices that are connected to vertex_in, but are not
included in or 'behind' vertices_border.
def get_part(self, vertex_in, vertices_border):
"""List all vertices that are connected to vertex_in, but are not
included in or 'behind' vertices_border.
"""
vertices_n... |
Compute the two parts separated by ``(vertex_a1, vertex_b1)`` and ``(vertex_a2, vertex_b2)``
Raise a GraphError when ``(vertex_a1, vertex_b1)`` and
``(vertex_a2, vertex_b2)`` do not separate the graph in two
disconnected parts. The edges must be neighbors. If not a GraphError
... |
Find the mapping between vertex indexes in self and other.
This also works on disconnected graphs. Derived classes should just
implement get_vertex_string and get_edge_string to make this method
aware of the different nature of certain vertices. In case molecules,
this would... |
Add new a relation to the bejection
def add_relation(self, source, destination):
"""Add new a relation to the bejection"""
if self.in_sources(source):
if self.forward[source] != destination:
raise ValueError("Source is already in use. Destination does "
... |
Add multiple relations to a bijection
def add_relations(self, relations):
"""Add multiple relations to a bijection"""
for source, destination in relations:
self.add_relation(source, destination) |
Returns the inverse bijection.
def inverse(self):
"""Returns the inverse bijection."""
result = self.__class__()
result.forward = copy.copy(self.reverse)
result.reverse = copy.copy(self.forward)
return result |
Intialize a fresh match based on the first relation
def from_first_relation(cls, vertex0, vertex1):
"""Intialize a fresh match based on the first relation"""
result = cls([(vertex0, vertex1)])
result.previous_ends1 = set([vertex1])
return result |
Get new edges from the subject graph for the graph search algorithm
The Graph search algorithm extends the matches iteratively by adding
matching vertices that are one edge further from the starting vertex
at each iteration.
def get_new_edges(self, subject_graph):
"""Get new e... |
Create a new match object extended with new relations
def copy_with_new_relations(self, new_relations):
"""Create a new match object extended with new relations"""
result = self.__class__(self.forward.items())
result.add_relations(new_relations.items())
result.previous_ends1 = set(new_r... |
Initialize the pattern_graph
def _set_pattern_graph(self, pattern_graph):
"""Initialize the pattern_graph"""
self.pattern_graph = pattern_graph
self.level_edges = {}
self.level_constraints = {}
self.duplicate_checks = set([])
if pattern_graph is None:
return
... |
Iterate over all valid initial relations for a match
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
vertex0 = self.start_vertex
for vertex1 in range(subject_graph.num_vertices):
if self.compare(vertex0, vertex1, subject_gr... |
Get new edges from the pattern graph for the graph search algorithm
The level argument denotes the distance of the new edges from the
starting vertex in the pattern graph.
def get_new_edges(self, level):
"""Get new edges from the pattern graph for the graph search algorithm
T... |
Check if the (onset for a) match can be a valid
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid"""
# only returns true for ecaxtly one set of new_relations from all the
# ones that are symmetrically equivalent
... |
Given a match, iterate over all related equivalent matches
When criteria sets are defined, the iterator runs over all symmetric
equivalent matches that fulfill one of the criteria sets. When not
criteria sets are defined, the iterator only yields the input match.
def iter_final_matche... |
Return the closed cycles corresponding to this permutation
The cycle will be normalized to facilitate the elimination of
duplicates. The following is guaranteed:
1) If this permutation is represented by disconnected cycles, the
cycles will be sorted by the lowest index t... |
Iterate over all valid initial relations for a match
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
if self.pattern_graph.num_edges != subject_graph.num_edges:
return # don't even try
for pair in CustomPattern.iter_initial... |
Returns true when the two vertices are of the same kind
def compare(self, vertex0, vertex1, subject_graph):
"""Returns true when the two vertices are of the same kind"""
return (
self.pattern_graph.vertex_fingerprints[vertex0] ==
subject_graph.vertex_fingerprints[vertex1]
... |
Iterate over all valid initial relations for a match
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
vertex0 = 0
for vertex1 in range(subject_graph.num_vertices):
yield vertex0, vertex1 |
Get new edges from the pattern graph for the graph search algorithm
The level argument denotes the distance of the new edges from the
starting vertex in the pattern graph.
def get_new_edges(self, level):
"""Get new edges from the pattern graph for the graph search algorithm
T... |
Check if the (onset for a) match can be a valid (part of a) ring
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid (part of a) ring"""
# avoid duplicate rings (order of traversal)
if len(match) == 3:
if mat... |
Check the completeness of a ring match
def complete(self, match, subject_graph):
"""Check the completeness of a ring match"""
size = len(match)
# check whether we have an odd strong ring
if match.forward[size-1] in subject_graph.neighbors[match.forward[size-2]]:
# we have an... |
Only prints debug info on screen when self.debug == True.
def print_debug(self, text, indent=0):
"""Only prints debug info on screen when self.debug == True."""
if self.debug:
if indent > 0:
print(" "*self.debug, text)
self.debug += indent
if indent <... |
Divide the edges into groups
def _iter_candidate_groups(self, init_match, edges0, edges1):
"""Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same
# group.
sources = {}
for start_vertex0, end_vertex0 in edges0:
l = sou... |
Given an onset for a match, iterate over all possible new key-value pairs
def _iter_new_relations(self, init_match, subject_graph, edges0, constraints0, edges1):
"""Given an onset for a match, iterate over all possible new key-value pairs"""
# Count the number of unique edges0[i][1] values. This is als... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.