pase-framework 1.0.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.
pase/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Patient-level association estimates for multi-patient single-cell studies."""
2
+
3
+ from .association import associate
4
+ from .result import AssociationResult
5
+ from . import datasets
6
+
7
+ __version__ = "1.0.0"
8
+ __all__ = ["associate", "AssociationResult", "datasets", "__version__"]
pase/_statistics.py ADDED
@@ -0,0 +1,255 @@
1
+ """Patient-level PASE summaries. The r and Fisher-z summaries have distinct targets."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from functools import lru_cache
6
+
7
+ import numpy as np
8
+ from scipy import optimize, special
9
+
10
+
11
+ def _number(value):
12
+ if isinstance(value, (bool, np.bool_)):
13
+ return None
14
+ try:
15
+ result = float(value)
16
+ except (ValueError, TypeError, OverflowError):
17
+ return None
18
+ return result if math.isfinite(result) else None
19
+
20
+
21
+ def _count(value):
22
+ result = _number(value)
23
+ if result is None or not result.is_integer() or not 0 <= result < 2**53:
24
+ return None
25
+ return int(result)
26
+
27
+
28
+ def _patient(row):
29
+ pid = row.get("patient_id")
30
+ if pid is None or not str(pid).strip():
31
+ raise ValueError("Each record requires a patient_id.")
32
+ eligible = str(row.get("eligible", True)).strip().lower()
33
+ if eligible not in ("true", "false", "1", "0"):
34
+ raise ValueError(f"Unrecognized upstream eligibility for patient {pid}.")
35
+ r = _number(row.get("r", row.get("partial_r")))
36
+ n = _count(row.get("n", row.get("n_cells")))
37
+ rank = _count(row.get("design_rank"))
38
+ k = _count(row.get("k")) if "k" in row else rank - 1 if rank else None
39
+ equal_reason = None
40
+ if eligible in ("false", "0"):
41
+ equal_reason = row.get("failure_reason") or "upstream_ineligible"
42
+ elif r is None or abs(r) > 1:
43
+ equal_reason = "missing_or_invalid_r"
44
+ elif n is not None and k is not None and n - k - 1 < 2:
45
+ equal_reason = "insufficient_residual_df"
46
+ fisher_reason = equal_reason
47
+ if fisher_reason is None:
48
+ if abs(r) == 1:
49
+ fisher_reason = "boundary_r"
50
+ elif n is None:
51
+ fisher_reason = "missing_or_invalid_complete_case_n"
52
+ elif k is None:
53
+ fisher_reason = "missing_or_invalid_covariate_rank"
54
+ elif n - k - 3 <= 0:
55
+ fisher_reason = "nonpositive_fisher_denominator"
56
+ elif "design_rank" in row and "k" in row and rank != k + 1:
57
+ fisher_reason = "inconsistent_design_rank"
58
+ return {
59
+ "patient_id": str(pid), "r": r, "n": n, "k": k,
60
+ "equal_eligible": equal_reason is None, "equal_reason": equal_reason,
61
+ "fisher_eligible": fisher_reason is None, "fisher_reason": fisher_reason,
62
+ "z": math.atanh(r) if fisher_reason is None else None,
63
+ "v": 1.0 / (n - k - 3) if fisher_reason is None else None,
64
+ }
65
+
66
+
67
+ @lru_cache(maxsize=256)
68
+ def _critical(alpha, df):
69
+ return -float(special.ndtri(alpha / 2) if df is None
70
+ else special.stdtrit(df, alpha / 2))
71
+
72
+
73
+ def _interval(mean, se, alpha, df=None, fisher=False):
74
+ if se is None:
75
+ return dict(ci_low=None, ci_high=None, se=None, p_value=None,
76
+ df=df, status="insufficient_patients")
77
+ if se == 0:
78
+ return dict(ci_low=None, ci_high=None, se=0.0, p_value=None,
79
+ df=df, status="degenerate_zero_se")
80
+ margin = _critical(alpha, df) * se
81
+ lo, hi = mean - margin, mean + margin
82
+ if fisher:
83
+ lo, hi = math.tanh(lo), math.tanh(hi)
84
+ if lo >= hi:
85
+ return dict(ci_low=None, ci_high=None, se=se, p_value=None, df=df,
86
+ status="degenerate_zero_width")
87
+ t = -abs(mean / se)
88
+ p = 2 * float(special.ndtr(t) if df is None else special.stdtr(df, t))
89
+ return dict(ci_low=lo, ci_high=hi, se=se, p_value=p, df=df,
90
+ status="ok")
91
+
92
+
93
+ def _equal(rows, alpha):
94
+ r = np.array([p["r"] for p in rows if p["equal_eligible"]])
95
+ j = len(r)
96
+ mean = float(r.mean()) if j else None
97
+ if j and np.all(r == r[0]):
98
+ mean = float(r[0])
99
+ se = 0.0 if j > 1 else None
100
+ else:
101
+ se = float(r.std(ddof=1) / math.sqrt(j)) if j > 1 else None
102
+ return dict(J=j, estimate=mean, target="equal_patient_arithmetic_mean_of_finite_cell_r",
103
+ **_interval(mean, se, alpha, df=(j - 1 if j > 1 else None)))
104
+
105
+
106
+ def _weighted_mean(z, w):
107
+ # Center first, giving exact zero residuals for identical z values.
108
+ return float(z[0] + np.dot(w, z - z[0]) / w.sum())
109
+
110
+
111
+ def _reml_tau2(z, v):
112
+ """Minimize the intercept-only restricted negative log-likelihood over tau² >= 0."""
113
+ if len(z) == 2:
114
+ return max(0.0, float(((z[0] - z[1])**2 - v.sum()) / 2))
115
+ if np.all(v == v[0]):
116
+ return max(0.0, float(z.var(ddof=1) - v[0]))
117
+ # In orthonormal intercept-free contrasts the upper bound on any squared
118
+ # contrast coefficient is ||z-zbar||². Above this bound minus min(v),
119
+ # every contrast's negative log-likelihood is increasing.
120
+ ss = float(np.sum((z - z.mean())**2))
121
+ upper = ss - float(v.min())
122
+ if upper <= 0:
123
+ return 0.0
124
+ # Score stationary points can include multiple optima. Sample a log1p
125
+ # scale anchored to the smallest variance and refine each visible basin.
126
+ scale = float(v.min())
127
+ limit = math.log1p(upper / scale)
128
+ grid = np.linspace(0.0, limit, max(41, math.ceil(limit / 0.08) + 1))
129
+ t = scale * np.expm1(grid)
130
+ def objective(x):
131
+ var = v + scale * math.expm1(x)
132
+ w = 1 / var
133
+ resid = z - _weighted_mean(z, w)
134
+ return float(np.log(var).sum() + math.log(w.sum()) + np.dot(w, resid**2))
135
+ var = v[None, :] + t[:, None]
136
+ w = 1 / var
137
+ mu = z[0] + (w * (z - z[0])).sum(axis=1) / w.sum(axis=1)
138
+ loss = (np.log(var).sum(axis=1) + np.log(w.sum(axis=1))
139
+ + (w * (z - mu[:, None])**2).sum(axis=1))
140
+ best_x, best_loss = 0.0, float(loss[0])
141
+ basins = list(np.where((loss[1:-1] <= loss[:-2]) & (loss[1:-1] <= loss[2:]))[0] + 1)
142
+ # A shallow interior minimum can lie between the boundary and first grid point.
143
+ basins.extend([0, len(grid) - 1])
144
+ for i in basins:
145
+ lo, hi = grid[max(0, i - 1)], grid[min(len(grid) - 1, i + 1)]
146
+ fit = optimize.minimize_scalar(objective, bounds=(lo, hi), method="bounded",
147
+ options={"xatol": 1e-13, "maxiter": 150})
148
+ if not fit.success or not np.isfinite(fit.fun):
149
+ raise ArithmeticError("restricted likelihood minimization failed")
150
+ # Prefer the exact boundary when differences are at round-off scale.
151
+ tol = 8 * np.finfo(float).eps * max(1.0, abs(best_loss))
152
+ if fit.fun < best_loss - tol:
153
+ best_x, best_loss = float(fit.x), float(fit.fun)
154
+ return scale * math.expm1(best_x)
155
+
156
+
157
+ def _empty_weighted(j, reason):
158
+ skipped = dict(ci_low=None, ci_high=None, p_value=None, se=None, df=None, status=reason)
159
+ return dict(J=j, estimate=None, estimate_z=None, tau2=None, weights={},
160
+ q=None, wald=skipped.copy(), hk=skipped.copy(), mkh=skipped.copy(),
161
+ ci_low=None, ci_high=None, p_value=None, status=reason)
162
+
163
+
164
+ def _fit_z(pids, z, v, tau2, alpha, random):
165
+ w = 1 / (v + tau2)
166
+ mu = _weighted_mean(z, w)
167
+ j = len(z)
168
+ se = math.sqrt(1 / float(w.sum()))
169
+ weights = dict(zip(pids, (float(x) for x in w / w.sum())))
170
+ target = ("backtransformed_random_effects_mean_fisher_z" if random
171
+ else "backtransformed_common_effect_or_precision_weighted_fisher_z")
172
+ result = dict(J=j, estimate=math.tanh(mu), estimate_z=mu, weights=weights,
173
+ target=target, tau2=tau2, status="ok")
174
+ wald = _interval(mu, se, alpha, fisher=True)
175
+ if not random:
176
+ return {**result, **wald}
177
+ df = j - 1
178
+ q = float(np.dot(w, (z - mu)**2) / df)
179
+ return dict(result, q=q, wald=wald,
180
+ hk=_interval(mu, math.sqrt(q) * se, alpha, df, True),
181
+ mkh=_interval(mu, math.sqrt(max(1.0, q)) * se, alpha, df, True))
182
+
183
+
184
+ def summarize_patients(records, alpha=0.05, shrinkage=False):
185
+ """Summarize one record per independent patient. See README.md for schema."""
186
+ if not 0 < alpha < 1:
187
+ raise ValueError("alpha must lie strictly between zero and one.")
188
+ rows = [_patient(row) for row in records]
189
+ if len(set(p["patient_id"] for p in rows)) != len(rows):
190
+ raise ValueError("Duplicate patient_id. Supply one effect per independent patient.")
191
+ fit_rows = [p for p in rows if p["fisher_eligible"]]
192
+ j = len(fit_rows)
193
+ ids = [p["patient_id"] for p in fit_rows]
194
+ z = np.array([p["z"] for p in fit_rows])
195
+ v = np.array([p["v"] for p in fit_rows])
196
+ out = dict(equal_r=_equal(rows, alpha), patients=rows, alpha=alpha, warnings=[],
197
+ shrinkage=[], shrinkage_status="not_requested")
198
+ if j < len([p for p in rows if p["equal_eligible"]]):
199
+ out["warnings"].append("Fisher analyses use a smaller eligible patient set than equal-r.")
200
+ if j < 2:
201
+ for name in ("fixed_z", "dl", "reml"):
202
+ out[name] = _empty_weighted(j, "insufficient_patients")
203
+ if shrinkage:
204
+ out["shrinkage_status"] = "insufficient_patients"
205
+ return out
206
+ if j <= 5:
207
+ out["warnings"].append("Few patients: heterogeneity and t intervals have limited precision.")
208
+ out["fixed_z"] = _fit_z(ids, z, v, 0.0, alpha, False)
209
+ w = 1 / v
210
+ q_fe = float(np.dot(w, (z - out["fixed_z"]["estimate_z"])**2))
211
+ out["fixed_z"]["Q"] = q_fe
212
+ # 2 sum_{i<j} w_i w_j / sum(w), stable under extreme imbalance.
213
+ sorted_w = np.sort(w)
214
+ c_dl = 2 * float(np.dot(sorted_w[1:], np.cumsum(sorted_w)[:-1])) / w.sum()
215
+ tau2_dl = max(0.0, float((q_fe - j + 1) / c_dl))
216
+ out["dl"] = _fit_z(ids, z, v, tau2_dl, alpha, True)
217
+ try:
218
+ tau2_reml = _reml_tau2(z, v)
219
+ except (ArithmeticError, RuntimeError, ValueError) as error:
220
+ out["reml"] = _empty_weighted(j, "reml_optimization_failed")
221
+ out["warnings"].append(str(error))
222
+ if shrinkage:
223
+ out["shrinkage_status"] = "reml_optimization_failed"
224
+ return out
225
+ reml = out["reml"] = _fit_z(ids, z, v, tau2_reml, alpha, True)
226
+ if shrinkage:
227
+ status = "conditional_plugin" if tau2_reml > 0 else "zero_tau2_complete_pooling"
228
+ out["shrinkage_status"] = status
229
+ for p in fit_rows:
230
+ b = tau2_reml / (tau2_reml + p["v"])
231
+ mean = reml["estimate_z"] + b * (p["z"] - reml["estimate_z"])
232
+ se = math.sqrt(b * p["v"])
233
+ delta = _critical(alpha, None) * se
234
+ out["shrinkage"].append(dict(patient_id=p["patient_id"], status=status,
235
+ observed_data_weight=b, estimate_z=mean, estimate=math.tanh(mean),
236
+ conditional_se_z=se, ci_low=math.tanh(mean - delta) if se else None,
237
+ ci_high=math.tanh(mean + delta) if se else None))
238
+ return out
239
+
240
+
241
+ def summarize_arrays(r, n, k, alpha=0.05, shrinkage=False):
242
+ """Array interface using positional IDs. n and k may be scalar or patient-aligned."""
243
+ r = np.asarray(r, dtype=object)
244
+ if r.ndim != 1:
245
+ raise ValueError("r must be one-dimensional.")
246
+ def patient_values(value):
247
+ arr = np.asarray(value, dtype=object)
248
+ if arr.ndim == 0:
249
+ return np.full(r.shape, arr.item(), dtype=object)
250
+ if arr.shape != r.shape:
251
+ raise ValueError("n and k must be scalars or the same length as r.")
252
+ return arr
253
+ rows = (dict(patient_id=i, r=value, n=count, k=rank)
254
+ for i, (value, count, rank) in enumerate(zip(r, patient_values(n), patient_values(k))))
255
+ return summarize_patients(rows, alpha=alpha, shrinkage=shrinkage)
pase/association.py ADDED
@@ -0,0 +1,368 @@
1
+ """AnnData interface for patient-level molecular associations."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Sequence
5
+ from numbers import Integral, Real
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from scipy import sparse
10
+
11
+ from ._statistics import summarize_patients
12
+ from .result import AssociationResult
13
+
14
+
15
+ def _integer(value, name, minimum):
16
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < minimum:
17
+ raise ValueError(f"{name} must be an integer >= {minimum}.")
18
+ return int(value)
19
+
20
+
21
+ def _names(value, name, allow_empty=False):
22
+ if isinstance(value, str):
23
+ result = [value]
24
+ elif isinstance(value, Sequence) or isinstance(value, (np.ndarray, pd.Index)):
25
+ result = list(value)
26
+ else:
27
+ raise TypeError(f"{name} must be a column/gene name or a sequence of names.")
28
+ if (not result and not allow_empty) or any(not isinstance(x, str) or not x.strip() for x in result):
29
+ raise ValueError(f"{name} must contain nonempty string names.")
30
+ if len(set(result)) != len(result):
31
+ raise ValueError(f"{name} contains duplicate names.")
32
+ return result
33
+
34
+
35
+ def _patient_names(values, name):
36
+ result = []
37
+ for value in values:
38
+ if not np.isscalar(value) or pd.isna(value) or not str(value).strip():
39
+ raise ValueError(f"{name} contains missing or empty patient identifiers.")
40
+ result.append(str(value))
41
+ return result
42
+
43
+
44
+ def _mask(obs, value):
45
+ if value is None:
46
+ return np.ones(len(obs), dtype=bool)
47
+ if isinstance(value, str):
48
+ if value not in obs:
49
+ raise KeyError(f"cell_mask column {value!r} is absent from adata.obs.")
50
+ value = obs[value]
51
+ if isinstance(value, pd.Series) and not value.index.equals(obs.index):
52
+ raise ValueError("A Series cell_mask must have exactly the same index and order as adata.obs.")
53
+ arr = np.asarray(value)
54
+ if arr.ndim != 1 or len(arr) != len(obs):
55
+ raise ValueError("cell_mask must be a one-dimensional boolean vector with one value per cell.")
56
+ if pd.isna(arr).any():
57
+ raise ValueError("cell_mask must not contain missing values.")
58
+ if not all(isinstance(v, (bool, np.bool_)) for v in arr):
59
+ raise TypeError("cell_mask must contain booleans, not strings or numeric indicators.")
60
+ return arr.astype(bool, copy=True)
61
+
62
+
63
+ def _partial_correlation(x, y, design):
64
+ """Residualize against a rank-aware least-squares nuisance model."""
65
+ rank = int(np.linalg.matrix_rank(design))
66
+ residual_df = len(x) - rank
67
+ if residual_df < 3:
68
+ return np.nan, rank, residual_df, "insufficient_residual_df"
69
+ # Center and scale outcomes first for numerical stability. The design has
70
+ # an intercept, so these operations leave its partial correlation unchanged.
71
+ x = np.asarray(x, dtype=float) - np.mean(x)
72
+ y = np.asarray(y, dtype=float) - np.mean(y)
73
+ x_scale = np.max(np.abs(x))
74
+ y_scale = np.max(np.abs(y))
75
+ if x_scale == 0 or y_scale == 0:
76
+ return np.nan, rank, residual_df, "zero_residual_variance"
77
+ x, y = x / x_scale, y / y_scale
78
+ residuals = np.column_stack([x, y])
79
+ residuals -= design @ np.linalg.lstsq(design, residuals, rcond=None)[0]
80
+ ux, uy = residuals.T
81
+ nx, ny = np.linalg.norm(ux), np.linalg.norm(uy)
82
+ tol = 64 * np.finfo(float).eps
83
+ if nx <= tol * np.linalg.norm(x) or ny <= tol * np.linalg.norm(y):
84
+ return np.nan, rank, residual_df, "zero_residual_variance"
85
+ correlation = float(np.dot(ux / nx, uy / ny))
86
+ if not np.isfinite(correlation):
87
+ return np.nan, rank, residual_df, "numerical_failure"
88
+ correlation = float(np.clip(correlation, -1.0, 1.0))
89
+ if 1 - abs(correlation) <= 8 * np.finfo(float).eps:
90
+ correlation = float(np.sign(correlation))
91
+ return correlation, rank, residual_df, None
92
+
93
+
94
+ def _patient_effect(pid, indices, mask, expression, covariate_values, module, min_cells):
95
+ selected = indices[mask[indices]]
96
+ result = dict(patient_id=pid, n_total=len(indices), n_selected=len(selected),
97
+ n_expression_complete=0, n_complete=0, n_cells=0,
98
+ n_nonfinite_expression=0, n_nonfinite_covariates=0,
99
+ design_rank=0, residual_df=0, r=np.nan, eligible=False,
100
+ failure_reason=None)
101
+ if not len(indices):
102
+ result["failure_reason"] = "no_observed_cells"
103
+ return result
104
+ if not len(selected):
105
+ result["failure_reason"] = "no_selected_cells"
106
+ return result
107
+ values = expression[selected]
108
+ finite_expression = np.isfinite(values).all(axis=1)
109
+ result["n_nonfinite_expression"] = int((~finite_expression).sum())
110
+ selected = selected[finite_expression]
111
+ values = values[finite_expression]
112
+ result["n_expression_complete"] = len(selected)
113
+ if not len(selected):
114
+ result["failure_reason"] = "no_finite_expression"
115
+ return result
116
+ x = values[:, 0]
117
+ if module:
118
+ outcomes = values[:, 1:]
119
+ centered = outcomes - outcomes.mean(axis=0)
120
+ scale = outcomes.std(axis=0, ddof=1) if len(outcomes) > 1 else np.zeros(outcomes.shape[1])
121
+ varying = np.ptp(outcomes, axis=0) != 0
122
+ standardized = np.divide(centered, scale, out=np.zeros_like(centered),
123
+ where=varying & (scale > 0))
124
+ y = standardized.mean(axis=1)
125
+ else:
126
+ y = values[:, 1]
127
+ nuisance = covariate_values[selected]
128
+ complete = np.isfinite(nuisance).all(axis=1)
129
+ result["n_nonfinite_covariates"] = int((~complete).sum())
130
+ n = int(complete.sum())
131
+ result["n_complete"] = result["n_cells"] = n
132
+ if not n:
133
+ result["failure_reason"] = "no_complete_cases"
134
+ return result
135
+ # Standardization preserves the projection with an intercept while keeping
136
+ # numerical rank invariant to covariate units. Constant columns add no rank.
137
+ design_columns = [np.ones(n)]
138
+ for values in nuisance[complete].T:
139
+ if n > 1 and np.ptp(values) != 0:
140
+ centered = values - values.mean()
141
+ size = np.max(np.abs(centered))
142
+ scaled = centered / size
143
+ design_columns.append(scaled / scaled.std(ddof=1))
144
+ design = np.column_stack(design_columns)
145
+ try:
146
+ r, rank, df, failure = _partial_correlation(x[complete], y[complete], design)
147
+ except (np.linalg.LinAlgError, FloatingPointError, ValueError):
148
+ r, rank, df, failure = np.nan, 0, 0, "numerical_failure"
149
+ result.update(r=r, design_rank=rank, residual_df=df)
150
+ result["failure_reason"] = failure or ("below_min_cells" if n < min_cells else None)
151
+ result["eligible"] = result["failure_reason"] is None
152
+ return result
153
+
154
+
155
+ def associate(adata, anchor, target, patient_key, covariates=None, cell_mask=None,
156
+ aggregate="equal", min_cells=30, min_patients=2, layer=None,
157
+ alpha=0.05, patient_ids=None):
158
+ """Estimate an association within each patient and summarize across patients.
159
+
160
+ Parameters
161
+ ----------
162
+ adata : anndata.AnnData
163
+ Cells by genes. X (or ``layer``) must already contain transformed
164
+ expression, such as log1p(CP10K). This function does not normalize counts.
165
+ anchor : str
166
+ Anchor gene name in ``adata.var_names``.
167
+ target : str or sequence of str
168
+ A gene, or a module computed as the mean of within-patient gene z scores
169
+ (sample SD, ddof=1). Constant measured genes contribute zero. Module
170
+ standardization precedes covariate complete-case filtering.
171
+ patient_key : str
172
+ Column in ``adata.obs`` identifying independent patients.
173
+ covariates : sequence of str, optional
174
+ Numeric observation columns centered and scaled within each patient's
175
+ complete cells, then included with an intercept in least-squares
176
+ residualization. Constant columns add no rank; collinear covariates use
177
+ the design rank. Scaling does not change the regression projection.
178
+ cell_mask : str or boolean vector, optional
179
+ Boolean observation column or cell-aligned selection. Patients with no
180
+ selected cells remain in the output. Missing mask values are an error.
181
+ aggregate : {'equal', 're_hksj', 'eb'}, default 'equal'
182
+ Arithmetic mean of patient correlations with a t interval; Fisher-z
183
+ random effects fitted by REML with classical HKSJ; or conditional
184
+ empirical Bayes patient estimates, respectively. Their targets differ.
185
+ min_cells : int, default 30
186
+ Minimum complete cells for patient eligibility. Regardless of this
187
+ setting, at least three residual degrees of freedom are required.
188
+ min_patients : int, default 2
189
+ Minimum eligible patients before inference is returned. Two is only a
190
+ mathematical minimum, not an empirically validated adequacy threshold.
191
+ layer : str, optional
192
+ Transformed-expression layer instead of X. ``adata.raw`` is not used.
193
+ alpha : float, default 0.05
194
+ Two-sided interval error probability.
195
+ patient_ids : sequence, optional
196
+ Additional patient IDs to retain even if they have no observed cells.
197
+ Observed IDs are always retained. Output IDs are strings.
198
+
199
+ Returns
200
+ -------
201
+ AssociationResult
202
+ Per-patient effects and exclusion reasons, a summary table, and metadata.
203
+
204
+ Notes
205
+ -----
206
+ Cells with nonfinite anchor or target expression are excluded before module
207
+ construction. Nonfinite covariates are then excluded. There is no outcome
208
+ detection gate. Fisher variance is approximated as 1/(n-k-3), with k equal
209
+ to design rank minus one; its independent-cell assumptions may not hold for
210
+ all single-cell data. Raw patient correlations remain visible when cohort
211
+ inference is withheld. Inputs are not modified.
212
+ """
213
+ min_cells = _integer(min_cells, "min_cells", 1)
214
+ min_patients = _integer(min_patients, "min_patients", 2)
215
+ if isinstance(alpha, (bool, np.bool_)) or not isinstance(alpha, Real) or not 0 < alpha < 1:
216
+ raise ValueError("alpha must be a finite number strictly between zero and one.")
217
+ if aggregate not in ("equal", "re_hksj", "eb"):
218
+ raise ValueError("aggregate must be 'equal', 're_hksj', or 'eb'.")
219
+ if not all(hasattr(adata, attr) for attr in ("obs", "var_names", "X", "layers")):
220
+ raise TypeError("adata must provide the AnnData cells-by-genes interface.")
221
+ obs = adata.obs
222
+ if not obs.columns.is_unique:
223
+ raise ValueError("adata.obs has duplicate column names.")
224
+ if not isinstance(patient_key, str) or patient_key not in obs:
225
+ raise KeyError("patient_key must name a column in adata.obs.")
226
+ anchor = _names(anchor, "anchor")
227
+ if len(anchor) != 1:
228
+ raise ValueError("anchor must be a single gene name.")
229
+ anchor = anchor[0]
230
+ module = not isinstance(target, str)
231
+ targets = _names(target, "target")
232
+ if anchor in targets:
233
+ raise ValueError("anchor must not also occur in target.")
234
+ if not adata.var_names.is_unique:
235
+ raise ValueError("adata.var_names contains duplicate gene names.")
236
+ genes = [anchor, *targets]
237
+ gene_indices = adata.var_names.get_indexer(genes)
238
+ missing = [gene for gene, index in zip(genes, gene_indices) if index < 0]
239
+ if missing:
240
+ raise KeyError(f"Genes missing from adata.var_names: {missing}.")
241
+ if layer is not None and (not isinstance(layer, str) or layer not in adata.layers):
242
+ raise KeyError(f"Requested layer {layer!r} is absent from adata.layers.")
243
+ matrix = adata.X if layer is None else adata.layers[layer]
244
+ selected_matrix = matrix[:, gene_indices]
245
+ if sparse.issparse(selected_matrix):
246
+ selected_matrix = selected_matrix.toarray()
247
+ expression = np.asarray(selected_matrix)
248
+ if not np.issubdtype(expression.dtype, np.number) or np.iscomplexobj(expression):
249
+ raise TypeError("Selected expression values must be real numeric data.")
250
+ expression = expression.astype(float, copy=False)
251
+ selected_mask = _mask(obs, cell_mask)
252
+ covariates = [] if covariates is None else _names(covariates, "covariates", allow_empty=True)
253
+ columns = []
254
+ for name in covariates:
255
+ if name not in obs:
256
+ raise KeyError(f"Covariate {name!r} is absent from adata.obs.")
257
+ if not pd.api.types.is_numeric_dtype(obs[name].dtype) or pd.api.types.is_complex_dtype(obs[name].dtype):
258
+ raise TypeError(f"Covariate {name!r} must be numeric; encode categories explicitly.")
259
+ columns.append(obs[name].to_numpy(dtype=float, na_value=np.nan))
260
+ nuisance = np.column_stack(columns) if columns else np.empty((len(obs), 0))
261
+ raw_ids = obs[patient_key].tolist()
262
+ ids = _patient_names(raw_ids, "patient_key")
263
+ # Do not merge distinct identifiers merely because their string forms match.
264
+ original_unique = pd.unique(obs[patient_key])
265
+ unique_ids = _patient_names(original_unique, "patient_key")
266
+ if len(set(unique_ids)) != len(unique_ids):
267
+ raise ValueError("Distinct patient identifiers collide after conversion to strings.")
268
+ if patient_ids is not None:
269
+ if isinstance(patient_ids, (str, bytes)):
270
+ raise TypeError("patient_ids must be a sequence, not a single string.")
271
+ additional_ids = _patient_names(list(patient_ids), "patient_ids")
272
+ if len(set(additional_ids)) != len(additional_ids):
273
+ raise ValueError("patient_ids contains duplicates.")
274
+ unique_ids.extend(pid for pid in additional_ids if pid not in set(unique_ids))
275
+ groups = {pid: [] for pid in unique_ids}
276
+ for index, pid in enumerate(ids):
277
+ groups[pid].append(index)
278
+ records = [_patient_effect(pid, np.asarray(indices, dtype=int), selected_mask,
279
+ expression, nuisance, module, min_cells)
280
+ for pid, indices in groups.items()]
281
+ # The statistical kernel retains the verified rank-aware Fisher variance
282
+ # and equal-r / REML / HK calculations used by the standalone implementation.
283
+ fits = summarize_patients(records, alpha=float(alpha), shrinkage=aggregate == "eb")
284
+ patient_columns = ["patient_id", "n_total", "n_selected", "n_expression_complete",
285
+ "n_complete", "n_cells", "n_nonfinite_expression", "n_nonfinite_covariates",
286
+ "design_rank", "residual_df", "r", "eligible", "failure_reason"]
287
+ patients = pd.DataFrame(records, columns=patient_columns)
288
+ flags = {row["patient_id"]: row for row in fits["patients"]}
289
+ for key in ("equal_eligible", "equal_reason", "fisher_eligible", "fisher_reason", "z", "v"):
290
+ patients[key] = [flags[pid][key] for pid in patients.patient_id]
291
+ fisher = aggregate != "equal"
292
+ patients["eligible"] = patients["fisher_eligible" if fisher else "equal_eligible"].astype(bool)
293
+ patients["reason"] = patients["fisher_reason" if fisher else "equal_reason"]
294
+ patients["status"] = np.where(patients.eligible, "eligible", "excluded")
295
+ eligible = int(patients.eligible.sum())
296
+ target_definition = ("Mean of eligible patients' observed within-patient correlations"
297
+ if aggregate == "equal" else
298
+ "Back-transformed mean of the random-effects distribution on the Fisher-z scale"
299
+ if aggregate == "re_hksj" else
300
+ "Individual patient associations shrunk toward the fitted Fisher-z population mean")
301
+ summary = dict(method=aggregate, target=target_definition, n_patients_total=len(patients),
302
+ n_patients_eligible=eligible, n_patients_excluded=len(patients)-eligible,
303
+ estimate=np.nan, ci_low=np.nan, ci_high=np.nan, p_value=np.nan,
304
+ standard_error=np.nan, se_scale="r" if aggregate == "equal" else "Fisher z",
305
+ df=np.nan, tau2=np.nan, confidence_level=1-float(alpha),
306
+ min_cells=min_cells, min_patients=min_patients, status="withheld_technical", reason="")
307
+ patients["weight"] = np.nan
308
+ for key in ("eb_estimate", "eb_estimate_z", "eb_ci_low", "eb_ci_high", "eb_data_weight", "eb_conditional_se_z"):
309
+ patients[key] = np.nan
310
+ patients["eb_status"] = "not_requested" if aggregate != "eb" else "not_eligible"
311
+ if aggregate == "equal":
312
+ fitted = fits["equal_r"]
313
+ interval = fitted
314
+ if eligible:
315
+ patients.loc[patients.eligible, "weight"] = 1 / eligible
316
+ else:
317
+ fitted = fits["reml"]
318
+ interval = fitted["hk"]
319
+ if eligible < min_patients:
320
+ summary.update(status="withheld_policy", reason="below_min_eligible_patients")
321
+ if aggregate == "eb":
322
+ patients.loc[patients.eligible, "eb_status"] = "withheld_policy"
323
+ elif aggregate == "eb":
324
+ if fits["shrinkage_status"] in ("conditional_plugin", "zero_tau2_complete_pooling"):
325
+ summary.update(status="individual_estimates_only", reason=fits["shrinkage_status"],
326
+ tau2=fitted["tau2"])
327
+ eb_rows = {p["patient_id"]: p for p in fits["shrinkage"]}
328
+ mapping = {"eb_estimate": "estimate", "eb_estimate_z": "estimate_z",
329
+ "eb_ci_low": "ci_low", "eb_ci_high": "ci_high",
330
+ "eb_data_weight": "observed_data_weight", "eb_conditional_se_z": "conditional_se_z",
331
+ "eb_status": "status"}
332
+ for index, row in patients.loc[patients.eligible].iterrows():
333
+ for public, private in mapping.items():
334
+ patients.loc[index, public] = eb_rows[row.patient_id][private]
335
+ else:
336
+ summary["reason"] = fits["shrinkage_status"]
337
+ elif interval["status"] == "ok":
338
+ summary.update(status="reported", reason="", estimate=fitted["estimate"],
339
+ ci_low=interval["ci_low"], ci_high=interval["ci_high"],
340
+ p_value=interval["p_value"], standard_error=interval["se"], df=interval["df"],
341
+ tau2=fitted.get("tau2", np.nan))
342
+ else:
343
+ summary["reason"] = interval["status"]
344
+ if fisher and eligible >= min_patients and fitted["status"] == "ok":
345
+ patients["weight"] = patients.patient_id.map(fitted["weights"])
346
+ warnings = list(fits["warnings"])
347
+ warnings.append("min_patients is a configurable reporting policy, not a validated adequacy threshold.")
348
+ if fisher:
349
+ warnings.append("Fisher sampling variances are approximations and assume independent cell-level information.")
350
+ if aggregate == "eb":
351
+ warnings.append("EB intervals condition on fitted population parameters and omit their estimation uncertainty.")
352
+ if patients.n_nonfinite_expression.sum() or patients.n_nonfinite_covariates.sum():
353
+ warnings.append("Nonfinite expression or covariates excluded cells; see per-patient complete-case counts.")
354
+ metadata = dict(anchor=anchor, target_genes=targets,
355
+ target_label=targets[0] if not module else "mean z score (" + ", ".join(targets) + ")",
356
+ target_definition=target_definition,
357
+ target_score="within-patient mean z score; ddof=1; constant genes contribute zero" if module else "single transformed gene",
358
+ expression="Pretransformed input; no normalization performed",
359
+ expression_source="X" if layer is None else f"layers[{layer!r}]",
360
+ score_standardization="Selected cells with finite anchor and all target genes; before covariate complete cases",
361
+ patient_key=patient_key, covariates=covariates, cell_mask=cell_mask if isinstance(cell_mask, str) else "provided vector" if cell_mask is not None else None,
362
+ covariate_standardization="Centered and scaled within patient complete cases; constant columns omitted",
363
+ aggregate=aggregate, min_cells=min_cells, min_patients=min_patients,
364
+ minimum_residual_df=3, alpha=float(alpha), warnings=warnings,
365
+ eb_interval_interpretation="conditional plug-in intervals, holding fitted population parameters fixed; no cohort inference",
366
+ interval_method="Student t" if aggregate == "equal" else "REML with classical HKSJ" if aggregate == "re_hksj" else "conditional empirical Bayes",
367
+ patient_id_order="first observed, then additional patient_ids")
368
+ return AssociationResult(patients, summary, metadata)
@@ -0,0 +1,37 @@
1
+ # GSE234933 tutorial data
2
+
3
+ These small files contain selected, transformed observations from publicly
4
+ deposited third-party data. They are **not covered by PASE's MIT software license**,
5
+ and PASE's authors do not claim ownership of, or grant a new license to, the source
6
+ data. No patient names or inferred clinical attributes are included. The retained
7
+ specimen labels and cell barcodes are the identifiers deposited by the study.
8
+
9
+ Source: [GSE234933](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE234933),
10
+ public since 24 July 2023. Please cite:
11
+
12
+ Bill R, Wirapati P, Messemaker M, et al. CXCL9:SPP1 macrophage polarity identifies
13
+ a network of cellular programs that control human cancers. Science.
14
+ 2023;381:515-524. https://doi.org/10.1126/science.ade2292
15
+
16
+ GEO places no repository restrictions on use or distribution, while noting that
17
+ submitters may hold intellectual-property rights. See the
18
+ [GEO data-use terms](https://www.ncbi.nlm.nih.gov/geo/info/disclaimer.html).
19
+ Respect any applicable source-holder terms and acknowledge the source study in
20
+ subsequent use. Inclusion here does not imply endorsement by the source authors.
21
+
22
+ `gse234933_demo_manifest.json` lists the original input checksums, extraction
23
+ rules, dimensions and output checksums. `examples/build_gse234933_subset.py`
24
+ reconstructs these files from the deposited count archive and annotation table.
25
+ The sample uses only the author's broad myeloid annotation, positive library size
26
+ and deterministic cell sampling; it is not selected for a favorable association.
27
+
28
+ `X` is log1p(CP10K), with the denominator calculated from **all original genes**
29
+ before retaining the tutorial's genes. The reduced `counts` layer cannot recover
30
+ the full library by summing its columns. Use the supplied full library sizes.
31
+
32
+ The 15-gene SPP1-positive macrophage list is recorded in the manifest and can be
33
+ traced to https://doi.org/10.3389/fimmu.2021.694801. Using it in this software
34
+ tutorial does not recreate the source publication's scoring procedure.
35
+
36
+ This is a compact teaching dataset, not a replication of the full PASE paper or
37
+ an independent external validation cohort.
Binary file