INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parses. transdos ( total DOS ) and. transdos_x_y ( partial DOS ) files Args: path_dir: ( str ) dir containing DOS files efermi: ( float ) Fermi energy dos_spin: ( int ) - 1 for spin down + 1 for spin up trim_dos: ( bool ) whether to post - process/ trim DOS
def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): """ Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files Args: path_dir: (str) dir containing DOS files efermi: (float) Fermi energy dos_spin: (int) -1 for spin down, +1 for spin ...
Parses boltztrap. intrans mainly to extract the value of scissor applied to the bands or some other inputs Args: path_dir: ( str ) dir containing the boltztrap. intrans file Returns: intrans ( dict ): a dictionary containing various inputs that had been used in the Boltztrap run.
def parse_intrans(path_dir): """ Parses boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs Args: path_dir: (str) dir containing the boltztrap.intrans file Returns: intrans (dict): a dictionary containing various inpu...
Parses boltztrap. struct file ( only the volume ) Args: path_dir: ( str ) dir containing the boltztrap. struct file
def parse_struct(path_dir): """ Parses boltztrap.struct file (only the volume) Args: path_dir: (str) dir containing the boltztrap.struct file Returns: (float) volume """ with open(os.path.join(path_dir, "boltztrap.struct"), 'r') as f: ...
Parses the conductivity and Hall tensors Args: path_dir: Path containing. condtens/. halltens files doping_levels: ( [ float ] ) - doping lvls parse outtrans to get this
def parse_cond_and_hall(path_dir, doping_levels=None): """ Parses the conductivity and Hall tensors Args: path_dir: Path containing .condtens / .halltens files doping_levels: ([float]) - doping lvls, parse outtrans to get this Returns: mu_steps, cond,...
get a BoltztrapAnalyzer object from a set of files
def from_files(path_dir, dos_spin=1): """ get a BoltztrapAnalyzer object from a set of files Args: path_dir: directory where the boltztrap files are dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down Returns: a BoltztrapAnalyzer object ...
Check for the defined errors put all found errors in self. errors return True if any were found False if no errors were found
def check(self): """ Check for the defined errors, put all found errors in self.errors, return True if any were found False if no errors were found """ parser = get_parser(self.scheduler_adapter.name, err_file=self.err_file, out_file=self.out_file, run...
Method to directly apply the corrections.
def apply_corrections(self): """ Method to directly apply the corrections. """ for error in self.errors: for solution in error.scheduler_adapter_solutions: if self.scheduler_adapter is not None: if self.scheduler_adapter.__getattribut__(sol...
Generator that parses dump file ( s ).
def parse_lammps_dumps(file_pattern): """ Generator that parses dump file(s). Args: file_pattern (str): Filename to parse. The timestep wildcard (e.g., dump.atom.'*') is supported and the files are parsed in the sequence of timestep. Yields: LammpsDump for each ...
Parses log file with focus on thermo data. Both one and multi line formats are supported. Any incomplete runs ( no Loop time marker ) will not be parsed.
def parse_lammps_log(filename="log.lammps"): """ Parses log file with focus on thermo data. Both one and multi line formats are supported. Any incomplete runs (no "Loop time" marker) will not be parsed. Notes: SHAKE stats printed with thermo data are not supported yet. They are igno...
Constructor from string parsing.
def from_string(cls, string): """ Constructor from string parsing. Args: string (str): Input string. """ lines = string.split("\n") timestep = int(lines[1]) natoms = int(lines[3]) box_arr = np.loadtxt(StringIO("\n".join(lines[5:8]))) ...
Helper function for calling aconvasp with different arguments
def run_aconvasp_command(command, structure): """ Helper function for calling aconvasp with different arguments """ poscar = Poscar(structure) p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) ou...
Get kpoint divisions for a given k - point density ( per reciprocal - atom ): kppa and a given structure
def get_num_division_kpoints(structure, kppa): """ Get kpoint divisions for a given k-point density (per reciprocal-atom): kppa and a given structure """ output = run_aconvasp_command(["aconvasp", "--kpoints", str(kppa)], structure) tmp = output[0].rsplit("\n")[...
Get a minkowski reduced structure
def get_minkowski_red(structure): """ Get a minkowski reduced structure """ output = run_aconvasp_command(["aconvasp", "--kpath"], structure) started = False poscar_string = "" if "ERROR" in output[1]: raise AconvaspError(output[1]) for line in output[0].split("\n"): if s...
Get a minkowski reduced structure
def get_conv_struct(structure): """ Get a minkowski reduced structure """ output = run_aconvasp_command(["aconvasp", "--std_conv"], structure) if "ERROR" in output[1]: raise AconvaspError(output[1]) tmp = Poscar.from_string(output[0]) return {'struct': tmp.structure, 'comm': tmp.comm...
get a kpoint file ready to be ran in VASP along the symmetry lines of the Brillouin Zone
def get_vasp_kpoint_file_sym(structure): """ get a kpoint file ready to be ran in VASP along the symmetry lines of the Brillouin Zone """ output = run_aconvasp_command(["aconvasp", "--kpath"], structure) if "ERROR" in output[1]: raise AconvaspError(output[1]) started = False kpoi...
Partial returns a partial object and therefore we cannot inherit class methods defined in FloatWithUnit. This function calls partial and patches the new class before returning.
def _my_partial(func, *args, **kwargs): """ Partial returns a partial object and therefore we cannot inherit class methods defined in FloatWithUnit. This function calls partial and patches the new class before returning. """ newobj = partial(func, *args, **kwargs) # monkey patch newobj.f...
Returns a FloatWithUnit instance if obj is scalar a dictionary of objects with units if obj is a dict else an instance of ArrayWithFloatWithUnit.
def obj_with_unit(obj, unit): """ Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`. Args: unit: Specific units (eV, Ha, m, ang, etc.). """ unit_type = _UNAME2UTYPE[unit] if isi...
Useful decorator to assign units to the output of a function. You can also use it to standardize the output units of a function that already returns a FloatWithUnit or ArrayWithUnit. For sequences all values in the sequences are assigned the same unit. It works with Python sequences only. The creation of numpy arrays l...
def unitized(unit): """ Useful decorator to assign units to the output of a function. You can also use it to standardize the output units of a function that already returns a FloatWithUnit or ArrayWithUnit. For sequences, all values in the sequences are assigned the same unit. It works with Python s...
Converts all units to base SI units including derived units.
def as_base_units(self): """ Converts all units to base SI units, including derived units. Returns: (base_units_dict, scaling factor). base_units_dict will not contain any constants, which are gathered in the scaling factor. """ b = collections.defaultdic...
Returns a conversion factor between this unit and a new unit. Compound units are supported but must have the same powers in each unit type.
def get_conversion_factor(self, new_unit): """ Returns a conversion factor between this unit and a new unit. Compound units are supported, but must have the same powers in each unit type. Args: new_unit: The new unit. """ uo_base, ofactor = self.as_ba...
Initialize a FloatWithUnit from a string. Example Memory. from_string ( 1. Mb )
def from_string(cls, s): """ Initialize a FloatWithUnit from a string. Example Memory.from_string("1. Mb") """ # Extract num and unit string. s = s.strip() for i, char in enumerate(s): if char.isalpha() or char.isspace(): break else: ...
Conversion to a new_unit. Right now only supports 1 to 1 mapping of units of each type.
def to(self, new_unit): """ Conversion to a new_unit. Right now, only supports 1 to 1 mapping of units of each type. Args: new_unit: New unit type. Returns: A FloatWithUnit object in the new units. Example usage: >>> e = Energy(1.1, "eV"...
Conversion to a new_unit.
def to(self, new_unit): """ Conversion to a new_unit. Args: new_unit: New unit type. Returns: A ArrayWithFloatWithUnit object in the new units. Example usage: >>> e = EnergyArray([1, 1.1], "Ha") >>> e.to("eV") arr...
Returns a string showing the available conversions. Useful tool in interactive mode.
def conversions(self): """ Returns a string showing the available conversions. Useful tool in interactive mode. """ return "\n".join(str(self.to(unit)) for unit in self.supported_units)
Attempt to convert a vector of floats to whole numbers.
def get_integer_index( miller_index: bool, round_dp: int = 4, verbose: bool = True ) -> Tuple[int, int, int]: """ Attempt to convert a vector of floats to whole numbers. Args: miller_index (list of float): A list miller indexes. round_dp (int, optional): The number of decimal places to ...
Returns the angles ( alpha beta gamma ) of the lattice.
def angles(self) -> Tuple[float]: """ Returns the angles (alpha, beta, gamma) of the lattice. """ m = self._matrix lengths = self.lengths angles = np.zeros(3) for i in range(3): j = (i + 1) % 3 k = (i + 2) % 3 angles[i] = abs_ca...
Inverse of lattice matrix.
def inv_matrix(self) -> np.ndarray: """ Inverse of lattice matrix. """ if self._inv_matrix is None: self._inv_matrix = inv(self._matrix) self._inv_matrix.setflags(write=False) return self._inv_matrix
The metric tensor of the lattice.
def metric_tensor(self) -> np.ndarray: """ The metric tensor of the lattice. """ return dot(self._matrix, self._matrix.T)
Returns the cartesian coordinates given fractional coordinates.
def get_cartesian_coords(self, fractional_coords: Vector3Like) -> np.ndarray: """ Returns the cartesian coordinates given fractional coordinates. Args: fractional_coords (3x1 array): Fractional coords. Returns: Cartesian coordinates """ return do...
Returns the fractional coordinates given cartesian coordinates.
def get_fractional_coords(self, cart_coords: Vector3Like) -> np.ndarray: """ Returns the fractional coordinates given cartesian coordinates. Args: cart_coords (3x1 array): Cartesian coords. Returns: Fractional coordinates. """ return dot(cart_coo...
Returns the distance between the hkl plane and the origin
def d_hkl(self, miller_index: Vector3Like) -> float: """ Returns the distance between the hkl plane and the origin Args: miller_index ([h,k,l]): Miller index of plane Returns: d_hkl (float) """ gstar = self.reciprocal_lattice_crystallographic.me...
Convenience constructor for a tetragonal lattice.
def tetragonal(a: float, c: float): """ Convenience constructor for a tetragonal lattice. Args: a (float): *a* lattice parameter of the tetragonal cell. c (float): *c* lattice parameter of the tetragonal cell. Returns: Tetragonal lattice of dimension...
Convenience constructor for an orthorhombic lattice.
def orthorhombic(a: float, b: float, c: float): """ Convenience constructor for an orthorhombic lattice. Args: a (float): *a* lattice parameter of the orthorhombic cell. b (float): *b* lattice parameter of the orthorhombic cell. c (float): *c* lattice paramet...
Convenience constructor for a monoclinic lattice.
def monoclinic(a: float, b: float, c: float, beta: float): """ Convenience constructor for a monoclinic lattice. Args: a (float): *a* lattice parameter of the monoclinc cell. b (float): *b* lattice parameter of the monoclinc cell. c (float): *c* lattice param...
Convenience constructor for a hexagonal lattice.
def hexagonal(a: float, c: float): """ Convenience constructor for a hexagonal lattice. Args: a (float): *a* lattice parameter of the hexagonal cell. c (float): *c* lattice parameter of the hexagonal cell. Returns: Hexagonal lattice of dimensions a x...
Convenience constructor for a rhombohedral lattice.
def rhombohedral(a: float, alpha: float): """ Convenience constructor for a rhombohedral lattice. Args: a (float): *a* lattice parameter of the rhombohedral cell. alpha (float): Angle for the rhombohedral lattice in degrees. Returns: Rhombohedral lat...
Create a Lattice using unit cell lengths and angles ( in degrees ).
def from_lengths_and_angles(abc: List[float], ang: List[float]): """ Create a Lattice using unit cell lengths and angles (in degrees). Args: abc (3x1 array): Lattice parameters, e.g. (4, 4, 5). ang (3x1 array): Lattice angles in degrees, e.g., (90,90,120). Retur...
Create a Lattice using unit cell lengths and angles ( in degrees ).
def from_parameters( cls, a: float, b: float, c: float, alpha: float, beta: float, gamma: float, vesta: bool = False, ): """ Create a Lattice using unit cell lengths and angles (in degrees). Args: a (float): *a* lat...
Create a Lattice from a dictionary containing the a b c alpha beta and gamma parameters if fmt is None.
def from_dict(cls, d: Dict, fmt: str = None, **kwargs): """ Create a Lattice from a dictionary containing the a, b, c, alpha, beta, and gamma parameters if fmt is None. If fmt == "abivars", the function build a `Lattice` object from a dictionary with the Abinit variables `acell`...
Volume of the unit cell.
def volume(self) -> float: """ Volume of the unit cell. """ m = self._matrix return float(abs(dot(np.cross(m[0], m[1]), m[2])))
Returns ( lattice lengths lattice angles ).
def lengths_and_angles(self) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]: """ Returns (lattice lengths, lattice angles). """ return self.lengths, self.angles
Return the reciprocal lattice. Note that this is the standard reciprocal lattice used for solid state physics with a factor of 2 * pi. If you are looking for the crystallographic reciprocal lattice use the reciprocal_lattice_crystallographic property. The property is lazily generated for efficiency.
def reciprocal_lattice(self) -> "Lattice": """ Return the reciprocal lattice. Note that this is the standard reciprocal lattice used for solid state physics with a factor of 2 * pi. If you are looking for the crystallographic reciprocal lattice, use the reciprocal_lattice_crystal...
Json - serialization dict representation of the Lattice.
def as_dict(self, verbosity: int = 0) -> Dict: """"" Json-serialization dict representation of the Lattice. Args: verbosity (int): Verbosity level. Default of 0 only includes the matrix representation. Set to 1 for more details. """ d = { ...
Finds all mappings between current lattice and another lattice.
def find_all_mappings( self, other_lattice: "Lattice", ltol: float = 1e-5, atol: float = 1, skip_rotation_matrix: bool = False, ) -> Iterator[Tuple["Lattice", Optional[np.ndarray], np.ndarray]]: """ Finds all mappings between current lattice and another lattic...
Finds a mapping between current lattice and another lattice. There are an infinite number of choices of basis vectors for two entirely equivalent lattices. This method returns a mapping that maps other_lattice to this lattice.
def find_mapping( self, other_lattice: "Lattice", ltol: float = 1e-5, atol: float = 1, skip_rotation_matrix: bool = False, ) -> Optional[Tuple["Lattice", Optional[np.ndarray], np.ndarray]]: """ Finds a mapping between current lattice and another lattice. There...
Performs a Lenstra - Lenstra - Lovasz lattice basis reduction to obtain a c - reduced basis. This method returns a basis which is as good as possible with good defined by orthongonality of the lattice vectors.
def _calculate_lll(self, delta: float = 0.75) -> Tuple[np.ndarray, np.ndarray]: """ Performs a Lenstra-Lenstra-Lovasz lattice basis reduction to obtain a c-reduced basis. This method returns a basis which is as "good" as possible, with "good" defined by orthongonality of the lattice vect...
Given fractional coordinates in the lattice basis returns corresponding fractional coordinates in the lll basis.
def get_lll_frac_coords(self, frac_coords: Vector3Like) -> np.ndarray: """ Given fractional coordinates in the lattice basis, returns corresponding fractional coordinates in the lll basis. """ return dot(frac_coords, self.lll_inverse)
Given fractional coordinates in the lll basis returns corresponding fractional coordinates in the lattice basis.
def get_frac_coords_from_lll(self, lll_frac_coords: Vector3Like) -> np.ndarray: """ Given fractional coordinates in the lll basis, returns corresponding fractional coordinates in the lattice basis. """ return dot(lll_frac_coords, self.lll_mapping)
Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse - Kunstleve N. K. Sauter & P. D. Adams Acta Crystallographica Section A Foundations of Crystallography 2003 60 ( 1 ) 1 - 6. doi: 10. 1107/ S010876730302186X
def get_niggli_reduced_lattice(self, tol: float = 1e-5) -> "Lattice": """ Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams, Acta Crystallographica Section A Foundations of Crystallography, 2003, 60(1)...
Return a new Lattice with volume new_volume by performing a scaling of the lattice vectors so that length proportions and angles are preserved.
def scale(self, new_volume: float) -> "Lattice": """ Return a new Lattice with volume new_volume by performing a scaling of the lattice vectors so that length proportions and angles are preserved. Args: new_volume: New volume to scale to. Ret...
Returns the Wigner - Seitz cell for the given lattice.
def get_wigner_seitz_cell(self) -> List[List[np.ndarray]]: """ Returns the Wigner-Seitz cell for the given lattice. Returns: A list of list of coordinates. Each element in the list is a "facet" of the boundary of the Wigner Seitz cell. For instance, a list of...
Compute the scalar product of vector ( s ).
def dot( self, coords_a: Vector3Like, coords_b: Vector3Like, frac_coords: bool = False ) -> np.ndarray: """ Compute the scalar product of vector(s). Args: coords_a, coords_b: Array-like objects with the coordinates. frac_coords (bool): Boolean stating whether...
Compute the norm of vector ( s ).
def norm(self, coords: Vector3Like, frac_coords: bool = True) -> float: """ Compute the norm of vector(s). Args: coords: Array-like object with the coordinates. frac_coords: Boolean stating whether the vector corresponds to fractional or ...
Find all points within a sphere from the point taking into account periodic boundary conditions. This includes sites in other periodic images.
def get_points_in_sphere( self, frac_points: List[Vector3Like], center: Vector3Like, r: float, zip_results=True, ) -> Union[ List[Tuple[np.ndarray, float, int, np.ndarray]], Tuple[List[np.ndarray], List[float], List[int], List[np.ndarray]], ]: """ ...
Returns the distances between two lists of coordinates taking into account periodic boundary conditions and the lattice. Note that this computes an MxN array of distances ( i. e. the distance between each point in fcoords1 and every coordinate in fcoords2 ). This is different functionality from pbc_diff.
def get_all_distances( self, fcoords1: Union[Vector3Like, List[Vector3Like]], fcoords2: Union[Vector3Like, List[Vector3Like]], ) -> np.ndarray: """ Returns the distances between two lists of coordinates taking into account periodic boundary conditions and the lattice....
Gets distance between two frac_coords assuming periodic boundary conditions. If the index jimage is not specified it selects the j image nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations. If the index jimage is specified it returns the distance between the frac_co...
def get_distance_and_image( self, frac_coords1: Vector3Like, frac_coords2: Vector3Like, jimage: Optional[Union[List[int], np.ndarray]] = None, ) -> Tuple[float, np.ndarray]: """ Gets distance between two frac_coords assuming periodic boundary conditions. If th...
Get the Miller index of a plane from a list of site coordinates.
def get_miller_index_from_coords( self, coords: Vector3Like, coords_are_cartesian: bool = True, round_dp: int = 4, verbose: bool = True, ) -> Tuple[int, int, int]: """ Get the Miller index of a plane from a list of site coordinates. A minimum of 3 set...
read route line in gaussian input/ output and return functional basis_set and a dictionary of other route parameters
def read_route_line(route): """ read route line in gaussian input/output and return functional basis_set and a dictionary of other route parameters Args: route (str) : the route line return functional (str) : the method (HF, PBE ...) basis_set (str) : the basis set ...
Helper method to parse coordinates.
def _parse_coords(coord_lines): """ Helper method to parse coordinates. """ paras = {} var_pattern = re.compile(r"^([A-Za-z]+\S*)[\s=,]+([\d\-\.]+)$") for l in coord_lines: m = var_pattern.match(l.strip()) if m: paras[m.group(1).str...
Creates GaussianInput from a string.
def from_string(contents): """ Creates GaussianInput from a string. Args: contents: String representing an Gaussian input file. Returns: GaussianInput object """ lines = [l.strip() for l in contents.split("\n")] link0_patt = re.compile(r...
Returns index of nearest neighbor atoms.
def _find_nn_pos_before_site(self, siteindex): """ Returns index of nearest neighbor atoms. """ alldist = [(self._mol.get_distance(siteindex, i), i) for i in range(siteindex)] alldist = sorted(alldist, key=lambda x: x[0]) return [d[1] for d in alldist]
Returns a z - matrix representation of the molecule.
def get_zmatrix(self): """ Returns a z-matrix representation of the molecule. """ output = [] outputvar = [] for i, site in enumerate(self._mol): if i == 0: output.append("{}".format(site.specie)) elif i == 1: nn = s...
Return the cartesian coordinates of the molecule
def get_cart_coords(self): """ Return the cartesian coordinates of the molecule """ def to_s(x): return "%0.6f" % x outs = [] for i, site in enumerate(self._mol): outs.append(" ".join([site.species_string, " ".joi...
Return GaussianInput string
def to_string(self, cart_coords=False): """ Return GaussianInput string Option: whe cart_coords sets to True return the cartesian coordinates instead of the z-matrix """ def para_dict_to_string(para, joiner=" "): para_str = [] # sorted is...
Write the input string into a file
def write_file(self, filename, cart_coords=False): """ Write the input string into a file Option: see __str__ method """ with zopen(filename, "w") as f: f.write(self.to_string(cart_coords))
Json - serializable dict representation.
def as_dict(self): """ Json-serializable dict representation. """ structure = self.final_structure d = {"has_gaussian_completed": self.properly_terminated, "nsites": len(structure)} comp = structure.composition d["unit_cell_formula"] = comp.as_dict() ...
Read a potential energy surface from a gaussian scan calculation.
def read_scan(self): """ Read a potential energy surface from a gaussian scan calculation. Returns: A dict: {"energies": [ values ], "coords": {"d1": [ values ], "A2", [ values ], ... }} "energies" are the energies of all points of the potential en...
Get a matplotlib plot of the potential energy surface.
def get_scan_plot(self, coords=None): """ Get a matplotlib plot of the potential energy surface. Args: coords: internal coordinate name to use as abcissa. """ from pymatgen.util.plotting import pretty_plot plt = pretty_plot(12, 8) d = self.read_scan...
Save matplotlib plot of the potential energy surface to a file.
def save_scan_plot(self, filename="scan.pdf", img_format="pdf", coords=None): """ Save matplotlib plot of the potential energy surface to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. co...
Read a excitation energies after a TD - DFT calculation.
def read_excitation_energies(self): """ Read a excitation energies after a TD-DFT calculation. Returns: A list: A list of tuple for each transition such as [(energie (eV), lambda (nm), oscillatory strength), ... ] """ transitions = list() ...
Get a matplotlib plot of the UV - visible xas. Transition are plotted as vertical lines and as a sum of normal functions with sigma with. The broadening is applied in energy and the xas is plotted as a function of the wavelength.
def get_spectre_plot(self, sigma=0.05, step=0.01): """ Get a matplotlib plot of the UV-visible xas. Transition are plotted as vertical lines and as a sum of normal functions with sigma with. The broadening is applied in energy and the xas is plotted as a function of the wavelengt...
Save matplotlib plot of the spectre to a file.
def save_spectre_plot(self, filename="spectre.pdf", img_format="pdf", sigma=0.05, step=0.01): """ Save matplotlib plot of the spectre to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ...
Create a new input object using by default the last geometry read in the output file and with the same calculation parameters. Arguments are the same as GaussianInput class.
def to_input(self, mol=None, charge=None, spin_multiplicity=None, title=None, functional=None, basis_set=None, route_parameters=None, input_parameters=None, link0_parameters=None, dieze_tag=None, cart_coords=False): """ Create a new input object using ...
Args: species: list of species to_this_composition: If true substitutions with this as a final composition will be found. If false substitutions with this as a starting composition will be found ( these are slightly different ) Returns: List of predictions in the form of dictionaries. If to_this_composition is true the...
def list_prediction(self, species, to_this_composition=True): """ Args: species: list of species to_this_composition: If true, substitutions with this as a final composition will be found. If false, substitutions with this as a ...
Returns charged balanced substitutions from a starting or ending composition.
def composition_prediction(self, composition, to_this_composition=True): """ Returns charged balanced substitutions from a starting or ending composition. Args: composition: starting or ending composition to_this_composition: If tr...
Factory function to provide the parser for the specified scheduler. If the scheduler is not implemented None is returned. The files string correspond to file names of the out and err files: err_file stderr of the scheduler out_file stdout of the scheduler run_err_file stderr of the application batch_err_file stderr of ...
def get_parser(scheduler, err_file, out_file=None, run_err_file=None, batch_err_file=None): """ Factory function to provide the parser for the specified scheduler. If the scheduler is not implemented None is returned. The files, string, correspond to file names of the out and err files: err_file ...
Parse the provided files for the corresponding strings.
def parse_single(self, errmsg): """ Parse the provided files for the corresponding strings. """ found = False message = None metadata = None for k in errmsg.keys(): if self.files[k] is not None: #print('parsing ', self.files[k], ' for '...
Parse for the occurens of all errors defined in ERRORS
def parse(self): """ Parse for the occurens of all errors defined in ERRORS """ errors_tested = 0 for error in self.error_definitions: errors_tested += 1 result = self.parse_single(self.error_definitions[error]) if result[0]: se...
Returns a symmetrized molecule
def iterative_symmetrize(mol, max_n=10, tolerance=0.3, epsilon=1e-2): """Returns a symmetrized molecule The equivalent atoms obtained via :meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms` are rotated, mirrored... unto one position. Then the average position is calculated. ...
Cluster sites based on distance and species type.
def cluster_sites(mol, tol, give_only_index=False): """ Cluster sites based on distance and species type. Args: mol (Molecule): Molecule **with origin at center of mass**. tol (float): Tolerance to use. Returns: (origin_site, clustered_sites): origin_site is a site at the cente...
Recursive algorithm to permute through all possible combinations of the initially supplied symmetry operations to arrive at a complete set of operations mapping a single atom to all other equivalent atoms in the point group. This assumes that the initial number already uniquely identifies all operations.
def generate_full_symmops(symmops, tol): """ Recursive algorithm to permute through all possible combinations of the initially supplied symmetry operations to arrive at a complete set of operations mapping a single atom to all other equivalent atoms in the point group. This assumes that the initial...
Get the point group associated with the structure.
def get_point_group_symbol(self): """ Get the point group associated with the structure. Returns: (Pointgroup): Point group for structure. """ rotations = self._space_group_data["rotations"] # passing a 0-length rotations list to spglib can segfault i...
Get the crystal system for the structure e. g. ( triclinic orthorhombic cubic etc. ).
def get_crystal_system(self): """ Get the crystal system for the structure, e.g., (triclinic, orthorhombic, cubic, etc.). Returns: (str): Crystal system for structure or None if system cannot be detected. """ n = self._space_group_data["number"] f = ...
Get the lattice for the structure e. g. ( triclinic orthorhombic cubic etc. ). This is the same than the crystal system with the exception of the hexagonal/ rhombohedral lattice
def get_lattice_type(self): """ Get the lattice for the structure, e.g., (triclinic, orthorhombic, cubic, etc.).This is the same than the crystal system with the exception of the hexagonal/rhombohedral lattice Returns: (str): Lattice type for structure or Non...
Get the symmetry operations associated with the structure.
def _get_symmetry(self): """ Get the symmetry operations associated with the structure. Returns: Symmetry operations as a tuple of two equal length sequences. (rotations, translations). "rotations" is the numpy integer array of the rotation matrices for scale...
Return symmetry operations as a list of SymmOp objects. By default returns fractional coord symmops. But cartesian can be returned too.
def get_symmetry_operations(self, cartesian=False): """ Return symmetry operations as a list of SymmOp objects. By default returns fractional coord symmops. But cartesian can be returned too. Returns: ([SymmOp]): List of symmetry operations. """ rotat...
Get a symmetrized structure. A symmetrized structure is one where the sites have been grouped into symmetrically equivalent groups.
def get_symmetrized_structure(self): """ Get a symmetrized structure. A symmetrized structure is one where the sites have been grouped into symmetrically equivalent groups. Returns: :class:`pymatgen.symmetry.structure.SymmetrizedStructure` object. """ ds = se...
Get the refined structure based on detected symmetry. The refined structure is a * conventional * cell setting with atoms moved to the expected symmetry positions.
def get_refined_structure(self): """ Get the refined structure based on detected symmetry. The refined structure is a *conventional* cell setting with atoms moved to the expected symmetry positions. Returns: Refined structure. """ # Atomic positions h...
Find a primitive version of the unit cell.
def find_primitive(self): """ Find a primitive version of the unit cell. Returns: A primitive cell in the input cell is searched and returned as an Structure object. If no primitive cell is found, None is returned. """ lattice, scaled_position...
k - point mesh of the Brillouin zone generated taken into account symmetry. The method returns the irreducible kpoints of the mesh and their weights
def get_ir_reciprocal_mesh(self, mesh=(10, 10, 10), is_shift=(0, 0, 0)): """ k-point mesh of the Brillouin zone generated taken into account symmetry.The method returns the irreducible kpoints of the mesh and their weights Args: mesh (3x1 array): The number of kpoint...
Gives the transformation matrix to transform a conventional unit cell to a primitive cell according to certain standards the standards are defined in Setyawan W. & Curtarolo S. ( 2010 ). High - throughput electronic band structure calculations: Challenges and tools. Computational Materials Science 49 ( 2 ) 299 - 312. d...
def get_conventional_to_primitive_transformation_matrix(self, international_monoclinic=True): """ Gives the transformation matrix to transform a conventional unit cell to a primitive cell according to certain standards the standards are defined in Setyawan, W., & Curtarolo, S. (2010). ...
Gives a structure with a primitive cell according to certain standards the standards are defined in Setyawan W. & Curtarolo S. ( 2010 ). High - throughput electronic band structure calculations: Challenges and tools. Computational Materials Science 49 ( 2 ) 299 - 312. doi: 10. 1016/ j. commatsci. 2010. 05. 010
def get_primitive_standard_structure(self, international_monoclinic=True): """ Gives a structure with a primitive cell according to certain standards the standards are defined in Setyawan, W., & Curtarolo, S. (2010). High-throughput electronic band structure calculations: Challen...
Gives a structure with a conventional cell according to certain standards. The standards are defined in Setyawan W. & Curtarolo S. ( 2010 ). High - throughput electronic band structure calculations: Challenges and tools. Computational Materials Science 49 ( 2 ) 299 - 312. doi: 10. 1016/ j. commatsci. 2010. 05. 010 They...
def get_conventional_standard_structure( self, international_monoclinic=True): """ Gives a structure with a conventional cell according to certain standards. The standards are defined in Setyawan, W., & Curtarolo, S. (2010). High-throughput electronic band structure calculati...
Calculate the weights for a list of kpoints.
def get_kpoint_weights(self, kpoints, atol=1e-5): """ Calculate the weights for a list of kpoints. Args: kpoints (Sequence): Sequence of kpoints. np.arrays is fine. Note that the code does not check that the list of kpoints provided does not contain d...
Handles assymetric top molecules which cannot contain rotational symmetry larger than 2.
def _proc_asym_top(self): """ Handles assymetric top molecules, which cannot contain rotational symmetry larger than 2. """ self._check_R2_axes_asym() if len(self.rot_sym) == 0: logger.debug("No rotation symmetries detected.") self._proc_no_rot_sym...
Handles symetric top molecules which has one unique eigenvalue whose corresponding principal axis is a unique rotational axis. More complex handling required to look for R2 axes perpendicular to this unique axis.
def _proc_sym_top(self): """ Handles symetric top molecules which has one unique eigenvalue whose corresponding principal axis is a unique rotational axis. More complex handling required to look for R2 axes perpendicular to this unique axis. """ if abs(self.eigva...
Handles molecules with no rotational symmetry. Only possible point groups are C1 Cs and Ci.
def _proc_no_rot_sym(self): """ Handles molecules with no rotational symmetry. Only possible point groups are C1, Cs and Ci. """ self.sch_symbol = "C1" if self.is_valid_op(PointGroupAnalyzer.inversion_op): self.sch_symbol = "Ci" self.symmops.append...
Handles cyclic group molecules.
def _proc_cyclic(self): """ Handles cyclic group molecules. """ main_axis, rot = max(self.rot_sym, key=lambda v: v[1]) self.sch_symbol = "C{}".format(rot) mirror_type = self._find_mirror(main_axis) if mirror_type == "h": self.sch_symbol += "h" ...
Handles dihedral group molecules i. e those with intersecting R2 axes and a main axis.
def _proc_dihedral(self): """ Handles dihedral group molecules, i.e those with intersecting R2 axes and a main axis. """ main_axis, rot = max(self.rot_sym, key=lambda v: v[1]) self.sch_symbol = "D{}".format(rot) mirror_type = self._find_mirror(main_axis) i...
Test for 2 - fold rotation along the principal axes. Used to handle asymetric top molecules.
def _check_R2_axes_asym(self): """ Test for 2-fold rotation along the principal axes. Used to handle asymetric top molecules. """ for v in self.principal_axes: op = SymmOp.from_axis_angle_and_translation(v, 180) if self.is_valid_op(op): sel...