INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Open the SIGRES file located in the in self. outdir. Returns: class: ScrFile object None if file could not be found or file is not readable.
def open_scr(self): """ Open the SIGRES file located in the in self.outdir. Returns :class:`ScrFile` object, None if file could not be found or file is not readable. """ scr_path = self.scr_path if not scr_path: logger.critical("%s didn't produce a SCR.nc fil...
Absolute path of the SIGRES file. Empty string if file is not present.
def sigres_path(self): """Absolute path of the SIGRES file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._sigres_path except AttributeError: path = self.outdir.has_abiext("SIGRES") if p...
Open the SIGRES file located in the in self. outdir. Returns: class: SigresFile object None if file could not be found or file is not readable.
def open_sigres(self): """ Open the SIGRES file located in the in self.outdir. Returns :class:`SigresFile` object, None if file could not be found or file is not readable. """ sigres_path = self.sigres_path if not sigres_path: logger.critical("%s didn't produ...
Returns an instance of: class: ScissorsBuilder from the SIGRES file.
def get_scissors_builder(self): """ Returns an instance of :class:`ScissorsBuilder` from the SIGRES file. Raise: `RuntimeError` if SIGRES file is not found. """ from abipy.electrons.scissors import ScissorsBuilder if self.sigres_path: return Sciss...
BSE calculations with Haydock can be restarted only if we have the excitonic Hamiltonian and the HAYDR_SAVE file.
def restart(self): """ BSE calculations with Haydock can be restarted only if we have the excitonic Hamiltonian and the HAYDR_SAVE file. """ # TODO: This version seems to work but the main output file is truncated # TODO: Handle restart if CG method is used # TODO...
Absolute path of the MDF file. Empty string if file is not present.
def mdf_path(self): """Absolute path of the MDF file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._mdf_path except AttributeError: path = self.outdir.has_abiext("MDF.nc") if path: self...
Open the MDF file located in the in self. outdir. Returns: class: MdfFile object None if file could not be found or file is not readable.
def open_mdf(self): """ Open the MDF file located in the in self.outdir. Returns :class:`MdfFile` object, None if file could not be found or file is not readable. """ mdf_path = self.mdf_path if not mdf_path: logger.critical("%s didn't produce a MDF file in %s...
Set the working directory of the task.
def set_workdir(self, workdir, chroot=False): """Set the working directory of the task.""" super().set_workdir(workdir, chroot=chroot) # Small hack: the log file of optics is actually the main output file. self.output_file = self.log_file
Optic does not use get or ird variables hence we should never try to change the input when we connect this task
def set_vars(self, *args, **kwargs): """ Optic does not use `get` or `ird` variables hence we should never try to change the input when we connect this task """ kwargs.update(dict(*args)) self.history.info("OpticTask intercepted set_vars with args %s" % kwargs) i...
String with the list of files and prefixes needed to execute ABINIT.
def filesfile_string(self): """String with the list of files and prefixes needed to execute ABINIT.""" lines = [] app = lines.append #optic.in ! Name of input file #optic.out ! Unused #optic ! Root name for all files that will be produced app(self.i...
Returns ( at runtime ) the absolute path of the DDK files produced by the DDK runs.
def ddk_filepaths(self): """Returns (at runtime) the absolute path of the DDK files produced by the DDK runs.""" # This to support new version of optic that used DDK.nc paths = [ddk_task.outdir.has_abiext("DDK.nc") for ddk_task in self.ddk_nodes] if all(p for p in paths): ret...
Construct and write the input file of the calculation.
def make_input(self): """Construct and write the input file of the calculation.""" # Set the file paths. all_files ={"ddkfile_" + str(n + 1): ddk for n, ddk in enumerate(self.ddk_filepaths)} all_files.update({"wfkfile": self.wfk_filepath}) files_nml = {"FILES": all_files} ...
restart from scratch this is to be used if a job is restarted with more resources after a crash
def reset_from_scratch(self): """ restart from scratch, this is to be used if a job is restarted with more resources after a crash """ # Move output files produced in workdir to _reset otherwise check_status continues # to see the task as crashed even if the job did not run ...
Build a: class: AnaddbTask with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for post - processing the DDB files.
def temp_shell_task(cls, inp, ddb_node, mpi_procs=1, gkk_node=None, md_node=None, ddk_node=None, workdir=None, manager=None): """ Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for post-processing the ...
String with the list of files and prefixes needed to execute ABINIT.
def filesfile_string(self): """String with the list of files and prefixes needed to execute ABINIT.""" lines = [] app = lines.append app(self.input_file.path) # 1) Path of the input file app(self.output_file.path) # 2) Path of the output file app(self.dd...
Returns ( at runtime ) the absolute path of the input DDB file.
def ddb_filepath(self): """Returns (at runtime) the absolute path of the input DDB file.""" # This is not very elegant! A possible approach could to be path self.ddb_node.outdir! if isinstance(self.ddb_node, FileNode): return self.ddb_node.filepath path = self.ddb_node.outdir.has_abiext(...
Returns ( at runtime ) the absolute path of the input MD file.
def md_filepath(self): """Returns (at runtime) the absolute path of the input MD file.""" if self.md_node is None: return "MD_FILE_DOES_NOT_EXIST" if isinstance(self.md_node, FileNode): return self.md_node.filepath path = self.md_node.outdir.has_abiext("MD") return path if path ...
Returns ( at runtime ) the absolute path of the input GKK file.
def gkk_filepath(self): """Returns (at runtime) the absolute path of the input GKK file.""" if self.gkk_node is None: return "GKK_FILE_DOES_NOT_EXIST" if isinstance(self.gkk_node, FileNode): return self.gkk_node.filepath path = self.gkk_node.outdir.has_abiext("GKK") return path ...
Returns ( at runtime ) the absolute path of the input DKK file.
def ddk_filepath(self): """Returns (at runtime) the absolute path of the input DKK file.""" if self.ddk_node is None: return "DDK_FILE_DOES_NOT_EXIST" if isinstance(self.ddk_node, FileNode): return self.ddk_node.filepath path = self.ddk_node.outdir.has_abiext("DDK") return path ...
Open PHBST file produced by Anaddb and returns: class: PhbstFile object.
def open_phbst(self): """Open PHBST file produced by Anaddb and returns :class:`PhbstFile` object.""" from abipy.dfpt.phonons import PhbstFile phbst_path = os.path.join(self.workdir, "run.abo_PHBST.nc") if not phbst_path: if self.status == self.S_OK: logger.cr...
Open PHDOS file produced by Anaddb and returns: class: PhdosFile object.
def open_phdos(self): """Open PHDOS file produced by Anaddb and returns :class:`PhdosFile` object.""" from abipy.dfpt.phonons import PhdosFile phdos_path = os.path.join(self.workdir, "run.abo_PHDOS.nc") if not phdos_path: if self.status == self.S_OK: logger.cr...
Reads and returns a pymatgen structure from a NetCDF file containing crystallographic data in the ETSF - IO format.
def structure_from_ncdata(ncdata, site_properties=None, cls=Structure): """ Reads and returns a pymatgen structure from a NetCDF file containing crystallographic data in the ETSF-IO format. Args: ncdata: filename or NetcdfReader instance. site_properties: Dictionary with site properties...
Navigate all the groups in the file starting from top. If top is None the root group is used.
def walk_tree(self, top=None): """ Navigate all the groups in the file starting from top. If top is None, the root group is used. """ if top is None: top = self.rootgrp values = top.groups.values() yield values for value in top.groups.values()...
Returns the value of a dimension.
def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT): """ Returns the value of a dimension. Args: dimname: Name of the variable path: path to the group. default: return `default` if `dimname` is not present and `default` is not `NO_D...
List of variable names stored in the group specified by path.
def read_varnames(self, path="/"): """List of variable names stored in the group specified by path.""" if path == "/": return self.rootgrp.variables.keys() else: group = self.path2group[path] return group.variables.keys()
Returns the values of variable with name varname in the group specified by path.
def read_value(self, varname, path="/", cmode=None, default=NO_DEFAULT): """ Returns the values of variable with name varname in the group specified by path. Args: varname: Name of the variable path: path to the group. cmode: if cmode=="c", a complex ndarrays...
Read a list of variables/ dimensions from file. If a key is not present the corresponding entry in the output dictionary is set to None.
def read_keys(self, keys, dict_cls=AttrDict, path="/"): """ Read a list of variables/dimensions from file. If a key is not present the corresponding entry in the output dictionary is set to None. """ od = dict_cls() for k in keys: try: # Try to...
Chemical symbols char [ number of atom species ] [ symbol length ].
def chemical_symbols(self): """Chemical symbols char [number of atom species][symbol length].""" charr = self.read_value("chemical_symbols") symbols = [] for v in charr: s = "".join(c.decode("utf-8") for c in v) symbols.append(s.strip()) return symbols
Returns the crystalline structure.
def read_structure(self, cls=Structure): """Returns the crystalline structure.""" if self.ngroups != 1: raise NotImplementedError("In file %s: ngroups != 1" % self.path) return structure_from_ncdata(self, cls=cls)
Read the variables associated to the Abinit header.
def read_abinit_hdr(self): """ Read the variables associated to the Abinit header. Return :class:`AbinitHeader` """ d = {} for hvar in _HDR_VARIABLES.values(): ncname = hvar.etsf_name if hvar.etsf_name is not None else hvar.name if ncname in self....
String representation. kwargs are passed to pprint. pformat.
def to_string(self, verbose=0, title=None, **kwargs): """ String representation. kwargs are passed to `pprint.pformat`. Args: verbose: Verbosity level title: Title string. """ from pprint import pformat s = pformat(self, **kwargs) if title...
Add an electrode to the plot.
def add_electrode(self, electrode, label=None): """ Add an electrode to the plot. Args: electrode: An electrode. All electrodes satisfying the AbstractElectrode interface should work. label: A label for the electrode. If None, defaults to a counting ...
Returns a plot object.
def get_plot(self, width=8, height=8): """ Returns a plot object. Args: width: Width of the plot. Defaults to 8 in. height: Height of the plot. Defaults to 6 in. Returns: A matplotlib plot object. """ plt = pretty_plot(width, height) ...
Save the plot to an image file.
def save(self, filename, image_format="eps", width=8, height=6): """ Save the plot to an image file. Args: filename: Filename to save to. image_format: Format to save to. Defaults to eps. """ self.get_plot(width, height).savefig(filename, format=image_for...
Process structure from previous run.
def get_structure_from_prev_run(vasprun, outcar=None, sym_prec=0.1, international_monoclinic=True): """ Process structure from previous run. Args: vasprun (Vasprun): Vasprun that contains the final structure from previous run. outcar (Outcar): Out...
Batch write vasp input for a sequence of structures to output_dir following the format output_dir/ { group }/ { formula } _ { number }.
def batch_write_input(structures, vasp_input_set=MPRelaxSet, output_dir=".", make_dir_if_not_present=True, subfolder=None, sanitize=False, include_cif=False, **kwargs): """ Batch write vasp input for a sequence of structures to output_dir, following the format out...
List of POTCAR symbols.
def potcar_symbols(self): """ List of POTCAR symbols. """ elements = self.poscar.site_symbols potcar_symbols = [] settings = self._config_dict["POTCAR"] if isinstance(settings[elements[-1]], dict): for el in elements: potcar_symbols.ap...
Returns all input files as a dict of { filename: vasp object }
def all_input(self): """ Returns all input files as a dict of {filename: vasp object} Returns: dict of {filename: object}, e.g., {'INCAR': Incar object, ...} """ return {'INCAR': self.incar, 'KPOINTS': self.kpoints, 'POSCAR': self.posc...
Writes a set of VASP input to a directory.
def write_input(self, output_dir, make_dir_if_not_present=True, include_cif=False): """ Writes a set of VASP input to a directory. Args: output_dir (str): Directory to output the VASP input files make_dir_if_not_present (bool): Set to True if you want...
Gets the default number of electrons for a given structure.
def nelect(self): """ Gets the default number of electrons for a given structure. """ # if structure is not sorted this can cause problems, so must take # care to remove redundant symbols when counting electrons site_symbols = list(set(self.poscar.site_symbols)) n...
Writes out a KPOINTS file using the fully automated grid method. Uses Gamma centered meshes for hexagonal cells and Monk grids otherwise.
def kpoints(self): """ Writes out a KPOINTS file using the fully automated grid method. Uses Gamma centered meshes for hexagonal cells and Monk grids otherwise. Algorithm: Uses a simple approach scaling the number of divisions along each reciprocal lattice vector...
Generate a set of Vasp input files for static calculations from a directory of previous Vasp run.
def from_prev_calc(cls, prev_calc_dir, standardize=False, sym_prec=0.1, international_monoclinic=True, reciprocal_density=100, small_gap_multiply=None, **kwargs): """ Generate a set of Vasp input files for static calculations from a directory of prev...
Generate a set of Vasp input files for HSE calculations from a directory of previous Vasp run. if mode == gap it explicitly adds VBM and CBM of the prev run to the k - point list of this run.
def from_prev_calc(cls, prev_calc_dir, mode="gap", reciprocal_density=50, copy_chgcar=True, **kwargs): """ Generate a set of Vasp input files for HSE calculations from a directory of previous Vasp run. if mode=="gap", it explicitly adds VBM and CBM of the prev run ...
Generate a set of Vasp input files for NonSCF calculations from a directory of previous static Vasp run.
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, nbands_factor=1.2, standardize=False, sym_prec=0.1, international_monoclinic=True, reciprocal_density=100, kpoints_line_density=20, small_gap_multiply=None, **kwargs): ...
Generate a set of Vasp input files for SOC calculations from a directory of previous static Vasp run. SOC calc requires all 3 components for MAGMOM for each atom in the structure.
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, nbands_factor=1.2, standardize=False, sym_prec=0.1, international_monoclinic=True, reciprocal_density=100, small_gap_multiply=None, **kwargs): """ Generate a set of Vasp input fi...
Generate gamma center k - points mesh grid for GW calc which is requested by GW calculation.
def kpoints(self): """ Generate gamma center k-points mesh grid for GW calc, which is requested by GW calculation. """ return Kpoints.automatic_density_by_vol(self.structure, self.reciprocal_density, ...
Generate a set of Vasp input files for GW or BSE calculations from a directory of previous Exact Diag Vasp run.
def from_prev_calc(cls, prev_calc_dir, copy_wavecar=True, mode="DIAG", nbands_factor=5, ncores=16, **kwargs): """ Generate a set of Vasp input files for GW or BSE calculations from a directory of previous Exact Diag Vasp run. Args: prev_calc_dir (str):...
k_product default to 50 is kpoint number * length for a & b directions also for c direction in bulk calculations Automatic mesh & Gamma is the default setting.
def kpoints(self): """ k_product, default to 50, is kpoint number * length for a & b directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ # To get input sets, the input structure has to has the same number #...
k_product default to 40 is kpoint number * length for a & b directions also for c direction in bulk calculations Automatic mesh & Gamma is the default setting.
def kpoints(self): """ k_product, default to 40, is kpoint number * length for a & b directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ # To get input sets, the input structure has to has the same number # of ...
Remove any atom jumps across the cell
def _process_structures(structures): """ Remove any atom jumps across the cell """ input_structures = structures structures = [input_structures[0]] for s in input_structures[1:]: prev = structures[-1] for i in range(len(s)): t = np....
NEB inputs has a special directory structure where inputs are in 00 01 02....
def write_input(self, output_dir, make_dir_if_not_present=True, write_cif=False, write_path_cif=False, write_endpoint_inputs=False): """ NEB inputs has a special directory structure where inputs are in 00, 01, 02, .... Args: output_dir...
Gets a unit vector parallel to input vector
def get_uvec(vec): """ Gets a unit vector parallel to input vector""" l = np.linalg.norm(vec) if l < 1e-8: return vec return vec / l
Function that converts a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensor keys with symmop values corresponding to transformations that will result in derivative tensors from the original list
def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs): """ Function that converts a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensor keys with symmop values corresponding to transformations that will result in derivative tensors from the origina...
Helper function to find a value in a tensor - keyed - dictionary using an approximation to the key. This is useful if rounding errors in construction occur or hashing issues arise in tensor - keyed - dictionaries ( e. g. from symmetry_reduce ). Resolves most hashing issues and is preferable to redefining eq methods in ...
def get_tkd_value(tensor_keyed_dict, tensor, allclose_kwargs=None): """ Helper function to find a value in a tensor-keyed- dictionary using an approximation to the key. This is useful if rounding errors in construction occur or hashing issues arise in tensor-keyed-dictionaries (e. g. from symme...
returns the matrix with all entries below a certain threshold ( i. e. tol ) set to zero
def zeroed(self, tol=1e-3): """ returns the matrix with all entries below a certain threshold (i.e. tol) set to zero """ new_tensor = self.copy() new_tensor[abs(new_tensor) < tol] = 0 return new_tensor
Applies a rotation directly and tests input matrix to ensure a valid rotation.
def rotate(self, matrix, tol=1e-3): """ Applies a rotation directly, and tests input matrix to ensure a valid rotation. Args: matrix (3x3 array-like): rotation matrix to be applied to tensor tol (float): tolerance for testing rotation matrix validity """ ...
Calculates the result of an einstein summation expression
def einsum_sequence(self, other_arrays, einsum_string=None): """ Calculates the result of an einstein summation expression """ if not isinstance(other_arrays, list): raise ValueError("other tensors must be list of " "tensors or tensor input") ...
Convenience method for projection of a tensor into a vector. Returns the tensor dotted into a unit vector along the input n.
def project(self, n): """ Convenience method for projection of a tensor into a vector. Returns the tensor dotted into a unit vector along the input n. Args: n (3x1 array-like): direction to project onto Returns (float): scalar value correspondin...
Method for averaging the tensor projection over the unit with option for custom quadrature.
def average_over_unit_sphere(self, quad=None): """ Method for averaging the tensor projection over the unit with option for custom quadrature. Args: quad (dict): quadrature for integration, should be dictionary with "points" and "weights" keys defaults ...
Gets index sets for equivalent tensor values
def get_grouped_indices(self, voigt=False, **kwargs): """ Gets index sets for equivalent tensor values Args: voigt (bool): whether to get grouped indices of voigt or full notation tensor, defaults to false **kwargs: keyword args for np.isc...
Creates a summary dict for tensor with associated symbol
def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs): """ Creates a summary dict for tensor with associated symbol Args: voigt (bool): whether to get symbol dict for voigt notation tensor, as opposed to full notation, defaults to true ...
Wrapper around numpy. round to ensure object of same type is returned
def round(self, decimals=0): """ Wrapper around numpy.round to ensure object of same type is returned Args: decimals :Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left ...
Returns a generally symmetrized tensor calculated by taking the sum of the tensor and its transpose with respect to all possible permutations of indices
def symmetrized(self): """ Returns a generally symmetrized tensor, calculated by taking the sum of the tensor and its transpose with respect to all possible permutations of indices """ perms = list(itertools.permutations(range(self.rank))) return sum([np.transpose...
Returns a voigt - symmetrized tensor i. e. a voigt - notation tensor such that it is invariant wrt permutation of indices
def voigt_symmetrized(self): """ Returns a "voigt"-symmetrized tensor, i. e. a voigt-notation tensor such that it is invariant wrt permutation of indices """ if not (self.rank % 2 == 0 and self.rank >= 2): raise ValueError("V-symmetrization requires rank even and >= 2...
Returns a tensor that is invariant with respect to symmetry operations corresponding to a structure
def fit_to_structure(self, structure, symprec=0.1): """ Returns a tensor that is invariant with respect to symmetry operations corresponding to a structure Args: structure (Structure): structure from which to generate symmetry operations symprec (...
Tests whether a tensor is invariant with respect to the symmetry operations of a particular structure by testing whether the residual of the symmetric portion is below a tolerance
def is_fit_to_structure(self, structure, tol=1e-2): """ Tests whether a tensor is invariant with respect to the symmetry operations of a particular structure by testing whether the residual of the symmetric portion is below a tolerance Args: structure (Struct...
Returns the tensor in Voigt notation
def voigt(self): """ Returns the tensor in Voigt notation """ v_matrix = np.zeros(self._vscale.shape, dtype=self.dtype) this_voigt_map = self.get_voigt_dict(self.rank) for ind in this_voigt_map: v_matrix[this_voigt_map[ind]] = self[ind] if not self.is_...
Tests symmetry of tensor to that necessary for voigt - conversion by grouping indices into pairs and constructing a sequence of possible permutations to be used in a tensor transpose
def is_voigt_symmetric(self, tol=1e-6): """ Tests symmetry of tensor to that necessary for voigt-conversion by grouping indices into pairs and constructing a sequence of possible permutations to be used in a tensor transpose """ transpose_pieces = [[[0 for i in range(self...
Returns a dictionary that maps indices in the tensor to those in a voigt representation based on input rank
def get_voigt_dict(rank): """ Returns a dictionary that maps indices in the tensor to those in a voigt representation based on input rank Args: rank (int): Tensor rank to generate the voigt map """ vdict = {} for ind in itertools.product(*[range(3)] *...
Constructor based on the voigt notation vector or matrix.
def from_voigt(cls, voigt_input): """ Constructor based on the voigt notation vector or matrix. Args: voigt_input (array-like): voigt input for a given tensor """ voigt_input = np.array(voigt_input) rank = sum(voigt_input.shape) // 3 t = cls(np.zeros(...
Given a structure associated with a tensor determines the rotation matrix for IEEE conversion according to the 1987 IEEE standards.
def get_ieee_rotation(structure, refine_rotation=True): """ Given a structure associated with a tensor, determines the rotation matrix for IEEE conversion according to the 1987 IEEE standards. Args: structure (Structure): a structure associated with the ...
Given a structure associated with a tensor attempts a calculation of the tensor in IEEE format according to the 1987 IEEE standards.
def convert_to_ieee(self, structure, initial_fit=True, refine_rotation=True): """ Given a structure associated with a tensor, attempts a calculation of the tensor in IEEE format according to the 1987 IEEE standards. Args: structure (Structure)...
Transforms a tensor from one basis for an original structure into a new basis defined by a new structure.
def structure_transform(self, original_structure, new_structure, refine_rotation=True): """ Transforms a tensor from one basis for an original structure into a new basis defined by a new structure. Args: original_structure (Structure): structure c...
Creates a tensor from values and indices with options for populating the remainder of the tensor.
def from_values_indices(cls, values, indices, populate=False, structure=None, voigt_rank=None, vsym=True, verbose=False): """ Creates a tensor from values and indices, with options for populating the remainder of the tensor. Args: ...
Takes a partially populated tensor and populates the non - zero entries according to the following procedure iterated until the desired convergence ( specified via prec ) is achieved.
def populate(self, structure, prec=1e-5, maxiter=200, verbose=False, precond=True, vsym=True): """ Takes a partially populated tensor, and populates the non-zero entries according to the following procedure, iterated until the desired convergence (specified via prec) is ...
Serializes the tensor object
def as_dict(self, voigt=False): """ Serializes the tensor object Args: voigt (bool): flag for whether to store entries in voigt-notation. Defaults to false, as information may be lost in conversion. Returns (Dict): serialized for...
shorthand for matrix inverse on SquareTensor
def inv(self): """ shorthand for matrix inverse on SquareTensor """ if self.det == 0: raise ValueError("SquareTensor is non-invertible") return SquareTensor(np.linalg.inv(self))
Test to see if tensor is a valid rotation matrix performs a test to check whether the inverse is equal to the transpose and if the determinant is equal to one within the specified tolerance
def is_rotation(self, tol=1e-3, include_improper=True): """ Test to see if tensor is a valid rotation matrix, performs a test to check whether the inverse is equal to the transpose and if the determinant is equal to one within the specified tolerance Args: to...
Helper method for refining rotation matrix by ensuring that second and third rows are perpindicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new x and y
def refine_rotation(self): """ Helper method for refining rotation matrix by ensuring that second and third rows are perpindicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new x and y Args:...
Calculates the average oxidation state of a site
def compute_average_oxidation_state(site): """ Calculates the average oxidation state of a site Args: site: Site to compute average oxidation state Returns: Average oxidation state of site. """ try: avg_oxi = sum([sp.oxi_state * occu for sp, occu ...
Gives total ewald energy for certain sites being removed i. e. zeroed out.
def compute_partial_energy(self, removed_indices): """ Gives total ewald energy for certain sites being removed, i.e. zeroed out. """ total_energy_matrix = self.total_energy_matrix.copy() for i in removed_indices: total_energy_matrix[i, :] = 0 tota...
Gives total ewald energy for an sub structure in the same lattice. The sub_structure must be a subset of the original structure with possible different charges.
def compute_sub_structure(self, sub_structure, tol=1e-3): """ Gives total ewald energy for an sub structure in the same lattice. The sub_structure must be a subset of the original structure, with possible different charges. Args: substructure (Structure): Substructur...
The total energy.
def total_energy(self): """ The total energy. """ return sum(sum(self._recip)) + sum(sum(self._real)) + sum(self._point) + self._charged_cell_energy
The total energy matrix. Each matrix element ( i j ) corresponds to the total interaction energy between site i and site j.
def total_energy_matrix(self): """ The total energy matrix. Each matrix element (i, j) corresponds to the total interaction energy between site i and site j. Note that this does not include the charged-cell energy, which is only important when the simulation cell is not charge b...
Compute the energy for a single site in the structure Args: site_index ( int ): Index of site ReturnS: ( float ) - Energy of that site
def get_site_energy(self, site_index): """Compute the energy for a single site in the structure Args: site_index (int): Index of site ReturnS: (float) - Energy of that site""" if self._charged: warn('Per atom energies for charged structures no...
Perform the reciprocal space summation. Calculates the quantity E_recip = 1/ ( 2PiV ) sum_ { G < Gmax } exp ( - ( G. G/ 4/ eta ))/ ( G. G ) S ( G ) S ( - G ) where S ( G ) = sum_ { k = 1 N } q_k exp ( - i G. r_k ) S ( G ) S ( - G ) = |S ( G ) | ** 2
def _calc_recip(self): """ Perform the reciprocal space summation. Calculates the quantity E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G) where S(G) = sum_{k=1,N} q_k exp(-i G.r_k) S(G)S(-G) = |S(G)|**2 This method is heavily vectorized to ut...
Determines the self energy - ( eta/ pi ) ** ( 1/ 2 ) * sum_ { i = 1 } ^ { N } q_i ** 2
def _calc_real_and_point(self): """ Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2 """ fcoords = self._s.frac_coords forcepf = 2.0 * self._sqrt_eta / sqrt(pi) coords = self._coords numsites = self._s.num_sites ereal = np.empty((numsites...
This method finds and returns the permutations that produce the lowest ewald sum calls recursive function to iterate through permutations
def minimize_matrix(self): """ This method finds and returns the permutations that produce the lowest ewald sum calls recursive function to iterate through permutations """ if self._algo == EwaldMinimizer.ALGO_FAST or \ self._algo == EwaldMinimizer.ALGO_BE...
This adds an m_list to the output_lists and updates the current minimum if the list is full.
def add_m_list(self, matrix_sum, m_list): """ This adds an m_list to the output_lists and updates the current minimum if the list is full. """ if self._output_lists is None: self._output_lists = [[matrix_sum, m_list]] else: bisect.insort(self._outp...
Computes a best case given a matrix and manipulation list.
def best_case(self, matrix, m_list, indices_left): """ Computes a best case given a matrix and manipulation list. Args: matrix: the current matrix (with some permutations already performed) m_list: [(multiplication fraction, number_of_indices, indices, ...
Returns an index that should have the most negative effect on the matrix sum
def get_next_index(self, matrix, manipulation, indices_left): """ Returns an index that should have the most negative effect on the matrix sum """ f = manipulation[0] indices = list(indices_left.intersection(manipulation[2])) sums = np.sum(matrix[indices], axis=1)...
This method recursively finds the minimal permutations using a binary tree search strategy.
def _recurse(self, matrix, m_list, indices, output_m_list=[]): """ This method recursively finds the minimal permutations using a binary tree search strategy. Args: matrix: The current matrix (with some permutations already performed). m_list: The...
Calculates the ensemble averaged Voronoi coordination numbers of a list of Structures using VoronoiNN. Typically used for analyzing the output of a Molecular Dynamics run. Args: structures ( list ): list of Structures. freq ( int ): sampling frequency of coordination number [ every freq steps ]. Returns: Dictionary of ...
def average_coordination_number(structures, freq=10): """ Calculates the ensemble averaged Voronoi coordination numbers of a list of Structures using VoronoiNN. Typically used for analyzing the output of a Molecular Dynamics run. Args: structures (list): list of Structures. freq (int...
Helper method to calculate the solid angle of a set of coords from the center.
def solid_angle(center, coords): """ Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle. """ ...
Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: ( structure ) el_radius_updates: ( dict ) symbol - > float to update atomic radii Returns: ( dict ) - ( Element1 Element2 ) - > float. The two elements are ordered by Z.
def get_max_bond_lengths(structure, el_radius_updates=None): """ Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: (structure) el_radius_updates: (dict) symbol->float to update atomic radii Returns: (dict) - (Element...
This method returns whether a structure is 3D 2D ( layered ) or 1D ( linear chains or molecules ) according to the algorithm published in Gorai P. Toberer E. & Stevanovic V. Computational Identification of Promising Thermoelectric Materials Among Known Quasi - 2D Binary Compounds. J. Mater. Chem. A 2 4136 ( 2016 ).
def get_dimensionality(structure, max_hkl=2, el_radius_updates=None, min_slab_size=5, min_vacuum_size=5, standardize=True, bonds=None): """ This method returns whether a structure is 3D, 2D (layered), or 1D (linear chains or molecules) according to the algorithm...
Determines if a structure contains peroxide anions.
def contains_peroxide(structure, relative_cutoff=1.1): """ Determines if a structure contains peroxide anions. Args: structure (Structure): Input structure. relative_cutoff: The peroxide bond distance is 1.49 Angstrom. Relative_cutoff * 1.49 stipulates the maximum distance two O...
Determines if an oxide is a peroxide/ superoxide/ ozonide/ normal oxide
def oxide_type(structure, relative_cutoff=1.1, return_nbonds=False): """ Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide Args: structure (Structure): Input structure. relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the max distance two O at...
Determines if a structure is a sulfide/ polysulfide
def sulfide_type(structure): """ Determines if a structure is a sulfide/polysulfide Args: structure (Structure): Input structure. Returns: (str) sulfide/polysulfide/sulfate """ structure = structure.copy() structure.remove_oxidation_states() s = Element("S") comp = ...
Performs Voronoi analysis and returns the polyhedra around atom n in Schlaefli notation.
def analyze(self, structure, n=0): """ Performs Voronoi analysis and returns the polyhedra around atom n in Schlaefli notation. Args: structure (Structure): structure to analyze n (int): index of the center atom in structure Returns: voronoi ...