_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33300
BasePickerInput.format_js2py
train
def format_js2py(cls, datetime_format): """Convert moment datetime format to python datetime format.""" for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(js_format, py_format) return datetime_format
python
{ "resource": "" }
q33301
BasePickerInput._calculate_options
train
def _calculate_options(self): """Calculate and Return the options.""" _options = self._default_options.copy() _options.update(self.options) if self.options_param: _options.update(self.options_param) return _options
python
{ "resource": "" }
q33302
BasePickerInput._calculate_format
train
def _calculate_format(self): """Calculate and Return the datetime format.""" _format = self.format_param if self.format_param else self.format if self.config['options'].get('format'): _format = self.format_js2py(self.config['options'].get('format')) else: self.con...
python
{ "resource": "" }
q33303
BasePickerInput.get_context
train
def get_context(self, name, value, attrs): """Return widget context dictionary.""" context = super().get_context( name, value, attrs) context['widget']['attrs']['dp_config'] = json_dumps(self.config) return context
python
{ "resource": "" }
q33304
BasePickerInput.end_of
train
def end_of(self, event_id, import_options=True): """ Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE ...
python
{ "resource": "" }
q33305
get_base_input
train
def get_base_input(test=False): """ Return DateTimeBaseInput class from django.forms.widgets module Return _compatibility.DateTimeBaseInput class for older django versions. """ from django.forms.widgets import DateTimeBaseInput if 'get_context' in dir(DateTimeBaseInput) and not test: # ...
python
{ "resource": "" }
q33306
split_lines
train
def split_lines(source, maxline=79): """Split inputs according to lines. If a line is short enough, just yield it. Otherwise, fix it. """ result = [] extend = result.extend append = result.append line = [] multiline = False count = 0 find = str.find for item in sour...
python
{ "resource": "" }
q33307
wrap_line
train
def wrap_line(line, maxline=79, result=[], count=count): """ We have a line that is too long, so we're going to try to wrap it. """ # Extract the indentation append = result.append extend = result.extend indentation = line[0] lenfirst = len(indentation) indent = lenfirst - len...
python
{ "resource": "" }
q33308
split_group
train
def split_group(source, pos, maxline): """ Split a group into two subgroups. The first will be appended to the current line, the second will start the new line. Note that the first group must always contain at least one item. The original group may be destroyed. """ ...
python
{ "resource": "" }
q33309
delimiter_groups
train
def delimiter_groups(line, begin_delim=begin_delim, end_delim=end_delim): """Split a line into alternating groups. The first group cannot have a line feed inserted, the next one can, etc. """ text = [] line = iter(line) while True: # First build and yield a...
python
{ "resource": "" }
q33310
add_parens
train
def add_parens(line, maxline, indent, statements=statements, count=count): """Attempt to add parentheses around the line in order to make it splittable. """ if line[0] in statements: index = 1 if not line[0].endswith(' '): index = 2 assert line[1] == ' ' ...
python
{ "resource": "" }
q33311
_prep_triple_quotes
train
def _prep_triple_quotes(s, mysplit=mysplit, replacements=replacements): """ Split the string up and force-feed some replacements to make sure it will round-trip OK """ s = mysplit(s) s[1::2] = (replacements[x] for x in s[1::2]) return ''.join(s)
python
{ "resource": "" }
q33312
pretty_string
train
def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100): """There are a lot of reasons why we might not want to or be able to return a triple-quoted string. We can always punt back to the default normal string. """ default = repr(s) #...
python
{ "resource": "" }
q33313
TreeWalk.setup
train
def setup(self): """All the node-specific handlers are setup at object initialization time. """ self.pre_handlers = pre_handlers = {} self.post_handlers = post_handlers = {} for name in sorted(vars(type(self))): if name.startswith('init_'): ge...
python
{ "resource": "" }
q33314
TreeWalk.walk
train
def walk(self, node, name='', list=list, len=len, type=type): """Walk the tree starting at a given node. Maintain a stack of nodes. """ pre_handlers = self.pre_handlers.get post_handlers = self.post_handlers.get nodestack = self.nodestack emptystack = len(nodest...
python
{ "resource": "" }
q33315
TreeWalk.replace
train
def replace(self, new_node): """Replace a node after first checking integrity of node stack.""" cur_node = self.cur_node nodestack = self.nodestack cur = nodestack.pop() prev = nodestack[-1] index = prev[-1] - 1 oldnode, name = prev[-2][index] assert cur[0...
python
{ "resource": "" }
q33316
strip_tree
train
def strip_tree(node, # Runtime optimization iter_node=iter_node, special=ast.AST, list=list, isinstance=isinstance, type=type, len=len): """Strips an AST by removing all attributes not in _fields. Returns a set of the names of all attributes stripped. This cano...
python
{ "resource": "" }
q33317
fast_compare
train
def fast_compare(tree1, tree2): """ This is optimized to compare two AST trees for equality. It makes several assumptions that are currently true for AST trees used by rtrip, and it doesn't examine the _attributes. """ geta = ast.AST.__getattribute__ work = [(tree1, tree2)] pop = w...
python
{ "resource": "" }
q33318
get_op_symbol
train
def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type): """Given an AST node object, returns a string containing the symbol. """ return fmt % symbol_data[type(obj)]
python
{ "resource": "" }
q33319
CodeToAst.find_py_files
train
def find_py_files(srctree, ignore=None): """Return all the python files in a source tree Ignores any path that contains the ignore string This is not used by other class methods, but is designed to be used in code that uses this class. """ if not os.path.isdir(srctree)...
python
{ "resource": "" }
q33320
CodeToAst.parse_file
train
def parse_file(fname): """Parse a python file into an AST. This is a very thin wrapper around ast.parse TODO: Handle encodings other than the default for Python 2 (issue #26) """ try: with fopen(fname) as f: fstr = f.read(...
python
{ "resource": "" }
q33321
CodeToAst.get_file_info
train
def get_file_info(codeobj): """Returns the file and line number of a code object. If the code object has a __file__ attribute (e.g. if it is a module), then the returned line number will be 0 """ fname = getattr(codeobj, '__file__', None) linenum = 0 ...
python
{ "resource": "" }
q33322
validate_token_age
train
def validate_token_age(callback_token): """ Returns True if a given token is within the age expiration limit. """ try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_setti...
python
{ "resource": "" }
q33323
verify_user_alias
train
def verify_user_alias(user, token): """ Marks a user's contact point as verified depending on accepted token type. """ if token.to_alias_type == 'EMAIL': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_...
python
{ "resource": "" }
q33324
send_email_with_callback_token
train
def send_email_with_callback_token(user, email_token, **kwargs): """ Sends a Email to user.email. Passes silently without sending in test environment """ try: if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS: # Make sure we have a sending address before sending. ...
python
{ "resource": "" }
q33325
send_sms_with_callback_token
train
def send_sms_with_callback_token(user, mobile_token, **kwargs): """ Sends a SMS to user.mobile via Twilio. Passes silently without sending in test environment. """ base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE) try: if api_settings.PASSWORDLESS_MO...
python
{ "resource": "" }
q33326
invalidate_previous_tokens
train
def invalidate_previous_tokens(sender, instance, **kwargs): """ Invalidates all previously issued tokens as a post_save signal. """ active_tokens = None if isinstance(instance, CallbackToken): active_tokens = CallbackToken.objects.active().filter(user=instance.user).exclude(id=instance.id) ...
python
{ "resource": "" }
q33327
check_unique_tokens
train
def check_unique_tokens(sender, instance, **kwargs): """ Ensures that mobile and email tokens are unique or tries once more to generate. """ if isinstance(instance, CallbackToken): if CallbackToken.objects.filter(key=instance.key, is_active=True).exists(): instance.key = generate_num...
python
{ "resource": "" }
q33328
update_alias_verification
train
def update_alias_verification(sender, instance, **kwargs): """ Flags a user's email as unverified if they change it. Optionally sends a verification token to the new endpoint. """ if isinstance(instance, User): if instance.id: if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFI...
python
{ "resource": "" }
q33329
calc_dihedral
train
def calc_dihedral(point1, point2, point3, point4): """Calculates a dihedral angle Here, two planes are defined by (point1, point2, point3) and (point2, point3, point4). The angle between them is returned. Parameters ---------- point1, point2, point3, point4 : array-like, shape=(3,), dtype=floa...
python
{ "resource": "" }
q33330
Pattern.scale
train
def scale(self, by): """Scale the points in the Pattern. Parameters ---------- by : float or np.ndarray, shape=(3,) The factor to scale by. If a scalar, scale all directions isotropically. If np.ndarray, scale each direction independently. """ sel...
python
{ "resource": "" }
q33331
Pattern.apply
train
def apply(self, compound, orientation='', compound_port=''): """Arrange copies of a Compound as specified by the Pattern. Parameters ---------- compound orientation Returns ------- """ compounds = list() if self.orientations.get(orientat...
python
{ "resource": "" }
q33332
Pattern.apply_to_compound
train
def apply_to_compound(self, guest, guest_port_name='down', host=None, backfill=None, backfill_port_name='up', scale=True): """Attach copies of a guest Compound to Ports on a host Compound. Parameters ---------- guest : mb.Compound The Compound proto...
python
{ "resource": "" }
q33333
Lattice._sanitize_inputs
train
def _sanitize_inputs(self, lattice_spacing, lattice_vectors, lattice_points, angles): """Check for proper inputs and set instance attributes. validate_inputs takes the data passed to the constructor by the user and will ensure that the data is correctly formatted and wi...
python
{ "resource": "" }
q33334
Lattice._validate_lattice_spacing
train
def _validate_lattice_spacing(self, lattice_spacing): """Ensure that lattice spacing is provided and correct. _validate_lattice_spacing will ensure that the lattice spacing provided are acceptable values. Additional Numpy errors can also occur due to the conversion to a Numpy array. ...
python
{ "resource": "" }
q33335
Lattice._validate_angles
train
def _validate_angles(self, angles): """Ensure that the angles between the lattice_vectors are correct""" dataType = np.float64 tempAngles = np.asarray(angles, dtype=dataType) tempAngles = tempAngles.reshape((3,)) if np.shape(tempAngles) == (self.dimension,): if np.s...
python
{ "resource": "" }
q33336
Lattice._validate_lattice_vectors
train
def _validate_lattice_vectors(self, lattice_vectors): """Ensure that the lattice_vectors are reasonable inputs. """ dataType = np.float64 if lattice_vectors is None: lattice_vectors = np.identity(self.dimension, dtype=dataType) else: lattice_vectors =...
python
{ "resource": "" }
q33337
Lattice._from_lattice_parameters
train
def _from_lattice_parameters(self, angles): """Convert Bravais lattice parameters to lattice vectors. _from_lattice_parameters will generate the lattice vectors based on the parameters necessary to build a Bravais Lattice. The lattice vectors are in the lower diagonal matrix form. ...
python
{ "resource": "" }
q33338
Lattice._from_lattice_vectors
train
def _from_lattice_vectors(self): """Calculate the angles between the vectors that define the lattice. _from_lattice_vectors will calculate the angles alpha, beta, and gamma from the Lattice object attribute lattice_vectors. """ degreeConvsersion = 180.0 / np.pi vector_m...
python
{ "resource": "" }
q33339
Bilayer.create_layer
train
def create_layer(self, lipid_indices=None, flip_orientation=False): """Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, defau...
python
{ "resource": "" }
q33340
Bilayer.solvate_bilayer
train
def solvate_bilayer(self): """Solvate the constructed bilayer. """ solvent_number_density = self.solvent.n_particles / np.prod(self.solvent.periodicity) lengths = self.lipid_box.lengths water_box_z = self.solvent_per_layer / (lengths[0] * lengths[1] * solvent_number_density) mi...
python
{ "resource": "" }
q33341
Bilayer.solvent_per_layer
train
def solvent_per_layer(self): """Determine the number of solvent molecules per single layer. """ if self._solvent_per_layer: return self._solvent_per_layer assert not (self.solvent_per_lipid is None and self.n_solvent is None) if self.solvent_per_lipid is not None: ...
python
{ "resource": "" }
q33342
Bilayer.number_of_each_lipid_per_layer
train
def number_of_each_lipid_per_layer(self): """The number of each lipid per layer. """ if self._number_of_each_lipid_per_layer: return self._number_of_each_lipid_per_layer for lipid in self.lipids[:-1]: self._number_of_each_lipid_per_layer.append(int(round(lipid[1] * self....
python
{ "resource": "" }
q33343
Bilayer.lipid_box
train
def lipid_box(self): """The box containing all of the lipids. """ if self._lipid_box: return self._lipid_box else: self._lipid_box = self.lipid_components.boundingbox # Add buffer around lipid box. self._lipid_box.mins -= np.array([0.5*np.sqrt(self...
python
{ "resource": "" }
q33344
load
train
def load(filename, relative_to_module=None, compound=None, coords_only=False, rigid=False, use_parmed=False, smiles=False, **kwargs): """Load a file into an mbuild compound. Files are read using the MDTraj package unless the `use_parmed` argument is specified as True. Please refer to http://mdtraj...
python
{ "resource": "" }
q33345
Compound.successors
train
def successors(self): """Yield Compounds below self in the hierarchy. Yields ------- mb.Compound The next Particle below self in the hierarchy """ if not self.children: return for part in self.children: # Parts local to the cu...
python
{ "resource": "" }
q33346
Compound.ancestors
train
def ancestors(self): """Generate all ancestors of the Compound recursively. Yields ------ mb.Compound The next Compound above self in the hierarchy """ if self.parent is not None: yield self.parent for ancestor in self.parent.ancestor...
python
{ "resource": "" }
q33347
Compound.particles_by_name
train
def particles_by_name(self, name): """Return all Particles of the Compound with a specific name Parameters ---------- name : str Only particles with this name are returned Yields ------ mb.Compound The next Particle in the Compound with t...
python
{ "resource": "" }
q33348
Compound.contains_rigid
train
def contains_rigid(self): """Returns True if the Compound contains rigid bodies If the Compound contains any particle with a rigid_id != None then contains_rigid will return True. If the Compound has no children (i.e. the Compound resides at the bottom of the containment hierarc...
python
{ "resource": "" }
q33349
Compound.max_rigid_id
train
def max_rigid_id(self): """Returns the maximum rigid body ID contained in the Compound. This is usually used by compound.root to determine the maximum rigid_id in the containment hierarchy. Returns ------- int or None The maximum rigid body ID contained in t...
python
{ "resource": "" }
q33350
Compound.rigid_particles
train
def rigid_particles(self, rigid_id=None): """Generate all particles in rigid bodies. If a rigid_id is specified, then this function will only yield particles with a matching rigid_id. Parameters ---------- rigid_id : int, optional Include only particles with...
python
{ "resource": "" }
q33351
Compound.label_rigid_bodies
train
def label_rigid_bodies(self, discrete_bodies=None, rigid_particles=None): """Designate which Compounds should be treated as rigid bodies If no arguments are provided, this function will treat the compound as a single rigid body by providing all particles in `self` with the same rigid_id...
python
{ "resource": "" }
q33352
Compound.unlabel_rigid_bodies
train
def unlabel_rigid_bodies(self): """Remove all rigid body labels from the Compound """ self._check_if_contains_rigid_bodies = True for child in self.children: child._check_if_contains_rigid_bodies = True for particle in self.particles(): particle.rigid_id = None
python
{ "resource": "" }
q33353
Compound._increment_rigid_ids
train
def _increment_rigid_ids(self, increment): """Increment the rigid_id of all rigid Particles in a Compound Adds `increment` to the rigid_id of all Particles in `self` that already have an integer rigid_id. """ for particle in self.particles(): if particle.rigid_id is ...
python
{ "resource": "" }
q33354
Compound._reorder_rigid_ids
train
def _reorder_rigid_ids(self): """Reorder rigid body IDs ensuring consecutiveness. Primarily used internally to ensure consecutive rigid_ids following removal of a Compound. """ max_rigid = self.max_rigid_id unique_rigid_ids = sorted( set([p.rigid_id for p in...
python
{ "resource": "" }
q33355
Compound.add
train
def add(self, new_child, label=None, containment=True, replace=False, inherit_periodicity=True, reset_rigid_ids=True): """Add a part to the Compound. Note: This does not necessarily add the part to self.children but may instead be used to add a reference to the part ...
python
{ "resource": "" }
q33356
Compound.remove
train
def remove(self, objs_to_remove): """Remove children from the Compound. Parameters ---------- objs_to_remove : mb.Compound or list of mb.Compound The Compound(s) to be removed from self """ if not self.children: return if not hasattr(obj...
python
{ "resource": "" }
q33357
Compound._remove_references
train
def _remove_references(self, removed_part): """Remove labels pointing to this part and vice versa. """ removed_part.parent = None # Remove labels in the hierarchy pointing to this part. referrers_to_remove = set() for referrer in removed_part.referrers: if removed_pa...
python
{ "resource": "" }
q33358
Compound.referenced_ports
train
def referenced_ports(self): """Return all Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all ports referenced by the Compound """ from mbuild.port import Port return [port for port in self.labels.values() ...
python
{ "resource": "" }
q33359
Compound.all_ports
train
def all_ports(self): """Return all Ports referenced by this Compound and its successors Returns ------- list of mb.Compound A list of all Ports referenced by this Compound and its successors """ from mbuild.port import Port return [successor for succ...
python
{ "resource": "" }
q33360
Compound.available_ports
train
def available_ports(self): """Return all unoccupied Ports referenced by this Compound. Returns ------- list of mb.Compound A list of all unoccupied ports referenced by the Compound """ from mbuild.port import Port return [port for port in self.labels...
python
{ "resource": "" }
q33361
Compound.bonds
train
def bonds(self): """Return all bonds in the Compound and sub-Compounds. Yields ------- tuple of mb.Compound The next bond in the Compound See Also -------- bond_graph.edges_iter : Iterates over all edges in a BondGraph """ if self.ro...
python
{ "resource": "" }
q33362
Compound.add_bond
train
def add_bond(self, particle_pair): """Add a bond between two Particles. Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to add a bond between """ if self.root.bond_graph is None: self.root...
python
{ "resource": "" }
q33363
Compound.remove_bond
train
def remove_bond(self, particle_pair): """Deletes a bond between a pair of Particles Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to remove the bond between """ from mbuild.port import Port ...
python
{ "resource": "" }
q33364
Compound.xyz
train
def xyz(self): """Return all particle coordinates in this compound. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles. """ if not self.children: pos = np.expand_dims(self._pos, axis=0) el...
python
{ "resource": "" }
q33365
Compound.xyz_with_ports
train
def xyz_with_ports(self): """Return all particle coordinates in this compound including ports. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles and ports. """ if not self.children: pos = self._...
python
{ "resource": "" }
q33366
Compound.xyz
train
def xyz(self, arrnx3): """Set the positions of the particles in the Compound, excluding the Ports. This function does not set the position of the ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions """ ...
python
{ "resource": "" }
q33367
Compound.xyz_with_ports
train
def xyz_with_ports(self, arrnx3): """Set the positions of the particles in the Compound, including the Ports. Parameters ---------- arrnx3 : np.ndarray, shape=(n,3), dtype=float The new particle positions """ if not self.children: if not arrnx3.s...
python
{ "resource": "" }
q33368
Compound.center
train
def center(self): """The cartesian center of the Compound based on its Particles. Returns ------- np.ndarray, shape=(3,), dtype=float The cartesian center of the Compound based on its Particles """ if np.all(np.isfinite(self.xyz)): return np.mea...
python
{ "resource": "" }
q33369
Compound.boundingbox
train
def boundingbox(self): """Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound """ xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
python
{ "resource": "" }
q33370
Compound.min_periodic_distance
train
def min_periodic_distance(self, xyz0, xyz1): """Vectorized distance calculation considering minimum image. Parameters ---------- xyz0 : np.ndarray, shape=(3,), dtype=float Coordinates of first point xyz1 : np.ndarray, shape=(3,), dtype=float Coordinates o...
python
{ "resource": "" }
q33371
Compound.particles_in_range
train
def particles_in_range( self, compound, dmax, max_particles=20, particle_kdtree=None, particle_array=None): """Find particles within a specified range of another particle. Parameters ---------- compound : mb.Compoun...
python
{ "resource": "" }
q33372
Compound.visualize
train
def visualize(self, show_ports=False): """Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. Parameters ---------- show_ports : bool, optional, default=False Visualize Ports in addition to Particles """ ...
python
{ "resource": "" }
q33373
Compound.update_coordinates
train
def update_coordinates(self, filename, update_port_locations=True): """Update the coordinates of this Compound from a file. Parameters ---------- filename : str Name of file from which to load coordinates. Supported file types are the same as those supported by l...
python
{ "resource": "" }
q33374
Compound._update_port_locations
train
def _update_port_locations(self, initial_coordinates): """Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the loca...
python
{ "resource": "" }
q33375
Compound._kick
train
def _kick(self): """Slightly adjust all coordinates in a Compound Provides a slight adjustment to coordinates to kick them out of local energy minima. """ xyz_init = self.xyz for particle in self.particles(): particle.pos += (np.random.rand(3,) - 0.5) / 100 ...
python
{ "resource": "" }
q33376
Compound.save
train
def save(self, filename, show_ports=False, forcefield_name=None, forcefield_files=None, forcefield_debug=False, box=None, overwrite=False, residues=None, references_file=None, combining_rule='lorentz', foyerkwargs={}, **kwargs): """Save the Compound to a file. Par...
python
{ "resource": "" }
q33377
Compound.translate
train
def translate(self, by): """Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float """ new_positions = _translate(self.xyz_with_ports, by) self.xyz_with_ports = new_positions
python
{ "resource": "" }
q33378
Compound.rotate
train
def rotate(self, theta, around): """Rotate Compound around an arbitrary vector. Parameters ---------- theta : float The angle by which to rotate the Compound, in radians. around : np.ndarray, shape=(3,), dtype=float The vector about which to rotate the Co...
python
{ "resource": "" }
q33379
Compound.spin
train
def spin(self, theta, around): """Rotate Compound in place around an arbitrary vector. Parameters ---------- theta : float The angle by which to rotate the Compound, in radians. around : np.ndarray, shape=(3,), dtype=float The axis about which to spin the...
python
{ "resource": "" }
q33380
Compound.from_trajectory
train
def from_trajectory(self, traj, frame=-1, coords_only=False): """Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- traj : mdtraj.Trajectory ...
python
{ "resource": "" }
q33381
Compound.to_trajectory
train
def to_trajectory(self, show_ports=False, chains=None, residues=None, box=None): """Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajecto...
python
{ "resource": "" }
q33382
Compound._to_topology
train
def _to_topology(self, atom_list, chains=None, residues=None): """Create a mdtraj.Topology from a Compound. Parameters ---------- atom_list : list of mb.Compound Atoms to include in the topology chains : mb.Compound or list of mb.Compound Chain types to a...
python
{ "resource": "" }
q33383
Compound.from_parmed
train
def from_parmed(self, structure, coords_only=False): """Extract atoms and bonds from a pmd.Structure. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- structure : pmd.Structure ...
python
{ "resource": "" }
q33384
Compound.to_networkx
train
def to_networkx(self, names_only=False): """Create a NetworkX graph representing the hierarchy of a Compound. Parameters ---------- names_only : bool, optional, default=False Store only the names of the compounds in the graph. When set to False, the default behavior, ...
python
{ "resource": "" }
q33385
Compound.to_intermol
train
def to_intermol(self, molecule_types=None): """Create an InterMol system from a Compound. Parameters ---------- molecule_types : list or tuple of subclasses of Compound Returns ------- intermol_system : intermol.system.System """ from intermol.a...
python
{ "resource": "" }
q33386
Compound._add_intermol_molecule_type
train
def _add_intermol_molecule_type(intermol_system, parent): """Create a molecule type for the parent and add bonds. """ from intermol.moleculetype import MoleculeType from intermol.forces.bond import Bond as InterMolBond molecule_type = MoleculeType(name=parent.name) intermol_syst...
python
{ "resource": "" }
q33387
assert_port_exists
train
def assert_port_exists(port_name, compound): """Ensure that a Port label exists in a Compound. """ if port_name in compound.labels: return True else: from mbuild.port import Port available_ports = [name for name in compound.labels if isinstance(compound.la...
python
{ "resource": "" }
q33388
SilicaInterface._cleave_interface
train
def _cleave_interface(self, bulk_silica, tile_x, tile_y, thickness): """Carve interface from bulk silica. Also includes a buffer of O's above and below the surface to ensure the interface is coated. """ O_buffer = self._O_buffer tile_z = int(math.ceil((thickness + 2*O_bu...
python
{ "resource": "" }
q33389
SilicaInterface._strip_stray_atoms
train
def _strip_stray_atoms(self): """Remove stray atoms and surface pieces. """ components = self.bond_graph.connected_components() major_component = max(components, key=len) for atom in list(self.particles()): if atom not in major_component: self.remove(atom)
python
{ "resource": "" }
q33390
SilicaInterface._bridge_dangling_Os
train
def _bridge_dangling_Os(self, oh_density, thickness): """Form Si-O-Si bridges to yield desired density of reactive surface sites. References ---------- .. [1] Hartkamp, R., Siboulet, B., Dufreche, J.-F., Boasne, B. "Ion-specific adsorption and electroosmosis in charged ...
python
{ "resource": "" }
q33391
SilicaInterface._identify_surface_sites
train
def _identify_surface_sites(self, thickness): """Label surface sites and add ports above them. """ for atom in self.particles(): if len(self.bond_graph.neighbors(atom)) == 1: if atom.name == 'O' and atom.pos[2] > thickness: atom.name = 'OS' ...
python
{ "resource": "" }
q33392
fill_region
train
def fill_region(compound, n_compounds, region, overlap=0.2, seed=12345, edge=0.2, fix_orientation=False, temp_file=None): """Fill a region of a box with a compound using packmol. Parameters ---------- compound : mb.Compound or list of mb.Compound Compound or list of compounds to...
python
{ "resource": "" }
q33393
solvate
train
def solvate(solute, solvent, n_solvent, box, overlap=0.2, seed=12345, edge=0.2, fix_orientation=False, temp_file=None): """Solvate a compound in a box of solvent using packmol. Parameters ---------- solute : mb.Compound Compound to be placed in a box and solvated. solvent : mb.C...
python
{ "resource": "" }
q33394
_create_topology
train
def _create_topology(container, comp_to_add, n_compounds): """Return updated mBuild compound with new coordinates. Parameters ---------- container : mb.Compound, required Compound containing the updated system generated by PACKMOL. comp_to_add : mb.Compound or list of mb.Compounds, required...
python
{ "resource": "" }
q33395
_write_pair_information
train
def _write_pair_information(gsd_file, structure): """Write the special pairs in the system. Parameters ---------- gsd_file : The file object of the GSD file being written structure : parmed.Structure Parmed structure object holding system information """ pair_types = [] ...
python
{ "resource": "" }
q33396
_write_dihedral_information
train
def _write_dihedral_information(gsd_file, structure): """Write the dihedrals in the system. Parameters ---------- gsd_file : The file object of the GSD file being written structure : parmed.Structure Parmed structure object holding system information """ gsd_file.dihedrals...
python
{ "resource": "" }
q33397
import_
train
def import_(module): """Import a module, and issue a nice message to stderr if the module isn't installed. Parameters ---------- module : str The module you'd like to import, as a string Returns ------- module : {module, object} The module object Examples -------- ...
python
{ "resource": "" }
q33398
get_fn
train
def get_fn(name): """Get the full path to one of the reference files shipped for utils. In the source distribution, these files are in ``mbuild/utils/reference``, but on installation, they're moved to somewhere in the user's python site-packages directory. Parameters ---------- name : str ...
python
{ "resource": "" }
q33399
angle
train
def angle(u, v, w=None): """Returns the angle in radians between two vectors. """ if w is not None: u = u - v v = w - v c = np.dot(u, v) / norm(u) / norm(v) return np.arccos(np.clip(c, -1, 1))
python
{ "resource": "" }