docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
plot dos
Args:
sigma: a smearing
Returns:
a matplotlib object | def plot_dos(self, sigma=0.05):
plotter = DosPlotter(sigma=sigma)
plotter.add_dos("t", self._bz.dos)
return plotter.get_plot() | 141,111 |
Plot the carrier concentration in function of Fermi level
Args:
temp: the temperature
Returns:
a matplotlib object | def plot_carriers(self, temp=300):
import matplotlib.pyplot as plt
plt.semilogy(self._bz.mu_steps,
abs(self._bz._carrier_conc[temp] / (self._bz.vol * 1e-24)),
linewidth=3.0, color='r')
self._plot_bg_limits()
self._plot_doping(temp)
... | 141,112 |
Plot the Hall carrier concentration in function of Fermi level
Args:
temp: the temperature
Returns:
a matplotlib object | def plot_hall_carriers(self, temp=300):
import matplotlib.pyplot as plt
hall_carriers = [abs(i) for i in
self._bz.get_hall_carrier_concentration()[temp]]
plt.semilogy(self._bz.mu_steps,
hall_carriers,
linewidth=3.0, colo... | 141,113 |
Adds a COHP for plotting.
Args:
label: Label for the COHP. Must be unique.
cohp: COHP object. | def add_cohp(self, label, cohp):
energies = cohp.energies - cohp.efermi if self.zero_at_efermi \
else cohp.energies
populations = cohp.get_cohp()
int_populations = cohp.get_icohp()
self._cohps[label] = {"energies": energies, "COHP": populations,
... | 141,115 |
Adds a dictionary of COHPs with an optional sorting function
for the keys.
Args:
cohp_dict: dict of the form {label: Cohp}
key_sort_func: function used to sort the cohp_dict keys. | def add_cohp_dict(self, cohp_dict, key_sort_func=None):
if key_sort_func:
keys = sorted(cohp_dict.keys(), key=key_sort_func)
else:
keys = cohp_dict.keys()
for label in keys:
self.add_cohp(label, cohp_dict[label]) | 141,116 |
Initializes a Vacancy Generator
Args:
structure(Structure): pymatgen structure object | def __init__(self, structure, include_bv_charge=False):
self.structure = structure
self.include_bv_charge = include_bv_charge
# Find equivalent site list
sga = SpacegroupAnalyzer(self.structure)
self.symm_structure = sga.get_symmetrized_structure()
self.equiv_si... | 141,123 |
Initializes a Substitution Generator
note: an Antisite is considered a type of substitution
Args:
structure(Structure): pymatgen structure object
element (str or Element or Specie): element for the substitution | def __init__(self, structure, element):
self.structure = structure
self.element = element
# Find equivalent site list
sga = SpacegroupAnalyzer(self.structure)
self.symm_structure = sga.get_symmetrized_structure()
self.equiv_sub = []
for equiv_site_set i... | 141,125 |
Initializes an Interstitial generator using structure motifs
Args:
structure (Structure): pymatgen structure object
element (str or Element or Specie): element for the interstitial | def __init__(self, structure, element):
self.structure = structure
self.element = element
interstitial_finder = StructureMotifInterstitial(self.structure, self.element)
self.unique_defect_seq = []
# eliminate sublattice equivalent defects which may
# have slippe... | 141,126 |
Initializes an Interstitial generator using Voronoi sites
Args:
structure (Structure): pymatgen structure object
element (str or Element or Specie): element for the interstitial | def __init__(self, structure, element):
self.structure = structure
self.element = element
framework = list(self.structure.symbol_set)
get_voronoi = TopographyAnalyzer(self.structure, framework, [], check_volume=False)
get_voronoi.cluster_nodes()
get_voronoi.remo... | 141,127 |
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle. | def solid_angle(center, coords):
# Compute the displacement from the center
r = [np.subtract(c, center) for c in coords]
# Compute the magnitude of each vector
r_norm = [np.linalg.norm(i) for i in r]
# Compute the solid angle for each tetrahedron that makes up the facet
# Following: htt... | 141,131 |
Calculate the volume of a tetrahedron, given the four vertices of vt1,
vt2, vt3 and vt4.
Args:
vt1 (array-like): coordinates of vertex 1.
vt2 (array-like): coordinates of vertex 2.
vt3 (array-like): coordinates of vertex 3.
vt4 (array-like): coordinates of vertex 4.
Returns:
... | def vol_tetra(vt1, vt2, vt3, vt4):
vol_tetra = np.abs(np.dot((vt1 - vt4),
np.cross((vt2 - vt4), (vt3 - vt4)))) / 6
return vol_tetra | 141,132 |
Returns the elemental parameters related to atom size and
electronegativity which are used for estimating bond-valence
parameters (bond length) of pairs of atoms on the basis of data
provided in 'Atoms Sizes and Bond Lengths in Molecules and Crystals'
(O'Keeffe & Brese, 1991).
Args:
el_symb... | def get_okeeffe_params(el_symbol):
el = Element(el_symbol)
if el not in list(BV_PARAMS.keys()):
raise RuntimeError("Could not find O'Keeffe parameters for element"
" \"{}\" in \"BV_PARAMS\"dictonary"
" provided by pymatgen".format(el_symbol))
... | 141,133 |
Returns that part of the first input vector
that is orthogonal to the second input vector.
The output vector is not normalized.
Args:
vin (numpy array):
first input vector
uin (numpy array):
second input vector | def gramschmidt(vin, uin):
vin_uin = np.inner(vin, uin)
uin_uin = np.inner(uin, uin)
if uin_uin <= 0.0:
raise ValueError("Zero or negative inner product!")
return vin - (vin_uin / uin_uin) * uin | 141,137 |
Returns the weighted average bond length given by
Hoppe's effective coordination number formula.
Args:
bonds (list): list of floats that are the
bond distances between a cation and its
peripheral ions | def calculate_weighted_avg(bonds):
minimum_bond = min(bonds)
weighted_sum = 0.0
total_sum = 0.0
for entry in bonds:
weighted_sum += entry * exp(1 - (entry / minimum_bond) ** 6)
total_sum += exp(1 - (entry / minimum_bond) ** 6)
return weighted_sum / total_sum | 141,138 |
Get near neighbors of site with index n in structure.
Args:
structure (Structure): input structure.
n (integer): index of site in structure for which to determine
neighbors.
Returns:
sites (list of Site objects): near neighbors. | def get_nn(self, structure, n):
return [e['site'] for e in self.get_nn_info(structure, n)] | 141,146 |
Get weight associated with each near neighbor of site with
index n in structure.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine the weights.
Returns:
weights (list of floats): near-neighbor weights. | def get_weights_of_nn_sites(self, structure, n):
return [e['weight'] for e in self.get_nn_info(structure, n)] | 141,147 |
Get image location of all near neighbors of site with index n in
structure.
Args:
structure (Structure): input structure.
n (integer): index of site for which to determine the image
location of near neighbors.
Returns:
images (list of 3D integ... | def get_nn_images(self, structure, n):
return [e['image'] for e in self.get_nn_info(structure, n)] | 141,148 |
Get a listing of all neighbors for all sites in a structure
Args:
structure (Structure): Input structure
Return:
List of NN site information for each site in the structure. Each
entry has the same format as `get_nn_info` | def get_all_nn_info(self, structure):
return [self.get_nn_info(structure, n) for n in range(len(structure))] | 141,149 |
Obtain a StructureGraph object using this NearNeighbor
class. Requires the optional dependency networkx
(pip install networkx).
Args:
structure: Structure object.
decorate (bool): whether to annotate site properties
with order parameters using neighbors deter... | def get_bonded_structure(self, structure, decorate=False):
# requires optional dependency which is why it's not a top-level import
from pymatgen.analysis.graphs import StructureGraph
if decorate:
# Decorate all sites in the underlying structure
# with site prop... | 141,154 |
Get the list of elements for a Site
Args:
site (Site): Site to assess
Returns:
[Element]: List of elements | def _get_elements(self, site):
try:
if isinstance(site.specie, Element):
return [site.specie]
return [Element(site.specie)]
except:
return site.species.elements | 141,159 |
Test whether a site contains elements in the target list
Args:
site (Site): Site to assess
targets ([Element]) List of elements
Returns:
(boolean) Whether this site contains a certain list of elements | def _is_in_targets(self, site, targets):
elems = self._get_elements(site)
for elem in elems:
if elem not in targets:
return False
return True | 141,160 |
Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors
Args:
structure (Structure): Structure being evaluated
nns ([dicts]): Nearest neighbor information for a structure
Returns:
(list of tuples (Site, array, float)): See nn_info | def _extract_nn_info(self, structure, nns):
# Get the target information
if self.targets is None:
targets = structure.composition.elements
else:
targets = self.targets
# Extract the NN info
siw = []
max_weight = max(nn[self.weight] for n... | 141,164 |
Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length | def get_max_bond_distance(self, el1_sym, el2_sym):
return sqrt(
(self.el_radius[el1_sym] + self.el_radius[el2_sym] + self.tol) ** 2) | 141,166 |
Obtain a MoleculeGraph object using this NearNeighbor
class. Requires the optional dependency networkx
(pip install networkx).
Args:
structure: Molecule object.
decorate (bool): whether to annotate site properties
with order parameters using neighbors determi... | def get_bonded_structure(self, structure, decorate=False):
# requires optional dependency which is why it's not a top-level import
from pymatgen.analysis.graphs import MoleculeGraph
if decorate:
# Decorate all sites in the underlying structure
# with site prope... | 141,171 |
Return type of order parameter at the index provided and
represented by a short string.
Args:
index (int): index of order parameter for which type is
to be returned.
Returns:
str: OP type. | def get_type(self, index):
if index < 0 or index >= len(self._types):
raise ValueError("Index for getting order parameter type"
" out-of-bounds!")
return self._types[index] | 141,182 |
An internal method to get an integral between two bounds of a unit
semicircle. Used in algorithm to determine bond probabilities.
Args:
dist_bins: (float) list of all possible bond weights
idx: (float) index of starting bond weight
Returns:
(float) integral o... | def _semicircle_integral(dist_bins, idx):
r = 1
x1 = dist_bins[idx]
x2 = dist_bins[idx + 1]
if dist_bins[idx] == 1:
area1 = 0.25 * math.pi * r ** 2
else:
area1 = 0.5 * ((x1 * math.sqrt(r ** 2 - x1 ** 2)) + (
r ** 2 * math.ata... | 141,192 |
An internal method to get a "default" covalent/element radius
Args:
site: (Site)
Returns:
Covalent radius of element on site, or Atomic radius if unavailable | def _get_default_radius(site):
try:
return CovalentRadius.radius[site.specie.symbol]
except:
return site.specie.atomic_radius | 141,193 |
An internal method to get the expected radius for a site with
oxidation state.
Args:
site: (Site)
Returns:
Oxidation-state dependent radius: ionic, covalent, or atomic.
Returns 0 if no oxidation state or appropriate radius is found. | def _get_radius(site):
if hasattr(site.specie, 'oxi_state'):
el = site.specie.element
oxi = site.specie.oxi_state
if oxi == 0:
return CrystalNN._get_default_radius(site)
elif oxi in el.ionic_radii:
return el.ionic_radii[o... | 141,194 |
Given NNData, transforms data to the specified fingerprint length
Args:
nndata: (NNData)
length: (int) desired length of NNData | def transform_to_length(nndata, length):
if length is None:
return nndata
if length:
for cn in range(length):
if cn not in nndata.cn_weights:
nndata.cn_weights[cn] = 0
nndata.cn_nninfo[cn] = []
return nnd... | 141,195 |
Initialise a CutOffDictNN according to a preset set of cut-offs.
Args:
preset (str): A preset name. The list of supported presets are:
- "vesta_2019": The distance cut-offs used by the VESTA
visualisation program.
Returns:
A CutOffDictNN using... | def from_preset(preset):
if preset == 'vesta_2019':
cut_offs = loadfn(os.path.join(_directory, 'vesta_cutoffs.yaml'))
return CutOffDictNN(cut_off_dict=cut_offs)
else:
raise ValueError("Unrecognised preset: {}".format(preset)) | 141,197 |
Computes the volume and surface area of isolated void using Zeo++.
Useful to compute the volume and surface area of vacant site.
Args:
structure: pymatgen Structure containing vacancy
rad_dict(optional): Dictionary with short name of elements and their
radii.
chan_rad(option... | def get_void_volume_surfarea(structure, rad_dict=None, chan_rad=0.3,
probe_rad=0.1):
with ScratchDir('.'):
name = "temp_zeo"
zeo_inp_filename = name + ".cssr"
ZeoCssr(structure).write_file(zeo_inp_filename)
rad_file = None
if rad_dict:
... | 141,206 |
Reads a string representation to a ZeoCssr object.
Args:
string: A string representation of a ZeoCSSR.
Returns:
ZeoCssr object. | def from_string(string):
lines = string.split("\n")
toks = lines[0].split()
lengths = [float(i) for i in toks]
toks = lines[1].split()
angles = [float(i) for i in toks[0:3]]
# Zeo++ takes x-axis along a and pymatgen takes z-axis along c
a = lengths.pop(-1... | 141,208 |
Creates Zeo++ Voronoi XYZ object from a string.
from_string method of XYZ class is being redefined.
Args:
contents: String representing Zeo++ Voronoi XYZ file.
Returns:
ZeoVoronoiXYZ object | def from_string(contents):
lines = contents.split("\n")
num_sites = int(lines[0])
coords = []
sp = []
prop = []
coord_patt = re.compile(
r"(\w+)\s+([0-9\-\.]+)\s+([0-9\-\.]+)\s+([0-9\-\.]+)\s+" +
r"([0-9\-\.]+)"
)
for i in ... | 141,209 |
Set the maxium allowed memory.
Args:
total: The total memory. Integer. Unit: MBytes. If set to None,
this parameter will be neglected.
static: The static memory. Integer. Unit MBytes. If set to None,
this parameterwill be neglected. | def set_memory(self, total=None, static=None):
if total:
self.params["rem"]["mem_total"] = total
if static:
self.params["rem"]["mem_static"] = static | 141,217 |
Set algorithm used for converging SCF and max number of SCF iterations.
Args:
algorithm: The algorithm used for converging SCF. (str)
iterations: The max number of SCF iterations. (Integer) | def set_scf_algorithm_and_iterations(self, algorithm="diis",
iterations=50):
available_algorithms = {"diis", "dm", "diis_dm", "diis_gdm", "gdm",
"rca", "rca_diis", "roothaan"}
if algorithm.lower() not in available_algorith... | 141,218 |
Set the grid for DFT numerical integrations.
Args:
radical_points: Radical points. (Integer)
angular_points: Angular points. (Integer)
grid_type: The type of of the grid. There are two standard grids:
SG-1 and SG-0. The other two supported grids are "Lebedev"... | def set_dft_grid(self, radical_points=128, angular_points=302,
grid_type="Lebedev"):
available_lebedev_angular_points = {6, 18, 26, 38, 50, 74, 86, 110, 146,
170, 194, 230, 266, 302, 350, 434,
5... | 141,219 |
Set initial guess method to be used for SCF
Args:
guess: The initial guess method. (str) | def set_scf_initial_guess(self, guess="SAD"):
availabel_guesses = {"core", "sad", "gwh", "read", "fragmo"}
if guess.lower() not in availabel_guesses:
raise ValueError("The guess method " + guess + " is not supported "
"yet")... | 141,220 |
Set the solvent model to PCM. Default parameters are trying to comply to
gaussian default value
Args:
pcm_params (dict): The parameters of "$pcm" section.
solvent_key (str): for versions < 4.2 the section name is "pcm_solvent"
solvent_params (dict): The parameters of... | def use_pcm(self, pcm_params=None, solvent_key="solvent", solvent_params=None,
radii_force_field=None):
self.params["pcm"] = dict()
self.params[solvent_key] = dict()
default_pcm_params = {"Theory": "SSVPE",
"vdwScale": 1.1,
... | 141,223 |
Creates QcInput from a string.
Args:
contents: String representing a QChem input file.
Returns:
QcInput object | def from_string(cls, contents):
mol = None
charge = None
spin_multiplicity = None
params = dict()
lines = contents.split('\n')
parse_section = False
section_name = None
section_text = []
ghost_atoms = None
for line_num, line in enu... | 141,236 |
Sanitize our input structure by removing magnetic information
and making primitive.
Args:
input_structure: Structure
Returns: Structure | def _sanitize_input_structure(input_structure):
input_structure = input_structure.copy()
# remove any annotated spin
input_structure.remove_spin()
# sanitize input structure: first make primitive ...
input_structure = input_structure.get_primitive_structure(use_site_p... | 141,266 |
Parse a string with a symbol to extract a string representing an element.
Args:
sym (str): A symbol to be parsed.
Returns:
A string with the parsed symbol. None if no parsing was possible. | def _parse_symbol(self, sym):
# Common representations for elements/water in cif files
# TODO: fix inconsistent handling of water
special = {"Hw": "H", "Ow": "O", "Wat": "O",
"wat": "O", "OH": "", "OH2": "", "NO3": "N"}
parsed_sym = None
# try with sp... | 141,289 |
Return list of structures in CIF file. primitive boolean sets whether a
conventional cell structure or primitive cell structure is returned.
Args:
primitive (bool): Set to False to return conventional unit cells.
Defaults to True. With magnetic CIF files, will return primiti... | def get_structures(self, primitive=True):
structures = []
for d in self._cif.data.values():
try:
s = self._get_structure(d, primitive)
if s:
structures.append(s)
except (KeyError, ValueError) as exc:
# W... | 141,291 |
A wrapper around CifFile to write CIF files from pymatgen structures.
Args:
struct (Structure): structure to write
symprec (float): If not none, finds the symmetry of the structure
and writes the cif with symmetry information. Passes symprec
to the Spaceg... | def __init__(self, struct, symprec=None, write_magmoms=False):
if write_magmoms and symprec:
warnings.warn(
"Magnetic symmetry cannot currently be detected by pymatgen,"
"disabling symmetry detection.")
symprec = None
format_str = "{:.8f... | 141,294 |
Converts a list of SlabEntry to an appropriate dictionary. It is
assumed that if there is no adsorbate, then it is a clean SlabEntry
and that adsorbed SlabEntry has the clean_entry parameter set.
Args:
all_slab_entries (list): List of SlabEntry objects
Returns:
(dict): Dictionary of Sl... | def entry_dict_from_list(all_slab_entries):
entry_dict = {}
for entry in all_slab_entries:
hkl = tuple(entry.miller_index)
if hkl not in entry_dict.keys():
entry_dict[hkl] = {}
if entry.clean_entry:
clean = entry.clean_entry
else:
clean ... | 141,295 |
Uses dot product of numpy array to sub chemical potentials
into the surface grand potential. This is much faster
than using the subs function in sympy.
Args:
gamma_dict (dict): Surface grand potential equation
as a coefficient dictionary
chempots (dict): Dictionary assign... | def sub_chempots(gamma_dict, chempots):
coeffs = [gamma_dict[k] for k in gamma_dict.keys()]
chempot_vals = []
for k in gamma_dict.keys():
if k not in chempots.keys():
chempot_vals.append(k)
elif k == 1:
chempot_vals.append(1)
else:
chempot_va... | 141,296 |
Returns the adsorption energy or Gibb's binding energy
of an adsorbate on a surface
Args:
eads (bool): Whether to calculate the adsorption energy
(True) or the binding energy (False) which is just
adsorption energy normalized by number of adsorbates. | def gibbs_binding_energy(self, eads=False):
n = self.get_unit_primitive_area
Nads = self.Nads_in_slab
BE = (self.energy - n * self.clean_entry.energy) / Nads - \
sum([ads.energy_per_atom for ads in self.adsorbates])
return BE * Nads if eads else BE | 141,299 |
Helper function to assign each facet a unique color using a dictionary.
Args:
alpha (float): Degree of transparency
return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The keys are individual surface entries where
clean surfaces hav... | def color_palette_dict(self, alpha=0.35):
color_dict = {}
for hkl in self.all_slab_entries.keys():
rgb_indices = [0, 1, 2]
color = [0, 0, 0, 1]
random.shuffle(rgb_indices)
for i, ind in enumerate(rgb_indices):
if i == 2:
... | 141,315 |
Plots the binding energy energy as a function of monolayers (ML), i.e.
the fractional area adsorbate density for all facets. For each
facet at a specific monlayer, only plot the lowest binding energy.
Args:
plot_eads (bool): Option to plot the adsorption energy (binding
... | def monolayer_vs_BE(self, plot_eads=False):
plt = pretty_plot(width=8, height=7)
for hkl in self.all_slab_entries.keys():
ml_be_dict = {}
for clean_entry in self.all_slab_entries[hkl].keys():
if self.all_slab_entries[hkl][clean_entry]:
... | 141,318 |
Helper function to a chempot plot look nicer.
Args:
plt (Plot) Plot to add things to.
xrange (list): xlim parameter
ref_el (str): Element of the referenced chempot.
axes(axes) Axes object from matplotlib
pad (float) For tight layout
rect (... | def chempot_plot_addons(self, plt, xrange, ref_el, axes, pad=2.4,
rect=[-0.047, 0, 0.84, 1], ylim=[]):
# Make the figure look nice
plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
axes.set_xlabel(r"Chemical potential $\Delta\mu_{%s}$ (eV)" % (r... | 141,319 |
Returns a plot of the local potential (eV) vs the
position along the c axis of the slab model (Ang)
Args:
label_energies (bool): Whether to label relevant energy
quantities such as the work function, Fermi energy,
vacuum locpot, bulk-like locpot
... | def get_locpot_along_slab_plot(self, label_energies=True,
plt=None, label_fontsize=10):
plt = pretty_plot(width=6, height=4) if not plt else plt
# plot the raw locpot signal along c
plt.plot(self.along_c, self.locpot_along_c, 'b--')
# Get th... | 141,324 |
Handles the optional labelling of the plot with relevant quantities
Args:
plt (plt): Plot of the locpot vs c axis
label_fontsize (float): Fontsize of labels
Returns Labelled plt | def get_labels(self, plt, label_fontsize=10):
# center of vacuum and bulk region
if len(self.slab_regions) > 1:
label_in_vac = (self.slab_regions[0][1] + self.slab_regions[1][0])/2
if abs(self.slab_regions[0][0]-self.slab_regions[0][1]) > \
abs(self.... | 141,325 |
Average voltage for path satisfying between a min and max voltage.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.
Returns:
Aver... | def get_average_voltage(self, min_voltage=None, max_voltage=None):
pairs_in_range = self._select_in_voltage_range(min_voltage,
max_voltage)
if len(pairs_in_range) == 0:
return 0
total_cap_in_range = sum([p.mAh for p in p... | 141,336 |
Selects VoltagePairs within a certain voltage range.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.
Returns:
A list of VoltageP... | def _select_in_voltage_range(self, min_voltage=None, max_voltage=None):
min_voltage = min_voltage if min_voltage is not None \
else self.min_voltage
max_voltage = max_voltage if max_voltage is not None \
else self.max_voltage
return list(filter(lambda p: min_volt... | 141,341 |
Initializes with pymatgen Molecule or OpenBabel"s OBMol.
Args:
mol: pymatgen's Molecule or OpenBabel OBMol | def __init__(self, mol):
if isinstance(mol, Molecule):
if not mol.is_ordered:
raise ValueError("OpenBabel Molecule only supports ordered "
"molecules.")
# For some reason, manually adding atoms does not seem to create
... | 141,342 |
A wrapper to pybel's localopt method to optimize a Molecule.
Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500. | def localopt(self, forcefield='mmff94', steps=500):
pbmol = pb.Molecule(self._obmol)
pbmol.localopt(forcefield=forcefield, steps=steps)
self._obmol = pbmol.OBMol | 141,344 |
Remove a bond from an openbabel molecule
Args:
idx1: The atom index of one of the atoms participating the in bond
idx2: The atom index of the other atom participating in the bond | def remove_bond(self, idx1, idx2):
for obbond in ob.OBMolBondIter(self._obmol):
if (obbond.GetBeginAtomIdx() == idx1 and obbond.GetEndAtomIdx() == idx2) or (obbond.GetBeginAtomIdx() == idx2 and obbond.GetEndAtomIdx() == idx1):
self._obmol.DeleteBond(obbond) | 141,346 |
Uses OpenBabel to output all supported formats.
Args:
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats. | def write_file(self, filename, file_format="xyz"):
mol = pb.Molecule(self._obmol)
return mol.write(file_format, filename, overwrite=True) | 141,350 |
Uses OpenBabel to read a molecule from a file in all supported formats.
Args:
filename: Filename of input file
file_format: String specifying any OpenBabel supported formats.
Returns:
BabelMolAdaptor object | def from_file(filename, file_format="xyz"):
mols = list(pb.readfile(str(file_format), str(filename)))
return BabelMolAdaptor(mols[0].OBMol) | 141,351 |
Uses OpenBabel to read a molecule from a string in all supported
formats.
Args:
string_data: String containing molecule data.
file_format: String specifying any OpenBabel supported formats.
Returns:
BabelMolAdaptor object | def from_string(string_data, file_format="xyz"):
mols = pb.readstring(str(file_format), str(string_data))
return BabelMolAdaptor(mols.OBMol) | 141,352 |
Initialize a `Structure` object from a string with data in XSF format.
Args:
input_string: String with the structure in XSF format.
See http://www.xcrysden.org/doc/XSF.html
cls_: Structure class to be created. default: pymatgen structure | def from_string(cls, input_string, cls_=None):
# CRYSTAL see (1)
# these are primitive lattice vectors (in Angstroms)
# PRIMVEC
# 0.0000000 2.7100000 2.7100000 see (2)
# 2.7100000 0.0000000 2.7100000
... | 141,360 |
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
flow.walknset_vars(ecut=10, kptopt=4) | def walknset_vars(self, task_class=None, *args, **kwargs):
def change_task(task):
if task_class is not None and task.__class__ is not task_class: return False
return True
if self.is_work:
for task in self:
if not change_task(task): continue
... | 141,410 |
This function is called once we have completed the initialization
of the :class:`Work`. It sets the manager of each task (if not already done)
and defines the working directories of the tasks.
Args:
manager: :class:`TaskManager` object or None | def allocate(self, manager=None):
for i, task in enumerate(self):
if not hasattr(task, "manager"):
# Set the manager
# Use the one provided in input else the one of the work/flow.
if manager is not None:
task.set_manager(m... | 141,416 |
Returns a list with the status of the tasks in self.
Args:
only_min: If True, the minimum of the status is returned. | def get_all_status(self, only_min=False):
if len(self) == 0:
# The work will be created in the future.
if only_min:
return self.S_INIT
else:
return [self.S_INIT]
self.check_status()
status_list = [task.status for task ... | 141,419 |
Remove all files and directories in the working directory
Args:
exclude_wildcard: Optional string with regular expressions separated by `|`.
Files matching one of the regular expressions will be preserved.
example: exclude_wildard="*.nc|*.txt" preserves all the files... | def rmtree(self, exclude_wildcard=""):
if not exclude_wildcard:
shutil.rmtree(self.workdir)
else:
w = WildCard(exclude_wildcard)
for dirpath, dirnames, filenames in os.walk(self.workdir):
for fname in filenames:
path = os.... | 141,421 |
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. | def create_tasks(self, wfk_file, scr_input):
assert len(self) == 0
wfk_file = self.wfk_file = os.path.abspath(wfk_file)
# Build a temporary work in the tmpdir that will use a shell manager
# to run ABINIT in order to get the list of q-points for the screening.
shell_man... | 141,439 |
Build tasks for the computation of Born effective charges and add them to the work.
Args:
scf_task: ScfTask object.
ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run.
None to use AbiPy default.
ph_tolerance: dict {"varname": value}... | def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance):
if not isinstance(scf_task, ScfTask):
raise TypeError("task `%s` does not inherit from ScfTask" % scf_task)
# DDK calculations (self-consistent to get electric field).
multi_ddk = scf_task.input.make_ddk_inpu... | 141,442 |
This method is called when all the q-points have been computed.
It runs `mrgdvdb` in sequential on the local machine to produce
the final DVDB file in the outdir of the `Work`.
Args:
delete_source: True if POT1 files should be removed after (successful) merge.
Returns:
... | def merge_pot1_files(self, delete_source=True):
natom = len(self[0].input.structure)
max_pertcase = 3 * natom
pot1_files = []
for task in self:
if not isinstance(task, DfptTask): continue
paths = task.outdir.list_filepaths(wildcard="*_POT*")
... | 141,444 |
Build tasks for the computation of Born effective charges from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default.
ph_tolerance: dict {"varname": value} with the tolerance used in the phon... | def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None):
new = cls(manager=manager)
new.add_becs_from_scf_task(scf_task, ddk_tolerance, ph_tolerance)
return new | 141,452 |
Build a DteWork from a ground-state task.
Args:
scf_task: ScfTask object.
ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default.
manager: :class:`TaskManager` object. | def from_scf_task(cls, scf_task, ddk_tolerance=None, manager=None):
if not isinstance(scf_task, ScfTask):
raise TypeError("task `%s` does not inherit from ScfTask" % scf_task)
new = cls(manager=manager)
# DDK calculations
multi_ddk = scf_task.input.make_ddk_inputs(... | 141,454 |
Initializes an abstract defect
Args:
structure: Pymatgen Structure without any defects
defect_site (Site): site for defect within structure
must have same lattice as structure
charge: (int or float) defect charge
default is zero, meaning no ch... | def __init__(self, structure, defect_site, charge=0.):
self._structure = structure
self._charge = charge
self._defect_site = defect_site
if structure.lattice != defect_site.lattice:
raise ValueError("defect_site lattice must be same as structure lattice.") | 141,456 |
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
defect_structure = self.bulk_structure.copy()
defect_structure.make_supercell(supercell)
#create a trivial defect structure to find where supercell transformation moves the lattice
struct_for_defect_site = Structure( sel... | 141,458 |
Returns Defective Substitution structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
defect_structure = self.bulk_structure.copy()
defect_structure.make_supercell(supercell)
# consider modifying velocity property to make sure defect site is decorated
# consistently with bulk structure for final defect_st... | 141,461 |
Returns Defective Interstitial structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | def generate_defect_structure(self, supercell=(1, 1, 1)):
defect_structure = self.bulk_structure.copy()
defect_structure.make_supercell(supercell)
# consider modifying velocity property to make sure defect site is decorated
# consistently with bulk structure for final defect_st... | 141,464 |
Reconstitute a DefectEntry object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of DefectEntry.
Returns:
DefectEntry object | def from_dict(cls, d):
defect = MontyDecoder().process_decoded( d["defect"])
uncorrected_energy = d["uncorrected_energy"]
corrections = d.get("corrections", None)
parameters = d.get("parameters", None)
entry_id = d.get("entry_id", None)
return cls(defect, uncorr... | 141,469 |
Get the defect concentration for a temperature and Fermi level.
Args:
temperature:
the temperature in K
fermi_level:
the fermi level in eV (with respect to the VBM)
Returns:
defects concentration in cm^-3 | def defect_concentration(self, chemical_potentials, temperature=300, fermi_level=0.0):
n = self.multiplicity * 1e24 / self.defect.bulk_structure.volume
conc = n * np.exp(-1.0 * self.formation_energy(chemical_potentials, fermi_level=fermi_level) /
(kb * temperature))
... | 141,472 |
Corrects a single entry.
Args:
entry: A DefectEntry object.
Returns:
An processed entry.
Raises:
CompatibilityError if entry is not compatible. | def correct_entry(self, entry):
entry.correction.update(self.get_correction(entry))
return entry | 141,474 |
Returns the charge transferred for a particular atom. Requires POTCAR
to be supplied.
Args:
atom_index:
Index of atom.
Returns:
Charge transfer associated with atom from the Bader analysis.
Given by final charge on atom - nelectrons in POTCAR... | def get_charge_transfer(self, atom_index):
if self.potcar is None:
raise ValueError("POTCAR must be supplied in order to calculate "
"charge transfer!")
potcar_indices = []
for i, v in enumerate(self.natoms):
potcar_indices += [i] * v... | 141,478 |
Convenient constructor that takes in the path name of VASP run
to perform Bader analysis.
Args:
path (str): Name of directory where VASP output files are
stored.
suffix (str): specific suffix to look for (e.g. '.relax1'
for 'CHGCAR.relax1.gz'). | def from_path(cls, path, suffix=""):
def _get_filepath(filename):
name_pattern = filename + suffix + '*' if filename != 'POTCAR' \
else filename + '*'
paths = glob.glob(os.path.join(path, name_pattern))
fpath = None
if len(paths) >= 1:
... | 141,481 |
Given a tuple of tuples, generate a delimited string form.
>>> results = [["a","b","c"],["d","e","f"],[1,2,3]]
>>> print(str_delimited(results,delimiter=","))
a,b,c
d,e,f
1,2,3
Args:
result: 2d sequence of arbitrary types.
header: optional header
Returns:
Aligned st... | def str_delimited(results, header=None, delimiter="\t"):
returnstr = ""
if header is not None:
returnstr += delimiter.join(header) + "\n"
return returnstr + "\n".join([delimiter.join([str(m) for m in result])
for result in results]) | 141,519 |
This function is used to make pretty formulas by formatting the amounts.
Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4.
Args:
afloat (float): a float
ignore_ones (bool): if true, floats of 1 are ignored.
tol (float): Tolerance to round to nearest int. i.e. 2.0000000001 -> 2
Ret... | def formula_double_format(afloat, ignore_ones=True, tol=1e-8):
if ignore_ones and afloat == 1:
return ""
elif abs(afloat - int(afloat)) < tol:
return str(int(afloat))
else:
return str(round(afloat, 8)) | 141,520 |
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\\overline{1}$.
Args:
spacegroup_symbol (str): A spacegroup symbol
Returns:
A latex formatted spacegroup with proper subscripts and overlines. | def latexify_spacegroup(spacegroup_symbol):
sym = re.sub(r"_(\d+)", r"$_{\1}$", spacegroup_symbol)
return re.sub(r"-(\d)", r"$\\overline{\1}$", sym) | 141,522 |
Compare the bond table of the two molecules.
Args:
mol1: first molecule. pymatgen Molecule object.
mol2: second moleculs. pymatgen Molecule objec. | def are_equal(self, mol1, mol2):
b1 = set(self._get_bonds(mol1))
b2 = set(self._get_bonds(mol2))
return b1 == b2 | 141,528 |
Find all the bond in a molcule
Args:
mol: the molecule. pymatgen Molecule object
Returns:
List of tuple. Each tuple correspond to a bond represented by the
id of the two end atoms. | def _get_bonds(self, mol):
num_atoms = len(mol)
# index starting from 0
if self.ignore_ionic_bond:
covalent_atoms = [i for i in range(num_atoms) if mol.species[i].symbol not in self.ionic_element_list]
else:
covalent_atoms = list(range(num_atoms))
... | 141,530 |
Parses .outputtrans file
Args:
path_dir: dir containing boltztrap.outputtrans
Returns:
tuple - (run_type, warning, efermi, gap, doping_levels) | def parse_outputtrans(path_dir):
run_type = None
warning = None
efermi = None
gap = None
doping_levels = []
with open(os.path.join(path_dir, "boltztrap.outputtrans"), 'r') \
as f:
for line in f:
if "WARNING" in line:
... | 141,568 |
Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files
Args:
path_dir: (str) dir containing DOS files
efermi: (float) Fermi energy
dos_spin: (int) -1 for spin down, +1 for spin up
trim_dos: (bool) whether to post-process / trim DOS
Returns:
... | def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False):
data_dos = {'total': [], 'partial': {}}
# parse the total DOS data
## format is energy, DOS, integrated DOS
with open(os.path.join(path_dir, "boltztrap.transdos"), 'r') as f:
count_series = 0 # TODO... | 141,569 |
Parses boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs
Args:
path_dir: (str) dir containing the boltztrap.intrans file
Returns:
intrans (dict): a dictionary containing various inputs that had been used in the Boltztrap run. | def parse_intrans(path_dir):
intrans = {}
with open(os.path.join(path_dir, "boltztrap.intrans"), 'r') as f:
for line in f:
if "iskip" in line:
intrans["scissor"] = Energy(float(line.split(" ")[3]),
"... | 141,570 |
Parses boltztrap.struct file (only the volume)
Args:
path_dir: (str) dir containing the boltztrap.struct file
Returns:
(float) volume | def parse_struct(path_dir):
with open(os.path.join(path_dir, "boltztrap.struct"), 'r') as f:
tokens = f.readlines()
return Lattice([[Length(float(tokens[i].split()[j]), "bohr").
to("ang") for j in range(3)] for i in
range(1,... | 141,571 |
Parses the conductivity and Hall tensors
Args:
path_dir: Path containing .condtens / .halltens files
doping_levels: ([float]) - doping lvls, parse outtrans to get this
Returns:
mu_steps, cond, seebeck, kappa, hall, pn_doping_levels,
mu_doping, seebeck_dop... | def parse_cond_and_hall(path_dir, doping_levels=None):
# Step 1: parse raw data but do not convert to final format
t_steps = set()
mu_steps = set()
data_full = []
data_hall = []
data_doping_full = []
data_doping_hall = []
doping_levels = doping_l... | 141,572 |
get a BoltztrapAnalyzer object from a set of files
Args:
path_dir: directory where the boltztrap files are
dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down
Returns:
a BoltztrapAnalyzer object | def from_files(path_dir, dos_spin=1):
run_type, warning, efermi, gap, doping_levels = \
BoltztrapAnalyzer.parse_outputtrans(path_dir)
vol = BoltztrapAnalyzer.parse_struct(path_dir)
intrans = BoltztrapAnalyzer.parse_intrans(path_dir)
if run_type == "BOLTZ":
... | 141,573 |
Generator that parses dump file(s).
Args:
file_pattern (str): Filename to parse. The timestep wildcard
(e.g., dump.atom.'*') is supported and the files are parsed
in the sequence of timestep.
Yields:
LammpsDump for each available snapshot. | def parse_lammps_dumps(file_pattern):
files = glob.glob(file_pattern)
if len(files) > 1:
pattern = r"%s" % file_pattern.replace("*", "([0-9]+)")
pattern = pattern.replace("\\", "\\\\")
files = sorted(files,
key=lambda f: int(re.match(pattern, f).group(1)))
... | 141,580 |
Base constructor.
Args:
timestep (int): Current timestep.
natoms (int): Total number of atoms in the box.
box (LammpsBox): Simulation box.
data (pd.DataFrame): Dumped atomic data. | def __init__(self, timestep, natoms, box, data):
self.timestep = timestep
self.natoms = natoms
self.box = box
self.data = data | 141,582 |
Constructor from string parsing.
Args:
string (str): Input string. | def from_string(cls, string):
lines = string.split("\n")
timestep = int(lines[1])
natoms = int(lines[3])
box_arr = np.loadtxt(StringIO("\n".join(lines[5:8])))
bounds = box_arr[:, :2]
tilt = None
if "xy xz yz" in lines[4]:
tilt = box_arr[:, 2]
... | 141,583 |
Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of
objects with units if obj is a dict, else an instance of
`ArrayWithFloatWithUnit`.
Args:
unit: Specific units (eV, Ha, m, ang, etc.). | def obj_with_unit(obj, unit):
unit_type = _UNAME2UTYPE[unit]
if isinstance(obj, numbers.Number):
return FloatWithUnit(obj, unit=unit, unit_type=unit_type)
elif isinstance(obj, collections.Mapping):
return {k: obj_with_unit(v, unit) for k,v in obj.items()}
else:
return Array... | 141,604 |
Constructs a unit.
Args:
unit_def: A definition for the unit. Either a mapping of unit to
powers, e.g., {"m": 2, "s": -1} represents "m^2 s^-1",
or simply as a string "kg m^2 s^-1". Note that the supported
format uses "^" as the power operator and all... | def __init__(self, unit_def):
if isinstance(unit_def, str):
unit = collections.defaultdict(int)
import re
for m in re.finditer(r"([A-Za-z]+)\s*\^*\s*([\-0-9]*)", unit_def):
p = m.group(2)
p = 1 if not p else int(p)
k =... | 141,606 |
Returns a conversion factor between this unit and a new unit.
Compound units are supported, but must have the same powers in each
unit type.
Args:
new_unit: The new unit. | def get_conversion_factor(self, new_unit):
uo_base, ofactor = self.as_base_units
un_base, nfactor = Unit(new_unit).as_base_units
units_new = sorted(un_base.items(),
key=lambda d: _UNAME2UTYPE[d[0]])
units_old = sorted(uo_base.items(),
... | 141,611 |
Initializes a float with unit.
Args:
val (float): Value
unit (Unit): A unit. E.g., "C".
unit_type (str): A type of unit. E.g., "charge" | def __init__(self, val, unit, unit_type=None):
if unit_type is not None and str(unit) not in ALL_UNITS[unit_type]:
raise UnitError(
"{} is not a supported unit for {}".format(unit, unit_type))
self._unit = Unit(unit)
self._unit_type = unit_type | 141,614 |
Conversion to a new_unit. Right now, only supports 1 to 1 mapping of
units of each type.
Args:
new_unit: New unit type.
Returns:
A FloatWithUnit object in the new units.
Example usage:
>>> e = Energy(1.1, "eV")
>>> e = Energy(1.1, "Ha")
... | def to(self, new_unit):
return FloatWithUnit(
self * self.unit.get_conversion_factor(new_unit),
unit_type=self._unit_type,
unit=new_unit) | 141,622 |
Conversion to a new_unit.
Args:
new_unit:
New unit type.
Returns:
A ArrayWithFloatWithUnit object in the new units.
Example usage:
>>> e = EnergyArray([1, 1.1], "Ha")
>>> e.to("eV")
array([ 27.21138386, 29.93252225]) eV | def to(self, new_unit):
return self.__class__(
np.array(self) * self.unit.get_conversion_factor(new_unit),
unit_type=self.unit_type, unit=new_unit) | 141,629 |
Attempt to convert a vector of floats to whole numbers.
Args:
miller_index (list of float): A list miller indexes.
round_dp (int, optional): The number of decimal places to round the
miller index to.
verbose (bool, optional): Whether to print warnings.
Returns:
(tup... | def get_integer_index(
miller_index: bool, round_dp: int = 4, verbose: bool = True
) -> Tuple[int, int, int]:
miller_index = np.asarray(miller_index)
# deal with the case we have small irregular floats
# that are all equal or factors of each other
miller_index /= min([m for m in miller_index i... | 141,631 |
Returns the cartesian coordinates given fractional coordinates.
Args:
fractional_coords (3x1 array): Fractional coords.
Returns:
Cartesian coordinates | def get_cartesian_coords(self, fractional_coords: Vector3Like) -> np.ndarray:
return dot(fractional_coords, self._matrix) | 141,638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.