text
stringlengths
81
112k
Makes LibxcFunc obey the general json interface used in pymatgen for easier serialization. def as_dict(self): """ Makes LibxcFunc obey the general json interface used in pymatgen for easier serialization. """ return {"name": self.name, "@module": self.__c...
Converts a lattice object to LammpsBox, and calculates the symmetry operation used. Args: lattice (Lattice): Input lattice. origin: A (3,) array/list of floats setting lower bounds of simulation box. Default to (0, 0, 0). Returns: LammpsBox, SymmOp def lattice_2_lmpbox...
Converts a structure to a LammpsData object with no force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be present due to force field settings but not necessarily in the structure...
Volume of simulation box. def volume(self): """ Volume of simulation box. """ m = self._matrix return np.dot(np.cross(m[0], m[1]), m[2])
Returns the string representation of simulation box in LAMMPS data file format. Args: significant_figures (int): No. of significant figures to output for box settings. Default to 6. Returns: String representation def get_string(self, significant_figures...
Exports a periodic structure object representing the simulation box. Return: Structure def structure(self): """ Exports a periodic structure object representing the simulation box. Return: Structure """ masses = self.masses ...
Returns the string representation of LammpsData, essentially the string to be written to a file. Args: distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. Default to 6. velocity (int): No...
Writes LammpsData to file. Args: filename (str): Filename. distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. Default to 6. velocity (int): No. of significant figures to output for ...
Breaks down LammpsData to building blocks (LammpsBox, ForceField and a series of Topology). RESTRICTIONS APPLIED: 1. No complex force field defined not just on atom types, where the same type or equivalent types of topology may have more than one set of coefficients. ...
Constructor that parses a file. Args: filename (str): Filename to read. atom_style (str): Associated atom_style. Default to "full". sort_id (bool): Whether sort each section by id. Default to True. def from_file(cls, filename, atom_style="full", sort_id=Fals...
Constructor building LammpsData from a ForceField object and a list of Topology objects. Do not support intermolecular topologies since a Topology object includes data for ONE molecule or structure only. Args: box (LammpsBox): Simulation box. ff (ForceField): For...
Simple constructor building LammpsData from a structure without force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be present due to force field settings but not ...
Another constructor that creates an instance from a molecule. Covalent bonds and other bond-based topologies (angles and dihedrals) can be automatically determined. Cannot be used for non bond-based topologies, e.g., improper dihedrals. Args: molecule (Molecule): Input molec...
Saves object to a file in YAML format. Args: filename (str): Filename. def to_file(self, filename): """ Saves object to a file in YAML format. Args: filename (str): Filename. """ d = {"mass_info": self.mass_info, "nonbond_coeffs": ...
Constructor that reads in a file in YAML format. Args: filename (str): Filename. def from_file(cls, filename): """ Constructor that reads in a file in YAML format. Args: filename (str): Filename. """ yaml = YAML(typ="safe") with open(fi...
Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. def _read_nlines(filename, nlines): """ Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. """ if nlines < 0: with open(filename, 'r') as fh: return...
Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates the keys from the value (None if no separator is present). R...
Convert string into integer Raise: TypeError if string is not a valid integer def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ float_num = float(string) int_num = int(float_num) if float_num == int_num: ...
Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path. def as_pseudo(cls, obj): """ Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path. """ return obj if isinstance(obj, cls)...
String representation. def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append app("<%s: %s>" % (self.__class__.__name__, self.basename)) app(" summary: " + self.summary.strip()) app(" number of valence electrons: %s" % self.Z_val) ...
Pymatgen :class:`Element`. def element(self): """Pymatgen :class:`Element`.""" try: return Element.from_Z(self.Z) except (KeyError, IndexError): return Element.from_Z(int(self.Z))
Compute and erturn MD5 hash value. def compute_md5(self): """Compute and erturn MD5 hash value.""" import hashlib with open(self.path, "rt") as fh: text = fh.read() m = hashlib.md5(text.encode("utf-8")) return m.hexdigest()
Copy the pseudopotential to a temporary a file and returns a new pseudopotential object. Useful for unit tests in which we have to change the content of the file. Args: tmpdir: If None, a new temporary directory is created and files are copied here else tmpdir is used. def ...
The path of the djrepo file. None if file does not exist. def djrepo_path(self): """The path of the djrepo file. None if file does not exist.""" root, ext = os.path.splitext(self.filepath) path = root + ".djrepo" return path
Returns a :class:`Hint` object with the suggested value of ecut [Ha] and pawecutdg [Ha] for the given accuracy. ecut and pawecutdg are set to zero if no hint is available. Args: accuracy: ["low", "normal", "high"] def hint_for_accuracy(self, accuracy="normal"): """ ...
True if self provides hints on the cutoff energy. def has_hints(self): """ True if self provides hints on the cutoff energy. """ for acc in ["low", "normal", "high"]: try: if self.hint_for_accuracy(acc) is None: return False ex...
Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: ecut: Cutoff energy in Hartree. pawecutdg...
Parse the FHI abinit header. Example: Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994 21.00000 3.00000 940714 zatom, zion, pspdat 1 1 2 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well 1.80626423934776 .22824404...
Parse the HGH abinit header. Example: Hartwigsen-Goedecker-Hutter psp for Ne, from PRB58, 3641 (1998) 10 8 010605 zatom,zion,pspdat 3 1 1 0 2001 0 pspcod,pspxc,lmax,lloc,mmax,r2well def hgh_header(filename, ppdesc): """ Parse the HGH abinit header. Example: ...
Parse the ONCVPSP abinit header. Example: Li ONCVPSP r_core= 2.01 3.02 3.0000 3.0000 140504 zatom,zion,pspd 8 2 1 4 600 0 pspcod,pspxc,lmax,lloc,mmax,r2well 5.99000000 0.00000000 0.00000000 rchrg fchrg qchrg 2 2 ...
Parse the TM abinit header. Example: Troullier-Martins psp for element Fm Thu Oct 27 17:28:39 EDT 1994 100.00000 14.00000 940714 zatom, zion, pspdat 1 1 3 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well 0 4.085 6.246 0 2.8...
Parse the PAW abinit header. Examples: Paw atomic data for element Ni - Generated by AtomPAW (N. Holzwarth) + AtomPAW2Abinit v3.0.5 28.000 18.000 20061204 : zatom,zion,pspdat 7 7 2 0 350 0. : pspcod,pspxc,lmax,lloc,mmax,r2well paw3 1305 ...
Analyze the files contained in directory dirname. Args: dirname: directory path exclude_exts: list of file extensions that should be skipped. exclude_fnames: list of file names that should be skipped. Returns: List of pseudopotential objects. def scan_d...
Read the pseudopotential descriptor from file filename. Returns: Pseudopotential descriptor. None if filename is not a valid pseudopotential file. Raises: `PseudoParserError` if fileformat is not supported. def read_ppdesc(self, filename): """ Read the pseudopo...
Read and parse a pseudopotential file. Main entry point for client code. Returns: pseudopotential object or None if filename is not a valid pseudopotential file. def parse(self, filename): """ Read and parse a pseudopotential file. Main entry point for client code. Returns...
This function receives a dictionary with the parameters defining the radial mesh and returns a `ndarray` with the mesh def _eval_grid(grid_params): """ This function receives a dictionary with the parameters defining the radial mesh and returns a `ndarray` with the mesh """ ...
Parse the first occurence of func_name in the XML file. def _parse_radfunc(self, func_name): """Parse the first occurence of func_name in the XML file.""" node = self.root.find(func_name) grid = node.attrib["grid"] values = np.array([float(s) for s in node.text.split()]) return...
Parse all the nodes with tag func_name in the XML file. def _parse_all_radfuncs(self, func_name): """Parse all the nodes with tag func_name in the XML file.""" for node in self.root.findall(func_name): grid = node.attrib["grid"] values = np.array([float(s) for s in node.text.spl...
The all-electron radial density. def ae_core_density(self): """The all-electron radial density.""" mesh, values, attrib = self._parse_radfunc("ae_core_density") return RadialFunction(mesh, values)
The pseudized radial density. def pseudo_core_density(self): """The pseudized radial density.""" mesh, values, attrib = self._parse_radfunc("pseudo_core_density") return RadialFunction(mesh, values)
Dictionary with the AE partial waves indexed by state. def ae_partial_waves(self): """Dictionary with the AE partial waves indexed by state.""" ae_partial_waves = OrderedDict() for mesh, values, attrib in self._parse_all_radfuncs("ae_partial_wave"): state = attrib["state"] ...
Dictionary with the pseudo partial waves indexed by state. def pseudo_partial_waves(self): """Dictionary with the pseudo partial waves indexed by state.""" pseudo_partial_waves = OrderedDict() for (mesh, values, attrib) in self._parse_all_radfuncs("pseudo_partial_wave"): state = att...
Dictionary with the PAW projectors indexed by state. def projector_functions(self): """Dictionary with the PAW projectors indexed by state.""" projector_functions = OrderedDict() for (mesh, values, attrib) in self._parse_all_radfuncs("projector_function"): state = attrib["state"] ...
This function *generates* a predefined list of matplotlib figures with minimal input from the user. def yield_figs(self, **kwargs): # pragma: no cover """ This function *generates* a predefined list of matplotlib figures with minimal input from the user. """ yield self.plot_densities(t...
Plot the PAW densities. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure def plot_densities(self, ax=None, **kwargs): """ Plot the PAW densities. Args: ax: matplotlib :class:`Axes` o...
Plot the AE and the pseudo partial waves. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. fontsize: fontsize for legends and titles Returns: `matplotlib` figure def plot_waves(self, ax=None, fontsize=12, **kwargs): """ Plot the AE ...
Plot the PAW projectors. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure def plot_projectors(self, ax=None, fontsize=12, **kwargs): """ Plot the PAW projectors. Args: ax: matplotlib :class:`Axe...
Find all pseudos in the directory tree starting from top. Args: top: Top of the directory tree exts: List of files extensions. if exts == "all_files" we try to open all files in top exclude_dirs: Wildcard used to exclude directories. return: :cla...
True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential def is_complete(self, zmax=118): """ True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential """ for z in range(1, zmax): if not self[z]: return Fals...
Return a list with all the the possible combination of pseudos for the given list of element_symbols. Each item is a list of pseudopotential objects. Example:: table.all_combinations_for_elements(["Li", "F"]) def all_combinations_for_elements(self, element_symbols): """ ...
Return the pseudo with the given chemical symbol. Args: symbols: String with the chemical symbol of the element allow_multi: By default, the method raises ValueError if multiple occurrences are found. Use allow_multi to prevent this. Raises: ValueErr...
Return the pseudos with the given chemical symbols. Raises: ValueError if one of the symbols is not found or multiple occurences are present. def pseudos_with_symbols(self, symbols): """ Return the pseudos with the given chemical symbols. Raises: ValueError if ...
Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable...
A pretty ASCII printer for the periodic table, based on some filter_function. Args: stream: file-like object filter_function: A filtering function that take a Pseudo as input and returns a boolean. For example, setting filter_function = lambda p: p.Z_val ...
Return string with data in tabular form. def to_table(self, filter_function=None): """Return string with data in tabular form.""" table = [] for p in self: if filter_function is not None and filter_function(p): continue table.append([p.basename, p.symbol, p.Z_val, p.l_ma...
Sort the table according to the value of attribute attrname. Return: New class:`PseudoTable` object def sorted(self, attrname, reverse=False): """ Sort the table according to the value of attribute attrname. Return: New class:`PseudoTable` object """ ...
Return a new :class:`PseudoTable` with pseudos sorted by Z def sort_by_z(self): """Return a new :class:`PseudoTable` with pseudos sorted by Z""" return self.__class__(sorted(self, key=lambda p: p.Z))
Select only those pseudopotentials for which condition is True. Return new class:`PseudoTable` object. Args: condition: Function that accepts a :class:`Pseudo` object and returns True or False. def select(self, condition): """ Select only those pseudopotenti...
Return new class:`PseudoTable` object with pseudos in the given rows of the periodic table. rows can be either a int or a list of integers. def select_rows(self, rows): """ Return new class:`PseudoTable` object with pseudos in the given rows of the periodic table. rows can be either a i...
Flexible method to get any data using the Materials Project REST interface. Generally used by other methods for more specific queries. Format of REST return is *always* a list of dict (regardless of the number of pieces of data returned. The general format is as follows: [{"material_id...
Flexible method to get any data using the Materials Project REST interface. Generally used by other methods for more specific queries. Unlike the :func:`get_data`_, this method queries the task collection for specific run information. Format of REST return is *always* a list of dict (re...
Get a list of Structures corresponding to a chemical system, formula, or materials_id. Args: chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234). final (bool): Whether to get the final structure, o...
Finds matching structures on the Materials Project site. Args: filename_or_structure: filename or Structure object Returns: A list of matching structures. Raises: MPRestError def find_structure(self, filename_or_structure): """ Finds matchi...
Get a list of ComputedEntries or ComputedStructureEntries corresponding to a chemical system, formula, or materials_id or full criteria. Args: chemsys_formula_id_criteria (str/dict): A chemical system (e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id ...
A helper function to get all entries necessary to generate a pourbaix diagram from the rest interface. Args: chemsys ([str]): A list of elements comprising the chemical system, e.g. ['Li', 'Fe'] def get_pourbaix_entries(self, chemsys): """ A helper function ...
Get a Structure corresponding to a material_id. Args: material_id (str): Materials Project material_id (a string, e.g., mp-1234). final (bool): Whether to get the final structure, or the initial (pre-relaxation) structure. Defaults to True. co...
Get a ComputedEntry corresponding to a material_id. Args: material_id (str): Materials Project material_id (a string, e.g., mp-1234). compatible_only (bool): Whether to return only "compatible" entries. Compatible entries are entries that have been ...
Get a BandStructure corresponding to a material_id. REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure_uniform Args: material_id (str): Materials Project mater...
Helper method to get a list of ComputedEntries in a chemical system. For example, elements = ["Li", "Fe", "O"] will return a list of all entries in the Li-Fe-O chemical system, i.e., all LixOy, FexOy, LixFey, LixFeyOz, Li, Fe and O phases. Extremely useful for creating phase diagrams of ...
Submits a list of structures to the Materials Project as SNL files. The argument list mirrors the arguments for the StructureNL object, except that a list of structures with the same metadata is used as an input. .. note:: As of now, this MP REST feature is open only to a s...
Submits a list of StructureNL to the Materials Project site. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: snl (StructureNL/[StructureNL]): A...
Delete earlier submitted SNLs. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: snl_ids: List of SNL ids. Raises: MPRestErr...
Query for submitted SNLs. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: criteria (dict): Query criteria. Returns: A dict...
Assimilates all vasp run directories beneath a particular directory using BorgQueen to obtain structures, and then submits thhem to the Materials Project as SNL files. VASP related meta data like initial structure and final energies are automatically incorporated. .. note:: ...
Gets the cohesive for a material (eV per formula unit). Cohesive energy is defined as the difference between the bulk energy and the sum of total DFT energy of isolated atoms for atom elements in the bulk. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'....
Gets a reaction from the Materials Project. Args: reactants ([str]): List of formulas products ([str]): List of formulas Returns: rxn def get_reaction(self, reactants, products): """ Gets a reaction from the Materials Project. Args: ...
Get a substrate list for a material id. The list is in order of increasing elastic energy if a elastic tensor is available for the material_id. Otherwise the list is in order of increasing matching area. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. ...
Gets surface data for a material. Useful for Wulff shapes. Reference for surface data: Tran, R., Xu, Z., Radhakrishnan, B., Winston, D., Sun, W., Persson, K. A., & Ong, S. P. (2016). Data Descripter: Surface energies of elemental crystals. Scientific Data, 3(160080), 1–13. http...
Constructs a Wulff shape for a material. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. Returns: pymatgen.analysis.wulff.WulffShape def get_wulff_shape(self, material_id): """ Constructs a Wulff shape for a material. Args: ...
Gets critical reactions between two reactants. Get critical reactions ("kinks" in the mixing ratio where reaction products change) between two reactants. See the `pymatgen.analysis.interface_reactions` module for more info. Args: reactant1 (str): Chemical formula for reacta...
Parses a powerful and simple string criteria and generates a proper mongo syntax criteria. Args: criteria_string (str): A string representing a search criteria. Also supports wild cards. E.g., something like "*2O" gets converted to {'pretty_fo...
returns the maximum pairwise electronegativity difference def max_electronegativity(self): ''' returns the maximum pairwise electronegativity difference ''' maximum = 0 for e1, e2 in combinations(self.elements, 2): if abs(Element(e1).X - Element(e2).X) > maximum: ...
Returns a list of atomic orbitals, sorted from lowest to highest energy def aos_as_list(self): ''' Returns a list of atomic orbitals, sorted from lowest to highest energy ''' return sorted(chain.from_iterable( [self.aos[el] * int(self.composition[el]) for el in self.elements...
Fill up the atomic orbitals with available electrons. Return HOMO, LUMO, and whether it's a metal. def obtain_band_edges(self): ''' Fill up the atomic orbitals with available electrons. Return HOMO, LUMO, and whether it's a metal. ''' orbitals = self.aos_as_list() ...
Given a sequence of ComputedStructureEntries, use structure fitter to group them by structural similarity. Args: entries: Sequence of ComputedStructureEntries. species_to_remove: Sometimes you want to compare a host framework (e.g., in Li-ion battery analysis). This allows you to sp...
Returns: set representing the chemical system, e.g., {"Li", "Fe", "P", "O"} def chemsys(self) -> set: """ Returns: set representing the chemical system, e.g., {"Li", "Fe", "P", "O"} """ chemsys = set() for e in self.entries: chemsys.update([el...
Removes all non-ground state entries, i.e., only keep the lowest energy per atom entry at each composition. def remove_non_ground_states(self): """ Removes all non-ground state entries, i.e., only keep the lowest energy per atom entry at each composition. """ group_func ...
Returns an EntrySet containing only the set of entries belonging to a particular chemical system (in this definition, it includes all sub systems). For example, if the entries are from the Li-Fe-P-O system, and chemsys=["Li", "O"], only the Li, O, and Li-O entries are returned. ...
Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Format entry names to be LaTex compatible, e.g., Li_{2}O def to_csv(self, filename: str, latexify_names: bool = False): """ Exports...
Imports PDEntries from a csv. Args: filename: Filename to import from. Returns: List of Elements, List of PDEntries def from_csv(cls, filename: str): """ Imports PDEntries from a csv. Args: filename: Filename to import from. Return...
Helper function to convert a Vasprun parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml. def _parse_parameters(val_type, val): """ Helper function to convert a V...
Helper function to convert a Vasprun array-type parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml. filename: Fullpath of vasprun.xml. Used for robust error handl...
Helper function to parse a parameter from the INCAR. def _parse_from_incar(filename, key): """ Helper function to parse a parameter from the INCAR. """ dirname = os.path.dirname(filename) for f in os.listdir(dirname): if re.search(r"INCAR", f): warnings.warn("INCAR found. Using ...
Large numbers are often represented as ********* in the vasprun. This function parses these values as np.nan def _vasprun_float(f): """ Large numbers are often represented as ********* in the vasprun. This function parses these values as np.nan """ try: return float(f) except ValueE...
This method is used to get band structure info from a VASP directory. It takes into account that the run can be divided in several branches named "branch_x". If the run has not been divided in branches the method will turn to parsing vasprun.xml directly. The method returns None is there"s a parsing er...
When running a band structure computations the fermi level needs to be take from the static run that gave the charge density used for the non-self consistent band structure run. Sometimes this fermi level is however a little too low because of the mismatch between the uniform grid used in the static run...
Calculate the optical absorption coefficient from the dielectric constants. Note that this method is only implemented for optical properties calculated with GGA and BSE. Returns: optical absorption coefficient in list def optical_absorption_coeff(self): """ Calculate the...
Checks that electronic step convergence has been reached in the final ionic step def converged_electronic(self): """ Checks that electronic step convergence has been reached in the final ionic step """ final_esteps = self.ionic_steps[-1]["electronic_steps"] if 'L...
Checks that ionic step convergence has been reached, i.e. that vasp exited before reaching the max ionic steps for a relaxation run def converged_ionic(self): """ Checks that ionic step convergence has been reached, i.e. that vasp exited before reaching the max ionic steps for a relaxat...
Final energy from the vasp run. def final_energy(self): """ Final energy from the vasp run. """ try: final_istep = self.ionic_steps[-1] if final_istep["e_wo_entrp"] != final_istep[ 'electronic_steps'][-1]["e_0_energy"]: warnings.wa...