Skip to content

Commit

Permalink
Fix all files with pre-commit and ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
pablormier committed Apr 29, 2024
1 parent f63cc90 commit 443786a
Show file tree
Hide file tree
Showing 71 changed files with 563 additions and 344 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,4 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk

# End of https://www.toptal.com/developers/gitignore/api/windows,linux,python,visualstudiocode,jupyternotebooks
# End of https://www.toptal.com/developers/gitignore/api/windows,linux,python,visualstudiocode,jupyternotebooks
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
],
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false
}
}
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,3 @@ CORNETO is developed at the [Institute for Computational Biomedicine](https://sa
PerMedCoE project ([permedcoe.eu](https://permedcoe.eu/)) agreement no. 951773.

<img src="https://raw.githubusercontent.com/saezlab/.github/main/profile/logos/saezlab.png" alt="Saez lab logo" height="64px" style="height:64px; width:auto"> <img src="https://lcsb-biocore.github.io/COBREXA.jl/stable/assets/permedcoe.svg" alt="PerMedCoE logo" height="64px" style="height:64px; width:auto"> <img src="https://yt3.googleusercontent.com/ytc/AIf8zZSHTQJs12aUZjHsVBpfFiRyrK6rbPwb-7VIxZQk=s176-c-k-c0x00ffffff-no-rj" alt="UKHD logo" height="64px" style="height:64px; width:auto">

10 changes: 4 additions & 6 deletions corneto/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import sys

from corneto._constants import *

from corneto import _plotting as pl
from corneto._graph import Graph, Attr, Attributes, EdgeType
from corneto._constants import *
from corneto._graph import Attr, Attributes, EdgeType, Graph
from corneto._util import info
from corneto.utils import Attr, Attributes

from corneto.backend import DEFAULT_BACKEND, DEFAULT_SOLVER, available_backends
from corneto.backend import DEFAULT_BACKEND as K
from corneto.backend import DEFAULT_BACKEND as ops
Expand All @@ -20,6 +17,7 @@
signaling,
signflow_constraints,
)
from corneto.utils import Attr, Attributes

__all__ = [
"Attr",
Expand All @@ -30,7 +28,7 @@
"DEFAULT_BACKEND",
"available_backends",
"K",
"ops"
"ops",
]


Expand Down
17 changes: 9 additions & 8 deletions corneto/_core.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import abc
from collections import OrderedDict
from copy import deepcopy
from itertools import chain
from numbers import Number
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple

import numpy as np
from typing import Any, Optional, Iterable, Set, Tuple, Union, Dict, List
from corneto._settings import sparsify

from corneto._constants import *
from corneto._decorators import jit
from numbers import Number
from collections import OrderedDict
from itertools import chain
from corneto._settings import sparsify


def _set(e):
Expand Down Expand Up @@ -312,7 +313,7 @@ def to_graphviz(
s, t = e
s = list(s)
if len(s) == 0:
s = f"*_{str(t)}"
s = f"*_{t!s}"
g.node(s, shape="point")
elif len(s) == 1:
s = str(s[0])
Expand All @@ -322,7 +323,7 @@ def to_graphviz(
raise NotImplementedError("Represent- hyperedges as composite edges")
t = list(t)
if len(t) == 0:
t = f"{str(s)}_*"
t = f"{s!s}_*"
g.node(t, shape="point")
elif len(t) == 1:
t = str(t[0])
Expand Down
9 changes: 4 additions & 5 deletions corneto/_decorators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from functools import wraps
from typing import Callable

from corneto._settings import LOGGER, USE_NUMBA


Expand Down Expand Up @@ -27,8 +28,7 @@ def _wrapped_func(*args, **kwargs):


def _delegate(func):
"""
A decorator that wraps a function to provide extended functionality
"""A decorator that wraps a function to provide extended functionality
when applied within a class. This decorator modifies the behavior
of the function `func` to handle expression objects and delegate
calls to their underlying representations, while maintaining a set of
Expand Down Expand Up @@ -74,6 +74,7 @@ def __add__(self, other):
pass
```
"""

@wraps(func)
def _wrapper_func(self, *args, **kwargs):
symbols = set()
Expand All @@ -97,9 +98,7 @@ def _wrapper_func(self, *args, **kwargs):
# if available. E.g., if function is __add__, checks if the backend
# expression has that function and uses it instead, this returns a
# new backend expression which is wrapped back to CORNETO expr.
return self._create(
f(*args, **kwargs), symbols
)
return self._create(f(*args, **kwargs), symbols)
return self._create(func(self, *args, **kwargs), symbols)

return _wrapper_func
12 changes: 7 additions & 5 deletions corneto/_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
)

import numpy as np
from corneto._types import Edge, CobraModel, NxDiGraph, NxGraph
from corneto._util import unique_iter

from corneto._io import import_cobra_model
from corneto._types import CobraModel, Edge, NxDiGraph, NxGraph
from corneto._util import unique_iter
from corneto.utils import Attr, Attributes

T = TypeVar("T")
Expand Down Expand Up @@ -57,7 +58,8 @@ def _tpl(elements: Union[Any, Iterable[Any]]) -> Tuple[Any, ...]:

class BaseGraph(abc.ABC):
"""BaseGraph class for graphs or hypergraphs with directed/undirected/mixed
and self edges"""
and self edges
"""

def __init__(self, default_edge_type: EdgeType = EdgeType.DIRECTED) -> None:
"""Initialize BaseGraph with default edge type.
Expand Down Expand Up @@ -647,7 +649,7 @@ class Graph(BaseGraph):
default_edge_type
Default edge type :class:`~corneto._graph.EdgeType`.
Examples
Examples:
--------
>>> graph = corneto.Graph()
>>> graph.add_edge(1, 2)
Expand Down Expand Up @@ -688,7 +690,7 @@ def _add_edge(
) -> int:
sv = frozenset(source)
tv = frozenset(target)
#uv = sv | tv
# uv = sv | tv
edge = (sv, tv)
self._edges.append(edge)
idx = len(self._edges) - 1
Expand Down
26 changes: 13 additions & 13 deletions corneto/_io.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
from pathlib import Path
from typing import (
List,
Dict,
Iterable,
Tuple,
List,
Optional,
Dict,
Set,
Tuple,
Union,
TypeVar,
Any,
TYPE_CHECKING,
)
from corneto._types import TupleSIF, CobraModel

import numpy as np

from corneto._types import CobraModel, TupleSIF


def _read_sif(
sif_file: Union[str, Path],
Expand Down Expand Up @@ -54,7 +53,9 @@ def _read_sif_iter(
if has_header and i == 0:
continue
if len(line) <= 2:
raise ValueError(f"Invalid SIF line: {line}: expected at least 3 columns")
raise ValueError(
f"Invalid SIF line: {line}: expected at least 3 columns"
)
s, d, t = [line[idx] for idx in column_order]
if discard_self_loops and s == t:
continue
Expand Down Expand Up @@ -95,7 +96,7 @@ def _get_reaction_species(reactions: Dict[str, Dict[str, int]]) -> Set[str]:


def _stoichiometry(
reactions: Dict[str, Dict[str, int]]
reactions: Dict[str, Dict[str, int]],
) -> Tuple[np.ndarray, List[str], List[str]]:
reactions_ids = list(reactions.keys())
compounds_ids = list(_get_reaction_species(reactions))
Expand Down Expand Up @@ -173,7 +174,7 @@ def import_cobra_model(model: CobraModel) -> Tuple[np.ndarray, np.ndarray, np.nd
# Try to create a list
import re

subsys = re.findall("\['(.*?)'\]", subsys)
subsys = re.findall(r"\['(.*?)'\]", subsys)
if len(subsys) == 0:
subsys = rxn.subsystem
# A list containing a numpy array?
Expand Down Expand Up @@ -222,8 +223,7 @@ def import_cobra_model(model: CobraModel) -> Tuple[np.ndarray, np.ndarray, np.nd


def _is_url(url):
"""
Determine if the provided string is a valid url
"""Determine if the provided string is a valid url
:param url: string
:return: True if the string is a URL
"""
Expand All @@ -243,8 +243,8 @@ def _download(url_file):

if not _is_url(url_file):
raise ValueError("Invalid url")
import tempfile
import os
import tempfile
from urllib.request import urlopen

ext = pathlib.Path(url_file).suffix
Expand Down
6 changes: 3 additions & 3 deletions corneto/_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ def select(
if isinstance(ids, int) or isinstance(ids, str):
ids = [ids]
if not isinstance(ids, list):
raise ValueError(f"ids must be a list of ints or strings")
raise ValueError("ids must be a list of ints or strings")
for id in ids:
if isinstance(id, int):
nids.append(id)
Expand Down Expand Up @@ -998,7 +998,7 @@ def legacy_graphviz(
s, t = e
s = list(s)
if len(s) == 0:
s = f"*_{str(t)}"
s = f"*_{t!s}"
g.node(s, shape="point")
elif len(s) == 1:
s = str(s[0])
Expand All @@ -1008,7 +1008,7 @@ def legacy_graphviz(
raise NotImplementedError("Represent- hyperedges as composite edges")
t = list(t)
if len(t) == 0:
t = f"{str(s)}_*"
t = f"{s!s}_*"
g.node(t, shape="point")
elif len(t) == 1:
t = str(t[0])
Expand Down
11 changes: 6 additions & 5 deletions corneto/_nx.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import warnings
from typing import Any, Dict, Iterable, Optional

from corneto._legacy import ReNet
from corneto._types import StrOrInt
from typing import Any, Dict, List, Optional, Iterable, Union
import warnings

# TODO: Pass default style to plotting methods
_default_style = {
Expand Down Expand Up @@ -79,8 +80,8 @@ def plot(
):
try:
import matplotlib.pyplot as plt
from matplotlib.patches import ArrowStyle
import networkx as nx
from matplotlib.patches import ArrowStyle
except ImportError:
raise ImportError("matplotlib and networkx are required for plotting")

Expand All @@ -94,7 +95,7 @@ def plot(
pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
except Exception as err:
warnings.warn(
f"Failed to use graphviz with dot layout: {str(err)}. Using spring_layout instead."
f"Failed to use graphviz with dot layout: {err!s}. Using spring_layout instead."
)
pos = nx.spring_layout(G)

Expand Down Expand Up @@ -185,7 +186,7 @@ def to_nxgraph(
reactions: Optional[Iterable[StrOrInt]] = None,
):
try:
from networkx import DiGraph, set_node_attributes, set_edge_attributes
from networkx import DiGraph, set_edge_attributes, set_node_attributes
except ImportError:
raise ImportError(
"NetworkX is required to convert a Reaction Network to a networkx graph."
Expand Down
10 changes: 6 additions & 4 deletions corneto/_plotting.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Any, Dict, Optional, Literal
from corneto._graph import BaseGraph, Attr, EdgeType
from corneto.backend._base import EXPR_NAME_FLOW
from typing import Any, Dict, Literal, Optional

import numpy as np

from corneto._graph import Attr, BaseGraph, EdgeType
from corneto.backend._base import EXPR_NAME_FLOW


def clip_quantiles(arr, q):
if q < 0 or q > 1:
Expand All @@ -14,7 +16,7 @@ def clip_quantiles(arr, q):

def vertex_style(
P,
G, # TODO: G should not be required
G, # TODO: G should not be required
vertex_var: str = "vertex_values",
negative_color: str = "dodgerblue4",
positive_color: str = "firebrick4",
Expand Down
3 changes: 2 additions & 1 deletion corneto/_settings.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import logging
import os
import sys
import numpy as np
from importlib.util import find_spec

import numpy as np

LOGGER = logging.getLogger("__corneto__")
LOGGER.setLevel(logging.INFO)
LOGGER.propagate = False
Expand Down
5 changes: 3 additions & 2 deletions corneto/_types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING, FrozenSet, Tuple, Union, Any, TypeVar
from corneto._settings import LOGGER
import importlib
from typing import TYPE_CHECKING, Any, FrozenSet, Tuple, TypeVar, Union

from corneto._settings import LOGGER

Edge = Tuple[FrozenSet[Any], FrozenSet[Any]]
StrOrInt = Union[str, int]
Expand Down
2 changes: 1 addition & 1 deletion corneto/_typing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Union, Tuple
from typing import Tuple, Union

StrOrInt = Union[str, int]
TupleSIF = Tuple[str, int, str]
8 changes: 3 additions & 5 deletions corneto/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def get_latest_version(
if match:
version = match.group(1)
return version
except Exception as e:
except Exception:
return None


Expand All @@ -49,8 +49,6 @@ def _support_html_output(force_html: bool = False):
# and https://github.com/tqdm/tqdm/blob/0bb91857eca0d4aea08f66cf1c8949abe0cd6b7a/tqdm/notebook.py#L38
try:
from IPython import get_ipython
from IPython.core.display import display
from IPython.display import HTML

ipy = get_ipython()
if ipy is None:
Expand Down Expand Up @@ -115,7 +113,7 @@ def _get_info() -> Dict[str, Dict]:

info["graphviz_version"]["message"] = f"v{graphviz.__version__}"
info["graphviz_version"]["value"] = graphviz.__version__
except Exception as e:
except Exception:
pass
info["repo_url"] = {
"title": "Repository",
Expand Down Expand Up @@ -189,7 +187,7 @@ def _info():
if DEFAULT_BACKEND:
print("Default backend (corneto.K):", str(DEFAULT_BACKEND))
print(
f"Available solvers for {str(DEFAULT_BACKEND)}:",
f"Available solvers for {DEFAULT_BACKEND!s}:",
", ".join([s for s in DEFAULT_BACKEND.available_solvers()]),
)
else:
Expand Down
Loading

0 comments on commit 443786a

Please sign in to comment.