misato 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- misato/__init__.py +79 -0
- misato/_core/__init__.py +6 -0
- misato/_core/binning.py +31 -0
- misato/_core/formatting.py +26 -0
- misato/_core/i18n.py +36 -0
- misato/_core/kinds.py +37 -0
- misato/_core/optional.py +31 -0
- misato/_core/registry.py +46 -0
- misato/_core/sampling.py +28 -0
- misato/_core/tables.py +26 -0
- misato/_core/transforms.py +56 -0
- misato/_core/types.py +16 -0
- misato/_core/validation.py +64 -0
- misato/cache.py +117 -0
- misato/config/__init__.py +11 -0
- misato/config/defaults.py +104 -0
- misato/config/locales/en.toml +205 -0
- misato/config/locales/es.toml +205 -0
- misato/config/options.py +70 -0
- misato/config/palettes.py +141 -0
- misato/config/theme.py +233 -0
- misato/diagnostics/__init__.py +33 -0
- misato/diagnostics/multicollinearity.py +139 -0
- misato/diagnostics/pca.py +156 -0
- misato/diagnostics/regression.py +355 -0
- misato/evaluation/__init__.py +19 -0
- misato/evaluation/cross_validation.py +607 -0
- misato/geo/__init__.py +33 -0
- misato/geo/checks.py +64 -0
- misato/geo/distances.py +56 -0
- misato/geo/maps.py +162 -0
- misato/geo/regions.py +29 -0
- misato/interactive/__init__.py +19 -0
- misato/interactive/_base.py +22 -0
- misato/interactive/conditional.py +201 -0
- misato/interactive/influence.py +60 -0
- misato/interactive/joint.py +195 -0
- misato/plots/__init__.py +75 -0
- misato/plots/_annotate.py +47 -0
- misato/plots/_base.py +193 -0
- misato/plots/_normality.py +383 -0
- misato/plots/categorical.py +362 -0
- misato/plots/comparison.py +130 -0
- misato/plots/correlation.py +261 -0
- misato/plots/diagnostics.py +303 -0
- misato/plots/distribution.py +293 -0
- misato/plots/evaluation.py +345 -0
- misato/plots/intervals.py +146 -0
- misato/plots/missing.py +40 -0
- misato/py.typed +0 -0
- misato/stats/__init__.py +29 -0
- misato/stats/association.py +577 -0
- misato/stats/correlation.py +68 -0
- misato/stats/intervals.py +118 -0
- misato/stats/normality.py +299 -0
- misato/stats/probability.py +104 -0
- misato/stats/relevance.py +90 -0
- misato-0.1.0.dist-info/METADATA +149 -0
- misato-0.1.0.dist-info/RECORD +61 -0
- misato-0.1.0.dist-info/WHEEL +4 -0
- misato-0.1.0.dist-info/licenses/LICENSE +21 -0
misato/__init__.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""misato: exploratory data analysis, statistical tests and model diagnostics.
|
|
2
|
+
|
|
3
|
+
Subpackages load on first use, so ``import misato`` stays light:
|
|
4
|
+
|
|
5
|
+
- :mod:`misato.plots` static charts (matplotlib / seaborn)
|
|
6
|
+
- :mod:`misato.stats` statistical tests and association measures
|
|
7
|
+
- :mod:`misato.diagnostics` multicollinearity, OLS diagnostics, PCA
|
|
8
|
+
- :mod:`misato.evaluation` cross-validated classifier evaluation (extra ``ml``)
|
|
9
|
+
- :mod:`misato.interactive` interactive charts (extra ``interactive``)
|
|
10
|
+
- :mod:`misato.geo` coordinate checks, distances and maps (extra ``geo``)
|
|
11
|
+
- :mod:`misato.cache` disk cache for slow computations
|
|
12
|
+
- :mod:`misato.config` options, theme, palettes, thresholds, locales
|
|
13
|
+
|
|
14
|
+
Examples
|
|
15
|
+
--------
|
|
16
|
+
>>> import misato as ms
|
|
17
|
+
>>> ms.set_option("locale", "en") # figure text in English (default "es")
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import importlib
|
|
23
|
+
from typing import TYPE_CHECKING, Any
|
|
24
|
+
|
|
25
|
+
from misato.config import get_option, option_context, reset_option, set_option
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
|
|
29
|
+
_SUBPACKAGES = frozenset(
|
|
30
|
+
{
|
|
31
|
+
"cache",
|
|
32
|
+
"config",
|
|
33
|
+
"diagnostics",
|
|
34
|
+
"evaluation",
|
|
35
|
+
"geo",
|
|
36
|
+
"interactive",
|
|
37
|
+
"plots",
|
|
38
|
+
"stats",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"__version__",
|
|
44
|
+
"cache",
|
|
45
|
+
"config",
|
|
46
|
+
"diagnostics",
|
|
47
|
+
"evaluation",
|
|
48
|
+
"geo",
|
|
49
|
+
"get_option",
|
|
50
|
+
"interactive",
|
|
51
|
+
"option_context",
|
|
52
|
+
"plots",
|
|
53
|
+
"reset_option",
|
|
54
|
+
"set_option",
|
|
55
|
+
"stats",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def __getattr__(name: str) -> Any:
|
|
60
|
+
if name in _SUBPACKAGES:
|
|
61
|
+
return importlib.import_module(f"misato.{name}")
|
|
62
|
+
raise AttributeError(f"module 'misato' has no attribute {name!r}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def __dir__() -> list[str]:
|
|
66
|
+
return sorted(__all__)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if TYPE_CHECKING:
|
|
70
|
+
from misato import (
|
|
71
|
+
cache,
|
|
72
|
+
config,
|
|
73
|
+
diagnostics,
|
|
74
|
+
evaluation,
|
|
75
|
+
geo,
|
|
76
|
+
interactive,
|
|
77
|
+
plots,
|
|
78
|
+
stats,
|
|
79
|
+
)
|
misato/_core/__init__.py
ADDED
misato/_core/binning.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Histogram binning shared by every chart that bins a numeric variable.
|
|
2
|
+
|
|
3
|
+
Layer: core. Pure numpy.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from misato.config.defaults import MAX_BINS, MIN_BINS
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def default_bins(
|
|
14
|
+
values: np.ndarray, min_bins: int = MIN_BINS, max_bins: int = MAX_BINS
|
|
15
|
+
) -> int:
|
|
16
|
+
"""Freedman-Diaconis bin count, clipped to ``[min_bins, max_bins]``.
|
|
17
|
+
|
|
18
|
+
When the interquartile range or the full range is zero (near-constant
|
|
19
|
+
columns) the rule is undefined and the square root of n is used.
|
|
20
|
+
"""
|
|
21
|
+
q1, q3 = np.percentile(values, [25, 75])
|
|
22
|
+
iqr, spread = q3 - q1, values.max() - values.min()
|
|
23
|
+
if iqr <= 0 or spread <= 0:
|
|
24
|
+
return int(np.clip(np.sqrt(values.size), min_bins, max_bins))
|
|
25
|
+
width = 2.0 * iqr * values.size ** (-1 / 3)
|
|
26
|
+
return int(np.clip(np.ceil(spread / width), min_bins, max_bins))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def bin_edges(values: np.ndarray, n_bins: int | None = None) -> np.ndarray:
|
|
30
|
+
"""Bin edges over ``values``; an explicit ``n_bins`` overrides the rule."""
|
|
31
|
+
return np.histogram_bin_edges(values, bins=n_bins or default_bins(values))
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Text formatting for labels, ticks and annotations.
|
|
2
|
+
|
|
3
|
+
Layer: core.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Hashable
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def pretty(name: Hashable) -> str:
|
|
12
|
+
"""A column name as a readable label: ``"property_type"`` -> ``"Property Type"``."""
|
|
13
|
+
return str(name).replace("_", " ").title()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
#: Unit suffixes written on their own line in axis labels:
|
|
17
|
+
#: ``"bill_mm"`` -> ``"bill"`` and ``"(mm)"`` on the next line.
|
|
18
|
+
UNIT_SUFFIXES = {"_mm": "\n(mm)", "_g": "\n(g)"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unit_label(name: Hashable) -> str:
|
|
22
|
+
"""A column name with a known unit suffix moved to its own line."""
|
|
23
|
+
text = str(name)
|
|
24
|
+
for suffix, label in UNIT_SUFFIXES.items():
|
|
25
|
+
text = text.replace(suffix, label)
|
|
26
|
+
return text
|
misato/_core/i18n.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Translation of user-facing text.
|
|
2
|
+
|
|
3
|
+
Layer: core. Strings live in ``config/locales/<locale>.toml`` as
|
|
4
|
+
``[section] key = "template"``; :func:`t` formats the template of the active
|
|
5
|
+
``locale`` option and falls back to English for a key a locale lacks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import tomllib
|
|
11
|
+
from functools import cache
|
|
12
|
+
from importlib.resources import files
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from misato.config import get_option
|
|
16
|
+
|
|
17
|
+
FALLBACK = "en"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@cache
|
|
21
|
+
def _table(locale: str) -> dict[str, dict[str, str]]:
|
|
22
|
+
source = files("misato.config").joinpath("locales", f"{locale}.toml")
|
|
23
|
+
return tomllib.loads(source.read_text(encoding="utf-8"))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _lookup(locale: str, key: str) -> str | None:
|
|
27
|
+
section, _, name = key.partition(".")
|
|
28
|
+
return _table(locale).get(section, {}).get(name)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def t(key: str, **values: Any) -> str:
|
|
32
|
+
"""The text for ``key`` (``"section.name"``) in the active locale."""
|
|
33
|
+
template = _lookup(get_option("locale"), key) or _lookup(FALLBACK, key)
|
|
34
|
+
if template is None:
|
|
35
|
+
raise KeyError(f"no text for {key!r} in any locale")
|
|
36
|
+
return template.format(**values)
|
misato/_core/kinds.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Variable-kind resolution: categorical, discrete or continuous.
|
|
2
|
+
|
|
3
|
+
Layer: core. Every test that chooses its method from the kind of a column
|
|
4
|
+
reads it from here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Literal, get_args
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
Kind = Literal["categorical", "discrete", "continuous"]
|
|
15
|
+
KINDS: tuple[str, ...] = get_args(Kind)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def infer_kind(values: pd.Series, max_categories: int) -> Kind:
|
|
19
|
+
"""Classify a column, in order of precedence.
|
|
20
|
+
|
|
21
|
+
Non-numeric or boolean -> ``categorical``; whole numbers with at most
|
|
22
|
+
``max_categories`` distinct values -> ``categorical`` (codes such as
|
|
23
|
+
1-8 are labels, not quantities); other whole numbers -> ``discrete``;
|
|
24
|
+
anything with decimals -> ``continuous``.
|
|
25
|
+
"""
|
|
26
|
+
values = values.dropna()
|
|
27
|
+
if (
|
|
28
|
+
not pd.api.types.is_numeric_dtype(values)
|
|
29
|
+
or pd.api.types.is_bool_dtype(values)
|
|
30
|
+
or values.empty
|
|
31
|
+
):
|
|
32
|
+
return "categorical"
|
|
33
|
+
numbers = values.to_numpy(dtype=float)
|
|
34
|
+
whole = np.all(np.isfinite(numbers)) and np.all(np.equal(np.mod(numbers, 1), 0))
|
|
35
|
+
if whole:
|
|
36
|
+
return "categorical" if values.nunique() <= max_categories else "discrete"
|
|
37
|
+
return "continuous"
|
misato/_core/optional.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Lazy import of optional dependencies.
|
|
2
|
+
|
|
3
|
+
Layer: core. A function needing an extra calls :func:`require` when it runs,
|
|
4
|
+
so ``import misato`` works without the extra and a missing one fails with
|
|
5
|
+
the command that installs it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
from types import ModuleType
|
|
12
|
+
|
|
13
|
+
#: The extra that provides each optional top-level module.
|
|
14
|
+
EXTRAS: dict[str, str] = {
|
|
15
|
+
"sklearn": "ml",
|
|
16
|
+
"plotly": "interactive",
|
|
17
|
+
"folium": "geo",
|
|
18
|
+
"IPython": "geo",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def require(module: str) -> ModuleType:
|
|
23
|
+
"""Import ``module`` or raise ``ImportError`` naming the extra to install."""
|
|
24
|
+
try:
|
|
25
|
+
return importlib.import_module(module)
|
|
26
|
+
except ImportError as exc:
|
|
27
|
+
extra = EXTRAS.get(module.split(".")[0], "all")
|
|
28
|
+
raise ImportError(
|
|
29
|
+
f"{module!r} is needed for this function; install it with "
|
|
30
|
+
f'pip install "misato[{extra}]"'
|
|
31
|
+
) from exc
|
misato/_core/registry.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Name-to-strategy registry for interchangeable algorithms.
|
|
2
|
+
|
|
3
|
+
Layer: core. Statistical tests and measures register under a name, so a
|
|
4
|
+
public function selects one with a string and adding a method means adding
|
|
5
|
+
one registered function.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from typing import Generic, TypeVar
|
|
12
|
+
|
|
13
|
+
F = TypeVar("F", bound=Callable[..., object])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Registry(Generic[F]):
|
|
17
|
+
"""Strategies of one kind, looked up by name."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, kind: str) -> None:
|
|
20
|
+
self.kind = kind
|
|
21
|
+
self._items: dict[str, F] = {}
|
|
22
|
+
|
|
23
|
+
def register(self, name: str) -> Callable[[F], F]:
|
|
24
|
+
"""Decorator adding a strategy under ``name``."""
|
|
25
|
+
|
|
26
|
+
def add(fn: F) -> F:
|
|
27
|
+
if name in self._items:
|
|
28
|
+
raise ValueError(f"{self.kind} {name!r} is already registered")
|
|
29
|
+
self._items[name] = fn
|
|
30
|
+
return fn
|
|
31
|
+
|
|
32
|
+
return add
|
|
33
|
+
|
|
34
|
+
def get(self, name: str) -> F:
|
|
35
|
+
"""The strategy registered as ``name``; ``ValueError`` lists the options."""
|
|
36
|
+
try:
|
|
37
|
+
return self._items[name]
|
|
38
|
+
except KeyError:
|
|
39
|
+
options = ", ".join(map(repr, self._items))
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"{self.kind} must be one of {options}, got {name!r}"
|
|
42
|
+
) from None
|
|
43
|
+
|
|
44
|
+
def names(self) -> tuple[str, ...]:
|
|
45
|
+
"""Registered names, in registration order."""
|
|
46
|
+
return tuple(self._items)
|
misato/_core/sampling.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Reproducible randomness for drawing.
|
|
2
|
+
|
|
3
|
+
Layer: core.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@contextmanager
|
|
15
|
+
def seeded_global_rng(seed: int) -> Iterator[None]:
|
|
16
|
+
"""Seed numpy's global RNG for a block and restore its previous state after.
|
|
17
|
+
|
|
18
|
+
For third-party code (seaborn's strip-plot jitter) that draws from the
|
|
19
|
+
global RNG and takes no seed: output becomes reproducible without leaving
|
|
20
|
+
the caller's random state changed.
|
|
21
|
+
"""
|
|
22
|
+
# The global RNG is the point: it is what the third-party code draws from.
|
|
23
|
+
state = np.random.get_state() # noqa: NPY002
|
|
24
|
+
np.random.seed(seed) # noqa: NPY002
|
|
25
|
+
try:
|
|
26
|
+
yield
|
|
27
|
+
finally:
|
|
28
|
+
np.random.set_state(state) # noqa: NPY002
|
misato/_core/tables.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Frequency tables and the percentages charts draw from them.
|
|
2
|
+
|
|
3
|
+
Layer: core. Pure pandas: no plotting.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from misato._core.types import Along
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def shares(table: pd.DataFrame, along: Along) -> pd.DataFrame:
|
|
15
|
+
"""Each cell as a percentage of its row total, column total or grand total.
|
|
16
|
+
|
|
17
|
+
A total of zero yields NaN for its cells; callers decide how to show it.
|
|
18
|
+
"""
|
|
19
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
20
|
+
if along == "rows":
|
|
21
|
+
ratio = table.div(table.sum(axis=1), axis=0)
|
|
22
|
+
elif along == "columns":
|
|
23
|
+
ratio = table.div(table.sum(axis=0), axis=1)
|
|
24
|
+
else:
|
|
25
|
+
ratio = table.div(float(table.to_numpy().sum()))
|
|
26
|
+
return ratio.mul(100)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Log transformations of values that may contain zeros or negatives.
|
|
2
|
+
|
|
3
|
+
Layer: core. Pure numpy. Labels are mathematical notation, identical in
|
|
4
|
+
every locale, so they are written here rather than in the locale files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Literal, get_args
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from misato.config.defaults import MIN_N
|
|
15
|
+
|
|
16
|
+
#: How values ``<= 0`` are handled by :func:`log_transform`.
|
|
17
|
+
NegStrategy = Literal["shift", "signed", "drop"]
|
|
18
|
+
NEG_STRATEGIES: tuple[str, ...] = get_args(NegStrategy)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Transformed:
|
|
23
|
+
"""Transformed values, the formula applied, and how many rows were dropped."""
|
|
24
|
+
|
|
25
|
+
data: np.ndarray
|
|
26
|
+
label: str
|
|
27
|
+
n_dropped: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def log_transform(values: np.ndarray, strategy: NegStrategy) -> Transformed:
|
|
31
|
+
"""``log10`` of ``values``, applying ``strategy`` when any value is ``<= 0``.
|
|
32
|
+
|
|
33
|
+
``"shift"`` uses ``log10(x - min + 1)`` and keeps every row; ``"signed"``
|
|
34
|
+
uses ``sign(x)·log10(1+|x|)``; ``"drop"`` discards every ``x <= 0``
|
|
35
|
+
(zeros included). The strategy is chosen by name, never special-casing
|
|
36
|
+
zeros, which would turn them into artificial outliers.
|
|
37
|
+
"""
|
|
38
|
+
low = values.min()
|
|
39
|
+
if low > 0:
|
|
40
|
+
return Transformed(np.log10(values), "log(x)", 0)
|
|
41
|
+
if strategy == "drop":
|
|
42
|
+
positive = values[values > 0]
|
|
43
|
+
if positive.size < MIN_N:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"only {positive.size} positive values remain after 'drop' "
|
|
46
|
+
f"(minimum {MIN_N})"
|
|
47
|
+
)
|
|
48
|
+
return Transformed(
|
|
49
|
+
np.log10(positive), "log(x), x>0", int(values.size - positive.size)
|
|
50
|
+
)
|
|
51
|
+
if strategy == "signed":
|
|
52
|
+
return Transformed(
|
|
53
|
+
np.sign(values) * np.log10(1.0 + np.abs(values)), "sign(x)·log(1+|x|)", 0
|
|
54
|
+
)
|
|
55
|
+
label = "log(x + 1)" if low == 0 else f"log(x - min + 1) [min={low:,.4g}]"
|
|
56
|
+
return Transformed(np.log10(values - low + 1.0), label, 0)
|
misato/_core/types.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Shared type aliases.
|
|
2
|
+
|
|
3
|
+
Layer: core. Each ``Literal`` has a matching tuple of its values, so
|
|
4
|
+
validation and typing read the same decision.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Literal, get_args
|
|
10
|
+
|
|
11
|
+
#: What to write on top of each bar.
|
|
12
|
+
Labels = Literal["none", "count", "pct", "both"]
|
|
13
|
+
LABELS: tuple[str, ...] = get_args(Labels)
|
|
14
|
+
|
|
15
|
+
#: Which total a percentage is taken over in a two-way table.
|
|
16
|
+
Along = Literal["rows", "columns", "all"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Input validation shared by every public function.
|
|
2
|
+
|
|
3
|
+
Layer: core. Public functions check their inputs here, where data enters,
|
|
4
|
+
and trust them afterwards.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Collection, Hashable, Iterable
|
|
10
|
+
from difflib import get_close_matches
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def require_columns(df: pd.DataFrame, *columns: Hashable) -> None:
|
|
17
|
+
"""Raise ``KeyError`` naming any column ``df`` lacks, with suggestions."""
|
|
18
|
+
known = [str(c) for c in df.columns]
|
|
19
|
+
for column in columns:
|
|
20
|
+
if column in df.columns:
|
|
21
|
+
continue
|
|
22
|
+
close = get_close_matches(str(column), known, n=3)
|
|
23
|
+
hint = f"; did you mean {', '.join(map(repr, close))}?" if close else ""
|
|
24
|
+
raise KeyError(f"column {column!r} is not in the DataFrame{hint}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def require_choice(name: str, value: object, choices: Collection[object]) -> None:
|
|
28
|
+
"""Raise ``ValueError`` when ``value`` is not one of ``choices``."""
|
|
29
|
+
if value not in choices:
|
|
30
|
+
options = ", ".join(map(repr, choices))
|
|
31
|
+
raise ValueError(f"{name} must be one of {options}, got {value!r}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def require_positive_int(name: str, value: object) -> None:
|
|
35
|
+
"""Raise ``ValueError`` unless ``value`` is a positive ``int``."""
|
|
36
|
+
if not isinstance(value, int) or isinstance(value, bool) or value < 1:
|
|
37
|
+
raise ValueError(f"{name} must be a positive integer, got {value!r}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def numeric_values(df: pd.DataFrame, column: Hashable) -> np.ndarray:
|
|
41
|
+
"""The finite values of a numeric column as floats, ready to bin.
|
|
42
|
+
|
|
43
|
+
Raises ``TypeError`` for a non-numeric column and ``ValueError`` when no
|
|
44
|
+
finite value is left.
|
|
45
|
+
"""
|
|
46
|
+
require_columns(df, column)
|
|
47
|
+
series = df[column]
|
|
48
|
+
if not pd.api.types.is_numeric_dtype(series):
|
|
49
|
+
raise TypeError(
|
|
50
|
+
f"column {column!r} is not numeric (dtype {series.dtype}); "
|
|
51
|
+
"use a categorical chart instead"
|
|
52
|
+
)
|
|
53
|
+
values = pd.to_numeric(series, errors="coerce").to_numpy(dtype=float)
|
|
54
|
+
values = values[np.isfinite(values)]
|
|
55
|
+
if values.size == 0:
|
|
56
|
+
raise ValueError(f"column {column!r} has no finite values")
|
|
57
|
+
return values
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def column_list(columns: Hashable | Iterable[Hashable]) -> list[Hashable]:
|
|
61
|
+
"""One column name or an iterable of names, as a list of names."""
|
|
62
|
+
if isinstance(columns, str) or not isinstance(columns, Iterable):
|
|
63
|
+
return [columns]
|
|
64
|
+
return list(columns)
|
misato/cache.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Disk cache for slow computations: the package's only caching mechanism.
|
|
2
|
+
|
|
3
|
+
Layer: utility (depends on ``config`` only).
|
|
4
|
+
|
|
5
|
+
``cached`` stores a function's return value in a ``.pkl`` file and loads it
|
|
6
|
+
back when the function is called again with the same inputs. DataFrames
|
|
7
|
+
and Series are hashed by content, so a frame loaded from a pickle hits the
|
|
8
|
+
same entry as the frame it was saved from.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import functools
|
|
14
|
+
import inspect
|
|
15
|
+
import logging
|
|
16
|
+
from collections.abc import Callable, Iterable
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, ParamSpec, TypeVar
|
|
19
|
+
|
|
20
|
+
import joblib
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
from misato.config import get_option
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
P = ParamSpec("P")
|
|
28
|
+
R = TypeVar("R")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _content(obj: Any) -> Any:
|
|
32
|
+
"""Replace pandas objects by their values, so equal data hashes equal.
|
|
33
|
+
|
|
34
|
+
``joblib.hash`` pickles a DataFrame's internal block layout, which differs
|
|
35
|
+
between a frame just computed and the same frame loaded from a ``.pkl``.
|
|
36
|
+
Hashing values, labels and dtypes keeps the key stable.
|
|
37
|
+
"""
|
|
38
|
+
if isinstance(obj, pd.DataFrame | pd.Series):
|
|
39
|
+
frame = obj.to_frame() if isinstance(obj, pd.Series) else obj
|
|
40
|
+
return (
|
|
41
|
+
type(obj).__name__,
|
|
42
|
+
list(frame.columns),
|
|
43
|
+
[str(t) for t in frame.dtypes],
|
|
44
|
+
pd.util.hash_pandas_object(frame, index=True).to_numpy(),
|
|
45
|
+
)
|
|
46
|
+
if isinstance(obj, list | tuple):
|
|
47
|
+
return type(obj)(_content(o) for o in obj)
|
|
48
|
+
if isinstance(obj, dict):
|
|
49
|
+
return {k: _content(v) for k, v in obj.items()}
|
|
50
|
+
return obj
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def content_hash(*objs: Any) -> str:
|
|
54
|
+
"""``joblib.hash`` of ``objs``, with DataFrames and Series hashed by content."""
|
|
55
|
+
return str(joblib.hash(_content(objs)))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _source(func: Callable[..., Any]) -> str:
|
|
59
|
+
"""The function's source, or its qualified name when there is none."""
|
|
60
|
+
try:
|
|
61
|
+
return inspect.getsource(func)
|
|
62
|
+
except (OSError, TypeError):
|
|
63
|
+
return f"{func.__module__}.{func.__qualname__}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cached(
|
|
67
|
+
*,
|
|
68
|
+
cache_dir: str | Path | None = None,
|
|
69
|
+
watch: Iterable[str | Path] = (),
|
|
70
|
+
label: str | None = None,
|
|
71
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
72
|
+
"""Cache the return value of the decorated function on disk.
|
|
73
|
+
|
|
74
|
+
The result goes to ``<cache_dir>/<label>_<key>.pkl``; the key hashes the
|
|
75
|
+
function's source, every argument and the bytes of each file in
|
|
76
|
+
``watch``. Change any of them and the next call recomputes; change them
|
|
77
|
+
back and the older file is found again. ``cache_dir`` defaults to the
|
|
78
|
+
``cache_dir`` option. Call the decorated function with
|
|
79
|
+
``force_rerun=True`` to recompute and overwrite, e.g. after editing a
|
|
80
|
+
helper it calls (helpers are not part of the key).
|
|
81
|
+
|
|
82
|
+
Examples
|
|
83
|
+
--------
|
|
84
|
+
>>> @cached(cache_dir="cv_cache", watch=["pipeline_steps.py"])
|
|
85
|
+
... def fit_report(pipeline, X, y): ...
|
|
86
|
+
>>> from misato.diagnostics.multicollinearity import vif
|
|
87
|
+
>>> cached_vif = cached()(vif)
|
|
88
|
+
"""
|
|
89
|
+
watched = [Path(p) for p in watch]
|
|
90
|
+
|
|
91
|
+
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
92
|
+
prefix = label or func.__name__
|
|
93
|
+
source = _source(func)
|
|
94
|
+
|
|
95
|
+
@functools.wraps(func)
|
|
96
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
97
|
+
force_rerun = bool(kwargs.pop("force_rerun", False))
|
|
98
|
+
folder = Path(
|
|
99
|
+
cache_dir if cache_dir is not None else get_option("cache_dir")
|
|
100
|
+
)
|
|
101
|
+
files = [p.read_bytes() for p in watched]
|
|
102
|
+
key = content_hash(prefix, source, args, kwargs, files)
|
|
103
|
+
path = folder / f"{prefix}_{key}.pkl"
|
|
104
|
+
if path.exists() and not force_rerun:
|
|
105
|
+
log.info("loaded %s from the cache: %s", prefix, path)
|
|
106
|
+
result: R = joblib.load(path)
|
|
107
|
+
return result
|
|
108
|
+
log.info("computing %s (no cache entry or inputs changed)", prefix)
|
|
109
|
+
result = func(*args, **kwargs)
|
|
110
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
joblib.dump(result, path)
|
|
112
|
+
log.info("saved %s to %s", prefix, path)
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
return wrapper
|
|
116
|
+
|
|
117
|
+
return decorator
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Settings: the only place configurable values live.
|
|
2
|
+
|
|
3
|
+
Layer: config (bottom layer, imports nothing from the rest of misato).
|
|
4
|
+
|
|
5
|
+
No other module defines a colour, size, threshold or user-facing sentence;
|
|
6
|
+
they read it from here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from misato.config.options import get_option, option_context, reset_option, set_option
|
|
10
|
+
|
|
11
|
+
__all__ = ["get_option", "option_context", "reset_option", "set_option"]
|