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 init_ui(self): """Init the ui."""
self.id = 11 self.setFixedSize(self.field_width, self.field_height) self.setPixmap(QtGui.QPixmap(EMPTY_PATH).scaled( self.field_width*3, self.field_height*3)) self.setStyleSheet("QLabel {background-color: blue;}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mousePressEvent(self, event): """Define mouse press event."""
if event.button() == QtCore.Qt.LeftButton: # get label position p_wg = self.parent() p_layout = p_wg.layout() idx = p_layout.indexOf(self) loc = p_layout.getItemPosition(idx)[:2] if p_wg.ms_game.game_status == 2: p_wg.ms_ga...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info_label(self, indicator): """Set info label by given settings. Parameters indicator : int A number where 0-8 is number of mines in srrounding. 12 is a min...
if indicator in xrange(1, 9): self.id = indicator self.setPixmap(QtGui.QPixmap(NUMBER_PATHS[indicator]).scaled( self.field_width, self.field_height)) elif indicator == 0: self.id == 0 self.setPixmap(QtGui.QPixmap(NUMBER_PATHS[0]).scale...
<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): """Thread behavior."""
self.ms_game.tcp_accept() while True: data = self.ms_game.tcp_receive() if data == "help\n": self.ms_game.tcp_help() self.ms_game.tcp_send("> ") elif data == "exit\n": self.ms_game.tcp_close() elif data ==...
<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, options, conf): """Configure which kinds of exceptions trigger plugin. """
self.conf = conf self.enabled = options.epdb_debugErrors or options.epdb_debugFailures self.enabled_for_errors = options.epdb_debugErrors self.enabled_for_failures = options.epdb_debugFailures
<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_trace(self, skip=0): """Start debugging from here."""
frame = sys._getframe().f_back # go up the specified number of frames for i in range(skip): frame = frame.f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stackToList(stack): """ Convert a chain of traceback or frame objects into a list of frames. """
if isinstance(stack, types.TracebackType): while stack.tb_next: stack = stack.tb_next stack = stack.tb_frame out = [] while stack: out.append(stack) stack = stack.f_back return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_IAC(self, sock, cmd, option): """ Read in and parse IAC commands as passed by telnetlib. SB/SE commands are stored in sbdataq, and passed in w/ a com...
if cmd == DO: if option == TM: # timing mark - send WILL into outgoing stream os.write(self.remote, IAC + WILL + TM) else: pass elif cmd == IP: # interrupt process os.write(self.local, IPRESP) elif c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self): """ Creates a child process that is fully controlled by this request handler, and serves data to and from it via the protocol handler. """
pid, fd = pty.fork() if pid: protocol = TelnetServerProtocolHandler(self.request, fd) protocol.handle() else: self.execute()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_request(self): """ Handle one request - serve current process to one connection. Use close_request() to disconnect this process. """
try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): try: # we only serve once, and we want to free up the port # for future serves. self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def int_input(message, low, high, show_range = True): ''' Ask a user for a int input between two values args: message (str): Prompt for user low (int): Low value, user entered value must be > this value to be accepted high (int): High value, user entered value must be < this value t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def float_input(message, low, high): ''' Ask a user for a float input between two values args: message (str): Prompt for user low (float): Low value, user entered value must be > this value to be accepted high (float): High value, user entered value must be < this value to be accept...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bool_input(message): ''' Ask a user for a boolean input args: message (str): Prompt for user returns: bool_in (boolean): Input boolean ''' while True: suffix = ' (true or false): ' inp = input(message + suffix) if inp.lower() == '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 select_project(user_provided_project): ''' Select a project from configuration to run transfer on args: user_provided_project (str): Project name that should match a project in the config returns: project (dict): Configuration settings for a user selected project ''' home...
<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_config(updated_project): ''' Update project in configuration args: updated_project (dict): Updated project configuration values ''' home = os.path.expanduser('~') if os.path.isfile(os.path.join(home, '.transfer', 'config.yaml')): with open(os.path.join(home, '.trans...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atom_criteria(*params): """An auxiliary function to construct a dictionary of Criteria"""
result = {} for index, param in enumerate(params): if param is None: continue elif isinstance(param, int): result[index] = HasAtomNumber(param) else: result[index] = param 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 _check_symbols(self, symbols): """the size must be the same as the length of the array numbers and all elements must be strings"""
if len(symbols) != self.size: raise TypeError("The number of symbols in the graph does not " "match the length of the atomic numbers array.") for symbol in symbols: if not isinstance(symbol, str): raise TypeError("All symbols must be strings.")
<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_blob(cls, s): """Construct a molecular graph from the blob representation"""
atom_str, edge_str = s.split() numbers = np.array([int(s) for s in atom_str.split(",")]) edges = [] orders = [] for s in edge_str.split(","): i, j, o = (int(w) for w in s.split("_")) edges.append((i, j)) orders.append(o) return cls(edg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blob(self): """A compact text representation of the graph"""
atom_str = ",".join(str(number) for number in self.numbers) edge_str = ",".join("%i_%i_%i" % (i, j, o) for (i, j), o in zip(self.edges, self.orders)) return "%s %s" % (atom_str, edge_str)
<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_vertex_string(self, i): """Return a string based on the atom number"""
number = self.numbers[i] if number == 0: return Graph.get_vertex_string(self, i) else: # pad with zeros to make sure that string sort is identical to number sort return "%03i" % number
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_edge_string(self, i): """Return a string based on the bond order"""
order = self.orders[i] if order == 0: return Graph.get_edge_string(self, i) else: # pad with zeros to make sure that string sort is identical to number sort return "%03i" % order
<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_subgraph(self, subvertices, normalize=False): """Creates a subgraph of the current graph See :meth:`molmod.graphs.Graph.get_subgraph` for more informatio...
graph = Graph.get_subgraph(self, subvertices, normalize) if normalize: new_numbers = self.numbers[graph._old_vertex_indexes] # vertices do change else: new_numbers = self.numbers # vertices don't change! if self.symbols is None: new_symbols = 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 add_hydrogens(self, formal_charges=None): """Returns a molecular graph where hydrogens are added explicitely When the bond order is unknown, it assumes bond ...
new_edges = list(self.edges) counter = self.num_vertices for i in range(self.num_vertices): num_elec = self.numbers[i] if formal_charges is not None: num_elec -= int(formal_charges[i]) if num_elec >= 5 and num_elec <= 9: num_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complete(self, match, subject_graph): """Check the completeness of the ring match"""
if not CustomPattern.complete(self, match, subject_graph): return False if self.strong: # If the ring is not strong, return False if self.size % 2 == 0: # even ring for i in range(self.size//2): vertex1_start = matc...
<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(self, copy=False): """Return the value of the attribute"""
array = getattr(self.owner, self.name) if copy: return array.copy() else: return array
<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, skip): """Load the array data from a file-like object"""
array = self.get() counter = 0 counter_limit = array.size convert = array.dtype.type while counter < counter_limit: line = f.readline() words = line.split() for word in words: if counter >= counter_limit: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _register(self, name, AttrCls): """Register a new attribute to take care of with dump and load Arguments: | ``name`` -- the name to be used in the dump file ...
if not issubclass(AttrCls, StateAttr): raise TypeError("The second argument must a StateAttr instance.") if len(name) > 40: raise ValueError("Name can count at most 40 characters.") self._fields[name] = AttrCls(self._owner, 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 get(self, subset=None): """Return a dictionary object with the registered fields and their values Optional rgument: | ``subset`` -- a list of names to restri...
if subset is None: return dict((name, attr.get(copy=True)) for name, attr in self._fields.items()) else: return dict((name, attr.get(copy=True)) for name, attr in self._fields.items() if name in subset)
<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(self, new_fields, subset=None): """Assign the registered fields based on a dictionary Argument: | ``new_fields`` -- the dictionary with the data to be as...
for name in new_fields: if name not in self._fields and (subset is None or name in subset): raise ValueError("new_fields contains an unknown field '%s'." % name) if subset is not None: for name in subset: if name not in self._fields: ...
<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, filename): """Dump the registered fields to a file Argument: | ``filename`` -- the file to write to """
with open(filename, "w") as f: for name in sorted(self._fields): self._fields[name].dump(f, 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 load(self, filename, subset=None): """Load data into the registered fields Argument: | ``filename`` -- the filename to read from Optional argument: | ``subse...
with open(filename, "r") as f: name = None num_names = 0 while True: # read a header line line = f.readline() if len(line) == 0: break # process the header line words = 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_bond_data(self): """Load the bond data from the given file It's assumed that the uncommented lines in the data file have the following format: """
def read_units(unit_names): """convert unit_names into conversion factors""" tmp = { "A": units.angstrom, "pm": units.picometer, "nm": units.nanometer, } return [tmp[unit_name] for unit_name in unit_names] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _approximate_unkown_bond_lengths(self): """Completes the bond length database with approximations based on VDW radii"""
dataset = self.lengths[BOND_SINGLE] for n1 in periodic.iter_numbers(): for n2 in periodic.iter_numbers(): if n1 <= n2: pair = frozenset([n1, n2]) atom1 = periodic[n1] atom2 = periodic[n2] #if (pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bonded(self, n1, n2, distance): """Return the estimated bond type Arguments: | ``n1`` -- the atom number of the first atom in the bond | ``n2`` -- the atom n...
if distance > self.max_length * self.bond_tolerance: return None deviation = 0.0 pair = frozenset([n1, n2]) result = None for bond_type in bond_types: bond_length = self.lengths[bond_type].get(pair) if (bond_length is not None) and \ ...
<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_length(self, n1, n2, bond_type=BOND_SINGLE): """Return the length of a bond between n1 and n2 of type bond_type Arguments: | ``n1`` -- the atom number of...
dataset = self.lengths.get(bond_type) if dataset == None: return None return dataset.get(frozenset([n1, n2]))
<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_parameters3(cls, lengths, angles): """Construct a 3D unit cell with the given parameters The a vector is always parallel with the x-axis and they point ...
for length in lengths: if length <= 0: raise ValueError("The length parameters must be strictly positive.") for angle in angles: if angle <= 0 or angle >= np.pi: raise ValueError("The angle parameters must lie in the range ]0 deg, 180 deg[.") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def volume(self): """The volume of the unit cell The actual definition of the volume depends on the number of active directions: * num_active == 0 -- always -1 *...
active = self.active_inactive[0] if len(active) == 0: return -1 elif len(active) == 1: return np.linalg.norm(self.matrix[:, active[0]]) elif len(active) == 2: return np.linalg.norm(np.cross(self.matrix[:, active[0]], self.matrix[:, active[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 active_inactive(self): """The indexes of the active and the inactive cell vectors"""
active_indices = [] inactive_indices = [] for index, active in enumerate(self.active): if active: active_indices.append(index) else: inactive_indices.append(index) return active_indices, inactive_indices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reciprocal(self): """The reciprocal of the unit cell In case of a three-dimensional periodic system, this is trivially the transpose of the inverse of the ce...
U, S, Vt = np.linalg.svd(self.matrix*self.active) Sinv = np.zeros(S.shape, float) for i in range(3): if abs(S[i]) < self.eps: Sinv[i] = 0.0 else: Sinv[i] = 1.0/S[i] return np.dot(U*Sinv, Vt)*self.active
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ordered(self): """An equivalent unit cell with the active cell vectors coming first"""
active, inactive = self.active_inactive order = active + inactive return UnitCell(self.matrix[:,order], self.active[order])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignment_a(self): """Computes the rotation matrix that aligns the unit cell with the Cartesian axes, starting with cell vector a. * a parallel to x * b in x...
from molmod.transformations import Rotation new_x = self.matrix[:, 0].copy() new_x /= np.linalg.norm(new_x) new_z = np.cross(new_x, self.matrix[:, 1]) new_z /= np.linalg.norm(new_z) new_y = np.cross(new_z, new_x) new_y /= np.linalg.norm(new_y) return Rota...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spacings(self): """Computes the distances between neighboring crystal planes"""
result_invsq = (self.reciprocal**2).sum(axis=0) result = np.zeros(3, float) for i in range(3): if result_invsq[i] > 0: result[i] = result_invsq[i]**(-0.5) 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 add_cell_vector(self, vector): """Returns a new unit cell with an additional cell vector"""
act = self.active_inactive[0] if len(act) == 3: raise ValueError("The unit cell already has three active cell vectors.") matrix = np.zeros((3, 3), float) active = np.zeros(3, bool) if len(act) == 0: # Add the new vector matrix[:, 0] = vector ...
<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_radius_ranges(self, radius, mic=False): """Return ranges of indexes of the interacting neighboring unit cells Interacting neighboring unit cells have at ...
result = np.zeros(3, int) for i in range(3): if self.spacings[i] > 0: if mic: result[i] = np.ceil(radius/self.spacings[i]-0.5) else: result[i] = np.ceil(radius/self.spacings[i]) 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 get_radius_indexes(self, radius, max_ranges=None): """Return the indexes of the interacting neighboring unit cells Interacting neighboring unit cells have at...
if max_ranges is None: max_ranges = np.array([-1, -1, -1]) ranges = self.get_radius_ranges(radius)*2+1 mask = (max_ranges != -1) & (max_ranges < ranges) ranges[mask] = max_ranges[mask] max_size = np.product(self.get_radius_ranges(radius)*2 + 1) indexes = np.z...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_geometry(graph, unit_cell=None, verbose=False): """Construct a molecular geometry based on a molecular graph. This routine does not require initial coo...
N = len(graph.numbers) from molmod.minimizer import Minimizer, ConjugateGradient, \ NewtonLineSearch, ConvergenceCondition, StopLossCondition search_direction = ConjugateGradient() line_search = NewtonLineSearch() convergence = ConvergenceCondition(grad_rms=1e-6, step_rms=1e-6) stop_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energy(self): """Compute the energy of the system"""
result = 0.0 for index1 in range(self.numc): for index2 in range(index1): if self.scaling[index1, index2] > 0: for se, ve in self.yield_pair_energies(index1, index2): result += se*ve*self.scaling[index1, index2] return resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gradient_component(self, index1): """Compute the gradient of the energy for one atom"""
result = np.zeros(3, float) for index2 in range(self.numc): if self.scaling[index1, index2] > 0: for (se, ve), (sg, vg) in zip(self.yield_pair_energies(index1, index2), self.yield_pair_gradients(index1, index2)): result += (sg*self.directions[index1, inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gradient(self): """Compute the gradient of the energy for all atoms"""
result = np.zeros((self.numc, 3), float) for index1 in range(self.numc): result[index1] = self.gradient_component(index1) 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 hessian_component(self, index1, index2): """Compute the hessian of the energy for one atom pair"""
result = np.zeros((3, 3), float) if index1 == index2: for index3 in range(self.numc): if self.scaling[index1, index3] > 0: d_1 = 1/self.distances[index1, index3] for (se, ve), (sg, vg), (sh, vh) in zip( self.yie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hessian(self): """Compute the hessian of the energy"""
result = np.zeros((self.numc, 3, self.numc, 3), float) for index1 in range(self.numc): for index2 in range(self.numc): result[index1, :, index2, :] = self.hessian_component(index1, index2) 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 load_cml(cml_filename): """Load the molecules from a CML file Argument: | ``cml_filename`` -- The filename of a CML file. Returns a list of molecule objects ...
parser = make_parser() parser.setFeature(feature_namespaces, 0) dh = CMLMoleculeLoader() parser.setContentHandler(dh) parser.parse(cml_filename) return dh.molecules
<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_cml_molecule(f, molecule): """Dump a single molecule to a CML file Arguments: | ``f`` -- a file-like object | ``molecule`` -- a Molecule instance """
extra = getattr(molecule, "extra", {}) attr_str = " ".join("%s='%s'" % (key, value) for key, value in extra.items()) f.write(" <molecule id='%s' %s>\n" % (molecule.title, attr_str)) f.write(" <atomArray>\n") atoms_extra = getattr(molecule, "atoms_extra", {}) for counter, number, coordinate in ...
<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_cml(f, molecules): """Write a list of molecules to a CML file Arguments: | ``f`` -- a filename of a CML file or a file-like object | ``molecules`` -- a ...
if isinstance(f, str): f = open(f, "w") close = True else: close = False f.write("<?xml version='1.0'?>\n") f.write("<list xmlns='http://www.xml-cml.org/schema'>\n") for molecule in molecules: _dump_cml_molecule(f, molecule) f.write("</list>\n") if close: ...
<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_extra(self, attrs, exclude): """Read the extra properties, taking into account an exclude list"""
result = {} for key in attrs.getNames(): if key not in exclude: result[str(key)] = str(attrs[key]) 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 _read(self, filename, field_labels=None): """Read all the requested fields Arguments: | ``filename`` -- the filename of the FCHK file | ``field_labels`` -- w...
# if fields is None, all fields are read def read_field(f): """Read a single field""" datatype = None while datatype is None: # find a sane header line line = f.readline() if line == "": 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 _analyze(self): """Convert a few elementary fields into a molecule object"""
if ("Atomic numbers" in self.fields) and ("Current cartesian coordinates" in self.fields): self.molecule = Molecule( self.fields["Atomic numbers"], np.reshape(self.fields["Current cartesian coordinates"], (-1, 3)), self.title, )
<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_optimization_coordinates(self): """Return the coordinates of the geometries at each point in the optimization"""
coor_array = self.fields.get("Opt point 1 Geometries") if coor_array is None: return [] else: return np.reshape(coor_array, (-1, len(self.molecule.numbers), 3))
<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_optimized_molecule(self): """Return a molecule object of the optimal geometry"""
opt_coor = self.get_optimization_coordinates() if len(opt_coor) == 0: return None else: return Molecule( self.molecule.numbers, opt_coor[-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 get_optimization_gradients(self): """Return the energy gradients of all geometries during an optimization"""
grad_array = self.fields.get("Opt point 1 Gradient at each geome") if grad_array is None: return [] else: return np.reshape(grad_array, (-1, len(self.molecule.numbers), 3))
<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_hessian(self): """Return the hessian"""
force_const = self.fields.get("Cartesian Force Constants") if force_const is None: return None N = len(self.molecule.numbers) result = np.zeros((3*N, 3*N), float) counter = 0 for row in range(3*N): result[row, :row+1] = force_const[counter:counter...
<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(self, filename): """Internal routine that reads all data from the punch file."""
data = {} parsers = [ FirstDataParser(), CoordinateParser(), EnergyGradParser(), SkipApproxHessian(), HessianParser(), MassParser(), ] with open(filename) as f: while True: line = f.readline() if 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 setup_hydrocarbon_ff(graph): """Create a simple ForceField object for hydrocarbons based on the 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, val in list(bond_params.items()): if key[0] != key[1]: bond_params[(key[1], key[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 add_to_hessian(self, coordinates, hessian): """Add the contributions of this energy term to the Hessian Arguments: | ``coordinates`` -- A numpy array with 3N...
# Compute the derivatives of the bond stretch towards the two cartesian # coordinates. The bond length is computed too, but not used. q, g = self.icfn(coordinates[list(self.indexes)], 1) # Add the contribution to the Hessian (an outer product) for ja, ia in enumerate(self.indexe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hessian(self, coordinates): """Compute the force-field Hessian for the given coordinates. Argument: | ``coordinates`` -- A numpy array with the Cartesian ato...
# 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.terms: term.add_to_hessian(coordinates, hessian) return hessian
<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(molecule, graph, threshold=1e-3*angstrom): """Compute the rotational symmetry number Arguments: | ``molecule`` -- The molecule | ``graph`` -- ...
result = 0 for match in graph.symmetries: permutation = list(j for i,j in sorted(match.forward.items())) new_coordinates = molecule.coordinates[permutation] rmsd = fit_rmsd(molecule.coordinates, new_coordinates)[2] if rmsd < threshold: result += 1 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 quaternion_product(quat1, quat2): """Return the quaternion product of the two arguments"""
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]*quat2[1] - quat1[1]*quat2[3], quat1[0]*quat2[3] + quat2[0]*quat1[3] + quat1[1]*quat2[2]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quaternion_rotation(quat, vector): """Apply the rotation represented by the quaternion to the vector Warning: This only works correctly for normalized quater...
dp = np.dot(quat[1:], vector) cos = (2*quat[0]*quat[0] - 1) return np.array([ 2 * (quat[0] * (quat[2] * vector[2] - quat[3] * vector[1]) + quat[1] * dp) + cos * vector[0], 2 * (quat[0] * (quat[3] * vector[0] - quat[1] * vector[2]) + quat[2] * dp) + cos * vector[1], 2 * (quat[0] * (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 rotation_matrix_to_quaternion(rotation_matrix): """Compute the quaternion representing the rotation given by the 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 = np.sqrt(c2) r2 = 0.5*(1 + factor*np.diagonal(rotation_matrix)) - c2 #print "check", r2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ], [2*x*z - 2*c*y, 2*y*z + 2*c*x, c*c - x*x - y*y + z*z] ], 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 cosine(a, b): """Compute the cosine between two vectors The result is clipped within the range [-1, 1] """
result = np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b) return np.clip(result, -1, 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 random_unit(size=3): """Return a random unit vector of the given dimension Optional argument: size -- the number of dimensions of the unit vector [default=3]...
while True: result = np.random.normal(0, 1, size) length = np.linalg.norm(result) if length > 1e-3: return result/length
<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_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.sin(alpha)*v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triangle_normal(a, b, c): """Return a vector orthogonal to the given triangle Arguments: a, b, c -- three 3D numpy vectors """
normal = np.cross(a - c, b - c) norm = np.linalg.norm(normal) return normal/norm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot(r1, r2): """Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar) """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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("Both arguments must have the same deriv.") result = Vector3(r1.size, r1.deriv) result.x = r1.y*r2.z - r1.z*r2.y result.y = r1.z*r2.x - r1.x*r2.z re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bond_length_low(r, deriv): """Similar to bond_length, but with a relative vector"""
r = Vector3(3, deriv, r, (0, 1, 2)) d = r.norm() return d.results()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bend_cos_low(a, b, deriv): """Similar to bend_cos, but with relative vectors"""
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bend_angle_low(a, b, deriv): """Similar to bend_angle, but with relative vectors"""
result = _bend_cos_low(a, b, deriv) return _cos_to_angle(result, deriv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _opdist_low(av, bv, cv, deriv): """Similar to opdist, but with relative vectors"""
a = Vector3(9, deriv, av, (0, 1, 2)) b = Vector3(9, deriv, bv, (3, 4, 5)) c = Vector3(9, deriv, cv, (6, 7, 8)) n = cross(a, b) n /= n.norm() dist = dot(c, n) return dist.results()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _opbend_cos_low(a, b, c, deriv): """Similar to opbend_cos, but with relative vectors"""
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() result.v = np.sqrt(1.0-temp.v**2) if result.deriv > 0: result.d *= -temp.v ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _opbend_angle_low(a, b, c, deriv=0): """Similar to opbend_angle, but with relative vectors"""
result = _opbend_cos_low(a, b, c, deriv) sign = np.sign(np.linalg.det([a, b, c])) return _cos_to_angle(result, deriv, sign)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = factor1*result[1] if deriv == 1: return v*sign, d*sign factor2 = result[0]*factor1**3 dd = factor2*...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 if deriv == 0: return v*sign + offset, if abs(result[0]) >= 1: factor1 = 0 else: fact...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<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): """In place invert"""
self.v = 1/self.v tmp = self.v**2 if self.deriv > 1: self.dd[:] = tmp*(2*self.v*np.outer(self.d, self.d) - self.dd) if self.deriv > 0: self.d[:] = -tmp*self.d[:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 result.d += self.z.v*self.z.d result.d /= result.v if self.de...
<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_line(self): """Get a line or raise StopIteration"""
line = self._f.readline() if len(line) == 0: raise StopIteration 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 _read_frame(self): """Read one frame"""
# 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+2:])*picosecond else: time = 0.0 # Read the second line, the 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 _skip_frame(self): """Skip one frame"""
self._get_line() num_atoms = int(self._get_line()) if self.num_atoms is not None and self.num_atoms != num_atoms: raise ValueError("The number of atoms must be the same over the entire file.") for i in range(num_atoms+1): self._get_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 setup_ics(graph): """Make a list of internal coordinates based on the graph Argument: | ``graph`` -- A Graph instance. The list of internal coordinates will ...
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): n = list(graph.neighbors[i1]) for index, i0 in enumerate(n): for ...
<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_jacobian(ics, coordinates): """Construct a Jacobian for the given internal and Cartesian coordinates Arguments: | ``ics`` -- A list of internal coord...
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(jacobian[:,j], coordinates) return jacobian
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_jacobian_column(self, jaccol, coordinates): """Fill in a column of the Jacobian. Arguments: | ``jaccol`` -- The column of Jacobian to which the result m...
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
<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_similarity(a, b, margin=1.0, cutoff=10.0): """Compute the similarity between two molecules based on their descriptors Arguments: a -- the similarity ...
return similarity_measure( a.table_labels, a.table_distances, b.table_labels, b.table_distances, margin, cutoff )
<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_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, boolean or an array of strings, integers, booleans or floats. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 unique for the molecule composition and connectivity self.molecul...
<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(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 line 'PSF'.") # B) read in all the sections, without in...
<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_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.fingerprint.tobytes() name = self.name_cache.get(fingerprint) if name is None: name = "NM%02i" % len(self.name_cache) self.name_cache[fingerprint] = 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 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 estima...
molecular_graph = MolecularGraph.from_geometry(molecule) self.add_molecular_graph(molecular_graph, atom_types, charges, split, 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 add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None): """Add the molecular graph to the data structure Argume...
# add atom numbers and molecule indices new = len(molecular_graph.numbers) if new == 0: return prev = len(self.numbers) offset = prev self.numbers.resize(prev + new) self.numbers[-new:] = molecular_graph.numbers if atom_types is None: atom_typ...