From eb51ea025c97350d1122cea3483901ddc2ebe92a Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Thu, 16 Nov 2023 01:43:44 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- tests/io/orca/singles/test_sp.py | 21 --------------- tests/io/orca/test_io.py | 7 ----- wailord/_utils.py | 11 ++++---- wailord/exp/cookies.py | 6 +---- wailord/io/inp.py | 42 +++++++---------------------- wailord/io/orca.py | 46 +++++++++++++++----------------- 6 files changed, 37 insertions(+), 96 deletions(-) diff --git a/tests/io/orca/singles/test_sp.py b/tests/io/orca/singles/test_sp.py index 1dc026b..8957c22 100644 --- a/tests/io/orca/singles/test_sp.py +++ b/tests/io/orca/singles/test_sp.py @@ -22,7 +22,6 @@ def test_orca_get_sp_e(datadir): sEnerg = waio.orca.orcaVis(ofile=datadir / "orca_qcisdt.out") np.testing.assert_almost_equal(sEnerg.fin_sp_e.m, -1.01010039) - pass def test_orca_runinfo(datadir): @@ -35,7 +34,6 @@ def test_orca_runinfo(datadir): "theory": "QCISD", "slug": "H2_test", } - pass ########################## @@ -47,14 +45,12 @@ def test_orca_mdci_e_bounds(datadir): sEnerg = waio.orca.orcaVis(ofile=datadir / "orca_qcisdt.out") with pytest.raises(ValueError): sEnerg.single_energy_surface(npoints=34) - pass def test_orca_energ_error(datadir): sEnerg = waio.orca.orcaVis(ofile=datadir / "orca_qcisdt.out") with pytest.raises(NotImplementedError): sEnerg.single_energy_surface(etype="Squid") - pass def test_orca_energ_empty(datadir): @@ -64,7 +60,6 @@ def test_orca_energ_empty(datadir): sEnerg.single_energy_surface("MDCI", 33) with pytest.raises(ValueError): sEnerg.single_energy_surface("MDCI w/o Triples") - pass def test_orca_mdci_e_xvals(datadir): @@ -76,7 +71,6 @@ def test_orca_mdci_e_xvals(datadir): blength, np.linspace(0.4, 2, 33), ) - pass def test_orca_mdci_e_yvals(datadir): @@ -125,7 +119,6 @@ def test_orca_mdci_e_yvals(datadir): energy, exp_e, ) - pass def test_orca_mdci_e_mtrip_xvals(datadir): @@ -137,7 +130,6 @@ def test_orca_mdci_e_mtrip_xvals(datadir): blength, np.linspace(0.4, 2, 33), ) - pass def test_orca_mdci_e_mtrip_energy_evals(datadir): @@ -146,7 +138,6 @@ def test_orca_mdci_e_mtrip_energy_evals(datadir): eDat = sEnerg.single_energy_surface(npoints=33) eDat1 = sEnerg.single_energy_surface() pd.testing.assert_frame_equal(eDat, eDat1) - pass def test_orca_mdci_e_mtrip_yvals(datadir): @@ -195,7 +186,6 @@ def test_orca_mdci_e_mtrip_yvals(datadir): energy, exp_e, ) - pass ############################ @@ -211,7 +201,6 @@ def test_mult_energy_surf(datadir): pd.testing.assert_frame_equal(eDat, eDatAll[["bond_length", "MDCI w/o Triples"]]) pd.testing.assert_frame_equal(eDatMDCI, eDatAll[["bond_length", "MDCI"]]) assert len(eDatAll) == len(eDat) - pass def test_mult_energy_surf_subset(datadir): @@ -220,7 +209,6 @@ def test_mult_energy_surf_subset(datadir): assert "Actual Energy" not in eDatAll.columns assert "MDCI" in eDatAll.columns assert "SCF Energy" in eDatAll.columns - pass def test_mult_energy_surf_single(datadir): @@ -230,7 +218,6 @@ def test_mult_energy_surf_single(datadir): pd.testing.assert_frame_equal(eDatMDCI, eDatSingleL.loc[:, ["bond_length", "MDCI"]]) eDatSingle = sEnerg.mult_energy_surface(etype="MDCI") pd.testing.assert_frame_equal(eDatMDCI, eDatSingle.loc[:, ["bond_length", "MDCI"]]) - pass ############################## @@ -246,7 +233,6 @@ def test_orca_single_chargepop(datadir): sdat2 = spop.single_population_analysis("Loewdin") assert sdat2.shape == (4, 5) np.testing.assert_equal(sdat2.pcharge.to_numpy(), np.zeros(4)) - pass def test_orca_single_fullpop(datadir): @@ -258,7 +244,6 @@ def test_orca_single_fullpop(datadir): sdat2 = spop.single_population_analysis("Loewdin") assert sdat2.shape == (2, 6) np.testing.assert_equal(sdat2.pcharge.to_numpy(), np.zeros(2)) - pass def test_orca_nstep_pop(datadir): @@ -268,7 +253,6 @@ def test_orca_nstep_pop(datadir): assert (popdat >> si.filter(_.step == 1)).shape == ( popdat >> si.filter(_.step == 2) ).shape - pass ################################ @@ -281,7 +265,6 @@ def test_orca_mult_chargepop(datadir): sdat = spop.mult_population_analysis() assert sdat.shape == (8, 10) np.testing.assert_equal(sdat.pcharge.to_numpy(), np.zeros(8)) - pass def test_orca_mult_fullpop(datadir): @@ -290,7 +273,6 @@ def test_orca_mult_fullpop(datadir): assert sdat.shape == (4, 11) np.testing.assert_equal(sdat.pcharge.to_numpy(), np.zeros(4)) np.testing.assert_equal(sdat.pspin.to_numpy(), np.zeros(4)) - pass ############### @@ -308,7 +290,6 @@ def test_orca_irspec(datadir): sdat.freq.pint.m.to_numpy(), np.array([1639.47, 3807.28, 3903.73]) ) np.testing.assert_equal(sdat.Mode.to_numpy(), np.array([6, 7, 8])) - pass ###################### @@ -326,7 +307,6 @@ def test_orca_vpt2(datadir): sdat.harmonic_freq.pint.m.to_numpy(), np.array([1638.78, 3808.09, 3904.51]) ) np.testing.assert_equal(sdat.Mode.to_numpy(), np.array([1, 2, 3])) - pass ######################### @@ -360,4 +340,3 @@ def test_calc_htst(datadir): assert kf.u == "1/second" np.testing.assert_almost_equal(kf.m, 2.80583587e-07) np.testing.assert_almost_equal(kb.m, 3.31522447e-29) - pass diff --git a/tests/io/orca/test_io.py b/tests/io/orca/test_io.py index 520771f..57e1d90 100644 --- a/tests/io/orca/test_io.py +++ b/tests/io/orca/test_io.py @@ -92,7 +92,6 @@ def test_get_final_sp_energy(datadir): dtype=object, ), ) - pass ############################## @@ -121,7 +120,6 @@ def test_get_energy_surface_shape(datadir): assert len(edat[edat.isin(["3-21G"]).any(axis=1)]) == 3 * 33 #: 3 levels of theory assert len(edat[edat.isin(["UHF"]).any(axis=1)]) == 9 * 33 #: 9 basis sets assert edat.shape == (891, 8) #: Rows = basis (9) * theory (3) * npoints (33) - pass @pytest.mark.filterwarnings("ignore::UserWarning") @@ -129,7 +127,6 @@ def test_get_energy_surface_empty(datadir): expt = waio.orca.orcaExp(expfolder=datadir / "h2") with pytest.raises(ValueError): expt.get_energy_surface(etype=["MDCI", "Actual Energy"]) - pass def test_get_energy_surface_shape_more(datadir): @@ -159,7 +156,6 @@ def test_get_energy_surface_shape_more(datadir): edat.theory.value_counts().to_numpy(), np.repeat(33, 5), ) - pass ####################### @@ -193,7 +189,6 @@ def test_get_pop(datadir): popdat.theory.value_counts().to_numpy(), np.array([60, 50, 40]), ) - pass ############### @@ -207,7 +202,6 @@ def test_get_ir_freq(datadir): vdat = expt.get_ir_spec() assert vdat.shape == (63, 11) assert (vdat >> si.filter(_.slug == "O1H2_h2o")).shape == (9, 11) - pass ###################### @@ -220,4 +214,3 @@ def test_vpt2_transitions(datadir): expt = waio.orca.orcaExp(expfolder=datadir / "vpt2_h2o", order_theory=oth) vdat = expt.get_vpt2_transitions() assert vdat.shape == (9, 9) - pass diff --git a/wailord/_utils.py b/wailord/_utils.py index dc1a3c6..01dbb2b 100644 --- a/wailord/_utils.py +++ b/wailord/_utils.py @@ -38,13 +38,12 @@ def __init__(self, *args, **kwargs): self[key] = DotDict(self[key]) def __getitem__(self, key): - if isinstance(key, str): - try: - return super().__getitem__(key) - except KeyError: - raise MissingVariableError(f"No such variable '{key}' exists") from None - else: + if not isinstance(key, str): raise TypeError("Key must be a string") + try: + return super().__getitem__(key) + except KeyError: + raise MissingVariableError(f"No such variable '{key}' exists") from None def __setitem__(self, key, value): if isinstance(value, dict) and not isinstance(value, DotDict): diff --git a/wailord/exp/cookies.py b/wailord/exp/cookies.py index e606a4d..e0ed95b 100644 --- a/wailord/exp/cookies.py +++ b/wailord/exp/cookies.py @@ -12,11 +12,7 @@ def gen_base(filen=None, /, template="basicExperiment", *, absolute=False): """Generate a base template""" - if absolute: - template = str(template) - else: - template = str(TEMPLATE_DIR / template) - + template = str(template) if absolute else str(TEMPLATE_DIR / template) if filen is not None: with open(filen, "r") as ymlfile: config = yaml.safe_load(ymlfile) diff --git a/wailord/io/inp.py b/wailord/io/inp.py index 76aa671..db80bae 100644 --- a/wailord/io/inp.py +++ b/wailord/io/inp.py @@ -93,8 +93,7 @@ def read_yml(self): def parse_geom(self, geom): """Rework the geometry into output""" - textlines = [] - textlines.append("\n%geom") + textlines = ["\n%geom"] if "scan" in geom: textlines.append(f"\n Scan\n") for scanthing in geom.scan.keys(): @@ -106,7 +105,7 @@ def parse_geom(self, geom): raise TypeError( f"Only dihedral, bond and angle scan types are supported, got {scanthing} instead" ) - textlines.append(f" end") + textlines.append(" end") if "constrain" in geom: textlines.append(f"\n Constraints\n") for consthing in geom.constrain.keys(): @@ -120,7 +119,7 @@ def parse_geom(self, geom): raise TypeError( f"Only dihedral, bond, angle, and cartesian constraints are supported, got {consthing} instead" ) - textlines.append(f" end") + textlines.append(" end") if "maxiter" in geom: string = f""" maxiter {geom.maxiter} @@ -135,10 +134,7 @@ def geom_constrain(self, cons, constype): constype = constype[0][0].upper() for constraint in cons: btwn = constraint["between"] - if "value" in constraint.keys(): - value = float(constraint["value"]) - else: - value = "" + value = float(constraint["value"]) if "value" in constraint.keys() else "" if constype != "C": btwn_num = btwn.split(" ") # TODO Handle the other types as tuples (B,2) @@ -150,9 +146,7 @@ def geom_constrain(self, cons, constype): ) # if constype == 'B' and len(btwn_num) == 2: else: - warnings.warn( - f"Cartesian comments have not been implemented", UserWarning - ) + warnings.warn("Cartesian comments have not been implemented", UserWarning) comment = "" linesthing.append(f" {{ {constype} {btwn} {value} C }} # {comment}\n") return "".join(linesthing) @@ -232,7 +226,6 @@ def parse_xyz(self): if "blocks" in self.config.keys(): self.blocks = self.parse_blocks(self.config.blocks) self.gendir_qc(extra=None) - pass def parse_blocks(self, blocks): """Generic Block Handler @@ -268,9 +261,7 @@ def parse_blocks(self, blocks): return "".join(blines) def parse_keywords(self, keywords): - keylines = [] - for kl in keywords: - keylines.append(f"\n! {kl}") + keylines = [f"\n! {kl}" for kl in keywords] return "".join(keylines) def parse_yml(self): @@ -281,7 +272,6 @@ def parse_yml(self): self.parse_xyz() if self.qc.active is True: self.parse_qc() - pass def parse_viz(self, viz): if viz.chemcraft is True: @@ -296,8 +286,7 @@ def parse_viz(self, viz): return textwrap.dedent(string) def parse_scf(self, scf): - textlines = [] - textlines.append("\n%scf\n") + textlines = ["\n%scf\n"] if "brokensym" in scf: textlines.append( f" BrokenSym {scf.brokensym.more_unpaired}, {scf.brokensym.less_unpaired}" @@ -314,8 +303,7 @@ def parse_params(self, params): """Rework the parameters into output. Recall that these do not require relaxation, and can also take fixed variables. On the other hand, these need more information to set up.""" - textlines = [] - textlines.append("%paras\n") + textlines = ["%paras\n"] for param in params: if param.get("value"): param["slot"]["name"] = param["name"] @@ -326,14 +314,12 @@ def parse_params(self, params): self.xyzlines[-1], comment = self.params_slot(param["slot"]) textlines.append(self.params_range(param, comment)) else: - raise TypeError( - f"Currently only value and range variables are supported" - ) + raise TypeError("Currently only value and range variables are supported") textlines.append("end\n") return "".join(textlines) def params_slot(self, thing): - if not "xyz" in thing or thing["xyz"] is not True: + if "xyz" not in thing or thing["xyz"] is not True: raise TypeError("Currently only supports xyz") atype, anum, axis, name = itemgetter("atype", "anum", "axis", "name")(thing) xyztmp = self.xyzlines[-1].split("\n") @@ -393,7 +379,6 @@ def parse_qc(self): itertt.chain(self.qc.style, self.qc.calculations, self.qc.basis_sets) ) self.qcopts = qcList - pass def gendir_qc(self, basename=None, extra=None): """Function to generate QC folder structure recursively""" @@ -406,20 +391,17 @@ def gendir_qc(self, basename=None, extra=None): styl = styl.replace(" ", "_") self.gendir_qcspin(basename / styl) self.genharness(basename) - pass def gendir_qcspin(self, path): """Generates the style folders""" for sp in self.spin: sp = sp.replace(" ", "") self.gendir_qccalc(path / Path(f"spin_{sp}")) - pass def gendir_qccalc(self, path): """Generates set of calculation folders""" for cal in self.config.qc.calculations: self.gendir_qcbasis(path / cal) - pass def gendir_qcbasis(self, path): """Generates the directory of input files. Note that the folders will have + @@ -428,7 +410,6 @@ def gendir_qcbasis(self, path): bas = base.replace("+", "P").replace("*", "8") Path.mkdir(path / bas, parents=True, exist_ok=True) self.geninp(path / bas) - pass def geninp(self, path): """Uses the path to generate details for an input file""" @@ -453,7 +434,6 @@ def geninp(self, path): from_loc=self.conf_path.parent / self.config.jobscript, slug=f"{tmpconf['basis']}_{tmpconf['style']}", ) - pass def putscript(self, from_loc, to_loc, slug): """Copies the jobscript""" @@ -473,7 +453,6 @@ def putscript(self, from_loc, to_loc, slug): $orcadir/orca_2mkl orca -molden""" script.writelines(textwrap.dedent(string)) self.scripts.append(scriptname) - pass def writeinp(self, confobj, extralines=None): """Writes an input file. Minimally should have: @@ -511,7 +490,6 @@ def writeinp(self, confobj, extralines=None): op.write("\n") op.write(self.xyzlines[-1]) op.write("*") - pass class simpleInput: diff --git a/wailord/io/orca.py b/wailord/io/orca.py index 347b0ac..c936b73 100644 --- a/wailord/io/orca.py +++ b/wailord/io/orca.py @@ -133,9 +133,7 @@ def parseOut(filename, plotter=False): spin = "triplet" else: raise (NotImplementedError(f"Not yet implemented {runinfo['spin']}")) - finGeom = [] - for i in reversed(range(1, num_species + 1)): - finGeom.append(allAtoms[-i]) + finGeom = [allAtoms[-i] for i in reversed(range(1, num_species + 1))] # Creates a dictionary of the system H num O num systr = pd.DataFrame(finGeom).atype.value_counts().to_dict() # Flattens the dictionary to a list @@ -151,10 +149,7 @@ def parseOut(filename, plotter=False): spin=spin, theory=runinfo["theory"], ) - if plotter == True: - return oout, energ - else: - return oout + return (oout, energ) if plotter == True else oout def get_e(orcaoutdat, basis, system): @@ -207,9 +202,11 @@ def genEBASet( geometries. Depreciate this eventually.""" outs = [] for root, dirs, files in os.walk(rootdir.resolve()): - for filename in files: - if "out" in filename and "slurm" not in filename: - outs.append(parseOut(f"{root}/{filename}")) + outs.extend( + parseOut(f"{root}/{filename}") + for filename in files + if "out" in filename and "slurm" not in filename + ) outdat = pd.DataFrame(data=outs) basis_type = CategoricalDtype(categories=order_basis, ordered=True) theory_type = CategoricalDtype(categories=order_theory, ordered=True) @@ -368,9 +365,11 @@ def handle_exp(self, efol): with orca_config_path.open(mode="r") as ymlfile: self.inpconf = yaml.safe_load(ymlfile) for root, dirs, files in os.walk(efol.resolve()): - for filename in files: - if "out" in filename and "slurm" not in filename: - fnames.append(Path(f"{root}/{filename}")) + fnames.extend( + Path(f"{root}/{filename}") + for filename in files + if "out" in filename and "slurm" not in filename + ) self.orclist = fnames return @@ -599,7 +598,6 @@ def get_final_e(self, dat=False): raise ( ValueError(f"Final single point energy not found for {self.ofile}") ) - pass def final_sp_e(self): erow = self.runinfo @@ -677,7 +675,7 @@ def single_energy_surface(self, etype="Actual Energy", npoints=None): """ if etype not in OUT_REGEX: raise (NotImplementedError(f"{etype} has not been implemented yet")) - if npoints == None: + if npoints is None: npoints = self.eeval xaxis = [] yaxis = [] @@ -727,7 +725,7 @@ def vib_freq(self): imaginary=True, ) accumulate.append(v) - i = i + 1 + i += 1 vdat = pd.DataFrame(accumulate) vdat["freq"] = vdat["freq"].astype("pint[cm_1]") # TODO: Add experiment layer @@ -772,7 +770,7 @@ def vpt2_transitions(self): freq_diff=float(raw[3]), ) accumulate.append(v) - i = i + 1 + i += 1 vdat = pd.DataFrame(accumulate) vdat["harmonic_freq"] = vdat["harmonic_freq"].astype("pint[cm_1]") vdat["vpt2_freq"] = vdat["vpt2_freq"].astype("pint[cm_1]") @@ -783,9 +781,8 @@ def vpt2_transitions(self): f"Data not found for {self.runinfo['theory']}, did you run VPT2?" ) ) - else: - for key in self.runinfo.keys(): - vdat[key] = self.runinfo[key] + for key in self.runinfo.keys(): + vdat[key] = self.runinfo[key] return vdat def ir_spec(self): @@ -812,7 +809,7 @@ def ir_spec(self): TZ=float(raw[5].replace(")", "")), ) accumulate.append(v) - i = i + 1 + i += 1 vdat = pd.DataFrame(accumulate) vdat["T2"] = vdat["T2"].astype("pint[km/mol]") vdat["freq"] = vdat["freq"].astype("pint[cm_1]") @@ -822,9 +819,8 @@ def ir_spec(self): f"Spectra not found for {self.runinfo['theory']}, did you run FREQ?" ) ) - else: - for key in self.runinfo.keys(): - vdat[key] = self.runinfo[key] + for key in self.runinfo.keys(): + vdat[key] = self.runinfo[key] return vdat def single_population_analysis(self, poptype="Mulliken", /): @@ -869,7 +865,7 @@ def single_population_analysis(self, poptype="Mulliken", /): pcharge=float(raw[-1]), ) accumulate.append(c) - i = i + 1 + i += 1 popdat = pd.DataFrame(accumulate) step = popdat.anum.count() / popdat.anum.nunique() popdat["step"] = np.asarray(