text
stringlengths
81
112k
Vibrational entropy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result ...
Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimenta...
Phonon contribution to the Helmholtz free energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with exper...
Zero point energy energy of the system. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimental data the result should be divided by the number of unit form...
Get element projected Dos. Returns: dict of {Element: Dos} def get_element_dos(self): """ Get element projected Dos. Returns: dict of {Element: Dos} """ el_dos = {} for site, atom_dos in self.pdos.items(): el = site.specie ...
Returns CompleteDos object from dict representation. def from_dict(cls, d): """ Returns CompleteDos object from dict representation. """ tdos = PhononDos.from_dict(d) struct = Structure.from_dict(d["structure"]) pdoss = {} for at, pdos in zip(struct, d["pdos"]): ...
Json-serializable dict representation of CompletePhononDos. def as_dict(self): """ Json-serializable dict representation of CompletePhononDos. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "structure": self.structure.as_dict(...
Sorts a dict by value. Args: d: Input dictionary key: Function which takes an tuple (key, object) and returns a value to compare and sort by. By default, the function compares the values of the dict i.e. key = lambda t : t[1] reverse: Allows to reverse sort order. ...
Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value: def min_max_indexes(seq): """ Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value: """ l = sorted(enumerate(seq), key=lambda s...
True if values are stricly increasing. def strictly_increasing(values): """True if values are stricly increasing.""" return all(x < y for x, y in zip(values, values[1:]))
True if values are stricly decreasing. def strictly_decreasing(values): """True if values are stricly decreasing.""" return all(x > y for x, y in zip(values, values[1:]))
True if values are not increasing. def non_increasing(values): """True if values are not increasing.""" return all(x >= y for x, y in zip(values, values[1:]))
True if values are not decreasing. def non_decreasing(values): """True if values are not decreasing.""" return all(x <= y for x, y in zip(values, values[1:]))
Returns False if values are not monotonic (decreasing|increasing). mode is "<" for a decreasing sequence, ">" for an increasing sequence. Two numbers are considered equal if they differ less that atol. .. warning: Not very efficient for large data sets. >>> values = [1.2, 1.3, 1.4] >>> mon...
Rounds a number rounded to a specific number of significant figures instead of to a specific precision. def round_to_sigfigs(num, sigfigs): """ Rounds a number rounded to a specific number of significant figures instead of to a specific precision. """ if type(sigfigs) != int: raise Type...
Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [A_xx,A_yy,A_zz,A_xy,A_xz,A_yz] This will generate the full matrix: [[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz] def make_symmetric_matrix_from_upper_tri(val): """ Given a symmetric matrix in upper triangular ...
Returns a :class:`Work` object that performs G0W0 calculations for the given the material. Args: structure: Pymatgen structure. pseudos: List of `Pseudo` objects. scf_ Defines the sampling used for the SCF run. nscf_nband: Number of bands included in the NSCF run. ecuteps: C...
Gets information on the components in a bonded structure. Correctly determines the dimensionality of all structures, regardless of structure type or improper connections due to periodic boundary conditions. Requires a StructureGraph object as input. This can be generated using one of the NearNeighbor ...
Calculates the dimensionality of the component containing the given site. Implements directly the modified breadth-first-search algorithm described in Algorithm 1 of: P. Larsem, M. Pandey, M. Strange, K. W. Jacobsen, 2018, arXiv:1808.02114 Args: bonded_structure (StructureGraph): A structure ...
Converts a zero-dimensional networkx Graph object into a MoleculeGraph. Implements a similar breadth-first search to that in calculate_dimensionality_of_site(). Args: bonded_structure (StructureGraph): A structure with bonds, represented as a pymatgen structure graph. For example, gene...
Finds bonded atoms and returns a adjacency matrix of bonded atoms. Author: "Gowoon Cheon" Email: "gcheon@stanford.edu" Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + ...
Finds bonded clusters of atoms in the structure with periodic boundary conditions. If there are atoms that are not bonded to anything, returns [0,1,0]. (For faster computation time) Author: "Gowoon Cheon" Email: "gcheon@stanford.edu" Args: struct (Structure): Input structure c...
returns the deviatoric component of the stress def deviator_stress(self): """ returns the deviatoric component of the stress """ if not self.is_symmetric: raise warnings.warn("The stress tensor is not symmetric, " "so deviator stress will not ...
calculates the first Piola-Kirchoff stress Args: def_grad (3x3 array-like): deformation gradient tensor def piola_kirchoff_1(self, def_grad): """ calculates the first Piola-Kirchoff stress Args: def_grad (3x3 array-like): deformation gradient tensor """...
A slurm time parser. Accepts a string in one the following forms: # "days-hours", # "days-hours:minutes", # "days-hours:minutes:seconds". # "minutes", # "minutes:seconds", # "hours:minutes:seconds", Returns: Time in seconds. Raises: `ValueError`...
Convert a number representing a time value in the given unit (Default: seconds) to a string following the slurm convention: "days-hours:minutes:seconds". >>> assert time2slurm(61) == '0-0:1:1' and time2slurm(60*60+1) == '0-1:0:1' >>> assert time2slurm(0.5, unit="h") == '0-0:30:0' def time2slurm(timeval, u...
Convert a number representing a time value in the given unit (Default: seconds) to a string following the PbsPro convention: "hours:minutes:seconds". >>> assert time2pbspro(2, unit="d") == '48:0:0' def time2pbspro(timeval, unit="s"): """ Convert a number representing a time value in the given unit (De...
Convert string or number to memory in megabytes. def any2mb(s): """Convert string or number to memory in megabytes.""" if is_string(s): return int(Memory.from_string(s).to("Mb")) else: return int(s)
Maximum number of cation A that can be removed while maintaining charge-balance. Returns: integer amount of cation. Depends on cell size (this is an 'extrinsic' function!) def max_cation_removal(self): """ Maximum number of cation A that can be removed while maintaining charge-bala...
Maximum number of cation A that can be inserted while maintaining charge-balance. No consideration is given to whether there (geometrically speaking) are Li sites to actually accommodate the extra Li. Returns: integer amount of cation. Depends on cell size (this is an 'extrinsic' function!)...
Give max capacity in mAh for inserting and removing a charged cation This method does not normalize the capacity and intended as a helper method def _get_max_cap_ah(self, remove, insert): """ Give max capacity in mAh for inserting and removing a charged cation This method does not norma...
Give max capacity in mAh/g for inserting and removing a charged cation Note that the weight is normalized to the most lithiated state, thus removal of 1 Li from LiFePO4 gives the same capacity as insertion of 1 Li into FePO4. Args: remove: (bool) whether to allow cation removal ...
Give max capacity in mAh/cc for inserting and removing a charged cation into base structure. Args: remove: (bool) whether to allow cation removal insert: (bool) whether to allow cation insertion volume: (float) volume to use for normalization (default=volume of initial struc...
Returns a set of delithiation steps, e.g. set([1.0 2.0 4.0]) etc. in order to produce integer oxidation states of the redox metals. If multiple redox metals are present, all combinations of reduction/oxidation are tested. Note that having more than 3 redox metals will likely slow down the algori...
This is a helper method for get_removals_int_oxid! Args: spec_amts_oxi - a dict of species to their amounts in the structure oxid_el - the element to oxidize oxid_els - the full list of elements that might be oxidized numa - a running set of numbers of A cation a...
Helper method to reduce a sym_amt dict to a reduced formula and factor. Args: sym_amt (dict): {symbol: amount}. iupac_ordering (bool, optional): Whether to order the formula by the iupac "electronegativity" series, defined in Table VI of "Nomenclature of Inorganic Chemistry ...
Calculates the energy of a composition. Args: composition (Composition): input composition strict (bool): Whether all potentials must be specified def get_energy(self, composition, strict=True): """ Calculates the energy of a composition. Args: ...
Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters. :param molecule: Molecule object :param edges: dict representing the bonds of the functional group (format: {(from_index, to_index, from_image, to_image): props}, ...
Constructor for StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: def with_local_env_strategy(structure, strat...
Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0,...
Alters either the weight or the edge_properties of an edge in the StructureGraph. :param from_index: int :param to_index: int :param to_jimage: tuple :param new_weight: alter_edge does not require that weight be altered. As such, by default, this is None. If weig...
Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing...
Builds off of Structure.substitute to replace an atom in self.structure with a functional group. This method also amends self.graph to incorporate the new functional group. NOTE: Care must be taken to ensure that the functional group that is substituted will not place atoms to close to ...
Returns a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined. :param n: index of Site in Structure :param jimage: lattice vector of site ...
Returns the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n. :param n: index of site :return (int): def get_coordination_of_site(self, n): """ Returns the number of neighbors of site n. In graph terms, simply r...
Draws graph using GraphViz. The networkx graph object itself can also be drawn with networkx's in-built graph drawing methods, but note that this might give misleading results for multigraphs (edges are super-imposed on each other). If visualization is difficult to interpret, ...
Extract a dictionary summarizing the types and weights of edges in the graph. :return: A dictionary with keys specifying the species involved in a connection in alphabetical order (e.g. string 'Fe-O') and values which are a list of weights for those connections (e.g. bond length...
Extract a statistical summary of edge weights present in the graph. :return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' def weight_statistics(self): """ Extract a statistical summary of edge weights present in the graph. ...
Extract information on the different co-ordination environments present in the graph. :param anonymous: if anonymous, will replace specie names with A, B, C, etc. :return: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] def types_of_coordination_environments(s...
As in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. def from_dict(cls, d): """ As in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX to r...
Same as Structure.sort(), also remaps nodes in graph. :param key: :param reverse: :return: def sort(self, key=None, reverse=False): """ Same as Structure.sort(), also remaps nodes in graph. :param key: :param reverse: :return: """ old_str...
Compares two StructureGraphs. Returns dict with keys 'self', 'other', 'both' with edges that are present in only one StructureGraph ('self' and 'other'), and edges that are present in both. The Jaccard distance is a simple measure of the dissimilarity between two StructureGraphs...
Retrieve subgraphs as molecules, useful for extracting molecules from periodic crystals. Will only return unique molecules, not any duplicates present in the crystal (a duplicate defined as an isomorphic subgraph). :param use_weights (bool): If True, only treat subgraphs ...
Constructor for MoleculeGraph, returns a MoleculeGraph object with an empty graph (no edges, only nodes defined that correspond to Sites in Molecule). :param molecule (Molecule): :param name (str): name of graph, e.g. "bonds" :param edge_weight_name (str): name of edge weights, ...
Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters. :param molecule: Molecule object :param edges: dict representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of prope...
Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param reorder: bool, representing if graph nodes need to...
Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0,...
A wrapper around Molecule.insert(), which also incorporates the new site into the MoleculeGraph. :param i: Index at which to insert the new site :param species: Species for the new site :param coords: 3x1 array representing coordinates of the new site :param validate_proximity: ...
Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return: def set_node_attributes(self): """ Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return: """ species = {} coords = {} ...
Alters either the weight or the edge_properties of an edge in the MoleculeGraph. :param from_index: int :param to_index: int :param new_weight: alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be...
Remove an edge from the MoleculeGraph :param from_index: int :param to_index: int :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index). :return: ...
A wrapper for Molecule.remove_sites(). :param indices: list of indices in the current Molecule (and graph) to be removed. :return: def remove_nodes(self, indices): """ A wrapper for Molecule.remove_sites(). :param indices: list of indices in the current Molecule (a...
Split MoleculeGraph into two or more MoleculeGraphs by breaking a set of bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or more separate molecules). This function does not only alter the graph information, but also changes the underly...
Find all possible fragment combinations of the MoleculeGraphs (in other words, all connected induced subgraphs) :return: def build_unique_fragments(self): """ Find all possible fragment combinations of the MoleculeGraphs (in other words, all connected induced subgraphs) ...
Builds off of Molecule.substitute to replace an atom in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group. NOTE: using a MoleculeGraph will generally produce a different graph compared with using a Molecule or str (when not...
Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group. TODO: Figure out how to replace into a ring structure. :param...
Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and all rings will be returned. :return: dict {ind...
Returns a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined. :param n: index of Site in Molecule :param jimage: lattice vector of site ...
As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store graph information. def as_dict(self): """ As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store graph information. """ ...
As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. def from_dict(cls, d): """ As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to res...
Same as Molecule.sort(), also remaps nodes in graph. :param key: :param reverse: :return: def sort(self, key=None, reverse=False): """ Same as Molecule.sort(), also remaps nodes in graph. :param key: :param reverse: :return: """ old_molec...
Checks if the graphs of two MoleculeGraphs are isomorphic to one another. In order to prevent problems with misdirected edges, both graphs are converted into undirected nx.Graph objects. :param other: MoleculeGraph object to be compared. :return: bool def isomorphic_to(self, other): ...
Loads bond length data from json file def _load_bond_length_data(): """Loads bond length data from json file""" with open(os.path.join(os.path.dirname(__file__), "bond_lengths.json")) as f: data = collections.defaultdict(dict) for row in json.load(f): els ...
Obtain bond lengths for all bond orders from bond length database Args: sp1 (Specie): First specie. sp2 (Specie): Second specie. default_bl: If a particular type of bond does not exist, use this bond length as a default value (bond order = 1). If None, a ValueError w...
Calculate the bond order given the distance of 2 species Args: sp1 (Specie): First specie. sp2 (Specie): Second specie. dist: Their distance in angstrom tol (float): Relative tolerance to test. Basically, the code checks if the distance between the sites is larger than ...
Get the bond length between two species. Args: sp1 (Specie): First specie. sp2 (Specie): Second specie. bond_order: For species with different possible bond orders, this allows one to obtain the bond length for a particular bond order. For example, to get the C=C bon...
The bond order according the distance between the two sites Args: tol (float): Relative tolerance to test. (1 + tol) * the longest bond distance is considered to be the threshold length for a bond to exist. (1 - tol) * the shortest bond distance is con...
Test if two sites are bonded, up to a certain limit. Args: site1 (Site): First site site2 (Site): Second site tol (float): Relative tolerance to test. Basically, the code checks if the distance between the sites is less than (1 + tol) * typical...
Sends an e-mail with unix sendmail. Args: subject: String with the subject of the mail. text: String with the body of the mail. mailto: String or list of string with the recipients. sender: string with the sender address. If sender is None, username@hostname is used. ...
Declare a env variable. If val is None the variable is unset. def declare_var(self, key, val): """Declare a env variable. If val is None the variable is unset.""" if val is not None: line = "export " + key + '=' + str(val) else: line = "unset " + key self._add(l...
Declare the variables defined in the dictionary d. def declare_vars(self, d): """Declare the variables defined in the dictionary d.""" for k, v in d.items(): self.declare_var(k, v)
Export an environment variable. def export_envar(self, key, val): """Export an environment variable.""" line = "export " + key + "=" + str(val) self._add(line)
Export the environment variables contained in the dict env. def export_envars(self, env): """Export the environment variables contained in the dict env.""" for k, v in env.items(): self.export_envar(k, v)
Returns a string with the script and reset the editor if reset is True def get_script_str(self, reset=True): """Returns a string with the script and reset the editor if reset is True""" s = "\n".join(l for l in self._lines) if reset: self.reset() return s
Run the first :class:`Task` than is ready for execution. Returns: Number of jobs launched. def single_shot(self): """ Run the first :class:`Task` than is ready for execution. Returns: Number of jobs launched. """ num_launched = 0 # Get ...
Keeps submitting `Tasks` until we are out of jobs or no job is ready to run. Args: max_nlaunch: Maximum number of launches. default: no limit. max_loops: Maximum number of loops sleep_time: seconds to sleep between rapidfire loop iterations Returns: The ...
Return the list of tasks that can be submitted. Empty list if no task has been found. def fetch_tasks_to_run(self): """ Return the list of tasks that can be submitted. Empty list if no task has been found. """ tasks_to_run = [] for work in self.flow: ...
Read the configuration parameters from a Yaml file. def from_file(cls, filepath): """Read the configuration parameters from a Yaml file.""" with open(filepath, "rt") as fh: return cls(**yaml.safe_load(fh))
Create an istance from string s containing a YAML dictionary. def from_string(cls, s): """Create an istance from string s containing a YAML dictionary.""" stream = cStringIO(s) stream.seek(0) return cls(**yaml.safe_load(stream))
Initialize the :class:`PyFlowScheduler` from the YAML file 'scheduler.yml'. Search first in the working directory and then in the configuration directory of abipy. Raises: `RuntimeError` if file is not found. def from_user_config(cls): """ Initialize the :class:`PyFlowSched...
The pid of the process associated to the scheduler. def pid(self): """The pid of the process associated to the scheduler.""" try: return self._pid except AttributeError: self._pid = os.getpid() return self._pid
Add an :class:`Flow` flow to the scheduler. def add_flow(self, flow): """ Add an :class:`Flow` flow to the scheduler. """ if hasattr(self, "_flow"): raise self.Error("Only one flow can be added to the scheduler.") # Check if we are already using a scheduler to run t...
Validate input parameters if customer service is on then create directory for tarball files with correct premissions for user and group. def _validate_customer_service(self): """ Validate input parameters if customer service is on then create directory for tarball files with correct pre...
This method is called before the shutdown of the scheduler. If customer_service is on and the flow didn't completed successfully, a lightweight tarball file with inputs and the most important output files is created in customer_servide_dir. def _do_customer_service(self): """ Th...
Starts the scheduler in a new thread. Returns 0 if success. In standalone mode, this method will block until there are no more scheduled jobs. def start(self): """ Starts the scheduler in a new thread. Returns 0 if success. In standalone mode, this method will block until there are no m...
This function checks the status of all tasks, tries to fix tasks that went unconverged, abicritical, or queuecritical and tries to run all the tasks that can be submitted.+ def _runem_all(self): """ This function checks the status of all tasks, tries to fix tasks that went uncon...
The function that will be executed by the scheduler. def callback(self): """The function that will be executed by the scheduler.""" try: return self._callback() except: # All exceptions raised here will trigger the shutdown! s = straceback() self....
The actual callback. def _callback(self): """The actual callback.""" if self.debug: # Show the number of open file descriptors print(">>>>> _callback: Number of open file descriptors: %s" % get_open_fds()) self._runem_all() # Mission accomplished. Shutdown the ...
Cleanup routine: remove the pid file and save the pickle database def cleanup(self): """Cleanup routine: remove the pid file and save the pickle database""" try: os.remove(self.pid_file) except OSError as exc: logger.critical("Could not remove pid_file: %s", exc) ...
Shutdown the scheduler. def shutdown(self, msg): """Shutdown the scheduler.""" try: self.cleanup() self.history.append("Completed on: %s" % time.asctime()) self.history.append("Elapsed time: %s" % self.get_delta_etime()) if self.debug: p...