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

type: remove deprecated typing aliases as described in PEP-585 #16

Merged
merged 4 commits into from
Apr 5, 2024
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
5 changes: 2 additions & 3 deletions examples/CollectTips.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"import os\n",
"from functools import reduce\n",
"from operator import add\n",
"from typing import List\n",
"\n",
"import numpy as np\n",
"\n",
Expand All @@ -37,11 +36,11 @@
"metadata": {},
"outputs": [],
"source": [
"def collect_tips(cur: swcgeom.Tree.Node, children: List[int]) -> int:\n",
"def collect_tips(cur: swcgeom.Tree.Node, children: list[int]) -> int:\n",
" cur[\"tips\"] = max(1, reduce(add, children, 0))\n",
" return cur[\"tips\"]\n",
"\n",
"def collect_length(cur: swcgeom.Tree.Node, children: List[swcgeom.Tree.Node]) -> swcgeom.Tree.Node:\n",
"def collect_length(cur: swcgeom.Tree.Node, children: list[swcgeom.Tree.Node]) -> swcgeom.Tree.Node:\n",
" def length(acc: float, child: swcgeom.Tree.Node) -> float:\n",
" return acc + cur.distance(child) + child[\"length\"]\n",
"\n",
Expand Down
3 changes: 1 addition & 2 deletions examples/CutTree.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"outputs": [],
"source": [
"import math\n",
"from typing import List\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
Expand Down Expand Up @@ -138,7 +137,7 @@
"\n",
" removals = []\n",
"\n",
" def collect_cut(n: Tree.Node, children: List[int]) -> int:\n",
" def collect_cut(n: Tree.Node, children: list[int]) -> int:\n",
" if len(children) <= 1:\n",
" return n.id\n",
"\n",
Expand Down
4 changes: 2 additions & 2 deletions examples/Features.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"metadata": {},
"outputs": [],
"source": [
"from typing import Any, cast, Dict\n",
"from typing import Any, cast\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
Expand Down Expand Up @@ -88,7 +88,7 @@
],
"source": [
"features = extract_feature(tree3)\n",
"all_features: Dict[Feature, Dict] = {\n",
"all_features: dict[Feature, dict] = {\n",
" \"length\": {},\n",
" \"node_radial_distance\": {},\n",
" \"node_branch_order\": {},\n",
Expand Down
8 changes: 4 additions & 4 deletions examples/dgl/graph.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Dgl grapth transforms."""

from typing import List, cast
from typing import cast

import dgl

Expand All @@ -19,21 +19,21 @@ class ToDGLGraph(Transform[Tree, dgl.DGLGraph]):
this class is more of a toy and template.
"""

keys: List[str] | None
keys: list[str] | None
to_bidirected: bool

def __init__(
self,
to_bidirected: bool = False,
keys: List[str] | None = None,
keys: list[str] | None = None,
) -> None:
"""Transofrm tree to dgl graph.

Parameters
----------
to_bidirected : bool, default to `False`
If True, return bidirected graph.
keys : List[str], optional
keys : list[str], optional
Copy these keys as ndata of graph.
"""

Expand Down
3 changes: 2 additions & 1 deletion examples/pytorch/branch.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Transformations in branch requires pytorch."""

from typing import Callable, Literal
from collections.abc import Callable
from typing import Literal

import numpy as np
import numpy.typing as npt
Expand Down
3 changes: 2 additions & 1 deletion examples/pytorch/branch_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import os
import warnings
from typing import Generic, Iterable, TypeVar, cast
from collections.abc import Iterable
from typing import Generic, TypeVar, cast

import torch
import torch.utils.data
Expand Down
25 changes: 13 additions & 12 deletions swcgeom/analysis/feature_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
"""

from abc import ABC, abstractmethod
from collections.abc import Callable
from functools import cached_property
from itertools import chain
from os.path import basename
from typing import Any, Callable, Dict, List, Literal, Tuple, overload
from typing import Any, Literal, overload

import numpy as np
import numpy.typing as npt
Expand Down Expand Up @@ -54,7 +55,7 @@
]

NDArrayf32 = npt.NDArray[np.float32]
FeatAndKwargs = Feature | Tuple[Feature, Dict[str, Any]]
FeatAndKwargs = Feature | tuple[Feature, dict[str, Any]]

Feature1D = set(["length", "volume", "node_count", "bifurcation_count", "tip_count"])

Expand Down Expand Up @@ -121,9 +122,9 @@ class FeatureExtractor(ABC):
@overload
def get(self, feature: Feature, **kwargs) -> NDArrayf32: ...
@overload
def get(self, feature: List[FeatAndKwargs]) -> List[NDArrayf32]: ...
def get(self, feature: list[FeatAndKwargs]) -> list[NDArrayf32]: ...
@overload
def get(self, feature: Dict[Feature, Dict[str, Any]]) -> Dict[str, NDArrayf32]: ...
def get(self, feature: dict[Feature, dict[str, Any]]) -> dict[str, NDArrayf32]: ...
# fmt:on
def get(self, feature, **kwargs):
"""Get feature.
Expand Down Expand Up @@ -168,7 +169,7 @@ def plot(self, feature: FeatAndKwargs, title: str | bool = True, **kwargs) -> Ax

# Custom Plots

def plot_node_branch_order(self, feature_kwargs: Dict[str, Any], **kwargs) -> Axes:
def plot_node_branch_order(self, feature_kwargs: dict[str, Any], **kwargs) -> Axes:
vals = self._get("node_branch_order", **feature_kwargs)
bin_edges = np.arange(int(np.ceil(vals.max() + 1))) + 0.5
return self._plot_histogram_impl(vals, bin_edges, **kwargs)
Expand Down Expand Up @@ -234,7 +235,7 @@ def get_sholl(self, **kwargs) -> NDArrayf32:

def plot_sholl(
self,
feature_kwargs: Dict[str, Any], # pylint: disable=unused-argument
feature_kwargs: dict[str, Any], # pylint: disable=unused-argument
**kwargs,
) -> Axes:
_, ax = self._features.sholl.plot(**kwargs)
Expand Down Expand Up @@ -264,7 +265,7 @@ class PopulationFeatureExtractor(FeatureExtractor):
"""Extract features from population."""

_population: Population
_features: List[Features]
_features: list[Features]

def __init__(self, population: Population) -> None:
super().__init__()
Expand All @@ -279,7 +280,7 @@ def get_sholl(self, **kwargs) -> NDArrayf32:

# Custom Plots

def plot_sholl(self, feature_kwargs: Dict[str, Any], **kwargs) -> Axes:
def plot_sholl(self, feature_kwargs: dict[str, Any], **kwargs) -> Axes:
vals, rs = self._get_sholl_impl(**feature_kwargs)
ax = self._lineplot(xs=rs, ys=vals.flatten(), **kwargs)
ax.set_ylabel("Count of Intersections")
Expand All @@ -295,7 +296,7 @@ def _get_impl(self, feature: Feature, **kwargs) -> NDArrayf32:

def _get_sholl_impl(
self, steps: int = 20, **kwargs
) -> Tuple[NDArrayf32, NDArrayf32]:
) -> tuple[NDArrayf32, NDArrayf32]:
rmax = max(t.sholl.rmax for t in self._features)
rs = Sholl.get_rs(rmax=rmax, steps=steps)
vals = self._get_impl("sholl", steps=rs, **kwargs)
Expand Down Expand Up @@ -333,7 +334,7 @@ class PopulationsFeatureExtractor(FeatureExtractor):
"""Extract feature from population."""

_populations: Populations
_features: List[List[Features]]
_features: list[list[Features]]

def __init__(self, populations: Populations) -> None:
super().__init__()
Expand All @@ -348,7 +349,7 @@ def get_sholl(self, **kwargs) -> NDArrayf32:

# Custom Plots

def plot_sholl(self, feature_kwargs: Dict[str, Any], **kwargs) -> Axes:
def plot_sholl(self, feature_kwargs: dict[str, Any], **kwargs) -> Axes:
vals, rs = self._get_sholl_impl(**feature_kwargs)
ax = self._lineplot(xs=rs, ys=vals, **kwargs)
ax.set_ylabel("Count of Intersections")
Expand All @@ -369,7 +370,7 @@ def _get_impl(self, feature: Feature, **kwargs) -> NDArrayf32:

def _get_sholl_impl(
self, steps: int = 20, **kwargs
) -> Tuple[NDArrayf32, NDArrayf32]:
) -> tuple[NDArrayf32, NDArrayf32]:
rmaxs = chain.from_iterable((t.sholl.rmax for t in p) for p in self._features)
rmax = max(rmaxs)
rs = Sholl.get_rs(rmax=rmax, steps=steps)
Expand Down
8 changes: 4 additions & 4 deletions swcgeom/analysis/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from abc import ABC, abstractmethod
from functools import cached_property
from typing import List, TypeVar
from typing import TypeVar

import numpy as np
import numpy.typing as npt
Expand Down Expand Up @@ -163,7 +163,7 @@ def get_tortuosity(self) -> npt.NDArray[np.float32]:
return np.array([path.tortuosity() for path in self._paths], dtype=np.float32)

@cached_property
def _paths(self) -> List[Tree.Path]:
def _paths(self) -> list[Tree.Path]:
return self.tree.get_paths()


Expand Down Expand Up @@ -201,7 +201,7 @@ def get_angle(self, eps: float = 1e-7) -> npt.NDArray[np.float32]:
return self.calc_angle(self._branches, eps=eps)

@staticmethod
def calc_angle(branches: List[T], eps: float = 1e-7) -> npt.NDArray[np.float32]:
def calc_angle(branches: list[T], eps: float = 1e-7) -> npt.NDArray[np.float32]:
"""Calc agnle between branches.

Returns
Expand All @@ -219,5 +219,5 @@ def calc_angle(branches: List[T], eps: float = 1e-7) -> npt.NDArray[np.float32]:
return angle

@cached_property
def _branches(self) -> List[Tree.Branch]:
def _branches(self) -> list[Tree.Branch]:
return self.tree.get_branches()
10 changes: 5 additions & 5 deletions swcgeom/analysis/lmeasure.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""L-Measure analysis."""

import math
from typing import Literal, Tuple
from typing import Literal

import numpy as np
import numpy.typing as npt
Expand Down Expand Up @@ -274,7 +274,7 @@ def rall_power(self, bif: Tree.Node) -> float:
rall_power, _, _, _ = self._rall_power(bif)
return rall_power

def _rall_power_d(self, bif: Tree.Node) -> Tuple[float, float, float]:
def _rall_power_d(self, bif: Tree.Node) -> tuple[float, float, float]:
children = bif.children()
assert len(children) == 2, "Rall Power is only defined for bifurcations"
parent = bif.parent()
Expand All @@ -284,7 +284,7 @@ def _rall_power_d(self, bif: Tree.Node) -> Tuple[float, float, float]:
da, db = 2 * children[0].r, 2 * children[1].r
return dp, da, db

def _rall_power(self, bif: Tree.Node) -> Tuple[float, float, float, float]:
def _rall_power(self, bif: Tree.Node) -> tuple[float, float, float, float]:
dp, da, db = self._rall_power_d(bif)
start, stop, step = 0, 5, 5 / 1000
xs = np.arange(start, stop, step)
Expand Down Expand Up @@ -501,7 +501,7 @@ def bif_torque_remote(self, bif: Tree.Node) -> float:

def _bif_vector_local(
self, bif: Tree.Node
) -> Tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]:
) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]:
children = bif.children()
assert len(children) == 2, "Only defined for bifurcations"

Expand All @@ -511,7 +511,7 @@ def _bif_vector_local(

def _bif_vector_remote(
self, bif: Tree.Node
) -> Tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]:
) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.float32]]:
children = bif.children()
assert len(children) == 2, "Only defined for bifurcations"

Expand Down
8 changes: 4 additions & 4 deletions swcgeom/analysis/sholl.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Sholl analysis."""

import warnings
from typing import List, Literal, Optional, Tuple
from typing import Literal, Optional

import numpy as np
import numpy.typing as npt
Expand Down Expand Up @@ -84,18 +84,18 @@ def intersect(self, r: float) -> int:

def plot( # pylint: disable=too-many-arguments
self,
steps: List[float] | int = 20,
steps: list[float] | int = 20,
plot_type: str | None = None,
kind: Literal["bar", "linechart", "circles"] = "circles",
fig: Figure | None = None,
ax: Axes | None = None,
**kwargs,
) -> Tuple[Figure, Axes]:
) -> tuple[Figure, Axes]:
"""Plot Sholl analysis.

Parameters
----------
steps : int or List[float], default to 20
steps : int or list[float], default to 20
Steps of raius of circle. If steps is int, then it will be
evenly divided into n radii.
kind : "bar" | "linechart" | "circles", default `circles`
Expand Down
Loading
Loading