diff --git a/pymatgen/alchemy/transmuters.py b/pymatgen/alchemy/transmuters.py index 274b40cbcb5..7a4bc8f7ef1 100644 --- a/pymatgen/alchemy/transmuters.py +++ b/pymatgen/alchemy/transmuters.py @@ -60,7 +60,6 @@ def __init__( Uses multiprocessing.Pool. Default is None, which implies serial. """ - self.transformed_structures = transformed_structures self.ncores = ncores if transformations is not None: @@ -288,7 +287,6 @@ def from_filenames(filenames, transformations=None, primitive=True, extend_colle primitive: Same meaning as in __init__. extend_collection: Same meaning as in __init__. """ - allcifs = [] for fname in filenames: with open(fname) as f: diff --git a/pymatgen/analysis/adsorption.py b/pymatgen/analysis/adsorption.py index 6aa96caec61..d48f522f21a 100644 --- a/pymatgen/analysis/adsorption.py +++ b/pymatgen/analysis/adsorption.py @@ -164,7 +164,6 @@ def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05): Returns: list of sites selected to be within a threshold of the highest """ - # Get projection of coordinates along the miller index m_projs = np.array([np.dot(site.coords, self.mvec) for site in slab.sites]) @@ -482,7 +481,6 @@ def adsorb_both_surfaces( find_args (dict): dictionary of arguments to be passed to the call to self.find_adsorption_sites, e.g. {"distance":2.0} """ - # Get the adsorbed surfaces first find_args = find_args or {} ad_slabss = self.generate_adsorption_structures( @@ -545,7 +543,6 @@ def generate_substitution_structures( dist_from_surf (float): Distance from the surface to find viable substitution sites, defaults to 0 to substitute at the surface """ - target_species = target_species or [] # Get symmetrized structure in case we want to substitute both sides diff --git a/pymatgen/analysis/bond_dissociation.py b/pymatgen/analysis/bond_dissociation.py index b03809dfb26..743f4e54669 100644 --- a/pymatgen/analysis/bond_dissociation.py +++ b/pymatgen/analysis/bond_dissociation.py @@ -59,7 +59,6 @@ def __init__( of self.expected_charges below for more specific information. multibreak (bool): If True, additionally attempt to break pairs of bonds. Defaults to False. """ - self.molecule_entry = molecule_entry self.filter_fragment_entries(fragment_entries) print(str(len(self.filtered_entries)) + " filtered entries") diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index 7060969f7d1..d3b929c4632 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -383,7 +383,6 @@ def __len__(self): def compute_periodicity(self, algorithm="all_simple_paths"): """ - Args: algorithm (): @@ -399,7 +398,6 @@ def compute_periodicity(self, algorithm="all_simple_paths"): def compute_periodicity_all_simple_paths_algorithm(self): """ - Returns: """ self_loop_nodes = list(nx.nodes_with_selfloops(self._connected_subgraph)) @@ -487,7 +485,6 @@ def compute_periodicity_all_simple_paths_algorithm(self): def compute_periodicity_cycle_basis(self): """ - Returns: """ my_simple_graph = nx.Graph(self._connected_subgraph) @@ -534,7 +531,6 @@ def compute_periodicity_cycle_basis(self): def make_supergraph(self, multiplicity): """ - Args: multiplicity (): @@ -545,7 +541,6 @@ def make_supergraph(self, multiplicity): def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltshow=True): """ - Args: graph (): save_file (): @@ -597,7 +592,6 @@ def graph(self): @property def is_periodic(self): """ - Returns: """ return not self.is_0d @@ -605,7 +599,6 @@ def is_periodic(self): @property def is_0d(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -615,7 +608,6 @@ def is_0d(self): @property def is_1d(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -625,7 +617,6 @@ def is_1d(self): @property def is_2d(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -635,7 +626,6 @@ def is_2d(self): @property def is_3d(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -673,7 +663,6 @@ def _order_periodicity_vectors(self): @property def periodicity_vectors(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -683,7 +672,6 @@ def periodicity_vectors(self): @property def periodicity(self): """ - Returns: """ if self._periodicity_vectors is None: @@ -692,7 +680,6 @@ def periodicity(self): def elastic_centered_graph(self, start_node=None): """ - Args: start_node (): @@ -917,7 +904,6 @@ def from_graph(cls, g): def description(self, full=False): """ - Args: full (): diff --git a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py index 7eca8edbf8e..1e2bcb66cbe 100644 --- a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py +++ b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py @@ -79,7 +79,6 @@ def __init__( def environment_subgraph(self, environments_symbols=None, only_atoms=None): """ - Args: environments_symbols (): only_atoms (): @@ -262,7 +261,6 @@ def setup_environment_subgraph(self, environments_symbols, only_atoms=None): def setup_connectivity_description(self): """ - Returns: """ @@ -283,7 +281,6 @@ def get_connected_components(self, environments_symbols=None, only_atoms=None): def setup_atom_environment_subgraph(self, atom_environment): """ - Args: atom_environment (): @@ -293,7 +290,6 @@ def setup_atom_environment_subgraph(self, atom_environment): def setup_environments_subgraph(self, environments_symbols): """ - Args: environments_symbols (): @@ -303,7 +299,6 @@ def setup_environments_subgraph(self, environments_symbols): def setup_atom_environments_subgraph(self, atoms_environments): """ - Args: atoms_environments (): @@ -313,7 +308,6 @@ def setup_atom_environments_subgraph(self, atoms_environments): def print_links(self): """ - Returns: """ nodes = self.environment_subgraph().nodes() @@ -334,7 +328,6 @@ def print_links(self): def as_dict(self): """ - Returns: """ return { @@ -351,7 +344,6 @@ def as_dict(self): @classmethod def from_dict(cls, d): """ - Args: d (): diff --git a/pymatgen/analysis/cost.py b/pymatgen/analysis/cost.py index dee728f5c3a..32d182b01f8 100644 --- a/pymatgen/analysis/cost.py +++ b/pymatgen/analysis/cost.py @@ -156,7 +156,6 @@ def get_lowest_decomposition(self, composition): Returns: Decomposition as a dict of {Entry: amount} """ - entries_list = [] elements = [e.symbol for e in composition.elements] for i in range(len(elements)): @@ -180,7 +179,6 @@ def get_cost_per_mol(self, comp): Returns: float of cost/mol """ - comp = comp if isinstance(comp, Composition) else Composition(comp) decomp = self.get_lowest_decomposition(comp) return sum(k.energy_per_atom * v * comp.num_atoms for k, v in decomp.items()) diff --git a/pymatgen/analysis/elasticity/elastic.py b/pymatgen/analysis/elasticity/elastic.py index 5373729e588..5b0f5619528 100644 --- a/pymatgen/analysis/elasticity/elastic.py +++ b/pymatgen/analysis/elasticity/elastic.py @@ -97,7 +97,6 @@ def energy_density(self, strain, convert_GPa_to_eV=True): @classmethod def from_diff_fit(cls, strains, stresses, eq_stress=None, order=2, tol: float = 1e-10): """ - Args: strains (): stresses (): @@ -155,7 +154,6 @@ def __new__(cls, input_array, tol: float = 1e-4): tol (float): tolerance for initial symmetry test of tensor """ - obj = super().__new__(cls, input_array, check_rank=4, tol=tol) return obj.view(cls) diff --git a/pymatgen/analysis/elasticity/stress.py b/pymatgen/analysis/elasticity/stress.py index 03be69ba64e..da03007ac69 100644 --- a/pymatgen/analysis/elasticity/stress.py +++ b/pymatgen/analysis/elasticity/stress.py @@ -102,7 +102,6 @@ def piola_kirchoff_2(self, def_grad): Args: def_grad (3x3 array-like): rate of deformation tensor """ - def_grad = SquareTensor(def_grad) if not self.is_symmetric: raise ValueError( diff --git a/pymatgen/analysis/ewald.py b/pymatgen/analysis/ewald.py index c8744a50c2a..d61a7527743 100644 --- a/pymatgen/analysis/ewald.py +++ b/pymatgen/analysis/ewald.py @@ -453,7 +453,6 @@ def as_dict(self, verbosity: int = 0) -> dict: verbosity (int): Verbosity level. Default of 0 only includes the matrix representation. Set to 1 for more details. """ - d = { "@module": type(self).__module__, "@class": type(self).__name__, diff --git a/pymatgen/analysis/ferroelectricity/polarization.py b/pymatgen/analysis/ferroelectricity/polarization.py index 1da8509d063..17d37b20f7e 100644 --- a/pymatgen/analysis/ferroelectricity/polarization.py +++ b/pymatgen/analysis/ferroelectricity/polarization.py @@ -208,7 +208,6 @@ def get_pelecs_and_pions(self, convert_to_muC_per_cm2=False): convert_to_muC_per_cm2: Convert from electron * Angstroms to microCoulomb per centimeter**2 """ - if not convert_to_muC_per_cm2: return self.p_elecs, self.p_ions @@ -269,7 +268,6 @@ def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_ microCoulomb per centimeter**2 all_in_polar: convert polarization to be in polar (final structure) polarization lattice """ - p_elec, p_ion = self.get_pelecs_and_pions() p_tot = p_elec + p_ion p_tot = np.array(p_tot) diff --git a/pymatgen/analysis/functional_groups.py b/pymatgen/analysis/functional_groups.py index 12d1ba71978..c2b48617aee 100644 --- a/pymatgen/analysis/functional_groups.py +++ b/pymatgen/analysis/functional_groups.py @@ -45,7 +45,6 @@ def __init__(self, molecule, optimize=False): modified, adding Hydrogens, performing a simple conformer search, etc. """ - self.molgraph = None if isinstance(molecule, str): @@ -108,7 +107,6 @@ def get_heteroatoms(self, elements=None): functional groups are of interest). :return: set of ints representing node indices """ - heteroatoms = set() for node in self.molgraph.graph.nodes(): @@ -139,7 +137,6 @@ def get_special_carbon(self, elements=None): Default None. :return: set of ints representing node indices """ - specials = set() # For this function, only carbons are considered @@ -205,7 +202,6 @@ def link_marked_atoms(self, atoms): using other functions in this class. :return: list of sets of ints, representing groups of connected atoms """ - # We will add hydrogens to functional groups hydrogens = {n for n in self.molgraph.graph.nodes if str(self.species[n]) == "H"} @@ -241,7 +237,6 @@ def get_basic_functional_groups(self, func_groups=None): defined in this function will be sought. :return: list of sets of ints, representing groups of connected atoms """ - strat = OpenBabelNN() hydrogens = {n for n in self.molgraph.graph.nodes if str(self.species[n]) == "H"} @@ -306,7 +301,6 @@ def get_all_functional_groups(self, elements=None, func_groups=None, catch_basic other methods :return: list of sets of ints, representing groups of connected atoms """ - heteroatoms = self.get_heteroatoms(elements=elements) special_cs = self.get_special_carbon(elements=elements) groups = self.link_marked_atoms(heteroatoms.union(special_cs)) @@ -325,7 +319,6 @@ def categorize_functional_groups(self, groups): where the group occurs in the MoleculeGraph, and how many of each type of group there is. """ - categories = {} em = iso.numerical_edge_match("weight", 1) # pylint: disable=E1102 diff --git a/pymatgen/analysis/gb/grain.py b/pymatgen/analysis/gb/grain.py index 7f799bff212..c3886d53c0a 100644 --- a/pymatgen/analysis/gb/grain.py +++ b/pymatgen/analysis/gb/grain.py @@ -2089,7 +2089,6 @@ def slab_from_csl(csl, surface, normal, trans_cry, max_search=20, quick_gen=Fals Returns: t_matrix: a slab lattice ( 3 by 3 integer array): """ - # set the transform matrix in real space trans = trans_cry # transform matrix in reciprocal space diff --git a/pymatgen/analysis/graphs.py b/pymatgen/analysis/graphs.py index 74d06e1bc49..a4a381f9a7c 100644 --- a/pymatgen/analysis/graphs.py +++ b/pymatgen/analysis/graphs.py @@ -137,7 +137,6 @@ def __init__(self, structure: Structure, graph_data=None): dict format (not intended to be constructed manually, see as_dict method for format) """ - if isinstance(structure, StructureGraph): # just make a copy from input graph_data = structure.as_dict()["graphs"] @@ -181,7 +180,6 @@ def with_empty_graph( e.g. "Å" or "eV" :return (StructureGraph): """ - if edge_weight_name and (edge_weight_units is None): raise ValueError( "Please specify units associated " @@ -218,7 +216,6 @@ def with_edges(structure, edges): specified. :return: sg, a StructureGraph """ - sg = StructureGraph.with_empty_graph(structure, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): @@ -275,7 +272,6 @@ def with_local_env_strategy(structure, strategy, weights=False, edge_properties= :param edge_properties: if True, edge_properties from neighbors will be used :return: """ - if not strategy.structures_allowed: raise ValueError("Chosen strategy is not designed for use with structures! Please choose another strategy.") @@ -364,7 +360,6 @@ def add_edge( store on graph edges, similar to Structure's site_properties :return: """ - # this is not necessary for the class to work, but # just makes it neater if to_index < from_index: @@ -495,7 +490,6 @@ def insert_node( "weight" and a "properties" key. :return: """ - self.structure.insert( i, species, @@ -537,7 +531,6 @@ def set_node_attributes(self): :return: """ - species = {} coords = {} properties = {} @@ -575,7 +568,6 @@ def alter_edge( it should be a dictionary of edge properties to be changed. :return: """ - existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting to change it @@ -610,7 +602,6 @@ def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): will attempt to break (to_index, from_index). :return: """ - # ensure that edge exists before attempting to remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None @@ -649,7 +640,6 @@ def remove_nodes(self, indices): be removed. :return: """ - self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) @@ -785,7 +775,6 @@ def get_connected_sites(self, n, jimage=(0, 0, 0)): :return: list of ConnectedSite tuples, sorted by closest first """ - connected_sites = set() connected_site_images = set() @@ -887,7 +876,6 @@ def draw_graph_to_file( or "fdp" (for more crowded graphs) usually give good outputs :return: """ - if not which(algo): raise RuntimeError("StructureGraph graph drawing requires GraphViz binaries to be in the path.") @@ -1041,7 +1029,6 @@ def weight_statistics(self): :return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' """ - all_weights = [d.get("weight", None) for u, v, d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy="omit") @@ -1063,7 +1050,6 @@ def types_of_coordination_environments(self, anonymous=False): :return: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] """ - motifs = set() for idx, site in enumerate(self.structure): @@ -1101,7 +1087,6 @@ def as_dict(self): with using `to_dict_of_dicts` from NetworkX to store graph information. """ - d = { "@module": type(self).__module__, "@class": type(self).__name__, @@ -1133,7 +1118,6 @@ def __mul__(self, scaling_matrix): :param scaling_matrix: same as Structure.__mul__ :return: """ - # Developer note: a different approach was also trialed, using # a simple Graph (instead of MultiDiGraph), with node indices # representing both site index and periodic image. Here, the @@ -1395,7 +1379,6 @@ def sort(self, key=None, reverse=False): :param reverse: :return: """ - old_structure = self.structure.copy() # sort Structure @@ -1475,7 +1458,6 @@ def diff(self, other, strict=True): number of occurrences of bonds :return: """ - if self.structure != other.structure and strict: return ValueError("Meaningless to compare StructureGraphs if corresponding Structures are different.") @@ -1534,7 +1516,6 @@ def get_subgraphs_as_molecules(self, use_weights=False): :return: list of unique Molecules in Structure """ - # creating a supercell is an easy way to extract # molecules (and not, e.g., layers of a 2D crystal) # without adding extra logic @@ -1634,7 +1615,6 @@ def __init__(self, molecule, graph_data=None): dict format (not intended to be constructed manually, see as_dict method for format) """ - if isinstance(molecule, MoleculeGraph): # just make a copy from input graph_data = molecule.as_dict()["graphs"] @@ -1674,7 +1654,6 @@ def with_empty_graph(cls, molecule, name="bonds", edge_weight_name=None, edge_we e.g. "Å" or "eV" :return (MoleculeGraph): """ - if edge_weight_name and (edge_weight_units is None): raise ValueError( "Please specify units associated " @@ -1710,7 +1689,6 @@ def with_edges(molecule, edges): additional properties are to be specified. :return: mg, a MoleculeGraph """ - mg = MoleculeGraph.with_empty_graph(molecule, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): @@ -1755,7 +1733,6 @@ def with_local_env_strategy(molecule, strategy): :class:`pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph """ - if not strategy.molecules_allowed: raise ValueError("Chosen strategy is not designed for use with molecules! Please choose another strategy.") extend_structure = strategy.extend_structure_molecules @@ -1862,7 +1839,6 @@ def add_edge( store on graph edges, similar to Structure's site_properties :return: """ - # this is not necessary for the class to work, but # just makes it neater if to_index < from_index: @@ -1916,7 +1892,6 @@ def insert_node( "weight" and a "properties" key. :return: """ - self.molecule.insert( i, species, @@ -1955,7 +1930,6 @@ def set_node_attributes(self): :return: """ - species = {} coords = {} properties = {} @@ -1985,7 +1959,6 @@ def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties= it should be a dictionary of edge properties to be changed. :return: """ - existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting to change it @@ -2013,7 +1986,6 @@ def break_edge(self, from_index, to_index, allow_reverse=False): will attempt to break (to_index, from_index). :return: """ - # ensure that edge exists before attempting to remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None @@ -2041,7 +2013,6 @@ def remove_nodes(self, indices): be removed. :return: """ - self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) @@ -2066,7 +2037,6 @@ def get_disconnected_fragments(self): returns two or more new MoleculeGraph objects. :return: list of MoleculeGraphs """ - if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] @@ -2152,7 +2122,6 @@ def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None) will attempt to break (to_index, from_index). :return: list of MoleculeGraphs """ - self.set_node_attributes() original = copy.deepcopy(self) @@ -2424,7 +2393,6 @@ def replace_group( If None, default parameters will be used. :return: """ - self.set_node_attributes() neighbors = self.get_connected_sites(index) @@ -2482,7 +2450,6 @@ def find_rings(self, including=None): found in the Molecule. If there is no cycle including an index, the value will be an empty list. """ - # Copies self.graph such that all edges (u, v) matched by edges (v, u) undirected = self.graph.to_undirected() directed = undirected.to_directed() @@ -2530,7 +2497,6 @@ def get_connected_sites(self, n): :return: list of ConnectedSite tuples, sorted by closest first """ - connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True)) @@ -2623,7 +2589,6 @@ def draw_graph_to_file( or "fdp" (for more crowded graphs) usually give good outputs :return: """ - if not which(algo): raise RuntimeError("StructureGraph graph drawing requires GraphViz binaries to be in the path.") @@ -2753,7 +2718,6 @@ def as_dict(self): with using `to_dict_of_dicts` from NetworkX to store graph information. """ - d = { "@module": type(self).__module__, "@class": type(self).__name__, @@ -2933,7 +2897,6 @@ def diff(self, other, strict=True): number of occurrences of bonds :return: """ - if self.molecule != other.molecule and strict: return ValueError("Meaningless to compare MoleculeGraphs if corresponding Molecules are different.") diff --git a/pymatgen/analysis/hhi.py b/pymatgen/analysis/hhi.py index e5c531d1f8b..9b9c9a82847 100644 --- a/pymatgen/analysis/hhi.py +++ b/pymatgen/analysis/hhi.py @@ -73,7 +73,6 @@ def get_hhi(self, comp_or_form): Returns: A tuple representing the (HHI_production, HHI_reserve) """ - try: if not isinstance(comp_or_form, Composition): comp_or_form = Composition(comp_or_form) @@ -128,7 +127,6 @@ def get_hhi_designation(hhi): Returns: The designation as String """ - if hhi is None: return None diff --git a/pymatgen/analysis/interfaces/zsl.py b/pymatgen/analysis/interfaces/zsl.py index 218e93568c7..6e2a2e1083b 100644 --- a/pymatgen/analysis/interfaces/zsl.py +++ b/pymatgen/analysis/interfaces/zsl.py @@ -152,7 +152,6 @@ def generate_sl_transformation_sets(self, film_area, substrate_area): 2.) the transformation matrices for the substrate to create a super lattice of area j*film area """ - transformation_indices = [ (i, j) for i in range(1, int(self.max_area / film_area)) @@ -187,7 +186,6 @@ def get_equiv_transformations(self, transformation_sets, film_vectors, substrate substrate_vectors(array): substrate vectors to generate super lattices """ - for (film_transformations, substrate_transformations) in transformation_sets: # Apply transformations and reduce using Zur reduce methodology films = [reduce_vectors(*np.dot(f, film_vectors)) for f in film_transformations] @@ -207,7 +205,6 @@ def __call__(self, film_vectors, substrate_vectors, lowest=False) -> Iterator[ZS Runs the ZSL algorithm to generate all possible matching :return: """ - film_area = vec_area(*film_vectors) substrate_area = vec_area(*substrate_vectors) diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index 5cb420a9483..2e134f6aad8 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -337,7 +337,6 @@ def get_cn_dict(self, structure: Structure, n: int, use_weights: bool = False): Returns: cn (dict): dictionary of CN of each element bonded to site """ - siw = self.get_nn_info(structure, n) cn_dict = {} @@ -366,7 +365,6 @@ def get_nn(self, structure: Structure, n: int): Returns: sites (list of Site objects): near neighbors. """ - return [e["site"] for e in self.get_nn_info(structure, n)] def get_weights_of_nn_sites(self, structure: Structure, n: int): @@ -380,7 +378,6 @@ def get_weights_of_nn_sites(self, structure: Structure, n: int): Returns: weights (list of floats): near-neighbor weights. """ - return [e["weight"] for e in self.get_nn_info(structure, n)] def get_nn_images(self, structure: Structure, n: int): @@ -396,7 +393,6 @@ def get_nn_images(self, structure: Structure, n: int): images (list of 3D integer array): image locations of near neighbors. """ - return [e["image"] for e in self.get_nn_info(structure, n)] def get_nn_info(self, structure: Structure, n: int) -> list[dict]: @@ -456,7 +452,6 @@ def get_nn_shell_info(self, structure: Structure, site_idx, shell): a certain neighbor in the structure, in the same format as `get_nn_info`. """ - all_nn_info = self.get_all_nn_info(structure) sites = self._get_nn_shell_info(structure, all_nn_info, site_idx, shell) @@ -499,7 +494,6 @@ def _get_nn_shell_info( a certain neighbor in the structure, in the same format as `get_nn_info`. Does not update the site positions """ - if shell <= 0: raise ValueError("Shell must be positive") @@ -758,7 +752,6 @@ def get_voronoi_polyhedra(self, structure: Structure, n: int): - volume - Volume of Voronoi cell for this face - n_verts - Number of vertices on the facet """ - # Assemble the list of neighbors used in the tessellation # Gets all atoms within a certain radius if self.targets is None: @@ -813,7 +806,6 @@ def get_all_voronoi_polyhedra(self, structure): - volume - Volume of Voronoi cell for this face - n_verts - Number of vertices on the facet """ - # Special case: For atoms with 1 site, the atom in the root image is not # included in the get_all_neighbors output. Rather than creating logic to add # that atom to the neighbor list, which requires detecting whether it will be @@ -1009,7 +1001,6 @@ def get_nn_info(self, structure: Structure, n: int): of which represents a coordinated site, its image location, and its weight. """ - # Run the tessellation nns = self.get_voronoi_polyhedra(structure, n) @@ -1036,7 +1027,6 @@ def _extract_nn_info(self, structure: Structure, nns): Returns: (list of tuples (Site, array, float)): See nn_info """ - # Get the target information if self.targets is None: targets = structure.composition.elements @@ -1148,7 +1138,6 @@ def _filter_nns(self, structure: Structure, n: int, nns: dict[str, Any]) -> list Returns: See get_nn_info for the format of the returned data. """ - # Get the target information if self.targets is None: targets = structure.composition.elements @@ -1302,7 +1291,6 @@ def get_nn_info(self, structure: Structure, n: int): of which represents a neighbor site, its image location, and its weight. """ - site = structure[n] # Determine relevant bond lengths based on atomic radii table @@ -1394,7 +1382,6 @@ def get_nn_info(self, structure: Structure, n: int): of which represents a neighbor site, its image location, and its weight. """ - site = structure[n] neighs_dists = structure.get_neighbors(site, self.cutoff) is_periodic = isinstance(structure, (Structure, IStructure)) @@ -1487,7 +1474,6 @@ def get_nn_info(self, structure: Structure, n: int): (dict): representing a neighboring site and the type of bond present between site n and the neighboring site. """ - from pymatgen.io.babel import BabelMolAdaptor obmol = BabelMolAdaptor(structure).openbabel_mol @@ -1577,7 +1563,6 @@ def get_nn_shell_info(self, structure: Structure, site_idx, shell): a certain neighbor in the structure, in the same format as `get_nn_info`. """ - all_nn_info = self.get_all_nn_info(structure) sites = self._get_nn_shell_info(structure, all_nn_info, site_idx, shell) @@ -1647,7 +1632,6 @@ def get_nn_info(self, structure: Structure, n: int): :return: [dict] representing a neighboring site and the type of bond present between site n and the neighboring site. """ - # This is unfortunately inefficient, but is the best way to fit the # current NearNeighbors scheme self.bonds = bonds = structure.get_covalent_bonds(tol=self.tol) @@ -1687,7 +1671,6 @@ def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> Returns: a pymatgen.analysis.graphs.MoleculeGraph object """ - # requires optional dependency which is why it's not a top-level import from pymatgen.analysis.graphs import MoleculeGraph @@ -1729,7 +1712,6 @@ def get_nn_shell_info(self, structure: Structure, site_idx, shell): a certain neighbor in the structure, in the same format as `get_nn_info`. """ - all_nn_info = self.get_all_nn_info(structure) sites = self._get_nn_shell_info(structure, all_nn_info, site_idx, shell) @@ -1804,7 +1786,6 @@ def get_nn_info(self, structure: Structure, n: int): of which represents a neighbor site, its image location, and its weight. """ - site = structure[n] neighs_dists = structure.get_neighbors(site, self.cutoff) try: @@ -2425,7 +2406,6 @@ def num_ops(self): int: the number of different order parameters that are targeted to be calculated. """ - return len(self._types) @property @@ -2437,7 +2417,6 @@ def last_nneigh(self): that no such calculation has yet been performed for this instance. """ - return len(self._last_nneigh) def compute_trigonometric_terms(self, thetas, phis): @@ -2459,7 +2438,6 @@ def compute_trigonometric_terms(self, thetas, phis): neighbors. And, this sequence has to equal the sequence of neighbors in the list of polar angles. """ - if len(thetas) != len(phis): raise ValueError("List of polar and azimuthal angles have to be equal!") @@ -2495,7 +2473,6 @@ def get_q2(self, thetas=None, phis=None): float: bond orientational order parameter of weight l=2 corresponding to the input angles thetas and phis. """ - if thetas is not None and phis is not None: self.compute_trigonometric_terms(thetas, phis) nnn = len(self._pow_sin_t[1]) @@ -2562,7 +2539,6 @@ def get_q4(self, thetas=None, phis=None): float: bond orientational order parameter of weight l=4 corresponding to the input angles thetas and phis. """ - if thetas is not None and phis is not None: self.compute_trigonometric_terms(thetas, phis) nnn = len(self._pow_sin_t[1]) @@ -2670,7 +2646,6 @@ def get_q6(self, thetas=None, phis=None): float: bond orientational order parameter of weight l=6 corresponding to the input angles thetas and phis. """ - if thetas is not None and phis is not None: self.compute_trigonometric_terms(thetas, phis) nnn = len(self._pow_sin_t[1]) @@ -2907,7 +2882,6 @@ def get_order_parameters( does not permit calculation of angles between multiple neighbors. """ - # Do error-checking and initialization. if n < 0: raise ValueError("Site index smaller zero!") @@ -3929,7 +3903,6 @@ def get_nn_data(self, structure: Structure, n: int, length=None): - a dict of CN -> weight - a dict of CN -> associated near neighbor sites """ - length = length or self.fingerprint_length # determine possible bond targets @@ -4127,7 +4100,6 @@ def transform_to_length(nndata, length): nndata: (NNData) length: (int) desired length of NNData """ - if length is None: return nndata @@ -4219,7 +4191,6 @@ def __init__(self, cut_off_dict=None): the cut-off distances will have to explicitly include the oxidation state, e.g. {('Fe2+', 'O2-'): 2.0} """ - self.cut_off_dict = cut_off_dict or {} # for convenience diff --git a/pymatgen/analysis/magnetism/analyzer.py b/pymatgen/analysis/magnetism/analyzer.py index 334e1a2811a..015c478ac27 100644 --- a/pymatgen/analysis/magnetism/analyzer.py +++ b/pymatgen/analysis/magnetism/analyzer.py @@ -142,7 +142,6 @@ def __init__( below which nonmagnetic ions (with no magmom specified in default_magmoms) will be rounded to zero """ - if default_magmoms: self.default_magmoms = default_magmoms else: @@ -308,7 +307,6 @@ def _round_magmoms(magmoms: VectorLike, round_magmoms_mode: int | float) -> np.n of decimal places, else if set to a float will try and round intelligently by grouping magmoms. """ - if isinstance(round_magmoms_mode, int): # simple rounding to number of decimal places @@ -350,7 +348,6 @@ def get_structure_with_spin(self) -> Structure: """Returns a Structure with species decorated with spin values instead of using magmom site properties. """ - structure = self.structure.copy() structure.add_spin_by_site(structure.site_properties["magmom"]) structure.remove_site_property("magmom") @@ -366,7 +363,6 @@ def get_structure_with_only_magnetic_atoms(self, make_primitive: bool = True) -> Returns: Structure """ - sites = [site for site in self.structure if abs(site.properties["magmom"]) > 0] structure = Structure.from_sites(sites) @@ -386,7 +382,6 @@ def get_nonmagnetic_structure(self, make_primitive: bool = True) -> Structure: Returns: Structure """ - structure = self.structure.copy() structure.remove_site_property("magmom") @@ -406,7 +401,6 @@ def get_ferromagnetic_structure(self, make_primitive: bool = True) -> Structure: Returns: Structure """ - structure = self.structure.copy() structure.add_site_property("magmom", [abs(m) for m in self.magmoms]) @@ -458,7 +452,6 @@ def magnetic_species_and_magmoms(self) -> dict[str, Any]: Returns: dict of magnetic species and magmoms """ - structure = self.get_ferromagnetic_structure() magtypes: dict = {str(site.specie): set() for site in structure if site.properties["magmom"] != 0} @@ -482,7 +475,6 @@ def number_of_magnetic_sites(self) -> int: def number_of_unique_magnetic_sites(self, symprec: float = 1e-3, angle_tolerance: float = 5) -> int: """ - Args: symprec: same as in SpacegroupAnalyzer (Default value = 1e-3) angle_tolerance: same as in SpacegroupAnalyzer (Default value = 5) @@ -490,7 +482,6 @@ def number_of_unique_magnetic_sites(self, symprec: float = 1e-3, angle_tolerance Returns: Number of symmetrically-distinct magnetic sites present in structure. """ - structure = self.get_nonmagnetic_structure() sga = SpacegroupAnalyzer(structure, symprec=symprec, angle_tolerance=angle_tolerance) @@ -513,7 +504,6 @@ def ordering(self) -> Ordering: Returns: Ordering Enum ('FiM' is used as the abbreviation for ferrimagnetic) """ - if not self.is_collinear: warnings.warn("Detecting ordering in non-collinear structures not yet implemented.") return Ordering.Unknown @@ -557,7 +547,6 @@ def get_exchange_group_info(self, symprec: float = 1e-2, angle_tolerance: float Returns: spacegroup_symbol, international_number """ - structure = self.get_structure_with_spin() return structure.get_space_group_info(symprec=symprec, angle_tolerance=angle_tolerance) @@ -570,7 +559,6 @@ def matches_ordering(self, other: Structure) -> bool: Returns: True or False """ - a = CollinearMagneticStructureAnalyzer( self.structure, overwrite_magmom_mode="normalize" ).get_structure_with_spin() @@ -602,7 +590,6 @@ def __str__(self): two identical Structures with different magnetic orderings easier. """ - frac_coords = self.structure.frac_coords sorted_indices = np.lexsort((frac_coords[:, 2], frac_coords[:, 1], frac_coords[:, 0])) s = Structure.from_sites([self.structure[idx] for idx in sorted_indices]) @@ -673,7 +660,6 @@ def __init__( transformation_kwargs: keyword arguments to pass to MagOrderingTransformation, to change automatic cell size limits, etc. """ - self.logger = logging.getLogger(type(self).__name__) self.structure = structure @@ -748,7 +734,6 @@ def _sanitize_input_structure(input_structure: Structure) -> Structure: Returns: Structure """ - input_structure = input_structure.copy() # remove any annotated spin @@ -783,7 +768,6 @@ def _generate_transformations(self, structure: Structure) -> dict[str, MagOrderi Returns: dict of Transformations keyed by strategy """ - formula = structure.composition.reduced_formula transformations: dict[str, MagOrderingTransformation] = {} @@ -987,7 +971,6 @@ def _generate_ordered_structures( Returns: List of Structures """ - ordered_structures = self.ordered_structures ordered_structures_origins = self.ordered_structure_origins diff --git a/pymatgen/analysis/magnetism/heisenberg.py b/pymatgen/analysis/magnetism/heisenberg.py index 8027a2bc9aa..4e8b73b2afc 100644 --- a/pymatgen/analysis/magnetism/heisenberg.py +++ b/pymatgen/analysis/magnetism/heisenberg.py @@ -68,7 +68,6 @@ def __init__(self, ordered_structures, energies, cutoff=0.0, tol: float = 0.02): ex_mat (DataFrame): Invertible Heisenberg Hamiltonian for each graph. ex_params (dict): Exchange parameter values (meV/atom) """ - # Save original copies of inputs self.ordered_structures_ = ordered_structures self.energies_ = energies @@ -116,7 +115,6 @@ def _get_graphs(cutoff, ordered_structures): Returns: sgraphs (list): StructureGraph objects. """ - # Strategy for finding neighbors if cutoff: strategy = MinimumDistanceNN(cutoff=cutoff, get_all_sites=True) @@ -142,7 +140,6 @@ def _get_unique_sites(structure): wyckoff_ids (dict): maps tuples of equivalent site indices to their wyckoff symbols """ - # Get a nonmagnetic representation of the supercell geometry s0 = CollinearMagneticStructureAnalyzer( structure, make_primitive=False, threshold=0.0 @@ -178,7 +175,6 @@ def _get_nn_dict(self): Returns: None: (sets self.nn_interactions and self.dists instance variables) """ - tol = self.tol # tolerance on NN distances sgraph = self.sgraphs[0] unique_site_ids = self.unique_site_ids @@ -254,7 +250,6 @@ def _get_exchange_df(self): TODO: * Deal with large variance in |S| across configs """ - sgraphs = self.sgraphs tol = self.tol unique_site_ids = self.unique_site_ids @@ -373,7 +368,6 @@ def get_exchange(self): Returns: ex_params (dict): Exchange parameter values (meV/atom). """ - ex_mat = self.ex_mat # Solve the matrix equation for J_ij values E = ex_mat[["E"]] @@ -412,7 +406,6 @@ def get_low_energy_orderings(self): fm_e (float): fm energy afm_e (float): afm energy """ - fm_struct, afm_struct = None, None mag_min = np.inf mag_max = 0.001 @@ -485,7 +478,6 @@ def estimate_exchange(self, fm_struct=None, afm_struct=None, fm_e=None, afm_e=No Returns: j_avg (float): Average exchange parameter (meV/atom) """ - # Get low energy orderings if not supplied if any(arg is None for arg in [fm_struct, afm_struct, fm_e, afm_e]): fm_struct, afm_struct, fm_e, afm_e = self.get_low_energy_orderings() @@ -525,7 +517,6 @@ def get_mft_temperature(self, j_avg): Returns: mft_t (float): Critical temperature (K) """ - num_sublattices = len(self.unique_site_ids) k_boltzmann = 0.0861733 # meV/K @@ -568,7 +559,6 @@ def get_interaction_graph(self, filename=None): Returns: igraph (StructureGraph): Exchange interaction graph. """ - structure = self.ordered_structures[0] sgraph = self.sgraphs[0] @@ -618,7 +608,6 @@ def _get_j_exc(self, i, j, dist): Returns: j_exc (float): Exchange parameter in meV """ - # Get unique site identifiers for k, v in self.unique_site_ids.items(): if i in k: @@ -658,7 +647,6 @@ def get_heisenberg_model(self): Returns: hmodel (HeisenbergModel): MSONable object. """ - # Original formula unit with nonmagnetic ions hm_formula = str(self.ordered_structures_[0].composition.reduced_formula) @@ -718,7 +706,6 @@ def __init__(self, structures, energies, screen=False): screened_structures (list): Sorted structures. screened_energies (list): Sorted energies. """ - # Cleanup structures, energies = self._do_cleanup(structures, energies) @@ -750,7 +737,6 @@ def _do_cleanup(structures, energies): ordered_structures (list): Sanitized structures. ordered_energies (list): Sorted energies. """ - # Get only magnetic ions & give all structures site_properties['magmom'] # zero threshold so that magnetic ions with small moments # are preserved @@ -809,7 +795,6 @@ def _do_screen(structures, energies): screened_structures (list): Sorted structures. screened_energies (list): Sorted energies. """ - magmoms = [s.site_properties["magmom"] for s in structures] n_below_1ub = [len([m for m in ms if abs(m) < 1]) for ms in magmoms] @@ -864,7 +849,6 @@ def __init__( igraph=None, ): """ - Args: formula (str): Reduced formula of compound. structures (list): Structure objects with magmoms. @@ -885,7 +869,6 @@ def __init__( javg (float): exchange param (meV/atom). igraph (StructureGraph): Exchange interaction graph. """ - self.formula = formula self.structures = structures self.energies = energies @@ -905,7 +888,6 @@ def as_dict(self): """ Because some dicts have tuple keys, some sanitization is required for json compatibility. """ - d = {} d["@module"] = type(self).__module__ d["@class"] = type(self).__name__ @@ -1005,7 +987,6 @@ def _get_j_exc(self, i, j, dist): Returns: j_exc (float): Exchange parameter in meV """ - # Get unique site identifiers for k in self.unique_site_ids: if i in k: diff --git a/pymatgen/analysis/magnetism/jahnteller.py b/pymatgen/analysis/magnetism/jahnteller.py index 567e2dc0269..0aa73656b08 100644 --- a/pymatgen/analysis/magnetism/jahnteller.py +++ b/pymatgen/analysis/magnetism/jahnteller.py @@ -39,7 +39,6 @@ def __init__(self): """ Init for JahnTellerAnalyzer. """ - self.spin_configs = { "oct": { # key is number of d electrons 0: {"high": {"e_g": 0, "t_2g": 0}, "default": "high"}, @@ -111,7 +110,6 @@ def get_analysis_and_structure( analysis of structure, with key 'strength' which may be 'none', 'strong', 'weak', or 'unknown' (Default value = 0.1) and decorated structure """ - structure = structure.get_primitive_structure() if calculate_valences: @@ -289,7 +287,6 @@ def is_jahn_teller_active( Returns: boolean, True if might be Jahn-Teller active, False if not """ - active = False try: @@ -358,7 +355,6 @@ def _get_number_of_d_electrons(species: Species) -> float: Returns: Number of d electrons. """ - # TODO: replace with more generic Hund's rule algorithm? # taken from get_crystal_field_spin @@ -382,7 +378,6 @@ def get_magnitude_of_effect_from_species(self, species: str | Species, spin_stat Returns: "none", "weak" or "strong """ - magnitude = "none" sp = get_el_sp(species) diff --git a/pymatgen/analysis/molecule_matcher.py b/pymatgen/analysis/molecule_matcher.py index 27de709d663..2aa2180bebd 100644 --- a/pymatgen/analysis/molecule_matcher.py +++ b/pymatgen/analysis/molecule_matcher.py @@ -364,7 +364,6 @@ def _align_heavy_atoms(mol1, mol2, vmol1, vmol2, ilabel1, ilabel2, eq_atoms): Return: corrected inchi labels of heavy atoms of the second molecule """ - nvirtual = vmol1.NumAtoms() nheavy = len(ilabel1) @@ -836,7 +835,6 @@ def kabsch(P: np.ndarray, Q: np.ndarray): Returns: U: 3x3 rotation matrix """ - # Computation of the cross-covariance matrix C = np.dot(P.T, Q) @@ -880,7 +878,6 @@ def match(self, p: Molecule, ignore_warning=False): V: Translation vector rmsd: Root mean squared deviation between P and Q """ - q = self.target if sorted(p.atomic_numbers) != sorted(q.atomic_numbers): @@ -946,7 +943,6 @@ def fit(self, p: Molecule, ignore_warning=False): p_prime: Rotated and translated of the `p` `Molecule` object rmsd: Root-mean-square-deviation between `p_prime` and the `target` """ - inds, U, V, rmsd = self.match(p, ignore_warning=ignore_warning) p_prime = Molecule.from_sites([p[i] for i in inds]) @@ -990,7 +986,6 @@ def match(self, p: Molecule): V: Translation vector rmsd: Root mean squared deviation between P and Q """ - if sorted(p.atomic_numbers) != sorted(self.target.atomic_numbers): raise ValueError("The number of the same species aren't matching!") @@ -1039,7 +1034,6 @@ def fit(self, p: Molecule): p_prime: Rotated and translated of the `p` `Molecule` object rmsd: Root-mean-square-deviation between `p_prime` and the `target` """ - inds, U, V, rmsd = self.match(p) # Translate and rotate `mol1` unto `mol2` using Kabsch algorithm. @@ -1131,7 +1125,6 @@ def get_principal_axis(coords, weights): Returns: Array of dim 3 containing the principal axis """ - Ixx = Iyy = Izz = Ixy = Ixz = Iyz = 0.0 for (x, y, z), wt in zip(coords, weights): @@ -1165,7 +1158,6 @@ def rotation_matrix_vectors(v1, v2): Returns: 3x3 rotation matrix """ - if np.allclose(v1, v2): # same direction return np.eye(3) @@ -1280,7 +1272,6 @@ def permutations(self, p: Molecule): Returns: Array of index arrays """ - # caching atomic numbers and coordinates p_atoms, q_atoms = p.atomic_numbers, self.target.atomic_numbers p_coords, q_coords = p.cart_coords, self.target.cart_coords diff --git a/pymatgen/analysis/molecule_structure_comparator.py b/pymatgen/analysis/molecule_structure_comparator.py index 70c23763e81..7d4bf9cfb4d 100644 --- a/pymatgen/analysis/molecule_structure_comparator.py +++ b/pymatgen/analysis/molecule_structure_comparator.py @@ -288,7 +288,6 @@ def from_dict(cls, d): Returns: MoleculeStructureComparator """ - return cls( bond_length_cap=d["bond_length_cap"], covalent_radius=d["covalent_radius"], diff --git a/pymatgen/analysis/piezo_sensitivity.py b/pymatgen/analysis/piezo_sensitivity.py index 597e0d3454f..8fc69e0e721 100644 --- a/pymatgen/analysis/piezo_sensitivity.py +++ b/pymatgen/analysis/piezo_sensitivity.py @@ -42,7 +42,6 @@ def __init__(self, structure: Structure, bec, pointops, tol: float = 1e-3): input_matrix (Nx3x3 array-like): the Nx3x3 array-like representing the born effective charge tensor """ - self.structure = structure self.bec = bec self.pointops = pointops @@ -121,7 +120,6 @@ def get_rand_BEC(self, max_charge=1): Return: np.array Born effective charge tensor """ - struct = self.structure symstruc = sga(struct) symstruc = symstruc.get_symmetrized_structure() @@ -186,7 +184,6 @@ def __init__(self, structure: Structure, ist, pointops, tol: float = 1e-3): input_matrix (Nx3x3x3 array-like): the Nx3x3x3 array-like representing the internal strain tensor """ - self.structure = structure self.ist = ist self.pointops = pointops @@ -212,7 +209,6 @@ def get_IST_operations(self, opstol=1e-03): list of symmetry operations mapping equivalent sites and the indexes of those sites. """ - struct = self.structure ops = sga(struct).get_symmetry_operations(cartesian=True) uniquepointops = [] @@ -248,7 +244,6 @@ def get_rand_IST(self, max_force=1): Return: InternalStrainTensor object """ - l = len(self.structure) IST = np.zeros((l, 3, 3, 3)) for atom, ops in enumerate(self.IST_operations): @@ -285,7 +280,6 @@ def __init__(self, structure: Structure, fcm, pointops, sharedops, tol: float = input_matrix (NxNx3x3 array-like): the NxNx3x3 array-like representing the force constant matrix """ - self.structure = structure self.fcm = fcm self.pointops = pointops @@ -384,7 +378,6 @@ def get_unstable_FCM(self, max_force=1): Return: numpy array representing the force constant matrix """ - struct = self.structure operations = self.FCM_operations # set max force in reciprocal space @@ -447,7 +440,6 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1): Return: 3Nx3N numpy array representing the force constant matrix """ - operations = self.FCM_operations D = unsymmetrized_fcm for op in operations: @@ -512,7 +504,6 @@ def get_stable_FCM(self, fcm, fcmasum=10): Return: 3Nx3N numpy array representing the force constant matrix """ - check = 0 count = 0 while check == 0: diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index b82b0b44b09..6868902c3cc 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -693,7 +693,6 @@ def _generate_multielement_entries(self, entries, nproc=None): nproc (int): number of processes to be used in parallel treatment of entry combos """ - N = len(self._elt_comp) # No. of elements total_comp = Composition(self._elt_comp) @@ -873,7 +872,6 @@ def get_decomposition_energy(self, entry, pH, V): Decomposition energy for the entry, i. e. the energy above the "Pourbaix hull" in eV/atom at the given conditions """ - # Check composition consistency between entry and Pourbaix diagram: pbx_comp = Composition(self._elt_comp).fractional_composition entry_pbx_comp = Composition( diff --git a/pymatgen/analysis/prototypes.py b/pymatgen/analysis/prototypes.py index 01b7516efcb..0215dab1490 100644 --- a/pymatgen/analysis/prototypes.py +++ b/pymatgen/analysis/prototypes.py @@ -104,7 +104,6 @@ def get_prototypes(self, structure): but it is possible a material can match multiple prototypes. """ - tags = self._match_single_prototype(structure) if len(tags) == 0: diff --git a/pymatgen/analysis/reaction_calculator.py b/pymatgen/analysis/reaction_calculator.py index f7a9721faae..a134073677d 100644 --- a/pymatgen/analysis/reaction_calculator.py +++ b/pymatgen/analysis/reaction_calculator.py @@ -480,7 +480,6 @@ def calculated_reaction_energy_uncertainty(self): Calculates the uncertainty in the reaction energy based on the uncertainty in the energies of the products and reactants """ - calc_energies = {} for entry in self._reactant_entries + self._product_entries: diff --git a/pymatgen/analysis/structure_prediction/volume_predictor.py b/pymatgen/analysis/structure_prediction/volume_predictor.py index a4f59bf980e..51821b4bced 100644 --- a/pymatgen/analysis/structure_prediction/volume_predictor.py +++ b/pymatgen/analysis/structure_prediction/volume_predictor.py @@ -63,7 +63,6 @@ def predict(self, structure: Structure, ref_structure): Returns: a float value of the predicted volume """ - if self.check_isostructural: m = StructureMatcher() mapping = m.get_best_electronegativity_anonymous_mapping(structure, ref_structure) @@ -179,7 +178,6 @@ def predict(self, structure: Structure, icsd_vol=False): Returns: a float value of the predicted volume. """ - # Get standard deviation of electronnegativity in the structure. std_x = np.std([site.specie.X for site in structure]) # Sites that have atomic radii diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index 349e5816505..8681f18a7e1 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -127,7 +127,6 @@ def __init__( marker (str): Custom marker for gamma plots ("--" and "-" are typical) color (str or rgba): Custom color for gamma plots """ - self.miller_index = miller_index self.label = label self.adsorbates = [] if not adsorbates else adsorbates @@ -149,7 +148,6 @@ def as_dict(self): """ Returns dict which contains Slab Entry data. """ - d = {"@module": type(self).__module__, "@class": type(self).__name__} d["structure"] = self.structure d["energy"] = self.energy @@ -169,7 +167,6 @@ def gibbs_binding_energy(self, eads=False): (True) or the binding energy (False) which is just adsorption energy normalized by number of adsorbates. """ - n = self.get_unit_primitive_area Nads = self.Nads_in_slab @@ -190,7 +187,6 @@ def surface_energy(self, ucell_entry, ref_entries=None): Returns (Add (Sympy class)): Surface energy """ - # Set up ref_entries = [] if not ref_entries else ref_entries @@ -247,7 +243,6 @@ def get_unit_primitive_area(self): Returns the surface area of the adsorbed system per unit area of the primitive slab system. """ - A_ads = self.surface_area A_clean = self.clean_entry.surface_area n = A_ads / A_clean @@ -276,7 +271,6 @@ def Nsurfs_ads_in_slab(self): """ Returns the TOTAL number of adsorbed surfaces in the slab """ - struct = self.structure weights = [s.species.weight for s in struct] center_of_mass = np.average(struct.frac_coords, weights=weights, axis=0) @@ -300,7 +294,6 @@ def from_dict(cls, d): """ Returns a SlabEntry by reading in an dictionary """ - structure = SlabEntry.from_dict(d["structure"]) energy = SlabEntry.from_dict(d["energy"]) miller_index = d["miller_index"] @@ -341,7 +334,6 @@ def create_slab_label(self): Returns a label (str) for this particular slab based on composition, coverage and Miller index. """ - if "label" in self.data: return self.data["label"] @@ -445,7 +437,6 @@ def __init__(self, all_slab_entries, ucell_entry, ref_entries=None): LiFePO4 than your ref_entries should have an entry for Li, Fe, and P if you want to use the chempot of O as the variable. """ - self.ucell_entry = ucell_entry self.ref_entries = ref_entries self.all_slab_entries = ( @@ -509,7 +500,6 @@ def get_stable_entry_at_u( Returns: SlabEntry, surface_energy (float) """ - all_delu_dict = self.set_all_variables(delu_dict, delu_default) def get_coeffs(e): @@ -561,7 +551,6 @@ def wulff_from_chempot( Returns: (WulffShape): The WulffShape at u_ref and u_ads. """ - latt = SpacegroupAnalyzer(self.ucell_entry.structure).get_conventional_standard_structure().lattice miller_list = list(self.all_slab_entries) @@ -610,7 +599,6 @@ def area_frac_vs_chempot_plot( (Pylab): Plot of area frac on the Wulff shape for each facet vs chemical potential. """ - delu_dict = delu_dict or {} chempot_range = sorted(chempot_range) all_chempots = np.linspace(min(chempot_range), max(chempot_range), increments) @@ -850,7 +838,6 @@ def color_palette_dict(self, alpha=0.35): clean surfaces have a solid color while the corresponding adsorbed surface will be transparent. """ - color_dict = {} for hkl in self.all_slab_entries: rgb_indices = [0, 1, 2] @@ -1078,7 +1065,6 @@ def monolayer_vs_BE(self, plot_eads=False): Returns: (Plot): Plot of binding energy vs monolayer for all facets. """ - plt = pretty_plot(width=8, height=7) for hkl in self.all_slab_entries: ml_be_dict = {} @@ -1121,7 +1107,6 @@ def chempot_plot_addons(plt, xrange, ref_el, axes, pad=2.4, rect=None, ylim=None return (Plot): Modified plot with addons. return (Plot): Modified plot with addons. """ - # Make the figure look nice plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.0) axes.set_xlabel(rf"Chemical potential $\Delta\mu_{{{ref_el}}}$ (eV)") @@ -1168,7 +1153,6 @@ def BE_vs_clean_SE( (Plot): Plot of clean surface energy vs binding energy for all facets. """ - plt = pretty_plot(width=8, height=7) for hkl in self.all_slab_entries: for clean_entry in self.all_slab_entries[hkl]: @@ -1234,7 +1218,6 @@ def surface_chempot_range_map( show_unphyiscal_only (bool): Whether to only show the shaded region where surface energy is negative. Useful for drawing other chempot range maps. """ - # Set up delu_dict = delu_dict or {} plt = pretty_plot(12, 8) if not plt else plt @@ -1348,7 +1331,6 @@ def set_all_variables(self, delu_dict, delu_default): Returns: Dictionary of set chemical potential values """ - # Set up the variables all_delu_dict = {} for du in self.list_of_chempots: @@ -1474,7 +1456,6 @@ def __init__(self, structure: Structure, locpot_along_c, efermi, shift=0, blengt blength (float (Ang)): The longest bond length in the material. Used to handle pbc for noncontiguous slab layers """ - # ensure shift between 0 and 1 if shift < 0: shift += -1 * int(shift) + 1 @@ -1540,7 +1521,6 @@ def get_locpot_along_slab_plot(self, label_energies=True, plt=None, label_fontsi Returns plt of the locpot vs c axis """ - plt = pretty_plot(width=6, height=4) if not plt else plt # plot the raw locpot signal along c @@ -1592,7 +1572,6 @@ def get_labels(self, plt, label_fontsize=10): label_fontsize (float): Fontsize of labels Returns Labelled plt """ - # 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 @@ -1674,7 +1653,6 @@ def is_converged(self, min_points_frac=0.015, tol: float = 0.0025): Returns a bool (whether or not the work function is converged) """ - conv_within = tol * (max(self.locpot_along_c) - min(self.locpot_along_c)) min_points = int(min_points_frac * len(self.locpot_along_c)) peak_i = self.locpot_along_c.index(self.vacuum_locpot) @@ -1690,7 +1668,6 @@ def is_converged(self, min_points_frac=0.015, tol: float = 0.0025): @staticmethod def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5): """ - :param poscar_filename: POSCAR file :param locpot_filename: LOCPOT file :param outcar_filename: OUTCAR file @@ -1741,7 +1718,6 @@ def __init__(self, se_analyzers, symprec=1e-5): """ Analyzes the nanoscale stability of different polymorphs. """ - self.se_analyzers = se_analyzers self.symprec = symprec @@ -1767,7 +1743,6 @@ def solve_equilibrium_point(self, analyzer1, analyzer2, delu_dict=None, delu_def Returns: Particle radius in nm """ - # Set up wulff1 = analyzer1.wulff_from_chempot( delu_dict=delu_dict or {}, delu_default=delu_default, symprec=self.symprec @@ -1813,7 +1788,6 @@ def wulff_gform_and_r( Returns: particle formation energy (float in keV), effective radius """ - # Set up miller_se_dict = wulffshape.miller_energy_dict new_wulff = self.scaled_wulff(wulffshape, r) @@ -1871,7 +1845,6 @@ def scaled_wulff(self, wulffshape, r): Returns: WulffShape (scaled by r) """ - # get the scaling ratio for the energies r_ratio = r / wulffshape.effective_radius miller_list = wulffshape.miller_energy_dict.keys() @@ -1920,7 +1893,6 @@ def plot_one_stability_map( e_units (str): Can be keV or eV normalize (str): Whether or not to normalize energy by volume """ - plt = plt or pretty_plot(width=8, height=7) wulffshape = analyzer.wulff_from_chempot(delu_dict=delu_dict, delu_default=delu_default, symprec=self.symprec) @@ -1981,7 +1953,6 @@ def plot_all_stability_map( formation energy. Either by treating the volume and thus surface area of the particle as a perfect sphere, or as a Wulff shape. """ - plt = plt or pretty_plot(width=8, height=7) for i, analyzer in enumerate(self.se_analyzers): diff --git a/pymatgen/analysis/tests/test_wulff.py b/pymatgen/analysis/tests/test_wulff.py index 0979d09c2e6..25000b9669b 100644 --- a/pymatgen/analysis/tests/test_wulff.py +++ b/pymatgen/analysis/tests/test_wulff.py @@ -94,7 +94,6 @@ def symm_check(self, ucell, wulff_vertices): return (bool) """ - space_group_analyzer = SpacegroupAnalyzer(ucell) symm_ops = space_group_analyzer.get_point_group_operations(cartesian=True) for point in wulff_vertices: diff --git a/pymatgen/analysis/topological/spillage.py b/pymatgen/analysis/topological/spillage.py index 0a2a7ad8be6..af31b90a8df 100644 --- a/pymatgen/analysis/topological/spillage.py +++ b/pymatgen/analysis/topological/spillage.py @@ -24,7 +24,6 @@ def __init__(self, wf_noso="", wf_so=""): wf_noso : WAVECAR without spin-orbit coupling wf_so : WAVECAR with spin-orbit coupling """ - self.wf_noso = wf_noso self.wf_so = wf_so diff --git a/pymatgen/analysis/wulff.py b/pymatgen/analysis/wulff.py index 97bc324cc66..48305480f3e 100644 --- a/pymatgen/analysis/wulff.py +++ b/pymatgen/analysis/wulff.py @@ -174,7 +174,6 @@ def __init__(self, lattice: Lattice, miller_list, e_surf_list, symprec=1e-5): e_surf_list ([float]): list of corresponding surface energies symprec (float): for recp_operation, default is 1e-5. """ - if any(se < 0 for se in e_surf_list): warnings.warn("Unphysical (negative) surface energy detected.") @@ -362,7 +361,6 @@ def get_line_in_facet(self, facet): """ Returns the sorted pts in a facet used to draw a line """ - lines = list(facet.outer_lines) pt = [] prev = None @@ -554,7 +552,6 @@ def get_plotly( Return: (plotly.graph_objs.Figure) """ - units = "Jm⁻²" if units_in_JPERM2 else "eVÅ⁻²" ( color_list, diff --git a/pymatgen/analysis/xas/spectrum.py b/pymatgen/analysis/xas/spectrum.py index 45e1cd9cae3..6caa049f3e6 100644 --- a/pymatgen/analysis/xas/spectrum.py +++ b/pymatgen/analysis/xas/spectrum.py @@ -77,7 +77,6 @@ def __init__( """ Initializes a spectrum object. """ - super().__init__(x, y, structure, absorbing_element, edge) self.structure = structure self.absorbing_element = absorbing_element diff --git a/pymatgen/apps/battery/analyzer.py b/pymatgen/apps/battery/analyzer.py index ba8a2094ff4..64bf0ad4c66 100644 --- a/pymatgen/apps/battery/analyzer.py +++ b/pymatgen/apps/battery/analyzer.py @@ -65,7 +65,6 @@ def max_ion_removal(self): Returns: integer amount of ion. Depends on cell size (this is an 'extrinsic' function!) """ - # how much 'spare charge' is left in the redox metals for oxidation or reduction? if self.working_ion_charge < 0: lowest_oxid = defaultdict(lambda: 2, {"Cu": 1}) # only Cu can go down to 1+ @@ -164,7 +163,6 @@ def get_max_capvol(self, remove=True, insert=True, volume=None): Returns: max vol capacity in mAh/cc """ - vol = volume or self.struc_oxid.volume return self._get_max_cap_ah(remove, insert) * 1000 * 1e24 / (vol * const.N_A) @@ -183,7 +181,6 @@ def get_removals_int_oxid(self): Returns: array of integer ion removals. If you double the unit cell, your answers will be twice as large! """ - # the elements that can possibly be oxidized or reduced oxid_els = [Element(spec.symbol) for spec in self.comp if is_redox_active_intercalation(spec)] @@ -206,7 +203,6 @@ def _get_int_removals_helper(self, spec_amts_oxi, redox_el, redox_els, numa): Returns: a set of numbers A; steps for oxidizing oxid_el first, then the other oxid_els in this list """ - # If a given redox_el has multiple oxidation states present in the structure, we want # to oxidize the lowest state or reduce the highest state if self.working_ion_charge < 0: diff --git a/pymatgen/apps/battery/battery_abc.py b/pymatgen/apps/battery/battery_abc.py index 15b003be1fd..506aa852f04 100644 --- a/pymatgen/apps/battery/battery_abc.py +++ b/pymatgen/apps/battery/battery_abc.py @@ -402,7 +402,6 @@ def get_summary_dict(self, print_subelectrodes=True) -> dict: Returns: A summary of this electrode's properties in dict format. """ - d = { "average_voltage": self.get_average_voltage(), "max_voltage": self.max_voltage, diff --git a/pymatgen/apps/battery/conversion_battery.py b/pymatgen/apps/battery/conversion_battery.py index 960d78e652e..ff0a45f5389 100644 --- a/pymatgen/apps/battery/conversion_battery.py +++ b/pymatgen/apps/battery/conversion_battery.py @@ -146,7 +146,6 @@ def get_sub_electrodes(self, adjacent_only=True): Returns: A list of ConversionElectrode objects """ - # voltage_pairs = vpairs, working_ion_entry = working_ion_entry, # _initial_comp_formula = comp.reduced_formula, framework_formula = framework.reduced_formula if adjacent_only: @@ -250,7 +249,6 @@ def get_summary_dict(self, print_subelectrodes=True) -> dict: Returns: A summary of this electrode's properties in dict format. """ - d = super().get_summary_dict(print_subelectrodes=print_subelectrodes) d["reactions"] = [] d["reactant_compositions"] = [] diff --git a/pymatgen/apps/battery/insertion_battery.py b/pymatgen/apps/battery/insertion_battery.py index 909e9973ab7..7716d0088d9 100644 --- a/pymatgen/apps/battery/insertion_battery.py +++ b/pymatgen/apps/battery/insertion_battery.py @@ -60,7 +60,6 @@ def from_entries( ComputedEntry.data['volume']. If entries provided are ComputedEntries, must set strip_structures=False. """ - if strip_structures: ents = [] for ient in entries: @@ -330,7 +329,6 @@ def get_summary_dict(self, print_subelectrodes=True) -> dict: Returns: A summary of this electrode's properties in dict format. """ - d = super().get_summary_dict(print_subelectrodes=print_subelectrodes) chg_comp = self.fully_charged_entry.composition diff --git a/pymatgen/command_line/bader_caller.py b/pymatgen/command_line/bader_caller.py index 4d2acab0c60..12562ebbf08 100644 --- a/pymatgen/command_line/bader_caller.py +++ b/pymatgen/command_line/bader_caller.py @@ -387,7 +387,6 @@ def summary(self): """ :return: Dict summary of key analysis, e.g., atomic volume, charge, etc. """ - summary = { "min_dist": [d["min_dist"] for d in self.data], "charge": [d["charge"] for d in self.data], diff --git a/pymatgen/command_line/chargemol_caller.py b/pymatgen/command_line/chargemol_caller.py index dff7206cc22..7e5a10ec916 100644 --- a/pymatgen/command_line/chargemol_caller.py +++ b/pymatgen/command_line/chargemol_caller.py @@ -180,7 +180,6 @@ def _execute_chargemol(self, **jobcontrol_kwargs): Default: None. jobcontrol_kwargs: Keyword arguments for _write_jobscript_for_chargemol. """ - with ScratchDir("."): with zopen(self._chgcarpath, "rt") as f_in: with open("CHGCAR", "wt") as f_out: @@ -439,7 +438,6 @@ def _get_dipole_info(filepath): Args: filepath (str): The path to the DDEC6_even_tempered_net_atomic_charges.xyz file """ - i = 0 start = False dipoles = [] @@ -535,7 +533,6 @@ def summary(self): } } """ - summary = {} ddec_summary = { "partial_charges": self.ddec_charges, @@ -576,7 +573,6 @@ def _get_data_from_xyz(xyz_path): Returns: list[float]: site-specific properties """ - props = [] if os.path.exists(xyz_path): with open(xyz_path) as r: diff --git a/pymatgen/command_line/critic2_caller.py b/pymatgen/command_line/critic2_caller.py index 51645734bbd..f68757f295b 100644 --- a/pymatgen/command_line/critic2_caller.py +++ b/pymatgen/command_line/critic2_caller.py @@ -80,7 +80,6 @@ def __init__(self, input_script): :param input_script: string defining the critic2 input """ - # store if examining the input script is useful, # not otherwise used self._input_script = input_script @@ -179,7 +178,6 @@ def from_chgcar( (ZVAL in VASP pseudopotential), with which to properly augment core regions and calculate charge transfer. Optional. """ - settings = {"CPEPS": 0.1, "SEED": ["WS", "PAIR DIST 10"]} if user_input_settings: settings.update(user_input_settings) @@ -272,7 +270,6 @@ def from_path(cls, path, suffix="", zpsp=None): :param zpsp: manually specify ZPSP if POTCAR not present :return: """ - chgcar_path = get_filepath("CHGCAR", "Could not find CHGCAR!", path, suffix) chgcar = Chgcar.from_file(chgcar_path) chgcar_ref = None @@ -465,7 +462,6 @@ class with bonding information. By default, this returns (ZVAL in VASP pseudopotential), with which to calculate charge transfer. Optional. """ - self.structure = structure self._stdout = stdout @@ -501,7 +497,6 @@ def structure_graph(self, include_critical_points=("bond", "ring", "cage")): Returns: a StructureGraph """ - structure = self.structure.copy() point_idx_to_struct_idx = {} @@ -684,7 +679,6 @@ def _remap_indices(self): Re-maps indices on self.nodes and self.edges such that node indices match that of structure, and then sorts self.nodes by index. """ - # Order of nuclei provided by critic2 doesn't # necessarily match order of sites in Structure. # This is because critic2 performs a symmetrization step. diff --git a/pymatgen/command_line/enumlib_caller.py b/pymatgen/command_line/enumlib_caller.py index 4c36c8f595c..a722fc4911b 100644 --- a/pymatgen/command_line/enumlib_caller.py +++ b/pymatgen/command_line/enumlib_caller.py @@ -169,7 +169,6 @@ def _gen_input_file(self): different equivalent sites is dealt with by having determined the spacegroup earlier and labelling the species differently. """ - # index_species and index_amounts store mappings between the indices # used in the enum input file, and the actual species and amounts. index_species = [] diff --git a/pymatgen/command_line/tests/test_bader_caller.py b/pymatgen/command_line/tests/test_bader_caller.py index d92bcfb0089..1fbef4c2145 100644 --- a/pymatgen/command_line/tests/test_bader_caller.py +++ b/pymatgen/command_line/tests/test_bader_caller.py @@ -101,7 +101,6 @@ def test_automatic_runner(self): 'reference_used': True } """ - self.assertEqual( set(summary), { diff --git a/pymatgen/command_line/vampire_caller.py b/pymatgen/command_line/vampire_caller.py index 87c7e6d2398..5b4c27b39f3 100644 --- a/pymatgen/command_line/vampire_caller.py +++ b/pymatgen/command_line/vampire_caller.py @@ -94,7 +94,6 @@ def __init__( TODO: * Create input files in a temp folder that gets cleaned up after run terminates """ - self.mc_box_size = mc_box_size self.equil_timesteps = equil_timesteps self.mc_timesteps = mc_timesteps @@ -400,7 +399,6 @@ def parse_stdout(vamp_stdout, nmats): parsed_out (DataFrame): MSONable vampire output. critical_temp (float): Calculated critical temp. """ - names = ["T", "m_total"] + ["m_" + str(i) for i in range(1, nmats + 1)] + ["X_x", "X_y", "X_z", "X_m", "nan"] # Parsing vampire MC output @@ -428,7 +426,6 @@ def __init__(self, parsed_out=None, nmats=None, critical_temp=None): nmats (int): Number of distinct materials (1 for each specie and up/down spin). critical_temp (float): Monte Carlo Tc result. """ - self.parsed_out = parsed_out self.nmats = nmats self.critical_temp = critical_temp diff --git a/pymatgen/core/interface.py b/pymatgen/core/interface.py index ec7c77b2699..e12e1005e92 100644 --- a/pymatgen/core/interface.py +++ b/pymatgen/core/interface.py @@ -76,7 +76,6 @@ def __init__( the original distance between substrate and film sites vacuum_over_film: vacuum space above the film in Angstroms """ - assert ( "interface_label" in site_properties ), "Must provide labeling of substrate and film sites in site properties" @@ -201,7 +200,6 @@ def copy(self): Returns: Interface: A copy of the Interface. """ - return Interface.from_dict(self.as_dict()) def get_sorted_structure(self, key=None, reverse=False) -> Structure: diff --git a/pymatgen/core/ion.py b/pymatgen/core/ion.py index 171ef6bc1cc..13478d03f80 100644 --- a/pymatgen/core/ion.py +++ b/pymatgen/core/ion.py @@ -282,7 +282,6 @@ def oxi_state_guesses( # type: ignore oxidation state across all sites in that composition. If the composition is not charge balanced, an empty list is returned. """ - return self._get_oxid_state_guesses(all_oxi_states, max_sites, oxi_states_override, self.charge)[0] def __eq__(self, other: object) -> bool: diff --git a/pymatgen/core/lattice.py b/pymatgen/core/lattice.py index 3dcdcd74a04..01ac15adefd 100644 --- a/pymatgen/core/lattice.py +++ b/pymatgen/core/lattice.py @@ -213,7 +213,6 @@ def d_hkl(self, miller_index: ArrayLike) -> float: Returns: d_hkl (float) """ - gstar = self.reciprocal_lattice_crystallographic.metric_tensor hkl = np.array(miller_index) return 1 / ((dot(dot(hkl, gstar), hkl.T)) ** (1 / 2)) @@ -349,7 +348,6 @@ def from_parameters( Returns: Lattice with the specified lattice parameters. """ - angles_r = np.radians([alpha, beta, gamma]) cos_alpha, cos_beta, cos_gamma = np.cos(angles_r) sin_alpha, sin_beta, sin_gamma = np.sin(angles_r) @@ -971,7 +969,6 @@ def as_dict(self, verbosity: int = 0) -> dict: verbosity (int): Verbosity level. Default of 0 only includes the matrix representation. Set to 1 for more details. """ - d = { "@module": type(self).__module__, "@class": type(self).__name__, diff --git a/pymatgen/core/operations.py b/pymatgen/core/operations.py index ad9ab1d40c5..02fcdce7d8c 100644 --- a/pymatgen/core/operations.py +++ b/pymatgen/core/operations.py @@ -205,7 +205,6 @@ def are_symmetrically_related_vectors( Returns: (are_related, is_reversed) """ - from_c = self.operate(from_a) to_c = self.operate(to_a) @@ -567,7 +566,6 @@ class or as list or np array-like Returns: Magnetic moment after operator applied as Magmom class """ - magmom = Magmom(magmom) # type casting to handle lists as input transformed_moment = ( diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index 35e3f4d8fe9..b9e2a2e984b 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -1141,7 +1141,6 @@ def ionic_radius(self) -> float | None: """ Ionic radius of specie. Returns None if data is not present. """ - if self._oxi_state in self.ionic_radii: return self.ionic_radii[self._oxi_state] if self._oxi_state: @@ -1178,7 +1177,6 @@ def from_string(species_string: str) -> Species: Raises: ValueError if species_string cannot be interpreted. """ - # e.g. Fe2+,spin=5 # 1st group: ([A-Z][a-z]*) --> Fe # 2nd group: ([0-9.]*) --> "2" @@ -1246,7 +1244,6 @@ def get_nmr_quadrupole_moment(self, isotope: str | None = None) -> float: isotope (str): the isotope to get the quadrupole moment for default is None, which gets the lowest mass isotope """ - quad_mom = self._el.nmr_quadrupole_moment if not quad_mom: diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index 093d37201cc..6a138485813 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -308,7 +308,6 @@ def is_symmetric(self, symprec: float = 0.1): Returns: (bool) Whether surfaces are symmetric. """ - sg = SpacegroupAnalyzer(self, symprec=symprec) symmops = sg.get_point_group_operations() @@ -558,7 +557,6 @@ def get_surface_sites(self, tag=False): than one unequivalent site. This will allow us to use this for compound systems. """ - from pymatgen.analysis.local_env import VoronoiNN # Get a dictionary of coordination numbers @@ -624,7 +622,6 @@ def get_symmetric_site(self, point, cartesian=False): point: Fractional coordinate. A point equivalent to the parameter point, but on the other side of the slab """ - sg = SpacegroupAnalyzer(self) ops = sg.get_symmetry_operations(cartesian=cartesian) @@ -664,7 +661,6 @@ def symmetrically_add_atom(self, specie, point, coords_are_cartesian=False): Returns: (Slab): The modified slab """ - # For now just use the species of the # surface atom as the element to add @@ -684,7 +680,6 @@ def symmetrically_remove_atoms(self, indices): indices ([indices]): The indices of the sites in the slab to remove. """ - slabcopy = SpacegroupAnalyzer(self.copy()).get_symmetrized_structure() points = [slabcopy[i].frac_coords for i in indices] removal_list = [] @@ -943,7 +938,6 @@ def get_slab(self, shift=0, tol: float = 0.1, energy=None): Returns: (Slab) A Slab object with a particular shifted oriented unit cell. """ - h = self._proj_height p = round(h / self.parent.lattice.d_hkl(self.miller_index), 8) if self.in_unit_planes: @@ -1185,7 +1179,6 @@ def repair_broken_bonds(self, slab, bonds): Returns: (Slab) A Slab object with a particular shifted oriented unit cell. """ - for pair in bonds: blength = bonds[pair] @@ -1249,7 +1242,6 @@ def move_to_other_side(self, init_slab, index_of_sites): Returns: (Slab) A Slab object with a particular shifted oriented unit cell. """ - slab = init_slab.copy() # Determine what fraction the slab is of the total cell size @@ -1300,7 +1292,6 @@ def nonstoichiometric_symmetrized_slab(self, init_slab): Returns: Slab (structure): A symmetrized Slab object. """ - if init_slab.is_symmetric(): return [init_slab] @@ -1469,7 +1460,6 @@ def __init__(self, initial_structure, min_slab_size, min_vacuum_size, reconstruc WILL MODIFY THE BOTTOM SURFACE ACCORDINGLY TO RETURN A SLAB WITH EQUIVALENT SURFACES. """ - if reconstruction_name not in reconstructions_archive: raise KeyError( f"The reconstruction_name entered ({reconstruction_name}) does not exist in the " @@ -1523,7 +1513,6 @@ def build_slabs(self): Returns: (Slab): The reconstructed slab. """ - slabs = self.get_unreconstructed_slabs() recon_slabs = [] diff --git a/pymatgen/core/units.py b/pymatgen/core/units.py index 7826799cf09..1580e7d7918 100644 --- a/pymatgen/core/units.py +++ b/pymatgen/core/units.py @@ -183,7 +183,6 @@ def __init__(self, unit_def): format uses "^" as the power operator and all units must be space-separated. """ - if isinstance(unit_def, str): unit = collections.defaultdict(int) import re diff --git a/pymatgen/electronic_structure/bandstructure.py b/pymatgen/electronic_structure/bandstructure.py index ae17bbe4af4..b16443cbcb8 100644 --- a/pymatgen/electronic_structure/bandstructure.py +++ b/pymatgen/electronic_structure/bandstructure.py @@ -149,7 +149,6 @@ def from_dict(cls, d): Returns: A Kpoint object """ - return cls( coords=d["fcoords"], lattice=Lattice.from_dict(d["lattice"]), @@ -962,7 +961,6 @@ def as_dict(self): """ JSON-serializable dict representation of BandStructureSymmLine. """ - d = { "@module": type(self).__module__, "@class": type(self).__name__, diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index 428a5c78728..47ab35ca03c 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -557,7 +557,6 @@ def run( Returns: """ - # TODO: consider making this a part of custodian rather than pymatgen # A lot of this functionality (scratch dirs, handlers, monitors) # is built into custodian framework @@ -1366,7 +1365,6 @@ def get_seebeck_eff_mass(self, output="average", temp=300, doping_levels=False, if 'tensor' is selected, each element of the lists is a list containing the three components of the seebeck effective mass. """ - if doping_levels: sbk_mass = {} for dt in ("n", "p"): @@ -1423,7 +1421,6 @@ def get_complexity_factor(self, output="average", temp=300, doping_levels=False, if 'tensor' is selected, each element of the lists is a list containing the three components of the complexity factor. """ - if doping_levels: cmplx_fact = {} for dt in ("n", "p"): @@ -1688,7 +1685,6 @@ def get_carrier_concentration(self): (in cm^-3) at each temperature The array relates to each step of electron chemical potential """ - return {temp: [1e24 * i / self.vol for i in self._carrier_conc[temp]] for temp in self._carrier_conc} def get_hall_carrier_concentration(self): @@ -1757,7 +1753,6 @@ def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): Returns: tuple - (DOS, dict of partial DOS) """ - data_dos = {"total": [], "partial": {}} # parse the total DOS data # format is energy, DOS, integrated DOS @@ -1871,7 +1866,6 @@ def parse_cond_and_hall(path_dir, doping_levels=None): mu_doping, seebeck_doping, cond_doping, kappa_doping, hall_doping, carrier_conc """ - # Step 1: parse raw data but do not convert to final format t_steps = set() mu_steps = set() diff --git a/pymatgen/electronic_structure/boltztrap2.py b/pymatgen/electronic_structure/boltztrap2.py index a1d58fddb18..9cacaed70a2 100644 --- a/pymatgen/electronic_structure/boltztrap2.py +++ b/pymatgen/electronic_structure/boltztrap2.py @@ -74,7 +74,6 @@ def __init__(self, obj, structure=None, nelect=None): vrun = Vasprun('vasprun.xml') data = VasprunBSLoader(vrun) """ - if isinstance(obj, Vasprun): structure = obj.final_structure nelect = obj.parameters["NELECT"] @@ -206,7 +205,6 @@ def __init__(self, bs_obj, structure=None, nelect=None, mommat=None, magmom=None ne = vrun.parameters['NELECT'] data = BandstructureLoader(bs,st,ne) """ - warnings.warn("Deprecated Loader. Use VasprunBSLoader instead.") self.kpoints = np.array([kp.frac_coords for kp in bs_obj.kpoints]) @@ -327,7 +325,6 @@ def __init__(self, vrun_obj=None): """ vrun_obj: Vasprun object. """ - warnings.warn("Deprecated Loader. Use VasprunBSLoader instead.") if vrun_obj: @@ -531,7 +528,6 @@ def get_band_structure(self, kpaths=None, kpoints_lbls_dict=None, density=20): 'X':np.array(0.5,0.5,0.)} density: Number of points in each segment. """ - if isinstance(kpaths, list) and isinstance(kpoints_lbls_dict, dict): kpoints = [] for kpath in kpaths: @@ -811,7 +807,6 @@ def compute_properties_doping(self, doping, temp_r=None): Carriers_conc_doping: carriers concentration for each doping level and T. mu_doping_eV: the chemical potential corrispondent to each doping level. """ - if temp_r is None: temp_r = self.temp_r @@ -1081,7 +1076,6 @@ def plot_props( more example are provided in the notebook "How to use Boltztra2 interface.ipynb". """ - props = ( "Conductivity", "Seebeck", diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index d945eb18807..a46058048a2 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -1131,7 +1131,6 @@ def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up): Returns: float describing ICOHP/ICOOP value """ - icohp_here = self._icohplist[label] if icohp_here._is_spin_polarized: if summed_spin_channels: @@ -1206,7 +1205,6 @@ def get_icohp_dict_of_site( Returns: dict of IcohpValues, the keys correspond to the values from the initial list_labels """ - newicohp_dict = {} for key, value in self._icohplist.items(): atomnumber1 = int(re.split(r"(\d+)", value._atom1)[1]) - 1 diff --git a/pymatgen/electronic_structure/core.py b/pymatgen/electronic_structure/core.py index a0e1f0fc9f0..45c76f0f50b 100644 --- a/pymatgen/electronic_structure/core.py +++ b/pymatgen/electronic_structure/core.py @@ -222,7 +222,6 @@ def get_moment(self, saxis=(0, 0, 1)): :param saxis: (list/numpy array) spin quantization axis :return: np.ndarray of length 3 """ - # transform back to moment with spin axis [0, 0, 1] m_inv = self._get_transformation_matrix_inv(self.saxis) moment = np.matmul(self.moment, m_inv) diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index 3f056cfd5ec..7440003aafe 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -135,7 +135,6 @@ def get_plot(self, xlim=None, ylim=None): determination. ylim: Specifies the y-axis limits. """ - ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) @@ -263,7 +262,6 @@ def __init__(self, bs: BandStructureSymmLine) -> None: Args: bs: A BandStructureSymmLine object. """ - self._bs: list[BandStructureSymmLine] = [] self._nb_bands: list[int] = [] @@ -427,7 +425,6 @@ def bs_plot_data(self, zero_to_efermi=True, bs=None, bs_ref=None, split_branches is_metal: True if the band structure is metallic (i.e., there is at least one band crossing the fermi level). """ - if bs is None: if isinstance(self._bs, list): # if BSPlotter @@ -528,7 +525,6 @@ def _interpolate_bands(distances, energies, smooth_tol=0, smooth_k=3, smooth_np= number of branches (high symmetry lines) defined in the BandStructureSymmLine object (see BandStructureSymmLine._branches). """ - int_energies, int_distances = [], [] smooth_k_orig = smooth_k @@ -894,7 +890,6 @@ def plot_brillouin(self): """ plot the Brillouin zone """ - # get labels and lines labels = {} for k in self._bs[0].kpoints: @@ -2813,7 +2808,6 @@ def plot_seebeck_eff_mass_mu(self, temps=(300,), output="average", Lambda=0.5): Returns: a matplotlib object """ - plt = pretty_plot(9, 7) for T in temps: sbk_mass = self._bz.get_seebeck_eff_mass(output=output, temp=T, Lambda=0.5) @@ -3055,7 +3049,6 @@ def plot_seebeck_temp(self, doping="all", output="average"): Returns: a matplotlib object """ - if output == "average": sbk = self._bz.get_seebeck(output="average") elif output == "eigs": @@ -3110,7 +3103,6 @@ def plot_conductivity_temp(self, doping="all", output="average", relaxation_time Returns: a matplotlib object """ - if output == "average": cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output="average") elif output == "eigs": @@ -3166,7 +3158,6 @@ def plot_power_factor_temp(self, doping="all", output="average", relaxation_time Returns: a matplotlib object """ - if output == "average": pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output="average") elif output == "eigs": @@ -3221,7 +3212,6 @@ def plot_zt_temp(self, doping="all", output="average", relaxation_time=1e-14): Returns: a matplotlib object """ - if output == "average": zt = self._bz.get_zt(relaxation_time=relaxation_time, output="average") elif output == "eigs": @@ -3275,7 +3265,6 @@ def plot_eff_mass_temp(self, doping="all", output="average"): Returns: a matplotlib object """ - if output == "average": em = self._bz.get_average_eff_mass(output="average") elif output == "eigs": @@ -3328,7 +3317,6 @@ def plot_seebeck_dop(self, temps="all", output="average"): Returns: a matplotlib object """ - if output == "average": sbk = self._bz.get_seebeck(output="average") elif output == "eigs": @@ -3547,7 +3535,6 @@ def plot_eff_mass_dop(self, temps="all", output="average"): Returns: a matplotlib object """ - if output == "average": em = self._bz.get_average_eff_mass(output="average") elif output == "eigs": diff --git a/pymatgen/entries/__init__.py b/pymatgen/entries/__init__.py index 635d1263e33..76ead676059 100644 --- a/pymatgen/entries/__init__.py +++ b/pymatgen/entries/__init__.py @@ -100,7 +100,6 @@ def normalize(self, mode: Literal["formula_unit", "atom"] = "formula_unit") -> E mode ("formula_unit" | "atom"): "formula_unit" (the default) normalizes to composition.reduced_formula. "atom" normalizes such that the composition amounts sum to 1. """ - factor = self._normalization_factor(mode) new_composition = self._composition / factor new_energy = self._energy / factor diff --git a/pymatgen/entries/computed_entries.py b/pymatgen/entries/computed_entries.py index 48047958315..9d1626cca3c 100644 --- a/pymatgen/entries/computed_entries.py +++ b/pymatgen/entries/computed_entries.py @@ -439,7 +439,6 @@ def normalize(self, mode: Literal["formula_unit", "atom"] = "formula_unit") -> C mode ("formula_unit" | "atom"): "formula_unit" (the default) normalizes to composition.reduced_formula. "atom" normalizes such that the composition amounts sum to 1. """ - factor = self._normalization_factor(mode) new_composition = self._composition / factor new_energy = self._energy / factor @@ -604,7 +603,6 @@ def __init__( with the entry. Defaults to None. entry_id: An optional id to uniquely identify the entry. """ - if composition: composition = Composition(composition) if ( @@ -893,7 +891,6 @@ def _g_delta_sisso(vol_per_atom, reduced_mass, temp) -> float: Returns: float: G^delta [eV/atom] """ - return ( (-2.48e-4 * np.log(vol_per_atom) - 8.94e-5 * reduced_mass / vol_per_atom) * temp + 0.181 * np.log(temp) diff --git a/pymatgen/entries/entry_tools.py b/pymatgen/entries/entry_tools.py index 6adc1ea810a..04fd1cc0d5c 100644 --- a/pymatgen/entries/entry_tools.py +++ b/pymatgen/entries/entry_tools.py @@ -316,7 +316,6 @@ def to_csv(self, filename: str, latexify_names: bool = False) -> None: latexify_names: Format entry names to be LaTex compatible, e.g., Li_{2}O """ - els: set[Element] = set() for entry in self.entries: els.update(entry.composition.elements) diff --git a/pymatgen/entries/tests/test_correction_calculator.py b/pymatgen/entries/tests/test_correction_calculator.py index b45a32b81f4..e310f4df789 100644 --- a/pymatgen/entries/tests/test_correction_calculator.py +++ b/pymatgen/entries/tests/test_correction_calculator.py @@ -108,7 +108,6 @@ def test_normal_corrections(self): """ Test that the values in MPCompatiblity.yaml are reproduced correctly. """ - exp_path = os.path.join(self.test_dir, "exp_compounds_norm.json.gz") calc_path = os.path.join(self.test_dir, "calc_compounds_norm.json.gz") @@ -121,7 +120,6 @@ def test_warnings_options(self): """ Test that compounds can be included/excluded using the allow_{warning} optional parameters. """ - exp_path = os.path.join(self.test_dir, "exp_compounds_norm.json.gz") calc_path = os.path.join(self.test_dir, "calc_compounds_norm.json.gz") @@ -134,7 +132,6 @@ def test_no_uncertainties(self): """ Test that corrections can be calculated with no uncertainties. """ - exp_path = os.path.join(self.test_dir, "exp_no_error_compounds.json.gz") calc_path = os.path.join(self.test_dir, "calc_compounds_norm.json.gz") @@ -147,7 +144,6 @@ def test_missing_entry_response(self): """ Test that correct error is raised (ValueError) if the input is missing a computed entry. """ - exp_path = os.path.join(self.test_dir, "exp_compounds_norm.json.gz") calc_path = os.path.join(self.test_dir, "calc_missing_compounds.json.gz") diff --git a/pymatgen/ext/optimade.py b/pymatgen/ext/optimade.py index 426712d8068..5c0a14c6eb0 100644 --- a/pymatgen/ext/optimade.py +++ b/pymatgen/ext/optimade.py @@ -100,7 +100,6 @@ def __init__(self, aliases_or_resource_urls: str | list[str] | None = None, time timeout: number of seconds before an attempted request is abandoned, a good timeout is useful when querying many providers, some of which may be offline """ - # TODO: maybe we should use the nice pydantic models from optimade-python-tools # for response validation, and use the Lark parser for filter validation self.session = requests.Session() @@ -170,7 +169,6 @@ def _build_filter( """ Convenience method to build an OPTIMADE filter. """ - filters = [] if elements: @@ -222,7 +220,6 @@ def get_structures( Returns: Dict of (Dict Structures keyed by that database's id system) keyed by provider """ - optimade_filter = self._build_filter( elements=elements, nelements=nelements, @@ -263,7 +260,6 @@ def get_snls( Returns: Dict of (Dict of StructureNLs keyed by that database's id system) keyed by provider """ - optimade_filter = self._build_filter( elements=elements, nelements=nelements, @@ -283,7 +279,6 @@ def get_structures_with_filter(self, optimade_filter: str) -> dict[str, dict[str Returns: Dict of Structures keyed by that database's id system """ - all_snls = self.get_snls_with_filter(optimade_filter) all_structures = {} @@ -305,7 +300,6 @@ def get_snls_with_filter( Returns: Dict of Structures keyed by that database's id system """ - all_snls = {} fields = self._handle_response_fields(additional_response_fields) @@ -496,7 +490,6 @@ def _parse_provider(self, provider, provider_url) -> dict[str, Provider]: A dictionary of keys (in format of "provider.database") to Provider objects. """ - try: url = join(provider_url, "v1/links") provider_link_json = self._get_json(url) diff --git a/pymatgen/io/abinit/inputs.py b/pymatgen/io/abinit/inputs.py index c5dd5068582..4b61f6e861a 100644 --- a/pymatgen/io/abinit/inputs.py +++ b/pymatgen/io/abinit/inputs.py @@ -931,7 +931,6 @@ def set_kpath(self, ndivsm, kptbounds=None, iscf=-2): kptbounds: k-points defining the path in k-space. If None, we use the default high-symmetry k-path defined in the pymatgen database. """ - if kptbounds is None: from pymatgen.symmetry.bandstructure import HighSymmKpath diff --git a/pymatgen/io/adf.py b/pymatgen/io/adf.py index c35f5e0be15..940dfb5314c 100644 --- a/pymatgen/io/adf.py +++ b/pymatgen/io/adf.py @@ -654,7 +654,6 @@ def write_file(self, molecule, inpfile): inpfile : str The name where the input file will be saved. """ - mol_blocks = [] atom_block = AdfKey("Atoms", options=["cartesian"]) for site in molecule: @@ -771,7 +770,6 @@ def _parse_logfile(self, logfile): """ Parse the formatted logfile. """ - cycle_patt = re.compile(r"Coordinates\sin\sGeometry\sCycle\s(\d+)") coord_patt = re.compile(r"\s+([0-9]+)\.([A-Za-z]+)" + 3 * r"\s+([-\.0-9]+)") energy_patt = re.compile(r"<.*>\s<.*>\s+current\senergy\s+([-\.0-9]+)\sHartree") diff --git a/pymatgen/io/ase.py b/pymatgen/io/ase.py index 102adb4e6ae..fe55e7f4ac0 100644 --- a/pymatgen/io/ase.py +++ b/pymatgen/io/ase.py @@ -147,7 +147,6 @@ def get_structure(atoms, cls=None, **cls_kwargs): Returns: Equivalent pymatgen.core.structure.Structure """ - cls = Structure if cls is None else cls symbols = atoms.get_chemical_symbols() @@ -252,7 +251,6 @@ def get_molecule(atoms, cls=None, **cls_kwargs): Returns: Equivalent pymatgen.core.structure.Molecule """ - cls = Molecule if cls is None else cls molecule = AseAtomsAdaptor.get_structure(atoms, cls=cls, **cls_kwargs) if atoms.has("initial_charges"): diff --git a/pymatgen/io/atat.py b/pymatgen/io/atat.py index 809315e6b71..80964edc8f7 100644 --- a/pymatgen/io/atat.py +++ b/pymatgen/io/atat.py @@ -29,7 +29,6 @@ def __init__(self, structure): """ :param structure: input Structure """ - self.structure = structure def to_string(self): @@ -37,7 +36,6 @@ def to_string(self): Returns a structure in mcsqs rndstr.in format. :return (str): """ - # add lattice vectors m = self.structure.lattice.matrix output = [f"{l[0]:6f} {l[1]:6f} {l[2]:6f}" for l in m] @@ -71,7 +69,6 @@ def structure_from_string(data): :param data: contents of a rndstr.in, lat.in or bestsqs.out file :return: Structure object """ - data = data.splitlines() data = [x.split() for x in data if x] # remove empty lines diff --git a/pymatgen/io/cif.py b/pymatgen/io/cif.py index 1ebe70d50b4..6a413635311 100644 --- a/pymatgen/io/cif.py +++ b/pymatgen/io/cif.py @@ -389,7 +389,6 @@ def _sanitize_data(self, data): CIF files extracted from the Springer Materials/Pauling File databases, and that are different from standard ICSD formats. """ - # check for implicit hydrogens, warn if any present if "_atom_site_attached_hydrogens" in data.data: attached_hydrogens = [str2float(x) for x in data.data["_atom_site_attached_hydrogens"] if str2float(x) != 0] @@ -490,7 +489,6 @@ def _sanitize_data(self, data): as a result of magCIF being in widespread use prior to specification being finalized (on advice of Branton Campbell). """ - if self.feature_flags["magcif"]: # CIF-1 style has all underscores, interim standard @@ -1142,7 +1140,6 @@ def get_structures(self, primitive=True, symmetrized=False): Returns: List of Structures. """ - if primitive and symmetrized: raise ValueError( "Using both 'primitive' and 'symmetrized' arguments is not currently supported " @@ -1176,7 +1173,6 @@ def get_bibtex_string(self): :param data: :return: BibTeX string """ - try: from pybtex.database import BibliographyData, Entry except ImportError: @@ -1289,7 +1285,6 @@ def __init__( refine_struct: Used only if symprec is not None. If True, get_refined_structure is invoked to convert input structure from primitive to conventional. """ - if write_magmoms and symprec: warnings.warn("Magnetic symmetry cannot currently be detected by pymatgen,disabling symmetry detection.") symprec = None diff --git a/pymatgen/io/cp2k/inputs.py b/pymatgen/io/cp2k/inputs.py index 7606ba2fd39..8fb0094865b 100644 --- a/pymatgen/io/cp2k/inputs.py +++ b/pymatgen/io/cp2k/inputs.py @@ -297,7 +297,6 @@ def __init__( kwargs are interpreted as keyword, value pairs and added to the keywords array as Keyword objects """ - self.name = name self.subsections = subsections if subsections is not None else {} self.repeats = repeats @@ -745,7 +744,6 @@ def _from_dict(cls, d): """ Initialize from a dictionary """ - return Cp2kInput( "CP2K_INPUT", subsections=getattr( @@ -876,7 +874,6 @@ def __init__( project_name (str, optional): Defaults to "CP2K". run_type (str, optional) what type of calculation to run """ - self.project_name = project_name self.run_type = run_type self.kwargs = kwargs @@ -912,7 +909,6 @@ def __init__(self, subsections: dict = None, **kwargs): Args: subsections (dict, optional): Defaults to None. """ - self.subsections = subsections or {} self.kwargs = kwargs @@ -962,7 +958,6 @@ def __init__( wfn_restart_file_name (str, optional): Defaults to None. subsections (dict, optional): Any subsections to initialize with. Defaults to None. """ - self.basis_set_filenames = basis_set_filenames self.potential_filename = potential_filename self.uks = uks @@ -1040,7 +1035,6 @@ def __init__( or ASPC (ASPC especially for MD runs). See the manual for other options. subsections (dict): Subsections to initialize with. """ - self.method = method self.eps_default = eps_default self.extrapolation = extrapolation @@ -1096,7 +1090,6 @@ def __init__( "SPARSE": Generate a sparse wavefunction using the atomic code (for OT based methods). """ - self.max_scf = max_scf self.eps_scf = eps_scf self.scf_guess = scf_guess @@ -1153,7 +1146,6 @@ def __init__( progression_factor: divisor that decides how to map Gaussians the multigrid after the highest mapping is decided by rel_cutoff """ - self.cutoff = cutoff self.rel_cutoff = rel_cutoff self.ngrids = ngrids @@ -1205,7 +1197,6 @@ def __init__( """ Initialize the diagronalization section """ - self.eps_adapt = eps_adapt self.eps_iter = eps_iter self.eps_jacobi = eps_jacobi @@ -1330,7 +1321,6 @@ def __init__( GOLD should always find an electronic minimum. Whereas the 2PNT minimizer is almost always OK, 3PNT might be needed for systems in which successive OT CG steps do not decrease the total energy. """ - self.minimizer = minimizer self.preconditioner = preconditioner self.algorithm = algorithm @@ -1385,7 +1375,6 @@ def __init__(self, lattice: Lattice, **kwargs): Args: lattice: pymatgen lattice object """ - self.lattice = lattice self.kwargs = kwargs @@ -1435,7 +1424,6 @@ def __init__( potential file kwargs: Additional kwargs to pass to Section() """ - self.name = "KIND" self.specie = specie self.alias = alias @@ -1528,7 +1516,6 @@ def __init__( u_minus_j: (float) the effective U parameter, Ueff = U-J u_ramping: (float) stepwise amount to increase during ramping until u_minus_j is reached """ - self.name = "DFT_PLUS_U" self.eps_u_ramping = 1e-5 self.init_u_ramping_each_scf = False @@ -1575,7 +1562,6 @@ def __init__( alias (bool): whether or not to identify the sites by Element + number so you can do things like assign unique magnetization do different elements. """ - self.structure = structure self.aliases = aliases self.subsections = subsections or {} @@ -1620,7 +1606,6 @@ def __init__(self, nlumo: int = -1, **kwargs): Args: nlumo: how many unoccupied orbitals to include (-1==ALL) """ - self.nlumo = nlumo self.kwargs = kwargs @@ -1647,7 +1632,6 @@ def __init__(self, index: int = 1, alias: str | None = None, **kwargs): Args: index: Index of the atom to project onto """ - self.index = index self.alias = alias self.kwargs = kwargs @@ -1676,7 +1660,6 @@ def __init__(self, keywords=None, **kwargs): """ Initialize the V_HARTREE_CUBE section """ - self.keywords = keywords or {} self.kwargs = kwargs @@ -1705,7 +1688,6 @@ def __init__(self, write_cube: bool = False, nhomo: int = 1, nlumo: int = 1, **k """ Initialize the MO_CUBES section """ - self.write_cube = write_cube self.nhomo = nhomo self.nlumo = nlumo @@ -1742,7 +1724,6 @@ def __init__(self, keywords=None, **kwargs): """ Initialize the E_DENSITY_CUBE Section """ - self.keywords = keywords or {} self.kwargs = kwargs @@ -1776,7 +1757,6 @@ def __init__( """ Initialize the SMEAR section """ - self.elec_temp = elec_temp self.method = method self.fixed_magnetic_moment = fixed_magnetic_moment @@ -1829,7 +1809,6 @@ def __init__( n_beta: Same as N_alpha for beta channel nel_beta: Same as NEL_alpha for beta channel """ - self.l_alpha = l_alpha self.n_alpha = n_alpha self.nel_alpha = nel_alpha @@ -1946,7 +1925,6 @@ def __init__(self, functionals: Iterable = None, subsections: dict = None, **kwa """ Initialize the XC_FUNCTIONAL class """ - self.functionals = functionals or [] self.subsections = subsections or {} self.kwargs = kwargs @@ -1986,7 +1964,6 @@ def __init__( scale_c (float): scales the correlation part of the functional. scale_x (float): scales the exchange part of the functional. """ - self.parameterization = parameterization self.scale_c = scale_c self.scale_x = scale_x diff --git a/pymatgen/io/cp2k/outputs.py b/pymatgen/io/cp2k/outputs.py index d11c5652f51..4c0f69fec20 100644 --- a/pymatgen/io/cp2k/outputs.py +++ b/pymatgen/io/cp2k/outputs.py @@ -50,7 +50,6 @@ def __init__(self, filename, verbose=False, auto_load=False): verbose: (bool) Whether or not to parse with verbosity (will parse lots of data that may not be useful) auto_load (bool): Whether or not to automatically load basic info like energies and structures. """ - # IO Info self.filename = filename self.dir = os.path.dirname(filename) @@ -501,7 +500,6 @@ def parse_forces(self): """ Get the forces from the output file """ - if len(self.filenames["forces"]) == 1: self.data["forces"] = [ [list(atom.coords) for atom in step] @@ -525,7 +523,6 @@ def parse_stresses(self): """ Get the stresses from the output file. """ - if len(self.filenames["stress"]) == 1: dat = np.genfromtxt(self.filenames["stress"][0], skip_header=1) dat = [dat] if len(np.shape(dat)) == 1 else dat diff --git a/pymatgen/io/cp2k/sets.py b/pymatgen/io/cp2k/sets.py index b3a8c89b825..1090962453e 100644 --- a/pymatgen/io/cp2k/sets.py +++ b/pymatgen/io/cp2k/sets.py @@ -304,7 +304,6 @@ def __init__( smearing (bool): whether or not to activate smearing (should be done for systems containing no (or a very small) band gap. """ - super().__init__(structure, **kwargs) self.structure = structure diff --git a/pymatgen/io/exciting/inputs.py b/pymatgen/io/exciting/inputs.py index d36d11e788b..f7d2c503ee4 100644 --- a/pymatgen/io/exciting/inputs.py +++ b/pymatgen/io/exciting/inputs.py @@ -55,7 +55,6 @@ def __init__(self, structure: Structure, title=None, lockxyz=None): lockxyz (Nx3 array): bool values for selective dynamics, where N is number of sites. Defaults to None. """ - if structure.is_ordered: site_properties = {} if lockxyz: @@ -84,7 +83,6 @@ def from_string(data): """ Reads the exciting input from a string """ - root = ET.fromstring(data) speciesnode = root.find("structure").iter("species") elements = [] diff --git a/pymatgen/io/feff/inputs.py b/pymatgen/io/feff/inputs.py index 4b209bf0618..b8fbcfc0aab 100644 --- a/pymatgen/io/feff/inputs.py +++ b/pymatgen/io/feff/inputs.py @@ -758,7 +758,6 @@ def proc_val(key, val): key: Feff parameter key val: Actual value of Feff parameter. """ - list_type_keys = list(VALID_FEFF_TAGS) del list_type_keys[list_type_keys.index("ELNES")] del list_type_keys[list_type_keys.index("EXELFS")] @@ -920,7 +919,6 @@ def pot_dict_from_string(pot_data): Returns: forward and reverse atom symbol and potential number dictionaries. """ - pot_dict = {} pot_dict_reverse = {} begin = 0 diff --git a/pymatgen/io/feff/sets.py b/pymatgen/io/feff/sets.py index 79fd6d2ea0f..dd82b6d85a1 100644 --- a/pymatgen/io/feff/sets.py +++ b/pymatgen/io/feff/sets.py @@ -140,7 +140,6 @@ def __init__( spacegroup_analyzer_settings: dict | None = None, ): """ - Args: absorbing_atom (str/int): absorbing atom symbol or site index structure: Structure or Molecule object. If a Structure, SpaceGroupAnalyzer is used to @@ -563,7 +562,6 @@ def __init__( user_tag_settings (dict): override default tag settings **kwargs: Passthrough to FEFFDictSet """ - super().__init__( absorbing_atom, structure, @@ -622,7 +620,6 @@ def __init__( user_tag_settings (dict): override default tag settings **kwargs: Passthrough to FEFFDictSet """ - super().__init__( absorbing_atom, structure, diff --git a/pymatgen/io/fiesta.py b/pymatgen/io/fiesta.py index 932e1090e09..840397f6f58 100644 --- a/pymatgen/io/fiesta.py +++ b/pymatgen/io/fiesta.py @@ -45,7 +45,6 @@ def __init__(self, folder, filename="nwchem", log_file="log_n2f"): the run method launches NWCHEM2FIESTA """ - self.folder = folder self.filename = filename self.log_file = log_file @@ -59,7 +58,6 @@ def run(self): """ Performs actual NWCHEM2FIESTA run """ - init_folder = os.getcwd() os.chdir(self.folder) @@ -132,7 +130,6 @@ def _gw_run(self): """ Performs FIESTA (gw) run """ - if self.folder != os.getcwd(): init_folder = os.getcwd() os.chdir(self.folder) @@ -158,7 +155,6 @@ def bse_run(self): """ Performs BSE run """ - if self.folder != os.getcwd(): init_folder = os.getcwd() os.chdir(self.folder) @@ -274,7 +270,6 @@ def set_n_nlmo(self): """ :return: the number of nlm orbitals for the basis set """ - nnlmo = 0 data_tmp = self.data @@ -327,7 +322,6 @@ def __init__( :param GW_options: dict :param BSE_TDDFT_options: dict """ - self._mol = mol self.correlation_grid = correlation_grid or {"dE_grid": "0.500", "n_grid": "14"} self.Exc_DFT_option = Exc_DFT_option or {"rdVxcpsi": "1"} @@ -357,7 +351,6 @@ def set_auxiliary_basis_set(self, folder, auxiliary_folder, auxiliary_basis_set_ :param auxiliary_basis_set_type: type of basis set (string to be found in the extension of the file name; must be in lower case). ex: C2.ion_aug_cc_pvtz_RI_Weigend find "aug_cc_pvtz" """ - list_files = os.listdir(auxiliary_folder) for specie in self._mol.symbol_set: @@ -373,7 +366,6 @@ def set_GW_options(self, nv_band=10, nc_band=10, n_iteration=5, n_grid=6, dE_gri :param n_iteration: number of iteration :param n_grid and dE_grid:: number of points and spacing in eV for correlation grid """ - self.GW_options.update(nv_corr=nv_band, nc_corr=nc_band, nit_gw=n_iteration) self.correlation_grid.update(dE_grid=dE_grid, n_grid=n_grid) @@ -382,7 +374,6 @@ def make_FULL_BSE_Densities_folder(folder): """ mkdir "FULL_BSE_Densities" folder (needed for bse run) in the desired folder """ - if os.path.exists(folder + "/FULL_BSE_Densities"): return "FULL_BSE_Densities folder already exists" @@ -404,7 +395,6 @@ def dump_BSE_data_in_GW_run(self, BSE_dump=True): :param BSE_dump: boolean :return: set the "do_bse" variable to one in cell.in """ - if BSE_dump: self.BSE_TDDFT_options.update(do_bse=1, do_tddft=0) else: @@ -425,7 +415,6 @@ def infos_on_system(self): """ Returns infos on initial parameters as in the log file of Fiesta """ - o = [] o.append("=========================================") o.append("Reading infos on system:") @@ -604,7 +593,6 @@ def from_string(cls, string_input): Returns: FiestaInput object """ - correlation_grid = {} Exc_DFT_option = {} COHSEX_options = {} diff --git a/pymatgen/io/gaussian.py b/pymatgen/io/gaussian.py index 569008490d5..c17bdbcaf86 100644 --- a/pymatgen/io/gaussian.py +++ b/pymatgen/io/gaussian.py @@ -1357,7 +1357,6 @@ def read_excitation_energies(self): A list: A list of tuple for each transition such as [(energie (eV), lambda (nm), oscillatory strength), ... ] """ - transitions = [] # read in file diff --git a/pymatgen/io/lammps/data.py b/pymatgen/io/lammps/data.py index d62eab0f8a5..fd52ef4fc77 100644 --- a/pymatgen/io/lammps/data.py +++ b/pymatgen/io/lammps/data.py @@ -113,7 +113,6 @@ class LammpsBox(MSONable): def __init__(self, bounds, tilt=None): """ - Args: bounds: A (3, 2) array/list of floats setting the boundaries of simulation box. @@ -875,7 +874,6 @@ class Topology(MSONable): def __init__(self, sites, ff_label=None, charges=None, velocities=None, topologies=None): """ - Args: sites ([Site] or SiteCollection): A group of sites in a list or as a Molecule/Structure. @@ -1009,7 +1007,6 @@ def _is_valid(df): def __init__(self, mass_info, nonbond_coeffs=None, topo_coeffs=None): """ - Args: mass_info (list): List of atomic mass info. Elements, strings (symbols) and floats are all acceptable for the diff --git a/pymatgen/io/lammps/utils.py b/pymatgen/io/lammps/utils.py index 5bb28f3206c..c4ca38f2387 100644 --- a/pymatgen/io/lammps/utils.py +++ b/pymatgen/io/lammps/utils.py @@ -328,7 +328,6 @@ def write_pdb(mol, filename, name=None, num=None): """ dump the molecule into pdb file with custom residue name and number. """ - # ugly hack to get around the openbabel issues with inconsistent # residue labelling. scratch = tempfile.gettempdir() @@ -372,7 +371,6 @@ def convert_obatoms_to_molecule(self, atoms, residue_name=None, site_property="f Returns: Molecule object """ - restore_site_props = residue_name is not None if restore_site_props and not hasattr(self, "map_residue_to_mol"): @@ -416,7 +414,6 @@ def restore_site_properties(self, site_property="ff_map", filename=None): Returns: Molecule """ - # only for pdb if not self.control_params["filetype"] == "pdb": raise ValueError() diff --git a/pymatgen/io/lmto.py b/pymatgen/io/lmto.py index a7eb00587a1..07d872e4a1d 100644 --- a/pymatgen/io/lmto.py +++ b/pymatgen/io/lmto.py @@ -126,7 +126,6 @@ def as_dict(self): numbers with the second atom of the same species, e.g. "Bi", "Bi1", "Bi2", etc. """ - eq_atoms = sga.get_symmetry_dataset()["equivalent_atoms"] ineq_sites_index = list(set(eq_atoms)) sites = [] @@ -342,7 +341,6 @@ def __init__(self, filename="COPL", to_eV=False): to_eV: LMTO-ASA gives energies in Ry. To convert energies into eV, set to True. Defaults to False for energies in Ry. """ - # COPL files have an extra trailing blank line with zopen(filename, "rt") as f: contents = f.read().split("\n")[:-1] @@ -416,7 +414,6 @@ def _get_bond_data(line): The bond label, the bond length and a tuple of the site indices. """ - line = line.split() length = float(line[2]) # Replacing "/" with "-" makes splitting easier diff --git a/pymatgen/io/lobster/inputs.py b/pymatgen/io/lobster/inputs.py index a66e409318c..78fe3ed7c52 100644 --- a/pymatgen/io/lobster/inputs.py +++ b/pymatgen/io/lobster/inputs.py @@ -243,7 +243,6 @@ def write_lobsterin(self, path="lobsterin", overwritedict=None): path (str): filename of the lobsterin file that will be written overwritedict (dict): dict that can be used to overwrite lobsterin, e.g. {"skipdos": True} """ - # will overwrite previous entries # has to search first if entry is already in Lobsterindict (due to case insensitivity) if overwritedict is not None: @@ -379,7 +378,6 @@ def get_all_possible_basis_functions( address_basis_file_max: str = None, ): """ - Args: structure: Structure object potcar_symbols: list of the potcar symbols diff --git a/pymatgen/io/lobster/lobsterenv.py b/pymatgen/io/lobster/lobsterenv.py index 1dce27e1a5c..7d303bf488a 100644 --- a/pymatgen/io/lobster/lobsterenv.py +++ b/pymatgen/io/lobster/lobsterenv.py @@ -64,7 +64,6 @@ def __init__( id_blist_sg2="ICOBI", ): """ - Args: are_coops: (Bool) if True, the file is a ICOOPLIST.lobster and not a ICOHPLIST.lobster; only tested for ICOHPLIST.lobster so far @@ -99,7 +98,6 @@ def __init__( id_blist_sg2: (str) Identity of data in filename_blist_sg2, e.g., "icoop" or "icobi" """ - self.ICOHP = Icohplist(are_coops=are_coops, filename=filename_ICOHP) self.Icohpcollection = self.ICOHP.icohpcollection self.structure = structure @@ -260,7 +258,6 @@ def get_light_structure_environment(self, only_cation_environments=False, only_i only_indices: will only evaluate the list of isites in this list Returns: LobsterLightStructureEnvironments Object """ - lgf = LocalGeometryFinder() lgf.setup_structure(structure=self.structure) list_ce_symbols = [] @@ -375,7 +372,6 @@ def get_info_icohps_to_neighbors(self, isites=None, onlycation_isites=True): [the latter is useful for plotting summed COHP plots], list of the central isite for each label """ - if self.valences is None and onlycation_isites: raise ValueError("No valences are provided") if isites is None: @@ -434,7 +430,6 @@ def plot_cohps_of_neighbors( Returns: plt of the cohps """ - # include COHPPlotter and plot a sum of these COHPs # might include option to add Spin channels # implement only_bonds_to @@ -600,7 +595,6 @@ def get_info_icohps_between_neighbors(self, isites=None, onlycation_isites=True) Returns: """ - lowerlimit = self.lowerlimit upperlimit = self.upperlimit @@ -705,7 +699,6 @@ def _evaluate_ce( adapt_extremum_to_add_cond=False, ): """ - Args: lowerlimit: lower limit which determines the ICOHPs that are considered for the determination of the neighbors diff --git a/pymatgen/io/lobster/outputs.py b/pymatgen/io/lobster/outputs.py index 8a61dfddef4..b3ccf272efa 100644 --- a/pymatgen/io/lobster/outputs.py +++ b/pymatgen/io/lobster/outputs.py @@ -210,7 +210,6 @@ def _get_bond_data(line: str) -> dict: indices, a tuple containing the orbitals (if orbital-resolved), and a label for the orbitals (if orbital-resolved). """ - orb_labs = [ "s", "p_y", @@ -661,7 +660,6 @@ def get_structure_with_charges(self, structure_filename): Returns: Structure Object with Mulliken and Loewdin charges as site properties """ - struct = Structure.from_file(structure_filename) Mulliken = self.Mulliken Loewdin = self.Loewdin @@ -829,7 +827,6 @@ def __init__(self, filename="lobsterout"): def get_doc(self): """ - Returns: LobsterDict with all the information stored in lobsterout """ LobsterDict = {} @@ -1261,7 +1258,6 @@ def get_bandstructure(self): """ returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter """ - return LobsterBandStructureSymmLine( kpoints=self.kpoints_array, eigenvals=self.eigenvals, @@ -1343,7 +1339,6 @@ def has_good_quality_maxDeviation(self, limit_maxDeviation: float = 0.1) -> bool Returns: Boolean that will give you information about the quality of the projection """ - for deviation in self.max_deviation: if deviation > limit_maxDeviation: return False @@ -1368,7 +1363,6 @@ def has_good_quality_check_occupied_bands( Returns: Boolean that will give you information about the quality of the projection """ - for matrix in self.bandoverlapsdict[Spin.up].values(): for iband1, band1 in enumerate(matrix["matrix"]): for iband2, band2 in enumerate(band1): @@ -1442,7 +1436,6 @@ def get_structure_with_total_grosspop(self, structure_filename: str) -> Structur Returns: Structure Object with Mulliken and Loewdin total grosspopulations as site properties """ - struct = Structure.from_file(structure_filename) site_properties: dict[str, Any] = {} mullikengp = [] @@ -1486,12 +1479,10 @@ class Wavefunction: def __init__(self, filename, structure): """ - Args: filename: filename of wavecar file from Lobster structure: Structure object (e.g., created by Structure.from_file("")) """ - self.filename = filename self.structure = structure @@ -1595,7 +1586,6 @@ def get_volumetricdata_real(self): Returns: VolumetricData object """ - if not hasattr(self, "volumetricdata_real"): self.set_volumetric_data(self.grid, self.structure) return self.volumetricdata_real @@ -1666,11 +1656,9 @@ class MadelungEnergies: def __init__(self, filename: str = "MadelungEnergies.lobster"): """ - Args: filename: filename of the "MadelungEnergies.lobster" file """ - with zopen(filename, "rt") as f: data = f.read().split("\n")[5] if len(data) == 0: @@ -1708,7 +1696,6 @@ def __init__(self, filename: str = "SitePotentials.lobster"): Args: filename: filename for the SitePotentials file, typically "SitePotentials.lobster" """ - # site_potentials with zopen(filename, "rt") as f: data = f.read().split("\n") @@ -1741,7 +1728,6 @@ def get_structure_with_site_potentials(self, structure_filename): Returns: Structure Object with Mulliken and Loewdin charges as site properties """ - struct = Structure.from_file(structure_filename) Mulliken = self.sitepotentials_Mulliken Loewdin = self.sitepotentials_Loewdin diff --git a/pymatgen/io/prismatic.py b/pymatgen/io/prismatic.py index c0a89d3f7ab..318fd4caa29 100644 --- a/pymatgen/io/prismatic.py +++ b/pymatgen/io/prismatic.py @@ -30,7 +30,6 @@ def to_string(self) -> str: Returns: Prismatic XYZ file. This is similar to XYZ format but has specific requirements for extra fields, headers, etc. """ - lattice = self.structure.lattice lines = [self.comment, " ".join(map(str, lattice.lengths))] for site in self.structure: diff --git a/pymatgen/io/qchem/outputs.py b/pymatgen/io/qchem/outputs.py index 139d8058815..97d27ff3af7 100644 --- a/pymatgen/io/qchem/outputs.py +++ b/pymatgen/io/qchem/outputs.py @@ -813,7 +813,6 @@ def _read_gradients(self): """ Parses all gradients obtained during an optimization trajectory """ - grad_header_pattern = r"Gradient of (?:SCF)?(?:MP2)? Energy(?: \(in au\.\))?" footer_pattern = r"(?:Max gradient component|Gradient time)" @@ -1249,7 +1248,6 @@ def _read_pcm_information(self): """ Parses information from PCM solvent calculations. """ - temp_dict = read_pattern( self.text, { @@ -1281,7 +1279,6 @@ def _read_smd_information(self): """ Parses information from SMD solvent calculations. """ - temp_dict = read_pattern( self.text, { diff --git a/pymatgen/io/shengbte.py b/pymatgen/io/shengbte.py index a1fe1fd9ee2..8d1cf384127 100644 --- a/pymatgen/io/shengbte.py +++ b/pymatgen/io/shengbte.py @@ -179,7 +179,6 @@ def to_file(self, filename: str = "CONTROL"): Args: filename: A file name. """ - for param in self.required_params: if param not in self.as_dict(): warnings.warn(f"Required parameter '{param}' not specified!") @@ -218,7 +217,6 @@ def from_structure(cls, structure: Structure, reciprocal_density: int | None = 5 Returns: A ShengBTE control object. """ - elements = list(map(str, structure.composition.elements)) unique_nums = np.unique(structure.atomic_numbers) diff --git a/pymatgen/io/tests/test_cif.py b/pymatgen/io/tests/test_cif.py index e27b0863b0d..887d9d030d6 100644 --- a/pymatgen/io/tests/test_cif.py +++ b/pymatgen/io/tests/test_cif.py @@ -416,7 +416,6 @@ def test_parse_symbol(self): Test the _parse_symbol function with several potentially problematic examples of symbols and labels. """ - test_cases = { "MgT": "Mg", "MgT1": "Mg", diff --git a/pymatgen/io/tests/test_xcrysden.py b/pymatgen/io/tests/test_xcrysden.py index 2e18e8bd634..1eed907a71d 100644 --- a/pymatgen/io/tests/test_xcrysden.py +++ b/pymatgen/io/tests/test_xcrysden.py @@ -66,7 +66,6 @@ def test_xsf_symbolparse(self): even if the atomic symbol / number convention is different. """ - test_string = """ CRYSTAL PRIMVEC diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index f035968cbf4..d7f6b78830a 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -105,7 +105,6 @@ def __init__( sort_structure: bool = False, ): """ - :param structure: Structure object. :param comment: Optional comment line for POSCAR. Defaults to unit cell formula of structure. Defaults to None. diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index d70ce44f603..4b7902dbdad 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -134,7 +134,6 @@ def potcar(self): def get_vasp_input(self) -> VaspInput: """ - Returns: VaspInput """ @@ -691,7 +690,6 @@ def estimate_nbands(self) -> int: calculation with by default. Note that in practice this can depend on # of cores (if not set explicitly) """ - nions = len(self.structure) # from VASP's point of view, the number of magnetic atoms are @@ -758,7 +756,6 @@ def calculate_ng(self, max_prime_factor: int = 7, must_inc_2: bool = True) -> tu VASP has many different setting for this to handle many compiling options. For typical MPI options all prime factors up to 7 are allowed """ - # TODO throw error for Ultrasoft potentials _RYTOEV = 13.605826 @@ -1774,7 +1771,6 @@ def __init__( magmom (list[list[float]]): Override for the structure magmoms. **kwargs: kwargs supported by MPStaticSet. """ - if not hasattr(structure[0], "magmom") and not isinstance(structure[0].magmom, list): raise ValueError( "The structure must have the 'magmom' site " @@ -2228,7 +2224,6 @@ def kpoints(self): directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ - # To get input sets, the input structure has to has the same number # of required parameters as a Structure object (ie. 4). Slab # attributes aren't going to affect the VASP inputs anyways so @@ -2274,7 +2269,6 @@ class MVLGBSet(MPRelaxSet): def __init__(self, structure: Structure, k_product=40, slab_mode=False, is_metal=True, **kwargs): """ - Args: structure(Structure): provide the structure k_product: Kpoint number * length for a & b directions, also for c @@ -2302,7 +2296,6 @@ def kpoints(self): directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ - # To get input sets, the input structure has to has the same number # of required parameters as a Structure object. @@ -2521,7 +2514,6 @@ class MITMDSet(MITRelaxSet): def __init__(self, structure: Structure, start_temp, end_temp, nsteps, time_step=2, spin_polarized=False, **kwargs): """ - Args: structure (Structure): Input structure. start_temp (int): Starting temperature. @@ -2613,7 +2605,6 @@ def __init__(self, structure: Structure, start_temp, end_temp, nsteps, spin_pola The ISPIN parameter. Defaults to False. **kwargs: Other kwargs supported by :class:`DictSet`. """ - # MD default settings defaults = { "TEBEG": start_temp, @@ -3149,7 +3140,6 @@ def __init__( nedos: the density of DOS, default: 2001. **kwargs: All kwargs supported by DictSet. Typically, user_incar_settings is a commonly used option. """ - # Initialize the input set (default: IPA absorption) super().__init__(structure, **kwargs) diff --git a/pymatgen/io/xtb/inputs.py b/pymatgen/io/xtb/inputs.py index ccb29de3e71..ecb0f13d653 100644 --- a/pymatgen/io/xtb/inputs.py +++ b/pymatgen/io/xtb/inputs.py @@ -39,7 +39,6 @@ def __init__( constraints: dict[str, list[int] | float] | None = None, ): """ - :param molecule (pymatgen Molecule object): Input molecule, the only required CREST input. :param working_dir (str): @@ -60,7 +59,6 @@ def write_input_files(self): """ Write input files to working directory """ - self.molecule.to(filename=os.path.join(self.working_dir, self.coords_filename)) if self.constraints: constrains_string = self.constrains_template( @@ -74,7 +72,6 @@ def write_input_files(self): @staticmethod def constrains_template(molecule, reference_fnm, constraints) -> str: """ - :param molecule (pymatgen Molecule): Molecule the constraints will be performed on :param reference_fnm: diff --git a/pymatgen/io/xtb/outputs.py b/pymatgen/io/xtb/outputs.py index dab925063bf..fcc718d8372 100644 --- a/pymatgen/io/xtb/outputs.py +++ b/pymatgen/io/xtb/outputs.py @@ -35,7 +35,6 @@ def __init__(self, output_filename, path="."): path (str): Path to directory including output_filename and all other xtb output files (crest_best.xyz, etc.) """ - self.path = path self.filename = output_filename diff --git a/pymatgen/phonon/bandstructure.py b/pymatgen/phonon/bandstructure.py index de5bb2528ec..99639ac132b 100644 --- a/pymatgen/phonon/bandstructure.py +++ b/pymatgen/phonon/bandstructure.py @@ -162,7 +162,6 @@ def has_imaginary_freq(self, tol: float = 1e-5) -> bool: """ True if imaginary frequencies are present in the BS. """ - return self.min_freq()[1] + tol < 0 @property @@ -225,7 +224,6 @@ def asr_breaking(self, tol_eigendisplacements=1e-5): identified or eigendisplacements are missing the first 3 modes will be used (indices [0:3]). """ - for i in range(self.nb_qpoints): if np.allclose(self.qpoints[i].frac_coords, (0, 0, 0)): @@ -348,7 +346,6 @@ def __init__( associated with the band structure. This is needed if we provide projections to the band structure """ - super().__init__( qpoints=qpoints, frequencies=frequencies, @@ -600,7 +597,6 @@ def band_reorder(self): def as_dict(self): """ - Returns: MSONable dict """ d = super().as_dict() @@ -614,7 +610,6 @@ def as_dict(self): @classmethod def from_dict(cls, d): """ - Args: d: Dict representation diff --git a/pymatgen/phonon/dos.py b/pymatgen/phonon/dos.py index b279be8922f..e0ca63c61d7 100644 --- a/pymatgen/phonon/dos.py +++ b/pymatgen/phonon/dos.py @@ -56,7 +56,6 @@ def get_smeared_densities(self, sigma): Returns: Gaussian-smeared densities. """ - from scipy.ndimage.filters import gaussian_filter1d diff = [self.frequencies[i + 1] - self.frequencies[i] for i in range(len(self.frequencies) - 1)] @@ -91,7 +90,6 @@ def __radd__(self, other): Returns: Sum of the two DOSs. """ - return self.__add__(other) def get_interpolated_value(self, frequency): @@ -170,7 +168,6 @@ def cv(self, t, structure=None): Returns: Constant volume specific heat C_v """ - if t == 0: return 0 @@ -206,7 +203,6 @@ def entropy(self, t, structure=None): Returns: Vibrational entropy """ - if t == 0: return 0 @@ -240,7 +236,6 @@ def internal_energy(self, t, structure=None): Returns: Phonon contribution to the internal energy """ - if t == 0: return self.zero_point_energy(structure=structure) @@ -274,7 +269,6 @@ def helmholtz_free_energy(self, t, structure=None): Returns: Phonon contribution to the Helmholtz free energy """ - if t == 0: return self.zero_point_energy(structure=structure) @@ -306,7 +300,6 @@ def zero_point_energy(self, structure=None): Returns: Phonon contribution to the internal energy """ - freqs = self._positive_frequencies dens = self._positive_densities @@ -359,7 +352,6 @@ def get_element_dos(self): Returns: dict of {Element: Dos} """ - el_dos = {} for site, atom_dos in self.pdos.items(): el = site.specie diff --git a/pymatgen/phonon/gruneisen.py b/pymatgen/phonon/gruneisen.py index f5ac86bde39..07a6a2945f8 100644 --- a/pymatgen/phonon/gruneisen.py +++ b/pymatgen/phonon/gruneisen.py @@ -50,7 +50,6 @@ def __init__( lattice=None, ): """ - Args: qpoints: list of qpoints as numpy arrays, in frac_coords of the given lattice by default gruneisen: list of gruneisen parameters as numpy arrays, shape: (3*len(structure), len(qpoints)) @@ -60,7 +59,6 @@ def __init__( lattice: The reciprocal lattice as a pymatgen Lattice object. Pymatgen uses the physics convention of reciprocal lattice vectors WITH a 2*pi coefficient """ - self.qpoints = qpoints self.gruneisen = gruneisen self.frequencies = frequencies @@ -165,7 +163,6 @@ def tdos(self): """ The total DOS (re)constructed from the gruneisen.yaml file """ - # Here, we will reuse phonopy classes class TempMesh: """ @@ -184,7 +181,6 @@ class TempMesh: @property def phdos(self): """ - Returns: PhononDos object """ return PhononDos(self.tdos.frequency_points, self.tdos.dos) @@ -279,7 +275,6 @@ def __init__( associated with the band structure. This is needed if we provide projections to the band structure """ - PhononBandStructure.__init__( self, qpoints, @@ -296,7 +291,6 @@ def __init__( def as_dict(self): """ - Returns: MSONable (dict) """ @@ -327,14 +321,12 @@ def as_dict(self): @classmethod def from_dict(cls, d): """ - Args: d (dict): Dict representation Returns: GruneisenPhononBandStructure: Phonon band structure with Grueneisen parameters. """ - lattice_rec = Lattice(d["lattice_rec"]["matrix"]) eigendisplacements = np.array(d["eigendisplacements"]["real"]) + np.array(d["eigendisplacements"]["imag"]) * 1j structure = Structure.from_dict(d["structure"]) if "structure" in d else None @@ -367,7 +359,6 @@ def __init__( structure=None, ): """ - Args: qpoints: list of qpoints as numpy arrays, in frac_coords of the given lattice by default @@ -410,7 +401,6 @@ def __init__( @classmethod def from_dict(cls, d): """ - Args: d: Dict representation diff --git a/pymatgen/phonon/ir_spectra.py b/pymatgen/phonon/ir_spectra.py index 6aa16396375..fbf6f69a1be 100644 --- a/pymatgen/phonon/ir_spectra.py +++ b/pymatgen/phonon/ir_spectra.py @@ -173,7 +173,6 @@ def get_plotter(self, components=("xx",), reim="reim", broad=0.00005, emin=0, em emin, emax: minimum and maximum energy in which to obtain the spectra divs: number of frequency samples between emin and emax """ - directions_map = {"x": 0, "y": 1, "z": 2, 0: 0, 1: 1, 2: 2} reim_label = {"re": "Re", "im": "Im"} diff --git a/pymatgen/phonon/plotter.py b/pymatgen/phonon/plotter.py index 9691bf51700..da34e2be8f7 100644 --- a/pymatgen/phonon/plotter.py +++ b/pymatgen/phonon/plotter.py @@ -79,7 +79,6 @@ class PhononDosPlotter: def __init__(self, stack=False, sigma=None): """ - Args: stack: Whether to plot the DOS as a stacked area graph sigma: A float specifying a standard deviation for Gaussian smearing @@ -100,7 +99,6 @@ def add_dos(self, label, dos): dos: PhononDos object """ - densities = dos.get_smeared_densities(self.sigma) if self.sigma else dos.densities self._doses[label] = {"frequencies": dos.frequencies, "densities": densities} @@ -142,7 +140,6 @@ def get_plot(self, xlim=None, ylim=None, units="thz"): ylim: Specifies the y-axis limits. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. """ - u = freq_units(units) ncolors = max(3, len(self._doses)) @@ -343,7 +340,6 @@ def get_plot(self, ylim=None, units="thz"): the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. """ - u = freq_units(units) plt = pretty_plot(12, 8) @@ -444,7 +440,6 @@ def get_proj_plot( the code choose. units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. """ - from matplotlib.collections import LineCollection from pymatgen.electronic_structure.plotter import BSDOSPlotter @@ -618,7 +613,6 @@ def plot_compare(self, other_plotter, units="thz"): Returns: a matplotlib object with both band structures """ - u = freq_units(units) data_orig = self.bs_plot_data() @@ -644,7 +638,6 @@ def plot_brillouin(self): """ plot the Brillouin zone """ - # get labels and lines labels = {} for q in self._bs.qpoints: @@ -696,7 +689,6 @@ def _plot_thermo(self, func, temperatures, factor=1, ax=None, ylabel=None, label Returns: matplotlib figure """ - ax, fig, plt = get_ax_fig_plt(ax) values = [] @@ -886,7 +878,6 @@ def __init__(self, gruneisen): Args: gruneisen: GruneisenParameter Object """ - self._gruneisen = gruneisen def get_plot(self, marker="o", markersize=None, units="thz"): @@ -899,7 +890,6 @@ def get_plot(self, marker="o", markersize=None, units="thz"): Returns: plot """ - u = freq_units(units) xs = self._gruneisen.frequencies.flatten() * u.factor @@ -931,7 +921,6 @@ def show(self, units="thz"): Returns: plot """ - plt = self.get_plot(units=units) plt.show() @@ -945,7 +934,6 @@ def save_plot(self, filename, img_format="pdf", units="thz"): Returns: """ - plt = self.get_plot(units=units) plt.savefig(filename, format=img_format) plt.close() @@ -1013,7 +1001,6 @@ def get_plot_gs(self, ylim=None): ylim: Specify the y-axis (gruneisen) limits; by default None let the code choose. """ - plt = pretty_plot(12, 8) # band_linewidth = 1 @@ -1088,7 +1075,6 @@ def plot_compare_gs(self, other_plotter): Returns: a matplotlib object with both band structures """ - data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() diff --git a/pymatgen/symmetry/bandstructure.py b/pymatgen/symmetry/bandstructure.py index 7368e6e72af..f03d83f7264 100644 --- a/pymatgen/symmetry/bandstructure.py +++ b/pymatgen/symmetry/bandstructure.py @@ -81,7 +81,6 @@ def __init__( atol (float): Absolute tolerance used to determine symmetric equivalence of points and lines on the BZ. """ - super().__init__(structure, symprec=symprec, angle_tolerance=angle_tolerance, atol=atol) self._path_type = path_type @@ -190,7 +189,6 @@ def _get_lm_kpath(self, has_magmoms, magmom_axis, symprec, angle_tolerance, atol Returns: Latimer and Munro k-path with labels. """ - return KPathLatimerMunro(self._structure, has_magmoms, magmom_axis, symprec, angle_tolerance, atol) def _get_sc_kpath(self, symprec, angle_tolerance, atol): @@ -238,7 +236,6 @@ def _get_klabels(self, lm_bs, sc_bs, hin_bs, rpg): If an equivalent label can still not be found, or the point is not in the explicit kpath, its equivalent label will be set to itself in the output. """ - lm_path = lm_bs.kpath sc_path = sc_bs.kpath hin_path = hin_bs.kpath @@ -320,7 +317,6 @@ def get_continuous_path(bandstructure): Returns: bandstructure (BandstructureSymmLine): New BandstructureSymmLine object with continuous path. """ - G = nx.Graph() labels = [] diff --git a/pymatgen/symmetry/kpath.py b/pymatgen/symmetry/kpath.py index 4c3abee206a..c3095156b40 100644 --- a/pymatgen/symmetry/kpath.py +++ b/pymatgen/symmetry/kpath.py @@ -57,7 +57,6 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance= and determine symmetric equivalence of points and lines in the BZ. """ - self._structure = structure self._latt = self._structure.lattice self._rec_lattice = self._structure.lattice.reciprocal_lattice @@ -963,7 +962,6 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance= system_is_tri (boolean): Indicates if the system is time-reversal invariant. """ - super().__init__(structure, symprec=symprec, angle_tolerance=angle_tolerance, atol=atol) positions = structure.frac_coords @@ -2288,7 +2286,6 @@ def LabelPoints(index): """ Axes used in generating labels for Latimer-Munro convention """ - points = [ [1, 0, 0], [0, 1, 0], @@ -2325,7 +2322,6 @@ def LabelSymbol(index): """ Letters used in generating labels for the Latimer-Munro convention """ - symbols = [ "a", "b", diff --git a/pymatgen/symmetry/settings.py b/pymatgen/symmetry/settings.py index 05e687bf44b..8b37528f3ff 100644 --- a/pymatgen/symmetry/settings.py +++ b/pymatgen/symmetry/settings.py @@ -136,7 +136,6 @@ def P(self) -> list[list[float]]: @property def p(self) -> list[float]: """ - :return: translation vector """ return self._p @@ -144,7 +143,6 @@ def p(self) -> list[float]: @property def inverse(self) -> JonesFaithfulTransformation: """ - :return: JonesFaithfulTransformation """ Q = np.linalg.inv(self.P) diff --git a/pymatgen/transformations/advanced_transformations.py b/pymatgen/transformations/advanced_transformations.py index 992bc24a8af..840d94cba46 100644 --- a/pymatgen/transformations/advanced_transformations.py +++ b/pymatgen/transformations/advanced_transformations.py @@ -125,7 +125,6 @@ def __init__(self, transformations, nstructures_per_trans=1): nstructures_per_trans structures from each transformation are added to the full list. Defaults to 1, i.e., only best structure. """ - self._transformations = transformations self.nstructures_per_trans = nstructures_per_trans @@ -598,7 +597,6 @@ def __init__( :param site_constraints (list): list of values of the site property that the constraints should apply to """ - # validation if site_constraints and site_constraints != [None] and not site_constraint_name: raise ValueError("Specify the name of the site constraint.") @@ -665,7 +663,6 @@ def __init__(self, mag_species_spin, order_parameter=0.5, energy_model=None, **k :param kwargs: Additional kwargs that are passed to :class:`EnumerateStructureTransformation` such as min_cell_size etc. """ - # checking for sensible order_parameter values if isinstance(order_parameter, float): # convert to constraint format @@ -744,7 +741,6 @@ def _add_dummy_species(structure, order_parameters): This approach can also preserve site properties even after enumeration. """ - dummy_struct = structure.copy() def generate_dummy_specie(): @@ -1282,7 +1278,6 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): Returns: Transformed disordered structure(s) """ - if not structure.is_ordered: raise ValueError("This transformation is for disordered structures only.") @@ -1575,7 +1570,6 @@ def apply_transformation(self, structure: Structure) -> Structure: Returns: supercell: Transformed supercell. """ - lat_vecs = structure.lattice.matrix # boolean for if a sufficiently large supercell has been created @@ -1717,7 +1711,6 @@ def __init__( def apply_transformation(self, structure: Structure, return_ranked_list=False): """ - Args: structure: Must be a Slab structure return_ranked_list: Whether or not multiple structures are @@ -1726,7 +1719,6 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): Returns: Slab with adsorbate """ - sitefinder = AdsorbateSiteFinder( structure, selective_dynamics=self.selective_dynamics, @@ -1880,7 +1872,6 @@ def __init__( def apply_transformation(self, structure: Structure, return_ranked_list=False): """ - Args: structure: Must be a Slab structure return_ranked_list: Whether or not multiple structures are @@ -1889,7 +1880,6 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): Returns: Slab with sites substituted """ - sitefinder = AdsorbateSiteFinder( structure, selective_dynamics=self.selective_dynamics, @@ -2003,7 +1993,6 @@ def _get_max_neighbor_distance(struct, shell): Returns: maximum nearest neighbor distance, in angstroms """ - mdnn = MinimumDistanceNN() distances = [] @@ -2025,7 +2014,6 @@ def _get_disordered_substructure(struc_disordered): Returns: pymatgen Structure object representing a substructure of disordered sites """ - disordered_substructure = struc_disordered.copy() idx_to_remove = [] @@ -2046,7 +2034,6 @@ def _sqs_cluster_estimate(struc_disordered, cluster_size_and_shell: dict[int, in Returns: dict of {cluster size: distance in angstroms} for mcsqs calculation """ - cluster_size_and_shell = cluster_size_and_shell or {2: 3, 3: 2, 4: 1} disordered_substructure = SQSTransformation._get_disordered_substructure(struc_disordered) @@ -2067,7 +2054,6 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): Returns: pymatgen Structure which is an SQS of the input structure """ - if return_ranked_list and self.instances is None: raise ValueError("mcsqs has no instances, so cannot return a ranked list") if ( @@ -2121,7 +2107,6 @@ def _get_unique_bestsqs_strucs(sqs, best_only, return_ranked_list, remove_duplic list of dicts of the form {'structure': Structure, 'objective_function': ...}, unless run in serial (returns a single structure Sqs.bestsqs) """ - if not return_ranked_list: return_struc = sqs.bestsqs diff --git a/pymatgen/transformations/site_transformations.py b/pymatgen/transformations/site_transformations.py index 37a1d2b8081..e5ec26ac6be 100644 --- a/pymatgen/transformations/site_transformations.py +++ b/pymatgen/transformations/site_transformations.py @@ -150,7 +150,6 @@ def __init__(self, indices_to_remove): Args: indices_to_remove: List of indices to remove. E.g., [0, 1, 2] """ - self.indices_to_remove = indices_to_remove def apply_transformation(self, structure): diff --git a/pymatgen/transformations/standard_transformations.py b/pymatgen/transformations/standard_transformations.py index 19653dc1c91..7af233b379c 100644 --- a/pymatgen/transformations/standard_transformations.py +++ b/pymatgen/transformations/standard_transformations.py @@ -572,7 +572,6 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): be stored in the transformation_parameters dictionary in the transmuted structure class. """ - try: num_to_return = int(return_ranked_list) except ValueError: @@ -1082,7 +1081,6 @@ def apply_transformation(self, structure): structure (Structure): A structurally similar structure in regards to crystal and site positions. """ - if self.species_map is None: match = StructureMatcher() s_map = match.get_best_electronegativity_anonymous_mapping(self.unrelaxed_structure, structure) diff --git a/pymatgen/util/testing.py b/pymatgen/util/testing.py index 0d5a2983c00..9dec852c36b 100644 --- a/pymatgen/util/testing.py +++ b/pymatgen/util/testing.py @@ -85,7 +85,6 @@ def assertDictsAlmostEqual(actual, desired, decimal=7, err_msg="", verbose=True) Tests if two arrays are almost equal to a tolerance. The CamelCase naming is so that it is consistent with standard unittest methods. """ - for k, v in actual.items(): if k not in desired: return False diff --git a/pymatgen/vis/plotters.py b/pymatgen/vis/plotters.py index 43a17c56345..e43aea7d1e6 100644 --- a/pymatgen/vis/plotters.py +++ b/pymatgen/vis/plotters.py @@ -92,7 +92,6 @@ def get_plot(self, xlim=None, ylim=None): determination. ylim: Specifies the y-axis limits. """ - plt = pretty_plot(12, 8) base = 0.0 i = 0