Skip to content

Commit 13f8b74

Browse files
docs(examples): repair runnable tail examples
1 parent fa9a02f commit 13f8b74

9 files changed

Lines changed: 78 additions & 42 deletions

File tree

src/statspai/bcf/bcf.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,12 +81,18 @@ def bcf(
8181
8282
Examples
8383
--------
84-
>>> import statspai as sp
85-
>>> result = sp.bcf(df, y='outcome', treat='treatment',
86-
... covariates=['x1', 'x2', 'x3'])
84+
>>> import statspai as sp, numpy as np, pandas as pd
85+
>>> rng = np.random.default_rng(0)
86+
>>> n = 400
87+
>>> X = rng.normal(size=(n, 3))
88+
>>> treatment = rng.binomial(1, 0.5, n)
89+
>>> outcome = 2.0 * treatment + X @ np.array([1.0, -0.5, 0.3]) + rng.normal(size=n)
90+
>>> df = pd.DataFrame(X, columns=["x1", "x2", "x3"])
91+
>>> df["outcome"], df["treatment"] = outcome, treatment
92+
>>> result = sp.bcf(df, y="outcome", treat="treatment",
93+
... covariates=["x1", "x2", "x3"], n_bootstrap=10)
8794
>>> print(result.summary())
88-
>>> cate = result.model_info['cate'] # individual effects
89-
>>> cate_sd = result.model_info['cate_sd'] # posterior SD
95+
>>> cate = result.model_info["cate"] # individual effects
9096
"""
9197
est = BayesianCausalForest(
9298
data=data, y=y, treat=treat, covariates=covariates,

src/statspai/bunching/bunching.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,12 @@ def bunching(
9494
9595
Examples
9696
--------
97-
>>> import statspai as sp
98-
>>> result = sp.bunching(df, running_var='income',
99-
... threshold=50000, dt=0.10)
97+
>>> import statspai as sp, numpy as np, pandas as pd
98+
>>> rng = np.random.default_rng(0)
99+
>>> income = rng.exponential(50000, 2000) # taxable income, kink at 50k
100+
>>> df = pd.DataFrame({"income": income})
101+
>>> result = sp.bunching(df, running_var="income", threshold=50000)
100102
>>> print(result.summary())
101-
>>> print(f"Elasticity: {result.model_info['elasticity']:.4f}")
102103
"""
103104
est = BunchingEstimator(
104105
data=data, running_var=running_var, threshold=threshold,

src/statspai/causal_discovery/pcmci.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -275,9 +275,12 @@ def pcmci(
275275
276276
Examples
277277
--------
278-
>>> import statspai as sp
279-
>>> res = sp.pcmci(df_ts, variables=['gdp', 'inflation', 'rates'],
280-
... tau_max=4, pc_alpha=0.01)
278+
>>> import statspai as sp, numpy as np, pandas as pd
279+
>>> rng = np.random.default_rng(0)
280+
>>> df_ts = pd.DataFrame(rng.normal(size=(120, 3)),
281+
... columns=["gdp", "inflation", "rates"])
282+
>>> res = sp.pcmci(df_ts, variables=["gdp", "inflation", "rates"],
283+
... tau_max=2, pc_alpha=0.1)
281284
>>> res.discovered_links() # DataFrame of all significant links
282285
"""
283286
if variables is None:

src/statspai/causal_text/text_treatment.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -165,14 +165,15 @@ def text_treatment_effect(
165165
166166
Examples
167167
--------
168-
>>> import statspai as sp, pandas as pd
168+
>>> import statspai as sp, numpy as np, pandas as pd
169+
>>> rng = np.random.default_rng(0)
169170
>>> df = pd.DataFrame({
170-
... 'text': ['great product', 'terrible bug', 'okay tool', 'love it'],
171-
... 'treatment': [1, 0, 0, 1],
172-
... 'outcome': [4.5, 1.2, 2.8, 4.7],
171+
... "text": ["great product love it"] * 15 + ["terrible buggy slow"] * 15,
172+
... "treatment": [1] * 15 + [0] * 15,
173+
... "outcome": list(rng.normal(4.0, 0.3, 15)) + list(rng.normal(2.0, 0.3, 15)),
173174
... })
174-
>>> r = sp.text_treatment_effect(df, text_col='text', outcome='outcome',
175-
... treatment='treatment', n_components=4)
175+
>>> r = sp.text_treatment_effect(df, text_col="text", outcome="outcome",
176+
... treatment="treatment", n_components=2)
176177
>>> r.estimate
177178
"""
178179
for col in (text_col, outcome, treatment):

src/statspai/deepiv/deep_iv.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -169,15 +169,20 @@ def deepiv(
169169
170170
Examples
171171
--------
172-
>>> result = sp.deepiv(
172+
Requires the optional ``deepiv`` extra (PyTorch); the calls below are
173+
illustrative and are skipped by the doctest runner.
174+
175+
>>> import statspai as sp # doctest: +SKIP
176+
>>> result = sp.deepiv( # doctest: +SKIP
173177
... df, y='lwage', treat='educ',
174178
... instruments=['nearc4'],
175179
... covariates=['exper', 'expersq'],
176180
... )
177-
>>> print(result.summary())
181+
>>> print(result.summary()) # doctest: +SKIP
182+
183+
Custom architecture with the unbiased paired-sample gradient:
178184
179-
>>> # Custom architecture with unbiased gradient
180-
>>> result = sp.deepiv(
185+
>>> result = sp.deepiv( # doctest: +SKIP
181186
... df, y='sales', treat='price',
182187
... instruments=['cost_shifter'],
183188
... covariates=['demand_controls'],

src/statspai/did/report.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -697,11 +697,18 @@ def cs_report(
697697
698698
Examples
699699
--------
700-
>>> import statspai as sp
701-
>>> rpt = sp.did.cs_report(
702-
... df, y='y', g='g', t='t', i='id', random_state=42)
700+
>>> import statspai as sp, numpy as np, pandas as pd
701+
>>> rng = np.random.default_rng(0)
702+
>>> rows = []
703+
>>> for unit in range(80):
704+
... g = 4 if unit < 40 else 0 # cohort; 0 = never treated
705+
... for t in range(8):
706+
... post = g > 0 and t >= g
707+
... y = 0.3 * t + (2.0 if post else 0.0) + (unit % 5) + rng.normal()
708+
... rows.append((unit, t, g, y))
709+
>>> df = pd.DataFrame(rows, columns=["id", "t", "g", "y"])
710+
>>> rpt = sp.cs_report(df, y="y", g="g", t="t", i="id", random_state=42)
703711
>>> rpt.dynamic # event-study DataFrame w/ uniform bands
704-
>>> rpt.breakdown # R-R breakdown M* per post event time
705712
"""
706713
if isinstance(data_or_result, CausalResult):
707714
cs = data_or_result

src/statspai/dose_response/gps.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,18 @@ def dose_response(
9393
9494
Examples
9595
--------
96-
>>> import statspai as sp
97-
>>> result = sp.dose_response(df, y='outcome', treat='dosage',
98-
... covariates=['age', 'weight'])
99-
>>> print(result.detail) # dose-response curve
96+
>>> import statspai as sp, numpy as np, pandas as pd
97+
>>> rng = np.random.default_rng(0)
98+
>>> n = 400
99+
>>> age = rng.normal(40, 10, n)
100+
>>> weight = rng.normal(70, 12, n)
101+
>>> dosage = 0.5 * age + rng.normal(0, 5, n) # confounded dose
102+
>>> outcome = 0.2 * dosage + 0.1 * weight + rng.normal(0, 1, n)
103+
>>> df = pd.DataFrame({"outcome": outcome, "dosage": dosage,
104+
... "age": age, "weight": weight})
105+
>>> result = sp.dose_response(df, y="outcome", treat="dosage",
106+
... covariates=["age", "weight"])
107+
>>> result.detail # dose-response curve
100108
"""
101109
est = DoseResponse(
102110
data=data, y=y, treat=treat, covariates=covariates,

src/statspai/matching/match.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1149,9 +1149,13 @@ def psplot(
11491149
11501150
Examples
11511151
--------
1152-
>>> fig, ax = sp.psplot(df, treat='D', covariates=['x1', 'x2'])
1153-
>>> fig, ax = sp.psplot(df, treat='D', covariates=['x1', 'x2'],
1154-
... trim=0.1)
1152+
>>> import statspai as sp, numpy as np, pandas as pd
1153+
>>> rng = np.random.default_rng(0)
1154+
>>> n = 400
1155+
>>> x1, x2 = rng.normal(size=n), rng.normal(size=n)
1156+
>>> D = rng.binomial(1, 1 / (1 + np.exp(-(x1 + 0.5 * x2))))
1157+
>>> df = pd.DataFrame({"D": D, "x1": x1, "x2": x2})
1158+
>>> fig, ax = sp.psplot(df, treat="D", covariates=["x1", "x2"])
11551159
"""
11561160
try:
11571161
import matplotlib.pyplot as plt

src/statspai/tmle/tmle.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -98,16 +98,17 @@ def tmle(
9898
9999
Examples
100100
--------
101-
>>> import statspai as sp
102-
>>> result = sp.tmle(df, y='outcome', treat='treatment',
103-
... covariates=['x1', 'x2', 'x3'])
101+
>>> import statspai as sp, numpy as np, pandas as pd
102+
>>> rng = np.random.default_rng(0)
103+
>>> n = 400
104+
>>> X = rng.normal(size=(n, 3))
105+
>>> treatment = rng.binomial(1, 1 / (1 + np.exp(-X[:, 0])))
106+
>>> outcome = 2.0 * treatment + X @ np.array([1.0, -0.5, 0.3]) + rng.normal(size=n)
107+
>>> df = pd.DataFrame(X, columns=["x1", "x2", "x3"])
108+
>>> df["outcome"], df["treatment"] = outcome, treatment
109+
>>> result = sp.tmle(df, y="outcome", treat="treatment",
110+
... covariates=["x1", "x2", "x3"])
104111
>>> print(result.summary())
105-
106-
>>> # Custom learner library
107-
>>> from sklearn.ensemble import RandomForestRegressor
108-
>>> result = sp.tmle(df, y='outcome', treat='treatment',
109-
... covariates=['x1', 'x2'],
110-
... outcome_library=[RandomForestRegressor()])
111112
"""
112113
est = TMLE(
113114
data=data, y=y, treat=treat, covariates=covariates,

0 commit comments

Comments
 (0)