INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns a dictionary with the abinit variables. | def to_abivars(self):
"""Returns a dictionary with the abinit variables."""
abivars = dict(
gwcalctyp=self.gwcalctyp,
ecuteps=self.ecuteps,
ecutsigx=self.ecutsigx,
symsigma=self.symsigma,
gw_qprange=self.gw_qprange,
gwpara=self.gwpa... |
Returns a dictionary with the abinit variables. | def to_abivars(self):
"""Returns a dictionary with the abinit variables."""
abivars = dict(
bs_calctype=1,
bs_loband=self.bs_loband,
#nband=self.nband,
mbpt_sciss=self.mbpt_sciss,
ecuteps=self.ecuteps,
bs_algorithm=self._ALGO2VAR[se... |
Set fake upper/lower bands, useful to set the same energy
range in the spin up/down bands when calculating the DOS | def set_upper_lower_bands(self,e_lower,e_upper):
"""
Set fake upper/lower bands, useful to set the same energy
range in the spin up/down bands when calculating the DOS
"""
lower_band = e_lower*np.ones((1,self.ebands.shape[1]))
upper_band = e_upper*np.ones((1,self.... |
Cut out bands outside the range (emin,emax) | def bandana(self, emin=-np.inf, emax=np.inf):
"""Cut out bands outside the range (emin,emax)"""
bandmin = np.min(self.ebands, axis=1)
bandmax = np.max(self.ebands, axis=1)
ii = np.nonzero(bandmin < emax)
nemax = ii[0][-1]
ii = np.nonzero(bandmax > emin)
nemin = ii... |
Get a vasprun.xml file and return a VasprunLoader | def from_file(self, vasprun_file):
"""Get a vasprun.xml file and return a VasprunLoader"""
vrun_obj = Vasprun(vasprun_file, parse_projected_eigen=True)
return VasprunLoader(vrun_obj) |
Return a BandStructureSymmLine object interpolating bands along a
High symmetry path calculated from the structure using HighSymmKpath function | def get_band_structure(self):
"""Return a BandStructureSymmLine object interpolating bands along a
High symmetry path calculated from the structure using HighSymmKpath function"""
kpath = HighSymmKpath(self.data.structure)
kpt_line = [Kpoint(k, self.data.structure.lattice) for k
... |
Return a Dos object interpolating bands
Args:
partial_dos: if True, projections will be interpolated as well
and partial doses will be return. Projections must be available
in the loader.
npts_mu: number of energy points of the Dos
... | def get_dos(self, partial_dos=False, npts_mu=10000, T=None):
"""
Return a Dos object interpolating bands
Args:
partial_dos: if True, projections will be interpolated as well
and partial doses will be return. Projections must be available
... |
Return a CompleteDos object interpolating the projections
tdos: total dos previously calculated
npts_mu: number of energy points of the Dos
T: parameter used to smooth the Dos | def get_partial_doses(self, tdos, npts_mu, T):
"""
Return a CompleteDos object interpolating the projections
tdos: total dos previously calculated
npts_mu: number of energy points of the Dos
T: parameter used to smooth the Dos
"""
spin = self.data... |
Calculate all the properties w.r.t. the doping levels in input.
Args:
doping: numpy array specifing the doping levels
When executed, it add the following variable at the BztTransportProperties
object:
Conductivity_doping, Seebeck_doping, Kappa_doping, Power_Factor_dopin... | def compute_properties_doping(self, doping, temp_r=None):
"""
Calculate all the properties w.r.t. the doping levels in input.
Args:
doping: numpy array specifing the doping levels
When executed, it add the following variable at the BztTransportProperties
object:
... |
Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity","Seebeck","Kappa","Carrier_conc","Hall_carrier_conc_trace"). Abbreviations are possible, like "S" for "Seebeck"
prop_x: independent variable in the x-axis among ('mu','doping','te... | def plot_props(self, prop_y, prop_x, prop_z='temp',
output='avg_eigs', dop_type='n', doping=None,
temps=None, xlim=(-2, 2), ax=None):
"""
Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity... |
Plot a band structure on symmetry line using BSPlotter() | def plot_bands(self):
"""
Plot a band structure on symmetry line using BSPlotter()
"""
if self.bzt_interp is None:
raise BoltztrapError("BztInterpolator not present")
sbs = self.bzt_interp.get_band_structure()
return BSPlotter(sbs).get_plot() |
Plot the total Dos using DosPlotter() | def plot_dos(self, T=None, npoints=10000):
"""
Plot the total Dos using DosPlotter()
"""
if self.bzt_interp is None:
raise BoltztrapError("BztInterpolator not present")
tdos = self.bzt_interp.get_dos(T=T,npts_mu=npoints)
#print(npoints)
dosPlotter... |
Calculates the energy of the reaction.
Args:
energies ({Composition: float}): Energy for each composition.
E.g ., {comp1: energy1, comp2: energy2}.
Returns:
reaction energy as a float. | def calculate_energy(self, energies):
"""
Calculates the energy of the reaction.
Args:
energies ({Composition: float}): Energy for each composition.
E.g ., {comp1: energy1, comp2: energy2}.
Returns:
reaction energy as a float.
"""
... |
Normalizes the reaction to one of the compositions.
By default, normalizes such that the composition given has a
coefficient of 1. Another factor can be specified.
Args:
comp (Composition): Composition to normalize to
factor (float): Factor to normalize to. Defaults to 1... | def normalize_to(self, comp, factor=1):
"""
Normalizes the reaction to one of the compositions.
By default, normalizes such that the composition given has a
coefficient of 1. Another factor can be specified.
Args:
comp (Composition): Composition to normalize to
... |
Normalizes the reaction to one of the elements.
By default, normalizes such that the amount of the element is 1.
Another factor can be specified.
Args:
element (Element/Specie): Element to normalize to.
factor (float): Factor to normalize to. Defaults to 1. | def normalize_to_element(self, element, factor=1):
"""
Normalizes the reaction to one of the elements.
By default, normalizes such that the amount of the element is 1.
Another factor can be specified.
Args:
element (Element/Specie): Element to normalize to.
... |
Returns the amount of the element in the reaction.
Args:
element (Element/Specie): Element in the reaction
Returns:
Amount of that element in the reaction. | def get_el_amount(self, element):
"""
Returns the amount of the element in the reaction.
Args:
element (Element/Specie): Element in the reaction
Returns:
Amount of that element in the reaction.
"""
return sum([self._all_comp[i][element] * abs(sel... |
List of reactants | def reactants(self):
"""
List of reactants
"""
return [self._all_comp[i] for i in range(len(self._all_comp))
if self._coeffs[i] < 0] |
List of products | def products(self):
"""
List of products
"""
return [self._all_comp[i] for i in range(len(self._all_comp))
if self._coeffs[i] > 0] |
Returns a ComputedEntry representation of the reaction.
:return: | def as_entry(self, energies):
"""
Returns a ComputedEntry representation of the reaction.
:return:
"""
relevant_comp = [comp * abs(coeff) for coeff, comp
in zip(self._coeffs, self._all_comp)]
comp = sum(relevant_comp, Composition())
entry ... |
Generates a balanced reaction from a string. The reaction must
already be balanced.
Args:
rxn_string:
The reaction string. For example, "4 Li + O2-> 2Li2O"
Returns:
BalancedReaction | def from_string(rxn_string):
"""
Generates a balanced reaction from a string. The reaction must
already be balanced.
Args:
rxn_string:
The reaction string. For example, "4 Li + O2-> 2Li2O"
Returns:
BalancedReaction
"""
rct... |
Equivalent of all_comp but returns entries, in the same order as the
coefficients. | def all_entries(self):
"""
Equivalent of all_comp but returns entries, in the same order as the
coefficients.
"""
entries = []
for c in self._all_comp:
for e in self._all_entries:
if e.composition.reduced_formula == c.reduced_formula:
... |
Compute the energy of a structure using Tersoff potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place | def get_energy_tersoff(structure, gulp_cmd='gulp'):
"""
Compute the energy of a structure using Tersoff potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
"""
gio = GulpIO()
gc = GulpCaller(gulp_cmd)
gin = gio.tersof... |
Compute the energy of a structure using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
neutral. | def get_energy_buckingham(structure, gulp_cmd='gulp',
keywords=('optimise', 'conp', 'qok'),
valence_dict=None):
"""
Compute the energy of a structure using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: ... |
Relax a structure and compute the energy using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
n... | def get_energy_relax_structure_buckingham(structure,
gulp_cmd='gulp',
keywords=('optimise', 'conp'),
valence_dict=None):
"""
Relax a structure and compute the energy using Buckingham pot... |
Generates GULP input string corresponding to pymatgen structure.
Args:
structure: pymatgen Structure object
cell_flg (default = True): Option to use lattice parameters.
fractional_flg (default = True): If True, fractional coordinates
are used. Else, cartesian... | def structure_lines(self, structure, cell_flg=True, frac_flg=True,
anion_shell_flg=True, cation_shell_flg=False,
symm_flg=True):
"""
Generates GULP input string corresponding to pymatgen structure.
Args:
structure: pymatgen Structure o... |
Gets a GULP input with Tersoff potential for an oxide structure
Args:
structure: pymatgen.core.structure.Structure
periodic (Default=False): Flag denoting whether periodic
boundary conditions are used
library (Default=None): File containing the species and po... | def tersoff_input(self, structure, periodic=False, uc=True, *keywords):
"""
Gets a GULP input with Tersoff potential for an oxide structure
Args:
structure: pymatgen.core.structure.Structure
periodic (Default=False): Flag denoting whether periodic
boundar... |
Specifies GULP library file to read species and potential parameters.
If using library don't specify species and potential
in the input file and vice versa. Make sure the elements of
structure are in the library file.
Args:
file_name: Name of GULP library file
Retur... | def library_line(self, file_name):
"""
Specifies GULP library file to read species and potential parameters.
If using library don't specify species and potential
in the input file and vice versa. Make sure the elements of
structure are in the library file.
Args:
... |
Generate species, buckingham, and spring options for an oxide structure
using the parameters in default libraries.
Ref:
1. G.V. Lewis and C.R.A. Catlow, J. Phys. C: Solid State Phys.,
18, 1149-1161 (1985)
2. T.S.Bush, J.D.Gale, C.R.A.Catlow and P.D. Battle,
... | def buckingham_potential(self, structure, val_dict=None):
"""
Generate species, buckingham, and spring options for an oxide structure
using the parameters in default libraries.
Ref:
1. G.V. Lewis and C.R.A. Catlow, J. Phys. C: Solid State Phys.,
18, 1149-1161 ... |
Gets a GULP input for an oxide structure and buckingham potential
from library.
Args:
structure: pymatgen.core.structure.Structure
keywords: GULP first line keywords.
library (Default=None): File containing the species and potential.
uc (Default=True): Un... | def buckingham_input(self, structure, keywords, library=None,
uc=True, valence_dict=None):
"""
Gets a GULP input for an oxide structure and buckingham potential
from library.
Args:
structure: pymatgen.core.structure.Structure
keywords: GU... |
Generate the species, tersoff potential lines for an oxide structure
Args:
structure: pymatgen.core.structure.Structure | def tersoff_potential(self, structure):
"""
Generate the species, tersoff potential lines for an oxide structure
Args:
structure: pymatgen.core.structure.Structure
"""
bv = BVAnalyzer()
el = [site.specie.symbol for site in structure]
valences = bv.get... |
Run GULP using the gin as input
Args:
gin: GULP input string
Returns:
gout: GULP output string | def run(self, gin):
"""
Run GULP using the gin as input
Args:
gin: GULP input string
Returns:
gout: GULP output string
"""
with ScratchDir("."):
p = subprocess.Popen(
self._gulp_cmd, stdout=subprocess.PIPE,
... |
Print to the given string, the documentation for the events
and the associated handlers. | def autodoc_event_handlers(stream=sys.stdout):
"""
Print to the given string, the documentation for the events
and the associated handlers.
"""
lines = []
for cls in all_subclasses(EventHandler):
if cls in _ABC_EVHANDLER_CLASSES: continue
event_class = cls.event_class
lin... |
Return the list of handler classes. | def get_event_handler_classes(categories=None):
"""Return the list of handler classes."""
classes = [c for c in all_subclasses(EventHandler) if c not in _ABC_EVHANDLER_CLASSES]
return classes |
Convert obj into a subclass of AbinitEvent.
obj can be either a class or a string with the class name or the YAML tag | def as_event_class(obj):
"""
Convert obj into a subclass of AbinitEvent.
obj can be either a class or a string with the class name or the YAML tag
"""
if is_string(obj):
for c in all_subclasses(AbinitEvent):
if c.__name__ == obj or c.yaml_tag == obj: return c
raise ValueE... |
The baseclass of self. | def baseclass(self):
"""The baseclass of self."""
for cls in _BASE_CLASSES:
if isinstance(self, cls):
return cls
raise ValueError("Cannot determine the base class of %s" % self.__class__.__name__) |
Add an event to the list. | def append(self, event):
"""Add an event to the list."""
self._events.append(event)
self._events_by_baseclass[event.baseclass].append(event) |
Set the value of _run_completed. | def set_run_completed(self, boolean, start_datetime, end_datetime):
"""Set the value of _run_completed."""
self._run_completed = boolean
if (start_datetime, end_datetime) != (None, None):
# start_datetime: Sat Feb 28 23:54:27 2015
# end_datetime: Sat Feb 28 23:54:30 2015... |
Wall-time of the run as `timedelta` object. | def run_etime(self):
"""Wall-time of the run as `timedelta` object."""
if self.start_datetime is None or self.end_datetime is None:
return None
return self.end_datetime - self.start_datetime |
Parse the given file. Return :class:`EventReport`. | def parse(self, filename, verbose=0):
"""
Parse the given file. Return :class:`EventReport`.
"""
run_completed, start_datetime, end_datetime = False, None, None
filename = os.path.abspath(filename)
report = EventReport(filename)
w = WildCard("*Error|*Warning|*Com... |
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception. | def report_exception(self, filename, exc):
"""
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
"""
# Build fake event.
event = AbinitError(src_file="Unknown", src_line=0, mess... |
Return the number of times the event associated to this handler
has been already fixed in the :class:`Task`. | def count(self, task):
"""
Return the number of times the event associated to this handler
has been already fixed in the :class:`Task`.
"""
return len([c for c in task.corrections if c["event"]["@class"] == self.event_class]) |
Sets the stable charges and transition states for a series of
defect entries. This function uses scipy's HalfspaceInterection
to oncstruct the polygons corresponding to defect stability as
a function of the Fermi-level. The Halfspace Intersection
constructs N-dimensional hyperplanes, in ... | def find_stable_charges(self):
"""
Sets the stable charges and transition states for a series of
defect entries. This function uses scipy's HalfspaceInterection
to oncstruct the polygons corresponding to defect stability as
a function of the Fermi-level. The Halfspace Intersectio... |
List all unstable entries (defect+charge) in the DefectPhaseDiagram | def all_unstable_entries(self):
"""
List all unstable entries (defect+charge) in the DefectPhaseDiagram
"""
all_stable_entries = self.all_stable_entries
return [e for e in self.entries if e not in all_stable_entries] |
Give list of all concentrations at specified efermi in the DefectPhaseDiagram
args:
chemical_potentials = {Element: number} is dictionary of chemical potentials to provide formation energies for
temperature = temperature to produce concentrations from
fermi_level: (float) is ... | def defect_concentrations(self, chemical_potentials, temperature=300, fermi_level=0.):
"""
Give list of all concentrations at specified efermi in the DefectPhaseDiagram
args:
chemical_potentials = {Element: number} is dictionary of chemical potentials to provide formation energies fo... |
Suggest possible charges for defects to computee based on proximity
of known transitions from entires to VBM and CBM
Args:
tolerance (float): tolerance with respect to the VBM and CBM to
` continue to compute new charges | def suggest_charges(self, tolerance=0.1):
"""
Suggest possible charges for defects to computee based on proximity
of known transitions from entires to VBM and CBM
Args:
tolerance (float): tolerance with respect to the VBM and CBM to
` continue to... |
Solve for the Fermi energy self-consistently as a function of T
and p_O2
Observations are Defect concentrations, electron and hole conc
Args:
bulk_dos: bulk system dos (pymatgen Dos object)
gap: Can be used to specify experimental gap.
Will be useful if th... | def solve_for_fermi_energy(self, temperature, chemical_potentials, bulk_dos):
"""
Solve for the Fermi energy self-consistently as a function of T
and p_O2
Observations are Defect concentrations, electron and hole conc
Args:
bulk_dos: bulk system dos (pymatgen Dos obje... |
Convert object into Xcfunc. | def asxc(cls, obj):
"""Convert object into Xcfunc."""
if isinstance(obj, cls): return obj
if is_string(obj): return cls.from_name(obj)
raise TypeError("Don't know how to convert <%s:%s> to Xcfunc" % (type(obj), str(obj))) |
Build the object from Abinit ixc (integer) | def from_abinit_ixc(cls, ixc):
"""Build the object from Abinit ixc (integer)"""
ixc = int(ixc)
if ixc >= 0:
return cls(**cls.abinitixc_to_libxc[ixc])
else:
# libxc notation employed in Abinit: a six-digit number in the form XXXCCC or CCCXXX
#ixc = str(... |
Build the object from (type, name). | def from_type_name(cls, typ, name):
"""Build the object from (type, name)."""
# Try aliases first.
for k, nt in cls.defined_aliases.items():
if typ is not None and typ != nt.type: continue
#print(name, nt.name)
if name == nt.name:
if len(k) == ... |
Makes XcFunc obey the general json interface used in pymatgen for easier serialization. | def from_dict(cls, d):
"""
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
"""
return cls(xc=d.get("xc"), x=d.get("x"), c=d.get("c")) |
Makes XcFunc obey the general json interface used in pymatgen for easier serialization. | def as_dict(self):
"""
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
# print("in as_dict", type(self.x), type(self.c), type(self.xc))
i... |
The type of the functional. | def type(self):
"""The type of the functional."""
if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].type
xc = (self.x, self.c)
if xc in self.defined_aliases: return self.defined_aliases[xc].type
# If self is not in defined_aliases, use LibxcFunc family
... |
The name of the functional. If the functional is not found in the aliases,
the string has the form X_NAME+C_NAME | def name(self):
"""
The name of the functional. If the functional is not found in the aliases,
the string has the form X_NAME+C_NAME
"""
if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].name
xc = (self.x, self.c)
if xc in self.defined_alias... |
Returns the voronoi_list needed for the VoronoiContainer object from a bson-encoded voronoi_list (composed of
vlist and bson_nb_voro_list).
:param vlist: List of voronoi objects
:param bson_nb_voro_list: List of periodic sites involved in the Voronoi
:return: The voronoi_list needed for the VoronoiConta... | def from_bson_voronoi_list(bson_nb_voro_list, structure):
"""
Returns the voronoi_list needed for the VoronoiContainer object from a bson-encoded voronoi_list (composed of
vlist and bson_nb_voro_list).
:param vlist: List of voronoi objects
:param bson_nb_voro_list: List of periodic sites involved in... |
Set up of the voronoi list of neighbours by calling qhull
:param indices: indices of the sites for which the Voronoi is needed
:param voronoi_cutoff: Voronoi cutoff for the search of neighbours
:raise RuntimeError: If an infinite vertex is found in the voronoi construction | def setup_voronoi_list(self, indices, voronoi_cutoff):
"""
Set up of the voronoi list of neighbours by calling qhull
:param indices: indices of the sites for which the Voronoi is needed
:param voronoi_cutoff: Voronoi cutoff for the search of neighbours
:raise RuntimeError: If an ... |
Initializes the angle and distance separations
:param indices: indices of the sites for which the Voronoi is needed | def setup_neighbors_distances_and_angles(self, indices):
"""
Initializes the angle and distance separations
:param indices: indices of the sites for which the Voronoi is needed
"""
self.neighbors_distances = [None] * len(self.structure)
self.neighbors_normalized_distances... |
Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable.
:return: [vlist, bson_nb_voro_list], to be used in the as_dict method | def to_bson_voronoi_list2(self):
"""
Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable.
:return: [vlist, bson_nb_voro_list], to be used in the as_dict method
"""
bson_nb_voro_list2 = [None] * len(self.voronoi_list2)
for ivoro, voro in e... |
Bson-serializable dict representation of the VoronoiContainer.
:return: dictionary that is BSON-encodable | def as_dict(self):
"""
Bson-serializable dict representation of the VoronoiContainer.
:return: dictionary that is BSON-encodable
"""
bson_nb_voro_list2 = self.to_bson_voronoi_list2()
return {"@module": self.__class__.__module__,
"@class": self.__class__.__... |
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object | def from_dict(cls, d):
"""
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object
"""
structure = S... |
Decorator for :class:`Node` methods. Raise `SpectatorNodeError`. | def check_spectator(node_method):
"""
Decorator for :class:`Node` methods. Raise `SpectatorNodeError`.
"""
from functools import wraps
@wraps(node_method)
def wrapper(*args, **kwargs):
node = args[0]
if node.in_spectator_mode:
#raise node.SpectatorError("You should no... |
Save the id of the last node created. | def save_lastnode_id():
"""Save the id of the last node created."""
init_counter()
with FileLock(_COUNTER_FILE):
with AtomicFile(_COUNTER_FILE, mode="w") as fh:
fh.write("%d\n" % _COUNTER) |
Convert obj into Status. | def as_status(cls, obj):
"""Convert obj into Status."""
if obj is None: return None
return obj if isinstance(obj, cls) else cls.from_string(obj) |
Return a `Status` instance from its string representation. | def from_string(cls, s):
"""Return a `Status` instance from its string representation."""
for num, text in cls._STATUS2STR.items():
if text == s:
return cls(num)
else:
raise ValueError("Wrong string %s" % s) |
List of output files produces by self. | def products(self):
"""List of output files produces by self."""
_products = []
for ext in self.exts:
prod = Product(ext, self.node.opath_from_ext(ext))
_products.append(prod)
return _products |
This function is called when we specify the task dependencies with the syntax:
deps={node: "@property"}
In this case the task has to the get `property` from `node` before starting the calculation.
At present, the following properties are supported:
- @structure | def apply_getters(self, task):
"""
This function is called when we specify the task dependencies with the syntax:
deps={node: "@property"}
In this case the task has to the get `property` from `node` before starting the calculation.
At present, the following properties are ... |
Returns a dictionary with the variables that must be added to the
input file in order to connect this :class:`Node` to its dependencies. | def connecting_vars(self):
"""
Returns a dictionary with the variables that must be added to the
input file in order to connect this :class:`Node` to its dependencies.
"""
vars = {}
for prod in self.products:
vars.update(prod.connecting_vars())
return... |
Returns the paths of the output files produced by self and its extensions | def get_filepaths_and_exts(self):
"""Returns the paths of the output files produced by self and its extensions"""
filepaths = [prod.filepath for prod in self.products]
exts = [prod.ext for prod in self.products]
return filepaths, exts |
Build a :class:`Product` instance from a filepath. | def from_file(cls, filepath):
"""Build a :class:`Product` instance from a filepath."""
# Find the abinit extension.
for i in range(len(filepath)):
if filepath[i:] in abi_extensions():
ext = filepath[i:]
break
else:
raise ValueError(... |
Initialize an instance of `NodeResults` from a `Node` subclass. | def from_node(cls, node):
"""Initialize an instance of `NodeResults` from a `Node` subclass."""
kwargs = dict(
node_id=node.node_id,
node_finalized=node.finalized,
node_history=list(node.history),
node_name=node.name,
node_class=node.__class__.... |
This function registers the files that will be saved in GridFS.
kwargs is a dictionary mapping the key associated to the file (usually the extension)
to the absolute path. By default, files are assumed to be in binary form, for formatted files
one should pass a tuple ("filepath", "t").
... | def register_gridfs_files(self, **kwargs):
"""
This function registers the files that will be saved in GridFS.
kwargs is a dictionary mapping the key associated to the file (usually the extension)
to the absolute path. By default, files are assumed to be in binary form, for formatted fil... |
Update a mongodb collection. | def update_collection(self, collection):
"""
Update a mongodb collection.
"""
node = self.node
flow = node if node.is_flow else node.flow
# Build the key used to store the entry in the document.
key = node.name
if node.is_task:
key = "w" + str... |
Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet | def color_hex(self):
"""Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet"""
def clamp(x):
return max(0, min(int(x), 255))
r, g, b = np.trunc(self.color_rgb * 255)
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b)) |
Check whether the node is a instance of `class_or_string`.
Unlinke the standard isinstance builtin, the method accepts either a class or a string.
In the later case, the string is compared with self.__class__.__name__ (case insensitive). | def isinstance(self, class_or_string):
"""
Check whether the node is a instance of `class_or_string`.
Unlinke the standard isinstance builtin, the method accepts either a class or a string.
In the later case, the string is compared with self.__class__.__name__ (case insensitive).
... |
Convert obj into a Node instance.
Return:
obj if obj is a Node instance,
cast obj to :class:`FileNode` instance of obj is a string.
None if obj is None | def as_node(cls, obj):
"""
Convert obj into a Node instance.
Return:
obj if obj is a Node instance,
cast obj to :class:`FileNode` instance of obj is a string.
None if obj is None
"""
if isinstance(obj, cls):
return obj
elif... |
The name of the node
(only used for facilitating its identification in the user interface). | def name(self):
"""
The name of the node
(only used for facilitating its identification in the user interface).
"""
try:
return self._name
except AttributeError:
if self.is_task:
try:
return self.pos_str
... |
Return a relative version of the workdir | def relworkdir(self):
"""Return a relative version of the workdir"""
if getattr(self, "workdir", None) is None:
return None
try:
return os.path.relpath(self.workdir)
except OSError:
# current working directory may not be defined!
return sel... |
This method should be called once we have fixed the problem associated to this event.
It adds a new entry in the correction history of the node.
Args:
event: :class:`AbinitEvent` that triggered the correction.
action (str): Human-readable string with info on the action perfomed ... | def log_correction(self, event, action):
"""
This method should be called once we have fixed the problem associated to this event.
It adds a new entry in the correction history of the node.
Args:
event: :class:`AbinitEvent` that triggered the correction.
action (... |
Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"} | def add_deps(self, deps):
"""
Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"}
"""
if isinstan... |
Remove a list of dependencies from the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node. | def remove_deps(self, deps):
"""
Remove a list of dependencies from the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
"""
if not isinstance(deps, (list, tuple)):
deps = [deps]
assert all(... |
Returns a list with the status of the dependencies. | def deps_status(self):
"""Returns a list with the status of the dependencies."""
if not self.deps:
return [self.S_OK]
return [d.status for d in self.deps] |
Return the list of nodes in the :class:`Flow` that depends on this :class:`Node`
.. note::
This routine assumes the entire flow has been allocated. | def get_children(self):
"""
Return the list of nodes in the :class:`Flow` that depends on this :class:`Node`
.. note::
This routine assumes the entire flow has been allocated.
"""
# Specialized branch for FileNode.
if self.is_file:
return self.fi... |
Return the string representation of the dependencies of the node. | def str_deps(self):
"""Return the string representation of the dependencies of the node."""
lines = []
app = lines.append
app("Dependencies of node %s:" % str(self))
for i, dep in enumerate(self.deps):
app("%d) %s, status=%s" % (i, dep.info, str(dep.status)))
... |
Return pandas DataFrame with the value of the variables specified in `varnames`.
Can be used for task/works/flow. It's recursive!
.. example:
flow.get_vars_dataframe("ecut", "ngkpt")
work.get_vars_dataframe("acell", "usepawu") | def get_vars_dataframe(self, *varnames):
"""
Return pandas DataFrame with the value of the variables specified in `varnames`.
Can be used for task/works/flow. It's recursive!
.. example:
flow.get_vars_dataframe("ecut", "ngkpt")
work.get_vars_dataframe("acell", "... |
Generate directory graph in the DOT language. The graph show the files and directories
in the node workdir.
Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph> | def get_graphviz_dirtree(self, engine="automatic", **kwargs):
"""
Generate directory graph in the DOT language. The graph show the files and directories
in the node workdir.
Returns: graphviz.Digraph <https://graphviz.readthedocs.io/en/stable/api.html#digraph>
"""
if eng... |
The list of handlers registered for this node.
If the node is not a `Flow` and does not have its own list of
`handlers` the handlers registered at the level of the flow are returned.
This trick allows one to registered different handlers at the level of the Task
for testing purposes. By... | def event_handlers(self):
"""
The list of handlers registered for this node.
If the node is not a `Flow` and does not have its own list of
`handlers` the handlers registered at the level of the flow are returned.
This trick allows one to registered different handlers at the leve... |
Install the `EventHandlers for this `Node`. If no argument is provided
the default list of handlers is installed.
Args:
categories: List of categories to install e.g. base + can_change_physics
handlers: explicit list of :class:`EventHandler` instances.
This... | def install_event_handlers(self, categories=None, handlers=None):
"""
Install the `EventHandlers for this `Node`. If no argument is provided
the default list of handlers is installed.
Args:
categories: List of categories to install e.g. base + can_change_physics
... |
Print to `stream` the event handlers installed for this flow. | def show_event_handlers(self, stream=sys.stdout, verbose=0):
"""Print to `stream` the event handlers installed for this flow."""
lines = ["List of event handlers installed:"]
for handler in self.event_handlers:
if verbose:
lines.extend(handler.__class__.cls2str().spli... |
Send signal from this node to all connected receivers unless the node is in spectator mode.
signal -- (hashable) signal value, see `dispatcher` connect for details
Return a list of tuple pairs [(receiver, response), ... ]
or None if the node is in spectator mode.
if any receiver raise... | def send_signal(self, signal):
"""
Send signal from this node to all connected receivers unless the node is in spectator mode.
signal -- (hashable) signal value, see `dispatcher` connect for details
Return a list of tuple pairs [(receiver, response), ... ]
or None if the node i... |
Return the message after merging any user-supplied arguments with the message.
Args:
metadata: True if function and module name should be added.
asctime: True if time string should be added. | def get_message(self, metadata=False, asctime=True):
"""
Return the message after merging any user-supplied arguments with the message.
Args:
metadata: True if function and module name should be added.
asctime: True if time string should be added.
"""
msg... |
Returns a string with the history. Set metadata to True to have info on function and module. | def to_string(self, metadata=False):
"""Returns a string with the history. Set metadata to True to have info on function and module."""
return "\n".join(rec.get_message(metadata=metadata) for rec in self) |
Log 'msg % args' with the warning severity level | def warning(self, msg, *args, **kwargs):
"""Log 'msg % args' with the warning severity level"""
self._log("WARNING", msg, args, kwargs) |
Log 'msg % args' with the critical severity level | def critical(self, msg, *args, **kwargs):
"""Log 'msg % args' with the critical severity level"""
self._log("CRITICAL", msg, args, kwargs) |
Low-level logging routine which creates a :class:`HistoryRecord`. | def _log(self, level, msg, args, exc_info=None, extra=None):
"""Low-level logging routine which creates a :class:`HistoryRecord`."""
if exc_info and not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
self.append(HistoryRecord(level, "unknown filename", 0, msg, args, exc_info... |
Parse libxc_docs.txt file, return dictionary with mapping:
libxc_id --> info_dict | def parse_libxc_docs(path):
"""
Parse libxc_docs.txt file, return dictionary with mapping:
libxc_id --> info_dict
"""
def parse_section(section):
d = {}
for l in section:
key, value = l.split(":")
key = key.strip()
d[key] = value.strip()
return int(d["Number"]), d
d = Ordered... |
Main function. | def main():
"""Main function."""
if "-h" in sys.argv or "--help" in sys.argv:
print(__doc__)
print("Usage: regen_libxcfunc.py path_to_libxc_docs.txt")
return 0
try:
path = sys.argv[1]
except IndexError:
print(__doc__)
print("Usage: regen_libxcfunc.py path... |
Write json file with libxc metadata to path jpath. | def write_libxc_docs_json(xcfuncs, jpath):
"""Write json file with libxc metadata to path jpath."""
from copy import deepcopy
xcfuncs = deepcopy(xcfuncs)
# Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable.
for d in xcfuncs.values():
d["Family"] = d["Family"... |
Rotate the camera view.
Args:
axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis.
angle: Angle to rotate by. Defaults to 0. | def rotate_view(self, axis_ind=0, angle=0):
"""
Rotate the camera view.
Args:
axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis.
angle: Angle to rotate by. Defaults to 0.
"""
camera = self.ren.GetActiveCamera()
if axis_ind == 0:
... |
Save render window to an image.
Arguments:
filename:
filename to save to. Defaults to image.png.
magnification:
magnification. Use it to render high res images.
image_format:
choose between jpeg, png. Png is the default. | def write_image(self, filename="image.png", magnification=1,
image_format="png"):
"""
Save render window to an image.
Arguments:
filename:
filename to save to. Defaults to image.png.
magnification:
magnification. Use it... |
Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False. | def redraw(self, reset_camera=False):
"""
Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False.
"""
self.ren.RemoveAllViewProps()
self.picker = None
... |
Display the help for various keyboard shortcuts. | def display_help(self):
"""
Display the help for various keyboard shortcuts.
"""
helptxt = ["h : Toggle help",
"A/a, B/b or C/c : Increase/decrease cell by one a,"
" b or c unit vector", "# : Toggle showing of polyhedrons",
"-: Tog... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.