text
stringlengths
81
112k
Adds an adsorbate at a particular coordinate. Adsorbate represented by a Molecule object, and is positioned relative to the input adsorbate coordinate. Args: molecule (Molecule): molecule object representing the adsorbate ads_coord (array): coordinate of adsorbate posit...
Helper function to assign selective dynamics site_properties based on surface, subsurface site properties Args: slab (Slab): slab for which to assign selective dynamics def assign_selective_dynamics(self, slab): """ Helper function to assign selective dynamics site_properti...
Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of precursor slab as an input Args: molecule (Molecule): molecule corresponding to adsorbate repeat (3-tuple or list): repeat argument for...
Function that generates all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy where both surfaces need to be equivalent or if we want to calculate nonpolar systems. Args: molecule (Molecule): molec...
Function that performs substitution-type doping on the surface and returns all possible configurations where one dopant is substituted per surface. Can substitute one surface or both. Args: atom (str): atom corresponding to substitutional dopant sub_both_sides (b...
Reads the exciting input from a string def from_string(data): """ Reads the exciting input from a string """ root=ET.fromstring(data) speciesnode=root.find('structure').iter('species') elements = [] positions = [] vectors=[] lockxyz=[] ...
List of types of specie. Only works for ordered structures. Disordered structures will raise TypeError. def types_of_specie(self): """ List of types of specie. Only works for ordered structures. Disordered structures will raise TypeError. """ if not self.is_ordered: ...
Iterate over species grouped by type def group_by_types(self): """Iterate over species grouped by type""" for t in self.types_of_specie: for site in self: if site.specie == t: yield site
Returns a tuple with the sequential indices of the sites that contain an element with the given chemical symbol. def indices_from_symbol(self, symbol: str) -> tuple: """ Returns a tuple with the sequential indices of the sites that contain an element with the given chemical symbol. ...
Returns the site properties as a dict of sequences. E.g., {"magmom": (5,-5), "charge": (-4,4)}. def site_properties(self): """ Returns the site properties as a dict of sequences. E.g., {"magmom": (5,-5), "charge": (-4,4)}. """ props = {} prop_keys = set() ...
(Composition) Returns the composition def composition(self): """ (Composition) Returns the composition """ elmap = collections.defaultdict(float) for site in self: for species, occu in site.species.items(): elmap[species] += occu return Compos...
Returns the net charge of the structure based on oxidation states. If Elements are found, a charge of 0 is assumed. def charge(self): """ Returns the net charge of the structure based on oxidation states. If Elements are found, a charge of 0 is assumed. """ charge = 0 ...
Returns angle specified by three sites. Args: i: Index of first site. j: Index of second site. k: Index of third site. Returns: Angle in degrees. def get_angle(self, i: int, j: int, k: int) -> float: """ Returns angle specified by three ...
Returns dihedral angle specified by four sites. Args: i: Index of first site j: Index of second site k: Index of third site l: Index of fourth site Returns: Dihedral angle in degrees. def get_dihedral(self, i: int, j: int, k: int, l: int) ->...
True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is taken into account for periodic structures. Args: tol (float...
Adds a property to a site. Args: property_name (str): The name of the property to add. values (list): A sequence of values. Must be same length as number of sites. def add_site_property(self, property_name, values): """ Adds a property to a site. ...
Swap species. Args: species_mapping (dict): dict of species to swap. Species can be elements too. E.g., {Element("Li"): Element("Na")} performs a Li for Na substitution. The second species can be a sp_and_occu dict. For example, a site with 0.5 Si tha...
Add oxidation states. Args: oxidation_states (dict): Dict of oxidation states. E.g., {"Li":1, "Fe":2, "P":5, "O":-2} def add_oxidation_state_by_element(self, oxidation_states): """ Add oxidation states. Args: oxidation_states (dict): Dict of oxi...
Add oxidation states to a structure by site. Args: oxidation_states (list): List of oxidation states. E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2] def add_oxidation_state_by_site(self, oxidation_states): """ Add oxidation states to a structure by site....
Removes oxidation states from a structure. def remove_oxidation_states(self): """ Removes oxidation states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float) for el, occu in site.species.items(): sym = el.symbol ...
Decorates the structure with oxidation state, guessing using Composition.oxi_state_guesses() Args: **kwargs: parameters to pass into oxi_state_guesses() def add_oxidation_state_by_guess(self, **kwargs): """ Decorates the structure with oxidation state, guessing usin...
Add spin states to a structure. Args: spisn (dict): Dict of spins associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5} def add_spin_by_element(self, spins): """ Add spin states to a structure. Args: spisn (dict): Dict of spins associate...
Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0] def add_spin_by_site(self, spins): """ Add spin states to a structure by site. Args: spins (list): List of spins E.g., [+5, -5, 0, 0] ...
Removes spin states from a structure. def remove_spin(self): """ Removes spin states from a structure. """ for site in self.sites: new_sp = collections.defaultdict(float) for sp, occu in site.species.items(): oxi_state = getattr(sp, "oxi_state", N...
Extracts a cluster of atoms based on bond lengths Args: target_sites ([Site]): List of initial sites to nucleate cluster. \\*\\*kwargs: kwargs passed through to CovalentBond.is_bonded. Returns: [Site/PeriodicSite] Cluster of atoms. def extract_cluster(self, target_...
Convenience constructor to make a Structure from a list of sites. Args: sites: Sequence of PeriodicSites. Sites must have the same lattice. validate_proximity (bool): Whether to check if there are sites that are less than 0.01 Ang apart. Defaults to False...
Generate a structure using a spacegroup. Note that only symmetrically distinct species and coords should be provided. All equivalent sites are generated from the spacegroup operations. Args: sg (str/int): The spacegroup. If a string, it will be interpreted as one of ...
Generate a structure using a magnetic spacegroup. Note that only symmetrically distinct species, coords and magmoms should be provided.] All equivalent sites are generated from the spacegroup operations. Args: msg (str/list/:class:`pymatgen.symmetry.maggroups.MagneticSpaceGroup`): ...
Returns the density in units of g/cc def density(self): """ Returns the density in units of g/cc """ m = Mass(self.composition.weight, "amu") return m.to("g") / (self.volume * Length(1, "ang").to("cm") ** 3)
Convenience method to quickly get the spacegroup of a structure. Args: symprec (float): Same definition as in SpacegroupAnalyzer. Defaults to 1e-2. angle_tolerance (float): Same definition as in SpacegroupAnalyzer. Defaults to 5 degrees. Returns:...
Check whether this structure is similar to another structure. Basically a convenience method to call structure matching fitting. Args: other (IStructure/Structure): Another structure. **kwargs: Same **kwargs as in :class:`pymatgen.analysis.structure_matcher.Struc...
Get distance between site i and j assuming periodic boundary conditions. If the index jimage of two sites atom j is not specified it selects the jimage nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations if the index jimage of atom j ...
Find all sites within a sphere from the point. This includes sites in other periodic images. Algorithm: 1. place sphere of radius r in crystal and determine minimum supercell (parallelpiped) which would contain a sphere of radius r. for this we need the projection of a_1 ...
Get all neighbors to a site within a sphere of radius r. Excludes the site itself. Args: site (Site): Which is the center of the sphere. r (float): Radius of sphere. include_index (bool): Whether the non-supercell site index is included in the return...
Get neighbors for each atom in the unit cell, out to a distance r Returns a list of list of neighbors for each site in structure. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors a...
Returns all sites in a shell centered on origin (coords) between radii r-dr and r+dr. Args: origin (3x1 array): Cartesian coordinates of center of sphere. r (float): Inner radius of shell. dr (float): Width of shell. include_index (bool): Whether to inclu...
Get a sorted copy of the structure. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. Args: key: Specifies a function of one argument that is used to extract a comparison key from each list ele...
Get a reduced structure. Args: reduction_algo (str): The lattice reduction algorithm to use. Currently supported options are "niggli" or "LLL". def get_reduced_structure(self, reduction_algo="niggli"): """ Get a reduced structure. Args: reductio...
Convenience method to get a copy of the structure, with options to add site properties. Args: site_properties (dict): Properties to add or override. The properties are specified in the same way as the constructor, i.e., as a dict of the form {property: [value...
Interpolate between this structure and end_structure. Useful for construction of NEB inputs. Args: end_structure (Structure): structure to interpolate between this structure and end. nimages (int): No. of interpolation images. Defaults to 10 images. i...
Get the Miller index of a plane from a set of sites indexes. A minimum of 3 sites are required. If more than 3 sites are given the best plane that minimises the distance to all points will be calculated. Args: site_ids (list of int): A list of site indexes to consider. A ...
This finds a smaller unit cell than the input. Sometimes it doesn"t find the smallest possible one, so this method is recursively called until it is unable to find a smaller cell. NOTE: if the tolerance is greater than 1/2 the minimum inter-site distance in the primitive cell, the algor...
Dict representation of Structure. Args: verbosity (int): Verbosity level. Default of 1 includes both direct and cartesian coordinates for all sites, lattice parameters, etc. Useful for reading and for insertion into a database. Set to 0 for an extreme...
Reconstitute a Structure object from a dict representation of Structure created using as_dict(). Args: d (dict): Dict representation of structure. Returns: Structure object def from_dict(cls, d, fmt=None): """ Reconstitute a Structure object from a dict...
Outputs the structure to a file or string. Args: fmt (str): Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "cif", "poscar", "cssr", "json". Non-case sensit...
Reads a structure from a string. Args: input_string (str): String to parse. fmt (str): A format specification. primitive (bool): Whether to find a primitive cell. Defaults to False. sort (bool): Whether to sort the sites in accordance to the defau...
Reads a structure from a file. For example, anything ending in a "cif" is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR, Netcdf and pymatgen's JSON serialized structures. Args: filen...
Center of mass of molecule. def center_of_mass(self): """ Center of mass of molecule. """ center = np.zeros(3) total_weight = 0 for site in self: wt = site.species.weight center += site.coords * wt total_weight += wt return cen...
Convenience constructor to make a Molecule from a list of sites. Args: sites ([Site]): Sequence of Sites. charge (int): Charge of molecule. Defaults to 0. spin_multiplicity (int): Spin multicipity. Defaults to None, in which it is determined automatically. ...
Returns two molecules based on breaking the bond between atoms at index ind1 and ind2. Args: ind1 (int): Index of first site. ind2 (int): Index of second site. tol (float): Relative tolerance to test. Basically, the code checks if the distance between...
Determines the covalent bonds in a molecule. Args: tol (float): The tol to determine bonds in a structure. See CovalentBond.is_bonded. Returns: List of bonds def get_covalent_bonds(self, tol=0.2): """ Determines the covalent bonds in a molecule....
Json-serializable dict representation of Molecule def as_dict(self): """ Json-serializable dict representation of Molecule """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "charge": self._charge, "spin_multiplicity"...
Reconstitute a Molecule object from a dict representation created using as_dict(). Args: d (dict): dict representation of Molecule. Returns: Molecule object def from_dict(cls, d): """ Reconstitute a Molecule object from a dict representation created usi...
Find all sites within a sphere from a point. Args: pt (3x1 array): Cartesian coordinates of center of sphere. r (float): Radius of sphere. Returns: [(site, dist) ...] since most of the time, subsequent processing requires the distance. def get_sites_in_...
Get all neighbors to a site within a sphere of radius r. Excludes the site itself. Args: site (Site): Site at the center of the sphere. r (float): Radius of sphere. Returns: [(site, dist) ...] since most of the time, subsequent processing requir...
Returns all sites in a shell centered on origin (coords) between radii r-dr and r+dr. Args: origin (3x1 array): Cartesian coordinates of center of sphere. r (float): Inner radius of shell. dr (float): Width of shell. Returns: [(site, dist) ...] s...
Creates a Structure from a Molecule by putting the Molecule in the center of a orthorhombic box. Useful for creating Structure for calculating molecules using periodic codes. Args: a (float): a-lattice parameter. b (float): b-lattice parameter. c (float): c-l...
Returns a Molecule centered at the center of mass. Returns: Molecule centered with center of mass at origin. def get_centered_molecule(self): """ Returns a Molecule centered at the center of mass. Returns: Molecule centered with center of mass at origin. ...
Outputs the molecule to a file or string. Args: fmt (str): Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "xyz", "gjf", "g03", "json". If you have OpenBabe...
Reads the molecule from a string. Args: input_string (str): String to parse. fmt (str): Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "xyz", "gjf", "g03", "js...
Reads a molecule from a file. Supported formats include xyz, gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and pymatgen's JSON serialized molecules. Using openbabel, many more extensions are supported but requires openbabel to be installed. Args: filena...
Append a site to the structure. Args: species: Species of inserted site coords (3x1 array): Coordinates of inserted site coords_are_cartesian (bool): Whether coordinates are cartesian. Defaults to False. validate_proximity (bool): Whether to check...
Insert a site to the structure. Args: i (int): Index to insert site species (species-like): Species of inserted site coords (3x1 array): Coordinates of inserted site coords_are_cartesian (bool): Whether coordinates are cartesian. Defaults to False...
Replace a single site. Takes either a species or a dict of species and occupations. Args: i (int): Index of the site in the _sites list. species (species-like): Species of replacement site coords (3x1 array): Coordinates of replacement site. If None, ...
Substitute atom at index with a functional group. Args: index (int): Index of atom to substitute. func_grp: Substituent molecule. There are two options: 1. Providing an actual Molecule as the input. The first atom must be a DummySpecie X, indicating t...
Remove all occurrences of several species from a structure. Args: species: Sequence of species to remove, e.g., ["Li", "Na"]. def remove_species(self, species): """ Remove all occurrences of several species from a structure. Args: species: Sequence of species t...
Delete sites with at indices. Args: indices: Sequence of indices of sites to delete. def remove_sites(self, indices): """ Delete sites with at indices. Args: indices: Sequence of indices of sites to delete. """ self._sites = [s for i, s in enume...
Apply a symmetry operation to the structure and return the new structure. The lattice is operated by the rotation matrix only. Coords are operated in full and then transformed to the new lattice. Args: symmop (SymmOp): Symmetry operation to apply. fractional (bool): Whet...
Modify the lattice of the structure. Mainly used for changing the basis. Args: new_lattice (Lattice): New lattice def modify_lattice(self, new_lattice): """ Modify the lattice of the structure. Mainly used for changing the basis. Args: new_lat...
Apply a strain to the lattice. Args: strain (float or list): Amount of strain to apply. Can be a float, or a sequence of 3 numbers. E.g., 0.01 means all lattice vectors are increased by 1%. This is equivalent to calling modify_lattice with a lattice w...
Sort a structure in place. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. The difference between this method and get_sorted_structure (which also works in IStructure) is that the latter returns a new Structure, ...
Translate specific sites by some vector, keeping the sites within the unit cell. Args: indices: Integer or List of site indices on which to perform the translation. vector: Translation vector for sites. frac_coords (bool): Whether the vector correspon...
Rotate specific sites by some angle around vector at anchor. Args: indices (list): List of site indices on which to perform the translation. theta (float): Angle in radians axis (3x1 array): Rotation axis vector. anchor (3x1 array): Point of rotat...
Performs a random perturbation of the sites in a structure to break symmetries. Args: distance (float): Distance in angstroms by which to perturb each site. def perturb(self, distance): """ Performs a random perturbation of the sites in a structure to break ...
Create a supercell. Args: scaling_matrix: A scaling matrix for transforming the lattice vectors. Has to be all integers. Several options are possible: a. A full 3x3 scaling matrix defining the linear combination the old lattice vectors. E.g., [[2,...
Merges sites (adding occupancies) within tol of each other. Removes site properties. Args: tol (float): Tolerance for distance to merge sites. mode (str): Three modes supported. "delete" means duplicate sites are deleted. "sum" means the occupancies are summed fo...
Appends a site to the molecule. Args: species: Species of inserted site coords: Coordinates of inserted site validate_proximity (bool): Whether to check if inserted site is too close to an existing site. Defaults to True. properties (dict): A dict...
Set the charge and spin multiplicity. Args: charge (int): Charge for the molecule. Defaults to 0. spin_multiplicity (int): Spin multiplicity for molecule. Defaults to None, which means that the spin multiplicity is set to 1 if the molecule has no unpaired...
Insert a site to the molecule. Args: i (int): Index to insert site species: species of inserted site coords (3x1 array): coordinates of inserted site validate_proximity (bool): Whether to check if inserted site is too close to an existing site. De...
Remove all occurrences of a species from a molecule. Args: species: Species to remove. def remove_species(self, species): """ Remove all occurrences of a species from a molecule. Args: species: Species to remove. """ new_sites = [] speci...
Delete sites with at indices. Args: indices: Sequence of indices of sites to delete. def remove_sites(self, indices): """ Delete sites with at indices. Args: indices: Sequence of indices of sites to delete. """ self._sites = [self._sites[i] for ...
Translate specific sites by some vector, keeping the sites within the unit cell. Args: indices (list): List of site indices on which to perform the translation. vector (3x1 array): Translation vector for sites. def translate_sites(self, indices=None, vector=None...
Apply a symmetry operation to the molecule. Args: symmop (SymmOp): Symmetry operation to apply. def apply_operation(self, symmop): """ Apply a symmetry operation to the molecule. Args: symmop (SymmOp): Symmetry operation to apply. """ def opera...
:param structure (bulk structure to be scaled up - typically conventional unit cell) :return: defect_structure, with charge applied def apply_transformation(self, structure): """ :param structure (bulk structure to be scaled up - typically conventional unit cell) :return: ...
create the polymer from the monomer Args: monomer (Molecule) mon_vector (numpy.array): molecule vector that starts from the start atom index to the end atom index def _create(self, monomer, mon_vector): """ create the polymer from the monomer Ar...
pick a move at random from the list of moves def _next_move_direction(self): """ pick a move at random from the list of moves """ nmoves = len(self.moves) move = np.random.randint(1, nmoves+1) while self.prev_move == (move + 3) % nmoves: move = np.random.rand...
rotate the monomer so that it is aligned along the move direction Args: monomer (Molecule) mon_vector (numpy.array): molecule vector that starts from the start atom index to the end atom index move_direction (numpy.array): the direction of the polymer chain ...
extend the polymer molecule by adding a monomer along mon_vector direction Args: monomer (Molecule): monomer molecule mon_vector (numpy.array): monomer vector that points from head to tail. move_direction (numpy.array): direction along which the monomer will ...
Internal method to format values in the packmol parameter dictionaries Args: param_val: Some object to turn into String Returns: string representation of the object def _format_param_val(self, param_val): """ Internal method to format va...
Set the box size for the molecular assembly def _set_box(self): """ Set the box size for the molecular assembly """ net_volume = 0.0 for idx, mol in enumerate(self.mols): length = max([np.max(mol.cart_coords[:, i])-np.min(mol.cart_coords[:, i]) ...
Write the packmol input file to the input directory. Args: input_dir (string): path to the input directory def _write_input(self, input_dir="."): """ Write the packmol input file to the input directory. Args: input_dir (string): path to the input directory ...
Write the input file to the scratch directory, run packmol and return the packed molecule. Args: copy_to_current_on_exit (bool): Whether or not to copy the packmol input/output files from the scratch directory to the current directory. site_proper...
dump the molecule into pdb file with custom residue name and number. def write_pdb(self, mol, filename, name=None, num=None): """ dump the molecule into pdb file with custom residue name and number. """ # ugly hack to get around the openbabel issues with inconsistent # residue ...
map each residue to the corresponding molecule. def _set_residue_map(self): """ map each residue to the corresponding molecule. """ self.map_residue_to_mol = {} lookup = {} for idx, mol in enumerate(self.mols): if not mol.formula in lookup: mo...
Convert list of openbabel atoms to MOlecule. Args: atoms ([OBAtom]): list of OBAtom objects residue_name (str): the key in self.map_residue_to_mol. Usec to restore the site properties in the final packed molecule. site_property (str): the site property to be ...
Restore the site properties for the final packed molecule. Args: site_property (str): filename (str): path to the final packed molecule. Returns: Molecule def restore_site_properties(self, site_property="ff_map", filename=None): """ Restore the site...
Write the input/data files and run LAMMPS. def run(self): """ Write the input/data files and run LAMMPS. """ lammps_cmd = self.lammps_bin + ['-in', self.input_filename] print("Running: {}".format(" ".join(lammps_cmd))) p = Popen(lammps_cmd, stdout=PIPE, stderr=PIPE) ...
Utility method to get an Element or Specie from an input obj. If obj is in itself an element or a specie, it is returned automatically. If obj is an int or a string representing an integer, the Element with the atomic number obj is returned. If obj is a string, Specie parsing will be attempted (e.g., Mn...
Average ionic radius for element (with units). The average is taken over all oxidation states of the element for which data is present. def average_ionic_radius(self): """ Average ionic radius for element (with units). The average is taken over all oxidation states of the element for wh...
Average cationic radius for element (with units). The average is taken over all positive oxidation states of the element for which data is present. def average_cationic_radius(self): """ Average cationic radius for element (with units). The average is taken over all positive oxi...