docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Create from dict. Args: A dict with all data for a band structure object. Returns: A BandStructure object
def from_dict(cls, d): labels_dict = d['labels_dict'] projections = {} structure = None if isinstance(list(d['bands'].values())[0], dict): eigenvals = {Spin(int(k)): np.array(d['bands'][k]['data']) for k in d['bands']} else: ...
139,572
Returns the list of kpoint indices equivalent (meaning they are the same frac coords) to the given one. Args: index: the kpoint index Returns: a list of equivalent indices TODO: now it uses the label we might want to use coordinates instead (in case the...
def get_equivalent_kpoints(self, index): # if the kpoint has no label it can"t have a repetition along the band # structure line object if self.kpoints[index].label is None: return [index] list_index_kpoints = [] for i in range(len(self.kpoints)): ...
139,574
Apply a scissor operator (shift of the CBM) to fit the given band gap. If it's a metal. We look for the band crossing the fermi level and shift this one up. This will not work all the time for metals! Args: new_band_gap: the band gap the scissor band structure need to have. ...
def apply_scissor(self, new_band_gap): if self.is_metal(): # moves then the highest index band crossing the fermi level # find this band... max_index = -1000 # spin_index = None for i in range(self.nb_bands): below = False ...
139,578
The equation of state function with the paramters other than volume set to the ones obtained from fitting. Args: volume (list/numpy.array) Returns: numpy.array
def func(self, volume): return self._func(np.array(volume), self.eos_params)
139,584
Plot the equation of state on axis `ax` Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. fontsize: Legend fontsize. color (str): plot color. label (str): Plot label text (str): Legend text (options) Returns: ...
def plot_ax(self, ax=None, fontsize=12, **kwargs): ax, fig, plt = get_ax_fig_plt(ax=ax) color = kwargs.get("color", "r") label = kwargs.get("label", "{} fit".format(self.__class__.__name__)) lines = ["Equation of State: %s" % self.__class__.__name__, "Minimum e...
139,587
Fit energies as function of volumes. Args: volumes (list/np.array) energies (list/np.array) Returns: EOSBase: EOSBase object
def fit(self, volumes, energies): eos_fit = self.model(np.array(volumes), np.array(energies)) eos_fit.fit() return eos_fit
139,597
Vibrational Helmholtz free energy, A_vib(V, T). Eq(4) in doi.org/10.1016/j.comphy.2003.12.001 Args: temperature (float): temperature in K volume (float) Returns: float: vibrational free energy in eV
def vibrational_free_energy(self, temperature, volume): y = self.debye_temperature(volume) / temperature return self.kb * self.natoms * temperature * ( 9./8. * y + 3 * np.log(1 - np.exp(-y)) - self.debye_integral(y))
139,606
Vibrational internal energy, U_vib(V, T). Eq(4) in doi.org/10.1016/j.comphy.2003.12.001 Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: vibrational internal energy in eV
def vibrational_internal_energy(self, temperature, volume): y = self.debye_temperature(volume) / temperature return self.kb * self.natoms * temperature * (9./8. * y + 3*self.debye_integral(y))
139,607
Debye integral. Eq(5) in doi.org/10.1016/j.comphy.2003.12.001 Args: y (float): debye temperature/T, upper limit Returns: float: unitless
def debye_integral(y): # floating point limit is reached around y=155, so values beyond that # are set to the limiting value(T-->0, y --> \infty) of # 6.4939394 (from wolfram alpha). factor = 3. / y ** 3 if y < 155: integral = quadrature(lambda x: x ** 3 / (n...
139,609
Eq(17) in 10.1103/PhysRevB.90.174107 Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: thermal conductivity in W/K/m
def thermal_conductivity(self, temperature, volume): gamma = self.gruneisen_parameter(temperature, volume) theta_d = self.debye_temperature(volume) # K theta_a = theta_d * self.natoms**(-1./3.) # K prefactor = (0.849 * 3 * 4**(1./3.)) / (20. * np.pi**3) # kg/K^3/s^3 ...
139,611
Set all frac_coords of the input structure within [0,1]. Args: structure (pymatgen structure object): input structure matrix (lattice matrix, 3 by 3 array/matrix) new structure's lattice matrix, if none, use input structure's matrix Return: new struc...
def fix_pbc(structure, matrix=None): spec = [] coords = [] if matrix is None: latte = Lattice(structure.lattice.matrix) else: latte = Lattice(matrix) for site in structure: spec.append(site.specie) coord = np.array(site.frac_coords) for i in range(3): ...
139,613
obtain cubic symmetric eqivalents of the list of vectors. Args: matrix (lattice matrix, n by 3 array/matrix) Return: cubic symmetric eqivalents of the list of vectors.
def symm_group_cubic(mat): sym_group = np.zeros([24, 3, 3]) sym_group[0, :] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] sym_group[1, :] = [[1, 0, 0], [0, -1, 0], [0, 0, -1]] sym_group[2, :] = [[-1, 0, 0], [0, 1, 0], [0, 0, -1]] sym_group[3, :] = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]] sym_group[4, :] =...
139,614
find the axial ratio needed for GB generator input. Args: max_denominator (int): the maximum denominator for the computed ratio, default to be 5. index_none (int): specify the irrational axis. 0-a, 1-b, 2-c. Only may be needed for orthorombic system. ...
def get_ratio(self, max_denominator=5, index_none=None): structure = self.initial_structure lat_type = self.lat_type if lat_type == 't' or lat_type == 'h': # For tetragonal and hexagonal system, ratio = c2 / a2. a, c = (structure.lattice.a, structure.lattice.c) ...
139,628
Reduce integer array mat's determinant mag times by linear combination of its row vectors, so that the new array after rotation (r_matrix) is still an integer array Args: mat (3 by 3 array): input matrix mag (integer): reduce times for the determinant r_matri...
def reduce_mat(mat, mag, r_matrix): max_j = abs(int(round(np.linalg.det(mat) / mag))) reduced = False for h in range(3): k = h + 1 if h + 1 < 3 else abs(2 - h) l = h + 2 if h + 2 < 3 else abs(1 - h) j = np.arange(-max_j, max_j + 1) for j1,...
139,637
Transform a float vector to a surface miller index with integers. Args: vec (1 by 3 array float vector): input float vector Return: the surface miller index of the input vector.
def vec_to_surface(vec): miller = [None] * 3 index = [] for i, value in enumerate(vec): if abs(value) < 1.e-8: miller[i] = 0 else: index.append(i) if len(index) == 1: miller[index[0]] = 1 else: ...
139,638
Adds a Spectrum for plotting. Args: label (str): Label for the Spectrum. Must be unique. spectrum: Spectrum object color (str): This is passed on to matplotlib. E.g., "k--" indicates a dashed black line. If None, a color will be chosen based on ...
def add_spectrum(self, label, spectrum, color=None): self._spectra[label] = spectrum self.colors.append( color or self.colors_cycle[len(self._spectra) % len(self.colors_cycle)])
139,640
Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys.
def add_spectra(self, spectra_dict, key_sort_func=None): if key_sort_func: keys = sorted(spectra_dict.keys(), key=key_sort_func) else: keys = spectra_dict.keys() for label in keys: self.add_spectra(label, spectra_dict[label])
139,641
Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits.
def get_plot(self, xlim=None, ylim=None): plt = pretty_plot(12, 8) base = 0.0 i = 0 for key, sp in self._spectra.items(): if not self.stack: plt.plot(sp.x, sp.y + self.yshift * i, color=self.colors[i], label=str(key), linewid...
139,642
Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS.
def save_plot(self, filename, img_format="eps", **kwargs): plt = self.get_plot(**kwargs) plt.savefig(filename, format=img_format)
139,643
Returns most primitive cell for structure. Args: structure: A structure Returns: The same structure in a conventional standard setting
def apply_transformation(self, structure): sga = SpacegroupAnalyzer(structure, symprec=self.symprec, angle_tolerance=self.angle_tolerance) return sga.get_conventional_standard_structure(international_monoclinic=self.international_monoclinic)
139,659
Discretizes the site occupancies in the structure. Args: structure: disordered Structure to discretize occupancies Returns: A new disordered Structure with occupancies discretized
def apply_transformation(self, structure): if structure.is_ordered: return structure species = [dict(sp) for sp in structure.species_and_occu] for sp in species: for k, v in sp.items(): old_occ = sp[k] new_occ = float( ...
139,663
Converts a lattice object to LammpsBox, and calculates the symmetry operation used. Args: lattice (Lattice): Input lattice. origin: A (3,) array/list of floats setting lower bounds of simulation box. Default to (0, 0, 0). Returns: LammpsBox, SymmOp
def lattice_2_lmpbox(lattice, origin=(0, 0, 0)): a, b, c = lattice.abc xlo, ylo, zlo = origin xhi = a + xlo m = lattice.matrix xy = np.dot(m[1], m[0] / a) yhi = np.sqrt(b ** 2 - xy ** 2) + ylo xz = np.dot(m[2], m[0] / a) yz = (np.dot(m[1], m[2]) - xy * xz) / (yhi - ylo) zhi = np...
139,669
Converts a structure to a LammpsData object with no force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be present due to force field settings but not necessarily in the structure...
def structure_2_lmpdata(structure, ff_elements=None, atom_style="charge"): s = structure.get_sorted_structure() a, b, c = s.lattice.abc m = s.lattice.matrix xhi = a xy = np.dot(m[1], m[0] / xhi) yhi = np.sqrt(b ** 2 - xy ** 2) xz = np.dot(m[2], m[0] / xhi) yz = (np.dot(m[1], m[2]) ...
139,670
Returns the string representation of simulation box in LAMMPS data file format. Args: significant_figures (int): No. of significant figures to output for box settings. Default to 6. Returns: String representation
def get_string(self, significant_figures=6): ph = "{:.%df}" % significant_figures lines = [] for bound, d in zip(self.bounds, "xyz"): fillers = bound + [d] * 2 bound_format = " ".join([ph] * 2 + [" {}lo {}hi"]) lines.append(bound_format.format(*filler...
139,673
Writes LammpsData to file. Args: filename (str): Filename. distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. Default to 6. velocity (int): No. of significant figures to output for ...
def write_file(self, filename, distance=6, velocity=8, charge=3): with open(filename, "w") as f: f.write(self.get_string(distance=distance, velocity=velocity, charge=charge))
139,677
Constructor that parses a file. Args: filename (str): Filename to read. atom_style (str): Associated atom_style. Default to "full". sort_id (bool): Whether sort each section by id. Default to True.
def from_file(cls, filename, atom_style="full", sort_id=False): with open(filename) as f: lines = f.readlines() kw_pattern = r"|".join(itertools.chain(*SECTION_KEYWORDS.values())) section_marks = [i for i, l in enumerate(lines) if re.search(kw_patter...
139,679
Simple constructor building LammpsData from a structure without force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be present due to force field settings but not ...
def from_structure(cls, structure, ff_elements=None, atom_style="charge"): s = structure.get_sorted_structure() box, symmop = lattice_2_lmpbox(s.lattice) coords = symmop.operate_multi(s.cart_coords) site_properties = s.site_properties if "velocities" in site_properties: ...
139,681
Saves object to a file in YAML format. Args: filename (str): Filename.
def to_file(self, filename): d = {"mass_info": self.mass_info, "nonbond_coeffs": self.nonbond_coeffs, "topo_coeffs": self.topo_coeffs} yaml = YAML(typ="safe") with open(filename, "w") as f: yaml.dump(d, f)
139,689
Constructor that reads in a file in YAML format. Args: filename (str): Filename.
def from_file(cls, filename): yaml = YAML(typ="safe") with open(filename, "r") as f: d = yaml.load(f) return cls.from_dict(d)
139,690
Copy the pseudopotential to a temporary a file and returns a new pseudopotential object. Useful for unit tests in which we have to change the content of the file. Args: tmpdir: If None, a new temporary directory is created and files are copied here else tmpdir is used.
def as_tmpfile(self, tmpdir=None): import tempfile, shutil tmpdir = tempfile.mkdtemp() if tmpdir is None else tmpdir new_path = os.path.join(tmpdir, self.basename) shutil.copy(self.filepath, new_path) # Copy dojoreport file if present. root, ext = os.path.splite...
139,704
Returns a :class:`Hint` object with the suggested value of ecut [Ha] and pawecutdg [Ha] for the given accuracy. ecut and pawecutdg are set to zero if no hint is available. Args: accuracy: ["low", "normal", "high"]
def hint_for_accuracy(self, accuracy="normal"): if not self.has_dojo_report: return Hint(ecut=0., pawecutdg=0.) # Get hints from dojoreport. Try first in hints then in ppgen_hints. if "hints" in self.dojo_report: return Hint.from_dict(self.dojo_report["hints"][a...
139,706
Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: ecut: Cutoff energy in Hartree. pawecutdg...
def open_pspsfile(self, ecut=20, pawecutdg=None): from pymatgen.io.abinit.tasks import AbinitTask from abipy.core.structure import Structure from abipy.abio.factories import gs_input from abipy.electrons.psps import PspsFile # Build fake structure. lattice = 10 ...
139,708
Analyze the files contained in directory dirname. Args: dirname: directory path exclude_exts: list of file extensions that should be skipped. exclude_fnames: list of file names that should be skipped. Returns: List of pseudopotential objects.
def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()): for i, ext in enumerate(exclude_exts): if not ext.strip().startswith("."): exclude_exts[i] = "." + ext.strip() # Exclude files depending on the extension. paths = [] for fname in...
139,719
Plot the PAW densities. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure
def plot_densities(self, ax=None, **kwargs): ax, fig, plt = get_ax_fig_plt(ax) ax.grid(True) ax.set_xlabel('r [Bohr]') #ax.set_ylabel('density') for i, den_name in enumerate(["ae_core_density", "pseudo_core_density"]): rden = getattr(self, den_name) ...
139,734
Plot the AE and the pseudo partial waves. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. fontsize: fontsize for legends and titles Returns: `matplotlib` figure
def plot_waves(self, ax=None, fontsize=12, **kwargs): ax, fig, plt = get_ax_fig_plt(ax) ax.grid(True) ax.set_xlabel("r [Bohr]") ax.set_ylabel(r"$r\phi,\, r\tilde\phi\, [Bohr]^{-\frac{1}{2}}$") #ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle="--") ...
139,735
Plot the PAW projectors. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure
def plot_projectors(self, ax=None, fontsize=12, **kwargs): ax, fig, plt = get_ax_fig_plt(ax) title = kwargs.pop("title", "Projectors") ax.grid(True) ax.set_xlabel('r [Bohr]') ax.set_ylabel(r"$r\tilde p\, [Bohr]^{-\frac{1}{2}}$") #ax.axvline(x=self.paw_radius, li...
139,736
Find all pseudos in the directory tree starting from top. Args: top: Top of the directory tree exts: List of files extensions. if exts == "all_files" we try to open all files in top exclude_dirs: Wildcard used to exclude directories. return: :cla...
def from_dir(cls, top, exts=None, exclude_dirs="_*"): pseudos = [] if exts == "all_files": for f in [os.path.join(top, fn) for fn in os.listdir(top)]: if os.path.isfile(f): try: p = Pseudo.from_file(f) ...
139,737
Return the pseudo with the given chemical symbol. Args: symbols: String with the chemical symbol of the element allow_multi: By default, the method raises ValueError if multiple occurrences are found. Use allow_multi to prevent this. Raises: ValueErr...
def pseudo_with_symbol(self, symbol, allow_multi=False): pseudos = self.select_symbols(symbol, ret_list=True) if not pseudos or (len(pseudos) > 1 and not allow_multi): raise ValueError("Found %d occurrences of symbol %s" % (len(pseudos), symbol)) if not allow_multi: ...
139,745
Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable...
def select_symbols(self, symbols, ret_list=False): symbols = list_strings(symbols) exclude = symbols[0].startswith("-") if exclude: if not all(s.startswith("-") for s in symbols): raise ValueError("When excluding symbols, all strings must start with `-`") ...
139,747
A pretty ASCII printer for the periodic table, based on some filter_function. Args: stream: file-like object filter_function: A filtering function that take a Pseudo as input and returns a boolean. For example, setting filter_function = lambda p: p.Z_val ...
def print_table(self, stream=sys.stdout, filter_function=None): print(self.to_table(filter_function=filter_function), file=stream)
139,748
Select only those pseudopotentials for which condition is True. Return new class:`PseudoTable` object. Args: condition: Function that accepts a :class:`Pseudo` object and returns True or False.
def select(self, condition): return self.__class__([p for p in self if condition(p)])
139,752
Get a list of Structures corresponding to a chemical system, formula, or materials_id. Args: chemsys_formula_id (str): A chemical system (e.g., Li-Fe-O), or formula (e.g., Fe2O3) or materials_id (e.g., mp-1234). final (bool): Whether to get the final structure, o...
def get_structures(self, chemsys_formula_id, final=True): prop = "final_structure" if final else "initial_structure" data = self.get_data(chemsys_formula_id, prop=prop) return [d[prop] for d in data]
139,759
Finds matching structures on the Materials Project site. Args: filename_or_structure: filename or Structure object Returns: A list of matching structures. Raises: MPRestError
def find_structure(self, filename_or_structure): try: if isinstance(filename_or_structure, str): s = Structure.from_file(filename_or_structure) elif isinstance(filename_or_structure, Structure): s = filename_or_structure else: ...
139,760
A helper function to get all entries necessary to generate a pourbaix diagram from the rest interface. Args: chemsys ([str]): A list of elements comprising the chemical system, e.g. ['Li', 'Fe']
def get_pourbaix_entries(self, chemsys): from pymatgen.analysis.pourbaix_diagram import PourbaixEntry, IonEntry from pymatgen.analysis.phase_diagram import PhaseDiagram from pymatgen.core.ion import Ion from pymatgen.entries.compatibility import \ MaterialsProjectAqu...
139,762
Get a Structure corresponding to a material_id. Args: material_id (str): Materials Project material_id (a string, e.g., mp-1234). final (bool): Whether to get the final structure, or the initial (pre-relaxation) structure. Defaults to True. co...
def get_structure_by_material_id(self, material_id, final=True, conventional_unit_cell=False): prop = "final_structure" if final else "initial_structure" data = self.get_data(material_id, prop=prop) if conventional_unit_cell: data[0][prop...
139,763
Submits a list of StructureNL to the Materials Project site. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: snl (StructureNL/[StructureNL]): A...
def submit_snl(self, snl): try: snl = snl if isinstance(snl, list) else [snl] jsondata = [s.as_dict() for s in snl] payload = {"snl": json.dumps(jsondata, cls=MontyEncoder)} response = self.session.post("{}/snl/submit".format(self.preamble), ...
139,769
Delete earlier submitted SNLs. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: snl_ids: List of SNL ids. Raises: MPRestErr...
def delete_snl(self, snl_ids): try: payload = {"ids": json.dumps(snl_ids)} response = self.session.post( "{}/snl/delete".format(self.preamble), data=payload) if response.status_code in [200, 400]: resp = json.loads(response.text, cls=...
139,770
Query for submitted SNLs. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args: criteria (dict): Query criteria. Returns: A dict...
def query_snl(self, criteria): try: payload = {"criteria": json.dumps(criteria)} response = self.session.post("{}/snl/query".format(self.preamble), data=payload) if response.status_code in [200, 400]: resp = js...
139,771
Gets the cohesive for a material (eV per formula unit). Cohesive energy is defined as the difference between the bulk energy and the sum of total DFT energy of isolated atoms for atom elements in the bulk. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'....
def get_cohesive_energy(self, material_id, per_atom=False): entry = self.get_entry_by_material_id(material_id) ebulk = entry.energy / \ entry.composition.get_integer_formula_and_factor()[1] comp_dict = entry.composition.reduced_composition.as_dict() isolated_ato...
139,773
Gets a reaction from the Materials Project. Args: reactants ([str]): List of formulas products ([str]): List of formulas Returns: rxn
def get_reaction(self, reactants, products): return self._make_request("/reaction", payload={"reactants[]": reactants, "products[]": products}, mp_decode=False)
139,774
Constructs a Wulff shape for a material. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. Returns: pymatgen.analysis.wulff.WulffShape
def get_wulff_shape(self, material_id): from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.analysis.wulff import WulffShape, hkl_tuple_to_str structure = self.get_structure_by_material_id(material_id) surfaces = self.get_surface_data(material_id)["surfaces"...
139,777
Returns an EntrySet containing only the set of entries belonging to a particular chemical system (in this definition, it includes all sub systems). For example, if the entries are from the Li-Fe-P-O system, and chemsys=["Li", "O"], only the Li, O, and Li-O entries are returned. ...
def get_subset_in_chemsys(self, chemsys: List[str]): chemsys = set(chemsys) if not chemsys.issubset(self.chemsys): raise ValueError("%s is not a subset of %s" % (chemsys, self.chemsys)) subset = set() for e i...
139,790
Exports PDEntries to a csv Args: filename: Filename to write to. entries: PDEntries to export. latexify_names: Format entry names to be LaTex compatible, e.g., Li_{2}O
def to_csv(self, filename: str, latexify_names: bool = False): elements = set() for entry in self.entries: elements.update(entry.composition.elements) elements = sorted(list(elements), key=lambda a: a.X) writer = csv.writer(open(filename, "w"), delimiter=unicode2str...
139,791
Imports PDEntries from a csv. Args: filename: Filename to import from. Returns: List of Elements, List of PDEntries
def from_csv(cls, filename: str): with open(filename, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter=unicode2str(","), quotechar=unicode2str("\""), quoting=csv.QUOTE_MINIMAL) entries = list() ...
139,792
Helper function to convert a Vasprun parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml.
def _parse_parameters(val_type, val): if val_type == "logical": return val == "T" elif val_type == "int": return int(val) elif val_type == "string": return val.strip() else: return float(val)
139,793
Returns the grid for a particular axis. Args: ind (int): Axis index.
def get_axis_grid(self, ind): ng = self.dim num_pts = ng[ind] lengths = self.structure.lattice.abc return [i / num_pts * lengths[ind] for i in range(num_pts)]
139,858
Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum. Args: other (VolumetricData): Another VolumetricData object scale_factor (float): Factor to scale the other data by. Re...
def linear_add(self, other, scale_factor=1.0): if self.structure != other.structure: raise ValueError("Adding or subtraction operations can only be " "performed for volumetric data with the exact " "same structure.") # To add...
139,859
Convenience method to parse a generic volumetric data file in the vasp like format. Used by subclasses for parsing file. Args: filename (str): Path of file to parse Returns: (poscar, data)
def parse_file(filename): poscar_read = False poscar_string = [] dataset = [] all_dataset = [] # for holding any strings in input that are not Poscar # or VolumetricData (typically augmentation charges) all_dataset_aug = {} dim = None diml...
139,860
Write the VolumetricData object to a vasp compatible file. Args: file_name (str): Path to a file vasp4_compatible (bool): True if the format is vasp4 compatible
def write_file(self, file_name, vasp4_compatible=False): def _print_fortran_float(f): s = "{:.10E}".format(f) if f >= 0: return "0." + s[0] + s[2:12] + 'E' + "{:+03}".format(int(s[13:]) + 1) else: return "-." + s[1] + s[3...
139,861
Get the averaged total of the volumetric data a certain axis direction. For example, useful for visualizing Hartree Potentials from a LOCPOT file. Args: ind (int): Index of axis. Returns: Average total along axis
def get_average_along_axis(self, ind): m = self.data["total"] ng = self.dim if ind == 0: total = np.sum(np.sum(m, axis=1), 1) elif ind == 1: total = np.sum(np.sum(m, axis=0), 1) else: total = np.sum(np.sum(m, axis=0), 0) return...
139,863
Method returning a dictionary of projections on elements. Args: structure (Structure): Input structure. Returns: a dictionary in the {Spin.up:[k index][b index][{Element:values}]]
def get_projection_on_elements(self, structure): dico = {} for spin in self.data.keys(): dico[spin] = [[defaultdict(float) for i in range(self.nkpoints)] for j in range(self.nbands)] for iat in range(self.nions): ...
139,871
Init a Xdatcar. Args: filename (str): Filename of input XDATCAR file. ionicstep_start (int): Starting number of ionic step. ionicstep_end (int): Ending number of ionic step.
def __init__(self, filename, ionicstep_start=1, ionicstep_end=None, comment=None): preamble = None coords_str = [] structures = [] preamble_done = False if (ionicstep_start < 1): raise Exception('Start ionic step cannot be less than 1') ...
139,875
Write Xdatcar class into a file Args: filename (str): Filename of output XDATCAR file. ionicstep_start (int): Starting number of ionic step. ionicstep_end (int): Ending number of ionic step.
def get_string(self, ionicstep_start=1, ionicstep_end=None, significant_figures=8): from pymatgen.io.vasp import Poscar if (ionicstep_start < 1): raise Exception('Start ionic step cannot be less than 1') if (ionicstep_end is not None and...
139,878
Information is extracted from the given WAVECAR Args: filename (str): input file (default: WAVECAR) verbose (bool): determines whether processing information is shown precision (str): determines how fine the fft mesh is (normal or accurate), only...
def __init__(self, filename='WAVECAR', verbose=False, precision='normal'): self.filename = filename # c = 0.26246582250210965422 # 2m/hbar^2 in agreement with VASP self._C = 0.262465831 with open(self.filename, 'rb') as f: # read the header information ...
139,881
Helper function to generate G-points based on nbmax. This function iterates over possible G-point values and determines if the energy is less than G_{cut}. Valid values are appended to the output array. This function should not be called outside of initialization. Args: ...
def _generate_G_points(self, kpoint): gpoints = [] for i in range(2 * self._nbmax[2] + 1): i3 = i - 2 * self._nbmax[2] - 1 if i > self._nbmax[2] else i for j in range(2 * self._nbmax[1] + 1): j2 = j - 2 * self._nbmax[1] - 1 if j > self._nbmax[1] else j ...
139,883
Method returning a numpy array with elements [cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag] between bands band_i and band_j (vasp 1-based indexing) for all kpoints. Args: band_i (Integer): Index of band i band_j (Integer): Index of band ...
def get_elements_between_bands(self, band_i, band_j): if band_i < 1 or band_i > self.nb_bands or band_j < 1 or band_j > self.nb_bands: raise ValueError("Band index out of bounds") return self.data[:, band_i - 1, band_j - 1, :]
139,888
Method returning a value between bands band_i and band_j for k-point index, spin-channel and cartesian direction. Args: band_i (Integer): Index of band i band_j (Integer): Index of band j kpoint (Integer): Index of k-point spin (Integer): Index of spin-c...
def get_orbital_derivative_between_states(self, band_i, band_j, kpoint, spin, cart_dir): if band_i < 0 or band_i > self.nbands - 1 or band_j < 0 or band_j > self.nelect - 1: raise ValueError("Band index out of bounds") if kpoint > self.nkpoints: raise ValueError("K-point...
139,890
Initializes the SymmOp from a 4x4 affine transformation matrix. In general, this constructor should not be used unless you are transferring rotations. Use the static constructors instead to generate a SymmOp from proper rotations and translation. Args: affine_transformation...
def __init__(self, affine_transformation_matrix, tol=0.01): affine_transformation_matrix = np.array(affine_transformation_matrix) if affine_transformation_matrix.shape != (4, 4): raise ValueError("Affine Matrix must be a 4x4 numpy array!") self.affine_matrix = affine_transfo...
139,891
Creates a symmetry operation from a rotation matrix and a translation vector. Args: rotation_matrix (3x3 array): Rotation matrix. translation_vec (3x1 array): Translation vector. tol (float): Tolerance to determine if rotation matrix is valid. Returns: ...
def from_rotation_and_translation( rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec=(0, 0, 0), tol=0.1): rotation_matrix = np.array(rotation_matrix) translation_vec = np.array(translation_vec) if rotation_matrix.shape != (3, 3): rais...
139,892
Apply the operation on a point. Args: point: Cartesian coordinate. Returns: Coordinates of point after operation.
def operate(self, point): affine_point = np.array([point[0], point[1], point[2], 1]) return np.dot(self.affine_matrix, affine_point)[0:3]
139,895
Apply the operation on a list of points. Args: points: List of Cartesian coordinates Returns: Numpy array of coordinates after operation
def operate_multi(self, points): points = np.array(points) affine_points = np.concatenate( [points, np.ones(points.shape[:-1] + (1,))], axis=-1) return np.inner(affine_points, self.affine_matrix)[..., :-1]
139,896
Applies rotation portion to a tensor. Note that tensor has to be in full form, not the Voigt form. Args: tensor (numpy array): a rank n tensor Returns: Transformed tensor.
def transform_tensor(self, tensor): dim = tensor.shape rank = len(dim) assert all([i == 3 for i in dim]) # Build einstein sum string lc = string.ascii_lowercase indices = lc[:rank], lc[rank:2 * rank] einsum_string = ','.join([a + i for a, i in zip(*indice...
139,897
Checks if two points are symmetrically related. Args: point_a (3x1 array): First point. point_b (3x1 array): Second point. tol (float): Absolute tolerance for checking distance. Returns: True if self.operate(point_a) == point_b or vice versa.
def are_symmetrically_related(self, point_a, point_b, tol=0.001): if np.allclose(self.operate(point_a), point_b, atol=tol): return True if np.allclose(self.operate(point_b), point_a, atol=tol): return True return False
139,898
Returns reflection symmetry operation. Args: normal (3x1 array): Vector of the normal to the plane of reflection. origin (3x1 array): A point in which the mirror plane passes through. Returns: SymmOp for the reflection about the plane
def reflection(normal, origin=(0, 0, 0)): # Normalize the normal vector first. n = np.array(normal, dtype=float) / np.linalg.norm(normal) u, v, w = n translation = np.eye(4) translation[0:3, 3] = -np.array(origin) xx = 1 - 2 * u ** 2 yy = 1 - 2 * v ** ...
139,903
Inversion symmetry operation about axis. Args: origin (3x1 array): Origin of the inversion operation. Defaults to [0, 0, 0]. Returns: SymmOp representing an inversion operation about the origin.
def inversion(origin=(0, 0, 0)): mat = -np.eye(4) mat[3, 3] = 1 mat[0:3, 3] = 2 * np.array(origin) return SymmOp(mat)
139,904
Returns a roto-reflection symmetry operation Args: axis (3x1 array): Axis of rotation / mirror normal angle (float): Angle in degrees origin (3x1 array): Point left invariant by roto-reflection. Defaults to (0, 0, 0). Return: Roto-reflect...
def rotoreflection(axis, angle, origin=(0, 0, 0)): rot = SymmOp.from_origin_axis_angle(origin, axis, angle) refl = SymmOp.reflection(axis, origin) m = np.dot(rot.affine_matrix, refl.affine_matrix) return SymmOp(m)
139,905
Apply time reversal operator on the magnetic moment. Note that magnetic moments transform as axial vectors, not polar vectors. See 'Symmetry and magnetic structures', Rodríguez-Carvajal and Bourée for a good discussion. DOI: 10.1051/epjconf/20122200010 Args: magmom: Magnet...
def operate_magmom(self, magmom): magmom = Magmom(magmom) # type casting to handle lists as input transformed_moment = self.apply_rotation_only(magmom.global_moment) * \ np.linalg.det(self.rotation_matrix) * self.time_reversal # retains input spin axis if different from ...
139,912
Initialize a MagSymmOp from a SymmOp and time reversal operator. Args: symmop (SymmOp): SymmOp time_reversal (int): Time reversal operator, +1 or -1. Returns: MagSymmOp object
def from_symmop(cls, symmop, time_reversal): magsymmop = cls(symmop.affine_matrix, time_reversal, symmop.tol) return magsymmop
139,913
Creates a symmetry operation from a rotation matrix, translation vector and time reversal operator. Args: rotation_matrix (3x3 array): Rotation matrix. translation_vec (3x1 array): Translation vector. time_reversal (int): Time reversal operator, +1 or -1. ...
def from_rotation_and_translation_and_time_reversal( rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec=(0, 0, 0), time_reversal=1, tol=0.1): symmop = SymmOp.from_rotation_and_translation(rotation_matrix=rotation_matrix, ...
139,914
A class method for quickly creating DFT tasks with optional cosmo parameter . Args: mol: Input molecule xc: Exchange correlation to use. \\*\\*kwargs: Any of the other kwargs supported by NwTask. Note the theory is always "dft" for a dft task.
def dft_task(cls, mol, xc="b3lyp", **kwargs): t = NwTask.from_molecule(mol, theory="dft", **kwargs) t.theory_directives.update({"xc": xc, "mult": t.spin_multiplicity}) return t
139,932
Read an NwInput from a string. Currently tested to work with files generated from this class itself. Args: string_input: string_input to parse. Returns: NwInput object
def from_string(cls, string_input): directives = [] tasks = [] charge = None spin_multiplicity = None title = None basis_set = None basis_set_option = None theory_directives = {} geom_options = None symmetry_options = None ...
139,937
Generate an excitation spectra from the singlet roots of TDDFT calculations. Args: width (float): Width for Gaussian smearing. npoints (int): Number of energy points. More points => smoother curve. Returns: (ExcitationSpectrum) which can be p...
def get_excitation_spectrum(self, width=0.1, npoints=2000): roots = self.parse_tddft() data = roots["singlet"] en = np.array([d["energy"] for d in data]) osc = np.array([d["osc_strength"] for d in data]) epad = 20.0 * width emin = en[0] - epad emax = en[...
139,940
Generates an ion object from a dict created by as_dict(). Args: d: {symbol: amount} dict.
def from_dict(cls, d): charge = d.pop('charge') composition = Composition(d) return Ion(composition, charge)
139,949
Obtains a SpaceGroup name from its international number. Args: int_number (int): International number. hexagonal (bool): For rhombohedral groups, whether to return the hexagonal setting (default) or rhombohedral setting. Returns: (str) Spacegroup symbol
def sg_symbol_from_int_number(int_number, hexagonal=True): syms = [] for n, v in get_symm_data("space_group_encoding").items(): if v["int_number"] == int_number: syms.append(n) if len(syms) == 0: raise ValueError("Invalid international number!") if len(syms) == 2: ...
139,996
Extremely efficient nd-array comparison using numpy's broadcasting. This function checks if a particular array a, is present in a list of arrays. It works for arrays of any size, e.g., even matrix searches. Args: array_list ([array]): A list of arrays to compare to. a (array): The test arra...
def in_array_list(array_list, a, tol=1e-5): if len(array_list) == 0: return False axes = tuple(range(1, a.ndim + 1)) if not tol: return np.any(np.all(np.equal(array_list, a[None, :]), axes)) else: return np.any(np.sum(np.abs(array_list - a[None, :]), axes) < tol)
139,997
True if this group is a subgroup of the supplied group. Args: supergroup (SymmetryGroup): Supergroup to test. Returns: True if this group is a subgroup of the supplied group.
def is_subgroup(self, supergroup): warnings.warn("This is not fully functional. Only trivial subsets are tested right now. ") return set(self.symmetry_ops).issubset(supergroup.symmetry_ops)
139,999
True if this group is a supergroup of the supplied group. Args: subgroup (SymmetryGroup): Subgroup to test. Returns: True if this group is a supergroup of the supplied group.
def is_supergroup(self, subgroup): warnings.warn("This is not fully functional. Only trivial subsets are " "tested right now. ") return set(subgroup.symmetry_ops).issubset(self.symmetry_ops)
140,000
Strips whitespace, carriage returns and empty lines from a list of strings. Args: string_list: List of strings remove_empty_lines: Set to True to skip lines which are empty after stripping. Returns: List of clean strings with no whitespaces.
def clean_lines(string_list, remove_empty_lines=True): for s in string_list: clean_s = s if '#' in s: ind = s.index('#') clean_s = s[:ind] clean_s = clean_s.strip() if (not remove_empty_lines) or clean_s != '': yield clean_s
140,003
Convert a PhonopyAtoms object to pymatgen Structure object. Args: phonopy_structure (PhonopyAtoms): A phonopy structure object.
def get_pmg_structure(phonopy_structure): lattice = phonopy_structure.get_cell() frac_coords = phonopy_structure.get_scaled_positions() symbols = phonopy_structure.get_chemical_symbols() masses = phonopy_structure.get_masses() mms = phonopy_structure.get_magnetic_moments() mms = mms or [0]...
140,009
Convert a pymatgen Structure object to a PhonopyAtoms object. Args: pmg_structure (pymatgen Structure): A Pymatgen structure object.
def get_phonopy_structure(pmg_structure): symbols = [site.specie.symbol for site in pmg_structure] return PhonopyAtoms(symbols=symbols, cell=pmg_structure.lattice.matrix, scaled_positions=pmg_structure.frac_coords)
140,010
Creates a pymatgen CompletePhononDos from a partial_dos.dat and phonopy.yaml files. The second is produced when generating a Dos and is needed to extract the structure. Args: partial_dos_path: path to the partial_dos.dat file. phonopy_yaml_path: path to the phonopy.yaml file.
def get_complete_ph_dos(partial_dos_path, phonopy_yaml_path): a = np.loadtxt(partial_dos_path).transpose() d = loadfn(phonopy_yaml_path) structure = get_structure_from_dict(d['primitive_cell']) total_dos = PhononDos(a[0], a[1:].sum(axis=0)) pdoss = {} for site, pdos in zip(structure, a[1...
140,015
Returns unique families of Miller indices. Families must be permutations of each other. Args: hkls ([h, k, l]): List of Miller indices. Returns: {hkl: multiplicity}: A dict with unique hkl and multiplicity.
def get_unique_families(hkls): # TODO: Definitely can be sped up. def is_perm(hkl1, hkl2): h1 = np.abs(hkl1) h2 = np.abs(hkl2) return all([i == j for i, j in zip(sorted(h1), sorted(h2))]) unique = collections.defaultdict(list) for hkl1 in hkls: found = False ...
140,017
Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum of y to a value, i.e., like a probability density). value...
def normalize(self, mode="max", value=1): if mode.lower() == "sum": factor = np.sum(self.y, axis=0) elif mode.lower() == "max": factor = np.max(self.y, axis=0) else: raise ValueError("Unsupported normalization mode %s!" % mode) self.y /= fact...
140,028
Apply Gaussian smearing to spectrum y value. Args: sigma: Std dev for Gaussian smear function
def smear(self, sigma): diff = [self.x[i + 1] - self.x[i] for i in range(len(self.x) - 1)] avg_x_per_step = np.sum(diff) / len(diff) if len(self.ydim) == 1: self.y = gaussian_filter1d(self.y, sigma / avg_x_per_step) else: self.y = np.array([ ...
140,029
Returns an interpolated y value for a particular x value. Args: x: x value to return the y value for Returns: Value of y at x
def get_interpolated_value(self, x): if len(self.ydim) == 1: return get_linear_interpolated_value(self.x, self.y, x) else: return [get_linear_interpolated_value(self.x, self.y[:, k], x) for k in range(self.ydim[1])]
140,030
Add two Spectrum object together. Checks that x scales are the same. Otherwise, a ValueError is thrown. Args: other: Another Spectrum object Returns: Sum of the two Spectrum objects
def __add__(self, other): if not all(np.equal(self.x, other.x)): raise ValueError("X axis values are not compatible!") return self.__class__(self.x, self.y + other.y, *self._args, **self._kwargs)
140,032
Scale the Spectrum's y values Args: other: scalar, The scale amount Returns: Spectrum object with y values scaled
def __mul__(self, other): return self.__class__(self.x, other * self.y, *self._args, **self._kwargs)
140,033
True division of y Args: other: The divisor Returns: Spectrum object with y values divided
def __truediv__(self, other): return self.__class__(self.x, self.y.__truediv__(other), *self._args, **self._kwargs)
140,034
True division of y Args: other: The divisor Returns: Spectrum object with y values divided
def __floordiv__(self, other): return self.__class__(self.x, self.y.__floordiv__(other), *self._args, **self._kwargs)
140,035
Setup of the options for the spline interpolation Args: spline_options (dict): Options for cubic spline. For example, {"saddle_point": "zero_slope"} forces the slope at the saddle to be zero.
def setup_spline(self, spline_options=None): self.spline_options = spline_options relative_energies = self.energies - self.energies[0] if scipy_old_piecewisepolynomial: if self.spline_options: raise RuntimeError('Option for saddle point not available with' ...
140,040