Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff clean up #502

Merged
merged 15 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions overreact/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#!/usr/bin/env python3 # noqa: EXE001
""".. include:: ../README.md""" # noqa: D400

from __future__ import annotations

"""
.. include:: ../README.md
""" # noqa: D200, D400
__docformat__ = "restructuredtext"

import pkg_resources as _pkg_resources
Expand Down Expand Up @@ -52,7 +51,7 @@
__version__ = _pkg_resources.get_distribution(__name__).version
__license__ = "MIT" # I'm too lazy to get it from setup.py...

__headline__ = "📈 Create and analyze chemical microkinetic models built from computational chemistry data." # noqa: E501
__headline__ = "📈 Create and analyze chemical microkinetic models built from computational chemistry data."

__url_repo__ = "https://github.com/geem-lab/overreact"
__url_issues__ = f"{__url_repo__}/issues"
Expand All @@ -62,7 +61,7 @@

__doi__ = "10.1002/jcc.26861"
__zenodo_doi__ = "10.5281/zenodo.7865357"
__citations__ = ( # TODO: read from CITATION.bib
__citations__ = ( # TODO(schneiderfelipe): read from CITATION.bib
r"""
@article{overreact_paper2022,
title = {Overreact, an in silico lab: Automative quantum chemical microkinetic simulations for complex chemical reactions},
Expand All @@ -89,7 +88,7 @@
version = {vVERSION_PLACEHOLDER},
howpublished = {\url{URL_REPO_PLACEHOLDER}},
}
""".replace( # noqa: E501
""".replace(
"ZENODO_DOI_PLACEHOLDER",
__zenodo_doi__,
)
Expand Down
95 changes: 36 additions & 59 deletions overreact/_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python3 # noqa: EXE001

"""Command-line interface."""


Expand Down Expand Up @@ -132,8 +130,8 @@
────────────────────────────────────────────────────────────────────────────────
"""

def __init__( # noqa: PLR0913
self, # noqa: ANN101
def __init__(
self,
model,
concentrations=None,
savepath=None,
Expand Down Expand Up @@ -173,7 +171,7 @@
self.atol = atol
self.box_style = box_style

def __rich_console__(self, console, options): # noqa: ANN101, ANN204
def __rich_console__(self, console, options):
"""
Implement Rich Console protocol.

Expand All @@ -190,7 +188,7 @@
yield from self._yield_kinetics()
yield Markdown("---")

def _yield_scheme(self): # noqa: ANN101
def _yield_scheme(self):
"""Produce a renderables describing the reaction scheme.

This is meant to be used from within `__rich_console__`.
Expand All @@ -199,7 +197,7 @@
------
renderable
"""
scheme = rx.core._check_scheme(self.model.scheme) # noqa: SLF001
scheme = rx.core._check_scheme(self.model.scheme)

raw_table = Table(
title="(read) reactions",
Expand Down Expand Up @@ -236,7 +234,7 @@
parsed_table.add_row(*row)
yield parsed_table

def _yield_compounds(self): # noqa: ANN101
def _yield_compounds(self):
"""Produce a renderables describing the compounds.

This is meant to be used from within `__rich_console__`.
Expand All @@ -250,14 +248,12 @@
ValueError
If at least one compound has undefined data.
"""
undefined_compounds = []
for name in self.model.compounds:
if not self.model.compounds[name]:
undefined_compounds.append(name)
undefined_compounds = [
name for name in self.model.compounds if not self.model.compounds[name]
]
if undefined_compounds:
raise ValueError( # noqa: TRY003
f"undefined compounds: {', '.join(undefined_compounds)}", # noqa: EM102
) # noqa: RUF100
msg = f"undefined compounds: {', '.join(undefined_compounds)}"
raise ValueError(msg)

Check warning on line 256 in overreact/_cli.py

View check run for this annotation

Codecov / codecov/patch

overreact/_cli.py#L255-L256

Added lines #L255 - L256 were not covered by tests

logfiles_table = Table(
Column("no", justify="right"),
Expand Down Expand Up @@ -305,7 +301,7 @@
yield logfiles_table
yield compounds_table

def _yield_thermochemistry(self): # noqa: ANN101
def _yield_thermochemistry(self):
"""Produce a renderables describing the thermochemistry of the reaction scheme.

This is meant to be used from within `__rich_console__`.
Expand All @@ -314,7 +310,7 @@
------
renderable
"""
scheme = rx.core._check_scheme(self.model.scheme) # noqa: SLF001
scheme = rx.core._check_scheme(self.model.scheme)

molecular_masses = np.array(
[np.sum(data.atommasses) for name, data in self.model.compounds.items()],
Expand Down Expand Up @@ -391,7 +387,7 @@
temperature=self.temperature,
pressure=self.pressure,
),
), "reaction free energies do not match reaction enthalpies and reaction entropies" # noqa: E501
), "reaction free energies do not match reaction enthalpies and reaction entropies"

delta_activation_mass = rx.get_delta(scheme.B, molecular_masses)
delta_activation_energies = rx.get_delta(scheme.B, energies)
Expand All @@ -418,7 +414,7 @@
temperature=self.temperature,
pressure=self.pressure,
),
), "activation free energies do not match activation enthalpies and activation entropies" # noqa: E501
), "activation free energies do not match activation enthalpies and activation entropies"

circ_table = Table(
Column("no", justify="right"),
Expand Down Expand Up @@ -493,7 +489,7 @@
yield circ_table
yield dagger_table

def _yield_kinetics(self): # noqa: ANN101, C901, PLR0912, PLR0915
def _yield_kinetics(self):
"""Produce a renderables describing the kinetics of the system.

This is meant to be used from within `__rich_console__`.
Expand Down Expand Up @@ -607,7 +603,7 @@
f"{self.bias} J/mol.",
)
yield Markdown(
"For **half-equilibria**, only ratios make sense: in simulations, **equilibria will be adjusted to be faster than all other reactions**.", # noqa: E501
"For **half-equilibria**, only ratios make sense: in simulations, **equilibria will be adjusted to be faster than all other reactions**.",
)

if self.concentrations is not None and self.concentrations:
Expand Down Expand Up @@ -652,8 +648,8 @@

t_span = y.t_max - y.t_min
active = ~np.isclose(
y(y.t_min + 0.01 * t_span * np.random.rand()), # noqa: NPY002
y(y.t_max - 0.01 * t_span * np.random.rand()), # noqa: NPY002
y(y.t_min + 0.01 * t_span * np.random.rand()),
y(y.t_max - 0.01 * t_span * np.random.rand()),
rtol=0.01,
)
if self.plot == "all" or not np.any(active):
Expand Down Expand Up @@ -683,7 +679,7 @@
for i, name in enumerate(scheme.compounds):
if not rx.is_transition_state(name):
res = minimize_scalar(
lambda t: -r(t)[i], # noqa: B023
lambda t: -r(t)[i],
bounds=(y.t_min, (t_max + y.t_max) / 2),
method="bounded",
)
Expand All @@ -694,7 +690,7 @@

t.update(
np.geomspace(
np.min([_t for _t in t if _t > 0.0]), # noqa: PLR2004
np.min([_t for _t in t if _t > 0.0]),
t_max,
num=num,
),
Expand Down Expand Up @@ -747,11 +743,9 @@

try:
quantity = float(quantity)
except (IndexError, ValueError):
raise ValueError( # noqa: B904, TRY003, TRY200
"badly formatted concentrations: " # noqa: EM102
f"'{' '.join(concentrations)}'", # noqa: RUF100
)
except (IndexError, ValueError) as err:
msg = f"badly formatted concentrations: '{' '.join(concentrations)}'"
raise ValueError(msg) from err

Check warning on line 748 in overreact/_cli.py

View check run for this annotation

Codecov / codecov/patch

overreact/_cli.py#L746-L748

Added lines #L746 - L748 were not covered by tests

d[name] = quantity

Expand Down Expand Up @@ -787,16 +781,11 @@
)
parser.add_argument(
"path",
help="path to a source (`.k`) or compiled (`.jk`) model input file (if a source " # noqa: E501
"input file is given, but there is a compiled file available, the compiled "
"file will be used; use --compile|-c to force recompilation of the "
"source input file instead)",
help="path to a source (`.k`) or compiled (`.jk`) model input file (if a source input file is given, but there is a compiled file available, the compiled file will be used; use --compile|-c to force recompilation of the source input file instead)",
)
parser.add_argument(
"concentrations",
help="(optional) initial compound concentrations (in moles per liter) "
"in the form 'name:quantity' (if present, a microkinetic simulation "
"will be performed; more than one entry can be given)",
help="(optional) initial compound concentrations (in moles per liter) in the form 'name:quantity' (if present, a microkinetic simulation will be performed; more than one entry can be given)",
nargs="*",
)
parser.add_argument(
Expand All @@ -807,8 +796,7 @@
parser.add_argument(
"-v",
"--verbose",
help="increase output verbosity (can be given many times, each time "
"the amount of logged data is increased)",
help="increase output verbosity (can be given many times, each time the amount of logged data is increased)",
action="count",
default=0,
)
Expand All @@ -822,57 +810,46 @@
)
parser.add_argument(
"--plot",
help="plot the concentrations as a function of time from the "
"performed microkinetics simulation: can be either 'none', 'all', "
"'active' species only (i.e., the ones that actually change "
"concentration during the simulation) or a single compound name (e.g. "
"'NH3(w)')",
help="plot the concentrations as a function of time from the performed microkinetics simulation: can be either 'none', 'all', 'active' species only (i.e., the ones that actually change concentration during the simulation) or a single compound name (e.g. 'NH3(w)')",
# TODO(schneiderfelipe): validate inputs to avoid ValueError?
default="none",
)
parser.add_argument(
"-b",
"--bias",
help="an energy value (in kilocalories per mole) to be added to each "
"individual compound in order to mitigate eventual systematic errors",
help="an energy value (in kilocalories per mole) to be added to each individual compound in order to mitigate eventual systematic errors",
default=0.0,
)
parser.add_argument(
"--tunneling",
help="specify the tunneling method employed (use --tunneling=none for "
"no tunneling correction)",
help="specify the tunneling method employed (use --tunneling=none for no tunneling correction)",
choices=["eckart", "wigner", "none"],
default="eckart",
)
parser.add_argument(
"--no-qrrho",
help="disable the quasi-rigid rotor harmonic oscillator (QRRHO) "
"approximations to both enthalpies and entropies (see "
"doi:10.1021/jp509921r and doi:10.1002/chem.201200497)",
help="disable the quasi-rigid rotor harmonic oscillator (QRRHO) approximations to both enthalpies and entropies (see doi:10.1021/jp509921r and doi:10.1002/chem.201200497)",
choices=["both", "enthalpy", "entropy", "none"],
default="both",
dest="qrrho_descriptor",
)
parser.add_argument(
"-T",
"--temperature",
help="set working temperature (in kelvins) to be used in "
"thermochemistry and microkinetics",
help="set working temperature (in kelvins) to be used in thermochemistry and microkinetics",
type=float,
default=298.15,
)
parser.add_argument(
"-p",
"--pressure",
help="set working pressure (in pascals) to be used in "
"thermochemistry", # noqa: RUF100
help="set working pressure (in pascals) to be used in thermochemistry",
type=float,
default=constants.atm,
)
parser.add_argument(
"--method",
help="integrator used in solving the ODE system of the microkinetic "
"simulation",
help="integrator used in solving the ODE system of the microkinetic simulation",
choices=["RK23", "DOP853", "RK45", "LSODA", "BDF", "Radau"],
default="RK23",
)
Expand Down Expand Up @@ -963,7 +940,7 @@
report = Report(
model,
concentrations=args.concentrations,
savepath=f"{os.path.splitext(args.path)[0]}.csv", # noqa: PTH122
savepath=f"{os.path.splitext(args.path)[0]}.csv",
plot=args.plot,
qrrho_descriptor=args.qrrho_descriptor,
temperature=args.temperature,
Expand All @@ -979,6 +956,6 @@


if __name__ == "__main__":
# TODO: catch exceptions here and print a nice error
# TODO(schneiderfelipe): catch exceptions here and print a nice error
# (we can reraise them later if we want).
main()
4 changes: 2 additions & 2 deletions overreact/_constants.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/usr/bin/env python3 # noqa: EXE001

"""Module for storing constant data such as physical fundamental constants.

Most of this data comes from `scipy.constants`.
"""

from __future__ import annotations

import numpy as np
from scipy.constants import (
N_A,
Expand Down
18 changes: 9 additions & 9 deletions overreact/_datasets.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
#!/usr/bin/env python3 # noqa: EXE001

"""Small toy datasets for tests and benchmark."""

from __future__ import annotations

import os

import overreact as rx

data_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), "../data/"), # noqa: PTH118, PTH120
os.path.join(os.path.dirname(__file__), "../data/"),
)


logfiles = {}
for name in os.listdir(data_path):
walk_dir = os.path.join(data_path, name) # noqa: PTH118
if os.path.isdir(walk_dir): # noqa: PTH112
logfiles[name] = rx.io._LazyDict() # noqa: SLF001
logfiles[name]._function = rx.io.read_logfile # noqa: SLF001
walk_dir = os.path.join(data_path, name)
if os.path.isdir(walk_dir):
logfiles[name] = rx.io._LazyDict()
logfiles[name]._function = rx.io.read_logfile
for root, _, files in os.walk(walk_dir):
for filename in files:
if filename.endswith(".out"):
Expand All @@ -25,7 +25,7 @@
"@.",
"",
)
] = os.path.join( # noqa: PTH118
] = os.path.join(
root,
filename,
)
Expand All @@ -34,4 +34,4 @@
if __name__ == "__main__":
for name in logfiles:
for compound in logfiles[name]:
print(name, compound, logfiles[name][compound].logfile) # noqa: T201
print(name, compound, logfiles[name][compound].logfile)

Check warning on line 37 in overreact/_datasets.py

View check run for this annotation

Codecov / codecov/patch

overreact/_datasets.py#L37

Added line #L37 was not covered by tests
Loading