text
stringlengths
81
112k
Send an e-mail before completing the shutdown. Returns 0 if success. def send_email(self, msg, tag=None): """ Send an e-mail before completing the shutdown. Returns 0 if success. """ try: return self._send_email(msg, tag) except: self.exce...
Find all flows located withing the directory `top` and build the `BatchLauncher`. Args: top: Top level directory or list of directories. workdir: Batch workdir. name: manager: :class:`TaskManager` object. If None, the manager is read from `manager.yml` ...
Loads the object from a pickle file. Args: filepath: Filename or directory name. It filepath is a directory, we scan the directory tree starting from filepath and we read the first pickle database. Raise RuntimeError if multiple databases are found. ...
Save the status of the object in pickle format. def pickle_dump(self): """Save the status of the object in pickle format.""" with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh: pickle.dump(self, fh)
Add a flow. Accept filepath or :class:`Flow` object. Return 1 if flow was added else 0. def add_flow(self, flow): """ Add a flow. Accept filepath or :class:`Flow` object. Return 1 if flow was added else 0. """ from .flows import Flow flow = Flow.as_flow(flow) if flow in...
Submit a job script that will run the schedulers with `abirun.py`. Args: verbose: Verbosity level dry_run: Don't submit the script if dry_run. Default: False Returns: namedtuple with attributes: retcode: Return code as returned by the submission scri...
Write the submission script. Return (script, num_flows_in_batch) def _get_script_nflows(self): """ Write the submission script. Return (script, num_flows_in_batch) """ flows_torun = [f for f in self.flows if not f.all_ok] if not flows_torun: return "", 0 exe...
Generates the string representation of the CTRL file. This is the mininmal CTRL file necessary to execute lmhart.run. def get_string(self, sigfigs=8): """ Generates the string representation of the CTRL file. This is the mininmal CTRL file necessary to execute lmhart.run. """ ...
Returns the CTRL as a dictionary. "SITE" and "CLASS" are of the form {'CATEGORY': {'TOKEN': value}}, the rest is of the form 'TOKEN'/'CATEGORY': value. It gets the conventional standard structure because primitive cells use the conventional a-lattice parameter as the scaling factor and n...
Creates a CTRL file object from an existing file. Args: filename: The name of the CTRL file. Defaults to 'CTRL'. Returns: An LMTOCtrl object. def from_file(cls, filename="CTRL", **kwargs): """ Creates a CTRL file object from an existing file. Args: ...
Creates a CTRL file object from a string. This will mostly be used to read an LMTOCtrl object from a CTRL file. Empty spheres are ignored. Args: data: String representation of the CTRL file. Returns: An LMTOCtrl object. def from_string(cls, data, sigfigs=8): ...
Creates a CTRL file object from a dictionary. The dictionary must contain the items "ALAT", PLAT" and "SITE". Valid dictionary items are: ALAT: the a-lattice parameter PLAT: (3x3) array for the lattice vectors SITE: list of dictionaries: {'ATOM': class label, ...
Subroutine to extract bond label, site indices, and length from a COPL header line. The site indices are zero-based, so they can be easily used with a Structure object. Example header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang. Args: line: line in the COHPCAR header describi...
Finds a set of n_images from self.s1 to self.s2, where all sites except for the ones given in relax_sites, the interpolation is linear (as in pymatgen.core.structure.interpolate), and for the site indices given in relax_sites, the path is relaxed by the elastic band method within the sta...
Generates a POSCAR with the calculated diffusion path with respect to the first endpoint. :param outfile: Output file for the POSCAR def plot_images(self, outfile): """ Generates a POSCAR with the calculated diffusion path with respect to the first endpoint. :param outfile: Output file ...
Implements path relaxation via the elastic band method. In general, the method is to define a path by a set of points (images) connected with bands with some elasticity constant k. The images then relax along the forces found in the potential field V, counterbalanced by the elastic respo...
Converts fractional coordinates to discrete coordinates with respect to the grid size of v def __f2d(frac_coords, v): """ Converts fractional coordinates to discrete coordinates with respect to the grid size of v """ # frac_coords = frac_coords % 1 return np.arra...
Converts a point given in discrete coordinates withe respect to the grid in v to fractional coordinates. def __d2f(disc_coords, v): """ Converts a point given in discrete coordinates withe respect to the grid in v to fractional coordinates. """ return np.array([disc_coor...
Sets the potential range 0 to 1. def normalize(self): """ Sets the potential range 0 to 1. """ self.__v = self.__v - np.amin(self.__v) self.__v = self.__v / np.amax(self.__v)
Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of the cell. Alternatively useful for mixing potentials tha...
Applies an isotropic Gaussian smear of width (standard deviation) r to the potential field. This is necessary to avoid finding paths through narrow minima or nodes that may exist in the field (although any potential or charge distribution generated from GGA should be relatively smooth an...
Given a structure, returns the predicted volume. Args: structure (Structure): structure w/unknown volume ref_structure (Structure): A reference structure with a similar structure but different species. Returns: a float value of the predicted volume de...
Given a structure, returns back the structure scaled to predicted volume. Args: structure (Structure): structure w/unknown volume ref_structure (Structure): A reference structure with a similar structure but different species. Returns: a Struct...
Given a structure, returns the predicted volume. Args: structure (Structure) : a crystal structure with an unknown volume. icsd_vol (bool) : True if the input structure's volume comes from ICSD. Returns: a float value of the predicted volume. def pr...
Given a structure, returns back the structure scaled to predicted volume. Args: structure (Structure): structure w/unknown volume Returns: a Structure object with predicted volume def get_predicted_structure(self, structure, icsd_vol=False): """ Given a ...
Pair the geometrically equivalent atoms of the molecules. Calculate RMSD on all possible isomorphism mappings and return mapping with the least RMSD Args: mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object. mol2: Second molecule. OpenBabel OBMol or pymatge...
Return inchi as molecular hash def get_molecule_hash(self, mol): """ Return inchi as molecular hash """ obconv = ob.OBConversion() obconv.SetOutFormat(str("inchi")) obconv.AddOption(str("X"), ob.OBConversion.OUTOPTIONS, str("DoNotAddH")) inchi_text = obconv.Write...
Get the inchi canonical labels of the heavy atoms in the molecule Args: mol: The molecule. OpenBabel OBMol object Returns: The label mappings. List of tuple of canonical label, original label List of equivalent atoms. def _inchi_labels(mol): """...
Calculate the centroids of a group atoms indexed by the labels of inchi Args: mol: The molecule. OpenBabel OBMol object ilabel: inchi label map Returns: Centroid. Tuple (x, y, z) def _group_centroid(mol, ilabels, group_atoms): """ Calculate the cent...
Create a virtual molecule by unique atoms, the centriods of the equivalent atoms Args: mol: The molecule. OpenBabel OBMol object ilables: inchi label map eq_atoms: equivalent atom labels farthest_group_idx: The equivalent atom group index in which ...
Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second molecule. OpenBabel OBMol object vmol1: First virtual molecule constructed by centroids. OpenBabel ...
Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second molecule. OpenBabel OBMol object heavy_indices1: inchi label map of the first molecule heavy_indices...
The the elements of the atoms in the specified order Args: mol: The molecule. OpenBabel OBMol object. label: The atom indices. List of integers. Returns: Elements. List of integers. def _get_elements(mol, label): """ The the elements of the atoms in...
Is the molecule a linear one Args: mol: The molecule. OpenBabel OBMol object. Returns: Boolean value. def _is_molecule_linear(self, mol): """ Is the molecule a linear one Args: mol: The molecule. OpenBabel OBMol object. Returns: ...
Return inchi as molecular hash def get_molecule_hash(self, mol): """ Return inchi as molecular hash """ obmol = BabelMolAdaptor(mol).openbabel_mol inchi = self._inchi_labels(obmol)[2] return inchi
Fit two molecules. Args: mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object Returns: A boolean value indicates whether two molecules are the same. def fit(self, mol1, mol2): "...
Get RMSD between two molecule with arbitrary atom order. Returns: RMSD if topology of the two molecules are the same Infinite if the topology is different def get_rmsd(self, mol1, mol2): """ Get RMSD between two molecule with arbitrary atom order. Returns: ...
Calculate the RMSD. Args: mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule object mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule object clabel1: The atom indices that can reorder the first molecule to ...
Group molecules by structural equality. Args: mol_list: List of OpenBabel OBMol or pymatgen objects Returns: A list of lists of matched molecules Assumption: if s1=s2 and s2=s3, then s1=s3 This may not be true for small tolerances. def group_molecules(s...
Convert a dictionary representing a Fortran namelist into a string. def nmltostring(nml): """Convert a dictionary representing a Fortran namelist into a string.""" if not isinstance(nml,dict): raise ValueError("nml should be a dict !") curstr = "" for key,group in nml.items(): namelist = ...
Initialize an instance from an :class:`AbinitTask` instance. def from_node(cls, task): """Initialize an instance from an :class:`AbinitTask` instance.""" new = super().from_node(task) new.update( executable=task.executable, #executable_version: #task_events=...
Read the `AutoParal` section (YAML format) from filename. Assumes the file contains only one section. def parse(self, filename): """ Read the `AutoParal` section (YAML format) from filename. Assumes the file contains only one section. """ with abiinspect.YamlTokenizer(fi...
Build a list of Parallel configurations from two lists containing the number of MPI processes and the number of OpenMP threads i.e. product(mpi_procs, omp_threads). The configuration have parallel efficiency set to 1.0 and no input variables. Mainly used for preparing benchmarks. def fr...
Remove all the configurations that do not satisfy the given condition. Args: condition: dict or :class:`Condition` object with operators expressed with a Mongodb-like syntax key: Selects the sub-dictionary on which condition is applied, e.g. key="vars" if...
Sort the configurations in place. items with highest efficiency come first def sort_by_efficiency(self, reverse=True): """Sort the configurations in place. items with highest efficiency come first""" self._confs.sort(key=lambda c: c.efficiency, reverse=reverse) return self
Sort the configurations in place. items with highest speedup come first def sort_by_speedup(self, reverse=True): """Sort the configurations in place. items with highest speedup come first""" self._confs.sort(key=lambda c: c.speedup, reverse=reverse) return self
Sort the configurations in place. items with lowest memory per proc come first. def sort_by_mem_per_proc(self, reverse=False): """Sort the configurations in place. items with lowest memory per proc come first.""" # Avoid sorting if mem_per_cpu is not available. if any(c.mem_per_proc > 0.0 for c...
Sort and return a new list of configurations ordered according to the :class:`TaskPolicy` policy. def get_ordered_with_policy(self, policy, max_ncpus): """ Sort and return a new list of configurations ordered according to the :class:`TaskPolicy` policy. """ # Build new list since we are...
Converts an object obj into a `:class:`TaskPolicy. Accepts: * None * TaskPolicy * dict-like object def as_policy(cls, obj): """ Converts an object obj into a `:class:`TaskPolicy. Accepts: * None * TaskPolicy * dict-like object ...
Initialize the :class:`TaskManager` from the YAML file 'manager.yaml'. Search first in the working directory and then in the AbiPy configuration directory. Raises: RuntimeError if file is not found. def from_user_config(cls): """ Initialize the :class:`TaskManager` from the...
Read the configuration parameters from the Yaml file filename. def from_file(cls, filename): """Read the configuration parameters from the Yaml file filename.""" try: with open(filename, "r") as fh: return cls.from_dict(yaml.safe_load(fh)) except Exception as exc: ...
Convert obj into TaskManager instance. Accepts string, filepath, dictionary, `TaskManager` object. If obj is None, the manager is initialized from the user config file. def as_manager(cls, obj): """ Convert obj into TaskManager instance. Accepts string, filepath, dictionary, `TaskManager` objec...
Create an instance from a dictionary. def from_dict(cls, d): """Create an instance from a dictionary.""" return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})
Returns a new `TaskManager` with the same parameters as self but replace the :class:`QueueAdapter` with a :class:`ShellAdapter` with mpi_procs so that we can submit the job without passing through the queue. def to_shell_manager(self, mpi_procs=1): """ Returns a new `TaskManager` with the same ...
Return a new `TaskManager` in which autoparal has been disabled. The jobs will be executed with `mpi_procs` MPI processes and `omp_threads` OpenMP threads. Useful for generating input files for benchmarks. def new_with_fixed_mpi_omp(self, mpi_procs, omp_threads): """ Return a new `TaskM...
Given a list of parallel configurations, pconfs, this method select an `optimal` configuration according to some criterion as well as the :class:`QueueAdapter` to use. Args: pconfs: :class:`ParalHints` object with the list of parallel configurations Returns: :class:`Par...
This function is called when we have accepted the :class:`ParalConf` pconf. Returns pconf def _use_qadpos_pconf(self, qadpos, pconf): """ This function is called when we have accepted the :class:`ParalConf` pconf. Returns pconf """ self._qadpos = qadpos # Change...
Write the submission script. Return the path of the script ================ ============================================ kwargs Meaning ================ ============================================ exec_args List of arguments passed to task.executable. ...
Build the input files and submit the task via the :class:`Qadapter` Args: task: :class:`TaskObject` Returns: Process object. def launch(self, task, **kwargs): """ Build the input files and submit the task via the :class:`Qadapter` Args: tas...
Compare Abinit version to `version_string` with operator `op` def compare_version(self, version_string, op): """Compare Abinit version to `version_string` with operator `op`""" from pkg_resources import parse_version from monty.operator import operator_from_str op = operator_from_str(op...
Convert delta into a MyTimedelta object. def as_timedelta(cls, delta): """Convert delta into a MyTimedelta object.""" # Cannot monkey patch the __class__ and must pass through __new__ as the object is immutable. if isinstance(delta, cls): return delta return cls(delta.days, delta.second...
:class:`timedelta` with the run-time, None if the Task is not running def get_runtime(self): """:class:`timedelta` with the run-time, None if the Task is not running""" if self.start is None: return None if self.end is None: delta = datetime.datetime.now() - self.start else...
:class:`timedelta` with the time spent in the Queue, None if the Task is not running .. note: This value is always greater than the real value computed by the resource manager as we start to count only when check_status sets the `Task` status to S_RUN. def get_time_inqueue(self): ...
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 Value...
Set the :class:`Work` associated to this `Task`. def set_work(self, work): """Set the :class:`Work` associated to this `Task`.""" if not hasattr(self, "_work"): self._work = work else: if self._work != work: raise ValueError("self._work != work")
The position of the task in the :class:`Flow` def pos(self): """The position of the task in the :class:`Flow`""" for i, task in enumerate(self.work): if self == task: return self.work.pos, i raise ValueError("Cannot find the position of %s in flow %s" % (self, self.f...
Set the values of the ABINIT variables in the input file. Return dict with old values. def set_vars(self, *args, **kwargs): """ Set the values of the ABINIT variables in the input file. Return dict with old values. """ kwargs.update(dict(*args)) old_values = {vname: self.input.g...
Construct the input file of the calculation. def make_input(self, with_header=False): """Construct the input file of the calculation.""" s = str(self.input) if with_header: s = str(self) + "\n" + s return s
Returns the path of the input file with extension ext. Use it when the file does not exist yet. def ipath_from_ext(self, ext): """ Returns the path of the input file with extension ext. Use it when the file does not exist yet. """ return os.path.join(self.workdir, self.p...
Returns the path of the output file with extension ext. Use it when the file does not exist yet. def opath_from_ext(self, ext): """ Returns the path of the output file with extension ext. Use it when the file does not exist yet. """ return os.path.join(self.workdir, self...
The task can run if its status is < S_SUB and all the other dependencies (if any) are done! def can_run(self): """The task can run if its status is < S_SUB and all the other dependencies (if any) are done!""" all_ok = all(stat == self.S_OK for stat in self.deps_status) return self.status < self...
Cancel the job. Returns 1 if job was cancelled. def cancel(self): """Cancel the job. Returns 1 if job was cancelled.""" if self.queue_id is None: return 0 if self.status >= self.S_DONE: return 0 exit_status = self.manager.cancel(self.queue_id) if exit_status != 0: l...
Disable autoparal and force execution with `mpi_procs` MPI processes and `omp_threads` OpenMP threads. Useful for generating benchmarks. def with_fixed_mpi_omp(self, mpi_procs, omp_threads): """ Disable autoparal and force execution with `mpi_procs` MPI processes and `omp_threads` OpenM...
This method is called when the task reaches S_OK. It changes the extension of particular output files produced by Abinit so that the 'official' extension is preserved e.g. out_1WF14 --> out_1WF def fix_ofiles(self): """ This method is called when the task reaches S_OK. I...
Called by restart once we have finished preparing the task for restarting. Return: True if task has been restarted def _restart(self, submit=True): """ Called by restart once we have finished preparing the task for restarting. Return: True if task has been rest...
Check if child process has terminated. Set and return returncode attribute. def poll(self): """Check if child process has terminated. Set and return returncode attribute.""" self._returncode = self.process.poll() if self._returncode is not None: self.set_status(self.S_DONE, "status...
Wait for child process to terminate. Set and return returncode attribute. def wait(self): """Wait for child process to terminate. Set and return returncode attribute.""" self._returncode = self.process.wait() try: self.process.stderr.close() except: pass ...
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tupl...
Kill the child. def kill(self): """Kill the child.""" self.process.kill() self.set_status(self.S_ERROR, "status set to Error by task.kill") self._returncode = self.process.returncode
Reset the task status. Mainly used if we made a silly mistake in the initial setup of the queue manager and we want to fix it and rerun the task. Returns: 0 on success, 1 if reset failed. def reset(self): """ Reset the task status. Mainly used if we made a silly mistake in ...
Lock the task, source is the :class:`Node` that applies the lock. def lock(self, source_node): """Lock the task, source is the :class:`Node` that applies the lock.""" if self.status != self.S_INIT: raise ValueError("Trying to lock a task with status %s" % self.status) self._status ...
Unlock the task, set its status to `S_READY` so that the scheduler can submit it. source_node is the :class:`Node` that removed the lock Call task.check_status if check_status is True. def unlock(self, source_node, check_status=True): """ Unlock the task, set its status to `S_READY` so ...
Set and return the status of the task. Args: status: Status object or string representation of the status msg: string with human-readable message used in the case of errors. def set_status(self, status, msg): """ Set and return the status of the task. Args: ...
This function checks the status of the task by inspecting the output and the error files produced by the application and by the queue manager. def check_status(self): """ This function checks the status of the task by inspecting the output and the error files produced by the application...
Move an output file to the output data directory of the `Task` and rename the file so that ABINIT will read it as an input data file. Returns: The absolute path of the new file in the indata directory. def out_to_in(self, out_file): """ Move an output file to the output dat...
Create a symbolic link to the specified file in the directory containing the input files of the task. def inlink_file(self, filepath): """ Create a symbolic link to the specified file in the directory containing the input files of the task. """ if not os.path.exists(file...
Create symbolic links to the output files produced by the other tasks. .. warning:: This method should be called only when the calculation is READY because it uses a heuristic approach to find the file to link. def make_links(self): """ Create symbolic links to the out...
Analyzes the main logfile of the calculation for possible Errors or Warnings. If the ABINIT abort file is found, the error found in this file are added to the output report. Args: source: "output" for the main output file,"log" for the log file. Returns: :class:...
Returns :class:`NodeResults` instance. Subclasses should extend this method (if needed) by adding specialized code that performs some kind of post-processing. def get_results(self, **kwargs): """ Returns :class:`NodeResults` instance. Subclasses should extend this method (if nee...
Rename a file located in datadir. src_basename and dest_basename are the basename of the source file and of the destination file, respectively. def rename(self, src_basename, dest_basename, datadir="outdir"): """ Rename a file located in datadir. src_basename and dest_basename...
Creates the working directory and the input files of the :class:`Task`. It does not overwrite files if they already exist. def build(self, *args, **kwargs): """ Creates the working directory and the input files of the :class:`Task`. It does not overwrite files if they already exist. ...
Remove all the files listed in filenames. def remove_files(self, *filenames): """Remove all the files listed in filenames.""" filenames = list_strings(filenames) for dirpath, dirnames, fnames in os.walk(self.workdir): for fname in fnames: if fname in filenames: ...
This method is called when the task reaches S_OK. It removes all the output files produced by the task that are not needed by its children as well as the output files produced by its parents if no other node needs them. Args: follow_parents: If true, the output files of the parents ...
Starts the calculation by performing the following steps: - build dirs and files - call the _setup method - execute the job file by executing/submitting the job script. Main entry point for the `Launcher`. ============== ===========================================...
Helper method to start the task and wait for completion. Mainly used when we are submitting the task via the shell without passing through a queue manager. def start_and_wait(self, *args, **kwargs): """ Helper method to start the task and wait for completion. Mainly used when we are s...
Generate task graph in the DOT language (only parents and children of this task). Args: engine: ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_attr: Mapping of (attribute, value) pairs for the graph. node_attr: Mapping of (attribute, value) pai...
Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object. def from_input(cls, input, workdir=None, manager=None): """ Create an instance of `Abin...
Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for invoking Abinit to get important parameters needed to prepare the real task. Args: mpi_procs: Number of MPI processes to use. def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, ...
Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by renaming run.abo to run.abo_[number] if the output file "run.abo" alre...
Return the subclass of ScfCycle associated to the task or None if no SCF algorithm if associated to the task. def cycle_class(self): """ Return the subclass of ScfCycle associated to the task or None if no SCF algorithm if associated to the task. """ if isinstance(self, ...