docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
---|---|---|
apply the transformation
Args:
structure (Structure): structure to add site properties to | def apply_transformation(self, structure):
new_structure = structure.copy()
for prop in self.site_properties.keys():
new_structure.add_site_property(prop, self.site_properties[prop])
return new_structure | 138,558 |
Writes all input files (input script, and data if needed).
Other supporting files are not handled at this moment.
Args:
output_dir (str): Directory to output the input files.
**kwargs: kwargs supported by LammpsData.write_file. | def write_inputs(self, output_dir, **kwargs):
write_lammps_inputs(output_dir=output_dir,
script_template=self.script_template,
settings=self.settings, data=self.data,
script_filename=self.script_filename, **kwargs) | 138,561 |
Generate reciprocal vector magnitudes within the cutoff along the specied
lattice vectors.
Args:
a1: Lattice vector a (in Bohrs)
a2: Lattice vector b (in Bohrs)
a3: Lattice vector c (in Bohrs)
encut: Reciprocal vector energy cutoff
Returns:
[[g1^2], [g2^2], ...] Square of reciprocal vectors (1/Bohr)^2
determined by a1, a2, a3 and whose magntidue is less than gcut^2. | def generate_reciprocal_vectors_squared(a1, a2, a3, encut):
for vec in genrecip(a1, a2, a3, encut):
yield np.dot(vec, vec) | 138,564 |
Returns closest site to the input position
for both bulk and defect structures
Args:
struct_blk: Bulk structure
struct_def: Defect structure
pos: Position
Return: (site object, dist, index) | def closestsites(struct_blk, struct_def, pos):
blk_close_sites = struct_blk.get_sites_in_sphere(pos, 5, include_index=True)
blk_close_sites.sort(key=lambda x: x[1])
def_close_sites = struct_def.get_sites_in_sphere(pos, 5, include_index=True)
def_close_sites.sort(key=lambda x: x[1])
return blk_close_sites[0], def_close_sites[0] | 138,565 |
Reciprocal space model charge value
for input squared reciprocal vector.
Args:
g2: Square of reciprocal vector
Returns:
Charge density at the reciprocal vector magnitude | def rho_rec(self, g2):
return (self.expnorm / np.sqrt(1 + self.gamma2 * g2) + (
1 - self.expnorm) * np.exp(-0.25 * self.beta2 * g2)) | 138,569 |
Generate a sequence of supercells
in which each supercell contains a single interstitial,
except for the first supercell in the sequence
which is a copy of the defect-free input structure.
Args:
scaling_matrix (3x3 integer array): scaling matrix
to transform the lattice vectors.
Returns:
scs ([Structure]): sequence of supercells. | def make_supercells_with_defects(self, scaling_matrix):
scs = []
sc = self._structure.copy()
sc.make_supercell(scaling_matrix)
scs.append(sc)
for ids, defect_site in enumerate(self._defect_sites):
sc_with_inter = sc.copy()
sc_with_inter.append(
defect_site.species_string,
defect_site.frac_coords,
coords_are_cartesian=False,
validate_proximity=False,
properties=None)
if not sc_with_inter:
raise RuntimeError(
"could not generate supercell with" " interstitial {}".format(
ids + 1))
scs.append(sc_with_inter.copy())
return scs | 138,572 |
Cluster nodes that are too close together using a tol.
Args:
tol (float): A distance tolerance. PBC is taken into account. | def cluster_nodes(self, tol=0.2):
lattice = self.structure.lattice
vfcoords = [v.frac_coords for v in self.vnodes]
# Manually generate the distance matrix (which needs to take into
# account PBC.
dist_matrix = np.array(lattice.get_all_distances(vfcoords, vfcoords))
dist_matrix = (dist_matrix + dist_matrix.T) / 2
for i in range(len(dist_matrix)):
dist_matrix[i, i] = 0
condensed_m = squareform(dist_matrix)
z = linkage(condensed_m)
cn = fcluster(z, tol, criterion="distance")
merged_vnodes = []
for n in set(cn):
poly_indices = set()
frac_coords = []
for i, j in enumerate(np.where(cn == n)[0]):
poly_indices.update(self.vnodes[j].polyhedron_indices)
if i == 0:
frac_coords.append(self.vnodes[j].frac_coords)
else:
fcoords = self.vnodes[j].frac_coords
# We need the image to combine the frac_coords properly.
d, image = lattice.get_distance_and_image(frac_coords[0],
fcoords)
frac_coords.append(fcoords + image)
merged_vnodes.append(
VoronoiPolyhedron(lattice, np.average(frac_coords, axis=0),
poly_indices, self.coords))
self.vnodes = merged_vnodes
logger.debug("%d vertices after combination." % len(self.vnodes)) | 138,575 |
Remove vnodes that are too close to existing atoms in the structure
Args:
min_dist(float): The minimum distance that a vertex needs to be
from existing atoms. | def remove_collisions(self, min_dist=0.5):
vfcoords = [v.frac_coords for v in self.vnodes]
sfcoords = self.structure.frac_coords
dist_matrix = self.structure.lattice.get_all_distances(vfcoords,
sfcoords)
all_dist = np.min(dist_matrix, axis=1)
new_vnodes = []
for i, v in enumerate(self.vnodes):
if all_dist[i] > min_dist:
new_vnodes.append(v)
self.vnodes = new_vnodes | 138,576 |
Initialization.
Args:
chgcar (pmg.Chgcar): input Chgcar object. | def __init__(self, chgcar):
self.chgcar = chgcar
self.structure = chgcar.structure
self.extrema_coords = [] # list of frac_coords of local extrema
self.extrema_type = None # "local maxima" or "local minima"
self._extrema_df = None # extrema frac_coords - chg density table
self._charge_distribution_df = None | 138,584 |
Cluster nodes that are too close together using a tol.
Args:
tol (float): A distance tolerance. PBC is taken into account. | def cluster_nodes(self, tol=0.2):
lattice = self.structure.lattice
vf_coords = self.extrema_coords
if len(vf_coords) == 0:
if self.extrema_type is None:
logger.warning(
"Please run ChargeDensityAnalyzer.get_local_extrema first!")
return
new_f_coords = []
self._update_extrema(new_f_coords, self.extrema_type)
return new_f_coords
# Manually generate the distance matrix (which needs to take into
# account PBC.
dist_matrix = np.array(lattice.get_all_distances(vf_coords, vf_coords))
dist_matrix = (dist_matrix + dist_matrix.T) / 2
for i in range(len(dist_matrix)):
dist_matrix[i, i] = 0
condensed_m = squareform(dist_matrix)
z = linkage(condensed_m)
cn = fcluster(z, tol, criterion="distance")
merged_fcoords = []
for n in set(cn):
frac_coords = []
for i, j in enumerate(np.where(cn == n)[0]):
if i == 0:
frac_coords.append(self.extrema_coords[j])
else:
f_coords = self.extrema_coords[j]
# We need the image to combine the frac_coords properly.
d, image = lattice.get_distance_and_image(frac_coords[0],
f_coords)
frac_coords.append(f_coords + image)
merged_fcoords.append(np.average(frac_coords, axis=0))
merged_fcoords = [f - np.floor(f) for f in merged_fcoords]
merged_fcoords = [f * (np.abs(f - 1) > 1E-15) for f in merged_fcoords]
# the second line for fringe cases like
# np.array([ 5.0000000e-01 -4.4408921e-17 5.0000000e-01])
# where the shift to [0,1) does not work due to float precision
self._update_extrema(merged_fcoords, extrema_type=self.extrema_type)
logger.debug(
"{} vertices after combination.".format(len(self.extrema_coords))) | 138,589 |
Remove predicted sites that are too close to existing atoms in the
structure.
Args:
min_dist (float): The minimum distance (in Angstrom) that
a predicted site needs to be from existing atoms. A min_dist
with value <= 0 returns all sites without distance checking. | def remove_collisions(self, min_dist=0.5):
s_f_coords = self.structure.frac_coords
f_coords = self.extrema_coords
if len(f_coords) == 0:
if self.extrema_type is None:
logger.warning(
"Please run ChargeDensityAnalyzer.get_local_extrema first!")
return
new_f_coords = []
self._update_extrema(new_f_coords, self.extrema_type)
return new_f_coords
dist_matrix = self.structure.lattice.get_all_distances(f_coords,
s_f_coords)
all_dist = np.min(dist_matrix, axis=1)
new_f_coords = []
for i, f in enumerate(f_coords):
if all_dist[i] > min_dist:
new_f_coords.append(f)
self._update_extrema(new_f_coords, self.extrema_type)
return new_f_coords | 138,590 |
Get the average charge density around each local minima in the charge density
and store the result in _extrema_df
Args:
r (float): radius of sphere around each site to evaluate the average | def sort_sites_by_integrated_chg(self, r=0.4):
if self.extrema_type is None:
self.get_local_extrema()
int_den = []
for isite in self.extrema_coords:
mask = self._dist_mat(isite) < r
vol_sphere = self.chgcar.structure.volume * (mask.sum()/self.chgcar.ngridpts)
chg_in_sphere = np.sum(self.chgcar.data['total'] * mask) / mask.size / vol_sphere
int_den.append(chg_in_sphere)
self._extrema_df['avg_charge_den'] = int_den
self._extrema_df.sort_values(by=['avg_charge_den'], inplace=True)
self._extrema_df.reset_index(drop=True, inplace=True) | 138,592 |
Queries the COD for all cod ids associated with a formula. Requires
mysql executable to be in the path.
Args:
formula (str): Formula.
Returns:
List of cod ids. | def get_cod_ids(self, formula):
# TODO: Remove dependency on external mysql call. MySQL-python package does not support Py3!
# Standardize formula to the version used by COD.
sql = 'select file from data where formula="- %s -"' % \
Composition(formula).hill_formula
text = self.query(sql).split("\n")
cod_ids = []
for l in text:
m = re.search(r"(\d+)", l)
if m:
cod_ids.append(int(m.group(1)))
return cod_ids | 138,609 |
Queries the COD for a structure by id.
Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.
Returns:
A Structure. | def get_structure_by_id(self, cod_id, **kwargs):
r = requests.get("http://www.crystallography.net/cod/%s.cif" % cod_id)
return Structure.from_str(r.text, fmt="cif", **kwargs) | 138,610 |
Queries the COD for structures by formula. Requires mysql executable to
be in the path.
Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.
Returns:
A list of dict of the format
[{"structure": Structure, "cod_id": cod_id, "sg": "P n m a"}] | def get_structure_by_formula(self, formula, **kwargs):
structures = []
sql = 'select file, sg from data where formula="- %s -"' % \
Composition(formula).hill_formula
text = self.query(sql).split("\n")
text.pop(0)
for l in text:
if l.strip():
cod_id, sg = l.split("\t")
r = requests.get("http://www.crystallography.net/cod/%s.cif"
% cod_id.strip())
try:
s = Structure.from_str(r.text, fmt="cif", **kwargs)
structures.append({"structure": s, "cod_id": int(cod_id),
"sg": sg})
except Exception:
import warnings
warnings.warn("\nStructure.from_str failed while parsing CIF file:\n%s" % r.text)
raise
return structures | 138,611 |
get a Structure with Mulliken and Loewdin charges as site properties
Args:
structure_filename: filename of POSCAR
Returns:
Structure Object with Mulliken and Loewdin charges as site properties | def get_structure_with_charges(self, structure_filename):
struct = Structure.from_file(structure_filename)
Mulliken = self.Mulliken
Loewdin = self.Loewdin
site_properties = {"Mulliken Charges": Mulliken, "Loewdin Charges": Loewdin}
new_struct = struct.copy(site_properties=site_properties)
return new_struct | 138,662 |
Get the decomposition leading to lowest cost
Args:
composition:
Composition as a pymatgen.core.structure.Composition
Returns:
Decomposition as a dict of {Entry: amount} | def get_lowest_decomposition(self, composition):
entries_list = []
elements = [e.symbol for e in composition.elements]
for i in range(len(elements)):
for combi in itertools.combinations(elements, i + 1):
chemsys = [Element(e) for e in combi]
x = self.costdb.get_entries(chemsys)
entries_list.extend(x)
try:
pd = PhaseDiagram(entries_list)
return pd.get_decomposition(composition)
except IndexError:
raise ValueError("Error during PD building; most likely, "
"cost data does not exist!") | 138,680 |
Get best estimate of minimum cost/mol based on known data
Args:
comp:
Composition as a pymatgen.core.structure.Composition
Returns:
float of cost/mol | def get_cost_per_mol(self, comp):
comp = comp if isinstance(comp, Composition) else Composition(comp)
decomp = self.get_lowest_decomposition(comp)
return sum(k.energy_per_atom * v * comp.num_atoms for k, v in
decomp.items()) | 138,681 |
Get best estimate of minimum cost/kg based on known data
Args:
comp:
Composition as a pymatgen.core.structure.Composition
Returns:
float of cost/kg | def get_cost_per_kg(self, comp):
comp = comp if isinstance(comp, Composition) else Composition(comp)
return self.get_cost_per_mol(comp) / (
comp.weight.to("kg") * const.N_A) | 138,682 |
Return the list of absolute filepaths in the directory.
Args:
wildcard: String of tokens separated by "|". Each token represents a pattern.
If wildcard is not None, we return only those files that match the given shell pattern (uses fnmatch).
Example:
wildcard="*.nc|*.pdf" selects only those files that end with .nc or .pdf | def list_filepaths(self, wildcard=None):
# Select the files in the directory.
fnames = [f for f in os.listdir(self.path)]
filepaths = filter(os.path.isfile, [os.path.join(self.path, f) for f in fnames])
# Filter using the shell patterns.
if wildcard is not None:
filepaths = WildCard(wildcard).filter(filepaths)
return filepaths | 138,691 |
Finds the lowest entry energy for entries matching the composition.
Entries with non-negative formation energies are excluded. If no
entry is found, use the convex hull energy for the composition.
Args:
pd (PhaseDiagram): PhaseDiagram object.
composition (Composition): Composition object that the target
entry should match.
Returns:
The lowest entry energy among entries matching the composition. | def _get_entry_energy(pd, composition):
candidate = [i.energy_per_atom for i in pd.qhull_entries if
i.composition.fractional_composition ==
composition.fractional_composition]
if not candidate:
warnings.warn("The reactant " + composition.reduced_formula +
" has no matching entry with negative formation"
" energy, instead convex hull energy for this"
" composition will be used for reaction energy "
"calculation. ")
return pd.get_hull_energy(composition)
else:
min_entry_energy = min(candidate)
return min_entry_energy * composition.num_atoms | 138,715 |
Computes the grand potential Phi at a given composition and
chemical potential(s).
Args:
composition (Composition): Composition object.
Returns:
Grand potential at a given composition at chemical potential(s). | def _get_grand_potential(self, composition):
if self.use_hull_energy:
grand_potential = self.pd_non_grand.get_hull_energy(composition)
else:
grand_potential = InterfacialReactivity._get_entry_energy(
self.pd_non_grand, composition)
grand_potential -= sum([composition[e] * mu
for e, mu in self.pd.chempots.items()])
if self.norm:
# Normalizes energy to the composition excluding element(s)
# from reservoir.
grand_potential /= sum([composition[el]
for el in composition
if el not in self.pd.chempots])
return grand_potential | 138,716 |
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy. | def _get_energy(self, x):
return self.pd.get_hull_energy(self.comp1 * x + self.comp2 * (1-x)) - \
self.e1 * x - self.e2 * (1-x) | 138,717 |
Generates balanced reaction at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction object. | def _get_reaction(self, x):
mix_comp = self.comp1 * x + self.comp2 * (1-x)
decomp = self.pd.get_decomposition(mix_comp)
# Uses original composition for reactants.
if np.isclose(x, 0):
reactant = [self.c2_original]
elif np.isclose(x, 1):
reactant = [self.c1_original]
else:
reactant = list(set([self.c1_original, self.c2_original]))
if self.grand:
reactant += [Composition(e.symbol)
for e, v in self.pd.chempots.items()]
product = [Composition(k.name) for k, v in decomp.items()]
reaction = Reaction(reactant, product)
x_original = self._get_original_composition_ratio(reaction)
if np.isclose(x_original, 1):
reaction.normalize_to(self.c1_original, x_original)
else:
reaction.normalize_to(self.c2_original, 1-x_original)
return reaction | 138,718 |
Computes total number of atoms in a reaction formula for elements
not in external reservoir. This method is used in the calculation
of reaction energy per mol of reaction formula.
Args:
rxt (Reaction): a reaction.
Returns:
Total number of atoms for non_reservoir elements. | def _get_elmt_amt_in_rxt(self, rxt):
return sum([rxt.get_el_amount(e) for e in self.pd.elements]) | 138,719 |
Returns the molar mixing ratio between the reactants with ORIGINAL (
instead of processed) compositions for a reaction.
Args:
reaction (Reaction): Reaction object that contains the original
reactant compositions.
Returns:
The molar mixing ratio between the original reactant
compositions for a reaction. | def _get_original_composition_ratio(self, reaction):
if self.c1_original == self.c2_original:
return 1
c1_coeff = reaction.get_coeff(self.c1_original) \
if self.c1_original in reaction.reactants else 0
c2_coeff = reaction.get_coeff(self.c2_original) \
if self.c2_original in reaction.reactants else 0
return c1_coeff * 1.0 / (c1_coeff + c2_coeff) | 138,725 |
Returns a dict that maps each atomic symbol to a unique integer starting
from 1.
Args:
structure (Structure)
Returns:
dict | def get_atom_map(structure):
syms = [site.specie.symbol for site in structure]
unique_pot_atoms = []
[unique_pot_atoms.append(i) for i in syms if not unique_pot_atoms.count(i)]
atom_map = {}
for i, atom in enumerate(unique_pot_atoms):
atom_map[atom] = i + 1
return atom_map | 138,736 |
Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index | def get_absorbing_atom_symbol_index(absorbing_atom, structure):
if isinstance(absorbing_atom, str):
return absorbing_atom, structure.indices_from_symbol(absorbing_atom)[0]
elif isinstance(absorbing_atom, int):
return str(structure[absorbing_atom].specie), absorbing_atom
else:
raise ValueError("absorbing_atom must be either specie symbol or site index") | 138,737 |
Static method to create Header object from cif_file
Args:
cif_file: cif_file path and name
source: User supplied identifier, i.e. for Materials Project this
would be the material ID number
comment: User comment that goes in header
Returns:
Header Object | def from_cif_file(cif_file, source='', comment=''):
r = CifParser(cif_file)
structure = r.get_structures()[0]
return Header(structure, source, comment) | 138,739 |
Reads Header string from either a HEADER file or feff.inp file
Will also read a header from a non-pymatgen generated feff.inp file
Args:
filename: File name containing the Header data.
Returns:
Reads header string. | def header_string_from_file(filename='feff.inp'):
with zopen(filename, "r") as fobject:
f = fobject.readlines()
feff_header_str = []
ln = 0
# Checks to see if generated by pymatgen
try:
feffpmg = f[0].find("pymatgen")
except IndexError:
feffpmg = False
# Reads pymatgen generated header or feff.inp file
if feffpmg:
nsites = int(f[8].split()[2])
for line in f:
ln += 1
if ln <= nsites + 9:
feff_header_str.append(line)
else:
# Reads header from header from feff.inp file from unknown
# source
end = 0
for line in f:
if (line[0] == "*" or line[0] == "T") and end == 0:
feff_header_str.append(line.replace("\r", ""))
else:
end = 1
return ''.join(feff_header_str) | 138,740 |
Reads Header string and returns Header object if header was
generated by pymatgen.
Note: Checks to see if generated by pymatgen, if not it is impossible
to generate structure object so it is not possible to generate
header object and routine ends
Args:
header_str: pymatgen generated feff.inp header
Returns:
Structure object. | def from_string(header_str):
lines = tuple(clean_lines(header_str.split("\n"), False))
comment1 = lines[0]
feffpmg = comment1.find("pymatgen")
if feffpmg:
comment2 = ' '.join(lines[1].split()[2:])
source = ' '.join(lines[2].split()[2:])
basis_vec = lines[6].split(":")[-1].split()
# a, b, c
a = float(basis_vec[0])
b = float(basis_vec[1])
c = float(basis_vec[2])
lengths = [a, b, c]
# alpha, beta, gamma
basis_ang = lines[7].split(":")[-1].split()
alpha = float(basis_ang[0])
beta = float(basis_ang[1])
gamma = float(basis_ang[2])
angles = [alpha, beta, gamma]
lattice = Lattice.from_lengths_and_angles(lengths, angles)
natoms = int(lines[8].split(":")[-1].split()[0])
atomic_symbols = []
for i in range(9, 9 + natoms):
atomic_symbols.append(lines[i].split()[2])
# read the atomic coordinates
coords = []
for i in range(natoms):
toks = lines[i + 9].split()
coords.append([float(s) for s in toks[3:]])
struct = Structure(lattice, atomic_symbols, coords, False,
False, False)
h = Header(struct, source, comment2)
return h
else:
return "Header not generated by pymatgen, cannot return header object" | 138,741 |
Writes Header into filename on disk.
Args:
filename: Filename and path for file to be written to disk | def write_file(self, filename='HEADER'):
with open(filename, "w") as f:
f.write(str(self) + "\n") | 138,743 |
Reads atomic shells from file such as feff.inp or ATOMS file
The lines are arranged as follows:
x y z ipot Atom Symbol Distance Number
with distance being the shell radius and ipot an integer identifying
the potential used.
Args:
filename: File name containing atomic coord data.
Returns:
Atoms string. | def atoms_string_from_file(filename):
with zopen(filename, "rt") as fobject:
f = fobject.readlines()
coords = 0
atoms_str = []
for line in f:
if coords == 0:
find_atoms = line.find("ATOMS")
if find_atoms >= 0:
coords = 1
if coords == 1 and not ("END" in line):
atoms_str.append(line.replace("\r", ""))
return ''.join(atoms_str) | 138,746 |
Parse the feff input file and return the atomic cluster as a Molecule
object.
Args:
filename (str): path the feff input file
Returns:
Molecule: the atomic cluster as Molecule object. The absorbing atom
is the one at the origin. | def cluster_from_file(filename):
atoms_string = Atoms.atoms_string_from_file(filename)
line_list = [l.split() for l in atoms_string.splitlines()[3:]]
coords = []
symbols = []
for l in line_list:
if l:
coords.append([float(i) for i in l[:3]])
symbols.append(l[4])
return Molecule(symbols, coords) | 138,747 |
Creates Tags object from a dictionary.
Args:
d: Dict of feff parameters and values.
Returns:
Tags object | def from_dict(d):
i = Tags()
for k, v in d.items():
if k not in ("@module", "@class"):
i[k] = v
return i | 138,752 |
Returns a string representation of the Tags. The reason why this
method is different from the __str__ method is to provide options
for pretty printing.
Args:
sort_keys: Set to True to sort the Feff parameters alphabetically.
Defaults to False.
pretty: Set to True for pretty aligned output. Defaults to False.
Returns:
String representation of Tags. | def get_string(self, sort_keys=False, pretty=False):
keys = self.keys()
if sort_keys:
keys = sorted(keys)
lines = []
for k in keys:
if isinstance(self[k], dict):
if k in ["ELNES", "EXELFS"]:
lines.append([k, self._stringify_val(self[k]["ENERGY"])])
beam_energy = self._stringify_val(self[k]["BEAM_ENERGY"])
beam_energy_list = beam_energy.split()
if int(beam_energy_list[1]) == 0: # aver=0, specific beam direction
lines.append([beam_energy])
lines.append([self._stringify_val(self[k]["BEAM_DIRECTION"])])
else:
# no cross terms for orientation averaged spectrum
beam_energy_list[2] = str(0)
lines.append([self._stringify_val(beam_energy_list)])
lines.append([self._stringify_val(self[k]["ANGLES"])])
lines.append([self._stringify_val(self[k]["MESH"])])
lines.append([self._stringify_val(self[k]["POSITION"])])
else:
lines.append([k, self._stringify_val(self[k])])
if pretty:
return tabulate(lines)
else:
return str_delimited(lines, None, " ") | 138,753 |
Creates a Feff_tag dictionary from a PARAMETER or feff.inp file.
Args:
filename: Filename for either PARAMETER or feff.inp file
Returns:
Feff_tag object | def from_file(filename="feff.inp"):
with zopen(filename, "rt") as f:
lines = list(clean_lines(f.readlines()))
params = {}
eels_params = []
ieels = -1
ieels_max = -1
for i, line in enumerate(lines):
m = re.match(r"([A-Z]+\d*\d*)\s*(.*)", line)
if m:
key = m.group(1).strip()
val = m.group(2).strip()
val = Tags.proc_val(key, val)
if key not in ("ATOMS", "POTENTIALS", "END", "TITLE"):
if key in ["ELNES", "EXELFS"]:
ieels = i
ieels_max = ieels + 5
else:
params[key] = val
if ieels >= 0:
if i >= ieels and i <= ieels_max:
if i == ieels + 1:
if int(line.split()[1]) == 1:
ieels_max -= 1
eels_params.append(line)
if eels_params:
if len(eels_params) == 6:
eels_keys = ['BEAM_ENERGY', 'BEAM_DIRECTION', 'ANGLES', 'MESH', 'POSITION']
else:
eels_keys = ['BEAM_ENERGY', 'ANGLES', 'MESH', 'POSITION']
eels_dict = {"ENERGY": Tags._stringify_val(eels_params[0].split()[1:])}
for k, v in zip(eels_keys, eels_params[1:]):
eels_dict[k] = str(v)
params[str(eels_params[0].split()[0])] = eels_dict
return Tags(params) | 138,755 |
Static helper method to convert Feff parameters to proper types, e.g.
integers, floats, lists, etc.
Args:
key: Feff parameter key
val: Actual value of Feff parameter. | def proc_val(key, val):
list_type_keys = list(VALID_FEFF_TAGS)
del list_type_keys[list_type_keys.index("ELNES")]
del list_type_keys[list_type_keys.index("EXELFS")]
boolean_type_keys = ()
float_type_keys = ("S02", "EXAFS", "RPATH")
def smart_int_or_float(numstr):
if numstr.find(".") != -1 or numstr.lower().find("e") != -1:
return float(numstr)
else:
return int(numstr)
try:
if key.lower() == 'cif':
m = re.search(r"\w+.cif", val)
return m.group(0)
if key in list_type_keys:
output = list()
toks = re.split(r"\s+", val)
for tok in toks:
m = re.match(r"(\d+)\*([\d\.\-\+]+)", tok)
if m:
output.extend([smart_int_or_float(m.group(2))] *
int(m.group(1)))
else:
output.append(smart_int_or_float(tok))
return output
if key in boolean_type_keys:
m = re.search(r"^\W+([TtFf])", val)
if m:
if m.group(1) == "T" or m.group(1) == "t":
return True
else:
return False
raise ValueError(key + " should be a boolean type!")
if key in float_type_keys:
return float(val)
except ValueError:
return val.capitalize()
return val.capitalize() | 138,756 |
Reads Potential parameters from a feff.inp or FEFFPOT file.
The lines are arranged as follows:
ipot Z element lmax1 lmax2 stoichometry spinph
Args:
filename: file name containing potential data.
Returns:
FEFFPOT string. | def pot_string_from_file(filename='feff.inp'):
with zopen(filename, "rt") as f_object:
f = f_object.readlines()
ln = -1
pot_str = ["POTENTIALS\n"]
pot_tag = -1
pot_data = 0
pot_data_over = 1
sep_line_pattern = [re.compile('ipot.*Z.*tag.*lmax1.*lmax2.*spinph'),
re.compile('^[*]+.*[*]+$')]
for line in f:
if pot_data_over == 1:
ln += 1
if pot_tag == -1:
pot_tag = line.find("POTENTIALS")
ln = 0
if pot_tag >= 0 and ln > 0 and pot_data_over > 0:
try:
if len(sep_line_pattern[0].findall(line)) > 0 or \
len(sep_line_pattern[1].findall(line)) > 0:
pot_str.append(line)
elif int(line.split()[0]) == pot_data:
pot_data += 1
pot_str.append(line.replace("\r", ""))
except (ValueError, IndexError):
if pot_data > 0:
pot_data_over = 0
return ''.join(pot_str).rstrip('\n') | 138,759 |
Returns a `Lattice` object from a dictionary
with the Abinit variables `acell` and either `rprim` in Bohr or `angdeg`
If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr
Args:
cls: Lattice class to be instantiated. pymatgen.core.lattice.Lattice if `cls` is None
Example:
lattice_from_abivars(acell=3*[10], rprim=np.eye(3)) | def lattice_from_abivars(cls=None, *args, **kwargs):
cls = Lattice if cls is None else cls
kwargs.update(dict(*args))
d = kwargs
rprim = d.get("rprim", None)
angdeg = d.get("angdeg", None)
acell = d["acell"]
if rprim is not None:
if angdeg is not None:
raise ValueError("angdeg and rprimd are mutually exclusive")
rprim = np.reshape(rprim, (3,3))
rprimd = [float(acell[i]) * rprim[i] for i in range(3)]
# Call pymatgen constructors (note that pymatgen uses Angstrom instead of Bohr).
return cls(ArrayWithUnit(rprimd, "bohr").to("ang"))
elif angdeg is not None:
angdeg = np.reshape(angdeg, 3)
if np.any(angdeg <= 0.):
raise ValueError("Angles must be > 0 but got %s" % str(angdeg))
if angdeg.sum() >= 360.:
raise ValueError("The sum of angdeg must be lower that 360, angdeg %s" % str(angdeg))
# This code follows the implementation in ingeo.F90
# See also http://www.abinit.org/doc/helpfiles/for-v7.8/input_variables/varbas.html#angdeg
tol12 = 1e-12
pi, sin, cos, sqrt = np.pi, np.sin, np.cos, np.sqrt
rprim = np.zeros((3,3))
if (abs(angdeg[0] -angdeg[1]) < tol12 and abs(angdeg[1] - angdeg[2]) < tol12 and
abs(angdeg[0]-90.) + abs(angdeg[1]-90.) + abs(angdeg[2] -90) > tol12):
# Treat the case of equal angles (except all right angles):
# generates trigonal symmetry wrt third axis
cosang = cos(pi * angdeg[0]/180.0)
a2 = 2.0/3.0*(1.0 - cosang)
aa = sqrt(a2)
cc = sqrt(1.0-a2)
rprim[0,0] = aa ; rprim[0,1] = 0.0 ; rprim[0,2] = cc
rprim[1,0] = -0.5*aa; rprim[1,1] = sqrt(3.0)*0.5*aa ; rprim[1,2] = cc
rprim[2,0] = -0.5*aa; rprim[2,1] = -sqrt(3.0)*0.5*aa; rprim[2,2] = cc
else:
# Treat all the other cases
rprim[0,0] = 1.0
rprim[1,0] = cos(pi*angdeg[2]/180.)
rprim[1,1] = sin(pi*angdeg[2]/180.)
rprim[2,0] = cos(pi*angdeg[1]/180.)
rprim[2,1] = (cos(pi*angdeg[0]/180.0)-rprim[1,0]*rprim[2,0])/rprim[1,1]
rprim[2,2] = sqrt(1.0-rprim[2,0]**2-rprim[2,1]**2)
# Call pymatgen constructors (note that pymatgen uses Angstrom instead of Bohr).
rprimd = [float(acell[i]) * rprim[i] for i in range(3)]
return cls(ArrayWithUnit(rprimd, "bohr").to("ang"))
raise ValueError("Don't know how to construct a Lattice from dict:\n%s" % pformat(d)) | 138,765 |
Constructor for Electrons object.
Args:
comment: String comment for Electrons
charge: Total charge of the system. Default is 0. | def __init__(self, spin_mode="polarized", smearing="fermi_dirac:0.1 eV",
algorithm=None, nband=None, fband=None, charge=0.0, comment=None): # occupancies=None,
super().__init__()
self.comment = comment
self.smearing = Smearing.as_smearing(smearing)
self.spin_mode = SpinMode.as_spinmode(spin_mode)
self.nband = nband
self.fband = fband
self.charge = charge
self.algorithm = algorithm | 138,778 |
Convenient static constructor for a Monkhorst-Pack mesh.
Args:
ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
shiftk: Shift to be applied to the kpoints.
use_symmetries: Use spatial symmetries to reduce the number of k-points.
use_time_reversal: Use time-reversal symmetry to reduce the number of k-points.
Returns:
:class:`KSampling` object. | def monkhorst(cls, ngkpt, shiftk=(0.5, 0.5, 0.5), chksymbreak=None, use_symmetries=True,
use_time_reversal=True, comment=None):
return cls(
kpts=[ngkpt], kpt_shifts=shiftk,
use_symmetries=use_symmetries, use_time_reversal=use_time_reversal, chksymbreak=chksymbreak,
comment=comment if comment else "Monkhorst-Pack scheme with user-specified shiftk") | 138,784 |
Convenient static constructor for an automatic Monkhorst-Pack mesh.
Args:
structure: :class:`Structure` object.
ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: Use spatial symmetries to reduce the number of k-points.
use_time_reversal: Use time-reversal symmetry to reduce the number of k-points.
Returns:
:class:`KSampling` object. | def monkhorst_automatic(cls, structure, ngkpt,
use_symmetries=True, use_time_reversal=True, chksymbreak=None, comment=None):
sg = SpacegroupAnalyzer(structure)
#sg.get_crystal_system()
#sg.get_point_group_symbol()
# TODO
nshiftk = 1
#shiftk = 3*(0.5,) # this is the default
shiftk = 3*(0.5,)
#if lattice.ishexagonal:
#elif lattice.isbcc
#elif lattice.isfcc
return cls.monkhorst(
ngkpt, shiftk=shiftk, use_symmetries=use_symmetries, use_time_reversal=use_time_reversal,
chksymbreak=chksymbreak, comment=comment if comment else "Automatic Monkhorst-Pack scheme") | 138,785 |
Static constructor for path in k-space.
Args:
structure: :class:`Structure` object.
kpath_bounds: List with the reduced coordinates of the k-points defining the path.
ndivsm: Number of division for the smallest segment.
comment: Comment string.
Returns:
:class:`KSampling` object. | def _path(cls, ndivsm, structure=None, kpath_bounds=None, comment=None):
if kpath_bounds is None:
# Compute the boundaries from the input structure.
from pymatgen.symmetry.bandstructure import HighSymmKpath
sp = HighSymmKpath(structure)
# Flat the array since "path" is a a list of lists!
kpath_labels = []
for labels in sp.kpath["path"]:
kpath_labels.extend(labels)
kpath_bounds = []
for label in kpath_labels:
red_coord = sp.kpath["kpoints"][label]
#print("label %s, red_coord %s" % (label, red_coord))
kpath_bounds.append(red_coord)
return cls(mode=KSamplingModes.path, num_kpts=ndivsm, kpts=kpath_bounds,
comment=comment if comment else "K-Path scheme") | 138,786 |
Returns an automatic Kpoint object based on a structure and a kpoint
density. Uses Gamma centered meshes for hexagonal cells and Monkhorst-Pack grids otherwise.
Algorithm:
Uses a simple approach scaling the number of divisions along each
reciprocal lattice vector proportional to its length.
Args:
structure: Input structure
kppa: Grid density | def automatic_density(cls, structure, kppa, chksymbreak=None, use_symmetries=True, use_time_reversal=True,
shifts=(0.5, 0.5, 0.5)):
lattice = structure.lattice
lengths = lattice.abc
shifts = np.reshape(shifts, (-1, 3))
ngrid = kppa / structure.num_sites / len(shifts)
mult = (ngrid * lengths[0] * lengths[1] * lengths[2]) ** (1 / 3.)
num_div = [int(round(1.0 / lengths[i] * mult)) for i in range(3)]
# ensure that num_div[i] > 0
num_div = [i if i > 0 else 1 for i in num_div]
angles = lattice.angles
hex_angle_tol = 5 # in degrees
hex_length_tol = 0.01 # in angstroms
right_angles = [i for i in range(3) if abs(angles[i] - 90) < hex_angle_tol]
hex_angles = [i for i in range(3)
if abs(angles[i] - 60) < hex_angle_tol or
abs(angles[i] - 120) < hex_angle_tol]
is_hexagonal = (len(right_angles) == 2 and len(hex_angles) == 1
and abs(lengths[right_angles[0]] -
lengths[right_angles[1]]) < hex_length_tol)
#style = KSamplingModes.gamma
#if not is_hexagonal:
# num_div = [i + i % 2 for i in num_div]
# style = KSamplingModes.monkhorst
comment = "pymatge.io.abinit generated KPOINTS with grid density = " + "{} / atom".format(kppa)
return cls(
mode="monkhorst", num_kpts=0, kpts=[num_div], kpt_shifts=shifts,
use_symmetries=use_symmetries, use_time_reversal=use_time_reversal, chksymbreak=chksymbreak,
comment=comment) | 138,789 |
Return a Dos object interpolating bands
Args:
partial_dos: if True, projections will be interpolated as well
and partial doses will be return. Projections must be available
in the loader.
npts_mu: number of energy points of the Dos
T: parameter used to smooth the Dos | def get_dos(self, partial_dos=False, npts_mu=10000, T=None):
spin = self.data.spin if isinstance(self.data.spin,int) else 1
energies, densities, vvdos, cdos = BL.BTPDOS(self.eband, self.vvband, npts=npts_mu)
if T is not None:
densities = BL.smoothen_DOS(energies, densities, T)
tdos = Dos(self.efermi / units.eV, energies / units.eV,
{Spin(spin): densities})
if partial_dos:
tdos = self.get_partial_doses(tdos=tdos, npts_mu=npts_mu, T=T)
return tdos | 138,820 |
Reactants and products to be specified as dict of {Composition: coeff}.
Args:
reactants_coeffs ({Composition: float}): Reactants as dict of
{Composition: amt}.
products_coeffs ({Composition: float}): Products as dict of
{Composition: amt}. | def __init__(self, reactants_coeffs, products_coeffs):
# sum reactants and products
all_reactants = sum([k * v for k, v in reactants_coeffs.items()],
Composition({}))
all_products = sum([k * v for k, v in products_coeffs.items()],
Composition({}))
if not all_reactants.almost_equals(all_products, rtol=0,
atol=self.TOLERANCE):
raise ReactionError("Reaction is unbalanced!")
self._els = all_reactants.elements
self.reactants_coeffs = reactants_coeffs
self.products_coeffs = products_coeffs
# calculate net reaction coefficients
self._coeffs = []
self._els = []
self._all_comp = []
for c in set(list(reactants_coeffs.keys()) +
list(products_coeffs.keys())):
coeff = products_coeffs.get(c, 0) - reactants_coeffs.get(c, 0)
if abs(coeff) > self.TOLERANCE:
self._all_comp.append(c)
self._coeffs.append(coeff) | 138,830 |
Calculates the energy of the reaction.
Args:
energies ({Composition: float}): Energy for each composition.
E.g ., {comp1: energy1, comp2: energy2}.
Returns:
reaction energy as a float. | def calculate_energy(self, energies):
return sum([amt * energies[c] for amt, c in zip(self._coeffs,
self._all_comp)]) | 138,831 |
Normalizes the reaction to one of the compositions.
By default, normalizes such that the composition given has a
coefficient of 1. Another factor can be specified.
Args:
comp (Composition): Composition to normalize to
factor (float): Factor to normalize to. Defaults to 1. | def normalize_to(self, comp, factor=1):
scale_factor = abs(1 / self._coeffs[self._all_comp.index(comp)]
* factor)
self._coeffs = [c * scale_factor for c in self._coeffs] | 138,832 |
Normalizes the reaction to one of the elements.
By default, normalizes such that the amount of the element is 1.
Another factor can be specified.
Args:
element (Element/Specie): Element to normalize to.
factor (float): Factor to normalize to. Defaults to 1. | def normalize_to_element(self, element, factor=1):
all_comp = self._all_comp
coeffs = self._coeffs
current_el_amount = sum([all_comp[i][element] * abs(coeffs[i])
for i in range(len(all_comp))]) / 2
scale_factor = factor / current_el_amount
self._coeffs = [c * scale_factor for c in coeffs] | 138,833 |
Returns the amount of the element in the reaction.
Args:
element (Element/Specie): Element in the reaction
Returns:
Amount of that element in the reaction. | def get_el_amount(self, element):
return sum([self._all_comp[i][element] * abs(self._coeffs[i])
for i in range(len(self._all_comp))]) / 2 | 138,834 |
Generates a balanced reaction from a string. The reaction must
already be balanced.
Args:
rxn_string:
The reaction string. For example, "4 Li + O2-> 2Li2O"
Returns:
BalancedReaction | def from_string(rxn_string):
rct_str, prod_str = rxn_string.split("->")
def get_comp_amt(comp_str):
return {Composition(m.group(2)): float(m.group(1) or 1)
for m in re.finditer(r"([\d\.]*(?:[eE]-?[\d\.]+)?)\s*([A-Z][\w\.\(\)]*)",
comp_str)}
return BalancedReaction(get_comp_amt(rct_str), get_comp_amt(prod_str)) | 138,843 |
Reactants and products to be specified as list of
pymatgen.core.structure.Composition. e.g., [comp1, comp2]
Args:
reactants ([Composition]): List of reactants.
products ([Composition]): List of products. | def __init__(self, reactants, products):
self._input_reactants = reactants
self._input_products = products
self._all_comp = reactants + products
els = set()
for c in self.all_comp:
els.update(c.elements)
els = sorted(els)
# Solving:
# | 0 R |
# [ x y ] | | = [ 1 .. 1 0 .. 0]
# | C P |
# x, y are the coefficients of the reactants and products
# R, P the matrices of the element compositions of the reactants
# and products
# C is a constraint matrix that chooses which compositions to normalize to
# try just normalizing to just the first product
rp_mat = np.array([[c[el] for el in els] for c in self._all_comp])
f_mat = np.concatenate([np.zeros((len(rp_mat), 1)), rp_mat], axis=1)
f_mat[len(reactants), 0] = 1 # set normalization by the first product
b = np.zeros(len(els) + 1)
b[0] = 1
coeffs, res, _, s = np.linalg.lstsq(f_mat.T, b, rcond=None)
# for whatever reason the rank returned by lstsq isn't always correct
# seems to be a problem with low-rank M but inconsistent system
# M x = b.
# the singular values seem ok, so checking based on those
if sum(np.abs(s) > 1e-12) == len(f_mat):
if res.size > 0 and res[0] > self.TOLERANCE ** 2:
raise ReactionError("Reaction cannot be balanced.")
else:
ok = True
else:
# underdetermined, add product constraints to make non-singular
ok = False
n_constr = len(rp_mat) - np.linalg.matrix_rank(rp_mat)
f_mat = np.concatenate([np.zeros((len(rp_mat), n_constr)),
rp_mat], axis=1)
b = np.zeros(f_mat.shape[1])
b[:n_constr] = 1
# try setting C to all n_constr combinations of products
for inds in itertools.combinations(range(len(reactants),
len(f_mat)),
n_constr):
f_mat[:, :n_constr] = 0
for j, i in enumerate(inds):
f_mat[i, j] = 1
# try a solution
coeffs, res, _, s = np.linalg.lstsq(f_mat.T, b, rcond=None)
if sum(np.abs(s) > 1e-12) == len(self._all_comp) and \
(res.size == 0 or res[0] < self.TOLERANCE ** 2):
ok = True
break
if not ok:
r_mat = np.array([[c[el] for el in els] for c in reactants])
reactants_underdetermined = (
np.linalg.lstsq(r_mat.T, np.zeros(len(els)), rcond=None)[2]
!= len(reactants))
if reactants_underdetermined:
raise ReactionError("Reaction cannot be balanced. "
"Reactants are underdetermined.")
raise ReactionError("Reaction cannot be balanced. "
"Unknown error, please report.")
self._els = els
self._coeffs = coeffs | 138,844 |
Compute the energy of a structure using Tersoff potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place | def get_energy_tersoff(structure, gulp_cmd='gulp'):
gio = GulpIO()
gc = GulpCaller(gulp_cmd)
gin = gio.tersoff_input(structure)
gout = gc.run(gin)
return gio.get_energy(gout) | 138,852 |
Compute the energy of a structure using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
neutral. | def get_energy_buckingham(structure, gulp_cmd='gulp',
keywords=('optimise', 'conp', 'qok'),
valence_dict=None):
gio = GulpIO()
gc = GulpCaller(gulp_cmd)
gin = gio.buckingham_input(
structure, keywords, valence_dict=valence_dict
)
gout = gc.run(gin)
return gio.get_energy(gout) | 138,853 |
Relax a structure and compute the energy using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
neutral. | def get_energy_relax_structure_buckingham(structure,
gulp_cmd='gulp',
keywords=('optimise', 'conp'),
valence_dict=None):
gio = GulpIO()
gc = GulpCaller(gulp_cmd)
gin = gio.buckingham_input(
structure, keywords, valence_dict=valence_dict
)
gout = gc.run(gin)
energy = gio.get_energy(gout)
relax_structure = gio.get_relaxed_structure(gout)
return energy, relax_structure | 138,854 |
Specifies GULP library file to read species and potential parameters.
If using library don't specify species and potential
in the input file and vice versa. Make sure the elements of
structure are in the library file.
Args:
file_name: Name of GULP library file
Returns:
GULP input string specifying library option | def library_line(self, file_name):
gulplib_set = lambda: 'GULP_LIB' in os.environ.keys()
readable = lambda f: os.path.isfile(f) and os.access(f, os.R_OK)
#dirpath, fname = os.path.split(file_name)
#if dirpath: # Full path specified
# if readable(file_name):
# gin = 'library ' + file_name
# else:
# raise GulpError('GULP Library not found')
#else:
# fpath = os.path.join(os.getcwd(), file_name) # Check current dir
# if readable(fpath):
# gin = 'library ' + fpath
# elif gulplib_set():
# fpath = os.path.join(os.environ['GULP_LIB'], file_name)
# if readable(fpath):
# gin = 'library ' + file_name
# else:
# raise GulpError('GULP Library not found')
# else:
# raise GulpError('GULP Library not found')
#gin += "\n"
#return gin
gin = ""
dirpath, fname = os.path.split(file_name)
if dirpath and readable(file_name): # Full path specified
gin = 'library ' + file_name
else:
fpath = os.path.join(os.getcwd(), file_name) # Check current dir
if readable(fpath):
gin = 'library ' + fpath
elif gulplib_set(): # Check the GULP_LIB path
fpath = os.path.join(os.environ['GULP_LIB'], file_name)
if readable(fpath):
gin = 'library ' + file_name
if gin:
return gin + "\n"
else:
raise GulpError('GULP Library not found') | 138,856 |
Gets a GULP input for an oxide structure and buckingham potential
from library.
Args:
structure: pymatgen.core.structure.Structure
keywords: GULP first line keywords.
library (Default=None): File containing the species and potential.
uc (Default=True): Unit Cell Flag.
valence_dict: {El: valence} | def buckingham_input(self, structure, keywords, library=None,
uc=True, valence_dict=None):
gin = self.keyword_line(*keywords)
gin += self.structure_lines(structure, symm_flg=not uc)
if not library:
gin += self.buckingham_potential(structure, valence_dict)
else:
gin += self.library_line(library)
return gin | 138,857 |
Gets a GULP input with Tersoff potential for an oxide structure
Args:
structure: pymatgen.core.structure.Structure
periodic (Default=False): Flag denoting whether periodic
boundary conditions are used
library (Default=None): File containing the species and potential.
uc (Default=True): Unit Cell Flag.
keywords: GULP first line keywords. | def tersoff_input(self, structure, periodic=False, uc=True, *keywords):
#gin="static noelectrostatics \n "
gin = self.keyword_line(*keywords)
gin += self.structure_lines(
structure, cell_flg=periodic, frac_flg=periodic,
anion_shell_flg=False, cation_shell_flg=False, symm_flg=not uc
)
gin += self.tersoff_potential(structure)
return gin | 138,859 |
Generate the species, tersoff potential lines for an oxide structure
Args:
structure: pymatgen.core.structure.Structure | def tersoff_potential(self, structure):
bv = BVAnalyzer()
el = [site.specie.symbol for site in structure]
valences = bv.get_valences(structure)
el_val_dict = dict(zip(el, valences))
gin = "species \n"
qerfstring = "qerfc\n"
for key in el_val_dict.keys():
if key != "O" and el_val_dict[key] % 1 != 0:
raise SystemError("Oxide has mixed valence on metal")
specie_string = key + " core " + str(el_val_dict[key]) + "\n"
gin += specie_string
qerfstring += key + " " + key + " 0.6000 10.0000 \n"
gin += "# noelectrostatics \n Morse \n"
met_oxi_ters = TersoffPotential().data
for key in el_val_dict.keys():
if key != "O":
metal = key + "(" + str(int(el_val_dict[key])) + ")"
ters_pot_str = met_oxi_ters[metal]
gin += ters_pot_str
gin += qerfstring
return gin | 138,860 |
Initialize with the executable if not in the standard path
Args:
cmd: Command. Defaults to gulp. | def __init__(self, cmd='gulp'):
def is_exe(f):
return os.path.isfile(f) and os.access(f, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
self._gulp_cmd = cmd
return
else:
for path in os.environ['PATH'].split(os.pathsep):
path = path.strip('"')
file = os.path.join(path, cmd)
if is_exe(file):
self._gulp_cmd = file
return
raise GulpError("Executable not found") | 138,863 |
Run GULP using the gin as input
Args:
gin: GULP input string
Returns:
gout: GULP output string | def run(self, gin):
with ScratchDir("."):
p = subprocess.Popen(
self._gulp_cmd, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=subprocess.PIPE
)
out, err = p.communicate(bytearray(gin, "utf-8"))
out = out.decode("utf-8")
err = err.decode("utf-8")
if "Error" in err or "error" in err:
print(gin)
print("----output_0---------")
print(out)
print("----End of output_0------\n\n\n")
print("----output_1--------")
print(out)
print("----End of output_1------")
raise GulpError(err)
# We may not need this
if "ERROR" in out:
raise GulpError(out)
# Sometimes optimisation may fail to reach convergence
conv_err_string = "Conditions for a minimum have not been satisfied"
if conv_err_string in out:
raise GulpConvergenceError()
gout = ""
for line in out.split("\n"):
gout = gout + line + "\n"
return gout | 138,864 |
Basic constructor for :class:`AbinitEvent`.
Args:
message: String with human-readable message providing info on the event.
src_file: String with the name of the Fortran file where the event is raised.
src_line Integer giving the line number in src_file. | def __init__(self, src_file, src_line, message):
#print("src_file", src_file, "src_line", src_line)
self.message = message
self.src_file = src_file
self.src_line = src_line | 138,871 |
List of ABINIT events.
Args:
filename: Name of the file
events: List of Event objects | def __init__(self, filename, events=None):
self.filename = os.path.abspath(filename)
self.stat = os.stat(self.filename)
self.start_datetime, self.end_datetime = None, None
self._events = []
self._events_by_baseclass = collections.defaultdict(list)
if events is not None:
for ev in events:
self.append(ev) | 138,876 |
Give list of all concentrations at specified efermi in the DefectPhaseDiagram
args:
chemical_potentials = {Element: number} is dictionary of chemical potentials to provide formation energies for
temperature = temperature to produce concentrations from
fermi_level: (float) is fermi level relative to valence band maximum
Default efermi = 0 = VBM energy
returns:
list of dictionaries of defect concentrations | def defect_concentrations(self, chemical_potentials, temperature=300, fermi_level=0.):
concentrations = []
for dfct in self.all_stable_entries:
concentrations.append({
'conc':
dfct.defect_concentration(
chemical_potentials=chemical_potentials, temperature=temperature, fermi_level=fermi_level),
'name':
dfct.name,
'charge':
dfct.charge
})
return concentrations | 138,900 |
Suggest possible charges for defects to computee based on proximity
of known transitions from entires to VBM and CBM
Args:
tolerance (float): tolerance with respect to the VBM and CBM to
` continue to compute new charges | def suggest_charges(self, tolerance=0.1):
recommendations = {}
for def_type in self.defect_types:
test_charges = np.arange(
np.min(self.stable_charges[def_type]) - 1,
np.max(self.stable_charges[def_type]) + 2)
test_charges = [charge for charge in test_charges if charge not in self.finished_charges[def_type]]
if len(self.transition_level_map[def_type].keys()):
# More positive charges will shift the minimum transition level down
# Max charge is limited by this if its transition level is close to VBM
min_tl = min(self.transition_level_map[def_type].keys())
if min_tl < tolerance:
max_charge = max(self.transition_level_map[def_type][min_tl])
test_charges = [charge for charge in test_charges if charge < max_charge]
# More negative charges will shift the maximum transition level up
# Minimum charge is limited by this if transition level is near CBM
max_tl = max(self.transition_level_map[def_type].keys())
if max_tl > (self.band_gap - tolerance):
min_charge = min(self.transition_level_map[def_type][max_tl])
test_charges = [charge for charge in test_charges if charge > min_charge]
else:
test_charges = [charge for charge in test_charges if charge not in self.stable_charges[def_type]]
recommendations[def_type] = test_charges
return recommendations | 138,901 |
Solve for the Fermi energy self-consistently as a function of T
and p_O2
Observations are Defect concentrations, electron and hole conc
Args:
bulk_dos: bulk system dos (pymatgen Dos object)
gap: Can be used to specify experimental gap.
Will be useful if the self consistent Fermi level
is > DFT gap
Returns:
Fermi energy | def solve_for_fermi_energy(self, temperature, chemical_potentials, bulk_dos):
fdos = FermiDos(bulk_dos, bandgap=self.band_gap)
def _get_total_q(ef):
qd_tot = sum([
d['charge'] * d['conc']
for d in self.defect_concentrations(
chemical_potentials=chemical_potentials, temperature=temperature, fermi_level=ef)
])
qd_tot += fdos.get_doping(fermi=ef + self.vbm, T=temperature)
return qd_tot
return bisect(_get_total_q, -1., self.band_gap + 1.) | 138,902 |
This method should be called once we have fixed the problem associated to this event.
It adds a new entry in the correction history of the node.
Args:
event: :class:`AbinitEvent` that triggered the correction.
action (str): Human-readable string with info on the action perfomed to solve the problem. | def log_correction(self, event, action):
# TODO: Create CorrectionObject
action = str(action)
self.history.info(action)
self._corrections.append(dict(
event=event.as_dict(),
action=action,
)) | 138,962 |
Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"} | def add_deps(self, deps):
if isinstance(deps, collections.Mapping):
# Convert dictionary into list of dependencies.
deps = [Dependency(node, exts) for node, exts in deps.items()]
# We want a list
if not isinstance(deps, (list, tuple)):
deps = [deps]
assert all(isinstance(d, Dependency) for d in deps)
# Add the dependencies to the node
self._deps.extend(deps)
if self.is_work:
# The task in the work should inherit the same dependency.
for task in self:
task.add_deps(deps)
# If we have a FileNode as dependency, add self to its children
# Node.get_parents will use this list if node.is_isfile.
for dep in (d for d in deps if d.node.is_file):
dep.node.add_filechild(self) | 138,963 |
Remove a list of dependencies from the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node. | def remove_deps(self, deps):
if not isinstance(deps, (list, tuple)):
deps = [deps]
assert all(isinstance(d, Dependency) for d in deps)
self._deps = [d for d in self._deps if d not in deps]
if self.is_work:
# remove the same list of dependencies from the task in the work
for task in self:
task.remove_deps(deps) | 138,964 |
Install the `EventHandlers for this `Node`. If no argument is provided
the default list of handlers is installed.
Args:
categories: List of categories to install e.g. base + can_change_physics
handlers: explicit list of :class:`EventHandler` instances.
This is the most flexible way to install handlers.
.. note::
categories and handlers are mutually exclusive. | def install_event_handlers(self, categories=None, handlers=None):
if categories is not None and handlers is not None:
raise ValueError("categories and handlers are mutually exclusive!")
from .events import get_event_handler_classes
if categories:
raise NotImplementedError()
handlers = [cls() for cls in get_event_handler_classes(categories=categories)]
else:
handlers = handlers or [cls() for cls in get_event_handler_classes()]
self._event_handlers = handlers | 138,971 |
Return the message after merging any user-supplied arguments with the message.
Args:
metadata: True if function and module name should be added.
asctime: True if time string should be added. | def get_message(self, metadata=False, asctime=True):
msg = self.msg if is_string(self.msg) else str(self.msg)
if self.args:
try:
msg = msg % self.args
except:
msg += str(self.args)
if asctime: msg = "[" + self.asctime + "] " + msg
# Add metadata
if metadata:
msg += "\nCalled by %s at %s:%s\n" % (self.func_name, self.pathname, self.lineno)
return msg | 138,979 |
Rotate the camera view.
Args:
axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis.
angle: Angle to rotate by. Defaults to 0. | def rotate_view(self, axis_ind=0, angle=0):
camera = self.ren.GetActiveCamera()
if axis_ind == 0:
camera.Roll(angle)
elif axis_ind == 1:
camera.Azimuth(angle)
else:
camera.Pitch(angle)
self.ren_win.Render() | 138,992 |
Save render window to an image.
Arguments:
filename:
filename to save to. Defaults to image.png.
magnification:
magnification. Use it to render high res images.
image_format:
choose between jpeg, png. Png is the default. | def write_image(self, filename="image.png", magnification=1,
image_format="png"):
render_large = vtk.vtkRenderLargeImage()
render_large.SetInput(self.ren)
if image_format == "jpeg":
writer = vtk.vtkJPEGWriter()
writer.SetQuality(80)
else:
writer = vtk.vtkPNGWriter()
render_large.SetMagnification(magnification)
writer.SetFileName(filename)
writer.SetInputConnection(render_large.GetOutputPort())
self.ren_win.Render()
writer.Write()
del render_large | 138,993 |
Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False. | def redraw(self, reset_camera=False):
self.ren.RemoveAllViewProps()
self.picker = None
self.add_picker_fixed()
self.helptxt_mapper = vtk.vtkTextMapper()
tprops = self.helptxt_mapper.GetTextProperty()
tprops.SetFontSize(14)
tprops.SetFontFamilyToTimes()
tprops.SetColor(0, 0, 0)
if self.structure is not None:
self.set_structure(self.structure, reset_camera)
self.ren_win.Render() | 138,994 |
Add a structure to the visualizer.
Args:
structure: structure to visualize
reset_camera: Set to True to reset the camera to a default
determined based on the structure.
to_unit_cell: Whether or not to fall back sites into the unit cell. | def set_structure(self, structure, reset_camera=True, to_unit_cell=True):
self.ren.RemoveAllViewProps()
has_lattice = hasattr(structure, "lattice")
if has_lattice:
s = Structure.from_sites(structure, to_unit_cell=to_unit_cell)
s.make_supercell(self.supercell, to_unit_cell=to_unit_cell)
else:
s = structure
inc_coords = []
for site in s:
self.add_site(site)
inc_coords.append(site.coords)
count = 0
labels = ["a", "b", "c"]
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
if has_lattice:
matrix = s.lattice.matrix
if self.show_unit_cell and has_lattice:
#matrix = s.lattice.matrix
self.add_text([0, 0, 0], "o")
for vec in matrix:
self.add_line((0, 0, 0), vec, colors[count])
self.add_text(vec, labels[count], colors[count])
count += 1
for (vec1, vec2) in itertools.permutations(matrix, 2):
self.add_line(vec1, vec1 + vec2)
for (vec1, vec2, vec3) in itertools.permutations(matrix, 3):
self.add_line(vec1 + vec2, vec1 + vec2 + vec3)
if self.show_bonds or self.show_polyhedron:
elements = sorted(s.composition.elements, key=lambda a: a.X)
anion = elements[-1]
def contains_anion(site):
for sp in site.species.keys():
if sp.symbol == anion.symbol:
return True
return False
anion_radius = anion.average_ionic_radius
for site in s:
exclude = False
max_radius = 0
color = np.array([0, 0, 0])
for sp, occu in site.species.items():
if sp.symbol in self.excluded_bonding_elements \
or sp == anion:
exclude = True
break
max_radius = max(max_radius, sp.average_ionic_radius)
color = color + \
occu * np.array(self.el_color_mapping.get(sp.symbol,
[0, 0, 0]))
if not exclude:
max_radius = (1 + self.poly_radii_tol_factor) * \
(max_radius + anion_radius)
nn = structure.get_neighbors(site, float(max_radius))
nn_sites = []
for nnsite, dist in nn:
if contains_anion(nnsite):
nn_sites.append(nnsite)
if not in_coord_list(inc_coords, nnsite.coords):
self.add_site(nnsite)
if self.show_bonds:
self.add_bonds(nn_sites, site)
if self.show_polyhedron:
color = [i / 255 for i in color]
self.add_polyhedron(nn_sites, site, color)
if self.show_help:
self.helptxt_actor = vtk.vtkActor2D()
self.helptxt_actor.VisibilityOn()
self.helptxt_actor.SetMapper(self.helptxt_mapper)
self.ren.AddActor(self.helptxt_actor)
self.display_help()
camera = self.ren.GetActiveCamera()
if reset_camera:
if has_lattice:
#Adjust the camera for best viewing
lengths = s.lattice.abc
pos = (matrix[1] + matrix[2]) * 0.5 + \
matrix[0] * max(lengths) / lengths[0] * 3.5
camera.SetPosition(pos)
camera.SetViewUp(matrix[2])
camera.SetFocalPoint((matrix[0] + matrix[1] + matrix[2]) * 0.5)
else:
origin = s.center_of_mass
max_site = max(
s, key=lambda site: site.distance_from_point(origin))
camera.SetPosition(origin + 5 * (max_site.coords - origin))
camera.SetFocalPoint(s.center_of_mass)
self.structure = structure
self.title = s.composition.formula | 138,997 |
Add a site to the render window. The site is displayed as a sphere, the
color of which is determined based on the element. Partially occupied
sites are displayed as a single element color, though the site info
still shows the partial occupancy.
Args:
site: Site to add. | def add_site(self, site):
start_angle = 0
radius = 0
total_occu = 0
for specie, occu in site.species.items():
radius += occu * (specie.ionic_radius
if isinstance(specie, Specie)
and specie.ionic_radius
else specie.average_ionic_radius)
total_occu += occu
vis_radius = 0.2 + 0.002 * radius
for specie, occu in site.species.items():
if not specie:
color = (1, 1, 1)
elif specie.symbol in self.el_color_mapping:
color = [i / 255 for i in self.el_color_mapping[specie.symbol]]
mapper = self.add_partial_sphere(site.coords, vis_radius, color,
start_angle, start_angle + 360 * occu)
self.mapper_map[mapper] = [site]
start_angle += 360 * occu
if total_occu < 1:
mapper = self.add_partial_sphere(site.coords, vis_radius, (1,1,1),
start_angle, start_angle + 360 * (1 - total_occu))
self.mapper_map[mapper] = [site] | 139,000 |
Add text at a coordinate.
Args:
coords: Coordinates to add text at.
text: Text to place.
color: Color for text as RGB. Defaults to black. | def add_text(self, coords, text, color=(0, 0, 0)):
source = vtk.vtkVectorText()
source.SetText(text)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(source.GetOutputPort())
follower = vtk.vtkFollower()
follower.SetMapper(mapper)
follower.GetProperty().SetColor(color)
follower.SetPosition(coords)
follower.SetScale(0.5)
self.ren.AddActor(follower)
follower.SetCamera(self.ren.GetActiveCamera()) | 139,002 |
Adds a line.
Args:
start: Starting coordinates for line.
end: Ending coordinates for line.
color: Color for text as RGB. Defaults to grey.
width: Width of line. Defaults to 1. | def add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1):
source = vtk.vtkLineSource()
source.SetPoint1(start)
source.SetPoint2(end)
vertexIDs = vtk.vtkStringArray()
vertexIDs.SetNumberOfComponents(1)
vertexIDs.SetName("VertexIDs")
# Set the vertex labels
vertexIDs.InsertNextValue("a")
vertexIDs.InsertNextValue("b")
source.GetOutput().GetPointData().AddArray(vertexIDs)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(source.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(color)
actor.GetProperty().SetLineWidth(width)
self.ren.AddActor(actor) | 139,003 |
Adds a polyhedron.
Args:
neighbors: Neighbors of the polyhedron (the vertices).
center: The atom in the center of the polyhedron.
color: Color for text as RGB.
opacity: Opacity of the polyhedron
draw_edges: If set to True, the a line will be drawn at each edge
edges_color: Color of the line for the edges
edges_linewidth: Width of the line drawn for the edges | def add_polyhedron(self, neighbors, center, color, opacity=1.0,
draw_edges=False, edges_color=[0.0, 0.0, 0.0],
edges_linewidth=2):
points = vtk.vtkPoints()
conv = vtk.vtkConvexPointSet()
for i in range(len(neighbors)):
x, y, z = neighbors[i].coords
points.InsertPoint(i, x, y, z)
conv.GetPointIds().InsertId(i, i)
grid = vtk.vtkUnstructuredGrid()
grid.Allocate(1, 1)
grid.InsertNextCell(conv.GetCellType(), conv.GetPointIds())
grid.SetPoints(points)
dsm = vtk.vtkDataSetMapper()
polysites = [center]
polysites.extend(neighbors)
self.mapper_map[dsm] = polysites
if vtk.VTK_MAJOR_VERSION <= 5:
dsm.SetInputConnection(grid.GetProducerPort())
else:
dsm.SetInputData(grid)
ac = vtk.vtkActor()
#ac.SetMapper(mapHull)
ac.SetMapper(dsm)
ac.GetProperty().SetOpacity(opacity)
if color == 'element':
# If partial occupations are involved, the color of the specie with
# the highest occupation is used
myoccu = 0.0
for specie, occu in center.species.items():
if occu > myoccu:
myspecie = specie
myoccu = occu
color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]]
ac.GetProperty().SetColor(color)
else:
ac.GetProperty().SetColor(color)
if draw_edges:
ac.GetProperty().SetEdgeColor(edges_color)
ac.GetProperty().SetLineWidth(edges_linewidth)
ac.GetProperty().EdgeVisibilityOn()
self.ren.AddActor(ac) | 139,004 |
Adds a triangular surface between three atoms.
Args:
atoms: Atoms between which a triangle will be drawn.
color: Color for triangle as RGB.
center: The "central atom" of the triangle
opacity: opacity of the triangle
draw_edges: If set to True, the a line will be drawn at each edge
edges_color: Color of the line for the edges
edges_linewidth: Width of the line drawn for the edges | def add_triangle(self, neighbors, color, center=None, opacity=0.4,
draw_edges=False, edges_color=[0.0, 0.0, 0.0],
edges_linewidth=2):
points = vtk.vtkPoints()
triangle = vtk.vtkTriangle()
for ii in range(3):
points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y,
neighbors[ii].z)
triangle.GetPointIds().SetId(ii, ii)
triangles = vtk.vtkCellArray()
triangles.InsertNextCell(triangle)
# polydata object
trianglePolyData = vtk.vtkPolyData()
trianglePolyData.SetPoints( points )
trianglePolyData.SetPolys( triangles )
# mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(trianglePolyData)
ac = vtk.vtkActor()
ac.SetMapper(mapper)
ac.GetProperty().SetOpacity(opacity)
if color == 'element':
if center is None:
raise ValueError(
'Color should be chosen according to the central atom, '
'and central atom is not provided')
# If partial occupations are involved, the color of the specie with
# the highest occupation is used
myoccu = 0.0
for specie, occu in center.species.items():
if occu > myoccu:
myspecie = specie
myoccu = occu
color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]]
ac.GetProperty().SetColor(color)
else:
ac.GetProperty().SetColor(color)
if draw_edges:
ac.GetProperty().SetEdgeColor(edges_color)
ac.GetProperty().SetLineWidth(edges_linewidth)
ac.GetProperty().EdgeVisibilityOn()
self.ren.AddActor(ac) | 139,005 |
Adds bonds for a site.
Args:
neighbors: Neighbors of the site.
center: The site in the center for all bonds.
color: Color of the tubes representing the bonds
opacity: Opacity of the tubes representing the bonds
radius: Radius of tube s representing the bonds | def add_bonds(self, neighbors, center, color=None, opacity=None,
radius=0.1):
points = vtk.vtkPoints()
points.InsertPoint(0, center.x, center.y, center.z)
n = len(neighbors)
lines = vtk.vtkCellArray()
for i in range(n):
points.InsertPoint(i + 1, neighbors[i].coords)
lines.InsertNextCell(2)
lines.InsertCellPoint(0)
lines.InsertCellPoint(i + 1)
pd = vtk.vtkPolyData()
pd.SetPoints(points)
pd.SetLines(lines)
tube = vtk.vtkTubeFilter()
if vtk.VTK_MAJOR_VERSION <= 5:
tube.SetInputConnection(pd.GetProducerPort())
else:
tube.SetInputData(pd)
tube.SetRadius(radius)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(tube.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
if opacity is not None:
actor.GetProperty().SetOpacity(opacity)
if color is not None:
actor.GetProperty().SetColor(color)
self.ren.AddActor(actor) | 139,008 |
Gets an extended surface mesh for to use for adsorption
site finding by constructing supercell of surface sites
Args:
repeat (3-tuple): repeat for getting extended surface mesh | def get_extended_surface_mesh(self, repeat=(5, 5, 1)):
surf_str = Structure.from_sites(self.surface_sites)
surf_str.make_supercell(repeat)
return surf_str | 139,031 |
Reduces the set of adsorbate sites by finding removing
symmetrically equivalent duplicates
Args:
coords_set: coordinate set in cartesian coordinates
threshold: tolerance for distance equivalence, used
as input to in_coord_list_pbc for dupl. checking | def symm_reduce(self, coords_set, threshold=1e-6):
surf_sg = SpacegroupAnalyzer(self.slab, 0.1)
symm_ops = surf_sg.get_symmetry_operations()
unique_coords = []
# Convert to fractional
coords_set = [self.slab.lattice.get_fractional_coords(coords)
for coords in coords_set]
for coords in coords_set:
incoord = False
for op in symm_ops:
if in_coord_list_pbc(unique_coords, op.operate(coords),
atol=threshold):
incoord = True
break
if not incoord:
unique_coords += [coords]
# convert back to cartesian
return [self.slab.lattice.get_cartesian_coords(coords)
for coords in unique_coords] | 139,033 |
Prunes coordinate set for coordinates that are within
threshold
Args:
coords_set (Nx3 array-like): list or array of coordinates
threshold (float): threshold value for distance | def near_reduce(self, coords_set, threshold=1e-4):
unique_coords = []
coords_set = [self.slab.lattice.get_fractional_coords(coords)
for coords in coords_set]
for coord in coords_set:
if not in_coord_list_pbc(unique_coords, coord, threshold):
unique_coords += [coord]
return [self.slab.lattice.get_cartesian_coords(coords)
for coords in unique_coords] | 139,034 |
Finds the center of an ensemble of sites selected from
a list of sites. Helper method for the find_adsorption_sites
algorithm.
Args:
site_list (list of sites): list of sites
indices (list of ints): list of ints from which to select
sites from site list
cartesian (bool): whether to get average fractional or
cartesian coordinate | def ensemble_center(self, site_list, indices, cartesian=True):
if cartesian:
return np.average([site_list[i].coords for i in indices],
axis=0)
else:
return np.average([site_list[i].frac_coords for i in indices],
axis=0) | 139,035 |
Helper function to assign selective dynamics site_properties
based on surface, subsurface site properties
Args:
slab (Slab): slab for which to assign selective dynamics | def assign_selective_dynamics(self, slab):
sd_list = []
sd_list = [[False, False, False] if site.properties['surface_properties'] == 'subsurface'
else [True, True, True] for site in slab.sites]
new_sp = slab.site_properties
new_sp['selective_dynamics'] = sd_list
return slab.copy(site_properties=new_sp) | 139,037 |
Returns angle specified by three sites.
Args:
i: Index of first site.
j: Index of second site.
k: Index of third site.
Returns:
Angle in degrees. | def get_angle(self, i: int, j: int, k: int) -> float:
v1 = self[i].coords - self[j].coords
v2 = self[k].coords - self[j].coords
return get_angle(v1, v2, units="degrees") | 139,056 |
Returns dihedral angle specified by four sites.
Args:
i: Index of first site
j: Index of second site
k: Index of third site
l: Index of fourth site
Returns:
Dihedral angle in degrees. | def get_dihedral(self, i: int, j: int, k: int, l: int) -> float:
v1 = self[k].coords - self[l].coords
v2 = self[j].coords - self[k].coords
v3 = self[i].coords - self[j].coords
v23 = np.cross(v2, v3)
v12 = np.cross(v1, v2)
return math.degrees(math.atan2(np.linalg.norm(v2) * np.dot(v1, v23),
np.dot(v12, v23))) | 139,057 |
True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is taken into account for periodic structures.
Args:
tol (float): Distance tolerance. Default is 0.5A.
Returns:
(bool) True if SiteCollection does not contain atoms that are too
close together. | def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
if len(self.sites) == 1:
return True
all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]
return bool(np.min(all_dists) > tol) | 139,058 |
Adds a property to a site.
Args:
property_name (str): The name of the property to add.
values (list): A sequence of values. Must be same length as
number of sites. | def add_site_property(self, property_name, values):
if len(values) != len(self.sites):
raise ValueError("Values must be same length as sites.")
for site, val in zip(self.sites, values):
site.properties[property_name] = val | 139,059 |
Swap species.
Args:
species_mapping (dict): dict of species to swap. Species can be
elements too. E.g., {Element("Li"): Element("Na")} performs
a Li for Na substitution. The second species can be a
sp_and_occu dict. For example, a site with 0.5 Si that is
passed the mapping {Element('Si): {Element('Ge'):0.75,
Element('C'):0.25} } will have .375 Ge and .125 C. | def replace_species(self, species_mapping):
species_mapping = {get_el_sp(k): v
for k, v in species_mapping.items()}
sp_to_replace = set(species_mapping.keys())
sp_in_structure = set(self.composition.keys())
if not sp_in_structure.issuperset(sp_to_replace):
warnings.warn(
"Some species to be substituted are not present in "
"structure. Pls check your input. Species to be "
"substituted = %s; Species in structure = %s"
% (sp_to_replace, sp_in_structure))
for site in self._sites:
if sp_to_replace.intersection(site.species):
c = Composition()
for sp, amt in site.species.items():
new_sp = species_mapping.get(sp, sp)
try:
c += Composition(new_sp) * amt
except Exception:
c += {new_sp: amt}
site.species = c | 139,060 |
Add oxidation states.
Args:
oxidation_states (dict): Dict of oxidation states.
E.g., {"Li":1, "Fe":2, "P":5, "O":-2} | def add_oxidation_state_by_element(self, oxidation_states):
try:
for site in self.sites:
new_sp = {}
for el, occu in site.species.items():
sym = el.symbol
new_sp[Specie(sym, oxidation_states[sym])] = occu
site.species = new_sp
except KeyError:
raise ValueError("Oxidation state of all elements must be "
"specified in the dictionary.") | 139,061 |
Add oxidation states to a structure by site.
Args:
oxidation_states (list): List of oxidation states.
E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2] | def add_oxidation_state_by_site(self, oxidation_states):
if len(oxidation_states) != len(self.sites):
raise ValueError("Oxidation states of all sites must be "
"specified.")
for site, ox in zip(self.sites, oxidation_states):
new_sp = {}
for el, occu in site.species.items():
sym = el.symbol
new_sp[Specie(sym, ox)] = occu
site.species = new_sp | 139,062 |
Decorates the structure with oxidation state, guessing
using Composition.oxi_state_guesses()
Args:
**kwargs: parameters to pass into oxi_state_guesses() | def add_oxidation_state_by_guess(self, **kwargs):
oxid_guess = self.composition.oxi_state_guesses(**kwargs)
oxid_guess = oxid_guess or \
[dict([(e.symbol, 0) for e in self.composition])]
self.add_oxidation_state_by_element(oxid_guess[0]) | 139,064 |
Add spin states to a structure.
Args:
spisn (dict): Dict of spins associated with
elements or species, e.g. {"Ni":+5} or {"Ni2+":5} | def add_spin_by_element(self, spins):
for site in self.sites:
new_sp = {}
for sp, occu in site.species.items():
sym = sp.symbol
oxi_state = getattr(sp, "oxi_state", None)
new_sp[Specie(sym, oxidation_state=oxi_state,
properties={'spin': spins.get(str(sp), spins.get(sym, None))})] = occu
site.species = new_sp | 139,065 |
Add spin states to a structure by site.
Args:
spins (list): List of spins
E.g., [+5, -5, 0, 0] | def add_spin_by_site(self, spins):
if len(spins) != len(self.sites):
raise ValueError("Spin of all sites must be "
"specified in the dictionary.")
for site, spin in zip(self.sites, spins):
new_sp = {}
for sp, occu in site.species.items():
sym = sp.symbol
oxi_state = getattr(sp, "oxi_state", None)
new_sp[Specie(sym, oxidation_state=oxi_state,
properties={'spin': spin})] = occu
site.species = new_sp | 139,066 |
Extracts a cluster of atoms based on bond lengths
Args:
target_sites ([Site]): List of initial sites to nucleate cluster.
\\*\\*kwargs: kwargs passed through to CovalentBond.is_bonded.
Returns:
[Site/PeriodicSite] Cluster of atoms. | def extract_cluster(self, target_sites, **kwargs):
cluster = list(target_sites)
others = [site for site in self if site not in cluster]
size = 0
while len(cluster) > size:
size = len(cluster)
new_others = []
for site in others:
for site2 in cluster:
if CovalentBond.is_bonded(site, site2, **kwargs):
cluster.append(site)
break
else:
new_others.append(site)
others = new_others
return cluster | 139,068 |
Convenience method to quickly get the spacegroup of a structure.
Args:
symprec (float): Same definition as in SpacegroupAnalyzer.
Defaults to 1e-2.
angle_tolerance (float): Same definition as in SpacegroupAnalyzer.
Defaults to 5 degrees.
Returns:
spacegroup_symbol, international_number | def get_space_group_info(self, symprec=1e-2, angle_tolerance=5.0):
# Import within method needed to avoid cyclic dependency.
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
a = SpacegroupAnalyzer(self, symprec=symprec,
angle_tolerance=angle_tolerance)
return a.get_space_group_symbol(), a.get_space_group_number() | 139,074 |
Check whether this structure is similar to another structure.
Basically a convenience method to call structure matching fitting.
Args:
other (IStructure/Structure): Another structure.
**kwargs: Same **kwargs as in
:class:`pymatgen.analysis.structure_matcher.StructureMatcher`.
Returns:
(bool) True is the structures are similar under some affine
transformation. | def matches(self, other, **kwargs):
from pymatgen.analysis.structure_matcher import StructureMatcher
m = StructureMatcher(**kwargs)
return m.fit(Structure.from_sites(self), Structure.from_sites(other)) | 139,075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.