text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_groups(self):
"""Return a list of groups of atom indexes Each atom in a group belongs to the same molecule or residue. """ |
groups = []
for a_index, m_index in enumerate(self.molecules):
if m_index >= len(groups):
groups.append([a_index])
else:
groups[m_index].append(a_index)
return groups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_halfs_bend(graph):
"""Select randomly two consecutive bonds that divide the molecule in two""" |
for atom2 in range(graph.num_vertices):
neighbors = list(graph.neighbors[atom2])
for index1, atom1 in enumerate(neighbors):
for atom3 in neighbors[index1+1:]:
try:
affected_atoms = graph.get_halfs(atom2, atom1)[0]
# the affected at... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_halfs_double(graph):
"""Select two random non-consecutive bonds that divide the molecule in two""" |
edges = graph.edges
for index1, (atom_a1, atom_b1) in enumerate(edges):
for atom_a2, atom_b2 in edges[:index1]:
try:
affected_atoms1, affected_atoms2, hinge_atoms = graph.get_halfs_double(atom_a1, atom_b1, atom_a2, atom_b2)
yield affected_atoms1, affected_ato... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_nonbond(molecule, thresholds):
"""Check whether all nonbonded atoms are well separated. If a nonbond atom pair is found that has an interatomic distanc... |
# 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 < thresh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomize_molecule(molecule, manipulations, nonbond_thresholds, max_tries=1000):
"""Return a randomized copy of the molecule. If no randomized molecule can b... |
for m in range(max_tries):
random_molecule = randomize_molecule_low(molecule, manipulations)
if check_nonbond(random_molecule, nonbond_thresholds):
return random_molecule |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def single_random_manipulation(molecule, manipulations, nonbond_thresholds, max_tries=1000):
"""Apply a single random manipulation. If no randomized molecule can... |
for m in range(max_tries):
random_molecule, transformation = single_random_manipulation_low(molecule, manipulations)
if check_nonbond(random_molecule, nonbond_thresholds):
return random_molecule, transformation
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_dimer(molecule0, molecule1, thresholds, shoot_max):
"""Create a random dimer. molecule0 and molecule1 are placed in one reference frame at random rela... |
# 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.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = Complet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, coordinates):
"""Apply this distortion to Cartesian coordinates""" |
for i in self.affected_atoms:
coordinates[i] = self.transformation*coordinates[i] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_to_file(self, filename):
"""Write the object to a file""" |
r = self.transformation.r
t = self.transformation.t
with open(filename, "w") as f:
print("# A (random) transformation of a part of a molecule:", file=f)
print("# The translation vector is in atomic units.", file=f)
print("# Rx Ry R... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, coordinates):
"""Generate, apply and return a random manipulation""" |
transform = self.get_transformation(coordinates)
result = MolecularDistortion(self.affected_atoms, transform)
result.apply(coordinates)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_surrounding(self, center_key):
"""Iterate over all bins surrounding the given bin""" |
for shift in self.neighbor_indexes:
key = tuple(np.add(center_key, shift).astype(int))
if self.integer_cell is not None:
key = self.wrap_key(key)
bin = self._bins.get(key)
if bin is not None:
yield key, bin |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_key(self, key):
"""Translate the key into the central cell This method is only applicable in case of a periodic system. """ |
return tuple(np.round(
self.integer_cell.shortest_vector(key)
).astype(int)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_grid(self, cutoff, unit_cell, grid):
"""Choose a proper grid for the binning process""" |
if grid is None:
# automatically choose a decent grid
if unit_cell is None:
grid = cutoff/2.9
else:
# The following would be faster, but it is not reliable
# enough yet.
#grid = unit_cell.get_optimal_subcell(cut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_unit(expression):
"""Evaluate a python expression string containing constants Argument: | ``expression`` -- A string containing a numerical expressions... |
try:
g = globals()
g.update(shorthands)
return float(eval(str(expression), g))
except:
raise ValueError("Could not interpret '%s' as a unit or a measure." % expression) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parents(self):
""" Returns an simple FIFO queue with the ancestors and itself. """ |
q = self.__parent__.parents()
q.put(self)
return q |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
""" Returns the whole URL from the base to this node. """ |
path = None
nodes = self.parents()
while not nodes.empty():
path = urljoin(path, nodes.get().path())
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_required(self):
""" If any ancestor required an authentication, this node needs it too. """ |
if self._auth:
return self._auth, self
return self.__parent__.auth_required() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_graph(self, graph):
"""the atomic numbers must match""" |
if graph.num_vertices != self.size:
raise TypeError("The number of vertices in the graph does not "
"match the length of the atomic numbers array.")
# In practice these are typically the same arrays using the same piece
# of memory. Just checking to be sure.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename):
"""Construct a molecule object read from the given file. The file format is inferred from the extensions. Currently supported forma... |
# 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=[]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def com(self):
"""the center of mass of the molecule""" |
return (self.coordinates*self.masses.reshape((-1,1))).sum(axis=0)/self.mass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inertia_tensor(self):
"""the intertia tensor of the molecule""" |
result = np.zeros((3,3), float)
for i in range(self.size):
r = self.coordinates[i] - self.com
# the diagonal term
result.ravel()[::4] += self.masses[i]*(r**2).sum()
# the outer product term
result -= self.masses[i]*np.outer(r,r)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chemical_formula(self):
"""the chemical formula of the molecule""" |
counts = {}
for number in self.numbers:
counts[number] = counts.get(number, 0)+1
items = []
for number, count in sorted(counts.items(), reverse=True):
if count == 1:
items.append(periodic[number].symbol)
else:
items.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_default_masses(self):
"""Set self.masses based on self.numbers and periodic table.""" |
self.masses = np.array([periodic[n].mass for n in self.numbers]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_default_symbols(self):
"""Set self.symbols based on self.numbers and the periodic table.""" |
self.symbols = tuple(periodic[n].symbol for n in self.numbers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_to_file(self, filename):
"""Write the molecular geometry to a file. The file format is inferred from the extensions. Currently supported formats are: `... |
# 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.number... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rmsd(self, other):
"""Compute the RMSD between two molecules. Arguments: | ``other`` -- Another molecule with the same atom numbers Return values: | ``transf... |
if self.numbers.shape != other.numbers.shape or \
(self.numbers != other.numbers).all():
raise ValueError("The other molecule does not have the same numbers as this molecule.")
return fit_rmsd(self.coordinates, other.coordinates) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_rotsym(self, threshold=1e-3*angstrom):
"""Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results ... |
# 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:
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_current_label(self):
"""Get the label from the last line read""" |
if len(self._last) == 0:
raise StopIteration
return self._last[:self._last.find(":")] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_section(self):
"""Read and return an entire section""" |
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_next(self, label):
"""Get the next section with the given label""" |
while self._get_current_label() != label:
self._skip_section()
return self._read_section() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_cube_points(origin, axes, nrep):
'''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 numb... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_file(cls, filename):
'''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.
'''
with open(filename) as f:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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_line(n, v):
f.write('%5i % 11.6f % 11.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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(),
self.nrep.copy(), newdata, self.subtitle, self.nu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, child):
"""Add a child section or keyword""" |
if not (isinstance(child, CP2KSection) or isinstance(child, CP2KKeyword)):
raise TypeError("The child must be a CP2KSection or a CP2KKeyword, got: %s." % child)
l = self.__index.setdefault(child.name, [])
l.append(child)
self.__order.append(child) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_children(self, f, indent=''):
"""Dump the children of the current section to a file-like object""" |
for child in self.__order:
child.dump(f, indent+' ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, f, indent=''):
"""Dump this section and its children to a file-like object""" |
print(("%s&%s %s" % (indent, self.__name, self.section_parameters)).rstrip(), file=f)
self.dump_children(f, indent)
print("%s&END %s" % (indent, self.__name), file=f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readline(self, f):
"""A helper method that only reads uncommented lines""" |
while True:
line = f.readline()
if len(line) == 0:
raise EOFError
line = line[:line.find('#')]
line = line.strip()
if len(line) > 0:
return line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_children(self, f):
"""Load the children of this section from a file-like object""" |
while True:
line = self.readline(f)
if line[0] == '&':
if line[1:].startswith("END"):
check_name = line[4:].strip().upper()
if check_name != self.__name:
raise FileFormatError("CP2KSection end mismatch, pos=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, f, line=None):
"""Load this section from a file-like object""" |
if line is None:
# in case the file contains only a fragment of an input file,
# this is useful.
line = f.readlin()
words = line[1:].split()
self.__name = words[0].upper()
self.section_parameters = " ".join(words[1:])
try:
self.loa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, f, indent=''):
"""Dump this keyword to a file-like object""" |
if self.__unit is None:
print(("%s%s %s" % (indent, self.__name, self.__value)).rstrip(), file=f)
else:
print(("%s%s [%s] %s" % (indent, self.__name, self.__unit, self.__value)).rstrip(), file=f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, line):
"""Load this keyword from a file-like object""" |
words = line.split()
try:
float(words[0])
self.__name = ""
self.__value = " ".join(words)
except ValueError:
self.__name = words[0].upper()
if len(words) > 2 and words[1][0]=="[" and words[1][-1]=="]":
self.unit = words... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_value(self, value):
"""Set the value associated with the keyword""" |
if not isinstance(value, str):
raise TypeError("A value must be a string, got %s." % value)
self.__value = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_matrix(m):
"""Check the sanity of the given 4x4 transformation matrix""" |
if m.shape != (4, 4):
raise ValueError("The argument must be a 4x4 array.")
if max(abs(m[3, 0:3])) > eps:
raise ValueError("The given matrix does not have correct translational part")
if abs(m[3, 3] - 1.0) > eps:
raise ValueError("The lower right element of the given matrix must be ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def superpose(ras, rbs, weights=None):
"""Compute the transformation that minimizes the RMSD between the points ras and rbs Arguments: | ``ras`` -- a ``np.array`... |
if weights is None:
ma = ras.mean(axis=0)
mb = rbs.mean(axis=0)
else:
total_weight = weights.sum()
ma = np.dot(weights, ras)/total_weight
mb = np.dot(weights, rbs)/total_weight
# Kabsch
if weights is None:
A = np.dot((rbs-mb).transpose(), ras-ma)
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_rmsd(ras, rbs, weights=None):
"""Fit geometry rbs onto ras, returns more info than superpose Arguments: | ``ras`` -- a numpy array with 3D coordinates of... |
transformation = superpose(ras, rbs, weights)
rbs_trans = transformation * rbs
rmsd = compute_rmsd(ras, rbs_trans)
return transformation, rbs_trans, rmsd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inv(self):
"""The inverse translation""" |
result = Translation(-self.t)
result._cache_inv = self
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_to(self, x, columns=False):
"""Apply this translation to the given object The argument can be several sorts of objects: * ``np.array`` with shape (3, )... |
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns:
return x + self.t.reshape((3,1))
if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns:
return x + self.t
elif isinstance(x, Compl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, other, t_threshold=1e-3):
"""Compare two translations The RMSD of the translation vectors is computed. The return value is True when the RMSD i... |
return compute_rmsd(self.t, other.t) < t_threshold |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_r(self, r):
"""the columns must orthogonal""" |
if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
np.dot(r[:, 0], r[:, 1]) > eps or \
np.dot(r[:, 1], r[:, 2]) > eps or \
np.dot(r[:, 2], r[:, 0]) > eps:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_properties(cls, angle, axis, invert):
"""Initialize a rotation based on the properties""" |
norm = np.linalg.norm(axis)
if norm > 0:
x = axis[0] / norm
y = axis[1] / norm
z = axis[2] / norm
c = np.cos(angle)
s = np.sin(angle)
r = (1-2*invert) * np.array([
[x*x*(1-c)+c , x*y*(1-c)-z*s, x*z*(1-c)+y*s],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matrix(self):
"""The 4x4 matrix representation of this rotation""" |
result = np.identity(4, float)
result[0:3, 0:3] = self.r
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inv(self):
"""The inverse rotation""" |
result = Rotation(self.r.transpose())
result._cache_inv = self
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_to(self, x, columns=False):
"""Apply this rotation to the given object The argument can be several sorts of objects: * ``np.array`` with shape (3, ) * ... |
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns:
return np.dot(self.r, x)
if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns:
return np.dot(x, self.r.transpose())
elif isinstan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, other, r_threshold=1e-3):
"""Compare two rotations The RMSD of the rotation matrices is computed. The return value is True when the RMSD is bel... |
return compute_rmsd(self.r, other.r) < r_threshold |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_properties(cls, angle, axis, invert, translation):
"""Initialize a transformation based on the properties""" |
rot = Rotation.from_properties(angle, axis, invert)
return Complete(rot.r, translation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cast(cls, c):
"""Convert the first argument into a Complete object""" |
if isinstance(c, Complete):
return c
elif isinstance(c, Translation):
return Complete(np.identity(3, float), c.t)
elif isinstance(c, Rotation):
return Complete(c.r, np.zeros(3, float)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def about_axis(cls, center, angle, axis, invert=False):
"""Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the... |
return Translation(center) * \
Rotation.from_properties(angle, axis, invert) * \
Translation(-center) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inv(self):
"""The inverse transformation""" |
result = Complete(self.r.transpose(), np.dot(self.r.transpose(), -self.t))
result._cache_inv = self
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, other, t_threshold=1e-3, r_threshold=1e-3):
"""Compare two transformations The RMSD values of the rotation matrices and the translation vectors... |
return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _skip_frame(self):
"""Skip the next time frame""" |
for line in self._f:
if line == 'ITEM: ATOMS\n':
break
for i in range(self.num_atoms):
next(self._f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_atom_info(self, atom_info):
"""Add an atom info object to the database""" |
self.atoms_by_number[atom_info.number] = atom_info
self.atoms_by_symbol[atom_info.symbol.lower()] = atom_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, other):
"""Extend the current cluster with data from another cluster""" |
Cluster.update(self, other)
self.rules.extend(other.rules) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_related(self, *objects):
"""Add related items The arguments can be individual items or cluster objects containing several items. When two groups of relat... |
master = None # this will become the common cluster of all related items
slaves = set([]) # set of clusters that are going to be merged in the master
solitaire = set([]) # set of new items that are not yet part of a cluster
for new in objects:
if isinstance(new, self.cls):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def goto_next_frame(self):
"""Continue reading until the next frame is reached""" |
marked = False
while True:
line = next(self._f)[:-1]
if marked and len(line) > 0 and not line.startswith(" --------"):
try:
step = int(line[:10])
return step, line
except ValueError:
pass... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_frame(self):
"""Read a frame from the XYZ file""" |
size = self.read_size()
title = self._f.readline()[:-1]
if self.symbols is None:
symbols = []
coordinates = np.zeros((size, 3), float)
for counter in range(size):
line = self._f.readline()
if len(line) == 0:
raise StopIteratio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _skip_frame(self):
"""Skip a single frame from the trajectory""" |
size = self.read_size()
for i in range(size+1):
line = self._f.readline()
if len(line) == 0:
raise StopIteration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_first_molecule(self):
"""Get the first molecule from the trajectory This can be useful to configure your program before handeling the actual trajectory. ... |
title, coordinates = self._first
molecule = Molecule(self.numbers, coordinates, title, symbols=self.symbols)
return molecule |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, title, coordinates):
"""Dump a frame to the trajectory file Arguments: | ``title`` -- the title of the frame | ``coordinates`` -- a numpy array wi... |
print("% 8i" % len(self.symbols), file=self._f)
print(str(title), file=self._f)
for symbol, coordinate in zip(self.symbols, coordinates):
print("% 2s % 12.9f % 12.9f % 12.9f" % ((symbol, ) + tuple(coordinate/self.file_unit)), file=self._f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_molecule(self, index=0):
"""Get a molecule from the trajectory Optional argument: | ``index`` -- The frame index [default=0] """ |
return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_to_file(self, f, file_unit=angstrom):
"""Write the trajectory to a file Argument: | ``f`` -- a filename or a file-like object to write to Optional argu... |
xyz_writer = XYZWriter(f, self.symbols, file_unit=file_unit)
for title, coordinates in zip(self.titles, self.geometries):
xyz_writer.dump(title, coordinates) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_anagrad(fun, x0, epsilon, threshold):
"""Check the analytical gradient using finite differences Arguments: | ``fun`` -- the function to be tested, more... |
N = len(x0)
f0, ana_grad = fun(x0, do_gradient=True)
for i in range(N):
xh = x0.copy()
xh[i] += 0.5*epsilon
xl = x0.copy()
xl[i] -= 0.5*epsilon
num_grad_comp = (fun(xh)-fun(xl))/epsilon
if abs(num_grad_comp - ana_grad[i]) > threshold:
raise Assert... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_delta(fun, x, dxs, period=None):
"""Check the difference between two function values using the analytical gradient Arguments: | ``fun`` -- The function... |
dn1s = []
dn2s = []
dnds = []
for dx in dxs:
f0, grad0 = fun(x, do_gradient=True)
f1, grad1 = fun(x+dx, do_gradient=True)
grad = 0.5*(grad0+grad1)
d1 = f1 - f0
if period is not None:
d1 -= np.floor(d1/period + 0.5)*period
if hasattr(d1, '__ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_fd_hessian(fun, x0, epsilon, anagrad=True):
"""Compute the Hessian using the finite difference method Arguments: | ``fun`` -- the function for which ... |
N = len(x0)
def compute_gradient(x):
if anagrad:
return fun(x, do_gradient=True)[1]
else:
gradient = np.zeros(N, float)
for i in range(N):
xh = x.copy()
xh[i] += 0.5*epsilon
xl = x.copy()
xl[i] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 * beta - self.gradient
self.status = "CG" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def limit_step(self, step):
"""Clip the a step within the maximum allowed range""" |
if self.qmax is None:
return step
else:
return np.clip(step, -self.qmax, self.qmax) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bracket(self, qinit, f0, fun):
"""Find a bracket that does contain the minimum""" |
self.num_bracket = 0
qa = qinit
fa = fun(qa)
counter = 0
if fa >= f0:
while True:
self.num_bracket += 1
#print " bracket shrink"
qb, fb = qa, fa
qa /= 1+phi
fa = fun(qa)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _golden(self, triplet, fun):
"""Reduce the size of the bracket until the minimum is found""" |
self.num_golden = 0
(qa, fa), (qb, fb), (qc, fc) = triplet
while True:
self.num_golden += 1
qd = qa + (qb-qa)*phi/(1+phi)
fd = fun(qd)
if fd < fb:
#print "golden d"
(qa, fa), (qb, fb) = (qb, fb), (qd, fd)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do(self, x_orig):
"""Transform the unknowns to preconditioned coordinates This method also transforms the gradient to original coordinates """ |
if self.scales is None:
return x_orig
else:
return np.dot(self.rotation.transpose(), x_orig)*self.scales |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo(self, x_prec):
"""Transform the unknowns to original coordinates This method also transforms the gradient to preconditioned coordinates """ |
if self.scales is None:
return x_prec
else:
return np.dot(self.rotation, x_prec/self.scales) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_header(self):
"""Returns the header for screen logging of the minimization""" |
result = " "
if self.step_rms is not None:
result += " Step RMS"
if self.step_max is not None:
result += " Step MAX"
if self.grad_rms is not None:
result += " Grad RMS"
if self.grad_max is not None:
result += " Grad MAX... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, x0, axis):
"""Configure the 1D function for a line search Arguments: x0 -- the reference point (q=0) axis -- a unit vector in the direction o... |
self.x0 = x0
self.axis = axis |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _rough_shake(self, x, normals, values, error):
'''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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def free_shake(self, x):
'''Brings unknowns to the constraints.
Arguments:
| ``x`` -- The unknowns.
'''
self.lock[:] = False
normals, values, error = self._compute_equations(x)[:-1]
counter = 0
while True:
if error <= self.threshold:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def safe_shake(self, x, fun, fmax):
'''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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_final(self):
"""Return the final solution in the original coordinates""" |
if self.prec is None:
return self.x
else:
return self.prec.undo(self.x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run(self):
"""Run the iterative optimizer""" |
success = self.initialize()
while success is None:
success = self.propagate()
return success |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_header(self):
"""Print the header for screen logging""" |
header = " Iter Dir "
if self.constraints is not None:
header += ' SC CC'
header += " Function"
if self.convergence_condition is not None:
header += self.convergence_condition.get_header()
header += " Time"
self._screen("-"*(len(head... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=' ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
except ConstraintError:
self._screen("CONSTRAINT PROJECT FAILED", newline=True)
return False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def neighbors(self):
"""A dictionary with neighbors The dictionary will have the following form: This means that vertexX and vertexY1 are connected etc. This als... |
neighbors = dict(
(vertex, []) for vertex
in range(self.num_vertices)
)
for a, b in self.edges:
neighbors[a].append(b)
neighbors[b].append(a)
# turn lists into frozensets
neighbors = dict((key, frozenset(val)) for key, val in neigh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 big integer
#distances.ravel()[::len(distances)+1] = 0 # set diagonal to zero
for i, j in self.edges: # set edges to one
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 == max_distances_min).nonzero()[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def independent_vertices(self):
"""Lists of vertices that are only interconnected within each list This means that there is no path from a vertex in one list to ... |
candidates = set(range(self.num_vertices))
result = []
while len(candidates) > 0:
pivot = candidates.pop()
group = [
vertex for vertex, distance
in self.iter_breadth_first(pivot)
]
candidates.difference_update(grou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fingerprint(self):
"""A total graph fingerprint The result is invariant under permutation of the vertex indexes. The chance that two different (molecular) gr... |
if self.num_vertices == 0:
return np.zeros(20, np.ubyte)
else:
return sum(self.vertex_fingerprints) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vertex_fingerprints(self):
"""A fingerprint for each vertex The result is invariant under permutation of the vertex indexes. Vertices that are symmetrically ... |
return self.get_vertex_fingerprints(
[self.get_vertex_string(i) for i in range(self.num_vertices)],
[self.get_edge_string(i) for i in range(self.num_edges)],
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.