INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
This function should be called when the entire `Flow` has been built. It tries to reduce the pressure on the hard disk by using Abinit smart-io capabilities for those files that are not needed by other nodes. Smart-io means that big files (e.g. WFK) are written only if the calculation is...
def use_smartio(self): """ This function should be called when the entire `Flow` has been built. It tries to reduce the pressure on the hard disk by using Abinit smart-io capabilities for those files that are not needed by other nodes. Smart-io means that big files (e.g. WFK) are...
Writes to the given stream the ASCII representation of the dependency tree.
def show_dependencies(self, stream=sys.stdout): """Writes to the given stream the ASCII representation of the dependency tree.""" def child_iter(node): return [d.node for d in node.deps] def text_str(node): return colored(str(node), color=node.status.color_opts["color"])...
This method is called when the flow is completed. Return 0 if success
def finalize(self): """ This method is called when the flow is completed. Return 0 if success """ if self.finalized: self.history.warning("Calling finalize on an already finalized flow.") return 1 self.history.info("Calling flow.finalize.") ...
Enable the garbage collector that will remove the big output files that are not needed. Args: exts: string or list with the Abinit file extensions to be removed. A default is provided if exts is None policy: Either `flow` or `task`. If policy is set to 'task', we remove ...
def set_garbage_collector(self, exts=None, policy="task"): """ Enable the garbage collector that will remove the big output files that are not needed. Args: exts: string or list with the Abinit file extensions to be removed. A default is provided if exts is None ...
Connect the signals within the `Flow`. The `Flow` is responsible for catching the important signals raised from its works.
def connect_signals(self): """ Connect the signals within the `Flow`. The `Flow` is responsible for catching the important signals raised from its works. """ # Connect the signals inside each Work. for work in self: work.connect_signals() # Observe th...
Disable the signals within the `Flow`.
def disconnect_signals(self): """Disable the signals within the `Flow`.""" # Disconnect the signals inside each Work. for work in self: work.disconnect_signals() # Disable callbacks. for cbk in self._callbacks: cbk.disable()
When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks A spectator can still operate on the flow but the new status of the flow won't be saved in the pickle file. Usually the flow is in spectator mode when we are already running it via the scheduler or...
def set_spectator_mode(self, mode=True): """ When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks A spectator can still operate on the flow but the new status of the flow won't be saved in the pickle file. Usually the flow is in spectator mod...
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): """ 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 lau...
Use :class:`PyLauncher` to submits one task. kwargs contains the options passed to the launcher. Return: number of tasks submitted.
def single_shot(self, check_status=True, **kwargs): """ Use :class:`PyLauncher` to submits one task. kwargs contains the options passed to the launcher. Return: number of tasks submitted. """ self.check_pid_file() self.set_spectator_mode(False) ...
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): """ 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: "day...
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): """ 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 :c...
Lightweight tarball file. Mainly used for debugging. Return the name of the tarball file.
def make_light_tarfile(self, name=None): """Lightweight tarball file. Mainly used for debugging. Return the name of the tarball file.""" name = os.path.basename(self.workdir) + "-light.tar.gz" if name is None else name return self.make_tarfile(name=name, exclude_dirs=["outdata", "indata", "tmpda...
Create a tarball file. Args: name: Name of the tarball file. Set to os.path.basename(`flow.workdir`) + "tar.gz"` if name is None. max_filesize (int or string with unit): a file is included in the tar file if its size <= max_filesize Can be specified in bytes e.g. `max_fi...
def make_tarfile(self, name=None, max_filesize=None, exclude_exts=None, exclude_dirs=None, verbose=0, **kwargs): """ Create a tarball file. Args: name: Name of the tarball file. Set to os.path.basename(`flow.workdir`) + "tar.gz"` if name is None. max_filesize (int or str...
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): """ Generate flow graph in the DOT language. Args: engine: Layout command used. ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_attr: Mapping of (at...
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): """ 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 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...
def plot_networkx(self, mode="network", with_edge_labels=False, ax=None, arrows=False, node_size="num_cores", node_label="name_class", layout_type="spring", **kwargs): """ Use networkx to draw the flow with the connections among the nodes and the status of the tasks. ...
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 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. """ scr_input = cbk.data["...
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...
def from_scf_input(cls, workdir, scf_input, ph_ngqpt, with_becs=True, manager=None, allocate=True): """ Create a `PhononFlow` for phonon calculations from an `AbinitInput` defining a ground-state run. Args: workdir: Working directory of the flow. scf_input: :class:`Abini...
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:`DdbFile` object, None if file could not be found or file is not readable. """ ddb_path = self.outdir.has_abiext("DDB") if not ddb_path: if...
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 produced in the outdir of the work. out_ddb =...
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...
def from_scf_input(cls, workdir, scf_input, manager=None, allocate=True): """ 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:...
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...
def from_global_moment_and_saxis(cls, global_moment, saxis): """ 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 m...
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...
def get_moment(self, saxis=(0, 0, 1)): """ 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 arr...
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...
def get_00t_magmom_with_xyz_saxis(self): """ 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 ...
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) ...
def have_consistent_saxis(magmoms): """ 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 w...
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...
def get_consistent_set_and_saxis(magmoms, saxis=None): """ 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 specif...
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...
def get_suggested_saxis(magmoms): """ 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 ...
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. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :return: bool """ magmoms = [Magmom(magmom) for magmom in magmoms] if not Magmom....
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, lattice): """ 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: Lat...
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 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 """ # get ma...
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 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 f...
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): """ 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*/*CON...
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=MontyEncoder)) status['count'] += 1 count = status['count'] t...
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(rootpath): valid_paths.extend(self._drone.get_valid_p...
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(self._drone.get_valid_paths((parent, subdirs, ...
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 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. """ ...
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 overlaps in metric: maxval = 0 for i in reversed(ran...
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...
def get_nac_frequencies_along_dir(self, direction): """ 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 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): """ 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 l...
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...
def asr_breaking(self, tol_eigendisplacements=1e-5): """ 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 correspon...
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): """ 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 ...
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): """ 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 wh...
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 f: phononwebsite_json = json.dump(self.as_phononwebsite(),f)
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 d["lattice"] = self.structure.lattice._matrix.tolist() #define atoms atom_pos_c...
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 order = np.zeros([nqpoints,nphonons],dtype=int) order[0] = np....
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...
def batch_write_vasp_input(transformed_structures, vasp_input_set=MPRelaxSet, output_dir=".", create_directory=True, subfolder=None, include_cif=False, **kwargs): """ Batch write vasp input for a sequence of transformed structures ...
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...
def append_transformation(self, transformation, extend_collection=False, clear_redo=True): """ Appends a transformation to all TransformedStructures. Args: transformation: Transformation to append extend_collection: Whether to use more than ...
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...
def _apply_transformation(inputs): """ 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 th...
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 are stored in the as_dict() output. Args: key: The key for the parameter. value: The value for the parameter. """ for x in self.transformed_structures...
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. Args: structure_filter: StructureFilter to apply. """ def test_transformed_structure(ts): return structure_filter.tes...
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): """ 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...
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 ...
def from_structures(structures, transformations=None, extend_collection=0): """ Alternative constructor from structures rather than TransformedStructures. Args: structures: Sequence of structures transformations: New transformations to be applied to all ...
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): """ Generates a TransformedStructureCollection from a cif, possibly containing multiple structures. Args: filenames: List of strings of the cif files ...
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): """ Convenient constructor to generates a POSCAR transmuter from a list of POSCAR filenames. Args: poscar_filenames: List of POSCAR filenames transformatio...
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 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. """ ...
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 [AttrDict(**pert) for pert in d["irred_perts"]]
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 = _magic_parser(stream, magic=cls.MAGIC) if fields: fields.pop("iter") return cls(fields) ...
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. Args: fontsize: Legend fontsize. """ ax_list = None for i, (label, cycle) in enumerate(self.items()): ...
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".join(lines)
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 None: break cycles.append(scf_cycle) retur...
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: d = cycle.last_iteration for k, v in d.items(): if k in history: ...
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. Args: ax_list: List of axes. If None a new figure is produced. Returns: `matplotlib` figure """ for i, cycle in enumerate(self.cycles): ...
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): """ 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 ...
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 ...
def seek(self, offset, whence=0): """ 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, p...
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 explicitely with the sentinel '...' """ in_doc, lines, doc_tag = None, [], None for i, line in enumerate(self.stream): self.line...
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) if doc.tag == doc_tag: return doc except StopIte...
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) except StopIteration: break ...
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 (we used the tag just to locate the document). """ if self.tag is not None: return self.text.replace(self.tag, "") else: ...
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 workdir. Some executables fail if we try to launch them with mpirun. Use with_mpirun=False to run the binary without it. """ qadapter = self.manager.qadapter...
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` """ # We work with absolute paths. files_to_merge = [os.path.abspath(s) for s in list_strings(f...
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): """ 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 fi...
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(s) for s in list_strings(ddb_files)] if not os.path.isabs(out_ddb...
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 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. """...
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): """ 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. (st...
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...
def from_path(cls, path, suffix=''): """ 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,...
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 interpreted as e.g. degree of pi-bonding in organic molecules. Consult literature for more information. :return: ''' eig = np.linalg.eig(self.field_hessian) eig....
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_graph(self, edge_weight="bond_length", edge_weight_units="Å"): """ 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 support...
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, unique_idx, frac_coords): """ 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: fractiona...
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...
def _add_edge(self, idx, from_idx, from_lvec, to_idx, to_lvec): """ 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, ...
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): """ 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 fo...
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): """ 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...
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): """ 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]...
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...
def get_valences(self, structure): """ 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 ...
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): """ 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 dec...
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 = self.base_positions + cumulative_displacements self...
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.subtract(self.frac_coords, np.roll(self.frac_coords, 1, axis=0)) displacements[0] ...
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: raise ValueError('Trajectory not extended: Time steps of trajectories is incompatible') ...
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): """ 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. consta...
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): """ 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, s...
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): attribute = np.concatenate((attr_1, attr_2), axis=0) attribut...
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 ...
def get_correction(self, entry): """ 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 N...
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 are (in angstroms)" + str(lattice.abc)) ...