docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Returns the positions of the extrema along the MEP. Both local minimums and maximums are returned. Args: normalize_rxn_coordinate (bool): Whether to normalize the reaction coordinate to between 0 and 1. Defaults to True. Returns: (min_extrema, max_extrem...
def get_extrema(self, normalize_rxn_coordinate=True): x = np.arange(0, np.max(self.r), 0.01) y = self.spline(x) * 1000 scale = 1 if not normalize_rxn_coordinate else 1 / self.r[-1] min_extrema = [] max_extrema = [] for i in range(1, len(x) - 1): if y...
140,042
Returns the NEB plot. Uses Henkelman's approach of spline fitting each section of the reaction path based on tangent force and energies. Args: normalize_rxn_coordinate (bool): Whether to normalize the reaction coordinate to between 0 and 1. Defaults to True. labe...
def get_plot(self, normalize_rxn_coordinate=True, label_barrier=True): plt = pretty_plot(12, 8) scale = 1 if not normalize_rxn_coordinate else 1 / self.r[-1] x = np.arange(0, np.max(self.r), 0.01) y = self.spline(x) * 1000 relative_energies = self.energies - self.energie...
140,043
Check the status of the works in self. Args: show: True to show the status of the flow. kwargs: keyword arguments passed to show_status
def check_status(self, **kwargs): for work in self: work.check_status() if kwargs.pop("show", False): self.show_status(**kwargs)
140,075
Print a short summary with the status of the flow and a counter task_status --> number_of_tasks Args: stream: File-like object, Default: sys.stdout Example: Status Count --------- ------- Completed 10 <Flow, node_id=27163, work...
def show_summary(self, **kwargs): stream = kwargs.pop("stream", sys.stdout) stream.write("\n") table = list(self.status_counter.items()) s = tabulate(table, headers=["Status", "Count"]) stream.write(s + "\n") stream.write("\n") stream.write("%s, num_tasks...
140,079
Report the status of the works and the status of the different tasks on the specified stream. Args: stream: File-like object, Default: sys.stdout nids: List of node identifiers. By defaults all nodes are shown wslice: Slice object used to select works. verbose:...
def show_status(self, **kwargs): stream = kwargs.pop("stream", sys.stdout) nids = as_set(kwargs.pop("nids", None)) wslice = kwargs.pop("wslice", None) verbose = kwargs.pop("verbose", 0) wlist = None if wslice is not None: # Convert range to list of wo...
140,080
Print the Abinit events (ERRORS, WARNIING, COMMENTS) to stdout Args: status: if not None, only the tasks with this status are select nids: optional list of node identifiers used to filter the tasks.
def show_events(self, status=None, nids=None): nrows, ncols = get_terminal_size() for task in self.iflat_tasks(status=status, nids=nids): report = task.get_event_report() if report: print(make_banner(str(task), width=ncols, mark="=")) pri...
140,081
Show the corrections applied to the flow at run-time. Args: status: if not None, only the tasks with this status are select. nids: optional list of node identifiers used to filter the tasks. Return: The number of corrections found.
def show_corrections(self, status=None, nids=None): nrows, ncols = get_terminal_size() count = 0 for task in self.iflat_tasks(status=status, nids=nids): if task.num_corrections == 0: continue count += 1 print(make_banner(str(task), width=ncols, mark="...
140,082
Print the history of the flow to stdout. Args: status: if not None, only the tasks with this status are select full_history: Print full info set, including nodes with an empty history. nids: optional list of node identifiers used to filter the tasks. metadata: pr...
def show_history(self, status=None, nids=None, full_history=False, metadata=False): nrows, ncols = get_terminal_size() works_done = [] # Loop on the tasks and show the history of the work is not in works_done for task in self.iflat_tasks(status=status, nids=nids): w...
140,083
Print the input of the tasks to the given stream. Args: varnames: List of Abinit variables. If not None, only the variable in varnames are selected and printed. nids: List of node identifiers. By defaults all nodes are shown ws...
def show_inputs(self, varnames=None, nids=None, wslice=None, stream=sys.stdout): if varnames is not None: # Build dictionary varname --> [(task1, value), (task2, value), ...] varnames = [s.strip() for s in list_strings(varnames)] dlist = collections.defaultdict(list)...
140,084
Return a list with a subset of tasks. Args: nids: List of node identifiers. wslice: Slice object used to select works. task_class: String or class used to select tasks. Ignored if None. .. note:: nids and wslice are mutually exclusive. If no...
def select_tasks(self, nids=None, wslice=None, task_class=None): if nids is not None: assert wslice is None tasks = self.tasks_from_nids(nids) elif wslice is not None: tasks = [] for work in self[wslice]: tasks.extend([t for t in ...
140,086
Return list of (taks, scfcycle) tuples for all the tasks in the flow with a SCF algorithm e.g. electronic GS-SCF iteration, DFPT-SCF iterations etc. Args: nids: List of node identifiers. wslice: Slice object used to select works. task_class: String or class used to s...
def get_task_scfcycles(self, nids=None, wslice=None, task_class=None, exclude_ok_tasks=False): select_status = [self.S_RUN] if exclude_ok_tasks else [self.S_RUN, self.S_OK] tasks_cycles = [] for task in self.select_tasks(nids=nids, wslice=wslice): # Fileter if t...
140,087
Print list of tricky tasks i.e. tasks that have been restarted or launched more than once or tasks with corrections. Args: verbose: Verbosity level. If > 0, task history and corrections (if any) are printed.
def show_tricky_tasks(self, verbose=0): nids, tasks = [], [] for task in self.iflat_tasks(): if task.num_launches > 1 or any(n > 0 for n in (task.num_restarts, task.num_corrections)): nids.append(task.node_id) tasks.append(task) if not nids: ...
140,088
Inspect the tasks (SCF iterations, Structural relaxation ...) and produces matplotlib plots. Args: nids: List of node identifiers. wslice: Slice object used to select works. kwargs: keyword arguments passed to `task.inspect` method. .. note:: ni...
def inspect(self, nids=None, wslice=None, **kwargs): figs = [] for task in self.select_tasks(nids=nids, wslice=wslice): if hasattr(task, "inspect"): fig = task.inspect(**kwargs) if fig is None: cprint("Cannot inspect Task %s" % tas...
140,089
Parse the timer data in the main output file(s) of Abinit. Requires timopt /= 0 in the input file (usually timopt = -1) Args: nids: optional list of node identifiers used to filter the tasks. Return: :class:`AbinitTimerParser` instance, None if error.
def parse_timing(self, nids=None): # Get the list of output files according to nids. paths = [task.output_file.path for task in self.iflat_tasks(nids=nids)] # Parse data. from .abitimer import AbinitTimerParser parser = AbinitTimerParser() read_ok = parser.parse...
140,096
Write to the given stream the list of ABINIT errors for all tasks whose status is S_ABICRITICAL. Args: nids: optional list of node identifiers used to filter the tasks. stream: File-like object. Default: sys.stdout
def show_abierrors(self, nids=None, stream=sys.stdout): lines = [] app = lines.append for task in self.iflat_tasks(status=self.S_ABICRITICAL, nids=nids): header = "=== " + task.qout_file.path + "===" app(header) report = task.get_event_report() ...
140,097
Write to the given stream the content of the queue output file for all tasks whose status is S_QCRITICAL. Args: nids: optional list of node identifiers used to filter the tasks. stream: File-like object. Default: sys.stdout
def show_qouts(self, nids=None, stream=sys.stdout): lines = [] for task in self.iflat_tasks(status=self.S_QCRITICAL, nids=nids): header = "=== " + task.qout_file.path + "===" lines.append(header) if task.qout_file.exists: with open(task.qout_...
140,098
This method is usually used when the flow didn't completed succesfully It analyzes the files produced the tasks to facilitate debugging. Info are printed to stdout. Args: status: If not None, only the tasks with this status are selected nids: optional list of node identi...
def debug(self, status=None, nids=None): nrows, ncols = get_terminal_size() # Test for scheduler exceptions first. sched_excfile = os.path.join(self.workdir, "_exceptions") if os.path.exists(sched_excfile): with open(sched_excfile, "r") as fh: cprint...
140,099
Build dirs and file of the `Flow` and save the object in pickle format. Returns 0 if success Args: abivalidate: If True, all the input files are validate by calling the abinit parser. If the validation fails, ValueError is raise.
def build_and_pickle_dump(self, abivalidate=False): self.build() if not abivalidate: return self.pickle_dump() # Validation with Abinit. isok, errors = self.abivalidate_inputs() if isok: return self.pickle_dump() errlines = [] for i, e in enumerate(error...
140,103
Allocate the `Flow` i.e. assign the `workdir` and (optionally) the :class:`TaskManager` to the different tasks in the Flow. Args: workdir: Working directory of the flow. Must be specified here if we haven't initialized the workdir in the __init__. Return: ...
def allocate(self, workdir=None, use_smartio=False): if workdir is not None: # We set the workdir of the flow here self.set_workdir(workdir) for i, work in enumerate(self): work.set_workdir(os.path.join(self.workdir, "w" + str(i))) if not has...
140,109
Use :class:`PyLauncher` to submits tasks in rapidfire mode. kwargs contains the options passed to the launcher. Args: check_status: max_nlaunch: Maximum number of launches. default: no limit. max_loops: Maximum number of loops sleep_time: seconds to sleep...
def rapidfire(self, check_status=True, max_nlaunch=-1, max_loops=1, sleep_time=5, **kwargs): self.check_pid_file() self.set_spectator_mode(False) if check_status: self.check_status() from .launcher import PyLauncher return PyLauncher(self, **kwargs).rapidfire(max_nlaunch...
140,119
Build a return a :class:`PyFlowScheduler` to run the flow. Args: kwargs: if empty we use the user configuration file. if `filepath` in kwargs we init the scheduler from filepath. else pass **kwargs to :class:`PyFlowScheduler` __init__ method.
def make_scheduler(self, **kwargs): from .launcher import PyFlowScheduler if not kwargs: # User config if kwargs is empty sched = PyFlowScheduler.from_user_config() else: # Use from_file if filepath if present, else call __init__ filepath ...
140,121
Run the flow in batch mode, return exit status of the job script. Requires a manager.yml file and a batch_adapter adapter. Args: timelimit: Time limit (int with seconds or string with time given with the slurm convention: "days-hours:minutes:seconds"). If timelimit is None, the ...
def batch(self, timelimit=None): from .launcher import BatchLauncher # Create a batch dir from the flow.workdir. prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1]) prev_dir = os.path.join(os.path.sep, prev_dir) workdir = os.path.join(prev_dir, os.path.basenam...
140,122
Generate flow graph in the DOT language. Args: engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_attr: Mapping of (attribute, value) pairs for the graph. node_attr: Mapping of (attribute, value) pairs set for all nodes...
def get_graphviz(self, engine="automatic", graph_attr=None, node_attr=None, edge_attr=None): self.allocate() from graphviz import Digraph fg = Digraph("flow", #filename="flow_%s.gv" % os.path.basename(self.relworkdir), engine="fdp" if engine == "automatic" else engine) ...
140,125
Generate flow graph in the DOT language and plot it with matplotlib. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. figsize: matplotlib figure size (None to use default) dpi: DPI value. fmt: Select format for output image R...
def graphviz_imshow(self, ax=None, figsize=None, dpi=300, fmt="png", **kwargs): graph = self.get_graphviz(**kwargs) graph.format = fmt graph.attr(dpi=str(dpi)) #print(graph) _, tmpname = tempfile.mkstemp() path = graph.render(tmpname, view=False, cleanup=True) ...
140,126
Convenience method to get a crystal from the Materials Project database via the API. Requires PMG_MAPI_KEY to be set. Args: formula (str): A formula Returns: (Structure) The lowest energy structure in Materials Project with that formula.
def get_structure_from_mp(formula): m = MPRester() entries = m.get_entries(formula, inc_structure="final") if len(entries) == 0: raise ValueError("No structure with formula %s in Materials Project!" % formula) elif len(entries) > 1: warnings.warn("%d structu...
140,157
Convenience method to perform quick loading of data from a filename. The type of object returned depends the file type. Args: fname (string): A filename. Returns: Note that fname is matched using unix-style, i.e., fnmatch. (Structure) if *POSCAR*/*CONTCAR*/*.cif (Vasprun) *...
def loadfn(fname): if (fnmatch(fname, "*POSCAR*") or fnmatch(fname, "*CONTCAR*") or ".cif" in fname.lower()) or fnmatch(fname, "*.vasp"): return Structure.from_file(fname) elif fnmatch(fname, "*vasprun*"): from pymatgen.io.vasp import Vasprun return Vasprun(fname) el...
140,158
Save the assimilated data to a file. Args: filename (str): filename to save the assimilated data to. Note that if the filename ends with gz or bz2, the relevant gzip or bz2 compression will be applied.
def save_data(self, filename): with zopen(filename, "wt") as f: json.dump(list(self._data), f, cls=MontyEncoder)
140,163
Returns the nac_frequencies for the given direction (not necessarily a versor). None if the direction is not present or nac_frequencies has not been calculated. Args: direction: the direction as a list of 3 elements Returns: the frequencies as a numpy array o(3*len(struc...
def get_nac_frequencies_along_dir(self, direction): versor = [i / np.linalg.norm(direction) for i in direction] for d, f in self.nac_frequencies: if np.allclose(versor, d): return f return None
140,169
Returns the nac_eigendisplacements for the given direction (not necessarily a versor). None if the direction is not present or nac_eigendisplacements has not been calculated. Args: direction: the direction as a list of 3 elements Returns: the eigendisplacements as a nump...
def get_nac_eigendisplacements_along_dir(self, direction): versor = [i / np.linalg.norm(direction) for i in direction] for d, e in self.nac_eigendisplacements: if np.allclose(versor, d): return e return None
140,170
Returns the list of qpoint indices equivalent (meaning they are the same frac coords) to the given one. Args: index: the qpoint index Returns: a list of equivalent indices TODO: now it uses the label we might want to use coordinates instead (in case the...
def get_equivalent_qpoints(self, index): #if the qpoint has no label it can"t have a repetition along the band #structure line object if self.qpoints[index].label is None: return [index] list_index_qpoints = [] for i in range(self.nb_qpoints): i...
140,175
Returns in what branch(es) is the qpoint. There can be several branches. Args: index: the qpoint index Returns: A list of dictionaries [{"name","start_index","end_index","index"}] indicating all branches in which the qpoint is. It takes into acco...
def get_branch(self, index): to_return = [] for i in self.get_equivalent_qpoints(index): for b in self.branches: if b["start_index"] <= i <= b["end_index"]: to_return.append({"name": b["name"], "st...
140,176
Applies a structure_filter to the list of TransformedStructures in the transmuter. Args: structure_filter: StructureFilter to apply.
def apply_filter(self, structure_filter): def test_transformed_structure(ts): return structure_filter.test(ts.final_structure) self.transformed_structures = list(filter(test_transformed_structure, self.transformed_structures)) ...
140,186
Add parameters to the transmuter. Additional parameters are stored in the as_dict() output. Args: key: The key for the parameter. value: The value for the parameter.
def set_parameter(self, key, value): for x in self.transformed_structures: x.other_parameters[key] = value
140,187
Method is overloaded to accept either a list of transformed structures or transmuter, it which case it appends the second transmuter"s structures. Args: tstructs_or_transmuter: A list of transformed structures or a transmuter.
def append_transformed_structures(self, tstructs_or_transmuter): if isinstance(tstructs_or_transmuter, self.__class__): self.transformed_structures.extend(tstructs_or_transmuter .transformed_structures) else: for ts in tstru...
140,189
Generates a TransformedStructureCollection from a cif, possibly containing multiple structures. Args: filenames: List of strings of the cif files transformations: New transformations to be applied to all structures primitive: Same meaning as in __init...
def from_filenames(filenames, transformations=None, primitive=True, extend_collection=False): allcifs = [] for fname in filenames: with open(fname, "r") as f: allcifs.append(f.read()) return CifTransmuter("\n".join(allcifs), transforma...
140,192
Convenient constructor to generates a POSCAR transmuter from a list of POSCAR filenames. Args: poscar_filenames: List of POSCAR filenames transformations: New transformations to be applied to all structures. extend_collection: Same mea...
def from_filenames(poscar_filenames, transformations=None, extend_collection=False): tstructs = [] for filename in poscar_filenames: with open(filename, "r") as f: tstructs.append(TransformedStructure .from_posca...
140,194
Compare multiple cycels on a grid: one subplot per quantity, all cycles on the same subplot. Args: fontsize: Legend fontsize.
def combiplot(self, fontsize=8, **kwargs): ax_list = None for i, (label, cycle) in enumerate(self.items()): fig = cycle.plot(ax_list=ax_list, label=label, fontsize=fontsize, lw=2.0, marker="o", linestyle="-", show=False) ax_list = fig.axes ...
140,202
Uses matplotlib to plot the evolution of the structural relaxation. Args: ax_list: List of axes. If None a new figure is produced. Returns: `matplotlib` figure
def slideshow(self, **kwargs): for i, cycle in enumerate(self.cycles): cycle.plot(title="Relaxation step %s" % (i + 1), tight_layout=kwargs.pop("tight_layout", True), show=kwargs.pop("show", True))
140,208
Plot relaxation history i.e. the results of the last iteration of each SCF cycle. Args: ax_list: List of axes. If None a new figure is produced. fontsize: legend fontsize. kwargs: keyword arguments are passed to ax.plot Returns: matplotlib figure
def plot(self, ax_list=None, fontsize=12, **kwargs): history = self.history # Build grid of plots. num_plots, ncols, nrows = len(history), 1, 1 if num_plots > 1: ncols = 2 nrows = num_plots // ncols + num_plots % ncols ax_list, fig, plot = get_a...
140,209
Merge GGK files, return the absolute path of the new database. Args: gswfk_file: Ground-state WFK filename dfpt_files: List of 1WFK files to merge. gkk_files: List of GKK files to merge. out_gkk: Name of the output GKK file binascii: Integer flat. 0 -...
def merge(self, workdir, gswfk_file, dfpt_files, gkk_files, out_gkk, binascii=0): raise NotImplementedError("This method should be tested") #out_gkk = out_gkk if cwd is None else os.path.join(os.path.abspath(cwd), out_gkk) # We work with absolute paths. gswfk_file = os.path.abs...
140,222
Merge POT files containing 1st order DFPT potential return the absolute path of the new database in workdir. Args: delete_source: True if POT1 files should be removed after (successful) merge.
def merge(self, workdir, pot_files, out_dvdb, delete_source=True): # We work with absolute paths. pot_files = [os.path.abspath(s) for s in list_strings(pot_files)] if not os.path.isabs(out_dvdb): out_dvdb = os.path.join(os.path.abspath(workdir), os.path.basename(out_dvdb)) ...
140,224
Runs cut3d with a Cut3DInput Args: cut3d_input: a Cut3DInput object. workdir: directory where cut3d is executed. Returns: (string) absolute path to the standard output of the cut3d execution. (string) absolute path to the output filepath. None if output ...
def cut3d(self, cut3d_input, workdir): self.stdin_fname, self.stdout_fname, self.stderr_fname = \ map(os.path.join, 3 * [os.path.abspath(workdir)], ["cut3d.stdin", "cut3d.stdout", "cut3d.stderr"]) cut3d_input.write(self.stdin_fname) retcode = self._execute(workdir, with_mp...
140,225
Remove duplicate structures based on the structure matcher and symmetry (if symprec is given). Args: structure_matcher: Provides a structure matcher to be used for structure comparison. symprec: The precision in the symmetry finder algorithm if None ( ...
def __init__(self, structure_matcher=StructureMatcher( comparator=ElementComparator()), symprec=None): self.symprec = symprec self.structure_list = defaultdict(list) if isinstance(structure_matcher, dict): self.structure_matcher = StructureMatcher.from_dict(...
140,234
Calculates the BV sum of a site. Args: site: The site nn_list: List of nearest neighbors in the format [(nn_site, dist), ...]. scale_factor: A scale factor to be applied. This is useful for scaling distance, esp in the case of calculation-rela...
def calculate_bv_sum(site, nn_list, scale_factor=1.0): el1 = Element(site.specie.symbol) bvsum = 0 for (nn, dist) in nn_list: el2 = Element(nn.specie.symbol) if (el1 in ELECTRONEG or el2 in ELECTRONEG) and el1 != el2: r1 = BV_PARAMS[el1]["r"] r2 = BV_PARAMS[el2][...
140,256
Calculates the BV sum of a site for unordered structures. Args: site: The site nn_list: List of nearest neighbors in the format [(nn_site, dist), ...]. scale_factor: A scale factor to be applied. This is useful for scaling distance, esp in the...
def calculate_bv_sum_unordered(site, nn_list, scale_factor=1): # If the site "site" has N partial occupations as : f_{site}_0, # f_{site}_1, ... f_{site}_N of elements # X_{site}_0, X_{site}_1, ... X_{site}_N, and each neighbors nn_i in nn # has N_{nn_i} partial occupations as : # f_{nn_i}_0, f...
140,257
Add oxidation states to a structure by fractional site. Args: oxidation_states (list): List of list of oxidation states for each site fraction for each site. E.g., [[2, 4], [3], [-2], [-2], [-2]]
def add_oxidation_state_by_site_fraction(structure, oxidation_states): try: for i, site in enumerate(structure): new_sp = collections.defaultdict(float) for j, (el, occu) in enumerate(get_z_ordered_elmap(site .species)): ...
140,258
Get an oxidation state decorated structure. This currently works only for ordered structures only. Args: structure: Structure to analyze Returns: A modified structure that is oxidation state decorated. Raises: ValueError if the valences cannot be de...
def get_oxi_state_decorated_structure(self, structure): s = structure.copy() if s.is_ordered: valences = self.get_valences(s) s.add_oxidation_state_by_site(valences) else: valences = self.get_valences(s) s = add_oxidation_state_by_site_fra...
140,262
Concatenate another trajectory Args: trajectory (Trajectory): Trajectory to add
def extend(self, trajectory): if self.time_step != trajectory.time_step: raise ValueError('Trajectory not extended: Time steps of trajectories is incompatible') if len(self.species) != len(trajectory.species) and self.species != trajectory.species: raise ValueError('Tra...
140,266
Gets a subset of the trajectory if a slice is given, if an int is given, return a structure Args: frames (int, slice): int or slice of trajectory to return Return: (Trajectory, Structure) Subset of trajectory
def __getitem__(self, frames): if isinstance(frames, int) and frames < self.frac_coords.shape[0]: lattice = self.lattice if self.constant_lattice else self.lattice[frames] site_properties = self.site_properties[frames] if self.site_properties else None return Structu...
140,267
Convenience constructor to obtain trajectory from a list of structures. Note: Assumes no atoms removed during simulation Args: structures (list): list of pymatgen Structure objects. constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD ...
def from_structures(cls, structures, constant_lattice=True, **kwargs): frac_coords = [structure.frac_coords for structure in structures] if constant_lattice: lattice = structures[0].lattice.matrix else: lattice = [structure.lattice.matrix for structure in structu...
140,269
Convenience constructor to obtain trajectory from XDATCAR or vasprun.xml file Args: filename (str): The filename to read from. constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD simulation. True results in Returns: ...
def from_file(cls, filename, constant_lattice=True, **kwargs): # TODO: Support other filetypes fname = os.path.basename(filename) if fnmatch(fname, "*XDATCAR*"): structures = Xdatcar(filename).structures elif fnmatch(fname, "vasprun*.xml*"): structures =...
140,270
Return a new istance of the appropriate subclass. Args: qtype: String specifying the Resource manager type. queue_id: Job identifier. qname: Name of the queue (optional).
def from_qtype_and_id(qtype, queue_id, qname=None): for cls in all_subclasses(QueueJob): if cls.QTYPE == qtype: break else: logger.critical("Cannot find QueueJob subclass registered for qtype %s" % qtype) cls = QueueJob return cls(queue_id, qname=qna...
140,282
Create a new InsertionElectrode. Args: entries: A list of ComputedStructureEntries (or subclasses) representing the different topotactic states of the battery, e.g. TiO2 and LiTiO2. working_ion_entry: A single ComputedEntry or PDEntry repr...
def __init__(self, entries, working_ion_entry): self._entries = entries self._working_ion = working_ion_entry.composition.elements[0] self._working_ion_entry = working_ion_entry # Prepare to make phase diagram: determine elements and set their energy # to be very high ...
140,292
Get the stable entries. Args: charge_to_discharge: order from most charge to most discharged state? Default to True. Returns: A list of stable entries in the electrode, ordered by amount of the working ion.
def get_stable_entries(self, charge_to_discharge=True): list_copy = list(self._stable_entries) return list_copy if charge_to_discharge else list_copy.reverse()
140,293
Returns the unstable entries for the electrode. Args: charge_to_discharge: Order from most charge to most discharged state? Defaults to True. Returns: A list of unstable entries in the electrode, ordered by amount of the working ion.
def get_unstable_entries(self, charge_to_discharge=True): list_copy = list(self._unstable_entries) return list_copy if charge_to_discharge else list_copy.reverse()
140,294
Return all entries input for the electrode. Args: charge_to_discharge: order from most charge to most discharged state? Defaults to True. Returns: A list of all entries in the electrode (both stable and unstable), ordered by amount of...
def get_all_entries(self, charge_to_discharge=True): all_entries = list(self.get_stable_entries()) all_entries.extend(self.get_unstable_entries()) # sort all entries by amount of working ion ASC fsrt = lambda e: e.composition.get_atomic_fraction(self.working_ion) all_ent...
140,295
The maximum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum decomposition energy of all compounds along the insertion path (a subset of ...
def get_max_instability(self, min_voltage=None, max_voltage=None): data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None...
140,296
The minimum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum decomposition energy of all compounds along the insertion path (a subset of ...
def get_min_instability(self, min_voltage=None, max_voltage=None): data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.decomp_e_charge is not None: data.append(pair.decomp_e_charge) if pair.decomp_e_discharge is not None...
140,297
Maximum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Maximum critical oxygen chemical of all compounds along the insertion path (a subset of the path...
def get_max_muO2(self, min_voltage=None, max_voltage=None): data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None: data.extend([d['chempot'] for d in pair.muO2_discharge]) if pair.muO2_charge is ...
140,298
Minimum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage for a given step max_voltage: The maximum allowable voltage allowable for a given step Returns: Minimum critical oxygen chemical of all compounds ...
def get_min_muO2(self, min_voltage=None, max_voltage=None): data = [] for pair in self._select_in_voltage_range(min_voltage, max_voltage): if pair.muO2_discharge is not None: data.extend([d['chempot'] for d in pair.muO2_discharge]) if pair.muO2_charge is ...
140,299
Generate a summary dict. Args: print_subelectrodes: Also print data on all the possible subelectrodes. Returns: A summary of this electrode"s properties in dict format.
def as_dict_summary(self, print_subelectrodes=True): chg_comp = self.fully_charged_entry.composition dischg_comp = self.fully_discharged_entry.composition ion = self.working_ion d = {"average_voltage": self.get_average_voltage(), "max_voltage": self.max_voltage, ...
140,301
Given coords and a site, find closet site to coords. Args: coords (3x1 array): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cell Returns: Closest site and distance.
def get_nearest_site(self, coords, site, r=None): index = self.index(site) if r is None: r = np.linalg.norm(np.sum(self.lattice.matrix, axis=0)) ns = self.get_sites_in_sphere(coords, r, include_index=True) # Get sites with identical index to site ns = [n for ...
140,310
Process a single entry with the chosen Corrections. Args: entry: A ComputedEntry object. Returns: An adjusted entry if entry is compatible, otherwise None is returned.
def process_entry(self, entry): try: corrections = self.get_corrections_dict(entry) except CompatibilityError: return None entry.correction = sum(corrections.values()) return entry
140,328
Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value})
def get_corrections_dict(self, entry): corrections = {} for c in self.corrections: val = c.get_correction(entry) if val != 0: corrections[str(c)] = val return corrections
140,329
Prints an explanation of the corrections that are being applied for a given compatibility scheme. Inspired by the "explain" methods in many database methodologies. Args: entry: A ComputedEntry.
def explain(self, entry): d = self.get_explanation_dict(entry) print("The uncorrected value of the energy of %s is %f eV" % (entry.composition, d["uncorrected_energy"])) print("The following corrections / screening are applied for %s:\n" % d["compatibility"])...
140,331
Reads a string representation to a Cssr object. Args: string (str): A string representation of a CSSR. Returns: Cssr object.
def from_string(string): lines = string.split("\n") toks = lines[0].split() lengths = [float(i) for i in toks] toks = lines[1].split() angles = [float(i) for i in toks[0:3]] latt = Lattice.from_lengths_and_angles(lengths, angles) sp = [] coords = ...
140,334
Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object
def add_dos(self, label, dos): densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities self._doses[label] = {'frequencies': dos.frequencies, 'densities': densities}
140,337
Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys.
def add_dos_dict(self, dos_dict, key_sort_func=None): if key_sort_func: keys = sorted(dos_dict.keys(), key=key_sort_func) else: keys = dos_dict.keys() for label in keys: self.add_dos(label, dos_dict[label])
140,338
Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def get_plot(self, xlim=None, ylim=None, units="thz"): u = freq_units(units) ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) import palettable colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors y = None alldensities = [] ...
140,339
Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def show(self, xlim=None, ylim=None, units="thz"): plt = self.get_plot(xlim, ylim, units=units) plt.show()
140,340
Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def get_plot(self, ylim=None, units="thz"): u = freq_units(units) plt = pretty_plot(12, 8) band_linewidth = 1 data = self.bs_plot_data() for d in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][d],...
140,344
Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1.
def save_plot(self, filename, img_format="eps", ylim=None, units="thz"): plt = self.get_plot(ylim=ylim, units=units) plt.savefig(filename, format=img_format) plt.close()
140,345
plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter Args: another PhononBSPl...
def plot_compare(self, other_plotter): data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() if len(data_orig['distances']) != len(data['distances']): raise ValueError('The two objects are not compatible.') plt = self.get_plot() band_linewidt...
140,347
Plots the constant volume specific heat C_v in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. ...
def plot_cv(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) if self.structure: ylabel = r"$C_v$ (J/K/mol)" else: ylabel = r"$C_v$ (J/K/mol-c)" fig = self._plot_thermo(self.dos.cv, temperatures, ylabel=ylabel,...
140,351
Plots the vibrational entrpy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. Returns: ...
def plot_entropy(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) if self.structure: ylabel = r"$S$ (J/K/mol)" else: ylabel = r"$S$ (J/K/mol-c)" fig = self._plot_thermo(self.dos.entropy, temperatures, ylabel=y...
140,352
Plots the vibrational internal energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. R...
def plot_internal_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) if self.structure: ylabel = r"$\Delta E$ (kJ/mol)" else: ylabel = r"$\Delta E$ (kJ/mol-c)" fig = self._plot_thermo(self.dos.internal_en...
140,353
Plots the vibrational contribution to the Helmoltz free energy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib f...
def plot_helmholtz_free_energy(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) if self.structure: ylabel = r"$\Delta F$ (kJ/mol)" else: ylabel = r"$\Delta F$ (kJ/mol-c)" fig = self._plot_thermo(self.dos.helmh...
140,354
Plots all the thermodynamic properties in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. ...
def plot_thermodynamic_properties(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) mol = "" if self.structure else "-c" fig = self._plot_thermo(self.dos.cv, temperatures, ylabel="Thermodynamic properties", ylim=ylim, ...
140,355
Load a PWInput object from a dictionary. Args: pwinput_dict (dict): dictionary with PWInput data Returns: PWInput object
def from_dict(cls, pwinput_dict): pwinput = cls(structure=Structure.from_dict(pwinput_dict['structure']), pseudo=pwinput_dict['pseudo'], control=pwinput_dict['sections']['control'], system=pwinput_dict['sections']['system'], ...
140,359
Write the PWSCF input file. Args: filename (str): The string filename to output to.
def write_file(self, filename): with open(filename, "w") as f: f.write(self.__str__())
140,360
Reads an PWInput object from a string. Args: string (str): PWInput string Returns: PWInput object
def from_string(string): lines = list(clean_lines(string.splitlines())) def input_mode(line): if line[0] == "&": return ("sections", line[1:].lower()) elif "ATOMIC_SPECIES" in line: return ("pseudo", ) elif "K_POINTS" in line:...
140,361
Static helper method to convert PWINPUT parameters to proper type, e.g., integers, floats, etc. Args: key: PWINPUT parameter key val: Actual value of PWINPUT parameter.
def proc_val(key, val): float_keys = ('etot_conv_thr','forc_conv_thr','conv_thr','Hubbard_U','Hubbard_J0','defauss', 'starting_magnetization',) int_keys = ('nstep','iprint','nberrycyc','gdir','nppstr','ibrav','nat','ntyp','nbnd','nr1', 'nr2','nr3','nr1...
140,362
returns the number of jobs in the queue, probably using subprocess or shutil to call a command like 'qstat'. returns None when the number of jobs cannot be determined. Args: username: (str) the username of the jobs to count (default is to autodetect)
def get_njobs_in_queue(self, username=None): if username is None: username = getpass.getuser() njobs, process = self._get_njobs_in_queue(username=username) if process is not None and process.returncode != 0: # there's a problem talking to squeue server? err_msg ...
140,394
Plot pie charts of the different timers. Args: key: Keyword used to extract data from timers. minfract: Don't show sections whose relative weight is less that minfract. Returns: `matplotlib` figure
def plot_pie(self, key="wall_time", minfract=0.05, **kwargs): timers = self.timers() n = len(timers) # Make square figures and axes import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.gcf() gspec = GridSpec(n, 1) fo...
140,430
Plot stacked histogram of the different timers. Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. mmax: Maximum nuber of sections to show. Other entries are grouped together in the `others...
def plot_stacked_hist(self, key="wall_time", nmax=5, ax=None, **kwargs): ax, fig, plt = get_ax_fig_plt(ax=ax) mpi_rank = "0" timers = self.timers(mpi_rank=mpi_rank) n = len(timers) names, values = [], [] rest = np.zeros(n) for idx, sname in enumerate(s...
140,431
Plot pie chart for this timer. Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib...
def pie(self, key="wall_time", minfract=0.05, ax=None, **kwargs): ax, fig, plt = get_ax_fig_plt(ax=ax) # Set aspect ratio to be equal so that pie is drawn as a circle. ax.axis("equal") # Don't show section whose value is less that minfract labels, vals = self.names_and_v...
140,451
Returns ASE Atoms object from pymatgen structure. Args: structure: pymatgen.core.structure.Structure **kwargs: other keyword args to pass into the ASE Atoms constructor Returns: ASE Atoms object
def get_atoms(structure, **kwargs): if not structure.is_ordered: raise ValueError("ASE Atoms only supports ordered structures") symbols = [str(site.specie.symbol) for site in structure] positions = [site.coords for site in structure] cell = structure.lattice.matrix ...
140,453
Returns pymatgen structure from ASE Atoms. Args: atoms: ASE Atoms object cls: The Structure class to instantiate (defaults to pymatgen structure) Returns: Equivalent pymatgen.core.structure.Structure
def get_structure(atoms, cls=None): symbols = atoms.get_chemical_symbols() positions = atoms.get_positions() lattice = atoms.get_cell() cls = Structure if cls is None else cls return cls(lattice, symbols, positions, coords_are_cartesian=True)
140,454
Returns the densities, but with a Gaussian smearing of std dev sigma applied. Args: sigma: Std dev of Gaussian smearing function. Returns: Gaussian-smeared densities.
def get_smeared_densities(self, sigma): from scipy.ndimage.filters import gaussian_filter1d diff = [self.frequencies[i + 1] - self.frequencies[i] for i in range(len(self.frequencies) - 1)] avgdiff = sum(diff) / len(diff) smeared_dens = gaussian_filter1d(self.de...
140,456
Adds two DOS together. Checks that frequency scales are the same. Otherwise, a ValueError is thrown. Args: other: Another DOS object. Returns: Sum of the two DOSs.
def __add__(self, other): if not all(np.equal(self.frequencies, other.frequencies)): raise ValueError("Frequencies of both DOS are not compatible!") densities = self.densities + other.densities return PhononDos(self.frequencies, densities)
140,457
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. ...
def sort_dict(d, key=None, reverse=False): kv_items = [kv for kv in d.items()] # Sort kv_items according to key. if key is None: kv_items.sort(key=lambda t: t[1], reverse=reverse) else: kv_items.sort(key=key, reverse=reverse) # Build ordered dict. return collections.Ordere...
140,470
Create a Stress object. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays. Args: stress_matrix (3x3 array-like): the 3x3 array-like representing the stress
def __new__(cls, stress_matrix): obj = super().__new__(cls, stress_matrix) return obj.view(cls)
140,507
calculates the first Piola-Kirchoff stress Args: def_grad (3x3 array-like): deformation gradient tensor
def piola_kirchoff_1(self, def_grad): if not self.is_symmetric: raise ValueError("The stress tensor is not symmetric, \ PK stress is based on a symmetric stress tensor.") def_grad = SquareTensor(def_grad) return def_grad.det*np.dot(self, def_grad...
140,509
Pass in a structure for analysis Arguments: struc_oxid - a Structure object; oxidation states *must* be assigned for this structure; disordered structures should be OK cation - a String symbol or Element for the cation. It must be positively charged, but can be 1+/2+/3+ etc.
def __init__(self, struc_oxid, cation='Li'): for site in struc_oxid: if not hasattr(site.specie, 'oxi_state'): raise ValueError('BatteryAnalyzer requires oxidation states assigned to structure!') self.struc_oxid = struc_oxid self.comp = self.struc_oxid.compo...
140,514
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 ...
def get_max_capgrav(self, remove=True, insert=True): weight = self.comp.weight if insert: weight += self.max_cation_insertion * self.cation.atomic_mass return self._get_max_cap_ah(remove, insert) / (weight / 1000)
140,518
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...
def get_max_capvol(self, remove=True, insert=True, volume=None): vol = volume if volume else self.struc_oxid.volume return self._get_max_cap_ah(remove, insert) * 1000 * 1E24 / (vol * const.N_A)
140,519
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...
def _get_int_removals_helper(self, spec_amts_oxi, oxid_el, oxid_els, numa): # If Mn is the oxid_el, we have a mixture of Mn2+, Mn3+, determine the minimum oxidation state for Mn #this is the state we want to oxidize! oxid_old = min([spec.oxi_state for spec in spec_amts_oxi if spec.symb...
140,521
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): if strict and set(composition.keys()) > set(self.keys()): s = set(composition.keys()) - set(self.keys()) raise ValueError("Potentials not specified for {}".format(s)) return sum(self.get(k, 0) * v for k, v in composition.it...
140,526
Create an PiezoTensor object. The constructor throws an error if the shape of the input_matrix argument is not 3x3x3, i. e. in true tensor notation. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays. Args:...
def __new__(cls, input_array, tol=1e-3): obj = super().__new__(cls, input_array, check_rank=3) if not (obj - np.transpose(obj, (0, 2, 1)) < tol).all(): warnings.warn("Input piezo tensor does " "not satisfy standard symmetries") return obj.view(cls)
140,527
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...
def obtain_all_bond_lengths(sp1, sp2, default_bl=None): if isinstance(sp1, Element): sp1 = sp1.symbol if isinstance(sp2, Element): sp2 = sp2.symbol syms = tuple(sorted([sp1, sp2])) if syms in bond_lengths: return bond_lengths[syms].copy() elif default_bl is not None: ...
140,573