INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
A function to order the phonon eigenvectors taken from phonopy | def estimate_band_connection(prev_eigvecs, eigvecs, prev_band_order):
"""
A function to order the phonon eigenvectors taken from phonopy
"""
metric = np.abs(np.dot(prev_eigvecs.conjugate().T, eigvecs))
connection_order = []
for overlaps in metric:
maxval = 0
for i in reversed(ran... |
Returns the point where the minimum frequency is reached and its value | def min_freq(self):
"""
Returns the point where the minimum frequency is reached and its value
"""
i = np.unravel_index(np.argmin(self.bands), self.bands.shape)
return self.qpoints[i[1]], self.bands[i] |
Returns the nac_frequencies for the given direction ( not necessarily a versor ). None if the direction is not present or nac_frequencies has not been calculated. | def get_nac_frequencies_along_dir(self, direction):
"""
Returns the nac_frequencies for the given direction (not necessarily a versor).
None if the direction is not present or nac_frequencies has not been calculated.
Args:
direction: the direction as a list of 3 elements
... |
Returns the nac_eigendisplacements for the given direction ( not necessarily a versor ). None if the direction is not present or nac_eigendisplacements has not been calculated. | def get_nac_eigendisplacements_along_dir(self, direction):
"""
Returns the nac_eigendisplacements for the given direction (not necessarily a versor).
None if the direction is not present or nac_eigendisplacements has not been calculated.
Args:
direction: the direction as a l... |
Returns the breaking of the acoustic sum rule for the three acoustic modes if Gamma is present. None otherwise. If eigendisplacements are available they are used to determine the acoustic modes: selects the bands corresponding to the eigendisplacements that represent to a translation within tol_eigendisplacements. If t... | def asr_breaking(self, tol_eigendisplacements=1e-5):
"""
Returns the breaking of the acoustic sum rule for the three acoustic modes,
if Gamma is present. None otherwise.
If eigendisplacements are available they are used to determine the acoustic
modes: selects the bands correspon... |
Returns the list of qpoint indices equivalent ( meaning they are the same frac coords ) to the given one. | def get_equivalent_qpoints(self, index):
"""
Returns the list of qpoint indices equivalent (meaning they are the
same frac coords) to the given one.
Args:
index: the qpoint index
Returns:
a list of equivalent indices
TODO: now it uses the label ... |
Returns in what branch ( es ) is the qpoint. There can be several branches. | def get_branch(self, index):
"""
Returns in what branch(es) is the qpoint. There can be several
branches.
Args:
index: the qpoint index
Returns:
A list of dictionaries [{"name","start_index","end_index","index"}]
indicating all branches in wh... |
Write a json file for the phononwebsite: http:// henriquemiranda. github. io/ phononwebsite | def write_phononwebsite(self,filename):
"""
Write a json file for the phononwebsite:
http://henriquemiranda.github.io/phononwebsite
"""
import json
with open(filename,'w') as f:
phononwebsite_json = json.dump(self.as_phononwebsite(),f) |
Return a dictionary with the phononwebsite format: http:// henriquemiranda. github. io/ phononwebsite | def as_phononwebsite(self):
"""
Return a dictionary with the phononwebsite format:
http://henriquemiranda.github.io/phononwebsite
"""
d = {}
#define the lattice
d["lattice"] = self.structure.lattice._matrix.tolist()
#define atoms
atom_pos_c... |
Re - order the eigenvalues according to the similarity of the eigenvectors | def band_reorder(self):
"""
Re-order the eigenvalues according to the similarity of the eigenvectors
"""
eiv = self.eigendisplacements
eig = self.bands
nphonons,nqpoints = self.bands.shape
order = np.zeros([nqpoints,nphonons],dtype=int)
order[0] = np.... |
Batch write vasp input for a sequence of transformed structures to output_dir following the format output_dir/ { group }/ { formula } _ { number }. | def batch_write_vasp_input(transformed_structures, vasp_input_set=MPRelaxSet,
output_dir=".", create_directory=True,
subfolder=None,
include_cif=False, **kwargs):
"""
Batch write vasp input for a sequence of transformed structures ... |
Helper method for multiprocessing of apply_transformation. Must not be in the class so that it can be pickled. | def _apply_transformation(inputs):
"""
Helper method for multiprocessing of apply_transformation. Must not be
in the class so that it can be pickled.
Args:
inputs: Tuple containing the transformed structure, the transformation
to be applied, a boolean indicating whether to extend th... |
Appends a transformation to all TransformedStructures. | def append_transformation(self, transformation, extend_collection=False,
clear_redo=True):
"""
Appends a transformation to all TransformedStructures.
Args:
transformation: Transformation to append
extend_collection: Whether to use more than ... |
Applies a structure_filter to the list of TransformedStructures in the transmuter. | def apply_filter(self, structure_filter):
"""
Applies a structure_filter to the list of TransformedStructures
in the transmuter.
Args:
structure_filter: StructureFilter to apply.
"""
def test_transformed_structure(ts):
return structure_filter.tes... |
Add parameters to the transmuter. Additional parameters are stored in the as_dict () output. | def set_parameter(self, key, value):
"""
Add parameters to the transmuter. Additional parameters are stored in
the as_dict() output.
Args:
key: The key for the parameter.
value: The value for the parameter.
"""
for x in self.transformed_structures... |
Method is overloaded to accept either a list of transformed structures or transmuter it which case it appends the second transmuter s structures. | def append_transformed_structures(self, tstructs_or_transmuter):
"""
Method is overloaded to accept either a list of transformed structures
or transmuter, it which case it appends the second transmuter"s
structures.
Args:
tstructs_or_transmuter: A list of transformed... |
Alternative constructor from structures rather than TransformedStructures. | def from_structures(structures, transformations=None, extend_collection=0):
"""
Alternative constructor from structures rather than
TransformedStructures.
Args:
structures: Sequence of structures
transformations: New transformations to be applied to all
... |
Generates a TransformedStructureCollection from a cif possibly containing multiple structures. | def from_filenames(filenames, transformations=None, primitive=True,
extend_collection=False):
"""
Generates a TransformedStructureCollection from a cif, possibly
containing multiple structures.
Args:
filenames: List of strings of the cif files
... |
Convenient constructor to generates a POSCAR transmuter from a list of POSCAR filenames. | def from_filenames(poscar_filenames, transformations=None,
extend_collection=False):
"""
Convenient constructor to generates a POSCAR transmuter from a list of
POSCAR filenames.
Args:
poscar_filenames: List of POSCAR filenames
transformatio... |
Parse the section with the SCF cycle | def _magic_parser(stream, magic):
"""
Parse the section with the SCF cycle
Returns:
dict where the key are the name of columns and
the values are list of numbers. Note if no section was found.
.. warning::
The parser is very fragile and should be replaced by YAML.
"""
... |
Read the K - points from file. | def yaml_read_kpoints(filename, doc_tag="!Kpoints"):
"""Read the K-points from file."""
with YamlTokenizer(filename) as r:
doc = r.next_doc_with_tag(doc_tag)
d = yaml.safe_load(doc.text_notag)
return np.array(d["reduced_coordinates_of_qpoints"]) |
Read the list of irreducible perturbations from file. | def yaml_read_irred_perts(filename, doc_tag="!IrredPerts"):
"""Read the list of irreducible perturbations from file."""
with YamlTokenizer(filename) as r:
doc = r.next_doc_with_tag(doc_tag)
d = yaml.safe_load(doc.text_notag)
return [AttrDict(**pert) for pert in d["irred_perts"]] |
String representation. | def to_string(self, verbose=0):
"""String representation."""
rows = [[it + 1] + list(map(str, (self[k][it] for k in self.keys())))
for it in range(self.num_iterations)]
return tabulate(rows, headers=["Iter"] + list(self.keys())) |
Read the first occurrence of ScfCycle from stream. | def from_stream(cls, stream):
"""
Read the first occurrence of ScfCycle from stream.
Returns:
None if no `ScfCycle` entry is found.
"""
fields = _magic_parser(stream, magic=cls.MAGIC)
if fields:
fields.pop("iter")
return cls(fields)
... |
Add new cycle to the plotter with label label. | def add_label_cycle(self, label, cycle):
"""Add new cycle to the plotter with label `label`."""
self.labels.append(label)
self.cycles.append(cycle) |
Compare multiple cycels on a grid: one subplot per quantity all cycles on the same subplot. | def combiplot(self, fontsize=8, **kwargs):
"""
Compare multiple cycels on a grid: one subplot per quantity,
all cycles on the same subplot.
Args:
fontsize: Legend fontsize.
"""
ax_list = None
for i, (label, cycle) in enumerate(self.items()):
... |
Produce slides show of the different cycles. One plot per cycle. | def slideshow(self, **kwargs):
"""
Produce slides show of the different cycles. One plot per cycle.
"""
for label, cycle in self.items():
cycle.plot(title=label, tight_layout=True) |
String representation. | def to_string(self, verbose=0):
"""String representation."""
lines = []
app = lines.append
for i, cycle in enumerate(self):
app("")
app("RELAXATION STEP: %d" % (i + 1))
app(cycle.to_string(verbose=verbose))
return "\n".join(lines) |
Extract data from stream. Returns None if some error occurred. | def from_stream(cls, stream):
"""
Extract data from stream. Returns None if some error occurred.
"""
cycles = []
while True:
scf_cycle = GroundStateScfCycle.from_stream(stream)
if scf_cycle is None: break
cycles.append(scf_cycle)
retur... |
Ordered Dictionary of lists with the evolution of the data as function of the relaxation step. | def history(self):
"""
Ordered Dictionary of lists with the evolution of
the data as function of the relaxation step.
"""
history = OrderedDict()
for cycle in self:
d = cycle.last_iteration
for k, v in d.items():
if k in history:
... |
Uses matplotlib to plot the evolution of the structural relaxation. | def slideshow(self, **kwargs):
"""
Uses matplotlib to plot the evolution of the structural relaxation.
Args:
ax_list: List of axes. If None a new figure is produced.
Returns:
`matplotlib` figure
"""
for i, cycle in enumerate(self.cycles):
... |
Plot relaxation history i. e. the results of the last iteration of each SCF cycle. | def plot(self, ax_list=None, fontsize=12, **kwargs):
"""
Plot relaxation history i.e. the results of the last iteration of each SCF cycle.
Args:
ax_list: List of axes. If None a new figure is produced.
fontsize: legend fontsize.
kwargs: keyword arguments are ... |
seek ( offset [ whence ] ) - > None. Move to new file position. | def seek(self, offset, whence=0):
"""
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, p... |
Returns the first YAML document in stream. | def next(self):
"""
Returns the first YAML document in stream.
.. warning::
Assume that the YAML document are closed explicitely with the sentinel '...'
"""
in_doc, lines, doc_tag = None, [], None
for i, line in enumerate(self.stream):
self.line... |
Returns the next document with the specified tag. Empty string is no doc is found. | def next_doc_with_tag(self, doc_tag):
"""
Returns the next document with the specified tag. Empty string is no doc is found.
"""
while True:
try:
doc = next(self)
if doc.tag == doc_tag:
return doc
except StopIte... |
Returns all the documents with the specified tag. | def all_docs_with_tag(self, doc_tag):
"""
Returns all the documents with the specified tag.
"""
docs = []
while True:
try:
doc = self.next_doc_with(doc_tag)
docs.append(doc)
except StopIteration:
break
... |
Returns the YAML text without the tag. Useful if we don t have any constructor registered for the tag ( we used the tag just to locate the document ). | def text_notag(self):
"""
Returns the YAML text without the tag.
Useful if we don't have any constructor registered for the tag
(we used the tag just to locate the document).
"""
if self.tag is not None:
return self.text.replace(self.tag, "")
else:
... |
Execute the executable in a subprocess inside workdir. | def _execute(self, workdir, with_mpirun=False, exec_args=None):
"""
Execute the executable in a subprocess inside workdir.
Some executables fail if we try to launch them with mpirun.
Use with_mpirun=False to run the binary without it.
"""
qadapter = self.manager.qadapter... |
Execute mrgscr inside directory workdir to merge files_to_merge. Produce new file with prefix out_prefix | def merge_qpoints(self, workdir, files_to_merge, out_prefix):
"""
Execute mrgscr inside directory `workdir` to merge `files_to_merge`.
Produce new file with prefix `out_prefix`
"""
# We work with absolute paths.
files_to_merge = [os.path.abspath(s) for s in list_strings(f... |
Merge GGK files return the absolute path of the new database. | def merge(self, workdir, gswfk_file, dfpt_files, gkk_files, out_gkk, binascii=0):
"""
Merge GGK files, return the absolute path of the new database.
Args:
gswfk_file: Ground-state WFK filename
dfpt_files: List of 1WFK files to merge.
gkk_files: List of GKK fi... |
Merge DDB file return the absolute path of the new database in workdir. | def merge(self, workdir, ddb_files, out_ddb, description, delete_source_ddbs=True):
"""Merge DDB file, return the absolute path of the new database in workdir."""
# We work with absolute paths.
ddb_files = [os.path.abspath(s) for s in list_strings(ddb_files)]
if not os.path.isabs(out_ddb... |
Merge POT files containing 1st order DFPT potential return the absolute path of the new database in workdir. | def merge(self, workdir, pot_files, out_dvdb, delete_source=True):
"""
Merge POT files containing 1st order DFPT potential
return the absolute path of the new database in workdir.
Args:
delete_source: True if POT1 files should be removed after (successful) merge.
"""... |
Runs cut3d with a Cut3DInput | def cut3d(self, cut3d_input, workdir):
"""
Runs cut3d with a Cut3DInput
Args:
cut3d_input: a Cut3DInput object.
workdir: directory where cut3d is executed.
Returns:
(string) absolute path to the standard output of the cut3d execution.
(st... |
Convenience method to run critic2 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 critic2 analysis twice: once for... | def from_path(cls, path, suffix=''):
"""
Convenience method to run critic2 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,... |
Most meaningful for bond critical points can be physically interpreted as e. g. degree of pi - bonding in organic molecules. Consult literature for more information.: return: | def ellipticity(self):
'''
Most meaningful for bond critical points,
can be physically interpreted as e.g. degree
of pi-bonding in organic molecules. Consult
literature for more information.
:return:
'''
eig = np.linalg.eig(self.field_hessian)
eig.... |
A StructureGraph object describing bonding information in the crystal. Lazily constructed. | def structure_graph(self, edge_weight="bond_length", edge_weight_units="Å"):
"""
A StructureGraph object describing bonding information
in the crystal. Lazily constructed.
:param edge_weight: a value to store on the Graph edges,
by default this is "bond_length" but other support... |
Add information about a node describing a critical point. | def _add_node(self, idx, unique_idx, frac_coords):
"""
Add information about a node describing a critical point.
:param idx: unique index
:param unique_idx: index of unique CriticalPoint,
used to look up more information of point (field etc.)
:param frac_coord: fractiona... |
Add information about an edge linking two critical points. | def _add_edge(self, idx, from_idx, from_lvec, to_idx, to_lvec):
"""
Add information about an edge linking two critical points.
This actually describes two edges:
from_idx ------ idx ------ to_idx
However, in practice, from_idx and to_idx will typically be
atom nuclei, ... |
Calculates the BV sum of a site. | def calculate_bv_sum(site, nn_list, scale_factor=1.0):
"""
Calculates the BV sum of a site.
Args:
site:
The site
nn_list:
List of nearest neighbors in the format [(nn_site, dist), ...].
scale_factor:
A scale factor to be applied. This is useful fo... |
Calculates the BV sum of a site for unordered structures. | def calculate_bv_sum_unordered(site, nn_list, scale_factor=1):
"""
Calculates the BV sum of a site for unordered structures.
Args:
site:
The site
nn_list:
List of nearest neighbors in the format [(nn_site, dist), ...].
scale_factor:
A scale factor... |
Add oxidation states to a structure by fractional site. | def add_oxidation_state_by_site_fraction(structure, oxidation_states):
"""
Add oxidation states to a structure by fractional site.
Args:
oxidation_states (list): List of list of oxidation states for each
site fraction for each site.
E.g., [[2, 4], [3]... |
Returns a list of valences for the structure. This currently works only for ordered structures only. | def get_valences(self, structure):
"""
Returns a list of valences for the structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A list of valences for each site in the structure (for an ordered
... |
Get an oxidation state decorated structure. This currently works only for ordered structures only. | def get_oxi_state_decorated_structure(self, structure):
"""
Get an oxidation state decorated structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A modified structure that is oxidation state dec... |
Converts fractional coordinates of trajectory into positions | def to_positions(self):
"""
Converts fractional coordinates of trajectory into positions
"""
if self.coords_are_displacement:
cumulative_displacements = np.cumsum(self.frac_coords, axis=0)
positions = self.base_positions + cumulative_displacements
self... |
Converts position coordinates of trajectory into displacements between consecutive frames | def to_displacements(self):
"""
Converts position coordinates of trajectory into displacements between consecutive frames
"""
if not self.coords_are_displacement:
displacements = np.subtract(self.frac_coords, np.roll(self.frac_coords, 1, axis=0))
displacements[0] ... |
Concatenate another trajectory | def extend(self, trajectory):
"""
Concatenate another trajectory
Args:
trajectory (Trajectory): Trajectory to add
"""
if self.time_step != trajectory.time_step:
raise ValueError('Trajectory not extended: Time steps of trajectories is incompatible')
... |
Convenience constructor to obtain trajectory from a list of structures. Note: Assumes no atoms removed during simulation | def from_structures(cls, structures, constant_lattice=True, **kwargs):
"""
Convenience constructor to obtain trajectory from a list of structures.
Note: Assumes no atoms removed during simulation
Args:
structures (list): list of pymatgen Structure objects.
consta... |
Convenience constructor to obtain trajectory from XDATCAR or vasprun. xml file | def from_file(cls, filename, constant_lattice=True, **kwargs):
"""
Convenience constructor to obtain trajectory from XDATCAR or vasprun.xml file
Args:
filename (str): The filename to read from.
constant_lattice (bool): Whether the lattice changes during the simulation, s... |
Helper function to combine trajectory properties such as site_properties or lattice | def _combine_attribute(attr_1, attr_2, len_1, len_2):
"""
Helper function to combine trajectory properties such as site_properties or lattice
"""
if isinstance(attr_1, list) or isinstance(attr_2, list):
attribute = np.concatenate((attr_1, attr_2), axis=0)
attribut... |
Gets the Freysoldt correction for a defect entry Args: entry ( DefectEntry ): defect entry to compute Freysoldt correction on. Requires following parameters in the DefectEntry to exist: | def get_correction(self, entry):
"""
Gets the Freysoldt correction for a defect entry
Args:
entry (DefectEntry): defect entry to compute Freysoldt correction on.
Requires following parameters in the DefectEntry to exist:
axis_grid (3 x NGX where N... |
Peform Electrostatic Freysoldt Correction | def perform_es_corr(self, lattice, q, step=1e-4):
"""
Peform Electrostatic Freysoldt Correction
"""
logger.info("Running Freysoldt 2011 PC calculation (should be " "equivalent to sxdefectalign)")
logger.debug("defect lattice constants are (in angstroms)" + str(lattice.abc))
... |
For performing planar averaging potential alignment | def perform_pot_corr(self,
axis_grid,
pureavg,
defavg,
lattice,
q,
defect_position,
axis,
madetol=0.0001,
... |
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt | def plot(self, axis, title=None, saved=False):
"""
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt
"""
x = self.metadata['pot_plot_data'][axis]['x']
v_R = self.metadata['pot_plot_data'][axis]['Vr']
dft_diff =... |
Gets the BandFilling correction for a defect entry | def get_correction(self, entry):
"""
Gets the BandFilling correction for a defect entry
"""
eigenvalues = entry.parameters["eigenvalues"]
kpoint_weights = entry.parameters["kpoint_weights"]
potalign = entry.parameters["potalign"]
vbm = entry.parameters["vbm"]
... |
This calculates the band filling correction based on excess of electrons/ holes in CB/ VB... | def perform_bandfill_corr(self, eigenvalues, kpoint_weights, potalign, vbm, cbm):
"""
This calculates the band filling correction based on excess of electrons/holes in CB/VB...
Note that the total free holes and electrons may also be used for a "shallow donor/acceptor"
correction... |
Gets the BandEdge correction for a defect entry | def get_correction(self, entry):
"""
Gets the BandEdge correction for a defect entry
"""
# TODO: add smarter defect level shifting based on defect level projection onto host bands
hybrid_cbm = entry.parameters["hybrid_cbm"]
hybrid_vbm = entry.parameters["hybrid_vbm"]
... |
Return a: class: JobStatus instance from its string representation. | def from_string(cls, s):
"""Return a :class:`JobStatus` instance from its string representation."""
for num, text in cls._STATUS_TABLE.items():
if text == s: return cls(num)
else:
#raise ValueError("Wrong string %s" % s)
logger.warning("Got unknown status: %s"... |
Return a new istance of the appropriate subclass. | def from_qtype_and_id(qtype, queue_id, qname=None):
"""
Return a new istance of the appropriate subclass.
Args:
qtype: String specifying the Resource manager type.
queue_id: Job identifier.
qname: Name of the queue (optional).
"""
for cls in a... |
Get the stable entries. | def get_stable_entries(self, charge_to_discharge=True):
"""
Get the stable entries.
Args:
charge_to_discharge: order from most charge to most discharged
state? Default to True.
Returns:
A list of stable entries in the electrode, ordered by amount... |
Returns the unstable entries for the electrode. | def get_unstable_entries(self, charge_to_discharge=True):
"""
Returns the unstable entries for the electrode.
Args:
charge_to_discharge: Order from most charge to most discharged
state? Defaults to True.
Returns:
A list of unstable entries in the... |
Return all entries input for the electrode. | def get_all_entries(self, charge_to_discharge=True):
"""
Return all entries input for the electrode.
Args:
charge_to_discharge:
order from most charge to most discharged state? Defaults to
True.
Returns:
A list of all entries in t... |
The maximum instability along a path for a specific voltage range. | def get_max_instability(self, min_voltage=None, max_voltage=None):
"""
The maximum instability along a path for a specific voltage range.
Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.
Returns:
Maximum d... |
The minimum instability along a path for a specific voltage range. | def get_min_instability(self, min_voltage=None, max_voltage=None):
"""
The minimum instability along a path for a specific voltage range.
Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.
Returns:
Minimum d... |
Maximum critical oxygen chemical potential along path. | def get_max_muO2(self, min_voltage=None, max_voltage=None):
"""
Maximum critical oxygen chemical potential along path.
Args:
min_voltage: The minimum allowable voltage.
max_voltage: The maximum allowable voltage.
Returns:
Maximum critical oxygen chem... |
Minimum critical oxygen chemical potential along path. | def get_min_muO2(self, min_voltage=None, max_voltage=None):
"""
Minimum critical oxygen chemical potential along path.
Args:
min_voltage: The minimum allowable voltage for a given step
max_voltage: The maximum allowable voltage allowable for a given
step
... |
If this electrode contains multiple voltage steps then it is possible to use only a subset of the voltage steps to define other electrodes. For example an LiTiO2 electrode might contain three subelectrodes: [ LiTiO2 -- > TiO2 LiTiO2 -- > Li0. 5TiO2 Li0. 5TiO2 -- > TiO2 ] This method can be used to return all the subele... | def get_sub_electrodes(self, adjacent_only=True, include_myself=True):
"""
If this electrode contains multiple voltage steps, then it is possible
to use only a subset of the voltage steps to define other electrodes.
For example, an LiTiO2 electrode might contain three subelectrodes:
... |
Generate a summary dict. | def as_dict_summary(self, print_subelectrodes=True):
"""
Generate a summary dict.
Args:
print_subelectrodes: Also print data on all the possible
subelectrodes.
Returns:
A summary of this electrode"s properties in dict format.
"""
... |
Creates zval_dictionary for calculating the ionic polarization from Potcar object | def zval_dict_from_potcar(potcar):
"""
Creates zval_dictionary for calculating the ionic polarization from
Potcar object
potcar: Potcar object
"""
zval_dict = {}
for p in potcar:
zval_dict.update({p.element: p.ZVAL})
return zval_dict |
Calculate the ionic dipole moment using ZVAL from pseudopotential | def calc_ionic(site, structure, zval):
"""
Calculate the ionic dipole moment using ZVAL from pseudopotential
site: PeriodicSite
structure: Structure
zval: Charge value for ion (ZVAL for VASP pseudopotential)
Returns polarization in electron Angstroms.
"""
norms = structure.lattice.leng... |
Get the total ionic dipole moment for a structure. | def get_total_ionic_dipole(structure, zval_dict):
"""
Get the total ionic dipole moment for a structure.
structure: pymatgen Structure
zval_dict: specie, zval dictionary pairs
center (np.array with shape [3,1]) : dipole center used by VASP
tiny (float) : tolerance for determining boundary of ca... |
Given coords and a site find closet site to coords. Args: coords ( 3x1 array ): cartesian coords of center of sphere site: site to find closest to coords r: radius of sphere. Defaults to diagonal of unit cell | def get_nearest_site(self, coords, site, r=None):
"""
Given coords and a site, find closet site to coords.
Args:
coords (3x1 array): cartesian coords of center of sphere
site: site to find closest to coords
r: radius of sphere. Defaults to diagonal of unit cel... |
Create Polarization object from list of Outcars and Structures in order of nonpolar to polar. | def from_outcars_and_structures(cls, outcars, structures,
calc_ionic_from_zval=False):
"""
Create Polarization object from list of Outcars and Structures in order
of nonpolar to polar.
Note, we recommend calculating the ionic dipole moment using calc_... |
Get the electronic and ionic dipole moments/ polarizations. | def get_pelecs_and_pions(self, convert_to_muC_per_cm2=False):
"""
Get the electronic and ionic dipole moments / polarizations.
convert_to_muC_per_cm2: Convert from electron * Angstroms to microCoulomb
per centimeter**2
"""
if not convert_to_muC_per_cm2:
... |
Get same branch dipole moment ( convert_to_muC_per_cm2 = False ) or polarization for given polarization data ( convert_to_muC_per_cm2 = True ). | def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Get same branch dipole moment (convert_to_muC_per_cm2=False)
or polarization for given polarization data (convert_to_muC_per_cm2=True).
Polarization is a lattice vector, meaning it is only d... |
Returns the dipole/ polarization quanta along a b and c for all structures. | def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Returns the dipole / polarization quanta along a, b, and c for
all structures.
"""
lattices = [s.lattice for s in self.structures]
volumes = np.array([s.lattice.volume for s in self.structur... |
Get difference between nonpolar and polar same branch polarization. | def get_polarization_change(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Get difference between nonpolar and polar same branch polarization.
"""
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_pola... |
Get magnitude of difference between nonpolar and polar same branch polarization. | def get_polarization_change_norm(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Get magnitude of difference between nonpolar and polar same branch
polarization.
"""
polar = self.structures[-1]
a, b, c = polar.lattice.matrix
a, b, c = a / np.linalg.norm... |
Fit splines to same branch polarization. This is used to assess any jumps in the same branch polarizaiton. | def same_branch_splines(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Fit splines to same branch polarization. This is used to assess any jumps
in the same branch polarizaiton.
"""
from scipy.interpolate import UnivariateSpline
tot = self.get_same_branch_pola... |
Get maximum difference between spline and same branch polarization data. | def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Get maximum difference between spline and same branch polarization data.
"""
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)... |
Get rms average difference between spline and same branch polarization data. | def smoothness(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Get rms average difference between spline and same branch polarization data.
"""
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)
... |
Fit spline to energy trend data. | def spline(self):
"""
Fit spline to energy trend data.
"""
from scipy.interpolate import UnivariateSpline
sp = UnivariateSpline(range(len(self.energies)), self.energies, k=4)
return sp |
Get rms average difference between spline and energy trend. | def smoothness(self):
"""
Get rms average difference between spline and energy trend.
"""
energies = self.energies
try:
sp = self.spline()
except:
print("Energy spline failed.")
return None
spline_energies = sp(range(len(energie... |
Get maximum difference between spline and energy trend. | def max_spline_jump(self):
"""
Get maximum difference between spline and energy trend.
"""
sp = self.spline()
return max(self.energies - sp(range(len(self.energies)))) |
Test if spline endpoints are at minima for a given slope cutoff. | def endpoints_minima(self, slope_cutoff=5e-3):
"""
Test if spline endpoints are at minima for a given slope cutoff.
"""
energies = self.energies
try:
sp = self.spline()
except:
print("Energy spline failed.")
return None
der = sp... |
Process a single entry with the chosen Corrections. | def process_entry(self, entry):
"""
Process a single entry with the chosen Corrections.
Args:
entry: A ComputedEntry object.
Returns:
An adjusted entry if entry is compatible, otherwise None is
returned.
"""
try:
correctio... |
Returns the corrections applied to a particular entry. | def get_corrections_dict(self, entry):
"""
Returns the corrections applied to a particular entry.
Args:
entry: A ComputedEntry object.
Returns:
({correction_name: value})
"""
corrections = {}
for c in self.corrections:
val = c... |
Provides an explanation dict of the corrections that are being applied for a given compatibility scheme. Inspired by the explain methods in many database methodologies. | def get_explanation_dict(self, entry):
"""
Provides an explanation dict of the corrections that are being applied
for a given compatibility scheme. Inspired by the "explain" methods
in many database methodologies.
Args:
entry: A ComputedEntry.
Returns:
... |
Prints an explanation of the corrections that are being applied for a given compatibility scheme. Inspired by the explain methods in many database methodologies. | def explain(self, entry):
"""
Prints an explanation of the corrections that are being applied for a
given compatibility scheme. Inspired by the "explain" methods in many
database methodologies.
Args:
entry: A ComputedEntry.
"""
d = self.get_explanatio... |
Reads a string representation to a Cssr object. | def from_string(string):
"""
Reads a string representation to a Cssr object.
Args:
string (str): A string representation of a CSSR.
Returns:
Cssr object.
"""
lines = string.split("\n")
toks = lines[0].split()
lengths = [float(i) f... |
Returns conversion factor from THz to the requred units and the label in the form of a namedtuple Accepted values: thz ev mev ha cm - 1 cm^ - 1 | def freq_units(units):
"""
Returns conversion factor from THz to the requred units and the label in the form of a namedtuple
Accepted values: thz, ev, mev, ha, cm-1, cm^-1
"""
d = {"thz": FreqUnits(1, "THz"),
"ev": FreqUnits(const.value("hertz-electron volt relationship") * const.tera, "eV... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.