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 atoms never contain atom1!
yield affected_atoms, (atom1, atom2, atom3)
continue
except GraphError:
pass
try:
affected_atoms = graph.get_halfs(atom2, atom3)[0]
# the affected atoms never contain atom3!
yield affected_atoms, (atom3, atom2, atom1)
except GraphError:
pass |
<SYSTEM_TASK:>
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_atoms2, hinge_atoms
except GraphError:
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 check_nonbond(molecule, thresholds):
"""Check whether all nonbonded atoms are well separated. If a nonbond atom pair is found that has an interatomic distance below the given thresholds. The thresholds dictionary has the following format: {frozenset([atom_number1, atom_number2]):
distance} When random geometries are generated for sampling the conformational space of a molecule without strong repulsive nonbonding interactions, try to underestimate the thresholds at first instance and exclude bond stretches and bending motions for the random manipuulations. Then compute the forces projected on the nonbonding distance gradients. The distance for which the absolute value of these gradients drops below 100 kJ/mol is a coarse guess of a proper threshold value. """ |
# check that no atoms overlap
for atom1 in range(molecule.graph.num_vertices):
for atom2 in range(atom1):
if molecule.graph.distances[atom1, atom2] > 2:
distance = np.linalg.norm(molecule.coordinates[atom1] - molecule.coordinates[atom2])
if distance < thresholds[frozenset([molecule.numbers[atom1], molecule.numbers[atom2]])]:
return False
return True |
<SYSTEM_TASK:>
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 be generated that survives the nonbond check after max_tries repetitions, None is returned. In case of success, the randomized molecule is returned. The original molecule is not altered. """ |
for m in range(max_tries):
random_molecule = randomize_molecule_low(molecule, manipulations)
if check_nonbond(random_molecule, nonbond_thresholds):
return random_molecule |
<SYSTEM_TASK:>
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 be generated that survives the nonbond check after max_tries repetitions, None is returned. In case of success, the randomized molecule and the corresponding transformation is returned. The original molecule is not altered. """ |
for m in range(max_tries):
random_molecule, transformation = single_random_manipulation_low(molecule, manipulations)
if check_nonbond(random_molecule, nonbond_thresholds):
return random_molecule, transformation
return None |
<SYSTEM_TASK:>
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 relative positions. Interatomic distances are above the thresholds. Initially a dimer is created where one interatomic distance approximates the threshold value. Then the molecules are given an additional separation in the range [0, shoot_max]. thresholds has the following format: {frozenset([atom_number1, atom_number2]):
distance} """ |
# apply a random rotation to molecule1
center = np.zeros(3, float)
angle = np.random.uniform(0, 2*np.pi)
axis = random_unit()
rotation = Complete.about_axis(center, angle, axis)
cor1 = np.dot(molecule1.coordinates, rotation.r)
# select a random atom in each molecule
atom0 = np.random.randint(len(molecule0.numbers))
atom1 = np.random.randint(len(molecule1.numbers))
# define a translation of molecule1 that brings both atoms in overlap
delta = molecule0.coordinates[atom0] - cor1[atom1]
cor1 += delta
# define a random direction
direction = random_unit()
cor1 += 1*direction
# move molecule1 along this direction until all intermolecular atomic
# distances are above the threshold values
threshold_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float)
distance_mat = np.zeros((len(molecule0.numbers), len(molecule1.numbers)), float)
for i1, n1 in enumerate(molecule0.numbers):
for i2, n2 in enumerate(molecule1.numbers):
threshold = thresholds.get(frozenset([n1, n2]))
threshold_mat[i1, i2] = threshold**2
while True:
cor1 += 0.1*direction
distance_mat[:] = 0
for i in 0, 1, 2:
distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2
if (distance_mat > threshold_mat).all():
break
# translate over a random distance [0, shoot] along the same direction
# (if necessary repeat until no overlap is found)
while True:
cor1 += direction*np.random.uniform(0, shoot_max)
distance_mat[:] = 0
for i in 0, 1, 2:
distance_mat += np.subtract.outer(molecule0.coordinates[:, i], cor1[:, i])**2
if (distance_mat > threshold_mat).all():
break
# done
dimer = Molecule(
np.concatenate([molecule0.numbers, molecule1.numbers]),
np.concatenate([molecule0.coordinates, cor1])
)
dimer.direction = direction
dimer.atom0 = atom0
dimer.atom1 = atom1
return dimer |
<SYSTEM_TASK:>
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 = Complete(r, t)
affected_atoms = set(int(word) for word in lines[3].split())
return cls(affected_atoms, transformation) |
<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 Rz T", file=f)
print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[0, 0], r[0, 1], r[0, 2], t[0]), file=f)
print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[1, 0], r[1, 1], r[1, 2], t[1]), file=f)
print("% 15.9e % 15.9e % 15.9e % 15.9e" % (r[2, 0], r[2, 1], r[2, 2], t[2]), file=f)
print("# The indexes of the affected atoms:", file=f)
print(" ".join(str(i) for i in self.affected_atoms), file=f) |
<SYSTEM_TASK:>
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(cutoff/2.0)
divisions = np.ceil(unit_cell.spacings/cutoff)
divisions[divisions<1] = 1
grid = unit_cell/divisions
if isinstance(grid, float):
grid_cell = UnitCell(np.array([
[grid, 0, 0],
[0, grid, 0],
[0, 0, grid]
]))
elif isinstance(grid, UnitCell):
grid_cell = grid
else:
raise TypeError("Grid must be None, a float or a UnitCell instance.")
if unit_cell is not None:
# The columns of integer_matrix are the unit cell vectors in
# fractional coordinates of the grid cell.
integer_matrix = grid_cell.to_fractional(unit_cell.matrix.transpose()).transpose()
if abs((integer_matrix - np.round(integer_matrix))*self.unit_cell.active).max() > 1e-6:
raise ValueError("The unit cell vectors are not an integer linear combination of grid cell vectors.")
integer_matrix = integer_matrix.round()
integer_cell = UnitCell(integer_matrix, unit_cell.active)
else:
integer_cell = None
return grid_cell, integer_cell |
<SYSTEM_TASK:>
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 including unit conversions. In addition to the variables in this module, also the following shorthands are supported: """ |
try:
g = globals()
g.update(shorthands)
return float(eval(str(expression), g))
except:
raise ValueError("Could not interpret '%s' as a unit or a measure." % expression) |
<SYSTEM_TASK:>
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.
if (self.numbers != graph.numbers).any():
raise TypeError("The atomic numbers in the graph do not match the "
"atomic numbers in the molecule.") |
<SYSTEM_TASK:>
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 formats are: ``*.cml``, ``*.fchk``, ``*.pdb``, ``*.sdf``, ``*.xyz`` If a file contains more than one molecule, only the first one is read. Argument: | ``filename`` -- the name of the file containing the molecule Example usage:: """ |
# TODO: many different API's to load files. brrr...
if filename.endswith(".cml"):
from molmod.io import load_cml
return load_cml(filename)[0]
elif filename.endswith(".fchk"):
from molmod.io import FCHKFile
fchk = FCHKFile(filename, field_labels=[])
return fchk.molecule
elif filename.endswith(".pdb"):
from molmod.io import load_pdb
return load_pdb(filename)
elif filename.endswith(".sdf"):
from molmod.io import SDFReader
return next(SDFReader(filename))
elif filename.endswith(".xyz"):
from molmod.io import XYZReader
xyz_reader = XYZReader(filename)
title, coordinates = next(xyz_reader)
return Molecule(xyz_reader.numbers, coordinates, title, symbols=xyz_reader.symbols)
else:
raise ValueError("Could not determine file format for %s." % filename) |
<SYSTEM_TASK:>
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 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 chemical_formula(self):
"""the chemical formula of the molecule""" |
counts = {}
for number in self.numbers:
counts[number] = counts.get(number, 0)+1
items = []
for number, count in sorted(counts.items(), reverse=True):
if count == 1:
items.append(periodic[number].symbol)
else:
items.append("%s%i" % (periodic[number].symbol, count))
return "".join(items) |
<SYSTEM_TASK:>
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: ``*.xyz``, ``*.cml`` Argument: | ``filename`` -- a filename """ |
# TODO: give all file format writers the same API
if filename.endswith('.cml'):
from molmod.io import dump_cml
dump_cml(filename, [self])
elif filename.endswith('.xyz'):
from molmod.io import XYZWriter
symbols = []
for n in self.numbers:
atom = periodic[n]
if atom is None:
symbols.append("X")
else:
symbols.append(atom.symbol)
xyz_writer = XYZWriter(filename, symbols)
xyz_writer.dump(self.title, self.coordinates)
del xyz_writer
else:
raise ValueError("Could not determine file format for %s." % filename) |
<SYSTEM_TASK:>
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: | ``transformation`` -- the transformation that brings 'self' into overlap with 'other' | ``other_trans`` -- the transformed coordinates of geometry 'other' | ``rmsd`` -- the rmsd of the distances between corresponding atoms in 'self' and 'other' Make sure the atoms in `self` and `other` are in the same order. Usage:: """ |
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 in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself. """ |
# Generate a graph with a more permissive threshold for bond lengths:
# (is convenient in case of transition state geometries)
graph = MolecularGraph.from_geometry(self, scaling=1.5)
try:
return compute_rotsym(self, graph, threshold)
except ValueError:
raise ValueError("The rotational symmetry number can only be computed when the graph is fully connected.") |
<SYSTEM_TASK:>
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 number of grid points along each axis.
'''
points = np.zeros((nrep[0], nrep[1], nrep[2], 3), float)
points[:] = origin
points[:] += np.outer(np.arange(nrep[0], dtype=float), axes[0]).reshape((-1,1,1,3))
points[:] += np.outer(np.arange(nrep[1], dtype=float), axes[1]).reshape((1,-1,1,3))
points[:] += np.outer(np.arange(nrep[2], dtype=float), axes[2]).reshape((1,1,-1,3))
return points |
<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:
molecule, origin, axes, nrep, subtitle, nuclear_charges = \
read_cube_header(f)
data = np.zeros(tuple(nrep), float)
tmp = data.ravel()
counter = 0
while True:
line = f.readline()
if len(line) == 0:
break
words = line.split()
for word in words:
tmp[counter] = float(word)
counter += 1
return cls(molecule, origin, axes, nrep, data, subtitle, nuclear_charges) |
<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.6f % 11.6f\n' % (n, v[0], v[1], v[2]))
write_grid_line(self.molecule.size, self.origin)
write_grid_line(self.data.shape[0], self.axes[0])
write_grid_line(self.data.shape[1], self.axes[1])
write_grid_line(self.data.shape[2], self.axes[2])
def write_atom_line(n, nc, v):
f.write('%5i % 11.6f % 11.6f % 11.6f % 11.6f\n' % (n, nc, v[0], v[1], v[2]))
for i in range(self.molecule.size):
write_atom_line(self.molecule.numbers[i], self.nuclear_charges[i],
self.molecule.coordinates[i])
for i0 in range(self.data.shape[0]):
for i1 in range(self.data.shape[1]):
col = 0
for i2 in range(self.data.shape[2]):
value = self.data[i0, i1, i2]
if col % 6 == 5:
f.write(' % 12.5e\n' % value)
else:
f.write(' % 12.5e' % value)
col += 1
if col % 6 != 5:
f.write('\n') |
<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.nuclear_charges
) |
<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=%s", f.tell())
break
else:
section = CP2KSection()
section.load(f, line)
self.append(section)
else:
keyword = CP2KKeyword()
keyword.load(line)
self.append(keyword) |
<SYSTEM_TASK:>
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.load_children(f)
except EOFError:
raise FileFormatError("Unexpected end of file, section '%s' not ended." % self.__name) |
<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[1][1:-1]
self.__value = " ".join(words[2:])
else:
self.__value = " ".join(words[1:]) |
<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 1.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 superpose(ras, rbs, weights=None):
"""Compute the transformation that minimizes the RMSD between the points ras and rbs Arguments: | ``ras`` -- a ``np.array`` with 3D coordinates of geometry A, shape=(N,3) | ``rbs`` -- a ``np.array`` with 3D coordinates of geometry B, shape=(N,3) Optional arguments: | ``weights`` -- a numpy array with fitting weights for each coordinate, shape=(N,) Return value: | ``transformation`` -- the transformation that brings geometry A into overlap with geometry B Each row in ras and rbs represents a 3D coordinate. Corresponding rows contain the points that are brought into overlap by the fitting procedure. The implementation is based on the Kabsch Algorithm: http://dx.doi.org/10.1107%2FS0567739476001873 """ |
if weights is None:
ma = ras.mean(axis=0)
mb = rbs.mean(axis=0)
else:
total_weight = weights.sum()
ma = np.dot(weights, ras)/total_weight
mb = np.dot(weights, rbs)/total_weight
# Kabsch
if weights is None:
A = np.dot((rbs-mb).transpose(), ras-ma)
else:
weights = weights.reshape((-1, 1))
A = np.dot(((rbs-mb)*weights).transpose(), (ras-ma)*weights)
v, s, wt = np.linalg.svd(A)
s[:] = 1
if np.linalg.det(np.dot(v, wt)) < 0:
s[2] = -1
r = np.dot(wt.T*s, v.T)
return Complete(r, np.dot(r, -mb) + ma) |
<SYSTEM_TASK:>
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 geometry A, shape=(N,3) | ``rbs`` -- a numpy array with 3D coordinates of geometry B, shape=(N,3) Optional arguments: | ``weights`` -- a numpy array with fitting weights for each coordinate, shape=(N,) Return values: | ``transformation`` -- the transformation that brings geometry A into overlap with geometry B | ``rbs_trans`` -- the transformed coordinates of geometry B | ``rmsd`` -- the rmsd of the distances between corresponding atoms in geometry A and B This is a utility routine based on the function superpose. It just computes rbs_trans and rmsd after calling superpose with the same arguments """ |
transformation = superpose(ras, rbs, weights)
rbs_trans = transformation * rbs
rmsd = compute_rmsd(ras, rbs_trans)
return transformation, rbs_trans, rmsd |
<SYSTEM_TASK:>
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, ) * ``np.array`` with shape (N, 3) * ``np.array`` with shape (3, N), use ``columns=True`` * ``Translation`` * ``Rotation`` * ``Complete`` * ``UnitCell`` In case of arrays, the 3D vectors are translated. In case of trans- formations, a new transformation is returned that consists of this translation applied AFTER the given translation. In case of a unit cell, the original object is returned. This method is equivalent to ``self*x``. """ |
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns:
return x + self.t.reshape((3,1))
if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns:
return x + self.t
elif isinstance(x, Complete):
return Complete(x.r, x.t + self.t)
elif isinstance(x, Translation):
return Translation(x.t + self.t)
elif isinstance(x, Rotation):
return Complete(x.r, self.t)
elif isinstance(x, UnitCell):
return x
else:
raise ValueError("Can not apply this translation to %s" % x) |
<SYSTEM_TASK:>
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 is below the threshold, i.e. when the two translations are almost identical. """ |
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:
raise ValueError("The rotation matrix is significantly non-orthonormal.") |
<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],
[x*y*(1-c)+z*s, y*y*(1-c)+c , y*z*(1-c)-x*s],
[x*z*(1-c)-y*s, y*z*(1-c)+x*s, z*z*(1-c)+c ]
])
else:
r = np.identity(3) * (1-2*invert)
return cls(r) |
<SYSTEM_TASK:>
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, ) * ``np.array`` with shape (N, 3) * ``np.array`` with shape (3, N), use ``columns=True`` * ``Translation`` * ``Rotation`` * ``Complete`` * ``UnitCell`` In case of arrays, the 3D vectors are rotated. In case of trans- formations, a transformation is returned that consists of this rotation applied AFTER the given translation. In case of a unit cell, a unit cell with rotated cell vectors is returned. This method is equivalent to ``self*x``. """ |
if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns:
return np.dot(self.r, x)
if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns:
return np.dot(x, self.r.transpose())
elif isinstance(x, Complete):
return Complete(np.dot(self.r, x.r), np.dot(self.r, x.t))
elif isinstance(x, Translation):
return Complete(self.r, np.dot(self.r, x.t))
elif isinstance(x, Rotation):
return Rotation(np.dot(self.r, x.r))
elif isinstance(x, UnitCell):
return UnitCell(np.dot(self.r, x.matrix), x.active)
else:
raise ValueError("Can not apply this rotation to %s" % x) |
<SYSTEM_TASK:>
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 below the threshold, i.e. when the two rotations are almost identical. """ |
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 axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- When True, an inversion rotation is constructed [default=False] """ |
return Translation(center) * \
Rotation.from_properties(angle, axis, invert) * \
Translation(-center) |
<SYSTEM_TASK:>
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 are computed. The return value is True when the RMSD values are below the thresholds, i.e. when the two transformations are almost identical. """ |
return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold |
<SYSTEM_TASK:>
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 related items share one or more common members, they will be merged into one cluster. """ |
master = None # this will become the common cluster of all related items
slaves = set([]) # set of clusters that are going to be merged in the master
solitaire = set([]) # set of new items that are not yet part of a cluster
for new in objects:
if isinstance(new, self.cls):
if master is None:
master = new
else:
slaves.add(new)
for item in new.items:
existing = self.lookup.get(item)
if existing is not None:
slaves.add(existing)
else:
cluster = self.lookup.get(new)
if cluster is None:
#print "solitaire", new
solitaire.add(new)
elif master is None:
#print "starting master", new
master = cluster
elif master != cluster:
#print "in slave", new
slaves.add(cluster)
#else:
##nothing to do
#print "new in master", new
if master is None:
master = self.cls([])
for slave in slaves:
master.update(slave)
for item in solitaire:
master.add_item(item)
for item in master.items:
self.lookup[item] = master |
<SYSTEM_TASK:>
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
marked = (len(line) == 131 and line == self._marker) |
<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 StopIteration
words = line.split()
if len(words) < 4:
raise StopIteration
if self.symbols is None:
symbols.append(words[0])
try:
coordinates[counter, 0] = float(words[1])
coordinates[counter, 1] = float(words[2])
coordinates[counter, 2] = float(words[3])
except ValueError:
raise StopIteration
coordinates *= self.file_unit
if self.symbols is None:
self.symbols = symbols
return title, coordinates |
<SYSTEM_TASK:>
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 with coordinates in atomic units """ |
print("% 8i" % len(self.symbols), file=self._f)
print(str(title), file=self._f)
for symbol, coordinate in zip(self.symbols, coordinates):
print("% 2s % 12.9f % 12.9f % 12.9f" % ((symbol, ) + tuple(coordinate/self.file_unit)), file=self._f) |
<SYSTEM_TASK:>
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 argument: | ``file_unit`` -- the unit of the values written to file [default=angstrom] """ |
xyz_writer = XYZWriter(f, self.symbols, file_unit=file_unit)
for title, coordinates in zip(self.titles, self.geometries):
xyz_writer.dump(title, coordinates) |
<SYSTEM_TASK:>
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 info below | ``x0`` -- the reference point around which the function should be tested | ``epsilon`` -- a small scalar used for the finite differences | ``threshold`` -- the maximum acceptable difference between the analytical gradient and the gradient obtained by finite differentiation The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- the arguments of the function to be tested | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned [default=False] """ |
N = len(x0)
f0, ana_grad = fun(x0, do_gradient=True)
for i in range(N):
xh = x0.copy()
xh[i] += 0.5*epsilon
xl = x0.copy()
xl[i] -= 0.5*epsilon
num_grad_comp = (fun(xh)-fun(xl))/epsilon
if abs(num_grad_comp - ana_grad[i]) > threshold:
raise AssertionError("Error in the analytical gradient, component %i, got %s, should be about %s" % (i, ana_grad[i], num_grad_comp)) |
<SYSTEM_TASK:>
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 to be tested, more info below. | ``x`` -- The argument vector. | ``dxs`` -- A matrix where each row is a vector of small differences to be added to the argument vector. Optional argument: | ``period`` -- If the function value is periodic, one may provide the period such that differences are computed using periodic boundary conditions. The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- The arguments of the function to be tested. | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned. [default=False] For every row in dxs, the following computation is repeated: 1) D1 = 'f(x+dx) - f(x)' is computed. 2) D2 = '0.5 (grad f(x+dx) + grad f(x)) . dx' is computed. A threshold is set to the median of the D1 set. For each case where |D1| is larger than the threshold, |D1 - D2|, should be smaller than the threshold. """ |
dn1s = []
dn2s = []
dnds = []
for dx in dxs:
f0, grad0 = fun(x, do_gradient=True)
f1, grad1 = fun(x+dx, do_gradient=True)
grad = 0.5*(grad0+grad1)
d1 = f1 - f0
if period is not None:
d1 -= np.floor(d1/period + 0.5)*period
if hasattr(d1, '__iter__'):
norm = np.linalg.norm
else:
norm = abs
d2 = np.dot(grad, dx)
dn1s.append(norm(d1))
dn2s.append(norm(d2))
dnds.append(norm(d1-d2))
dn1s = np.array(dn1s)
dn2s = np.array(dn2s)
dnds = np.array(dnds)
# Get the threshold (and mask)
threshold = np.median(dn1s)
mask = dn1s > threshold
# Make sure that all cases for which dn1 is above the treshold, dnd is below
# the threshold
if not (dnds[mask] < threshold).all():
raise AssertionError((
'The first order approximation on the difference is too wrong. The '
'threshold is %.1e.\n\nDifferences:\n%s\n\nFirst order '
'approximation to differences:\n%s\n\nAbsolute errors:\n%s')
% (threshold,
' '.join('%.1e' % v for v in dn1s[mask]),
' '.join('%.1e' % v for v in dn2s[mask]),
' '.join('%.1e' % v for v in dnds[mask])
)) |
<SYSTEM_TASK:>
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 the Hessian should be computed, more info below | ``x0`` -- the point at which the Hessian must be computed | ``epsilon`` -- a small scalar step size used to compute the finite differences Optional argument: | ``anagrad`` -- when True, analytical gradients are used [default=True] The function ``fun`` takes a mandatory argument ``x`` and an optional argument ``do_gradient``: | ``x`` -- the arguments of the function to be tested | ``do_gradient`` -- When False, only the function value is returned. When True, a 2-tuple with the function value and the gradient are returned [default=False] """ |
N = len(x0)
def compute_gradient(x):
if anagrad:
return fun(x, do_gradient=True)[1]
else:
gradient = np.zeros(N, float)
for i in range(N):
xh = x.copy()
xh[i] += 0.5*epsilon
xl = x.copy()
xl[i] -= 0.5*epsilon
gradient[i] = (fun(xh)-fun(xl))/epsilon
return gradient
hessian = np.zeros((N,N), float)
for i in range(N):
xh = x0.copy()
xh[i] += 0.5*epsilon
xl = x0.copy()
xl[i] -= 0.5*epsilon
hessian[i] = (compute_gradient(xh) - compute_gradient(xl))/epsilon
return 0.5*(hessian + hessian.transpose()) |
<SYSTEM_TASK:>
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)
if qa < self.qtol:
return
if fa < f0:
return (0, f0), (qa, fa), (qb, fb)
counter += 1
if self.max_iter is not None and counter > self.max_iter:
return
else:
self.num_bracket += 1
#print " bracket grow1"
qb, fb = qa, fa
qa *= (1+phi)
fa = fun(qa)
if fa >= fb:
return (0, f0), (qb, fb), (qa, fa)
while True:
self.num_bracket += 1
#print " bracket grow2"
qc, fc = qb, fb
qb, fb = qa, fa
qa = qb*(1+phi) - qc
fa = fun(qa)
if fa >= fb:
return (qc, fc), (qb, fb), (qa, fa)
counter += 1
if self.max_iter is not None and counter > self.max_iter:
return |
<SYSTEM_TASK:>
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)
else:
#print "golden b"
(qa, fa), (qc, fc) = (qd, fd), (qa, fa)
if abs(qa-qb) < self.qtol:
return qc, fc |
<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"
if self.rel_grad_rms is not None:
result += " Grad/F RMS"
if self.rel_grad_max is not None:
result += " Grad/F MAX"
return result |
<SYSTEM_TASK:>
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 of the line search """ |
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 one gradient.
| ``values`` -- A numpy array with the values of the constraint
functions.
| ``error`` -- The square root of the constraint cost function.
'''
counter = 0
while error > self.threshold and counter < self.max_iter:
dxs = []
for i in range(len(normals)):
dx = -normals[i]*values[i]/np.dot(normals[i], normals[i])
dxs.append(dx)
dxs = np.array(dxs)
dx = dxs[abs(values).argmax()]
x = x+dx
self.lock[:] = False
normals, values, error = self._compute_equations(x)[:-1]
counter += 1
return x, normals, values, error |
<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:
break
# try a well-behaved move to the constrains
result = self._fast_shake(x, normals, values, error)
counter += 1
if result is not None:
x, normals, values, error = result
else:
# well-behaved move is too slow.
# do a cumbersome move to satisfy constraints approximately.
x, normals, values, error = self._rough_shake(x, normals, values, error)
counter += 1
# When too many iterations are required, just give up.
if counter > self.max_iter:
raise ConstraintError('Exceeded maximum number of shake iterations.')
return x, counter, len(values) |
<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
minimized.
The function ``fun`` takes a mandatory argument ``x`` and an optional
argument ``do_gradient``:
| ``x`` -- the arguments of the function to be tested
| ``do_gradient`` -- when False, only the function value is
returned. when True, a 2-tuple with the
function value and the gradient are returned
[default=False]
'''
self.lock[:] = False
def extra_equation(xx):
f, g = fun(xx, do_gradient=True)
return (f-fmax)/abs(fmax), g/abs(fmax)
self.equations.append((-1,extra_equation))
x, shake_counter, constraint_couter = self.free_shake(x)
del self.equations[-1]
return x, shake_counter, constraint_couter |
<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(header)), newline=True)
self._screen(header, newline=True)
self._screen("-"*(len(header)), newline=True) |
<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
direction_norm = np.linalg.norm(direction)
if direction_norm == 0:
return False
self.line.configure(self.x, direction/direction_norm)
success, wolfe, qopt, fopt = \
self.line_search(self.line, self.initial_step_size, self.epsilon)
if success:
self.step = qopt*self.line.axis
self.initial_step_size = np.linalg.norm(self.step)
self.x = self.x + self.step
self.f = fopt
if wolfe:
self._screen("W")
else:
self._screen(" ")
self.search_direction.reset()
return True
else:
if self.debug_line:
import matplotlib.pyplot as pt
import datetime
pt.clf()
qs = np.arange(0.0, 100.1)*(5*self.initial_step_size/100.0)
fs = np.array([self.line(q) for q in qs])
pt.plot(qs, fs)
pt.xlim(qs[0], qs[-1])
fdelta = fs.max() - fs.min()
if fdelta == 0.0:
fdelta = fs.mean()
fmargin = fdelta*0.1
pt.ylim(fs.min() - fmargin, fs.max() + fmargin)
pt.title('fdelta = %.2e fmean = %.2e' % (fdelta, fs.mean()))
pt.xlabel('Line coordinate, q')
pt.ylabel('Function value, f')
pt.savefig('line_failed_%s.png' % (datetime.datetime.now().isoformat()))
self._reset_state()
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 also implies that the following elements are part of the dictionary: """ |
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 neighbors.items())
return neighbors |
<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
distances[i, j] = 1
distances[j, i] = 1
graphs_floyd_warshall(distances)
return distances |
<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 a vertex in another list. In case of a molecular graph, this would yield the atoms that belong to individual molecules. """ |
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(group)
# this sort makes sure that the order of the vertices is respected
group.sort()
result.append(group)
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 fingerprint(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.)""" |
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 equivalent will get the same fingerprint, e.g. the hydrogens in methane would get the same fingerprint. """ |
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.