output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
data["energy"] = float(f.readline().split()[1])
N = len(data["symbols"])
# if the data are already read before, just overwrite them
gradient = data.get("gradient")
if gradient is None:
gradient ... | Create a Python 3 function to
read the energy and gradient from a Punch file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
line = f.readline()
assert(line == " $HESS\n")
while line != " $END\n":
line = f.readline() | How would you implement a function in Python 3 that
reads a single HESS or ALM. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read a single entry from the Punch file. | Given the following Python 3 function, write the documentation
def read(self, line, f, data):
assert("hessian" not in data)
f.readline()
N = len(data["symbols"])
hessian = np.zeros((3*N, 3*N), float)
tmp = hessian.ravel()
counter = 0
while True:
line =... | You are a Python code generator, capable of creating scripts from specifications. |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
N = len(data["symbols"])
masses = np.zeros(N, float)
counter = 0
while counter < N:
words = f.readline().split()
for word in words:
masses[counter] = float(word)*amu
... | How would you code a function in Python 3 to
read the masses from a Punch file. | As a python code expert, you are capable of creating scripts from specifications. |
Create a simple ForceField object for hydrocarbons based on the graph. | Can you generate a brief explanation for the following Python 3 code
def setup_hydrocarbon_ff(graph):
# A) Define parameters.
# the bond parameters:
bond_params = {
(6, 1): 310*kcalmol/angstrom**2,
(6, 6): 220*kcalmol/angstrom**2,
}
# for every (a, b), also add (b, a)
for key, va... | As a python code expert, you are capable of creating scripts from specifications. |
def add_to_hessian(self, coordinates, hessian):
"""Add the contributions of this energy term to the Hessian
Arguments:
| ``coordinates`` -- A numpy array with 3N Cartesian coordinates.
| ``hessian`` -- A matrix for the full Hessian to which this energy
... | Write a Python 3 script to
add the contributions of this energy term to the Hessian. | As a Python code composer, you craft elegant and concise scripts. |
Compute the force - field Hessian for the given coordinates. | Can you tell what is the following Python 3 function doing
def hessian(self, coordinates):
# N3 is 3 times the number of atoms.
N3 = coordinates.size
# Start with a zero hessian.
hessian = numpy.zeros((N3,N3), float)
# Add the contribution of each term.
for term in self.t... | As a Python code composer, you craft elegant and concise scripts. |
Compute the rotational symmetry number of the given molecule and graph. | Can you generate a brief explanation for the following Python 3 code
def compute_rotsym(molecule, graph, threshold=1e-3*angstrom):
result = 0
for match in graph.symmetries:
permutation = list(j for i,j in sorted(match.forward.items()))
new_coordinates = molecule.coordinates[permutation]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the quaternion product of the two arguments | Can you tell what is the following Python 3 function doing
def quaternion_product(quat1, quat2):
return np.array([
quat1[0]*quat2[0] - np.dot(quat1[1:], quat2[1:]),
quat1[0]*quat2[1] + quat2[0]*quat1[1] + quat1[2]*quat2[3] - quat1[3]*quat2[2],
quat1[0]*quat2[2] + quat2[0]*quat1[2] + quat1[3]... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def quaternion_rotation(quat, vector):
"""Apply the rotation represented by the quaternion to the vector
Warning: This only works correctly for normalized quaternions.
"""
dp = np.dot(quat[1:], vector)
cos = (2*quat[0]*quat[0] - 1)
return np.array([
2 * (quat[0] * (quat[2] * vector[2... | Can you implement a function in Python 3 that
applies the rotation represented by the quaternion to the vector | As a python code expert, you are capable of creating scripts from specifications. |
Compute the quaternion representing the rotation given by the matrix | Explain what the following Python 3 code does
def rotation_matrix_to_quaternion(rotation_matrix):
invert = (np.linalg.det(rotation_matrix) < 0)
if invert:
factor = -1
else:
factor = 1
c2 = 0.25*(factor*np.trace(rotation_matrix) + 1)
if c2 < 0:
#print c2
c2 = 0.0
c... | As a Python code composer, you craft elegant and concise scripts. |
def quaternion_to_rotation_matrix(quaternion):
"""Compute the rotation matrix representated by the quaternion"""
c, x, y, z = quaternion
return np.array([
[c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ],
[2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ... | How would you implement a function in Python 3 that
computes the rotation matrix representated by the quaternion | As a python code expert, you are capable of creating scripts from specifications. |
Compute the cosine between two vectors
uggers | Can you tell what is the following Python 3 function doing
def cosine(a, b):
result = np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b)
return np.clip(result, -1, 1) | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a random unit vector of the given dimension | Make a summary of the following Python 3 code
def random_unit(size=3):
while True:
result = np.random.normal(0, 1, size)
length = np.linalg.norm(result)
if length > 1e-3:
return result/length | As a Python code composer, you craft elegant and concise scripts. |
def random_orthonormal(normal):
"""Return a random normalized vector orthogonal to the given vector"""
u = normal_fns[np.argmin(np.fabs(normal))](normal)
u /= np.linalg.norm(u)
v = np.cross(normal, u)
v /= np.linalg.norm(v)
alpha = np.random.uniform(0.0, np.pi*2)
return np.cos(alpha)*u + np.... | Create a Python 3 function for
returning a random normalized vector orthogonal to the given vector | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a vector orthogonal to the given triangle | Make a summary of the following Python 3 code
def triangle_normal(a, b, c):
normal = np.cross(a - c, b - c)
norm = np.linalg.norm(normal)
return normal/norm | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the dot product of two Vector3 objects. | Can you tell what is the following Python 3 function doing
def dot(r1, r2):
if r1.size != r2.size:
raise ValueError("Both arguments must have the same input size.")
if r1.deriv != r2.deriv:
raise ValueError("Both arguments must have the same deriv.")
return r1.x*r2.x + r1.y*r2.y + r1.z*r2.z | As a Python code composer, you craft elegant and concise scripts. |
def cross(r1, r2):
"""Compute the cross product
Arguments:
| ``r1``, ``r2`` -- two :class:`Vector3` objects
(Returns a Vector3)
"""
if r1.size != r2.size:
raise ValueError("Both arguments must have the same input size.")
if r1.deriv != r2.deriv:
raise ValueError(... | Can you write a function in Python 3 where it
computes the cross product of two Vector3 objects. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the mean of the 3 opbends
| Explain what the following Python 3 code does
def _opbend_transform_mean(rs, fn_low, deriv=0):
v = 0.0
d = np.zeros((4,3), float)
dd = np.zeros((4,3,4,3), float)
#loop over the 3 cyclic permutations
for p in np.array([[0,1,2], [2,0,1], [1,2,0]]):
opbend = _opbend_transform([rs[p[0]], rs[p[1]... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Similar to bond_length but with a relative vector | How would you explain what the following Python 3 function does
def _bond_length_low(r, deriv):
r = Vector3(3, deriv, r, (0, 1, 2))
d = r.norm()
return d.results() | As a python code expert, you are capable of creating scripts from specifications. |
Similar to bend_cos but with relative vectors | How would you explain what the following Python 3 function does
def _bend_cos_low(a, b, deriv):
a = Vector3(6, deriv, a, (0, 1, 2))
b = Vector3(6, deriv, b, (3, 4, 5))
a /= a.norm()
b /= b.norm()
return dot(a, b).results() | You are a Python code analyst, evaluating scripts for potential improvements. |
Similar to dihed_cos but with relative vectors | Here you have a function in Python 3, explain what it does
def _dihed_cos_low(a, b, c, deriv):
a = Vector3(9, deriv, a, (0, 1, 2))
b = Vector3(9, deriv, b, (3, 4, 5))
c = Vector3(9, deriv, c, (6, 7, 8))
b /= b.norm()
tmp = b.copy()
tmp *= dot(a, b)
a -= tmp
tmp = b.copy()
tmp *= dot(... | You are a Python code analyst, evaluating scripts for potential improvements. |
Similar to dihed_cos but with relative vectors | Can you generate a brief explanation for the following Python 3 code
def _dihed_angle_low(av, bv, cv, deriv):
a = Vector3(9, deriv, av, (0, 1, 2))
b = Vector3(9, deriv, bv, (3, 4, 5))
c = Vector3(9, deriv, cv, (6, 7, 8))
b /= b.norm()
tmp = b.copy()
tmp *= dot(a, b)
a -= tmp
tmp = b.copy... | As a Python code analyst, you investigate and solve complex coding mysteries |
Similar to opbend_cos but with relative vectors | Can you tell what is the following Python 3 function doing
def _opbend_cos_low(a, b, c, deriv):
a = Vector3(9, deriv, a, (0, 1, 2))
b = Vector3(9, deriv, b, (3, 4, 5))
c = Vector3(9, deriv, c, (6, 7, 8))
n = cross(a,b)
n /= n.norm()
c /= c.norm()
temp = dot(n,c)
result = temp.copy()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Similar to opbend_angle but with relative vectors | Here you have a function in Python 3, explain what it does
def _opbend_angle_low(a, b, c, deriv=0):
result = _opbend_cos_low(a, b, c, deriv)
sign = np.sign(np.linalg.det([a, b, c]))
return _cos_to_angle(result, deriv, sign) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _cos_to_angle(result, deriv, sign=1):
"""Convert a cosine and its derivatives to an angle and its derivatives"""
v = np.arccos(np.clip(result[0], -1, 1))
if deriv == 0:
return v*sign,
if abs(result[0]) >= 1:
factor1 = 0
else:
factor1 = -1.0/np.sqrt(1-result[0]**2)
d =... | Write a Python 3 script for
converting a cosine and its derivatives to an angle and its derivatives | You are a Python code generator, capable of creating scripts from specifications. |
def _sin_to_angle(result, deriv, side=1):
"""Convert a sine and its derivatives to an angle and its derivatives"""
v = np.arcsin(np.clip(result[0], -1, 1))
sign = side
if sign == -1:
if v < 0:
offset = -np.pi
else:
offset = np.pi
else:
offset = 0.0
... | Implement a function in Python 3 to
convert a sine and its derivatives to an angle and its derivatives | You are a Python code architect, reviewing and designing scalable and efficient code |
def copy(self):
"""Return a deep copy"""
result = Scalar(self.size, self.deriv)
result.v = self.v
if self.deriv > 0: result.d[:] = self.d[:]
if self.deriv > 1: result.dd[:] = self.dd[:]
return result | Create a Python 3 function for
returning a deep copy of the current Scalar object | You are a Python code architect, reviewing and designing scalable and efficient code |
def results(self):
"""Return the value and optionally derivative and second order derivative"""
if self.deriv == 0:
return self.v,
if self.deriv == 1:
return self.v, self.d
if self.deriv == 2:
return self.v, self.d, self.dd | Implement a Python 3 function for
returning the value and optionally derivative and second order derivative | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a deep copy of the current Vector3. | Can you generate the documentation for the following Python 3 function
def copy(self):
result = Vector3(self.size, self.deriv)
result.x.v = self.x.v
result.y.v = self.y.v
result.z.v = self.z.v
if self.deriv > 0:
result.x.d[:] = self.x.d
result.y.d[:] = sel... | As a Python code composer, you craft elegant and concise scripts. |
def norm(self):
"""Return a Scalar object with the norm of this vector"""
result = Scalar(self.size, self.deriv)
result.v = np.sqrt(self.x.v**2 + self.y.v**2 + self.z.v**2)
if self.deriv > 0:
result.d += self.x.v*self.x.d
result.d += self.y.v*self.y.d
... | How would you code a function in Python 3 to
return a Scalar object with the norm of this vector | As a Python code composer, you craft elegant and concise scripts. |
def _get_line(self):
"""Get a line or raise StopIteration"""
line = self._f.readline()
if len(line) == 0:
raise StopIteration
return line | Implement a function in Python 3 to
get a line of data from the file and return it. | You are a Python code architect, reviewing and designing scalable and efficient code |
Read one frame from the file. | Can you generate a brief explanation for the following Python 3 code
def _read_frame(self):
# Read the first line, ignore the title and try to get the time. The
# time field is optional.
line = self._get_line()
pos = line.rfind("t=")
if pos >= 0:
time = float(line[pos... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function creates a list of internal coordinates based on the graph. | Can you generate the documentation for the following Python 3 function
def setup_ics(graph):
ics = []
# A) Collect all bonds.
for i0, i1 in graph.edges:
ics.append(BondLength(i0, i1))
# B) Collect all bends. (see b_bending_angles.py for the explanation)
for i1 in range(graph.num_vertices):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Construct a Jacobian matrix for the given internal and Cartesian coordinates. | Can you generate a brief explanation for the following Python 3 code
def compute_jacobian(ics, coordinates):
N3 = coordinates.size
jacobian = numpy.zeros((N3, len(ics)), float)
for j, ic in enumerate(ics):
# Let the ic object fill in each column of the Jacobian.
ic.fill_jacobian_column(jacob... | As a Python code composer, you craft elegant and concise scripts. |
Fill in a column of the Jacobian. | Explain what the following Python 3 code does
def fill_jacobian_column(self, jaccol, coordinates):
q, g = self.icfn(coordinates[list(self.indexes)], 1)
for i, j in enumerate(self.indexes):
jaccol[3*j:3*j+3] += g[i]
return jaccol | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the similarity between two molecules based on their descriptors. | Can you generate a brief explanation for the following Python 3 code
def compute_similarity(a, b, margin=1.0, cutoff=10.0):
return similarity_measure(
a.table_labels, a.table_distances,
b.table_labels, b.table_distances,
margin, cutoff
) | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize a similarity descriptor from a Molecule object. | Can you generate the documentation for the following Python 3 function
def from_molecule(cls, molecule, labels=None):
if labels is None:
labels = molecule.numbers
return cls(molecule.distance_matrix, labels) | As a Python code composer, you craft elegant and concise scripts. |
Initialize a similarity descriptor from a MolecularGraph object. | Can you generate a brief explanation for the following Python 3 code
def from_molecular_graph(cls, molecular_graph, labels=None):
if labels is None:
labels = molecular_graph.numbers.astype(int)
return cls(molecular_graph.distances, labels) | As a Python code composer, you craft elegant and concise scripts. |
def from_coordinates(cls, coordinates, labels):
"""Initialize a similarity descriptor
Arguments:
coordinates -- a Nx3 numpy array
labels -- a list with integer labels used to identify atoms of
the same type
"""
from molmod.ext im... | Write a Python 3 script to
initialize a similarity descriptor from a set of coordinates and labels | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load a checkpoint file from a checkpoint file. | Can you generate a brief explanation for the following Python 3 code
def load_chk(filename):
'''Load a checkpoint file
Argument:
| filename -- the file to load from
The return value is a dictionary whose keys are field labels and the
values can be None, string, integer, float, boole... | You are a Python code architect, reviewing and designing scalable and efficient code |
Dump a checkpoint file to a file. | How would you explain what the following Python 3 function does
def dump_chk(filename, data):
'''Dump a checkpoint file
Argument:
| filename -- the file to write to
| data -- a dictionary whose keys are field labels and the values can
be None, string, integer, float, bo... | As a Python code analyst, you investigate and solve complex coding mysteries |
def clear(self):
"""Clear the contents of the data structure"""
self.title = None
self.numbers = np.zeros(0, int)
self.atom_types = [] # the atom_types in the second column, used to associate ff parameters
self.charges = [] # ff charges
self.names = [] # a name that is un... | Implement a function in Python 3 to
clear the contents of the data structure | You are a Python code generator, capable of creating scripts from specifications. |
def read_from_file(self, filename):
"""Load a PSF file"""
self.clear()
with open(filename) as f:
# A) check the first line
line = next(f)
if not line.startswith("PSF"):
raise FileFormatError("Error while reading: A PSF file must start with a li... | Can you create a Python 3 function that
reads a PSF file into the internal dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_name(self, graph, group=None):
"""Convert a molecular graph into a unique name
This method is not sensitive to the order of the atoms in the graph.
"""
if group is not None:
graph = graph.get_subgraph(group, normalize=True)
fingerprint = graph.fingerprin... | Write a Python 3 script for
converting a molecular graph into a unique name | As a Python code composer, you craft elegant and concise scripts. |
def dump(self, f):
"""Dump the data structure to a file-like object"""
# header
print("PSF", file=f)
print(file=f)
# title
print(" 1 !NTITLE", file=f)
print(self.title, file=f)
print(file=f)
# atoms
print("% 7i !NATOM" % len(self.num... | How would you code a function in Python 3 to
dump the data structure to a file - like object | You are a Python code generator, capable of creating scripts from specifications. |
def add_molecule(self, molecule, atom_types=None, charges=None, split=True):
"""Add the graph of the molecule to the data structure
The molecular graph is estimated from the molecular geometry based on
interatomic distances.
Argument:
| ``molecule`` -- a Molecule... | Can you implement a function in Python 3 that
adds the molecular graph of the given molecule to the data structure | As a python code expert, you are capable of creating scripts from specifications. |
Adds the molecular graph to the data structure | How would you explain what the following Python 3 function does
def add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None):
# add atom numbers and molecule indices
new = len(molecular_graph.numbers)
if new == 0: return
prev = len(self.numbers... | You are a Python code generator, capable of creating scripts from specifications. |
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])
... | Write a Python 3 script for
returning a list of groups of atom indexes Each atom in a group belongs to the same molecule or residue. | You are a Python code generator, capable of creating scripts from specifications. |
Iterate over the bonds that divides the molecule in two | Here you have a function in Python 3, explain what it does
def iter_halfs_bond(graph):
for atom1, atom2 in graph.edges:
try:
affected_atoms1, affected_atoms2 = graph.get_halfs(atom1, atom2)
yield affected_atoms1, affected_atoms2, (atom1, atom2)
except GraphError:
... | As a Python code composer, you craft elegant and concise scripts. |
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:
... | How would you implement a function in Python 3 that
iterates over the bonds that divide the molecule in two | As a python code expert, you are capable of creating scripts from specifications. |
Iterate over the two random non - consecutive bonds that divide the molecule in two | Can you generate a brief explanation for the following Python 3 code
def iter_halfs_double(graph):
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_ha... | You are a Python code generator, capable of creating scripts from specifications. |
Generates a set of random manipulations for a single molecule. | How would you explain what the following Python 3 function does
def generate_manipulations(
molecule, bond_stretch_factor=0.15, torsion_amplitude=np.pi,
bending_amplitude=0.30
):
"""Generate a (complete) set of manipulations
The result can be used as input for the functions 'randomize_molecule'
... | As a Python code composer, you craft elegant and concise scripts. |
Checks whether all nonbonded atoms are well separated and if they are not then returns False. | Can you generate the documentation for the following Python 3 function
def check_nonbond(molecule, thresholds):
# 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 =... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 molecul... | How would you code a function in Python 3 to
return a randomized copy of the molecule. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a randomized copy of the molecule with the nonbond check applied. | Can you generate a brief explanation for the following Python 3 code
def randomize_molecule_low(molecule, manipulations):
manipulations = copy.copy(manipulations)
shuffle(manipulations)
coordinates = molecule.coordinates.copy()
for manipulation in manipulations:
manipulation.apply(coordinates)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 molec... | Implement a Python 3 function for
applying a single random manipulation. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a randomized copy of the molecule without the nonbond check. | Here you have a function in Python 3, explain what it does
def single_random_manipulation_low(molecule, manipulations):
manipulation = sample(manipulations, 1)[0]
coordinates = molecule.coordinates.copy()
transformation = manipulation.apply(coordinates)
return molecule.copy_with(coordinates=coordinates... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 approxima... | Write a Python 3 script for
creating a random dimer that can be used to create a random molecule. | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct a MolecularDistortion object from a file | Can you generate the documentation for the following Python 3 function
def read_from_file(cls, filename):
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.s... | You are a Python code analyst, evaluating scripts for potential improvements. |
def apply(self, coordinates):
"""Apply this distortion to Cartesian coordinates"""
for i in self.affected_atoms:
coordinates[i] = self.transformation*coordinates[i] | Write a Python 3 function for
applying this distortion to Cartesian coordinates | As a python code expert, you are capable of creating scripts from specifications. |
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 atomi... | Write a Python 3 function for
writing the object to a file | As a python code expert, you are capable of creating scripts from specifications. |
Generate apply and return a random manipulation | Here you have a function in Python 3, explain what it does
def apply(self, coordinates):
transform = self.get_transformation(coordinates)
result = MolecularDistortion(self.affected_atoms, transform)
result.apply(coordinates)
return result | As a Python code translator, you convert algorithms and pseudocode into Python. |
Construct a translation object from the given coordinates | Can you generate a brief explanation for the following Python 3 code
def get_transformation(self, coordinates):
atom1, atom2 = self.hinge_atoms
direction = coordinates[atom1] - coordinates[atom2]
direction /= np.linalg.norm(direction)
direction *= np.random.uniform(-self.max_amplitude, s... | You are a Python code analyst, evaluating scripts for potential improvements. |
Construct a transformation object from the given coordinates. | Can you tell what is the following Python 3 function doing
def get_transformation(self, coordinates):
atom1, atom2 = self.hinge_atoms
center = coordinates[atom1]
axis = coordinates[atom1] - coordinates[atom2]
axis /= np.linalg.norm(axis)
angle = np.random.uniform(-self.max_amplit... | As a Python code composer, you craft elegant and concise scripts. |
Construct a transformation object from the given coordinates. | How would you explain what the following Python 3 function does
def get_transformation(self, coordinates):
atom1, atom2, atom3 = self.hinge_atoms
center = coordinates[atom2]
a = coordinates[atom1] - coordinates[atom2]
b = coordinates[atom3] - coordinates[atom2]
axis = np.cross(a,... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_transformation(self, coordinates):
"""Construct a transformation object"""
atom1, atom2, atom3, atom4 = self.hinge_atoms
a = coordinates[atom1] - coordinates[atom2]
a /= np.linalg.norm(a)
b = coordinates[atom3] - coordinates[atom4]
b /= np.linalg.norm(b)
d... | Implement a function in Python 3 to
construct a translation object from the given coordinates | You are a Python code generator, capable of creating scripts from specifications. |
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._... | Write a Python 3 function that can
iterate over all bins surrounding the given center key | You are a Python code architect, reviewing and designing scalable and efficient code |
Translate the key into the central cell
| Make a summary of the following Python 3 code
def wrap_key(self, key):
return tuple(np.round(
self.integer_cell.shortest_vector(key)
).astype(int)) | As a python code expert, you are capable of creating scripts from specifications. |
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 ... | Create a Python 3 function for
choosing a proper grid for the binning process | You are a Python code architect, reviewing and designing scalable and efficient code |
Evaluate a python expression string containing constants
ATTRIBS and return a float. | Can you generate a brief explanation for the following Python 3 code
def parse_unit(expression):
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) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a FIFO queue with the ancestors and itself. | Can you generate a brief explanation for the following Python 3 code
def parents(self):
q = self.__parent__.parents()
q.put(self)
return q | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the whole URL from the base to this node. | Make a summary of the following Python 3 code
def url(self):
path = None
nodes = self.parents()
while not nodes.empty():
path = urljoin(path, nodes.get().path())
return path | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a tuple of the authentication and the parent node if any. | Given the following Python 3 function, write the documentation
def auth_required(self):
if self._auth:
return self._auth, self
return self.__parent__.auth_required() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check that the atomic numbers in the graph are consistent with the molecule. | Can you tell what is the following Python 3 function doing
def _check_graph(self, graph):
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct a Molecule object from a file. | Can you generate the documentation for the following Python 3 function
def from_file(cls, filename):
# 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... | As a Python code translator, you convert algorithms and pseudocode into Python. |
the chemical formula of the molecule | Can you generate the documentation for the following Python 3 function
def chemical_formula(self):
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:... | You are a Python code analyst, evaluating scripts for potential improvements. |
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]) | Can you create a Python 3 function that
sets self. masses based on self. numbers and periodic table. | You are a Python code generator, capable of creating scripts from specifications. |
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) | Can you create a Python 3 function that
sets self. symbols based on self. numbers and the periodic table. | As a Python code analyst, you investigate and solve complex coding mysteries |
Write the molecular geometry to a file. | Can you tell what is the following Python 3 function doing
def write_to_file(self, 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'):
... | As a python code expert, you are capable of creating scripts from specifications. |
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 ... | Create a Python 3 function for
computing the RMSD between two molecules. | You are a Python code generator, capable of creating scripts from specifications. |
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
... | Can you implement a function in Python 3 that
computes the rotational symmetry number. | As a Python code analyst, you investigate and solve complex coding mysteries |
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(":")] | How would you code a function in Python 3 to
get the label from the last line read | As a Python code analyst, you investigate and solve complex coding mysteries |
Skip a section of the log file. | Explain what the following Python 3 code does
def _skip_section(self):
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
self._last = self._f.readline() | As a Python code composer, you craft elegant and concise scripts. |
Read and return an entire section | Can you generate a brief explanation for the following Python 3 code
def _read_section(self):
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 =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the next section with the given label | Can you tell what is the following Python 3 function doing
def get_next(self, label):
while self._get_current_label() != label:
self._skip_section()
return self._read_section() | As a python code expert, you are capable of creating scripts from specifications. |
def _read_frame(self):
"""Read a single frame from the trajectory"""
self._secfile.get_next("Frame Number")
frame = ATRJFrame()
# Read the time and energy
energy_lines = self._secfile.get_next("Time/Energy")
energy_words = energy_lines[0].split()
frame.time = floa... | Create a Python 3 function for
reading a single ATRJFrame from the trajectory | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Write a Python 3 function that can
generate the Cartesian coordinates of the points in a cube file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a cube object by loading data from a file. | Make a summary of the following Python 3 code
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.
'... | You are a Python code architect, reviewing and designing scalable and efficient code |
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.... | Write a Python 3 function that can
write the cube to a file in the Gaussian cube format. | As a python code expert, you are capable of creating scripts from specifications. |
Return a copy of the cube with optionally new data. | Make a summary of the following Python 3 code
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(),
sel... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _consistent(self):
"""Checks the constency between self.__index and self.__order"""
if len(self.__order) != sum(len(values) for values in self.__index.values()):
return False
import copy
tmp = copy.copy(self.__order)
for key, values in self.__index.items():
... | Implement a function in Python 3 to
check the constency between self. __index and self. order | You are a Python code analyst, evaluating scripts for potential improvements. |
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(... | Write a Python 3 function for
adding a child section or keyword to the end of the list. | As a Python code composer, you craft elegant and concise scripts. |
Dump the children of the current section to a file - like object | Explain what the following Python 3 code does
def dump_children(self, f, indent=''):
for child in self.__order:
child.dump(f, indent+' ') | You are a Python code architect, reviewing and designing scalable and efficient code |
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) | How would you code a function in Python 3 to
dump this section and its children to a file - like object | As a python code expert, you are capable of creating scripts from specifications. |
A helper method that only reads uncommented lines | Can you generate the documentation for the following Python 3 function
def readline(self, f):
while True:
line = f.readline()
if len(line) == 0:
raise EOFError
line = line[:line.find('#')]
line = line.strip()
if len(line) > 0:
... | As a python code expert, you are capable of creating scripts from specifications. |
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... | Implement a function in Python 3 to
load the children of this section from a file - like object | You are a Python code analyst, evaluating scripts for potential improvements. |
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()
... | Can you write a function in Python 3 where it
loads this section from a file - like object | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | Implement a Python 3 function for
dumping this keyword to a file - like object | You are a Python code analyst, evaluating scripts for potential improvements. |
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 ... | Create a Python 3 function for
loading this keyword from a file - like object | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.