INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
A slurm time parser. Accepts a string in one the following forms:
def slurm_parse_timestr(s): """ 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 se...
Convert a number representing a time value in the given unit ( Default: seconds ) to a string following the slurm convention: days - hours: minutes: seconds.
def time2slurm(timeval, unit="s"): """ 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, uni...
Convert a number representing a time value in the given unit ( Default: seconds ) to a string following the PbsPro convention: hours: minutes: seconds.
def time2pbspro(timeval, unit="s"): """ 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' """ h, m, s = 3600, 60, 1 timeval = Time(timeval, un...
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.
def max_cation_removal(self): """ 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!) """ # how much 'spare charge' is left in the redox metals fo...
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.
def max_cation_insertion(self): """ 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. Dep...
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 normalize the capacity and intended as a helper method """ num_cations = 0 if remove: num_cations += self.max_cation_remova...
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.
def get_max_capgrav(self, remove=True, insert=True): """ 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. ...
Give max capacity in mAh/ cc for inserting and removing a charged cation into base structure.
def get_max_capvol(self, remove=True, insert=True, volume=None): """ 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 ...
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 algorithm.
def get_removals_int_oxid(self): """ 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...
This is a helper method for get_removals_int_oxid!
def _get_int_removals_helper(self, spec_amts_oxi, oxid_el, oxid_els, numa): """ 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 l...
Helper method to reduce a sym_amt dict to a reduced formula and factor.
def reduce_formula(sym_amt, iupac_ordering=False): """ 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 i...
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: composition (Composition): input composition strict (bool): Whether all potentials must be specified """ if strict and set(composition.keys()) > set(...
Constructor for MoleculeGraph using pre - existing or pre - defined edges with optional edge parameters.
def with_edges(structure, edges): """ 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, t...
Constructor for StructureGraph using a strategy from: Class: pymatgen. analysis. local_env.
def with_local_env_strategy(structure, strategy): """ 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`...
Add edge to graph.
def add_edge(self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have ...
Alters either the weight or the edge_properties of an edge in the StructureGraph.
def alter_edge(self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None): """ 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: t...
Remove an edge from the StructureGraph. If no image is given this method will fail.
def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): """ 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_re...
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.
def substitute_group(self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None): """ 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 ...
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: return: list of ConnectedSite tuples sorted by closest fi...
def get_connected_sites(self, n, jimage=(0, 0, 0)): """ 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 o...
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 returns degree of node corresponding to site n. :param n: index of site :return (int): """ number_of_self_loops = sum([1 for n, v in self.graph.edg...
Draws graph using GraphViz.
def draw_graph_to_file(self, filename="graph", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_la...
Extract a dictionary summarizing the types and weights of edges in the graph.
def types_and_weights_of_connections(self): """ 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...
Extract a statistical summary of edge weights present in the graph.
def weight_statistics(self): """ 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' """ all_weights = [d.get('weight', None) for u, v, d ...
Extract information on the different co - ordination environments present in the graph.
def types_of_coordination_environments(self, anonymous=False): """ 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 environm...
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 restore graph information. """ s = Structure.from_dict(d['structure']) return cls(s, d['graphs'])
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_structure = self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._site...
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.
def diff(self, other, strict=True): """ 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 ...
Retrieve subgraphs as molecules useful for extracting molecules from periodic crystals.
def get_subgraphs_as_molecules(self, use_weights=False): """ 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 subgra...
Constructor for MoleculeGraph returns a MoleculeGraph object with an empty graph ( no edges only nodes defined that correspond to Sites in Molecule ).
def with_empty_graph(cls, molecule, name="bonds", edge_weight_name=None, edge_weight_units=None): """ Constructor for MoleculeGraph, returns a MoleculeGraph object with an empty graph (no edges, only nodes defined that correspond to Sites...
Constructor for MoleculeGraph using pre - existing or pre - defined edges with optional edge parameters.
def with_edges(molecule, edges): """ 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},...
Constructor for MoleculeGraph using a strategy from: Class: pymatgen. analysis. local_env.
def with_local_env_strategy(molecule, strategy, reorder=True, extend_structure=True): """ Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of ...
Add edge to graph.
def add_edge(self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swap...
A wrapper around Molecule. insert () which also incorporates the new site into the MoleculeGraph.
def insert_node(self, i, species, coords, validate_proximity=False, site_properties=None, edges=None): """ 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 ...
Replicates molecule site properties ( specie coords etc. ) in the MoleculeGraph.
def set_node_attributes(self): """ Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return: """ species = {} coords = {} properties = {} for node in self.graph.nodes(): species[node] = self.molecule[no...
Alters either the weight or the edge_properties of an edge in the MoleculeGraph.
def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): """ 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 n...
Remove an edge from the MoleculeGraph
def break_edge(self, from_index, to_index, allow_reverse=False): """ 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, f...
A wrapper for Molecule. remove_sites ().
def remove_nodes(self, indices): """ A wrapper for Molecule.remove_sites(). :param indices: list of indices in the current Molecule (and graph) to be removed. :return: """ self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) ...
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 underlying Moledules. If the bonds parameter ...
def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): """ Split MoleculeGraph into two or more MoleculeGraphs by breaking a set of bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs ...
Find all possible fragment combinations of the MoleculeGraphs ( in other words all connected induced subgraphs )
def build_unique_fragments(self): """ Find all possible fragment combinations of the MoleculeGraphs (in other words, all connected induced subgraphs) :return: """ self.set_node_attributes() graph = self.graph.to_undirected() nm = iso.categorical_node_ma...
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.
def substitute_group(self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, reorder=True, extend_structure=True): """ Builds off of Molecule.substitute to replace an atom in self.molecule with a functional group. Th...
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.
def replace_group(self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, reorder=True, extend_structure=True): """ Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self...
Find ring structures in the MoleculeGraph.
def find_rings(self, including=None): """ 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 ...
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: return: list of ConnectedSite tuples sorted by closest fir...
def get_connected_sites(self, n): """ 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...
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. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "molecule": self.molec...
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 restore graph information. """ m = Molecule.from_dict(d['molecule']) return cls(m, d['graphs'])
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_molecule = self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites, key...
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.
def isomorphic_to(self, other): """ 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. ...
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 = sorted(row['elements']) d...
Obtain bond lengths for all bond orders from bond length database
def obtain_all_bond_lengths(sp1, sp2, default_bl=None): """ 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...
Calculate the bond order given the distance of 2 species
def get_bond_order(sp1, sp2, dist, tol=0.2, default_bl=None): """ 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 ...
Get the bond length between two species.
def get_bond_length(sp1, sp2, bond_order=1): """ 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 particula...
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 considered to be the shortest possible bond length Defaults to 0....
def get_bond_order(self, tol=0.2, default_bl=None): """ 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...
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 bond distances. Defaults to 0. 2 i. e. 20% longer. bond_order: Bond o...
def is_bonded(site1, site2, tol=0.2, bond_order=None, default_bl=None): """ 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 ...
Sends an e - mail with unix sendmail.
def sendmail(subject, text, mailto, sender=None): """ 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....
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(line)
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.
def single_shot(self): """ Run the first :class:`Task` than is ready for execution. Returns: Number of jobs launched. """ num_launched = 0 # Get the tasks that can be executed in each workflow. tasks = [] for work in self.flow: tr...
Keeps submitting Tasks until we are out of jobs or no job is ready to run.
def rapidfire(self, max_nlaunch=-1, max_loops=1, sleep_time=5): """ 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: s...
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: tasks_to_run.extend(work.fetch_alltasks_to_run()) return tasks_to_run
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.
def from_user_config(cls): """ 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. """ # Try in the cu...
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 this flow flow.check_pid_file() ...
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 premissions for user and group. """ direc = self.customer_service_dir if not direc.exists: mode = 0o750 ...
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): """ 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. ...
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 more scheduled jobs. """ self.history.append("Started on %s" % time.asctime()) self.start_time = time.time() if not has_...
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 unconverged, abicritical, or queuecritical and tries to run all the tasks that can be submitted.+ """ excs = [] flow = self.flow # Allow to change the man...
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.exceptions.append(s) # This is useful whe...
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 scheduler. all...
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) # Save the final status of the flow. self.flow.pickle_dum...
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: print(">>>>> shutdown: Num...
Send an e - mail before completing the shutdown. Returns 0 if success.
def send_email(self, msg, tag=None): """ Send an e-mail before completing the shutdown. Returns 0 if success. """ try: return self._send_email(msg, tag) except: self.exceptions.append(straceback()) return -2
Find all flows located withing the directory top and build the BatchLauncher.
def from_dir(cls, top, workdir=None, name=None, manager=None, max_depth=2): """ Find all flows located withing the directory `top` and build the `BatchLauncher`. Args: top: Top level directory or list of directories. workdir: Batch workdir. name: ...
Loads the object from a pickle file.
def pickle_load(cls, filepath): """ Loads the object from a pickle file. Args: filepath: Filename or directory name. It filepath is a directory, we scan the directory tree starting from filepath and we read the first pickle database. Raise RuntimeErro...
Save the status of the object in pickle format.
def pickle_dump(self): """Save the status of the object in pickle format.""" with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh: pickle.dump(self, fh)
Add a flow. Accept filepath or: class: Flow object. Return 1 if flow was added else 0.
def add_flow(self, flow): """ Add a flow. Accept filepath or :class:`Flow` object. Return 1 if flow was added else 0. """ from .flows import Flow flow = Flow.as_flow(flow) if flow in self.flows: raise self.Error("Cannot add same flow twice!") if not ...
Submit a job script that will run the schedulers with abirun. py.
def submit(self, **kwargs): """ Submit a job script that will run the schedulers with `abirun.py`. Args: verbose: Verbosity level dry_run: Don't submit the script if dry_run. Default: False Returns: namedtuple with attributes: retcode...
Write the submission script. Return ( script num_flows_in_batch )
def _get_script_nflows(self): """ Write the submission script. Return (script, num_flows_in_batch) """ flows_torun = [f for f in self.flows if not f.all_ok] if not flows_torun: return "", 0 executable = [ 'export _LOG=%s' % self.log_file.path, ...
Generates the string representation of the CTRL file. This is the mininmal CTRL file necessary to execute lmhart. run.
def get_string(self, sigfigs=8): """ Generates the string representation of the CTRL file. This is the mininmal CTRL file necessary to execute lmhart.run. """ ctrl_dict = self.as_dict() lines = [] if "HEADER" not in ctrl_dict else \ ["HEADER".ljust(10) + self....
Returns the CTRL as a dictionary. SITE and CLASS are of the form { CATEGORY: { TOKEN: value }} the rest is of the form TOKEN/ CATEGORY: value. It gets the conventional standard structure because primitive cells use the conventional a - lattice parameter as the scaling factor and not the a - lattice parameter of the pri...
def as_dict(self): """ Returns the CTRL as a dictionary. "SITE" and "CLASS" are of the form {'CATEGORY': {'TOKEN': value}}, the rest is of the form 'TOKEN'/'CATEGORY': value. It gets the conventional standard structure because primitive cells use the conventional a-lattic...
Creates a CTRL file object from an existing file.
def from_file(cls, filename="CTRL", **kwargs): """ Creates a CTRL file object from an existing file. Args: filename: The name of the CTRL file. Defaults to 'CTRL'. Returns: An LMTOCtrl object. """ with zopen(filename, "rt") as f: cont...
Creates a CTRL file object from a string. This will mostly be used to read an LMTOCtrl object from a CTRL file. Empty spheres are ignored.
def from_string(cls, data, sigfigs=8): """ Creates a CTRL file object from a string. This will mostly be used to read an LMTOCtrl object from a CTRL file. Empty spheres are ignored. Args: data: String representation of the CTRL file. Returns: An ...
Creates a CTRL file object from a dictionary. The dictionary must contain the items ALAT PLAT and SITE.
def from_dict(cls, d): """ Creates a CTRL file object from a dictionary. The dictionary must contain the items "ALAT", PLAT" and "SITE". Valid dictionary items are: ALAT: the a-lattice parameter PLAT: (3x3) array for the lattice vectors SITE: list of ...
Subroutine to extract bond label site indices and length from a COPL header line. The site indices are zero - based so they can be easily used with a Structure object.
def _get_bond_data(line): """ Subroutine to extract bond label, site indices, and length from a COPL header line. The site indices are zero-based, so they can be easily used with a Structure object. Example header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang. Args: ...
Finds a set of n_images from self. s1 to self. s2 where all sites except for the ones given in relax_sites the interpolation is linear ( as in pymatgen. core. structure. interpolate ) and for the site indices given in relax_sites the path is relaxed by the elastic band method within the static potential V.
def interpolate(self): """ Finds a set of n_images from self.s1 to self.s2, where all sites except for the ones given in relax_sites, the interpolation is linear (as in pymatgen.core.structure.interpolate), and for the site indices given in relax_sites, the path is relaxed by the...
Generates a POSCAR with the calculated diffusion path with respect to the first endpoint.: param outfile: Output file for the POSCAR
def plot_images(self, outfile): """ Generates a POSCAR with the calculated diffusion path with respect to the first endpoint. :param outfile: Output file for the POSCAR """ sum_struct = self.__images[0].sites for image in self.__images: for site_i in self.__re...
Implements path relaxation via the elastic band method. In general the method is to define a path by a set of points ( images ) connected with bands with some elasticity constant k. The images then relax along the forces found in the potential field V counterbalanced by the elastic response of the elastic band. In gene...
def string_relax(start, end, V, n_images=25, dr=None, h=3.0, k=0.17, min_iter=100, max_iter=10000, max_tol=5e-6): """ Implements path relaxation via the elastic band method. In general, the method is to define a path by a set of points (images) connected with bands w...
Converts fractional coordinates to discrete coordinates with respect to the grid size of v
def __f2d(frac_coords, v): """ Converts fractional coordinates to discrete coordinates with respect to the grid size of v """ # frac_coords = frac_coords % 1 return np.array([int(frac_coords[0] * v.shape[0]), int(frac_coords[1] * v.shape[1]), ...
Converts a point given in discrete coordinates withe respect to the grid in v to fractional coordinates.
def __d2f(disc_coords, v): """ Converts a point given in discrete coordinates withe respect to the grid in v to fractional coordinates. """ return np.array([disc_coords[0] / v.shape[0], disc_coords[1] / v.shape[1], disc_coords[2] ...
Sets the potential range 0 to 1.
def normalize(self): """ Sets the potential range 0 to 1. """ self.__v = self.__v - np.amin(self.__v) self.__v = self.__v / np.amax(self.__v)
Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed or is too fine or coarse. Obeys periodic boundary conditions at the edges of the cell. Alternatively useful for mixing potentials that originally are on different gri...
def rescale_field(self, new_dim): """ Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of th...
Applies an isotropic Gaussian smear of width ( standard deviation ) r to the potential field. This is necessary to avoid finding paths through narrow minima or nodes that may exist in the field ( although any potential or charge distribution generated from GGA should be relatively smooth anyway ). The smearing obeys pe...
def gaussian_smear(self, r): """ Applies an isotropic Gaussian smear of width (standard deviation) r to the potential field. This is necessary to avoid finding paths through narrow minima or nodes that may exist in the field (although any potential or charge distribution generate...
Given a structure returns the predicted volume. Args: structure ( Structure ): structure w/ unknown volume ref_structure ( Structure ): A reference structure with a similar structure but different species. Returns: a float value of the predicted volume
def predict(self, structure, ref_structure): """ Given a structure, returns the predicted volume. Args: structure (Structure): structure w/unknown volume ref_structure (Structure): A reference structure with a similar structure but different species. ...
Given a structure returns back the structure scaled to predicted volume. Args: structure ( Structure ): structure w/ unknown volume ref_structure ( Structure ): A reference structure with a similar structure but different species. Returns: a Structure object with predicted volume
def get_predicted_structure(self, structure, ref_structure): """ Given a structure, returns back the structure scaled to predicted volume. Args: structure (Structure): structure w/unknown volume ref_structure (Structure): A reference structure with a similar ...
Given a structure returns the predicted volume.
def predict(self, structure, icsd_vol=False): """ Given a structure, returns the predicted volume. Args: structure (Structure) : a crystal structure with an unknown volume. icsd_vol (bool) : True if the input structure's volume comes from ICSD. R...