INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
generates a list of similar artists in lastfm by utiliizing the similar_items api of the models
def calculate_similar_artists(output_filename, model_name="als"): """ generates a list of similar artists in lastfm by utiliizing the 'similar_items' api of the models """ artists, users, plays = get_lastfm() # create a model from the input data model = get_model(model_name) # if we're trainin...
Generates artist recommendations for each user in the dataset
def calculate_recommendations(output_filename, model_name="als"): """ Generates artist recommendations for each user in the dataset """ # train the model based off input params artists, users, plays = get_lastfm() # create a model from the input data model = get_model(model_name) # if we're tr...
Returns either an ion object or composition object given a formula.
def ion_or_solid_comp_object(formula): """ Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object """ m = re.search(r"\[(...
Generates a label for the pourbaix plotter
def generate_entry_label(entry): """ Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for """ if isinstance(entry, MultiEntry): return " + ".join([latexify_ion(e.name) for e in entry.entry_list]) else: return late...
Get free energy for a given pH and V
def energy_at_conditions(self, pH, V): """ Get free energy for a given pH and V Args: pH (float): pH at which to evaluate free energy V (float): voltage at which to evaluate free energy Returns: free energy at conditions """ return se...
Energy at an electrochemical condition compatible with numpy arrays for pH/ V input
def normalized_energy_at_conditions(self, pH, V): """ Energy at an electrochemical condition, compatible with numpy arrays for pH/V input Args: pH (float): pH at condition V (float): applied potential at condition Returns: energy normalized b...
Returns dict which contains Pourbaix Entry data. Note that the pH voltage H2O factors are always calculated when constructing a PourbaixEntry object.
def as_dict(self): """ Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} ...
Invokes
def from_dict(cls, d): """ Invokes """ entry_type = d["entry_type"] if entry_type == "Ion": entry = IonEntry.from_dict(d["entry"]) else: entry = PDEntry.from_dict(d["entry"]) entry_id = d["entry_id"] concentration = d["concentration...
Sum of number of atoms minus the number of H and O in composition
def normalization_factor(self): """ Sum of number of atoms minus the number of H and O in composition """ return 1.0 / (self.num_atoms - self.composition.get('H', 0) - self.composition.get('O', 0))
Returns an IonEntry object from a dict.
def from_dict(cls, d): """ Returns an IonEntry object from a dict. """ return IonEntry(Ion.from_dict(d["ion"]), d["energy"], d.get("name", None))
Creates a dict of composition energy and ion name
def as_dict(self): """ Creates a dict of composition, energy, and ion name """ d = {"ion": self.ion.as_dict(), "energy": self.energy, "name": self.name} return d
Create entries for multi - element Pourbaix construction.
def _generate_multielement_entries(self, entries, forced_include=None, nproc=None): """ Create entries for multi-element Pourbaix construction. This works by finding all possible linear combinations of entries that can result in the specified compo...
Static method for finding a multientry based on a list of entries and a product composition. Essentially checks to see if a valid aqueous reaction exists between the entries and the product composition and returns a MultiEntry with weights according to the coefficients if so.
def process_multientry(entry_list, prod_comp, coeff_threshold=1e-4): """ Static method for finding a multientry based on a list of entries and a product composition. Essentially checks to see if a valid aqueous reaction exists between the entries and the product compositi...
Returns a set of pourbaix stable domains ( i. e. polygons ) in pH - V space from a list of pourbaix_entries
def get_pourbaix_domains(pourbaix_entries, limits=None): """ Returns a set of pourbaix stable domains (i. e. polygons) in pH-V space from a list of pourbaix_entries This function works by using scipy's HalfspaceIntersection function to construct all of the 2-D polygons that form...
Finds stable entry at a pH V condition Args: pH ( float ): pH to find stable entry V ( float ): V to find stable entry
def find_stable_entry(self, pH, V): """ Finds stable entry at a pH,V condition Args: pH (float): pH to find stable entry V (float): V to find stable entry Returns: """ energies_at_conditions = [e.normalized_energy_at_conditions(pH, V) ...
Finds decomposition to most stable entry
def get_decomposition_energy(self, entry, pH, V): """ Finds decomposition to most stable entry Args: entry (PourbaixEntry): PourbaixEntry corresponding to compound to find the decomposition for pH (float): pH at which to find the decomposition ...
Shows the pourbaix plot
def show(self, *args, **kwargs): """ Shows the pourbaix plot Args: *args: args to get_pourbaix_plot **kwargs: kwargs to get_pourbaix_plot Returns: None """ plt = self.get_pourbaix_plot(*args, **kwargs) plt.show()
Plot Pourbaix diagram.
def get_pourbaix_plot(self, limits=None, title="", label_domains=True, plt=None): """ Plot Pourbaix diagram. Args: limits: 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]] title (str): Title ...
Json - serializable dict representation.
def as_dict(self): """ Json-serializable dict representation. """ d = MSONable.as_dict(self) d["translation_vector"] = self.translation_vector.tolist() return d
This method uses the matrix form of ewaldsum to calculate the ewald sums of the potential structures. This is on the order of 4 orders of magnitude faster when there are large numbers of permutations to consider. There are further optimizations possible ( doing a smarter search of permutations for example ) but this wo...
def fast_ordering(self, structure, num_remove_dict, num_to_return=1): """ This method uses the matrix form of ewaldsum to calculate the ewald sums of the potential structures. This is on the order of 4 orders of magnitude faster when there are large numbers of permutations to con...
Apply the transformation.
def apply_transformation(self, structure, return_ranked_list=False): """ Apply the transformation. Args: structure: input structure return_ranked_list (bool): Whether or not multiple structures are returned. If return_ranked_list is a number, that number ...
apply the transformation Args: structure ( Structure ): structure to add site properties to
def apply_transformation(self, structure): """ apply the transformation Args: structure (Structure): structure to add site properties to """ new_structure = structure.copy() for prop in self.site_properties.keys(): new_structure.add_site_p...
Writes input files for a LAMMPS run. Input script is constructed from a str template with placeholders to be filled by custom settings. Data file is either written from a LammpsData instance or copied from an existing file if read_data cmd is inspected in the input script. Other supporting files are not handled at the ...
def write_lammps_inputs(output_dir, script_template, settings=None, data=None, script_filename="in.lammps", make_dir_if_not_present=True, **kwargs): """ Writes input files for a LAMMPS run. Input script is constructed from a str template with placeholders to b...
Writes all input files ( input script and data if needed ). Other supporting files are not handled at this moment.
def write_inputs(self, output_dir, **kwargs): """ Writes all input files (input script, and data if needed). Other supporting files are not handled at this moment. Args: output_dir (str): Directory to output the input files. **kwargs: kwargs supported by LammpsDa...
Example for a simple MD run based on template md. txt.
def md(cls, data, force_field, temperature, nsteps, other_settings=None): """ Example for a simple MD run based on template md.txt. Args: data (LammpsData or str): Data file as a LammpsData instance or path to an existing data file. force_field...
Args: a1 a2 a3: lattice vectors in bohr encut: energy cut off in eV Returns: reciprocal lattice vectors with energy less than encut
def genrecip(a1, a2, a3, encut): """ Args: a1, a2, a3: lattice vectors in bohr encut: energy cut off in eV Returns: reciprocal lattice vectors with energy less than encut """ vol = np.dot(a1, np.cross(a2, a3)) # 1/bohr^3 b1 = (2 * np.pi / vol) * np.cross(a2, a3) # units...
Generate reciprocal vector magnitudes within the cutoff along the specied lattice vectors. Args: a1: Lattice vector a ( in Bohrs ) a2: Lattice vector b ( in Bohrs ) a3: Lattice vector c ( in Bohrs ) encut: Reciprocal vector energy cutoff
def generate_reciprocal_vectors_squared(a1, a2, a3, encut): """ Generate reciprocal vector magnitudes within the cutoff along the specied lattice vectors. Args: a1: Lattice vector a (in Bohrs) a2: Lattice vector b (in Bohrs) a3: Lattice vector c (in Bohrs) encut: Reciproc...
Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: ( site object dist index )
def closestsites(struct_blk, struct_def, pos): """ Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) """ blk_close_sites = struc...
simple newton iteration based convergence function
def converge(f, step, tol, max_h): """ simple newton iteration based convergence function """ g = f(0) dx = 10000 h = step while (dx > tol): g2 = f(h) dx = abs(g - g2) g = g2 h += step if h > max_h: raise Exception("Did not converge before...
Reciprocal space model charge value for input squared reciprocal vector. Args: g2: Square of reciprocal vector
def rho_rec(self, g2): """ Reciprocal space model charge value for input squared reciprocal vector. Args: g2: Square of reciprocal vector Returns: Charge density at the reciprocal vector magnitude """ return (self.expnorm / np.sqrt(1 + sel...
Reciprocal space model charge value close to reciprocal vector 0. rho_rec ( g - > 0 ) - > 1 + rho_rec_limit0 * g^2
def rho_rec_limit0(self): """ Reciprocal space model charge value close to reciprocal vector 0 . rho_rec(g->0) -> 1 + rho_rec_limit0 * g^2 """ return -2 * self.gamma2 * self.expnorm - 0.25 * self.beta2 * ( 1 - self.expnorm)
Generate a sequence of supercells in which each supercell contains a single interstitial except for the first supercell in the sequence which is a copy of the defect - free input structure.
def make_supercells_with_defects(self, scaling_matrix): """ Generate a sequence of supercells in which each supercell contains a single interstitial, except for the first supercell in the sequence which is a copy of the defect-free input structure. Args: scal...
Cluster nodes that are too close together using a tol.
def cluster_nodes(self, tol=0.2): """ Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC is taken into account. """ lattice = self.structure.lattice vfcoords = [v.frac_coords for v in self.vnodes] # M...
Remove vnodes that are too close to existing atoms in the structure
def remove_collisions(self, min_dist=0.5): """ Remove vnodes that are too close to existing atoms in the structure Args: min_dist(float): The minimum distance that a vertex needs to be from existing atoms. """ vfcoords = [v.frac_coords for v in self.v...
Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X.
def get_structure_with_nodes(self): """ Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X. """ new_s = Structure.from_sites(self.structure) for v in self.vnodes: new_s.append("X", v.frac_coords) return ne...
Return a complete table of fractional coordinates - charge density.
def _get_charge_distribution_df(self): """ Return a complete table of fractional coordinates - charge density. """ # Fraction coordinates and corresponding indices axis_grid = np.array([np.array(self.chgcar.get_axis_grid(i)) / self.structure.lattice....
Update _extrema_df extrema_type and extrema_coords
def _update_extrema(self, f_coords, extrema_type, threshold_frac=None, threshold_abs=None): """Update _extrema_df, extrema_type and extrema_coords""" if threshold_frac is not None: if threshold_abs is not None: logger.warning( # Exit if both filter a...
Get all local extrema fractional coordinates in charge density searching for local minimum by default. Note that sites are NOT grouped symmetrically.
def get_local_extrema(self, find_min=True, threshold_frac=None, threshold_abs=None): """ Get all local extrema fractional coordinates in charge density, searching for local minimum by default. Note that sites are NOT grouped symmetrically. Args: ...
Cluster nodes that are too close together using a tol.
def cluster_nodes(self, tol=0.2): """ Cluster nodes that are too close together using a tol. Args: tol (float): A distance tolerance. PBC is taken into account. """ lattice = self.structure.lattice vf_coords = self.extrema_coords if len(vf_coords) ==...
Remove predicted sites that are too close to existing atoms in the structure.
def remove_collisions(self, min_dist=0.5): """ Remove predicted sites that are too close to existing atoms in the structure. Args: min_dist (float): The minimum distance (in Angstrom) that a predicted site needs to be from existing atoms. A min_dist ...
Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X.
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): """ Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_mi...
Get the average charge density around each local minima in the charge density and store the result in _extrema_df Args: r ( float ): radius of sphere around each site to evaluate the average
def sort_sites_by_integrated_chg(self, r=0.4): """ Get the average charge density around each local minima in the charge density and store the result in _extrema_df Args: r (float): radius of sphere around each site to evaluate the average """ if self.extrema...
Parses a QChem output file with multiple calculations 1. ) Seperates the output into sub - files e. g. qcout - > qcout. 0 qcout. 1 qcout. 2... qcout. N a. ) Find delimeter for multiple calcualtions b. ) Make seperate output sub - files 2. ) Creates seperate QCCalcs for each one from the sub - files
def multiple_outputs_from_file(cls, filename, keep_sub_files=True): """ Parses a QChem output file with multiple calculations 1.) Seperates the output into sub-files e.g. qcout -> qcout.0, qcout.1, qcout.2 ... qcout.N a.) Find delimeter for multiple calcua...
Parses charge and multiplicity.
def _read_charge_and_multiplicity(self): """ Parses charge and multiplicity. """ temp_charge = read_pattern( self.text, { "key": r"\$molecule\s+([\-\d]+)\s+\d" }, terminate_on_match=True).get('key') if temp_charge != None: ...
Parses species and initial geometry.
def _read_species_and_inital_geometry(self): """ Parses species and initial geometry. """ header_pattern = r"Standard Nuclear Orientation \(Angstroms\)\s+I\s+Atom\s+X\s+Y\s+Z\s+-+" table_pattern = r"\s*\d+\s+([a-zA-Z]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*" footer...
Parses both old and new SCFs.
def _read_SCF(self): """ Parses both old and new SCFs. """ if self.data.get('using_GEN_SCFMAN', []): if "SCF_failed_to_converge" in self.data.get("errors"): footer_pattern = r"^\s*gen_scfman_exception: SCF failed to converge" else: ...
Parses Mulliken charges. Also parses spins given an unrestricted SCF.
def _read_mulliken(self): """ Parses Mulliken charges. Also parses spins given an unrestricted SCF. """ if self.data.get('unrestricted', []): header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+" tab...
Parses optimized XYZ coordinates. If not present parses optimized Z - matrix.
def _read_optimized_geometry(self): """ Parses optimized XYZ coordinates. If not present, parses optimized Z-matrix. """ header_pattern = r"\*+\s+OPTIMIZATION\s+CONVERGED\s+\*+\s+\*+\s+Coordinates \(Angstroms\)\s+ATOM\s+X\s+Y\s+Z" table_pattern = r"\s+\d+\s+\w+\s+([\d\-\.]+)\s+([...
Parses the last geometry from an optimization trajectory for use in a new input file.
def _read_last_geometry(self): """ Parses the last geometry from an optimization trajectory for use in a new input file. """ header_pattern = r"\s+Optimization\sCycle:\s+" + \ str(len(self.data.get("energy_trajectory"))) + \ r"\s+Coordinates \(Angstroms\)\s+ATOM\s...
Parses frequencies enthalpy entropy and mode vectors.
def _read_frequency_data(self): """ Parses frequencies, enthalpy, entropy, and mode vectors. """ temp_dict = read_pattern( self.text, { "frequencies": r"\s*Frequency:\s+([\d\-\.]+)(?:\s+([\d\-\.]+)(?:\s+([\d\-\.]+))*)*", "IR_int...
Parses final free energy information from single - point calculations.
def _read_single_point_data(self): """ Parses final free energy information from single-point calculations. """ temp_dict = read_pattern( self.text, { "final_energy": r"\s*SCF\s+energy in the final basis set\s+=\s*([\d\-\.]+)" }...
Parses information from PCM solvent calculations.
def _read_pcm_information(self): """ Parses information from PCM solvent calculations. """ temp_dict = read_pattern( self.text, { "g_electrostatic": r"\s*G_electrostatic\s+=\s+([\d\-\.]+)\s+hartree\s+=\s+([\d\-\.]+)\s+kcal/mol\s*", "g_cavitati...
Parses three potential optimization errors: failing to converge within the allowed number of optimization cycles failure to determine the lamda needed to continue and inconsistent size of MO files due to a linear dependence in the AO basis.
def _check_optimization_errors(self): """ Parses three potential optimization errors: failing to converge within the allowed number of optimization cycles, failure to determine the lamda needed to continue, and inconsistent size of MO files due to a linear dependence in the AO basis. ...
Parses four potential errors that can cause jobs to crash: inability to transform coordinates due to a bad symmetric specification an input file that fails to pass inspection and errors reading and writing files.
def _check_completion_errors(self): """ Parses four potential errors that can cause jobs to crash: inability to transform coordinates due to a bad symmetric specification, an input file that fails to pass inspection, and errors reading and writing files. """ if read_patte...
Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path.
def get_cod_ids(self, formula): """ Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: formula (str): Formula. Returns: List of cod ids. """ # TODO: Remove dependency on external ...
Queries the COD for a structure by id.
def get_structure_by_id(self, cod_id, **kwargs): """ Queries the COD for a structure by id. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A Structure. ...
Queries the COD for structures by formula. Requires mysql executable to be in the path.
def get_structure_by_formula(self, formula, **kwargs): """ Queries the COD for structures by formula. Requires mysql executable to be in the path. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure...
Returns the continuous symmetry measure ( s ) of site with index isite with respect to the perfect coordination environment with mp_symbol. For some environments a given mp_symbol might not be available ( if there is no voronoi parameters leading to a number of neighbours corresponding to the coordination number of env...
def get_csms(self, isite, mp_symbol): """ Returns the continuous symmetry measure(s) of site with index isite with respect to the perfect coordination environment with mp_symbol. For some environments, a given mp_symbol might not be available (if there is no voronoi parameters leading ...
Plotting of the coordination numbers of a given site for all the distfactor/ angfactor parameters. If the chemical environments are given a color map is added to the plot with the lowest continuous symmetry measure as the value for the color of that distfactor/ angfactor set.: param isite: Index of the site for which t...
def plot_csm_and_maps(self, isite, max_csm=8.0): """ Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the chemical environments are given, a color map is added to the plot, with the lowest continuous symmetry measure as the value for th...
Plotting of the coordination environments of a given site for all the distfactor/ angfactor regions. The chemical environments with the lowest continuous symmetry measure is shown for each distfactor/ angfactor region as the value for the color of that distfactor/ angfactor region ( using a colormap ).: param isite: In...
def get_environments_figure(self, isite, plot_type=None, title='Coordination numbers', max_dist=2.0, additional_condition=AC.ONLY_ACB, colormap=None, figsize=None, strategy=None): """ Plotting of the coordination environments of a given sit...
Plotting of the coordination numbers of a given site for all the distfactor/ angfactor parameters. If the chemical environments are given a color map is added to the plot with the lowest continuous symmetry measure as the value for the color of that distfactor/ angfactor set.: param isite: Index of the site for which t...
def plot_environments(self, isite, plot_type=None, title='Coordination numbers', max_dist=2.0, additional_condition=AC.ONLY_ACB, figsize=None, strategy=None): """ Plotting of the coordination numbers of a given site for all the distfactor/angfactor parameters. If the c...
Bson - serializable dict representation of the StructureEnvironments object.: return: Bson - serializable dict representation of the StructureEnvironments object.
def as_dict(self): """ Bson-serializable dict representation of the StructureEnvironments object. :return: Bson-serializable dict representation of the StructureEnvironments object. """ ce_list_dict = [{str(cn): [ce.as_dict() if ce is not None else None for ce in ce_dict[cn]] ...
Reconstructs the StructureEnvironments object from a dict representation of the StructureEnvironments created using the as_dict method.: param d: dict representation of the StructureEnvironments object: return: StructureEnvironments object
def from_dict(cls, d): """ Reconstructs the StructureEnvironments object from a dict representation of the StructureEnvironments created using the as_dict method. :param d: dict representation of the StructureEnvironments object :return: StructureEnvironments object """ ...
Checks whether the structure contains a given atom in a given environment: param atom_symbol: Symbol of the atom: param ce_symbol: Symbol of the coordination environment: return: True if the coordination environment is found False otherwise
def structure_contains_atom_environment(self, atom_symbol, ce_symbol): """ Checks whether the structure contains a given atom in a given environment :param atom_symbol: Symbol of the atom :param ce_symbol: Symbol of the coordination environment :return: True if the coordination e...
Bson - serializable dict representation of the LightStructureEnvironments object.: return: Bson - serializable dict representation of the LightStructureEnvironments object.
def as_dict(self): """ Bson-serializable dict representation of the LightStructureEnvironments object. :return: Bson-serializable dict representation of the LightStructureEnvironments object. """ return {"@module": self.__class__.__module__, "@class": self.__class...
Reconstructs the LightStructureEnvironments object from a dict representation of the LightStructureEnvironments created using the as_dict method.: param d: dict representation of the LightStructureEnvironments object: return: LightStructureEnvironments object
def from_dict(cls, d): """ Reconstructs the LightStructureEnvironments object from a dict representation of the LightStructureEnvironments created using the as_dict method. :param d: dict representation of the LightStructureEnvironments object :return: LightStructureEnvironments ...
Returns the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments: return: tuple ( symbol csm ) with symbol being the geometry with the minimum continuous symmetry measure and csm being the continuous symmetry measure associted to it: raise: ValueError if no coordination geometry is found i...
def minimum_geometry(self, symmetry_measure_type=None, max_csm=None): """ Returns the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments :return: tuple (symbol, csm) with symbol being the geometry with the minimum continuous symmetry measure and csm being ...
Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object: param n: Number of geometries to be included in the list: return: list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object: raise: ValueError if no coordination geometr...
def minimum_geometries(self, n=None, symmetry_measure_type=None, max_csm=None): """ Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object :param n: Number of geometries to be included in the list :return: list of geometries with incr...
Adds a coordination geometry to the ChemicalEnvironments object: param mp_symbol: Symbol ( internal ) of the coordination geometry added: param symmetry_measure: Symmetry measure of the coordination geometry added: param algo: Algorithm used for the search of the coordination geometry added: param permutation: Permutat...
def add_coord_geom(self, mp_symbol, symmetry_measure, algo='UNKNOWN', permutation=None, override=False, local2perfect_map=None, perfect2local_map=None, detailed_voronoi_index=None, other_symmetry_measures=None, rotation_matrix=None, scaling_factor=None): """ ...
Returns a dictionary representation of the ChemicalEnvironments object: return:
def as_dict(self): """ Returns a dictionary representation of the ChemicalEnvironments object :return: """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "coord_geoms": jsanitize(self.coord_geoms)}
Reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created using the as_dict method.: param d: dict representation of the ChemicalEnvironments object: return: ChemicalEnvironments object
def from_dict(cls, d): """ Reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created using the as_dict method. :param d: dict representation of the ChemicalEnvironments object :return: ChemicalEnvironments object """ ...
Subroutine to extract bond label site indices and length from a LOBSTER header line. The site indices are zero - based so they can be easily used with a Structure object.
def _get_bond_data(line): """ Subroutine to extract bond label, site indices, and length from a LOBSTER header line. The site indices are zero-based, so they can be easily used with a Structure object. Example header line: No.4:Fe1->Fe9(2.4524893531900283) Example header...
Returns: icohplist compatible with older version of this class
def icohplist(self): """ Returns: icohplist compatible with older version of this class """ icohplist_new = {} for key, value in self._icohpcollection._icohplist.items(): icohplist_new[key] = {"length": value._length, "number_of_bonds": value._num, ...
get a Structure with Mulliken and Loewdin charges as site properties Args: structure_filename: filename of POSCAR Returns: Structure Object with Mulliken and Loewdin charges as site properties
def get_structure_with_charges(self, structure_filename): """ get a Structure with Mulliken and Loewdin charges as site properties Args: structure_filename: filename of POSCAR Returns: Structure Object with Mulliken and Loewdin charges as site properties "...
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter
def get_bandstructure(self): """ returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter """ return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice, efe...
Get the decomposition leading to lowest cost
def get_lowest_decomposition(self, composition): """ Get the decomposition leading to lowest cost Args: composition: Composition as a pymatgen.core.structure.Composition Returns: Decomposition as a dict of {Entry: amount} """ entr...
Get best estimate of minimum cost/ mol based on known data
def get_cost_per_mol(self, comp): """ Get best estimate of minimum cost/mol based on known data Args: comp: Composition as a pymatgen.core.structure.Composition Returns: float of cost/mol """ comp = comp if isinstance(comp, Compos...
Get best estimate of minimum cost/ kg based on known data
def get_cost_per_kg(self, comp): """ Get best estimate of minimum cost/kg based on known data Args: comp: Composition as a pymatgen.core.structure.Composition Returns: float of cost/kg """ comp = comp if isinstance(comp, Compositio...
Convert a string into a boolean.
def as_bool(s): """ Convert a string into a boolean. >>> assert as_bool(True) is True and as_bool("Yes") is True and as_bool("false") is False """ if s in (False, True): return s # Assume string s = s.lower() if s in ("yes", "true"): return True elif s in ("no", "false"): ...
Split the ABINIT extension from a filename. Extension are found by searching in an internal database.
def abi_splitext(filename): """ Split the ABINIT extension from a filename. "Extension" are found by searching in an internal database. Returns "(root, ext)" where ext is the registered ABINIT extension The final ".nc" is included (if any) >>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK') ...
Convert a Mongodb - like dictionary to a RPN list of operands and operators.
def map2rpn(map, obj): """ Convert a Mongodb-like dictionary to a RPN list of operands and operators. Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, e.g. 3 - 4 + 5 --> 3 4 - 5 + >>> d = {2.0: {'$eq': 1.0}} >>> assert map2rpn...
Evaluates the RPN form produced my map2rpn.
def evaluate_rpn(rpn): """ Evaluates the RPN form produced my map2rpn. Returns: bool """ vals_stack = [] for item in rpn: if item in _ALL_OPS: # Apply the operator and push to the task. v2 = vals_stack.pop() if item in _UNARY_OPS: ...
Relative path.
def relpath(self): """Relative path.""" try: return os.path.relpath(self.path) except OSError: # current working directory may not be defined! return self.path
Write string to file.
def write(self, string): """Write string to file.""" self.make_dir() with open(self.path, "w") as f: if not string.endswith("\n"): return f.write(string + "\n") else: return f.write(string)
Write a list of strings to file.
def writelines(self, lines): """Write a list of strings to file.""" self.make_dir() with open(self.path, "w") as f: return f.writelines(lines)
Make the directory where the file is located.
def make_dir(self): """Make the directory where the file is located.""" if not os.path.exists(self.dirname): os.makedirs(self.dirname)
Return the list of absolute filepaths in the directory.
def list_filepaths(self, wildcard=None): """ Return the list of absolute filepaths in the directory. Args: wildcard: String of tokens separated by "|". Each token represents a pattern. If wildcard is not None, we return only those files that match the given shell pat...
Returns the absolute path of the ABINIT file with extension ext. Support both Fortran files and netcdf files. In the later case we check whether a file with extension ext +. nc is present in the directory. Returns empty string is file is not present.
def has_abiext(self, ext, single_file=True): """ Returns the absolute path of the ABINIT file with extension ext. Support both Fortran files and netcdf files. In the later case, we check whether a file with extension ext + ".nc" is present in the directory. Returns empty string i...
Create a simbolic link ( outext -- > inext ). The file names are implicitly given by the ABINIT file extension.
def symlink_abiext(self, inext, outext): """ Create a simbolic link (outext --> inext). The file names are implicitly given by the ABINIT file extension. Example: outdir.symlink_abiext('1WF', 'DDK') creates the link out_DDK that points to out_1WF Return: 0...
Rename the Abinit file with extension inext with the new extension outext
def rename_abiext(self, inext, outext): """Rename the Abinit file with extension inext with the new extension outext""" infile = self.has_abiext(inext) if not infile: raise RuntimeError('no file with extension %s in %s' % (inext, self)) for i in range(len(infile) - 1, -1, -1...
Copy the Abinit file with extension inext to a new file withw extension outext
def copy_abiext(self, inext, outext): """Copy the Abinit file with extension inext to a new file withw extension outext""" infile = self.has_abiext(inext) if not infile: raise RuntimeError('no file with extension %s in %s' % (inext, self)) for i in range(len(infile) - 1, -1,...
Remove the files with the given extensions. Unlike rmtree this function preserves the directory path. Return list with the absolute paths of the files that have been removed.
def remove_exts(self, exts): """ Remove the files with the given extensions. Unlike rmtree, this function preserves the directory path. Return list with the absolute paths of the files that have been removed. """ paths = [] for ext in list_strings(exts): path...
ABINIT produces lots of out_TIM1_DEN files for each step and we need to find the lat one in order to prepare the restart or to connect other tasks to the structural relaxation.
def find_last_timden_file(self): """ ABINIT produces lots of out_TIM1_DEN files for each step and we need to find the lat one in order to prepare the restart or to connect other tasks to the structural relaxation. This function finds all the TIM?_DEN files in self and return a namedtupl...
Abinit adds the idir - ipert index at the end of the 1WF file and this breaks the extension e. g. out_1WF4. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the path of the 1FK file and the pertcase index.
def find_1wf_files(self): """ Abinit adds the idir-ipert index at the end of the 1WF file and this breaks the extension e.g. out_1WF4. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the `path` of the 1FK file and the `pertcase` inde...
Abinit adds the idir - ipert index at the end of the 1DEN file and this breaks the extension e. g. out_DEN1. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the path of the 1DEN file and the pertcase index.
def find_1den_files(self): """ Abinit adds the idir-ipert index at the end of the 1DEN file and this breaks the extension e.g. out_DEN1. This method scans the files in the directories and returns a list of namedtuple Each named tuple gives the `path` of the 1DEN file and the `pertcase` i...
Fix the filenames in the iterable paths
def fix_paths(self, paths): """ Fix the filenames in the iterable paths Returns: old2new: Mapping old_path --> new_path """ old2new, fixed_exts = {}, [] for path in list_strings(paths): newpath, ext = self._fix_path(path) if newpath ...
Convert obj into: class: Condition
def as_condition(cls, obj): """Convert obj into :class:`Condition`""" if isinstance(obj, cls): return obj else: return cls(cmap=obj)
Plot the histogram with matplotlib returns matplotlib figure.
def plot(self, ax=None, **kwargs): """ Plot the histogram with matplotlib, returns `matplotlib` figure. """ ax, fig, plt = get_ax_fig_plt(ax) yy = [len(v) for v in self.values] ax.plot(self.binvals, yy, **kwargs) return fig
Generate directory graph in the DOT language. Directories are shown as clusters
def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None): """ Generate directory graph in the DOT language. Directories are shown as clusters .. warning:: This function scans the entire directory tree starting from top so the resulting ...
Finds the lowest entry energy for entries matching the composition. Entries with non - negative formation energies are excluded. If no entry is found use the convex hull energy for the composition.
def _get_entry_energy(pd, composition): """ Finds the lowest entry energy for entries matching the composition. Entries with non-negative formation energies are excluded. If no entry is found, use the convex hull energy for the composition. Args: pd (PhaseDiagram): P...