INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Looks for mirror symmetry of specified type about axis. Possible types are h or vd. Horizontal ( h ) mirrors are perpendicular to the axis while vertical ( v ) or diagonal ( d ) mirrors are parallel. v mirrors has atoms lying on the mirror plane while d mirrors do not.
def _find_mirror(self, axis): """ Looks for mirror symmetry of specified type about axis. Possible types are "h" or "vd". Horizontal (h) mirrors are perpendicular to the axis while vertical (v) or diagonal (d) mirrors are parallel. v mirrors has atoms lying on the mirror plane...
Returns the smallest list of atoms with the same species and distance from origin AND does not lie on the specified axis. This maximal set limits the possible rotational symmetry operations since atoms lying on a test axis is irrelevant in testing rotational symmetryOperations.
def _get_smallest_set_not_on_axis(self, axis): """ Returns the smallest list of atoms with the same species and distance from origin AND does not lie on the specified axis. This maximal set limits the possible rotational symmetry operations, since atoms lying on a test axis is i...
Determines the rotational symmetry about supplied axis. Used only for symmetric top molecules which has possible rotational symmetry operations > 2.
def _check_rot_sym(self, axis): """ Determines the rotational symmetry about supplied axis. Used only for symmetric top molecules which has possible rotational symmetry operations > 2. """ min_set = self._get_smallest_set_not_on_axis(axis) max_sym = len(min_set) ...
Checks for R2 axes perpendicular to unique axis. For handling symmetric top molecules.
def _check_perpendicular_r2_axis(self, axis): """ Checks for R2 axes perpendicular to unique axis. For handling symmetric top molecules. """ min_set = self._get_smallest_set_not_on_axis(axis) for s1, s2 in itertools.combinations(min_set, 2): test_axis = np.cr...
Handles Sperhical Top Molecules which belongs to the T O or I point groups.
def _proc_sph_top(self): """ Handles Sperhical Top Molecules, which belongs to the T, O or I point groups. """ self._find_spherical_axes() if len(self.rot_sym) == 0: logger.debug("Accidental speherical top!") self._proc_sym_top() main_axis,...
Looks for R5 R4 R3 and R2 axes in spherical top molecules. Point group T molecules have only one unique 3 - fold and one unique 2 - fold axis. O molecules have one unique 4 3 and 2 - fold axes. I molecules have a unique 5 - fold axis.
def _find_spherical_axes(self): """ Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point group T molecules have only one unique 3-fold and one unique 2-fold axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules have a unique 5-fold axis. """ ...
Check if a particular symmetry operation is a valid symmetry operation for a molecule i. e. the operation maps all atoms to another equivalent atom.
def is_valid_op(self, symmop): """ Check if a particular symmetry operation is a valid symmetry operation for a molecule, i.e., the operation maps all atoms to another equivalent atom. Args: symmop (SymmOp): Symmetry operation to test. Returns: (...
Calculates the dictionary for mapping equivalent atoms onto each other.
def _get_eq_sets(self): """ Calculates the dictionary for mapping equivalent atoms onto each other. Args: None Returns: dict: The returned dictionary has two possible keys: ``eq_sets``: A dictionary of indices mapping to sets of indices,...
Combines the dicts of _get_equivalent_atom_dicts into one
def _combine_eq_sets(eq_sets, operations): """Combines the dicts of _get_equivalent_atom_dicts into one Args: eq_sets (dict) operations (dict) Returns: dict: The returned dictionary has two possible keys: ``eq_sets``: A dictionary of...
Returns a symmetrized molecule
def symmetrize_molecule(self): """Returns a symmetrized molecule The equivalent atoms obtained via :meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms` are rotated, mirrored... unto one position. Then the average position is calculated. The average...
Given two sets of PeriodicSites test if they are actually symmetrically equivalent under this space group. Useful for example if you want to test if selecting atoms 1 and 2 out of a set of 4 atoms are symmetrically the same as selecting atoms 3 and 4 etc.
def are_symmetrically_equivalent(self, sites1, sites2, symm_prec=1e-3): """ Given two sets of PeriodicSites, test if they are actually symmetrically equivalent under this space group. Useful, for example, if you want to test if selecting atoms 1 and 2 out of a set of 4 atoms are...
Find the indices of matches of a particular coord in a coord_list.
def find_in_coord_list(coord_list, coord, atol=1e-8): """ Find the indices of matches of a particular coord in a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. ...
Tests if a particular coord is within a coord_list.
def in_coord_list(coord_list, coord, atol=1e-8): """ Tests if a particular coord is within a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. Returns: ...
Tests if all coords in subset are contained in superset. Doesn t use periodic boundary conditions
def is_coord_subset(subset, superset, atol=1e-8): """ Tests if all coords in subset are contained in superset. Doesn't use periodic boundary conditions Args: subset, superset: List of coords Returns: True if all of subset is in superset. """ c1 = np.array(subset) c2 = n...
Gives the index mapping from a subset to a superset. Subset and superset cannot contain duplicate rows
def coord_list_mapping(subset, superset, atol=1e-8): """ Gives the index mapping from a subset to a superset. Subset and superset cannot contain duplicate rows Args: subset, superset: List of coords Returns: list of indices such that superset[indices] = subset """ c1 = np.a...
Gives the index mapping from a subset to a superset. Superset cannot contain duplicate matching rows
def coord_list_mapping_pbc(subset, superset, atol=1e-8): """ Gives the index mapping from a subset to a superset. Superset cannot contain duplicate matching rows Args: subset, superset: List of frac_coords Returns: list of indices such that superset[indices] = subset """ at...
Returns an interpolated value by linear interpolation between two values. This method is written to avoid dependency on scipy which causes issues on threading servers.
def get_linear_interpolated_value(x_values, y_values, x): """ Returns an interpolated value by linear interpolation between two values. This method is written to avoid dependency on scipy, which causes issues on threading servers. Args: x_values: Sequence of x values. y_values: Corr...
Returns the distances between two lists of coordinates
def all_distances(coords1, coords2): """ Returns the distances between two lists of coordinates Args: coords1: First set of cartesian coordinates. coords2: Second set of cartesian coordinates. Returns: 2d array of cartesian distances. E.g the distance between coords1[i]...
Returns the fractional distance between two coordinates taking into account periodic boundary conditions.
def pbc_diff(fcoords1, fcoords2): """ Returns the 'fractional distance' between two coordinates taking into account periodic boundary conditions. Args: fcoords1: First set of fractional coordinates. e.g., [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single ...
Get the indices of all points in a fractional coord list that are equal to a fractional coord ( with a tolerance ) taking into account periodic boundary conditions.
def find_in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8): """ Get the indices of all points in a fractional coord list that are equal to a fractional coord (with a tolerance), taking into account periodic boundary conditions. Args: fcoord_list: List of fractional coords fcoord: A ...
Tests if a particular fractional coord is within a fractional coord_list.
def in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8): """ Tests if a particular fractional coord is within a fractional coord_list. Args: fcoord_list: List of fractional coords to test fcoord: A specific fractional coord to test. atol: Absolute tolerance. Defaults to 1e-8. Ret...
Tests if all fractional coords in subset are contained in superset.
def is_coord_subset_pbc(subset, superset, atol=1e-8, mask=None): """ Tests if all fractional coords in subset are contained in superset. Args: subset, superset: List of fractional coords atol (float or size 3 array): Tolerance for matching mask (boolean array): Mask of matches that ...
Returns the list of points on the original lattice contained in the supercell in fractional coordinates ( with the supercell basis ). e. g. [[ 2 0 0 ] [ 0 1 0 ] [ 0 0 1 ]] returns [[ 0 0 0 ] [ 0. 5 0 0 ]]
def lattice_points_in_supercell(supercell_matrix): """ Returns the list of points on the original lattice contained in the supercell in fractional coordinates (with the supercell basis). e.g. [[2,0,0],[0,1,0],[0,0,1]] returns [[0,0,0],[0.5,0,0]] Args: supercell_matrix: 3x3 matrix describing...
Converts a list of coordinates to barycentric coordinates given a simplex with d + 1 points. Only works for d > = 2.
def barycentric_coords(coords, simplex): """ Converts a list of coordinates to barycentric coordinates, given a simplex with d+1 points. Only works for d >= 2. Args: coords: list of n coords to transform, shape should be (n,d) simplex: list of coordinates that form the simplex, shape sh...
Calculates the angle between two vectors.
def get_angle(v1, v2, units="degrees"): """ Calculates the angle between two vectors. Args: v1: Vector 1 v2: Vector 2 units: "degrees" or "radians". Defaults to "degrees". Returns: Angle between them in degrees. """ d = np.dot(v1, v2) / np.linalg.norm(v1) / np.l...
Volume of the simplex.
def volume(self): """ Volume of the simplex. """ return abs(np.linalg.det(self._aug)) / math.factorial(self.simplex_dim)
Computes the intersection points of a line with a simplex Args: point1 point2 ( [ float ] ): Points that determine the line Returns: points where the line intersects the simplex ( 0 1 or 2 )
def line_intersection(self, point1, point2, tolerance=1e-8): """ Computes the intersection points of a line with a simplex Args: point1, point2 ([float]): Points that determine the line Returns: points where the line intersects the simplex (0, 1, or 2) """...
Use pybtex to validate that a reference is in proper BibTeX format
def is_valid_bibtex(reference): """ Use pybtex to validate that a reference is in proper BibTeX format Args: reference: A String reference in BibTeX format. Returns: Boolean indicating if reference is valid bibtex. """ # str is necessary since pybtex seems to have an issue with...
Parses a History Node object from either a dict or a tuple.
def parse_history_node(h_node): """ Parses a History Node object from either a dict or a tuple. Args: h_node: A dict with name/url/description fields or a 3-element tuple. Returns: History node. """ if isinstance(h_node, dict): ...
Parses an Author object from either a String dict or tuple
def parse_author(author): """ Parses an Author object from either a String, dict, or tuple Args: author: A String formatted as "NAME <email@domain.com>", (name, email) tuple, or a dict with name and email keys. Returns: An Author object. ...
A convenience method for getting a list of StructureNL objects by specifying structures and metadata separately. Some of the metadata is applied to all of the structures for ease of use.
def from_structures(cls, structures, authors, projects=None, references='', remarks=None, data=None, histories=None, created_at=None): """ A convenience method for getting a list of StructureNL objects by specifying structures and metadata separate...
This function converts a strain to a deformation gradient that will produce that strain. Supports three methods:
def convert_strain_to_deformation(strain, shape="upper"): """ This function converts a strain to a deformation gradient that will produce that strain. Supports three methods: Args: strain (3x3 array-like): strain matrix shape: (string): method for determining deformation, supports ...
Gets indices of perturbed elements of the deformation gradient i. e. those that differ from the identity
def get_perturbed_indices(self, tol=1e-8): """ Gets indices of perturbed elements of the deformation gradient, i. e. those that differ from the identity """ indices = list(zip(*np.where(abs(self - np.eye(3)) > tol))) return indices
Apply the deformation gradient to a structure.
def apply_to_structure(self, structure): """ Apply the deformation gradient to a structure. Args: structure (Structure object): the structure object to be modified by the deformation """ def_struct = structure.copy() old_latt = def_struct.latt...
Factory method for constructing a Deformation object from a matrix position and amount
def from_index_amount(cls, matrixpos, amt): """ Factory method for constructing a Deformation object from a matrix position and amount Args: matrixpos (tuple): tuple corresponding the matrix position to have a perturbation added amt (float): amoun...
Factory method that returns a Strain object from a deformation gradient
def from_deformation(cls, deformation): """ Factory method that returns a Strain object from a deformation gradient Args: deformation (3x3 array-like): """ dfm = Deformation(deformation) return cls(0.5 * (np.dot(dfm.trans, dfm) - np.eye(3)))
Like Deformation. from_index_amount except generates a strain from the zero 3x3 tensor or voigt vector with the amount specified in the index location. Ensures symmetric strain.
def from_index_amount(cls, idx, amount): """ Like Deformation.from_index_amount, except generates a strain from the zero 3x3 tensor or voigt vector with the amount specified in the index location. Ensures symmetric strain. Args: idx (tuple or integer): index...
Equivalent strain to Von Mises Stress
def von_mises_strain(self): """ Equivalent strain to Von Mises Stress """ eps = self - 1/3 * np.trace(self) * np.identity(3) return np.sqrt(np.sum(eps * eps) * 2/3)
Prepare for display on plots ( hkl ) for surfaces Agrs: hkl: in the form of [ h k l ] or ( h k l )
def hkl_tuple_to_str(hkl): """ Prepare for display on plots "(hkl)" for surfaces Agrs: hkl: in the form of [h, k, l] or (h, k, l) """ str_format = '($' for x in hkl: if x < 0: str_format += '\\overline{' + str(-x) + '}' else: str_format += str(...
Given a list of coords for 3 points Compute the area of this triangle.
def get_tri_area(pts): """ Given a list of coords for 3 points, Compute the area of this triangle. Args: pts: [a, b, c] three points """ a, b, c = pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a) v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, ...
from self: get miller_list ( unique_miller ) e_surf_list and symmetry operations ( symmops ) according to lattice apply symmops to get all the miller index then get normal get all the facets functions for wulff shape calculation: |normal| = 1 e_surf is plane s distance to ( 0 0 0 ) normal [ 0 ] x + normal [ 1 ] y + nor...
def _get_all_miller_e(self): """ from self: get miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according to lattice apply symmops to get all the miller index, then get normal, get all the facets functions for wulff shape calculation: ...
|normal| = 1 e_surf is plane s distance to ( 0 0 0 ) plane function: normal [ 0 ] x + normal [ 1 ] y + normal [ 2 ] z = e_surf
def _get_cross_pt_dual_simp(self, dual_simp): """ |normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices from...
Locate the plane for simpx of on wulff_cv by comparing the center of the simpx triangle with the plane functions.
def _get_simpx_plane(self): """ Locate the plane for simpx of on wulff_cv, by comparing the center of the simpx triangle with the plane functions. """ on_wulff = [False] * len(self.miller_list) surface_area = [0.0] * len(self.miller_list) for simpx in self.wulff_c...
assign colors according to the surface energies of on_wulff facets.
def _get_colors(self, color_set, alpha, off_color, custom_colors={}): """ assign colors according to the surface energies of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) """ import matplot...
Returns the sorted pts in a facet used to draw a line
def get_line_in_facet(self, facet): """ Returns the sorted pts in a facet used to draw a line """ lines = list(facet.outer_lines) pt = [] prev = None while len(lines) > 0: if prev is None: l = lines.pop(0) else: ...
Get the Wulff shape plot.
def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): """ ...
Args: miller_index: viewing direction
def _get_azimuth_elev(self, miller_index): """ Args: miller_index: viewing direction Returns: azim, elev for plotting """ if miller_index == (0, 0, 1) or miller_index == (0, 0, 0, 1): return 0, 90 else: cart = self.lattice....
Returns: ( dict ): { hkl: area_hkl/ total area on wulff }
def area_fraction_dict(self): """ Returns: (dict): {hkl: area_hkl/total area on wulff} """ return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()}
Returns: ( float ) Coefficient of Variation from weighted surface energy The ideal sphere is 0.
def anisotropy(self): """ Returns: (float) Coefficient of Variation from weighted surface energy The ideal sphere is 0. """ square_diff_energy = 0 weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict mille...
Total surface energy of the Wulff shape.
def total_surface_energy(self): """ Total surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) """ tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hk...
Returns the number of edges in the convex hull. Useful for identifying catalytically active sites.
def tot_edges(self): """ Returns the number of edges in the convex hull. Useful for identifying catalytically active sites. """ all_edges = [] for facet in self.facets: edges = [] pt = self.get_line_in_facet(facet) lines = [] ...
Construct SpaceGroupTransformation from its transformation string.: param P: matrix: param p: origin shift vector: return:
def from_transformation_string(cls, transformation_string="a,b,c;0,0,0"): """ Construct SpaceGroupTransformation from its transformation string. :param P: matrix :param p: origin shift vector :return: """ P, p = JonesFaithfulTransformation.parse_transformation_str...
: return: JonesFaithfulTransformation
def inverse(self): # type: () -> JonesFaithfulTransformation """ :return: JonesFaithfulTransformation """ Q = np.linalg.inv(self.P) return JonesFaithfulTransformation(Q, -np.matmul(Q, self.p))
Takes a symmetry operation and transforms it.: param symmop: SymmOp or MagSymmOp: return:
def transform_symmop(self, symmop): # type: (Union[SymmOp, MagSymmOp]) -> Union[SymmOp, MagSymmOp] """ Takes a symmetry operation and transforms it. :param symmop: SymmOp or MagSymmOp :return: """ W = symmop.rotation_matrix w = symmop.translation_vector ...
Takes a list of co - ordinates and transforms them.: param coords: List of coords: return:
def transform_coords(self, coords): # type: (List[List[float]]) -> List[List[float]] """ Takes a list of co-ordinates and transforms them. :param coords: List of coords :return: """ new_coords = [] for x in coords: x = np.array(x) ...
Takes a Lattice object and transforms it.: param lattice: Lattice: return:
def transform_lattice(self, lattice): # type: (Lattice) -> Lattice """ Takes a Lattice object and transforms it. :param lattice: Lattice :return: """ return Lattice(np.matmul(lattice.matrix, self.P))
Finds the element from allowed elements that ( i ) possesses the desired oxidation state and ( ii ) is closest in ionic radius to the target specie
def _find_codopant(target, oxidation_state, allowed_elements=None): """ Finds the element from "allowed elements" that (i) possesses the desired "oxidation state" and (ii) is closest in ionic radius to the target specie Args: target: (Specie) provides target ionic radius. oxidation_stat...
Return either a single ordered structure or a sequence of all ordered structures.
def apply_transformation(self, structure, return_ranked_list=False): """ Return either a single ordered structure or a sequence of all ordered structures. Args: structure: Structure to order. return_ranked_list (bool): Whether or not multiple structures are ...
Checks if a periodic site satisfies the constraint.
def satisfies_constraint(self, site): """ Checks if a periodic site satisfies the constraint. """ if not site.is_ordered: return False if self.species_constraints \ and str(site.specie) in self.species_constraints: satisfies_constraints = ...
Determine the smallest supercell that is able to enumerate the provided structure with the given order parameter
def determine_min_cell(disordered_structure): """ Determine the smallest supercell that is able to enumerate the provided structure with the given order parameter """ def lcm(n1, n2): """ Find least common multiple of two numbers """ ...
: param structure: ordered Structure: param order_parameters: list of MagOrderParameterConstraints: return: A structure decorated with disordered DummySpecies on which to perform the enumeration. Note that the DummySpecies are super - imposed on to the original sites to make it easier to retrieve the original site afte...
def _add_dummy_species(structure, order_parameters): """ :param structure: ordered Structure :param order_parameters: list of MagOrderParameterConstraints :return: A structure decorated with disordered DummySpecies on which to perform the enumeration. Note that the DummyS...
: return: Structure with dummy species removed but their corresponding spin properties merged with the original sites. Used after performing enumeration.
def _remove_dummy_species(structure): """ :return: Structure with dummy species removed, but their corresponding spin properties merged with the original sites. Used after performing enumeration. """ if not structure.is_ordered: raise Exception("Something went...
Replaces Spin. up/ Spin. down with spin magnitudes specified by mag_species_spin.: param structure:: return:
def _add_spin_magnitudes(self, structure): """ Replaces Spin.up/Spin.down with spin magnitudes specified by mag_species_spin. :param structure: :return: """ for idx, site in enumerate(structure): if getattr(site.specie, '_properties', None): ...
Apply MagOrderTransformation to an input structure.: param structure: Any ordered structure.: param return_ranked_list: As in other Transformations.: return:
def apply_transformation(self, structure, return_ranked_list=False): """ Apply MagOrderTransformation to an input structure. :param structure: Any ordered structure. :param return_ranked_list: As in other Transformations. :return: """ if not structure.is_ordered:...
Args: structure ( Structure ): Input structure to dope
def apply_transformation(self, structure, return_ranked_list=False): """ Args: structure (Structure): Input structure to dope Returns: [{"structure": Structure, "energy": float}] """ comp = structure.composition logger.info("Composition: %s" % com...
Args: structure: ordered structure return_ranked_list: as in other pymatgen Transformations
def apply_transformation(self, structure, return_ranked_list=False): """ Args: structure: ordered structure return_ranked_list: as in other pymatgen Transformations Returns: transformed disordered structure(s) """ if not structure.is_ordered: ...
Private method to split a list of species into various partitions.
def _partition_species(composition, max_components=2): """ Private method to split a list of species into various partitions. """ def _partition(collection): # thanks https://stackoverflow.com/a/30134039 if len(collection) == 1: yield [co...
Private method to obtain the mapping to create a disordered structure from a given partition.
def _get_disorder_mappings(composition, partitions): """ Private method to obtain the mapping to create a disordered structure from a given partition. """ def _get_replacement_dict_from_partition(partition): d = {} # to be passed to Structure.replace_species() ...
helper to clean up an input string
def clean(some_string, uppercase=False): """ helper to clean up an input string """ if uppercase: return some_string.strip().upper() else: return some_string.strip().lower()
Read the results of a full set of calculations from file
def read_grid_from_file(filename): """ Read the results of a full set of calculations from file """ try: f = open(filename, mode='r') full_res = ast.literal_eval(f.read()) f.close() except SyntaxError: print('Problems reading ', filename) full_res = {'grid': 0...
performs a structure prediction targeting compounds containing all of the target_species based on a list of structure ( those structures can for instance come from a database like the ICSD ). It will return all the structures formed by ionic substitutions with a probability higher than the threshold
def pred_from_structures(self, target_species, structures_list, remove_duplicates=True, remove_existing=False): """ performs a structure prediction targeting compounds containing all of the target_species, based on a list of structure (those structures can fo...
checks if the structure object is charge balanced
def _is_charge_balanced(struct): """ checks if the structure object is charge balanced """ if sum([s.specie.oxi_state for s in struct.sites]) == 0.0: return True else: return False
checks if the structure object is from the given chemical system
def _is_from_chemical_system(chemical_system, struct): """ checks if the structure object is from the given chemical system """ chemsys = list(set([sp.symbol for sp in struct.composition])) if len(chemsys) != len(chemical_system): return False for el in chemsy...
There are an exceptionally large number of substitutions to look at ( 260^n ) where n is the number of species in the list. We need a more efficient than brute force way of going through these possibilities. The brute force method would be::
def pred_from_list(self, species_list): """ There are an exceptionally large number of substitutions to look at (260^n), where n is the number of species in the list. We need a more efficient than brute force way of going through these possibilities. The brute force method would ...
Similar to pred_from_list except this method returns a list after checking that compositions are charge balanced.
def pred_from_comp(self, composition): """ Similar to pred_from_list except this method returns a list after checking that compositions are charge balanced. """ output = [] predictions = self.pred_from_list(composition.elements) for p in predictions: s...
Provides a publication quality plot with nice defaults for font sizes etc.
def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=("qualitative", "Set1_9")): """ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in ...
Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib examples. Makes it easier to create plots with different axes.
def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None, width=8, height=None, dpi=300): """ Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib examples. Makes it easier to create plots with different axes. Args: x (np.ndarray...
Convenience method to plot data with trend lines based on polynomial fit.
def pretty_polyfit_plot(x, y, deg=1, xlabel=None, ylabel=None, **kwargs): """ Convenience method to plot data with trend lines based on polynomial fit. Args: x: Sequence of x data. y: Sequence of y data. deg (int): Degree of polynomial. Defaults to 1. xlabel (str): Label for...
A static method that generates a heat map overlapped on a periodic table.
def periodic_table_heatmap(elemental_data, cbar_label="", show_plot=False, cmap="YlOrRd", blank_color="grey", value_format=None, max_row=9): """ A static method that generates a heat map overlapped on a periodic table. Args: elemental_data (dic...
Converts str of chemical formula into latex format for labelling purposes
def format_formula(formula): """ Converts str of chemical formula into latex format for labelling purposes Args: formula (str): Chemical formula """ formatted_formula = "" number_format = "" for i, s in enumerate(formula): if s.isdigit(): if not number_forma...
A static method that generates a binary van Arkel - Ketelaar triangle to quantify the ionic metallic and covalent character of a compound by plotting the electronegativity difference ( y ) vs average ( x ). See: A. E. van Arkel Molecules and Crystals in Inorganic Chemistry Interscience New York ( 1956 ) and J. A. A Ket...
def van_arkel_triangle(list_of_materials, annotate=True): """ A static method that generates a binary van Arkel-Ketelaar triangle to quantify the ionic, metallic and covalent character of a compound by plotting the electronegativity difference (y) vs average (x). See: A.E. va...
Helper function used in plot functions supporting an optional Axes argument. If ax is None we build the matplotlib figure and create the Axes else we return the current active figure.
def get_ax_fig_plt(ax=None, **kwargs): """ Helper function used in plot functions supporting an optional Axes argument. If ax is None, we build the `matplotlib` figure and create the Axes else we return the current active figure. Args: kwargs: keyword arguments are passed to plt.figure if a...
Helper function used in plot functions supporting an optional Axes3D argument. If ax is None we build the matplotlib figure and create the Axes3D else we return the current active figure.
def get_ax3d_fig_plt(ax=None, **kwargs): """ Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. Args: kwargs: keyword arguments are passed to plt.figur...
Helper function used in plot functions that accept an optional array of Axes as argument. If ax_array is None we build the matplotlib figure and create the array of Axes by calling plt. subplots else we return the current active figure.
def get_axarray_fig_plt(ax_array, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ Helper function used in plot functions that accept an optional array of Axes as argument. If ax_array is None, we bu...
Decorator that adds keyword arguments for functions returning matplotlib figures.
def add_fig_kwargs(func): """ Decorator that adds keyword arguments for functions returning matplotlib figures. The function should return either a matplotlib figure or None to signal some sort of error/unexpected event. See doc string below for the list of supported options. """ from f...
Method to sum two densities.
def add_densities(density1, density2): """ Method to sum two densities. Args: density1: First density. density2: Second density. Returns: Dict of {spin: density}. """ return {spin: np.array(density1[spin]) + np.array(density2[spin]) for spin in density1.keys...
Returns the equilibrium fermi - dirac. Args: E ( float ): energy in eV fermi ( float ): the fermi level in eV T ( float ): the temperature in kelvin
def f0(E, fermi, T): """ Returns the equilibrium fermi-dirac. Args: E (float): energy in eV fermi (float): the fermi level in eV T (float): the temperature in kelvin """ return 1. / (1. + np.exp((E - fermi) / (_cd("Boltzmann constant in eV/K") * T)))
Args: orb: string representation of orbital Returns: OrbitalType
def _get_orb_type_lobster(orb): """ Args: orb: string representation of orbital Returns: OrbitalType """ orb_labs = ["s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2", "d_xz", "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz", "f_yz^2", "f_z^3", "f_xz^2", "f_z(x^2-y^2)"...
Args: orb: string representation of orbital Returns: Orbital
def _get_orb_lobster(orb): """ Args: orb: string representation of orbital Returns: Orbital """ orb_labs = ["s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2", "d_xz", "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz", "f_yz^2", "f_z^3", "f_xz^2", "f_z(x^2-y^2)", ...
Expects a DOS object and finds the gap
def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. ...
Expects a DOS object and finds the cbm and vbm.
def get_cbm_vbm(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the cbm and vbm. Args: tol: tolerance in occupations for determining the gap abs_tol: An absolute tolerance (True) and a relative one (False) spin: Possible values ...
Expects a DOS object and finds the gap.
def get_gap(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the gap. Args: tol: tolerance in occupations for determining the gap abs_tol: An absolute tolerance (True) and a relative one (False) spin: Possible values are None - f...
Returns the density of states for a particular spin.
def get_densities(self, spin=None): """ Returns the density of states for a particular spin. Args: spin: Spin Returns: Returns the density of states for a particular spin. If Spin is None, the sum of all spins is returned. """ if self...
Returns the Dict representation of the densities { Spin: densities } but with a Gaussian smearing of std dev sigma applied about the fermi level.
def get_smeared_densities(self, sigma): """ Returns the Dict representation of the densities, {Spin: densities}, but with a Gaussian smearing of std dev sigma applied about the fermi level. Args: sigma: Std dev of Gaussian smearing function. Returns: ...
Returns interpolated density for a particular energy.
def get_interpolated_value(self, energy): """ Returns interpolated density for a particular energy. Args: energy: Energy to return the density for. """ f = {} for spin in self.densities.keys(): f[spin] = get_linear_interpolated_value(self.energies...
Expects a DOS object and finds the cbm and vbm.
def get_cbm_vbm(self, tol=0.001, abs_tol=False, spin=None): """ Expects a DOS object and finds the cbm and vbm. Args: tol: tolerance in occupations for determining the gap abs_tol: An absolute tolerance (True) and a relative one (False) spin: Possible values ...
Returns Dos object from dict representation of Dos.
def from_dict(cls, d): """ Returns Dos object from dict representation of Dos. """ return Dos(d["efermi"], d["energies"], {Spin(int(k)): v for k, v in d["densities"].items()})
Json - serializable dict representation of Dos.
def as_dict(self): """ Json-serializable dict representation of Dos. """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "efermi": self.efermi, "energies": list(self.energies), "densities": {str(spin): list(...
Calculate the doping ( majority carrier concentration ) at a given fermi level and temperature. A simple Left Riemann sum is used for integrating the density of states over energy & equilibrium Fermi - Dirac distribution
def get_doping(self, fermi, T): """ Calculate the doping (majority carrier concentration) at a given fermi level and temperature. A simple Left Riemann sum is used for integrating the density of states over energy & equilibrium Fermi-Dirac distribution Args: fermi (f...
Similar to get_fermi except that when get_fermi fails to converge an interpolated or extrapolated fermi ( depending on c ) is returned with the assumption that the fermi level changes linearly with log ( abs ( c )).
def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=1e10, **kwargs): """ Similar to get_fermi except that when get_fermi fails to converge, an interpolated or extrapolated fermi (depending on c) is returned with the assumption that the fermi level changes linearly with log(abs(c...