spec-agents-statistics 0.2.1__tar.gz
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.
- spec_agents_statistics-0.2.1/.gitignore +11 -0
- spec_agents_statistics-0.2.1/CHANGELOG.md +28 -0
- spec_agents_statistics-0.2.1/LICENSE +21 -0
- spec_agents_statistics-0.2.1/PKG-INFO +60 -0
- spec_agents_statistics-0.2.1/README.md +32 -0
- spec_agents_statistics-0.2.1/pyproject.toml +60 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/__init__.py +16 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/app.py +86 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/__init__.py +6 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/base.py +47 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/descriptive.py +121 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/inferential.py +404 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/multivariate.py +317 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/components/temporal.py +186 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/domain.py +29 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/py.typed +0 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/rules.py +104 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/schemas.py +24 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/anova/SKILL.md +54 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/clustering/SKILL.md +54 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/experiment_analysis/SKILL.md +43 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/exploratory_analysis/SKILL.md +42 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/full_study/SKILL.md +31 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/linear_model/SKILL.md +64 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/pca/SKILL.md +54 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/pca/references/interpretation_examples.md +9 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/summary/SKILL.md +46 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/skills/time_series/SKILL.md +49 -0
- spec_agents_statistics-0.2.1/src/stat_fabric/testing.py +40 -0
- spec_agents_statistics-0.2.1/tests/conftest.py +21 -0
- spec_agents_statistics-0.2.1/tests/test_stats_domain.py +166 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.2.1](https://github.com/marcionicolau/spec-agents/compare/statistics-v0.2.0...statistics-v0.2.1) (2026-10-02)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* document the spec-agents-* distribution names in the package READMEs ([#96](https://github.com/marcionicolau/spec-agents/issues/96)) ([fffad88](https://github.com/marcionicolau/spec-agents/commit/fffad88e5c8405bb01c7d9dddf66b7cf52a13e28)), closes [#76](https://github.com/marcionicolau/spec-agents/issues/76)
|
|
9
|
+
|
|
10
|
+
## [0.2.0](https://github.com/marcionicolau/spec-agents/compare/statistics-v0.1.0...statistics-v0.2.0) (2026-10-02)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Features
|
|
14
|
+
|
|
15
|
+
* **agent-fabric:** core/pack API level contract ([#75](https://github.com/marcionicolau/spec-agents/issues/75)) ([d880a74](https://github.com/marcionicolau/spec-agents/commit/d880a744481b888e1e435a1c0d482e44fa942e03)), closes [#20](https://github.com/marcionicolau/spec-agents/issues/20)
|
|
16
|
+
* **agent-fabric:** define the public API surface with __all__, fix __version__ ([#57](https://github.com/marcionicolau/spec-agents/issues/57)) ([c9ab564](https://github.com/marcionicolau/spec-agents/commit/c9ab56432fb2e95c5f1a1ebd9428a23c42b9d89f)), closes [#56](https://github.com/marcionicolau/spec-agents/issues/56)
|
|
17
|
+
|
|
18
|
+
## [0.1.0](https://github.com/marcionicolau/spec-agents/compare/statistics-v0.0.1...statistics-v0.1.0) (2026-10-01)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
### Features
|
|
22
|
+
|
|
23
|
+
* **agent-fabric:** enforce architecture boundaries and type-check the core; fix live view crash ([#38](https://github.com/marcionicolau/spec-agents/issues/38)) ([45b277f](https://github.com/marcionicolau/spec-agents/commit/45b277f586b14bf966d13f3eaacb66df52f5649b))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Bug Fixes
|
|
27
|
+
|
|
28
|
+
* **statistics:** warn on perfect collinearity with inf VIF; ci: require lowest-versions job ([#35](https://github.com/marcionicolau/spec-agents/issues/35)) ([e1502a1](https://github.com/marcionicolau/spec-agents/commit/e1502a1a7d0cfb65dd65e6087843ae6bddc4a378))
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marcio Nicolau
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: spec-agents-statistics
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Statistics domain pack for agent-fabric: summary, linear_model, anova, time_series, pca, clustering
|
|
5
|
+
Project-URL: Homepage, https://github.com/marcionicolau/spec-agents
|
|
6
|
+
Project-URL: Repository, https://github.com/marcionicolau/spec-agents
|
|
7
|
+
Project-URL: Issues, https://github.com/marcionicolau/spec-agents/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/marcionicolau/spec-agents/blob/main/packages/statistics/CHANGELOG.md
|
|
9
|
+
Project-URL: Documentation, https://github.com/marcionicolau/spec-agents/tree/main/docs
|
|
10
|
+
Author: Marcio Nicolau
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agents,pandas,statistics
|
|
14
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Requires-Dist: pandas>=2.1
|
|
23
|
+
Requires-Dist: scikit-learn>=1.4
|
|
24
|
+
Requires-Dist: scipy>=1.12
|
|
25
|
+
Requires-Dist: spec-agents-core<1,>=0.0.1
|
|
26
|
+
Requires-Dist: statsmodels>=0.14.2
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# spec-agents-statistics (`stat_fabric`)
|
|
30
|
+
|
|
31
|
+
Statistics domain pack for [agent-fabric](../agent-fabric/README.md): deterministic components `summary`, `linear_model`, `anova`,
|
|
32
|
+
`time_series`, `pca`, `clustering` and the pipelines `exploratory_analysis`, `experiment_analysis`, `full_study`. Formulas are built from
|
|
33
|
+
validated column names; no model-written code is executed. Also provides `StatsRulePlanner` (planner backend `stats_rules`, no LLM).
|
|
34
|
+
|
|
35
|
+
> **Status:** pre-release. Until the first PyPI release, install a wheel from the
|
|
36
|
+
> [GitHub Releases](https://github.com/marcionicolau/spec-agents/releases) or use `uv sync --all-packages` in a checkout;
|
|
37
|
+
> the `pip install` lines below are the PyPI names.
|
|
38
|
+
|
|
39
|
+
## Names
|
|
40
|
+
|
|
41
|
+
| | |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| PyPI distribution | `spec-agents-statistics` |
|
|
44
|
+
| Import name | `stat_fabric` |
|
|
45
|
+
| Directory in the monorepo | `packages/statistics` |
|
|
46
|
+
| Release tag / PR scope | `statistics-vX.Y.Z` / `statistics` |
|
|
47
|
+
|
|
48
|
+
The distribution is named `spec-agents-statistics` because the shorter names are taken on PyPI; the import name and the entry point do not change.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
```bash
|
|
52
|
+
pip install spec-agents-statistics # pulls spec-agents-core, pandas, scipy, statsmodels, scikit-learn
|
|
53
|
+
```
|
|
54
|
+
The pack registers as the `statistics` domain via the `agent_fabric.domains` entry point:
|
|
55
|
+
```python
|
|
56
|
+
from agent_fabric import build_registry
|
|
57
|
+
|
|
58
|
+
registry = build_registry(discover=True) # or build_registry([stat_fabric.domain.register])
|
|
59
|
+
```
|
|
60
|
+
Each component's contract and guidance is a `SKILL.md` under `stat_fabric/skills/`.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# spec-agents-statistics (`stat_fabric`)
|
|
2
|
+
|
|
3
|
+
Statistics domain pack for [agent-fabric](../agent-fabric/README.md): deterministic components `summary`, `linear_model`, `anova`,
|
|
4
|
+
`time_series`, `pca`, `clustering` and the pipelines `exploratory_analysis`, `experiment_analysis`, `full_study`. Formulas are built from
|
|
5
|
+
validated column names; no model-written code is executed. Also provides `StatsRulePlanner` (planner backend `stats_rules`, no LLM).
|
|
6
|
+
|
|
7
|
+
> **Status:** pre-release. Until the first PyPI release, install a wheel from the
|
|
8
|
+
> [GitHub Releases](https://github.com/marcionicolau/spec-agents/releases) or use `uv sync --all-packages` in a checkout;
|
|
9
|
+
> the `pip install` lines below are the PyPI names.
|
|
10
|
+
|
|
11
|
+
## Names
|
|
12
|
+
|
|
13
|
+
| | |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| PyPI distribution | `spec-agents-statistics` |
|
|
16
|
+
| Import name | `stat_fabric` |
|
|
17
|
+
| Directory in the monorepo | `packages/statistics` |
|
|
18
|
+
| Release tag / PR scope | `statistics-vX.Y.Z` / `statistics` |
|
|
19
|
+
|
|
20
|
+
The distribution is named `spec-agents-statistics` because the shorter names are taken on PyPI; the import name and the entry point do not change.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
```bash
|
|
24
|
+
pip install spec-agents-statistics # pulls spec-agents-core, pandas, scipy, statsmodels, scikit-learn
|
|
25
|
+
```
|
|
26
|
+
The pack registers as the `statistics` domain via the `agent_fabric.domains` entry point:
|
|
27
|
+
```python
|
|
28
|
+
from agent_fabric import build_registry
|
|
29
|
+
|
|
30
|
+
registry = build_registry(discover=True) # or build_registry([stat_fabric.domain.register])
|
|
31
|
+
```
|
|
32
|
+
Each component's contract and guidance is a `SKILL.md` under `stat_fabric/skills/`.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "spec-agents-statistics"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Statistics domain pack for agent-fabric: summary, linear_model, anova, time_series, pca, clustering"
|
|
5
|
+
requires-python = ">=3.12"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
authors = [{ name = "Marcio Nicolau" }]
|
|
10
|
+
keywords = ["statistics", "agents", "pandas"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"spec-agents-core>=0.0.1,<1",
|
|
22
|
+
"pandas>=2.1",
|
|
23
|
+
"scipy>=1.12",
|
|
24
|
+
"statsmodels>=0.14.2",
|
|
25
|
+
"scikit-learn>=1.4",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.entry-points."agent_fabric.domains"]
|
|
29
|
+
statistics = "stat_fabric.domain:register"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/marcionicolau/spec-agents"
|
|
33
|
+
Repository = "https://github.com/marcionicolau/spec-agents"
|
|
34
|
+
Issues = "https://github.com/marcionicolau/spec-agents/issues"
|
|
35
|
+
Changelog = "https://github.com/marcionicolau/spec-agents/blob/main/packages/statistics/CHANGELOG.md"
|
|
36
|
+
Documentation = "https://github.com/marcionicolau/spec-agents/tree/main/docs"
|
|
37
|
+
|
|
38
|
+
[build-system]
|
|
39
|
+
requires = ["hatchling", "uv-dynamic-versioning>=0.14"]
|
|
40
|
+
build-backend = "hatchling.build"
|
|
41
|
+
|
|
42
|
+
[tool.uv]
|
|
43
|
+
package = true
|
|
44
|
+
|
|
45
|
+
[tool.uv.sources]
|
|
46
|
+
spec-agents-core = { workspace = true }
|
|
47
|
+
|
|
48
|
+
# version = latest "statistics-vX.Y.Z" git tag (other packages' tags are ignored); untagged commits get X.Y.(Z+1).devN+<sha>
|
|
49
|
+
[tool.hatch.version]
|
|
50
|
+
source = "uv-dynamic-versioning"
|
|
51
|
+
|
|
52
|
+
[tool.hatch.build.targets.wheel]
|
|
53
|
+
packages = ["src/stat_fabric"]
|
|
54
|
+
|
|
55
|
+
[tool.uv-dynamic-versioning]
|
|
56
|
+
vcs = "git"
|
|
57
|
+
style = "pep440"
|
|
58
|
+
bump = true
|
|
59
|
+
pattern-prefix = "statistics-"
|
|
60
|
+
fallback-version = "0.0.0"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Statistics domain pack for agent_fabric."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
__all__ = ["register"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name: str) -> Any:
|
|
11
|
+
"""Lazy export: ``register`` (the ``agent_fabric.domains`` entry point) without importing the pack's heavy dependencies."""
|
|
12
|
+
if name == "register":
|
|
13
|
+
from .domain import register
|
|
14
|
+
|
|
15
|
+
return register
|
|
16
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Facade for the statistics domain on top of the generic agent fabric.
|
|
2
|
+
|
|
3
|
+
fabric = StatisticalAnalysisFabric.from_config("config", domains=[text_pack.register]) # AGENT.md tree
|
|
4
|
+
report = fabric.analyze(df, "Which treatments raise yield?", session_id="trial-2026")
|
|
5
|
+
print(render_markdown(report))
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Iterable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
from agent_fabric import build_registry
|
|
17
|
+
from agent_fabric.agents import AgentFabric, AgentRunReport, AgentsConfig, AgentSpec
|
|
18
|
+
from agent_fabric.llm.backends import LLMBackend
|
|
19
|
+
from agent_fabric.memory import MemoryPort
|
|
20
|
+
|
|
21
|
+
from .domain import register
|
|
22
|
+
from .schemas import SCHEMAS
|
|
23
|
+
|
|
24
|
+
DEFAULT_CONFIG = AgentsConfig(
|
|
25
|
+
root="statistician",
|
|
26
|
+
agents={
|
|
27
|
+
"statistician": AgentSpec(
|
|
28
|
+
kind="planner",
|
|
29
|
+
backend="fabric",
|
|
30
|
+
fallback="stats_rules",
|
|
31
|
+
domains=["statistics"],
|
|
32
|
+
role="Senior statistician",
|
|
33
|
+
goal="Plan and run the smallest valid statistical pipeline",
|
|
34
|
+
interpret="rules",
|
|
35
|
+
options={"repair": True},
|
|
36
|
+
),
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class StatisticalAnalysisFabric:
|
|
42
|
+
"""Facade over the generic fabric for statistical analysis.
|
|
43
|
+
|
|
44
|
+
``from_config(path, domains=...)`` loads an agent tree (default: one ``statistician`` planner with a rules fallback); ``analyze(df, question)``
|
|
45
|
+
runs it on a DataFrame and returns an `AgentRunReport`.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
config: AgentsConfig | None = None,
|
|
51
|
+
*,
|
|
52
|
+
backend: LLMBackend | None = None,
|
|
53
|
+
memory: MemoryPort | None = None,
|
|
54
|
+
registry: Any = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
self.registry = registry or build_registry([register])
|
|
57
|
+
self.agents = AgentFabric(self.registry, config or DEFAULT_CONFIG, backend=backend, memory=memory)
|
|
58
|
+
for name, model in SCHEMAS.items():
|
|
59
|
+
self.agents.register_schema(name, model)
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def from_config(cls, path: str | Path, domains: Iterable[Callable] = (), **kw: Any) -> StatisticalAnalysisFabric:
|
|
63
|
+
"""``path``: agents directory (fabric.md + agents/*/AGENT.md) or legacy YAML file.
|
|
64
|
+
``domains``: extra domain packs the tree needs besides statistics."""
|
|
65
|
+
return cls(AgentsConfig.load(path), registry=build_registry([register, *domains]), **kw)
|
|
66
|
+
|
|
67
|
+
def analyze(
|
|
68
|
+
self,
|
|
69
|
+
df: pd.DataFrame,
|
|
70
|
+
objective: str,
|
|
71
|
+
*,
|
|
72
|
+
session_id: str = "default",
|
|
73
|
+
root: str | None = None,
|
|
74
|
+
extra_inputs: dict[str, Any] | None = None,
|
|
75
|
+
) -> AgentRunReport:
|
|
76
|
+
"""Run the agent tree on a DataFrame and a question; returns the `AgentRunReport`.
|
|
77
|
+
|
|
78
|
+
The frame is bound to the ``data`` input (``extra_inputs`` add more, e.g. ``notes``); ``root`` picks the root agent when the config has
|
|
79
|
+
several candidates and ``session_id`` selects the memory session.
|
|
80
|
+
"""
|
|
81
|
+
return self.agents.run(objective, {"data": df, **(extra_inputs or {})}, root=root, session_id=session_id)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
__all__ = [
|
|
85
|
+
"StatisticalAnalysisFabric",
|
|
86
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Base for statistics components: a component whose main input port is a ``dataframe``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import abstractmethod
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from pydantic import Field
|
|
10
|
+
|
|
11
|
+
from agent_fabric.component import Component, ComponentParams, ComponentResult, Num, StepContext
|
|
12
|
+
from agent_fabric.errors import ErrorDetail
|
|
13
|
+
|
|
14
|
+
__all__ = ["ComponentParams", "Num", "StepContext", "TableComponent", "TableResult"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TableResult(ComponentResult):
|
|
18
|
+
n_used: int = Field(0, description="rows actually used after dropping missing values")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TableComponent[P: ComponentParams, R: TableResult](Component[P, R]):
|
|
22
|
+
data_port: ClassVar[str] = "data"
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def min_rows(self) -> int:
|
|
26
|
+
"""Minimum number of rows declared by the constraints of the data port."""
|
|
27
|
+
return self.port_constraints[self.data_port].min_rows
|
|
28
|
+
|
|
29
|
+
def compute(self, inputs: dict[str, Any], params: P, ctx: StepContext) -> R:
|
|
30
|
+
"""Run the component on the DataFrame bound to its data port; delegates to `compute_table`."""
|
|
31
|
+
return self.compute_table(inputs.get(self.data_port), params, ctx, inputs)
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def compute_table(self, df: pd.DataFrame | None, params: P, ctx: StepContext, inputs: dict[str, Any]) -> R:
|
|
35
|
+
"""Compute the result from the DataFrame (``None`` when the component also works without one).
|
|
36
|
+
|
|
37
|
+
Subclasses implement this; ``inputs`` holds every bound input and ``ctx.emit`` stores declared extra outputs.
|
|
38
|
+
"""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def extra_checks(self, inputs: dict[str, Any], params: P) -> list[ErrorDetail]:
|
|
42
|
+
df = inputs.get(self.data_port)
|
|
43
|
+
return self.extra_data_checks(df, params) if df is not None else []
|
|
44
|
+
|
|
45
|
+
def extra_data_checks(self, df: pd.DataFrame, params: P) -> list[ErrorDetail]:
|
|
46
|
+
"""Component-specific checks on the data, run after the generic table checks; returns located errors (default: none)."""
|
|
47
|
+
return []
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
from agent_fabric.registry import component
|
|
8
|
+
from agent_fabric.tabular import ColumnKind, infer_kind
|
|
9
|
+
|
|
10
|
+
from .base import ComponentParams, Num, StepContext, TableComponent, TableResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SummaryParams(ComponentParams):
|
|
14
|
+
columns: list[str] | None = Field(None, description="columns to describe; None = all")
|
|
15
|
+
include_normality: bool = True
|
|
16
|
+
max_categories: int = Field(10, ge=1, le=50)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class NumericSummary(BaseModel):
|
|
20
|
+
count: int
|
|
21
|
+
missing: int
|
|
22
|
+
mean: Num
|
|
23
|
+
std: Num
|
|
24
|
+
min: Num
|
|
25
|
+
q1: Num
|
|
26
|
+
median: Num
|
|
27
|
+
q3: Num
|
|
28
|
+
max: Num
|
|
29
|
+
skewness: Num
|
|
30
|
+
kurtosis: Num
|
|
31
|
+
shapiro_p: Num = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CategoricalSummary(BaseModel):
|
|
35
|
+
count: int
|
|
36
|
+
missing: int
|
|
37
|
+
n_levels: int
|
|
38
|
+
top_levels: dict[str, int]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SummaryResult(TableResult):
|
|
42
|
+
n_rows: int
|
|
43
|
+
numeric: dict[str, NumericSummary]
|
|
44
|
+
categorical: dict[str, CategoricalSummary]
|
|
45
|
+
correlations: dict[str, dict[str, Num]] = Field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@component("summary")
|
|
49
|
+
class Summary(TableComponent[SummaryParams, SummaryResult]):
|
|
50
|
+
Params = SummaryParams
|
|
51
|
+
Result = SummaryResult
|
|
52
|
+
|
|
53
|
+
def summarize(self, r: dict) -> tuple[str, list[str]]:
|
|
54
|
+
head = f"{r['n_rows']} rows: {len(r['numeric'])} numeric and {len(r['categorical'])} categorical variables described."
|
|
55
|
+
return head, [
|
|
56
|
+
f"{k}: mean {v['mean']:.4g}, sd {v['std']:.4g}"
|
|
57
|
+
for k, v in list(r["numeric"].items())[:5]
|
|
58
|
+
if v["mean"] is not None and v["std"] is not None
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
def compute_table(self, df: pd.DataFrame, params: SummaryParams, ctx: StepContext, inputs: dict) -> SummaryResult:
|
|
62
|
+
"""Describe the selected columns.
|
|
63
|
+
|
|
64
|
+
Numeric columns get count, missing values, mean, standard deviation, quartiles, skewness, kurtosis and, optionally, a Shapiro-Wilk
|
|
65
|
+
normality test (only for 3 to 5000 values). Categorical and boolean columns get the number of levels and the top levels. With two or
|
|
66
|
+
more numeric columns the Pearson correlation matrix is added. Warns about non-normal columns and columns with over 20% missing values.
|
|
67
|
+
"""
|
|
68
|
+
cols = params.columns or list(df.columns)
|
|
69
|
+
numeric, categorical, warns = {}, {}, []
|
|
70
|
+
for c in cols:
|
|
71
|
+
s = df[c]
|
|
72
|
+
kind = infer_kind(s)
|
|
73
|
+
if kind == ColumnKind.NUMERIC:
|
|
74
|
+
x = s.dropna().astype(float)
|
|
75
|
+
shapiro_p = None
|
|
76
|
+
if params.include_normality and 3 <= len(x) <= 5000 and x.nunique() > 1:
|
|
77
|
+
shapiro_p = float(stats.shapiro(x).pvalue)
|
|
78
|
+
if shapiro_p < 0.05:
|
|
79
|
+
warns.append(f"'{c}' departs from normality (Shapiro p={shapiro_p:.3g})")
|
|
80
|
+
numeric[c] = NumericSummary(
|
|
81
|
+
count=len(x),
|
|
82
|
+
missing=int(s.isna().sum()),
|
|
83
|
+
mean=x.mean(),
|
|
84
|
+
std=x.std(),
|
|
85
|
+
min=x.min(),
|
|
86
|
+
q1=x.quantile(0.25),
|
|
87
|
+
median=x.median(),
|
|
88
|
+
q3=x.quantile(0.75),
|
|
89
|
+
max=x.max(),
|
|
90
|
+
skewness=x.skew() if len(x) > 2 else None,
|
|
91
|
+
kurtosis=x.kurt() if len(x) > 3 else None,
|
|
92
|
+
shapiro_p=shapiro_p,
|
|
93
|
+
)
|
|
94
|
+
elif kind in (ColumnKind.CATEGORICAL, ColumnKind.BOOLEAN):
|
|
95
|
+
vc = s.astype(str).where(s.notna()).value_counts()
|
|
96
|
+
categorical[c] = CategoricalSummary(
|
|
97
|
+
count=int(s.notna().sum()),
|
|
98
|
+
missing=int(s.isna().sum()),
|
|
99
|
+
n_levels=int(vc.size),
|
|
100
|
+
top_levels={str(k): int(v) for k, v in vc.head(params.max_categories).items()},
|
|
101
|
+
)
|
|
102
|
+
if s.isna().mean() > 0.2:
|
|
103
|
+
warns.append(f"'{c}' has {s.isna().mean():.0%} missing values")
|
|
104
|
+
corr = {}
|
|
105
|
+
if len(numeric) >= 2:
|
|
106
|
+
m = df[list(numeric)].corr(method="pearson")
|
|
107
|
+
corr = {a: {b: m.loc[a, b] for b in m.columns if b != a} for a in m.index}
|
|
108
|
+
strong = {tuple(sorted((a, b))) for a in m.index for b in m.columns if a != b and abs(m.loc[a, b]) >= 0.9}
|
|
109
|
+
warns += [f"'{a}' and '{b}' are highly correlated (|r|>=0.9)" for a, b in sorted(strong)]
|
|
110
|
+
return SummaryResult(
|
|
111
|
+
n_rows=len(df), n_used=len(df), numeric=numeric, categorical=categorical, correlations=corr, warnings=warns
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
__all__ = [
|
|
116
|
+
"CategoricalSummary",
|
|
117
|
+
"NumericSummary",
|
|
118
|
+
"Summary",
|
|
119
|
+
"SummaryParams",
|
|
120
|
+
"SummaryResult",
|
|
121
|
+
]
|