INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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) def zvals(results, match):...
Read the core state eigenenergies at each ionic step.
def read_core_state_eigen(self): """ 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: ...
Read the core potential at each ionic step.
def read_avg_core_poten(self): """ 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 o...
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 - 0. 051 0. 000 - 0. 052 2 - 0. 002 - 0. 002 - 0. 051 0. 000 - ...
def read_fermi_contact_shift(self): ''' output example: Fermi contact (isotropic) hyperfine coupling parameter (MHz) ------------------------------------------------------------- ion A_pw A_1PS A_1AE A_1c A_tot --------------------------------------...
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 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. ...
Returns the grid for a particular axis.
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.structure.lattice.abc return [i / num_pts * lengths[ind] for i in range(num_pts)]
Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum.
def linear_add(self, other, scale_factor=1.0): """ 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 s...
Convenience method to parse a generic volumetric data file in the vasp like format. Used by subclasses for parsing file.
def parse_file(filename): """ 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) """ poscar_read = F...
Write the VolumetricData object to a vasp compatible file.
def write_file(self, file_name, vasp4_compatible=False): """ 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 _print_fortran_float(f):...
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.
def get_integrated_diff(self, ind, radius, nbins=1): """ 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....
Get the averaged total of the volumetric data a certain axis direction. For example useful for visualizing Hartree Potentials from a LOCPOT file.
def get_average_along_axis(self, ind): """ 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 a...
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:
def to_hdf5(self, filename): """ 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...
Method returning a dictionary of projections on elements.
def get_projection_on_elements(self, structure): """ 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}]] """ dico = {}...
Returns the occupation for a particular orbital of a particular atom.
def get_occupation(self, atom_index, orbital): """ 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 conve...
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 list of energies, e.g., ((4507.24605593, 143.824705755, -512.073149912, ...), ...) """ all_energies = [] for i in range(len(self.electronic_steps)): ...
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]] return [a[0] for a in itertools.groupby(syms)]
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 for site in self.structures[0]] return [len(tuple(a[1])) for a in itertools.groupby(syms)]
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): """ Write Xdatcar class into a file Args: filename (str): Filename of output XDATCAR file. ionicstep_start (int): Starting number of ionic step. ...
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.itervalues(): ...
Helper function that determines maximum number of b vectors for each direction.
def _generate_nbmax(self): """ 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. """ ...
Helper function to generate G - points based on nbmax.
def _generate_G_points(self, kpoint): """ 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...
r Evaluates the wavefunction for a given position r.
def evaluate_wavefunc(self, kpoint, band, r, spin=0): 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...
Places the coefficients of a wavefunction onto an fft mesh.
def fft_mesh(self, kpoint, band, spin=0, shift=True): """ 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...
Generates a Chgcar object which is the charge density of the specified wavefunction.
def get_parchg(self, poscar, kpoint, band, spin=None, phase=False, scale=2): """ 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...
Method returning a numpy array with elements
def get_elements_between_bands(self, band_i, band_j): """ 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...
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 ca...
def get_orbital_derivative_between_states(self, band_i, band_j, kpoint, spin, cart_dir): """ 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):...
Creates a symmetry operation from a rotation matrix and a translation vector.
def from_rotation_and_translation( rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec=(0, 0, 0), tol=0.1): """ Creates a symmetry operation from a rotation matrix and a translation vector. Args: rotation_matrix (3x3 array): Rotation ma...
Apply the operation on a point.
def operate(self, point): """ Apply the operation on a point. Args: point: Cartesian coordinate. Returns: Coordinates of point after operation. """ affine_point = np.array([point[0], point[1], point[2], 1]) return np.dot(self.affine_matri...
Apply the operation on a list of points.
def operate_multi(self, points): """ Apply the operation on a list of points. Args: points: List of Cartesian coordinates Returns: Numpy array of coordinates after operation """ points = np.array(points) affine_points = np.concatenate( ...
Applies rotation portion to a tensor. Note that tensor has to be in full form not the Voigt form.
def transform_tensor(self, tensor): """ 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. """ dim = tensor.shape ...
Checks if two points are symmetrically related.
def are_symmetrically_related(self, point_a, point_b, tol=0.001): """ 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. Re...
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.
def from_axis_angle_and_translation(axis, angle, angle_in_radians=False, translation_vec=(0, 0, 0)): """ Generates a SymmOp for a rotation about a given axis plus translation. Args: axis: The axis of rotation in cartesian space. For example, ...
Generates a SymmOp for a rotation about a given axis through an origin.
def from_origin_axis_angle(origin, axis, angle, angle_in_radians=False): """ 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 cart...
Returns reflection symmetry operation.
def reflection(normal, origin=(0, 0, 0)): """ 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. ...
Inversion symmetry operation about axis.
def inversion(origin=(0, 0, 0)): """ 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. """ ...
Returns a roto - reflection symmetry operation
def rotoreflection(axis, angle, origin=(0, 0, 0)): """ 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. ...
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 """ xyz = ['x', 'y', 'z'] strings = [] # test for invalid rotation matrix if not np.all(np.isclose(self...
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-y+1/2', etc. Returns: SymmOp """ rot_matrix = np.zeros((3, 3)) trans = np.zeros(3) toks = xyz_string.strip...
Apply time reversal operator on the magnetic moment. Note that magnetic moments transform as axial vectors not polar vectors.
def operate_magmom(self, magmom): """ 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...
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): """ 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 "...
Creates a symmetry operation from a rotation matrix translation vector and time reversal operator.
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): """ Creates a symmetry operation from a rotation matrix, translation vector and time reversal operator. A...
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', '-2y+1/2, 3x+1/2, z-y+1/2, +1', etc. Returns: MagSymmOp object """ symmop = SymmOp.from_xyz_string(xyzt_string.rsplit(',', 1)[0]) ...
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 rotation matrices """ xyzt_string = SymmOp.as_xyz_string(self) return xyzt_string + ", {:+}".format(self.time_reversal)
Very flexible arguments to support many types of potential setups. Users should use more friendly static methods unless they need the flexibility.
def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None, basis_set="6-31g", basis_set_option="cartesian", title=None, operation="optimize", theory_directives=None, alternate_directives=None): """ Very flexible arguments to...
A class method for quickly creating DFT tasks with optional cosmo parameter.
def dft_task(cls, mol, xc="b3lyp", **kwargs): """ 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 ...
Read an NwInput from a string. Currently tested to work with files generated from this class itself.
def from_string(cls, string_input): """ 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 """ directives = [] ta...
Parses TDDFT roots. Adapted from nw_spectrum. py script.
def parse_tddft(self): """ Parses TDDFT roots. Adapted from nw_spectrum.py script. Returns: { "singlet": [ { "energy": float, "osc_strength: float } ], ...
Generate an excitation spectra from the singlet roots of TDDFT calculations.
def get_excitation_spectrum(self, width=0.1, npoints=2000): """ 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 ...
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.charge > 0: chg_str = " +" + formula_double_format(self.charge, False) elif sel...
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_str = "" if chg > 0: chg_str += ("{}{}".format('+', str(int(chg)))...
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: if abs(charge) == 1: chg_str...
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_format(self.charge, False) elif self.charge < 0: ...
Generates an ion object from a dict created by as_dict ().
def from_dict(cls, d): """ Generates an ion object from a dict created by as_dict(). Args: d: {symbol: amount} dict. """ charge = d.pop('charge') composition = Composition(d) return Ion(composition, charge)
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 d['charge'] = self.charge return d
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 = np.unique(np.argmin(self.c, axis=0), return_index=True) s...
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 loop can be proportional to 1/epsilon ...
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] - mu #augment the solution with the minimum co...
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 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 """ #find unassigned i* istar = np.a...
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) def wrapper(*args, **kwargs): self = args[0] d = method(*args, **kwargs) # Add @module and @c...
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, sort_keys=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 and # a key return obj.__class__.__name__, obj.symbol ...
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: type_tag, key_id = pid except Exception as exc: # Sometimes we get a string such as ('Elemen...
Get value from dict using MongoDB dot - separated path semantics. For example:
def mongo_getattr(rec, key): """ 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 N...
Scan a nested dict d and return the first value associated to the given key. Returns None if key is not found.
def scan_nestdict(d, key): """ 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:...
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.
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 = MongoClient(host=config.host, port=config.port) else: cl...
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(trans_json[0]) as f: return json.load(f)["history"] ...
Obtains a SpaceGroup name from its international number.
def sg_symbol_from_int_number(int_number, hexagonal=True): """ 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 sett...
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.
def in_array_list(array_list, a, tol=1e-5): """ 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 o...
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 supplied group. Args: supergroup (SymmetryGroup): Supergroup to test. Returns: True if this group is a subgroup of the supplied group. """ warnings.warn("This is not f...
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 supplied group. Args: subgroup (SymmetryGroup): Subgroup to test. Returns: True if this group is a supergroup of the supplied group. """ warnings.warn("This is not f...
Strips whitespace carriage returns and empty lines from a list of strings.
def clean_lines(string_list, remove_empty_lines=True): """ 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 ...
Small awk - mimicking search routine.
def micro_pyawk(filename, search, results=None, debug=None, postdebug=None): """ 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 ...
Create a temporary file with the filename similar the given name. The permission bits are copied from the original file or createmode. Returns: the name of the temporary file.
def _maketemp(name, createmode=None): """ Create a temporary file with the filename similar the given ``name``. The permission bits are copied from the original file or ``createmode``. Returns: the name of the temporary file. """ d, fn = os.path.split(name) fd, tempname = tempfile.mkstemp(pr...
Convert a PhonopyAtoms object to pymatgen Structure object.
def get_pmg_structure(phonopy_structure): """ Convert a PhonopyAtoms object to pymatgen Structure object. Args: phonopy_structure (PhonopyAtoms): A phonopy structure object. """ lattice = phonopy_structure.get_cell() frac_coords = phonopy_structure.get_scaled_positions() symbols =...
Convert a pymatgen Structure object to a PhonopyAtoms object.
def get_phonopy_structure(pmg_structure): """ Convert a pymatgen Structure object to a PhonopyAtoms object. Args: pmg_structure (pymatgen Structure): A Pymatgen structure object. """ symbols = [site.specie.symbol for site in pmg_structure] return PhonopyAtoms(symbols=symbols, cell=pm...
Extracts a structure from the dictionary extracted from the output files of phonopy like phonopy. yaml or band. yaml. Adds phonopy_masses in the site_properties of the structures. Compatible with older phonopy versions.
def get_structure_from_dict(d): """ Extracts a structure from the dictionary extracted from the output files of phonopy like phonopy.yaml or band.yaml. Adds "phonopy_masses" in the site_properties of the structures. Compatible with older phonopy versions. """ species = [] frac_coords = ...
Converts a single eigenvector to an eigendisplacement in the primitive cell according to the formula:: exp ( 2 * pi * i * ( frac_coords \\ dot q )/ sqrt ( mass ) * v Compared to the modulation option in phonopy here all the additional multiplicative and phase factors are set to 1. Args: v: the vector that should be con...
def eigvec_to_eigdispl(v, q, frac_coords, mass): """ Converts a single eigenvector to an eigendisplacement in the primitive cell according to the formula:: exp(2*pi*i*(frac_coords \\dot q) / sqrt(mass) * v Compared to the modulation option in phonopy, here all the additional mu...
Creates a pymatgen PhononBandStructure object from the dictionary extracted by the band. yaml file produced by phonopy. The labels will be extracted from the dictionary if present. If the eigenvector key is found the eigendisplacements will be calculated according to the formula:: exp ( 2 * pi * i * ( frac_coords \\ do...
def get_ph_bs_symm_line_from_dict(bands_dict, has_nac=False, labels_dict=None): """ Creates a pymatgen PhononBandStructure object from the dictionary extracted by the band.yaml file produced by phonopy. The labels will be extracted from the dictionary, if present. If the 'eigenvector' key is found t...
Creates a pymatgen PhononBandStructure from a band. yaml file. The labels will be extracted from the dictionary if present. If the eigenvector key is found the eigendisplacements will be calculated according to the formula: \\ exp ( 2 * pi * i * ( frac_coords \\ dot q )/ sqrt ( mass ) * v and added to the object.
def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None): """ Creates a pymatgen PhononBandStructure from a band.yaml file. The labels will be extracted from the dictionary, if present. If the 'eigenvector' key is found the eigendisplacements will be calculated according to the formula:...
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.
def get_complete_ph_dos(partial_dos_path, phonopy_yaml_path): """ 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 ...
Generate a set of symmetrically inequivalent displaced structures for phonon calculations.
def get_displaced_structures(pmg_structure, atom_disp=0.01, supercell_matrix=None, yaml_fname=None, **kwargs): """ Generate a set of symmetrically inequivalent displaced structures for phonon calculations. Args: pmg_structure (Structure): A pymatgen structure object...
Returns unique families of Miller indices. Families must be permutations of each other.
def get_unique_families(hkls): """ 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. """ # TODO: Definitely can be sp...
Returns the diffraction plot as a matplotlib. pyplot.
def get_plot(self, structure, two_theta_range=(0, 90), annotate_peaks=True, ax=None, with_labels=True, fontsize=16): """ Returns the diffraction plot as a matplotlib.pyplot. Args: structure: Input structure two_theta_range ([float of len...
Plot diffraction patterns for multiple structures on the same figure.
def plot_structures(self, structures, fontsize=6, **kwargs): """ Plot diffraction patterns for multiple structures on the same figure. Args: structures (Structure): List of structures two_theta_range ([float of length 2]): Tuple for range of two_thetas to...
A function to visualize pymatgen Structure objects in jupyter notebook using chemview package.
def quick_view(structure, bonds=True, conventional=False, transform=None, show_box=True, bond_tol=0.2, stick_radius=0.1): """ A function to visualize pymatgen Structure objects in jupyter notebook using chemview package. Args: structure: pymatgen Structure bonds: (bool) visualize bonds. Bon...
Normalize the spectrum with respect to the sum of intensity
def normalize(self, mode="max", value=1): """ 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...
Apply Gaussian smearing to spectrum y value.
def smear(self, sigma): """ Apply Gaussian smearing to spectrum y value. Args: sigma: Std dev for Gaussian smear function """ 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...
Returns an interpolated y value for a particular x value.
def get_interpolated_value(self, x): """ 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 """ if len(self.ydim) == 1: return get_linear_interpolated_value(s...
Returns: Copy of Spectrum object.
def copy(self): """ Returns: Copy of Spectrum object. """ return self.__class__(self.x, self.y, *self._args, **self._kwargs)
Write all magnetic space groups to a human - readable text file. Should contain same information as text files provided by ISO - MAG.: param filename:: return:
def _write_all_magnetic_space_groups_to_file(filename): """ Write all magnetic space groups to a human-readable text file. Should contain same information as text files provided by ISO-MAG. :param filename: :return: """ s = ('Data parsed from raw data from:\n' 'ISO-MAG, ISOTROPY S...
neb_analyses: a list of NEBAnalysis objects
def combine_neb_plots(neb_analyses, arranged_neb_analyses=False, reverse_plot=False): """ neb_analyses: a list of NEBAnalysis objects arranged_neb_analyses: The code connects two end points with the smallest-energy difference. If all end points have very close energies, it's l...
Setup of the options for the spline interpolation
def setup_spline(self, spline_options=None): """ 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. ""...
Initializes an NEBAnalysis from Outcar and Structure objects. Use the static constructors e. g.: class: from_dir instead if you prefer to have these automatically generated from a directory of NEB calculations.
def from_outcars(cls, outcars, structures, **kwargs): """ Initializes an NEBAnalysis from Outcar and Structure objects. Use the static constructors, e.g., :class:`from_dir` instead if you prefer to have these automatically generated from a directory of NEB calculations. ...
Returns the positions of the extrema along the MEP. Both local minimums and maximums are returned.
def get_extrema(self, normalize_rxn_coordinate=True): """ Returns the positions of the extrema along the MEP. Both local minimums and maximums are returned. Args: normalize_rxn_coordinate (bool): Whether to normalize the reaction coordinate to between 0 and 1...
Returns the NEB plot. Uses Henkelman s approach of spline fitting each section of the reaction path based on tangent force and energies.
def get_plot(self, normalize_rxn_coordinate=True, label_barrier=True): """ Returns the NEB plot. Uses Henkelman's approach of spline fitting each section of the reaction path based on tangent force and energies. Args: normalize_rxn_coordinate (bool): Whether to normalize the...
Initializes a NEBAnalysis object from a directory of a NEB run. Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations you can specify the locations using relaxation_dir. If these are not specified the code will attempt to look for the OUTCARs in 00 and 0n dire...
def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs): """ Initializes a NEBAnalysis object from a directory of a NEB run. Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations, you can specify the locations using ...