trustframe 0.1.0__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.
- trustframe-0.1.0/.gitignore +3 -0
- trustframe-0.1.0/LICENSE +21 -0
- trustframe-0.1.0/PKG-INFO +203 -0
- trustframe-0.1.0/README.md +167 -0
- trustframe-0.1.0/pyproject.toml +43 -0
- trustframe-0.1.0/src/trustframe/__init__.py +50 -0
- trustframe-0.1.0/src/trustframe/_util.py +90 -0
- trustframe-0.1.0/src/trustframe/causal.py +517 -0
- trustframe-0.1.0/src/trustframe/cli.py +55 -0
- trustframe-0.1.0/src/trustframe/explain.py +299 -0
- trustframe-0.1.0/src/trustframe/parity.py +320 -0
- trustframe-0.1.0/src/trustframe/py.typed +0 -0
- trustframe-0.1.0/src/trustframe/quality.py +704 -0
- trustframe-0.1.0/src/trustframe/report.py +398 -0
- trustframe-0.1.0/src/trustframe/trace.py +614 -0
- trustframe-0.1.0/src/trustframe/uncertainty.py +388 -0
- trustframe-0.1.0/tests/test_causal.py +99 -0
- trustframe-0.1.0/tests/test_explain.py +92 -0
- trustframe-0.1.0/tests/test_parity.py +57 -0
- trustframe-0.1.0/tests/test_quality.py +127 -0
- trustframe-0.1.0/tests/test_report.py +88 -0
- trustframe-0.1.0/tests/test_trace.py +112 -0
- trustframe-0.1.0/tests/test_uncertainty.py +80 -0
trustframe-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 trustframe contributors
|
|
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,203 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: trustframe
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Trustworthy data analysis: catch silent dataframe bugs, leakage and bad data, explain metric changes, estimate causal effects, check backend parity, quantify uncertainty and write reports whose numbers are verified.
|
|
5
|
+
Author: trustframe contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: causal-inference,data-quality,data-science,leakage,llm,pandas,root-cause-analysis,uncertainty
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: numpy>=1.21
|
|
18
|
+
Requires-Dist: pandas>=1.5
|
|
19
|
+
Provides-Extra: all
|
|
20
|
+
Requires-Dist: duckdb>=0.9; extra == 'all'
|
|
21
|
+
Requires-Dist: matplotlib>=3.5; extra == 'all'
|
|
22
|
+
Requires-Dist: polars>=0.20; extra == 'all'
|
|
23
|
+
Requires-Dist: pyarrow>=10; extra == 'all'
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: matplotlib>=3.5; extra == 'dev'
|
|
26
|
+
Requires-Dist: polars>=0.20; extra == 'dev'
|
|
27
|
+
Requires-Dist: pyarrow>=10; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
29
|
+
Provides-Extra: plot
|
|
30
|
+
Requires-Dist: matplotlib>=3.5; extra == 'plot'
|
|
31
|
+
Provides-Extra: polars
|
|
32
|
+
Requires-Dist: polars>=0.20; extra == 'polars'
|
|
33
|
+
Provides-Extra: sql
|
|
34
|
+
Requires-Dist: duckdb>=0.9; extra == 'sql'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# trustframe
|
|
38
|
+
|
|
39
|
+
**Trustworthy data analysis for pandas.** Libraries such as pandas, Polars and scikit-learn make computing easy. trustframe helps with what they leave to you: knowing whether the result is *right*.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install trustframe # numpy + pandas only
|
|
43
|
+
pip install "trustframe[all]" # + polars, duckdb, matplotlib, pyarrow
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Module | The gap it fills | Main entry points |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| `trace` | Silent pandas bugs: fan-out joins, lossy `dropna`, filters that match nothing | `audit()`, `check_join()` |
|
|
49
|
+
| `quality` | Problems you didn't write a rule for: target leakage, `-999`/`"N/A"` placeholders, unit changes, hidden duplicates | `scan()` |
|
|
50
|
+
| `explain` | "Revenue dropped 8%, why?": contribution and drill-down analysis | `explain_change()` |
|
|
51
|
+
| `causal` | Causal effects with their assumptions and robustness checks attached | `estimate_effect()`, `diff_in_diff()`, `placebo_test()` |
|
|
52
|
+
| `parity` | Same analysis, different backend, different answer? | `compare()`, `check_parity()` |
|
|
53
|
+
| `uncertainty` | Error bars by default; valid inference from LLM labels | `bootstrap_ci()`, `ppi_mean()`, `conformal_*()`, `sample_size_*()` |
|
|
54
|
+
| `report` | Reports where every number is computed, verified and keeps its caveats | `Report`, `verify_text()`, `lint_chart()` |
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import trustframe as tf
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 1. Catch silent pandas bugs: `audit`
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
with tf.audit() as log:
|
|
66
|
+
df = orders.merge(customer_tags, on="customer_id")
|
|
67
|
+
df = df.dropna()
|
|
68
|
+
active = df.query("status == 'Active'")
|
|
69
|
+
|
|
70
|
+
print(log)
|
|
71
|
+
```
|
|
72
|
+
```
|
|
73
|
+
AuditLog: 3 operations, 3 warnings
|
|
74
|
+
!! 1. merge 10,000 -> 34,512 @ analysis.py:12
|
|
75
|
+
! join increased rows from 10,000 to 34,512 (x3.45); 2,871 key value(s) are duplicated in the
|
|
76
|
+
right table, so sums over left-table columns will be double-counted
|
|
77
|
+
!! 2. dropna 34,512 -> 19,880 @ analysis.py:13
|
|
78
|
+
! dropna removed 14,632 rows (42%); column 'coupon' alone has 14,600 nulls (consider subset=)
|
|
79
|
+
!! 3. query 19,880 -> 0 @ analysis.py:14
|
|
80
|
+
! filter returned 0 rows for "status == 'Active'"; 'status' contains 'active' (case/whitespace differs)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
It traces `merge`, `join`, `dropna`, `drop_duplicates`, `query`, boolean filtering and `concat`. Suspicious steps raise a `TrustWarning`, or a `TrustError` with `audit(strict=True)`, which works well for checking LLM-generated pipelines. `@tf.audited` is the decorator form. Before joining, `tf.check_join(left, right, on="id")` reports the relationship (1:1, 1:many, ...), match rates and expected row counts.
|
|
84
|
+
|
|
85
|
+
## 2. Find what your validation rules miss: `scan`
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
report = tf.scan(df, target="churned", time_col="signup_date")
|
|
89
|
+
print(report)
|
|
90
|
+
```
|
|
91
|
+
```
|
|
92
|
+
QualityReport: 600 rows x 7 columns, 4 issue(s) (2 high, 1 medium, 1 low)
|
|
93
|
+
HIGH leakage [cancel_date] whether 'cancel_date' is missing almost determines 'churned' (AUC 1.00);
|
|
94
|
+
the field is probably filled in only after the outcome
|
|
95
|
+
HIGH unit_change [monthly_spend] typical magnitude jumps about x100 around 2022-10-28 and stays there;
|
|
96
|
+
possible unit change (dollars->cents, seconds->ms, thousands->units)
|
|
97
|
+
MEDIUM placeholder [tenure] value -999 appears 30 times (5.0%) outside the range of every other value [1, 59]
|
|
98
|
+
LOW id_column [customer_id] looks like an identifier; exclude it from model features
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Checks include leakage (by value and by missingness), placeholder numbers, strings and dates, numbers stored as text, unit changes over time, exact duplicates, duplicates hidden by an ID column or by case/whitespace, heavy missingness and constant columns. From the shell:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
trustframe scan data.csv --target churned --time signup_date --fail-on high
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## 3. Explain why a metric changed: `explain_change`
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
exp = tf.explain_change(sales, "revenue", by=["region", "channel", "product"],
|
|
111
|
+
period_col="quarter", before="Q2", after="Q3")
|
|
112
|
+
print(exp)
|
|
113
|
+
exp.top(10) # ranked segments across all dimensions
|
|
114
|
+
```
|
|
115
|
+
```
|
|
116
|
+
revenue went from 600 to 550 (-50, -8.3%).
|
|
117
|
+
Largest driver: region = EU, contributing -60 (120.0% of the change).
|
|
118
|
+
Partly offset by region = APAC (+10).
|
|
119
|
+
Drill-down: region=EU -> channel=paid accounts for -60 (120.0% of the total change).
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Sums and counts are split exactly. For averages and ratios (`agg="mean"`, or `metric=("orders", "sessions")` for a conversion rate) each segment's contribution is split into a **rate effect** (the segment changed) and a **mix effect** (its share of volume changed).
|
|
123
|
+
|
|
124
|
+
## 4. Causal effects with assumptions attached: `causal`
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
res = tf.estimate_effect(df, treatment="got_email", outcome="spend", confounders=["age", "segment", "tenure"])
|
|
128
|
+
print(res)
|
|
129
|
+
```
|
|
130
|
+
```
|
|
131
|
+
Effect of 'got_email' on 'spend': +1.94 (95% CI 1.76 to 2.13, p<0.001; doubly robust (AIPW), n=3,000, treated=1,484)
|
|
132
|
+
Without adjustment the difference is +4.68; adjusting for 3 confounder(s) moves it to +1.94.
|
|
133
|
+
Estimators:
|
|
134
|
+
naive difference +4.68 [4.44, 4.91]
|
|
135
|
+
regression adjustment +1.94 [1.78, 2.11]
|
|
136
|
+
inverse propensity +1.89 [1.5, 2.27]
|
|
137
|
+
doubly robust (AIPW) +1.94 [1.76, 2.13]
|
|
138
|
+
Sensitivity: an unmeasured confounder would need a risk-ratio association of 2.81 with both treatment
|
|
139
|
+
and outcome to explain the estimate away (2.63 to make the CI include 0).
|
|
140
|
+
This is causal only if:
|
|
141
|
+
- no unmeasured confounding: [...] capture every common cause of 'got_email' and 'spend'
|
|
142
|
+
...
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
It also reports covariate balance, overlap problems and disagreement between estimators. `tf.diff_in_diff(df, "y", treated="group", post="after_launch", unit="store", time="week")` adds clustered errors and a parallel-trends pre-test. `tf.placebo_test(...)` re-estimates with shuffled treatment.
|
|
146
|
+
|
|
147
|
+
## 5. Same answer on every backend: `parity`
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
import polars as pl
|
|
151
|
+
res = tf.check_parity(df, {
|
|
152
|
+
"pandas": lambda d: d.groupby("region", as_index=False)["revenue"].sum(),
|
|
153
|
+
"polars": ("polars", lambda d: d.group_by("region").agg(pl.col("revenue").sum())),
|
|
154
|
+
"duckdb": "SELECT region, SUM(revenue) AS revenue FROM df GROUP BY region",
|
|
155
|
+
}, keys=["region"])
|
|
156
|
+
res.assert_all_equal()
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`tf.compare(a, b, keys=...)` diffs any two tables (pandas, Polars, Arrow, DuckDB). It tolerates float noise and row order, treats all null flavours as equal, and points out an empty string compared against a null.
|
|
160
|
+
|
|
161
|
+
## 6. Uncertainty by default: `uncertainty`
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
tf.bootstrap_ci(x, np.median) # any statistic
|
|
165
|
+
tf.metric_ci(y_true, y_pred, "auc") # model metrics
|
|
166
|
+
tf.proportion_ci(17, 120) # Wilson interval
|
|
167
|
+
|
|
168
|
+
# 50,000 items labelled by an LLM, 300 also labelled by humans:
|
|
169
|
+
iv = tf.ppi_mean(human_labels, llm_labels_on_those_300, llm_labels_on_the_rest)
|
|
170
|
+
print(iv) # valid CI even though the LLM is biased
|
|
171
|
+
iv.details["effective_labeled_n"] # what the LLM labels were worth in human labels
|
|
172
|
+
|
|
173
|
+
tf.labeler_report(human, llm) # accuracy CI, kappa, per-class recall, label-rate shift
|
|
174
|
+
lo, hi = tf.conformal_regression(y_cal, pred_cal, pred_test, alpha=0.1) # 90% coverage, any model
|
|
175
|
+
tf.sample_size_ab(p_baseline=0.10, mde=0.02) # users per arm
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## 7. Reports whose numbers are verified: `report`
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
r = tf.Report("Q3 revenue review")
|
|
182
|
+
r.add("revenue", 1_234_567, fmt="money", source="warehouse.revenue_q3")
|
|
183
|
+
r.add("growth", -0.12, fmt="pct", ci=(-0.15, -0.09), caveat="Pending refunds are excluded")
|
|
184
|
+
r.add("conversion", tf.proportion_ci(312, 10_000), fmt="pct")
|
|
185
|
+
r.write("Revenue was {revenue}, a change of {growth|ci}. Conversion held at {conversion}.")
|
|
186
|
+
r.write("Intervals are bootstrap over orders.", detail=True) # analyst-only
|
|
187
|
+
r.save("q3.html", audience="exec")
|
|
188
|
+
|
|
189
|
+
# Check an LLM-written summary against the facts:
|
|
190
|
+
print(r.verify("Revenue hit $1.2M, down 12%, while churn rose to 7.5%."))
|
|
191
|
+
```
|
|
192
|
+
```
|
|
193
|
+
3 number(s) checked: 2 supported, 1 unsupported
|
|
194
|
+
ok '$1.2M' = revenue
|
|
195
|
+
ok '12%' = growth
|
|
196
|
+
!! '7.5%' (no matching fact)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`tf.lint_chart(fig)` flags bar axes that don't start at zero, pies with too many slices, crowded line charts, missing labels and legends, and dual y-axes.
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
Requires Python 3.9+, NumPy and pandas. MIT licensed.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# trustframe
|
|
2
|
+
|
|
3
|
+
**Trustworthy data analysis for pandas.** Libraries such as pandas, Polars and scikit-learn make computing easy. trustframe helps with what they leave to you: knowing whether the result is *right*.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install trustframe # numpy + pandas only
|
|
7
|
+
pip install "trustframe[all]" # + polars, duckdb, matplotlib, pyarrow
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
| Module | The gap it fills | Main entry points |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| `trace` | Silent pandas bugs: fan-out joins, lossy `dropna`, filters that match nothing | `audit()`, `check_join()` |
|
|
13
|
+
| `quality` | Problems you didn't write a rule for: target leakage, `-999`/`"N/A"` placeholders, unit changes, hidden duplicates | `scan()` |
|
|
14
|
+
| `explain` | "Revenue dropped 8%, why?": contribution and drill-down analysis | `explain_change()` |
|
|
15
|
+
| `causal` | Causal effects with their assumptions and robustness checks attached | `estimate_effect()`, `diff_in_diff()`, `placebo_test()` |
|
|
16
|
+
| `parity` | Same analysis, different backend, different answer? | `compare()`, `check_parity()` |
|
|
17
|
+
| `uncertainty` | Error bars by default; valid inference from LLM labels | `bootstrap_ci()`, `ppi_mean()`, `conformal_*()`, `sample_size_*()` |
|
|
18
|
+
| `report` | Reports where every number is computed, verified and keeps its caveats | `Report`, `verify_text()`, `lint_chart()` |
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import trustframe as tf
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 1. Catch silent pandas bugs: `audit`
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
with tf.audit() as log:
|
|
30
|
+
df = orders.merge(customer_tags, on="customer_id")
|
|
31
|
+
df = df.dropna()
|
|
32
|
+
active = df.query("status == 'Active'")
|
|
33
|
+
|
|
34
|
+
print(log)
|
|
35
|
+
```
|
|
36
|
+
```
|
|
37
|
+
AuditLog: 3 operations, 3 warnings
|
|
38
|
+
!! 1. merge 10,000 -> 34,512 @ analysis.py:12
|
|
39
|
+
! join increased rows from 10,000 to 34,512 (x3.45); 2,871 key value(s) are duplicated in the
|
|
40
|
+
right table, so sums over left-table columns will be double-counted
|
|
41
|
+
!! 2. dropna 34,512 -> 19,880 @ analysis.py:13
|
|
42
|
+
! dropna removed 14,632 rows (42%); column 'coupon' alone has 14,600 nulls (consider subset=)
|
|
43
|
+
!! 3. query 19,880 -> 0 @ analysis.py:14
|
|
44
|
+
! filter returned 0 rows for "status == 'Active'"; 'status' contains 'active' (case/whitespace differs)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
It traces `merge`, `join`, `dropna`, `drop_duplicates`, `query`, boolean filtering and `concat`. Suspicious steps raise a `TrustWarning`, or a `TrustError` with `audit(strict=True)`, which works well for checking LLM-generated pipelines. `@tf.audited` is the decorator form. Before joining, `tf.check_join(left, right, on="id")` reports the relationship (1:1, 1:many, ...), match rates and expected row counts.
|
|
48
|
+
|
|
49
|
+
## 2. Find what your validation rules miss: `scan`
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
report = tf.scan(df, target="churned", time_col="signup_date")
|
|
53
|
+
print(report)
|
|
54
|
+
```
|
|
55
|
+
```
|
|
56
|
+
QualityReport: 600 rows x 7 columns, 4 issue(s) (2 high, 1 medium, 1 low)
|
|
57
|
+
HIGH leakage [cancel_date] whether 'cancel_date' is missing almost determines 'churned' (AUC 1.00);
|
|
58
|
+
the field is probably filled in only after the outcome
|
|
59
|
+
HIGH unit_change [monthly_spend] typical magnitude jumps about x100 around 2022-10-28 and stays there;
|
|
60
|
+
possible unit change (dollars->cents, seconds->ms, thousands->units)
|
|
61
|
+
MEDIUM placeholder [tenure] value -999 appears 30 times (5.0%) outside the range of every other value [1, 59]
|
|
62
|
+
LOW id_column [customer_id] looks like an identifier; exclude it from model features
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Checks include leakage (by value and by missingness), placeholder numbers, strings and dates, numbers stored as text, unit changes over time, exact duplicates, duplicates hidden by an ID column or by case/whitespace, heavy missingness and constant columns. From the shell:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
trustframe scan data.csv --target churned --time signup_date --fail-on high
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## 3. Explain why a metric changed: `explain_change`
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
exp = tf.explain_change(sales, "revenue", by=["region", "channel", "product"],
|
|
75
|
+
period_col="quarter", before="Q2", after="Q3")
|
|
76
|
+
print(exp)
|
|
77
|
+
exp.top(10) # ranked segments across all dimensions
|
|
78
|
+
```
|
|
79
|
+
```
|
|
80
|
+
revenue went from 600 to 550 (-50, -8.3%).
|
|
81
|
+
Largest driver: region = EU, contributing -60 (120.0% of the change).
|
|
82
|
+
Partly offset by region = APAC (+10).
|
|
83
|
+
Drill-down: region=EU -> channel=paid accounts for -60 (120.0% of the total change).
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Sums and counts are split exactly. For averages and ratios (`agg="mean"`, or `metric=("orders", "sessions")` for a conversion rate) each segment's contribution is split into a **rate effect** (the segment changed) and a **mix effect** (its share of volume changed).
|
|
87
|
+
|
|
88
|
+
## 4. Causal effects with assumptions attached: `causal`
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
res = tf.estimate_effect(df, treatment="got_email", outcome="spend", confounders=["age", "segment", "tenure"])
|
|
92
|
+
print(res)
|
|
93
|
+
```
|
|
94
|
+
```
|
|
95
|
+
Effect of 'got_email' on 'spend': +1.94 (95% CI 1.76 to 2.13, p<0.001; doubly robust (AIPW), n=3,000, treated=1,484)
|
|
96
|
+
Without adjustment the difference is +4.68; adjusting for 3 confounder(s) moves it to +1.94.
|
|
97
|
+
Estimators:
|
|
98
|
+
naive difference +4.68 [4.44, 4.91]
|
|
99
|
+
regression adjustment +1.94 [1.78, 2.11]
|
|
100
|
+
inverse propensity +1.89 [1.5, 2.27]
|
|
101
|
+
doubly robust (AIPW) +1.94 [1.76, 2.13]
|
|
102
|
+
Sensitivity: an unmeasured confounder would need a risk-ratio association of 2.81 with both treatment
|
|
103
|
+
and outcome to explain the estimate away (2.63 to make the CI include 0).
|
|
104
|
+
This is causal only if:
|
|
105
|
+
- no unmeasured confounding: [...] capture every common cause of 'got_email' and 'spend'
|
|
106
|
+
...
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
It also reports covariate balance, overlap problems and disagreement between estimators. `tf.diff_in_diff(df, "y", treated="group", post="after_launch", unit="store", time="week")` adds clustered errors and a parallel-trends pre-test. `tf.placebo_test(...)` re-estimates with shuffled treatment.
|
|
110
|
+
|
|
111
|
+
## 5. Same answer on every backend: `parity`
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
import polars as pl
|
|
115
|
+
res = tf.check_parity(df, {
|
|
116
|
+
"pandas": lambda d: d.groupby("region", as_index=False)["revenue"].sum(),
|
|
117
|
+
"polars": ("polars", lambda d: d.group_by("region").agg(pl.col("revenue").sum())),
|
|
118
|
+
"duckdb": "SELECT region, SUM(revenue) AS revenue FROM df GROUP BY region",
|
|
119
|
+
}, keys=["region"])
|
|
120
|
+
res.assert_all_equal()
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`tf.compare(a, b, keys=...)` diffs any two tables (pandas, Polars, Arrow, DuckDB). It tolerates float noise and row order, treats all null flavours as equal, and points out an empty string compared against a null.
|
|
124
|
+
|
|
125
|
+
## 6. Uncertainty by default: `uncertainty`
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
tf.bootstrap_ci(x, np.median) # any statistic
|
|
129
|
+
tf.metric_ci(y_true, y_pred, "auc") # model metrics
|
|
130
|
+
tf.proportion_ci(17, 120) # Wilson interval
|
|
131
|
+
|
|
132
|
+
# 50,000 items labelled by an LLM, 300 also labelled by humans:
|
|
133
|
+
iv = tf.ppi_mean(human_labels, llm_labels_on_those_300, llm_labels_on_the_rest)
|
|
134
|
+
print(iv) # valid CI even though the LLM is biased
|
|
135
|
+
iv.details["effective_labeled_n"] # what the LLM labels were worth in human labels
|
|
136
|
+
|
|
137
|
+
tf.labeler_report(human, llm) # accuracy CI, kappa, per-class recall, label-rate shift
|
|
138
|
+
lo, hi = tf.conformal_regression(y_cal, pred_cal, pred_test, alpha=0.1) # 90% coverage, any model
|
|
139
|
+
tf.sample_size_ab(p_baseline=0.10, mde=0.02) # users per arm
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## 7. Reports whose numbers are verified: `report`
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
r = tf.Report("Q3 revenue review")
|
|
146
|
+
r.add("revenue", 1_234_567, fmt="money", source="warehouse.revenue_q3")
|
|
147
|
+
r.add("growth", -0.12, fmt="pct", ci=(-0.15, -0.09), caveat="Pending refunds are excluded")
|
|
148
|
+
r.add("conversion", tf.proportion_ci(312, 10_000), fmt="pct")
|
|
149
|
+
r.write("Revenue was {revenue}, a change of {growth|ci}. Conversion held at {conversion}.")
|
|
150
|
+
r.write("Intervals are bootstrap over orders.", detail=True) # analyst-only
|
|
151
|
+
r.save("q3.html", audience="exec")
|
|
152
|
+
|
|
153
|
+
# Check an LLM-written summary against the facts:
|
|
154
|
+
print(r.verify("Revenue hit $1.2M, down 12%, while churn rose to 7.5%."))
|
|
155
|
+
```
|
|
156
|
+
```
|
|
157
|
+
3 number(s) checked: 2 supported, 1 unsupported
|
|
158
|
+
ok '$1.2M' = revenue
|
|
159
|
+
ok '12%' = growth
|
|
160
|
+
!! '7.5%' (no matching fact)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`tf.lint_chart(fig)` flags bar axes that don't start at zero, pies with too many slices, crowded line charts, missing labels and legends, and dual y-axes.
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
Requires Python 3.9+, NumPy and pandas. MIT licensed.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "trustframe"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Trustworthy data analysis: catch silent dataframe bugs, leakage and bad data, explain metric changes, estimate causal effects, check backend parity, quantify uncertainty and write reports whose numbers are verified."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "trustframe contributors" }]
|
|
14
|
+
keywords = ["data-science", "pandas", "data-quality", "leakage", "causal-inference", "uncertainty", "root-cause-analysis", "llm"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["numpy>=1.21", "pandas>=1.5"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
polars = ["polars>=0.20"]
|
|
28
|
+
sql = ["duckdb>=0.9"]
|
|
29
|
+
plot = ["matplotlib>=3.5"]
|
|
30
|
+
all = ["polars>=0.20", "duckdb>=0.9", "matplotlib>=3.5", "pyarrow>=10"]
|
|
31
|
+
dev = ["pytest>=7", "polars>=0.20", "matplotlib>=3.5", "pyarrow>=10"]
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
trustframe = "trustframe.cli:main"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.sdist]
|
|
37
|
+
include = ["src/trustframe", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/trustframe"]
|
|
41
|
+
|
|
42
|
+
[tool.pytest.ini_options]
|
|
43
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""trustframe: trustworthy data analysis.
|
|
2
|
+
|
|
3
|
+
Modules map to the gaps that dataframe libraries leave open:
|
|
4
|
+
|
|
5
|
+
* :mod:`trustframe.trace` - catch silent pandas bugs (fan-out joins, lossy dropna, empty filters)
|
|
6
|
+
* :mod:`trustframe.quality` - find leakage, placeholders, unit changes and hidden duplicates
|
|
7
|
+
* :mod:`trustframe.explain` - explain why a metric changed (root-cause / contribution analysis)
|
|
8
|
+
* :mod:`trustframe.causal` - causal effects with assumptions and robustness checks attached
|
|
9
|
+
* :mod:`trustframe.parity` - check results agree across pandas, Polars, DuckDB, ...
|
|
10
|
+
* :mod:`trustframe.uncertainty` - intervals, LLM-label inference (PPI), conformal sets, sample sizes
|
|
11
|
+
* :mod:`trustframe.report` - reports whose numbers are computed and verified
|
|
12
|
+
"""
|
|
13
|
+
from .causal import CausalEstimate, DiDResult, PlaceboResult, diff_in_diff, e_value, estimate_effect, placebo_test
|
|
14
|
+
from .explain import ChangeExplanation, explain_change
|
|
15
|
+
from .parity import ParityReport, ParityResults, check_parity, compare, sql, to_pandas
|
|
16
|
+
from .quality import Issue, QualityReport, scan
|
|
17
|
+
from .report import Fact, Report, UnknownFactError, VerificationResult, lint_chart, verify_text
|
|
18
|
+
from .trace import AuditLog, JoinCheck, Thresholds, TrustError, TrustWarning, audit, audited, check_join
|
|
19
|
+
from .uncertainty import (
|
|
20
|
+
Interval,
|
|
21
|
+
bootstrap_ci,
|
|
22
|
+
cohen_kappa,
|
|
23
|
+
conformal_classification,
|
|
24
|
+
conformal_regression,
|
|
25
|
+
fleiss_kappa,
|
|
26
|
+
labeler_report,
|
|
27
|
+
mean_ci,
|
|
28
|
+
metric_ci,
|
|
29
|
+
minimum_detectable_effect,
|
|
30
|
+
ppi_mean,
|
|
31
|
+
proportion_ci,
|
|
32
|
+
sample_size_ab,
|
|
33
|
+
sample_size_mean,
|
|
34
|
+
sample_size_proportion,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"audit", "audited", "check_join", "AuditLog", "JoinCheck", "Thresholds", "TrustWarning", "TrustError",
|
|
41
|
+
"scan", "QualityReport", "Issue",
|
|
42
|
+
"explain_change", "ChangeExplanation",
|
|
43
|
+
"estimate_effect", "diff_in_diff", "placebo_test", "e_value", "CausalEstimate", "DiDResult", "PlaceboResult",
|
|
44
|
+
"compare", "check_parity", "sql", "to_pandas", "ParityReport", "ParityResults",
|
|
45
|
+
"Interval", "bootstrap_ci", "mean_ci", "proportion_ci", "metric_ci", "ppi_mean", "cohen_kappa", "fleiss_kappa",
|
|
46
|
+
"labeler_report", "conformal_regression", "conformal_classification", "sample_size_proportion",
|
|
47
|
+
"sample_size_mean", "sample_size_ab", "minimum_detectable_effect",
|
|
48
|
+
"Report", "Fact", "verify_text", "VerificationResult", "lint_chart", "UnknownFactError",
|
|
49
|
+
"__version__",
|
|
50
|
+
]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Small numeric and formatting helpers shared across trustframe (no SciPy needed)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from statistics import NormalDist
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
_NORMAL = NormalDist()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def z_value(confidence: float) -> float:
|
|
14
|
+
"""Two-sided critical value of the standard normal for a confidence level."""
|
|
15
|
+
if not 0 < confidence < 1:
|
|
16
|
+
raise ValueError("confidence must be between 0 and 1")
|
|
17
|
+
return _NORMAL.inv_cdf(0.5 + confidence / 2)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def t_value(confidence: float, df: float) -> float:
|
|
21
|
+
"""Two-sided critical value of Student's t; falls back to the normal without SciPy."""
|
|
22
|
+
try:
|
|
23
|
+
from scipy import stats # type: ignore
|
|
24
|
+
|
|
25
|
+
return float(stats.t.ppf(0.5 + confidence / 2, df))
|
|
26
|
+
except Exception: # pragma: no cover - SciPy is optional
|
|
27
|
+
return z_value(confidence)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def p_two_sided(z: float) -> float:
|
|
31
|
+
if not math.isfinite(z):
|
|
32
|
+
return 0.0 if abs(z) == math.inf else float("nan")
|
|
33
|
+
return 2 * (1 - _NORMAL.cdf(abs(z)))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def auc_score(scores, y01) -> float:
|
|
37
|
+
"""Rank-based ROC AUC (Mann-Whitney), ties averaged. Returns nan if one class is absent."""
|
|
38
|
+
s = pd.Series(np.asarray(scores, dtype=float))
|
|
39
|
+
y = np.asarray(y01).astype(bool)
|
|
40
|
+
n1 = int(y.sum())
|
|
41
|
+
n0 = len(y) - n1
|
|
42
|
+
if n1 == 0 or n0 == 0:
|
|
43
|
+
return float("nan")
|
|
44
|
+
ranks = s.rank(method="average").to_numpy()
|
|
45
|
+
return float((ranks[y].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def spearman(x, y) -> float:
|
|
49
|
+
rx = pd.Series(np.asarray(x, dtype=float)).rank().to_numpy()
|
|
50
|
+
ry = pd.Series(np.asarray(y, dtype=float)).rank().to_numpy()
|
|
51
|
+
if rx.std() == 0 or ry.std() == 0:
|
|
52
|
+
return float("nan")
|
|
53
|
+
return float(np.corrcoef(rx, ry)[0, 1])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fmt_num(x, digits: int = 3, signed: bool = False) -> str:
|
|
57
|
+
"""Human-friendly number: 1234567 -> '1.23M', 0.012345 -> '0.0123'."""
|
|
58
|
+
try:
|
|
59
|
+
x = float(x)
|
|
60
|
+
except (TypeError, ValueError):
|
|
61
|
+
return str(x)
|
|
62
|
+
if math.isnan(x):
|
|
63
|
+
return "nan"
|
|
64
|
+
if math.isinf(x):
|
|
65
|
+
return ("+" if signed and x > 0 else "") + ("inf" if x > 0 else "-inf")
|
|
66
|
+
sign = "+" if signed and x > 0 else ""
|
|
67
|
+
ax = abs(x)
|
|
68
|
+
for limit, suffix in ((1e12, "T"), (1e9, "B"), (1e6, "M"), (1e3, "k")):
|
|
69
|
+
if ax >= limit:
|
|
70
|
+
return f"{sign}{x / limit:.{digits}g}{suffix}"
|
|
71
|
+
if x == int(x):
|
|
72
|
+
return f"{sign}{int(x):,}"
|
|
73
|
+
return f"{sign}{x:.{max(digits, len(str(int(ax))))}g}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def fmt_pct(x, digits: int = 1, signed: bool = False) -> str:
|
|
77
|
+
try:
|
|
78
|
+
x = float(x)
|
|
79
|
+
except (TypeError, ValueError):
|
|
80
|
+
return str(x)
|
|
81
|
+
if math.isnan(x):
|
|
82
|
+
return "nan"
|
|
83
|
+
return f"{x * 100:{'+' if signed else ''}.{digits}f}%"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def fmt_p(p: float) -> str:
|
|
87
|
+
"""p-value for display: 'p<0.001' instead of 'p=0'."""
|
|
88
|
+
if p != p:
|
|
89
|
+
return "p=nan"
|
|
90
|
+
return "p<0.001" if p < 0.001 else f"p={p:.3g}"
|