repairsplit 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.
@@ -0,0 +1,3 @@
1
+ """RepairSplit: responders versus a uniform shift in small trials."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
repairsplit/analyze.py ADDED
@@ -0,0 +1,254 @@
1
+ """Read a tidy trial CSV and run every method that the design supports.
2
+
3
+ See docs/DATA_FORMAT.md for the layout.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from .crossover import analyze_differences, period_adjusted_differences
12
+ from .mixture import mixture_check
13
+ from .moderators import DEFAULT_MAX_MODERATORS, check_count, moderators_crossover
14
+ from .moderators import moderators_parallel as _moderators_parallel
15
+ from .variance import brown_forsythe_p, sd_ir
16
+
17
+ DISCLAIMER = (
18
+ "Statistical description of trial outcomes only. Not medical advice and not a "
19
+ "statement about any individual participant."
20
+ )
21
+
22
+
23
+ class FormatError(ValueError):
24
+ pass
25
+
26
+
27
+ def _has(df: pd.DataFrame, col: str) -> bool:
28
+ if col not in df.columns:
29
+ return False
30
+ s = df[col]
31
+ return bool((s.notna() & (s.astype(str).str.strip() != "")).any())
32
+
33
+
34
+ def detect_design(df: pd.DataFrame) -> str:
35
+ if _has(df, "sequence"):
36
+ return "crossover"
37
+ if _has(df, "arm"):
38
+ return "parallel"
39
+ raise FormatError("need an 'arm' column (parallel) or a 'sequence' column (crossover)")
40
+
41
+
42
+ def _require(df, cols):
43
+ missing = [c for c in cols if c not in df.columns]
44
+ if missing:
45
+ raise FormatError(f"missing column(s): {', '.join(missing)}")
46
+
47
+
48
+ def _covariates(frame, moderators):
49
+ _require(frame, moderators)
50
+ cov = frame[list(moderators)].apply(pd.to_numeric, errors="coerce")
51
+ if cov.isna().any().any():
52
+ raise FormatError("moderator columns must be numeric with no missing values")
53
+ return cov
54
+
55
+
56
+ def analyze_parallel(
57
+ df, moderators, treatment_label, max_moderators, allow_many, method, n_bootstrap, seed,
58
+ fpr_sims,
59
+ ) -> dict:
60
+ _require(df, ["participant", "arm", "baseline", "outcome"])
61
+ if df["participant"].duplicated().any():
62
+ raise FormatError("parallel design: one row per participant expected")
63
+ labels = sorted(df["arm"].astype(str).unique())
64
+ if len(labels) != 2 or treatment_label not in labels:
65
+ raise FormatError(
66
+ f"'arm' must hold exactly two labels, one of them '{treatment_label}'; found {labels}"
67
+ )
68
+ df = df.dropna(subset=["baseline", "outcome"])
69
+ treated = (df["arm"].astype(str) == treatment_label).to_numpy()
70
+ change = (df["outcome"] - df["baseline"]).to_numpy(dtype=float)
71
+ xt, xc = change[treated], change[~treated]
72
+ res = sd_ir(xt, xc)
73
+ t_bf, p_bf = brown_forsythe_p(xt, xc)
74
+ out = {
75
+ "design": "parallel",
76
+ "n": int(change.size),
77
+ "mean_effect": float(xt.mean() - xc.mean()),
78
+ "sd_individual_response": res.to_dict(),
79
+ "brown_forsythe": {"t": float(t_bf), "p_one_sided": float(p_bf)},
80
+ "mixture": mixture_check(xt, n_bootstrap, seed=seed, fpr_sims=fpr_sims).to_dict(),
81
+ "moderators": [],
82
+ }
83
+ if moderators:
84
+ rows = _moderators_parallel(
85
+ change, treated, _covariates(df, moderators), method=method,
86
+ max_moderators=max_moderators, allow_many=allow_many,
87
+ )
88
+ out["moderators"] = [r.to_dict() for r in rows]
89
+ out["moderator_correction"] = method
90
+ return out
91
+
92
+
93
+ def crossover_wide(df: pd.DataFrame) -> pd.DataFrame:
94
+ """One row per participant: sequence, treated and control outcome, difference."""
95
+ _require(df, ["participant", "sequence", "period", "outcome"])
96
+ df = df.copy()
97
+ df["sequence"] = df["sequence"].astype(str).str.strip().str.upper()
98
+ bad = sorted(set(df["sequence"]) - {"TC", "CT"})
99
+ if bad:
100
+ raise FormatError(f"'sequence' must be 'TC' or 'CT'; found {bad}")
101
+ df["period"] = pd.to_numeric(df["period"], errors="coerce")
102
+ if not set(df["period"].dropna().unique()) <= {1, 2}:
103
+ raise FormatError("'period' must be 1 or 2; replicated periods are not supported")
104
+ if df.duplicated(["participant", "period"]).any():
105
+ raise FormatError("more than one row for a participant and period")
106
+ if (df.groupby("participant")["sequence"].nunique() > 1).any():
107
+ raise FormatError("a participant has two different sequences")
108
+ wide = df.pivot(index="participant", columns="period", values="outcome").dropna()
109
+ if wide.shape[1] != 2:
110
+ raise FormatError("both periods are needed")
111
+ first = df.drop_duplicates("participant").set_index("participant")
112
+ wide = wide.join(first.drop(columns=["period", "outcome"]))
113
+ wide["treatment_first"] = wide["sequence"] == "TC"
114
+ wide["difference"] = np.where(wide["treatment_first"], wide[1] - wide[2], wide[2] - wide[1])
115
+ return wide
116
+
117
+
118
+ def analyze_crossover(
119
+ df, moderators, retest_sd_difference, retest_df, max_moderators, allow_many, method,
120
+ n_bootstrap, seed, fpr_sims,
121
+ ) -> dict:
122
+ wide = crossover_wide(df)
123
+ tf = wide["treatment_first"].to_numpy()
124
+ d = wide["difference"].to_numpy(dtype=float)
125
+ res = analyze_differences(d[tf], d[~tf], retest_sd_difference, retest_df)
126
+ a_tc, a_ct = period_adjusted_differences(d[tf], d[~tf])
127
+ out = {
128
+ "design": "crossover",
129
+ "n": int(d.size),
130
+ "mean_effect": res.mean_effect,
131
+ "crossover": res.to_dict(),
132
+ "mixture": mixture_check(
133
+ np.concatenate([a_tc, a_ct]), n_bootstrap, seed=seed, fpr_sims=fpr_sims
134
+ ).to_dict(),
135
+ "moderators": [],
136
+ }
137
+ if moderators:
138
+ rows = moderators_crossover(
139
+ d, tf, _covariates(wide, moderators), method=method,
140
+ max_moderators=max_moderators, allow_many=allow_many,
141
+ )
142
+ out["moderators"] = [r.to_dict() for r in rows]
143
+ out["moderator_correction"] = method
144
+ return out
145
+
146
+
147
+ def analyze(
148
+ df: pd.DataFrame,
149
+ moderators: list[str] | None = None,
150
+ design: str = "auto",
151
+ treatment_label: str = "treatment",
152
+ retest_sd_difference: float | None = None,
153
+ retest_df: float | None = None,
154
+ max_moderators: int = DEFAULT_MAX_MODERATORS,
155
+ allow_many_moderators: bool = False,
156
+ correction: str = "holm",
157
+ n_bootstrap: int = 999,
158
+ seed: int = 0,
159
+ fpr_sims: int = 400,
160
+ ) -> dict:
161
+ moderators = list(moderators or [])
162
+ check_count(moderators, max_moderators, allow_many_moderators)
163
+ if design == "auto":
164
+ design = detect_design(df)
165
+ if design == "parallel":
166
+ out = analyze_parallel(
167
+ df, moderators, treatment_label, max_moderators, allow_many_moderators, correction,
168
+ n_bootstrap, seed, fpr_sims,
169
+ )
170
+ elif design == "crossover":
171
+ out = analyze_crossover(
172
+ df, moderators, retest_sd_difference, retest_df, max_moderators,
173
+ allow_many_moderators, correction, n_bootstrap, seed, fpr_sims,
174
+ )
175
+ else:
176
+ raise FormatError(f"unknown design '{design}'")
177
+ out["disclaimer"] = DISCLAIMER
178
+ return out
179
+
180
+
181
+ def _f(x, nd=2):
182
+ return "n/a" if x is None else f"{x:.{nd}f}"
183
+
184
+
185
+ def format_report(r: dict) -> str:
186
+ """Plain-text report of an `analyze` result."""
187
+ L = [f"Design: {r['design']}, {r['n']} participants analysed", ""]
188
+ if r["design"] == "parallel":
189
+ s = r["sd_individual_response"]
190
+ L += [
191
+ f"Mean effect (treated minus control change): {_f(r['mean_effect'])}",
192
+ "",
193
+ "Spread of change scores",
194
+ f" treated SD {_f(s['sd_treated'])} (n={s['n_treated']}), "
195
+ f"control SD {_f(s['sd_control'])} (n={s['n_control']})",
196
+ f" SD of individual response: {_f(s['sd_ir'])} "
197
+ f"(95% CI {_f(s['sd_ir_ci_low'])} to {_f(s['sd_ir_ci_high'])})",
198
+ " A negative value means the treated arm varied less than the control arm.",
199
+ f" variance ratio {_f(s['variance_ratio'])} "
200
+ f"(95% CI {_f(s['variance_ratio_ci_low'])} to {_f(s['variance_ratio_ci_high'])})",
201
+ f" F test, treated more variable: one-sided p = {_f(s['p_f_one_sided'], 3)}",
202
+ f" Brown-Forsythe test, same question: one-sided p = "
203
+ f"{_f(r['brown_forsythe']['p_one_sided'], 3)}",
204
+ ]
205
+ else:
206
+ c = r["crossover"]
207
+ L += [
208
+ f"Mean effect (treated minus control): {_f(c['mean_effect'])} "
209
+ f"(95% CI {_f(c['mean_effect_ci_low'])} to {_f(c['mean_effect_ci_high'])})",
210
+ f"Period effect (period 2 minus period 1): {_f(c['period_effect'])}",
211
+ "",
212
+ "Individual response",
213
+ f" SD of within-person differences: {_f(c['sd_difference'])} (df={c['df']})",
214
+ " This is response spread and measurement noise added together.",
215
+ f" Upper bound on SD of individual response: {_f(c['sd_ir_upper_bound'])} "
216
+ f"(95% upper confidence limit {_f(c['sd_ir_upper_bound_conf_limit'])})",
217
+ ]
218
+ if c["sd_ir_estimable"]:
219
+ L += [
220
+ f" Outside test-retest SD of differences: {_f(c['retest_sd_difference'])} "
221
+ f"(df={'treated as known' if c['retest_df'] is None else c['retest_df']})",
222
+ f" SD of individual response: {_f(c['sd_ir'])} "
223
+ f"(95% CI {_f(c['sd_ir_ci_low'])} to {_f(c['sd_ir_ci_high'])})",
224
+ f" Test that differences vary more than noise: one-sided p = "
225
+ f"{_f(c['p_response_variance'], 3)}",
226
+ ]
227
+ L += [" " + c["statement"]]
228
+ m = r["mixture"]
229
+ L += [
230
+ "",
231
+ "Two-group mixture check (responders versus non-responders)",
232
+ f" likelihood-ratio statistic {_f(m['lrt'])}, bootstrap p = {_f(m['p_bootstrap'], 3)} "
233
+ f"({m['n_bootstrap']} bootstrap samples, n={m['n']})",
234
+ f" best two-group fit: {_f(100 * m['weight_low'], 0)}% around {_f(m['mean_low'])}, "
235
+ f"the rest around {_f(m['mean_high'])}, common SD {_f(m['component_sd'])}",
236
+ f" false-positive rate at this sample size: {_f(100 * m['false_positive_rate_normal'], 0)}"
237
+ "% if noise is normal"
238
+ + (
239
+ ""
240
+ if m["false_positive_rate_heavy_tailed"] is None
241
+ else f", {_f(100 * m['false_positive_rate_heavy_tailed'], 0)}% if noise is "
242
+ "heavy-tailed (t, 5 df)"
243
+ ),
244
+ ]
245
+ if r["moderators"]:
246
+ L += ["", f"Pre-specified moderators ({r['moderator_correction']} correction)"]
247
+ for row in r["moderators"]:
248
+ L.append(
249
+ f" {row['moderator']}: effect changes by {_f(row['interaction'], 3)} per unit "
250
+ f"(95% CI {_f(row['ci_low'], 3)} to {_f(row['ci_high'], 3)}), "
251
+ f"p = {_f(row['p_raw'], 3)}, corrected p = {_f(row['p_adjusted'], 3)}"
252
+ )
253
+ L += ["", r["disclaimer"]]
254
+ return "\n".join(L)
repairsplit/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """Command line: `repairsplit analyze` and `repairsplit simulate`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ import pandas as pd
10
+
11
+ from . import __version__
12
+ from .analyze import FormatError, analyze, format_report
13
+ from .moderators import DEFAULT_MAX_MODERATORS, TooManyModerators
14
+ from .simulate import NOISE_KINDS, Scenario, simulate_trial
15
+
16
+
17
+ def build_parser() -> argparse.ArgumentParser:
18
+ p = argparse.ArgumentParser(
19
+ prog="repairsplit",
20
+ description="Responders versus a uniform shift in small two-arm or crossover trials. "
21
+ "Statistics only; not medical advice.",
22
+ )
23
+ p.add_argument("--version", action="version", version=__version__)
24
+ sub = p.add_subparsers(dest="command", required=True)
25
+
26
+ a = sub.add_parser("analyze", help="analyse a tidy trial CSV")
27
+ a.add_argument("csv")
28
+ a.add_argument("--design", choices=["auto", "parallel", "crossover"], default="auto")
29
+ a.add_argument("--treatment-label", default="treatment",
30
+ help="value of 'arm' that marks the treated arm (parallel)")
31
+ a.add_argument("--moderators", nargs="*", default=[],
32
+ help="pre-specified covariate columns to test as moderators")
33
+ a.add_argument("--max-moderators", type=int, default=DEFAULT_MAX_MODERATORS)
34
+ a.add_argument("--allow-many-moderators", action="store_true",
35
+ help="run even if more moderators are listed than --max-moderators")
36
+ a.add_argument("--correction", default="holm", choices=["holm", "bonferroni", "fdr_bh"])
37
+ a.add_argument("--retest-sd-diff", type=float, default=None,
38
+ help="crossover: outside test-retest SD of the difference between two "
39
+ "measurements on the same untreated person")
40
+ a.add_argument("--retest-sd-within", type=float, default=None,
41
+ help="crossover: outside within-person SD of one measurement "
42
+ "(converted to an SD of differences by multiplying by sqrt 2)")
43
+ a.add_argument("--retest-df", type=float, default=None,
44
+ help="degrees of freedom of the outside estimate (people minus 1); "
45
+ "omit to treat it as known exactly")
46
+ a.add_argument("--bootstrap", type=int, default=999)
47
+ a.add_argument("--fpr-sims", type=int, default=400,
48
+ help="simulations for the heavy-tailed false-positive rate (0 = skip)")
49
+ a.add_argument("--seed", type=int, default=0)
50
+ a.add_argument("--json", action="store_true", help="print JSON instead of text")
51
+
52
+ s = sub.add_parser("simulate", help="write a simulated trial with a known answer")
53
+ s.add_argument("--design", choices=["parallel", "crossover"], required=True)
54
+ s.add_argument("--n", type=int, required=True, help="total participants")
55
+ s.add_argument("--responder-share", type=float, required=True)
56
+ s.add_argument("--responder-effect", type=float, required=True)
57
+ s.add_argument("--between-sd", type=float, required=True)
58
+ s.add_argument("--noise-sd", type=float, required=True,
59
+ help="SD of one measurement around a person's true level")
60
+ s.add_argument("--moderator-corr", type=float, default=0.0)
61
+ s.add_argument("--baseline-mean", type=float, default=0.0)
62
+ s.add_argument("--period-effect", type=float, default=0.0)
63
+ s.add_argument("--carryover", type=float, default=0.0)
64
+ s.add_argument("--noise", choices=NOISE_KINDS, default="normal")
65
+ s.add_argument("--seed", type=int, default=0)
66
+ s.add_argument("--out", default="-", help="output CSV path, '-' for stdout")
67
+ return p
68
+
69
+
70
+ def main(argv: list[str] | None = None) -> int:
71
+ args = build_parser().parse_args(argv)
72
+ if args.command == "simulate":
73
+ sc = Scenario(
74
+ design=args.design, n=args.n, responder_share=args.responder_share,
75
+ responder_effect=args.responder_effect, between_sd=args.between_sd,
76
+ noise_sd=args.noise_sd, moderator_corr=args.moderator_corr,
77
+ baseline_mean=args.baseline_mean, period_effect=args.period_effect,
78
+ carryover=args.carryover, noise=args.noise,
79
+ )
80
+ df = simulate_trial(sc, args.seed)
81
+ df.to_csv(sys.stdout if args.out == "-" else args.out, index=False)
82
+ return 0
83
+
84
+ if args.retest_sd_diff is not None and args.retest_sd_within is not None:
85
+ print("error: give --retest-sd-diff or --retest-sd-within, not both", file=sys.stderr)
86
+ return 2
87
+ retest = args.retest_sd_diff
88
+ if args.retest_sd_within is not None:
89
+ retest = args.retest_sd_within * 2**0.5
90
+ try:
91
+ result = analyze(
92
+ pd.read_csv(args.csv, keep_default_na=True),
93
+ moderators=args.moderators,
94
+ design=args.design,
95
+ treatment_label=args.treatment_label,
96
+ retest_sd_difference=retest,
97
+ retest_df=args.retest_df,
98
+ max_moderators=args.max_moderators,
99
+ allow_many_moderators=args.allow_many_moderators,
100
+ correction=args.correction,
101
+ n_bootstrap=args.bootstrap,
102
+ seed=args.seed,
103
+ fpr_sims=args.fpr_sims,
104
+ )
105
+ except (FormatError, TooManyModerators, ValueError) as exc:
106
+ print(f"error: {exc}", file=sys.stderr)
107
+ return 2
108
+ print(json.dumps(result, indent=2) if args.json else format_report(result))
109
+ return 0
110
+
111
+
112
+ if __name__ == "__main__":
113
+ raise SystemExit(main())
@@ -0,0 +1,183 @@
1
+ """What a two-period crossover can and cannot say about individual response.
2
+
3
+ Model for participant i in period j:
4
+
5
+ y_ij = person_i + period_j + response_i * treated_ij + noise_ij
6
+
7
+ Each person gives one treated value and one control value. Their difference is
8
+
9
+ d_i = response_i +/- period effect + (noise_i,treated - noise_i,control)
10
+
11
+ so, within a sequence group,
12
+
13
+ Var(d) = Var(response) + 2 * Var(noise).
14
+
15
+ ESTIMABLE from a plain two-period crossover:
16
+ * the mean treatment effect and the period effect;
17
+ * Var(d), the SUM of response variance and noise variance;
18
+ * therefore an UPPER BOUND on the SD of individual response (if noise were
19
+ zero, all of Var(d) would be response).
20
+
21
+ NOT ESTIMABLE from a plain two-period crossover:
22
+ * Var(response) on its own. A person who "improved more on drug" may simply
23
+ have had two noisy measurements. Participant-by-treatment interaction is
24
+ completely confounded with within-person noise. No analysis of the trial's
25
+ own data can pull them apart (Senn 2001, 2016).
26
+
27
+ What breaks the confounding:
28
+ * replicated periods (each person gets each treatment at least twice); not
29
+ implemented in this version;
30
+ * an OUTSIDE estimate of the noise: the SD of the difference between two
31
+ measurements on the same untreated person, taken about as far apart as the
32
+ two period-end measurements. Supply it and Var(response) = Var(d) - noise.
33
+ This is only as good as the assumption that the outside study's noise
34
+ applies to this trial's people, equipment and time gap.
35
+
36
+ Carryover is assumed absent. If the treatment effect persists into the control
37
+ period, differences shrink in the treatment-first group and Var(d) is distorted.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from dataclasses import asdict, dataclass
43
+
44
+ import numpy as np
45
+ from scipy import stats
46
+
47
+ from .variance import signed_sqrt, var_diff_ci
48
+
49
+
50
+ @dataclass
51
+ class CrossoverResult:
52
+ n: int
53
+ n_treatment_first: int
54
+ n_control_first: int
55
+ mean_effect: float
56
+ mean_effect_ci_low: float
57
+ mean_effect_ci_high: float
58
+ period_effect: float
59
+ sd_difference: float
60
+ df: int
61
+ ci_level: float
62
+ sd_ir_estimable: bool
63
+ sd_ir_upper_bound: float
64
+ sd_ir_upper_bound_conf_limit: float
65
+ retest_sd_difference: float | None
66
+ retest_df: float | None
67
+ sd_ir: float | None
68
+ sd_ir_ci_low: float | None
69
+ sd_ir_ci_high: float | None
70
+ p_response_variance: float | None
71
+ statement: str
72
+
73
+ def to_dict(self) -> dict:
74
+ return asdict(self)
75
+
76
+
77
+ def pooled_difference_variance(d_tc, d_ct):
78
+ """Pooled within-sequence variance of treated-minus-control differences.
79
+
80
+ Arrays may carry leading batch axes. Returns (variance, df).
81
+ """
82
+ d_tc = np.asarray(d_tc, dtype=float)
83
+ d_ct = np.asarray(d_ct, dtype=float)
84
+ n1, n2 = d_tc.shape[-1], d_ct.shape[-1]
85
+ df = n1 + n2 - 2
86
+ ss = (n1 - 1) * d_tc.var(axis=-1, ddof=1) + (n2 - 1) * d_ct.var(axis=-1, ddof=1)
87
+ return ss / df, df
88
+
89
+
90
+ def retest_p(var_d, df, retest_var, retest_df=None):
91
+ """One-sided p-value that Var(d) exceeds the outside noise variance.
92
+
93
+ With retest_df the outside estimate is treated as a sample variance (F test).
94
+ Without it the noise variance is treated as known exactly (chi-square test),
95
+ which overstates the evidence unless the outside study was very large.
96
+ """
97
+ ratio = np.asarray(var_d, dtype=float) / np.asarray(retest_var, dtype=float)
98
+ if retest_df is None:
99
+ return stats.chi2.sf(ratio * df, df)
100
+ return stats.f.sf(ratio, df, retest_df)
101
+
102
+
103
+ def period_adjusted_differences(d_tc, d_ct):
104
+ """Differences with the period effect removed, centred on the mean effect."""
105
+ d_tc = np.asarray(d_tc, dtype=float)
106
+ d_ct = np.asarray(d_ct, dtype=float)
107
+ m1 = d_tc.mean(axis=-1, keepdims=True)
108
+ m2 = d_ct.mean(axis=-1, keepdims=True)
109
+ effect = (m1 + m2) / 2.0
110
+ return d_tc - m1 + effect, d_ct - m2 + effect
111
+
112
+
113
+ def analyze_differences(
114
+ d_tc,
115
+ d_ct,
116
+ retest_sd_difference: float | None = None,
117
+ retest_df: float | None = None,
118
+ level: float = 0.95,
119
+ ) -> CrossoverResult:
120
+ """Crossover analysis from treated-minus-control differences by sequence.
121
+
122
+ d_tc: differences for participants who had treatment first.
123
+ d_ct: differences for participants who had control first.
124
+ """
125
+ d_tc = np.asarray(d_tc, dtype=float)
126
+ d_ct = np.asarray(d_ct, dtype=float)
127
+ n1, n2 = d_tc.size, d_ct.size
128
+ if n1 < 2 or n2 < 2:
129
+ raise ValueError("need at least 2 participants in each sequence")
130
+ m1, m2 = d_tc.mean(), d_ct.mean()
131
+ var_d, df = pooled_difference_variance(d_tc, d_ct)
132
+ var_d = float(var_d)
133
+ effect = (m1 + m2) / 2.0
134
+ se = np.sqrt(var_d / 4.0 * (1.0 / n1 + 1.0 / n2))
135
+ tcrit = stats.t.ppf(0.5 + level / 2.0, df)
136
+ upper_var = df * var_d / stats.chi2.ppf(1.0 - level, df)
137
+
138
+ sd_ir = lo = hi = p = None
139
+ estimable = retest_sd_difference is not None
140
+ if estimable:
141
+ nv = retest_sd_difference**2
142
+ if retest_df is None:
143
+ a = (1.0 - level) / 2.0
144
+ diff = var_d - nv
145
+ v_lo = df * var_d / stats.chi2.ppf(1 - a, df) - nv
146
+ v_hi = df * var_d / stats.chi2.ppf(a, df) - nv
147
+ else:
148
+ diff, v_lo, v_hi = var_diff_ci(var_d, df, nv, retest_df, level)
149
+ sd_ir, lo, hi = (float(signed_sqrt(v)) for v in (diff, v_lo, v_hi))
150
+ p = float(retest_p(var_d, df, nv, retest_df))
151
+ statement = (
152
+ "SD of individual response is estimated by subtracting the supplied outside "
153
+ "test-retest noise from the variance of within-person differences. It is valid "
154
+ "only if that noise estimate applies to this trial."
155
+ )
156
+ else:
157
+ statement = (
158
+ "A plain two-period crossover cannot separate individual response from "
159
+ "within-person noise. Only the upper bound is reported. Supply an outside "
160
+ "test-retest SD of differences to estimate the SD of individual response."
161
+ )
162
+ return CrossoverResult(
163
+ n=n1 + n2,
164
+ n_treatment_first=n1,
165
+ n_control_first=n2,
166
+ mean_effect=float(effect),
167
+ mean_effect_ci_low=float(effect - tcrit * se),
168
+ mean_effect_ci_high=float(effect + tcrit * se),
169
+ period_effect=float((m2 - m1) / 2.0),
170
+ sd_difference=float(np.sqrt(var_d)),
171
+ df=int(df),
172
+ ci_level=level,
173
+ sd_ir_estimable=estimable,
174
+ sd_ir_upper_bound=float(np.sqrt(var_d)),
175
+ sd_ir_upper_bound_conf_limit=float(np.sqrt(upper_var)),
176
+ retest_sd_difference=retest_sd_difference,
177
+ retest_df=retest_df,
178
+ sd_ir=sd_ir,
179
+ sd_ir_ci_low=lo,
180
+ sd_ir_ci_high=hi,
181
+ p_response_variance=p,
182
+ statement=statement,
183
+ )