output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Set the value associated with the keyword | Can you tell what is the following Python 3 function doing
def set_value(self, value):
if not isinstance(value, str):
raise TypeError("A value must be a string, got %s." % value)
self.__value = value | As a Python code analyst, you investigate and solve complex coding mysteries |
Reads a file containing the contents of the file. | How would you explain what the following Python 3 function does
def read_from_file(filename):
with open(filename) as f:
result = CP2KInputFile()
try:
while True:
result.load_children(f)
except EOFError:
pass
return r... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _read_frame(self):
"""Read and return the next time frame"""
pos = np.zeros((self.num_atoms, 3), float)
vel = np.zeros((self.num_atoms, 3), float)
for i in range(self.num_atoms):
line = next(self._f)
words = line.split()
pos[i, 0] = float(words[1])... | Implement a Python 3 function for
reading and return the next time frame | As a Python code translator, you convert algorithms and pseudocode into Python. |
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)... | Implement a function in Python 3 to
check the sanity of the given 4x4 transformation matrix | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 geom... | Create a Python 3 function for
computing the transformation that minimizes the RMSD between the points ras and rbs. | You are a Python code analyst, evaluating scripts for potential improvements. |
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``
* ``T... | Implement a Python 3 function for
applying this translation to the given object x. | As a python code expert, you are capable of creating scripts from specifications. |
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. | Explain what the following Python 3 code does
def compare(self, other, t_threshold=1e-3):
return compute_rmsd(self.t, other.t) < t_threshold | You are a Python code analyst, evaluating scripts for potential improvements. |
check that the columns must orthogonal | Can you tell what is the following Python 3 function doing
def _check_r(self, r):
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... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a random rotation | How would you explain what the following Python 3 function does
def random(cls):
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) | You are a Python code analyst, evaluating scripts for potential improvements. |
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)
... | Implement a Python 3 function for
initializing a rotation based on the properties | As a Python code analyst, you investigate and solve complex coding mysteries |
Rotation properties for the current object | Make a summary of the following Python 3 code
def properties(self):
# determine wether an inversion rotation has been applied
invert = (np.linalg.det(self.r) < 0)
factor = {True: -1, False: 1}[invert]
# get the rotation data
# trace(r) = 1+2*cos(angle)
cos_angle = 0.5*(fa... | As a Python code analyst, you investigate and solve complex coding mysteries |
The 4x4 matrix representation of this rotation | Explain what the following Python 3 code does
def matrix(self):
result = np.identity(4, float)
result[0:3, 0:3] = self.r
return result | As a Python code analyst, you investigate and solve complex coding mysteries |
The inverse rotation of the current object | Explain what the following Python 3 code does
def inv(self):
result = Rotation(self.r.transpose())
result._cache_inv = self
return result | You are a Python code analyst, evaluating scripts for potential improvements. |
Apply this rotation to the given object x. | Can you tell what is the following Python 3 function doing
def apply_to(self, x, columns=False):
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
Compare two rotations returning True if the RMSD of the rotation matrices is below the threshold. | Can you tell what is the following Python 3 function doing
def compare(self, other, r_threshold=1e-3):
return compute_rmsd(self.r, other.r) < r_threshold | As a Python code composer, you craft elegant and concise scripts. |
Initialize a transformation based on the properties | Can you tell what is the following Python 3 function doing
def from_properties(cls, angle, axis, invert, translation):
rot = Rotation.from_properties(angle, axis, invert)
return Complete(rot.r, translation) | As a Python code composer, you craft elegant and concise scripts. |
Convert the first argument into a Complete object | Explain what the following Python 3 code does
def cast(cls, c):
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)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create transformation that represents a rotation about an axis | Here you have a function in Python 3, explain what it does
def about_axis(cls, center, angle, axis, invert=False):
return Translation(center) * \
Rotation.from_properties(angle, axis, invert) * \
Translation(-center) | As a Python code translator, you convert algorithms and pseudocode into Python. |
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. | Explain what the following Python 3 code does
def compare(self, other, t_threshold=1e-3, r_threshold=1e-3):
return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold | As a Python code analyst, you investigate and solve complex coding mysteries |
def _read_frame(self):
"""Read and return the next time frame"""
# Read one frame, we assume that the current file position is at the
# line 'ITEM: TIMESTEP' and that this line marks the beginning of a
# time frame.
line = next(self._f)
if line != 'ITEM: TIMESTEP\n':
... | Create a Python 3 function to
read and return the next time frame. | You are a Python code analyst, evaluating scripts for potential improvements. |
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) | How would you code a function in Python 3 to
skip the next time frame | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Can you implement a function in Python 3 that
adds an atom info object to the database | You are a Python code architect, reviewing and designing scalable and efficient code |
def update(self, other):
"""Extend the current cluster with data from another cluster"""
Cluster.update(self, other)
self.rules.extend(other.rules) | Write a Python 3 script to
extend the current cluster with data from another cluster | As a python code expert, you are capable of creating scripts from specifications. |
Add related items to the common cluster. | Can you generate a brief explanation for the following Python 3 code
def add_related(self, *objects):
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 ... | As a Python code composer, you craft elegant and concise scripts. |
def _read_frame(self):
"""Read a single frame from the trajectory"""
# auxiliary read function
def read_three(msg):
"""Read three words as floating point numbers"""
line = next(self._f)
try:
return [float(line[:12]), float(line[12:24]), float(l... | Write a Python 3 script to
read a single time frame from the trajectory. | You are a Python code analyst, evaluating scripts for potential improvements. |
Continue reading until the next frame is reached | Given the following Python 3 function, write the documentation
def goto_next_frame(self):
marked = False
while True:
line = next(self._f)[:-1]
if marked and len(line) > 0 and not line.startswith(" --------"):
try:
step = int(line[:10])
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read a single frame from the trajectory | Can you tell what is the following Python 3 function doing
def _read_frame(self):
# optionally skip the equilibration
if self.skip_equi_period:
while True:
step, line = self.goto_next_frame()
self._counter += 1
if step >= self.equi_period:
... | As a python code expert, you are capable of creating scripts from specifications. |
Read a single frame from the XYZ file | Given the following Python 3 function, write the documentation
def _read_frame(self):
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 =... | As a python code expert, you are capable of creating scripts from specifications. |
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 | Can you implement a function in Python 3 that
skips a single frame from the trajectory | You are a Python code generator, capable of creating scripts from specifications. |
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.... | How would you code a function in Python 3 to
get the first molecule from the trajectory | You are a Python code analyst, evaluating scripts for potential improvements. |
Dump a frame to the trajectory file
| Can you tell what is the following Python 3 function doing
def dump(self, title, coordinates):
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, ) ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a Molecule object from the trajectory
Optional argument index = 0 | Make a summary of the following Python 3 code
def get_molecule(self, index=0):
return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols) | You are a Python code analyst, evaluating scripts for potential improvements. |
Write the trajectory to a file | How would you explain what the following Python 3 function does
def write_to_file(self, f, file_unit=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) | As a Python code analyst, you investigate and solve complex coding mysteries |
Efficiently test if the counter is in the sequence of objects in the object. | Explain what the following Python 3 code does
def slice_match(sub, counter):
if sub.start is not None and counter < sub.start:
return False
if sub.stop is not None and counter >= sub.stop:
raise StopIteration
if sub.step is not None:
if sub.start is None:
if counter % su... | You are a Python code analyst, evaluating scripts for potential improvements. |
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
| ``epsilo... | Write a Python 3 function that can
check the analytical gradient using finite differences | As a Python code composer, you craft elegant and concise scripts. |
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 s... | Create a Python 3 function to
check the difference between two functions using the analytical gradient. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 compu... | Write a Python 3 function that can
compute the Hessian using the finite difference method. | You are a Python code generator, capable of creating scripts from specifications. |
Update the search direction given the latest gradient and step | Make a summary of the following Python 3 code
def update(self, gradient, step):
do_sd = self.gradient_old is None
self.gradient_old = self.gradient
self.gradient = gradient
if do_sd:
self._update_sd()
else:
self._update_cg() | As a Python code composer, you craft elegant and concise scripts. |
Update the conjugate gradient | Can you generate a brief explanation for the following Python 3 code
def _update_cg(self):
beta = self._beta()
# Automatic direction reset
if beta < 0:
self.direction = -self.gradient
self.status = "SD"
else:
self.direction = self.direction * beta - se... | You are a Python code analyst, evaluating scripts for potential improvements. |
def update(self, gradient, step):
"""Update the search direction given the latest gradient and step"""
self.old_gradient = self.gradient
self.gradient = gradient
N = len(self.gradient)
if self.inv_hessian is None:
# update the direction
self.direction = -s... | Create a Python 3 function for
updating the search direction given the latest gradient and step | You are a Python code analyst, evaluating scripts for potential improvements. |
Clip the a step within the maximum allowed range | Can you generate the documentation for the following Python 3 function
def limit_step(self, step):
if self.qmax is None:
return step
else:
return np.clip(step, -self.qmax, self.qmax) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find a bracket that does contain the minimum | Given the following Python 3 function, write the documentation
def _bracket(self, qinit, f0, fun):
self.num_bracket = 0
qa = qinit
fa = fun(qa)
counter = 0
if fa >= f0:
while True:
self.num_bracket += 1
#print " bracket shrink"
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 < ... | How would you implement a function in Python 3 that
reduces the size of the bracket until the minimum is found | You are a Python code architect, reviewing and designing scalable and efficient code |
Perform an update of the linear transformation of the given object. | Can you tell what is the following Python 3 function doing
def update(self, counter, f, x_orig, gradient_orig):
if counter - self.last_update > self.each:
grad_rms = np.sqrt((gradient_orig**2).mean())
if grad_rms < self.grad_rms:
self.last_update = counter
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Perform an update of the linear transformation of the minimizer. | Here you have a function in Python 3, explain what it does
def update(self, counter, f, x_orig, gradient_orig):
do_update = Preconditioner.update(self, counter, f, x_orig, gradient_orig)
if do_update:
# determine a new preconditioner
N = len(x_orig)
if self.scales is ... | As a python code expert, you are capable of creating scripts from specifications. |
Perform an update of the linear transformation of the minimizer. | Can you generate a brief explanation for the following Python 3 code
def update(self, counter, f, x_orig, gradient_orig):
if Preconditioner.update(self, counter, f, x_orig, gradient_orig):
# determine a new preconditioner
hessian = compute_fd_hessian(self.fun, x_orig, self.epsilon)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Transform the unknowns to preconditioned coordinates
This method transforms the gradient to original coordinates
| Here you have a function in Python 3, explain what it does
def do(self, x_orig):
if self.scales is None:
return x_orig
else:
return np.dot(self.rotation.transpose(), x_orig)*self.scales | As a Python code composer, you craft elegant and concise scripts. |
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) | Can you implement a function in Python 3 that
transforms the unknowns to original coordinates This method also transforms the gradient to preconditioned coordinates Integrity | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the header for screen logging of the minimization | Can you tell what is the following Python 3 function doing
def get_header(self):
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 += " Gra... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 | Implement a function in Python 3 to
configure the 1D function for a line search | You are a Python code analyst, evaluating scripts for potential improvements. |
def _compute_equations(self, x, verbose=False):
'''Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
'''
# compute the error and the normals.
normals = []
values = []
signs = []
error ... | Write a Python 3 function for
computing the values and normals of active constraints. | As a Python code composer, you craft elegant and concise scripts. |
Take a robust but not very efficient step towards the constraints. | How would you explain what the following Python 3 function does
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 t... | As a Python code composer, you craft elegant and concise scripts. |
This routine is used to fast shake the active set of unknowns. | Can you generate the documentation for the following Python 3 function
def _fast_shake(self, x, normals, values, error):
'''Take an efficient (not always robust) step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradient... | As a Python code composer, you craft elegant and concise scripts. |
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:
... | Write a Python 3 script to
bring unknowns to the constraints. | As a Python code analyst, you investigate and solve complex coding mysteries |
Brings unknowns to the constraints without increasing fun above fmax. | Can you generate the documentation for the following Python 3 function
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.
| ``... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Project a vector on the active constraints. | Explain what the following Python 3 code does
def project(self, x, vector):
'''Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is... | As a Python code analyst, you investigate and solve complex coding mysteries |
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) | Write a Python 3 script to
return the final solution in the original coordinates | As a python code expert, you are capable of creating scripts from specifications. |
Run the iterative optimizer | Explain what the following Python 3 code does
def _run(self):
success = self.initialize()
while success is None:
success = self.propagate()
return success | As a Python code translator, you convert algorithms and pseudocode into Python. |
Print the header for screen logging | Make a summary of the following Python 3 code
def _print_header(self):
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_he... | You are a Python code generator, capable of creating scripts from specifications. |
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=' ') | Implement a Python 3 function for
printing something on screen when self. verbose == True | You are a Python code analyst, evaluating scripts for potential improvements. |
Perform a line search along the current direction | How would you explain what the following Python 3 function does
def _line_opt(self):
direction = self.search_direction.direction
if self.constraints is not None:
try:
direction = self.constraints.project(self.x, direction)
except ConstraintError:
s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
A dictionary with neighbors of the current node. | Can you tell what is the following Python 3 function doing
def neighbors(self):
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 ... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 molecule... | Create a Python 3 function to
list of vertices that are only interconnected within each list | You are a Python code architect, reviewing and designing scalable and efficient code |
A dictionary with symmetrically equivalent vertices. | Given the following Python 3 function, write the documentation
def equivalent_vertices(self):
level1 = {}
for i, row in enumerate(self.vertex_fingerprints):
key = row.tobytes()
l = level1.get(key)
if l is None:
l = set([i])
level1[key] ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def symmetries(self):
"""Graph symmetries (permutations) that map the graph onto itself."""
symmetry_cycles = set([])
symmetries = set([])
for match in GraphSearch(EqualPattern(self))(self):
match.cycles = match.get_closed_cycles()
if match.cycles in symmetry_cyc... | Write a Python 3 function that can
graph symmetries that map the graph onto itself. | As a python code expert, you are capable of creating scripts from specifications. |
Iterate over the vertices with the breadth - first algorithm. | Can you generate the documentation for the following Python 3 function
def iter_breadth_first(self, start=None, do_paths=False, do_duplicates=False):
if start is None:
start = self.central_vertex
else:
try:
start = int(start)
except ValueError:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def iter_breadth_first_edges(self, start=None):
"""Iterate over the edges with the breadth first convention.
We need this for the pattern matching algorithms, but a quick look at
Wikipedia did not result in a known and named algorithm.
The edges are yielded one by one, togethe... | Implement a Python 3 function for
iterating over the breadth first edges of the current node. | You are a Python code analyst, evaluating scripts for potential improvements. |
Constructs a subgraph of the current graph with the given set of subvertices. | Given the following Python 3 function, write the documentation
def get_subgraph(self, subvertices, normalize=False):
if normalize:
revorder = dict((j, i) for i, j in enumerate(subvertices))
new_edges = []
old_edge_indexes = []
for counter, (i, j) in enumerate(self... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return an array with fingerprints for each vertex | Here you have a function in Python 3, explain what it does
def get_vertex_fingerprints(self, vertex_strings, edge_strings, num_iter=None):
import hashlib
def str2array(x):
"""convert a hash string to a numpy array of bytes"""
if len(x) == 0:
return np.zeros(0, np.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Split the graph in two halfs by cutting the edge vertex1 - vertex2 and return the vertices in both halfs. | Given the following Python 3 function, write the documentation
def get_halfs(self, vertex1, vertex2):
def grow(origin, other):
frontier = set(self.neighbors[origin])
frontier.discard(other)
result = set([origin])
while len(frontier) > 0:
pivot = fr... | As a python code expert, you are capable of creating scripts from specifications. |
List all vertices that are connected to vertex_in but are not covered in or behind vertices_border. | Can you generate the documentation for the following Python 3 function
def get_part(self, vertex_in, vertices_border):
vertices_new = set(self.neighbors[vertex_in])
vertices_part = set([vertex_in])
while len(vertices_new) > 0:
pivot = vertices_new.pop()
if pivot in verti... | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the two halfs separated by vertex_a1 and vertex_b1 and vertex_b2 and return the two halfs separated by vertex_a1 and vertex_b1 and vertex_b2. | Can you generate a brief explanation for the following Python 3 code
def get_halfs_double(self, vertex_a1, vertex_b1, vertex_a2, vertex_b2):
if vertex_a1 not in self.neighbors[vertex_b1]:
raise GraphError("vertex_a1 must be a neighbor of vertex_b1.")
if vertex_a2 not in self.neighbors[vertex... | As a python code expert, you are capable of creating scripts from specifications. |
def full_match(self, other):
"""Find the mapping between vertex indexes in self and other.
This also works on disconnected graphs. Derived classes should just
implement get_vertex_string and get_edge_string to make this method
aware of the different nature of certain vertices. ... | Write a Python 3 function for
finding the mapping between vertex indexes in self and other. | As a python code expert, you are capable of creating scripts from specifications. |
def add_relation(self, source, destination):
"""Add new a relation to the bejection"""
if self.in_sources(source):
if self.forward[source] != destination:
raise ValueError("Source is already in use. Destination does "
"not match.")
... | Implement a Python 3 function for
adding a new relation between source and destination. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add multiple relations to a bijection | Make a summary of the following Python 3 code
def add_relations(self, relations):
for source, destination in relations:
self.add_relation(source, destination) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the inverse bijection. | Make a summary of the following Python 3 code
def inverse(self):
result = self.__class__()
result.forward = copy.copy(self.reverse)
result.reverse = copy.copy(self.forward)
return result | As a Python code composer, you craft elegant and concise scripts. |
Get new edges from the subject graph for the graph search algorithm
| Here you have a function in Python 3, explain what it does
def get_new_edges(self, subject_graph):
result = []
#print "Match.get_new_edges self.previous_ends1", self.previous_ends1
for vertex in self.previous_ends1:
for neighbor in subject_graph.neighbors[vertex]:
if ... | As a Python code composer, you craft elegant and concise scripts. |
Create a new match object extended with new relations | Here you have a function in Python 3, explain what it does
def copy_with_new_relations(self, new_relations):
result = self.__class__(self.forward.items())
result.add_relations(new_relations.items())
result.previous_ends1 = set(new_relations.values())
return result | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the pattern_graph and initialize the internal state of the object. | Can you generate the documentation for the following Python 3 function
def _set_pattern_graph(self, pattern_graph):
self.pattern_graph = pattern_graph
self.level_edges = {}
self.level_constraints = {}
self.duplicate_checks = set([])
if pattern_graph is None:
return
... | As a python code expert, you are capable of creating scripts from specifications. |
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
vertex0 = self.start_vertex
for vertex1 in range(subject_graph.num_vertices):
if self.compare(vertex0, vertex1, subject_graph):
yield vertex0, vertex1 | Can you write a function in Python 3 where it
iterates over all valid initial relations for a match | You are a Python code generator, capable of creating scripts from specifications. |
Get new edges from the pattern graph for the graph search algorithm
| Here you have a function in Python 3, explain what it does
def get_new_edges(self, level):
return (
self.level_edges.get(level, []),
self.level_constraints.get(level, [])
) | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid"""
# only returns true for ecaxtly one set of new_relations from all the
# ones that are symmetrically equivalent
if not (self.criteria_sets is None or one_match... | Implement a function in Python 3 to
check if the next match can be a valid one. | As a Python code composer, you craft elegant and concise scripts. |
def iter_final_matches(self, canonical_match, subject_graph, one_match):
"""Given a match, iterate over all related equivalent matches
When criteria sets are defined, the iterator runs over all symmetric
equivalent matches that fulfill one of the criteria sets. When not
criteri... | Create a Python 3 function to
give a match iterate over all related equivalent matches that fulfill one of the criteria sets. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_closed_cycles(self):
"""Return the closed cycles corresponding to this permutation
The cycle will be normalized to facilitate the elimination of
duplicates. The following is guaranteed:
1) If this permutation is represented by disconnected cycles, the
cyc... | Create a Python 3 function to
return the closed cycles corresponding to this permutation. | You are a Python code analyst, evaluating scripts for potential improvements. |
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
if self.pattern_graph.num_edges != subject_graph.num_edges:
return # don't even try
for pair in CustomPattern.iter_initial_relations(self, subject_graph):
yield pai... | How would you implement a function in Python 3 that
iterates over all valid initial relations for a match | As a Python code composer, you craft elegant and concise scripts. |
Returns true when the two vertices are of the same kind | Can you generate the documentation for the following Python 3 function
def compare(self, vertex0, vertex1, subject_graph):
return (
self.pattern_graph.vertex_fingerprints[vertex0] ==
subject_graph.vertex_fingerprints[vertex1]
).all() | You are a Python code analyst, evaluating scripts for potential improvements. |
def iter_initial_relations(self, subject_graph):
"""Iterate over all valid initial relations for a match"""
vertex0 = 0
for vertex1 in range(subject_graph.num_vertices):
yield vertex0, vertex1 | How would you code a function in Python 3 to
iterate over all valid initial relations for a match | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_new_edges(self, level):
"""Get new edges from the pattern graph for the graph search algorithm
The level argument denotes the distance of the new edges from the
starting vertex in the pattern graph.
"""
if level == 0:
edges0 = [(0, 1), (0, 2)]
e... | How would you code a function in Python 3 to
get the new edges from the pattern graph for the graph search algorithm. | As a Python code composer, you craft elegant and concise scripts. |
Check if the next match can be a valid one | Here you have a function in Python 3, explain what it does
def check_next_match(self, match, new_relations, subject_graph, one_match):
# avoid duplicate rings (order of traversal)
if len(match) == 3:
if match.forward[1] < match.forward[2]:
#print "RingPattern.check_next_match... | You are a Python code analyst, evaluating scripts for potential improvements. |
Check whether a match is complete. | Given the following Python 3 function, write the documentation
def complete(self, match, subject_graph):
size = len(match)
# check whether we have an odd strong ring
if match.forward[size-1] in subject_graph.neighbors[match.forward[size-2]]:
# we have an odd closed cycle. check if th... | You are a Python code analyst, evaluating scripts for potential improvements. |
Only prints debug info on screen when self. debug == True. | Can you generate the documentation for the following Python 3 function
def print_debug(self, text, indent=0):
if self.debug:
if indent > 0:
print(" "*self.debug, text)
self.debug += indent
if indent <= 0:
print(" "*self.debug, text) | You are a Python code analyst, evaluating scripts for potential improvements. |
Divide the edges into groups. | Explain what the following Python 3 code does
def _iter_candidate_groups(self, init_match, edges0, edges1):
# collect all end vertices0 and end vertices1 that belong to the same
# group.
sources = {}
for start_vertex0, end_vertex0 in edges0:
l = sources.setdefault(start_verte... | As a python code expert, you are capable of creating scripts from specifications. |
def _iter_new_relations(self, init_match, subject_graph, edges0, constraints0, edges1):
"""Given an onset for a match, iterate over all possible new key-value pairs"""
# Count the number of unique edges0[i][1] values. This is also
# the number of new relations.
num_new_relations = len(se... | Write a Python 3 function for
iterating over all possible new relations in a subject graph. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _iter_matches(self, input_match, subject_graph, one_match, level=0):
"""Given an onset for a match, iterate over all completions of that match
This iterator works recursively. At each level the match is extended
with a new set of relations based on vertices in the pattern graph
... | Create a Python 3 function to
give an onset for a match, iterate over all completions of that match This iterator works recursively. At each level the match is extended with a new set of relations based on vertices in the pattern graph that are at a distances 'level' from the starting vertex | You are a Python code generator, capable of creating scripts from specifications. |
Writes a single molecule to a PDB file. | Can you tell what is the following Python 3 function doing
def dump_pdb(filename, molecule, atomnames=None, resnames=None, chain_ids=None, occupancies=None, betas=None):
with open(filename, "w") as f:
res_id = 1
old_resname = None
for i in range(molecule.size):
symbol = periodi... | As a Python code composer, you craft elegant and concise scripts. |
def load_pdb(filename):
"""Loads a single molecule from a pdb file.
This function does support only a small fragment from the pdb specification.
It assumes that there is only one molecular geometry in the pdb file.
"""
with open(filename) as f:
numbers = []
coordinates = []
... | Implement a Python 3 function for
loading a single molecule from a pdb file. | As a Python code composer, you craft elegant and concise scripts. |
def zmat_to_cart(zmat):
"""Converts a ZMatrix back to cartesian coordinates."""
numbers = zmat["number"]
N = len(numbers)
coordinates = np.zeros((N, 3), float)
# special cases for the first coordinates
coordinates[1, 2] = zmat["distance"][1]
if zmat["rel1"][2] == 1:
sign = -1
e... | Write a Python 3 script to
convert a ZMatrix back to cartesian coordinates. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a new reference atom for a row in the ZMatrix. | Here you have a function in Python 3, explain what it does
def _get_new_ref(self, existing_refs):
# ref0 is the atom whose position is defined by the current row in the
# zmatrix.
ref0 = existing_refs[0]
for ref in existing_refs:
# try to find a neighbor of the ref that can s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert cartesian coordinates to ZMatrix format | Make a summary of the following Python 3 code
def cart_to_zmat(self, coordinates):
N = len(self.graph.numbers)
if coordinates.shape != (N, 3):
raise ValueError("The shape of the coordinates must be (%i, 3)" % N)
result = np.zeros(N, dtype=self.dtype)
for i in range(N):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return True if the mapper can map all the IPA characters in the given IPA string. | How would you explain what the following Python 3 function does
def can_map_ipa_string(self, ipa_string):
canonical = [(c.canonical_representation, ) for c in ipa_string]
split = split_using_dictionary(canonical, self, self.max_key_length, single_char_parsing=False)
for sub in split:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.