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: eigenvals = {Spin(int(k)): d['bands'][k] for k in d['bands']} if 'structure' in d: structure = Structure.from_dict(d['structure']) if d.get('projections'): projections = {Spin(int(spin)): np.array(v) for spin, v in d["projections"].items()} return BandStructure( d['kpoints'], eigenvals, Lattice(d['lattice_rec']['matrix']), d['efermi'], labels_dict, structure=structure, projections=projections)
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 there was a mislabel)
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)): if self.kpoints[i].label == self.kpoints[index].label: list_index_kpoints.append(i) return list_index_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. Returns: a BandStructureSymmLine object with the applied scissor shift
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 above = False for j in range(len(self.kpoints)): if self.bands[Spin.up][i][j] < self.efermi: below = True if self.bands[Spin.up][i][j] > self.efermi: above = True if above and below: if i > max_index: max_index = i # spin_index = Spin.up if self.is_spin_polarized: below = False above = False for j in range(len(self.kpoints)): if self.bands[Spin.down][i][j] < self.efermi: below = True if self.bands[Spin.down][i][j] > self.efermi: above = True if above and below: if i > max_index: max_index = i # spin_index = Spin.down old_dict = self.as_dict() shift = new_band_gap for spin in old_dict['bands']: for k in range(len(old_dict['bands'][spin])): for v in range(len(old_dict['bands'][spin][k])): if k >= max_index: old_dict['bands'][spin][k][v] = \ old_dict['bands'][spin][k][v] + shift else: shift = new_band_gap - self.get_band_gap()['energy'] old_dict = self.as_dict() for spin in old_dict['bands']: for k in range(len(old_dict['bands'][spin])): for v in range(len(old_dict['bands'][spin][k])): if old_dict['bands'][spin][k][v] >= \ old_dict['cbm']['energy']: old_dict['bands'][spin][k][v] = \ old_dict['bands'][spin][k][v] + shift old_dict['efermi'] = old_dict['efermi'] + shift return LobsterBandStructureSymmLine.from_dict(old_dict)
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: Matplotlib figure object.
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 energy = %1.2f eV" % self.e0, "Minimum or reference volume = %1.2f Ang^3" % self.v0, "Bulk modulus = %1.2f eV/Ang^3 = %1.2f GPa" % (self.b0, self.b0_GPa), "Derivative of bulk modulus wrt pressure = %1.2f" % self.b1] text = "\n".join(lines) text = kwargs.get("text", text) # Plot input data. ax.plot(self.volumes, self.energies, linestyle="None", marker="o", color=color) # Plot eos fit. vmin, vmax = min(self.volumes), max(self.volumes) vmin, vmax = (vmin - 0.01 * abs(vmin), vmax + 0.01 * abs(vmax)) vfit = np.linspace(vmin, vmax, 100) ax.plot(vfit, self.func(vfit), linestyle="dashed", color=color, label=label) ax.grid(True) ax.set_xlabel("Volume $\\AA^3$") ax.set_ylabel("Energy (eV)") ax.legend(loc="best", shadow=True) # Add text with fit parameters. ax.text(0.5, 0.5, text, fontsize=fontsize, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) return fig
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 / (np.exp(x) - 1.), 0, y) return list(integral)[0] * factor else: return 6.493939 * factor
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 prefactor = prefactor * (self.kb/self.hbar)**3 * self.avg_mass kappa = prefactor / (gamma**2 - 0.514 * gamma + 0.228) # kg/K/s^3 * Ang = (kg m/s^2)/(Ks)*1e-10 # = N/(Ks)*1e-10 = Nm/(Kms)*1e-10 = W/K/m*1e-10 kappa = kappa * theta_a**2 * volume**(1./3.) * 1e-10 return kappa
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 structure with fixed frac_coords and lattice matrix
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): coord[i] -= floor(coord[i]) if np.allclose(coord[i], 1): coord[i] = 0 elif np.allclose(coord[i], 0): coord[i] = 0 else: coord[i] = round(coord[i], 7) coords.append(coord) return Structure(latte, spec, coords, site_properties=structure.site_properties)
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, :] = [[0, -1, 0], [-1, 0, 0], [0, 0, -1]] sym_group[5, :] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] sym_group[6, :] = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]] sym_group[7, :] = [[0, 1, 0], [1, 0, 0], [0, 0, -1]] sym_group[8, :] = [[-1, 0, 0], [0, 0, -1], [0, -1, 0]] sym_group[9, :] = [[-1, 0, 0], [0, 0, 1], [0, 1, 0]] sym_group[10, :] = [[1, 0, 0], [0, 0, -1], [0, 1, 0]] sym_group[11, :] = [[1, 0, 0], [0, 0, 1], [0, -1, 0]] sym_group[12, :] = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] sym_group[13, :] = [[0, 1, 0], [0, 0, -1], [-1, 0, 0]] sym_group[14, :] = [[0, -1, 0], [0, 0, 1], [-1, 0, 0]] sym_group[15, :] = [[0, -1, 0], [0, 0, -1], [1, 0, 0]] sym_group[16, :] = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] sym_group[17, :] = [[0, 0, 1], [-1, 0, 0], [0, -1, 0]] sym_group[18, :] = [[0, 0, -1], [1, 0, 0], [0, -1, 0]] sym_group[19, :] = [[0, 0, -1], [-1, 0, 0], [0, 1, 0]] sym_group[20, :] = [[0, 0, -1], [0, -1, 0], [-1, 0, 0]] sym_group[21, :] = [[0, 0, -1], [0, 1, 0], [1, 0, 0]] sym_group[22, :] = [[0, 0, 1], [0, -1, 0], [1, 0, 0]] sym_group[23, :] = [[0, 0, 1], [0, 1, 0], [-1, 0, 0]] mat = np.atleast_2d(mat) all_vectors = [] for sym in sym_group: for vec in mat: all_vectors.append(np.dot(sym, vec)) return np.unique(np.array(all_vectors), axis=0)
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. Returns: axial ratio needed for GB generator (list of integers).
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) if c > a: frac = Fraction(c ** 2 / a ** 2).limit_denominator(max_denominator) ratio = [frac.numerator, frac.denominator] else: frac = Fraction(a ** 2 / c ** 2).limit_denominator(max_denominator) ratio = [frac.denominator, frac.numerator] elif lat_type == 'r': # For rhombohedral system, ratio = (1 + 2 * cos(alpha)) / cos(alpha). cos_alpha = cos(structure.lattice.alpha / 180 * np.pi) frac = Fraction((1 + 2 * cos_alpha) / cos_alpha).limit_denominator(max_denominator) ratio = [frac.numerator, frac.denominator] elif lat_type == 'o': # For orthorhombic system, ratio = c2:b2:a2.If irrational for one axis, set it to None. ratio = [None] * 3 lat = (structure.lattice.c, structure.lattice.b, structure.lattice.a) index = [0, 1, 2] if index_none is None: min_index = np.argmin(lat) index.pop(min_index) frac1 = Fraction(lat[index[0]] ** 2 / lat[min_index] ** 2).limit_denominator(max_denominator) frac2 = Fraction(lat[index[1]] ** 2 / lat[min_index] ** 2).limit_denominator(max_denominator) com_lcm = lcm(frac1.denominator, frac2.denominator) ratio[min_index] = com_lcm ratio[index[0]] = frac1.numerator * int(round((com_lcm / frac1.denominator))) ratio[index[1]] = frac2.numerator * int(round((com_lcm / frac2.denominator))) else: index.pop(index_none) if (lat[index[0]] > lat[index[1]]): frac = Fraction(lat[index[0]] ** 2 / lat[index[1]] ** 2).limit_denominator(max_denominator) ratio[index[0]] = frac.numerator ratio[index[1]] = frac.denominator else: frac = Fraction(lat[index[1]] ** 2 / lat[index[0]] ** 2).limit_denominator(max_denominator) ratio[index[1]] = frac.numerator ratio[index[0]] = frac.denominator elif lat_type == 'c': raise RuntimeError('Cubic system does not need axial ratio.') else: raise RuntimeError('Lattice type not implemented.') return ratio
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_matrix (3 by 3 array): rotation matrix Return: the reduced integer array
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, j2 in itertools.product(j, repeat=2): temp = mat[h] + j1 * mat[k] + j2 * mat[l] if all([np.round(x, 5).is_integer() for x in list(temp / mag)]): mat_copy = mat.copy() mat_copy[h] = np.array([int(round(ele / mag)) for ele in temp]) new_mat = np.dot(mat_copy, np.linalg.inv(r_matrix.T)) if all([np.round(x, 5).is_integer() for x in list(np.ravel(new_mat))]): reduced = True mat[h] = np.array([int(round(ele / mag)) for ele in temp]) break if reduced: break if not reduced: warnings.warn("Matrix reduction not performed, may lead to non-primitive gb cell.") return mat
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: min_index = np.argmin([i for i in vec if i != 0]) true_index = index[min_index] index.pop(min_index) frac = [] for i, value in enumerate(index): frac.append(Fraction(vec[value] / vec[true_index]).limit_denominator(100)) if len(index) == 1: miller[true_index] = frac[0].denominator miller[index[0]] = frac[0].numerator else: com_lcm = lcm(frac[0].denominator, frac[1].denominator) miller[true_index] = com_lcm miller[index[0]] = frac[0].numerator * int(round((com_lcm / frac[0].denominator))) miller[index[1]] = frac[1].numerator * int(round((com_lcm / frac[1].denominator))) return miller
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 the default color cycle.
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), linewidth=3) else: plt.fill_between(sp.x, base, sp.y + self.yshift * i, color=self.colors[i], label=str(key), linewidth=3) base = sp.y + base plt.xlabel(sp.XLABEL) plt.ylabel(sp.YLABEL) i += 1 if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt
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( Fraction(old_occ).limit_denominator(self.max_denominator)) if self.fix_denominator: new_occ = around(old_occ*self.max_denominator)\ / self.max_denominator if round(abs(old_occ - new_occ), 6) > self.tol: raise RuntimeError( "Cannot discretize structure within tolerance!") sp[k] = new_occ return Structure(structure.lattice, species, structure.frac_coords)
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.sqrt(c ** 2 - xz ** 2 - yz ** 2) + zlo tilt = None if lattice.is_orthogonal else [xy, xz, yz] rot_matrix = np.linalg.solve([[xhi - xlo, 0, 0], [xy, yhi - ylo, 0], [xz, yz, zhi - zlo]], m) bounds = [[xlo, xhi], [ylo, yhi], [zlo, zhi]] symmop = SymmOp.from_rotation_and_translation(rot_matrix, origin) return LammpsBox(bounds, tilt), symmop
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. Default to None. atom_style (str): Choose between "atomic" (neutral) and "charge" (charged). Default to "charge". Returns: LammpsData
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]) - xy * xz) / yhi zhi = np.sqrt(c ** 2 - xz ** 2 - yz ** 2) box_bounds = [[0.0, xhi], [0.0, yhi], [0.0, zhi]] box_tilt = [xy, xz, yz] box_tilt = None if not any(box_tilt) else box_tilt box = LammpsBox(box_bounds, box_tilt) new_latt = Lattice([[xhi, 0, 0], [xy, yhi, 0], [xz, yz, zhi]]) s.lattice = new_latt symbols = list(s.symbol_set) if ff_elements: symbols.extend(ff_elements) elements = sorted(Element(el) for el in set(symbols)) mass_info = [tuple([i.symbol] * 2) for i in elements] ff = ForceField(mass_info) topo = Topology(s) return LammpsData.from_ff_and_topologies(box=box, ff=ff, topologies=[topo], atom_style=atom_style)
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(*fillers)) if self.tilt: tilt_format = " ".join([ph] * 3 + [" xy xz yz"]) lines.append(tilt_format.format(*self.tilt)) return "\n".join(lines)
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 velocities. Default to 8. charge (int): No. of significant figures to output for charges. Default to 3.
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_pattern, l)] parts = np.split(lines, section_marks) float_group = r"([0-9eE.+-]+)" header_pattern = dict() header_pattern["counts"] = r"^\s*(\d+)\s+([a-zA-Z]+)$" header_pattern["types"] = r"^\s*(\d+)\s+([a-zA-Z]+)\s+types$" header_pattern["bounds"] = r"^\s*{}$".format(r"\s+".join( [float_group] * 2 + [r"([xyz])lo \3hi"])) header_pattern["tilt"] = r"^\s*{}$".format(r"\s+".join( [float_group] * 3 + ["xy xz yz"])) header = {"counts": {}, "types": {}} bounds = {} for l in clean_lines(parts[0][1:]): # skip the 1st line match = None for k, v in header_pattern.items(): match = re.match(v, l) if match: break else: continue if match and k in ["counts", "types"]: header[k][match.group(2)] = int(match.group(1)) elif match and k == "bounds": g = match.groups() bounds[g[2]] = [float(i) for i in g[:2]] elif match and k == "tilt": header["tilt"] = [float(i) for i in match.groups()] header["bounds"] = [bounds.get(i, [-0.5, 0.5]) for i in "xyz"] box = LammpsBox(header["bounds"], header.get("tilt")) def parse_section(sec_lines): title_info = sec_lines[0].split("#", 1) kw = title_info[0].strip() sio = StringIO("".join(sec_lines[2:])) # skip the 2nd line df = pd.read_csv(sio, header=None, comment="#", delim_whitespace=True) if kw.endswith("Coeffs") and not kw.startswith("PairIJ"): names = ["id"] + ["coeff%d" % i for i in range(1, df.shape[1])] elif kw == "PairIJ Coeffs": names = ["id1", "id2"] + ["coeff%d" % i for i in range(1, df.shape[1] - 1)] df.index.name = None elif kw in SECTION_HEADERS: names = ["id"] + SECTION_HEADERS[kw] elif kw == "Atoms": names = ["id"] + ATOMS_HEADERS[atom_style] if df.shape[1] == len(names): pass elif df.shape[1] == len(names) + 3: names += ["nx", "ny", "nz"] else: raise ValueError("Format in Atoms section inconsistent" " with atom_style %s" % atom_style) else: raise NotImplementedError("Parser for %s section" " not implemented" % kw) df.columns = names if sort_id: sort_by = "id" if kw != "PairIJ Coeffs" else ["id1", "id2"] df.sort_values(sort_by, inplace=True) if "id" in df.columns: df.set_index("id", drop=True, inplace=True) df.index.name = None return kw, df err_msg = "Bad LAMMPS data format where " body = {} seen_atoms = False for part in parts[1:]: name, section = parse_section(part) if name == "Atoms": seen_atoms = True if name in ["Velocities"] + SECTION_KEYWORDS["topology"] and \ not seen_atoms: # Atoms must appear earlier than these raise RuntimeError(err_msg + "%s section appears before" " Atoms section" % name) body.update({name: section}) err_msg += "Nos. of {} do not match between header and {} section" assert len(body["Masses"]) == header["types"]["atom"], \ err_msg.format("atom types", "Masses") atom_sections = ["Atoms", "Velocities"] \ if "Velocities" in body else ["Atoms"] for s in atom_sections: assert len(body[s]) == header["counts"]["atoms"], \ err_msg.format("atoms", s) for s in SECTION_KEYWORDS["topology"]: if header["counts"].get(s.lower(), 0) > 0: assert len(body[s]) == header["counts"][s.lower()], \ err_msg.format(s.lower(), s) items = {k.lower(): body[k] for k in ["Masses", "Atoms"]} items["velocities"] = body.get("Velocities") ff_kws = [k for k in body if k in SECTION_KEYWORDS["ff"] + SECTION_KEYWORDS["class2"]] items["force_field"] = {k: body[k] for k in ff_kws} if ff_kws \ else None topo_kws = [k for k in body if k in SECTION_KEYWORDS["topology"]] items["topology"] = {k: body[k] for k in topo_kws} \ if topo_kws else None items["atom_style"] = atom_style items["box"] = box return cls(**items)
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 necessarily in the structure. Default to None. atom_style (str): Choose between "atomic" (neutral) and "charge" (charged). Default to "charge".
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: velos = np.array(s.site_properties["velocities"]) rot = SymmOp.from_rotation_and_translation(symmop.rotation_matrix) rot_velos = rot.operate_multi(velos) site_properties.update({"velocities": rot_velos}) boxed_s = Structure(box.to_lattice(), s.species, coords, site_properties=site_properties, coords_are_cartesian=True) symbols = list(s.symbol_set) if ff_elements: symbols.extend(ff_elements) elements = sorted(Element(el) for el in set(symbols)) mass_info = [tuple([i.symbol] * 2) for i in elements] ff = ForceField(mass_info) topo = Topology(boxed_s) return cls.from_ff_and_topologies(box=box, ff=ff, topologies=[topo], atom_style=atom_style)
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.splitext(self.filepath) djrepo = root + ".djrepo" if os.path.exists(djrepo): shutil.copy(djrepo, os.path.join(tmpdir, os.path.basename(djrepo))) # Build new object and copy dojo_report if present. new = self.__class__.from_file(new_path) if self.has_dojo_report: new.dojo_report = self.dojo_report.deepcopy() return new
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"][accuracy]) elif "ppgen_hints" in self.dojo_report: return Hint.from_dict(self.dojo_report["ppgen_hints"][accuracy]) return Hint(ecut=0., pawecutdg=0.)
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: Cutoff energy for the PAW double grid.
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 * np.eye(3) structure = Structure(lattice, [self.element], coords=[[0, 0, 0]]) if self.ispaw and pawecutdg is None: pawecutdg = ecut * 4 inp = gs_input(structure, pseudos=[self], ecut=ecut, pawecutdg=pawecutdg, spin_mode="unpolarized", kppa=1) # Add prtpsps = -1 to make Abinit print the PSPS.nc file and stop. inp["prtpsps"] = -1 # Build temporary task and run it (ignore retcode because we don't exit cleanly) task = AbinitTask.temp_shell_task(inp) task.start_and_wait() filepath = task.outdir.has_abiext("_PSPS.nc") if not filepath: logger.critical("Cannot find PSPS.nc file in %s" % task.outdir) return None # Open the PSPS.nc file. try: return PspsFile(filepath) except Exception as exc: logger.critical("Exception while reading PSPS file at %s:\n%s" % (filepath, str(exc))) return None
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 os.listdir(dirname): root, ext = os.path.splitext(fname) path = os.path.join(dirname, fname) if (ext in exclude_exts or fname in exclude_fnames or fname.startswith(".") or not os.path.isfile(path)): continue paths.append(path) pseudos = [] for path in paths: # Parse the file and generate the pseudo. try: pseudo = self.parse(path) except: pseudo = None if pseudo is not None: pseudos.append(pseudo) self._parsed_paths.extend(path) else: self._wrong_paths.extend(path) return pseudos
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) label = "$n_c$" if i == 1 else r"$\tilde{n}_c$" ax.plot(rden.mesh, rden.mesh * rden.values, label=label, lw=2) ax.legend(loc="best") return fig
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="--") #ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1)) for state, rfunc in self.pseudo_partial_waves.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="PS-WAVE: " + state) for state, rfunc in self.ae_partial_waves.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="AE-WAVE: " + state) ax.legend(loc="best", shadow=True, fontsize=fontsize) return fig
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, linewidth=2, color='k', linestyle="--") #ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1)) for state, rfunc in self.projector_functions.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, label="TPROJ: " + state) ax.legend(loc="best", shadow=True, fontsize=fontsize) return fig
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: :class:`PseudoTable` sorted by atomic number Z.
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) if p: pseudos.append(p) else: logger.info('Skipping file %s' % f) except: logger.info('Skipping file %s' % f) if not pseudos: logger.warning('No pseudopotentials parsed from folder %s' % top) return None logger.info('Creating PseudoTable with %i pseudopotentials' % len(pseudos)) else: if exts is None: exts=("psp8",) for p in find_exts(top, exts, exclude_dirs=exclude_dirs): try: pseudos.append(Pseudo.from_file(p)) except Exception as exc: logger.critical("Error in %s:\n%s" % (p, exc)) return cls(pseudos).sort_by_z()
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: ValueError if symbol is not found or multiple occurences are present and not allow_multi
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: return pseudos[0] else: return pseudos
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 `-`") symbols = [s[1:] for s in symbols] symbols = set(symbols) pseudos = [] for p in self: if exclude: if p.symbol in symbols: continue else: if p.symbol not in symbols: continue pseudos.append(p) if ret_list: return pseudos else: return self.__class__(pseudos)
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 > 2 will print a periodic table containing only pseudos with Z_val > 2.
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, or the initial (pre-relaxation) structure. Defaults to True. Returns: List of Structure objects.
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: raise MPRestError("Provide filename or Structure object.") payload = {'structure': json.dumps(s.as_dict(), cls=MontyEncoder)} response = self.session.post( '{}/find_structure'.format(self.preamble), data=payload ) if response.status_code in [200, 400]: resp = json.loads(response.text, cls=MontyDecoder) if resp['valid_response']: return resp['response'] else: raise MPRestError(resp["error"]) raise MPRestError("REST error with status code {} and error {}" .format(response.status_code, response.text)) except Exception as ex: raise MPRestError(str(ex))
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 \ MaterialsProjectAqueousCompatibility pbx_entries = [] # Get ion entries first, because certain ions have reference # solids that aren't necessarily in the chemsys (Na2SO4) url = '/pourbaix_diagram/reference_data/' + '-'.join(chemsys) ion_data = self._make_request(url) ion_ref_comps = [Composition(d['Reference Solid']) for d in ion_data] ion_ref_elts = list(itertools.chain.from_iterable( i.elements for i in ion_ref_comps)) ion_ref_entries = self.get_entries_in_chemsys( list(set([str(e) for e in ion_ref_elts] + ['O', 'H'])), property_data=['e_above_hull'], compatible_only=False) compat = MaterialsProjectAqueousCompatibility("Advanced") ion_ref_entries = compat.process_entries(ion_ref_entries) ion_ref_pd = PhaseDiagram(ion_ref_entries) # position the ion energies relative to most stable reference state for n, i_d in enumerate(ion_data): ion_entry = IonEntry(Ion.from_formula(i_d['Name']), i_d['Energy']) refs = [e for e in ion_ref_entries if e.composition.reduced_formula == i_d['Reference Solid']] if not refs: raise ValueError("Reference solid not contained in entry list") stable_ref = sorted(refs, key=lambda x: x.data['e_above_hull'])[0] rf = stable_ref.composition.get_reduced_composition_and_factor()[1] solid_diff = ion_ref_pd.get_form_energy(stable_ref) \ - i_d['Reference solid energy'] * rf elt = i_d['Major_Elements'][0] correction_factor = ion_entry.ion.composition[elt] \ / stable_ref.composition[elt] ion_entry.energy += solid_diff * correction_factor pbx_entries.append(PourbaixEntry(ion_entry, 'ion-{}'.format(n))) # Construct the solid pourbaix entries from filtered ion_ref entries extra_elts = set(ion_ref_elts) - {Element(s) for s in chemsys} \ - {Element('H'), Element('O')} for entry in ion_ref_entries: entry_elts = set(entry.composition.elements) # Ensure no OH chemsys or extraneous elements from ion references if not (entry_elts <= {Element('H'), Element('O')} or \ extra_elts.intersection(entry_elts)): # replace energy with formation energy, use dict to # avoid messing with the ion_ref_pd and to keep all old params form_e = ion_ref_pd.get_form_energy(entry) new_entry = deepcopy(entry) new_entry.uncorrected_energy = form_e new_entry.correction = 0.0 pbx_entry = PourbaixEntry(new_entry) pbx_entries.append(pbx_entry) return pbx_entries
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. conventional_unit_cell (bool): Whether to get the standard conventional unit cell Returns: Structure object.
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] = SpacegroupAnalyzer(data[0][prop]). \ get_conventional_standard_structure() return 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 single StructureNL, or a list of StructureNL objects Returns: A list of inserted submission ids. Raises: MPRestError
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), data=payload) if response.status_code in [200, 400]: resp = json.loads(response.text, cls=MontyDecoder) if resp["valid_response"]: if resp.get("warning"): warnings.warn(resp["warning"]) return resp['inserted_ids'] else: raise MPRestError(resp["error"]) raise MPRestError("REST error with status code {} and error {}" .format(response.status_code, response.text)) except Exception as ex: raise MPRestError(str(ex))
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: MPRestError
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=MontyDecoder) if resp["valid_response"]: if resp.get("warning"): warnings.warn(resp["warning"]) return resp else: raise MPRestError(resp["error"]) raise MPRestError("REST error with status code {} and error {}" .format(response.status_code, response.text)) except Exception as ex: raise MPRestError(str(ex))
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, with a list of submitted SNLs in the "response" key. Raises: MPRestError
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 = json.loads(response.text) if resp["valid_response"]: if resp.get("warning"): warnings.warn(resp["warning"]) return resp["response"] else: raise MPRestError(resp["error"]) raise MPRestError("REST error with status code {} and error {}" .format(response.status_code, response.text)) except Exception as ex: raise MPRestError(str(ex))
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'. per_atom (bool): Whether or not to return cohesive energy per atom Returns: Cohesive energy (eV).
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_atom_e_sum, n = 0, 0 for el in comp_dict.keys(): e = self._make_request("/element/%s/tasks/isolated_atom" % (el), mp_decode=False)[0] isolated_atom_e_sum += e['output']["final_energy"] * comp_dict[el] n += comp_dict[el] ecoh_per_formula = isolated_atom_e_sum - ebulk return ecoh_per_formula/n if per_atom else ecoh_per_formula
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"] lattice = (SpacegroupAnalyzer(structure) .get_conventional_standard_structure().lattice) miller_energy_map = {} for surf in surfaces: miller = tuple(surf["miller_index"]) # Prefer reconstructed surfaces, which have lower surface energies. if (miller not in miller_energy_map) or surf["is_reconstructed"]: miller_energy_map[miller] = surf["surface_energy"] millers, energies = zip(*miller_energy_map.items()) return WulffShape(lattice, millers, energies)
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. Args: chemsys: Chemical system specified as list of elements. E.g., ["Li", "O"] Returns: EntrySet
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 in self.entries: elements = [sp.symbol for sp in e.composition.keys()] if chemsys.issuperset(elements): subset.add(e) return EntrySet(subset)
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(","), quotechar=unicode2str("\""), quoting=csv.QUOTE_MINIMAL) writer.writerow(["Name"] + elements + ["Energy"]) for entry in self.entries: row = [entry.name if not latexify_names else re.sub(r"([0-9]+)", r"_{\1}", entry.name)] row.extend([entry.composition[el] for el in elements]) row.append(entry.energy) writer.writerow(row)
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() header_read = False elements = None for row in reader: if not header_read: elements = row[1:(len(row) - 1)] header_read = True else: name = row[0] energy = float(row[-1]) comp = dict() for ind in range(1, len(row) - 1): if float(row[ind]) > 0: comp[Element(elements[ind - 1])] = float(row[ind]) entries.append(PDEntry(Composition(comp), energy, name)) return cls(entries)
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. Returns: VolumetricData corresponding to self + scale_factor * other.
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 checks data = {} for k in self.data.keys(): data[k] = self.data[k] + scale_factor * other.data[k] return VolumetricData(self.structure, data, self._distance_matrix)
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 dimline = None read_dataset = False ngrid_pts = 0 data_count = 0 poscar = None with zopen(filename, "rt") as f: for line in f: original_line = line line = line.strip() if read_dataset: toks = line.split() for tok in toks: if data_count < ngrid_pts: # This complicated procedure is necessary because # vasp outputs x as the fastest index, followed by y # then z. x = data_count % dim[0] y = int(math.floor(data_count / dim[0])) % dim[1] z = int(math.floor(data_count / dim[0] / dim[1])) dataset[x, y, z] = float(tok) data_count += 1 if data_count >= ngrid_pts: read_dataset = False data_count = 0 all_dataset.append(dataset) elif not poscar_read: if line != "" or len(poscar_string) == 0: poscar_string.append(line) elif line == "": poscar = Poscar.from_string("\n".join(poscar_string)) poscar_read = True elif not dim: dim = [int(i) for i in line.split()] ngrid_pts = dim[0] * dim[1] * dim[2] dimline = line read_dataset = True dataset = np.zeros(dim) elif line == dimline: # when line == dimline, expect volumetric data to follow # so set read_dataset to True read_dataset = True dataset = np.zeros(dim) else: # store any extra lines that were not part of the # volumetric data so we know which set of data the extra # lines are associated with key = len(all_dataset) - 1 if key not in all_dataset_aug: all_dataset_aug[key] = [] all_dataset_aug[key].append(original_line) if len(all_dataset) == 4: data = {"total": all_dataset[0], "diff_x": all_dataset[1], "diff_y": all_dataset[2], "diff_z": all_dataset[3]} data_aug = {"total": all_dataset_aug.get(0, None), "diff_x": all_dataset_aug.get(1, None), "diff_y": all_dataset_aug.get(2, None), "diff_z": all_dataset_aug.get(3, None)} # construct a "diff" dict for scalar-like magnetization density, # referenced to an arbitrary direction (using same method as # pymatgen.electronic_structure.core.Magmom, see # Magmom documentation for justification for this) # TODO: re-examine this, and also similar behavior in # Magmom - @mkhorton # TODO: does CHGCAR change with different SAXIS? diff_xyz = np.array([data["diff_x"], data["diff_y"], data["diff_z"]]) diff_xyz = diff_xyz.reshape((3, dim[0] * dim[1] * dim[2])) ref_direction = np.array([1.01, 1.02, 1.03]) ref_sign = np.sign(np.dot(ref_direction, diff_xyz)) diff = np.multiply(np.linalg.norm(diff_xyz, axis=0), ref_sign) data["diff"] = diff.reshape((dim[0], dim[1], dim[2])) elif len(all_dataset) == 2: data = {"total": all_dataset[0], "diff": all_dataset[1]} data_aug = {"total": all_dataset_aug.get(0, None), "diff": all_dataset_aug.get(1, None)} else: data = {"total": all_dataset[0]} data_aug = {"total": all_dataset_aug.get(0, None)} return poscar, data, data_aug
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:13] + 'E' + "{:+03}".format(int(s[14:]) + 1) with zopen(file_name, "wt") as f: p = Poscar(self.structure) # use original name if it's been set (e.g. from Chgcar) comment = getattr(self, 'name', p.comment) lines = comment + "\n" lines += " 1.00000000000000\n" latt = self.structure.lattice.matrix lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :]) lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :]) lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :]) if not vasp4_compatible: lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n" lines += "".join(["%6d" % x for x in p.natoms]) + "\n" lines += "Direct\n" for site in self.structure: lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords) lines += " \n" f.write(lines) a = self.dim def write_spin(data_type): lines = [] count = 0 f.write(" {} {} {}\n".format(a[0], a[1], a[2])) for (k, j, i) in itertools.product(list(range(a[2])), list(range(a[1])), list(range(a[0]))): lines.append(_print_fortran_float(self.data[data_type][i, j, k])) count += 1 if count % 5 == 0: f.write(" " + "".join(lines) + "\n") lines = [] else: lines.append(" ") f.write(" " + "".join(lines) + " \n") f.write("".join(self.data_aug.get(data_type, []))) write_spin("total") if self.is_spin_polarized and self.is_soc: write_spin("diff_x") write_spin("diff_y") write_spin("diff_z") elif self.is_spin_polarized: write_spin("diff")
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 total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]
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): name = structure.species[iat].symbol for spin, d in self.data.items(): for k, b in itertools.product(range(self.nkpoints), range(self.nbands)): dico[spin][b][k][name] = np.sum(d[k, b, iat, :]) return dico
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') if (ionicstep_end is not None and ionicstep_start < 1): raise Exception('End ionic step cannot be less than 1') ionicstep_cnt = 1 with zopen(filename, "rt") as f: for l in f: l = l.strip() if preamble is None: preamble = [l] elif not preamble_done: if l == "" or "Direct configuration=" in l: preamble_done = True tmp_preamble = [preamble[0]] for i in range(1, len(preamble)): if preamble[0] != preamble[i]: tmp_preamble.append(preamble[i]) else: break preamble = tmp_preamble else: preamble.append(l) elif l == "" or "Direct configuration=" in l: p = Poscar.from_string("\n".join(preamble + ["Direct"] + coords_str)) if ionicstep_end is None: if (ionicstep_cnt >= ionicstep_start): structures.append(p.structure) else: if ionicstep_start <= ionicstep_cnt < ionicstep_end: structures.append(p.structure) ionicstep_cnt += 1 coords_str = [] else: coords_str.append(l) p = Poscar.from_string("\n".join(preamble + ["Direct"] + coords_str)) if ionicstep_end is None: if ionicstep_cnt >= ionicstep_start: structures.append(p.structure) else: if ionicstep_start <= ionicstep_cnt < ionicstep_end: structures.append(p.structure) self.structures = structures self.comment = comment or self.structures[0].formula
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 ionicstep_start < 1): raise Exception('End ionic step cannot be less than 1') latt = self.structures[0].lattice if np.linalg.det(latt.matrix) < 0: latt = Lattice(-latt.matrix) lines = [self.comment, "1.0", str(latt)] lines.append(" ".join(self.site_symbols)) lines.append(" ".join([str(x) for x in self.natoms])) format_str = "{{:.{0}f}}".format(significant_figures) ionicstep_cnt = 1 output_cnt = 1 for cnt, structure in enumerate(self.structures): ionicstep_cnt = cnt + 1 if ionicstep_end is None: if (ionicstep_cnt >= ionicstep_start): lines.append("Direct configuration=" + ' ' * (7 - len(str(output_cnt))) + str(output_cnt)) for (i, site) in enumerate(structure): coords = site.frac_coords line = " ".join([format_str.format(c) for c in coords]) lines.append(line) output_cnt += 1 else: if ionicstep_start <= ionicstep_cnt < ionicstep_end: lines.append("Direct configuration=" + ' ' * (7 - len(str(output_cnt))) + str(output_cnt)) for (i, site) in enumerate(structure): coords = site.frac_coords line = " ".join([format_str.format(c) for c in coords]) lines.append(line) output_cnt += 1 return "\n".join(lines) + "\n"
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 the first letter matters
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 recl, spin, rtag = np.fromfile(f, dtype=np.float64, count=3) \ .astype(np.int) if verbose: print('recl={}, spin={}, rtag={}'.format(recl, spin, rtag)) recl8 = int(recl / 8) self.spin = spin # check that ISPIN wasn't set to 2 # if spin == 2: # raise ValueError('spin polarization not currently supported') # check to make sure we have precision correct if rtag != 45200 and rtag != 45210: raise ValueError('invalid rtag of {}'.format(rtag)) # padding np.fromfile(f, dtype=np.float64, count=(recl8 - 3)) # extract kpoint, bands, energy, and lattice information self.nk, self.nb, self.encut = np.fromfile(f, dtype=np.float64, count=3).astype(np.int) self.a = np.fromfile(f, dtype=np.float64, count=9).reshape((3, 3)) self.efermi = np.fromfile(f, dtype=np.float64, count=1)[0] if verbose: print('kpoints = {}, bands = {}, energy cutoff = {}, fermi ' 'energy= {:.04f}\n'.format(self.nk, self.nb, self.encut, self.efermi)) print('primitive lattice vectors = \n{}'.format(self.a)) self.vol = np.dot(self.a[0, :], np.cross(self.a[1, :], self.a[2, :])) if verbose: print('volume = {}\n'.format(self.vol)) # calculate reciprocal lattice b = np.array([np.cross(self.a[1, :], self.a[2, :]), np.cross(self.a[2, :], self.a[0, :]), np.cross(self.a[0, :], self.a[1, :])]) b = 2 * np.pi * b / self.vol self.b = b if verbose: print('reciprocal lattice vectors = \n{}'.format(b)) print('reciprocal lattice vector magnitudes = \n{}\n' .format(np.linalg.norm(b, axis=1))) # calculate maximum number of b vectors in each direction self._generate_nbmax() if verbose: print('max number of G values = {}\n\n'.format(self._nbmax)) self.ng = self._nbmax * 3 if precision.lower()[0] == 'n' else \ self._nbmax * 4 # padding np.fromfile(f, dtype=np.float64, count=recl8 - 13) # reading records # np.set_printoptions(precision=7, suppress=True) self.Gpoints = [None for _ in range(self.nk)] self.kpoints = [] if spin == 2: self.coeffs = [[[None for i in range(self.nb)] for j in range(self.nk)] for _ in range(spin)] self.band_energy = [[] for _ in range(spin)] else: self.coeffs = [[None for i in range(self.nb)] for j in range(self.nk)] self.band_energy = [] for ispin in range(spin): if verbose: print('reading spin {}'.format(ispin)) for ink in range(self.nk): # information for this kpoint nplane = int(np.fromfile(f, dtype=np.float64, count=1)[0]) kpoint = np.fromfile(f, dtype=np.float64, count=3) if ispin == 0: self.kpoints.append(kpoint) else: assert np.allclose(self.kpoints[ink], kpoint) if verbose: print('kpoint {: 4} with {: 5} plane waves at {}' .format(ink, nplane, kpoint)) # energy and occupation information enocc = np.fromfile(f, dtype=np.float64, count=3 * self.nb).reshape((self.nb, 3)) if spin == 2: self.band_energy[ispin].append(enocc) else: self.band_energy.append(enocc) if verbose: print(enocc[:, [0, 2]]) # padding np.fromfile(f, dtype=np.float64, count=(recl8 - 4 - 3 * self.nb)) # generate G integers self.Gpoints[ink] = self._generate_G_points(kpoint) if len(self.Gpoints[ink]) != nplane: raise ValueError('failed to generate the correct ' 'number of G points') # extract coefficients for inb in range(self.nb): if rtag == 45200: data = np.fromfile(f, dtype=np.complex64, count=nplane) np.fromfile(f, dtype=np.float64, count=recl8 - nplane) elif rtag == 45210: # this should handle double precision coefficients # but I don't have a WAVECAR to test it with data = np.fromfile(f, dtype=np.complex128, count=nplane) np.fromfile(f, dtype=np.float64, count=recl8 - 2 * nplane) if spin == 2: self.coeffs[ispin][ink][inb] = data else: self.coeffs[ink][inb] = data
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: kpoint (np.array): the array containing the current k-point value Returns: a list containing valid G-points
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 for k in range(2 * self._nbmax[0] + 1): k1 = k - 2 * self._nbmax[0] - 1 if k > self._nbmax[0] else k G = np.array([k1, j2, i3]) v = kpoint + G g = np.linalg.norm(np.dot(v, self.b)) E = g ** 2 / self._C if E < self.encut: gpoints.append(G) return np.array(gpoints, dtype=np.float64)
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 j Returns: a numpy list of elements for each kpoint
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-channel (0 or 1) cart_dir (Integer): Index of cartesian direction (0,1,2) Returns: a float value
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 index out of bounds") if cart_dir > 2 or cart_dir < 0: raise ValueError("cart_dir index out of bounds") return self.cder_data[band_i, band_j, kpoint, spin, cart_dir]
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_matrix (4x4 array): Representing an affine transformation. tol (float): Tolerance for determining if matrices are equal.
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_transformation_matrix self.tol = tol
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: SymmOp object
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): raise ValueError("Rotation Matrix must be a 3x3 numpy array.") if translation_vec.shape != (3,): raise ValueError("Translation vector must be a rank 1 numpy array " "with 3 elements.") affine_matrix = np.eye(4) affine_matrix[0:3][:, 0:3] = rotation_matrix affine_matrix[0:3][:, 3] = translation_vec return SymmOp(affine_matrix, tol)
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(*indices)]) einsum_string += ',{}->{}'.format(*indices[::-1]) einsum_args = [self.rotation_matrix] * rank + [tensor] return np.einsum(einsum_string, *einsum_args)
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 ** 2 zz = 1 - 2 * w ** 2 xy = -2 * u * v xz = -2 * u * w yz = -2 * v * w mirror_mat = [[xx, xy, xz, 0], [xy, yy, yz, 0], [xz, yz, zz, 0], [0, 0, 0, 1]] if np.linalg.norm(origin) > 1e-6: mirror_mat = np.dot(np.linalg.inv(translation), np.dot(mirror_mat, translation)) return SymmOp(mirror_mat)
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-reflection operation
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: Magnetic moment as electronic_structure.core.Magmom class or as list or np array-like Returns: Magnetic moment after operator applied as Magmom class
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 default return Magmom.from_global_moment_and_saxis(transformed_moment, magmom.saxis)
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. tol (float): Tolerance to determine if rotation matrix is valid. Returns: MagSymmOp object
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, translation_vec=translation_vec, tol=tol) return MagSymmOp.from_symmop(symmop, time_reversal)
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 memory_options = None lines = string_input.strip().split("\n") while len(lines) > 0: l = lines.pop(0).strip() if l == "": continue toks = l.split() if toks[0].lower() == "geometry": geom_options = toks[1:] l = lines.pop(0).strip() toks = l.split() if toks[0].lower() == "symmetry": symmetry_options = toks[1:] l = lines.pop(0).strip() # Parse geometry species = [] coords = [] while l.lower() != "end": toks = l.split() species.append(toks[0]) coords.append([float(i) for i in toks[1:]]) l = lines.pop(0).strip() mol = Molecule(species, coords) elif toks[0].lower() == "charge": charge = int(toks[1]) elif toks[0].lower() == "title": title = l[5:].strip().strip("\"") elif toks[0].lower() == "basis": # Parse basis sets l = lines.pop(0).strip() basis_set = {} while l.lower() != "end": toks = l.split() basis_set[toks[0]] = toks[-1].strip("\"") l = lines.pop(0).strip() elif toks[0].lower() in NwTask.theories: # read the basis_set_option if len(toks) > 1: basis_set_option = toks[1] # Parse theory directives. theory = toks[0].lower() l = lines.pop(0).strip() theory_directives[theory] = {} while l.lower() != "end": toks = l.split() theory_directives[theory][toks[0]] = toks[-1] if toks[0] == "mult": spin_multiplicity = float(toks[1]) l = lines.pop(0).strip() elif toks[0].lower() == "task": tasks.append( NwTask(charge=charge, spin_multiplicity=spin_multiplicity, title=title, theory=toks[1], operation=toks[2], basis_set=basis_set, basis_set_option=basis_set_option, theory_directives=theory_directives.get(toks[1]))) elif toks[0].lower() == "memory": memory_options = ' '.join(toks[1:]) else: directives.append(l.strip().split()) return NwInput(mol, tasks=tasks, directives=directives, geometry_options=geom_options, symmetry_options=symmetry_options, memory_options=memory_options)
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 plotted using pymatgen.vis.plotters.SpectrumPlotter.
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[-1] + epad de = (emax - emin) / npoints # Use width of at least two grid points if width < 2 * de: width = 2 * de energies = [emin + ie * de for ie in range(npoints)] cutoff = 20.0 * width gamma = 0.5 * width gamma_sqrd = gamma * gamma de = (energies[-1] - energies[0]) / (len(energies) - 1) prefac = gamma / np.pi * de x = [] y = [] for energy in energies: xx0 = energy - en stot = osc / (xx0 * xx0 + gamma_sqrd) t = np.sum(stot[np.abs(xx0) <= cutoff]) x.append(energy) y.append(t * prefac) return ExcitationSpectrum(x, y)
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: if hexagonal: syms = list(filter(lambda s: s.endswith("H"), syms)) else: syms = list(filter(lambda s: not s.endswith("H"), syms)) return syms.pop()
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 array for comparison. tol (float): The tolerance. Defaults to 1e-5. If 0, an exact match is done. Returns: (bool)
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] * len(symbols) return Structure(lattice, symbols, frac_coords, site_properties={"phonopy_masses": masses, "magnetic_moments": mms})
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:]): pdoss[site] = pdos.tolist() return CompletePhononDos(structure, total_dos, pdoss)
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 for hkl2 in unique.keys(): if is_perm(hkl1, hkl2): found = True unique[hkl2].append(hkl1) break if not found: unique[hkl1].append(hkl1) pretty_unique = {} for k, v in unique.items(): pretty_unique[sorted(v)[-1]] = len(v) return pretty_unique
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 (float): Value to normalize to. Defaults to 1.
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 /= factor / value
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([ gaussian_filter1d(self.y[:, k], sigma / avg_x_per_step) for k in range(self.ydim[1])]).T
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' 'old scipy implementation') self.spline = PiecewisePolynomial( self.r, np.array([relative_energies, -self.forces]).T, orders=3) else: # New scipy implementation for scipy > 0.18.0 if self.spline_options.get('saddle_point', '') == 'zero_slope': imax = np.argmax(relative_energies) self.spline = CubicSpline(x=self.r[:imax + 1], y=relative_energies[:imax + 1], bc_type=((1, 0.0), (1, 0.0))) cspline2 = CubicSpline(x=self.r[imax:], y=relative_energies[imax:], bc_type=((1, 0.0), (1, 0.0))) self.spline.extend(c=cspline2.c, x=cspline2.x[1:]) else: self.spline = CubicSpline(x=self.r, y=relative_energies, bc_type=((1, 0.0), (1, 0.0)))
140,040