text
stringlengths
81
112k
A complete dos object which incorporates the total dos and all projected dos. def complete_dos(self): """ A complete dos object which incorporates the total dos and all projected dos. """ final_struct = self.final_structure pdoss = {final_struct[i]: pdos for i, p...
Hubbard U values used if a vasprun is a GGA+U run. {} otherwise. def hubbards(self): """ Hubbard U values used if a vasprun is a GGA+U run. {} otherwise. """ symbols = [s.split()[1] for s in self.potcar_symbols] symbols = [re.split(r"_", s)[0] for s in symbols] if not se...
Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs. TODO: Fix for other functional types like PW91, other vdW types, etc. def run_type(self): """ Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs. TODO: Fix for other functional types like PW91,...
True if run is a DFT+U run. def is_hubbard(self): """ True if run is a DFT+U run. """ if len(self.hubbards) == 0: return False return sum(self.hubbards.values()) > 1e-8
Returns a ComputedStructureEntry from the vasprun. Args: inc_structure (bool): Set to True if you want ComputedStructureEntries to be returned instead of ComputedEntries. parameters (list): Input parameters to include. It has to be one of ...
Returns the band structure as a BandStructure object Args: kpoints_filename (str): Full path of the KPOINTS file from which the band structure is generated. If none is provided, the code will try to intelligently determine the appropriate KPOINTS file...
Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct). def eigenvalue_band_properties(self): """ Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct). """ vbm = -float("inf") vbm_kpoint = No...
Json-serializable dict representation. def as_dict(self): """ Json-serializable dict representation. """ d = {"vasp_version": self.vasp_version, "has_vasp_completed": self.converged, "nsites": len(self.final_structure)} comp = self.final_structure.compo...
Json-serializable dict representation. def as_dict(self): """ Json-serializable dict representation. """ d = {"vasp_version": self.vasp_version, "has_vasp_completed": True, "nsites": len(self.final_structure)} comp = self.final_structure.composition ...
General pattern reading. Uses monty's regrep method. Takes the same arguments. Args: patterns (dict): A dict of patterns, e.g., {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for ...
Parse table-like data. A table composes of three parts: header, main body, footer. All the data matches "row pattern" in the main body will be returned. Args: header_pattern (str): The regular expression pattern matches the table header. This pattern should match all...
Parses the eletrostatic potential for the last ionic step def read_electrostatic_potential(self): """ Parses the eletrostatic potential for the last ionic step """ pattern = {"ngf": r"\s+dimension x,y,z NGXF=\s+([\.\-\d]+)\sNGYF=\s+([\.\-\d]+)\sNGZF=\s+([\.\-\d]+)"} self.read_pa...
Parses the frequency dependent dielectric function (obtained with LOPTICS). Frequencies (in eV) are in self.frequencies, and dielectric tensor function is given as self.dielectric_tensor_function. def read_freq_dielectric(self): """ Parses the frequency dependent dielectric function (ob...
Parse the NMR chemical shieldings data. Only the second part "absolute, valence and core" will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved. Returns: List of chemical shieldings in the order of atoms from the OUTCAR. Maryland notation is adopt...
Parse the G0 contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. def read_cs_g0_contribution(self): """ Parse the G0 contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. ...
Parse the core contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. def read_cs_core_contribution(self): """ Parse the core contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. ...
Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in the order of atoms. def read_cs_raw_symmetrized_tensors(self): """ Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in ...
Parses the NMR Electric Field Gradient Raw Tensors Returns: A list of Electric Field Gradient Tensors in the order of Atoms from OUTCAR def read_nmr_efg_tensor(self): """ Parses the NMR Electric Field Gradient Raw Tensors Returns: A list of Electric Field Gradi...
Parse the NMR Electric Field Gradient interpretted values. Returns: Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR. Each dict key/value pair corresponds to a component of the tensors. def read_nmr_efg(self): """ Parse the NMR Electri...
Parse the elastic tensor data. Returns: 6x6 array corresponding to the elastic tensor from the OUTCAR. def read_elastic_tensor(self): """ Parse the elastic tensor data. Returns: 6x6 array corresponding to the elastic tensor from the OUTCAR. """ ...
Parse the piezo tensor data def read_piezo_tensor(self): """ Parse the piezo tensor data """ header_pattern = r"PIEZOELECTRIC TENSOR for field in x, y, " \ r"z\s+\(C/m\^2\)\s+([X-Z][X-Z]\s+)+\-+" row_pattern = r"[x-z]\s+" + r"\s+".join([r"(\-*[\.\d]+)"]...
Reads NEB data. This only works with OUTCARs from both normal VASP NEB calculations or from the CI NEB method implemented by Henkelman et al. Args: reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used wit...
Renders accessible: er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys) er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys) er_ev_tot = spin up + spin down summed er_bp_tot = spin up + spin down summed p_elc = spin up + spin down summed ...
Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation tensors for each site. def read_internal_strain_tensor(self): """ Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation ...
Create pseudopotential ZVAL dictionary. def read_pseudo_zval(self): """ Create pseudopotential ZVAL dictionary. """ try: def poscar_line(results, match): poscar_line = match.group(1) results.poscar_line = re.findall(r'[A-Z][a-z]?', poscar_line...
Read the core state eigenenergies at each ionic step. Returns: A list of dict over the atom such as [{"AO":[core state eig]}]. The core state eigenenergie list for each AO is over all ionic step. Example: The core state eigenenergie of the 2s AO of the 6...
Read the core potential at each ionic step. Returns: A list for each ionic step containing a list of the average core potentials for each atom: [[avg core pot]]. Example: The average core potential of the 2nd atom of the structure at the last ionic step ...
output example: Fermi contact (isotropic) hyperfine coupling parameter (MHz) ------------------------------------------------------------- ion A_pw A_1PS A_1AE A_1c A_tot ------------------------------------------------------------- 1 -0.002 -0.002...
The data decomposed into actual spin data as {spin: data}. Essentially, this provides the actual Spin.up and Spin.down data instead of the total and diff. Note that by definition, a non-spin-polarized run would have Spin.up data == Spin.down data. def spin_data(self): """ The d...
Returns the grid for a particular axis. Args: ind (int): Axis index. def get_axis_grid(self, ind): """ Returns the grid for a particular axis. Args: ind (int): Axis index. """ ng = self.dim num_pts = ng[ind] lengths = self.struct...
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...
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): """ Convenience method to parse a gene...
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): """ Write the VolumetricData object to a vasp compat...
Get integrated difference of atom index ind up to radius. This can be an extremely computationally intensive process, depending on how many grid points are in the VolumetricData. Args: ind (int): Index of atom. radius (float): Radius of integration. nbins (in...
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): "...
Writes the VolumetricData to a HDF5 format, which is a highly optimized format for reading storing large data. The mapping of the VolumetricData to this file format is as follows: VolumetricData.data -> f["vdata"] VolumetricData.structure -> f["Z"]: Sequence of atomic number...
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): """ Method returning a dictionar...
Returns the occupation for a particular orbital of a particular atom. Args: atom_num (int): Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is converted to 0-based indexing in this parser to be consi...
Compilation of all energies from all electronic steps and ionic steps as a tuple of list of energies, e.g., ((4507.24605593, 143.824705755, -512.073149912, ...), ...) def all_energies(self): """ Compilation of all energies from all electronic steps and ionic steps as a tuple of ...
Sequence of symbols associated with the Xdatcar. Similar to 6th line in vasp 5+ Xdatcar. def site_symbols(self): """ Sequence of symbols associated with the Xdatcar. Similar to 6th line in vasp 5+ Xdatcar. """ syms = [site.specie.symbol for site in self.structures[0]] ...
Sequence of number of sites of each type associated with the Poscar. Similar to 7th line in vasp 5+ Xdatcar. def natoms(self): """ Sequence of number of sites of each type associated with the Poscar. Similar to 7th line in vasp 5+ Xdatcar. """ syms = [site.specie.symbol ...
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, ...
calculate phonon frequencies def get_phonon_frequencies(self): """calculate phonon frequencies""" # TODO: the following is most likely not correct or suboptimal # hence for demonstration purposes only frequencies = [] for k, v0 in self.data.iteritems(): for v1 in v0....
Helper function that determines maximum number of b vectors for each direction. This algorithm is adapted from WaveTrans (see Class docstring). There should be no reason for this function to be called outside of initialization. def _generate_nbmax(self): """ Helper func...
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: ...
r""" Evaluates the wavefunction for a given position, r. The wavefunction is given by the k-point and band. It is evaluated at the given position by summing over the components. Formally, \psi_n^k (r) = \sum_{i=1}^N c_i^{n,k} \exp (i (k + G_i^{n,k}) \cdot r) where \psi_n^k is ...
Places the coefficients of a wavefunction onto an fft mesh. Once the mesh has been obtained, a discrete fourier transform can be used to obtain real-space evaluation of the wavefunction. The output of this function can be passed directly to numpy's fft function. For example: ...
Generates a Chgcar object, which is the charge density of the specified wavefunction. This function generates a Chgcar object with the charge density of the wavefunction specified by band and kpoint (and spin, if the WAVECAR corresponds to a spin-polarized calculation). The phase tag is...
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 ...
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...
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: ...
Apply the operation on a point. Args: point: Cartesian coordinate. Returns: Coordinates of point after operation. def operate(self, point): """ Apply the operation on a point. Args: point: Cartesian coordinate. Returns: ...
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): """ Apply the operation on a list of points. Args: points: List of Car...
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): """ Applies rotation portion to a tensor. Not...
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_sy...
Returns inverse of transformation. def inverse(self): """ Returns inverse of transformation. """ invr = np.linalg.inv(self.affine_matrix) return SymmOp(invr)
Generates a SymmOp for a rotation about a given axis plus translation. Args: axis: The axis of rotation in cartesian space. For example, [1, 0, 0]indicates rotation about x-axis. angle (float): Angle of rotation. angle_in_radians (bool): Set to True if angles...
Generates a SymmOp for a rotation about a given axis through an origin. Args: origin (3x1 array): The origin which the axis passes through. axis (3x1 array): The axis of rotation in cartesian space. For example, [1, 0, 0]indicates rotation about x-axis. ...
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...
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)): """ Inversion sym...
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...
Returns a string of the form 'x, y, z', '-x, -y, z', '-y+1/2, x+1/2, z+1/2', etc. Only works for integer rotation matrices def as_xyz_string(self): """ Returns a string of the form 'x, y, z', '-x, -y, z', '-y+1/2, x+1/2, z+1/2', etc. Only works for integer rotation matrices """ ...
Args: xyz_string: string of the form 'x, y, z', '-x, -y, z', '-2y+1/2, 3x+1/2, z-y+1/2', etc. Returns: SymmOp def from_xyz_string(xyz_string): """ Args: xyz_string: string of the form 'x, y, z', '-x, -y, z', '-2y+1/2, 3x+1/2, z...
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...
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): """ Initiali...
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. ...
Args: xyz_string: string of the form 'x, y, z, +1', '-x, -y, z, -1', '-2y+1/2, 3x+1/2, z-y+1/2, +1', etc. Returns: MagSymmOp object def from_xyzt_string(xyzt_string): """ Args: xyz_string: string of the form 'x, y, z, +1', '-x, -y, z, -1', ...
Returns a string of the form 'x, y, z, +1', '-x, -y, z, -1', '-y+1/2, x+1/2, z+1/2, +1', etc. Only works for integer rotation matrices def as_xyzt_string(self): """ Returns a string of the form 'x, y, z, +1', '-x, -y, z, -1', '-y+1/2, x+1/2, z+1/2, +1', etc. Only works for integer rotat...
Very flexible arguments to support many types of potential setups. Users should use more friendly static methods unless they need the flexibility. Args: mol: Input molecule charge: Charge of the molecule. If None, charge on molecule is used. Defaults to N...
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 df...
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): """ Read an NwInput from a string. Currently test...
Parses TDDFT roots. Adapted from nw_spectrum.py script. Returns: { "singlet": [ { "energy": float, "osc_strength: float } ], "triplet": [ { ...
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...
Returns a formula string, with elements sorted by electronegativity, e.g., Li4 Fe4 P4 O16. def formula(self): """ Returns a formula string, with elements sorted by electronegativity, e.g., Li4 Fe4 P4 O16. """ formula = super().formula chg_str = "" if self...
An anonymized formula. Appends charge to the end of anonymized composition def anonymized_formula(self): """ An anonymized formula. Appends charge to the end of anonymized composition """ anon_formula = super().anonymized_formula chg = self._charge chg_st...
Returns a reduced formula string with appended charge. def reduced_formula(self): """ Returns a reduced formula string with appended charge. """ reduced_formula = super().reduced_formula charge = self._charge / self.get_reduced_composition_and_factor()[1] if charge > 0: ...
Returns a reduced formula string with appended charge def alphabetical_formula(self): """ Returns a reduced formula string with appended charge """ alph_formula = super().alphabetical_formula chg_str = "" if self.charge > 0: chg_str = " +" + formula_double_fo...
Generates an ion object from a dict created by as_dict(). Args: d: {symbol: amount} dict. def from_dict(cls, d): """ Generates an ion object from a dict created by as_dict(). Args: d: {symbol: amount} dict. """ ch...
Returns: dict with element symbol and reduced amount e.g., {"Fe": 2.0, "O":3.0}. def to_reduced_dict(self): """ Returns: dict with element symbol and reduced amount e.g., {"Fe": 2.0, "O":3.0}. """ d = self.composition.to_reduced_dict ...
Returns the cost of the best assignment def min_cost(self): """ Returns the cost of the best assignment """ if self._min_cost: return self._min_cost self._min_cost = np.sum(self.c[np.arange(self.nx), self.solution]) return self._min_cost
Column reduction and reduction transfer steps from LAPJV algorithm def _column_reduction(self): """ Column reduction and reduction transfer steps from LAPJV algorithm """ #assign each column to its lowest cost row, ensuring that only row #or column is assigned once i1, j...
Augmenting row reduction step from LAPJV algorithm def _augmenting_row_reduction(self): """ Augmenting row reduction step from LAPJV algorithm """ unassigned = np.where(self._x == -1)[0] for i in unassigned: for _ in range(self.c.size): # Time in this...
Updates the reduced costs with the values from the dual solution def _update_cred(self): """ Updates the reduced costs with the values from the dual solution """ ui = self.c[self._inds, self._x] - self._v[self._x] self.cred = self.c - ui[:, None] - self._v[None, ...
Finds a minimum cost path and adds it to the matching def _augment(self): """ Finds a minimum cost path and adds it to the matching """ #build a minimum cost tree _pred, _ready, istar, j, mu = self._build_tree() #update prices self._v[_ready] += self._d[_ready] ...
Builds the tree finding an augmenting path. Alternates along matched and unmatched edges between X and Y. The paths are stored in _pred (new predecessor of nodes in Y), and self._x and self._y def _build_tree(self): """ Builds the tree finding an augmenting path. Alternates alon...
Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details def pmg_serialize(method): """ Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details """ @functools.wraps(method...
Serialize obj as a JSON formatted stream to the given filename ( pretty printing version) def json_pretty_dump(obj, filename): """ Serialize obj as a JSON formatted stream to the given filename ( pretty printing version) """ with open(filename, "wt") as fh: json.dump(obj, fh, indent=4, ...
Instead of pickling as a regular class instance, we emit a persistent ID. def persistent_id(self, obj): """Instead of pickling as a regular class instance, we emit a persistent ID.""" if isinstance(obj, Element): # Here, our persistent ID is simply a tuple, containing a tag ...
This method is invoked whenever a persistent ID is encountered. Here, pid is the tuple returned by PmgPickler. def persistent_load(self, pid): """ This method is invoked whenever a persistent ID is encountered. Here, pid is the tuple returned by PmgPickler. """ try: ...
Get value from dict using MongoDB dot-separated path semantics. For example: >>> assert mongo_getattr({'a': {'b': 1}, 'x': 2}, 'a.b') == 1 >>> assert mongo_getattr({'a': {'b': 1}, 'x': 2}, 'x') == 2 >>> assert mongo_getattr({'a': {'b': 1}, 'x': 2}, 'a.b.c') is None :param rec: mongodb document ...
Scan a nested dict d, and return the first value associated to the given key. Returns None if key is not found. >>> d = {0: 1, 1: {"hello": {"world": {None: [1,2,3]}}}, "foo": [{"bar": 1}, {"color": "red"}]} >>> assert scan_nestdict(d, 1) == {"hello": {"world": {None: [1,2,3]}}} >>> assert scan_nestdic...
Set the name of the collection, return old value def set_collection_name(self, value): """Set the name of the collection, return old value""" old = self.collection self.collection = str(value) return old
Establish a connection with the database. Returns MongoDb collection def get_collection(self, **kwargs): """ Establish a connection with the database. Returns MongoDb collection """ from pymongo import MongoClient if self.host and self.port: client...
Checks for a transformations.json* file and returns the history. def _get_transformation_history(path): """ Checks for a transformations.json* file and returns the history. """ trans_json = glob.glob(os.path.join(path, "transformations.json*")) if trans_json: try: with zopen(tra...
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_...
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...
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): """ True if this group is a subgroup of the supplie...
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): """ True if this group is a supergroup of the suppl...
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, re...
Small awk-mimicking search routine. 'file' is file to search through. 'search' is the "search program", a list of lists/tuples with 3 elements; i.e. [[regex,test,run],[regex,test,run],...] 'results' is a an object that your search program will have access to for storing results. Here regex is ...