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], ...] Squa...
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_...
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 ...
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( ...
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)) ...
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 = n...
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 t...
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!") ...
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 check...
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 firs...
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....
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 ...
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 ...
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(): ...
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_properti...
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] ...
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: ...
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: ...
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): C...
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.re...
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...
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 ...
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...
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 t...
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) \ ...
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: ra...
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: ...
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") ...
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...
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:]) basi...
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 contai...
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_...
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]]) ...
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: Se...
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._strin...
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*(.*)", li...
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)...
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.comp...
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: ...
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 ValueE...
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_m...
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_rev...
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=chksymbr...
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_tim...
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 #s...
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: ...
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 ...
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...
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...
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 ...
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,...
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()], C...
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 ...
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\.\(\)]*)", ...
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: ...
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 ...
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 n...
def get_energy_relax_structure_buckingham(structure, gulp_cmd='gulp', keywords=('optimise', 'conp'), valence_dict=None): gio = GulpIO() gc = GulpCaller(gulp_cmd) gin = gio.bucki...
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 Retur...
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): ...
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): Un...
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_...
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 po...
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=Fal...
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()...
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.env...
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("ut...
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 ...
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 ...
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...
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 c...
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 th...
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( che...
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 ...
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] ...
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 th...
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...
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 NotImplem...
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...
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) el...
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() ...
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, t...
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 ...
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.GetPro...
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...
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 ...
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 = ...
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 l...
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(ne...
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 th...
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 ...
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...
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): ...
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 ...
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], ...
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_li...
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....
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...
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 tha...
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_repl...
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 ...
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 = {} ...
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, ...
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...
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: ...
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:...
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_toler...
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.Struc...
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