id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
229,600
mosdef-hub/mbuild
mbuild/compound.py
Compound.translate
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
def translate(self, by): new_positions = _translate(self.xyz_with_ports, by) self.xyz_with_ports = new_positions
[ "def", "translate", "(", "self", ",", "by", ")", ":", "new_positions", "=", "_translate", "(", "self", ".", "xyz_with_ports", ",", "by", ")", "self", ".", "xyz_with_ports", "=", "new_positions" ]
Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float
[ "Translate", "the", "Compound", "by", "a", "vector" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1771-L1780
229,601
mosdef-hub/mbuild
mbuild/compound.py
Compound.rotate
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 Compound. """ new_positions = _rotate(self.xyz_with_ports, theta, around) self.xyz_with_ports = new_positions
python
def rotate(self, theta, around): new_positions = _rotate(self.xyz_with_ports, theta, around) self.xyz_with_ports = new_positions
[ "def", "rotate", "(", "self", ",", "theta", ",", "around", ")", ":", "new_positions", "=", "_rotate", "(", "self", ".", "xyz_with_ports", ",", "theta", ",", "around", ")", "self", ".", "xyz_with_ports", "=", "new_positions" ]
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 Compound.
[ "Rotate", "Compound", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1792-L1804
229,602
mosdef-hub/mbuild
mbuild/compound.py
Compound.spin
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 Compound. """ around = np.asarray(around).reshape(3) center_pos = self.center self.translate(-center_pos) self.rotate(theta, around) self.translate(center_pos)
python
def spin(self, theta, around): around = np.asarray(around).reshape(3) center_pos = self.center self.translate(-center_pos) self.rotate(theta, around) self.translate(center_pos)
[ "def", "spin", "(", "self", ",", "theta", ",", "around", ")", ":", "around", "=", "np", ".", "asarray", "(", "around", ")", ".", "reshape", "(", "3", ")", "center_pos", "=", "self", ".", "center", "self", ".", "translate", "(", "-", "center_pos", "...
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 Compound.
[ "Rotate", "Compound", "in", "place", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1806-L1821
229,603
mosdef-hub/mbuild
mbuild/compound.py
Compound.from_trajectory
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 The trajectory to load. frame : int, optional, default=-1 (last) The frame to take coordinates from. coords_only : bool, optional, default=False Only read coordinate information """ if coords_only: if traj.n_atoms != self.n_particles: raise ValueError('Number of atoms in {traj} does not match' ' {self}'.format(**locals())) atoms_particles = zip(traj.topology.atoms, self.particles(include_ports=False)) if None in self._particles(include_ports=False): raise ValueError('Some particles are None') for mdtraj_atom, particle in atoms_particles: particle.pos = traj.xyz[frame, mdtraj_atom.index] return atom_mapping = dict() for chain in traj.topology.chains: if traj.topology.n_chains > 1: chain_compound = Compound() self.add(chain_compound, 'chain[$]') else: chain_compound = self for res in chain.residues: for atom in res.atoms: new_atom = Particle(name=str(atom.name), pos=traj.xyz[frame, atom.index]) chain_compound.add( new_atom, label='{0}[$]'.format( atom.name)) atom_mapping[atom] = new_atom for mdtraj_atom1, mdtraj_atom2 in traj.topology.bonds: atom1 = atom_mapping[mdtraj_atom1] atom2 = atom_mapping[mdtraj_atom2] self.add_bond((atom1, atom2)) if np.any(traj.unitcell_lengths) and np.any(traj.unitcell_lengths[0]): self.periodicity = traj.unitcell_lengths[0] else: self.periodicity = np.array([0., 0., 0.])
python
def from_trajectory(self, traj, frame=-1, coords_only=False): if coords_only: if traj.n_atoms != self.n_particles: raise ValueError('Number of atoms in {traj} does not match' ' {self}'.format(**locals())) atoms_particles = zip(traj.topology.atoms, self.particles(include_ports=False)) if None in self._particles(include_ports=False): raise ValueError('Some particles are None') for mdtraj_atom, particle in atoms_particles: particle.pos = traj.xyz[frame, mdtraj_atom.index] return atom_mapping = dict() for chain in traj.topology.chains: if traj.topology.n_chains > 1: chain_compound = Compound() self.add(chain_compound, 'chain[$]') else: chain_compound = self for res in chain.residues: for atom in res.atoms: new_atom = Particle(name=str(atom.name), pos=traj.xyz[frame, atom.index]) chain_compound.add( new_atom, label='{0}[$]'.format( atom.name)) atom_mapping[atom] = new_atom for mdtraj_atom1, mdtraj_atom2 in traj.topology.bonds: atom1 = atom_mapping[mdtraj_atom1] atom2 = atom_mapping[mdtraj_atom2] self.add_bond((atom1, atom2)) if np.any(traj.unitcell_lengths) and np.any(traj.unitcell_lengths[0]): self.periodicity = traj.unitcell_lengths[0] else: self.periodicity = np.array([0., 0., 0.])
[ "def", "from_trajectory", "(", "self", ",", "traj", ",", "frame", "=", "-", "1", ",", "coords_only", "=", "False", ")", ":", "if", "coords_only", ":", "if", "traj", ".", "n_atoms", "!=", "self", ".", "n_particles", ":", "raise", "ValueError", "(", "'Nu...
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 The trajectory to load. frame : int, optional, default=-1 (last) The frame to take coordinates from. coords_only : bool, optional, default=False Only read coordinate information
[ "Extract", "atoms", "and", "bonds", "from", "a", "md", ".", "Trajectory", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1825-L1877
229,604
mosdef-hub/mbuild
mbuild/compound.py
Compound.to_trajectory
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 trajectory. chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be used when converting to a `Trajectory`. If 'None', a bounding box is used with a 0.5nm buffer in each dimension. to avoid overlapping atoms, unless `self.periodicity` is not None, in which case those values are used for the box lengths. Returns ------- trajectory : md.Trajectory See also -------- _to_topology """ atom_list = [particle for particle in self.particles(show_ports)] top = self._to_topology(atom_list, chains, residues) # Coordinates. xyz = np.ndarray(shape=(1, top.n_atoms, 3), dtype='float') for idx, atom in enumerate(atom_list): xyz[0, idx] = atom.pos # Unitcell information. unitcell_angles = [90.0, 90.0, 90.0] if box is None: unitcell_lengths = np.empty(3) for dim, val in enumerate(self.periodicity): if val: unitcell_lengths[dim] = val else: unitcell_lengths[dim] = self.boundingbox.lengths[dim] + 0.5 else: unitcell_lengths = box.lengths unitcell_angles = box.angles return md.Trajectory(xyz, top, unitcell_lengths=unitcell_lengths, unitcell_angles=unitcell_angles)
python
def to_trajectory(self, show_ports=False, chains=None, residues=None, box=None): atom_list = [particle for particle in self.particles(show_ports)] top = self._to_topology(atom_list, chains, residues) # Coordinates. xyz = np.ndarray(shape=(1, top.n_atoms, 3), dtype='float') for idx, atom in enumerate(atom_list): xyz[0, idx] = atom.pos # Unitcell information. unitcell_angles = [90.0, 90.0, 90.0] if box is None: unitcell_lengths = np.empty(3) for dim, val in enumerate(self.periodicity): if val: unitcell_lengths[dim] = val else: unitcell_lengths[dim] = self.boundingbox.lengths[dim] + 0.5 else: unitcell_lengths = box.lengths unitcell_angles = box.angles return md.Trajectory(xyz, top, unitcell_lengths=unitcell_lengths, unitcell_angles=unitcell_angles)
[ "def", "to_trajectory", "(", "self", ",", "show_ports", "=", "False", ",", "chains", "=", "None", ",", "residues", "=", "None", ",", "box", "=", "None", ")", ":", "atom_list", "=", "[", "particle", "for", "particle", "in", "self", ".", "particles", "("...
Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajectory. chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be used when converting to a `Trajectory`. If 'None', a bounding box is used with a 0.5nm buffer in each dimension. to avoid overlapping atoms, unless `self.periodicity` is not None, in which case those values are used for the box lengths. Returns ------- trajectory : md.Trajectory See also -------- _to_topology
[ "Convert", "to", "an", "md", ".", "Trajectory", "and", "flatten", "the", "compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1879-L1931
229,605
mosdef-hub/mbuild
mbuild/compound.py
Compound._to_topology
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 add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. Returns ------- top : mdtraj.Topology See Also -------- mdtraj.Topology : Details on the mdtraj Topology object """ from mdtraj.core.topology import Topology if isinstance(chains, string_types): chains = [chains] if isinstance(chains, (list, set)): chains = tuple(chains) if isinstance(residues, string_types): residues = [residues] if isinstance(residues, (list, set)): residues = tuple(residues) top = Topology() atom_mapping = {} default_chain = top.add_chain() default_residue = top.add_residue('RES', default_chain) compound_residue_map = dict() atom_residue_map = dict() compound_chain_map = dict() atom_chain_map = dict() for atom in atom_list: # Chains if chains: if atom.name in chains: current_chain = top.add_chain() compound_chain_map[atom] = current_chain else: for parent in atom.ancestors(): if chains and parent.name in chains: if parent not in compound_chain_map: current_chain = top.add_chain() compound_chain_map[parent] = current_chain current_residue = top.add_residue( 'RES', current_chain) break else: current_chain = default_chain else: current_chain = default_chain atom_chain_map[atom] = current_chain # Residues if residues: if atom.name in residues: current_residue = top.add_residue(atom.name, current_chain) compound_residue_map[atom] = current_residue else: for parent in atom.ancestors(): if residues and parent.name in residues: if parent not in compound_residue_map: current_residue = top.add_residue( parent.name, current_chain) compound_residue_map[parent] = current_residue break else: current_residue = default_residue else: if chains: try: # Grab the default residue from the custom chain. current_residue = next(current_chain.residues) except StopIteration: # Add the residue to the current chain current_residue = top.add_residue('RES', current_chain) else: # Grab the default chain's default residue current_residue = default_residue atom_residue_map[atom] = current_residue # Add the actual atoms try: elem = get_by_symbol(atom.name) except KeyError: elem = get_by_symbol("VS") at = top.add_atom(atom.name, elem, atom_residue_map[atom]) at.charge = atom.charge atom_mapping[atom] = at # Remove empty default residues. chains_to_remove = [ chain for chain in top.chains if chain.n_atoms == 0] residues_to_remove = [res for res in top.residues if res.n_atoms == 0] for chain in chains_to_remove: top._chains.remove(chain) for res in residues_to_remove: for chain in top.chains: try: chain._residues.remove(res) except ValueError: # Already gone. pass for atom1, atom2 in self.bonds(): # Ensure that both atoms are part of the compound. This becomes an # issue if you try to convert a sub-compound to a topology which is # bonded to a different subcompound. if all(a in atom_mapping.keys() for a in [atom1, atom2]): top.add_bond(atom_mapping[atom1], atom_mapping[atom2]) return top
python
def _to_topology(self, atom_list, chains=None, residues=None): from mdtraj.core.topology import Topology if isinstance(chains, string_types): chains = [chains] if isinstance(chains, (list, set)): chains = tuple(chains) if isinstance(residues, string_types): residues = [residues] if isinstance(residues, (list, set)): residues = tuple(residues) top = Topology() atom_mapping = {} default_chain = top.add_chain() default_residue = top.add_residue('RES', default_chain) compound_residue_map = dict() atom_residue_map = dict() compound_chain_map = dict() atom_chain_map = dict() for atom in atom_list: # Chains if chains: if atom.name in chains: current_chain = top.add_chain() compound_chain_map[atom] = current_chain else: for parent in atom.ancestors(): if chains and parent.name in chains: if parent not in compound_chain_map: current_chain = top.add_chain() compound_chain_map[parent] = current_chain current_residue = top.add_residue( 'RES', current_chain) break else: current_chain = default_chain else: current_chain = default_chain atom_chain_map[atom] = current_chain # Residues if residues: if atom.name in residues: current_residue = top.add_residue(atom.name, current_chain) compound_residue_map[atom] = current_residue else: for parent in atom.ancestors(): if residues and parent.name in residues: if parent not in compound_residue_map: current_residue = top.add_residue( parent.name, current_chain) compound_residue_map[parent] = current_residue break else: current_residue = default_residue else: if chains: try: # Grab the default residue from the custom chain. current_residue = next(current_chain.residues) except StopIteration: # Add the residue to the current chain current_residue = top.add_residue('RES', current_chain) else: # Grab the default chain's default residue current_residue = default_residue atom_residue_map[atom] = current_residue # Add the actual atoms try: elem = get_by_symbol(atom.name) except KeyError: elem = get_by_symbol("VS") at = top.add_atom(atom.name, elem, atom_residue_map[atom]) at.charge = atom.charge atom_mapping[atom] = at # Remove empty default residues. chains_to_remove = [ chain for chain in top.chains if chain.n_atoms == 0] residues_to_remove = [res for res in top.residues if res.n_atoms == 0] for chain in chains_to_remove: top._chains.remove(chain) for res in residues_to_remove: for chain in top.chains: try: chain._residues.remove(res) except ValueError: # Already gone. pass for atom1, atom2 in self.bonds(): # Ensure that both atoms are part of the compound. This becomes an # issue if you try to convert a sub-compound to a topology which is # bonded to a different subcompound. if all(a in atom_mapping.keys() for a in [atom1, atom2]): top.add_bond(atom_mapping[atom1], atom_mapping[atom2]) return top
[ "def", "_to_topology", "(", "self", ",", "atom_list", ",", "chains", "=", "None", ",", "residues", "=", "None", ")", ":", "from", "mdtraj", ".", "core", ".", "topology", "import", "Topology", "if", "isinstance", "(", "chains", ",", "string_types", ")", "...
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 add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. Returns ------- top : mdtraj.Topology See Also -------- mdtraj.Topology : Details on the mdtraj Topology object
[ "Create", "a", "mdtraj", ".", "Topology", "from", "a", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1933-L2051
229,606
mosdef-hub/mbuild
mbuild/compound.py
Compound.from_parmed
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 The structure to load. coords_only : bool Set preexisting atoms in compound to coordinates given by structure. """ if coords_only: if len(structure.atoms) != self.n_particles: raise ValueError( 'Number of atoms in {structure} does not match' ' {self}'.format( **locals())) atoms_particles = zip(structure.atoms, self.particles(include_ports=False)) if None in self._particles(include_ports=False): raise ValueError('Some particles are None') for parmed_atom, particle in atoms_particles: particle.pos = np.array([parmed_atom.xx, parmed_atom.xy, parmed_atom.xz]) / 10 return atom_mapping = dict() chain_id = None chains = defaultdict(list) for residue in structure.residues: chains[residue.chain].append(residue) for chain, residues in chains.items(): if len(chains) > 1: chain_compound = Compound() self.add(chain_compound, chain_id) else: chain_compound = self for residue in residues: for atom in residue.atoms: pos = np.array([atom.xx, atom.xy, atom.xz]) / 10 new_atom = Particle(name=str(atom.name), pos=pos) chain_compound.add( new_atom, label='{0}[$]'.format( atom.name)) atom_mapping[atom] = new_atom for bond in structure.bonds: atom1 = atom_mapping[bond.atom1] atom2 = atom_mapping[bond.atom2] self.add_bond((atom1, atom2)) if structure.box is not None: # Convert from A to nm self.periodicity = 0.1 * structure.box[0:3] else: self.periodicity = np.array([0., 0., 0.])
python
def from_parmed(self, structure, coords_only=False): if coords_only: if len(structure.atoms) != self.n_particles: raise ValueError( 'Number of atoms in {structure} does not match' ' {self}'.format( **locals())) atoms_particles = zip(structure.atoms, self.particles(include_ports=False)) if None in self._particles(include_ports=False): raise ValueError('Some particles are None') for parmed_atom, particle in atoms_particles: particle.pos = np.array([parmed_atom.xx, parmed_atom.xy, parmed_atom.xz]) / 10 return atom_mapping = dict() chain_id = None chains = defaultdict(list) for residue in structure.residues: chains[residue.chain].append(residue) for chain, residues in chains.items(): if len(chains) > 1: chain_compound = Compound() self.add(chain_compound, chain_id) else: chain_compound = self for residue in residues: for atom in residue.atoms: pos = np.array([atom.xx, atom.xy, atom.xz]) / 10 new_atom = Particle(name=str(atom.name), pos=pos) chain_compound.add( new_atom, label='{0}[$]'.format( atom.name)) atom_mapping[atom] = new_atom for bond in structure.bonds: atom1 = atom_mapping[bond.atom1] atom2 = atom_mapping[bond.atom2] self.add_bond((atom1, atom2)) if structure.box is not None: # Convert from A to nm self.periodicity = 0.1 * structure.box[0:3] else: self.periodicity = np.array([0., 0., 0.])
[ "def", "from_parmed", "(", "self", ",", "structure", ",", "coords_only", "=", "False", ")", ":", "if", "coords_only", ":", "if", "len", "(", "structure", ".", "atoms", ")", "!=", "self", ".", "n_particles", ":", "raise", "ValueError", "(", "'Number of atom...
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 The structure to load. coords_only : bool Set preexisting atoms in compound to coordinates given by structure.
[ "Extract", "atoms", "and", "bonds", "from", "a", "pmd", ".", "Structure", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L2053-L2113
229,607
mosdef-hub/mbuild
mbuild/compound.py
Compound.to_networkx
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, the nodes are the compounds themselves. Returns ------- G : networkx.DiGraph """ nx = import_('networkx') nodes = list() edges = list() if names_only: nodes.append(self.name) else: nodes.append(self) nodes, edges = self._iterate_children(nodes, edges, names_only=names_only) graph = nx.DiGraph() graph.add_nodes_from(nodes) graph.add_edges_from(edges) return graph
python
def to_networkx(self, names_only=False): nx = import_('networkx') nodes = list() edges = list() if names_only: nodes.append(self.name) else: nodes.append(self) nodes, edges = self._iterate_children(nodes, edges, names_only=names_only) graph = nx.DiGraph() graph.add_nodes_from(nodes) graph.add_edges_from(edges) return graph
[ "def", "to_networkx", "(", "self", ",", "names_only", "=", "False", ")", ":", "nx", "=", "import_", "(", "'networkx'", ")", "nodes", "=", "list", "(", ")", "edges", "=", "list", "(", ")", "if", "names_only", ":", "nodes", ".", "append", "(", "self", ...
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, the nodes are the compounds themselves. Returns ------- G : networkx.DiGraph
[ "Create", "a", "NetworkX", "graph", "representing", "the", "hierarchy", "of", "a", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L2250-L2276
229,608
mosdef-hub/mbuild
mbuild/compound.py
Compound.to_intermol
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.atom import Atom as InterMolAtom from intermol.molecule import Molecule from intermol.system import System import simtk.unit as u if isinstance(molecule_types, list): molecule_types = tuple(molecule_types) elif molecule_types is None: molecule_types = (type(self),) intermol_system = System() last_molecule_compound = None for atom_index, atom in enumerate(self.particles()): for parent in atom.ancestors(): # Don't want inheritance via isinstance(). if type(parent) in molecule_types: # Check if we have encountered this molecule type before. if parent.name not in intermol_system.molecule_types: self._add_intermol_molecule_type( intermol_system, parent) if parent != last_molecule_compound: last_molecule_compound = parent last_molecule = Molecule(name=parent.name) intermol_system.add_molecule(last_molecule) break else: # Should never happen if molecule_types only contains # type(self) raise ValueError( 'Found an atom {} that is not part of any of ' 'the specified molecule types {}'.format( atom, molecule_types)) # Add the actual intermol atoms. intermol_atom = InterMolAtom(atom_index + 1, name=atom.name, residue_index=1, residue_name='RES') intermol_atom.position = atom.pos * u.nanometers last_molecule.add_atom(intermol_atom) return intermol_system
python
def to_intermol(self, molecule_types=None): from intermol.atom import Atom as InterMolAtom from intermol.molecule import Molecule from intermol.system import System import simtk.unit as u if isinstance(molecule_types, list): molecule_types = tuple(molecule_types) elif molecule_types is None: molecule_types = (type(self),) intermol_system = System() last_molecule_compound = None for atom_index, atom in enumerate(self.particles()): for parent in atom.ancestors(): # Don't want inheritance via isinstance(). if type(parent) in molecule_types: # Check if we have encountered this molecule type before. if parent.name not in intermol_system.molecule_types: self._add_intermol_molecule_type( intermol_system, parent) if parent != last_molecule_compound: last_molecule_compound = parent last_molecule = Molecule(name=parent.name) intermol_system.add_molecule(last_molecule) break else: # Should never happen if molecule_types only contains # type(self) raise ValueError( 'Found an atom {} that is not part of any of ' 'the specified molecule types {}'.format( atom, molecule_types)) # Add the actual intermol atoms. intermol_atom = InterMolAtom(atom_index + 1, name=atom.name, residue_index=1, residue_name='RES') intermol_atom.position = atom.pos * u.nanometers last_molecule.add_atom(intermol_atom) return intermol_system
[ "def", "to_intermol", "(", "self", ",", "molecule_types", "=", "None", ")", ":", "from", "intermol", ".", "atom", "import", "Atom", "as", "InterMolAtom", "from", "intermol", ".", "molecule", "import", "Molecule", "from", "intermol", ".", "system", "import", ...
Create an InterMol system from a Compound. Parameters ---------- molecule_types : list or tuple of subclasses of Compound Returns ------- intermol_system : intermol.system.System
[ "Create", "an", "InterMol", "system", "from", "a", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L2291-L2341
229,609
mosdef-hub/mbuild
mbuild/compound.py
Compound._add_intermol_molecule_type
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_system.add_molecule_type(molecule_type) for index, parent_atom in enumerate(parent.particles()): parent_atom.index = index + 1 for atom1, atom2 in parent.bonds(): intermol_bond = InterMolBond(atom1.index, atom2.index) molecule_type.bonds.add(intermol_bond)
python
def _add_intermol_molecule_type(intermol_system, parent): from intermol.moleculetype import MoleculeType from intermol.forces.bond import Bond as InterMolBond molecule_type = MoleculeType(name=parent.name) intermol_system.add_molecule_type(molecule_type) for index, parent_atom in enumerate(parent.particles()): parent_atom.index = index + 1 for atom1, atom2 in parent.bonds(): intermol_bond = InterMolBond(atom1.index, atom2.index) molecule_type.bonds.add(intermol_bond)
[ "def", "_add_intermol_molecule_type", "(", "intermol_system", ",", "parent", ")", ":", "from", "intermol", ".", "moleculetype", "import", "MoleculeType", "from", "intermol", ".", "forces", ".", "bond", "import", "Bond", "as", "InterMolBond", "molecule_type", "=", ...
Create a molecule type for the parent and add bonds.
[ "Create", "a", "molecule", "type", "for", "the", "parent", "and", "add", "bonds", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L2344-L2357
229,610
mosdef-hub/mbuild
mbuild/utils/validation.py
assert_port_exists
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.labels[name], Port)] compound_name = compound.__class__.__name__ raise ValueError("No port named '{port_name}' in {compound_name}'s" " labels. Labeled Ports in {compound_name} are:" " {available_ports}".format(**locals()))
python
def assert_port_exists(port_name, 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.labels[name], Port)] compound_name = compound.__class__.__name__ raise ValueError("No port named '{port_name}' in {compound_name}'s" " labels. Labeled Ports in {compound_name} are:" " {available_ports}".format(**locals()))
[ "def", "assert_port_exists", "(", "port_name", ",", "compound", ")", ":", "if", "port_name", "in", "compound", ".", "labels", ":", "return", "True", "else", ":", "from", "mbuild", ".", "port", "import", "Port", "available_ports", "=", "[", "name", "for", "...
Ensure that a Port label exists in a Compound.
[ "Ensure", "that", "a", "Port", "label", "exists", "in", "a", "Compound", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/validation.py#L1-L12
229,611
mosdef-hub/mbuild
mbuild/lib/recipes/silica_interface.py
SilicaInterface._cleave_interface
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_buffer) / bulk_silica.periodicity[2])) bulk = mb.recipes.TiledCompound(bulk_silica, n_tiles=(tile_x, tile_y, tile_z)) interface = mb.Compound(periodicity=(bulk.periodicity[0], bulk.periodicity[1], 0.0)) for i, particle in enumerate(bulk.particles()): if ((particle.name == 'Si' and O_buffer < particle.pos[2] < (thickness + O_buffer)) or (particle.name == 'O' and particle.pos[2] < (thickness + 2*O_buffer))): interface_particle = mb.Compound(name=particle.name, pos=particle.pos) interface.add(interface_particle, particle.name + "_{}".format(i)) self.add(interface)
python
def _cleave_interface(self, bulk_silica, tile_x, tile_y, thickness): O_buffer = self._O_buffer tile_z = int(math.ceil((thickness + 2*O_buffer) / bulk_silica.periodicity[2])) bulk = mb.recipes.TiledCompound(bulk_silica, n_tiles=(tile_x, tile_y, tile_z)) interface = mb.Compound(periodicity=(bulk.periodicity[0], bulk.periodicity[1], 0.0)) for i, particle in enumerate(bulk.particles()): if ((particle.name == 'Si' and O_buffer < particle.pos[2] < (thickness + O_buffer)) or (particle.name == 'O' and particle.pos[2] < (thickness + 2*O_buffer))): interface_particle = mb.Compound(name=particle.name, pos=particle.pos) interface.add(interface_particle, particle.name + "_{}".format(i)) self.add(interface)
[ "def", "_cleave_interface", "(", "self", ",", "bulk_silica", ",", "tile_x", ",", "tile_y", ",", "thickness", ")", ":", "O_buffer", "=", "self", ".", "_O_buffer", "tile_z", "=", "int", "(", "math", ".", "ceil", "(", "(", "thickness", "+", "2", "*", "O_b...
Carve interface from bulk silica. Also includes a buffer of O's above and below the surface to ensure the interface is coated.
[ "Carve", "interface", "from", "bulk", "silica", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/silica_interface.py#L56-L74
229,612
mosdef-hub/mbuild
mbuild/lib/recipes/silica_interface.py
SilicaInterface._strip_stray_atoms
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
def _strip_stray_atoms(self): 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)
[ "def", "_strip_stray_atoms", "(", "self", ")", ":", "components", "=", "self", ".", "bond_graph", ".", "connected_components", "(", ")", "major_component", "=", "max", "(", "components", ",", "key", "=", "len", ")", "for", "atom", "in", "list", "(", "self"...
Remove stray atoms and surface pieces.
[ "Remove", "stray", "atoms", "and", "surface", "pieces", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/silica_interface.py#L76-L82
229,613
mosdef-hub/mbuild
mbuild/lib/recipes/silica_interface.py
SilicaInterface._bridge_dangling_Os
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 amorphous porous silica." (2015) Phys. Chem. Chem. Phys. 17, 24683-24695 """ area = self.periodicity[0] * self.periodicity[1] target = int(oh_density * area) dangling_Os = [atom for atom in self.particles() if atom.name == 'O' and atom.pos[2] > thickness and len(self.bond_graph.neighbors(atom)) == 1] n_bridges = int((len(dangling_Os) - target) / 2) for _ in range(n_bridges): bridged = False while not bridged: O1 = random.choice(dangling_Os) Si1 = self.bond_graph.neighbors(O1)[0] for O2 in dangling_Os: if O2 == O1: continue Si2 = self.bond_graph.neighbors(O2)[0] if Si1 == Si2: continue if any(neigh in self.bond_graph.neighbors(Si2) for neigh in self.bond_graph.neighbors(Si1)): continue r = self.min_periodic_distance(Si1.pos, Si2.pos) if r < 0.45: bridged = True self.add_bond((O1, Si2)) dangling_Os.remove(O1) dangling_Os.remove(O2) self.remove(O2) break
python
def _bridge_dangling_Os(self, oh_density, thickness): area = self.periodicity[0] * self.periodicity[1] target = int(oh_density * area) dangling_Os = [atom for atom in self.particles() if atom.name == 'O' and atom.pos[2] > thickness and len(self.bond_graph.neighbors(atom)) == 1] n_bridges = int((len(dangling_Os) - target) / 2) for _ in range(n_bridges): bridged = False while not bridged: O1 = random.choice(dangling_Os) Si1 = self.bond_graph.neighbors(O1)[0] for O2 in dangling_Os: if O2 == O1: continue Si2 = self.bond_graph.neighbors(O2)[0] if Si1 == Si2: continue if any(neigh in self.bond_graph.neighbors(Si2) for neigh in self.bond_graph.neighbors(Si1)): continue r = self.min_periodic_distance(Si1.pos, Si2.pos) if r < 0.45: bridged = True self.add_bond((O1, Si2)) dangling_Os.remove(O1) dangling_Os.remove(O2) self.remove(O2) break
[ "def", "_bridge_dangling_Os", "(", "self", ",", "oh_density", ",", "thickness", ")", ":", "area", "=", "self", ".", "periodicity", "[", "0", "]", "*", "self", ".", "periodicity", "[", "1", "]", "target", "=", "int", "(", "oh_density", "*", "area", ")",...
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 amorphous porous silica." (2015) Phys. Chem. Chem. Phys. 17, 24683-24695
[ "Form", "Si", "-", "O", "-", "Si", "bridges", "to", "yield", "desired", "density", "of", "reactive", "surface", "sites", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/silica_interface.py#L84-L126
229,614
mosdef-hub/mbuild
mbuild/lib/recipes/silica_interface.py
SilicaInterface._identify_surface_sites
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' port = mb.Port(anchor=atom) port.spin(np.pi/2, [1, 0, 0]) port.translate(np.array([0.0, 0.0, 0.1])) self.add(port, "port_{}".format(len(self.referenced_ports())))
python
def _identify_surface_sites(self, thickness): 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' port = mb.Port(anchor=atom) port.spin(np.pi/2, [1, 0, 0]) port.translate(np.array([0.0, 0.0, 0.1])) self.add(port, "port_{}".format(len(self.referenced_ports())))
[ "def", "_identify_surface_sites", "(", "self", ",", "thickness", ")", ":", "for", "atom", "in", "self", ".", "particles", "(", ")", ":", "if", "len", "(", "self", ".", "bond_graph", ".", "neighbors", "(", "atom", ")", ")", "==", "1", ":", "if", "atom...
Label surface sites and add ports above them.
[ "Label", "surface", "sites", "and", "add", "ports", "above", "them", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/silica_interface.py#L128-L137
229,615
mosdef-hub/mbuild
mbuild/packing.py
fill_region
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 be put in region. n_compounds : int or list of int Number of compounds to be put in region. region : mb.Box or list of mb.Box Region to be filled by compounds. overlap : float, units nm, default=0.2 Minimum separation between atoms of different molecules. seed : int, default=12345 Random seed to be passed to PACKMOL. edge : float, units nm, default=0.2 Buffer at the edge of the region to not place molecules. This is necessary in some systems because PACKMOL does not account for periodic boundary conditions in its optimization. fix_orientation : bool or list of bools Specify that compounds should not be rotated when filling the box, default=False. temp_file : str, default=None File name to write PACKMOL's raw output to. Returns ------- filled : mb.Compound If using mulitple regions and compounds, the nth value in each list are used in order. For example, if the third compound will be put in the third region using the third value in n_compounds. """ _check_packmol(PACKMOL) if not isinstance(compound, (list, set)): compound = [compound] if not isinstance(n_compounds, (list, set)): n_compounds = [n_compounds] if not isinstance(fix_orientation, (list, set)): fix_orientation = [fix_orientation]*len(compound) if compound is not None and n_compounds is not None: if len(compound) != len(n_compounds): msg = ("`compound` and `n_compounds` must be of equal length.") raise ValueError(msg) if compound is not None: if len(compound) != len(fix_orientation): msg = ("`compound`, `n_compounds`, and `fix_orientation` must be of equal length.") raise ValueError(msg) # See if region is a single region or list if isinstance(region, Box): # Cannot iterate over boxes region = [region] elif not any(isinstance(reg, (list, set, Box)) for reg in region): region = [region] region = [_validate_box(reg) for reg in region] # In angstroms for packmol. overlap *= 10 # Build the input file and call packmol. filled_xyz = _new_xyz_file() # List to hold file handles for the temporary compounds compound_xyz_list = list() try: input_text = PACKMOL_HEADER.format(overlap, filled_xyz.name, seed) for comp, m_compounds, reg, rotate in zip(compound, n_compounds, region, fix_orientation): m_compounds = int(m_compounds) compound_xyz = _new_xyz_file() compound_xyz_list.append(compound_xyz) comp.save(compound_xyz.name, overwrite=True) reg_mins = reg.mins * 10 reg_maxs = reg.maxs * 10 reg_maxs -= edge * 10 # Apply edge buffer input_text += PACKMOL_BOX.format(compound_xyz.name, m_compounds, reg_mins[0], reg_mins[1], reg_mins[2], reg_maxs[0], reg_maxs[1], reg_maxs[2], PACKMOL_CONSTRAIN if rotate else "") _run_packmol(input_text, filled_xyz, temp_file) # Create the topology and update the coordinates. filled = Compound() filled = _create_topology(filled, compound, n_compounds) filled.update_coordinates(filled_xyz.name) finally: for file_handle in compound_xyz_list: file_handle.close() os.unlink(file_handle.name) filled_xyz.close() os.unlink(filled_xyz.name) return filled
python
def fill_region(compound, n_compounds, region, overlap=0.2, seed=12345, edge=0.2, fix_orientation=False, temp_file=None): _check_packmol(PACKMOL) if not isinstance(compound, (list, set)): compound = [compound] if not isinstance(n_compounds, (list, set)): n_compounds = [n_compounds] if not isinstance(fix_orientation, (list, set)): fix_orientation = [fix_orientation]*len(compound) if compound is not None and n_compounds is not None: if len(compound) != len(n_compounds): msg = ("`compound` and `n_compounds` must be of equal length.") raise ValueError(msg) if compound is not None: if len(compound) != len(fix_orientation): msg = ("`compound`, `n_compounds`, and `fix_orientation` must be of equal length.") raise ValueError(msg) # See if region is a single region or list if isinstance(region, Box): # Cannot iterate over boxes region = [region] elif not any(isinstance(reg, (list, set, Box)) for reg in region): region = [region] region = [_validate_box(reg) for reg in region] # In angstroms for packmol. overlap *= 10 # Build the input file and call packmol. filled_xyz = _new_xyz_file() # List to hold file handles for the temporary compounds compound_xyz_list = list() try: input_text = PACKMOL_HEADER.format(overlap, filled_xyz.name, seed) for comp, m_compounds, reg, rotate in zip(compound, n_compounds, region, fix_orientation): m_compounds = int(m_compounds) compound_xyz = _new_xyz_file() compound_xyz_list.append(compound_xyz) comp.save(compound_xyz.name, overwrite=True) reg_mins = reg.mins * 10 reg_maxs = reg.maxs * 10 reg_maxs -= edge * 10 # Apply edge buffer input_text += PACKMOL_BOX.format(compound_xyz.name, m_compounds, reg_mins[0], reg_mins[1], reg_mins[2], reg_maxs[0], reg_maxs[1], reg_maxs[2], PACKMOL_CONSTRAIN if rotate else "") _run_packmol(input_text, filled_xyz, temp_file) # Create the topology and update the coordinates. filled = Compound() filled = _create_topology(filled, compound, n_compounds) filled.update_coordinates(filled_xyz.name) finally: for file_handle in compound_xyz_list: file_handle.close() os.unlink(file_handle.name) filled_xyz.close() os.unlink(filled_xyz.name) return filled
[ "def", "fill_region", "(", "compound", ",", "n_compounds", ",", "region", ",", "overlap", "=", "0.2", ",", "seed", "=", "12345", ",", "edge", "=", "0.2", ",", "fix_orientation", "=", "False", ",", "temp_file", "=", "None", ")", ":", "_check_packmol", "("...
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 be put in region. n_compounds : int or list of int Number of compounds to be put in region. region : mb.Box or list of mb.Box Region to be filled by compounds. overlap : float, units nm, default=0.2 Minimum separation between atoms of different molecules. seed : int, default=12345 Random seed to be passed to PACKMOL. edge : float, units nm, default=0.2 Buffer at the edge of the region to not place molecules. This is necessary in some systems because PACKMOL does not account for periodic boundary conditions in its optimization. fix_orientation : bool or list of bools Specify that compounds should not be rotated when filling the box, default=False. temp_file : str, default=None File name to write PACKMOL's raw output to. Returns ------- filled : mb.Compound If using mulitple regions and compounds, the nth value in each list are used in order. For example, if the third compound will be put in the third region using the third value in n_compounds.
[ "Fill", "a", "region", "of", "a", "box", "with", "a", "compound", "using", "packmol", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/packing.py#L220-L319
229,616
mosdef-hub/mbuild
mbuild/packing.py
solvate
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.Compound Compound to solvate the box. n_solvent : int Number of solvents to be put in box. box : mb.Box Box to be filled by compounds. overlap : float, units nm, default=0.2 Minimum separation between atoms of different molecules. seed : int, default=12345 Random seed to be passed to PACKMOL. edge : float, units nm, default=0.2 Buffer at the edge of the box to not place molecules. This is necessary in some systems because PACKMOL does not account for periodic boundary conditions in its optimization. fix_orientation : bool Specify if solvent should not be rotated when filling box, default=False. temp_file : str, default=None File name to write PACKMOL's raw output to. Returns ------- solvated : mb.Compound """ _check_packmol(PACKMOL) box = _validate_box(box) if not isinstance(solvent, (list, set)): solvent = [solvent] if not isinstance(n_solvent, (list, set)): n_solvent = [n_solvent] if not isinstance(fix_orientation, (list, set)): fix_orientation = [fix_orientation] * len(solvent) if len(solvent) != len(n_solvent): msg = ("`n_solvent` and `n_solvent` must be of equal length.") raise ValueError(msg) # In angstroms for packmol. box_mins = box.mins * 10 box_maxs = box.maxs * 10 overlap *= 10 center_solute = (box_maxs + box_mins) / 2 # Apply edge buffer box_maxs -= edge * 10 # Build the input file for each compound and call packmol. solvated_xyz = _new_xyz_file() solute_xyz = _new_xyz_file() # generate list of temp files for the solvents solvent_xyz_list = list() try: solute.save(solute_xyz.name, overwrite=True) input_text = (PACKMOL_HEADER.format(overlap, solvated_xyz.name, seed) + PACKMOL_SOLUTE.format(solute_xyz.name, *center_solute)) for solv, m_solvent, rotate in zip(solvent, n_solvent, fix_orientation): m_solvent = int(m_solvent) solvent_xyz = _new_xyz_file() solvent_xyz_list.append(solvent_xyz) solv.save(solvent_xyz.name, overwrite=True) input_text += PACKMOL_BOX.format(solvent_xyz.name, m_solvent, box_mins[0], box_mins[1], box_mins[2], box_maxs[0], box_maxs[1], box_maxs[2], PACKMOL_CONSTRAIN if rotate else "") _run_packmol(input_text, solvated_xyz, temp_file) # Create the topology and update the coordinates. solvated = Compound() solvated.add(solute) solvated = _create_topology(solvated, solvent, n_solvent) solvated.update_coordinates(solvated_xyz.name) finally: for file_handle in solvent_xyz_list: file_handle.close() os.unlink(file_handle.name) solvated_xyz.close() solute_xyz.close() os.unlink(solvated_xyz.name) os.unlink(solute_xyz.name) return solvated
python
def solvate(solute, solvent, n_solvent, box, overlap=0.2, seed=12345, edge=0.2, fix_orientation=False, temp_file=None): _check_packmol(PACKMOL) box = _validate_box(box) if not isinstance(solvent, (list, set)): solvent = [solvent] if not isinstance(n_solvent, (list, set)): n_solvent = [n_solvent] if not isinstance(fix_orientation, (list, set)): fix_orientation = [fix_orientation] * len(solvent) if len(solvent) != len(n_solvent): msg = ("`n_solvent` and `n_solvent` must be of equal length.") raise ValueError(msg) # In angstroms for packmol. box_mins = box.mins * 10 box_maxs = box.maxs * 10 overlap *= 10 center_solute = (box_maxs + box_mins) / 2 # Apply edge buffer box_maxs -= edge * 10 # Build the input file for each compound and call packmol. solvated_xyz = _new_xyz_file() solute_xyz = _new_xyz_file() # generate list of temp files for the solvents solvent_xyz_list = list() try: solute.save(solute_xyz.name, overwrite=True) input_text = (PACKMOL_HEADER.format(overlap, solvated_xyz.name, seed) + PACKMOL_SOLUTE.format(solute_xyz.name, *center_solute)) for solv, m_solvent, rotate in zip(solvent, n_solvent, fix_orientation): m_solvent = int(m_solvent) solvent_xyz = _new_xyz_file() solvent_xyz_list.append(solvent_xyz) solv.save(solvent_xyz.name, overwrite=True) input_text += PACKMOL_BOX.format(solvent_xyz.name, m_solvent, box_mins[0], box_mins[1], box_mins[2], box_maxs[0], box_maxs[1], box_maxs[2], PACKMOL_CONSTRAIN if rotate else "") _run_packmol(input_text, solvated_xyz, temp_file) # Create the topology and update the coordinates. solvated = Compound() solvated.add(solute) solvated = _create_topology(solvated, solvent, n_solvent) solvated.update_coordinates(solvated_xyz.name) finally: for file_handle in solvent_xyz_list: file_handle.close() os.unlink(file_handle.name) solvated_xyz.close() solute_xyz.close() os.unlink(solvated_xyz.name) os.unlink(solute_xyz.name) return solvated
[ "def", "solvate", "(", "solute", ",", "solvent", ",", "n_solvent", ",", "box", ",", "overlap", "=", "0.2", ",", "seed", "=", "12345", ",", "edge", "=", "0.2", ",", "fix_orientation", "=", "False", ",", "temp_file", "=", "None", ")", ":", "_check_packmo...
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.Compound Compound to solvate the box. n_solvent : int Number of solvents to be put in box. box : mb.Box Box to be filled by compounds. overlap : float, units nm, default=0.2 Minimum separation between atoms of different molecules. seed : int, default=12345 Random seed to be passed to PACKMOL. edge : float, units nm, default=0.2 Buffer at the edge of the box to not place molecules. This is necessary in some systems because PACKMOL does not account for periodic boundary conditions in its optimization. fix_orientation : bool Specify if solvent should not be rotated when filling box, default=False. temp_file : str, default=None File name to write PACKMOL's raw output to. Returns ------- solvated : mb.Compound
[ "Solvate", "a", "compound", "in", "a", "box", "of", "solvent", "using", "packmol", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/packing.py#L472-L567
229,617
mosdef-hub/mbuild
mbuild/packing.py
_create_topology
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 Compound(s) to add to the container. container : int or list of int, required Amount of comp_to_add to container. Return ------ container : mb.Compound Compound with added compounds from PACKMOL. """ for comp, m_compound in zip(comp_to_add, n_compounds): for _ in range(m_compound): container.add(clone(comp)) return container
python
def _create_topology(container, comp_to_add, n_compounds): for comp, m_compound in zip(comp_to_add, n_compounds): for _ in range(m_compound): container.add(clone(comp)) return container
[ "def", "_create_topology", "(", "container", ",", "comp_to_add", ",", "n_compounds", ")", ":", "for", "comp", ",", "m_compound", "in", "zip", "(", "comp_to_add", ",", "n_compounds", ")", ":", "for", "_", "in", "range", "(", "m_compound", ")", ":", "contain...
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 Compound(s) to add to the container. container : int or list of int, required Amount of comp_to_add to container. Return ------ container : mb.Compound Compound with added compounds from PACKMOL.
[ "Return", "updated", "mBuild", "compound", "with", "new", "coordinates", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/packing.py#L596-L617
229,618
mosdef-hub/mbuild
mbuild/formats/gsdwriter.py
_write_pair_information
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 = [] pair_typeid = [] pairs = [] for ai in structure.atoms: for aj in ai.dihedral_partners: #make sure we don't double add if ai.idx > aj.idx: ps = '-'.join(sorted([ai.type, aj.type], key=natural_sort)) if ps not in pair_types: pair_types.append(ps) pair_typeid.append(pair_types.index(ps)) pairs.append((ai.idx, aj.idx)) gsd_file.pairs.types = pair_types gsd_file.pairs.typeid = pair_typeid gsd_file.pairs.group = pairs gsd_file.pairs.N = len(pairs)
python
def _write_pair_information(gsd_file, structure): pair_types = [] pair_typeid = [] pairs = [] for ai in structure.atoms: for aj in ai.dihedral_partners: #make sure we don't double add if ai.idx > aj.idx: ps = '-'.join(sorted([ai.type, aj.type], key=natural_sort)) if ps not in pair_types: pair_types.append(ps) pair_typeid.append(pair_types.index(ps)) pairs.append((ai.idx, aj.idx)) gsd_file.pairs.types = pair_types gsd_file.pairs.typeid = pair_typeid gsd_file.pairs.group = pairs gsd_file.pairs.N = len(pairs)
[ "def", "_write_pair_information", "(", "gsd_file", ",", "structure", ")", ":", "pair_types", "=", "[", "]", "pair_typeid", "=", "[", "]", "pairs", "=", "[", "]", "for", "ai", "in", "structure", ".", "atoms", ":", "for", "aj", "in", "ai", ".", "dihedral...
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
[ "Write", "the", "special", "pairs", "in", "the", "system", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/gsdwriter.py#L134-L159
229,619
mosdef-hub/mbuild
mbuild/formats/gsdwriter.py
_write_dihedral_information
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.N = len(structure.rb_torsions) unique_dihedral_types = set() for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3], key=natural_sort): dihedral_type = ('-'.join((t1, t2, t3, t4))) else: dihedral_type = ('-'.join((t4, t3, t2, t1))) unique_dihedral_types.add(dihedral_type) unique_dihedral_types = sorted(list(unique_dihedral_types), key=natural_sort) gsd_file.dihedrals.types = unique_dihedral_types dihedral_typeids = [] dihedral_groups = [] for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3], key=natural_sort): dihedral_type = ('-'.join((t1, t2, t3, t4))) else: dihedral_type = ('-'.join((t4, t3, t2, t1))) dihedral_typeids.append(unique_dihedral_types.index(dihedral_type)) dihedral_groups.append((dihedral.atom1.idx, dihedral.atom2.idx, dihedral.atom3.idx, dihedral.atom4.idx)) gsd_file.dihedrals.typeid = dihedral_typeids gsd_file.dihedrals.group = dihedral_groups
python
def _write_dihedral_information(gsd_file, structure): gsd_file.dihedrals.N = len(structure.rb_torsions) unique_dihedral_types = set() for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3], key=natural_sort): dihedral_type = ('-'.join((t1, t2, t3, t4))) else: dihedral_type = ('-'.join((t4, t3, t2, t1))) unique_dihedral_types.add(dihedral_type) unique_dihedral_types = sorted(list(unique_dihedral_types), key=natural_sort) gsd_file.dihedrals.types = unique_dihedral_types dihedral_typeids = [] dihedral_groups = [] for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3], key=natural_sort): dihedral_type = ('-'.join((t1, t2, t3, t4))) else: dihedral_type = ('-'.join((t4, t3, t2, t1))) dihedral_typeids.append(unique_dihedral_types.index(dihedral_type)) dihedral_groups.append((dihedral.atom1.idx, dihedral.atom2.idx, dihedral.atom3.idx, dihedral.atom4.idx)) gsd_file.dihedrals.typeid = dihedral_typeids gsd_file.dihedrals.group = dihedral_groups
[ "def", "_write_dihedral_information", "(", "gsd_file", ",", "structure", ")", ":", "gsd_file", ".", "dihedrals", ".", "N", "=", "len", "(", "structure", ".", "rb_torsions", ")", "unique_dihedral_types", "=", "set", "(", ")", "for", "dihedral", "in", "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
[ "Write", "the", "dihedrals", "in", "the", "system", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/gsdwriter.py#L242-L282
229,620
mosdef-hub/mbuild
mbuild/utils/io.py
import_
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 -------- >>> # the following two lines are equivalent. the difference is that the >>> # second will check for an ImportError and print you a very nice >>> # user-facing message about what's wrong (where you can install the >>> # module from, etc) if the import fails >>> import tables >>> tables = import_('tables') """ try: return importlib.import_module(module) except ImportError as e: try: message = MESSAGES[module] except KeyError: message = 'The code at {filename}:{line_number} requires the ' + module + ' package' e = ImportError('No module named %s' % module) frame, filename, line_number, function_name, lines, index = \ inspect.getouterframes(inspect.currentframe())[1] m = message.format(filename=os.path.basename(filename), line_number=line_number) m = textwrap.dedent(m) bar = '\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\033[0m' print('', file=sys.stderr) print(bar, file=sys.stderr) print(m, file=sys.stderr) print(bar, file=sys.stderr) raise DelayImportError(m)
python
def import_(module): try: return importlib.import_module(module) except ImportError as e: try: message = MESSAGES[module] except KeyError: message = 'The code at {filename}:{line_number} requires the ' + module + ' package' e = ImportError('No module named %s' % module) frame, filename, line_number, function_name, lines, index = \ inspect.getouterframes(inspect.currentframe())[1] m = message.format(filename=os.path.basename(filename), line_number=line_number) m = textwrap.dedent(m) bar = '\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\033[0m' print('', file=sys.stderr) print(bar, file=sys.stderr) print(m, file=sys.stderr) print(bar, file=sys.stderr) raise DelayImportError(m)
[ "def", "import_", "(", "module", ")", ":", "try", ":", "return", "importlib", ".", "import_module", "(", "module", ")", "except", "ImportError", "as", "e", ":", "try", ":", "message", "=", "MESSAGES", "[", "module", "]", "except", "KeyError", ":", "messa...
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 -------- >>> # the following two lines are equivalent. the difference is that the >>> # second will check for an ImportError and print you a very nice >>> # user-facing message about what's wrong (where you can install the >>> # module from, etc) if the import fails >>> import tables >>> tables = import_('tables')
[ "Import", "a", "module", "and", "issue", "a", "nice", "message", "to", "stderr", "if", "the", "module", "isn", "t", "installed", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/io.py#L81-L124
229,621
mosdef-hub/mbuild
mbuild/utils/io.py
get_fn
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 Name of the file to load (with respect to the reference/ folder). """ fn = resource_filename('mbuild', os.path.join('utils', 'reference', name)) if not os.path.exists(fn): raise IOError('Sorry! {} does not exists.'.format(fn)) return fn
python
def get_fn(name): fn = resource_filename('mbuild', os.path.join('utils', 'reference', name)) if not os.path.exists(fn): raise IOError('Sorry! {} does not exists.'.format(fn)) return fn
[ "def", "get_fn", "(", "name", ")", ":", "fn", "=", "resource_filename", "(", "'mbuild'", ",", "os", ".", "path", ".", "join", "(", "'utils'", ",", "'reference'", ",", "name", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fn", ")", ...
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 Name of the file to load (with respect to the reference/ folder).
[ "Get", "the", "full", "path", "to", "one", "of", "the", "reference", "files", "shipped", "for", "utils", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/io.py#L162-L178
229,622
mosdef-hub/mbuild
mbuild/coordinate_transform.py
angle
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
def angle(u, v, w=None): 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))
[ "def", "angle", "(", "u", ",", "v", ",", "w", "=", "None", ")", ":", "if", "w", "is", "not", "None", ":", "u", "=", "u", "-", "v", "v", "=", "w", "-", "v", "c", "=", "np", ".", "dot", "(", "u", ",", "v", ")", "/", "norm", "(", "u", ...
Returns the angle in radians between two vectors.
[ "Returns", "the", "angle", "in", "radians", "between", "two", "vectors", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L256-L262
229,623
mosdef-hub/mbuild
mbuild/coordinate_transform.py
_create_equivalence_transform
def _create_equivalence_transform(equiv): """Compute an equivalence transformation that transforms this compound to another compound's coordinate system. Parameters ---------- equiv : np.ndarray, shape=(n, 3), dtype=float Array of equivalent points. Returns ------- T : CoordinateTransform Transform that maps this point cloud to the other point cloud's coordinates system. """ from mbuild.compound import Compound self_points = np.array([]) self_points.shape = (0, 3) other_points = np.array([]) other_points.shape = (0, 3) for pair in equiv: if not isinstance(pair, tuple) or len(pair) != 2: raise ValueError('Equivalence pair not a 2-tuple') if not (isinstance(pair[0], Compound) and isinstance(pair[1], Compound)): raise ValueError('Equivalence pair type mismatch: pair[0] is a {0} ' 'and pair[1] is a {1}'.format(type(pair[0]), type(pair[1]))) # TODO: vstack is slow, replace with list concatenation if not pair[0].children: self_points = np.vstack([self_points, pair[0].pos]) other_points = np.vstack([other_points, pair[1].pos]) else: for atom0 in pair[0]._particles(include_ports=True): self_points = np.vstack([self_points, atom0.pos]) for atom1 in pair[1]._particles(include_ports=True): other_points = np.vstack([other_points, atom1.pos]) T = RigidTransform(self_points, other_points) return T
python
def _create_equivalence_transform(equiv): from mbuild.compound import Compound self_points = np.array([]) self_points.shape = (0, 3) other_points = np.array([]) other_points.shape = (0, 3) for pair in equiv: if not isinstance(pair, tuple) or len(pair) != 2: raise ValueError('Equivalence pair not a 2-tuple') if not (isinstance(pair[0], Compound) and isinstance(pair[1], Compound)): raise ValueError('Equivalence pair type mismatch: pair[0] is a {0} ' 'and pair[1] is a {1}'.format(type(pair[0]), type(pair[1]))) # TODO: vstack is slow, replace with list concatenation if not pair[0].children: self_points = np.vstack([self_points, pair[0].pos]) other_points = np.vstack([other_points, pair[1].pos]) else: for atom0 in pair[0]._particles(include_ports=True): self_points = np.vstack([self_points, atom0.pos]) for atom1 in pair[1]._particles(include_ports=True): other_points = np.vstack([other_points, atom1.pos]) T = RigidTransform(self_points, other_points) return T
[ "def", "_create_equivalence_transform", "(", "equiv", ")", ":", "from", "mbuild", ".", "compound", "import", "Compound", "self_points", "=", "np", ".", "array", "(", "[", "]", ")", "self_points", ".", "shape", "=", "(", "0", ",", "3", ")", "other_points", ...
Compute an equivalence transformation that transforms this compound to another compound's coordinate system. Parameters ---------- equiv : np.ndarray, shape=(n, 3), dtype=float Array of equivalent points. Returns ------- T : CoordinateTransform Transform that maps this point cloud to the other point cloud's coordinates system.
[ "Compute", "an", "equivalence", "transformation", "that", "transforms", "this", "compound", "to", "another", "compound", "s", "coordinate", "system", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L265-L305
229,624
mosdef-hub/mbuild
mbuild/coordinate_transform.py
_choose_correct_port
def _choose_correct_port(from_port, to_port): """Chooses the direction when using an equivalence transform on two Ports. Each Port object actually contains 2 sets of 4 atoms, either of which can be used to make a connection with an equivalence transform. This function chooses the set of 4 atoms that makes the anchor atoms not overlap which is the intended behavior for most use-cases. TODO: -Increase robustness for cases where the anchors are a different distance from their respective ports. -Provide options in `force_overlap` to override this behavior. Parameters ---------- from_port : mb.Port to_port : mb.Port Returns ------- equivalence_pairs : tuple of Ports, shape=(2,) Technically, a tuple of the Ports' sub-Compounds ('up' or 'down') that are used to make the correct connection between components. """ # First we try matching the two 'up' ports. T1 = _create_equivalence_transform([(from_port['up'], to_port['up'])]) new_position = T1.apply_to(np.array(from_port.anchor.pos, ndmin=2)) dist_between_anchors_up_up = norm(new_position[0] - to_port.anchor.pos) # Then matching a 'down' with an 'up' port. T2 = _create_equivalence_transform([(from_port['down'], to_port['up'])]) new_position = T2.apply_to(np.array(from_port.anchor.pos, ndmin=2)) # Determine which transform places the anchors further away from each other. dist_between_anchors_down_up = norm(new_position[0] - to_port.anchor.pos) difference_between_distances = dist_between_anchors_down_up - dist_between_anchors_up_up if difference_between_distances > 0: correct_port = from_port['down'] T = T2 else: correct_port = from_port['up'] T = T1 return [(correct_port, to_port['up'])], T
python
def _choose_correct_port(from_port, to_port): # First we try matching the two 'up' ports. T1 = _create_equivalence_transform([(from_port['up'], to_port['up'])]) new_position = T1.apply_to(np.array(from_port.anchor.pos, ndmin=2)) dist_between_anchors_up_up = norm(new_position[0] - to_port.anchor.pos) # Then matching a 'down' with an 'up' port. T2 = _create_equivalence_transform([(from_port['down'], to_port['up'])]) new_position = T2.apply_to(np.array(from_port.anchor.pos, ndmin=2)) # Determine which transform places the anchors further away from each other. dist_between_anchors_down_up = norm(new_position[0] - to_port.anchor.pos) difference_between_distances = dist_between_anchors_down_up - dist_between_anchors_up_up if difference_between_distances > 0: correct_port = from_port['down'] T = T2 else: correct_port = from_port['up'] T = T1 return [(correct_port, to_port['up'])], T
[ "def", "_choose_correct_port", "(", "from_port", ",", "to_port", ")", ":", "# First we try matching the two 'up' ports.", "T1", "=", "_create_equivalence_transform", "(", "[", "(", "from_port", "[", "'up'", "]", ",", "to_port", "[", "'up'", "]", ")", "]", ")", "...
Chooses the direction when using an equivalence transform on two Ports. Each Port object actually contains 2 sets of 4 atoms, either of which can be used to make a connection with an equivalence transform. This function chooses the set of 4 atoms that makes the anchor atoms not overlap which is the intended behavior for most use-cases. TODO: -Increase robustness for cases where the anchors are a different distance from their respective ports. -Provide options in `force_overlap` to override this behavior. Parameters ---------- from_port : mb.Port to_port : mb.Port Returns ------- equivalence_pairs : tuple of Ports, shape=(2,) Technically, a tuple of the Ports' sub-Compounds ('up' or 'down') that are used to make the correct connection between components.
[ "Chooses", "the", "direction", "when", "using", "an", "equivalence", "transform", "on", "two", "Ports", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L351-L395
229,625
mosdef-hub/mbuild
mbuild/coordinate_transform.py
translate
def translate(compound, pos): """Translate a compound by a vector. Parameters ---------- compound : mb.Compound The compound being translated. pos : np.ndarray, shape=(3,), dtype=float The vector to translate the compound by. """ atom_positions = compound.xyz_with_ports atom_positions = Translation(pos).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
python
def translate(compound, pos): atom_positions = compound.xyz_with_ports atom_positions = Translation(pos).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
[ "def", "translate", "(", "compound", ",", "pos", ")", ":", "atom_positions", "=", "compound", ".", "xyz_with_ports", "atom_positions", "=", "Translation", "(", "pos", ")", ".", "apply_to", "(", "atom_positions", ")", "compound", ".", "xyz_with_ports", "=", "at...
Translate a compound by a vector. Parameters ---------- compound : mb.Compound The compound being translated. pos : np.ndarray, shape=(3,), dtype=float The vector to translate the compound by.
[ "Translate", "a", "compound", "by", "a", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L400-L413
229,626
mosdef-hub/mbuild
mbuild/coordinate_transform.py
translate_to
def translate_to(compound, pos): """Translate a compound to a coordinate. Parameters ---------- compound : mb.Compound The compound being translated. pos : np.ndarray, shape=(3,), dtype=float The coordinate to translate the compound to. """ atom_positions = compound.xyz_with_ports atom_positions -= compound.center atom_positions = Translation(pos).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
python
def translate_to(compound, pos): atom_positions = compound.xyz_with_ports atom_positions -= compound.center atom_positions = Translation(pos).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
[ "def", "translate_to", "(", "compound", ",", "pos", ")", ":", "atom_positions", "=", "compound", ".", "xyz_with_ports", "atom_positions", "-=", "compound", ".", "center", "atom_positions", "=", "Translation", "(", "pos", ")", ".", "apply_to", "(", "atom_position...
Translate a compound to a coordinate. Parameters ---------- compound : mb.Compound The compound being translated. pos : np.ndarray, shape=(3,), dtype=float The coordinate to translate the compound to.
[ "Translate", "a", "compound", "to", "a", "coordinate", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L417-L431
229,627
mosdef-hub/mbuild
mbuild/coordinate_transform.py
_translate_to
def _translate_to(coordinates, to): """Translate a set of coordinates to a location. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being translated. to : np.ndarray, shape=(3,), dtype=float The new average position of the coordinates. """ coordinates -= np.mean(coordinates, axis=0) return Translation(to).apply_to(coordinates)
python
def _translate_to(coordinates, to): coordinates -= np.mean(coordinates, axis=0) return Translation(to).apply_to(coordinates)
[ "def", "_translate_to", "(", "coordinates", ",", "to", ")", ":", "coordinates", "-=", "np", ".", "mean", "(", "coordinates", ",", "axis", "=", "0", ")", "return", "Translation", "(", "to", ")", ".", "apply_to", "(", "coordinates", ")" ]
Translate a set of coordinates to a location. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being translated. to : np.ndarray, shape=(3,), dtype=float The new average position of the coordinates.
[ "Translate", "a", "set", "of", "coordinates", "to", "a", "location", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L448-L460
229,628
mosdef-hub/mbuild
mbuild/coordinate_transform.py
_rotate
def _rotate(coordinates, theta, around): """Rotate a set of coordinates around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being rotated. theta : float The angle by which to rotate the coordinates, in radians. around : np.ndarray, shape=(3,), dtype=float The vector about which to rotate the coordinates. """ around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot rotate around a zero vector') return Rotation(theta, around).apply_to(coordinates)
python
def _rotate(coordinates, theta, around): around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot rotate around a zero vector') return Rotation(theta, around).apply_to(coordinates)
[ "def", "_rotate", "(", "coordinates", ",", "theta", ",", "around", ")", ":", "around", "=", "np", ".", "asarray", "(", "around", ")", ".", "reshape", "(", "3", ")", "if", "np", ".", "array_equal", "(", "around", ",", "np", ".", "zeros", "(", "3", ...
Rotate a set of coordinates around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being rotated. theta : float The angle by which to rotate the coordinates, in radians. around : np.ndarray, shape=(3,), dtype=float The vector about which to rotate the coordinates.
[ "Rotate", "a", "set", "of", "coordinates", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L463-L479
229,629
mosdef-hub/mbuild
mbuild/coordinate_transform.py
rotate
def rotate(compound, theta, around): """Rotate a compound around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. 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 compound. """ around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot rotate around a zero vector') atom_positions = compound.xyz_with_ports atom_positions = Rotation(theta, around).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
python
def rotate(compound, theta, around): around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot rotate around a zero vector') atom_positions = compound.xyz_with_ports atom_positions = Rotation(theta, around).apply_to(atom_positions) compound.xyz_with_ports = atom_positions
[ "def", "rotate", "(", "compound", ",", "theta", ",", "around", ")", ":", "around", "=", "np", ".", "asarray", "(", "around", ")", ".", "reshape", "(", "3", ")", "if", "np", ".", "array_equal", "(", "around", ",", "np", ".", "zeros", "(", "3", ")"...
Rotate a compound around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. 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 compound.
[ "Rotate", "a", "compound", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L484-L502
229,630
mosdef-hub/mbuild
mbuild/coordinate_transform.py
spin
def spin(compound, theta, around): """Rotate a compound in place around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. 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 compound. """ around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot spin around a zero vector') center_pos = compound.center translate(compound, -center_pos) rotate(compound, theta, around) translate(compound, center_pos)
python
def spin(compound, theta, around): around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot spin around a zero vector') center_pos = compound.center translate(compound, -center_pos) rotate(compound, theta, around) translate(compound, center_pos)
[ "def", "spin", "(", "compound", ",", "theta", ",", "around", ")", ":", "around", "=", "np", ".", "asarray", "(", "around", ")", ".", "reshape", "(", "3", ")", "if", "np", ".", "array_equal", "(", "around", ",", "np", ".", "zeros", "(", "3", ")", ...
Rotate a compound in place around an arbitrary vector. Parameters ---------- compound : mb.Compound The compound being rotated. 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 compound.
[ "Rotate", "a", "compound", "in", "place", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L555-L574
229,631
mosdef-hub/mbuild
mbuild/coordinate_transform.py
_spin
def _spin(coordinates, theta, around): """Rotate a set of coordinates in place around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being spun. theta : float The angle by which to spin the coordinates, in radians. around : np.ndarray, shape=(3,), dtype=float The axis about which to spin the coordinates. """ around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot spin around a zero vector') center_pos = np.mean(coordinates, axis=0) coordinates -= center_pos coordinates = _rotate(coordinates, theta, around) coordinates += center_pos return coordinates
python
def _spin(coordinates, theta, around): around = np.asarray(around).reshape(3) if np.array_equal(around, np.zeros(3)): raise ValueError('Cannot spin around a zero vector') center_pos = np.mean(coordinates, axis=0) coordinates -= center_pos coordinates = _rotate(coordinates, theta, around) coordinates += center_pos return coordinates
[ "def", "_spin", "(", "coordinates", ",", "theta", ",", "around", ")", ":", "around", "=", "np", ".", "asarray", "(", "around", ")", ".", "reshape", "(", "3", ")", "if", "np", ".", "array_equal", "(", "around", ",", "np", ".", "zeros", "(", "3", "...
Rotate a set of coordinates in place around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being spun. theta : float The angle by which to spin the coordinates, in radians. around : np.ndarray, shape=(3,), dtype=float The axis about which to spin the coordinates.
[ "Rotate", "a", "set", "of", "coordinates", "in", "place", "around", "an", "arbitrary", "vector", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L577-L597
229,632
mosdef-hub/mbuild
mbuild/coordinate_transform.py
x_axis_transform
def x_axis_transform(compound, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None): """Move a compound such that the x-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_x_axis : mb.Compound or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new x-axis. point_on_xy_plane : mb.Compound, or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new xy-plane. """ import mbuild as mb if new_origin is None: new_origin = np.array([0, 0, 0]) elif isinstance(new_origin, mb.Compound): new_origin = new_origin.pos elif isinstance(new_origin, (tuple, list,np.ndarray)): new_origin = np.asarray(new_origin) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of length 3 or None for the new_origin' ' parameter. User passed type: {}.'.format(type(new_origin))) if point_on_x_axis is None: point_on_x_axis = np.array([1.0, 0.0, 0.0]) elif isinstance(point_on_x_axis, mb.Compound): point_on_x_axis = point_on_x_axis.pos elif isinstance(point_on_x_axis, (list, tuple, np.ndarray)): point_on_x_axis = np.asarray(point_on_x_axis) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_x_axis' ' parameter. User passed type: {}.'.format(type(point_on_x_axis))) if point_on_xy_plane is None: point_on_xy_plane = np.array([1.0, 1.0, 0.0]) elif isinstance(point_on_xy_plane, mb.Compound): point_on_xy_plane = point_on_xy_plane.pos elif isinstance(point_on_xy_plane, (list, tuple, np.ndarray)): point_on_xy_plane = np.asarray(point_on_xy_plane) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_xy_plane' ' parameter. User passed type: {}.'.format(type(point_on_xy_plane))) atom_positions = compound.xyz_with_ports transform = AxisTransform(new_origin=new_origin, point_on_x_axis=point_on_x_axis, point_on_xy_plane=point_on_xy_plane) atom_positions = transform.apply_to(atom_positions) compound.xyz_with_ports = atom_positions
python
def x_axis_transform(compound, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None): import mbuild as mb if new_origin is None: new_origin = np.array([0, 0, 0]) elif isinstance(new_origin, mb.Compound): new_origin = new_origin.pos elif isinstance(new_origin, (tuple, list,np.ndarray)): new_origin = np.asarray(new_origin) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of length 3 or None for the new_origin' ' parameter. User passed type: {}.'.format(type(new_origin))) if point_on_x_axis is None: point_on_x_axis = np.array([1.0, 0.0, 0.0]) elif isinstance(point_on_x_axis, mb.Compound): point_on_x_axis = point_on_x_axis.pos elif isinstance(point_on_x_axis, (list, tuple, np.ndarray)): point_on_x_axis = np.asarray(point_on_x_axis) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_x_axis' ' parameter. User passed type: {}.'.format(type(point_on_x_axis))) if point_on_xy_plane is None: point_on_xy_plane = np.array([1.0, 1.0, 0.0]) elif isinstance(point_on_xy_plane, mb.Compound): point_on_xy_plane = point_on_xy_plane.pos elif isinstance(point_on_xy_plane, (list, tuple, np.ndarray)): point_on_xy_plane = np.asarray(point_on_xy_plane) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_xy_plane' ' parameter. User passed type: {}.'.format(type(point_on_xy_plane))) atom_positions = compound.xyz_with_ports transform = AxisTransform(new_origin=new_origin, point_on_x_axis=point_on_x_axis, point_on_xy_plane=point_on_xy_plane) atom_positions = transform.apply_to(atom_positions) compound.xyz_with_ports = atom_positions
[ "def", "x_axis_transform", "(", "compound", ",", "new_origin", "=", "None", ",", "point_on_x_axis", "=", "None", ",", "point_on_xy_plane", "=", "None", ")", ":", "import", "mbuild", "as", "mb", "if", "new_origin", "is", "None", ":", "new_origin", "=", "np", ...
Move a compound such that the x-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_x_axis : mb.Compound or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new x-axis. point_on_xy_plane : mb.Compound, or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new xy-plane.
[ "Move", "a", "compound", "such", "that", "the", "x", "-", "axis", "lies", "on", "specified", "points", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L648-L703
229,633
mosdef-hub/mbuild
mbuild/coordinate_transform.py
y_axis_transform
def y_axis_transform(compound, new_origin=None, point_on_y_axis=None, point_on_xy_plane=None): """Move a compound such that the y-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or like-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_y_axis : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0] A point on the new y-axis. point_on_xy_plane : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0] A point on the new xy-plane. """ x_axis_transform(compound, new_origin=new_origin, point_on_x_axis=point_on_y_axis, point_on_xy_plane=point_on_xy_plane) rotate_around_z(compound, np.pi / 2)
python
def y_axis_transform(compound, new_origin=None, point_on_y_axis=None, point_on_xy_plane=None): x_axis_transform(compound, new_origin=new_origin, point_on_x_axis=point_on_y_axis, point_on_xy_plane=point_on_xy_plane) rotate_around_z(compound, np.pi / 2)
[ "def", "y_axis_transform", "(", "compound", ",", "new_origin", "=", "None", ",", "point_on_y_axis", "=", "None", ",", "point_on_xy_plane", "=", "None", ")", ":", "x_axis_transform", "(", "compound", ",", "new_origin", "=", "new_origin", ",", "point_on_x_axis", "...
Move a compound such that the y-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or like-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_y_axis : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0] A point on the new y-axis. point_on_xy_plane : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0] A point on the new xy-plane.
[ "Move", "a", "compound", "such", "that", "the", "y", "-", "axis", "lies", "on", "specified", "points", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L706-L726
229,634
mosdef-hub/mbuild
mbuild/coordinate_transform.py
z_axis_transform
def z_axis_transform(compound, new_origin=None, point_on_z_axis=None, point_on_zx_plane=None): """Move a compound such that the z-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_z_axis : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 1.0] A point on the new z-axis. point_on_zx_plane : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 1.0] A point on the new xz-plane. """ x_axis_transform(compound, new_origin=new_origin, point_on_x_axis=point_on_z_axis, point_on_xy_plane=point_on_zx_plane) rotate_around_y(compound, np.pi * 3 / 2)
python
def z_axis_transform(compound, new_origin=None, point_on_z_axis=None, point_on_zx_plane=None): x_axis_transform(compound, new_origin=new_origin, point_on_x_axis=point_on_z_axis, point_on_xy_plane=point_on_zx_plane) rotate_around_y(compound, np.pi * 3 / 2)
[ "def", "z_axis_transform", "(", "compound", ",", "new_origin", "=", "None", ",", "point_on_z_axis", "=", "None", ",", "point_on_zx_plane", "=", "None", ")", ":", "x_axis_transform", "(", "compound", ",", "new_origin", "=", "new_origin", ",", "point_on_x_axis", "...
Move a compound such that the z-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_z_axis : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 1.0] A point on the new z-axis. point_on_zx_plane : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 1.0] A point on the new xz-plane.
[ "Move", "a", "compound", "such", "that", "the", "z", "-", "axis", "lies", "on", "specified", "points", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L729-L749
229,635
mosdef-hub/mbuild
mbuild/coordinate_transform.py
CoordinateTransform.apply_to
def apply_to(self, A): """Apply the coordinate transformation to points in A. """ if A.ndim == 1: A = np.expand_dims(A, axis=0) rows, cols = A.shape A_new = np.hstack([A, np.ones((rows, 1))]) A_new = np.transpose(self.T.dot(np.transpose(A_new))) return A_new[:, 0:cols]
python
def apply_to(self, A): if A.ndim == 1: A = np.expand_dims(A, axis=0) rows, cols = A.shape A_new = np.hstack([A, np.ones((rows, 1))]) A_new = np.transpose(self.T.dot(np.transpose(A_new))) return A_new[:, 0:cols]
[ "def", "apply_to", "(", "self", ",", "A", ")", ":", "if", "A", ".", "ndim", "==", "1", ":", "A", "=", "np", ".", "expand_dims", "(", "A", ",", "axis", "=", "0", ")", "rows", ",", "cols", "=", "A", ".", "shape", "A_new", "=", "np", ".", "hst...
Apply the coordinate transformation to points in A.
[ "Apply", "the", "coordinate", "transformation", "to", "points", "in", "A", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L72-L80
229,636
mosdef-hub/mbuild
mbuild/lib/recipes/tiled_compound.py
TiledCompound._add_tile
def _add_tile(self, new_tile, ijk): """Add a tile with a label indicating its tiling position. """ tile_label = "{0}_{1}".format(self.name, '-'.join(str(d) for d in ijk)) self.add(new_tile, label=tile_label, inherit_periodicity=False)
python
def _add_tile(self, new_tile, ijk): tile_label = "{0}_{1}".format(self.name, '-'.join(str(d) for d in ijk)) self.add(new_tile, label=tile_label, inherit_periodicity=False)
[ "def", "_add_tile", "(", "self", ",", "new_tile", ",", "ijk", ")", ":", "tile_label", "=", "\"{0}_{1}\"", ".", "format", "(", "self", ".", "name", ",", "'-'", ".", "join", "(", "str", "(", "d", ")", "for", "d", "in", "ijk", ")", ")", "self", ".",...
Add a tile with a label indicating its tiling position.
[ "Add", "a", "tile", "with", "a", "label", "indicating", "its", "tiling", "position", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/tiled_compound.py#L117-L120
229,637
mosdef-hub/mbuild
mbuild/lib/recipes/tiled_compound.py
TiledCompound._find_particle_image
def _find_particle_image(self, query, match, all_particles): """Find particle with the same index as match in a neighboring tile. """ _, idxs = self.particle_kdtree.query(query.pos, k=10) neighbors = all_particles[idxs] for particle in neighbors: if particle.index == match.index: return particle raise MBuildError('Unable to find matching particle image while' ' stitching bonds.')
python
def _find_particle_image(self, query, match, all_particles): _, idxs = self.particle_kdtree.query(query.pos, k=10) neighbors = all_particles[idxs] for particle in neighbors: if particle.index == match.index: return particle raise MBuildError('Unable to find matching particle image while' ' stitching bonds.')
[ "def", "_find_particle_image", "(", "self", ",", "query", ",", "match", ",", "all_particles", ")", ":", "_", ",", "idxs", "=", "self", ".", "particle_kdtree", ".", "query", "(", "query", ".", "pos", ",", "k", "=", "10", ")", "neighbors", "=", "all_part...
Find particle with the same index as match in a neighboring tile.
[ "Find", "particle", "with", "the", "same", "index", "as", "match", "in", "a", "neighboring", "tile", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/lib/recipes/tiled_compound.py#L128-L138
229,638
mosdef-hub/mbuild
mbuild/utils/conversion.py
RB_to_OPLS
def RB_to_OPLS(c0, c1, c2, c3, c4, c5): """Converts Ryckaert-Bellemans type dihedrals to OPLS type. Parameters ---------- c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol) Returns ------- opls_coeffs : np.array, shape=(4,) Array containing the OPLS dihedrals coeffs f1, f2, f3, and f4 (in kcal/mol) """ f1 = (-1.5 * c3) - (2 * c1) f2 = c0 + c1 + c3 f3 = -0.5 * c3 f4 = -0.25 * c4 return np.array([f1, f2, f3, f4])
python
def RB_to_OPLS(c0, c1, c2, c3, c4, c5): f1 = (-1.5 * c3) - (2 * c1) f2 = c0 + c1 + c3 f3 = -0.5 * c3 f4 = -0.25 * c4 return np.array([f1, f2, f3, f4])
[ "def", "RB_to_OPLS", "(", "c0", ",", "c1", ",", "c2", ",", "c3", ",", "c4", ",", "c5", ")", ":", "f1", "=", "(", "-", "1.5", "*", "c3", ")", "-", "(", "2", "*", "c1", ")", "f2", "=", "c0", "+", "c1", "+", "c3", "f3", "=", "-", "0.5", ...
Converts Ryckaert-Bellemans type dihedrals to OPLS type. Parameters ---------- c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol) Returns ------- opls_coeffs : np.array, shape=(4,) Array containing the OPLS dihedrals coeffs f1, f2, f3, and f4 (in kcal/mol)
[ "Converts", "Ryckaert", "-", "Bellemans", "type", "dihedrals", "to", "OPLS", "type", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/conversion.py#L4-L23
229,639
mosdef-hub/mbuild
mbuild/formats/hoomdxml.py
write_hoomdxml
def write_hoomdxml(structure, filename, ref_distance=1.0, ref_mass=1.0, ref_energy=1.0, rigid_bodies=None, shift_coords=True, auto_scale=False): """Output a HOOMD XML file. Parameters ---------- structure : parmed.Structure ParmEd structure object filename : str Path of the output file. ref_distance : float, optional, default=1.0, units=nanometers Reference distance for conversion to reduced units ref_mass : float, optional, default=1.0, units=amu Reference mass for conversion to reduced units ref_energy : float, optional, default=1.0, units=kJ/mol Reference energy for conversion to reduced units rigid_bodies : list List of rigid body information. An integer value is required for each particle corresponding to the number of the rigid body with which the particle should be included. A value of None indicates the particle is not part of any rigid body. shift_coords : bool, optional, default=True Shift coordinates from (0, L) to (-L/2, L/2) if necessary. auto_scale : bool, optional, default=False Automatically use largest sigma value as ref_distance, largest mass value as ref_mass and largest epsilon value as ref_energy. Returns ------- ReferenceValues : namedtuple Values used in scaling Example ------- ref_values = ethane.save(filename='ethane-opls.hoomdxml', forcefield_name='oplsaa', auto_scale=True) print(ref_values.mass, ref_values.distance, ref_values.energy) Notes ----- The following elements are always written: * **position** : particle positions * **type** : particle types * **mass** : particle masses (default 1.0) * **charge** : particle charges The following elements may be written if applicable: * **pair_coeffs** : Pair coefficients for each particle type (assumes a 12-6 LJ pair style). The following information is written for each particle type: * type : particle type * epsilon : LJ epsilon * sigma : LJ sigma * **bond_coeffs** : Coefficients for each bond type (assumes a harmonic bond style). The following information is written for each bond type: * type : bond type * k : force constant (units of energy/distance^2) * r0 : bond rest length (units of distance) * **bond** : system bonds * **angle_coeffs** : Coefficients for each angle type (assumes a harmonic angle style). The following information is written for each angle type: * type : angle type * k : force constant (units of energy/radians^2) * theta : rest angle (units of radians) * **angle** : system angles * **dihedral_coeffs** : Coefficients for each dihedral type (assumes an OPLS dihedral style). The following information is written for each dihedral type: * type : dihedral type * k1, k2, k3, k4 : force coefficients (units of energy) * **dihedral** : system dihedrals * **body** : ID of the rigid body to which each particle belongs """ ref_distance *= 10 # Parmed unit hack ref_energy /= 4.184 # Parmed unit hack forcefield = True if structure[0].type == '': forcefield = False if auto_scale and forcefield: ref_mass = max([atom.mass for atom in structure.atoms]) pair_coeffs = list(set((atom.type, atom.epsilon, atom.sigma) for atom in structure.atoms)) ref_energy = max(pair_coeffs, key=operator.itemgetter(1))[1] ref_distance = max(pair_coeffs, key=operator.itemgetter(2))[2] xyz = np.array([[atom.xx, atom.xy, atom.xz] for atom in structure.atoms]) if shift_coords: xyz = coord_shift(xyz, structure.box[:3]) with open(filename, 'w') as xml_file: xml_file.write('<?xml version="1.2" encoding="UTF-8"?>\n') xml_file.write('<hoomd_xml version="1.2">\n') xml_file.write('<!-- ref_distance (nm) ref_mass (amu) ref_energy (kJ/mol) -->\n') xml_file.write('<!-- {} {} {} -->\n'.format(ref_distance, ref_mass, ref_energy)) xml_file.write('<configuration time_step="0">\n') _write_box_information(xml_file, structure, ref_distance) _write_particle_information(xml_file, structure, xyz, forcefield, ref_distance, ref_mass, ref_energy) _write_bond_information(xml_file, structure, ref_distance, ref_energy) _write_angle_information(xml_file, structure, ref_energy) _write_dihedral_information(xml_file, structure, ref_energy) _write_rigid_information(xml_file, rigid_bodies) xml_file.write('</configuration>\n') xml_file.write('</hoomd_xml>') ReferenceValues = namedtuple("ref_values", ["distance", "mass", "energy"]) return ReferenceValues(ref_distance, ref_mass, ref_energy)
python
def write_hoomdxml(structure, filename, ref_distance=1.0, ref_mass=1.0, ref_energy=1.0, rigid_bodies=None, shift_coords=True, auto_scale=False): ref_distance *= 10 # Parmed unit hack ref_energy /= 4.184 # Parmed unit hack forcefield = True if structure[0].type == '': forcefield = False if auto_scale and forcefield: ref_mass = max([atom.mass for atom in structure.atoms]) pair_coeffs = list(set((atom.type, atom.epsilon, atom.sigma) for atom in structure.atoms)) ref_energy = max(pair_coeffs, key=operator.itemgetter(1))[1] ref_distance = max(pair_coeffs, key=operator.itemgetter(2))[2] xyz = np.array([[atom.xx, atom.xy, atom.xz] for atom in structure.atoms]) if shift_coords: xyz = coord_shift(xyz, structure.box[:3]) with open(filename, 'w') as xml_file: xml_file.write('<?xml version="1.2" encoding="UTF-8"?>\n') xml_file.write('<hoomd_xml version="1.2">\n') xml_file.write('<!-- ref_distance (nm) ref_mass (amu) ref_energy (kJ/mol) -->\n') xml_file.write('<!-- {} {} {} -->\n'.format(ref_distance, ref_mass, ref_energy)) xml_file.write('<configuration time_step="0">\n') _write_box_information(xml_file, structure, ref_distance) _write_particle_information(xml_file, structure, xyz, forcefield, ref_distance, ref_mass, ref_energy) _write_bond_information(xml_file, structure, ref_distance, ref_energy) _write_angle_information(xml_file, structure, ref_energy) _write_dihedral_information(xml_file, structure, ref_energy) _write_rigid_information(xml_file, rigid_bodies) xml_file.write('</configuration>\n') xml_file.write('</hoomd_xml>') ReferenceValues = namedtuple("ref_values", ["distance", "mass", "energy"]) return ReferenceValues(ref_distance, ref_mass, ref_energy)
[ "def", "write_hoomdxml", "(", "structure", ",", "filename", ",", "ref_distance", "=", "1.0", ",", "ref_mass", "=", "1.0", ",", "ref_energy", "=", "1.0", ",", "rigid_bodies", "=", "None", ",", "shift_coords", "=", "True", ",", "auto_scale", "=", "False", ")...
Output a HOOMD XML file. Parameters ---------- structure : parmed.Structure ParmEd structure object filename : str Path of the output file. ref_distance : float, optional, default=1.0, units=nanometers Reference distance for conversion to reduced units ref_mass : float, optional, default=1.0, units=amu Reference mass for conversion to reduced units ref_energy : float, optional, default=1.0, units=kJ/mol Reference energy for conversion to reduced units rigid_bodies : list List of rigid body information. An integer value is required for each particle corresponding to the number of the rigid body with which the particle should be included. A value of None indicates the particle is not part of any rigid body. shift_coords : bool, optional, default=True Shift coordinates from (0, L) to (-L/2, L/2) if necessary. auto_scale : bool, optional, default=False Automatically use largest sigma value as ref_distance, largest mass value as ref_mass and largest epsilon value as ref_energy. Returns ------- ReferenceValues : namedtuple Values used in scaling Example ------- ref_values = ethane.save(filename='ethane-opls.hoomdxml', forcefield_name='oplsaa', auto_scale=True) print(ref_values.mass, ref_values.distance, ref_values.energy) Notes ----- The following elements are always written: * **position** : particle positions * **type** : particle types * **mass** : particle masses (default 1.0) * **charge** : particle charges The following elements may be written if applicable: * **pair_coeffs** : Pair coefficients for each particle type (assumes a 12-6 LJ pair style). The following information is written for each particle type: * type : particle type * epsilon : LJ epsilon * sigma : LJ sigma * **bond_coeffs** : Coefficients for each bond type (assumes a harmonic bond style). The following information is written for each bond type: * type : bond type * k : force constant (units of energy/distance^2) * r0 : bond rest length (units of distance) * **bond** : system bonds * **angle_coeffs** : Coefficients for each angle type (assumes a harmonic angle style). The following information is written for each angle type: * type : angle type * k : force constant (units of energy/radians^2) * theta : rest angle (units of radians) * **angle** : system angles * **dihedral_coeffs** : Coefficients for each dihedral type (assumes an OPLS dihedral style). The following information is written for each dihedral type: * type : dihedral type * k1, k2, k3, k4 : force coefficients (units of energy) * **dihedral** : system dihedrals * **body** : ID of the rigid body to which each particle belongs
[ "Output", "a", "HOOMD", "XML", "file", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/hoomdxml.py#L16-L131
229,640
mosdef-hub/mbuild
mbuild/formats/hoomdxml.py
_write_dihedral_information
def _write_dihedral_information(xml_file, structure, ref_energy): """Write dihedrals in the system. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 Reference energy for conversion to reduced units """ unique_dihedral_types = set() xml_file.write('<dihedral>\n') for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type, t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3]): types_in_dihedral = '-'.join((t1, t2, t3, t4)) else: types_in_dihedral = '-'.join((t4, t3, t2, t1)) dihedral_type = (types_in_dihedral, dihedral.type.c0, dihedral.type.c1, dihedral.type.c2, dihedral.type.c3, dihedral.type.c4, dihedral.type.c5, dihedral.type.scee, dihedral.type.scnb) unique_dihedral_types.add(dihedral_type) xml_file.write('{} {} {} {} {}\n'.format( dihedral_type[0], dihedral.atom1.idx, dihedral.atom2.idx, dihedral.atom3.idx, dihedral.atom4.idx)) xml_file.write('</dihedral>\n') xml_file.write('<dihedral_coeffs>\n') xml_file.write('<!-- type k1 k2 k3 k4 -->\n') for dihedral_type, c0, c1, c2, c3, c4, c5, scee, scnb in unique_dihedral_types: opls_coeffs = RB_to_OPLS(c0, c1, c2, c3, c4, c5) opls_coeffs /= ref_energy xml_file.write('{} {:.5f} {:.5f} {:.5f} {:.5f}\n'.format( dihedral_type, *opls_coeffs)) xml_file.write('</dihedral_coeffs>\n')
python
def _write_dihedral_information(xml_file, structure, ref_energy): unique_dihedral_types = set() xml_file.write('<dihedral>\n') for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type, t3, t4 = dihedral.atom3.type, dihedral.atom4.type if [t2, t3] == sorted([t2, t3]): types_in_dihedral = '-'.join((t1, t2, t3, t4)) else: types_in_dihedral = '-'.join((t4, t3, t2, t1)) dihedral_type = (types_in_dihedral, dihedral.type.c0, dihedral.type.c1, dihedral.type.c2, dihedral.type.c3, dihedral.type.c4, dihedral.type.c5, dihedral.type.scee, dihedral.type.scnb) unique_dihedral_types.add(dihedral_type) xml_file.write('{} {} {} {} {}\n'.format( dihedral_type[0], dihedral.atom1.idx, dihedral.atom2.idx, dihedral.atom3.idx, dihedral.atom4.idx)) xml_file.write('</dihedral>\n') xml_file.write('<dihedral_coeffs>\n') xml_file.write('<!-- type k1 k2 k3 k4 -->\n') for dihedral_type, c0, c1, c2, c3, c4, c5, scee, scnb in unique_dihedral_types: opls_coeffs = RB_to_OPLS(c0, c1, c2, c3, c4, c5) opls_coeffs /= ref_energy xml_file.write('{} {:.5f} {:.5f} {:.5f} {:.5f}\n'.format( dihedral_type, *opls_coeffs)) xml_file.write('</dihedral_coeffs>\n')
[ "def", "_write_dihedral_information", "(", "xml_file", ",", "structure", ",", "ref_energy", ")", ":", "unique_dihedral_types", "=", "set", "(", ")", "xml_file", ".", "write", "(", "'<dihedral>\\n'", ")", "for", "dihedral", "in", "structure", ".", "rb_torsions", ...
Write dihedrals in the system. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 Reference energy for conversion to reduced units
[ "Write", "dihedrals", "in", "the", "system", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/hoomdxml.py#L270-L308
229,641
mosdef-hub/mbuild
mbuild/formats/hoomdxml.py
_write_rigid_information
def _write_rigid_information(xml_file, rigid_bodies): """Write rigid body information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written rigid_bodies : list, len=n_particles The rigid body that each particle belongs to (-1 for none) """ if not all(body is None for body in rigid_bodies): xml_file.write('<body>\n') for body in rigid_bodies: if body is None: body = -1 xml_file.write('{}\n'.format(int(body))) xml_file.write('</body>\n')
python
def _write_rigid_information(xml_file, rigid_bodies): if not all(body is None for body in rigid_bodies): xml_file.write('<body>\n') for body in rigid_bodies: if body is None: body = -1 xml_file.write('{}\n'.format(int(body))) xml_file.write('</body>\n')
[ "def", "_write_rigid_information", "(", "xml_file", ",", "rigid_bodies", ")", ":", "if", "not", "all", "(", "body", "is", "None", "for", "body", "in", "rigid_bodies", ")", ":", "xml_file", ".", "write", "(", "'<body>\\n'", ")", "for", "body", "in", "rigid_...
Write rigid body information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written rigid_bodies : list, len=n_particles The rigid body that each particle belongs to (-1 for none)
[ "Write", "rigid", "body", "information", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/hoomdxml.py#L311-L329
229,642
mosdef-hub/mbuild
mbuild/formats/hoomdxml.py
_write_box_information
def _write_box_information(xml_file, structure, ref_distance): """Write box information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 Reference energy for conversion to reduced units """ if np.allclose(structure.box[3:6], np.array([90, 90, 90])): box_str = '<box units="sigma" Lx="{}" Ly="{}" Lz="{}"/>\n' xml_file.write(box_str.format(*structure.box[:3] / ref_distance)) else: a, b, c = structure.box[0:3] / ref_distance alpha, beta, gamma = np.radians(structure.box[3:6]) lx = a xy = b * np.cos(gamma) xz = c * np.cos(beta) ly = np.sqrt(b**2 - xy**2) yz = (b*c*np.cos(alpha) - xy*xz) / ly lz = np.sqrt(c**2 - xz**2 - yz**2) box_str = '<box units="sigma" Lx="{}" Ly="{}" Lz="{}" xy="{}" xz="{}" yz="{}"/>\n' xml_file.write(box_str.format(lx, ly, lz, xy, xz, yz))
python
def _write_box_information(xml_file, structure, ref_distance): if np.allclose(structure.box[3:6], np.array([90, 90, 90])): box_str = '<box units="sigma" Lx="{}" Ly="{}" Lz="{}"/>\n' xml_file.write(box_str.format(*structure.box[:3] / ref_distance)) else: a, b, c = structure.box[0:3] / ref_distance alpha, beta, gamma = np.radians(structure.box[3:6]) lx = a xy = b * np.cos(gamma) xz = c * np.cos(beta) ly = np.sqrt(b**2 - xy**2) yz = (b*c*np.cos(alpha) - xy*xz) / ly lz = np.sqrt(c**2 - xz**2 - yz**2) box_str = '<box units="sigma" Lx="{}" Ly="{}" Lz="{}" xy="{}" xz="{}" yz="{}"/>\n' xml_file.write(box_str.format(lx, ly, lz, xy, xz, yz))
[ "def", "_write_box_information", "(", "xml_file", ",", "structure", ",", "ref_distance", ")", ":", "if", "np", ".", "allclose", "(", "structure", ".", "box", "[", "3", ":", "6", "]", ",", "np", ".", "array", "(", "[", "90", ",", "90", ",", "90", "]...
Write box information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 Reference energy for conversion to reduced units
[ "Write", "box", "information", "." ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/hoomdxml.py#L331-L358
229,643
mosdef-hub/mbuild
mbuild/port.py
Port.access_labels
def access_labels(self): """List of labels used to access the Port Returns ------- list of str Strings that can be used to access this Port relative to self.root """ access_labels = [] for referrer in self.referrers: referrer_labels = [key for key, val in self.root.labels.items() if val == referrer] port_labels = [key for key, val in referrer.labels.items() if val == self] if referrer is self.root: for label in port_labels: access_labels.append("['{}']".format(label)) for label in itertools.product(referrer_labels, port_labels): access_labels.append("['{}']".format("']['".join(label))) return access_labels
python
def access_labels(self): access_labels = [] for referrer in self.referrers: referrer_labels = [key for key, val in self.root.labels.items() if val == referrer] port_labels = [key for key, val in referrer.labels.items() if val == self] if referrer is self.root: for label in port_labels: access_labels.append("['{}']".format(label)) for label in itertools.product(referrer_labels, port_labels): access_labels.append("['{}']".format("']['".join(label))) return access_labels
[ "def", "access_labels", "(", "self", ")", ":", "access_labels", "=", "[", "]", "for", "referrer", "in", "self", ".", "referrers", ":", "referrer_labels", "=", "[", "key", "for", "key", ",", "val", "in", "self", ".", "root", ".", "labels", ".", "items",...
List of labels used to access the Port Returns ------- list of str Strings that can be used to access this Port relative to self.root
[ "List", "of", "labels", "used", "to", "access", "the", "Port" ]
dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/port.py#L98-L118
229,644
GeospatialPython/pyshp
shapefile.py
signed_area
def signed_area(coords): """Return the signed area enclosed by a ring using the linear time algorithm. A value >= 0 indicates a counter-clockwise oriented ring. """ xs, ys = map(list, zip(*coords)) xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0
python
def signed_area(coords): xs, ys = map(list, zip(*coords)) xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0
[ "def", "signed_area", "(", "coords", ")", ":", "xs", ",", "ys", "=", "map", "(", "list", ",", "zip", "(", "*", "coords", ")", ")", "xs", ".", "append", "(", "xs", "[", "1", "]", ")", "ys", ".", "append", "(", "ys", "[", "1", "]", ")", "retu...
Return the signed area enclosed by a ring using the linear time algorithm. A value >= 0 indicates a counter-clockwise oriented ring.
[ "Return", "the", "signed", "area", "enclosed", "by", "a", "ring", "using", "the", "linear", "time", "algorithm", ".", "A", "value", ">", "=", "0", "indicates", "a", "counter", "-", "clockwise", "oriented", "ring", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L159-L166
229,645
GeospatialPython/pyshp
shapefile.py
Reader.load
def load(self, shapefile=None): """Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file name as an argument.""" if shapefile: (shapeName, ext) = os.path.splitext(shapefile) self.shapeName = shapeName self.load_shp(shapeName) self.load_shx(shapeName) self.load_dbf(shapeName) if not (self.shp or self.dbf): raise ShapefileException("Unable to open %s.dbf or %s.shp." % (shapeName, shapeName)) if self.shp: self.__shpHeader() if self.dbf: self.__dbfHeader()
python
def load(self, shapefile=None): if shapefile: (shapeName, ext) = os.path.splitext(shapefile) self.shapeName = shapeName self.load_shp(shapeName) self.load_shx(shapeName) self.load_dbf(shapeName) if not (self.shp or self.dbf): raise ShapefileException("Unable to open %s.dbf or %s.shp." % (shapeName, shapeName)) if self.shp: self.__shpHeader() if self.dbf: self.__dbfHeader()
[ "def", "load", "(", "self", ",", "shapefile", "=", "None", ")", ":", "if", "shapefile", ":", "(", "shapeName", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "shapefile", ")", "self", ".", "shapeName", "=", "shapeName", "self", ".", ...
Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file name as an argument.
[ "Opens", "a", "shapefile", "from", "a", "filename", "or", "file", "-", "like", "object", ".", "Normally", "this", "method", "would", "be", "called", "by", "the", "constructor", "with", "the", "file", "name", "as", "an", "argument", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L635-L650
229,646
GeospatialPython/pyshp
shapefile.py
Reader.load_shp
def load_shp(self, shapefile_name): """ Attempts to load file with .shp extension as both lower and upper case """ shp_ext = 'shp' try: self.shp = open("%s.%s" % (shapefile_name, shp_ext), "rb") except IOError: try: self.shp = open("%s.%s" % (shapefile_name, shp_ext.upper()), "rb") except IOError: pass
python
def load_shp(self, shapefile_name): shp_ext = 'shp' try: self.shp = open("%s.%s" % (shapefile_name, shp_ext), "rb") except IOError: try: self.shp = open("%s.%s" % (shapefile_name, shp_ext.upper()), "rb") except IOError: pass
[ "def", "load_shp", "(", "self", ",", "shapefile_name", ")", ":", "shp_ext", "=", "'shp'", "try", ":", "self", ".", "shp", "=", "open", "(", "\"%s.%s\"", "%", "(", "shapefile_name", ",", "shp_ext", ")", ",", "\"rb\"", ")", "except", "IOError", ":", "try...
Attempts to load file with .shp extension as both lower and upper case
[ "Attempts", "to", "load", "file", "with", ".", "shp", "extension", "as", "both", "lower", "and", "upper", "case" ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L652-L663
229,647
GeospatialPython/pyshp
shapefile.py
Reader.load_shx
def load_shx(self, shapefile_name): """ Attempts to load file with .shx extension as both lower and upper case """ shx_ext = 'shx' try: self.shx = open("%s.%s" % (shapefile_name, shx_ext), "rb") except IOError: try: self.shx = open("%s.%s" % (shapefile_name, shx_ext.upper()), "rb") except IOError: pass
python
def load_shx(self, shapefile_name): shx_ext = 'shx' try: self.shx = open("%s.%s" % (shapefile_name, shx_ext), "rb") except IOError: try: self.shx = open("%s.%s" % (shapefile_name, shx_ext.upper()), "rb") except IOError: pass
[ "def", "load_shx", "(", "self", ",", "shapefile_name", ")", ":", "shx_ext", "=", "'shx'", "try", ":", "self", ".", "shx", "=", "open", "(", "\"%s.%s\"", "%", "(", "shapefile_name", ",", "shx_ext", ")", ",", "\"rb\"", ")", "except", "IOError", ":", "try...
Attempts to load file with .shx extension as both lower and upper case
[ "Attempts", "to", "load", "file", "with", ".", "shx", "extension", "as", "both", "lower", "and", "upper", "case" ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L665-L676
229,648
GeospatialPython/pyshp
shapefile.py
Reader.load_dbf
def load_dbf(self, shapefile_name): """ Attempts to load file with .dbf extension as both lower and upper case """ dbf_ext = 'dbf' try: self.dbf = open("%s.%s" % (shapefile_name, dbf_ext), "rb") except IOError: try: self.dbf = open("%s.%s" % (shapefile_name, dbf_ext.upper()), "rb") except IOError: pass
python
def load_dbf(self, shapefile_name): dbf_ext = 'dbf' try: self.dbf = open("%s.%s" % (shapefile_name, dbf_ext), "rb") except IOError: try: self.dbf = open("%s.%s" % (shapefile_name, dbf_ext.upper()), "rb") except IOError: pass
[ "def", "load_dbf", "(", "self", ",", "shapefile_name", ")", ":", "dbf_ext", "=", "'dbf'", "try", ":", "self", ".", "dbf", "=", "open", "(", "\"%s.%s\"", "%", "(", "shapefile_name", ",", "dbf_ext", ")", ",", "\"rb\"", ")", "except", "IOError", ":", "try...
Attempts to load file with .dbf extension as both lower and upper case
[ "Attempts", "to", "load", "file", "with", ".", "dbf", "extension", "as", "both", "lower", "and", "upper", "case" ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L678-L689
229,649
GeospatialPython/pyshp
shapefile.py
Reader.__getFileObj
def __getFileObj(self, f): """Checks to see if the requested shapefile file object is available. If not a ShapefileException is raised.""" if not f: raise ShapefileException("Shapefile Reader requires a shapefile or file-like object.") if self.shp and self.shpLength is None: self.load() if self.dbf and len(self.fields) == 0: self.load() return f
python
def __getFileObj(self, f): if not f: raise ShapefileException("Shapefile Reader requires a shapefile or file-like object.") if self.shp and self.shpLength is None: self.load() if self.dbf and len(self.fields) == 0: self.load() return f
[ "def", "__getFileObj", "(", "self", ",", "f", ")", ":", "if", "not", "f", ":", "raise", "ShapefileException", "(", "\"Shapefile Reader requires a shapefile or file-like object.\"", ")", "if", "self", ".", "shp", "and", "self", ".", "shpLength", "is", "None", ":"...
Checks to see if the requested shapefile file object is available. If not a ShapefileException is raised.
[ "Checks", "to", "see", "if", "the", "requested", "shapefile", "file", "object", "is", "available", ".", "If", "not", "a", "ShapefileException", "is", "raised", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L702-L711
229,650
GeospatialPython/pyshp
shapefile.py
Reader.__restrictIndex
def __restrictIndex(self, i): """Provides list-like handling of a record index with a clearer error message if the index is out of bounds.""" if self.numRecords: rmax = self.numRecords - 1 if abs(i) > rmax: raise IndexError("Shape or Record index out of range.") if i < 0: i = range(self.numRecords)[i] return i
python
def __restrictIndex(self, i): if self.numRecords: rmax = self.numRecords - 1 if abs(i) > rmax: raise IndexError("Shape or Record index out of range.") if i < 0: i = range(self.numRecords)[i] return i
[ "def", "__restrictIndex", "(", "self", ",", "i", ")", ":", "if", "self", ".", "numRecords", ":", "rmax", "=", "self", ".", "numRecords", "-", "1", "if", "abs", "(", "i", ")", ">", "rmax", ":", "raise", "IndexError", "(", "\"Shape or Record index out of r...
Provides list-like handling of a record index with a clearer error message if the index is out of bounds.
[ "Provides", "list", "-", "like", "handling", "of", "a", "record", "index", "with", "a", "clearer", "error", "message", "if", "the", "index", "is", "out", "of", "bounds", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L713-L721
229,651
GeospatialPython/pyshp
shapefile.py
Reader.iterShapes
def iterShapes(self): """Serves up shapes in a shapefile as an iterator. Useful for handling large shapefiles.""" shp = self.__getFileObj(self.shp) shp.seek(0,2) self.shpLength = shp.tell() shp.seek(100) while shp.tell() < self.shpLength: yield self.__shape()
python
def iterShapes(self): shp = self.__getFileObj(self.shp) shp.seek(0,2) self.shpLength = shp.tell() shp.seek(100) while shp.tell() < self.shpLength: yield self.__shape()
[ "def", "iterShapes", "(", "self", ")", ":", "shp", "=", "self", ".", "__getFileObj", "(", "self", ".", "shp", ")", "shp", ".", "seek", "(", "0", ",", "2", ")", "self", ".", "shpLength", "=", "shp", ".", "tell", "(", ")", "shp", ".", "seek", "("...
Serves up shapes in a shapefile as an iterator. Useful for handling large shapefiles.
[ "Serves", "up", "shapes", "in", "a", "shapefile", "as", "an", "iterator", ".", "Useful", "for", "handling", "large", "shapefiles", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L871-L879
229,652
GeospatialPython/pyshp
shapefile.py
Reader.iterRecords
def iterRecords(self): """Serves up records in a dbf file as an iterator. Useful for large shapefiles or dbf files.""" if self.numRecords is None: self.__dbfHeader() f = self.__getFileObj(self.dbf) f.seek(self.__dbfHdrLength) for i in xrange(self.numRecords): r = self.__record() if r: yield r
python
def iterRecords(self): if self.numRecords is None: self.__dbfHeader() f = self.__getFileObj(self.dbf) f.seek(self.__dbfHdrLength) for i in xrange(self.numRecords): r = self.__record() if r: yield r
[ "def", "iterRecords", "(", "self", ")", ":", "if", "self", ".", "numRecords", "is", "None", ":", "self", ".", "__dbfHeader", "(", ")", "f", "=", "self", ".", "__getFileObj", "(", "self", ".", "dbf", ")", "f", ".", "seek", "(", "self", ".", "__dbfHd...
Serves up records in a dbf file as an iterator. Useful for large shapefiles or dbf files.
[ "Serves", "up", "records", "in", "a", "dbf", "file", "as", "an", "iterator", ".", "Useful", "for", "large", "shapefiles", "or", "dbf", "files", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1017-L1027
229,653
GeospatialPython/pyshp
shapefile.py
Writer.close
def close(self): """ Write final shp, shx, and dbf headers, close opened files. """ # Check if any of the files have already been closed shp_open = self.shp and not (hasattr(self.shp, 'closed') and self.shp.closed) shx_open = self.shx and not (hasattr(self.shx, 'closed') and self.shx.closed) dbf_open = self.dbf and not (hasattr(self.dbf, 'closed') and self.dbf.closed) # Balance if already not balanced if self.shp and shp_open and self.dbf and dbf_open: if self.autoBalance: self.balance() if self.recNum != self.shpNum: raise ShapefileException("When saving both the dbf and shp file, " "the number of records (%s) must correspond " "with the number of shapes (%s)" % (self.recNum, self.shpNum)) # Fill in the blank headers if self.shp and shp_open: self.__shapefileHeader(self.shp, headerType='shp') if self.shx and shx_open: self.__shapefileHeader(self.shx, headerType='shx') # Update the dbf header with final length etc if self.dbf and dbf_open: self.__dbfHeader() # Close files, if target is a filepath if self.target: for attribute in (self.shp, self.shx, self.dbf): if hasattr(attribute, 'close'): try: attribute.close() except IOError: pass
python
def close(self): # Check if any of the files have already been closed shp_open = self.shp and not (hasattr(self.shp, 'closed') and self.shp.closed) shx_open = self.shx and not (hasattr(self.shx, 'closed') and self.shx.closed) dbf_open = self.dbf and not (hasattr(self.dbf, 'closed') and self.dbf.closed) # Balance if already not balanced if self.shp and shp_open and self.dbf and dbf_open: if self.autoBalance: self.balance() if self.recNum != self.shpNum: raise ShapefileException("When saving both the dbf and shp file, " "the number of records (%s) must correspond " "with the number of shapes (%s)" % (self.recNum, self.shpNum)) # Fill in the blank headers if self.shp and shp_open: self.__shapefileHeader(self.shp, headerType='shp') if self.shx and shx_open: self.__shapefileHeader(self.shx, headerType='shx') # Update the dbf header with final length etc if self.dbf and dbf_open: self.__dbfHeader() # Close files, if target is a filepath if self.target: for attribute in (self.shp, self.shx, self.dbf): if hasattr(attribute, 'close'): try: attribute.close() except IOError: pass
[ "def", "close", "(", "self", ")", ":", "# Check if any of the files have already been closed\r", "shp_open", "=", "self", ".", "shp", "and", "not", "(", "hasattr", "(", "self", ".", "shp", ",", "'closed'", ")", "and", "self", ".", "shp", ".", "closed", ")", ...
Write final shp, shx, and dbf headers, close opened files.
[ "Write", "final", "shp", "shx", "and", "dbf", "headers", "close", "opened", "files", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1106-L1140
229,654
GeospatialPython/pyshp
shapefile.py
Writer.__getFileObj
def __getFileObj(self, f): """Safety handler to verify file-like objects""" if not f: raise ShapefileException("No file-like object available.") elif hasattr(f, "write"): return f else: pth = os.path.split(f)[0] if pth and not os.path.exists(pth): os.makedirs(pth) return open(f, "wb+")
python
def __getFileObj(self, f): if not f: raise ShapefileException("No file-like object available.") elif hasattr(f, "write"): return f else: pth = os.path.split(f)[0] if pth and not os.path.exists(pth): os.makedirs(pth) return open(f, "wb+")
[ "def", "__getFileObj", "(", "self", ",", "f", ")", ":", "if", "not", "f", ":", "raise", "ShapefileException", "(", "\"No file-like object available.\"", ")", "elif", "hasattr", "(", "f", ",", "\"write\"", ")", ":", "return", "f", "else", ":", "pth", "=", ...
Safety handler to verify file-like objects
[ "Safety", "handler", "to", "verify", "file", "-", "like", "objects" ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1142-L1152
229,655
GeospatialPython/pyshp
shapefile.py
Writer.balance
def balance(self): """Adds corresponding empty attributes or null geometry records depending on which type of record was created to make sure all three files are in synch.""" while self.recNum > self.shpNum: self.null() while self.recNum < self.shpNum: self.record()
python
def balance(self): while self.recNum > self.shpNum: self.null() while self.recNum < self.shpNum: self.record()
[ "def", "balance", "(", "self", ")", ":", "while", "self", ".", "recNum", ">", "self", ".", "shpNum", ":", "self", ".", "null", "(", ")", "while", "self", ".", "recNum", "<", "self", ".", "shpNum", ":", "self", ".", "record", "(", ")" ]
Adds corresponding empty attributes or null geometry records depending on which type of record was created to make sure all three files are in synch.
[ "Adds", "corresponding", "empty", "attributes", "or", "null", "geometry", "records", "depending", "on", "which", "type", "of", "record", "was", "created", "to", "make", "sure", "all", "three", "files", "are", "in", "synch", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1602-L1609
229,656
GeospatialPython/pyshp
shapefile.py
Writer.point
def point(self, x, y): """Creates a POINT shape.""" shapeType = POINT pointShape = Shape(shapeType) pointShape.points.append([x, y]) self.shape(pointShape)
python
def point(self, x, y): shapeType = POINT pointShape = Shape(shapeType) pointShape.points.append([x, y]) self.shape(pointShape)
[ "def", "point", "(", "self", ",", "x", ",", "y", ")", ":", "shapeType", "=", "POINT", "pointShape", "=", "Shape", "(", "shapeType", ")", "pointShape", ".", "points", ".", "append", "(", "[", "x", ",", "y", "]", ")", "self", ".", "shape", "(", "po...
Creates a POINT shape.
[ "Creates", "a", "POINT", "shape", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1617-L1622
229,657
GeospatialPython/pyshp
shapefile.py
Writer.multipoint
def multipoint(self, points): """Creates a MULTIPOINT shape. Points is a list of xy values.""" shapeType = MULTIPOINT points = [points] # nest the points inside a list to be compatible with the generic shapeparts method self._shapeparts(parts=points, shapeType=shapeType)
python
def multipoint(self, points): shapeType = MULTIPOINT points = [points] # nest the points inside a list to be compatible with the generic shapeparts method self._shapeparts(parts=points, shapeType=shapeType)
[ "def", "multipoint", "(", "self", ",", "points", ")", ":", "shapeType", "=", "MULTIPOINT", "points", "=", "[", "points", "]", "# nest the points inside a list to be compatible with the generic shapeparts method\r", "self", ".", "_shapeparts", "(", "parts", "=", "points"...
Creates a MULTIPOINT shape. Points is a list of xy values.
[ "Creates", "a", "MULTIPOINT", "shape", ".", "Points", "is", "a", "list", "of", "xy", "values", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1642-L1647
229,658
GeospatialPython/pyshp
shapefile.py
Writer.line
def line(self, lines): """Creates a POLYLINE shape. Lines is a collection of lines, each made up of a list of xy values.""" shapeType = POLYLINE self._shapeparts(parts=lines, shapeType=shapeType)
python
def line(self, lines): shapeType = POLYLINE self._shapeparts(parts=lines, shapeType=shapeType)
[ "def", "line", "(", "self", ",", "lines", ")", ":", "shapeType", "=", "POLYLINE", "self", ".", "_shapeparts", "(", "parts", "=", "lines", ",", "shapeType", "=", "shapeType", ")" ]
Creates a POLYLINE shape. Lines is a collection of lines, each made up of a list of xy values.
[ "Creates", "a", "POLYLINE", "shape", ".", "Lines", "is", "a", "collection", "of", "lines", "each", "made", "up", "of", "a", "list", "of", "xy", "values", "." ]
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1667-L1671
229,659
GeospatialPython/pyshp
shapefile.py
Writer.poly
def poly(self, polys): """Creates a POLYGON shape. Polys is a collection of polygons, each made up of a list of xy values. Note that for ordinary polygons the coordinates must run in a clockwise direction. If some of the polygons are holes, these must run in a counterclockwise direction.""" shapeType = POLYGON self._shapeparts(parts=polys, shapeType=shapeType)
python
def poly(self, polys): shapeType = POLYGON self._shapeparts(parts=polys, shapeType=shapeType)
[ "def", "poly", "(", "self", ",", "polys", ")", ":", "shapeType", "=", "POLYGON", "self", ".", "_shapeparts", "(", "parts", "=", "polys", ",", "shapeType", "=", "shapeType", ")" ]
Creates a POLYGON shape. Polys is a collection of polygons, each made up of a list of xy values. Note that for ordinary polygons the coordinates must run in a clockwise direction. If some of the polygons are holes, these must run in a counterclockwise direction.
[ "Creates", "a", "POLYGON", "shape", ".", "Polys", "is", "a", "collection", "of", "polygons", "each", "made", "up", "of", "a", "list", "of", "xy", "values", ".", "Note", "that", "for", "ordinary", "polygons", "the", "coordinates", "must", "run", "in", "a"...
71231ddc5aa54f155d4f0563c56006fffbfc84e7
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1689-L1695
229,660
jrmontag/STLDecompose
stldecompose/stl.py
forecast
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs): """Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting function ``fc_func``, optionally including the calculated seasonality. This is an additive model, Y[t] = T[t] + S[t] + e[t] Args: stl (a modified statsmodels.tsa.seasonal.DecomposeResult): STL decomposition of observed time series created using the ``stldecompose.decompose()`` method. fc_func (function): Function which takes an array of observations and returns a single valued forecast for the next point. steps (int, optional): Number of forward steps to include in the forecast seasonal (bool, optional): Include seasonal component in forecast fc_func_kwargs: keyword arguments All remaining arguments are passed to the forecasting function ``fc_func`` Returns: forecast_frame (pd.Dataframe): A ``pandas.Dataframe`` containing forecast values and a DatetimeIndex matching the observed index. """ # container for forecast values forecast_array = np.array([]) # forecast trend # unpack precalculated trend array stl frame trend_array = stl.trend # iteratively forecast trend ("seasonally adjusted") component # note: this loop can be slow for step in range(steps): # make this prediction on all available data pred = fc_func(np.append(trend_array, forecast_array), **fc_func_kwargs) # add this prediction to current array forecast_array = np.append(forecast_array, pred) col_name = fc_func.__name__ # forecast start and index are determined by observed data observed_timedelta = stl.observed.index[-1] - stl.observed.index[-2] forecast_idx_start = stl.observed.index[-1] + observed_timedelta forecast_idx = pd.date_range(start=forecast_idx_start, periods=steps, freq=pd.tseries.frequencies.to_offset(observed_timedelta)) # (optionally) forecast seasonal & combine if seasonal: # track index and value of max correlation seasonal_ix = 0 max_correlation = -np.inf # loop over indexes=length of period avgs detrended_array = np.asanyarray(stl.observed - stl.trend).squeeze() for i, x in enumerate(stl.period_averages): # work slices backward from end of detrended observations if i == 0: # slicing w/ [x:-0] doesn't work detrended_slice = detrended_array[-len(stl.period_averages):] else: detrended_slice = detrended_array[-(len(stl.period_averages) + i):-i] # calculate corr b/w period_avgs and detrend_slice this_correlation = np.correlate(detrended_slice, stl.period_averages)[0] if this_correlation > max_correlation: # update ix and max correlation max_correlation = this_correlation seasonal_ix = i # roll seasonal signal to matching phase rolled_period_averages = np.roll(stl.period_averages, -seasonal_ix) # tile as many time as needed to reach "steps", then truncate tiled_averages = np.tile(rolled_period_averages, (steps // len(stl.period_averages) + 1))[:steps] # add seasonal values to previous forecast forecast_array += tiled_averages col_name += '+seasonal' # combine data array with index into named dataframe forecast_frame = pd.DataFrame(data=forecast_array, index=forecast_idx) forecast_frame.columns = [col_name] return forecast_frame
python
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs): # container for forecast values forecast_array = np.array([]) # forecast trend # unpack precalculated trend array stl frame trend_array = stl.trend # iteratively forecast trend ("seasonally adjusted") component # note: this loop can be slow for step in range(steps): # make this prediction on all available data pred = fc_func(np.append(trend_array, forecast_array), **fc_func_kwargs) # add this prediction to current array forecast_array = np.append(forecast_array, pred) col_name = fc_func.__name__ # forecast start and index are determined by observed data observed_timedelta = stl.observed.index[-1] - stl.observed.index[-2] forecast_idx_start = stl.observed.index[-1] + observed_timedelta forecast_idx = pd.date_range(start=forecast_idx_start, periods=steps, freq=pd.tseries.frequencies.to_offset(observed_timedelta)) # (optionally) forecast seasonal & combine if seasonal: # track index and value of max correlation seasonal_ix = 0 max_correlation = -np.inf # loop over indexes=length of period avgs detrended_array = np.asanyarray(stl.observed - stl.trend).squeeze() for i, x in enumerate(stl.period_averages): # work slices backward from end of detrended observations if i == 0: # slicing w/ [x:-0] doesn't work detrended_slice = detrended_array[-len(stl.period_averages):] else: detrended_slice = detrended_array[-(len(stl.period_averages) + i):-i] # calculate corr b/w period_avgs and detrend_slice this_correlation = np.correlate(detrended_slice, stl.period_averages)[0] if this_correlation > max_correlation: # update ix and max correlation max_correlation = this_correlation seasonal_ix = i # roll seasonal signal to matching phase rolled_period_averages = np.roll(stl.period_averages, -seasonal_ix) # tile as many time as needed to reach "steps", then truncate tiled_averages = np.tile(rolled_period_averages, (steps // len(stl.period_averages) + 1))[:steps] # add seasonal values to previous forecast forecast_array += tiled_averages col_name += '+seasonal' # combine data array with index into named dataframe forecast_frame = pd.DataFrame(data=forecast_array, index=forecast_idx) forecast_frame.columns = [col_name] return forecast_frame
[ "def", "forecast", "(", "stl", ",", "fc_func", ",", "steps", "=", "10", ",", "seasonal", "=", "False", ",", "*", "*", "fc_func_kwargs", ")", ":", "# container for forecast values", "forecast_array", "=", "np", ".", "array", "(", "[", "]", ")", "# forecast ...
Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting function ``fc_func``, optionally including the calculated seasonality. This is an additive model, Y[t] = T[t] + S[t] + e[t] Args: stl (a modified statsmodels.tsa.seasonal.DecomposeResult): STL decomposition of observed time series created using the ``stldecompose.decompose()`` method. fc_func (function): Function which takes an array of observations and returns a single valued forecast for the next point. steps (int, optional): Number of forward steps to include in the forecast seasonal (bool, optional): Include seasonal component in forecast fc_func_kwargs: keyword arguments All remaining arguments are passed to the forecasting function ``fc_func`` Returns: forecast_frame (pd.Dataframe): A ``pandas.Dataframe`` containing forecast values and a DatetimeIndex matching the observed index.
[ "Forecast", "the", "given", "decomposition", "stl", "forward", "by", "steps", "steps", "using", "the", "forecasting", "function", "fc_func", "optionally", "including", "the", "calculated", "seasonality", "." ]
f53f89dab4b13618c1cf13f88a01e3e3dc8abdec
https://github.com/jrmontag/STLDecompose/blob/f53f89dab4b13618c1cf13f88a01e3e3dc8abdec/stldecompose/stl.py#L71-L146
229,661
jrmontag/STLDecompose
stldecompose/forecast_funcs.py
mean
def mean(data, n=3, **kwargs): """The mean forecast for the next point is the mean value of the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate the mean Returns: float: a single-valued forecast for the next value in the series. """ # don't start averaging until we've seen n points if len(data[-n:]) < n: forecast = np.nan else: # nb: we'll keep the forecast as a float forecast = np.mean(data[-n:]) return forecast
python
def mean(data, n=3, **kwargs): # don't start averaging until we've seen n points if len(data[-n:]) < n: forecast = np.nan else: # nb: we'll keep the forecast as a float forecast = np.mean(data[-n:]) return forecast
[ "def", "mean", "(", "data", ",", "n", "=", "3", ",", "*", "*", "kwargs", ")", ":", "# don't start averaging until we've seen n points", "if", "len", "(", "data", "[", "-", "n", ":", "]", ")", "<", "n", ":", "forecast", "=", "np", ".", "nan", "else", ...
The mean forecast for the next point is the mean value of the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate the mean Returns: float: a single-valued forecast for the next value in the series.
[ "The", "mean", "forecast", "for", "the", "next", "point", "is", "the", "mean", "value", "of", "the", "previous", "n", "points", "in", "the", "series", "." ]
f53f89dab4b13618c1cf13f88a01e3e3dc8abdec
https://github.com/jrmontag/STLDecompose/blob/f53f89dab4b13618c1cf13f88a01e3e3dc8abdec/stldecompose/forecast_funcs.py#L41-L58
229,662
jrmontag/STLDecompose
stldecompose/forecast_funcs.py
drift
def drift(data, n=3, **kwargs): """The drift forecast for the next point is a linear extrapolation from the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate linear model for extrapolation Returns: float: a single-valued forecast for the next value in the series. """ yi = data[-n] yf = data[-1] slope = (yf - yi) / (n - 1) forecast = yf + slope return forecast
python
def drift(data, n=3, **kwargs): yi = data[-n] yf = data[-1] slope = (yf - yi) / (n - 1) forecast = yf + slope return forecast
[ "def", "drift", "(", "data", ",", "n", "=", "3", ",", "*", "*", "kwargs", ")", ":", "yi", "=", "data", "[", "-", "n", "]", "yf", "=", "data", "[", "-", "1", "]", "slope", "=", "(", "yf", "-", "yi", ")", "/", "(", "n", "-", "1", ")", "...
The drift forecast for the next point is a linear extrapolation from the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate linear model for extrapolation Returns: float: a single-valued forecast for the next value in the series.
[ "The", "drift", "forecast", "for", "the", "next", "point", "is", "a", "linear", "extrapolation", "from", "the", "previous", "n", "points", "in", "the", "series", "." ]
f53f89dab4b13618c1cf13f88a01e3e3dc8abdec
https://github.com/jrmontag/STLDecompose/blob/f53f89dab4b13618c1cf13f88a01e3e3dc8abdec/stldecompose/forecast_funcs.py#L61-L76
229,663
soundcloud/soundcloud-python
soundcloud/client.py
Client.exchange_token
def exchange_token(self, code): """Given the value of the code parameter, request an access token.""" url = '%s%s/oauth2/token' % (self.scheme, self.host) options = { 'grant_type': 'authorization_code', 'redirect_uri': self._redirect_uri(), 'client_id': self.options.get('client_id'), 'client_secret': self.options.get('client_secret'), 'code': code, } options.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) self.token = wrapped_resource( make_request('post', url, options)) self.access_token = self.token.access_token return self.token
python
def exchange_token(self, code): url = '%s%s/oauth2/token' % (self.scheme, self.host) options = { 'grant_type': 'authorization_code', 'redirect_uri': self._redirect_uri(), 'client_id': self.options.get('client_id'), 'client_secret': self.options.get('client_secret'), 'code': code, } options.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) self.token = wrapped_resource( make_request('post', url, options)) self.access_token = self.token.access_token return self.token
[ "def", "exchange_token", "(", "self", ",", "code", ")", ":", "url", "=", "'%s%s/oauth2/token'", "%", "(", "self", ".", "scheme", ",", "self", ".", "host", ")", "options", "=", "{", "'grant_type'", ":", "'authorization_code'", ",", "'redirect_uri'", ":", "s...
Given the value of the code parameter, request an access token.
[ "Given", "the", "value", "of", "the", "code", "parameter", "request", "an", "access", "token", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/client.py#L48-L65
229,664
soundcloud/soundcloud-python
soundcloud/client.py
Client._authorization_code_flow
def _authorization_code_flow(self): """Build the the auth URL so the user can authorize the app.""" options = { 'scope': getattr(self, 'scope', 'non-expiring'), 'client_id': self.options.get('client_id'), 'response_type': 'code', 'redirect_uri': self._redirect_uri() } url = '%s%s/connect' % (self.scheme, self.host) self._authorize_url = '%s?%s' % (url, urlencode(options))
python
def _authorization_code_flow(self): options = { 'scope': getattr(self, 'scope', 'non-expiring'), 'client_id': self.options.get('client_id'), 'response_type': 'code', 'redirect_uri': self._redirect_uri() } url = '%s%s/connect' % (self.scheme, self.host) self._authorize_url = '%s?%s' % (url, urlencode(options))
[ "def", "_authorization_code_flow", "(", "self", ")", ":", "options", "=", "{", "'scope'", ":", "getattr", "(", "self", ",", "'scope'", ",", "'non-expiring'", ")", ",", "'client_id'", ":", "self", ".", "options", ".", "get", "(", "'client_id'", ")", ",", ...
Build the the auth URL so the user can authorize the app.
[ "Build", "the", "the", "auth", "URL", "so", "the", "user", "can", "authorize", "the", "app", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/client.py#L71-L80
229,665
soundcloud/soundcloud-python
soundcloud/client.py
Client._refresh_token_flow
def _refresh_token_flow(self): """Given a refresh token, obtain a new access token.""" url = '%s%s/oauth2/token' % (self.scheme, self.host) options = { 'grant_type': 'refresh_token', 'client_id': self.options.get('client_id'), 'client_secret': self.options.get('client_secret'), 'refresh_token': self.options.get('refresh_token') } options.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) self.token = wrapped_resource( make_request('post', url, options)) self.access_token = self.token.access_token
python
def _refresh_token_flow(self): url = '%s%s/oauth2/token' % (self.scheme, self.host) options = { 'grant_type': 'refresh_token', 'client_id': self.options.get('client_id'), 'client_secret': self.options.get('client_secret'), 'refresh_token': self.options.get('refresh_token') } options.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) self.token = wrapped_resource( make_request('post', url, options)) self.access_token = self.token.access_token
[ "def", "_refresh_token_flow", "(", "self", ")", ":", "url", "=", "'%s%s/oauth2/token'", "%", "(", "self", ".", "scheme", ",", "self", ".", "host", ")", "options", "=", "{", "'grant_type'", ":", "'refresh_token'", ",", "'client_id'", ":", "self", ".", "opti...
Given a refresh token, obtain a new access token.
[ "Given", "a", "refresh", "token", "obtain", "a", "new", "access", "token", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/client.py#L82-L97
229,666
soundcloud/soundcloud-python
soundcloud/client.py
Client._request
def _request(self, method, resource, **kwargs): """Given an HTTP method, a resource name and kwargs, construct a request and return the response. """ url = self._resolve_resource_name(resource) if hasattr(self, 'access_token'): kwargs.update(dict(oauth_token=self.access_token)) if hasattr(self, 'client_id'): kwargs.update(dict(client_id=self.client_id)) kwargs.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) return wrapped_resource(make_request(method, url, kwargs))
python
def _request(self, method, resource, **kwargs): url = self._resolve_resource_name(resource) if hasattr(self, 'access_token'): kwargs.update(dict(oauth_token=self.access_token)) if hasattr(self, 'client_id'): kwargs.update(dict(client_id=self.client_id)) kwargs.update({ 'verify_ssl': self.options.get('verify_ssl', True), 'proxies': self.options.get('proxies', None) }) return wrapped_resource(make_request(method, url, kwargs))
[ "def", "_request", "(", "self", ",", "method", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "_resolve_resource_name", "(", "resource", ")", "if", "hasattr", "(", "self", ",", "'access_token'", ")", ":", "kwargs", ".", "u...
Given an HTTP method, a resource name and kwargs, construct a request and return the response.
[ "Given", "an", "HTTP", "method", "a", "resource", "name", "and", "kwargs", "construct", "a", "request", "and", "return", "the", "response", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/client.py#L118-L133
229,667
soundcloud/soundcloud-python
soundcloud/request.py
extract_files_from_dict
def extract_files_from_dict(d): """Return any file objects from the provided dict. >>> extract_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... }}) # doctest:+ELLIPSIS {'track': {'asset_data': <...}} """ files = {} for key, value in six.iteritems(d): if isinstance(value, dict): files[key] = extract_files_from_dict(value) elif is_file_like(value): files[key] = value return files
python
def extract_files_from_dict(d): files = {} for key, value in six.iteritems(d): if isinstance(value, dict): files[key] = extract_files_from_dict(value) elif is_file_like(value): files[key] = value return files
[ "def", "extract_files_from_dict", "(", "d", ")", ":", "files", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "d", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "files", "[", "key", "]", "=", "...
Return any file objects from the provided dict. >>> extract_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... }}) # doctest:+ELLIPSIS {'track': {'asset_data': <...}}
[ "Return", "any", "file", "objects", "from", "the", "provided", "dict", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/request.py#L19-L36
229,668
soundcloud/soundcloud-python
soundcloud/request.py
remove_files_from_dict
def remove_files_from_dict(d): """Return the provided dict with any file objects removed. >>> remove_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... } ... }) == {'track': {'title': 'bar'}, 'oauth_token': 'foo'} ... # doctest:+ELLIPSIS True """ file_free = {} for key, value in six.iteritems(d): if isinstance(value, dict): file_free[key] = remove_files_from_dict(value) elif not is_file_like(value): if hasattr(value, '__iter__'): file_free[key] = value else: if hasattr(value, 'encode'): file_free[key] = value.encode('utf-8') else: file_free[key] = str(value) return file_free
python
def remove_files_from_dict(d): file_free = {} for key, value in six.iteritems(d): if isinstance(value, dict): file_free[key] = remove_files_from_dict(value) elif not is_file_like(value): if hasattr(value, '__iter__'): file_free[key] = value else: if hasattr(value, 'encode'): file_free[key] = value.encode('utf-8') else: file_free[key] = str(value) return file_free
[ "def", "remove_files_from_dict", "(", "d", ")", ":", "file_free", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "d", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "file_free", "[", "key", "]", "...
Return the provided dict with any file objects removed. >>> remove_files_from_dict({ ... 'oauth_token': 'foo', ... 'track': { ... 'title': 'bar', ... 'asset_data': open('setup.py', 'rb') ... } ... }) == {'track': {'title': 'bar'}, 'oauth_token': 'foo'} ... # doctest:+ELLIPSIS True
[ "Return", "the", "provided", "dict", "with", "any", "file", "objects", "removed", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/request.py#L39-L64
229,669
soundcloud/soundcloud-python
soundcloud/request.py
namespaced_query_string
def namespaced_query_string(d, prefix=""): """Transform a nested dict into a string with namespaced query params. >>> namespaced_query_string({ ... 'oauth_token': 'foo', ... 'track': {'title': 'bar', 'sharing': 'private'}}) == { ... 'track[sharing]': 'private', ... 'oauth_token': 'foo', ... 'track[title]': 'bar'} # doctest:+ELLIPSIS True """ qs = {} prefixed = lambda k: prefix and "%s[%s]" % (prefix, k) or k for key, value in six.iteritems(d): if isinstance(value, dict): qs.update(namespaced_query_string(value, prefix=key)) else: qs[prefixed(key)] = value return qs
python
def namespaced_query_string(d, prefix=""): qs = {} prefixed = lambda k: prefix and "%s[%s]" % (prefix, k) or k for key, value in six.iteritems(d): if isinstance(value, dict): qs.update(namespaced_query_string(value, prefix=key)) else: qs[prefixed(key)] = value return qs
[ "def", "namespaced_query_string", "(", "d", ",", "prefix", "=", "\"\"", ")", ":", "qs", "=", "{", "}", "prefixed", "=", "lambda", "k", ":", "prefix", "and", "\"%s[%s]\"", "%", "(", "prefix", ",", "k", ")", "or", "k", "for", "key", ",", "value", "in...
Transform a nested dict into a string with namespaced query params. >>> namespaced_query_string({ ... 'oauth_token': 'foo', ... 'track': {'title': 'bar', 'sharing': 'private'}}) == { ... 'track[sharing]': 'private', ... 'oauth_token': 'foo', ... 'track[title]': 'bar'} # doctest:+ELLIPSIS True
[ "Transform", "a", "nested", "dict", "into", "a", "string", "with", "namespaced", "query", "params", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/request.py#L67-L85
229,670
soundcloud/soundcloud-python
soundcloud/request.py
make_request
def make_request(method, url, params): """Make an HTTP request, formatting params as required.""" empty = [] # TODO # del params[key] # without list for key, value in six.iteritems(params): if value is None: empty.append(key) for key in empty: del params[key] # allow caller to disable automatic following of redirects allow_redirects = params.get('allow_redirects', True) kwargs = { 'allow_redirects': allow_redirects, 'headers': { 'User-Agent': soundcloud.USER_AGENT } } # options, not params if 'verify_ssl' in params: if params['verify_ssl'] is False: kwargs['verify'] = params['verify_ssl'] del params['verify_ssl'] if 'proxies' in params: kwargs['proxies'] = params['proxies'] del params['proxies'] if 'allow_redirects' in params: del params['allow_redirects'] params = hashconversions.to_params(params) files = namespaced_query_string(extract_files_from_dict(params)) data = namespaced_query_string(remove_files_from_dict(params)) request_func = getattr(requests, method, None) if request_func is None: raise TypeError('Unknown method: %s' % (method,)) if method == 'get': kwargs['headers']['Accept'] = 'application/json' qs = urlencode(data) if '?' in url: url_qs = '%s&%s' % (url, qs) else: url_qs = '%s?%s' % (url, qs) result = request_func(url_qs, **kwargs) else: kwargs['data'] = data if files: kwargs['files'] = files result = request_func(url, **kwargs) # if redirects are disabled, don't raise for 301 / 302 if result.status_code in (301, 302): if allow_redirects: result.raise_for_status() else: result.raise_for_status() return result
python
def make_request(method, url, params): empty = [] # TODO # del params[key] # without list for key, value in six.iteritems(params): if value is None: empty.append(key) for key in empty: del params[key] # allow caller to disable automatic following of redirects allow_redirects = params.get('allow_redirects', True) kwargs = { 'allow_redirects': allow_redirects, 'headers': { 'User-Agent': soundcloud.USER_AGENT } } # options, not params if 'verify_ssl' in params: if params['verify_ssl'] is False: kwargs['verify'] = params['verify_ssl'] del params['verify_ssl'] if 'proxies' in params: kwargs['proxies'] = params['proxies'] del params['proxies'] if 'allow_redirects' in params: del params['allow_redirects'] params = hashconversions.to_params(params) files = namespaced_query_string(extract_files_from_dict(params)) data = namespaced_query_string(remove_files_from_dict(params)) request_func = getattr(requests, method, None) if request_func is None: raise TypeError('Unknown method: %s' % (method,)) if method == 'get': kwargs['headers']['Accept'] = 'application/json' qs = urlencode(data) if '?' in url: url_qs = '%s&%s' % (url, qs) else: url_qs = '%s?%s' % (url, qs) result = request_func(url_qs, **kwargs) else: kwargs['data'] = data if files: kwargs['files'] = files result = request_func(url, **kwargs) # if redirects are disabled, don't raise for 301 / 302 if result.status_code in (301, 302): if allow_redirects: result.raise_for_status() else: result.raise_for_status() return result
[ "def", "make_request", "(", "method", ",", "url", ",", "params", ")", ":", "empty", "=", "[", "]", "# TODO", "# del params[key]", "# without list", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "params", ")", ":", "if", "value", "is", ...
Make an HTTP request, formatting params as required.
[ "Make", "an", "HTTP", "request", "formatting", "params", "as", "required", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/request.py#L88-L149
229,671
soundcloud/soundcloud-python
soundcloud/resource.py
wrapped_resource
def wrapped_resource(response): """Return a response wrapped in the appropriate wrapper type. Lists will be returned as a ```ResourceList``` instance, dicts will be returned as a ```Resource``` instance. """ # decode response text, assuming utf-8 if unset response_content = response.content.decode(response.encoding or 'utf-8') try: content = json.loads(response_content) except ValueError: # not JSON content = response_content if isinstance(content, list): result = ResourceList(content) else: result = Resource(content) if hasattr(result, 'collection'): result.collection = ResourceList(result.collection) result.raw_data = response_content for attr in ('encoding', 'url', 'status_code', 'reason'): setattr(result, attr, getattr(response, attr)) return result
python
def wrapped_resource(response): # decode response text, assuming utf-8 if unset response_content = response.content.decode(response.encoding or 'utf-8') try: content = json.loads(response_content) except ValueError: # not JSON content = response_content if isinstance(content, list): result = ResourceList(content) else: result = Resource(content) if hasattr(result, 'collection'): result.collection = ResourceList(result.collection) result.raw_data = response_content for attr in ('encoding', 'url', 'status_code', 'reason'): setattr(result, attr, getattr(response, attr)) return result
[ "def", "wrapped_resource", "(", "response", ")", ":", "# decode response text, assuming utf-8 if unset", "response_content", "=", "response", ".", "content", ".", "decode", "(", "response", ".", "encoding", "or", "'utf-8'", ")", "try", ":", "content", "=", "json", ...
Return a response wrapped in the appropriate wrapper type. Lists will be returned as a ```ResourceList``` instance, dicts will be returned as a ```Resource``` instance.
[ "Return", "a", "response", "wrapped", "in", "the", "appropriate", "wrapper", "type", "." ]
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/resource.py#L50-L75
229,672
soundcloud/soundcloud-python
soundcloud/hashconversions.py
normalize_param
def normalize_param(key, value): """Convert a set of key, value parameters into a dictionary suitable for passing into requests. This will convert lists into the syntax required by SoundCloud. Heavily lifted from HTTParty. >>> normalize_param('playlist', { ... 'title': 'foo', ... 'sharing': 'private', ... 'tracks': [ ... {id: 1234}, {id: 4567} ... ]}) == { ... u'playlist[tracks][][<built-in function id>]': [1234, 4567], ... u'playlist[sharing]': 'private', ... u'playlist[title]': 'foo'} # doctest:+ELLIPSIS True >>> normalize_param('oauth_token', 'foo') {'oauth_token': 'foo'} >>> normalize_param('playlist[tracks]', [1234, 4567]) == { ... u'playlist[tracks][]': [1234, 4567]} True """ params = {} stack = [] if isinstance(value, list): normalized = [normalize_param(u"{0[key]}[]".format(dict(key=key)), e) for e in value] keys = [item for sublist in tuple(h.keys() for h in normalized) for item in sublist] lists = {} if len(keys) != len(set(keys)): duplicates = [x for x, y in collections.Counter(keys).items() if y > 1] for dup in duplicates: lists[dup] = [h[dup] for h in normalized] for h in normalized: del h[dup] params.update(dict((k, v) for d in normalized for (k, v) in d.items())) params.update(lists) elif isinstance(value, dict): stack.append([key, value]) else: params.update({key: value}) for (parent, hash) in stack: for (key, value) in six.iteritems(hash): if isinstance(value, dict): stack.append([u"{0[parent]}[{0[key]}]".format(dict(parent=parent, key=key)), value]) else: params.update(normalize_param(u"{0[parent]}[{0[key]}]".format(dict(parent=parent, key=key)), value)) return params
python
def normalize_param(key, value): params = {} stack = [] if isinstance(value, list): normalized = [normalize_param(u"{0[key]}[]".format(dict(key=key)), e) for e in value] keys = [item for sublist in tuple(h.keys() for h in normalized) for item in sublist] lists = {} if len(keys) != len(set(keys)): duplicates = [x for x, y in collections.Counter(keys).items() if y > 1] for dup in duplicates: lists[dup] = [h[dup] for h in normalized] for h in normalized: del h[dup] params.update(dict((k, v) for d in normalized for (k, v) in d.items())) params.update(lists) elif isinstance(value, dict): stack.append([key, value]) else: params.update({key: value}) for (parent, hash) in stack: for (key, value) in six.iteritems(hash): if isinstance(value, dict): stack.append([u"{0[parent]}[{0[key]}]".format(dict(parent=parent, key=key)), value]) else: params.update(normalize_param(u"{0[parent]}[{0[key]}]".format(dict(parent=parent, key=key)), value)) return params
[ "def", "normalize_param", "(", "key", ",", "value", ")", ":", "params", "=", "{", "}", "stack", "=", "[", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "normalized", "=", "[", "normalize_param", "(", "u\"{0[key]}[]\"", ".", "format", "(...
Convert a set of key, value parameters into a dictionary suitable for passing into requests. This will convert lists into the syntax required by SoundCloud. Heavily lifted from HTTParty. >>> normalize_param('playlist', { ... 'title': 'foo', ... 'sharing': 'private', ... 'tracks': [ ... {id: 1234}, {id: 4567} ... ]}) == { ... u'playlist[tracks][][<built-in function id>]': [1234, 4567], ... u'playlist[sharing]': 'private', ... u'playlist[title]': 'foo'} # doctest:+ELLIPSIS True >>> normalize_param('oauth_token', 'foo') {'oauth_token': 'foo'} >>> normalize_param('playlist[tracks]', [1234, 4567]) == { ... u'playlist[tracks][]': [1234, 4567]} True
[ "Convert", "a", "set", "of", "key", "value", "parameters", "into", "a", "dictionary", "suitable", "for", "passing", "into", "requests", ".", "This", "will", "convert", "lists", "into", "the", "syntax", "required", "by", "SoundCloud", ".", "Heavily", "lifted", ...
d77f6e5a7ce4852244e653cb67bb20a8a5f04849
https://github.com/soundcloud/soundcloud-python/blob/d77f6e5a7ce4852244e653cb67bb20a8a5f04849/soundcloud/hashconversions.py#L16-L67
229,673
psd-tools/psd-tools
src/psd_tools/api/smart_object.py
SmartObject.open
def open(self, external_dir=None): """ Open the smart object as binary IO. :param external_dir: Path to the directory of the external file. Example:: with layer.smart_object.open() as f: data = f.read() """ if self.kind == 'data': with io.BytesIO(self._data.data) as f: yield f elif self.kind == 'external': filepath = self._data.linked_file[b'fullPath'].value filepath = filepath.replace('\x00', '').replace('file://', '') if not os.path.exists(filepath): filepath = self._data.linked_file[b'relPath'].value filepath = filepath.replace('\x00', '') if external_dir is not None: filepath = os.path.join(external_dir, filepath) if not os.path.exists(filepath): raise FileNotFoundError(filepath) with open(filepath, 'rb') as f: yield f else: raise NotImplementedError('alias is not supported.')
python
def open(self, external_dir=None): if self.kind == 'data': with io.BytesIO(self._data.data) as f: yield f elif self.kind == 'external': filepath = self._data.linked_file[b'fullPath'].value filepath = filepath.replace('\x00', '').replace('file://', '') if not os.path.exists(filepath): filepath = self._data.linked_file[b'relPath'].value filepath = filepath.replace('\x00', '') if external_dir is not None: filepath = os.path.join(external_dir, filepath) if not os.path.exists(filepath): raise FileNotFoundError(filepath) with open(filepath, 'rb') as f: yield f else: raise NotImplementedError('alias is not supported.')
[ "def", "open", "(", "self", ",", "external_dir", "=", "None", ")", ":", "if", "self", ".", "kind", "==", "'data'", ":", "with", "io", ".", "BytesIO", "(", "self", ".", "_data", ".", "data", ")", "as", "f", ":", "yield", "f", "elif", "self", ".", ...
Open the smart object as binary IO. :param external_dir: Path to the directory of the external file. Example:: with layer.smart_object.open() as f: data = f.read()
[ "Open", "the", "smart", "object", "as", "binary", "IO", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/smart_object.py#L50-L77
229,674
psd-tools/psd-tools
src/psd_tools/api/smart_object.py
SmartObject.data
def data(self): """Embedded file content, or empty if kind is `external` or `alias`""" if self.kind == 'data': return self._data.data else: with self.open() as f: return f.read()
python
def data(self): if self.kind == 'data': return self._data.data else: with self.open() as f: return f.read()
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "kind", "==", "'data'", ":", "return", "self", ".", "_data", ".", "data", "else", ":", "with", "self", ".", "open", "(", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Embedded file content, or empty if kind is `external` or `alias`
[ "Embedded", "file", "content", "or", "empty", "if", "kind", "is", "external", "or", "alias" ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/smart_object.py#L80-L86
229,675
psd-tools/psd-tools
src/psd_tools/api/smart_object.py
SmartObject.filesize
def filesize(self): """File size of the object.""" if self.kind == 'data': return len(self._data.data) return self._data.filesize
python
def filesize(self): if self.kind == 'data': return len(self._data.data) return self._data.filesize
[ "def", "filesize", "(", "self", ")", ":", "if", "self", ".", "kind", "==", "'data'", ":", "return", "len", "(", "self", ".", "_data", ".", "data", ")", "return", "self", ".", "_data", ".", "filesize" ]
File size of the object.
[ "File", "size", "of", "the", "object", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/smart_object.py#L94-L98
229,676
psd-tools/psd-tools
src/psd_tools/api/smart_object.py
SmartObject.save
def save(self, filename=None): """ Save the smart object to a file. :param filename: File name to export. If None, use the embedded name. """ if filename is None: filename = self.filename with open(filename, 'wb') as f: f.write(self.data)
python
def save(self, filename=None): if filename is None: filename = self.filename with open(filename, 'wb') as f: f.write(self.data)
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "filename", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ...
Save the smart object to a file. :param filename: File name to export. If None, use the embedded name.
[ "Save", "the", "smart", "object", "to", "a", "file", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/smart_object.py#L119-L128
229,677
psd-tools/psd-tools
src/psd_tools/psd/base.py
BaseElement._traverse
def _traverse(element, condition=None): """ Traversal API intended for debugging. """ if condition is None or condition(element): yield element if isinstance(element, DictElement): for child in element.values(): for _ in BaseElement._traverse(child, condition): yield _ elif isinstance(element, ListElement): for child in element: for _ in BaseElement._traverse(child, condition): yield _ elif attr.has(element.__class__): for field in attr.fields(element.__class__): child = getattr(element, field.name) for _ in BaseElement._traverse(child, condition): yield _
python
def _traverse(element, condition=None): if condition is None or condition(element): yield element if isinstance(element, DictElement): for child in element.values(): for _ in BaseElement._traverse(child, condition): yield _ elif isinstance(element, ListElement): for child in element: for _ in BaseElement._traverse(child, condition): yield _ elif attr.has(element.__class__): for field in attr.fields(element.__class__): child = getattr(element, field.name) for _ in BaseElement._traverse(child, condition): yield _
[ "def", "_traverse", "(", "element", ",", "condition", "=", "None", ")", ":", "if", "condition", "is", "None", "or", "condition", "(", "element", ")", ":", "yield", "element", "if", "isinstance", "(", "element", ",", "DictElement", ")", ":", "for", "child...
Traversal API intended for debugging.
[ "Traversal", "API", "intended", "for", "debugging", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/psd/base.py#L104-L122
229,678
psd-tools/psd-tools
src/psd_tools/psd/descriptor.py
read_length_and_key
def read_length_and_key(fp): """ Helper to read descriptor key. """ length = read_fmt('I', fp)[0] key = fp.read(length or 4) if length == 0 and key not in _TERMS: logger.debug('Unknown term: %r' % (key)) _TERMS.add(key) return key
python
def read_length_and_key(fp): length = read_fmt('I', fp)[0] key = fp.read(length or 4) if length == 0 and key not in _TERMS: logger.debug('Unknown term: %r' % (key)) _TERMS.add(key) return key
[ "def", "read_length_and_key", "(", "fp", ")", ":", "length", "=", "read_fmt", "(", "'I'", ",", "fp", ")", "[", "0", "]", "key", "=", "fp", ".", "read", "(", "length", "or", "4", ")", "if", "length", "==", "0", "and", "key", "not", "in", "_TERMS",...
Helper to read descriptor key.
[ "Helper", "to", "read", "descriptor", "key", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/psd/descriptor.py#L48-L57
229,679
psd-tools/psd-tools
src/psd_tools/psd/descriptor.py
write_length_and_key
def write_length_and_key(fp, value): """ Helper to write descriptor key. """ written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value)) written += write_bytes(fp, value) return written
python
def write_length_and_key(fp, value): written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value)) written += write_bytes(fp, value) return written
[ "def", "write_length_and_key", "(", "fp", ",", "value", ")", ":", "written", "=", "write_fmt", "(", "fp", ",", "'I'", ",", "0", "if", "value", "in", "_TERMS", "else", "len", "(", "value", ")", ")", "written", "+=", "write_bytes", "(", "fp", ",", "val...
Helper to write descriptor key.
[ "Helper", "to", "write", "descriptor", "key", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/psd/descriptor.py#L60-L66
229,680
psd-tools/psd-tools
src/psd_tools/__main__.py
main
def main(argv=None): """ psd-tools command line utility. Usage: psd-tools export <input_file> <output_file> [options] psd-tools show <input_file> [options] psd-tools debug <input_file> [options] psd-tools -h | --help psd-tools --version Options: -v --verbose Be more verbose. Example: psd-tools show example.psd # Show the file content psd-tools export example.psd example.png # Export as PNG psd-tools export example.psd[0] example-0.png # Export layer as PNG """ args = docopt.docopt(main.__doc__, version=__version__, argv=argv) if args['--verbose']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['export']: input_parts = args['<input_file>'].split('[') input_file = input_parts[0] if len(input_parts) > 1: indices = [int(x.rstrip(']')) for x in input_parts[1:]] else: indices = [] layer = PSDImage.open(input_file) for index in indices: layer = layer[index] if isinstance(layer, PSDImage) and layer.has_preview(): image = layer.topil() else: image = layer.compose() image.save(args['<output_file>']) elif args['show']: psd = PSDImage.open(args['<input_file>']) pprint(psd) elif args['debug']: psd = PSDImage.open(args['<input_file>']) pprint(psd._record)
python
def main(argv=None): args = docopt.docopt(main.__doc__, version=__version__, argv=argv) if args['--verbose']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['export']: input_parts = args['<input_file>'].split('[') input_file = input_parts[0] if len(input_parts) > 1: indices = [int(x.rstrip(']')) for x in input_parts[1:]] else: indices = [] layer = PSDImage.open(input_file) for index in indices: layer = layer[index] if isinstance(layer, PSDImage) and layer.has_preview(): image = layer.topil() else: image = layer.compose() image.save(args['<output_file>']) elif args['show']: psd = PSDImage.open(args['<input_file>']) pprint(psd) elif args['debug']: psd = PSDImage.open(args['<input_file>']) pprint(psd._record)
[ "def", "main", "(", "argv", "=", "None", ")", ":", "args", "=", "docopt", ".", "docopt", "(", "main", ".", "__doc__", ",", "version", "=", "__version__", ",", "argv", "=", "argv", ")", "if", "args", "[", "'--verbose'", "]", ":", "logger", ".", "set...
psd-tools command line utility. Usage: psd-tools export <input_file> <output_file> [options] psd-tools show <input_file> [options] psd-tools debug <input_file> [options] psd-tools -h | --help psd-tools --version Options: -v --verbose Be more verbose. Example: psd-tools show example.psd # Show the file content psd-tools export example.psd example.png # Export as PNG psd-tools export example.psd[0] example-0.png # Export layer as PNG
[ "psd", "-", "tools", "command", "line", "utility", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/__main__.py#L17-L66
229,681
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.new
def new(cls, mode, size, color=0, depth=8, **kwargs): """ Create a new PSD document. :param mode: The color mode to use for the new image. :param size: A tuple containing (width, height) in pixels. :param color: What color to use for the image. Default is black. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object. """ header = cls._make_header(mode, size, depth) image_data = ImageData.new(header, color=color, **kwargs) # TODO: Add default metadata. return cls(PSD( header=header, image_data=image_data, image_resources=ImageResources.new(), ))
python
def new(cls, mode, size, color=0, depth=8, **kwargs): header = cls._make_header(mode, size, depth) image_data = ImageData.new(header, color=color, **kwargs) # TODO: Add default metadata. return cls(PSD( header=header, image_data=image_data, image_resources=ImageResources.new(), ))
[ "def", "new", "(", "cls", ",", "mode", ",", "size", ",", "color", "=", "0", ",", "depth", "=", "8", ",", "*", "*", "kwargs", ")", ":", "header", "=", "cls", ".", "_make_header", "(", "mode", ",", "size", ",", "depth", ")", "image_data", "=", "I...
Create a new PSD document. :param mode: The color mode to use for the new image. :param size: A tuple containing (width, height) in pixels. :param color: What color to use for the image. Default is black. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object.
[ "Create", "a", "new", "PSD", "document", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L49-L65
229,682
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.frompil
def frompil(cls, image, compression=Compression.PACK_BITS): """ Create a new PSD document from PIL Image. :param image: PIL Image object. :param compression: ImageData compression option. See :py:class:`~psd_tools.constants.Compression`. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object. """ header = cls._make_header(image.mode, image.size) # TODO: Add default metadata. # TODO: Perhaps make this smart object. image_data = ImageData(compression=compression) image_data.set_data([channel.tobytes() for channel in image.split()], header) return cls(PSD( header=header, image_data=image_data, image_resources=ImageResources.new(), ))
python
def frompil(cls, image, compression=Compression.PACK_BITS): header = cls._make_header(image.mode, image.size) # TODO: Add default metadata. # TODO: Perhaps make this smart object. image_data = ImageData(compression=compression) image_data.set_data([channel.tobytes() for channel in image.split()], header) return cls(PSD( header=header, image_data=image_data, image_resources=ImageResources.new(), ))
[ "def", "frompil", "(", "cls", ",", "image", ",", "compression", "=", "Compression", ".", "PACK_BITS", ")", ":", "header", "=", "cls", ".", "_make_header", "(", "image", ".", "mode", ",", "image", ".", "size", ")", "# TODO: Add default metadata.", "# TODO: Pe...
Create a new PSD document from PIL Image. :param image: PIL Image object. :param compression: ImageData compression option. See :py:class:`~psd_tools.constants.Compression`. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object.
[ "Create", "a", "new", "PSD", "document", "from", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L68-L87
229,683
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.open
def open(cls, fp): """ Open a PSD document. :param fp: filename or file-like object. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object. """ if hasattr(fp, 'read'): self = cls(PSD.read(fp)) else: with open(fp, 'rb') as f: self = cls(PSD.read(f)) return self
python
def open(cls, fp): if hasattr(fp, 'read'): self = cls(PSD.read(fp)) else: with open(fp, 'rb') as f: self = cls(PSD.read(f)) return self
[ "def", "open", "(", "cls", ",", "fp", ")", ":", "if", "hasattr", "(", "fp", ",", "'read'", ")", ":", "self", "=", "cls", "(", "PSD", ".", "read", "(", "fp", ")", ")", "else", ":", "with", "open", "(", "fp", ",", "'rb'", ")", "as", "f", ":",...
Open a PSD document. :param fp: filename or file-like object. :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object.
[ "Open", "a", "PSD", "document", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L90-L102
229,684
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.save
def save(self, fp, mode='wb'): """ Save the PSD file. :param fp: filename or file-like object. :param mode: file open mode, default 'wb'. """ if hasattr(fp, 'write'): self._record.write(fp) else: with open(fp, mode) as f: self._record.write(f)
python
def save(self, fp, mode='wb'): if hasattr(fp, 'write'): self._record.write(fp) else: with open(fp, mode) as f: self._record.write(f)
[ "def", "save", "(", "self", ",", "fp", ",", "mode", "=", "'wb'", ")", ":", "if", "hasattr", "(", "fp", ",", "'write'", ")", ":", "self", ".", "_record", ".", "write", "(", "fp", ")", "else", ":", "with", "open", "(", "fp", ",", "mode", ")", "...
Save the PSD file. :param fp: filename or file-like object. :param mode: file open mode, default 'wb'.
[ "Save", "the", "PSD", "file", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L104-L115
229,685
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.topil
def topil(self, **kwargs): """ Get PIL Image. :return: :py:class:`PIL.Image`, or `None` if the composed image is not available. """ if self.has_preview(): return pil_io.convert_image_data_to_pil(self._record, **kwargs) return None
python
def topil(self, **kwargs): if self.has_preview(): return pil_io.convert_image_data_to_pil(self._record, **kwargs) return None
[ "def", "topil", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "has_preview", "(", ")", ":", "return", "pil_io", ".", "convert_image_data_to_pil", "(", "self", ".", "_record", ",", "*", "*", "kwargs", ")", "return", "None" ]
Get PIL Image. :return: :py:class:`PIL.Image`, or `None` if the composed image is not available.
[ "Get", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L117-L126
229,686
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.compose
def compose(self, force=False, bbox=None, **kwargs): """ Compose the PSD image. See :py:func:`~psd_tools.compose` for available extra arguments. :param bbox: Viewport tuple (left, top, right, bottom). :return: :py:class:`PIL.Image`, or `None` if there is no pixel. """ from psd_tools.api.composer import compose image = None if not force or len(self) == 0: image = self.topil(**kwargs) if image is None: image = compose( self, bbox=bbox or self.viewbox, force=force, **kwargs ) return image
python
def compose(self, force=False, bbox=None, **kwargs): from psd_tools.api.composer import compose image = None if not force or len(self) == 0: image = self.topil(**kwargs) if image is None: image = compose( self, bbox=bbox or self.viewbox, force=force, **kwargs ) return image
[ "def", "compose", "(", "self", ",", "force", "=", "False", ",", "bbox", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "psd_tools", ".", "api", ".", "composer", "import", "compose", "image", "=", "None", "if", "not", "force", "or", "len", ...
Compose the PSD image. See :py:func:`~psd_tools.compose` for available extra arguments. :param bbox: Viewport tuple (left, top, right, bottom). :return: :py:class:`PIL.Image`, or `None` if there is no pixel.
[ "Compose", "the", "PSD", "image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L128-L145
229,687
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.bbox
def bbox(self): """ Minimal bounding box that contains all the visible layers. Use :py:attr:`~psd_tools.api.psd_image.PSDImage.viewbox` to get viewport bounding box. When the psd is empty, bbox is equal to the canvas bounding box. :return: (left, top, right, bottom) `tuple`. """ bbox = super(PSDImage, self).bbox if bbox == (0, 0, 0, 0): bbox = self.viewbox return bbox
python
def bbox(self): bbox = super(PSDImage, self).bbox if bbox == (0, 0, 0, 0): bbox = self.viewbox return bbox
[ "def", "bbox", "(", "self", ")", ":", "bbox", "=", "super", "(", "PSDImage", ",", "self", ")", ".", "bbox", "if", "bbox", "==", "(", "0", ",", "0", ",", "0", ",", "0", ")", ":", "bbox", "=", "self", ".", "viewbox", "return", "bbox" ]
Minimal bounding box that contains all the visible layers. Use :py:attr:`~psd_tools.api.psd_image.PSDImage.viewbox` to get viewport bounding box. When the psd is empty, bbox is equal to the canvas bounding box. :return: (left, top, right, bottom) `tuple`.
[ "Minimal", "bounding", "box", "that", "contains", "all", "the", "visible", "layers", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L278-L291
229,688
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.viewbox
def viewbox(self): """ Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`. """ return self.left, self.top, self.right, self.bottom
python
def viewbox(self): return self.left, self.top, self.right, self.bottom
[ "def", "viewbox", "(", "self", ")", ":", "return", "self", ".", "left", ",", "self", ".", "top", ",", "self", ".", "right", ",", "self", ".", "bottom" ]
Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`.
[ "Return", "bounding", "box", "of", "the", "viewport", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L294-L300
229,689
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage.thumbnail
def thumbnail(self): """ Returns a thumbnail image in PIL.Image. When the file does not contain an embedded thumbnail image, returns None. """ if 'THUMBNAIL_RESOURCE' in self.image_resources: return pil_io.convert_thumbnail_to_pil( self.image_resources.get_data('THUMBNAIL_RESOURCE') ) elif 'THUMBNAIL_RESOURCE_PS4' in self.image_resources: return pil_io.convert_thumbnail_to_pil( self.image_resources.get_data('THUMBNAIL_RESOURCE_PS4'), 'BGR' ) return None
python
def thumbnail(self): if 'THUMBNAIL_RESOURCE' in self.image_resources: return pil_io.convert_thumbnail_to_pil( self.image_resources.get_data('THUMBNAIL_RESOURCE') ) elif 'THUMBNAIL_RESOURCE_PS4' in self.image_resources: return pil_io.convert_thumbnail_to_pil( self.image_resources.get_data('THUMBNAIL_RESOURCE_PS4'), 'BGR' ) return None
[ "def", "thumbnail", "(", "self", ")", ":", "if", "'THUMBNAIL_RESOURCE'", "in", "self", ".", "image_resources", ":", "return", "pil_io", ".", "convert_thumbnail_to_pil", "(", "self", ".", "image_resources", ".", "get_data", "(", "'THUMBNAIL_RESOURCE'", ")", ")", ...
Returns a thumbnail image in PIL.Image. When the file does not contain an embedded thumbnail image, returns None.
[ "Returns", "a", "thumbnail", "image", "in", "PIL", ".", "Image", ".", "When", "the", "file", "does", "not", "contain", "an", "embedded", "thumbnail", "image", "returns", "None", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L387-L400
229,690
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage._get_pattern
def _get_pattern(self, pattern_id): """Get pattern item by id.""" for key in ('PATTERNS1', 'PATTERNS2', 'PATTERNS3'): if key in self.tagged_blocks: data = self.tagged_blocks.get_data(key) for pattern in data: if pattern.pattern_id == pattern_id: return pattern return None
python
def _get_pattern(self, pattern_id): for key in ('PATTERNS1', 'PATTERNS2', 'PATTERNS3'): if key in self.tagged_blocks: data = self.tagged_blocks.get_data(key) for pattern in data: if pattern.pattern_id == pattern_id: return pattern return None
[ "def", "_get_pattern", "(", "self", ",", "pattern_id", ")", ":", "for", "key", "in", "(", "'PATTERNS1'", ",", "'PATTERNS2'", ",", "'PATTERNS3'", ")", ":", "if", "key", "in", "self", ".", "tagged_blocks", ":", "data", "=", "self", ".", "tagged_blocks", "....
Get pattern item by id.
[ "Get", "pattern", "item", "by", "id", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L442-L450
229,691
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
PSDImage._init
def _init(self): """Initialize layer structure.""" group_stack = [self] clip_stack = [] last_layer = None for record, channels in self._record._iter_layers(): current_group = group_stack[-1] blocks = record.tagged_blocks end_of_group = False divider = blocks.get_data('SECTION_DIVIDER_SETTING', None) divider = blocks.get_data('NESTED_SECTION_DIVIDER_SETTING', divider) if divider is not None: if divider.kind == SectionDivider.BOUNDING_SECTION_DIVIDER: layer = Group(self, None, None, current_group) group_stack.append(layer) elif divider.kind in (SectionDivider.OPEN_FOLDER, SectionDivider.CLOSED_FOLDER): layer = group_stack.pop() assert layer is not self layer._record = record layer._channels = channels for key in ( 'ARTBOARD_DATA1', 'ARTBOARD_DATA2', 'ARTBOARD_DATA3' ): if key in blocks: layer = Artboard._move(layer) end_of_group = True elif ( 'TYPE_TOOL_OBJECT_SETTING' in blocks or 'TYPE_TOOL_INFO' in blocks ): layer = TypeLayer(self, record, channels, current_group) elif ( record.flags.pixel_data_irrelevant and ( 'VECTOR_ORIGINATION_DATA' in blocks or 'VECTOR_MASK_SETTING1' in blocks or 'VECTOR_MASK_SETTING2' in blocks or 'VECTOR_STROKE_DATA' in blocks or 'VECTOR_STROKE_CONTENT_DATA' in blocks ) ): layer = ShapeLayer(self, record, channels, current_group) elif ( 'SMART_OBJECT_LAYER_DATA1' in blocks or 'SMART_OBJECT_LAYER_DATA2' in blocks or 'PLACED_LAYER1' in blocks or 'PLACED_LAYER2' in blocks ): layer = SmartObjectLayer(self, record, channels, current_group) else: layer = None for key in adjustments.TYPES.keys(): if key in blocks: layer = adjustments.TYPES[key]( self, record, channels, current_group ) break # If nothing applies, this is a pixel layer. if layer is None: layer = PixelLayer( self, record, channels, current_group ) if record.clipping == Clipping.NON_BASE: clip_stack.append(layer) else: if clip_stack: last_layer._clip_layers = clip_stack clip_stack = [] if not end_of_group: current_group._layers.append(layer) last_layer = layer if clip_stack and last_layer: last_layer._clip_layers = clip_stack
python
def _init(self): group_stack = [self] clip_stack = [] last_layer = None for record, channels in self._record._iter_layers(): current_group = group_stack[-1] blocks = record.tagged_blocks end_of_group = False divider = blocks.get_data('SECTION_DIVIDER_SETTING', None) divider = blocks.get_data('NESTED_SECTION_DIVIDER_SETTING', divider) if divider is not None: if divider.kind == SectionDivider.BOUNDING_SECTION_DIVIDER: layer = Group(self, None, None, current_group) group_stack.append(layer) elif divider.kind in (SectionDivider.OPEN_FOLDER, SectionDivider.CLOSED_FOLDER): layer = group_stack.pop() assert layer is not self layer._record = record layer._channels = channels for key in ( 'ARTBOARD_DATA1', 'ARTBOARD_DATA2', 'ARTBOARD_DATA3' ): if key in blocks: layer = Artboard._move(layer) end_of_group = True elif ( 'TYPE_TOOL_OBJECT_SETTING' in blocks or 'TYPE_TOOL_INFO' in blocks ): layer = TypeLayer(self, record, channels, current_group) elif ( record.flags.pixel_data_irrelevant and ( 'VECTOR_ORIGINATION_DATA' in blocks or 'VECTOR_MASK_SETTING1' in blocks or 'VECTOR_MASK_SETTING2' in blocks or 'VECTOR_STROKE_DATA' in blocks or 'VECTOR_STROKE_CONTENT_DATA' in blocks ) ): layer = ShapeLayer(self, record, channels, current_group) elif ( 'SMART_OBJECT_LAYER_DATA1' in blocks or 'SMART_OBJECT_LAYER_DATA2' in blocks or 'PLACED_LAYER1' in blocks or 'PLACED_LAYER2' in blocks ): layer = SmartObjectLayer(self, record, channels, current_group) else: layer = None for key in adjustments.TYPES.keys(): if key in blocks: layer = adjustments.TYPES[key]( self, record, channels, current_group ) break # If nothing applies, this is a pixel layer. if layer is None: layer = PixelLayer( self, record, channels, current_group ) if record.clipping == Clipping.NON_BASE: clip_stack.append(layer) else: if clip_stack: last_layer._clip_layers = clip_stack clip_stack = [] if not end_of_group: current_group._layers.append(layer) last_layer = layer if clip_stack and last_layer: last_layer._clip_layers = clip_stack
[ "def", "_init", "(", "self", ")", ":", "group_stack", "=", "[", "self", "]", "clip_stack", "=", "[", "]", "last_layer", "=", "None", "for", "record", ",", "channels", "in", "self", ".", "_record", ".", "_iter_layers", "(", ")", ":", "current_group", "=...
Initialize layer structure.
[ "Initialize", "layer", "structure", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L452-L531
229,692
psd-tools/psd-tools
src/psd_tools/api/effects.py
_AngleMixin.angle
def angle(self): """Angle value.""" if self.use_global_light: return self._image_resources.get_data('global_angle', 30.0) return self.value.get(Key.LocalLightingAngle).value
python
def angle(self): if self.use_global_light: return self._image_resources.get_data('global_angle', 30.0) return self.value.get(Key.LocalLightingAngle).value
[ "def", "angle", "(", "self", ")", ":", "if", "self", ".", "use_global_light", ":", "return", "self", ".", "_image_resources", ".", "get_data", "(", "'global_angle'", ",", "30.0", ")", "return", "self", ".", "value", ".", "get", "(", "Key", ".", "LocalLig...
Angle value.
[ "Angle", "value", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/effects.py#L169-L173
229,693
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
get_color_mode
def get_color_mode(mode): """Convert PIL mode to ColorMode.""" name = mode.upper() name = name.rstrip('A') # Trim alpha. name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name) return getattr(ColorMode, name)
python
def get_color_mode(mode): name = mode.upper() name = name.rstrip('A') # Trim alpha. name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name) return getattr(ColorMode, name)
[ "def", "get_color_mode", "(", "mode", ")", ":", "name", "=", "mode", ".", "upper", "(", ")", "name", "=", "name", ".", "rstrip", "(", "'A'", ")", "# Trim alpha.", "name", "=", "{", "'1'", ":", "'BITMAP'", ",", "'L'", ":", "'GRAYSCALE'", "}", ".", "...
Convert PIL mode to ColorMode.
[ "Convert", "PIL", "mode", "to", "ColorMode", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L14-L19
229,694
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
get_pil_mode
def get_pil_mode(value, alpha=False): """Get PIL mode from ColorMode.""" name = { 'GRAYSCALE': 'L', 'BITMAP': '1', 'DUOTONE': 'L', 'INDEXED': 'P', }.get(value, value) if alpha and name in ('L', 'RGB'): name += 'A' return name
python
def get_pil_mode(value, alpha=False): name = { 'GRAYSCALE': 'L', 'BITMAP': '1', 'DUOTONE': 'L', 'INDEXED': 'P', }.get(value, value) if alpha and name in ('L', 'RGB'): name += 'A' return name
[ "def", "get_pil_mode", "(", "value", ",", "alpha", "=", "False", ")", ":", "name", "=", "{", "'GRAYSCALE'", ":", "'L'", ",", "'BITMAP'", ":", "'1'", ",", "'DUOTONE'", ":", "'L'", ",", "'INDEXED'", ":", "'P'", ",", "}", ".", "get", "(", "value", ","...
Get PIL mode from ColorMode.
[ "Get", "PIL", "mode", "from", "ColorMode", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L22-L32
229,695
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
convert_image_data_to_pil
def convert_image_data_to_pil(psd, apply_icc=True, **kwargs): """Convert ImageData to PIL Image. .. note:: Image resources contain extra alpha channels in these keys: `ALPHA_NAMES_UNICODE`, `ALPHA_NAMES_PASCAL`, `ALPHA_IDENTIFIERS`. """ from PIL import Image, ImageOps header = psd.header size = (header.width, header.height) channels = [] for channel_data in psd.image_data.get_data(header): channels.append(_create_channel(size, channel_data, header.depth)) alpha = _get_alpha_use(psd) mode = get_pil_mode(header.color_mode.name) if mode == 'P': image = Image.merge('L', channels[:get_pil_channels(mode)]) image.putpalette(psd.color_mode_data.interleave()) elif mode == 'MULTICHANNEL': image = channels[0] # Multi-channel mode is a collection of alpha. else: image = Image.merge(mode, channels[:get_pil_channels(mode)]) if mode == 'CMYK': image = image.point(lambda x: 255 - x) if apply_icc and 'ICC_PROFILE' in psd.image_resources: image = _apply_icc(image, psd.image_resources.get_data('ICC_PROFILE')) if alpha and mode in ('L', 'RGB'): image.putalpha(channels[-1]) return _remove_white_background(image)
python
def convert_image_data_to_pil(psd, apply_icc=True, **kwargs): from PIL import Image, ImageOps header = psd.header size = (header.width, header.height) channels = [] for channel_data in psd.image_data.get_data(header): channels.append(_create_channel(size, channel_data, header.depth)) alpha = _get_alpha_use(psd) mode = get_pil_mode(header.color_mode.name) if mode == 'P': image = Image.merge('L', channels[:get_pil_channels(mode)]) image.putpalette(psd.color_mode_data.interleave()) elif mode == 'MULTICHANNEL': image = channels[0] # Multi-channel mode is a collection of alpha. else: image = Image.merge(mode, channels[:get_pil_channels(mode)]) if mode == 'CMYK': image = image.point(lambda x: 255 - x) if apply_icc and 'ICC_PROFILE' in psd.image_resources: image = _apply_icc(image, psd.image_resources.get_data('ICC_PROFILE')) if alpha and mode in ('L', 'RGB'): image.putalpha(channels[-1]) return _remove_white_background(image)
[ "def", "convert_image_data_to_pil", "(", "psd", ",", "apply_icc", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "PIL", "import", "Image", ",", "ImageOps", "header", "=", "psd", ".", "header", "size", "=", "(", "header", ".", "width", ",", "he...
Convert ImageData to PIL Image. .. note:: Image resources contain extra alpha channels in these keys: `ALPHA_NAMES_UNICODE`, `ALPHA_NAMES_PASCAL`, `ALPHA_IDENTIFIERS`.
[ "Convert", "ImageData", "to", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L52-L79
229,696
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
convert_layer_to_pil
def convert_layer_to_pil(layer, apply_icc=True, **kwargs): """Convert Layer to PIL Image.""" from PIL import Image header = layer._psd._record.header if header.color_mode == ColorMode.BITMAP: raise NotImplementedError width, height = layer.width, layer.height channels, alpha = [], None for ci, cd in zip(layer._record.channel_info, layer._channels): if ci.id in (ChannelID.USER_LAYER_MASK, ChannelID.REAL_USER_LAYER_MASK): continue channel = cd.get_data(width, height, header.depth, header.version) channel_image = _create_channel( (width, height), channel, header.depth ) if ci.id == ChannelID.TRANSPARENCY_MASK: alpha = channel_image else: channels.append(channel_image) mode = get_pil_mode(header.color_mode.name) channels = _check_channels(channels, header.color_mode) image = Image.merge(mode, channels) if mode == 'CMYK': image = image.point(lambda x: 255 - x) if alpha is not None: if mode in ('RGB', 'L'): image.putalpha(alpha) else: logger.debug('Alpha channel is not supported in %s' % (mode)) if apply_icc and 'ICC_PROFILE' in layer._psd.image_resources: image = _apply_icc( image, layer._psd.image_resources.get_data('ICC_PROFILE') ) return image
python
def convert_layer_to_pil(layer, apply_icc=True, **kwargs): from PIL import Image header = layer._psd._record.header if header.color_mode == ColorMode.BITMAP: raise NotImplementedError width, height = layer.width, layer.height channels, alpha = [], None for ci, cd in zip(layer._record.channel_info, layer._channels): if ci.id in (ChannelID.USER_LAYER_MASK, ChannelID.REAL_USER_LAYER_MASK): continue channel = cd.get_data(width, height, header.depth, header.version) channel_image = _create_channel( (width, height), channel, header.depth ) if ci.id == ChannelID.TRANSPARENCY_MASK: alpha = channel_image else: channels.append(channel_image) mode = get_pil_mode(header.color_mode.name) channels = _check_channels(channels, header.color_mode) image = Image.merge(mode, channels) if mode == 'CMYK': image = image.point(lambda x: 255 - x) if alpha is not None: if mode in ('RGB', 'L'): image.putalpha(alpha) else: logger.debug('Alpha channel is not supported in %s' % (mode)) if apply_icc and 'ICC_PROFILE' in layer._psd.image_resources: image = _apply_icc( image, layer._psd.image_resources.get_data('ICC_PROFILE') ) return image
[ "def", "convert_layer_to_pil", "(", "layer", ",", "apply_icc", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "PIL", "import", "Image", "header", "=", "layer", ".", "_psd", ".", "_record", ".", "header", "if", "header", ".", "color_mode", "==", ...
Convert Layer to PIL Image.
[ "Convert", "Layer", "to", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L82-L117
229,697
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
convert_mask_to_pil
def convert_mask_to_pil(mask, real=True): """Convert Mask to PIL Image.""" from PIL import Image header = mask._layer._psd._record.header channel_ids = [ci.id for ci in mask._layer._record.channel_info] if real and mask._has_real(): width = mask._data.real_right - mask._data.real_left height = mask._data.real_bottom - mask._data.real_top channel = mask._layer._channels[ channel_ids.index(ChannelID.REAL_USER_LAYER_MASK) ] else: width = mask._data.right - mask._data.left height = mask._data.bottom - mask._data.top channel = mask._layer._channels[ channel_ids.index(ChannelID.USER_LAYER_MASK) ] data = channel.get_data(width, height, header.depth, header.version) return _create_channel((width, height), data, header.depth)
python
def convert_mask_to_pil(mask, real=True): from PIL import Image header = mask._layer._psd._record.header channel_ids = [ci.id for ci in mask._layer._record.channel_info] if real and mask._has_real(): width = mask._data.real_right - mask._data.real_left height = mask._data.real_bottom - mask._data.real_top channel = mask._layer._channels[ channel_ids.index(ChannelID.REAL_USER_LAYER_MASK) ] else: width = mask._data.right - mask._data.left height = mask._data.bottom - mask._data.top channel = mask._layer._channels[ channel_ids.index(ChannelID.USER_LAYER_MASK) ] data = channel.get_data(width, height, header.depth, header.version) return _create_channel((width, height), data, header.depth)
[ "def", "convert_mask_to_pil", "(", "mask", ",", "real", "=", "True", ")", ":", "from", "PIL", "import", "Image", "header", "=", "mask", ".", "_layer", ".", "_psd", ".", "_record", ".", "header", "channel_ids", "=", "[", "ci", ".", "id", "for", "ci", ...
Convert Mask to PIL Image.
[ "Convert", "Mask", "to", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L120-L138
229,698
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
convert_pattern_to_pil
def convert_pattern_to_pil(pattern, version=1): """Convert Pattern to PIL Image.""" from PIL import Image mode = get_pil_mode(pattern.image_mode.name, False) # The order is different here. size = pattern.data.rectangle[3], pattern.data.rectangle[2] channels = [ _create_channel(size, c.get_data(version), c.pixel_depth).convert('L') for c in pattern.data.channels if c.is_written ] if len(channels) == len(mode) + 1: mode += 'A' # TODO: Perhaps doesn't work for some modes. if mode == 'P': image = channels[0] image.putpalette([x for rgb in pattern.color_table for x in rgb]) else: image = Image.merge(mode, channels) if mode == 'CMYK': image = image.point(lambda x: 255 - x) return image
python
def convert_pattern_to_pil(pattern, version=1): from PIL import Image mode = get_pil_mode(pattern.image_mode.name, False) # The order is different here. size = pattern.data.rectangle[3], pattern.data.rectangle[2] channels = [ _create_channel(size, c.get_data(version), c.pixel_depth).convert('L') for c in pattern.data.channels if c.is_written ] if len(channels) == len(mode) + 1: mode += 'A' # TODO: Perhaps doesn't work for some modes. if mode == 'P': image = channels[0] image.putpalette([x for rgb in pattern.color_table for x in rgb]) else: image = Image.merge(mode, channels) if mode == 'CMYK': image = image.point(lambda x: 255 - x) return image
[ "def", "convert_pattern_to_pil", "(", "pattern", ",", "version", "=", "1", ")", ":", "from", "PIL", "import", "Image", "mode", "=", "get_pil_mode", "(", "pattern", ".", "image_mode", ".", "name", ",", "False", ")", "# The order is different here.", "size", "="...
Convert Pattern to PIL Image.
[ "Convert", "Pattern", "to", "PIL", "Image", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L141-L160
229,699
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
convert_thumbnail_to_pil
def convert_thumbnail_to_pil(thumbnail, mode='RGB'): """Convert thumbnail resource.""" from PIL import Image if thumbnail.fmt == 0: size = (thumbnail.width, thumbnail.height) stride = thumbnail.widthbytes return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode, stride) elif thumbnail.fmt == 1: return Image.open(io.BytesIO(thumbnail.data)) else: raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
python
def convert_thumbnail_to_pil(thumbnail, mode='RGB'): from PIL import Image if thumbnail.fmt == 0: size = (thumbnail.width, thumbnail.height) stride = thumbnail.widthbytes return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode, stride) elif thumbnail.fmt == 1: return Image.open(io.BytesIO(thumbnail.data)) else: raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
[ "def", "convert_thumbnail_to_pil", "(", "thumbnail", ",", "mode", "=", "'RGB'", ")", ":", "from", "PIL", "import", "Image", "if", "thumbnail", ".", "fmt", "==", "0", ":", "size", "=", "(", "thumbnail", ".", "width", ",", "thumbnail", ".", "height", ")", ...
Convert thumbnail resource.
[ "Convert", "thumbnail", "resource", "." ]
4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L163-L174