docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Get a reduced structure.
Args:
reduction_algo (str): The lattice reduction algorithm to use.
Currently supported options are "niggli" or "LLL". | def get_reduced_structure(self, reduction_algo="niggli"):
if reduction_algo == "niggli":
reduced_latt = self._lattice.get_niggli_reduced_lattice()
elif reduction_algo == "LLL":
reduced_latt = self._lattice.get_lll_reduced_lattice()
else:
raise ValueEr... | 139,084 |
Reconstitute a Structure object from a dict representation of Structure
created using as_dict().
Args:
d (dict): Dict representation of structure.
Returns:
Structure object | def from_dict(cls, d, fmt=None):
if fmt == "abivars":
from pymatgen.io.abinit.abiobjects import structure_from_abivars
return structure_from_abivars(cls=cls, **d)
lattice = Lattice.from_dict(d["lattice"])
sites = [PeriodicSite.from_dict(sd, lattice) for sd in d[... | 139,092 |
Convenience constructor to make a Molecule from a list of sites.
Args:
sites ([Site]): Sequence of Sites.
charge (int): Charge of molecule. Defaults to 0.
spin_multiplicity (int): Spin multicipity. Defaults to None,
in which it is determined automatically.
... | def from_sites(cls, sites, charge=0, spin_multiplicity=None,
validate_proximity=False):
props = collections.defaultdict(list)
for site in sites:
for k, v in site.properties.items():
props[k].append(v)
return cls([site.species for site in si... | 139,098 |
Determines the covalent bonds in a molecule.
Args:
tol (float): The tol to determine bonds in a structure. See
CovalentBond.is_bonded.
Returns:
List of bonds | def get_covalent_bonds(self, tol=0.2):
bonds = []
for site1, site2 in itertools.combinations(self._sites, 2):
if CovalentBond.is_bonded(site1, site2, tol):
bonds.append(CovalentBond(site1, site2))
return bonds | 139,100 |
Reconstitute a Molecule object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of Molecule.
Returns:
Molecule object | def from_dict(cls, d):
sites = [Site.from_dict(sd) for sd in d["sites"]]
charge = d.get("charge", 0)
spin_multiplicity = d.get("spin_multiplicity")
return cls.from_sites(sites, charge=charge, spin_multiplicity=spin_multiplicity) | 139,105 |
Find all sites within a sphere from a point.
Args:
pt (3x1 array): Cartesian coordinates of center of sphere.
r (float): Radius of sphere.
Returns:
[(site, dist) ...] since most of the time, subsequent processing
requires the distance. | def get_sites_in_sphere(self, pt, r):
neighbors = []
for site in self._sites:
dist = site.distance_from_point(pt)
if dist <= r:
neighbors.append((site, dist))
return neighbors | 139,106 |
Get all neighbors to a site within a sphere of radius r. Excludes the
site itself.
Args:
site (Site): Site at the center of the sphere.
r (float): Radius of sphere.
Returns:
[(site, dist) ...] since most of the time, subsequent processing
requir... | def get_neighbors(self, site, r):
nn = self.get_sites_in_sphere(site.coords, r)
return [(s, dist) for (s, dist) in nn if site != s] | 139,107 |
Returns all sites in a shell centered on origin (coords) between radii
r-dr and r+dr.
Args:
origin (3x1 array): Cartesian coordinates of center of sphere.
r (float): Inner radius of shell.
dr (float): Width of shell.
Returns:
[(site, dist) ...] s... | def get_neighbors_in_shell(self, origin, r, dr):
outer = self.get_sites_in_sphere(origin, r + dr)
inner = r - dr
return [(site, dist) for (site, dist) in outer if dist > inner] | 139,108 |
Reads a molecule from a file. Supported formats include xyz,
gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and
pymatgen's JSON serialized molecules. Using openbabel,
many more extensions are supported but requires openbabel to be
installed.
Args:
filena... | def from_file(cls, filename):
filename = str(filename)
from pymatgen.io.gaussian import GaussianOutput
with zopen(filename) as f:
contents = f.read()
fname = filename.lower()
if fnmatch(fname, "*.xyz*"):
return cls.from_str(contents, fmt="xyz")
... | 139,113 |
Remove all occurrences of several species from a structure.
Args:
species: Sequence of species to remove, e.g., ["Li", "Na"]. | def remove_species(self, species):
new_sites = []
species = [get_el_sp(s) for s in species]
for site in self._sites:
new_sp_occu = {sp: amt for sp, amt in site.species.items()
if sp not in species}
if len(new_sp_occu) > 0:
... | 139,121 |
Delete sites with at indices.
Args:
indices: Sequence of indices of sites to delete. | def remove_sites(self, indices):
self._sites = [s for i, s in enumerate(self._sites)
if i not in indices] | 139,122 |
Apply a symmetry operation to the structure and return the new
structure. The lattice is operated by the rotation matrix only.
Coords are operated in full and then transformed to the new lattice.
Args:
symmop (SymmOp): Symmetry operation to apply.
fractional (bool): Whet... | def apply_operation(self, symmop, fractional=False):
if not fractional:
self._lattice = Lattice([symmop.apply_rotation_only(row)
for row in self._lattice.matrix])
def operate_site(site):
new_cart = symmop.operate(site.coords)... | 139,123 |
Modify the lattice of the structure. Mainly used for changing the
basis.
Args:
new_lattice (Lattice): New lattice | def modify_lattice(self, new_lattice):
self._lattice = new_lattice
for site in self._sites:
site.lattice = new_lattice | 139,124 |
Apply a strain to the lattice.
Args:
strain (float or list): Amount of strain to apply. Can be a float,
or a sequence of 3 numbers. E.g., 0.01 means all lattice
vectors are increased by 1%. This is equivalent to calling
modify_lattice with a lattice w... | def apply_strain(self, strain):
s = (1 + np.array(strain)) * np.eye(3)
self.lattice = Lattice(np.dot(self._lattice.matrix.T, s).T) | 139,125 |
Translate specific sites by some vector, keeping the sites within the
unit cell.
Args:
indices: Integer or List of site indices on which to perform the
translation.
vector: Translation vector for sites.
frac_coords (bool): Whether the vector correspon... | def translate_sites(self, indices, vector, frac_coords=True,
to_unit_cell=True):
if not isinstance(indices, collections.abc.Iterable):
indices = [indices]
for i in indices:
site = self._sites[i]
if frac_coords:
fcoords... | 139,127 |
Rotate specific sites by some angle around vector at anchor.
Args:
indices (list): List of site indices on which to perform the
translation.
theta (float): Angle in radians
axis (3x1 array): Rotation axis vector.
anchor (3x1 array): Point of rotat... | def rotate_sites(self, indices=None, theta=0, axis=None, anchor=None,
to_unit_cell=True):
from numpy.linalg import norm
from numpy import cross, eye
from scipy.linalg import expm
if indices is None:
indices = range(len(self))
if axis i... | 139,128 |
Performs a random perturbation of the sites in a structure to break
symmetries.
Args:
distance (float): Distance in angstroms by which to perturb each
site. | def perturb(self, distance):
def get_rand_vec():
# deals with zero vectors.
vector = np.random.randn(3)
vnorm = np.linalg.norm(vector)
return vector / vnorm * distance if vnorm != 0 else get_rand_vec()
for i in range(len(self._sites)):
... | 139,129 |
Merges sites (adding occupancies) within tol of each other.
Removes site properties.
Args:
tol (float): Tolerance for distance to merge sites.
mode (str): Three modes supported. "delete" means duplicate sites are
deleted. "sum" means the occupancies are summed fo... | def merge_sites(self, tol=0.01, mode="sum"):
mode = mode.lower()[0]
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import fcluster, linkage
d = self.distance_matrix
np.fill_diagonal(d, 0)
clusters = fcluster(linkage(squareform((d + d.... | 139,131 |
Appends a site to the molecule.
Args:
species: Species of inserted site
coords: Coordinates of inserted site
validate_proximity (bool): Whether to check if inserted site is
too close to an existing site. Defaults to True.
properties (dict): A dict... | def append(self, species, coords, validate_proximity=True, properties=None):
return self.insert(len(self), species, coords,
validate_proximity=validate_proximity,
properties=properties) | 139,134 |
Set the charge and spin multiplicity.
Args:
charge (int): Charge for the molecule. Defaults to 0.
spin_multiplicity (int): Spin multiplicity for molecule.
Defaults to None, which means that the spin multiplicity is
set to 1 if the molecule has no unpaired... | def set_charge_and_spin(self, charge, spin_multiplicity=None):
self._charge = charge
nelectrons = 0
for site in self._sites:
for sp, amt in site.species.items():
if not isinstance(sp, DummySpecie):
nelectrons += sp.Z * amt
nelectro... | 139,135 |
Insert a site to the molecule.
Args:
i (int): Index to insert site
species: species of inserted site
coords (3x1 array): coordinates of inserted site
validate_proximity (bool): Whether to check if inserted site is
too close to an existing site. De... | def insert(self, i, species, coords, validate_proximity=False,
properties=None):
new_site = Site(species, coords, properties=properties)
if validate_proximity:
for site in self:
if site.distance(new_site) < self.DISTANCE_TOLERANCE:
... | 139,136 |
Remove all occurrences of a species from a molecule.
Args:
species: Species to remove. | def remove_species(self, species):
new_sites = []
species = [get_el_sp(sp) for sp in species]
for site in self._sites:
new_sp_occu = {sp: amt for sp, amt in site.species.items()
if sp not in species}
if len(new_sp_occu) > 0:
... | 139,137 |
Delete sites with at indices.
Args:
indices: Sequence of indices of sites to delete. | def remove_sites(self, indices):
self._sites = [self._sites[i] for i in range(len(self._sites))
if i not in indices] | 139,138 |
Translate specific sites by some vector, keeping the sites within the
unit cell.
Args:
indices (list): List of site indices on which to perform the
translation.
vector (3x1 array): Translation vector for sites. | def translate_sites(self, indices=None, vector=None):
if indices is None:
indices = range(len(self))
if vector is None:
vector == [0, 0, 0]
for i in indices:
site = self._sites[i]
new_site = Site(site.species, site.coords + vector,
... | 139,139 |
Apply a symmetry operation to the molecule.
Args:
symmop (SymmOp): Symmetry operation to apply. | def apply_operation(self, symmop):
def operate_site(site):
new_cart = symmop.operate(site.coords)
return Site(site.species, new_cart,
properties=site.properties)
self._sites = [operate_site(s) for s in self._sites] | 139,140 |
create the polymer from the monomer
Args:
monomer (Molecule)
mon_vector (numpy.array): molecule vector that starts from the
start atom index to the end atom index | def _create(self, monomer, mon_vector):
while self.length != (self.n_units-1):
if self.linear_chain:
move_direction = np.array(mon_vector) / np.linalg.norm(mon_vector)
else:
move_direction = self._next_move_direction()
self._add_monome... | 139,145 |
rotate the monomer so that it is aligned along the move direction
Args:
monomer (Molecule)
mon_vector (numpy.array): molecule vector that starts from the
start atom index to the end atom index
move_direction (numpy.array): the direction of the polymer chain
... | def _align_monomer(self, monomer, mon_vector, move_direction):
axis = np.cross(mon_vector, move_direction)
origin = monomer[self.start].coords
angle = get_angle(mon_vector, move_direction)
op = SymmOp.from_origin_axis_angle(origin, axis, angle)
monomer.apply_operation(op... | 139,147 |
extend the polymer molecule by adding a monomer along mon_vector direction
Args:
monomer (Molecule): monomer molecule
mon_vector (numpy.array): monomer vector that points from head to tail.
move_direction (numpy.array): direction along which the monomer
will ... | def _add_monomer(self, monomer, mon_vector, move_direction):
translate_by = self.molecule.cart_coords[self.end] + \
self.link_distance * move_direction
monomer.translate_sites(range(len(monomer)), translate_by)
if not self.linear_chain:
self._align_mon... | 139,148 |
Internal method to format values in the packmol parameter dictionaries
Args:
param_val:
Some object to turn into String
Returns:
string representation of the object | def _format_param_val(self, param_val):
if isinstance(param_val, list):
return ' '.join(str(x) for x in param_val)
else:
return str(param_val) | 139,150 |
Write the packmol input file to the input directory.
Args:
input_dir (string): path to the input directory | def _write_input(self, input_dir="."):
with open(os.path.join(input_dir, self.input_file), 'wt', encoding="utf-8") as inp:
for k, v in self.control_params.items():
inp.write('{} {}\n'.format(k, self._format_param_val(v)))
# write the structures of the constituent... | 139,152 |
Write the input file to the scratch directory, run packmol and return
the packed molecule.
Args:
copy_to_current_on_exit (bool): Whether or not to copy the packmol
input/output files from the scratch directory to the current
directory.
site_proper... | def run(self, copy_to_current_on_exit=False, site_property=None):
scratch = tempfile.gettempdir()
with ScratchDir(scratch, copy_to_current_on_exit=copy_to_current_on_exit) as scratch_dir:
self._write_input(input_dir=scratch_dir)
packmol_input = open(os.path.join(scratch_... | 139,153 |
Convert list of openbabel atoms to MOlecule.
Args:
atoms ([OBAtom]): list of OBAtom objects
residue_name (str): the key in self.map_residue_to_mol. Usec to
restore the site properties in the final packed molecule.
site_property (str): the site property to be ... | def convert_obatoms_to_molecule(self, atoms, residue_name=None, site_property="ff_map"):
restore_site_props = True if residue_name is not None else False
if restore_site_props and not hasattr(self, "map_residue_to_mol"):
self._set_residue_map()
coords = []
zs = []... | 139,156 |
Restore the site properties for the final packed molecule.
Args:
site_property (str):
filename (str): path to the final packed molecule.
Returns:
Molecule | def restore_site_properties(self, site_property="ff_map", filename=None):
# only for pdb
if not self.control_params["filetype"] == "pdb":
raise ValueError()
filename = filename or self.control_params["output"]
bma = BabelMolAdaptor.from_file(filename, "pdb")
... | 139,157 |
LAMMPS wrapper
Args:
input_filename (string): input file name
bin (string): command to run, excluding the input file name | def __init__(self, input_filename="lammps.in", bin="lammps"):
self.lammps_bin = bin.split()
if not which(self.lammps_bin[-1]):
raise RuntimeError(
"LammpsRunner requires the executable {} to be in the path. "
"Please download and install LAMMPS from "... | 139,158 |
Get an element from an atomic number.
Args:
z (int): Atomic number
Returns:
Element with atomic number z. | def from_Z(z: int):
for sym, data in _pt_data.items():
if data["Atomic no"] == z:
return Element(sym)
raise ValueError("No element with this atomic number %s" % z) | 139,175 |
Returns an element from a row and group number.
Args:
row (int): Row number
group (int): Group number
.. note::
The 18 group number system is used, i.e., Noble gases are group 18. | def from_row_and_group(row: int, group: int):
for sym in _pt_data.keys():
el = Element(sym)
if el.row == row and el.group == group:
return el
raise ValueError("No element with this row and group!") | 139,176 |
A pretty ASCII printer for the periodic table, based on some
filter_function.
Args:
filter_function: A filtering function taking an Element as input
and returning a boolean. For example, setting
filter_function = lambda el: el.X > 2 will print a periodic
... | def print_periodic_table(filter_function: callable = None):
for row in range(1, 10):
rowstr = []
for group in range(1, 19):
try:
el = Element.from_row_and_group(row, group)
except ValueError:
el = None
... | 139,184 |
Returns a Specie from a string representation.
Args:
species_string (str): A typical string representation of a
species, e.g., "Mn2+", "Fe3+", "O2-".
Returns:
A Specie object.
Raises:
ValueError if species_string cannot be intepreted. | def from_string(species_string: str):
m = re.search(r"([A-Z][a-z]*)([0-9.]*)([+\-])(.*)", species_string)
if m:
sym = m.group(1)
oxi = 1 if m.group(2) == "" else float(m.group(2))
oxi = -oxi if m.group(3) == "-" else oxi
properties = None
... | 139,190 |
Gets the nuclear electric quadrupole moment in units of
e*millibarns
Args:
isotope (str): the isotope to get the quadrupole moment for
default is None, which gets the lowest mass isotope | def get_nmr_quadrupole_moment(self, isotope=None):
quad_mom = self._el.nmr_quadrupole_moment
if len(quad_mom) == 0:
return 0.0
if isotope is None:
isotopes = list(quad_mom.keys())
isotopes.sort(key=lambda x: int(x.split("-")[1]), reverse=False)
... | 139,192 |
Returns a Dummy from a string representation.
Args:
species_string (str): A string representation of a dummy
species, e.g., "X2+", "X3+".
Returns:
A DummySpecie object.
Raises:
ValueError if species_string cannot be intepreted. | def from_string(species_string: str):
m = re.search(r"([A-Z][a-z]*)([0-9.]*)([+\-]*)(.*)", species_string)
if m:
sym = m.group(1)
if m.group(2) == "" and m.group(3) == "":
oxi = 0
else:
oxi = 1 if m.group(2) == "" else float(m.... | 139,199 |
Find the symmetric operations of the reciprocal lattice,
to be used for hkl transformations
Args:
structure (Structure): conventional unit cell
symprec: default is 0.001 | def get_recp_symmetry_operation(structure, symprec=0.01):
recp_lattice = structure.lattice.reciprocal_lattice_crystallographic
# get symmetry operations from input conventional unit cell
# Need to make sure recp lattice is big enough, otherwise symmetry
# determination will fail. We set the overall... | 139,213 |
Returns all symmetrically distinct indices below a certain max-index for
a given structure. Analysis is based on the symmetry of the reciprocal
lattice of the structure.
Args:
structure (Structure): input structure.
max_index (int): The maximum index. For example, a max_index of 1
... | def get_symmetrically_distinct_miller_indices(structure, max_index):
r = list(range(-max_index, max_index + 1))
r.reverse()
# First we get a list of all hkls for conventional (including equivalent)
conv_hkl_list = [miller for miller in itertools.product(r, r, r) if any([i != 0 for i in miller])]
... | 139,214 |
Returns the Miller index from setting
A to B using a transformation matrix
Args:
transf (3x3 array): The transformation matrix
that transforms a lattice of A to B
miller_index ([h, k, l]): Miller index to transform to setting B | def hkl_transformation(transf, miller_index):
# Get a matrix of whole numbers (ints)
lcm = lambda a, b: a * b // math.gcd(a, b)
reduced_transf = reduce(lcm, [int(1 / i) for i in itertools.chain(*transf) if i != 0]) * transf
reduced_transf = reduced_transf.astype(int)
# perform the transformati... | 139,215 |
Function to get the ranges of the slab regions. Useful for discerning where
the slab ends and vacuum begins if the slab is not fully within the cell
Args:
slab (Structure): Structure object modelling the surface
blength (float, Ang): The bondlength between atoms. You generally
want t... | def get_slab_regions(slab, blength=3.5):
fcoords, indices, all_indices = [], [], []
for site in slab:
# find sites with c < 0 (noncontiguous)
neighbors = slab.get_neighbors(site, blength, include_index=True,
include_image=True)
for nn in neigh... | 139,217 |
Checks if slab is symmetric, i.e., contains inversion symmetry.
Args:
symprec (float): Symmetry precision used for SpaceGroup analyzer.
Returns:
(bool) Whether slab contains inversion symmetry. | def is_symmetric(self, symprec=0.1):
sg = SpacegroupAnalyzer(self, symprec=symprec)
return sg.is_laue() | 139,224 |
Gets the structure of single atom adsorption.
slab structure from the Slab class(in [0, 0, 1])
Args:
indices ([int]): Indices of sites on which to put the absorbate.
Absorbed atom will be displaced relative to the center of
these sites.
specie (Sp... | def add_adsorbate_atom(self, indices, specie, distance):
# Let's do the work in cartesian coords
center = np.sum([self[i].coords for i in indices], axis=0) / len(
indices)
coords = center + self.normal * distance / np.linalg.norm(self.normal)
self.append(specie, co... | 139,232 |
Creates an Incar object.
Args:
params (dict): A set of input parameters as a dictionary. | def __init__(self, params=None):
super().__init__()
if params:
# if Incar contains vector-like magmoms given as a list
# of floats, convert to a list of lists
if (params.get("MAGMOM") and isinstance(params["MAGMOM"][0], (int, float))) \
a... | 139,263 |
Returns a string representation of the INCAR. The reason why this
method is different from the __str__ method is to provide options for
pretty printing.
Args:
sort_keys (bool): Set to True to sort the INCAR parameters
alphabetically. Defaults to False.
p... | def get_string(self, sort_keys=False, pretty=False):
keys = self.keys()
if sort_keys:
keys = sorted(keys)
lines = []
for k in keys:
if k == "MAGMOM" and isinstance(self[k], list):
value = []
if (isinstance(self[k][0], list... | 139,267 |
Reads an Incar object from a string.
Args:
string (str): Incar string
Returns:
Incar object | def from_string(string):
lines = list(clean_lines(string.splitlines()))
params = {}
for line in lines:
for sline in line.split(';'):
m = re.match(r'(\w+)\s*=\s*(.*)', sline.strip())
if m:
key = m.group(1).strip()
... | 139,268 |
Static helper method to convert INCAR parameters to proper types, e.g.,
integers, floats, lists, etc.
Args:
key: INCAR parameter key
val: Actual value of INCAR parameter. | def proc_val(key, val):
list_keys = ("LDAUU", "LDAUL", "LDAUJ", "MAGMOM", "DIPOL",
"LANGEVIN_GAMMA", "QUAD_EFG", "EINT")
bool_keys = ("LDAU", "LWAVE", "LSCALU", "LCHARG", "LPLANE", "LUSE_VDW",
"LHFCALC", "ADDGRID", "LSORBIT", "LNONCOLLINEAR")
fl... | 139,269 |
Convenient static constructor for an automatic Gamma centered Kpoint
grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice
vectors. Defaults to (1,1,1)
shift: Shift to be applied to the kpoints. Defaults to (0,0,0).
Returns:
... | def gamma_automatic(kpts=(1, 1, 1), shift=(0, 0, 0)):
return Kpoints("Automatic kpoint scheme", 0,
Kpoints.supported_modes.Gamma, kpts=[kpts],
kpts_shift=shift) | 139,275 |
Convenient static constructor for an automatic Monkhorst pack Kpoint
grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice
vectors. Defaults to (2,2,2)
shift: Shift to be applied to the kpoints. Defaults to (0,0,0).
Returns:
... | def monkhorst_automatic(kpts=(2, 2, 2), shift=(0, 0, 0)):
return Kpoints("Automatic kpoint scheme", 0,
Kpoints.supported_modes.Monkhorst, kpts=[kpts],
kpts_shift=shift) | 139,276 |
Returns an automatic Kpoint object based on a structure and a kpoint
density. Uses Gamma centered meshes always. For GW.
Algorithm:
Uses a simple approach scaling the number of divisions along each
reciprocal lattice vector proportional to its length.
Args:
... | def automatic_gamma_density(structure, kppa):
latt = structure.lattice
lengths = latt.abc
ngrid = kppa / structure.num_sites
mult = (ngrid * lengths[0] * lengths[1] * lengths[2]) ** (1 / 3)
num_div = [int(round(mult / l)) for l in lengths]
# ensure that numDiv... | 139,278 |
Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Structure): Input structure
kppvol (int): Grid density per Angstrom^(-3) of recipr... | def automatic_density_by_vol(structure, kppvol, force_gamma=False):
vol = structure.lattice.reciprocal_lattice.volume
kppa = kppvol * vol * structure.num_sites
return Kpoints.automatic_density(structure, kppa,
force_gamma=force_gamma) | 139,279 |
Convenient static constructor for a KPOINTS in mode line_mode.
gamma centered Monkhorst-Pack grids and the number of subdivisions
along each reciprocal lattice vector determined by the scheme in the
VASP manual.
Args:
divisions: Parameter determining the number of k-points a... | def automatic_linemode(divisions, ibz):
kpoints = list()
labels = list()
for path in ibz.kpath["path"]:
kpoints.append(ibz.kpath["kpoints"][path[0]])
labels.append(path[0])
for i in range(1, len(path) - 1):
kpoints.append(ibz.kpath["kp... | 139,280 |
Reads a Kpoints object from a KPOINTS string.
Args:
string (str): KPOINTS string.
Returns:
Kpoints object | def from_string(string):
lines = [line.strip() for line in string.splitlines()]
comment = lines[0]
num_kpts = int(lines[1].split()[0].strip())
style = lines[2].lower()[0]
# Fully automatic KPOINTS
if style == "a":
return Kpoints.automatic(int(lines[... | 139,281 |
Write VASP input to a directory.
Args:
output_dir (str): Directory to write to. Defaults to current
directory (".").
make_dir_if_not_present (bool): Create the directory if not
present. Defaults to True. | def write_input(self, output_dir=".", make_dir_if_not_present=True):
if make_dir_if_not_present and not os.path.exists(output_dir):
os.makedirs(output_dir)
for k, v in self.items():
with zopen(os.path.join(output_dir, k), "wt") as f:
f.write(v.__str__()) | 139,299 |
Read in a set of VASP input from a directory. Note that only the
standard INCAR, POSCAR, POTCAR and KPOINTS files are read unless
optional_filenames is specified.
Args:
input_dir (str): Directory to read VASP input from.
optional_files (dict): Optional files to read in a... | def from_directory(input_dir, optional_files=None):
sub_d = {}
for fname, ftype in [("INCAR", Incar), ("KPOINTS", Kpoints),
("POSCAR", Poscar), ("POTCAR", Potcar)]:
fullzpath = zpath(os.path.join(input_dir, fname))
sub_d[fname.lower()] = ftyp... | 139,300 |
Get the simplex facets for the Convex hull.
Args:
qhull_data (np.ndarray): The data from which to construct the convex
hull as a Nxd array (N being number of data points and d being the
dimension)
joggle (boolean): Whether to joggle the input to avoid precision
e... | def get_facets(qhull_data, joggle=False):
if joggle:
return ConvexHull(qhull_data, qhull_options="QJ i").simplices
else:
return ConvexHull(qhull_data, qhull_options="Qt i").simplices | 139,303 |
Given all the facets, convert it into a set of unique lines. Specifically
used for converting convex hull facets into line pairs of coordinates.
Args:
q: A 2-dim sequence, where each row represents a facet. E.g.,
[[1,2,3],[3,6,7],...]
Returns:
setoflines:
A set of ... | def uniquelines(q):
setoflines = set()
for facets in q:
for line in itertools.combinations(facets, 2):
setoflines.add(tuple(sorted(line)))
return setoflines | 139,304 |
Convert a 2D coordinate into a triangle-based coordinate system for a
prettier phase diagram.
Args:
coordinate: coordinate used in the convex hull computation.
Returns:
coordinates in a triangular-based coordinate system. | def triangular_coord(coord):
unitvec = np.array([[1, 0], [0.5, math.sqrt(3) / 2]])
result = np.dot(np.array(coord), unitvec)
return result.transpose() | 139,305 |
Standard constructor for phase diagram.
Args:
entries ([PDEntry]): A list of PDEntry-like objects having an
energy, energy_per_atom and composition.
elements ([Element]): Optional list of elements in the phase
diagram. If set to None, the elements are det... | def __init__(self, entries, elements=None):
if elements is None:
elements = set()
for entry in entries:
elements.update(entry.composition.elements)
elements = list(elements)
dim = len(elements)
get_reduced_comp = lambda e: e.composition.r... | 139,320 |
Returns the formation energy for an entry (NOT normalized) from the
elemental references.
Args:
entry: A PDEntry-like object.
Returns:
Formation energy from the elemental references. | def get_form_energy(self, entry):
c = entry.composition
return entry.energy - sum([c[el] * self.el_refs[el].energy_per_atom
for el in c.elements]) | 139,323 |
Calculates the chemical potentials for each element within a facet.
Args:
facet: Facet of the phase diagram.
Returns:
{ element: chempot } for all elements in the phase diagram. | def _get_facet_chempots(self, facet):
complist = [self.qhull_entries[i].composition for i in facet]
energylist = [self.qhull_entries[i].energy_per_atom for i in facet]
m = [[c.get_atomic_fraction(e) for e in self.elements] for c in
complist]
chempots = np.linalg.sol... | 139,327 |
Provides the decomposition at a particular composition.
Args:
comp: A composition
Returns:
Decomposition as a dict of {Entry: amount} | def get_decomposition(self, comp):
facet, simplex = self._get_facet_and_simplex(comp)
decomp_amts = simplex.bary_coords(self.pd_coords(comp))
return {self.qhull_entries[f]: amt
for f, amt in zip(facet, decomp_amts)
if abs(amt) > PhaseDiagram.numerical_tol... | 139,328 |
Provides the reaction energy of a stable entry from the neighboring
equilibrium stable entries (also known as the inverse distance to
hull).
Args:
entry: A PDEntry like object
Returns:
Equilibrium reaction energy of entry. Stable entries should have
... | def get_equilibrium_reaction_energy(self, entry):
if entry not in self.stable_entries:
raise ValueError("Equilibrium reaction energy is available only "
"for stable entries.")
if entry.is_element:
return 0
entries = [e for e in self.s... | 139,331 |
Get the critical chemical potentials for an element in the Phase
Diagram.
Args:
element: An element. Has to be in the PD in the first place.
Returns:
A sorted sequence of critical chemical potentials, from less
negative to more negative. | def get_transition_chempots(self, element):
if element not in self.elements:
raise ValueError("get_transition_chempots can only be called with "
"elements in the phase diagram.")
critical_chempots = []
for facet in self.facets:
chemp... | 139,334 |
Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition): compositions that define the tieline
Returns:
[(Composition)]: list of critic... | def get_critical_compositions(self, comp1, comp2):
n1 = comp1.num_atoms
n2 = comp2.num_atoms
pd_els = self.elements
# the reduced dimensionality Simplexes don't use the
# first element in the PD
c1 = self.pd_coords(comp1)
c2 = self.pd_coords(comp2)
... | 139,335 |
Writes the phase diagram to an image in a stream.
Args:
stream:
stream to write to. Can be a file stream or a StringIO stream.
image_format
format for image. Can be any of matplotlib supported formats.
Defaults to svg for best results for ... | def write_image(self, stream, image_format="svg", **kwargs):
plt = self.get_plot(**kwargs)
f = plt.gcf()
f.set_size_inches((12, 10))
plt.savefig(stream, format=image_format) | 139,356 |
Writes a set of FEFF input to a directory.
Args:
output_dir: Directory to output the FEFF input files
make_dir_if_not_present: Set to True if you want the directory (
and the whole path) to be created if it is not present. | def write_input(self, output_dir=".", make_dir_if_not_present=True):
if make_dir_if_not_present and not os.path.exists(output_dir):
os.makedirs(output_dir)
feff = self.all_input()
feff_input = "\n\n".join(str(feff[k]) for k in
["HEADER", "P... | 139,361 |
Method that creates two quarter-ellipse functions based on points xx and yy. The ellipsis is supposed to
be aligned with the axes. The two ellipsis pass through the two points xx and yy.
Args:
xx:
First point
yy:
Second point
Returns:
A dictionary with the l... | def quarter_ellipsis_functions(xx, yy):
npxx = np.array(xx)
npyy = np.array(yy)
if np.any(npxx == npyy):
raise RuntimeError('Invalid points for quarter_ellipsis_functions')
if np.all(npxx < npyy) or np.all(npxx > npyy):
if npxx[0] < npyy[0]:
p1 = npxx
p2 = np... | 139,371 |
Method that creates two (upper and lower) spline functions based on points lower_points and upper_points.
Args:
lower_points:
Points defining the lower function.
upper_points:
Points defining the upper function.
degree:
Degree for the spline function
... | def spline_functions(lower_points, upper_points, degree=3):
lower_xx = np.array([pp[0] for pp in lower_points])
lower_yy = np.array([pp[1] for pp in lower_points])
upper_xx = np.array([pp[0] for pp in upper_points])
upper_yy = np.array([pp[1] for pp in upper_points])
lower_spline = UnivariateS... | 139,372 |
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center:
Center to measure solid angle from.
coords:
List of coords to determine solid angle.
Returns:
The solid angle. | def my_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]))
phi = 0.0
for i in range(len(n) - 1):
try:
value = math.acos(-np.dot... | 139,375 |
Adds two COHP together. Checks that energy scales are the same.
Otherwise, it raises a ValueError. It also adds ICOHP if present.
If ICOHP is only present in one object, it displays a warning and
will not add ICOHP.
Args:
other: Another COHP object.
Returns:
... | def __add__(self, other):
if not all(np.equal(self.energies, other.energies)):
raise ValueError("Energies of both COHP are not compatible.")
populations = {spin: self.populations[spin] + other.populations[spin]
for spin in self.cohp}
if self.icohp is n... | 139,418 |
Returns the COHP or ICOHP for a particular spin.
Args:
spin: Spin. Can be parsed as spin object, integer (-1/1)
or str ("up"/"down")
integrated: Return COHP (False) or ICOHP (True)
Returns:
Returns the CHOP or ICOHP for the input spin. If Spin is
... | def get_cohp(self, spin=None, integrated=False):
if not integrated:
populations = self.cohp
else:
populations = self.icohp
if populations is None:
return None
elif spin is None:
return populations
else:
if isin... | 139,421 |
Returns the COHP for a particular energy.
Args:
energy: Energy to return the COHP value for. | def get_interpolated_value(self, energy, integrated=False):
inter = {}
for spin in self.cohp:
if not integrated:
inter[spin] = get_linear_interpolated_value(self.energies,
self.cohp[spin],
... | 139,422 |
Get specific COHP object.
Args:
label: string (for newer Lobster versions: a number)
Returns:
Returns the COHP object to simplify plotting | def get_cohp_by_label(self, label):
if label.lower() == "average":
return Cohp(efermi=self.efermi, energies=self.energies,
cohp=self.cohp, are_coops=self.are_coops, icohp=self.icohp)
else:
try:
return Cohp(efermi=self.efermi, energ... | 139,428 |
Returns a COHP object that includes a summed COHP divided by divisor
Args:
label_list: list of labels for the COHP that should be included in the summed cohp
divisor: float/int, the summed cohp will be divided by this divisor
Returns:
Returns a COHP object including ... | def get_summed_cohp_by_label_list(self, label_list, divisor=1):
# check if cohps are spinpolarized or not
first_cohpobject = self.get_cohp_by_label(label_list[0])
summed_cohp = first_cohpobject.cohp.copy()
summed_icohp = first_cohpobject.icohp.copy()
for label in label_l... | 139,429 |
Returns a COHP object that includes a summed COHP divided by divisor
Args:
label_list: list of labels for the COHP that should be included in the summed cohp
orbital_list: list of orbitals for the COHPs that should be included in the summed cohp (same order as label_list)
di... | def get_summed_cohp_by_label_and_orbital_list(self, label_list, orbital_list, divisor=1):
# check if cohps are spinpolarized or not
first_cohpobject = self.get_orbital_resolved_cohp(label_list[0], orbital_list[0])
summed_cohp = first_cohpobject.cohp.copy()
summed_icohp = first_c... | 139,430 |
get a dict of IcohpValues corresponding to certaind bond lengths
Args:
minbondlength: defines the minimum of the bond lengths of the bonds
maxbondlength: defines the maximum of the bond lengths of the bonds
Returns:
dict of IcohpValues, the keys correspond to the val... | def get_icohp_dict_by_bondlengths(self, minbondlength=0.0, maxbondlength=8.0):
newicohp_dict = {}
for value in self._icohplist.values():
if value._length >= minbondlength and value._length <= maxbondlength:
newicohp_dict[value._label] = value
return newicohp_... | 139,442 |
get ICOHP/ICOOP of strongest bond
Args:
summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed
spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned
Returns:
lowe... | def extremum_icohpvalue(self, summed_spin_channels=True, spin=Spin.up):
if not self._are_coops:
extremum = sys.float_info.max
else:
extremum = -sys.float_info.max
if not self._is_spin_polarized:
if spin == Spin.down:
warnings.warn("Th... | 139,444 |
Get distance between two sites.
Args:
other: Other site.
Returns:
Distance (float) | def distance(self, other):
return np.linalg.norm(other.coords - self.coords) | 139,448 |
Returns distance between the site and a point in space.
Args:
pt: Cartesian coordinates of point.
Returns:
Distance (float) | def distance_from_point(self, pt):
return np.linalg.norm(np.array(pt) - self.coords) | 139,449 |
Returns True if sites are periodic images of each other.
Args:
other (PeriodicSite): Other site
tolerance (float): Tolerance to compare fractional coordinates
check_lattice (bool): Whether to check if the two sites have the
same lattice.
Returns:
... | def is_periodic_image(self, other, tolerance=1e-8, check_lattice=True):
if check_lattice and self.lattice != other.lattice:
return False
if self.species != other.species:
return False
frac_diff = pbc_diff(self.frac_coords, other.frac_coords)
return np.al... | 139,467 |
Json-serializable dict representation of PeriodicSite.
Args:
verbosity (int): Verbosity level. Default of 0 only includes the
matrix representation. Set to 1 for more details such as
cartesian coordinates, etc. | def as_dict(self, verbosity=0):
species_list = []
for spec, occu in self._species.items():
d = spec.as_dict()
del d["@module"]
del d["@class"]
d["occu"] = occu
species_list.append(d)
d = {"species": species_list,
... | 139,470 |
Finds all symmetrically equivalent sites for a particular site
Args:
site (PeriodicSite): A site in the structure
Returns:
([PeriodicSite]): List of all symmetrically equivalent sites. | def find_equivalent_sites(self, site):
for sites in self.equivalent_sites:
if site in sites:
return sites
raise ValueError("Site not in structure") | 139,480 |
Read an FiestaInput from a string. Currently tested to work with
files generated from this class itself.
Args:
string_input: string_input to parse.
Returns:
FiestaInput object | def from_string(cls, string_input):
correlation_grid = {}
Exc_DFT_option = {}
COHSEX_options = {}
GW_options = {}
BSE_TDDFT_options = {}
lines = string_input.strip().split("\n")
# number of atoms and species
lines.pop(0)
l = lines.pop(0... | 139,504 |
Read an Fiesta input from a file. Currently tested to work with
files generated from this class itself.
Args:
filename: Filename to parse.
Returns:
FiestaInput object | def from_file(cls, filename):
with zopen(filename) as f:
return cls.from_string(f.read()) | 139,505 |
Initializes a transformed structure from a structure.
Args:
structure (Structure): Input structure
transformations ([Transformations]): List of transformations to
apply.
history (list): Previous history.
other_parameters (dict): Additional paramet... | def __init__(self, structure, transformations=None, history=None,
other_parameters=None):
self.final_structure = structure
self.history = history or []
self.other_parameters = other_parameters or {}
self._undone = []
transformations = transformations or... | 139,510 |
Adds a filter.
Args:
structure_filter (StructureFilter): A filter implementating the
AbstractStructureFilter API. Tells transmuter waht structures
to retain. | def append_filter(self, structure_filter):
hdict = structure_filter.as_dict()
hdict["input_structure"] = self.final_structure.as_dict()
self.history.append(hdict) | 139,515 |
Extends a sequence of transformations to the TransformedStructure.
Args:
transformations: Sequence of Transformations
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a nu... | def extend_transformations(self, transformations,
return_alternatives=False):
for t in transformations:
self.append_transformation(t,
return_alternatives=return_alternatives) | 139,516 |
Returns VASP input as a dict of vasp objects.
Args:
vasp_input_set (pymatgen.io.vaspio_set.VaspInputSet): input set
to create vasp input files from structures | def get_vasp_input(self, vasp_input_set=MPRelaxSet, **kwargs):
d = vasp_input_set(self.final_structure, **kwargs).get_vasp_input()
d["transformations.json"] = json.dumps(self.as_dict())
return d | 139,517 |
Writes VASP input to an output_dir.
Args:
vasp_input_set:
pymatgen.io.vaspio_set.VaspInputSet like object that creates
vasp input files from structures
output_dir: Directory to output files
create_directory: Create the directory if not present... | def write_vasp_input(self, vasp_input_set=MPRelaxSet, output_dir=".",
create_directory=True, **kwargs):
vasp_input_set(self.final_structure, **kwargs).write_input(
output_dir, make_dir_if_not_present=create_directory)
with open(os.path.join(output_dir, "tran... | 139,518 |
Generates TransformedStructure from a poscar string.
Args:
poscar_string (str): Input POSCAR string.
transformations ([Transformations]): Sequence of transformations
to be applied to the input structure. | def from_poscar_string(poscar_string, transformations=None):
p = Poscar.from_string(poscar_string)
if not p.true_names:
raise ValueError("Transformation can be craeted only from POSCAR "
"strings with proper VASP5 element symbols.")
raw_string = ... | 139,522 |
Create TransformedStructure from SNL.
Args:
snl (StructureNL): Starting snl
Returns:
TransformedStructure | def from_snl(cls, snl):
hist = []
for h in snl.history:
d = h.description
d['_snl'] = {'url': h.url, 'name': h.name}
hist.append(d)
return cls(snl.structure, history=hist) | 139,526 |
Creates LDos object from raw Feff ldos files by
by assuming they are numbered consecutively, i.e. ldos01.dat
ldos02.dat...
Args:
feff_inp_file (str): input file of run to obtain structure
ldos_file (str): output ldos file of run to obtain dos info, etc. | def from_file(feff_inp_file='feff.inp', ldos_file='ldos'):
header_str = Header.header_string_from_file(feff_inp_file)
header = Header.from_string(header_str)
structure = header.struct
nsites = structure.num_sites
parameters = Tags.from_file(feff_inp_file)
if "RE... | 139,528 |
Get charge transfer from file.
Args:
feff_inp_file (str): name of feff.inp file for run
ldos_file (str): ldos filename for run, assume consequetive order,
i.e., ldos01.dat, ldos02.dat....
Returns:
dictionary of dictionaries in order of potential site... | def charge_transfer_from_file(feff_inp_file, ldos_file):
cht = OrderedDict()
parameters = Tags.from_file(feff_inp_file)
if 'RECIPROCAL' in parameters:
dicts = [dict()]
pot_dict = dict()
dos_index = 1
begin = 0
pot_inp = re.sub... | 139,529 |
Get Xmu from file.
Args:
xmu_dat_file (str): filename and path for xmu.dat
feff_inp_file (str): filename and path of feff.inp input file
Returns:
Xmu object | def from_file(xmu_dat_file="xmu.dat", feff_inp_file="feff.inp"):
data = np.loadtxt(xmu_dat_file)
header = Header.from_file(feff_inp_file)
parameters = Tags.from_file(feff_inp_file)
pots = Potential.pot_string_from_file(feff_inp_file)
# site index (Note: in feff it starts... | 139,532 |
Returns a list of unique symmetrically equivalent k-points.
Args:
kpoint (1x3 array): coordinate of the k-point
cartesian (bool): kpoint is in cartesian or fractional coordinates
tol (float): tolerance below which coordinates are considered equal
Returns:
... | def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol=1e-2):
if not self.structure:
return None
sg = SpacegroupAnalyzer(self.structure)
symmops = sg.get_point_group_operations(cartesian=cartesian)
points = np.dot(kpoint, [m.rotation_matrix for m in symmops])
... | 139,570 |
Returns degeneracy of a given k-point based on structure symmetry
Args:
kpoint (1x3 array): coordinate of the k-point
cartesian (bool): kpoint is in cartesian or fractional coordinates
tol (float): tolerance below which coordinates are considered equal
Returns:
... | def get_kpoint_degeneracy(self, kpoint, cartesian=False, tol=1e-2):
all_kpts = self.get_sym_eq_kpoints(kpoint, cartesian, tol=tol)
if all_kpts is not None:
return len(all_kpts) | 139,571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.