docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
plot dos Args: sigma: a smearing Returns: a matplotlib object
def plot_dos(self, sigma=0.05): plotter = DosPlotter(sigma=sigma) plotter.add_dos("t", self._bz.dos) return plotter.get_plot()
141,111
Plot the carrier concentration in function of Fermi level Args: temp: the temperature Returns: a matplotlib object
def plot_carriers(self, temp=300): import matplotlib.pyplot as plt plt.semilogy(self._bz.mu_steps, abs(self._bz._carrier_conc[temp] / (self._bz.vol * 1e-24)), linewidth=3.0, color='r') self._plot_bg_limits() self._plot_doping(temp) plt.xlim(-0.5, self._bz.gap + 0.5) plt.ylim(1e14, 1e22) plt.ylabel("carrier concentration (cm-3)", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) return plt
141,112
Plot the Hall carrier concentration in function of Fermi level Args: temp: the temperature Returns: a matplotlib object
def plot_hall_carriers(self, temp=300): import matplotlib.pyplot as plt hall_carriers = [abs(i) for i in self._bz.get_hall_carrier_concentration()[temp]] plt.semilogy(self._bz.mu_steps, hall_carriers, linewidth=3.0, color='r') self._plot_bg_limits() self._plot_doping(temp) plt.xlim(-0.5, self._bz.gap + 0.5) plt.ylim(1e14, 1e22) plt.ylabel("Hall carrier concentration (cm-3)", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) return plt
141,113
Adds a COHP for plotting. Args: label: Label for the COHP. Must be unique. cohp: COHP object.
def add_cohp(self, label, cohp): energies = cohp.energies - cohp.efermi if self.zero_at_efermi \ else cohp.energies populations = cohp.get_cohp() int_populations = cohp.get_icohp() self._cohps[label] = {"energies": energies, "COHP": populations, "ICOHP": int_populations, "efermi": cohp.efermi}
141,115
Adds a dictionary of COHPs with an optional sorting function for the keys. Args: cohp_dict: dict of the form {label: Cohp} key_sort_func: function used to sort the cohp_dict keys.
def add_cohp_dict(self, cohp_dict, key_sort_func=None): if key_sort_func: keys = sorted(cohp_dict.keys(), key=key_sort_func) else: keys = cohp_dict.keys() for label in keys: self.add_cohp(label, cohp_dict[label])
141,116
Initializes a Vacancy Generator Args: structure(Structure): pymatgen structure object
def __init__(self, structure, include_bv_charge=False): self.structure = structure self.include_bv_charge = include_bv_charge # Find equivalent site list sga = SpacegroupAnalyzer(self.structure) self.symm_structure = sga.get_symmetrized_structure() self.equiv_site_seq = list(self.symm_structure.equivalent_sites) self.struct_valences = None if self.include_bv_charge: bv = BVAnalyzer() self.struct_valences = bv.get_valences(self.structure)
141,123
Initializes a Substitution Generator note: an Antisite is considered a type of substitution Args: structure(Structure): pymatgen structure object element (str or Element or Specie): element for the substitution
def __init__(self, structure, element): self.structure = structure self.element = element # Find equivalent site list sga = SpacegroupAnalyzer(self.structure) self.symm_structure = sga.get_symmetrized_structure() self.equiv_sub = [] for equiv_site_set in list(self.symm_structure.equivalent_sites): vac_site = equiv_site_set[0] if isinstance(element, str): # make sure you compare with specie symbol or Element type vac_specie = vac_site.specie.symbol else: vac_specie = vac_site.specie if element != vac_specie: defect_site = PeriodicSite(element, vac_site.coords, structure.lattice, coords_are_cartesian=True) sub = Substitution(structure, defect_site) self.equiv_sub.append(sub)
141,125
Initializes an Interstitial generator using structure motifs Args: structure (Structure): pymatgen structure object element (str or Element or Specie): element for the interstitial
def __init__(self, structure, element): self.structure = structure self.element = element interstitial_finder = StructureMotifInterstitial(self.structure, self.element) self.unique_defect_seq = [] # eliminate sublattice equivalent defects which may # have slipped through interstitial finder pdc = PointDefectComparator() for poss_site in interstitial_finder.enumerate_defectsites(): now_defect = Interstitial( self.structure, poss_site) append_defect = True for unique_defect in self.unique_defect_seq: if pdc.are_equal( now_defect, unique_defect): append_defect = False if append_defect: self.unique_defect_seq.append( now_defect) self.count_def = 0
141,126
Initializes an Interstitial generator using Voronoi sites Args: structure (Structure): pymatgen structure object element (str or Element or Specie): element for the interstitial
def __init__(self, structure, element): self.structure = structure self.element = element framework = list(self.structure.symbol_set) get_voronoi = TopographyAnalyzer(self.structure, framework, [], check_volume=False) get_voronoi.cluster_nodes() get_voronoi.remove_collisions() # trim equivalent nodes with symmetry analysis struct_to_trim = self.structure.copy() for poss_inter in get_voronoi.vnodes: struct_to_trim.append(self.element, poss_inter.frac_coords, coords_are_cartesian=False) symmetry_finder = SpacegroupAnalyzer(struct_to_trim, symprec=1e-1) equiv_sites_list = symmetry_finder.get_symmetrized_structure().equivalent_sites # do additional screening for sublattice equivalent # defects which may have slipped through pdc = PointDefectComparator() self.unique_defect_seq = [] for poss_site_list in equiv_sites_list: poss_site = poss_site_list[0] if poss_site not in self.structure: now_defect = Interstitial( self.structure, poss_site) append_defect = True for unique_defect in self.unique_defect_seq: if pdc.are_equal( now_defect, unique_defect): append_defect = False if append_defect: self.unique_defect_seq.append( now_defect) self.count_def = 0
141,127
Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle.
def solid_angle(center, coords): # Compute the displacement from the center r = [np.subtract(c, center) for c in coords] # Compute the magnitude of each vector r_norm = [np.linalg.norm(i) for i in r] # Compute the solid angle for each tetrahedron that makes up the facet # Following: https://en.wikipedia.org/wiki/Solid_angle#Tetrahedron angle = 0 for i in range(1, len(r) - 1): j = i + 1 tp = np.abs(np.dot(r[0], np.cross(r[i], r[j]))) de = r_norm[0] * r_norm[i] * r_norm[j] + \ r_norm[j] * np.dot(r[0], r[i]) + \ r_norm[i] * np.dot(r[0], r[j]) + \ r_norm[0] * np.dot(r[i], r[j]) if de == 0: my_angle = 0.5 * pi if tp > 0 else -0.5 * pi else: my_angle = np.arctan(tp / de) angle += (my_angle if my_angle > 0 else my_angle + np.pi) * 2 return angle
141,131
Calculate the volume of a tetrahedron, given the four vertices of vt1, vt2, vt3 and vt4. Args: vt1 (array-like): coordinates of vertex 1. vt2 (array-like): coordinates of vertex 2. vt3 (array-like): coordinates of vertex 3. vt4 (array-like): coordinates of vertex 4. Returns: (float): volume of the tetrahedron.
def vol_tetra(vt1, vt2, vt3, vt4): vol_tetra = np.abs(np.dot((vt1 - vt4), np.cross((vt2 - vt4), (vt3 - vt4)))) / 6 return vol_tetra
141,132
Returns the elemental parameters related to atom size and electronegativity which are used for estimating bond-valence parameters (bond length) of pairs of atoms on the basis of data provided in 'Atoms Sizes and Bond Lengths in Molecules and Crystals' (O'Keeffe & Brese, 1991). Args: el_symbol (str): element symbol. Returns: (dict): atom-size ('r') and electronegativity-related ('c') parameter.
def get_okeeffe_params(el_symbol): el = Element(el_symbol) if el not in list(BV_PARAMS.keys()): raise RuntimeError("Could not find O'Keeffe parameters for element" " \"{}\" in \"BV_PARAMS\"dictonary" " provided by pymatgen".format(el_symbol)) return BV_PARAMS[el]
141,133
Returns that part of the first input vector that is orthogonal to the second input vector. The output vector is not normalized. Args: vin (numpy array): first input vector uin (numpy array): second input vector
def gramschmidt(vin, uin): vin_uin = np.inner(vin, uin) uin_uin = np.inner(uin, uin) if uin_uin <= 0.0: raise ValueError("Zero or negative inner product!") return vin - (vin_uin / uin_uin) * uin
141,137
Returns the weighted average bond length given by Hoppe's effective coordination number formula. Args: bonds (list): list of floats that are the bond distances between a cation and its peripheral ions
def calculate_weighted_avg(bonds): minimum_bond = min(bonds) weighted_sum = 0.0 total_sum = 0.0 for entry in bonds: weighted_sum += entry * exp(1 - (entry / minimum_bond) ** 6) total_sum += exp(1 - (entry / minimum_bond) ** 6) return weighted_sum / total_sum
141,138
Get near neighbors of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site in structure for which to determine neighbors. Returns: sites (list of Site objects): near neighbors.
def get_nn(self, structure, n): return [e['site'] for e in self.get_nn_info(structure, n)]
141,146
Get weight associated with each near neighbor of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site for which to determine the weights. Returns: weights (list of floats): near-neighbor weights.
def get_weights_of_nn_sites(self, structure, n): return [e['weight'] for e in self.get_nn_info(structure, n)]
141,147
Get image location of all near neighbors of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site for which to determine the image location of near neighbors. Returns: images (list of 3D integer array): image locations of near neighbors.
def get_nn_images(self, structure, n): return [e['image'] for e in self.get_nn_info(structure, n)]
141,148
Get a listing of all neighbors for all sites in a structure Args: structure (Structure): Input structure Return: List of NN site information for each site in the structure. Each entry has the same format as `get_nn_info`
def get_all_nn_info(self, structure): return [self.get_nn_info(structure, n) for n in range(len(structure))]
141,149
Obtain a StructureGraph object using this NearNeighbor class. Requires the optional dependency networkx (pip install networkx). Args: structure: Structure object. decorate (bool): whether to annotate site properties with order parameters using neighbors determined by this NearNeighbor class Returns: a pymatgen.analysis.graphs.BondedStructure object
def get_bonded_structure(self, structure, decorate=False): # requires optional dependency which is why it's not a top-level import from pymatgen.analysis.graphs import StructureGraph if decorate: # Decorate all sites in the underlying structure # with site properties that provides information on the # coordination number and coordination pattern based # on the (current) structure of this graph. order_parameters = [self.get_local_order_parameters(structure, n) for n in range(len(structure))] structure.add_site_property('order_parameters', order_parameters) sg = StructureGraph.with_local_env_strategy(structure, self) return sg
141,154
Get the list of elements for a Site Args: site (Site): Site to assess Returns: [Element]: List of elements
def _get_elements(self, site): try: if isinstance(site.specie, Element): return [site.specie] return [Element(site.specie)] except: return site.species.elements
141,159
Test whether a site contains elements in the target list Args: site (Site): Site to assess targets ([Element]) List of elements Returns: (boolean) Whether this site contains a certain list of elements
def _is_in_targets(self, site, targets): elems = self._get_elements(site) for elem in elems: if elem not in targets: return False return True
141,160
Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors Args: structure (Structure): Structure being evaluated nns ([dicts]): Nearest neighbor information for a structure Returns: (list of tuples (Site, array, float)): See nn_info
def _extract_nn_info(self, structure, nns): # Get the target information if self.targets is None: targets = structure.composition.elements else: targets = self.targets # Extract the NN info siw = [] max_weight = max(nn[self.weight] for nn in nns.values()) for nstats in nns.values(): site = nstats['site'] if nstats[self.weight] > self.tol * max_weight \ and self._is_in_targets(site, targets): nn_info = {'site': site, 'image': self._get_image(structure, site), 'weight': nstats[self.weight] / max_weight, 'site_index': self._get_original_site( structure, site)} if self.extra_nn_info: # Add all the information about the site poly_info = nstats del poly_info['site'] nn_info['poly_info'] = poly_info siw.append(nn_info) return siw
141,164
Use Jmol algorithm to determine bond length from atomic parameters Args: el1_sym: (str) symbol of atom 1 el2_sym: (str) symbol of atom 2 Returns: (float) max bond length
def get_max_bond_distance(self, el1_sym, el2_sym): return sqrt( (self.el_radius[el1_sym] + self.el_radius[el2_sym] + self.tol) ** 2)
141,166
Obtain a MoleculeGraph object using this NearNeighbor class. Requires the optional dependency networkx (pip install networkx). Args: structure: Molecule object. decorate (bool): whether to annotate site properties with order parameters using neighbors determined by this NearNeighbor class Returns: a pymatgen.analysis.graphs.MoleculeGraph object
def get_bonded_structure(self, structure, decorate=False): # requires optional dependency which is why it's not a top-level import from pymatgen.analysis.graphs import MoleculeGraph if decorate: # Decorate all sites in the underlying structure # with site properties that provides information on the # coordination number and coordination pattern based # on the (current) structure of this graph. order_parameters = [self.get_local_order_parameters(structure, n) for n in range(len(structure))] structure.add_site_property('order_parameters', order_parameters) mg = MoleculeGraph.with_local_env_strategy(structure, self) return mg
141,171
Return type of order parameter at the index provided and represented by a short string. Args: index (int): index of order parameter for which type is to be returned. Returns: str: OP type.
def get_type(self, index): if index < 0 or index >= len(self._types): raise ValueError("Index for getting order parameter type" " out-of-bounds!") return self._types[index]
141,182
An internal method to get an integral between two bounds of a unit semicircle. Used in algorithm to determine bond probabilities. Args: dist_bins: (float) list of all possible bond weights idx: (float) index of starting bond weight Returns: (float) integral of portion of unit semicircle
def _semicircle_integral(dist_bins, idx): r = 1 x1 = dist_bins[idx] x2 = dist_bins[idx + 1] if dist_bins[idx] == 1: area1 = 0.25 * math.pi * r ** 2 else: area1 = 0.5 * ((x1 * math.sqrt(r ** 2 - x1 ** 2)) + ( r ** 2 * math.atan(x1 / math.sqrt(r ** 2 - x1 ** 2)))) area2 = 0.5 * ((x2 * math.sqrt(r ** 2 - x2 ** 2)) + ( r ** 2 * math.atan(x2 / math.sqrt(r ** 2 - x2 ** 2)))) return (area1 - area2) / (0.25 * math.pi * r ** 2)
141,192
An internal method to get a "default" covalent/element radius Args: site: (Site) Returns: Covalent radius of element on site, or Atomic radius if unavailable
def _get_default_radius(site): try: return CovalentRadius.radius[site.specie.symbol] except: return site.specie.atomic_radius
141,193
An internal method to get the expected radius for a site with oxidation state. Args: site: (Site) Returns: Oxidation-state dependent radius: ionic, covalent, or atomic. Returns 0 if no oxidation state or appropriate radius is found.
def _get_radius(site): if hasattr(site.specie, 'oxi_state'): el = site.specie.element oxi = site.specie.oxi_state if oxi == 0: return CrystalNN._get_default_radius(site) elif oxi in el.ionic_radii: return el.ionic_radii[oxi] # e.g., oxi = 2.667, average together 2+ and 3+ radii elif int(math.floor(oxi)) in el.ionic_radii and \ int(math.ceil(oxi)) in el.ionic_radii: oxi_low = el.ionic_radii[int(math.floor(oxi))] oxi_high = el.ionic_radii[int(math.ceil(oxi))] x = oxi - int(math.floor(oxi)) return (1 - x) * oxi_low + x * oxi_high elif oxi > 0 and el.average_cationic_radius > 0: return el.average_cationic_radius elif oxi < 0 and el.average_anionic_radius > 0: return el.average_anionic_radius else: warnings.warn("CrystalNN: distance cutoffs set but no oxidation " "states specified on sites! For better results, set " "the site oxidation states in the structure.") return 0
141,194
Given NNData, transforms data to the specified fingerprint length Args: nndata: (NNData) length: (int) desired length of NNData
def transform_to_length(nndata, length): if length is None: return nndata if length: for cn in range(length): if cn not in nndata.cn_weights: nndata.cn_weights[cn] = 0 nndata.cn_nninfo[cn] = [] return nndata
141,195
Initialise a CutOffDictNN according to a preset set of cut-offs. Args: preset (str): A preset name. The list of supported presets are: - "vesta_2019": The distance cut-offs used by the VESTA visualisation program. Returns: A CutOffDictNN using the preset cut-off dictionary.
def from_preset(preset): if preset == 'vesta_2019': cut_offs = loadfn(os.path.join(_directory, 'vesta_cutoffs.yaml')) return CutOffDictNN(cut_off_dict=cut_offs) else: raise ValueError("Unrecognised preset: {}".format(preset))
141,197
Computes the volume and surface area of isolated void using Zeo++. Useful to compute the volume and surface area of vacant site. Args: structure: pymatgen Structure containing vacancy rad_dict(optional): Dictionary with short name of elements and their radii. chan_rad(optional): Minimum channel Radius. probe_rad(optional): Probe radius for Monte Carlo sampling. Returns: volume: floating number representing the volume of void
def get_void_volume_surfarea(structure, rad_dict=None, chan_rad=0.3, probe_rad=0.1): with ScratchDir('.'): name = "temp_zeo" zeo_inp_filename = name + ".cssr" ZeoCssr(structure).write_file(zeo_inp_filename) rad_file = None if rad_dict: rad_file = name + ".rad" with open(rad_file, 'w') as fp: for el in rad_dict.keys(): fp.write("{0} {1}".format(el, rad_dict[el])) atmnet = AtomNetwork.read_from_CSSR(zeo_inp_filename, True, rad_file) vol_str = volume(atmnet, 0.3, probe_rad, 10000) sa_str = surface_area(atmnet, 0.3, probe_rad, 10000) vol = None sa = None for line in vol_str.split("\n"): if "Number_of_pockets" in line: fields = line.split() if float(fields[1]) > 1: vol = -1.0 break if float(fields[1]) == 0: vol = -1.0 break vol = float(fields[3]) for line in sa_str.split("\n"): if "Number_of_pockets" in line: fields = line.split() if float(fields[1]) > 1: # raise ValueError("Too many voids") sa = -1.0 break if float(fields[1]) == 0: sa = -1.0 break sa = float(fields[3]) if not vol or not sa: raise ValueError("Error in zeo++ output stream") return vol, sa
141,206
Reads a string representation to a ZeoCssr object. Args: string: A string representation of a ZeoCSSR. Returns: ZeoCssr object.
def from_string(string): lines = string.split("\n") toks = lines[0].split() lengths = [float(i) for i in toks] toks = lines[1].split() angles = [float(i) for i in toks[0:3]] # Zeo++ takes x-axis along a and pymatgen takes z-axis along c a = lengths.pop(-1) lengths.insert(0, a) alpha = angles.pop(-1) angles.insert(0, alpha) latt = Lattice.from_lengths_and_angles(lengths, angles) sp = [] coords = [] chrg = [] for l in lines[4:]: m = re.match(r'\d+\s+(\w+)\s+([0-9\-\.]+)\s+([0-9\-\.]+)\s+' + r'([0-9\-\.]+)\s+(?:0\s+){8}([0-9\-\.]+)', l.strip()) if m: sp.append(m.group(1)) # coords.append([float(m.group(i)) for i in xrange(2, 5)]) # Zeo++ takes x-axis along a and pymatgen takes z-axis along c coords.append([float(m.group(i)) for i in [3, 4, 2]]) chrg.append(m.group(5)) return ZeoCssr( Structure(latt, sp, coords, site_properties={'charge': chrg}) )
141,208
Creates Zeo++ Voronoi XYZ object from a string. from_string method of XYZ class is being redefined. Args: contents: String representing Zeo++ Voronoi XYZ file. Returns: ZeoVoronoiXYZ object
def from_string(contents): lines = contents.split("\n") num_sites = int(lines[0]) coords = [] sp = [] prop = [] coord_patt = re.compile( r"(\w+)\s+([0-9\-\.]+)\s+([0-9\-\.]+)\s+([0-9\-\.]+)\s+" + r"([0-9\-\.]+)" ) for i in range(2, 2 + num_sites): m = coord_patt.search(lines[i]) if m: sp.append(m.group(1)) # this is 1-indexed # coords.append(map(float, m.groups()[1:4])) # this is 0-indexed coords.append([float(j) for j in [m.group(i) for i in [3, 4, 2]]]) prop.append(float(m.group(5))) return ZeoVoronoiXYZ( Molecule(sp, coords, site_properties={'voronoi_radius': prop}) )
141,209
Set the maxium allowed memory. Args: total: The total memory. Integer. Unit: MBytes. If set to None, this parameter will be neglected. static: The static memory. Integer. Unit MBytes. If set to None, this parameterwill be neglected.
def set_memory(self, total=None, static=None): if total: self.params["rem"]["mem_total"] = total if static: self.params["rem"]["mem_static"] = static
141,217
Set algorithm used for converging SCF and max number of SCF iterations. Args: algorithm: The algorithm used for converging SCF. (str) iterations: The max number of SCF iterations. (Integer)
def set_scf_algorithm_and_iterations(self, algorithm="diis", iterations=50): available_algorithms = {"diis", "dm", "diis_dm", "diis_gdm", "gdm", "rca", "rca_diis", "roothaan"} if algorithm.lower() not in available_algorithms: raise ValueError("Algorithm " + algorithm + " is not available in QChem") self.params["rem"]["scf_algorithm"] = algorithm.lower() self.params["rem"]["max_scf_cycles"] = iterations
141,218
Set the grid for DFT numerical integrations. Args: radical_points: Radical points. (Integer) angular_points: Angular points. (Integer) grid_type: The type of of the grid. There are two standard grids: SG-1 and SG-0. The other two supported grids are "Lebedev" and "Gauss-Legendre"
def set_dft_grid(self, radical_points=128, angular_points=302, grid_type="Lebedev"): available_lebedev_angular_points = {6, 18, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294} if grid_type.lower() == "sg-0": self.params["rem"]["xc_grid"] = 0 elif grid_type.lower() == "sg-1": self.params["rem"]["xc_grid"] = 1 elif grid_type.lower() == "lebedev": if angular_points not in available_lebedev_angular_points: raise ValueError(str(angular_points) + " is not a valid " "Lebedev angular points number") self.params["rem"]["xc_grid"] = "{rp:06d}{ap:06d}".format( rp=radical_points, ap=angular_points) elif grid_type.lower() == "gauss-legendre": self.params["rem"]["xc_grid"] = "-{rp:06d}{ap:06d}".format( rp=radical_points, ap=angular_points) else: raise ValueError("Grid type " + grid_type + " is not supported " "currently")
141,219
Set initial guess method to be used for SCF Args: guess: The initial guess method. (str)
def set_scf_initial_guess(self, guess="SAD"): availabel_guesses = {"core", "sad", "gwh", "read", "fragmo"} if guess.lower() not in availabel_guesses: raise ValueError("The guess method " + guess + " is not supported " "yet") self.params["rem"]["scf_guess"] = guess.lower()
141,220
Set the solvent model to PCM. Default parameters are trying to comply to gaussian default value Args: pcm_params (dict): The parameters of "$pcm" section. solvent_key (str): for versions < 4.2 the section name is "pcm_solvent" solvent_params (dict): The parameters of solvent_key section radii_force_field (str): The force fied used to set the solute radii. Default to UFF.
def use_pcm(self, pcm_params=None, solvent_key="solvent", solvent_params=None, radii_force_field=None): self.params["pcm"] = dict() self.params[solvent_key] = dict() default_pcm_params = {"Theory": "SSVPE", "vdwScale": 1.1, "Radii": "UFF"} if not solvent_params: solvent_params = {"Dielectric": 78.3553} if pcm_params: for k, v in pcm_params.items(): self.params["pcm"][k.lower()] = v.lower() \ if isinstance(v, str) else v for k, v in default_pcm_params.items(): if k.lower() not in self.params["pcm"].keys(): self.params["pcm"][k.lower()] = v.lower() \ if isinstance(v, str) else v for k, v in solvent_params.items(): self.params[solvent_key][k.lower()] = v.lower() \ if isinstance(v, str) else copy.deepcopy(v) self.params["rem"]["solvent_method"] = "pcm" if radii_force_field: self.params["pcm"]["radii"] = "bondi" self.params["rem"]["force_fied"] = radii_force_field.lower()
141,223
Creates QcInput from a string. Args: contents: String representing a QChem input file. Returns: QcInput object
def from_string(cls, contents): mol = None charge = None spin_multiplicity = None params = dict() lines = contents.split('\n') parse_section = False section_name = None section_text = [] ghost_atoms = None for line_num, line in enumerate(lines): l = line.strip().lower() if len(l) == 0: continue if (not parse_section) and (l == "$end" or not l.startswith("$")): raise ValueError("Format error, parsing failed") if parse_section and l != "$end": section_text.append(line) if l.startswith("$") and not parse_section: parse_section = True section_name = l[1:] available_sections = ["comment", "molecule", "rem"] + \ sorted(list(cls.optional_keywords_list)) if section_name not in available_sections: raise ValueError("Unrecognized keyword " + line.strip() + " at line " + str(line_num)) if section_name in params: raise ValueError("duplicated keyword " + line.strip() + "at line " + str(line_num)) if parse_section and l == "$end": func_name = "_parse_" + section_name if func_name not in QcTask.__dict__: raise Exception(func_name + " is not implemented yet, " "please implement it") parse_func = QcTask.__dict__[func_name].__get__(None, QcTask) if section_name == "molecule": mol, charge, spin_multiplicity, ghost_atoms = parse_func(section_text) else: d = parse_func(section_text) params[section_name] = d parse_section = False section_name = None section_text = [] if parse_section: raise ValueError("Format error. " + section_name + " is not " "terminated") jobtype = params["rem"]["jobtype"] title = params.get("comment", None) exchange = params["rem"].get("exchange", "hf") method = params["rem"].get("method", None) correlation = params["rem"].get("correlation", None) basis_set = params["rem"]["basis"] aux_basis_set = params["rem"].get("aux_basis", None) ecp = params["rem"].get("ecp", None) optional_params = None op_keys = set(params.keys()) - {"comment", "rem"} if len(op_keys) > 0: optional_params = dict() for k in op_keys: optional_params[k] = params[k] return QcTask(molecule=mol, charge=charge, spin_multiplicity=spin_multiplicity, jobtype=jobtype, title=title, exchange=exchange, correlation=correlation, basis_set=basis_set, aux_basis_set=aux_basis_set, ecp=ecp, rem_params=params["rem"], optional_params=optional_params, ghost_atoms=ghost_atoms, method=method)
141,236
Sanitize our input structure by removing magnetic information and making primitive. Args: input_structure: Structure Returns: Structure
def _sanitize_input_structure(input_structure): input_structure = input_structure.copy() # remove any annotated spin input_structure.remove_spin() # sanitize input structure: first make primitive ... input_structure = input_structure.get_primitive_structure(use_site_props=False) # ... and strip out existing magmoms, which can cause conflicts # with later transformations otherwise since sites would end up # with both magmom site properties and Specie spins defined if "magmom" in input_structure.site_properties: input_structure.remove_site_property("magmom") return input_structure
141,266
Parse a string with a symbol to extract a string representing an element. Args: sym (str): A symbol to be parsed. Returns: A string with the parsed symbol. None if no parsing was possible.
def _parse_symbol(self, sym): # Common representations for elements/water in cif files # TODO: fix inconsistent handling of water special = {"Hw": "H", "Ow": "O", "Wat": "O", "wat": "O", "OH": "", "OH2": "", "NO3": "N"} parsed_sym = None # try with special symbols, otherwise check the first two letters, # then the first letter alone. If everything fails try extracting the # first letters. m_sp = re.match("|".join(special.keys()), sym) if m_sp: parsed_sym = special[m_sp.group()] elif Element.is_valid_symbol(sym[:2].title()): parsed_sym = sym[:2].title() elif Element.is_valid_symbol(sym[0].upper()): parsed_sym = sym[0].upper() else: m = re.match(r"w?[A-Z][a-z]*", sym) if m: parsed_sym = m.group() if parsed_sym is not None and (m_sp or not re.match(r"{}\d*".format(parsed_sym), sym)): msg = "{} parsed as {}".format(sym, parsed_sym) warnings.warn(msg) self.errors.append(msg) return parsed_sym
141,289
Return list of structures in CIF file. primitive boolean sets whether a conventional cell structure or primitive cell structure is returned. Args: primitive (bool): Set to False to return conventional unit cells. Defaults to True. With magnetic CIF files, will return primitive magnetic cell which may be larger than nuclear primitive cell. Returns: List of Structures.
def get_structures(self, primitive=True): structures = [] for d in self._cif.data.values(): try: s = self._get_structure(d, primitive) if s: structures.append(s) except (KeyError, ValueError) as exc: # Warn the user (Errors should never pass silently) # A user reported a problem with cif files produced by Avogadro # in which the atomic coordinates are in Cartesian coords. self.errors.append(str(exc)) warnings.warn(str(exc)) if self.errors: warnings.warn("Issues encountered while parsing CIF:") for error in self.errors: warnings.warn(error) if len(structures) == 0: raise ValueError("Invalid cif file with no structures!") return structures
141,291
A wrapper around CifFile to write CIF files from pymatgen structures. Args: struct (Structure): structure to write symprec (float): If not none, finds the symmetry of the structure and writes the cif with symmetry information. Passes symprec to the SpacegroupAnalyzer write_magmoms (bool): If True, will write magCIF file. Incompatible with symprec
def __init__(self, struct, symprec=None, write_magmoms=False): if write_magmoms and symprec: warnings.warn( "Magnetic symmetry cannot currently be detected by pymatgen," "disabling symmetry detection.") symprec = None format_str = "{:.8f}" block = OrderedDict() loops = [] spacegroup = ("P 1", 1) if symprec is not None: sf = SpacegroupAnalyzer(struct, symprec) spacegroup = (sf.get_space_group_symbol(), sf.get_space_group_number()) # Needs the refined struture when using symprec. This converts # primitive to conventional structures, the standard for CIF. struct = sf.get_refined_structure() latt = struct.lattice comp = struct.composition no_oxi_comp = comp.element_composition block["_symmetry_space_group_name_H-M"] = spacegroup[0] for cell_attr in ['a', 'b', 'c']: block["_cell_length_" + cell_attr] = format_str.format( getattr(latt, cell_attr)) for cell_attr in ['alpha', 'beta', 'gamma']: block["_cell_angle_" + cell_attr] = format_str.format( getattr(latt, cell_attr)) block["_symmetry_Int_Tables_number"] = spacegroup[1] block["_chemical_formula_structural"] = no_oxi_comp.reduced_formula block["_chemical_formula_sum"] = no_oxi_comp.formula block["_cell_volume"] = "%.8f" % latt.volume reduced_comp, fu = no_oxi_comp.get_reduced_composition_and_factor() block["_cell_formula_units_Z"] = str(int(fu)) if symprec is None: block["_symmetry_equiv_pos_site_id"] = ["1"] block["_symmetry_equiv_pos_as_xyz"] = ["x, y, z"] else: sf = SpacegroupAnalyzer(struct, symprec) symmops = [] for op in sf.get_symmetry_operations(): v = op.translation_vector symmops.append(SymmOp.from_rotation_and_translation( op.rotation_matrix, v)) ops = [op.as_xyz_string() for op in symmops] block["_symmetry_equiv_pos_site_id"] = \ ["%d" % i for i in range(1, len(ops) + 1)] block["_symmetry_equiv_pos_as_xyz"] = ops loops.append(["_symmetry_equiv_pos_site_id", "_symmetry_equiv_pos_as_xyz"]) try: symbol_to_oxinum = OrderedDict([ (el.__str__(), float(el.oxi_state)) for el in sorted(comp.elements)]) block["_atom_type_symbol"] = symbol_to_oxinum.keys() block["_atom_type_oxidation_number"] = symbol_to_oxinum.values() loops.append(["_atom_type_symbol", "_atom_type_oxidation_number"]) except (TypeError, AttributeError): symbol_to_oxinum = OrderedDict([(el.symbol, 0) for el in sorted(comp.elements)]) atom_site_type_symbol = [] atom_site_symmetry_multiplicity = [] atom_site_fract_x = [] atom_site_fract_y = [] atom_site_fract_z = [] atom_site_label = [] atom_site_occupancy = [] atom_site_moment_label = [] atom_site_moment_crystalaxis_x = [] atom_site_moment_crystalaxis_y = [] atom_site_moment_crystalaxis_z = [] count = 1 if symprec is None: for site in struct: for sp, occu in sorted(site.species.items()): atom_site_type_symbol.append(sp.__str__()) atom_site_symmetry_multiplicity.append("1") atom_site_fract_x.append("{0:f}".format(site.a)) atom_site_fract_y.append("{0:f}".format(site.b)) atom_site_fract_z.append("{0:f}".format(site.c)) atom_site_label.append("{}{}".format(sp.symbol, count)) atom_site_occupancy.append(occu.__str__()) magmom = Magmom( site.properties.get('magmom', getattr(sp, 'spin', 0))) if write_magmoms and abs(magmom) > 0: moment = Magmom.get_moment_relative_to_crystal_axes( magmom, latt) atom_site_moment_label.append( "{}{}".format(sp.symbol, count)) atom_site_moment_crystalaxis_x.append("%.5f" % moment[0]) atom_site_moment_crystalaxis_y.append("%.5f" % moment[1]) atom_site_moment_crystalaxis_z.append("%.5f" % moment[2]) count += 1 else: # The following just presents a deterministic ordering. unique_sites = [ (sorted(sites, key=lambda s: tuple([abs(x) for x in s.frac_coords]))[0], len(sites)) for sites in sf.get_symmetrized_structure().equivalent_sites ] for site, mult in sorted( unique_sites, key=lambda t: (t[0].species.average_electroneg, -t[1], t[0].a, t[0].b, t[0].c)): for sp, occu in site.species.items(): atom_site_type_symbol.append(sp.__str__()) atom_site_symmetry_multiplicity.append("%d" % mult) atom_site_fract_x.append("{0:f}".format(site.a)) atom_site_fract_y.append("{0:f}".format(site.b)) atom_site_fract_z.append("{0:f}".format(site.c)) atom_site_label.append("{}{}".format(sp.symbol, count)) atom_site_occupancy.append(occu.__str__()) count += 1 block["_atom_site_type_symbol"] = atom_site_type_symbol block["_atom_site_label"] = atom_site_label block["_atom_site_symmetry_multiplicity"] = \ atom_site_symmetry_multiplicity block["_atom_site_fract_x"] = atom_site_fract_x block["_atom_site_fract_y"] = atom_site_fract_y block["_atom_site_fract_z"] = atom_site_fract_z block["_atom_site_occupancy"] = atom_site_occupancy loops.append(["_atom_site_type_symbol", "_atom_site_label", "_atom_site_symmetry_multiplicity", "_atom_site_fract_x", "_atom_site_fract_y", "_atom_site_fract_z", "_atom_site_occupancy"]) if write_magmoms: block["_atom_site_moment_label"] = atom_site_moment_label block[ "_atom_site_moment_crystalaxis_x"] = atom_site_moment_crystalaxis_x block[ "_atom_site_moment_crystalaxis_y"] = atom_site_moment_crystalaxis_y block[ "_atom_site_moment_crystalaxis_z"] = atom_site_moment_crystalaxis_z loops.append(["_atom_site_moment_label", "_atom_site_moment_crystalaxis_x", "_atom_site_moment_crystalaxis_y", "_atom_site_moment_crystalaxis_z"]) d = OrderedDict() d[comp.reduced_formula] = CifBlock(block, loops, comp.reduced_formula) self._cf = CifFile(d)
141,294
Converts a list of SlabEntry to an appropriate dictionary. It is assumed that if there is no adsorbate, then it is a clean SlabEntry and that adsorbed SlabEntry has the clean_entry parameter set. Args: all_slab_entries (list): List of SlabEntry objects Returns: (dict): Dictionary of SlabEntry with the Miller index as the main key to a dictionary with a clean SlabEntry as the key to a list of adsorbed SlabEntry.
def entry_dict_from_list(all_slab_entries): entry_dict = {} for entry in all_slab_entries: hkl = tuple(entry.miller_index) if hkl not in entry_dict.keys(): entry_dict[hkl] = {} if entry.clean_entry: clean = entry.clean_entry else: clean = entry if clean not in entry_dict[hkl].keys(): entry_dict[hkl][clean] = [] if entry.adsorbates: entry_dict[hkl][clean].append(entry) return entry_dict
141,295
Uses dot product of numpy array to sub chemical potentials into the surface grand potential. This is much faster than using the subs function in sympy. Args: gamma_dict (dict): Surface grand potential equation as a coefficient dictionary chempots (dict): Dictionary assigning each chemical potential (key) in gamma a value Returns: Surface energy as a float
def sub_chempots(gamma_dict, chempots): coeffs = [gamma_dict[k] for k in gamma_dict.keys()] chempot_vals = [] for k in gamma_dict.keys(): if k not in chempots.keys(): chempot_vals.append(k) elif k == 1: chempot_vals.append(1) else: chempot_vals.append(chempots[k]) return np.dot(coeffs, chempot_vals)
141,296
Returns the adsorption energy or Gibb's binding energy of an adsorbate on a surface Args: eads (bool): Whether to calculate the adsorption energy (True) or the binding energy (False) which is just adsorption energy normalized by number of adsorbates.
def gibbs_binding_energy(self, eads=False): n = self.get_unit_primitive_area Nads = self.Nads_in_slab BE = (self.energy - n * self.clean_entry.energy) / Nads - \ sum([ads.energy_per_atom for ads in self.adsorbates]) return BE * Nads if eads else BE
141,299
Helper function to assign each facet a unique color using a dictionary. Args: alpha (float): Degree of transparency return (dict): Dictionary of colors (r,g,b,a) when plotting surface energy stability. The keys are individual surface entries where clean surfaces have a solid color while the corresponding adsorbed surface will be transparent.
def color_palette_dict(self, alpha=0.35): color_dict = {} for hkl in self.all_slab_entries.keys(): rgb_indices = [0, 1, 2] color = [0, 0, 0, 1] random.shuffle(rgb_indices) for i, ind in enumerate(rgb_indices): if i == 2: break color[ind] = np.random.uniform(0, 1) # Get the clean (solid) colors first clean_list = np.linspace(0, 1, len(self.all_slab_entries[hkl])) for i, clean in enumerate(self.all_slab_entries[hkl].keys()): c = copy.copy(color) c[rgb_indices[2]] = clean_list[i] color_dict[clean] = c # Now get the adsorbed (transparent) colors for ads_entry in self.all_slab_entries[hkl][clean]: c_ads = copy.copy(c) c_ads[3] = alpha color_dict[ads_entry] = c_ads return color_dict
141,315
Plots the binding energy energy as a function of monolayers (ML), i.e. the fractional area adsorbate density for all facets. For each facet at a specific monlayer, only plot the lowest binding energy. Args: plot_eads (bool): Option to plot the adsorption energy (binding energy multiplied by number of adsorbates) instead. Returns: (Plot): Plot of binding energy vs monolayer for all facets.
def monolayer_vs_BE(self, plot_eads=False): plt = pretty_plot(width=8, height=7) for hkl in self.all_slab_entries.keys(): ml_be_dict = {} for clean_entry in self.all_slab_entries[hkl].keys(): if self.all_slab_entries[hkl][clean_entry]: for ads_entry in self.all_slab_entries[hkl][clean_entry]: if ads_entry.get_monolayer not in ml_be_dict.keys(): ml_be_dict[ads_entry.get_monolayer] = 1000 be = ads_entry.gibbs_binding_energy(eads=plot_eads) if be < ml_be_dict[ads_entry.get_monolayer]: ml_be_dict[ads_entry.get_monolayer] = be # sort the binding energies and monolayers # in order to properly draw a line plot vals = sorted(ml_be_dict.items()) monolayers, BEs = zip(*vals) plt.plot(monolayers, BEs, '-o', c=self.color_dict[clean_entry], label=hkl) adsorbates = tuple(ads_entry.ads_entries_dict.keys()) plt.xlabel(" %s" * len(adsorbates) % adsorbates + " Coverage (ML)") plt.ylabel("Adsorption Energy (eV)") if plot_eads \ else plt.ylabel("Binding Energy (eV)") plt.legend() plt.tight_layout() return plt
141,318
Helper function to a chempot plot look nicer. Args: plt (Plot) Plot to add things to. xrange (list): xlim parameter ref_el (str): Element of the referenced chempot. axes(axes) Axes object from matplotlib pad (float) For tight layout rect (list): For tight layout ylim (ylim parameter): return (Plot): Modified plot with addons. return (Plot): Modified plot with addons.
def chempot_plot_addons(self, plt, xrange, ref_el, axes, pad=2.4, rect=[-0.047, 0, 0.84, 1], ylim=[]): # Make the figure look nice plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) axes.set_xlabel(r"Chemical potential $\Delta\mu_{%s}$ (eV)" % (ref_el)) ylim = ylim if ylim else axes.get_ylim() plt.xticks(rotation=60) plt.ylim(ylim) xlim = axes.get_xlim() plt.xlim(xlim) plt.tight_layout(pad=pad, rect=rect) plt.plot([xrange[0], xrange[0]], ylim, '--k') plt.plot([xrange[1], xrange[1]], ylim, '--k') xy = [np.mean([xrange[1]]), np.mean(ylim)] plt.annotate("%s-rich" % (ref_el), xy=xy, xytext=xy, rotation=90, fontsize=17) xy = [np.mean([xlim[0]]), np.mean(ylim)] plt.annotate("%s-poor" % (ref_el), xy=xy, xytext=xy, rotation=90, fontsize=17) return plt
141,319
Returns a plot of the local potential (eV) vs the position along the c axis of the slab model (Ang) Args: label_energies (bool): Whether to label relevant energy quantities such as the work function, Fermi energy, vacuum locpot, bulk-like locpot plt (plt): Matplotlib pylab object label_fontsize (float): Fontsize of labels Returns plt of the locpot vs c axis
def get_locpot_along_slab_plot(self, label_energies=True, plt=None, label_fontsize=10): plt = pretty_plot(width=6, height=4) if not plt else plt # plot the raw locpot signal along c plt.plot(self.along_c, self.locpot_along_c, 'b--') # Get the local averaged signal of the locpot along c xg, yg = [], [] for i, p in enumerate(self.locpot_along_c): # average signal is just the bulk-like potential when in the slab region in_slab = False for r in self.slab_regions: if r[0] <= self.along_c[i] <= r[1]: in_slab = True if len(self.slab_regions) > 1: if self.along_c[i] >= self.slab_regions[1][1]: in_slab = True if self.along_c[i] <= self.slab_regions[0][0]: in_slab = True if in_slab: yg.append(self.ave_bulk_p) xg.append(self.along_c[i]) elif p < self.ave_bulk_p: yg.append(self.ave_bulk_p) xg.append(self.along_c[i]) else: yg.append(p) xg.append(self.along_c[i]) xg, yg = zip(*sorted(zip(xg, yg))) plt.plot(xg, yg, 'r', linewidth=2.5, zorder=-1) # make it look nice if label_energies: plt = self.get_labels(plt, label_fontsize=label_fontsize) plt.xlim([0, 1]) plt.ylim([min(self.locpot_along_c), self.vacuum_locpot+self.ave_locpot*0.2]) plt.xlabel(r"Fractional coordinates ($\hat{c}$)", fontsize=25) plt.xticks(fontsize=15, rotation=45) plt.ylabel(r"Potential (eV)", fontsize=25) plt.yticks(fontsize=15) return plt
141,324
Handles the optional labelling of the plot with relevant quantities Args: plt (plt): Plot of the locpot vs c axis label_fontsize (float): Fontsize of labels Returns Labelled plt
def get_labels(self, plt, label_fontsize=10): # center of vacuum and bulk region if len(self.slab_regions) > 1: label_in_vac = (self.slab_regions[0][1] + self.slab_regions[1][0])/2 if abs(self.slab_regions[0][0]-self.slab_regions[0][1]) > \ abs(self.slab_regions[1][0]-self.slab_regions[1][1]): label_in_bulk = self.slab_regions[0][1]/2 else: label_in_bulk = (self.slab_regions[1][1] + self.slab_regions[1][0]) / 2 else: label_in_bulk = (self.slab_regions[0][0] + self.slab_regions[0][1])/2 if self.slab_regions[0][0] > 1-self.slab_regions[0][1]: label_in_vac = self.slab_regions[0][0] / 2 else: label_in_vac = (1 + self.slab_regions[0][1]) / 2 plt.plot([0, 1], [self.vacuum_locpot]*2, 'b--', zorder=-5, linewidth=1) xy = [label_in_bulk, self.vacuum_locpot+self.ave_locpot*0.05] plt.annotate(r"$V_{vac}=%.2f$" %(self.vacuum_locpot), xy=xy, xytext=xy, color='b', fontsize=label_fontsize) # label the fermi energy plt.plot([0, 1], [self.efermi]*2, 'g--', zorder=-5, linewidth=3) xy = [label_in_bulk, self.efermi+self.ave_locpot*0.05] plt.annotate(r"$E_F=%.2f$" %(self.efermi), xytext=xy, xy=xy, fontsize=label_fontsize, color='g') # label the bulk-like locpot plt.plot([0, 1], [self.ave_bulk_p]*2, 'r--', linewidth=1., zorder=-1) xy = [label_in_vac, self.ave_bulk_p + self.ave_locpot * 0.05] plt.annotate(r"$V^{interior}_{slab}=%.2f$" % (self.ave_bulk_p), xy=xy, xytext=xy, color='r', fontsize=label_fontsize) # label the work function as a barrier plt.plot([label_in_vac]*2, [self.efermi, self.vacuum_locpot], 'k--', zorder=-5, linewidth=2) xy = [label_in_vac, self.efermi + self.ave_locpot * 0.05] plt.annotate(r"$\Phi=%.2f$" %(self.work_function), xy=xy, xytext=xy, fontsize=label_fontsize) return plt
141,325
Average voltage for path satisfying between a min and max voltage. Args: min_voltage (float): The minimum allowable voltage for a given step. max_voltage (float): The maximum allowable voltage allowable for a given step. Returns: Average voltage in V across the insertion path (a subset of the path can be chosen by the optional arguments)
def get_average_voltage(self, min_voltage=None, max_voltage=None): pairs_in_range = self._select_in_voltage_range(min_voltage, max_voltage) if len(pairs_in_range) == 0: return 0 total_cap_in_range = sum([p.mAh for p in pairs_in_range]) total_edens_in_range = sum([p.mAh * p.voltage for p in pairs_in_range]) return total_edens_in_range / total_cap_in_range
141,336
Selects VoltagePairs within a certain voltage range. Args: min_voltage (float): The minimum allowable voltage for a given step. max_voltage (float): The maximum allowable voltage allowable for a given step. Returns: A list of VoltagePair objects
def _select_in_voltage_range(self, min_voltage=None, max_voltage=None): min_voltage = min_voltage if min_voltage is not None \ else self.min_voltage max_voltage = max_voltage if max_voltage is not None \ else self.max_voltage return list(filter(lambda p: min_voltage <= p.voltage <= max_voltage, self.voltage_pairs))
141,341
Initializes with pymatgen Molecule or OpenBabel"s OBMol. Args: mol: pymatgen's Molecule or OpenBabel OBMol
def __init__(self, mol): if isinstance(mol, Molecule): if not mol.is_ordered: raise ValueError("OpenBabel Molecule only supports ordered " "molecules.") # For some reason, manually adding atoms does not seem to create # the correct OBMol representation to do things like force field # optimization. So we go through the indirect route of creating # an XYZ file and reading in that file. obmol = ob.OBMol() obmol.BeginModify() for site in mol: coords = [c for c in site.coords] atomno = site.specie.Z obatom = ob.OBAtom() obatom.thisown = 0 obatom.SetAtomicNum(atomno) obatom.SetVector(*coords) obmol.AddAtom(obatom) del obatom obmol.ConnectTheDots() obmol.PerceiveBondOrders() obmol.SetTotalSpinMultiplicity(mol.spin_multiplicity) obmol.SetTotalCharge(mol.charge) obmol.Center() obmol.Kekulize() obmol.EndModify() self._obmol = obmol elif isinstance(mol, ob.OBMol): self._obmol = mol
141,342
A wrapper to pybel's localopt method to optimize a Molecule. Args: forcefield: Default is mmff94. Options are 'gaff', 'ghemical', 'mmff94', 'mmff94s', and 'uff'. steps: Default is 500.
def localopt(self, forcefield='mmff94', steps=500): pbmol = pb.Molecule(self._obmol) pbmol.localopt(forcefield=forcefield, steps=steps) self._obmol = pbmol.OBMol
141,344
Remove a bond from an openbabel molecule Args: idx1: The atom index of one of the atoms participating the in bond idx2: The atom index of the other atom participating in the bond
def remove_bond(self, idx1, idx2): for obbond in ob.OBMolBondIter(self._obmol): if (obbond.GetBeginAtomIdx() == idx1 and obbond.GetEndAtomIdx() == idx2) or (obbond.GetBeginAtomIdx() == idx2 and obbond.GetEndAtomIdx() == idx1): self._obmol.DeleteBond(obbond)
141,346
Uses OpenBabel to output all supported formats. Args: filename: Filename of file to output file_format: String specifying any OpenBabel supported formats.
def write_file(self, filename, file_format="xyz"): mol = pb.Molecule(self._obmol) return mol.write(file_format, filename, overwrite=True)
141,350
Uses OpenBabel to read a molecule from a file in all supported formats. Args: filename: Filename of input file file_format: String specifying any OpenBabel supported formats. Returns: BabelMolAdaptor object
def from_file(filename, file_format="xyz"): mols = list(pb.readfile(str(file_format), str(filename))) return BabelMolAdaptor(mols[0].OBMol)
141,351
Uses OpenBabel to read a molecule from a string in all supported formats. Args: string_data: String containing molecule data. file_format: String specifying any OpenBabel supported formats. Returns: BabelMolAdaptor object
def from_string(string_data, file_format="xyz"): mols = pb.readstring(str(file_format), str(string_data)) return BabelMolAdaptor(mols.OBMol)
141,352
Initialize a `Structure` object from a string with data in XSF format. Args: input_string: String with the structure in XSF format. See http://www.xcrysden.org/doc/XSF.html cls_: Structure class to be created. default: pymatgen structure
def from_string(cls, input_string, cls_=None): # CRYSTAL see (1) # these are primitive lattice vectors (in Angstroms) # PRIMVEC # 0.0000000 2.7100000 2.7100000 see (2) # 2.7100000 0.0000000 2.7100000 # 2.7100000 2.7100000 0.0000000 # these are conventional lattice vectors (in Angstroms) # CONVVEC # 5.4200000 0.0000000 0.0000000 see (3) # 0.0000000 5.4200000 0.0000000 # 0.0000000 0.0000000 5.4200000 # these are atomic coordinates in a primitive unit cell (in Angstroms) # PRIMCOORD # 2 1 see (4) # 16 0.0000000 0.0000000 0.0000000 see (5) # 30 1.3550000 -1.3550000 -1.3550000 lattice, coords, species = [], [], [] lines = input_string.splitlines() for i in range(len(lines)): if "PRIMVEC" in lines[i]: for j in range(i+1, i+4): lattice.append([float(c) for c in lines[j].split()]) if "PRIMCOORD" in lines[i]: num_sites = int(lines[i+1].split()[0]) for j in range(i+2, i+2+num_sites): tokens = lines[j].split() species.append(int(tokens[0])) coords.append([float(j) for j in tokens[1:4]]) break else: raise ValueError("Invalid XSF data") if cls_ is None: from pymatgen.core.structure import Structure cls_ = Structure s = cls_(lattice, species, coords, coords_are_cartesian=True) return XSF(s)
141,360
Set the values of the ABINIT variables in the input files of the nodes Args: task_class: If not None, only the input files of the tasks belonging to class `task_class` are modified. Example: flow.walknset_vars(ecut=10, kptopt=4)
def walknset_vars(self, task_class=None, *args, **kwargs): def change_task(task): if task_class is not None and task.__class__ is not task_class: return False return True if self.is_work: for task in self: if not change_task(task): continue task.set_vars(*args, **kwargs) elif self.is_flow: for task in self.iflat_tasks(): if not change_task(task): continue task.set_vars(*args, **kwargs) else: raise TypeError("Don't know how to set variables for object class %s" % self.__class__.__name__)
141,410
This function is called once we have completed the initialization of the :class:`Work`. It sets the manager of each task (if not already done) and defines the working directories of the tasks. Args: manager: :class:`TaskManager` object or None
def allocate(self, manager=None): for i, task in enumerate(self): if not hasattr(task, "manager"): # Set the manager # Use the one provided in input else the one of the work/flow. if manager is not None: task.set_manager(manager) else: # Look first in work and then in the flow. if hasattr(self, "manager"): task.set_manager(self.manager) else: task.set_manager(self.flow.manager) task_workdir = os.path.join(self.workdir, "t" + str(i)) if not hasattr(task, "workdir"): task.set_workdir(task_workdir) else: if task.workdir != task_workdir: raise ValueError("task.workdir != task_workdir: %s, %s" % (task.workdir, task_workdir))
141,416
Returns a list with the status of the tasks in self. Args: only_min: If True, the minimum of the status is returned.
def get_all_status(self, only_min=False): if len(self) == 0: # The work will be created in the future. if only_min: return self.S_INIT else: return [self.S_INIT] self.check_status() status_list = [task.status for task in self] if only_min: return min(status_list) else: return status_list
141,419
Remove all files and directories in the working directory Args: exclude_wildcard: Optional string with regular expressions separated by `|`. Files matching one of the regular expressions will be preserved. example: exclude_wildard="*.nc|*.txt" preserves all the files whose extension is in ["nc", "txt"].
def rmtree(self, exclude_wildcard=""): if not exclude_wildcard: shutil.rmtree(self.workdir) else: w = WildCard(exclude_wildcard) for dirpath, dirnames, filenames in os.walk(self.workdir): for fname in filenames: path = os.path.join(dirpath, fname) if not w.match(fname): os.remove(path)
141,421
Create the SCR tasks and register them in self. Args: wfk_file: Path to the ABINIT WFK file to use for the computation of the screening. scr_input: Input for the screening calculation.
def create_tasks(self, wfk_file, scr_input): assert len(self) == 0 wfk_file = self.wfk_file = os.path.abspath(wfk_file) # Build a temporary work in the tmpdir that will use a shell manager # to run ABINIT in order to get the list of q-points for the screening. shell_manager = self.manager.to_shell_manager(mpi_procs=1) w = Work(workdir=self.tmpdir.path_join("_qptdm_run"), manager=shell_manager) fake_input = scr_input.deepcopy() fake_task = w.register(fake_input) w.allocate() w.build() # Create the symbolic link and add the magic value # nqpdm = -1 to the input to get the list of q-points. fake_task.inlink_file(wfk_file) fake_task.set_vars({"nqptdm": -1}) fake_task.start_and_wait() # Parse the section with the q-points with NetcdfReader(fake_task.outdir.has_abiext("qptdms.nc")) as reader: qpoints = reader.read_value("reduced_coordinates_of_kpoints") #print("qpoints) # Now we can register the task for the different q-points for qpoint in qpoints: qptdm_input = scr_input.deepcopy() qptdm_input.set_vars(nqptdm=1, qptdm=qpoint) new_task = self.register_scr_task(qptdm_input, manager=self.manager) # Add the garbage collector. if self.flow.gc is not None: new_task.set_gc(self.flow.gc) self.allocate()
141,439
Build tasks for the computation of Born effective charges and add them to the work. Args: scf_task: ScfTask object. ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run. None to use AbiPy default. ph_tolerance: dict {"varname": value} with the tolerance used in the phonon run. None to use AbiPy default. Return: (ddk_tasks, bec_tasks)
def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance): if not isinstance(scf_task, ScfTask): raise TypeError("task `%s` does not inherit from ScfTask" % scf_task) # DDK calculations (self-consistent to get electric field). multi_ddk = scf_task.input.make_ddk_inputs(tolerance=ddk_tolerance) ddk_tasks = [] for ddk_inp in multi_ddk: ddk_task = self.register_ddk_task(ddk_inp, deps={scf_task: "WFK"}) ddk_tasks.append(ddk_task) # Build the list of inputs for electric field perturbation and phonons # Each BEC task is connected to all the previous DDK task and to the scf_task. bec_deps = {ddk_task: "DDK" for ddk_task in ddk_tasks} bec_deps.update({scf_task: "WFK"}) bec_inputs = scf_task.input.make_bec_inputs(tolerance=ph_tolerance) bec_tasks = [] for bec_inp in bec_inputs: bec_task = self.register_bec_task(bec_inp, deps=bec_deps) bec_tasks.append(bec_task) return ddk_tasks, bec_tasks
141,442
This method is called when all the q-points have been computed. It runs `mrgdvdb` in sequential on the local machine to produce the final DVDB file in the outdir of the `Work`. Args: delete_source: True if POT1 files should be removed after (successful) merge. Returns: path to the output DVDB file. None if not DFPT POT file is found.
def merge_pot1_files(self, delete_source=True): natom = len(self[0].input.structure) max_pertcase = 3 * natom pot1_files = [] for task in self: if not isinstance(task, DfptTask): continue paths = task.outdir.list_filepaths(wildcard="*_POT*") for path in paths: # Include only atomic perturbations i.e. files whose ext <= 3 * natom i = path.rindex("_POT") pertcase = int(path[i+4:].replace(".nc", "")) if pertcase <= max_pertcase: pot1_files.append(path) # prtpot = 0 disables the output of the DFPT POT files so an empty list is not fatal here. if not pot1_files: return None self.history.info("Will call mrgdvdb to merge %s files:" % len(pot1_files)) # Final DDB file will be produced in the outdir of the work. out_dvdb = self.outdir.path_in("out_DVDB") if len(pot1_files) == 1: # Avoid the merge. Just move the DDB file to the outdir of the work shutil.copy(pot1_files[0], out_dvdb) else: # FIXME: The merge may require a non-negligible amount of memory if lots of qpts. # Besides there are machines such as lemaitre3 that are problematic when # running MPI applications on the front-end mrgdvdb = wrappers.Mrgdvdb(manager=self[0].manager, verbose=0) mrgdvdb.merge(self.outdir.path, pot1_files, out_dvdb, delete_source=delete_source) return out_dvdb
141,444
Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. ph_tolerance: dict {"varname": value} with the tolerance used in the phonon run. None to use AbiPy default. manager: :class:`TaskManager` object.
def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None): new = cls(manager=manager) new.add_becs_from_scf_task(scf_task, ddk_tolerance, ph_tolerance) return new
141,452
Build a DteWork from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. manager: :class:`TaskManager` object.
def from_scf_task(cls, scf_task, ddk_tolerance=None, manager=None): if not isinstance(scf_task, ScfTask): raise TypeError("task `%s` does not inherit from ScfTask" % scf_task) new = cls(manager=manager) # DDK calculations multi_ddk = scf_task.input.make_ddk_inputs(tolerance=ddk_tolerance) ddk_tasks = [] for ddk_inp in multi_ddk: ddk_task = new.register_ddk_task(ddk_inp, deps={scf_task: "WFK"}) ddk_tasks.append(ddk_task) # Build the list of inputs for electric field perturbation # Each task is connected to all the previous DDK, DDE task and to the scf_task. multi_dde = scf_task.input.make_dde_inputs(use_symmetries=False) # To compute the nonlinear coefficients all the directions of the perturbation # have to be taken in consideration # DDE calculations dde_tasks = [] dde_deps = {ddk_task: "DDK" for ddk_task in ddk_tasks} dde_deps.update({scf_task: "WFK"}) for dde_inp in multi_dde: dde_task = new.register_dde_task(dde_inp, deps=dde_deps) dde_tasks.append(dde_task) # DTE calculations dte_deps = {scf_task: "WFK DEN"} dte_deps.update({dde_task: "1WF 1DEN" for dde_task in dde_tasks}) multi_dte = scf_task.input.make_dte_inputs() dte_tasks = [] for dte_inp in multi_dte: dte_task = new.register_dte_task(dte_inp, deps=dte_deps) dte_tasks.append(dte_task) return new
141,454
Initializes an abstract defect Args: structure: Pymatgen Structure without any defects defect_site (Site): site for defect within structure must have same lattice as structure charge: (int or float) defect charge default is zero, meaning no change to NELECT after defect is created in the structure (assuming use_structure_charge=True in vasp input set)
def __init__(self, structure, defect_site, charge=0.): self._structure = structure self._charge = charge self._defect_site = defect_site if structure.lattice != defect_site.lattice: raise ValueError("defect_site lattice must be same as structure lattice.")
141,456
Returns Defective Vacancy structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): defect_structure = self.bulk_structure.copy() defect_structure.make_supercell(supercell) #create a trivial defect structure to find where supercell transformation moves the lattice struct_for_defect_site = Structure( self.bulk_structure.copy().lattice, [self.site.specie], [self.site.frac_coords], to_unit_cell=True) struct_for_defect_site.make_supercell(supercell) defect_site = struct_for_defect_site[0] poss_deflist = sorted( defect_structure.get_sites_in_sphere(defect_site.coords, 2, include_index=True), key=lambda x: x[1]) defindex = poss_deflist[0][2] defect_structure.remove_sites([defindex]) defect_structure.set_charge(self.charge) return defect_structure
141,458
Returns Defective Substitution structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): defect_structure = self.bulk_structure.copy() defect_structure.make_supercell(supercell) # consider modifying velocity property to make sure defect site is decorated # consistently with bulk structure for final defect_structure defect_properties = self.site.properties.copy() if ('velocities' in self.bulk_structure.site_properties) and \ 'velocities' not in defect_properties: if all( vel == self.bulk_structure.site_properties['velocities'][0] for vel in self.bulk_structure.site_properties['velocities']): defect_properties['velocities'] = self.bulk_structure.site_properties['velocities'][0] else: raise ValueError("No velocity property specified for defect site and " "bulk_structure velocities are not homogeneous. Please specify this " "property within the initialized defect_site object.") #create a trivial defect structure to find where supercell transformation moves the lattice site_properties_for_fake_struct = {prop: [val] for prop,val in defect_properties.items()} struct_for_defect_site = Structure( self.bulk_structure.copy().lattice, [self.site.specie], [self.site.frac_coords], to_unit_cell=True, site_properties = site_properties_for_fake_struct) struct_for_defect_site.make_supercell(supercell) defect_site = struct_for_defect_site[0] poss_deflist = sorted( defect_structure.get_sites_in_sphere(defect_site.coords, 2, include_index=True), key=lambda x: x[1]) defindex = poss_deflist[0][2] subsite = defect_structure.pop(defindex) defect_structure.append(self.site.specie.symbol, subsite.coords, coords_are_cartesian=True, properties = defect_site.properties) defect_structure.set_charge(self.charge) return defect_structure
141,461
Returns Defective Interstitial structure, decorated with charge Args: supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
def generate_defect_structure(self, supercell=(1, 1, 1)): defect_structure = self.bulk_structure.copy() defect_structure.make_supercell(supercell) # consider modifying velocity property to make sure defect site is decorated # consistently with bulk structure for final defect_structure defect_properties = self.site.properties.copy() if ('velocities' in self.bulk_structure.site_properties) and \ 'velocities' not in defect_properties: if all( vel == self.bulk_structure.site_properties['velocities'][0] for vel in self.bulk_structure.site_properties['velocities']): defect_properties['velocities'] = self.bulk_structure.site_properties['velocities'][0] else: raise ValueError("No velocity property specified for defect site and " "bulk_structure velocities are not homogeneous. Please specify this " "property within the initialized defect_site object.") #create a trivial defect structure to find where supercell transformation moves the defect site site_properties_for_fake_struct = {prop: [val] for prop,val in defect_properties.items()} struct_for_defect_site = Structure( self.bulk_structure.copy().lattice, [self.site.specie], [self.site.frac_coords], to_unit_cell=True, site_properties = site_properties_for_fake_struct) struct_for_defect_site.make_supercell(supercell) defect_site = struct_for_defect_site[0] defect_structure.append(self.site.specie.symbol, defect_site.coords, coords_are_cartesian=True, properties = defect_site.properties) defect_structure.set_charge(self.charge) return defect_structure
141,464
Reconstitute a DefectEntry object from a dict representation created using as_dict(). Args: d (dict): dict representation of DefectEntry. Returns: DefectEntry object
def from_dict(cls, d): defect = MontyDecoder().process_decoded( d["defect"]) uncorrected_energy = d["uncorrected_energy"] corrections = d.get("corrections", None) parameters = d.get("parameters", None) entry_id = d.get("entry_id", None) return cls(defect, uncorrected_energy, corrections=corrections, parameters=parameters, entry_id=entry_id)
141,469
Get the defect concentration for a temperature and Fermi level. Args: temperature: the temperature in K fermi_level: the fermi level in eV (with respect to the VBM) Returns: defects concentration in cm^-3
def defect_concentration(self, chemical_potentials, temperature=300, fermi_level=0.0): n = self.multiplicity * 1e24 / self.defect.bulk_structure.volume conc = n * np.exp(-1.0 * self.formation_energy(chemical_potentials, fermi_level=fermi_level) / (kb * temperature)) return conc
141,472
Corrects a single entry. Args: entry: A DefectEntry object. Returns: An processed entry. Raises: CompatibilityError if entry is not compatible.
def correct_entry(self, entry): entry.correction.update(self.get_correction(entry)) return entry
141,474
Returns the charge transferred for a particular atom. Requires POTCAR to be supplied. Args: atom_index: Index of atom. Returns: Charge transfer associated with atom from the Bader analysis. Given by final charge on atom - nelectrons in POTCAR for associated atom.
def get_charge_transfer(self, atom_index): if self.potcar is None: raise ValueError("POTCAR must be supplied in order to calculate " "charge transfer!") potcar_indices = [] for i, v in enumerate(self.natoms): potcar_indices += [i] * v nelect = self.potcar[potcar_indices[atom_index]].nelectrons return self.data[atom_index]["charge"] - nelect
141,478
Convenient constructor that takes in the path name of VASP run to perform Bader analysis. Args: path (str): Name of directory where VASP output files are stored. suffix (str): specific suffix to look for (e.g. '.relax1' for 'CHGCAR.relax1.gz').
def from_path(cls, path, suffix=""): def _get_filepath(filename): name_pattern = filename + suffix + '*' if filename != 'POTCAR' \ else filename + '*' paths = glob.glob(os.path.join(path, name_pattern)) fpath = None if len(paths) >= 1: # using reverse=True because, if multiple files are present, # they likely have suffixes 'static', 'relax', 'relax2', etc. # and this would give 'static' over 'relax2' over 'relax' # however, better to use 'suffix' kwarg to avoid this! paths.sort(reverse=True) warning_msg = "Multiple files detected, using %s" \ % os.path.basename(paths[0]) if len(paths) > 1 \ else None fpath = paths[0] else: warning_msg = "Could not find %s" % filename if filename in ['AECCAR0', 'AECCAR2']: warning_msg += ", cannot calculate charge transfer." elif filename == "POTCAR": warning_msg += ", interpret Bader results with caution." if warning_msg: warnings.warn(warning_msg) return fpath chgcar_filename = _get_filepath("CHGCAR") if chgcar_filename is None: raise IOError("Could not find CHGCAR!") potcar_filename = _get_filepath("POTCAR") aeccar0 = _get_filepath("AECCAR0") aeccar2 = _get_filepath("AECCAR2") if (aeccar0 and aeccar2): # `chgsum.pl AECCAR0 AECCAR2` equivalent to obtain chgref_file chgref = Chgcar.from_file(aeccar0) + Chgcar.from_file(aeccar2) chgref_filename = "CHGREF" chgref.write_file(chgref_filename) else: chgref_filename = None return cls(chgcar_filename, potcar_filename=potcar_filename, chgref_filename=chgref_filename)
141,481
Given a tuple of tuples, generate a delimited string form. >>> results = [["a","b","c"],["d","e","f"],[1,2,3]] >>> print(str_delimited(results,delimiter=",")) a,b,c d,e,f 1,2,3 Args: result: 2d sequence of arbitrary types. header: optional header Returns: Aligned string output in a table-like format.
def str_delimited(results, header=None, delimiter="\t"): returnstr = "" if header is not None: returnstr += delimiter.join(header) + "\n" return returnstr + "\n".join([delimiter.join([str(m) for m in result]) for result in results])
141,519
This function is used to make pretty formulas by formatting the amounts. Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4. Args: afloat (float): a float ignore_ones (bool): if true, floats of 1 are ignored. tol (float): Tolerance to round to nearest int. i.e. 2.0000000001 -> 2 Returns: A string representation of the float for formulas.
def formula_double_format(afloat, ignore_ones=True, tol=1e-8): if ignore_ones and afloat == 1: return "" elif abs(afloat - int(afloat)) < tol: return str(int(afloat)) else: return str(round(afloat, 8))
141,520
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to P2$_{1}$/c and P-1 is converted to P$\\overline{1}$. Args: spacegroup_symbol (str): A spacegroup symbol Returns: A latex formatted spacegroup with proper subscripts and overlines.
def latexify_spacegroup(spacegroup_symbol): sym = re.sub(r"_(\d+)", r"$_{\1}$", spacegroup_symbol) return re.sub(r"-(\d)", r"$\\overline{\1}$", sym)
141,522
Compare the bond table of the two molecules. Args: mol1: first molecule. pymatgen Molecule object. mol2: second moleculs. pymatgen Molecule objec.
def are_equal(self, mol1, mol2): b1 = set(self._get_bonds(mol1)) b2 = set(self._get_bonds(mol2)) return b1 == b2
141,528
Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms.
def _get_bonds(self, mol): num_atoms = len(mol) # index starting from 0 if self.ignore_ionic_bond: covalent_atoms = [i for i in range(num_atoms) if mol.species[i].symbol not in self.ionic_element_list] else: covalent_atoms = list(range(num_atoms)) all_pairs = list(itertools.combinations(covalent_atoms, 2)) pair_dists = [mol.get_distance(*p) for p in all_pairs] elements = mol.composition.as_dict().keys() unavailable_elements = list(set(elements) - set(self.covalent_radius.keys())) if len(unavailable_elements) > 0: raise ValueError("The covalent radius for element {} is not " "available".format(unavailable_elements)) bond_13 = self.get_13_bonds(self.priority_bonds) max_length = [(self.covalent_radius[mol.sites[p[0]].specie.symbol] + self.covalent_radius[mol.sites[p[1]].specie.symbol]) * (1 + (self.priority_cap if p in self.priority_bonds else (self.bond_length_cap if p not in bond_13 else self.bond_13_cap))) * (0.1 if (self.ignore_halogen_self_bond and p not in self.priority_bonds and mol.sites[p[0]].specie.symbol in self.halogen_list and mol.sites[p[1]].specie.symbol in self.halogen_list) else 1.0) for p in all_pairs] bonds = [bond for bond, dist, cap in zip(all_pairs, pair_dists, max_length) if dist <= cap] return bonds
141,530
Parses .outputtrans file Args: path_dir: dir containing boltztrap.outputtrans Returns: tuple - (run_type, warning, efermi, gap, doping_levels)
def parse_outputtrans(path_dir): run_type = None warning = None efermi = None gap = None doping_levels = [] with open(os.path.join(path_dir, "boltztrap.outputtrans"), 'r') \ as f: for line in f: if "WARNING" in line: warning = line elif "Calc type:" in line: run_type = line.split()[-1] elif line.startswith("VBM"): efermi = Energy(line.split()[1], "Ry").to("eV") elif line.startswith("Egap:"): gap = Energy(float(line.split()[1]), "Ry").to("eV") elif line.startswith("Doping level number"): doping_levels.append(float(line.split()[6])) return run_type, warning, efermi, gap, doping_levels
141,568
Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files Args: path_dir: (str) dir containing DOS files efermi: (float) Fermi energy dos_spin: (int) -1 for spin down, +1 for spin up trim_dos: (bool) whether to post-process / trim DOS Returns: tuple - (DOS, dict of partial DOS)
def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): data_dos = {'total': [], 'partial': {}} # parse the total DOS data ## format is energy, DOS, integrated DOS with open(os.path.join(path_dir, "boltztrap.transdos"), 'r') as f: count_series = 0 # TODO: why is count_series needed? for line in f: if line.lstrip().startswith("#"): count_series += 1 if count_series > 1: break else: data_dos['total'].append( [Energy(float(line.split()[0]), "Ry").to("eV"), float(line.split()[1])]) total_elec = float(line.split()[2]) lw_l = 0 hg_l = -len(data_dos['total']) if trim_dos: # Francesco knows what this does # It has something to do with a trick of adding fake energies # at the endpoints of the DOS, and then re-trimming it. This is # to get the same energy scale for up and down spin DOS. tmp_data = np.array(data_dos['total']) tmp_den = np.trim_zeros(tmp_data[:, 1], 'f')[1:] lw_l = len(tmp_data[:, 1]) - len(tmp_den) tmp_ene = tmp_data[lw_l:, 0] tmp_den = np.trim_zeros(tmp_den, 'b')[:-1] hg_l = len(tmp_ene) - len(tmp_den) tmp_ene = tmp_ene[:-hg_l] tmp_data = np.vstack((tmp_ene, tmp_den)).T data_dos['total'] = tmp_data.tolist() # parse partial DOS data for file_name in os.listdir(path_dir): if file_name.endswith( "transdos") and file_name != 'boltztrap.transdos': tokens = file_name.split(".")[1].split("_") site = tokens[1] orb = '_'.join(tokens[2:]) with open(os.path.join(path_dir, file_name), 'r') as f: for line in f: if not line.lstrip().startswith(" #"): if site not in data_dos['partial']: data_dos['partial'][site] = {} if orb not in data_dos['partial'][site]: data_dos['partial'][site][orb] = [] data_dos['partial'][site][orb].append( float(line.split()[1])) data_dos['partial'][site][orb] = data_dos['partial'][site][ orb][lw_l:-hg_l] dos_full = {'energy': [], 'density': []} for t in data_dos['total']: dos_full['energy'].append(t[0]) dos_full['density'].append(t[1]) dos = Dos(efermi, dos_full['energy'], {Spin(dos_spin): dos_full['density']}) dos_partial = data_dos['partial'] # TODO: make this real DOS object? return dos, dos_partial
141,569
Parses boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs Args: path_dir: (str) dir containing the boltztrap.intrans file Returns: intrans (dict): a dictionary containing various inputs that had been used in the Boltztrap run.
def parse_intrans(path_dir): intrans = {} with open(os.path.join(path_dir, "boltztrap.intrans"), 'r') as f: for line in f: if "iskip" in line: intrans["scissor"] = Energy(float(line.split(" ")[3]), "Ry").to("eV") if "HISTO" in line or "TETRA" in line: intrans["dos_type"] = line[:-1] return intrans
141,570
Parses boltztrap.struct file (only the volume) Args: path_dir: (str) dir containing the boltztrap.struct file Returns: (float) volume
def parse_struct(path_dir): with open(os.path.join(path_dir, "boltztrap.struct"), 'r') as f: tokens = f.readlines() return Lattice([[Length(float(tokens[i].split()[j]), "bohr"). to("ang") for j in range(3)] for i in range(1, 4)]).volume
141,571
Parses the conductivity and Hall tensors Args: path_dir: Path containing .condtens / .halltens files doping_levels: ([float]) - doping lvls, parse outtrans to get this Returns: mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, mu_doping, seebeck_doping, cond_doping, kappa_doping, hall_doping, carrier_conc
def parse_cond_and_hall(path_dir, doping_levels=None): # Step 1: parse raw data but do not convert to final format t_steps = set() mu_steps = set() data_full = [] data_hall = [] data_doping_full = [] data_doping_hall = [] doping_levels = doping_levels or [] # parse the full conductivity/Seebeck/kappa0/etc data ## also initialize t_steps and mu_steps with open(os.path.join(path_dir, "boltztrap.condtens"), 'r') as f: for line in f: if not line.startswith("#"): mu_steps.add(float(line.split()[0])) t_steps.add(int(float(line.split()[1]))) data_full.append([float(c) for c in line.split()]) # parse the full Hall tensor with open(os.path.join(path_dir, "boltztrap.halltens"), 'r') as f: for line in f: if not line.startswith("#"): data_hall.append([float(c) for c in line.split()]) if len(doping_levels) != 0: # parse doping levels version of full cond. tensor, etc. with open( os.path.join(path_dir, "boltztrap.condtens_fixdoping"), 'r') as f: for line in f: if not line.startswith("#") and len(line) > 2: data_doping_full.append([float(c) for c in line.split()]) # parse doping levels version of full hall tensor with open( os.path.join(path_dir, "boltztrap.halltens_fixdoping"), 'r') as f: for line in f: if not line.startswith("#") and len(line) > 2: data_doping_hall.append( [float(c) for c in line.split()]) # Step 2: convert raw data to final format # sort t and mu_steps (b/c they are sets not lists) # and convert to correct energy t_steps = sorted([t for t in t_steps]) mu_steps = sorted([Energy(m, "Ry").to("eV") for m in mu_steps]) # initialize output variables - could use defaultdict instead # I am leaving things like this for clarity cond = {t: [] for t in t_steps} seebeck = {t: [] for t in t_steps} kappa = {t: [] for t in t_steps} hall = {t: [] for t in t_steps} carrier_conc = {t: [] for t in t_steps} dos_full = {'energy': [], 'density': []} mu_doping = {'p': {t: [] for t in t_steps}, 'n': {t: [] for t in t_steps}} seebeck_doping = {'p': {t: [] for t in t_steps}, 'n': {t: [] for t in t_steps}} cond_doping = {'p': {t: [] for t in t_steps}, 'n': {t: [] for t in t_steps}} kappa_doping = {'p': {t: [] for t in t_steps}, 'n': {t: [] for t in t_steps}} hall_doping = {'p': {t: [] for t in t_steps}, 'n': {t: [] for t in t_steps}} # process doping levels pn_doping_levels = {'p': [], 'n': []} for d in doping_levels: if d > 0: pn_doping_levels['p'].append(d) else: pn_doping_levels['n'].append(-d) # process raw conductivity data, etc. for d in data_full: temp, doping = d[1], d[2] carrier_conc[temp].append(doping) cond[temp].append(np.reshape(d[3:12], (3, 3)).tolist()) seebeck[temp].append(np.reshape(d[12:21], (3, 3)).tolist()) kappa[temp].append(np.reshape(d[21:30], (3, 3)).tolist()) # process raw Hall data for d in data_hall: temp, doping = d[1], d[2] hall_tens = [np.reshape(d[3:12], (3, 3)).tolist(), np.reshape(d[12:21], (3, 3)).tolist(), np.reshape(d[21:30], (3, 3)).tolist()] hall[temp].append(hall_tens) # process doping conductivity data, etc. for d in data_doping_full: temp, doping, mu = d[0], d[1], d[-1] pn = 'p' if doping > 0 else 'n' mu_doping[pn][temp].append(Energy(mu, "Ry").to("eV")) cond_doping[pn][temp].append( np.reshape(d[2:11], (3, 3)).tolist()) seebeck_doping[pn][temp].append( np.reshape(d[11:20], (3, 3)).tolist()) kappa_doping[pn][temp].append( np.reshape(d[20:29], (3, 3)).tolist()) # process doping Hall data for d in data_doping_hall: temp, doping, mu = d[0], d[1], d[-1] pn = 'p' if doping > 0 else 'n' hall_tens = [np.reshape(d[2:11], (3, 3)).tolist(), np.reshape(d[11:20], (3, 3)).tolist(), np.reshape(d[20:29], (3, 3)).tolist()] hall_doping[pn][temp].append(hall_tens) return mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, \ mu_doping, seebeck_doping, cond_doping, kappa_doping, \ hall_doping, carrier_conc
141,572
get a BoltztrapAnalyzer object from a set of files Args: path_dir: directory where the boltztrap files are dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down Returns: a BoltztrapAnalyzer object
def from_files(path_dir, dos_spin=1): run_type, warning, efermi, gap, doping_levels = \ BoltztrapAnalyzer.parse_outputtrans(path_dir) vol = BoltztrapAnalyzer.parse_struct(path_dir) intrans = BoltztrapAnalyzer.parse_intrans(path_dir) if run_type == "BOLTZ": dos, pdos = BoltztrapAnalyzer.parse_transdos( path_dir, efermi, dos_spin=dos_spin, trim_dos=False) mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, mu_doping, \ seebeck_doping, cond_doping, kappa_doping, hall_doping, \ carrier_conc = BoltztrapAnalyzer. \ parse_cond_and_hall(path_dir, doping_levels) return BoltztrapAnalyzer( gap, mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, mu_doping, seebeck_doping, cond_doping, kappa_doping, hall_doping, intrans, dos, pdos, carrier_conc, vol, warning) elif run_type == "DOS": trim = True if intrans["dos_type"] == "HISTO" else False dos, pdos = BoltztrapAnalyzer.parse_transdos( path_dir, efermi, dos_spin=dos_spin, trim_dos=trim) return BoltztrapAnalyzer(gap=gap, dos=dos, dos_partial=pdos, warning=warning, vol=vol) elif run_type == "BANDS": bz_kpoints = np.loadtxt( os.path.join(path_dir, "boltztrap_band.dat"))[:, -3:] bz_bands = np.loadtxt( os.path.join(path_dir, "boltztrap_band.dat"))[:, 1:-6] return BoltztrapAnalyzer(bz_bands=bz_bands, bz_kpoints=bz_kpoints, warning=warning, vol=vol) elif run_type == "FERMI": if os.path.exists(os.path.join(path_dir, 'boltztrap_BZ.cube')): fs_data = read_cube_file( os.path.join(path_dir, 'boltztrap_BZ.cube')) elif os.path.exists(os.path.join(path_dir, 'fort.30')): fs_data = read_cube_file(os.path.join(path_dir, 'fort.30')) else: raise BoltztrapError("No data file found for fermi surface") return BoltztrapAnalyzer(fermi_surface_data=fs_data) else: raise ValueError("Run type: {} not recognized!".format(run_type))
141,573
Generator that parses dump file(s). Args: file_pattern (str): Filename to parse. The timestep wildcard (e.g., dump.atom.'*') is supported and the files are parsed in the sequence of timestep. Yields: LammpsDump for each available snapshot.
def parse_lammps_dumps(file_pattern): files = glob.glob(file_pattern) if len(files) > 1: pattern = r"%s" % file_pattern.replace("*", "([0-9]+)") pattern = pattern.replace("\\", "\\\\") files = sorted(files, key=lambda f: int(re.match(pattern, f).group(1))) for fname in files: with zopen(fname, "rt") as f: dump_cache = [] for line in f: if line.startswith("ITEM: TIMESTEP"): if len(dump_cache) > 0: yield LammpsDump.from_string("".join(dump_cache)) dump_cache = [line] else: dump_cache.append(line) yield LammpsDump.from_string("".join(dump_cache))
141,580
Base constructor. Args: timestep (int): Current timestep. natoms (int): Total number of atoms in the box. box (LammpsBox): Simulation box. data (pd.DataFrame): Dumped atomic data.
def __init__(self, timestep, natoms, box, data): self.timestep = timestep self.natoms = natoms self.box = box self.data = data
141,582
Constructor from string parsing. Args: string (str): Input string.
def from_string(cls, string): lines = string.split("\n") timestep = int(lines[1]) natoms = int(lines[3]) box_arr = np.loadtxt(StringIO("\n".join(lines[5:8]))) bounds = box_arr[:, :2] tilt = None if "xy xz yz" in lines[4]: tilt = box_arr[:, 2] x = (0, tilt[0], tilt[1], tilt[0] + tilt[1]) y = (0, tilt[2]) bounds -= np.array([[min(x), max(x)], [min(y), max(y)], [0, 0]]) box = LammpsBox(bounds, tilt) data_head = lines[8].replace("ITEM: ATOMS", "").split() data = pd.read_csv(StringIO("\n".join(lines[9:])), names=data_head, delim_whitespace=True) return cls(timestep, natoms, box, data)
141,583
Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`. Args: unit: Specific units (eV, Ha, m, ang, etc.).
def obj_with_unit(obj, unit): unit_type = _UNAME2UTYPE[unit] if isinstance(obj, numbers.Number): return FloatWithUnit(obj, unit=unit, unit_type=unit_type) elif isinstance(obj, collections.Mapping): return {k: obj_with_unit(v, unit) for k,v in obj.items()} else: return ArrayWithUnit(obj, unit=unit, unit_type=unit_type)
141,604
Constructs a unit. Args: unit_def: A definition for the unit. Either a mapping of unit to powers, e.g., {"m": 2, "s": -1} represents "m^2 s^-1", or simply as a string "kg m^2 s^-1". Note that the supported format uses "^" as the power operator and all units must be space-separated.
def __init__(self, unit_def): if isinstance(unit_def, str): unit = collections.defaultdict(int) import re for m in re.finditer(r"([A-Za-z]+)\s*\^*\s*([\-0-9]*)", unit_def): p = m.group(2) p = 1 if not p else int(p) k = m.group(1) unit[k] += p else: unit = {k: v for k, v in dict(unit_def).items() if v != 0} self._unit = check_mappings(unit)
141,606
Returns a conversion factor between this unit and a new unit. Compound units are supported, but must have the same powers in each unit type. Args: new_unit: The new unit.
def get_conversion_factor(self, new_unit): uo_base, ofactor = self.as_base_units un_base, nfactor = Unit(new_unit).as_base_units units_new = sorted(un_base.items(), key=lambda d: _UNAME2UTYPE[d[0]]) units_old = sorted(uo_base.items(), key=lambda d: _UNAME2UTYPE[d[0]]) factor = ofactor / nfactor for uo, un in zip(units_old, units_new): if uo[1] != un[1]: raise UnitError("Units %s and %s are not compatible!" % (uo, un)) c = ALL_UNITS[_UNAME2UTYPE[uo[0]]] factor *= (c[uo[0]] / c[un[0]]) ** uo[1] return factor
141,611
Initializes a float with unit. Args: val (float): Value unit (Unit): A unit. E.g., "C". unit_type (str): A type of unit. E.g., "charge"
def __init__(self, val, unit, unit_type=None): if unit_type is not None and str(unit) not in ALL_UNITS[unit_type]: raise UnitError( "{} is not a supported unit for {}".format(unit, unit_type)) self._unit = Unit(unit) self._unit_type = unit_type
141,614
Conversion to a new_unit. Right now, only supports 1 to 1 mapping of units of each type. Args: new_unit: New unit type. Returns: A FloatWithUnit object in the new units. Example usage: >>> e = Energy(1.1, "eV") >>> e = Energy(1.1, "Ha") >>> e.to("eV") 29.932522246 eV
def to(self, new_unit): return FloatWithUnit( self * self.unit.get_conversion_factor(new_unit), unit_type=self._unit_type, unit=new_unit)
141,622
Conversion to a new_unit. Args: new_unit: New unit type. Returns: A ArrayWithFloatWithUnit object in the new units. Example usage: >>> e = EnergyArray([1, 1.1], "Ha") >>> e.to("eV") array([ 27.21138386, 29.93252225]) eV
def to(self, new_unit): return self.__class__( np.array(self) * self.unit.get_conversion_factor(new_unit), unit_type=self.unit_type, unit=new_unit)
141,629
Attempt to convert a vector of floats to whole numbers. Args: miller_index (list of float): A list miller indexes. round_dp (int, optional): The number of decimal places to round the miller index to. verbose (bool, optional): Whether to print warnings. Returns: (tuple): The Miller index.
def get_integer_index( miller_index: bool, round_dp: int = 4, verbose: bool = True ) -> Tuple[int, int, int]: miller_index = np.asarray(miller_index) # deal with the case we have small irregular floats # that are all equal or factors of each other miller_index /= min([m for m in miller_index if m != 0]) miller_index /= np.max(np.abs(miller_index)) # deal with the case we have nice fractions md = [Fraction(n).limit_denominator(12).denominator for n in miller_index] miller_index *= reduce(lambda x, y: x * y, md) int_miller_index = np.int_(np.round(miller_index, 1)) miller_index /= np.abs(reduce(gcd, int_miller_index)) # round to a reasonable precision miller_index = np.array([round(h, round_dp) for h in miller_index]) # need to recalculate this after rounding as values may have changed int_miller_index = np.int_(np.round(miller_index, 1)) if np.any(np.abs(miller_index - int_miller_index) > 1e-6) and verbose: warnings.warn("Non-integer encountered in Miller index") else: miller_index = int_miller_index # minimise the number of negative indexes miller_index += 0 # converts -0 to 0 def n_minus(index): return len([h for h in index if h < 0]) if n_minus(miller_index) > n_minus(miller_index * -1): miller_index *= -1 # if only one index is negative, make sure it is the smallest # e.g. (-2 1 0) -> (2 -1 0) if ( sum(miller_index != 0) == 2 and n_minus(miller_index) == 1 and abs(min(miller_index)) > max(miller_index) ): miller_index *= -1 return tuple(miller_index)
141,631
Returns the cartesian coordinates given fractional coordinates. Args: fractional_coords (3x1 array): Fractional coords. Returns: Cartesian coordinates
def get_cartesian_coords(self, fractional_coords: Vector3Like) -> np.ndarray: return dot(fractional_coords, self._matrix)
141,638