Skip to content

Commit

Permalink
Delete variable self assignments (#3196)
Browse files Browse the repository at this point in the history
* delete self-assignments

pymatgen/io/lobster/outputs.py simplify if cond: x = True else x = False to x = cond

* del unused w_area_has_intersection_smoothstep

strictly speaking breaking but wasn't actually doing anything except call w_area_intersection_specific so recommended fix is to just use that
  • Loading branch information
janosh authored Jul 31, 2023
1 parent f1ac4aa commit d35e1ec
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 82 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.279
rev: v0.0.281
hooks:
- id: ruff
args: [--fix]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2024,7 +2024,6 @@ def __init__(
self.area_weight = self.w_area_has_intersection
elif weight_type == "has_intersection_smoothstep":
raise NotImplementedError
# self.area_weight = self.w_area_has_intersection_smoothstep
else:
raise ValueError(f'Weight type is {weight_type!r} while it should be "has_intersection"')
self.surface_definition = surface_definition
Expand Down Expand Up @@ -2064,28 +2063,6 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No
additional_info=additional_info,
)

def w_area_has_intersection_smoothstep(self, nb_set, structure_environments, cn_map, additional_info):
"""Get intersection of the neighbors set area with the surface.
:param nb_set: Neighbors set.
:param structure_environments: Structure environments.
:param cn_map: Mapping index of the neighbors set.
:param additional_info: Additional information.
:return: Area intersection between neighbors set and surface.
"""
w_area = self.w_area_intersection_specific(
nb_set=nb_set,
structure_environments=structure_environments,
cn_map=cn_map,
additional_info=additional_info,
)
if w_area > 0:
if self.smoothstep_distance is not None:
w_area = w_area
if self.smoothstep_angle is not None:
w_area = w_area
return w_area

def w_area_has_intersection(self, nb_set, structure_environments, cn_map, additional_info):
"""Get intersection of the neighbors set area with the surface.
Expand Down
1 change: 0 additions & 1 deletion pymatgen/analysis/wulff.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,6 @@ def get_plot(
ax.set_zlim([-r_range * 1.1, r_range * 1.1]) # pylint: disable=E1101
# add legend
if legend_on:
color_proxy = color_proxy
if show_area:
ax.legend(
color_proxy,
Expand Down
19 changes: 8 additions & 11 deletions pymatgen/apps/battery/conversion_battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ def from_composition_and_pd(cls, comp, pd, working_ion_symbol="Li", allow_unstab
profile.reverse()
if len(profile) < 2:
return None
working_ion_entry = working_ion_entry
working_ion = working_ion_entry.composition.elements[0].symbol
normalization_els = {}
for el, amt in comp.items():
Expand All @@ -83,7 +82,7 @@ def from_composition_and_pd(cls, comp, pd, working_ion_symbol="Li", allow_unstab
framework.pop(working_ion)
framework = Composition(framework)

vpairs = [
v_pairs = [
ConversionVoltagePair.from_steps(
profile[i],
profile[i + 1],
Expand All @@ -94,7 +93,7 @@ def from_composition_and_pd(cls, comp, pd, working_ion_symbol="Li", allow_unstab
]

return ConversionElectrode( # pylint: disable=E1123
voltage_pairs=vpairs,
voltage_pairs=v_pairs,
working_ion_entry=working_ion_entry,
initial_comp_formula=comp.reduced_formula,
framework_formula=framework.reduced_formula,
Expand Down Expand Up @@ -338,26 +337,24 @@ def from_steps(cls, step1, step2, normalization_els, framework_formula):
sum(curr_rxn.all_comp[i].weight * abs(curr_rxn.coeffs[i]) for i in range(len(curr_rxn.all_comp))) / 2
)
mass_charge = prev_mass_dischg
mass_discharge = mass_discharge
vol_discharge = sum(
abs(curr_rxn.get_coeff(e.composition)) * e.structure.volume
for e in step2["entries"]
if e.composition.reduced_formula != working_ion
)

totalcomp = Composition({})
total_comp = Composition({})
for comp in prev_rxn.products:
if comp.reduced_formula != working_ion:
totalcomp += comp * abs(prev_rxn.get_coeff(comp))
frac_charge = totalcomp.get_atomic_fraction(Element(working_ion))
total_comp += comp * abs(prev_rxn.get_coeff(comp))
frac_charge = total_comp.get_atomic_fraction(Element(working_ion))

totalcomp = Composition({})
total_comp = Composition({})
for comp in curr_rxn.products:
if comp.reduced_formula != working_ion:
totalcomp += comp * abs(curr_rxn.get_coeff(comp))
frac_discharge = totalcomp.get_atomic_fraction(Element(working_ion))
total_comp += comp * abs(curr_rxn.get_coeff(comp))
frac_discharge = total_comp.get_atomic_fraction(Element(working_ion))

rxn = rxn
entries_charge = step1["entries"]
entries_discharge = step2["entries"]

Expand Down
1 change: 0 additions & 1 deletion pymatgen/command_line/tests/test_gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ def test_run(self):
gin += "buck\n"
gin += "Mg core O shel 946.627 0.31813 0.00000 0.0 10.0\n"
gin += "O shel O shel 22764.000 0.14900 27.87900 0.0 12.0\n"
gin = gin
gc = GulpCaller()

"""Some inherent checks are in the run_gulp function itself.
Expand Down
3 changes: 0 additions & 3 deletions pymatgen/io/abinit/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,9 +1087,6 @@ def __init__(self, structure: Structure, pseudos, pseudo_dir="", ndtset=1):
if isinstance(pseudos, Pseudo):
pseudos = [pseudos]

elif isinstance(pseudos, PseudoTable):
pseudos = pseudos

elif all(isinstance(p, Pseudo) for p in pseudos):
pseudos = PseudoTable(pseudos)

Expand Down
2 changes: 0 additions & 2 deletions pymatgen/io/lobster/lobsterenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -1279,9 +1279,7 @@ def from_Lobster(
Returns: LobsterLightStructureEnvironments
"""
strategy = None
valences = valences
valences_origin = "user-defined"
structure = structure

coordination_environments = []

Expand Down
49 changes: 18 additions & 31 deletions pymatgen/io/lobster/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,8 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s
# Subtract 1 to skip the average
num_bonds = int(parameters[0]) - 1
self.efermi = float(parameters[-1])
if int(parameters[1]) == 2:
spins = [Spin.up, Spin.down]
self.is_spin_polarized = True
else:
spins = [Spin.up]
self.is_spin_polarized = False
self.is_spin_polarized = int(parameters[1]) == 2
spins = [Spin.up, Spin.down] if int(parameters[1]) == 2 else [Spin.up]

# The COHP data start in row num_bonds + 3
data = np.array([np.array(row.split(), dtype=float) for row in contents[num_bonds + 3 :]]).transpose()
Expand All @@ -135,22 +131,22 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s

orb_cohp: dict[str, Any] = {}
# present for Lobster versions older than Lobster 2.2.0
veryold = False
very_old = False
# the labeling had to be changed: there are more than one COHP for each atom combination
# this is done to make the labeling consistent with ICOHPLIST.lobster
bondnumber = 0
bond_num = 0
for bond in range(num_bonds):
bond_data = self._get_bond_data(contents[3 + bond])

label = str(bondnumber)
label = str(bond_num)

orbs = bond_data["orbitals"]
cohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 3] for s, spin in enumerate(spins)}

icohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 4] for s, spin in enumerate(spins)}
if orbs is None:
bondnumber = bondnumber + 1
label = str(bondnumber)
bond_num = bond_num + 1
label = str(bond_num)
cohp_data[label] = {
"COHP": cohp,
"ICOHP": icohp,
Expand All @@ -172,11 +168,11 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s
)
else:
# present for Lobster versions older than Lobster 2.2.0
if bondnumber == 0:
veryold = True
if veryold:
bondnumber += 1
label = str(bondnumber)
if bond_num == 0:
very_old = True
if very_old:
bond_num += 1
label = str(bond_num)

orb_cohp[label] = {
bond_data["orb_label"]: {
Expand All @@ -189,7 +185,7 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s
}

# present for lobster older than 2.2.0
if veryold:
if very_old:
for bond_str in orb_cohp:
cohp_data[bond_str] = {
"COHP": None,
Expand Down Expand Up @@ -302,18 +298,12 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s

# If the calculation is spin polarized, the line in the middle
# of the file will be another header line.
if "distance" in data[len(data) // 2]:
# TODO: adapt this for orbitalwise stuff
self.is_spin_polarized = True
else:
self.is_spin_polarized = False
# TODO: adapt this for orbitalwise stuff
self.is_spin_polarized = "distance" in data[len(data) // 2]

# check if orbitalwise ICOHPLIST
# include case when there is only one ICOHP!!!
if len(data) > 2 and "_" in data[1].split()[1]:
self.orbitalwise = True
else:
self.orbitalwise = False
self.orbitalwise = len(data) > 2 and "_" in data[1].split()[1]

if self.orbitalwise:
data_without_orbitals = []
Expand Down Expand Up @@ -364,7 +354,7 @@ def __init__(self, are_coops: bool = False, are_cobis: bool = False, filename: s
length = float(line[3])
translation = [int(line[4]), int(line[5]), int(line[6])]
icohp[Spin.up] = float(line[7])
num = int(1)
num = 1

if self.is_spin_polarized:
icohp[Spin.down] = float(data_without_orbitals[bond + num_bonds + 1].split()[7])
Expand Down Expand Up @@ -1141,10 +1131,7 @@ def __init__(self, filenames=".", vasprun="vasprun.xml", Kpointsfile="KPOINTS"):
linenumbers.append(iline)

if ifilename == 0:
if len(linenumbers) == 2:
self.is_spinpolarized = True
else:
self.is_spinpolarized = False
self.is_spinpolarized = len(linenumbers) == 2

if ifilename == 0:
eigenvals = {}
Expand Down
12 changes: 5 additions & 7 deletions pymatgen/io/nwchem.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,25 +261,23 @@ def from_molecule(
example, to perform cosmo calculations with DFT, you'd supply
{'cosmo': "cosmo"}.
"""
title = title if title is not None else "{} {} {}".format(re.sub(r"\s", "", mol.formula), theory, operation)
formula = re.sub(r"\s", "", mol.formula)
title = title if title is not None else f"{formula} {theory} {operation}"

charge = charge if charge is not None else mol.charge
nelectrons = -charge + mol.charge + mol.nelectrons # pylint: disable=E1130
n_electrons = -charge + mol.charge + mol.nelectrons # pylint: disable=E1130
if spin_multiplicity is not None:
spin_multiplicity = spin_multiplicity
if (nelectrons + spin_multiplicity) % 2 != 1:
if (n_electrons + spin_multiplicity) % 2 != 1:
raise ValueError(f"{charge=} and {spin_multiplicity=} is not possible for this molecule")
elif charge == mol.charge:
spin_multiplicity = mol.spin_multiplicity
else:
spin_multiplicity = 1 if nelectrons % 2 == 0 else 2
spin_multiplicity = 1 if n_electrons % 2 == 0 else 2

elements = set(mol.composition.get_el_amt_dict())
if isinstance(basis_set, str):
basis_set = {el: basis_set for el in elements}

basis_set_option = basis_set_option

return NwTask(
charge,
spin_multiplicity,
Expand Down
2 changes: 0 additions & 2 deletions pymatgen/io/xtb/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ def constrains_template(molecule, reference_fnm, constraints) -> str:
"""
atoms_to_constrain = constraints["atoms"]
force_constant = constraints["force_constant"]
reference_fnm = reference_fnm
mol = molecule
atoms_for_mtd = [idx for idx in range(1, len(mol) + 1) if idx not in atoms_to_constrain]
# Write as 1-3,5 instead of 1,2,3,5
Expand All @@ -91,7 +90,6 @@ def constrains_template(molecule, reference_fnm, constraints) -> str:
interval_list.append(v)
if i != len(atoms_for_mtd) - 1:
interval_list.append(atoms_for_mtd[i + 1])
force_constant = force_constant
allowed_mtd_string = ",".join(
[f"{interval_list[i]}-{interval_list[i + 1]}" for i in range(len(interval_list)) if i % 2 == 0]
)
Expand Down

0 comments on commit d35e1ec

Please sign in to comment.