Skip to content

Commit

Permalink
Typing exploratory submodule.
Browse files Browse the repository at this point in the history
  • Loading branch information
vnmabus committed Sep 2, 2022
1 parent d361529 commit 2f7bdc9
Show file tree
Hide file tree
Showing 18 changed files with 326 additions and 236 deletions.
43 changes: 36 additions & 7 deletions skfda/exploratory/depth/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,38 @@
"""Depth."""
from . import multivariate
from ._depth import (
BandDepth,
DistanceBasedDepth,
IntegratedDepth,
ModifiedBandDepth,

from typing import TYPE_CHECKING

import lazy_loader as lazy

__getattr__, __dir__, __all__ = lazy.attach(
__name__,
submodules=[
"multivariate",
],
submod_attrs={
'_depth': [
"BandDepth",
"DistanceBasedDepth",
"IntegratedDepth",
"ModifiedBandDepth",
],
"multivariate": [
"Depth",
"Outlyingness",
"OutlyingnessBasedDepth",
],
},
)
from .multivariate import Depth, Outlyingness, OutlyingnessBasedDepth

if TYPE_CHECKING:
from ._depth import (
BandDepth as BandDepth,
DistanceBasedDepth as DistanceBasedDepth,
IntegratedDepth as IntegratedDepth,
ModifiedBandDepth as ModifiedBandDepth,
)
from .multivariate import (
Depth as Depth,
Outlyingness as Outlyingness,
OutlyingnessBasedDepth as OutlyingnessBasedDepth,
)
33 changes: 27 additions & 6 deletions skfda/exploratory/outliers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
from ._boxplot import BoxplotOutlierDetector
from ._directional_outlyingness import (
MSPlotOutlierDetector,
directional_outlyingness_stats,
"""Outlier detection methods."""
from typing import TYPE_CHECKING

import lazy_loader as lazy

__getattr__, __dir__, __all__ = lazy.attach(
__name__,
submod_attrs={
'_boxplot': ["BoxplotOutlierDetector"],
"_directional_outlyingness": [
"MSPlotOutlierDetector",
"directional_outlyingness_stats",
],
"_outliergram": ["OutliergramOutlierDetector"],
"neighbors_outlier": ["LocalOutlierFactor"],
},
)
from ._outliergram import OutliergramOutlierDetector
from .neighbors_outlier import LocalOutlierFactor

if TYPE_CHECKING:
from ._boxplot import BoxplotOutlierDetector as BoxplotOutlierDetector
from ._directional_outlyingness import (
MSPlotOutlierDetector as MSPlotOutlierDetector,
directional_outlyingness_stats as directional_outlyingness_stats,
)
from ._outliergram import (
OutliergramOutlierDetector as OutliergramOutlierDetector
)
from .neighbors_outlier import LocalOutlierFactor as LocalOutlierFactor
5 changes: 3 additions & 2 deletions skfda/exploratory/outliers/neighbors_outlier.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,11 +308,12 @@ def fit_predict(
# In this estimator fit_predict cannot be wrapped as fit().predict()

self._estimator = self._init_estimator()
metric = self.metric

if self.metric == 'precomputed':
if metric == 'precomputed':
res = self._estimator.fit_predict(X, y)
else:
X_dist = PairwiseMetric(self.metric)(X)
X_dist = PairwiseMetric(metric)(X)
res = self._estimator.fit_predict(X_dist, y)

self._store_fit_data()
Expand Down
6 changes: 3 additions & 3 deletions skfda/exploratory/stats/_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from scipy import integrate
from scipy.stats import rankdata

from ...misc.metrics import l2_distance
from ...misc.metrics._lp_distances import l2_distance
from ...representation import FData, FDataGrid
from ...typing._metric import Metric
from ...typing._numpy import NDArrayFloat
Expand Down Expand Up @@ -46,7 +46,7 @@ def var(X: FData) -> FDataGrid:
:term:`functional data object` with just one sample.
"""
return X.var()
return X.var() # type: ignore[no-any-return]


def gmean(X: FDataGrid) -> FDataGrid:
Expand Down Expand Up @@ -79,7 +79,7 @@ def cov(X: FData) -> FDataGrid:
:term:`functional data object` with just one sample.
"""
return X.cov()
return X.cov() # type: ignore[no-any-return]


def modified_epigraph_index(X: FDataGrid) -> NDArrayFloat:
Expand Down
40 changes: 31 additions & 9 deletions skfda/exploratory/visualization/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
"""Initialization module of visualization folder."""

from . import clustering, representation
from ._baseplot import BasePlot
from ._boxplot import Boxplot, SurfaceBoxplot
from ._ddplot import DDPlot
from ._magnitude_shape_plot import MagnitudeShapePlot
from ._multiple_display import MultipleDisplay
from ._outliergram import Outliergram
from ._parametric_plot import ParametricPlot
from .fpca import FPCAPlot
from typing import TYPE_CHECKING

import lazy_loader as lazy

__getattr__, __dir__, __all__ = lazy.attach(
__name__,
submodules=[
"clustering",
"representation",
],
submod_attrs={
"_baseplot": ["BasePlot"],
"_boxplot": ["Boxplot", "SurfaceBoxplot"],
"_ddplot": ["DDPlot"],
"_magnitude_shape_plot": ["MagnitudeShapePlot"],
"_multiple_display": ["MultipleDisplay"],
"_outliergram": ["Outliergram"],
"_parametric_plot": ["ParametricPlot"],
"fpca": ["FPCAPlot"],
},
)

if TYPE_CHECKING:
from ._baseplot import BasePlot as BasePlot
from ._boxplot import Boxplot as Boxplot, SurfaceBoxplot as SurfaceBoxplot
from ._ddplot import DDPlot as DDPlot
from ._magnitude_shape_plot import MagnitudeShapePlot as MagnitudeShapePlot
from ._multiple_display import MultipleDisplay as MultipleDisplay
from ._outliergram import Outliergram as Outliergram
from ._parametric_plot import ParametricPlot as ParametricPlot
from .fpca import FPCAPlot as FPCAPlot
43 changes: 23 additions & 20 deletions skfda/exploratory/visualization/_baseplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
the visualization modules, containing the basic functionality
common to all of them.
"""
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Optional, Sequence, Tuple, Union
from typing import Sequence, Tuple

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.artist import Artist
from matplotlib.axes import Axes
from matplotlib.backend_bases import LocationEvent, MouseEvent
Expand All @@ -19,7 +19,7 @@
from matplotlib.text import Annotation

from ...representation import FData
from ...typing._numpy import NDArrayInt
from ...typing._numpy import NDArrayInt, NDArrayObject
from ._utils import _figure_to_svg, _get_figure_and_axes, _set_figure_layout


Expand All @@ -38,18 +38,18 @@ class BasePlot(ABC):
@abstractmethod
def __init__(
self,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
fig: Optional[Figure] = None,
axes: Union[Axes, Sequence[Axes], None] = None,
n_rows: Optional[int] = None,
n_cols: Optional[int] = None,
c: Optional[NDArrayInt] = None,
fig: Figure | None = None,
axes: Axes | Sequence[Axes] | None = None,
n_rows: int | None = None,
n_cols: int | None = None,
c: NDArrayInt | None = None,
cmap_bold: ListedColormap = None,
x_label: Optional[str] = None,
y_label: Optional[str] = None,
x_label: str | None = None,
y_label: str | None = None,
) -> None:
self.artists: Optional[np.ndarray] = None
self.artists: NDArrayObject | None = None
self.chart = chart
self.fig = fig
self.axes = axes
Expand Down Expand Up @@ -78,15 +78,18 @@ def plot(
Figure: figure object in which the displays and
widgets will be plotted.
"""
fig = getattr(self, "fig_", None)
axes = getattr(self, "axes_", None)
fig: Figure | None = getattr(self, "fig_", None)
axes: Sequence[Axes] | None = getattr(self, "axes_", None)

if fig is None:
fig, axes = self._set_figure_and_axes(
self.chart,
fig=self.fig,
axes=self.axes,
)

assert axes is not None

if self.x_label is not None:
axes[0].set_xlabel(self.x_label)
if self.y_label is not None:
Expand All @@ -112,16 +115,16 @@ def n_subplots(self) -> int:
return 1

@property
def n_samples(self) -> Optional[int]:
def n_samples(self) -> int | None:
"""Get the number of instances that will be used for interactivity."""
return None

def _set_figure_and_axes(
self,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
fig: Optional[Figure] = None,
axes: Union[Axes, Sequence[Axes], None] = None,
fig: Figure | None = None,
axes: Axes | Sequence[Axes] | None = None,
) -> Tuple[Figure, Sequence[Axes]]:
fig, axes = _get_figure_and_axes(chart, fig, axes)
fig, axes = _set_figure_layout(
Expand Down Expand Up @@ -173,7 +176,7 @@ def _update_annotation(
*,
axes: Axes,
sample_number: int,
fdata: Optional[FData],
fdata: FData | None,
position: Tuple[float, float],
) -> None:
"""
Expand Down Expand Up @@ -226,7 +229,7 @@ def _update_annotation(
def _sample_artist_from_event(
self,
event: LocationEvent,
) -> Optional[Tuple[int, Optional[FData], Artist]]:
) -> Tuple[int, FData | None, Artist] | None:
"""Get the number, fdata and artist under a location event."""
if self.artists is None:
return None
Expand Down
41 changes: 20 additions & 21 deletions skfda/exploratory/visualization/_boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@

import math
from abc import abstractmethod
from typing import Optional, Sequence, Tuple, Union
from typing import Sequence, Tuple

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.artist import Artist
from matplotlib.axes import Axes
from matplotlib.colors import Colormap
from matplotlib.figure import Figure
Expand Down Expand Up @@ -45,13 +44,13 @@ class FDataBoxplot(BasePlot):
@abstractmethod
def __init__(
self,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
factor: float = 1.5,
fig: Optional[Figure] = None,
axes: Optional[Axes] = None,
n_rows: Optional[int] = None,
n_cols: Optional[int] = None,
fig: Figure | None = None,
axes: Axes | None = None,
n_rows: int | None = None,
n_cols: int | None = None,
) -> None:
if factor < 0:
raise ValueError(
Expand Down Expand Up @@ -269,15 +268,15 @@ class Boxplot(FDataBoxplot):
def __init__(
self,
fdatagrid: FData,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
depth_method: Optional[Depth[FDataGrid]] = None,
depth_method: Depth[FDataGrid] | None = None,
prob: Sequence[float] = (0.5,),
factor: float = 1.5,
fig: Optional[Figure] = None,
axes: Optional[Axes] = None,
n_rows: Optional[int] = None,
n_cols: Optional[int] = None,
fig: Figure | None = None,
axes: Axes | None = None,
n_rows: int | None = None,
n_cols: int | None = None,
):
"""Initialize the Boxplot class.
Expand Down Expand Up @@ -389,7 +388,7 @@ def fdatagrid(self) -> FDataGrid:

@property
def median(self) -> NDArrayFloat:
return self._median
return self._median # type: ignore[no-any-return]

@property
def central_envelope(self) -> Tuple[NDArrayFloat, NDArrayFloat]:
Expand Down Expand Up @@ -648,14 +647,14 @@ class SurfaceBoxplot(FDataBoxplot):
def __init__(
self,
fdatagrid: FDataGrid,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
depth_method: Optional[Depth[FDataGrid]] = None,
depth_method: Depth[FDataGrid] | None = None,
factor: float = 1.5,
fig: Optional[Figure] = None,
axes: Optional[Axes] = None,
n_rows: Optional[int] = None,
n_cols: Optional[int] = None,
fig: Figure | None = None,
axes: Axes | None = None,
n_rows: int | None = None,
n_cols: int | None = None,
) -> None:

super().__init__(
Expand Down Expand Up @@ -712,7 +711,7 @@ def fdatagrid(self) -> FDataGrid:

@property
def median(self) -> NDArrayFloat:
return self._median
return self._median # type: ignore[no-any-return]

@property
def central_envelope(self) -> Tuple[NDArrayFloat, NDArrayFloat]:
Expand Down
11 changes: 6 additions & 5 deletions skfda/exploratory/visualization/_ddplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
To do this depth is calculated for the two chosen distributions, and then
a scatter plot is created of this two variables.
"""
from __future__ import annotations

from typing import Optional, TypeVar, Union
from typing import TypeVar

import numpy as np
from matplotlib.artist import Artist
Expand Down Expand Up @@ -56,12 +57,12 @@ def __init__(
fdata: T,
dist1: T,
dist2: T,
chart: Union[Figure, Axes, None] = None,
chart: Figure | Axes | None = None,
*,
depth_method: Depth[T],
fig: Optional[Figure] = None,
axes: Optional[Axes] = None,
c: Optional[NDArrayInt] = None,
fig: Figure | None = None,
axes: Axes | None = None,
c: NDArrayInt | None = None,
cmap_bold: ListedColormap = None,
x_label: str = "X depth",
y_label: str = "Y depth",
Expand Down
Loading

0 comments on commit 2f7bdc9

Please sign in to comment.