From 36cde41ebdbb30c71dca746dd5140273a1514d40 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Sat, 8 Jun 2024 11:11:51 -0400 Subject: [PATCH] np.newaxis -> None json->JSON, yaml->YAML in doc strings --- .pre-commit-config.yaml | 4 +- dev_scripts/regen_libxcfunc.py | 11 ++-- pymatgen/analysis/bond_valence.py | 2 +- pymatgen/analysis/dimensionality.py | 4 +- .../analysis/ferroelectricity/polarization.py | 12 ++-- pymatgen/analysis/graphs.py | 4 +- pymatgen/analysis/magnetism/heisenberg.py | 56 +++++++++---------- .../substitution_probability.py | 10 ++-- pymatgen/analysis/transition_state.py | 2 +- pymatgen/cli/pmg.py | 2 +- pymatgen/command_line/critic2_caller.py | 6 +- pymatgen/command_line/vampire_caller.py | 2 +- pymatgen/core/__init__.py | 2 +- pymatgen/core/libxcfunc.py | 4 +- pymatgen/core/periodic_table.py | 2 +- pymatgen/core/surface.py | 4 +- pymatgen/electronic_structure/plotter.py | 2 +- pymatgen/ext/matproj_legacy.py | 2 +- pymatgen/io/common.py | 2 +- pymatgen/io/phonopy.py | 4 +- pymatgen/io/vasp/inputs.py | 4 +- pymatgen/io/vasp/outputs.py | 4 +- pymatgen/phonon/bandstructure.py | 2 +- pymatgen/phonon/ir_spectra.py | 9 ++- .../test_substitution_probability.py | 2 +- tests/apps/battery/test_insertion_battery.py | 27 +++++---- tests/electronic_structure/test_cohp.py | 2 +- .../test_advanced_transformations.py | 4 +- 28 files changed, 92 insertions(+), 99 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eb7a72ef6ca..0c66fbd86bf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,7 +8,7 @@ ci: repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.4.7 + rev: v0.4.8 hooks: - id: ruff args: [--fix, --unsafe-fixes] @@ -64,6 +64,6 @@ repos: args: [--drop-empty-cells, --keep-output] - repo: https://github.com/RobertCraigie/pyright-python - rev: v1.1.365 + rev: v1.1.366 hooks: - id: pyright diff --git a/dev_scripts/regen_libxcfunc.py b/dev_scripts/regen_libxcfunc.py index 885c7ac1f2e..98f9936a5c0 100755 --- a/dev_scripts/regen_libxcfunc.py +++ b/dev_scripts/regen_libxcfunc.py @@ -2,7 +2,7 @@ """ This script regenerates the enum values in pymatgen.core.libxc_func.py. It requires in input the path of the `libxc_docs.txt` file contained in libxc/src -The script parses this file, creates a new json file inside pymatgen.core +The script parses this file, creates a new JSON file inside pymatgen.core and update the enum values declared in LibxcFunc. The script must be executed inside pymatgen/dev_scripts. """ @@ -16,10 +16,7 @@ def parse_libxc_docs(path): - """ - Parse libxc_docs.txt file, return dictionary with mapping: - libxc_id --> info_dict. - """ + """Parse libxc_docs.txt file, return dictionary {libxc_id: info_dict}.""" def parse_section(section): dct = {} @@ -46,7 +43,7 @@ def parse_section(section): def write_libxc_docs_json(xc_funcs, json_path): - """Write json file with libxc metadata to path jpath.""" + """Write JSON file with libxc metadata to path jpath.""" xc_funcs = deepcopy(xc_funcs) # Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable. @@ -85,7 +82,7 @@ def main(): xc_funcs = parse_libxc_docs(path) - # Generate new json file in pycore + # Generate new JSON file in pycore pmg_core = os.path.abspath("../pymatgen/core/") json_path = f"{pmg_core}/libxc_docs.json" write_libxc_docs_json(xc_funcs, json_path) diff --git a/pymatgen/analysis/bond_valence.py b/pymatgen/analysis/bond_valence.py index bdfef485abc..e9cbe1fc47b 100644 --- a/pymatgen/analysis/bond_valence.py +++ b/pymatgen/analysis/bond_valence.py @@ -29,7 +29,7 @@ for key, val in loadfn(f"{module_dir}/bvparam_1991.yaml").items(): BV_PARAMS[Element(key)] = val -# Read in yaml containing data-mined ICSD BV data. +# Read in YAML containing data-mined ICSD BV data. all_data = loadfn(f"{module_dir}/icsd_bv.yaml") ICSD_BV_DATA = {Species.from_str(sp): data for sp, data in all_data["bvsum"].items()} PRIOR_PROB = {Species.from_str(sp): data for sp, data in all_data["occurrence"].items()} diff --git a/pymatgen/analysis/dimensionality.py b/pymatgen/analysis/dimensionality.py index 0ba591a3155..7ce19444e03 100644 --- a/pymatgen/analysis/dimensionality.py +++ b/pymatgen/analysis/dimensionality.py @@ -403,9 +403,9 @@ def find_connected_atoms(struct, tolerance=0.45, ldict=None): n_atoms = len(struct.species) fc = np.array(struct.frac_coords) - fc_copy = np.repeat(fc[:, :, np.newaxis], 27, axis=2) + fc_copy = np.repeat(fc[:, :, None], 27, axis=2) neighbors = np.array(list(itertools.product([0, 1, -1], [0, 1, -1], [0, 1, -1]))).T - neighbors = np.repeat(neighbors[np.newaxis, :, :], 1, axis=0) + neighbors = np.repeat(neighbors[None, :, :], 1, axis=0) fc_diff = fc_copy - neighbors species = list(map(str, struct.species)) # in case of charged species diff --git a/pymatgen/analysis/ferroelectricity/polarization.py b/pymatgen/analysis/ferroelectricity/polarization.py index 08df27786b6..398fee58930 100644 --- a/pymatgen/analysis/ferroelectricity/polarization.py +++ b/pymatgen/analysis/ferroelectricity/polarization.py @@ -146,7 +146,9 @@ class Polarization: electron Angstroms along the three lattice directions (a,b,c). """ - def __init__(self, p_elecs, p_ions, structures, p_elecs_in_cartesian=True, p_ions_in_cartesian=False): + def __init__( + self, p_elecs, p_ions, structures: Sequence[Structure], p_elecs_in_cartesian=True, p_ions_in_cartesian=False + ): """ p_elecs: np.array of electronic contribution to the polarization with shape [N, 3] p_ions: np.array of ionic contribution to the polarization with shape [N, 3] @@ -260,8 +262,8 @@ def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_ p_tot = p_elec + p_ion p_tot = np.array(p_tot) - lattices = [s.lattice for s in self.structures] - volumes = np.array([s.lattice.volume for s in self.structures]) + lattices = [struct.lattice for struct in self.structures] + volumes = np.array([latt.volume for latt in lattices]) n_elecs = len(p_elec) @@ -273,7 +275,7 @@ def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_ # convert polarizations and lattice lengths prior to adjustment if convert_to_muC_per_cm2 and not all_in_polar: # Convert the total polarization - p_tot = np.multiply(units.T[:, np.newaxis], p_tot) + p_tot = np.multiply(units.T[:, None], p_tot) # adjust lattices for idx in range(n_elecs): lattice = lattices[idx] @@ -316,7 +318,7 @@ def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True): """Get the dipole / polarization quanta along a, b, and c for all structures. """ - lattices = [s.lattice for s in self.structures] + lattices = [struct.lattice for struct in self.structures] volumes = np.array([struct.volume for struct in self.structures]) n_structs = len(self.structures) diff --git a/pymatgen/analysis/graphs.py b/pymatgen/analysis/graphs.py index 82cd352b036..1722aea1720 100644 --- a/pymatgen/analysis/graphs.py +++ b/pymatgen/analysis/graphs.py @@ -150,7 +150,7 @@ def __init__(self, structure: Structure, graph_data: dict | None = None) -> None self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) - # tidy up edge attr dicts, reading to/from json duplicates information + # tidy up edge attr dicts, reading to/from JSON duplicates information for _, _, _, data in self.graph.edges(keys=True, data=True): for key in ("id", "key"): data.pop(key, None) @@ -1585,7 +1585,7 @@ def __init__(self, molecule, graph_data=None): self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) - # tidy up edge attr dicts, reading to/from json duplicates + # tidy up edge attr dicts, reading to/from JSON duplicates # information for _, _, _, data in self.graph.edges(keys=True, data=True): for key in ("id", "key"): diff --git a/pymatgen/analysis/magnetism/heisenberg.py b/pymatgen/analysis/magnetism/heisenberg.py index 42279314659..35f4c12f116 100644 --- a/pymatgen/analysis/magnetism/heisenberg.py +++ b/pymatgen/analysis/magnetism/heisenberg.py @@ -555,18 +555,18 @@ def get_interaction_graph(self, filename=None): logging.warning(warning_msg) # J_ij exchange interaction matrix - for i, _node in enumerate(sgraph.graph.nodes): - connections = sgraph.get_connected_sites(i) + for idx in range(len(sgraph.graph.nodes)): + connections = sgraph.get_connected_sites(idx) for c in connections: jimage = c[1] # relative integer coordinates of atom j j = c[2] # index of neighbor dist = c[-1] # i <-> j distance - j_exc = self._get_j_exc(i, j, dist) + j_exc = self._get_j_exc(idx, j, dist) - igraph.add_edge(i, j, to_jimage=jimage, weight=j_exc, warn_duplicates=False) + igraph.add_edge(idx, j, to_jimage=jimage, weight=j_exc, warn_duplicates=False) - # Save to a json file if desired + # Save to a JSON file if desired if filename: if not filename.endswith(".json"): filename += ".json" @@ -641,7 +641,7 @@ def get_heisenberg_model(self): hm_nni = self.nn_interactions hm_d = self.dists - # Exchange matrix DataFrame in json format + # Exchange matrix DataFrame in JSON format hm_em = self.ex_mat.to_json() hm_ep = self.get_exchange() hm_javg = self.estimate_exchange() @@ -860,29 +860,27 @@ def __init__( self.igraph = igraph def as_dict(self): - """Because some dicts have tuple keys, some sanitization is required for json compatibility.""" - dct = {} - dct["@module"] = type(self).__module__ - dct["@class"] = type(self).__name__ - dct["@version"] = __version__ - dct["formula"] = self.formula - dct["structures"] = [s.as_dict() for s in self.structures] - dct["energies"] = self.energies - dct["cutoff"] = self.cutoff - dct["tol"] = self.tol - dct["sgraphs"] = [sgraph.as_dict() for sgraph in self.sgraphs] - dct["dists"] = self.dists - dct["ex_params"] = self.ex_params - dct["javg"] = self.javg - dct["igraph"] = self.igraph.as_dict() - - # Sanitize tuple & int keys - dct["ex_mat"] = jsanitize(self.ex_mat) - dct["nn_interactions"] = jsanitize(self.nn_interactions) - dct["unique_site_ids"] = jsanitize(self.unique_site_ids) - dct["wyckoff_ids"] = jsanitize(self.wyckoff_ids) - - return dct + """Because some dicts have tuple keys, some sanitization is required for JSON compatibility.""" + return { + "@module": type(self).__module__, + "@class": type(self).__name__, + "@version": __version__, + "formula": self.formula, + "structures": [struct.as_dict() for struct in self.structures], + "energies": self.energies, + "cutoff": self.cutoff, + "tol": self.tol, + "sgraphs": [sgraph.as_dict() for sgraph in self.sgraphs], + "dists": self.dists, + "ex_params": self.ex_params, + "javg": self.javg, + "igraph": self.igraph.as_dict(), + # Sanitize tuple & int keys + "ex_mat": jsanitize(self.ex_mat), + "nn_interactions": jsanitize(self.nn_interactions), + "unique_site_ids": jsanitize(self.unique_site_ids), + "wyckoff_ids": jsanitize(self.wyckoff_ids), + } @classmethod def from_dict(cls, dct: dict) -> Self: diff --git a/pymatgen/analysis/structure_prediction/substitution_probability.py b/pymatgen/analysis/structure_prediction/substitution_probability.py index 07409e0bca7..bcdcd8598e5 100644 --- a/pymatgen/analysis/structure_prediction/substitution_probability.py +++ b/pymatgen/analysis/structure_prediction/substitution_probability.py @@ -50,11 +50,9 @@ class SubstitutionProbability: def __init__(self, lambda_table=None, alpha=-5): """ Args: - lambda_table: - json table of the weight functions lambda if None, + lambda_table: JSON table of the weight functions lambda if None, will use the default lambda.json table - alpha: - weight function for never observed substitutions. + alpha (float): weight function for never observed substitutions. """ if lambda_table is not None: self._lambda_table = lambda_table @@ -94,8 +92,8 @@ def get_lambda(self, s1, s2): Returns: Lambda values """ - k = frozenset([get_el_sp(s1), get_el_sp(s2)]) - return self._l.get(k, self.alpha) + key = frozenset([get_el_sp(s1), get_el_sp(s2)]) + return self._l.get(key, self.alpha) def get_px(self, sp): """ diff --git a/pymatgen/analysis/transition_state.py b/pymatgen/analysis/transition_state.py index 792a51ff45f..5dbbe1fbb54 100644 --- a/pymatgen/analysis/transition_state.py +++ b/pymatgen/analysis/transition_state.py @@ -274,7 +274,7 @@ def as_dict(self): "r": jsanitize(self.r), "energies": jsanitize(self.energies), "forces": jsanitize(self.forces), - "structures": [s.as_dict() for s in self.structures], + "structures": [struct.as_dict() for struct in self.structures], } diff --git a/pymatgen/cli/pmg.py b/pymatgen/cli/pmg.py index b239f36e4fe..491d4ab2c11 100755 --- a/pymatgen/cli/pmg.py +++ b/pymatgen/cli/pmg.py @@ -131,7 +131,7 @@ def main(): metavar="dir_name", nargs=2, help="Initial directory where the CP2K data is located and the output directory where the " - "CP2K yaml data files will be written", + "CP2K YAML data files will be written", ) parser_config.add_argument( diff --git a/pymatgen/command_line/critic2_caller.py b/pymatgen/command_line/critic2_caller.py index e2394ecf852..6d43959576d 100644 --- a/pymatgen/command_line/critic2_caller.py +++ b/pymatgen/command_line/critic2_caller.py @@ -180,7 +180,7 @@ def from_chgcar( critical points to a file 'table.cml' in the working directory useful for visualization write_json (bool): Whether to write out critical points - and YT json. YT integration will be performed with this setting. + and YT JSON. YT integration will be performed with this setting. zpsp (dict): Dict of element/symbol name to number of electrons (ZVAL in VASP pseudopotential), with which to properly augment core regions and calculate charge transfer. Optional. @@ -453,8 +453,8 @@ class with bonding information. By default, this returns structure: associated Structure stdout: stdout from running critic2 in automatic mode stderr: stderr from running critic2 in automatic mode - cpreport: json output from CPREPORT command - yt: json output from YT command + cpreport: JSON output from CPREPORT command + yt: JSON output from YT command zpsp (dict): Dict of element/symbol name to number of electrons (ZVAL in VASP pseudopotential), with which to calculate charge transfer. Optional. diff --git a/pymatgen/command_line/vampire_caller.py b/pymatgen/command_line/vampire_caller.py index d239054506d..8709088514d 100644 --- a/pymatgen/command_line/vampire_caller.py +++ b/pymatgen/command_line/vampire_caller.py @@ -400,7 +400,7 @@ class VampireOutput(MSONable): def __init__(self, parsed_out=None, nmats=None, critical_temp=None): """ Args: - parsed_out (json): json rep of parsed stdout DataFrame. + parsed_out (str): JSON rep of parsed stdout DataFrame. nmats (int): Number of distinct materials (1 for each specie and up/down spin). critical_temp (float): Monte Carlo Tc result. """ diff --git a/pymatgen/core/__init__.py b/pymatgen/core/__init__.py index 194c6ff4012..2459aa7e534 100644 --- a/pymatgen/core/__init__.py +++ b/pymatgen/core/__init__.py @@ -50,7 +50,7 @@ def _load_pmg_settings() -> dict[str, Any]: except Exception as exc: # If there are any errors, default to using environment variables # if present. - warnings.warn(f"Error loading {file_path}: {exc}.\nYou may need to reconfigure your yaml file.") + warnings.warn(f"Error loading {file_path}: {exc}.\nYou may need to reconfigure your YAML file.") # Override .pmgrc.yaml with env vars (if present) for key, val in os.environ.items(): diff --git a/pymatgen/core/libxcfunc.py b/pymatgen/core/libxcfunc.py index ac1c8116a11..73ded142640 100644 --- a/pymatgen/core/libxcfunc.py +++ b/pymatgen/core/libxcfunc.py @@ -26,7 +26,7 @@ __status__ = "Production" __date__ = "May 16, 2016" -# Load libxc info from json file +# Load libxc info from JSON file with open(os.path.join(os.path.dirname(__file__), "libxc_docs.json"), encoding="utf-8") as file: _all_xcfuncs = {int(k): v for k, v in json.load(file).items()} @@ -497,5 +497,5 @@ def from_dict(cls, dct: dict) -> Self: return cls[dct["name"]] def to_json(self) -> str: - """Get a json string representation of the LibxcFunc.""" + """Get a JSON string representation of the LibxcFunc.""" return json.dumps(self.as_dict(), cls=MontyEncoder) diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index c444d5a6e05..d21a33e4129 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -29,7 +29,7 @@ from pymatgen.util.typing import SpeciesLike -# Load element data from json file +# Load element data from JSON file with open(Path(__file__).absolute().parent / "periodic_table.json", encoding="utf-8") as ptable_json: _pt_data = json.load(ptable_json) diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index 9809d7b0a17..7e8e969e405 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -1679,7 +1679,7 @@ def generate_all_slabs( return all_slabs -# Load the reconstructions_archive json file +# Load the reconstructions_archive JSON file module_dir = os.path.dirname(os.path.abspath(__file__)) with open(f"{module_dir}/reconstructions_archive.json", encoding="utf-8") as data_file: RECONSTRUCTIONS_ARCHIVE = json.load(data_file) @@ -1715,7 +1715,7 @@ class ReconstructionGenerator: the reconstructed slab. Only the a and b lattice vectors are actually changed while the c vector remains the same. This matrix is what the Wood's notation is based on. - reconstruction_json (dict): The full json or dictionary containing + reconstruction_json (dict): The full JSON or dictionary containing the instructions for building the slab. Todo: diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index 6a5e7465ca4..29dae3e718d 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -4062,7 +4062,7 @@ def plot_fermi_surface( polydata = cp.actor.actors[0].mapper.input pts = np.array(polydata.points) # - 1 - polydata.points = np.dot(pts, cell / np.array(data.shape)[:, np.newaxis]) + polydata.points = np.dot(pts, cell / np.array(data.shape)[:, None]) cx, cy, cz = (np.mean(np.array(polydata.points)[:, i]) for i in range(3)) diff --git a/pymatgen/ext/matproj_legacy.py b/pymatgen/ext/matproj_legacy.py index 36bd8792c36..62fc26dd9b0 100644 --- a/pymatgen/ext/matproj_legacy.py +++ b/pymatgen/ext/matproj_legacy.py @@ -364,7 +364,7 @@ def get_doc(self, materials_id): materials_id (str): e.g. mp-1143 for Al2O3 Returns: - Dict of json document of all data that is displayed on a materials + Dict of JSON document of all data that is displayed on a materials details page. """ return self._make_request(f"/materials/{materials_id}/doc", mp_decode=False) diff --git a/pymatgen/io/common.py b/pymatgen/io/common.py index 6b078364856..073f26b7935 100644 --- a/pymatgen/io/common.py +++ b/pymatgen/io/common.py @@ -276,7 +276,7 @@ def to_hdf5(self, filename): f["fcoords"]: Fractional coords f["lattice"]: Lattice in the pymatgen.core.Lattice matrix format - f.attrs["structure_json"]: String of json representation + f.attrs["structure_json"]: String of JSON representation Args: filename (str): Filename to output to. diff --git a/pymatgen/io/phonopy.py b/pymatgen/io/phonopy.py index dfb0190f6ca..e0fda1c8e33 100644 --- a/pymatgen/io/phonopy.py +++ b/pymatgen/io/phonopy.py @@ -241,7 +241,7 @@ def get_displaced_structures(pmg_structure, atom_disp=0.01, supercell_matrix=Non atom_disp (float): Atomic displacement. Default is 0.01 $\\AA$. supercell_matrix (3x3 array): Scaling matrix for supercell. yaml_fname (str): If not None, it represents the full path to - the outputting displacement yaml file, e.g. disp.yaml. + the outputting displacement YAML file, e.g. disp.yaml. **kwargs: Parameters used in Phonopy.generate_displacement method. Returns: @@ -411,7 +411,7 @@ def get_phonon_band_structure_symm_line_from_fc( def get_gruneisenparameter(gruneisen_path, structure=None, structure_path=None) -> GruneisenParameter: """Get Gruneisen object from gruneisen.yaml file, as obtained from phonopy (Frequencies in THz!). The order is structure > structure path > structure from gruneisen dict. - Newer versions of phonopy include the structure in the yaml file, + Newer versions of phonopy include the structure in the YAML file, the structure/structure_path is kept for compatibility. Args: diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index a30e8cb8611..dde4b9ef7cb 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -679,11 +679,11 @@ def set_temperature(self, temperature: float) -> None: dof = 3 * len(self.structure) - 3 # Remove linear drift (net momentum) - velocities -= np.mean(atomic_masses[:, np.newaxis] * velocities, axis=0) / np.mean(atomic_masses) + velocities -= np.mean(atomic_masses[:, None] * velocities, axis=0) / np.mean(atomic_masses) # Scale velocities due to atomic masses # mean 0 std proportional to sqrt(1/m) - velocities /= atomic_masses[:, np.newaxis] ** (1 / 2) + velocities /= atomic_masses[:, None] ** (1 / 2) # Scale velocities to get correct temperature energy = np.sum(1 / 2 * atomic_masses * np.sum(velocities**2, axis=1)) diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 682e659f33e..8b2c0f4932e 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -1231,8 +1231,8 @@ def update_charge_from_potcar(self, path: PathLike | bool) -> None: potcar_nelect = sum(ps.ZVAL * num for ps, num in zip(potcar, nums)) charge = potcar_nelect - nelect - for s in self.structures: - s._charge = charge + for struct in self.structures: + struct._charge = charge if hasattr(self, "initial_structure"): self.initial_structure._charge = charge if hasattr(self, "final_structure"): diff --git a/pymatgen/phonon/bandstructure.py b/pymatgen/phonon/bandstructure.py index d22c535acba..d56ff99df89 100644 --- a/pymatgen/phonon/bandstructure.py +++ b/pymatgen/phonon/bandstructure.py @@ -506,7 +506,7 @@ def get_branch(self, index: int) -> list[dict[str, str | int]]: return lst def write_phononwebsite(self, filename: str | PathLike) -> None: - """Write a json file for the phononwebsite: + """Write a JSON file for the phononwebsite: http://henriquemiranda.github.io/phononwebsite. """ with open(filename, mode="w") as file: diff --git a/pymatgen/phonon/ir_spectra.py b/pymatgen/phonon/ir_spectra.py index 284ad312a38..462f4fa94b9 100644 --- a/pymatgen/phonon/ir_spectra.py +++ b/pymatgen/phonon/ir_spectra.py @@ -90,7 +90,7 @@ def as_dict(self) -> dict: } def write_json(self, filename: str | PathLike) -> None: - """Save a json file with this data.""" + """Save a JSON file with this data.""" with open(filename, mode="w") as file: json.dump(self.as_dict(), file) @@ -120,14 +120,13 @@ def get_ir_spectra( emax = self.max_phfreq + max(broad) * 20 frequencies = np.linspace(emin, emax, divs) - na = np.newaxis dielectric_tensor = np.zeros((divs, 3, 3), dtype=complex) for i in range(3, len(self.ph_freqs_gamma)): g = broad[i] * self.ph_freqs_gamma[i] num = self.oscillator_strength[i, :, :] - den = self.ph_freqs_gamma[i] ** 2 - frequencies[:, na, na] ** 2 - 1j * g + den = self.ph_freqs_gamma[i] ** 2 - frequencies[:, None, None] ** 2 - 1j * g dielectric_tensor += num / den - dielectric_tensor += self.epsilon_infinity[na, :, :] + dielectric_tensor += self.epsilon_infinity[None, :, :] return frequencies, dielectric_tensor @@ -145,7 +144,7 @@ def plot( Arguments: components: A list with the components of the dielectric tensor to plot. - Can be either two indexes or a string like 'xx' to plot the (0,0) component + Can be either two indexes or a string like 'xx' to plot the (0,0) component reim: If 're' (im) is present in the string plots the real (imaginary) part of the dielectric tensor show_phonon_frequencies: plot a dot where the phonon frequencies are to help identify IR inactive modes xlim: x-limits of the plot. Defaults to None for automatic determination. diff --git a/tests/analysis/structure_prediction/test_substitution_probability.py b/tests/analysis/structure_prediction/test_substitution_probability.py index fdbdd1ab699..e6c5f9786d0 100644 --- a/tests/analysis/structure_prediction/test_substitution_probability.py +++ b/tests/analysis/structure_prediction/test_substitution_probability.py @@ -29,7 +29,7 @@ def get_table(): class TestSubstitutionProbability(TestCase): def test_full_lambda_table(self): """Check specific values in the data folder. If the - json is updated, these tests will have to be as well. + JSON is updated, these tests will have to be as well. """ sp = SubstitutionProbability(alpha=-5.0) sp1 = Species("Fe", 4) diff --git a/tests/apps/battery/test_insertion_battery.py b/tests/apps/battery/test_insertion_battery.py index 0c4520467c8..4c6b9caa951 100644 --- a/tests/apps/battery/test_insertion_battery.py +++ b/tests/apps/battery/test_insertion_battery.py @@ -88,7 +88,7 @@ def test_as_from_dict(self): assert ie.min_voltage == approx(0.89702381) assert ie.get_average_voltage() == approx(1.84143141) - # Just to make sure json string works. + # Just to make sure JSON string works. json_str = json.dumps(self.ie_LTO, cls=MontyEncoder) ie = json.loads(json_str, cls=MontyDecoder) assert ie.max_voltage == approx(2.78583901) @@ -96,20 +96,19 @@ def test_as_from_dict(self): assert ie.get_average_voltage() == approx(1.84143141) def test_voltage_pair(self): - vpair = self.ie_LTO[0] - assert vpair.voltage == approx(2.78583901) - assert vpair.mAh == approx(13400.7411749) - assert vpair.mass_charge == approx(79.8658) - assert vpair.mass_discharge == approx(83.3363) - assert vpair.vol_charge == approx(37.553684467) - assert vpair.vol_discharge == approx(37.917719932) - assert vpair.frac_charge == approx(0) - assert vpair.frac_discharge == approx(0.14285714285714285) - assert vpair.x_charge == approx(0) - assert vpair.x_discharge == approx(0.5) + volt_pair = self.ie_LTO[0] + assert volt_pair.voltage == approx(2.78583901) + assert volt_pair.mAh == approx(13400.7411749) + assert volt_pair.mass_charge == approx(79.8658) + assert volt_pair.mass_discharge == approx(83.3363) + assert volt_pair.vol_charge == approx(37.553684467) + assert volt_pair.vol_discharge == approx(37.917719932) + assert volt_pair.frac_charge == approx(0) + assert volt_pair.frac_discharge == approx(0.14285714285714285) + assert volt_pair.x_charge == approx(0) + assert volt_pair.x_discharge == approx(0.5) # reconstruct the voltage pair - dct = vpair.as_dict() - vv = InsertionVoltagePair.from_dict(dct) + vv = InsertionVoltagePair.from_dict(volt_pair.as_dict()) assert vv.entry_charge.energy == approx(-105.53608265) assert vv.voltage == approx(2.78583901) diff --git a/tests/electronic_structure/test_cohp.py b/tests/electronic_structure/test_cohp.py index a5052cc655d..2f9f827ba8b 100644 --- a/tests/electronic_structure/test_cohp.py +++ b/tests/electronic_structure/test_cohp.py @@ -924,7 +924,7 @@ def test_average_multi_center_cobi(self): assert icohp1 == approx(icohp2, abs=1e-4) def test_dict(self): - # The json files are dict representations of the COHPs from the LMTO + # The JSON files are dict representations of the COHPs from the LMTO # and LOBSTER calculations and should thus be the same. def is_equal(a, b): diff --git a/tests/transformations/test_advanced_transformations.py b/tests/transformations/test_advanced_transformations.py index 71ef890053d..5dcc3fae6d4 100644 --- a/tests/transformations/test_advanced_transformations.py +++ b/tests/transformations/test_advanced_transformations.py @@ -338,7 +338,7 @@ def test_ferrimagnetic(self): def test_as_from_dict(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75) dct = trans.as_dict() - # Check json encodability + # Check JSON encodability _ = json.dumps(dct) trans = MagOrderingTransformation.from_dict(dct) assert trans.mag_species_spin == {"Fe": 5} @@ -536,7 +536,7 @@ def test_apply_transformation(self): def test_as_from_dict(self): trans = DopingTransformation("Al3+", min_length=5, alio_tol=1, codopant=False, max_structures_per_enum=1) dct = trans.as_dict() - # Check json encodability + # Check JSON encodability _ = json.dumps(dct) trans = DopingTransformation.from_dict(dct) assert str(trans.dopant) == "Al3+"