INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Algorithm for finding the dimensions of connected subunits in a crystal structure.
This method finds the dimensionality of the material even when the material is not layered along low-index planes, or does not have flat layers/molecular wires.
See details at : Cheon, G.; Duerloo, K.-A. N.; Sendek, A. D.; Porter... | def find_dimension(structure_raw, tolerance=0.45, ldict=JmolNN().el_radius, standardize=True):
"""
Algorithm for finding the dimensions of connected subunits in a crystal structure.
This method finds the dimensionality of the material even when the material is not layered along low-index planes, or does not... |
Returns a string with the structure in XSF format
See http://www.xcrysden.org/doc/XSF.html | def to_string(self):
"""
Returns a string with the structure in XSF format
See http://www.xcrysden.org/doc/XSF.html
"""
lines = []
app = lines.append
app("CRYSTAL")
app("# Primitive lattice vectors in Angstrom")
app("PRIMVEC")
cell = self.... |
Initialize a `Structure` object from a string with data in XSF format.
Args:
input_string: String with the structure in XSF format.
See http://www.xcrysden.org/doc/XSF.html
cls_: Structure class to be created. default: pymatgen structure | def from_string(cls, input_string, cls_=None):
"""
Initialize a `Structure` object from a string with data in XSF format.
Args:
input_string: String with the structure in XSF format.
See http://www.xcrysden.org/doc/XSF.html
cls_: Structure class to be cre... |
Returns:
the kpoints along the paths in cartesian coordinates
together with the labels for symmetry points -Wei | def get_kpoints(self, line_density=20, coords_are_cartesian=True):
"""
Returns:
the kpoints along the paths in cartesian coordinates
together with the labels for symmetry points -Wei
"""
list_k_points = []
sym_point_labels = []
for b in self.kpath[... |
Initialize an instance from a :class:`Work` instance. | def from_node(cls, work):
"""Initialize an instance from a :class:`Work` instance."""
new = super().from_node(work)
# Will put all files found in outdir in GridFs
# Warning: assuming binary files.
d = {os.path.basename(f): f for f in work.outdir.list_filepaths()}
new.reg... |
Returns the number of cores reserved in this moment.
A core is reserved if it's still not running but
we have submitted the task to the queue manager. | def ncores_reserved(self):
"""
Returns the number of cores reserved in this moment.
A core is reserved if it's still not running but
we have submitted the task to the queue manager.
"""
return sum(task.manager.num_cores for task in self if task.status == task.S_SUB) |
Returns the number of CPUs allocated in this moment.
A core is allocated if it's running a task or if we have
submitted a task to the queue manager but the job is still pending. | def ncores_allocated(self):
"""
Returns the number of CPUs allocated in this moment.
A core is allocated if it's running a task or if we have
submitted a task to the queue manager but the job is still pending.
"""
return sum(task.manager.num_cores for task in self if task... |
Returns the number of cores used in this moment.
A core is used if there's a job that is running on it. | def ncores_used(self):
"""
Returns the number of cores used in this moment.
A core is used if there's a job that is running on it.
"""
return sum(task.manager.num_cores for task in self if task.status == task.S_RUN) |
Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done. | def fetch_task_to_run(self):
"""
Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done.
"""
# All the tasks are done so raise an exception
# that will be handled by th... |
Connect the signals within the work.
The :class:`Work` is responsible for catching the important signals raised from
its task and raise new signals when some particular condition occurs. | def connect_signals(self):
"""
Connect the signals within the work.
The :class:`Work` is responsible for catching the important signals raised from
its task and raise new signals when some particular condition occurs.
"""
for task in self:
dispatcher.connect(s... |
Disable the signals within the work. This function reverses the process of `connect_signals` | def disconnect_signals(self):
"""
Disable the signals within the work. This function reverses the process of `connect_signals`
"""
for task in self:
try:
dispatcher.disconnect(self.on_ok, signal=task.S_OK, sender=task)
except dispatcher.errors.Disp... |
This callback is called when one task reaches status `S_OK`.
It executes on_all_ok when all tasks in self have reached `S_OK`. | def on_ok(self, sender):
"""
This callback is called when one task reaches status `S_OK`.
It executes on_all_ok when all tasks in self have reached `S_OK`.
"""
logger.debug("in on_ok with sender %s" % sender)
if self.all_ok:
if self.finalized:
... |
Register a Scf task that perform a SCF run first with nsppol = 2 and then nspinor = 2 | def register_collinear_then_noncollinear_scf_task(self, *args, **kwargs):
"""Register a Scf task that perform a SCF run first with nsppol = 2 and then nspinor = 2"""
kwargs["task_class"] = CollinearThenNonCollinearScfTask
return self.register_task(*args, **kwargs) |
Register a Scf task. | def register_scf_task(self, *args, **kwargs):
"""Register a Scf task."""
kwargs["task_class"] = ScfTask
return self.register_task(*args, **kwargs) |
Register a nscf task. | def register_nscf_task(self, *args, **kwargs):
"""Register a nscf task."""
kwargs["task_class"] = NscfTask
return self.register_task(*args, **kwargs) |
Register a task for structural optimization. | def register_relax_task(self, *args, **kwargs):
"""Register a task for structural optimization."""
kwargs["task_class"] = RelaxTask
return self.register_task(*args, **kwargs) |
Register a phonon task. | def register_phonon_task(self, *args, **kwargs):
"""Register a phonon task."""
kwargs["task_class"] = PhononTask
return self.register_task(*args, **kwargs) |
Register an elastic task. | def register_elastic_task(self, *args, **kwargs):
"""Register an elastic task."""
kwargs["task_class"] = ElasticTask
return self.register_task(*args, **kwargs) |
Register a ddk task. | def register_ddk_task(self, *args, **kwargs):
"""Register a ddk task."""
kwargs["task_class"] = DdkTask
return self.register_task(*args, **kwargs) |
Register a screening task. | def register_scr_task(self, *args, **kwargs):
"""Register a screening task."""
kwargs["task_class"] = ScrTask
return self.register_task(*args, **kwargs) |
Register a sigma task. | def register_sigma_task(self, *args, **kwargs):
"""Register a sigma task."""
kwargs["task_class"] = SigmaTask
return self.register_task(*args, **kwargs) |
Register a Dde task. | def register_dde_task(self, *args, **kwargs):
"""Register a Dde task."""
kwargs["task_class"] = DdeTask
return self.register_task(*args, **kwargs) |
Register a Dte task. | def register_dte_task(self, *args, **kwargs):
"""Register a Dte task."""
kwargs["task_class"] = DteTask
return self.register_task(*args, **kwargs) |
Register a BEC task. | def register_bec_task(self, *args, **kwargs):
"""Register a BEC task."""
kwargs["task_class"] = BecTask
return self.register_task(*args, **kwargs) |
Register a Bethe-Salpeter task. | def register_bse_task(self, *args, **kwargs):
"""Register a Bethe-Salpeter task."""
kwargs["task_class"] = BseTask
return self.register_task(*args, **kwargs) |
Register an electron-phonon task. | def register_eph_task(self, *args, **kwargs):
"""Register an electron-phonon task."""
kwargs["task_class"] = EphTask
return self.register_task(*args, **kwargs) |
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
flow.walknset_vars(ecut=10, kptopt=4) | def walknset_vars(self, task_class=None, *args, **kwargs):
"""
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
... |
Set the :class:`TaskManager` to use to launch the :class:`Task`. | def set_manager(self, manager):
"""Set the :class:`TaskManager` to use to launch the :class:`Task`."""
self.manager = manager.deepcopy()
for task in self:
task.set_manager(manager) |
Set the flow associated to this :class:`Work`. | def set_flow(self, flow):
"""Set the flow associated to this :class:`Work`."""
if not hasattr(self, "_flow"):
self._flow = flow
else:
if self._flow != flow:
raise ValueError("self._flow != flow") |
Returns a `Counter` object that counts the number of task with
given status (use the string representation of the status as key). | def status_counter(self):
"""
Returns a `Counter` object that counts the number of task with
given status (use the string representation of the status as key).
"""
counter = collections.Counter()
for task in self:
counter[str(task.status)] += 1
retur... |
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` object or None | def allocate(self, manager=None):
"""
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` ... |
Registers a new :class:`Task` and add it to the internal list, taking into account possible dependencies.
Args:
obj: :class:`AbinitInput` instance or `Task` object.
deps: Dictionary specifying the dependency of this node or list of dependencies
None means that this obj... | def register(self, obj, deps=None, required_files=None, manager=None, task_class=None):
"""
Registers a new :class:`Task` and add it to the internal list, taking into account possible dependencies.
Args:
obj: :class:`AbinitInput` instance or `Task` object.
deps: Dictiona... |
Creates the top level directory. | def build(self, *args, **kwargs):
"""Creates the top level directory."""
# Create the directories of the work.
self.indir.makedirs()
self.outdir.makedirs()
self.tmpdir.makedirs()
# Build dirs and files of each task.
for task in self:
task.build(*args,... |
Returns a list with the status of the tasks in self.
Args:
only_min: If True, the minimum of the status is returned. | def get_all_status(self, only_min=False):
"""
Returns a list with the status of the tasks in self.
Args:
only_min: If True, the minimum of the status is returned.
"""
if len(self) == 0:
# The work will be created in the future.
if only_min:
... |
Check the status of the tasks. | def check_status(self):
"""Check the status of the tasks."""
# Recompute the status of the tasks
# Ignore OK and LOCKED tasks.
for task in self:
if task.status in (task.S_OK, task.S_LOCKED): continue
task.check_status()
# Take into account possible depend... |
Remove all files and directories in the working directory
Args:
exclude_wildcard: Optional string with regular expressions separated by `|`.
Files matching one of the regular expressions will be preserved.
example: exclude_wildard="*.nc|*.txt" preserves all the files... | def rmtree(self, exclude_wildcard=""):
"""
Remove all files and directories in the working directory
Args:
exclude_wildcard: Optional string with regular expressions separated by `|`.
Files matching one of the regular expressions will be preserved.
ex... |
Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.rename() semantics.
Be default, dest is located in the parent... | def move(self, dest, isabspath=False):
"""
Recursively move self.workdir to another location. This is similar to the Unix "mv" command.
The destination path must not already exist. If the destination already exists
but is not a directory, it may be overwritten depending on os.rename() se... |
Submits the task in self and wait.
TODO: change name. | def submit_tasks(self, wait=False):
"""
Submits the task in self and wait.
TODO: change name.
"""
for task in self:
task.start()
if wait:
for task in self: task.wait() |
Start the work. Calls build and _setup first, then submit the tasks.
Non-blocking call unless wait is set to True | def start(self, *args, **kwargs):
"""
Start the work. Calls build and _setup first, then submit the tasks.
Non-blocking call unless wait is set to True
"""
wait = kwargs.pop("wait", False)
# Initial setup
self._setup(*args, **kwargs)
# Build dirs and fil... |
Reads the total energy from the GSR file produced by the task.
Return a numpy array with the total energies in Hartree
The array element is set to np.inf if an exception is raised while reading the GSR file. | def read_etotals(self, unit="Ha"):
"""
Reads the total energy from the GSR file produced by the task.
Return a numpy array with the total energies in Hartree
The array element is set to np.inf if an exception is raised while reading the GSR file.
"""
if not self.all_done... |
Parse the TIMER section reported in the ABINIT output files.
Returns:
:class:`AbinitTimerParser` object | def parse_timers(self):
"""
Parse the TIMER section reported in the ABINIT output files.
Returns:
:class:`AbinitTimerParser` object
"""
filenames = list(filter(os.path.exists, [task.output_file.path for task in self]))
parser = AbinitTimerParser()
pa... |
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure | def plot_ebands(self, **kwargs):
"""
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure
"""
with self.nscf_task.open_gsr() as gsr:
return gsr.ebands.plot(**kwargs) |
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained (note: 0 refers to the first DOS task).
method: String defining the method for the computation of the DOS.
step: Energy step (eV) of the linear mesh.
width... | def plot_ebands_with_edos(self, dos_pos=0, method="gaussian", step=0.01, width=0.1, **kwargs):
"""
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained (note: 0 refers to the first DOS task).
method: String defining ... |
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained.
None is all DOSes should be displayed. Accepts integer or list of integers.
method: String defining the method for the computation of the DOS.
st... | def plot_edoses(self, dos_pos=None, method="gaussian", step=0.01, width=0.1, **kwargs):
"""
Plot the band structure and the DOS.
Args:
dos_pos: Index of the task from which the DOS should be obtained.
None is all DOSes should be displayed. Accepts integer or lis... |
This callback is called when one task reaches status S_OK.
If sender == self.ion_task, we update the initial structure
used by self.ioncell_task and we unlock it so that the job can be submitted. | def on_ok(self, sender):
"""
This callback is called when one task reaches status S_OK.
If sender == self.ion_task, we update the initial structure
used by self.ioncell_task and we unlock it so that the job can be submitted.
"""
logger.debug("in on_ok with sender %s" % se... |
Plot the history of the ion-cell relaxation.
kwargs are passed to the plot method of :class:`HistFile`
Return `matplotlib` figure or None if hist file is not found. | def plot_ion_relaxation(self, **kwargs):
"""
Plot the history of the ion-cell relaxation.
kwargs are passed to the plot method of :class:`HistFile`
Return `matplotlib` figure or None if hist file is not found.
"""
with self.ion_task.open_hist() as hist:
retur... |
Plot the history of the ion-cell relaxation.
kwargs are passed to the plot method of :class:`HistFile`
Return `matplotlib` figure or None if hist file is not found. | def plot_ioncell_relaxation(self, **kwargs):
"""
Plot the history of the ion-cell relaxation.
kwargs are passed to the plot method of :class:`HistFile`
Return `matplotlib` figure or None if hist file is not found.
"""
with self.ioncell_task.open_hist() as hist:
... |
Builds and returns a :class:`MdfRobot` for analyzing the results in the MDF files. | def get_mdf_robot(self):
"""Builds and returns a :class:`MdfRobot` for analyzing the results in the MDF files."""
from abilab.robots import MdfRobot
robot = MdfRobot()
for task in self[2:]:
mdf_path = task.outdir.has_abiext(robot.EXT)
if mdf_path:
... |
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. | def create_tasks(self, wfk_file, scr_input):
"""
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation.
"""
assert len(self) ... |
This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`.
If remove_scrfiles is True, the partial SCR files are removed after the merge. | def merge_scrfiles(self, remove_scrfiles=True):
"""
This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`.
If remove_scrfiles is True, the partial SCR files are... |
This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`. | def on_all_ok(self):
"""
This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`.
"""
final_scr = self.merge_scrfiles()
return self.Results(node=s... |
Build tasks for the computation of Born effective charges and add them to the work.
Args:
scf_task: ScfTask object.
ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run.
None to use AbiPy default.
ph_tolerance: dict {"varname": value}... | def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance):
"""
Build tasks for the computation of Born effective charges and add them to the work.
Args:
scf_task: ScfTask object.
ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run.... |
This method is called when all the q-points have been computed.
It runs `mrgddb` in sequential on the local machine to produce
the final DDB file in the outdir of the `Work`.
Args:
delete_source_ddbs: True if input DDB should be removed once final DDB is created.
only_df... | def merge_ddb_files(self, delete_source_ddbs=True, only_dfpt_tasks=True,
exclude_tasks=None, include_tasks=None):
"""
This method is called when all the q-points have been computed.
It runs `mrgddb` in sequential on the local machine to produce
the final DDB file ... |
This method is called when all the q-points have been computed.
It runs `mrgdvdb` in sequential on the local machine to produce
the final DVDB file in the outdir of the `Work`.
Args:
delete_source: True if POT1 files should be removed after (successful) merge.
Returns:
... | def merge_pot1_files(self, delete_source=True):
"""
This method is called when all the q-points have been computed.
It runs `mrgdvdb` in sequential on the local machine to produce
the final DVDB file in the outdir of the `Work`.
Args:
delete_source: True if POT1 file... |
Construct a `PhononWork` from a :class:`ScfTask` object.
The input file for phonons is automatically generated from the input of the ScfTask.
Each phonon task depends on the WFK file produced by the `scf_task`.
Args:
scf_task: ScfTask object.
qpoints: q-points in reduced... | def from_scf_task(cls, scf_task, qpoints, is_ngqpt=False, tolerance=None, with_becs=False,
ddk_tolerance=None, manager=None):
"""
Construct a `PhononWork` from a :class:`ScfTask` object.
The input file for phonons is automatically generated from the input of the ScfTask.
... |
Similar to `from_scf_task`, the difference is that this method requires
an input for SCF calculation. A new ScfTask is created and added to the Work.
This API should be used if the DDB of the GS task should be merged. | def from_scf_input(cls, scf_input, qpoints, is_ngqpt=False, tolerance=None,
with_becs=False, ddk_tolerance=None, manager=None):
"""
Similar to `from_scf_task`, the difference is that this method requires
an input for SCF calculation. A new ScfTask is created and added to t... |
Construct a `PhononWfkqWork` from a :class:`ScfTask` object.
The input files for WFQ and phonons are automatically generated from the input of the ScfTask.
Each phonon task depends on the WFK file produced by scf_task and the associated WFQ file.
Args:
scf_task: ScfTask object.
... | def from_scf_task(cls, scf_task, ngqpt, ph_tolerance=None, tolwfr=1.0e-22, nband=None,
with_becs=False, ddk_tolerance=None, shiftq=(0, 0, 0), is_ngqpt=True, remove_wfkq=True,
manager=None):
"""
Construct a `PhononWfkqWork` from a :class:`ScfTask` object.
... |
This callback is called when one task reaches status `S_OK`.
It removes the WFKQ file if all its children have reached `S_OK`. | def on_ok(self, sender):
"""
This callback is called when one task reaches status `S_OK`.
It removes the WFKQ file if all its children have reached `S_OK`.
"""
if self.remove_wfkq:
for task in self.wfkq_tasks:
if task.status != task.S_OK: continue
... |
Construct a `PhononWfkqWork` from a DDB and DVDB file.
For each q found, a WFQ task and an EPH task computing the matrix elements are created. | def from_den_ddb_dvdb(cls, inp, den_path, ddb_path, dvdb_path, mpiprocs=1, remove_wfkq=True,
qpath=None, with_ddk=True, expand=True, manager=None):
"""
Construct a `PhononWfkqWork` from a DDB and DVDB file.
For each q found, a WFQ task and an EPH task computing the matr... |
Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands | def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=True, manager=None):
"""
Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands
"""
# Get list of qpoints f... |
This callback is called when one task reaches status `S_OK`.
It removes the WFKQ file if all its children have reached `S_OK`. | def on_ok(self, sender):
"""
This callback is called when one task reaches status `S_OK`.
It removes the WFKQ file if all its children have reached `S_OK`.
"""
if self.remove_wfkq:
for task in self.wfkq_tasks:
if task.status != task.S_OK: continue
... |
Build tasks for the computation of Born effective charges from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default.
ph_tolerance: dict {"varname": value} with the tolerance used in the phon... | def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None):
"""
Build tasks for the computation of Born effective charges from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None ... |
This method is called when all tasks reach S_OK
Ir runs `mrgddb` in sequential on the local machine to produce
the final DDB file in the outdir of the `Work`. | def on_all_ok(self):
"""
This method is called when all tasks reach S_OK
Ir runs `mrgddb` in sequential on the local machine to produce
the final DDB file in the outdir of the `Work`.
"""
# Merge DDB files.
out_ddb = self.merge_ddb_files()
return self.Resu... |
Build a DteWork from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default.
manager: :class:`TaskManager` object. | def from_scf_task(cls, scf_task, ddk_tolerance=None, manager=None):
"""
Build a DteWork from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default.
manager: :class:`TaskManager` obje... |
this takes a Interstitial defect object and generates the
sublattice for it based on the structure's space group.
Useful for understanding multiplicity of an interstitial
defect in thermodynamic analysis.
NOTE: if large relaxation happens to interstitial or
defect involves a complex then there ... | def create_saturated_interstitial_structure( interstitial_def, dist_tol=0.1):
"""
this takes a Interstitial defect object and generates the
sublattice for it based on the structure's space group.
Useful for understanding multiplicity of an interstitial
defect in thermodynamic analysis.
NOTE: if... |
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... |
Returns the multiplicity of a defect site within the structure (needed for concentration analysis) | def multiplicity(self):
"""
Returns the multiplicity of a defect site within the structure (needed for concentration analysis)
"""
sga = SpacegroupAnalyzer(self.bulk_structure)
periodic_struc = sga.get_symmetrized_structure()
poss_deflist = sorted(
periodic_st... |
Returns Defective Substitution structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Substitution structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... |
Returns a name for this defect | def name(self):
"""
Returns a name for this defect
"""
poss_deflist = sorted(
self.bulk_structure.get_sites_in_sphere(self.site.coords, 2, include_index=True), key=lambda x: x[1])
defindex = poss_deflist[0][2]
return "Sub_{}_on_{}_mult{}".format(self.site.spec... |
Returns Defective Interstitial structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Interstitial structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... |
Returns the multiplicity of a defect site within the structure (needed for concentration analysis) | def multiplicity(self):
"""
Returns the multiplicity of a defect site within the structure (needed for concentration analysis)
"""
if self._multiplicity is None:
# generate multiplicity based on space group symmetry operations performed on defect coordinates
try:
... |
Returns a name for this defect | def name(self):
"""
Returns a name for this defect
"""
if self.site_name:
return "Int_{}_{}_mult{}".format(self.site.specie, self.site_name, self.multiplicity)
else:
return "Int_{}_mult{}".format(self.site.specie, self.multiplicity) |
Json-serializable dict representation of DefectEntry | def as_dict(self):
"""
Json-serializable dict representation of DefectEntry
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"defect": self.defect.as_dict(),
"uncorrected_energy": self.uncorrected_energy,
... |
Reconstitute a DefectEntry object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of DefectEntry.
Returns:
DefectEntry object | def from_dict(cls, d):
"""
Reconstitute a DefectEntry object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of DefectEntry.
Returns:
DefectEntry object
"""
defect = MontyDecoder().process_decoded( ... |
Returns the *corrected* energy of the entry | def energy(self):
"""
Returns the *corrected* energy of the entry
"""
return self.uncorrected_energy + np.sum(list(self.corrections.values())) |
Computes the formation energy for a defect taking into account a given chemical potential and fermi_level | def formation_energy(self, chemical_potentials=None, fermi_level=0):
"""
Computes the formation energy for a defect taking into account a given chemical potential and fermi_level
"""
chemical_potentials = chemical_potentials if chemical_potentials else {}
chempot_correction = su... |
Get the defect concentration for a temperature and Fermi level.
Args:
temperature:
the temperature in K
fermi_level:
the fermi level in eV (with respect to the VBM)
Returns:
defects concentration in cm^-3 | def defect_concentration(self, chemical_potentials, temperature=300, fermi_level=0.0):
"""
Get the defect concentration for a temperature and Fermi level.
Args:
temperature:
the temperature in K
fermi_level:
the fermi level in eV (with resp... |
Corrects a single entry.
Args:
entry: A DefectEntry object.
Returns:
An processed entry.
Raises:
CompatibilityError if entry is not compatible. | def correct_entry(self, entry):
"""
Corrects a single entry.
Args:
entry: A DefectEntry object.
Returns:
An processed entry.
Raises:
CompatibilityError if entry is not compatible.
"""
entry.correction.update(self.get_correcti... |
Convenience method to run Bader analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temporary reference
file as AECCAR0 + AECCAR2
3. Runs B... | def bader_analysis_from_path(path, suffix=''):
"""
Convenience method to run Bader analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temp... |
Convenience method to run Bader analysis from a set
of pymatgen Chgcar and Potcar objects.
This method will:
1. If aeccar objects are present, constructs a temporary reference
file as AECCAR0 + AECCAR2
2. Runs Bader analysis twice: once for charge, and a second time
for the charge difference (... | def bader_analysis_from_objects(chgcar, potcar=None, aeccar0=None, aeccar2=None):
"""
Convenience method to run Bader analysis from a set
of pymatgen Chgcar and Potcar objects.
This method will:
1. If aeccar objects are present, constructs a temporary reference
file as AECCAR0 + AECCAR2
2.... |
Returns the charge transferred for a particular atom. Requires POTCAR
to be supplied.
Args:
atom_index:
Index of atom.
Returns:
Charge transfer associated with atom from the Bader analysis.
Given by final charge on atom - nelectrons in POTCAR... | def get_charge_transfer(self, atom_index):
"""
Returns the charge transferred for a particular atom. Requires POTCAR
to be supplied.
Args:
atom_index:
Index of atom.
Returns:
Charge transfer associated with atom from the Bader analysis.
... |
Returns an oxidation state decorated structure.
Returns:
Returns an oxidation state decorated structure. Requires POTCAR
to be supplied. | def get_oxidation_state_decorated_structure(self):
"""
Returns an oxidation state decorated structure.
Returns:
Returns an oxidation state decorated structure. Requires POTCAR
to be supplied.
"""
structure = self.chgcar.structure
charges = [-self.... |
Convenient constructor that takes in the path name of VASP run
to perform Bader analysis.
Args:
path (str): Name of directory where VASP output files are
stored.
suffix (str): specific suffix to look for (e.g. '.relax1'
for 'CHGCAR.relax1.gz'). | def from_path(cls, path, suffix=""):
"""
Convenient constructor that takes in the path name of VASP run
to perform Bader analysis.
Args:
path (str): Name of directory where VASP output files are
stored.
suffix (str): specific suffix to look for (e... |
return the derivatives of y(x) at the points x
if scipy is available a spline is generated to calculate the derivatives
if scipy is not available the left and right slopes are calculated, if both exist the average is returned
putting fd to zero always returns the finite difference slopes | def get_derivatives(xs, ys, fd=False):
"""
return the derivatives of y(x) at the points x
if scipy is available a spline is generated to calculate the derivatives
if scipy is not available the left and right slopes are calculated, if both exist the average is returned
putting fd to zero always retur... |
reciprocal function to the power n to fit convergence data | def reciprocal(x, a, b, n):
"""
reciprocal function to the power n to fit convergence data
"""
if n < 1:
n = 1
elif n > 5:
n = 5
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / x_v ** n)
y = np.array(y_l)
else:
y =... |
predictor for first guess for reciprocal | def p0_reciprocal(xs, ys):
"""
predictor for first guess for reciprocal
"""
a0 = ys[len(ys) - 1]
b0 = ys[0]*xs[0] - a0*xs[0]
return [a0, b0, 1] |
reciprocal function to fit convergence data | def single_reciprocal(x, a, b, c):
"""
reciprocal function to fit convergence data
"""
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / (x_v - c))
y = np.array(y_l)
else:
y = a + b / (x - c)
return y |
reciprocal function to fit convergence data | def simple_reciprocal(x, a, b):
"""
reciprocal function to fit convergence data
"""
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / x_v)
y = np.array(y_l)
else:
y = a + b / x
return y |
return the parameters such that a + b / x^n hits the last two data points | def extrapolate_reciprocal(xs, ys, n, noise):
"""
return the parameters such that a + b / x^n hits the last two data points
"""
if len(xs) > 4 and noise:
y1 = (ys[-3] + ys[-4]) / 2
y2 = (ys[-1] + ys[-2]) / 2
x1 = (xs[-3] + xs[-4]) / 2
x2 = (xs[-1] + xs[-2]) / 2
tr... |
measure the quality of a fit | def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n]
elif len(popt) == 3:
m += (ys[n] - func... |
fit multiple functions to the x, y data, return the best fit | def multi_curve_fit(xs, ys, verbose):
"""
fit multiple functions to the x, y data, return the best fit
"""
#functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal}
functions = {
exponential: p0_exponential,
reciprocal: p0_reciproc... |
Calculates for a series of powers ns the parameters for which the last two points are at the curve.
With these parameters measure how well the other data points fit.
return the best fit. | def multi_reciprocal_extra(xs, ys, noise=False):
"""
Calculates for a series of powers ns the parameters for which the last two points are at the curve.
With these parameters measure how well the other data points fit.
return the best fit.
"""
ns = np.linspace(0.5, 6.0, num=56)
best = ['', n... |
print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters | def print_plot_line(function, popt, xs, ys, name, tol=0.05, extra=''):
"""
print the gnuplot command line to plot the x, y data with the fitted function using the popt parameters
"""
idp = id_generator()
f = open('convdat.'+str(idp), mode='w')
for n in range(0, len(ys), 1):
f.write(str(x... |
test it and at which x_value dy(x)/dx < tol for all x >= x_value, conv is true is such a x_value exists. | def determine_convergence(xs, ys, name, tol=0.0001, extra='', verbose=False, mode='extra', plots=True):
"""
test it and at which x_value dy(x)/dx < tol for all x >= x_value, conv is true is such a x_value exists.
"""
if len(xs) != len(ys):
raise RuntimeError('the range of x and y are not equal')... |
Lists prime factors of a given natural integer, from greatest to smallest
:param n: Natural integer
:rtype : list of all prime factors of the given natural n | def prime_factors(n):
"""Lists prime factors of a given natural integer, from greatest to smallest
:param n: Natural integer
:rtype : list of all prime factors of the given natural n
"""
i = 2
while i <= sqrt(n):
if n % i == 0:
l = prime_factors(n/i)
l.append(i)
... |
From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return: | def _factor_generator(n):
"""
From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return:
"""
p = prime_factors(n)
factors = {}
for p1 in p:
try:
factors[p1] += 1
except KeyError:
factors[p1] = ... |
From a given natural integer, returns the list of divisors in ascending order
:param n: Natural integer
:return: List of divisors of n in ascending order | def divisors(n):
"""
From a given natural integer, returns the list of divisors in ascending order
:param n: Natural integer
:return: List of divisors of n in ascending order
"""
factors = _factor_generator(n)
_divisors = []
listexponents = [[k**x for x in range(0, factors[k]+1)] for k i... |
Given a tuple of tuples, generate a delimited string form.
>>> results = [["a","b","c"],["d","e","f"],[1,2,3]]
>>> print(str_delimited(results,delimiter=","))
a,b,c
d,e,f
1,2,3
Args:
result: 2d sequence of arbitrary types.
header: optional header
Returns:
Aligned st... | def str_delimited(results, header=None, delimiter="\t"):
"""
Given a tuple of tuples, generate a delimited string form.
>>> results = [["a","b","c"],["d","e","f"],[1,2,3]]
>>> print(str_delimited(results,delimiter=","))
a,b,c
d,e,f
1,2,3
Args:
result: 2d sequence of arbitrary ty... |
This function is used to make pretty formulas by formatting the amounts.
Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4.
Args:
afloat (float): a float
ignore_ones (bool): if true, floats of 1 are ignored.
tol (float): Tolerance to round to nearest int. i.e. 2.0000000001 -> 2
Ret... | def formula_double_format(afloat, ignore_ones=True, tol=1e-8):
"""
This function is used to make pretty formulas by formatting the amounts.
Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4.
Args:
afloat (float): a float
ignore_ones (bool): if true, floats of 1 are ignored.
tol ... |
Generates a formula with unicode subscripts, e.g. Fe2O3 is transformed
to Fe₂O₃. Does not support formulae with decimal points.
:param formula:
:return: | def unicodeify(formula):
"""
Generates a formula with unicode subscripts, e.g. Fe2O3 is transformed
to Fe₂O₃. Does not support formulae with decimal points.
:param formula:
:return:
"""
if '.' in formula:
raise ValueError('No unicode character exists for subscript period.')
su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.