text
stringlengths
81
112k
Use networkx to draw the flow with the connections among the nodes and the status of the tasks. Args: mode: `networkx` to show connections, `status` to group tasks by status. with_edge_labels: True to draw edge labels. ax: matplotlib :class:`Axes` or None if a new fi...
This callback is executed by the flow when bands_work.nscf_task reaches S_OK. It computes the list of q-points for the W(q,G,G'), creates nqpt tasks in the second work (QptdmWork), and connect the signals. def cbk_qptdm_workflow(self, cbk): """ This callback is executed by the flow whe...
True if we can execute the callback. def can_execute(self): """True if we can execute the callback.""" return not self._disabled and all(dep.status == dep.node.S_OK for dep in self.deps)
Create a `PhononFlow` for phonon calculations from an `AbinitInput` defining a ground-state run. Args: workdir: Working directory of the flow. scf_input: :class:`AbinitInput` object with the parameters for the GS-SCF run. ph_ngqpt: q-mesh for phonons. Must be a sub-mesh of t...
Open the DDB file located in the output directory of the flow. Return: :class:`DdbFile` object, None if file could not be found or file is not readable. def open_final_ddb(self): """ Open the DDB file located in the output directory of the flow. Return: :class:...
This method is called when the flow is completed. def finalize(self): """This method is called when the flow is completed.""" # Merge all the out_DDB files found in work.outdir. ddb_files = list(filter(None, [work.outdir.has_abiext("DDB") for work in self])) # Final DDB file will be pr...
Create a `NonlinearFlow` for second order susceptibility calculations from an `AbinitInput` defining a ground-state run. Args: workdir: Working directory of the flow. scf_input: :class:`AbinitInput` object with the parameters for the GS-SCF run. manager: :class:`Task...
Convenience method to initialize Magmom from a given global magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and provided saxis. Method is useful if you do not know the components of your magnetic moment in frame of your desired saxis. :param global_mom...
Get magnetic moment relative to a given spin quantization axis. If no axis is provided, moment will be given relative to the Magmom's internal spin quantization axis, i.e. equivalent to Magmom.moment :param axis: (list/numpy array) spin quantization axis :return: np.ndarray of l...
For internal implementation reasons, in non-collinear calculations VASP prefers: MAGMOM = 0 0 total_magnetic_moment SAXIS = x y z to an equivalent: MAGMOM = x y z SAXIS = 0 0 1 This method returns a Magmom object with magnetic moment [0, 0, t], where t...
This method checks that all Magmom objects in a list have a consistent spin quantization axis. To write MAGMOM tags to a VASP INCAR, a global SAXIS value for all magmoms has to be used. If saxis are inconsistent, can create consistent set with: Magmom.get_consistent_set(magmoms) ...
Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specific global spin axis :return: (list of Magmoms, global spin axis) tu...
This method returns a suggested spin axis for a set of magmoms, taking the largest magnetic moment as the reference. For calculations with collinear spins, this would give a sensible saxis for a ncl calculation. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :retu...
Method checks to see if a set of magnetic moments are collinear with each other. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :return: bool def are_collinear(magmoms): """ Method checks to see if a set of magnetic moments are collinear with each other. ...
Obtaining a Magmom object from a magnetic moment provided relative to crystal axes. Used for obtaining moments from magCIF file. :param magmom: list of floats specifying vector magmom :param lattice: Lattice :return: Magmom def from_moment_relative_to_crystal_axes(cls, moment, ...
If scalar magmoms, moments will be given arbitrarily along z. Used for writing moments to magCIF file. :param magmom: Magmom :param lattice: Lattice :return: vector as list of floats def get_moment_relative_to_crystal_axes(self, lattice): """ If scalar magmoms, moments ...
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): ...
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) *...
Internal helper method for BorgQueen to process assimilation def order_assimilation(args): """ Internal helper method for BorgQueen to process assimilation """ (path, drone, data, status) = args newdata = drone.assimilate(path) if newdata: data.append(json.dumps(newdata, cls=MontyEncode...
Assimilate the entire subdirectory structure in rootpath. def parallel_assimilate(self, rootpath): """ Assimilate the entire subdirectory structure in rootpath. """ logger.info('Scanning for valid paths...') valid_paths = [] for (parent, subdirs, files) in os.walk(rootpa...
Assimilate the entire subdirectory structure in rootpath serially. def serial_assimilate(self, rootpath): """ Assimilate the entire subdirectory structure in rootpath serially. """ valid_paths = [] for (parent, subdirs, files) in os.walk(rootpath): valid_paths.extend...
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): """ Save the assi...
Load assimilated data from a file def load_data(self, filename): """ Load assimilated data from a file """ with zopen(filename, "rt") as f: self._data = json.load(f, cls=MontyDecoder)
Calculate the eigenvectors from the atomic displacements def eigenvectors_from_displacements(disp,masses): """ Calculate the eigenvectors from the atomic displacements """ nphonons,natoms,ndirections = disp.shape sqrt_masses = np.sqrt(masses) return np.einsum("nax,a->nax",disp,sqrt_masses)
A function to order the phonon eigenvectors taken from phonopy def estimate_band_connection(prev_eigvecs, eigvecs, prev_band_order): """ A function to order the phonon eigenvectors taken from phonopy """ metric = np.abs(np.dot(prev_eigvecs.conjugate().T, eigvecs)) connection_order = [] for over...
Returns the point where the minimum frequency is reached and its value def min_freq(self): """ Returns the point where the minimum frequency is reached and its value """ i = np.unravel_index(np.argmin(self.bands), self.bands.shape) return self.qpoints[i[1]], self.bands[i]
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...
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...
Returns the breaking of the acoustic sum rule for the three acoustic modes, if Gamma is present. None otherwise. If eigendisplacements are available they are used to determine the acoustic modes: selects the bands corresponding to the eigendisplacements that represent to a translation w...
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...
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...
Write a json file for the phononwebsite: http://henriquemiranda.github.io/phononwebsite def write_phononwebsite(self,filename): """ Write a json file for the phononwebsite: http://henriquemiranda.github.io/phononwebsite """ import json with open(filename,'w') as ...
Return a dictionary with the phononwebsite format: http://henriquemiranda.github.io/phononwebsite def as_phononwebsite(self): """ Return a dictionary with the phononwebsite format: http://henriquemiranda.github.io/phononwebsite """ d = {} #define the lattice ...
Re-order the eigenvalues according to the similarity of the eigenvectors def band_reorder(self): """ Re-order the eigenvalues according to the similarity of the eigenvectors """ eiv = self.eigendisplacements eig = self.bands nphonons,nqpoints = self.bands.shape ...
Batch write vasp input for a sequence of transformed structures to output_dir, following the format output_dir/{group}/{formula}_{number}. Args: transformed_structures: Sequence of TransformedStructures. vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet to creates vasp input files...
Helper method for multiprocessing of apply_transformation. Must not be in the class so that it can be pickled. Args: inputs: Tuple containing the transformed structure, the transformation to be applied, a boolean indicating whether to extend the collection, and a boolean indicat...
Appends a transformation to all TransformedStructures. Args: transformation: Transformation to append extend_collection: Whether to use more than one output structure from one-to-many transformations. extend_collection can be a number, which determines th...
Applies a structure_filter to the list of TransformedStructures in the transmuter. Args: structure_filter: StructureFilter to apply. def apply_filter(self, structure_filter): """ Applies a structure_filter to the list of TransformedStructures in the transmuter. ...
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): """ Add parameters to the transmuter. Additional parameters...
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,...
Alternative constructor from structures rather than TransformedStructures. Args: structures: Sequence of structures transformations: New transformations to be applied to all structures extend_collection: Whether to use more than one output structure ...
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...
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...
Parse the section with the SCF cycle Returns: dict where the key are the name of columns and the values are list of numbers. Note if no section was found. .. warning:: The parser is very fragile and should be replaced by YAML. def _magic_parser(stream, magic): """ Parse the s...
Read the K-points from file. def yaml_read_kpoints(filename, doc_tag="!Kpoints"): """Read the K-points from file.""" with YamlTokenizer(filename) as r: doc = r.next_doc_with_tag(doc_tag) d = yaml.safe_load(doc.text_notag) return np.array(d["reduced_coordinates_of_qpoints"])
Read the list of irreducible perturbations from file. def yaml_read_irred_perts(filename, doc_tag="!IrredPerts"): """Read the list of irreducible perturbations from file.""" with YamlTokenizer(filename) as r: doc = r.next_doc_with_tag(doc_tag) d = yaml.safe_load(doc.text_notag) return ...
String representation. def to_string(self, verbose=0): """String representation.""" rows = [[it + 1] + list(map(str, (self[k][it] for k in self.keys()))) for it in range(self.num_iterations)] return tabulate(rows, headers=["Iter"] + list(self.keys()))
Read the first occurrence of ScfCycle from stream. Returns: None if no `ScfCycle` entry is found. def from_stream(cls, stream): """ Read the first occurrence of ScfCycle from stream. Returns: None if no `ScfCycle` entry is found. """ fields = _m...
Add new cycle to the plotter with label `label`. def add_label_cycle(self, label, cycle): """Add new cycle to the plotter with label `label`.""" self.labels.append(label) self.cycles.append(cycle)
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): """ Compare multiple cycels on a grid: one subplot per quantity, all cycles on the same subplot. ...
Produce slides show of the different cycles. One plot per cycle. def slideshow(self, **kwargs): """ Produce slides show of the different cycles. One plot per cycle. """ for label, cycle in self.items(): cycle.plot(title=label, tight_layout=True)
String representation. def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append for i, cycle in enumerate(self): app("") app("RELAXATION STEP: %d" % (i + 1)) app(cycle.to_string(verbose=verbose)) return "\n"....
Extract data from stream. Returns None if some error occurred. def from_stream(cls, stream): """ Extract data from stream. Returns None if some error occurred. """ cycles = [] while True: scf_cycle = GroundStateScfCycle.from_stream(stream) if scf_cycle is...
Ordered Dictionary of lists with the evolution of the data as function of the relaxation step. def history(self): """ Ordered Dictionary of lists with the evolution of the data as function of the relaxation step. """ history = OrderedDict() for cycle in self: ...
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): """ Uses matplotlib to plot the evolution of the structural relaxation...
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_...
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to ...
Returns the first YAML document in stream. .. warning:: Assume that the YAML document are closed explicitely with the sentinel '...' def next(self): """ Returns the first YAML document in stream. .. warning:: Assume that the YAML document are closed explicite...
Returns the next document with the specified tag. Empty string is no doc is found. def next_doc_with_tag(self, doc_tag): """ Returns the next document with the specified tag. Empty string is no doc is found. """ while True: try: doc = next(self) ...
Returns all the documents with the specified tag. def all_docs_with_tag(self, doc_tag): """ Returns all the documents with the specified tag. """ docs = [] while True: try: doc = self.next_doc_with(doc_tag) docs.append(doc) ...
Returns the YAML text without the tag. Useful if we don't have any constructor registered for the tag (we used the tag just to locate the document). def text_notag(self): """ Returns the YAML text without the tag. Useful if we don't have any constructor registered for the tag ...
Execute the executable in a subprocess inside workdir. Some executables fail if we try to launch them with mpirun. Use with_mpirun=False to run the binary without it. def _execute(self, workdir, with_mpirun=False, exec_args=None): """ Execute the executable in a subprocess inside workd...
Execute mrgscr inside directory `workdir` to merge `files_to_merge`. Produce new file with prefix `out_prefix` def merge_qpoints(self, workdir, files_to_merge, out_prefix): """ Execute mrgscr inside directory `workdir` to merge `files_to_merge`. Produce new file with prefix `out_prefix`...
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 -...
Merge DDB file, return the absolute path of the new database in workdir. def merge(self, workdir, ddb_files, out_ddb, description, delete_source_ddbs=True): """Merge DDB file, return the absolute path of the new database in workdir.""" # We work with absolute paths. ddb_files = [os.path.abspath...
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): """ Merge POT ...
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 ...
Convenience method to run critic2 analysis on a folder containing typical VASP output files. This method will: 1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped counterparts. 2. If AECCAR* files are present, constructs a temporary reference file as AECCAR0...
Most meaningful for bond critical points, can be physically interpreted as e.g. degree of pi-bonding in organic molecules. Consult literature for more information. :return: def ellipticity(self): ''' Most meaningful for bond critical points, can be physically int...
A StructureGraph object describing bonding information in the crystal. Lazily constructed. :param edge_weight: a value to store on the Graph edges, by default this is "bond_length" but other supported values are any of the attributes of CriticalPoint :return: def structure_grap...
Add information about a node describing a critical point. :param idx: unique index :param unique_idx: index of unique CriticalPoint, used to look up more information of point (field etc.) :param frac_coord: fractional co-ordinates of point :return: def _add_node(self, idx, uniq...
Add information about an edge linking two critical points. This actually describes two edges: from_idx ------ idx ------ to_idx However, in practice, from_idx and to_idx will typically be atom nuclei, with the center node (idx) referring to a bond critical point. Thus, it will...
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...
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...
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):...
Returns a list of valences for the structure. This currently works only for ordered structures only. Args: structure: Structure to analyze Returns: A list of valences for each site in the structure (for an ordered structure), e.g., [1, 1, -2] or a list of li...
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...
Converts fractional coordinates of trajectory into positions def to_positions(self): """ Converts fractional coordinates of trajectory into positions """ if self.coords_are_displacement: cumulative_displacements = np.cumsum(self.frac_coords, axis=0) positions = s...
Converts position coordinates of trajectory into displacements between consecutive frames def to_displacements(self): """ Converts position coordinates of trajectory into displacements between consecutive frames """ if not self.coords_are_displacement: displacements = np.sub...
Concatenate another trajectory Args: trajectory (Trajectory): Trajectory to add def extend(self, trajectory): """ Concatenate another trajectory Args: trajectory (Trajectory): Trajectory to add """ if self.time_step != trajectory.time_step: ...
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 ...
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: ...
Helper function to combine trajectory properties such as site_properties or lattice def _combine_attribute(attr_1, attr_2, len_1, len_2): """ Helper function to combine trajectory properties such as site_properties or lattice """ if isinstance(attr_1, list) or isinstance(attr_2, list): ...
Gets the Freysoldt correction for a defect entry Args: entry (DefectEntry): defect entry to compute Freysoldt correction on. Requires following parameters in the DefectEntry to exist: axis_grid (3 x NGX where NGX is the length of the NGX grid ...
Peform Electrostatic Freysoldt Correction def perform_es_corr(self, lattice, q, step=1e-4): """ Peform Electrostatic Freysoldt Correction """ logger.info("Running Freysoldt 2011 PC calculation (should be " "equivalent to sxdefectalign)") logger.debug("defect lattice constants ar...
For performing planar averaging potential alignment title is for name of plot, if you dont want a plot then leave it as None widthsample is the width (in Angstroms) of the region in between defects where the potential alignment correction is averaged def perform_pot_corr(self, ...
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt def plot(self, axis, title=None, saved=False): """ Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt """ x = self.m...
Gets the BandFilling correction for a defect entry def get_correction(self, entry): """ Gets the BandFilling correction for a defect entry """ eigenvalues = entry.parameters["eigenvalues"] kpoint_weights = entry.parameters["kpoint_weights"] potalign = entry.parameters["p...
This calculates the band filling correction based on excess of electrons/holes in CB/VB... Note that the total free holes and electrons may also be used for a "shallow donor/acceptor" correction with specified band shifts: +num_elec_cbm * Delta E_CBM (or -num_hole_vbm * Delta E_VBM) ...
Gets the BandEdge correction for a defect entry def get_correction(self, entry): """ Gets the BandEdge correction for a defect entry """ # TODO: add smarter defect level shifting based on defect level projection onto host bands hybrid_cbm = entry.parameters["hybrid_cbm"] ...
Return a :class:`JobStatus` instance from its string representation. def from_string(cls, s): """Return a :class:`JobStatus` instance from its string representation.""" for num, text in cls._STATUS_TABLE.items(): if text == s: return cls(num) else: #raise ValueError("Wro...
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): """ Return a new istance of the app...
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_dis...
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_unstabl...
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...
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 ...
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 ...
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...
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 ...
If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be ...