docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Initializes a covalent bond between two sites.
Args:
site1 (Site): First site.
site2 (Site): Second site. | def __init__(self, site1, site2):
self.site1 = site1
self.site2 = site2 | 140,576 |
Sends an e-mail with unix sendmail.
Args:
subject: String with the subject of the mail.
text: String with the body of the mail.
mailto: String or list of string with the recipients.
sender: string with the sender address.
If sender is None, username@hostname is used.
... | def sendmail(subject, text, mailto, sender=None):
def user_at_host():
from socket import gethostname
return os.getlogin() + "@" + gethostname()
# Body of the message.
try:
sender = user_at_host() if sender is None else sender
except OSError:
sender = 'abipyscheduler... | 140,581 |
Initialize the object
Args:
flow: :class:`Flow` object
max_njobs_inqueue: The launcher will stop submitting jobs when the
number of jobs in the queue is >= Max number of jobs | def __init__(self, flow, **kwargs):
self.flow = flow
self.max_njobs_inqueue = kwargs.get("max_njobs_inqueue", 200) | 140,588 |
Keeps submitting `Tasks` until we are out of jobs or no job is ready to run.
Args:
max_nlaunch: Maximum number of launches. default: no limit.
max_loops: Maximum number of loops
sleep_time: seconds to sleep between rapidfire loop iterations
Returns:
The ... | def rapidfire(self, max_nlaunch=-1, max_loops=1, sleep_time=5):
num_launched, do_exit, launched = 0, False, []
for count in range(max_loops):
if do_exit:
break
if count > 0:
time.sleep(sleep_time)
tasks = self.fetch_tasks_to_... | 140,590 |
Loads the object from a pickle file.
Args:
filepath: Filename or directory name. It filepath is a directory, we
scan the directory tree starting from filepath and we
read the first pickle database. Raise RuntimeError if multiple
databases are found. | def pickle_load(cls, filepath):
if os.path.isdir(filepath):
# Walk through each directory inside path and find the pickle database.
for dirpath, dirnames, filenames in os.walk(filepath):
fnames = [f for f in filenames if f == cls.PICKLE_FNAME]
if ... | 140,611 |
Creates a CTRL file object from an existing file.
Args:
filename: The name of the CTRL file. Defaults to 'CTRL'.
Returns:
An LMTOCtrl object. | def from_file(cls, filename="CTRL", **kwargs):
with zopen(filename, "rt") as f:
contents = f.read()
return LMTOCtrl.from_string(contents, **kwargs) | 140,622 |
Creates a CTRL file object from a string. This will mostly be
used to read an LMTOCtrl object from a CTRL file. Empty spheres
are ignored.
Args:
data: String representation of the CTRL file.
Returns:
An LMTOCtrl object. | def from_string(cls, data, sigfigs=8):
lines = data.split("\n")[:-1]
struc_lines = {"HEADER": [], "VERS": [], "SYMGRP": [],
"STRUC": [], "CLASS": [], "SITE": []}
for line in lines:
if line != "" and not line.isspace():
if not line[0].is... | 140,623 |
Subroutine to extract bond label, site indices, and length from
a COPL header line. The site indices are zero-based, so they
can be easily used with a Structure object.
Example header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang.
Args:
line: line in the COHPCAR header describi... | def _get_bond_data(line):
line = line.split()
length = float(line[2])
# Replacing "/" with "-" makes splitting easier
sites = line[0].replace("/", "-").split("-")
site_indices = tuple(int(ind) - 1 for ind in sites[1:4:2])
species = tuple(re.split(r"\d+", spec)[0... | 140,626 |
Given a structure, returns the predicted volume.
Args:
structure (Structure): structure w/unknown volume
ref_structure (Structure): A reference structure with a similar
structure but different species.
Returns:
a float value of the predicted volume | def predict(self, structure, ref_structure):
if self.check_isostructural:
m = StructureMatcher()
mapping = m.get_best_electronegativity_anonymous_mapping(
structure, ref_structure)
if mapping is None:
raise ValueError("Input structure... | 140,643 |
Given a structure, returns back the structure scaled to predicted
volume.
Args:
structure (Structure): structure w/unknown volume
ref_structure (Structure): A reference structure with a similar
structure but different species.
Returns:
a Struct... | def get_predicted_structure(self, structure, ref_structure):
new_structure = structure.copy()
new_structure.scale_lattice(self.predict(structure, ref_structure))
return new_structure | 140,644 |
Given a structure, returns the predicted volume.
Args:
structure (Structure) : a crystal structure with an unknown volume.
icsd_vol (bool) : True if the input structure's volume comes from
ICSD.
Returns:
a float value of the predicted volume. | def predict(self, structure, icsd_vol=False):
# Get standard deviation of electronnegativity in the structure.
std_x = np.std([site.specie.X for site in structure])
# Sites that have atomic radii
sub_sites = []
# Record the "DLS estimated radius" from bond_params.
... | 140,646 |
Given a structure, returns back the structure scaled to predicted
volume.
Args:
structure (Structure): structure w/unknown volume
Returns:
a Structure object with predicted volume | def get_predicted_structure(self, structure, icsd_vol=False):
new_structure = structure.copy()
new_structure.scale_lattice(self.predict(structure, icsd_vol=icsd_vol))
return new_structure | 140,647 |
Get the inchi canonical labels of the heavy atoms in the molecule
Args:
mol: The molecule. OpenBabel OBMol object
Returns:
The label mappings. List of tuple of canonical label,
original label
List of equivalent atoms. | def _inchi_labels(mol):
obconv = ob.OBConversion()
obconv.SetOutFormat(str("inchi"))
obconv.AddOption(str("a"), ob.OBConversion.OUTOPTIONS)
obconv.AddOption(str("X"), ob.OBConversion.OUTOPTIONS, str("DoNotAddH"))
inchi_text = obconv.WriteString(mol)
match = re.se... | 140,652 |
Calculate the centroids of a group atoms indexed by the labels of inchi
Args:
mol: The molecule. OpenBabel OBMol object
ilabel: inchi label map
Returns:
Centroid. Tuple (x, y, z) | def _group_centroid(mol, ilabels, group_atoms):
c1x, c1y, c1z = 0.0, 0.0, 0.0
for i in group_atoms:
orig_idx = ilabels[i-1]
oa1 = mol.GetAtom(orig_idx)
c1x += float(oa1.x())
c1y += float(oa1.y())
c1z += float(oa1.z())
num_atoms... | 140,653 |
Create a virtual molecule by unique atoms, the centriods of the
equivalent atoms
Args:
mol: The molecule. OpenBabel OBMol object
ilables: inchi label map
eq_atoms: equivalent atom labels
farthest_group_idx: The equivalent atom group index in which
... | def _virtual_molecule(self, mol, ilabels, eq_atoms):
vmol = ob.OBMol()
non_unique_atoms = set([a for g in eq_atoms for a in g])
all_atoms = set(range(1, len(ilabels) + 1))
unique_atom_labels = sorted(all_atoms - non_unique_atoms)
#try to align molecules using unique at... | 140,654 |
Align the label of topologically identical atoms of second molecule
towards first molecule
Args:
mol1: First molecule. OpenBabel OBMol object
mol2: Second molecule. OpenBabel OBMol object
heavy_indices1: inchi label map of the first molecule
heavy_indices... | def _align_hydrogen_atoms(mol1, mol2, heavy_indices1,
heavy_indices2):
num_atoms = mol2.NumAtoms()
all_atom = set(range(1, num_atoms+1))
hydrogen_atoms1 = all_atom - set(heavy_indices1)
hydrogen_atoms2 = all_atom - set(heavy_indices2)
label1... | 140,656 |
The the elements of the atoms in the specified order
Args:
mol: The molecule. OpenBabel OBMol object.
label: The atom indices. List of integers.
Returns:
Elements. List of integers. | def _get_elements(mol, label):
elements = [int(mol.GetAtom(i).GetAtomicNum()) for i in label]
return elements | 140,657 |
Is the molecule a linear one
Args:
mol: The molecule. OpenBabel OBMol object.
Returns:
Boolean value. | def _is_molecule_linear(self, mol):
if mol.NumAtoms() < 3:
return True
a1 = mol.GetAtom(1)
a2 = mol.GetAtom(2)
for i in range(3, mol.NumAtoms()+1):
angle = float(mol.GetAtom(i).GetAngle(a2, a1))
if angle < 0.0:
angle = -angle
... | 140,658 |
Fit two molecules.
Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object
mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object
Returns:
A boolean value indicates whether two molecules are the same. | def fit(self, mol1, mol2):
return self.get_rmsd(mol1, mol2) < self._tolerance | 140,662 |
Calculate the RMSD.
Args:
mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule
object
mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule
object
clabel1: The atom indices that can reorder the first molecule to
... | def _calc_rms(mol1, mol2, clabel1, clabel2):
obmol1 = BabelMolAdaptor(mol1).openbabel_mol
obmol2 = BabelMolAdaptor(mol2).openbabel_mol
cmol1 = ob.OBMol()
for i in clabel1:
oa1 = obmol1.GetAtom(i)
a1 = cmol1.NewAtom()
a1.SetAtomicNum(oa1.GetAt... | 140,664 |
Group molecules by structural equality.
Args:
mol_list: List of OpenBabel OBMol or pymatgen objects
Returns:
A list of lists of matched molecules
Assumption: if s1=s2 and s2=s3, then s1=s3
This may not be true for small tolerances. | def group_molecules(self, mol_list):
mol_hash = [(i, self._mapper.get_molecule_hash(m))
for i, m in enumerate(mol_list)]
mol_hash.sort(key=lambda x: x[1])
#Use molecular hash to pre-group molecules.
raw_groups = tuple([tuple([m[0] for m in g]) for k, g
... | 140,665 |
Remove all the configurations that do not satisfy the given condition.
Args:
condition: dict or :class:`Condition` object with operators expressed with a Mongodb-like syntax
key: Selects the sub-dictionary on which condition is applied, e.g. key="vars"
if... | def select_with_condition(self, condition, key=None):
condition = Condition.as_condition(condition)
new_confs = []
for conf in self:
# Select the object on which condition is applied
obj = conf if key is None else AttrDict(conf[key])
add_it = conditi... | 140,675 |
Given a list of parallel configurations, pconfs, this method select an `optimal` configuration
according to some criterion as well as the :class:`QueueAdapter` to use.
Args:
pconfs: :class:`ParalHints` object with the list of parallel configurations
Returns:
:class:`Par... | def select_qadapter(self, pconfs):
# Order the list of configurations according to policy.
policy, max_ncpus = self.policy, self.max_cores
pconfs = pconfs.get_ordered_with_policy(policy, max_ncpus)
if policy.precedence == "qadapter":
# Try to run on the qadapter wi... | 140,692 |
Build the input files and submit the task via the :class:`Qadapter`
Args:
task: :class:`TaskObject`
Returns:
Process object. | def launch(self, task, **kwargs):
if task.status == task.S_LOCKED:
raise ValueError("You shall not submit a locked task!")
# Build the task
task.build()
# Pass information on the time limit to Abinit (we always assume ndtset == 1)
if isinstance(task, Abinit... | 140,696 |
Set and return the status of the task.
Args:
status: Status object or string representation of the status
msg: string with human-readable message used in the case of errors. | def set_status(self, status, msg):
# truncate string if it's long. msg will be logged in the object and we don't want to waste memory.
if len(msg) > 2000:
msg = msg[:2000]
msg += "\n... snip ...\n"
# Locked files must be explicitly unlocked
if self.statu... | 140,730 |
Analyzes the main logfile of the calculation for possible Errors or Warnings.
If the ABINIT abort file is found, the error found in this file are added to
the output report.
Args:
source: "output" for the main output file,"log" for the log file.
Returns:
:class:... | def get_event_report(self, source="log"):
# By default, we inspect the main log file.
ofile = {
"output": self.output_file,
"log": self.log_file}[source]
parser = events.EventsParser()
if not ofile.exists:
if not self.mpiabort_file.exists:
... | 140,735 |
This method is called when the task reaches S_OK. It removes all the output files
produced by the task that are not needed by its children as well as the output files
produced by its parents if no other node needs them.
Args:
follow_parents: If true, the output files of the parents ... | def clean_output_files(self, follow_parents=True):
paths = []
if self.status != self.S_OK:
logger.warning("Calling task.clean_output_files on a task whose status != S_OK")
# Remove all files in tmpdir.
self.tmpdir.clean()
# Find the file extensions that sho... | 140,740 |
Create an instance of `AbinitTask` from an ABINIT input.
Args:
ainput: `AbinitInput` object.
workdir: Path to the working directory.
manager: :class:`TaskManager` object. | def from_input(cls, input, workdir=None, manager=None):
return cls(input, workdir=workdir, manager=manager) | 140,744 |
Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc.
Mainly used for invoking Abinit to get important parameters needed to prepare the real task.
Args:
mpi_procs: Number of MPI processes to use. | def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, manager=None):
# Build a simple manager to run the job in a shell subprocess
import tempfile
workdir = tempfile.mkdtemp() if workdir is None else workdir
if manager is None: manager = TaskManager.from_user_config()
... | 140,745 |
Helper function used to select the files of a task.
Args:
what: string with the list of characters selecting the file type
Possible choices:
i ==> input_file,
o ==> output_file,
f ==> files_file,
j ==>... | def select_files(self, what="o"):
choices = collections.OrderedDict([
("i", self.input_file),
("o", self.output_file),
("f", self.files_file),
("j", self.job_file),
("l", self.log_file),
("e", self.stderr_file),
("q", s... | 140,753 |
Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via
the shell with 1 MPI proc. Mainly used for post-processing the DDB files.
Args:
mpi_procs: Number of MPI processes to use.
anaddb_input: string with the anaddb variables.
ddb_node: The nod... | def temp_shell_task(cls, inp, ddb_node, mpi_procs=1,
gkk_node=None, md_node=None, ddk_node=None, workdir=None, manager=None):
# Build a simple manager to run the job in a shell subprocess
import tempfile
workdir = tempfile.mkdtemp() if workdir is None else workdi... | 140,796 |
Reads and returns a pymatgen structure from a NetCDF file
containing crystallographic data in the ETSF-IO format.
Args:
ncdata: filename or NetcdfReader instance.
site_properties: Dictionary with site properties.
cls: The Structure class to instanciate. | def structure_from_ncdata(ncdata, site_properties=None, cls=Structure):
ncdata, closeit = as_ncreader(ncdata)
# TODO check whether atomic units are used
lattice = ArrayWithUnit(ncdata.read_value("primitive_vectors"), "bohr").to("ang")
red_coords = ncdata.read_value("reduced_atom_positions")
n... | 140,806 |
Returns the value of a dimension.
Args:
dimname: Name of the variable
path: path to the group.
default: return `default` if `dimname` is not present and
`default` is not `NO_DEFAULT` else raise self.Error. | def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT):
try:
dim = self._read_dimensions(dimname, path=path)[0]
return len(dim)
except self.Error:
if default is NO_DEFAULT: raise
return default | 140,810 |
String representation. kwargs are passed to `pprint.pformat`.
Args:
verbose: Verbosity level
title: Title string. | def to_string(self, verbose=0, title=None, **kwargs):
from pprint import pformat
s = pformat(self, **kwargs)
if title is not None:
return "\n".join([marquee(title, mark="="), s])
return s | 140,819 |
Add an electrode to the plot.
Args:
electrode: An electrode. All electrodes satisfying the
AbstractElectrode interface should work.
label: A label for the electrode. If None, defaults to a counting
system, i.e. 'Electrode 1', 'Electrode 2', ... | def add_electrode(self, electrode, label=None):
if not label:
label = "Electrode {}".format(len(self._electrodes) + 1)
self._electrodes[label] = electrode | 140,820 |
Returns a plot object.
Args:
width: Width of the plot. Defaults to 8 in.
height: Height of the plot. Defaults to 6 in.
Returns:
A matplotlib plot object. | def get_plot(self, width=8, height=8):
plt = pretty_plot(width, height)
for label, electrode in self._electrodes.items():
(x, y) = self.get_plot_data(electrode)
plt.plot(x, y, '-', linewidth=2, label=label)
plt.legend()
if self.xaxis == "capacity":
... | 140,822 |
Save the plot to an image file.
Args:
filename: Filename to save to.
image_format: Format to save to. Defaults to eps. | def save(self, filename, image_format="eps", width=8, height=6):
self.get_plot(width, height).savefig(filename, format=image_format) | 140,823 |
Writes a set of VASP input to a directory.
Args:
output_dir (str): Directory to output the VASP input files
make_dir_if_not_present (bool): Set to True if you want the
directory (and the whole path) to be created if it is not
present.
include_... | def write_input(self, output_dir,
make_dir_if_not_present=True, include_cif=False):
vinput = self.get_vasp_input()
vinput.write_input(
output_dir, make_dir_if_not_present=make_dir_if_not_present)
if include_cif:
s = vinput["POSCAR"].structure
... | 140,831 |
Create a Tensor object. Note that the constructor uses __new__
rather than __init__ according to the standard method of
subclassing numpy ndarrays.
Args:
input_array: (array-like with shape 3^N): array-like representing
a tensor quantity in standard (i. e. non-voigt... | def __new__(cls, input_array, vscale=None, check_rank=None):
obj = np.asarray(input_array).view(cls)
obj.rank = len(obj.shape)
if check_rank and check_rank != obj.rank:
raise ValueError("{} input must be rank {}".format(
obj.__class__.__name__, check_rank))
... | 140,879 |
Applies a rotation directly, and tests input matrix to ensure a valid
rotation.
Args:
matrix (3x3 array-like): rotation matrix to be applied to tensor
tol (float): tolerance for testing rotation matrix validity | def rotate(self, matrix, tol=1e-3):
matrix = SquareTensor(matrix)
if not matrix.is_rotation(tol):
raise ValueError("Rotation matrix is not valid.")
sop = SymmOp.from_rotation_and_translation(matrix,
[0., 0., 0.])
ret... | 140,883 |
Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
scalar value corresponding to the projection of
the ten... | def project(self, n):
n = get_uvec(n)
return self.einsum_sequence([n] * self.rank) | 140,885 |
Method for averaging the tensor projection over the unit
with option for custom quadrature.
Args:
quad (dict): quadrature for integration, should be
dictionary with "points" and "weights" keys defaults
to quadpy.sphere.Lebedev(19) as read from file
R... | def average_over_unit_sphere(self, quad=None):
quad = quad or DEFAULT_QUAD
weights, points = quad['weights'], quad['points']
return sum([w * self.project(n) for w, n in zip(weights, points)]) | 140,886 |
Wrapper around numpy.round to ensure object
of same type is returned
Args:
decimals :Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of
positions to the left of the decimal point.
Returns (Tensor):
... | def round(self, decimals=0):
return self.__class__(np.round(self, decimals=decimals)) | 140,889 |
Returns a tensor that is invariant with respect to symmetry
operations corresponding to a structure
Args:
structure (Structure): structure from which to generate
symmetry operations
symprec (float): symmetry tolerance for the Spacegroup Analyzer
u... | def fit_to_structure(self, structure, symprec=0.1):
sga = SpacegroupAnalyzer(structure, symprec)
symm_ops = sga.get_symmetry_operations(cartesian=True)
return sum([self.transform(symm_op)
for symm_op in symm_ops]) / len(symm_ops) | 140,892 |
Tests whether a tensor is invariant with respect to the
symmetry operations of a particular structure by testing
whether the residual of the symmetric portion is below a
tolerance
Args:
structure (Structure): structure to be fit to
tol (float): tolerance for symm... | def is_fit_to_structure(self, structure, tol=1e-2):
return (self - self.fit_to_structure(structure) < tol).all() | 140,893 |
Returns a dictionary that maps indices in the tensor to those
in a voigt representation based on input rank
Args:
rank (int): Tensor rank to generate the voigt map | def get_voigt_dict(rank):
vdict = {}
for ind in itertools.product(*[range(3)] * rank):
v_ind = ind[:rank % 2]
for j in range(rank // 2):
pos = rank % 2 + 2 * j
v_ind += (reverse_voigt_map[ind[pos:pos + 2]],)
vdict[ind] = v_ind
... | 140,896 |
Constructor based on the voigt notation vector or matrix.
Args:
voigt_input (array-like): voigt input for a given tensor | def from_voigt(cls, voigt_input):
voigt_input = np.array(voigt_input)
rank = sum(voigt_input.shape) // 3
t = cls(np.zeros([3] * rank))
if voigt_input.shape != t._vscale.shape:
raise ValueError("Invalid shape for voigt matrix")
voigt_input = voigt_input / t._v... | 140,897 |
Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
tensor to be converted to the IEEE standard
refine_rotation (... | def get_ieee_rotation(structure, refine_rotation=True):
# Check conventional setting:
sga = SpacegroupAnalyzer(structure)
dataset = sga.get_symmetry_dataset()
trans_mat = dataset['transformation_matrix']
conv_latt = Lattice(np.transpose(np.dot(np.transpose(
s... | 140,898 |
Serializes the tensor object
Args:
voigt (bool): flag for whether to store entries in
voigt-notation. Defaults to false, as information
may be lost in conversion.
Returns (Dict):
serialized format tensor object | def as_dict(self, voigt=False):
input_array = self.voigt if voigt else self
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"input_array": input_array.tolist()}
if voigt:
d.update({"voigt": voigt})
return d | 140,903 |
Helper method for refining rotation matrix by ensuring
that second and third rows are perpindicular to the first.
Gets new y vector from an orthogonal projection of x onto y
and the new z vector from a cross product of the new x and y
Args:
tol to test for rotation
... | def refine_rotation(self):
new_x, y = get_uvec(self[0]), get_uvec(self[1])
# Get a projection on y
new_y = y - np.dot(new_x, y) * new_x
new_z = np.cross(new_x, new_y)
return SquareTensor([new_x, new_y, new_z]) | 140,918 |
Initialize a TensorMapping
Args:
tensor_list ([Tensor]): list of tensors
value_list ([]): list of values to be associated with tensors
tol (float): an absolute tolerance for getting and setting
items in the mapping | def __init__(self, tensors=None, values=None, tol=1e-5):
self._tensor_list = tensors or []
self._value_list = values or []
if not len(self._tensor_list) == len(self._value_list):
raise ValueError("TensorMapping must be initialized with tensors"
"... | 140,919 |
Calculates the average oxidation state of a site
Args:
site: Site to compute average oxidation state
Returns:
Average oxidation state of site. | def compute_average_oxidation_state(site):
try:
avg_oxi = sum([sp.oxi_state * occu
for sp, occu in site.species.items()
if sp is not None])
return avg_oxi
except AttributeError:
pass
try:
return site.charge
except Attribu... | 140,924 |
Gives total ewald energy for an sub structure in the same
lattice. The sub_structure must be a subset of the original
structure, with possible different charges.
Args:
substructure (Structure): Substructure to compute Ewald sum for.
tol (float): Tolerance for site matchi... | def compute_sub_structure(self, sub_structure, tol=1e-3):
total_energy_matrix = self.total_energy_matrix.copy()
def find_match(site):
for test_site in sub_structure:
frac_diff = abs(np.array(site.frac_coords)
- np.array(test_site.frac... | 140,927 |
Compute the energy for a single site in the structure
Args:
site_index (int): Index of site
ReturnS:
(float) - Energy of that site | def get_site_energy(self, site_index):
if self._charged:
warn('Per atom energies for charged structures not supported in EwaldSummation')
return np.sum(self._recip[:,site_index]) + np.sum(self._real[:,site_index]) \
+ self._point[site_index] | 140,930 |
Computes a best case given a matrix and manipulation list.
Args:
matrix: the current matrix (with some permutations already
performed)
m_list: [(multiplication fraction, number_of_indices, indices,
species)] describing the manipulation
indices... | def best_case(self, matrix, m_list, indices_left):
m_indices = []
fraction_list = []
for m in m_list:
m_indices.extend(m[2])
fraction_list.extend([m[0]] * m[1])
indices = list(indices_left.intersection(m_indices))
interaction_matrix = matrix[ind... | 140,937 |
This method recursively finds the minimal permutations using a binary
tree search strategy.
Args:
matrix: The current matrix (with some permutations already
performed).
m_list: The list of permutations still to be performed
indices: Set of indices whi... | def _recurse(self, matrix, m_list, indices, output_m_list=[]):
# check to see if we've found all the solutions that we need
if self._finished:
return
# if we're done with the current manipulation, pop it off.
while m_list[-1][1] == 0:
m_list = copy(m_lis... | 140,939 |
Calculates the ensemble averaged Voronoi coordination numbers
of a list of Structures using VoronoiNN.
Typically used for analyzing the output of a Molecular Dynamics run.
Args:
structures (list): list of Structures.
freq (int): sampling frequency of coordination number [every freq steps].
... | def average_coordination_number(structures, freq=10):
coordination_numbers = {}
for spec in structures[0].composition.as_dict().keys():
coordination_numbers[spec] = 0.0
count = 0
for t in range(len(structures)):
if t % freq != 0:
continue
count += 1
vnn =... | 140,940 |
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle. | def solid_angle(center, coords):
o = np.array(center)
r = [np.array(c) - o for c in coords]
r.append(r[0])
n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]
n.append(np.cross(r[1], r[0]))
vals = []
for i in range(len(n) - 1):
v = -np.dot(n[i], n[i + 1]) \
/ (... | 140,941 |
Provides max bond length estimates for a structure based on the JMol
table and algorithms.
Args:
structure: (structure)
el_radius_updates: (dict) symbol->float to update atomic radii
Returns: (dict) - (Element1, Element2) -> float. The two elements are
ordered by Z. | def get_max_bond_lengths(structure, el_radius_updates=None):
#jmc = JMolCoordFinder(el_radius_updates)
jmnn = JmolNN(el_radius_updates=el_radius_updates)
bonds_lens = {}
els = sorted(structure.composition.elements, key=lambda x: x.Z)
for i1 in range(len(els)):
for i2 in range(len(els)... | 140,942 |
Determines if a structure contains peroxide anions.
Args:
structure (Structure): Input structure.
relative_cutoff: The peroxide bond distance is 1.49 Angstrom.
Relative_cutoff * 1.49 stipulates the maximum distance two O
atoms must be to each other to be considered a peroxid... | def contains_peroxide(structure, relative_cutoff=1.1):
ox_type = oxide_type(structure, relative_cutoff)
if ox_type == "peroxide":
return True
else:
return False | 140,944 |
Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide
Args:
structure (Structure): Input structure.
relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the
max distance two O atoms must be from each other.
return_nbonds (bool): Should number of bonds... | def oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):
ox_obj = OxideType(structure, relative_cutoff)
if return_nbonds:
return ox_obj.oxide_type, ox_obj.nbonds
else:
return ox_obj.oxide_type | 140,945 |
Determines if a structure is a sulfide/polysulfide
Args:
structure (Structure): Input structure.
Returns:
(str) sulfide/polysulfide/sulfate | def sulfide_type(structure):
structure = structure.copy()
structure.remove_oxidation_states()
s = Element("S")
comp = structure.composition
if comp.is_element or s not in comp:
return None
finder = SpacegroupAnalyzer(structure, symprec=0.1)
symm_structure = finder.get_symmetriz... | 140,946 |
Performs Voronoi analysis and returns the polyhedra around atom n
in Schlaefli notation.
Args:
structure (Structure): structure to analyze
n (int): index of the center atom in structure
Returns:
voronoi index of n: <c3,c4,c6,c6,c7,c8,c9,c10>
... | def analyze(self, structure, n=0):
center = structure[n]
neighbors = structure.get_sites_in_sphere(center.coords, self.cutoff)
neighbors = [i[0] for i in sorted(neighbors, key=lambda s: s[1])]
qvoronoi_input = np.array([s.coords for s in neighbors])
voro = Voronoi(qvoron... | 140,948 |
Please note that the input and final structures should have the same
ordering of sites. This is typically the case for most computational
codes.
Args:
initial_structure (Structure): Initial input structure to
calculation.
final_structure (Structure): Fina... | def __init__(self, initial_structure, final_structure):
if final_structure.formula != initial_structure.formula:
raise ValueError("Initial and final structures have different " +
"formulas!")
self.initial = initial_structure
self.final = final_st... | 140,951 |
Assuming there is some value in the connectivity array at indices
(1, 3, 12). sitei can be obtained directly from the input structure
(structure[1]). sitej can be obtained by passing 3, 12 to this function
Args:
site_index (int): index of the site (3 in the example)
imag... | def get_sitej(self, site_index, image_index):
atoms_n_occu = self.s[site_index].species
lattice = self.s.lattice
coords = self.s[site_index].frac_coords + self.offsets[image_index]
return PeriodicSite(atoms_n_occu, coords, lattice) | 140,958 |
Finds stress corresponding to zero strain state in stress-strain list
Args:
strains (Nx3x3 array-like): array corresponding to strains
stresses (Nx3x3 array-like): array corresponding to stresses
tol (float): tolerance to find zero strain state | def find_eq_stress(strains, stresses, tol=1e-10):
stress_array = np.array(stresses)
strain_array = np.array(strains)
eq_stress = stress_array[np.all(abs(strain_array)<tol, axis=(1,2))]
if eq_stress.size != 0:
all_same = (abs(eq_stress - eq_stress[0]) < 1e-8).all()
if len(eq_stress)... | 140,970 |
Helper function to find difference coefficients of an
derivative on an arbitrary mesh.
Args:
hvec (1D array-like): sampling stencil
n (int): degree of derivative to find | def get_diff_coeff(hvec, n=1):
hvec = np.array(hvec, dtype=np.float)
acc = len(hvec)
exp = np.column_stack([np.arange(acc)]*acc)
a = np.vstack([hvec] * acc) ** exp
b = np.zeros(acc)
b[n] = factorial(n)
return np.linalg.solve(a, b) | 140,974 |
Calculate's a given elastic tensor's contribution to the
stress using Einstein summation
Args:
strain (3x3 array-like): matrix corresponding to strain | def calculate_stress(self, strain):
strain = np.array(strain)
if strain.shape == (6,):
strain = Strain.from_voigt(strain)
assert strain.shape == (3, 3), "Strain must be 3x3 or voigt-notation"
stress_matrix = self.einsum_sequence([strain]*(self.order - 1)) \
... | 140,976 |
Calculates the poisson ratio for a specific direction
relative to a second, orthogonal direction
Args:
n (3-d vector): principal direction
m (3-d vector): secondary direction orthogonal to n
tol (float): tolerance for testing of orthogonality | def directional_poisson_ratio(self, n, m, tol=1e-8):
n, m = get_uvec(n), get_uvec(m)
if not np.abs(np.dot(n, m)) < tol:
raise ValueError("n and m must be orthogonal")
v = self.compliance_tensor.einsum_sequence([n]*2 + [m]*2)
v *= -1 / self.compliance_tensor.einsum_se... | 140,983 |
Calculates transverse sound velocity (in SI units) using the
Voigt-Reuss-Hill average bulk modulus
Args:
structure: pymatgen structure object
Returns: transverse sound velocity (in SI units) | def trans_v(self, structure):
nsites = structure.num_sites
volume = structure.volume
natoms = structure.composition.num_atoms
weight = float(structure.composition.weight)
mass_density = 1.6605e3 * nsites * weight / (natoms * volume)
if self.g_vrh < 0:
... | 140,984 |
Calculates Snyder's acoustic sound velocity (in SI units)
Args:
structure: pymatgen structure object
Returns: Snyder's acoustic sound velocity (in SI units) | def snyder_ac(self, structure):
nsites = structure.num_sites
volume = structure.volume
natoms = structure.composition.num_atoms
num_density = 1e30 * nsites / volume
tot_mass = sum([e.atomic_mass for e in structure.species])
avg_mass = 1.6605e-27 * tot_mass / nato... | 140,985 |
Calculates Snyder's optical sound velocity (in SI units)
Args:
structure: pymatgen structure object
Returns: Snyder's optical sound velocity (in SI units) | def snyder_opt(self, structure):
nsites = structure.num_sites
volume = structure.volume
num_density = 1e30 * nsites / volume
return 1.66914e-23 * \
(self.long_v(structure) + 2.*self.trans_v(structure))/3. \
/ num_density ** (-2./3.) * (1 - nsites ** (-1./... | 140,986 |
Calculates Clarke's thermal conductivity (in SI units)
Args:
structure: pymatgen structure object
Returns: Clarke's thermal conductivity (in SI units) | def clarke_thermalcond(self, structure):
nsites = structure.num_sites
volume = structure.volume
tot_mass = sum([e.atomic_mass for e in structure.species])
natoms = structure.composition.num_atoms
weight = float(structure.composition.weight)
avg_mass = 1.6605e-27 ... | 140,987 |
Estimates the debye temperature from longitudinal and
transverse sound velocities
Args:
structure: pymatgen structure object
Returns: debye temperature (in SI units) | def debye_temperature(self, structure):
v0 = (structure.volume * 1e-30 / structure.num_sites)
vl, vt = self.long_v(structure), self.trans_v(structure)
vm = 3**(1./3.) * (1 / vl**3 + 2 / vt**3)**(-1./3.)
td = 1.05457e-34 / 1.38065e-23 * vm * (6 * np.pi**2 / v0) ** (1./3.)
... | 140,988 |
returns a dictionary of properties derived from the elastic tensor
and an associated structure
Args:
structure (Structure): structure object for which to calculate
associated properties
include_base_props (bool): whether to include base properties,
... | def get_structure_property_dict(self, structure, include_base_props=True,
ignore_errors=False):
s_props = ["trans_v", "long_v", "snyder_ac", "snyder_opt",
"snyder_total", "clarke_thermalcond", "cahill_thermalcond",
"debye_tempera... | 140,991 |
Class method to fit an elastic tensor from stress/strain
data. Method uses Moore-Penrose pseudoinverse to invert
the s = C*e equation with elastic tensor, stress, and
strain in voigt notation
Args:
stresses (Nx3x3 array-like): list or array of stresses
strains (... | def from_pseudoinverse(cls, strains, stresses):
# convert the stress/strain to Nx6 arrays of voigt-notation
warnings.warn("Pseudoinverse fitting of Strain/Stress lists may yield "
"questionable results from vasp data, use with caution.")
stresses = np.array([Stress... | 140,992 |
Initialization method for ElasticTensorExpansion
Args:
c_list (list or tuple): sequence of Tensor inputs
or tensors from which the elastic tensor
expansion is constructed. | def __init__(self, c_list):
c_list = [NthOrderElasticTensor(c, check_rank=4+i*2)
for i, c in enumerate(c_list)]
super().__init__(c_list) | 140,995 |
Gets the Generalized Gruneisen tensor for a given
third-order elastic tensor expansion.
Args:
n (3x1 array-like): normal mode direction
u (3x1 array-like): polarization direction | def get_ggt(self, n, u):
gk = self[0].einsum_sequence([n, u, n, u])
result = -(2*gk*np.outer(u, u) + self[0].einsum_sequence([n, n])
+ self[1].einsum_sequence([n, u, n, u])) / (2*gk)
return result | 140,998 |
Finds directional frequency contribution to the heat
capacity from direction and polarization
Args:
structure (Structure): Structure to be used in directional heat
capacity determination
n (3x1 array-like): direction for Cv determination
u (3x1 array-... | def omega(self, structure, n, u):
l0 = np.dot(np.sum(structure.lattice.matrix, axis=0), n)
l0 *= 1e-10 # in A
weight = float(structure.composition.weight) * 1.66054e-27 # in kg
vol = structure.volume * 1e-30 # in m^3
vel = (1e9 * self[0].einsum_sequence([n, u, n, u])
... | 141,002 |
Returns the effective elastic constants
from the elastic tensor expansion.
Args:
strain (Strain or 3x3 array-like): strain condition
under which to calculate the effective constants
order (int): order of the ecs to be returned | def get_effective_ecs(self, strain, order=2):
ec_sum = 0
for n, ecs in enumerate(self[order-2:]):
ec_sum += ecs.einsum_sequence([strain] * n) / factorial(n)
return ec_sum | 141,006 |
Gets the Wallace Tensor for determining yield strength
criteria.
Args:
tau (3x3 array-like): stress at which to evaluate
the wallace tensor | def get_wallace_tensor(self, tau):
b = 0.5 * (np.einsum("ml,kn->klmn", tau, np.eye(3)) +
np.einsum("km,ln->klmn", tau, np.eye(3)) +
np.einsum("nl,km->klmn", tau, np.eye(3)) +
np.einsum("kn,lm->klmn", tau, np.eye(3)) +
-2*np.ein... | 141,007 |
Gets the symmetrized wallace tensor for determining
yield strength criteria.
Args:
tau (3x3 array-like): stress at which to evaluate
the wallace tensor. | def get_symmetric_wallace_tensor(self, tau):
wallace = self.get_wallace_tensor(tau)
return Tensor(0.5 * (wallace + np.transpose(wallace, [2, 3, 0, 1]))) | 141,008 |
Gets the stability criteria from the symmetric
Wallace tensor from an input vector and stress
value.
Args:
s (float): Stress value at which to evaluate
the stability criteria
n (3x1 array-like): direction of the applied
stress | def get_stability_criteria(self, s, n):
n = get_uvec(n)
stress = s * np.outer(n, n)
sym_wallace = self.get_symmetric_wallace_tensor(stress)
return np.linalg.det(sym_wallace.voigt) | 141,009 |
Gets the yield stress for a given direction
Args:
n (3x1 array-like): direction for which to find the
yield stress | def get_yield_stress(self, n):
# TODO: root finding could be more robust
comp = root(self.get_stability_criteria, -1, args=n)
tens = root(self.get_stability_criteria, 1, args=n)
return (comp.x, tens.x) | 141,010 |
Adds the skeleton of the Wigner-Seitz cell of the lattice to a matplotlib Axes
Args:
lattice: Lattice object
ax: matplotlib :class:`Axes` or None if a new figure should be created.
kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to black
and linewidth to ... | def plot_wigner_seitz(lattice, ax=None, **kwargs):
ax, fig, plt = get_ax3d_fig_plt(ax)
if "color" not in kwargs:
kwargs["color"] = "k"
if "linewidth" not in kwargs:
kwargs["linewidth"] = 1
bz = lattice.get_wigner_seitz_cell()
ax, fig, plt = get_ax3d_fig_plt(ax)
for iface i... | 141,065 |
Adds the basis vectors of the lattice provided to a matplotlib Axes
Args:
lattice: Lattice object
ax: matplotlib :class:`Axes` or None if a new figure should be created.
kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to green
and linewidth to 3.
Ret... | def plot_lattice_vectors(lattice, ax=None, **kwargs):
ax, fig, plt = get_ax3d_fig_plt(ax)
if "color" not in kwargs:
kwargs["color"] = "g"
if "linewidth" not in kwargs:
kwargs["linewidth"] = 3
vertex1 = lattice.get_cartesian_coords([0.0, 0.0, 0.0])
vertex2 = lattice.get_cartesi... | 141,066 |
Folds a point with coordinates p inside the first Brillouin zone of the lattice.
Args:
p: coordinates of one point
lattice: Lattice object used to convert from reciprocal to cartesian coordinates
coords_are_cartesian: Set to True if you are providing
coordinates in cartesian coo... | def fold_point(p, lattice, coords_are_cartesian=False):
if coords_are_cartesian:
p = lattice.get_fractional_coords(p)
else:
p = np.array(p)
p = np.mod(p + 0.5 - 1e-10, 1) - 0.5 + 1e-10
p = lattice.get_cartesian_coords(p)
closest_lattice_point = None
smallest_distance = 10... | 141,069 |
Gives the plot (as a matplotlib object) of the symmetry line path in
the Brillouin Zone.
Args:
kpath (HighSymmKpath): a HighSymmKPath object
ax: matplotlib :class:`Axes` or None if a new figure should be created.
**kwargs: provided by add_fig_kwargs decorator
Returns:
m... | def plot_brillouin_zone_from_kpath(kpath, ax=None, **kwargs):
lines = [[kpath.kpath['kpoints'][k] for k in p]
for p in kpath.kpath['path']]
return plot_brillouin_zone(bz_lattice=kpath.prim_rec, lines=lines, ax=ax,
labels=kpath.kpath['kpoints'], **kwargs) | 141,071 |
Adds a dos for plotting.
Args:
label:
label for the DOS. Must be unique.
dos:
Dos object | def add_dos(self, label, dos):
energies = dos.energies - dos.efermi if self.zero_at_efermi \
else dos.energies
densities = dos.get_smeared_densities(self.sigma) if self.sigma \
else dos.densities
efermi = dos.efermi
self._doses[label] = {'energies': energ... | 141,075 |
Get a matplotlib plot showing the DOS.
Args:
xlim: Specifies the x-axis limits. Set to None for automatic
determination.
ylim: Specifies the y-axis limits. | def get_plot(self, xlim=None, ylim=None):
ncolors = max(3, len(self._doses))
ncolors = min(9, ncolors)
import palettable
colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors
y = None
alldensities = []
allenergies = []
plt = pretty_plo... | 141,076 |
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits. | def save_plot(self, filename, img_format="eps", ylim=None,
zero_to_efermi=True, smooth=False):
plt = self.get_plot(ylim=ylim, zero_to_efermi=zero_to_efermi,
smooth=smooth)
plt.savefig(filename, format=img_format)
plt.close() | 141,080 |
plot two band structure for comparison. One is in red the other in blue
(no difference in spins). The two band structures need to be defined
on the same symmetry lines! and the distance between symmetry lines is
the one of the band structure used to build the BSPlotter
Args:
... | def plot_compare(self, other_plotter, legend=True):
# TODO: add exception if the band structures are not compatible
import matplotlib.lines as mlines
plt = self.get_plot()
data_orig = self.bs_plot_data()
data = other_plotter.bs_plot_data()
band_linewidth = 1
... | 141,081 |
Get a matplotlib plot object.
Args:
bs (BandStructureSymmLine): the bandstructure to plot. Projection
data must exist for projected plots.
dos (Dos): the Dos to plot. Projection data must exist (i.e.,
CompleteDos) for projected plots.
Returns:
... | def get_plot(self, bs, dos=None):
import matplotlib.lines as mlines
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as mplt
# make sure the user-specified band structure projection is valid
bs_projection = self.bs_projection
if dos:
... | 141,095 |
An RGB colored line for plotting.
creation of segments based on:
http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb
Args:
ax: matplotlib axis
k: x-axis data (k-points)
e: y-axis data (energies)
red:... | def _rgbline(ax, k, e, red, green, blue, alpha=1, linestyles="solid"):
from matplotlib.collections import LineCollection
pts = np.array([k, e]).T.reshape(-1, 1, 2)
seg = np.concatenate([pts[:-1], pts[1:]], axis=1)
nseg = len(k) - 1
r = [0.5 * (red[i] + red[i + 1]) for ... | 141,096 |
Get color data, including projected band structures
Args:
bs: Bandstructure object
elements: elements (in desired order) for setting to blue, red, green
bs_projection: None for no projection, "elements" for element projection
Returns: | def _get_colordata(bs, elements, bs_projection):
contribs = {}
if bs_projection and bs_projection.lower() == "elements":
projections = bs.get_projection_on_elements()
for spin in (Spin.up, Spin.down):
if spin in bs.bands:
contribs[spin] = []
... | 141,097 |
Plot the seebeck coefficient in function of Fermi level
Args:
temp:
the temperature
xlim:
a list of min and max fermi energy by default (0, and band gap)
Returns:
a matplotlib object | def plot_seebeck_mu(self, temp=600, output='eig', xlim=None):
import matplotlib.pyplot as plt
plt.figure(figsize=(9, 7))
seebeck = self._bz.get_seebeck(output=output, doping_levels=False)[
temp]
plt.plot(self._bz.mu_steps, seebeck,
linewidth=3.0)
... | 141,104 |
Plot the conductivity in function of Fermi level. Semi-log plot
Args:
temp: the temperature
xlim: a list of min and max fermi energy by default (0, and band
gap)
tau: A relaxation time in s. By default none and the plot is by
units of relaxatio... | def plot_conductivity_mu(self, temp=600, output='eig',
relaxation_time=1e-14, xlim=None):
import matplotlib.pyplot as plt
cond = self._bz.get_conductivity(relaxation_time=relaxation_time,
output=output, doping_levels=False)[
... | 141,105 |
Plot the power factor in function of Fermi level. Semi-log plot
Args:
temp: the temperature
xlim: a list of min and max fermi energy by default (0, and band
gap)
tau: A relaxation time in s. By default none and the plot is by
units of relaxatio... | def plot_power_factor_mu(self, temp=600, output='eig',
relaxation_time=1e-14, xlim=None):
import matplotlib.pyplot as plt
plt.figure(figsize=(9, 7))
pf = self._bz.get_power_factor(relaxation_time=relaxation_time,
output... | 141,106 |
Plot the ZT in function of Fermi level.
Args:
temp: the temperature
xlim: a list of min and max fermi energy by default (0, and band
gap)
tau: A relaxation time in s. By default none and the plot is by
units of relaxation time
Returns:... | def plot_zt_mu(self, temp=600, output='eig', relaxation_time=1e-14,
xlim=None):
import matplotlib.pyplot as plt
plt.figure(figsize=(9, 7))
zt = self._bz.get_zt(relaxation_time=relaxation_time, output=output,
doping_levels=False)[temp]
... | 141,107 |
Plot the Seebeck coefficient in function of temperature for different
doping levels.
Args:
dopings: the default 'all' plots all the doping levels in the analyzer.
Specify a list of doping levels if you want to plot only some.
output: with 'average' you get ... | def plot_seebeck_temp(self, doping='all', output='average'):
import matplotlib.pyplot as plt
if output == 'average':
sbk = self._bz.get_seebeck(output='average')
elif output == 'eigs':
sbk = self._bz.get_seebeck(output='eigs')
plt.figure(figsize=(22, 14... | 141,108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.