INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Dict representation of NEBAnalysis.
def as_dict(self): """ Dict representation of NEBAnalysis. Returns: JSON serializable dict representation. """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, 'r': jsanitize(self.r), 'en...
Build a: class: Flow for band structure calculations.
def bandstructure_flow(workdir, scf_input, nscf_input, dos_inputs=None, manager=None, flow_class=Flow, allocate=True): """ Build a :class:`Flow` for band structure calculations. Args: workdir: Working directory. scf_input: Input for the GS SCF run. nscf_input: Input for the NSCF run...
Build a: class: Flow for one - shot $G_0W_0$ calculations.
def g0w0_flow(workdir, scf_input, nscf_input, scr_input, sigma_inputs, manager=None, flow_class=Flow, allocate=True): """ Build a :class:`Flow` for one-shot $G_0W_0$ calculations. Args: workdir: Working directory. scf_input: Input for the GS SCF run. nscf_input: Input for the NSCF r...
Build a: class: PhononFlow for phonon calculations.
def phonon_flow(workdir, scf_input, ph_inputs, with_nscf=False, with_ddk=False, with_dde=False, manager=None, flow_class=PhononFlow, allocate=True): """ Build a :class:`PhononFlow` for phonon calculations. Args: workdir: Working directory. scf_input: Input for the GS SCF run...
Create a: class: Flow to perform convergence studies for phonon calculations.
def phonon_conv_flow(workdir, scf_input, qpoints, params, manager=None, allocate=True): """ Create a :class:`Flow` to perform convergence studies for phonon calculations. Args: workdir: Working directory of the flow. scf_input: :class:`AbinitInput` object defining a GS-SCF calculation. ...
Initialize an instance from a Work instance.
def from_node(cls, flow): """Initialize an instance from a Work instance.""" new = super().from_node(flow) # Will put all files found in outdir in GridFs d = {os.path.basename(f): f for f in flow.outdir.list_filepaths()} # Add the pickle file. d["pickle"] = flow.pickle_...
Construct a simple flow from a list of inputs. The flow contains a single Work with tasks whose class is given by task_class.
def from_inputs(cls, workdir, inputs, manager=None, pickle_protocol=-1, task_class=ScfTask, work_class=Work, remove=False): """ Construct a simple flow from a list of inputs. The flow contains a single Work with tasks whose class is given by task_class. .. warning::...
Convert obj into a Flow. Accepts filepath dict or Flow object.
def as_flow(cls, obj): """Convert obj into a Flow. Accepts filepath, dict, or Flow object.""" if isinstance(obj, cls): return obj if is_string(obj): return cls.pickle_load(obj) elif isinstance(obj, collections.Mapping): return cls.from_dict(obj) else: ...
Set the working directory. Cannot be set more than once unless chroot is True
def set_workdir(self, workdir, chroot=False): """ Set the working directory. Cannot be set more than once unless chroot is True """ if not chroot and hasattr(self, "workdir") and self.workdir != workdir: raise ValueError("self.workdir != workdir: %s, %s" % (self.workdir, wor...
Reload the flow from the pickle file. Used when we are monitoring the flow executed by the scheduler. In this case indeed the flow might have been changed by the scheduler and we have to reload the new flow in memory.
def reload(self): """ Reload the flow from the pickle file. Used when we are monitoring the flow executed by the scheduler. In this case, indeed, the flow might have been changed by the scheduler and we have to reload the new flow in memory. """ new = self.__class__.pickl...
Loads the object from a pickle file and performs initial setup.
def pickle_load(cls, filepath, spectator_mode=True, remove_lock=False): """ Loads the object from a pickle file and performs initial setup. Args: filepath: Filename or directory name. It filepath is a directory, we scan the directory tree starting from filepath and w...
Reconstruct the flow from a string.
def pickle_loads(cls, s): """Reconstruct the flow from a string.""" strio = StringIO() strio.write(s) strio.seek(0) flow = pmg_pickle_load(strio) return flow
This function checks if we are already running the: class: Flow with a: class: PyFlowScheduler. Raises: Flow. Error if the pid file of the scheduler exists.
def check_pid_file(self): """ This function checks if we are already running the :class:`Flow` with a :class:`PyFlowScheduler`. Raises: Flow.Error if the pid file of the scheduler exists. """ if not os.path.exists(self.pid_file): return 0 self.show_status() ...
Validate the JSON schema. Return list of errors.
def validate_json_schema(self): """Validate the JSON schema. Return list of errors.""" errors = [] for work in self: for task in work: if not task.get_results().validate_json_schema(): errors.append(task) if not work.get_results().vali...
List of errored tasks.
def errored_tasks(self): """List of errored tasks.""" etasks = [] for status in [self.S_ERROR, self.S_QCRITICAL, self.S_ABICRITICAL]: etasks.extend(list(self.iflat_tasks(status=status))) return set(etasks)
Returns a: class: Counter object that counts the number of tasks with given status ( use the string representation of the status as key ).
def status_counter(self): """ Returns a :class:`Counter` object that counts the number of tasks with given status (use the string representation of the status as key). """ # Count the number of tasks with given status in each work. counter = self[0].status_counter ...
Change the workir of the: class: Flow. Mainly used for allowing the user to open the GUI on the local host and access the flow from remote via sshfs.
def chroot(self, new_workdir): """ Change the workir of the :class:`Flow`. Mainly used for allowing the user to open the GUI on the local host and access the flow from remote via sshfs. .. note:: Calling this method will make the flow go in read-only mode. ""...
Returns a ordered dictionary mapping the task status to the list of named tuples ( task work_index task_index ).
def groupby_status(self): """ Returns a ordered dictionary mapping the task status to the list of named tuples (task, work_index, task_index). """ Entry = collections.namedtuple("Entry", "task wi ti") d = collections.defaultdict(list) for task, wi, ti in self.ifl...
Returns a dictionary mapping the task class to the list of tasks in the flow
def groupby_task_class(self): """ Returns a dictionary mapping the task class to the list of tasks in the flow """ # Find all Task classes class2tasks = OrderedDict() for task in self.iflat_tasks(): cls = task.__class__ if cls not in class2tasks: c...
Generators that produces a flat sequence of nodes. if status is not None only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the nodes.
def iflat_nodes(self, status=None, op="==", nids=None): """ Generators that produces a flat sequence of nodes. if status is not None, only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the nodes. """ nids = a...
Return the node in the Flow with the given nid identifier
def node_from_nid(self, nid): """Return the node in the `Flow` with the given `nid` identifier""" for node in self.iflat_nodes(): if node.node_id == nid: return node raise ValueError("Cannot find node with node id: %s" % nid)
Generator to iterate over all the tasks of the Flow. Yields:
def iflat_tasks_wti(self, status=None, op="==", nids=None): """ Generator to iterate over all the tasks of the `Flow`. Yields: (task, work_index, task_index) If status is not None, only the tasks whose status satisfies the condition (task.status op status) are selec...
Generator to iterate over all the tasks of the: class: Flow.
def iflat_tasks(self, status=None, op="==", nids=None): """ Generator to iterate over all the tasks of the :class:`Flow`. If status is not None, only the tasks whose status satisfies the condition (task.status op status) are selected status can be either one of the flags defined...
Generators that produces a flat sequence of task. if status is not None only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the tasks.
def _iflat_tasks_wti(self, status=None, op="==", nids=None, with_wti=True): """ Generators that produces a flat sequence of task. if status is not None, only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the tasks. ...
Run ABINIT in dry mode to validate all the inputs of the flow.
def abivalidate_inputs(self): """ Run ABINIT in dry mode to validate all the inputs of the flow. Return: (isok, tuples) isok is True if all inputs are ok. tuples is List of `namedtuple` objects, one for each task in the flow. Each namedtuple has ...
Test the dependencies of the nodes for possible deadlocks.
def check_dependencies(self): """Test the dependencies of the nodes for possible deadlocks.""" deadlocks = [] for task in self.iflat_tasks(): for dep in task.deps: if dep.node.depends_on(task): deadlocks.append((task, dep.node)) if deadlo...
This function detects deadlocks
def find_deadlocks(self): """ This function detects deadlocks Return: named tuple with the tasks grouped in: deadlocks, runnables, running """ # Find jobs that can be submitted and and the jobs that are already in the queue. runnables = [] for work in...
Check the status of the works in self.
def check_status(self, **kwargs): """ 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 """ for work in self: work.check_status() if kwargs.pop("sho...
This function tries to fix critical events originating from ABINIT. Returns the number of tasks that have been fixed.
def fix_abicritical(self): """ This function tries to fix critical events originating from ABINIT. Returns the number of tasks that have been fixed. """ count = 0 for task in self.iflat_tasks(status=self.S_ABICRITICAL): count += task.fix_abicritical() ...
This function tries to fix critical events originating from the queue submission system.
def fix_queue_critical(self): """ This function tries to fix critical events originating from the queue submission system. Returns the number of tasks that have been fixed. """ count = 0 for task in self.iflat_tasks(status=self.S_QCRITICAL): logger.info("Will...
Print info on the flow i. e. total number of tasks works tasks grouped by class.
def show_info(self, **kwargs): """ Print info on the flow i.e. total number of tasks, works, tasks grouped by class. Example: Task Class Number ------------ -------- ScfTask 1 NscfTask 1 ScrTask ...
Print a short summary with the status of the flow and a counter task_status -- > number_of_tasks
def show_summary(self, **kwargs): """ 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 --------- ------- Comp...
Report the status of the works and the status of the different tasks on the specified stream.
def show_status(self, **kwargs): """ 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: Sl...
Print the Abinit events ( ERRORS WARNIING COMMENTS ) to stdout
def show_events(self, status=None, nids=None): """ 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. """ nrows, n...
Show the corrections applied to the flow at run - time.
def show_corrections(self, status=None, nids=None): """ 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 num...
Print the history of the flow to stdout.
def show_history(self, status=None, nids=None, full_history=False, metadata=False): """ 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...
Print the input of the tasks to the given stream.
def show_inputs(self, varnames=None, nids=None, wslice=None, stream=sys.stdout): """ 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. ...
Print to the given stream a table with the list of the output files with the given ext produced by the flow.
def listext(self, ext, stream=sys.stdout): """ Print to the given `stream` a table with the list of the output files with the given `ext` produced by the flow. """ nodes_files = [] for node in self.iflat_nodes(): filepath = node.outdir.has_abiext(ext) ...
Return a list with a subset of tasks.
def select_tasks(self, nids=None, wslice=None, task_class=None): """ 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. ...
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.
def get_task_scfcycles(self, nids=None, wslice=None, task_class=None, exclude_ok_tasks=False): """ 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 id...
Print list of tricky tasks i. e. tasks that have been restarted or launched more than once or tasks with corrections.
def show_tricky_tasks(self, verbose=0): """ 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. """ nid...
Inspect the tasks ( SCF iterations Structural relaxation... ) and produces matplotlib plots.
def inspect(self, nids=None, wslice=None, **kwargs): """ 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 argu...
This function returns a dictionary with the attributes that will be put in the mongodb document to facilitate the query. Subclasses may want to replace or extend the default behaviour.
def get_dict_for_mongodb_queries(self): """ This function returns a dictionary with the attributes that will be put in the mongodb document to facilitate the query. Subclasses may want to replace or extend the default behaviour. """ d = {} return d # TODO ...
This method should be called before running the calculation to make sure that the most important requirements are satisfied.
def look_before_you_leap(self): """ This method should be called before running the calculation to make sure that the most important requirements are satisfied. Return: List of strings with inconsistencies/errors. """ errors = [] try: sel...
Insert results in the MongDB database.
def db_insert(self): """ Insert results in the `MongDB` database. """ assert self.has_db # Connect to MongoDb and get the collection. coll = self.manager.db_connector.get_collection() print("Mongodb collection %s with count %d", coll, coll.count()) start ...
Return the list of tasks associated to the given list of node identifiers ( nids ).
def tasks_from_nids(self, nids): """ Return the list of tasks associated to the given list of node identifiers (nids). .. note:: Invalid ids are ignored """ if not isinstance(nids, collections.abc.Iterable): nids = [nids] n2task = {task.node_id: task for ta...
Open the files of the flow inside an editor ( command line interface ).
def open_files(self, what="o", status=None, op="==", nids=None, editor=None): """ Open the files of the flow inside an editor (command line interface). Args: what: string with the list of characters selecting the file type Possible choices: i ==...
Parse the timer data in the main output file ( s ) of Abinit. Requires timopt/ = 0 in the input file ( usually timopt = - 1 )
def parse_timing(self, nids=None): """ 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` ...
Write to the given stream the list of ABINIT errors for all tasks whose status is S_ABICRITICAL.
def show_abierrors(self, nids=None, stream=sys.stdout): """ 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.std...
Write to the given stream the content of the queue output file for all tasks whose status is S_QCRITICAL.
def show_qouts(self, nids=None, stream=sys.stdout): """ 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: sy...
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.
def debug(self, status=None, nids=None): """ 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 statu...
Cancel all the tasks that are in the queue. nids is an optional list of node identifiers used to filter the tasks.
def cancel(self, nids=None): """ Cancel all the tasks that are in the queue. nids is an optional list of node identifiers used to filter the tasks. Returns: Number of jobs cancelled, negative value if error """ if self.has_chrooted: # TODO: Use pa...
Remove workdir ( same API as shutil. rmtree ).
def rmtree(self, ignore_errors=False, onerror=None): """Remove workdir (same API as shutil.rmtree).""" if not os.path.exists(self.workdir): return shutil.rmtree(self.workdir, ignore_errors=ignore_errors, onerror=onerror)
Make directories and files of the Flow.
def build(self, *args, **kwargs): """Make directories and files of the `Flow`.""" # Allocate here if not done yet! if not self.allocated: self.allocate() self.indir.makedirs() self.outdir.makedirs() self.tmpdir.makedirs() # Check the nodeid file in workdir ...
Build dirs and file of the Flow and save the object in pickle format. Returns 0 if success
def build_and_pickle_dump(self, abivalidate=False): """ 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 f...
Save the status of the object in pickle format. Returns 0 if success
def pickle_dump(self): """ Save the status of the object in pickle format. Returns 0 if success """ if self.has_chrooted: warnings.warn("Cannot pickle_dump since we have chrooted from %s" % self.has_chrooted) return -1 #if self.in_spectator_mode: ...
Return a string with the pickle representation. protocol selects the pickle protocol. self. pickle_protocol is used if protocol is None
def pickle_dumps(self, protocol=None): """ Return a string with the pickle representation. `protocol` selects the pickle protocol. self.pickle_protocol is used if `protocol` is None """ strio = StringIO() pmg_pickle_dump(self, strio, proto...
Utility function that generates a Work made of a single task
def register_task(self, input, deps=None, manager=None, task_class=None, append=False): """ Utility function that generates a `Work` made of a single task Args: input: :class:`AbinitInput` deps: List of :class:`Dependency` objects specifying the dependency of this node. ...
Register a new: class: Work and add it to the internal list taking into account possible dependencies.
def register_work(self, work, deps=None, manager=None, workdir=None): """ Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies. Args: work: :class:`Work` object. deps: List of :class:`Dependency` objects specifying the d...
Registers a callback function that will generate the: class: Task of the: class: Work.
def register_work_from_cbk(self, cbk_name, cbk_data, deps, work_class, manager=None): """ Registers a callback function that will generate the :class:`Task` of the :class:`Work`. Args: cbk_name: Name of the callback function (must be a bound method of self) cbk_data: Add...
Allocate the Flow i. e. assign the workdir and ( optionally ) the: class: TaskManager to the different tasks in the Flow.
def allocate(self, workdir=None, use_smartio=False): """ 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 hav...
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 unconverged so that we can...
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.
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 other means and we should...
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.
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.
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) ...
Build a return a: class: PyFlowScheduler to run the flow.
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...
Run the flow in batch mode return exit status of the job script. Requires a manager. yml file and a batch_adapter adapter.
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...
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.
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.
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.
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.
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.
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.
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.
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.
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_moment:: param saxis: desired saxis: return:
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
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:
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.
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.
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.
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.
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.
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.
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.
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)