INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add a structure to the visualizer. Args: structure: structure to visualize reset_camera: Set to True to reset the camera to a default determined based on the structure. to_unit_cell: Whether or not to fall back sites into the unit cell.
def set_structure(self, structure, reset_camera=True, to_unit_cell=True): """ Add a structure to the visualizer. Args: structure: structure to visualize reset_camera: Set to True to reset the camera to a default determined based on the structure. ...
Zoom the camera view by a factor.
def zoom(self, factor): """ Zoom the camera view by a factor. """ camera = self.ren.GetActiveCamera() camera.Zoom(factor) self.ren_win.Render()
Display the visualizer.
def show(self): """ Display the visualizer. """ self.iren.Initialize() self.ren_win.SetSize(800, 800) self.ren_win.SetWindowName(self.title) self.ren_win.Render() self.iren.Start()
Add a site to the render window. The site is displayed as a sphere, the color of which is determined based on the element. Partially occupied sites are displayed as a single element color, though the site info still shows the partial occupancy. Args: site: Site to add.
def add_site(self, site): """ Add a site to the render window. The site is displayed as a sphere, the color of which is determined based on the element. Partially occupied sites are displayed as a single element color, though the site info still shows the partial occupancy. ...
Add text at a coordinate. Args: coords: Coordinates to add text at. text: Text to place. color: Color for text as RGB. Defaults to black.
def add_text(self, coords, text, color=(0, 0, 0)): """ Add text at a coordinate. Args: coords: Coordinates to add text at. text: Text to place. color: Color for text as RGB. Defaults to black. """ source = vtk.vtkVectorText() source.Se...
Adds a line. Args: start: Starting coordinates for line. end: Ending coordinates for line. color: Color for text as RGB. Defaults to grey. width: Width of line. Defaults to 1.
def add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1): """ Adds a line. Args: start: Starting coordinates for line. end: Ending coordinates for line. color: Color for text as RGB. Defaults to grey. width: Width of line. Defaults to 1. ...
Adds a polyhedron. Args: neighbors: Neighbors of the polyhedron (the vertices). center: The atom in the center of the polyhedron. color: Color for text as RGB. opacity: Opacity of the polyhedron draw_edges: If set to True, the a line will be drawn at ...
def add_polyhedron(self, neighbors, center, color, opacity=1.0, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a polyhedron. Args: neighbors: Neighbors of the polyhedron (the vertices). center: Th...
Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a l...
def add_triangle(self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): """ Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be draw...
Adds bonds for a site. Args: neighbors: Neighbors of the site. center: The site in the center for all bonds. color: Color of the tubes representing the bonds opacity: Opacity of the tubes representing the bonds radius: Radius of tube s representing th...
def add_bonds(self, neighbors, center, color=None, opacity=None, radius=0.1): """ Adds bonds for a site. Args: neighbors: Neighbors of the site. center: The site in the center for all bonds. color: Color of the tubes representing the bonds ...
Convenience function which returns the unit vector aligned with the miller index.
def get_mi_vec(slab): """ Convenience function which returns the unit vector aligned with the miller index. """ mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1]) return mvec / np.linalg.norm(mvec)
Gets the transformation to rotate the z axis into the miller index
def get_rot(slab): """ Gets the transformation to rotate the z axis into the miller index """ new_z = get_mi_vec(slab) a, b, c = slab.lattice.matrix new_x = a / np.linalg.norm(a) new_y = np.cross(new_z, new_x) x, y, z = np.eye(3) rot_matrix = np.array([np.dot(*el) for el in ...
converts a cartesian coordinate such that it is inside the unit cell.
def put_coord_inside(lattice, cart_coordinate): """ converts a cartesian coordinate such that it is inside the unit cell. """ fc = lattice.get_fractional_coords(cart_coordinate) return lattice.get_cartesian_coords([c - np.floor(c) for c in fc])
reorients a structure such that the z axis is concurrent with the normal to the A-B plane
def reorient_z(structure): """ reorients a structure such that the z axis is concurrent with the normal to the A-B plane """ struct = structure.copy() sop = get_rot(struct) struct.apply_operation(sop) return struct
Function that helps visualize the slab in a 2-D plot, for convenient viewing of output of AdsorbateSiteFinder. Args: slab (slab): Slab object to be visualized ax (axes): matplotlib axes with which to visualize scale (float): radius scaling for sites repeat (int): number of repea...
def plot_slab(slab, ax, scale=0.8, repeat=5, window=1.5, draw_unit_cell=True, decay=0.2, adsorption_sites=True): """ Function that helps visualize the slab in a 2-D plot, for convenient viewing of output of AdsorbateSiteFinder. Args: slab (slab): Slab object to be visualized ...
This method constructs the adsorbate site finder from a bulk structure and a miller index, which allows the surface sites to be determined from the difference in bulk and slab coordination, as opposed to the height threshold. Args: structure (Structure): structure from which...
def from_bulk_and_miller(cls, structure, miller_index, min_slab_size=8.0, min_vacuum_size=10.0, max_normal_search=None, center_slab=True, selective_dynamics=False, undercoord_threshold=0.09): """ This method construct...
This method finds surface sites by determining which sites are within a threshold value in height from the topmost site in a list of sites Args: site_list (list): list of sites from which to select surface sites height (float): threshold in angstroms of distance from topmost ...
def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05): """ This method finds surface sites by determining which sites are within a threshold value in height from the topmost site in a list of sites Args: site_list (list): list of sites from which to select su...
Assigns site properties.
def assign_site_properties(self, slab, height=0.9): """ Assigns site properties. """ if 'surface_properties' in slab.site_properties.keys(): return slab else: surf_sites = self.find_surface_sites_by_height(slab, height) surf_props = ['surface' if s...
Gets an extended surface mesh for to use for adsorption site finding by constructing supercell of surface sites Args: repeat (3-tuple): repeat for getting extended surface mesh
def get_extended_surface_mesh(self, repeat=(5, 5, 1)): """ Gets an extended surface mesh for to use for adsorption site finding by constructing supercell of surface sites Args: repeat (3-tuple): repeat for getting extended surface mesh """ surf_str = Structur...
Finds surface sites according to the above algorithm. Returns a list of corresponding cartesian coordinates. Args: distance (float): distance from the coordinating ensemble of atoms along the miller index for the site (i. e. the distance from the slab itself...
def find_adsorption_sites(self, distance=2.0, put_inside=True, symm_reduce=1e-2, near_reduce=1e-2, positions=['ontop', 'bridge', 'hollow'], no_obtuse_hollow=True): """ Finds surface sites according to the above alg...
Reduces the set of adsorbate sites by finding removing symmetrically equivalent duplicates Args: coords_set: coordinate set in cartesian coordinates threshold: tolerance for distance equivalence, used as input to in_coord_list_pbc for dupl. checking
def symm_reduce(self, coords_set, threshold=1e-6): """ Reduces the set of adsorbate sites by finding removing symmetrically equivalent duplicates Args: coords_set: coordinate set in cartesian coordinates threshold: tolerance for distance equivalence, used ...
Prunes coordinate set for coordinates that are within threshold Args: coords_set (Nx3 array-like): list or array of coordinates threshold (float): threshold value for distance
def near_reduce(self, coords_set, threshold=1e-4): """ Prunes coordinate set for coordinates that are within threshold Args: coords_set (Nx3 array-like): list or array of coordinates threshold (float): threshold value for distance """ unique_coord...
Finds the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm. Args: site_list (list of sites): list of sites indices (list of ints): list of ints from which to select sites from site list ...
def ensemble_center(self, site_list, indices, cartesian=True): """ Finds the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm. Args: site_list (list of sites): list of sites indices (list...
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...
def add_adsorbate(self, molecule, ads_coord, repeat=None, reorient=True): """ 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 ...
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_properties based on surface, subsurface site properties Args: slab (Slab): slab for which to assign selective dynamics """ sd_list = [] sd_list = [[False,...
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...
def generate_adsorption_structures(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of pre...
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...
def adsorb_both_surfaces(self, molecule, repeat=None, min_lw=5.0, reorient=True, find_args={}): """ Function that generates all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy whe...
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: raise TypeError("""\ types_of_species cannot be used with disordered structures and partial occupancies. ...
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=[] # get title title_in=str(ro...
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. """ return tuple((i for i, specie in enumerate(self.species) if specie.symbol == 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() for site in self: prop_keys.update(site.properties.keys()) for k in prop_keys: ...
(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 Composition(elmap)
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 for site in self: for specie, amt in site.species.items(): charge += getattr(specie, "oxi_s...
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 sites. Args: i: Index of first site. j: Index of second site. k: Index of third site. Returns: Angle in degrees. """ v1 = self[i].c...
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) -> float: """ 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: ...
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...
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool: """ 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 ...
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. 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. """ if len(values) ...
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...
def replace_species(self, species_mapping): """ 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 ...
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 oxidation states. E.g., {"Li":1, "Fe":2, "P":5, "O":-2} """ try: for site in self.sites: new_sp = ...
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. 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] """ if len(oxidation_states) ...
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 new_sp[Element(sym)] += occu...
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 using Composition.oxi_state_guesses() Args: **kwargs: parameters to pass into oxi_state_guesses() """ oxid_guess = self.composition.oxi_state_guesses(...
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 associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5} """ for site in self.sites: new_sp = {} for sp, occu in s...
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] """ if len(spins) != len(self.sites): raise ValueError("Spin of all sites must be " ...
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", None) new_sp[Specie(sp.s...
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_sites, **kwargs): """ 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: [...
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...
def from_sites(cls, sites, charge=None, validate_proximity=False, to_unit_cell=False): """ Convenience constructor to make a Structure from a list of sites. Args: sites: Sequence of PeriodicSites. Sites must have the same lattice. valid...
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 ...
def from_spacegroup(cls, sg, lattice, species, coords, site_properties=None, coords_are_cartesian=False, tol=1e-5): """ Generate a structure using a spacegroup. Note that only symmetrically distinct species and coords should be provided. All equivalent sites are g...
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`): ...
def from_magnetic_spacegroup( cls, msg, lattice, species, coords, site_properties, transform_setting=None, coords_are_cartesian=False, tol=1e-5): """ Generate a structure using a magnetic spacegroup. Note that only symmetrically distinct species, coords and magmoms should...
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:...
def get_space_group_info(self, symprec=1e-2, angle_tolerance=5.0): """ 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 defini...
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...
def matches(self, other, **kwargs): """ 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 ...
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 ...
def get_distance(self, i, j, jimage=None): """ 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 lat...
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 ...
def get_sites_in_sphere(self, pt, r, include_index=False, include_image=False): """ 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 (paralle...
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...
def get_neighbors(self, site, r, include_index=False, include_image=False): """ 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. incl...
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...
def get_all_neighbors(self, r, include_index=False, include_image=False): """ 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 cry...
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...
def get_neighbors_in_shell(self, origin, r, dr, include_index=False, include_image=False): """ 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): In...
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...
def get_sorted_structure(self, key=None, reverse=False): """ 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 argumen...
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: reduction_algo (str): The lattice reduction algorithm to use. Currently supported options are "niggli" or "LLL". """ if reduction_algo == "niggli": ...
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...
def copy(self, site_properties=None, sanitize=False): """ 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 ...
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...
def interpolate(self, end_structure, nimages=10, interpolate_lattices=False, pbc=True, autosort_tol=0): """ Interpolate between this structure and end_structure. Useful for construction of NEB inputs. Args: end_structure (Structure): structure to interpol...
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 ...
def get_miller_index_from_site_indexes(self, site_ids, round_dp=4, verbose=True): """ 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 t...
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...
def get_primitive_structure(self, tolerance=0.25, use_site_props=False, constrain_latt=None): """ 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...
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...
def as_dict(self, verbosity=1, fmt=None, **kwargs): """ 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 an...
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 representation of Structure created using as_dict(). Args: d (dict): Dict representation of structure. Returns: Structure object """ if fmt == "abivars": ...
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...
def to(self, fmt=None, filename=None, **kwargs): """ 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 inc...
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...
def from_str(cls, input_string, fmt, primitive=False, sort=False, merge_tol=0.0): """ 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...
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...
def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0): """ 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...
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 center / total_weight
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. ...
def from_sites(cls, sites, charge=0, spin_multiplicity=None, validate_proximity=False): """ 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. ...
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...
def break_bond(self, ind1, ind2, tol=0.2): """ 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. Bas...
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. Args: tol (float): The tol to determine bonds in a structure. See CovalentBond.is_bonded. Returns: List of bonds """ bonds = [] for si...
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": self._spin_multiplicity, "sites": []...
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 using as_dict(). Args: d (dict): dict representation of Molecule. Returns: Molecule object """ sites = [Site.from_dict(sd) for sd in d["sites"]] ...
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_sphere(self, pt, r): """ 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 proces...
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...
def get_neighbors(self, site, r): """ 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...
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...
def get_neighbors_in_shell(self, origin, r, dr): """ 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...
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...
def get_boxed_structure(self, a, b, c, images=(1, 1, 1), random_rotation=False, min_dist=1, cls=None, offset=None, no_cross=False): """ Creates a Structure from a Molecule by putting the Molecule in the center of a orthorhombic box. Useful ...
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. """ center = self.center_of_mass new_coords = np.array(self.cart_coords) - center return self.__class__(s...
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...
def to(self, fmt=None, filename=None): """ 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",...
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...
def from_str(cls, input_string, fmt): """ 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 ...
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...
def from_file(cls, filename): """ 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 ...
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...
def append(self, species, coords, coords_are_cartesian=False, validate_proximity=False, properties=None): """ Append a site to the structure. Args: species: Species of inserted site coords (3x1 array): Coordinates of inserted site coords_are_ca...
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...
def insert(self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, properties=None): """ Insert a site to the structure. Args: i (int): Index to insert site species (species-like): Species of inserted site coords (3x1 ar...
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, ...
def replace(self, i, species, coords=None, coords_are_cartesian=False, properties=None): """ 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-...
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...
def substitute(self, index, func_grp, bond_order=1): """ 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...
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 to remove, e.g., ["Li", "Na"]. """ new_sites = [] species = [get_el_sp(s) for s in species] for site in self._sites:...
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 enumerate(self._sites) if i not in indices]
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...
def apply_operation(self, symmop, fractional=False): """ 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 (...
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_lattice (Lattice): New lattice """ self._lattice = new_lattice for site in self._sites: site.lattice = new_latti...
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...
def apply_strain(self, strain): """ 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 cal...
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, ...
def sort(self, key=None, reverse=False): """ 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 ISt...
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...
def translate_sites(self, indices, vector, frac_coords=True, to_unit_cell=True): """ 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 ...
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...
def rotate_sites(self, indices=None, theta=0, axis=None, anchor=None, to_unit_cell=True): """ Rotate specific sites by some angle around vector at anchor. Args: indices (list): List of site indices on which to perform the translation. ...
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 symmetries. Args: distance (float): Distance in angstroms by which to perturb each site. """ def get_rand_vec(): # deals with zer...
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,...
def make_supercell(self, scaling_matrix, to_unit_cell=True): """ 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 defin...
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...
def merge_sites(self, tol=0.01, mode="sum"): """ 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 ...
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...
def append(self, species, coords, validate_proximity=True, properties=None): """ 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 ...
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...
def set_charge_and_spin(self, charge, spin_multiplicity=None): """ 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 tha...
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...
def insert(self, i, species, coords, validate_proximity=False, properties=None): """ 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 ...
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 = [] species = [get_el_sp(sp) for sp in species] for site in self._sites: new_sp_occu = {sp: amt fo...