INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Json - serializable dict representation of a kpoint
def as_dict(self): """ Json-serializable dict representation of a kpoint """ return {"lattice": self.lattice.as_dict(), "fcoords": list(self.frac_coords), "ccoords": list(self.cart_coords), "label": self.label, "@module": self.__class__.__m...
Method returning a dictionary of projections on elements.
def get_projection_on_elements(self): """ Method returning a dictionary of projections on elements. Returns: a dictionary in the {Spin.up:[][{Element:values}], Spin.down:[][{Element:values}]} format if there is no projections in the band structure ...
Method returning a dictionary of projections on elements and specific orbitals
def get_projections_on_elements_and_orbitals(self, el_orb_spec): """ Method returning a dictionary of projections on elements and specific orbitals Args: el_orb_spec: A dictionary of Elements and Orbitals for which we want to have projections on. It is given ...
Check if the band structure indicates a metal by looking if the fermi level crosses a band.
def is_metal(self, efermi_tol=1e-4): """ Check if the band structure indicates a metal by looking if the fermi level crosses a band. Returns: True if a metal, False if not """ for spin, values in self.bands.items(): for i in range(self.nb_bands): ...
Returns data about the VBM.
def get_vbm(self): """ Returns data about the VBM. Returns: dict as {"band_index","kpoint_index","kpoint","energy"} - "band_index": A dict with spin keys pointing to a list of the indices of the band containing the VBM (please note that you can ha...
Returns data about the CBM.
def get_cbm(self): """ Returns data about the CBM. Returns: {"band_index","kpoint_index","kpoint","energy"} - "band_index": A dict with spin keys pointing to a list of the indices of the band containing the VBM (please note that you can have sever...
Returns band gap data.
def get_band_gap(self): """ Returns band gap data. Returns: A dict {"energy","direct","transition"}: "energy": band gap energy "direct": A boolean telling if the gap is direct or not "transition": kpoint labels of the transition (e.g., "\\Gamma-X"...
Returns a dictionary of information about the direct band gap
def get_direct_band_gap_dict(self): """ Returns a dictionary of information about the direct band gap Returns: a dictionary of the band gaps indexed by spin along with their band indices and k-point index """ if self.is_metal(): raise ...
Returns the direct band gap.
def get_direct_band_gap(self): """ Returns the direct band gap. Returns: the value of the direct band gap """ if self.is_metal(): return 0.0 dg = self.get_direct_band_gap_dict() return min(v['value'] for v in dg.values())
Returns a list of unique symmetrically equivalent k - points.
def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol=1e-2): """ Returns a list of unique symmetrically equivalent k-points. Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in cartesian or fractional coordinates tol (float)...
Returns degeneracy of a given k - point based on structure symmetry Args: kpoint ( 1x3 array ): coordinate of the k - point cartesian ( bool ): kpoint is in cartesian or fractional coordinates tol ( float ): tolerance below which coordinates are considered equal
def get_kpoint_degeneracy(self, kpoint, cartesian=False, tol=1e-2): """ Returns degeneracy of a given k-point based on structure symmetry Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in cartesian or fractional coordinates tol...
Create from dict.
def from_dict(cls, d): """ Create from dict. Args: A dict with all data for a band structure object. Returns: A BandStructure object """ labels_dict = d['labels_dict'] projections = {} structure = None if isinstance(list(d...
Returns the list of kpoint indices equivalent ( meaning they are the same frac coords ) to the given one.
def get_equivalent_kpoints(self, index): """ Returns the list of kpoint indices equivalent (meaning they are the same frac coords) to the given one. Args: index: the kpoint index Returns: a list of equivalent indices TODO: now it uses the label ...
Json - serializable dict representation of BandStructureSymmLine.
def as_dict(self): """ Json-serializable dict representation of BandStructureSymmLine. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "lattice_rec": self.lattice_rec.as_dict(), "efermi": self.efermi, "kpoints": []...
Args: d ( dict ): A dict with all data for a band structure symm line object.
def from_dict(cls, d): """ Args: d (dict): A dict with all data for a band structure symm line object. Returns: A BandStructureSymmLine object """ try: # Strip the label to recover initial string (see trick used in as_dict to h...
Args: d ( dict ): A dict with all data for a band structure symm line object. Returns: A BandStructureSymmLine object
def from_old_dict(cls, d): """ Args: d (dict): A dict with all data for a band structure symm line object. Returns: A BandStructureSymmLine object """ # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)...
Apply a scissor operator ( shift of the CBM ) to fit the given band gap. If it s a metal. We look for the band crossing the fermi level and shift this one up. This will not work all the time for metals!
def apply_scissor(self, new_band_gap): """ Apply a scissor operator (shift of the CBM) to fit the given band gap. If it's a metal. We look for the band crossing the fermi level and shift this one up. This will not work all the time for metals! Args: new_band_gap: the...
Args: d ( dict ): A dict with all data for a band structure symm line object. Returns: A BandStructureSymmLine object
def from_old_dict(cls, d): """ Args: d (dict): A dict with all data for a band structure symm line object. Returns: A BandStructureSymmLine object """ # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)...
Method returning a dictionary of projections on elements and specific orbitals
def get_projections_on_elements_and_orbitals(self, el_orb_spec): """ Method returning a dictionary of projections on elements and specific orbitals Args: el_orb_spec: A dictionary of Elements and Orbitals for which we want to have projections on. It is given ...
Quadratic fit to get an initial guess for the parameters.
def _initial_guess(self): """ Quadratic fit to get an initial guess for the parameters. Returns: tuple: (e0, b0, b1, v0) """ a, b, c = np.polyfit(self.volumes, self.energies, 2) self.eos_params = [a, b, c] v0 = -b/(2*a) e0 = a*(v0**2) + b*v0 ...
Do the fitting. Does least square fitting. If you want to use custom fitting must override this.
def fit(self): """ Do the fitting. Does least square fitting. If you want to use custom fitting, must override this. """ # the objective function that will be minimized in the least square # fitting objective_func = lambda pars, x, y: y - self._func(x, pars) ...
The equation of state function with the paramters other than volume set to the ones obtained from fitting.
def func(self, volume): """ The equation of state function with the paramters other than volume set to the ones obtained from fitting. Args: volume (list/numpy.array) Returns: numpy.array """ return self._func(np.array(volume), self.eos_...
Returns a summary dict.
def results(self): """ Returns a summary dict. Returns: dict """ return dict(e0=self.e0, b0=self.b0, b1=self.b1, v0=self.v0)
Plot the equation of state.
def plot(self, width=8, height=None, plt=None, dpi=None, **kwargs): """ Plot the equation of state. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt ...
Plot the equation of state on axis ax
def plot_ax(self, ax=None, fontsize=12, **kwargs): """ Plot the equation of state on axis `ax` Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. fontsize: Legend fontsize. color (str): plot color. label (str): Plot labe...
From Intermetallic compounds: Principles and Practice Vol. I: Principles Chapter 9 pages 195 - 210 by M. Mehl. B. Klein D. Papaconstantopoulos. case where n = 0
def _func(self, volume, params): """ From Intermetallic compounds: Principles and Practice, Vol. I: Principles Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos. case where n=0 """ e0, b0, b1, v0 = tuple(params) return (e0 ...
BirchMurnaghan equation from PRB 70 224107
def _func(self, volume, params): """ BirchMurnaghan equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (v0 / volume) ** (1. / 3.) return (e0 + 9. * b0 * v0 / 16. * (eta ** 2 - 1)**2 * (6 + b1 * (eta ** 2 - 1.) - 4. * eta ...
Pourier - Tarantola equation from PRB 70 224107
def _func(self, volume, params): """ Pourier-Tarantola equation from PRB 70, 224107 """ e0, b0, b1, v0 = tuple(params) eta = (volume / v0) ** (1. / 3.) squiggle = -3.*np.log(eta) return e0 + b0 * v0 * squiggle ** 2 / 6. * (3. + squiggle * (b1 - 2))
Use the fit polynomial to compute the parameter e0 b0 b1 and v0 and set to the _params attribute.
def _set_params(self): """ Use the fit polynomial to compute the parameter e0, b0, b1 and v0 and set to the _params attribute. """ fit_poly = np.poly1d(self.eos_params) # the volume at min energy, used as the intial guess for the # optimization wrt volume. ...
Overriden since this eos works with volume ** ( 2/ 3 ) instead of volume.
def fit(self, order=3): """ Overriden since this eos works with volume**(2/3) instead of volume. """ x = self.volumes**(-2./3.) self.eos_params = np.polyfit(x, self.energies, order) self._set_params()
Overriden to account for the fact the fit with volume ** ( 2/ 3 ) instead of volume.
def _set_params(self): """ Overriden to account for the fact the fit with volume**(2/3) instead of volume. """ deriv0 = np.poly1d(self.eos_params) deriv1 = np.polyder(deriv0, 1) deriv2 = np.polyder(deriv1, 1) deriv3 = np.polyder(deriv2, 1) for x i...
Fit the input data to the numerical eos the equation of state employed in the quasiharmonic Debye model described in the paper: 10. 1103/ PhysRevB. 90. 174107.
def fit(self, min_ndata_factor=3, max_poly_order_factor=5, min_poly_order=2): """ Fit the input data to the 'numerical eos', the equation of state employed in the quasiharmonic Debye model described in the paper: 10.1103/PhysRevB.90.174107. credits: Cormac Toher Args: ...
Fit energies as function of volumes.
def fit(self, volumes, energies): """ Fit energies as function of volumes. Args: volumes (list/np.array) energies (list/np.array) Returns: EOSBase: EOSBase object """ eos_fit = self.model(np.array(volumes), np.array(energies)) ...
Compute the defect densities using dilute solution model.
def dilute_solution_model(structure, e0, vac_defs, antisite_defs, T, trial_chem_pot=None, generate='plot'): """ Compute the defect densities using dilute solution model. Args: structure: pymatgen.core.structure.Structure object representing the primitive or unitcell of the crystal. ...
Wrapper for the dilute_solution_model. The computed plot data is prepared based on plot_style.
def compute_defect_density(structure, e0, vac_defs, antisite_defs, T=800, trial_chem_pot=None, plot_style="highcharts"): """ Wrapper for the dilute_solution_model. The computed plot data is prepared based on plot_style. Args: structure: pymatgen.core.structure.Structure object representing the ...
Compute the solute defect densities using dilute solution model. Args: structure: pymatgen. core. structure. Structure object representing the primitive or unitcell of the crystal. e0: The total energy of the undefected system. This is E0 from VASP calculation. T: Temperature in Kelvin vac_defs: List of vacancy defect ...
def solute_site_preference_finder(structure, e0, T, vac_defs, antisite_defs, solute_defs, solute_concen=0.01, ...
Wrapper for the solute_site_preference_finder. The computed plot data is prepared based on plot_style.
def solute_defect_density(structure, e0, vac_defs, antisite_defs, solute_defs, solute_concen=0.01, T=800, trial_chem_pot=None, ...
Evaluate the gibbs free energy as a function of V T and P i. e G ( V T P ) minimize G ( V T P ) wrt V for each T and store the optimum values.
def optimize_gibbs_free_energy(self): """ Evaluate the gibbs free energy as a function of V, T and P i.e G(V, T, P), minimize G(V, T, P) wrt V for each T and store the optimum values. Note: The data points for which the equation of state fitting fails are skipped. ...
Evaluate G ( V T P ) at the given temperature ( and pressure ) and minimize it wrt V.
def optimizer(self, temperature): """ Evaluate G(V, T, P) at the given temperature(and pressure) and minimize it wrt V. 1. Compute the vibrational helmholtz free energy, A_vib. 2. Compute the gibbs free energy as a function of volume, temperature and pressure, G(V,T...
Vibrational Helmholtz free energy A_vib ( V T ). Eq ( 4 ) in doi. org/ 10. 1016/ j. comphy. 2003. 12. 001
def vibrational_free_energy(self, temperature, volume): """ Vibrational Helmholtz free energy, A_vib(V, T). Eq(4) in doi.org/10.1016/j.comphy.2003.12.001 Args: temperature (float): temperature in K volume (float) Returns: float: vibrational f...
Vibrational internal energy U_vib ( V T ). Eq ( 4 ) in doi. org/ 10. 1016/ j. comphy. 2003. 12. 001
def vibrational_internal_energy(self, temperature, volume): """ Vibrational internal energy, U_vib(V, T). Eq(4) in doi.org/10.1016/j.comphy.2003.12.001 Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: vibra...
Calculates the debye temperature. Eq ( 6 ) in doi. org/ 10. 1016/ j. comphy. 2003. 12. 001. Thanks to Joey.
def debye_temperature(self, volume): """ Calculates the debye temperature. Eq(6) in doi.org/10.1016/j.comphy.2003.12.001. Thanks to Joey. Eq(6) above is equivalent to Eq(3) in doi.org/10.1103/PhysRevB.37.790 which does not consider anharmonic effects. Eq(20) in the same paper ...
Debye integral. Eq ( 5 ) in doi. org/ 10. 1016/ j. comphy. 2003. 12. 001
def debye_integral(y): """ Debye integral. Eq(5) in doi.org/10.1016/j.comphy.2003.12.001 Args: y (float): debye temperature/T, upper limit Returns: float: unitless """ # floating point limit is reached around y=155, so values beyond that ...
Slater - gamma formulation ( the default ): gruneisen paramter = - d log ( theta )/ d log ( V ) = - ( 1/ 6 + 0. 5 d log ( B )/ d log ( V ) ) = - ( 1/ 6 + 0. 5 V/ B dB/ dV ) where dB/ dV = d^2E/ dV^2 + V * d^3E/ dV^3
def gruneisen_parameter(self, temperature, volume): """ Slater-gamma formulation(the default): gruneisen paramter = - d log(theta)/ d log(V) = - ( 1/6 + 0.5 d log(B)/ d log(V) ) = - (1/6 + 0.5 V/B dB/dV), ...
Eq ( 17 ) in 10. 1103/ PhysRevB. 90. 174107
def thermal_conductivity(self, temperature, volume): """ Eq(17) in 10.1103/PhysRevB.90.174107 Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: thermal conductivity in W/K/m """ gamma = self.gruneise...
Returns a dict with a summary of the computed properties.
def get_summary_dict(self): """ Returns a dict with a summary of the computed properties. """ d = defaultdict(list) d["pressure"] = self.pressure d["poisson"] = self.poisson d["mass"] = self.mass d["natoms"] = int(self.natoms) d["bulk_modulus"] = s...
Set all frac_coords of the input structure within [ 0 1 ].
def fix_pbc(structure, matrix=None): """ Set all frac_coords of the input structure within [0,1]. Args: structure (pymatgen structure object): input structure matrix (lattice matrix, 3 by 3 array/matrix) new structure's lattice matrix, if none, use input ...
obtain cubic symmetric eqivalents of the list of vectors.
def symm_group_cubic(mat): """ obtain cubic symmetric eqivalents of the list of vectors. Args: matrix (lattice matrix, n by 3 array/matrix) Return: cubic symmetric eqivalents of the list of vectors. """ sym_group = np.zeros([24, 3, 3]) sym_group[0, :] = [[1, 0, 0], [0, 1, ...
Convenience method to get a copy of the structure with options to add site properties.
def copy(self): """ Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized. """ return GrainBoundary(self.lattice, self...
Get a sorted copy of the structure. The parameters have the same meaning as in list. sort. By default sites are sorted by the electronegativity of the species. Note that Slab has to override this because of the different __init__ args. Args: key: Specifies a function of one argument that is used to extract a comparison...
def get_sorted_structure(self, key=None, reverse=False): """ Get a sorted copy of the structure. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. Note that Slab has to override this because of the differen...
This method returns the sigma value of the gb. If using quick_gen to generate GB this value is not valid.
def sigma(self): """ This method returns the sigma value of the gb. If using 'quick_gen' to generate GB, this value is not valid. """ return int(round(self.oriented_unit_cell.volume / self.init_cell.volume))
This method returns the sigma value of the gb from site properties. If the GB structure merge some atoms due to the atoms too closer with each other this property will not work.
def sigma_from_site_prop(self): """ This method returns the sigma value of the gb from site properties. If the GB structure merge some atoms due to the atoms too closer with each other, this property will not work. """ num_coi = 0 if None in self.site_properties['...
return the top grain ( Structure ) of the GB.
def top_grain(self): """ return the top grain (Structure) of the GB. """ top_sites = [] for i, tag in enumerate(self.site_properties['grain_label']): if 'top' in tag: top_sites.append(self.sites[i]) return Structure.from_sites(top_sites)
return the bottom grain ( Structure ) of the GB.
def bottom_grain(self): """ return the bottom grain (Structure) of the GB. """ bottom_sites = [] for i, tag in enumerate(self.site_properties['grain_label']): if 'bottom' in tag: bottom_sites.append(self.sites[i]) return Structure.from_sites(bo...
return the a list of coincident sites.
def coincidents(self): """ return the a list of coincident sites. """ coincident_sites = [] for i, tag in enumerate(self.site_properties['grain_label']): if 'incident' in tag: coincident_sites.append(self.sites[i]) return coincident_sites
Args: rotation_axis ( list ): Rotation axis of GB in the form of a list of integer e. g.: [ 1 1 0 ] rotation_angle ( float in unit of degree ): rotation angle used to generate GB. Make sure the angle is accurate enough. You can use the enum * functions in this class to extract the accurate angle. e. g.: The rotation an...
def gb_from_parameters(self, rotation_axis, rotation_angle, expand_times=4, vacuum_thickness=0.0, ab_shift=[0, 0], normal=False, ratio=None, plane=None, max_search=20, tol_coi=1.e-8, rm_ratio=0.7, quick_gen=False): """ Args: rotation_axis...
find the axial ratio needed for GB generator input. Args: max_denominator ( int ): the maximum denominator for the computed ratio default to be 5. index_none ( int ): specify the irrational axis. 0 - a 1 - b 2 - c. Only may be needed for orthorombic system. Returns: axial ratio needed for GB generator ( list of integer...
def get_ratio(self, max_denominator=5, index_none=None): """ find the axial ratio needed for GB generator input. Args: max_denominator (int): the maximum denominator for the computed ratio, default to be 5. index_none (int): specify the irrational axis. ...
Find the two transformation matrix for each grain from given rotation axis GB plane rotation angle and corresponding ratio ( see explanation for ratio below ). The structure of each grain can be obtained by applying the corresponding transformation matrix to the conventional cell. The algorithm for this code is from re...
def get_trans_mat(r_axis, angle, normal=False, trans_cry=np.eye(3), lat_type='c', ratio=None, surface=None, max_search=20, quick_gen=False): """ Find the two transformation matrix for each grain from given rotation axis, GB plane, rotation angle and corresponding ratio (see...
Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in cubic system. The algorithm for this code is from reference Acta Cryst A40 108 ( 1984 ) Args: cutoff ( integer ): the cutoff of sigma values. r_axis ( list of three integers e. g. u v w ): the rotati...
def enum_sigma_cubic(cutoff, r_axis): """ Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in cubic system. The algorithm for this code is from reference, Acta Cryst, A40,108(1984) Args: cutoff (inte...
Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in rhombohedral system. The algorithm for this code is from reference Acta Cryst A45 505 ( 1989 ).
def enum_sigma_rho(cutoff, r_axis, ratio_alpha): """ Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in rhombohedral system. The algorithm for this code is from reference, Acta Cryst, A45,505(1989). Args: ...
Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in tetragonal system. The algorithm for this code is from reference Acta Cryst B46 117 ( 1990 )
def enum_sigma_tet(cutoff, r_axis, c2_a2_ratio): """ Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in tetragonal system. The algorithm for this code is from reference, Acta Cryst, B46,117(1990) Args: ...
Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in orthorhombic system. The algorithm for this code is from reference Scipta Metallurgica 27 291 ( 1992 )
def enum_sigma_ort(cutoff, r_axis, c2_b2_a2_ratio): """ Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in orthorhombic system. The algorithm for this code is from reference, Scipta Metallurgica 27, 291(1992) ...
Find all possible plane combinations for GBs given a rotaion axis and angle for cubic system and classify them to different categories including Twist Symmetric tilt Normal tilt Mixed GBs.
def enum_possible_plane_cubic(plane_cutoff, r_axis, r_angle): """ Find all possible plane combinations for GBs given a rotaion axis and angle for cubic system, and classify them to different categories, including 'Twist', 'Symmetric tilt', 'Normal tilt', 'Mixed' GBs. Args: ...
Find all possible rotation angle for the given sigma value.
def get_rotation_angle_from_sigma(sigma, r_axis, lat_type='C', ratio=None): """ Find all possible rotation angle for the given sigma value. Args: sigma (integer): sigma value provided r_axis (list of three integers, e.g. u, v, w or...
By linear operation of csl lattice vectors to get the best corresponding slab lattice. That is the area of a b vectors ( within the surface plane ) is the smallest the c vector first has shortest length perpendicular to surface [ h k l ] second has shortest length itself.
def slab_from_csl(csl, surface, normal, trans_cry, max_search=20, quick_gen=False): """ By linear operation of csl lattice vectors to get the best corresponding slab lattice. That is the area of a,b vectors (within the surface plane) is the smallest, the c vector first, has shortest leng...
Reduce integer array mat s determinant mag times by linear combination of its row vectors so that the new array after rotation ( r_matrix ) is still an integer array
def reduce_mat(mat, mag, r_matrix): """ Reduce integer array mat's determinant mag times by linear combination of its row vectors, so that the new array after rotation (r_matrix) is still an integer array Args: mat (3 by 3 array): input matrix mag (intege...
Transform a float vector to a surface miller index with integers.
def vec_to_surface(vec): """ Transform a float vector to a surface miller index with integers. Args: vec (1 by 3 array float vector): input float vector Return: the surface miller index of the input vector. """ miller = [None] * 3 index = ...
Adds a Spectrum for plotting.
def add_spectrum(self, label, spectrum, color=None): """ Adds a Spectrum for plotting. Args: label (str): Label for the Spectrum. Must be unique. spectrum: Spectrum object color (str): This is passed on to matplotlib. E.g., "k--" indicates a d...
Add a dictionary of doses with an optional sorting function for the keys.
def add_spectra(self, spectra_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_fu...
Get a matplotlib plot showing the DOS.
def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = pretty_plot(12, 8) ...
Save matplotlib plot to a file.
def save_plot(self, filename, img_format="eps", **kwargs): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. """ plt = self.get_plot(**kwargs) plt.savefig(filename, format=i...
Apply the transformation.
def apply_transformation(self, structure, return_ranked_list=False): """ Apply the transformation. Args: structure: input structure return_ranked_list (bool/int): Boolean stating whether or not multiple structures are returned. If return_ranked_list is ...
For this transformation the apply_transformation method will return only the ordered structure with the lowest Ewald energy to be consistent with the method signature of the other transformations. However all structures are stored in the all_structures attribute in the transformation object for easy access.
def apply_transformation(self, structure, return_ranked_list=False): """ For this transformation, the apply_transformation method will return only the ordered structure with the lowest Ewald energy, to be consistent with the method signature of the other transformations. However,...
Returns most primitive cell for structure.
def apply_transformation(self, structure): """ Returns most primitive cell for structure. Args: structure: A structure Returns: The same structure in a conventional standard setting """ sga = SpacegroupAnalyzer(structure, symprec=self.symprec, ...
Discretizes the site occupancies in the structure.
def apply_transformation(self, structure): """ Discretizes the site occupancies in the structure. Args: structure: disordered Structure to discretize occupancies Returns: A new disordered Structure with occupancies discretized """ if structure.is...
Returns a copy of structure with lattice parameters and sites scaled to the same degree as the relaxed_structure.
def apply_transformation(self, structure): """ Returns a copy of structure with lattice parameters and sites scaled to the same degree as the relaxed_structure. Arg: structure (Structure): A structurally similar structure in regards to crystal and site positi...
Makes LibxcFunc obey the general json interface used in pymatgen for easier serialization.
def as_dict(self): """ Makes LibxcFunc obey the general json interface used in pymatgen for easier serialization. """ return {"name": self.name, "@module": self.__class__.__module__, "@class": self.__class__.__name__}
Converts a lattice object to LammpsBox and calculates the symmetry operation used.
def lattice_2_lmpbox(lattice, origin=(0, 0, 0)): """ Converts a lattice object to LammpsBox, and calculates the symmetry operation used. Args: lattice (Lattice): Input lattice. origin: A (3,) array/list of floats setting lower bounds of simulation box. Default to (0, 0, 0). ...
Converts a structure to a LammpsData object with no force field parameters and topologies.
def structure_2_lmpdata(structure, ff_elements=None, atom_style="charge"): """ Converts a structure to a LammpsData object with no force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of strings of elements that must be ...
Volume of simulation box.
def volume(self): """ Volume of simulation box. """ m = self._matrix return np.dot(np.cross(m[0], m[1]), m[2])
Returns the string representation of simulation box in LAMMPS data file format.
def get_string(self, significant_figures=6): """ Returns the string representation of simulation box in LAMMPS data file format. Args: significant_figures (int): No. of significant figures to output for box settings. Default to 6. Returns: ...
Exports a periodic structure object representing the simulation box.
def structure(self): """ Exports a periodic structure object representing the simulation box. Return: Structure """ masses = self.masses atoms = self.atoms.copy() if "nx" in atoms.columns: atoms.drop(["nx", "ny", "nz"], axis=1, in...
Returns the string representation of LammpsData essentially the string to be written to a file.
def get_string(self, distance=6, velocity=8, charge=3): """ Returns the string representation of LammpsData, essentially the string to be written to a file. Args: distance (int): No. of significant figures to output for box settings (bounds and tilt) and atom...
Writes LammpsData to file.
def write_file(self, filename, distance=6, velocity=8, charge=3): """ Writes LammpsData to file. Args: filename (str): Filename. distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. ...
Breaks down LammpsData to building blocks ( LammpsBox ForceField and a series of Topology ). RESTRICTIONS APPLIED:
def disassemble(self, atom_labels=None, guess_element=True, ff_label="ff_map"): """ Breaks down LammpsData to building blocks (LammpsBox, ForceField and a series of Topology). RESTRICTIONS APPLIED: 1. No complex force field defined not just on atom ...
Constructor that parses a file.
def from_file(cls, filename, atom_style="full", sort_id=False): """ Constructor that parses a file. Args: filename (str): Filename to read. atom_style (str): Associated atom_style. Default to "full". sort_id (bool): Whether sort each section by id. Default to...
Constructor building LammpsData from a ForceField object and a list of Topology objects. Do not support intermolecular topologies since a Topology object includes data for ONE molecule or structure only.
def from_ff_and_topologies(cls, box, ff, topologies, atom_style="full"): """ Constructor building LammpsData from a ForceField object and a list of Topology objects. Do not support intermolecular topologies since a Topology object includes data for ONE molecule or structure only....
Simple constructor building LammpsData from a structure without force field parameters and topologies.
def from_structure(cls, structure, ff_elements=None, atom_style="charge"): """ Simple constructor building LammpsData from a structure without force field parameters and topologies. Args: structure (Structure): Input structure. ff_elements ([str]): List of string...
Another constructor that creates an instance from a molecule. Covalent bonds and other bond - based topologies ( angles and dihedrals ) can be automatically determined. Cannot be used for non bond - based topologies e. g. improper dihedrals.
def from_bonding(cls, molecule, bond=True, angle=True, dihedral=True, tol=0.1, **kwargs): """ Another constructor that creates an instance from a molecule. Covalent bonds and other bond-based topologies (angles and dihedrals) can be automatically determined. Cannot b...
Saves object to a file in YAML format.
def to_file(self, filename): """ Saves object to a file in YAML format. Args: filename (str): Filename. """ d = {"mass_info": self.mass_info, "nonbond_coeffs": self.nonbond_coeffs, "topo_coeffs": self.topo_coeffs} yaml = YAML(typ="s...
Constructor that reads in a file in YAML format.
def from_file(cls, filename): """ Constructor that reads in a file in YAML format. Args: filename (str): Filename. """ yaml = YAML(typ="safe") with open(filename, "r") as f: d = yaml.load(f) return cls.from_dict(d)
Read at most nlines lines from file filename. If nlines is < 0 the entire file is read.
def _read_nlines(filename, nlines): """ Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. """ if nlines < 0: with open(filename, 'r') as fh: return fh.readlines() lines = [] with open(filename, 'r') as fh: for lineno, line i...
Helper function to parse formatted text structured like:
def _dict_from_lines(lines, key_nums, sep=None): """ Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates the keys...
Convert string into integer
def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ float_num = float(string) int_num = int(float_num) if float_num == int_num: return int_num else: # Needed to handle pseudos with fractional charge ...
Convert obj into a pseudo. Accepts:
def as_pseudo(cls, obj): """ Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path. """ return obj if isinstance(obj, cls) else cls.from_file(obj)
String representation.
def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append app("<%s: %s>" % (self.__class__.__name__, self.basename)) app(" summary: " + self.summary.strip()) app(" number of valence electrons: %s" % self.Z_val) app(" maximum ang...
Pymatgen: class: Element.
def element(self): """Pymatgen :class:`Element`.""" try: return Element.from_Z(self.Z) except (KeyError, IndexError): return Element.from_Z(int(self.Z))
Compute and erturn MD5 hash value.
def compute_md5(self): """Compute and erturn MD5 hash value.""" import hashlib with open(self.path, "rt") as fh: text = fh.read() m = hashlib.md5(text.encode("utf-8")) return m.hexdigest()
Copy the pseudopotential to a temporary a file and returns a new pseudopotential object. Useful for unit tests in which we have to change the content of the file.
def as_tmpfile(self, tmpdir=None): """ Copy the pseudopotential to a temporary a file and returns a new pseudopotential object. Useful for unit tests in which we have to change the content of the file. Args: tmpdir: If None, a new temporary directory is created and files are...
The path of the djrepo file. None if file does not exist.
def djrepo_path(self): """The path of the djrepo file. None if file does not exist.""" root, ext = os.path.splitext(self.filepath) path = root + ".djrepo" return path