Skip to content

Commit

Permalink
linted!
Browse files Browse the repository at this point in the history
  • Loading branch information
mikemhenry committed Feb 16, 2024
1 parent 4ce04bf commit 804a657
Show file tree
Hide file tree
Showing 30 changed files with 65 additions and 61 deletions.
2 changes: 1 addition & 1 deletion openfe/analysis/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def plot_lambda_transition_matrix(matrix: npt.NDArray) -> Axes:
ax.axhline(y=i, ls="-", lw=0.5, color="k", alpha=0.25)
for j in range(num_states):
val = matrix[i, j]
val_str = "{:.2f}".format(val)[1:]
val_str = f"{val:.2f}"[1:]
rel_prob = val / matrix.max()

# shade box
Expand Down
2 changes: 1 addition & 1 deletion openfe/due.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
__version__ = "0.0.9"


class InactiveDueCreditCollector(object):
class InactiveDueCreditCollector:
"""Just a stub at the Collector which would not do anything"""

def _donothing(self, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion openfe/protocols/openmm_rfe/_rfe_utils/lambdaprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from openmmtools.alchemy import AlchemicalState


class LambdaProtocol(object):
class LambdaProtocol:
"""Protocols for perturbing each of the component energy terms in alchemical
free energy simulations.
Expand Down
10 changes: 5 additions & 5 deletions openfe/protocols/openmm_rfe/_rfe_utils/multistate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
logger = logging.getLogger(__name__)


class HybridCompatibilityMixin(object):
class HybridCompatibilityMixin:
"""
Mixin that allows the MultistateSampler to accommodate the situation where
unsampled endpoints have a different number of degrees of freedom.
"""

def __init__(self, *args, hybrid_factory=None, **kwargs):
self._hybrid_factory = hybrid_factory
super(HybridCompatibilityMixin, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def setup(
self,
Expand Down Expand Up @@ -167,7 +167,7 @@ class HybridRepexSampler(HybridCompatibilityMixin, replicaexchange.ReplicaExchan
"""

def __init__(self, *args, hybrid_factory=None, **kwargs):
super(HybridRepexSampler, self).__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
super().__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
self._factory = hybrid_factory


Expand All @@ -178,7 +178,7 @@ class HybridSAMSSampler(HybridCompatibilityMixin, sams.SAMSSampler):
"""

def __init__(self, *args, hybrid_factory=None, **kwargs):
super(HybridSAMSSampler, self).__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
super().__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
self._factory = hybrid_factory


Expand All @@ -189,7 +189,7 @@ class HybridMultiStateSampler(HybridCompatibilityMixin, multistatesampler.MultiS
"""

def __init__(self, *args, hybrid_factory=None, **kwargs):
super(HybridMultiStateSampler, self).__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
super().__init__(*args, hybrid_factory=hybrid_factory, **kwargs)
self._factory = hybrid_factory


Expand Down
12 changes: 5 additions & 7 deletions openfe/protocols/openmm_rfe/_rfe_utils/topologyhelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,13 +277,11 @@ def get_alchemical_waters(
periodic=True,
)[0]

solvent_indices = set(
[
atom.residue.index
for atom in traj.topology.atoms
if (atom.index in water_atoms) and (atom.index not in excluded_waters)
],
)
solvent_indices = {
atom.residue.index
for atom in traj.topology.atoms
if (atom.index in water_atoms) and (atom.index not in excluded_waters)
}

if len(solvent_indices) < 1:
errmsg = (
Expand Down
2 changes: 1 addition & 1 deletion openfe/protocols/openmm_utils/system_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def validate_protein(state: ChemicalSystem):
raise ValueError(errmsg)


ParseCompRet = Tuple[
ParseCompRet = tuple[
Optional[SolventComponent],
Optional[ProteinComponent],
list[SmallMoleculeComponent],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# For details, see https://github.com/OpenFreeEnergy/openfe

import abc
from typing import Iterable
from collections.abc import Iterable

from gufe import AlchemicalNetwork

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# For details, see https://github.com/OpenFreeEnergy/openfe
import abc
import copy
from typing import Callable, Iterable, Optional, Type
from collections.abc import Iterable
from typing import Callable, Optional, Type

from gufe import (
AlchemicalNetwork,
Expand Down Expand Up @@ -93,7 +94,7 @@ def transformation_protocol(self) -> Protocol:
@property
def chemical_system_generator_type(
self,
) -> Type[AbstractChemicalSystemGenerator]:
) -> type[AbstractChemicalSystemGenerator]:
return self._chemical_system_generator_type

def _construct_ligand_network(self, ligands: Iterable[SmallMoleculeComponent]) -> LigandNetwork:
Expand Down
2 changes: 1 addition & 1 deletion openfe/setup/atom_mapping/ligandatommapper.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import abc
from typing import Iterable
from collections.abc import Iterable

import gufe
from gufe import SmallMoleculeComponent
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
import abc
from collections.abc import Iterable
from enum import Enum
from typing import Iterable

from gufe import ChemicalSystem

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe

from typing import Iterable, Optional
from collections.abc import Iterable
from typing import Optional

from gufe import ChemicalSystem, Component, ProteinComponent, SmallMoleculeComponent, SolventComponent

Expand Down
9 changes: 5 additions & 4 deletions openfe/setup/ligand_network_planning.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
import math
import warnings
from collections import Counter
from collections.abc import Iterable
from pathlib import Path
from typing import Callable, Iterable, Optional, Union
from typing import Callable, Optional, Union

import networkx as nx
from gufe import AtomMapper, SmallMoleculeComponent
Expand Down Expand Up @@ -330,7 +331,7 @@ def generate_network_from_names(
nm2idx = {l.name: i for i, l in enumerate(ligands)}

if len(nm2idx) < len(ligands):
dupes = Counter((l.name for l in ligands))
dupes = Counter(l.name for l in ligands)
dupe_names = [k for k, v in dupes.items() if v > 1]
raise ValueError(f"Duplicate names: {dupe_names}")

Expand Down Expand Up @@ -418,7 +419,7 @@ def load_orion_network(
If an unexpected line format is encountered.
"""

with open(network_file, "r") as f:
with open(network_file) as f:
network_lines = [l.strip().split(" ") for l in f if not l.startswith("#")]

names = []
Expand Down Expand Up @@ -458,7 +459,7 @@ def load_fepplus_network(
If an unexpected line format is encountered.
"""

with open(network_file, "r") as f:
with open(network_file) as f:
network_lines = [l.split() for l in f.readlines()]

names = []
Expand Down
2 changes: 1 addition & 1 deletion openfe/storage/metadatastore.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def store_metadata(self, location: str, metadata: Metadata):
raise NotImplementedError()

@abc.abstractmethod
def load_all_metadata(self) -> Dict[str, Metadata]:
def load_all_metadata(self) -> dict[str, Metadata]:
raise NotImplementedError()

@abc.abstractmethod
Expand Down
4 changes: 2 additions & 2 deletions openfe/tests/protocols/test_openmm_equil_rfe_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -1477,7 +1477,7 @@ def tyk2_xml(tmp_path_factory):
def tyk2_reference_xml():
with resources.files("openfe.tests.data.openmm_rfe") as d:
f = d / "reference.xml"
with open(f, "r") as i:
with open(f) as i:

Check warning on line 1480 in openfe/tests/protocols/test_openmm_equil_rfe_protocols.py

View check run for this annotation

Codecov / codecov/patch

openfe/tests/protocols/test_openmm_equil_rfe_protocols.py#L1478-L1480

Added lines #L1478 - L1480 were not covered by tests
xmldata = i.read()
return ET.fromstring(xmldata)

Expand Down Expand Up @@ -1620,7 +1620,7 @@ def test_filenotfound_replica_states(self, protocolresult):
def test_get_charge_difference(mapping_name, result, request):
mapping = request.getfixturevalue(mapping_name)
if result != 0:
ion = "Na\+" if result == -1 else "Cl\-"
ion = r"Na\+" if result == -1 else r"Cl\-"
wmsg = (
f"A charge difference of {result} is observed "
"between the end states. This will be addressed by "
Expand Down
8 changes: 4 additions & 4 deletions openfe/tests/setup/atom_mapping/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
from ...conftest import mol_from_smiles


def _translate_lomap_mapping(atom_mapping_str: str) -> Dict[int, int]:
def _translate_lomap_mapping(atom_mapping_str: str) -> dict[int, int]:
mapped_atom_tuples = map(lambda x: tuple(map(int, x.split(":"))), atom_mapping_str.split(","))
return {i: j for i, j in mapped_atom_tuples}


def _get_atom_mapping_dict(lomap_atom_mappings) -> Dict[Tuple[int, int], Dict[int, int]]:
def _get_atom_mapping_dict(lomap_atom_mappings) -> dict[tuple[int, int], dict[int, int]]:
return {
mol_pair: _translate_lomap_mapping(atom_mapping_str)
for mol_pair, atom_mapping_str in lomap_atom_mappings.mcs_map_store.items()
Expand All @@ -29,7 +29,7 @@ def _get_atom_mapping_dict(lomap_atom_mappings) -> Dict[Tuple[int, int], Dict[in
def gufe_atom_mapping_matrix(
lomap_basic_test_files_dir,
atom_mapping_basic_test_files,
) -> Dict[Tuple[int, int], LigandAtomMapping]:
) -> dict[tuple[int, int], LigandAtomMapping]:
dbmols = lomap.DBMolecules(lomap_basic_test_files_dir, verbose="off")
_, _ = dbmols.build_matrices()
molecule_pair_atom_mappings = _get_atom_mapping_dict(dbmols)
Expand All @@ -48,7 +48,7 @@ def gufe_atom_mapping_matrix(


@pytest.fixture()
def mol_pair_to_shock_perses_mapper() -> Tuple[SmallMoleculeComponent, SmallMoleculeComponent]:
def mol_pair_to_shock_perses_mapper() -> tuple[SmallMoleculeComponent, SmallMoleculeComponent]:
"""
This pair of Molecules leads to an empty Atom mapping in
Perses Mapper with certain settings.
Expand Down
4 changes: 2 additions & 2 deletions openfe/tests/storage/test_metadatastore.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def test_store_metadata(self, json_metadata):
base_path = json_metadata.external_store.root_dir
metadata_json = base_path / "metadata.json"
assert metadata_json.exists()
with open(metadata_json, mode="r") as f:
with open(metadata_json) as f:
metadata_dict = json.load(f)

metadata = {key: Metadata(**val) for key, val in metadata_dict.items()}
Expand Down Expand Up @@ -117,7 +117,7 @@ def test_store_metadata(self, per_file_metadata):
per_file_metadata.store_metadata("path/to/other.txt", meta)
assert expected_path.exists()
expected = {"path": "path/to/other.txt", "metadata": {"md5": "other"}}
with open(expected_path, mode="r") as f:
with open(expected_path) as f:
assert json.load(f) == expected

def test_load_all_metadata(self, per_file_metadata):
Expand Down
2 changes: 1 addition & 1 deletion openfe/tests/storage/test_resultclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def result_client(tmpdir):
result_client = ResultClient(external)

# store one file with contents "foo"
result_client.result_server.store_bytes("transformations/MAIN_TRANS/0/0/file.txt", "foo".encode("utf-8"))
result_client.result_server.store_bytes("transformations/MAIN_TRANS/0/0/file.txt", b"foo")

# create some empty files as well
empty_files = [
Expand Down
6 changes: 3 additions & 3 deletions openfe/tests/storage/test_resultserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def result_server(tmpdir):
external = FileStorage(tmpdir)
metadata = JSONMetadataStore(external)
result_server = ResultServer(external, metadata)
result_server.store_bytes("path/to/foo.txt", "foo".encode("utf-8"))
result_server.store_bytes("path/to/foo.txt", b"foo")
return result_server


Expand All @@ -32,7 +32,7 @@ def test_store_bytes(self, result_server):
mock_hash = mock.Mock(return_value=mock.Mock(hexdigest=mock.Mock(return_value="deadbeef")))
bar_loc = "path/to/bar.txt"
with mock.patch("hashlib.md5", mock_hash):
result_server.store_bytes(bar_loc, "bar".encode("utf-8"))
result_server.store_bytes(bar_loc, b"bar")

assert len(metadata_store) == 2
assert bar_loc in metadata_store
Expand All @@ -46,7 +46,7 @@ def test_store_path(self, result_server, tmp_path):
orig_file = tmp_path / ".hidden" / "bar.txt"
orig_file.parent.mkdir(parents=True, exist_ok=True)
with open(orig_file, mode="wb") as f:
f.write("bar".encode("utf-8"))
f.write(b"bar")

mock_hash = mock.Mock(return_value=mock.Mock(hexdigest=mock.Mock(return_value="deadc0de")))
bar_loc = "path/to/bar.txt"
Expand Down
3 changes: 2 additions & 1 deletion openfe/tests/utils/conftest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
from collections.abc import Iterable
from importlib import resources
from typing import Iterable, NamedTuple
from typing import NamedTuple

import pytest
from rdkit import Chem
Expand Down
2 changes: 1 addition & 1 deletion openfe/tests/utils/test_atommapping_network_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def test_select_mock_drawing(self, edge_str, left_right, molA_to_molB, network_d
node_dict = {node.smiles: node for node in network_drawing.graph.nodes}
edge_tuple = tuple(node_dict[node] for node in edge_str)
edge = network_drawing.edges[edge_tuple]
left, right = [network_drawing.nodes[node_dict[node]] for node in left_right]
left, right = (network_drawing.nodes[node_dict[node]] for node in left_right)
# ensure that we have them labelled correctly
assert left.xy[0] < right.xy[0]
func = edge._draw_mapped_molecule # save for bound_args
Expand Down
2 changes: 1 addition & 1 deletion openfe/tests/utils/test_network_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def test_on_drag(self):
event = mock_event("drag", 0.7, 0.7, self.fig)
# this test some integration, so we need more than a mock
drawing_graph = GraphDrawing(
nx.MultiDiGraph(([("A", "B"), ("B", "C"), ("B", "D")])),
nx.MultiDiGraph([("A", "B"), ("B", "C"), ("B", "D")]),
positions={"A": (0.0, 0.0), "B": (0.5, 0.0), "C": (0.5, 0.5), "D": (0.0, 0.5)},
)
# set up things that should happen on mousedown
Expand Down
6 changes: 3 additions & 3 deletions openfe/utils/atommapping_network_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ class AtomMappingEdge(Edge):
to an :class:`.AtomMapping`.
"""

def __init__(self, node_artist1: Node, node_artist2: Node, data: Dict):
def __init__(self, node_artist1: Node, node_artist2: Node, data: dict):
super().__init__(node_artist1, node_artist2, data)
self.left_image = None
self.right_image = None

def _draw_mapped_molecule(
self,
extent: Tuple[float, float, float, float],
extent: tuple[float, float, float, float],
molA: SmallMoleculeComponent,
molB: SmallMoleculeComponent,
molA_to_molB: Dict[int, int],
molA_to_molB: dict[int, int],
):
# create the image in a format matplotlib can handle
d2d = Chem.Draw.rdMolDraw2D.MolDraw2DCairo(300, 300, 300, 300)
Expand Down
8 changes: 4 additions & 4 deletions openfe/utils/network_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, node, x: float, y: float, dx=0.1, dy=0.1):
self.dy = dx
self.artist = self._make_artist(x, y, dx, dy)
self.picked = False
self.press: Optional[ClickLocation] = None
self.press: ClickLocation | None = None

def _make_artist(self, x, y, dx, dy):
return Rectangle((x, y), dx, dy, color="blue")
Expand Down Expand Up @@ -245,9 +245,9 @@ class EventHandler:

def __init__(self, graph: GraphDrawing):
self.graph = graph
self.active: Optional[Union[Node, Edge]] = None
self.selected: Optional[Union[Node, Edge]] = None
self.click_location: Optional[tuple[Optional[float], Optional[float]]] = None
self.active: Node | Edge | None = None
self.selected: Node | Edge | None = None
self.click_location: tuple[float | None, float | None] | None = None
self.connections: list[int] = []

def connect(self, canvas: MPL_FigureCanvasBase):
Expand Down
3 changes: 2 additions & 1 deletion openfe/utils/system_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import socket
import subprocess
import sys
from typing import Iterable, Optional
from collections.abc import Iterable
from typing import Optional

import psutil
from psutil._common import bytes2human
Expand Down
Loading

0 comments on commit 804a657

Please sign in to comment.