INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create an istance from string s containing a YAML dictionary.
def from_string(cls, s): """Create an istance from string s containing a YAML dictionary.""" stream = cStringIO(s) stream.seek(0) return cls(**yaml.safe_load(stream))
Initialize the :class:`PyFlowScheduler` from the YAML file 'scheduler.yml'. Search first in the working directory and then in the configuration directory of abipy. Raises: `RuntimeError` if file is not found.
def from_user_config(cls): """ Initialize the :class:`PyFlowScheduler` from the YAML file 'scheduler.yml'. Search first in the working directory and then in the configuration directory of abipy. Raises: `RuntimeError` if file is not found. """ # Try in the cu...
The pid of the process associated to the scheduler.
def pid(self): """The pid of the process associated to the scheduler.""" try: return self._pid except AttributeError: self._pid = os.getpid() return self._pid
Add an :class:`Flow` flow to the scheduler.
def add_flow(self, flow): """ Add an :class:`Flow` flow to the scheduler. """ if hasattr(self, "_flow"): raise self.Error("Only one flow can be added to the scheduler.") # Check if we are already using a scheduler to run this flow flow.check_pid_file() ...
Validate input parameters if customer service is on then create directory for tarball files with correct premissions for user and group.
def _validate_customer_service(self): """ Validate input parameters if customer service is on then create directory for tarball files with correct premissions for user and group. """ direc = self.customer_service_dir if not direc.exists: mode = 0o750 ...
This method is called before the shutdown of the scheduler. If customer_service is on and the flow didn't completed successfully, a lightweight tarball file with inputs and the most important output files is created in customer_servide_dir.
def _do_customer_service(self): """ This method is called before the shutdown of the scheduler. If customer_service is on and the flow didn't completed successfully, a lightweight tarball file with inputs and the most important output files is created in customer_servide_dir. ...
Starts the scheduler in a new thread. Returns 0 if success. In standalone mode, this method will block until there are no more scheduled jobs.
def start(self): """ Starts the scheduler in a new thread. Returns 0 if success. In standalone mode, this method will block until there are no more scheduled jobs. """ self.history.append("Started on %s" % time.asctime()) self.start_time = time.time() if not has_...
This function checks the status of all tasks, tries to fix tasks that went unconverged, abicritical, or queuecritical and tries to run all the tasks that can be submitted.+
def _runem_all(self): """ This function checks the status of all tasks, tries to fix tasks that went unconverged, abicritical, or queuecritical and tries to run all the tasks that can be submitted.+ """ excs = [] flow = self.flow # Allow to change the man...
The function that will be executed by the scheduler.
def callback(self): """The function that will be executed by the scheduler.""" try: return self._callback() except: # All exceptions raised here will trigger the shutdown! s = straceback() self.exceptions.append(s) # This is useful whe...
The actual callback.
def _callback(self): """The actual callback.""" if self.debug: # Show the number of open file descriptors print(">>>>> _callback: Number of open file descriptors: %s" % get_open_fds()) self._runem_all() # Mission accomplished. Shutdown the scheduler. all...
Cleanup routine: remove the pid file and save the pickle database
def cleanup(self): """Cleanup routine: remove the pid file and save the pickle database""" try: os.remove(self.pid_file) except OSError as exc: logger.critical("Could not remove pid_file: %s", exc) # Save the final status of the flow. self.flow.pickle_dum...
Shutdown the scheduler.
def shutdown(self, msg): """Shutdown the scheduler.""" try: self.cleanup() self.history.append("Completed on: %s" % time.asctime()) self.history.append("Elapsed time: %s" % self.get_delta_etime()) if self.debug: print(">>>>> shutdown: Num...
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.exceptions.append(straceback()) return -2
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` ...
def from_dir(cls, top, workdir=None, name=None, manager=None, max_depth=2): """ 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: ...
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.
def pickle_load(cls, filepath): """ 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 RuntimeErro...
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 self.flows: raise self.Error("Cannot add same flow twice!") if not ...
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...
def submit(self, **kwargs): """ 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...
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 executable = [ 'export _LOG=%s' % self.log_file.path, ...
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. """ ctrl_dict = self.as_dict() lines = [] if "HEADER" not in ctrl_dict else \ ["HEADER".ljust(10) + self....
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...
def as_dict(self): """ 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-lattic...
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: filename: The name of the CTRL file. Defaults to 'CTRL'. Returns: An LMTOCtrl object. """ with zopen(filename, "rt") as f: cont...
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 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 ...
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, ...
def from_dict(cls, d): """ 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 ...
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...
def _get_bond_data(line): """ 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: ...
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...
def interpolate(self): """ 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...
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 for the POSCAR """ sum_struct = self.__images[0].sites for image in self.__images: for site_i in self.__re...
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...
def string_relax(start, end, V, n_images=25, dr=None, h=3.0, k=0.17, min_iter=100, max_iter=10000, max_tol=5e-6): """ 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 w...
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.array([int(frac_coords[0] * v.shape[0]), int(frac_coords[1] * v.shape[1]), ...
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_coords[0] / v.shape[0], disc_coords[1] / v.shape[1], disc_coords[2] ...
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...
def rescale_field(self, new_dim): """ 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 th...
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...
def gaussian_smear(self, r): """ 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 generate...
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
def predict(self, structure, ref_structure): """ 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. ...
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...
def get_predicted_structure(self, structure, ref_structure): """ 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 ...
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 predict(self, structure, icsd_vol=False): """ 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. R...
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 structure, returns back the structure scaled to predicted volume. Args: structure (Structure): structure w/unknown volume Returns: a Structure object with predicted volume "...
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...
def uniform_labels(self, mol1, mol2): """ 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. ...
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.WriteString(mol) match = re.s...
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): """ 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...
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 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) """ ...
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 ...
def _virtual_molecule(self, mol, ilabels, eq_atoms): """ 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 ...
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 ...
def _align_heavy_atoms(mol1, mol2, vmol1, vmol2, ilabel1, ilabel2, eq_atoms): """ Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second...
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...
def _align_hydrogen_atoms(mol1, mol2, heavy_indices1, heavy_indices2): """ Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second mol...
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 the specified order Args: mol: The molecule. OpenBabel OBMol object. label: The atom indices. List of integers. Returns: Elements. List of integers. """ elements = [i...
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: Boolean value. """ if mol.NumAtoms() < 3: return True a1 = mol.GetAtom(1) a2 = mol.GetAtom(...
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): """ 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 ...
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: RMSD if topology of the two molecules are the same Infinite if the topology is different """ label1, label2 = self._mapper.uniform_labels(mol1, mol2) ...
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 ...
def _calc_rms(mol1, mol2, clabel1, clabel2): """ 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: Th...
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(self, mol_list): """ 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...
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 = ["&" + key] for k, v in group.items(): if isinstance(...
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= pseudos=[p.as_dict() for p in task.input.pseudos]...
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(filename) as r: doc = r.next_doc_with_tag("!Autoparal") try: d = yaml.saf...
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 from_mpi_omp_lists(cls, mpi_procs, omp_threads): """ 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 ...
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...
def select_with_condition(self, condition, key=None): """ 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-dictio...
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 in self): self._confs.sort(key=lambda c: c.mem_per_proc, reverse=rev...
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 gonna change the object in place. hints = self.__class__(self.info, confs=[c for c in self...
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 """ if obj is None: # Use default policy. return TaskPolicy() else: if isinstan...
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: print("Error while reading TaskManager parameters from...
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 YAML file 'manager.yaml'. Search first in the working directory and then in the AbiPy configuration directory. Raises: RuntimeError if file is not found. """ global _USER_CONFIG_TASKM...
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` object. If obj is None, the manager is initialized from the user config file. """ if isinstance(obj, cls): return obj if obj is None: return cls.from_u...
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})
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 `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. """ ...
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...
def select_qadapter(self, pconfs): """ 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 c...
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 the number of MPI/OMP cores. self.set_mpi_procs(pconf.mpi_procs) if self.has_omp: ...
Write the submission script. Return the path of the script ================ ============================================ kwargs Meaning ================ ============================================ exec_args List of arguments passed to task.executable. ...
def write_jobfile(self, task, **kwargs): """ Write the submission script. Return the path of the script ================ ============================================ kwargs Meaning ================ ============================================ exec_args ...
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: task: :class:`TaskObject` Returns: Process object. """ if task.status == task.S_LOCKED: raise ValueError("You shall not su...
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) return op(parse_version(self.version), parse_version(...
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.seconds, delta.microseconds)
: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: delta = self.end - self.start return MyTimedelta...
: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): """ :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` st...
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, workdir)) se...
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.flow))
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.get(vname) for vname in kwargs} self.input.set_vars(**kwargs) if kwargs o...
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.prefix.idata + "_" + ext)
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.prefix.odata + "_" + ext)
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.S_SUB and self.status != self.S_LOCKED and all_ok
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: logger.warning("manager.cancel returned exit_statu...
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` OpenMP threads. Useful for generating benchmarks. """ manager = self.manager if hasattr(self, "manager") else self.flow.manager ...
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. It changes the extension of particular output files produced by Abinit so that the 'official' extension is preserved e.g. out_1WF14 --> out_1WF """ filepaths = self.outdir.list_filepaths()...
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 restarted """ self.set_status(self.S_READY, msg="Restarted on %s" % time.asctime()) # Increase the counter. ...
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 set to Done") return self._returncode
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 self.set_status(self.S_DONE, "status set to Done") return self._re...
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...
def communicate(self, input=None): """ 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 s...
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 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. """ # Can only reset tasks that are done. ...
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 = self.S_LOCKED self.history.info("Locked by node %s", sour...
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 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. """ if self.status != self.S_LOCK...
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: status: Status object or string representation of the status msg: string with human-readable message used in the case of errors. """ # truncate string if it's long. msg wi...
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 and by the queue manager. """ # 1) see it the job is blocked # 2) see if an error occured at submitting the job the job was sub...
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 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. """ in_file = os.path....
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 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. """ for dep in se...
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(filepath): logger.debug("Creating symbolic link to not existent file %s" % filepath) # Extract...
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:...
def get_event_report(self, source="log"): """ 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...
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 needed) by adding specialized code that performs some kind of post-processing. """ # Check whether the process completed. if self.returncode is Non...