smallregnet 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,61 @@
1
+ """SmallRegNet: prior-guided GRN adaptation for small transcriptomic cohorts."""
2
+
3
+ from .adaptation import anchored_l2, select_genes, solve_anchored_weights
4
+ from .metrics import delta_correlation, edge_ranking_summary, normalized_ap, prediction_nmse
5
+ from .model import DEFAULT_STRENGTH_GRID, SmallRegNet, adapt_network
6
+ from .network_inputs import load_pyhlicorn_prior
7
+ from .node_universe import project_nodes, reference_nodes
8
+ from .reference_models import (
9
+ DEFAULT_ENCODER_MODE,
10
+ DEFAULT_LEARNING_RATE,
11
+ DEFAULT_OBSERVATION_STD,
12
+ DEFAULT_PRIOR_STD,
13
+ DEFAULT_SEED,
14
+ DEFAULT_TRAINING_STEPS,
15
+ DEFAULT_WARMUP_STEPS,
16
+ ReferenceAE,
17
+ ReferenceVAE,
18
+ adapt_with_reference_scores,
19
+ fit_reference,
20
+ full_predictive_gene_scores,
21
+ gene_residual_scores,
22
+ linear_warmup_beta_schedule,
23
+ raw_residual_scores,
24
+ )
25
+ from .validation import hidden_gene_indices, patient_folds
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "__version__",
31
+ "DEFAULT_ENCODER_MODE",
32
+ "DEFAULT_LEARNING_RATE",
33
+ "DEFAULT_OBSERVATION_STD",
34
+ "DEFAULT_PRIOR_STD",
35
+ "DEFAULT_SEED",
36
+ "DEFAULT_STRENGTH_GRID",
37
+ "DEFAULT_TRAINING_STEPS",
38
+ "DEFAULT_WARMUP_STEPS",
39
+ "ReferenceAE",
40
+ "ReferenceVAE",
41
+ "SmallRegNet",
42
+ "adapt_network",
43
+ "adapt_with_reference_scores",
44
+ "anchored_l2",
45
+ "delta_correlation",
46
+ "edge_ranking_summary",
47
+ "fit_reference",
48
+ "full_predictive_gene_scores",
49
+ "gene_residual_scores",
50
+ "hidden_gene_indices",
51
+ "linear_warmup_beta_schedule",
52
+ "load_pyhlicorn_prior",
53
+ "normalized_ap",
54
+ "patient_folds",
55
+ "prediction_nmse",
56
+ "project_nodes",
57
+ "raw_residual_scores",
58
+ "reference_nodes",
59
+ "select_genes",
60
+ "solve_anchored_weights",
61
+ ]
@@ -0,0 +1,206 @@
1
+ """Small, deterministic adaptation primitives; no experiment runs on import.
2
+
3
+ This implements the audited quadratic anchored-regression branch, not VAE
4
+ training or a claim of equivalence to every legacy estimator. Weights are T x R.
5
+ """
6
+ import numpy as np
7
+ from scipy.linalg import solve
8
+
9
+
10
+ def select_genes(scores, *, z_threshold):
11
+ """Population-Z gate on log1p nonnegative scores; a null gate abstains."""
12
+ scores = np.asarray(scores, dtype=float)
13
+ if scores.ndim != 1 or not np.isfinite(scores).all() or (scores < 0).any():
14
+ raise ValueError('Finite nonnegative gene scores required')
15
+ if not np.isfinite(z_threshold):
16
+ raise ValueError('Finite explicit threshold required')
17
+ transformed = np.log1p(scores)
18
+ if not len(scores) or transformed.std() == 0:
19
+ return np.zeros(len(scores), dtype=bool)
20
+ return (transformed-transformed.mean())/transformed.std() > z_threshold
21
+
22
+
23
+ def anchored_l2(regulators, targets, prior, selected, *, strength, allow_new_edges,
24
+ support_tolerance=1e-6, adaptive_gamma=0., epsilon=1e-8):
25
+ """Solve mean((X-R@W.T)**2) + sum(mu*D*(W-W0)**2)/2.
26
+
27
+ D=1/(abs(W0)**gamma+epsilon) for gamma>0, otherwise D=1.
28
+ Strength is a positive scalar or one positive value per target. No intercept
29
+ is fitted: inputs must already use the frozen source preprocessing. The
30
+ full-target MSE denominator preserves the audited loss's scaling even when
31
+ only a subset of genes adapts. Off mode freezes prior-absent entries at their
32
+ exact original values, including tiny coefficients below the support threshold.
33
+ """
34
+ r, x, w0 = [np.asarray(a, dtype=float) for a in (regulators, targets, prior)]
35
+ chosen = np.asarray(selected)
36
+ if (r.ndim != 2 or x.ndim != 2 or w0.ndim != 2 or not r.size or not x.size
37
+ or r.shape[0] != x.shape[0] or w0.shape != (x.shape[1], r.shape[1])):
38
+ raise ValueError('Expected sample x TF/target inputs and target x TF prior')
39
+ if any(not np.isfinite(a).all() for a in (r, x, w0)):
40
+ raise ValueError('Finite expression and prior required')
41
+ if chosen.dtype != bool or chosen.shape != (len(w0),):
42
+ raise ValueError('Explicit boolean target selection required')
43
+ if not isinstance(allow_new_edges, (bool, np.bool_)):
44
+ raise ValueError('Explicit boolean edge-addition mode required')
45
+ if (not np.isfinite([support_tolerance, adaptive_gamma, epsilon]).all()
46
+ or support_tolerance < 0 or adaptive_gamma < 0 or epsilon <= 0):
47
+ raise ValueError('Invalid support/anchor parameters')
48
+ mu = np.broadcast_to(np.asarray(strength, dtype=float), (len(w0),))
49
+ if not np.isfinite(mu).all() or (mu <= 0).any():
50
+ raise ValueError('Positive finite anchor strengths required')
51
+ after = w0.copy()
52
+ scale = 2./x.size
53
+ for j in np.flatnonzero(chosen):
54
+ active = np.ones(r.shape[1], dtype=bool) if allow_new_edges else abs(w0[j]) > support_tolerance
55
+ if not active.any():
56
+ continue
57
+ design = r[:, active]
58
+ diagonal = (1./(abs(w0[j, active])**adaptive_gamma+epsilon)
59
+ if adaptive_gamma > 0 else np.ones(active.sum()))
60
+ penalty = mu[j]*diagonal
61
+ # Solve for delta, retaining the prediction from all frozen prior entries.
62
+ residual = x[:, j]-r@w0[j]
63
+ if design.shape[0] < design.shape[1]:
64
+ # Exact Woodbury identity: solve in patient space when N << TFs.
65
+ # Avoid a TF x TF factorization for every selected target.
66
+ inverse_penalty_design = design.T/penalty[:, None]
67
+ lhs = np.eye(len(design))+scale*(design@inverse_penalty_design)
68
+ delta = scale*inverse_penalty_design@solve(lhs, residual, assume_a='pos')
69
+ else:
70
+ lhs = scale*(design.T@design)+np.diag(penalty)
71
+ delta = solve(lhs, scale*(design.T@residual), assume_a='pos')
72
+ after[j, active] += delta
73
+ return after
74
+
75
+
76
+ def solve_anchored_weights(
77
+ regulators,
78
+ targets,
79
+ prior,
80
+ strength,
81
+ *,
82
+ selected=None,
83
+ intercept=True,
84
+ adaptive_gamma=0.5,
85
+ epsilon=1e-8,
86
+ support_tolerance=1e-6,
87
+ allow_new_edges=True,
88
+ target_count=None,
89
+ batch_size=64,
90
+ ):
91
+ """Solve the manuscript prior-anchored quadratic objective with optional intercept.
92
+
93
+ Minimizes over target-specific changes delta_i = W_i - W0_i (and optional
94
+ unpenalized intercept alpha_i):
95
+
96
+ ||e_i - alpha_i * 1_N - R delta_i||_2^2 / (N * g) + (mu_i / 2) * delta_i^T D_i delta_i
97
+
98
+ where e_i = X[:, i] - R @ W0[i] and D_i = diag(1 / (|W0[i, j]|**gamma + epsilon))
99
+ when gamma > 0 (or identity when gamma == 0).
100
+
101
+ Uses the exact patient-space Woodbury identity solved in batches of target genes
102
+ matching the validated manuscript implementation. Returns ``(weights, intercepts)``.
103
+ """
104
+ r, x, w0 = [np.asarray(a, dtype=float) for a in (regulators, targets, prior)]
105
+ if (
106
+ r.ndim != 2
107
+ or x.ndim != 2
108
+ or w0.ndim != 2
109
+ or not r.size
110
+ or not x.size
111
+ or r.shape[0] != x.shape[0]
112
+ or w0.shape != (x.shape[1], r.shape[1])
113
+ ):
114
+ raise ValueError('Expected sample x TF/target inputs and target x TF prior')
115
+ if any(not np.isfinite(a).all() for a in (r, x, w0)):
116
+ raise ValueError('Finite expression and prior required')
117
+ if not isinstance(intercept, (bool, np.bool_)):
118
+ raise ValueError('Explicit boolean intercept flag required')
119
+ if not isinstance(allow_new_edges, (bool, np.bool_)):
120
+ raise ValueError('Explicit boolean edge-addition mode required')
121
+ if (
122
+ not np.isfinite([support_tolerance, adaptive_gamma, epsilon]).all()
123
+ or support_tolerance < 0
124
+ or adaptive_gamma < 0
125
+ or epsilon <= 0
126
+ ):
127
+ raise ValueError('Invalid support/anchor parameters')
128
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0:
129
+ raise ValueError('Positive integer batch_size required')
130
+ denom_g = x.shape[1] if target_count is None else target_count
131
+ if isinstance(denom_g, bool) or not isinstance(denom_g, (int, np.integer)) or denom_g <= 0:
132
+ raise ValueError('Positive integer target_count required')
133
+
134
+ if selected is None:
135
+ chosen_mask = np.ones(len(w0), dtype=bool)
136
+ else:
137
+ chosen_mask = np.asarray(selected)
138
+ if chosen_mask.dtype != bool or chosen_mask.shape != (len(w0),):
139
+ raise ValueError('Explicit boolean target selection required')
140
+
141
+ mu = np.broadcast_to(np.asarray(strength, dtype=float), (len(w0),))
142
+ if not np.isfinite(mu).all() or (mu <= 0).any():
143
+ raise ValueError('Positive finite anchor strengths required')
144
+
145
+ weights = w0.copy()
146
+ if intercept:
147
+ r_mean = r.mean(axis=0)
148
+ y_mean = x.mean(axis=0)
149
+ intercepts = y_mean - r_mean @ w0.T
150
+ else:
151
+ r_mean = None
152
+ y_mean = None
153
+ intercepts = np.zeros(len(w0), dtype=float)
154
+
155
+ chosen = np.flatnonzero(chosen_mask)
156
+ if not chosen.size:
157
+ return weights, intercepts
158
+
159
+ sub_r = r - r_mean if intercept else r
160
+ sub_y = x[:, chosen] - y_mean[chosen] if intercept else x[:, chosen]
161
+ sub_prior = w0[chosen]
162
+ sub_mu = mu[chosen]
163
+ scale = 2.0 / (len(sub_y) * int(denom_g))
164
+
165
+ if allow_new_edges:
166
+ denominator = (
167
+ np.abs(sub_prior) ** adaptive_gamma + epsilon
168
+ if adaptive_gamma > 0
169
+ else np.ones_like(sub_prior, dtype=float)
170
+ )
171
+ inverse_penalty = denominator / sub_mu[:, None]
172
+ residual = sub_y - sub_r @ sub_prior.T
173
+ updated = sub_prior.copy()
174
+ identity = np.eye(len(sub_r))
175
+ for start in range(0, len(sub_prior), batch_size):
176
+ rows = slice(start, start + batch_size)
177
+ gain = inverse_penalty[rows, :, None] * sub_r.T
178
+ lhs = identity + scale * (sub_r @ gain)
179
+ solved = np.linalg.solve(lhs, residual.T[rows, :, None])
180
+ updated[rows] += (scale * (gain @ solved)).squeeze(-1)
181
+ weights[chosen] = updated
182
+ else:
183
+ for idx, j in enumerate(chosen):
184
+ active = np.abs(w0[j]) > support_tolerance
185
+ if not active.any():
186
+ continue
187
+ design = sub_r[:, active]
188
+ diagonal = (
189
+ 1.0 / (np.abs(w0[j, active]) ** adaptive_gamma + epsilon)
190
+ if adaptive_gamma > 0
191
+ else np.ones(active.sum(), dtype=float)
192
+ )
193
+ penalty = sub_mu[idx] * diagonal
194
+ residual = sub_y[:, idx] - sub_r @ w0[j]
195
+ if design.shape[0] < design.shape[1]:
196
+ inv_design = design.T / penalty[:, None]
197
+ lhs = np.eye(len(design)) + scale * (design @ inv_design)
198
+ delta = scale * inv_design @ solve(lhs, residual, assume_a='pos')
199
+ else:
200
+ lhs = scale * (design.T @ design) + np.diag(penalty)
201
+ delta = solve(lhs, scale * (design.T @ residual), assume_a='pos')
202
+ weights[j, active] += delta
203
+
204
+ if intercept:
205
+ intercepts[chosen] = y_mean[chosen] - r_mean @ weights[chosen].T
206
+ return weights, intercepts
smallregnet/cohorts.py ADDED
@@ -0,0 +1,90 @@
1
+ """Patient/donor-level cohort selection and deterministic, sex-stratified pools."""
2
+ import re
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ TISSUES = {
7
+ 'BRCA': ('breast', 'Breast - Mammary Tissue', 'Breast Invasive Carcinoma'),
8
+ 'LUAD': ('lung', 'Lung', 'Lung Adenocarcinoma'),
9
+ }
10
+
11
+
12
+ def assert_same_tissue(frame, cancer, normal=None):
13
+ """Validate every biological label; a filename or tissue column is insufficient."""
14
+ if cancer not in TISSUES or frame.empty:
15
+ raise ValueError('Supported, nonempty same-tissue cohort required')
16
+ tissue, normal_label, cancer_label = TISSUES[cancer]
17
+ expected = {normal_label} if normal is True else {cancer_label} if normal is False else {normal_label,cancer_label}
18
+ if not set(frame['primary disease or tissue']).issubset(expected):
19
+ raise ValueError(f'Cross-tissue or wrong disease input rejected for {cancer}')
20
+ if 'tissue' in frame and not frame.tissue.eq(tissue).all():
21
+ raise ValueError('Tissue annotation disagrees with cohort disease')
22
+ if normal is True and (not frame['_study'].eq('GTEX').all() or not frame['_sample_type'].eq('Normal Tissue').all()):
23
+ raise ValueError('Normal-reference pool contains an ineligible sample')
24
+ if normal is False and (not frame['_study'].eq('TCGA').all() or not frame['_sample_type'].eq('Primary Tumor').all()):
25
+ raise ValueError('Tumor pool contains an ineligible sample')
26
+
27
+
28
+ def patient_id(sample):
29
+ if re.fullmatch(r'TCGA-[A-Z0-9]{2}-[A-Z0-9]{4}-\d{2}', sample):
30
+ return sample[:12]
31
+ if re.fullmatch(r'GTEX-[A-Z0-9]+-.+', sample):
32
+ return '-'.join(sample.split('-')[:2])
33
+ raise ValueError(f'Unsupported sample identifier: {sample}')
34
+
35
+
36
+ def eligible_cohort(phenotype, available, study, disease, sample_type):
37
+ q = phenotype.loc[(phenotype['_study'] == study) &
38
+ (phenotype['primary disease or tissue'] == disease) &
39
+ (phenotype['_sample_type'] == sample_type) & phenotype['sample'].isin(available)].copy()
40
+ if q['sample'].duplicated().any():
41
+ raise ValueError('Duplicate phenotype sample IDs')
42
+ q['patient_id'] = q['sample'].map(patient_id)
43
+ # A priori deterministic representative; never choose a sample by expression/outcome.
44
+ q = q.sort_values('sample').drop_duplicates('patient_id', keep='first')
45
+ q['_gender'] = q['_gender'].fillna('Unknown')
46
+ if not q['_gender'].isin(['Female', 'Male', 'Unknown']).all():
47
+ raise ValueError('Missing/unrecognized sex annotation; explicit handling required')
48
+ return q.rename(columns={'sample':'sample_id', '_gender':'sex'})[
49
+ ['sample_id','patient_id','sex','_study','_sample_type','primary disease or tissue']].reset_index(drop=True)
50
+
51
+
52
+ def stratified_take(frame, n, seed):
53
+ if not 0 <= n <= len(frame):
54
+ raise ValueError(f'Requested {n} patients from {len(frame)}')
55
+ frame = frame.sort_values('patient_id').reset_index(drop=True)
56
+ rng = np.random.default_rng(seed)
57
+ groups = [(str(k), g) for k,g in frame.groupby('sex', sort=True)]
58
+ expected = np.array([len(g) * n / len(frame) for _,g in groups]) if len(frame) else np.array([])
59
+ counts = np.floor(expected).astype(int)
60
+ order = np.argsort(-(expected - counts), kind='stable')
61
+ for i in order[:n-int(counts.sum())]: counts[i] += 1
62
+ picked = []
63
+ for (_, group), count in zip(groups, counts):
64
+ picked.extend(rng.choice(group.index.to_numpy(), size=count, replace=False).tolist())
65
+ selected = frame.loc[sorted(picked)].copy()
66
+ rest = frame.drop(index=picked).copy()
67
+ return selected.reset_index(drop=True), rest.reset_index(drop=True)
68
+
69
+
70
+ def tumor_pools(frame, adaptation_n=150, evaluation_n=100, seed=20261116):
71
+ a, remaining = stratified_take(frame, adaptation_n, seed)
72
+ e, s = stratified_take(remaining, evaluation_n, seed+1)
73
+ pools = {'A':a, 'S':s, 'E':e}
74
+ assert_disjoint(pools)
75
+ return pools
76
+
77
+
78
+ def assert_disjoint(pools):
79
+ seen = set()
80
+ for name, frame in pools.items():
81
+ ids = set(frame.patient_id)
82
+ if len(ids) != len(frame) or seen.intersection(ids):
83
+ raise ValueError(f'Patient overlap or duplicate in {name}')
84
+ seen.update(ids)
85
+
86
+
87
+ def draw_overlap(draws):
88
+ ids = {name:set(frame.patient_id) for name,frame in draws.items()}
89
+ return pd.DataFrame([{'draw_1':a, 'draw_2':b, 'shared_patients':len(ids[a]&ids[b]),
90
+ 'jaccard':len(ids[a]&ids[b])/len(ids[a]|ids[b])} for a in ids for b in ids if a < b])
@@ -0,0 +1,27 @@
1
+ """Descriptive silver-standard reliability diagnostics on a fixed edge universe."""
2
+ import numpy as np
3
+ from .metrics import normalized_ap
4
+
5
+
6
+ def _correlation(a,b):
7
+ a,b=np.asarray(a,dtype=float).ravel(),np.asarray(b,dtype=float).ravel()
8
+ if a.size<3 or a.std()==0 or b.std()==0:return None
9
+ return float(np.corrcoef(a,b)[0,1])
10
+
11
+
12
+ def agreement(one,two,tolerance=1e-6):
13
+ one,two=np.asarray(one,dtype=float),np.asarray(two,dtype=float)
14
+ if one.ndim!=2 or one.shape!=two.shape or not np.isfinite(one).all() or not np.isfinite(two).all():
15
+ raise ValueError('Aligned finite networks required')
16
+ a,b=np.abs(one)>tolerance,np.abs(two)>tolerance
17
+ union=a|b
18
+ forward=normalized_ap(one,two,tolerance)
19
+ reverse=normalized_ap(two,one,tolerance)
20
+ values=[forward['ap_norm'],reverse['ap_norm']]
21
+ return {'symmetric_ap_norm':float(np.mean(values)) if all(v is not None for v in values) else None,
22
+ 'ap_one_predicts_two':forward,'ap_two_predicts_one':reverse,
23
+ 'support_jaccard':float((a&b).sum()/union.sum()) if union.any() else None,
24
+ 'signed_weight_r_full':_correlation(one,two),
25
+ 'signed_weight_r_union':_correlation(one[union],two[union]),
26
+ 'edges_one':int(a.sum()),'edges_two':int(b.sum()),'intersection':int((a&b).sum()),
27
+ 'density_one':float(a.mean()),'density_two':float(b.mean())}
smallregnet/metrics.py ADDED
@@ -0,0 +1,61 @@
1
+ """Explicit support, weight-change, and observed-regulator prediction metrics.
2
+
3
+ Definitions are proposed for WP1 review, not a silently approved protocol.
4
+ Matrices are target x TF; targets and TFs are disjoint, so no self edges.
5
+ """
6
+ import numpy as np
7
+ from sklearn.metrics import average_precision_score, roc_auc_score
8
+
9
+
10
+ def _pair(a, b):
11
+ a,b = np.asarray(a,dtype=float),np.asarray(b,dtype=float)
12
+ if a.ndim != 2 or a.shape != b.shape or not a.size:
13
+ raise ValueError('Nonempty, equally shaped target x TF matrices required')
14
+ if not np.isfinite(a).all() or not np.isfinite(b).all():
15
+ raise ValueError('Nonfinite network values')
16
+ return a,b
17
+
18
+
19
+ def normalized_ap(scores, silver, support_tolerance=1e-6):
20
+ scores,silver = _pair(scores,silver)
21
+ labels = np.abs(silver).ravel() > support_tolerance
22
+ prevalence = float(labels.mean())
23
+ if prevalence in (0.,1.):
24
+ return {'ap':None, 'ap_norm':None, 'prevalence':prevalence, 'status':'degenerate_labels'}
25
+ ap = float(average_precision_score(labels,np.abs(scores).ravel()))
26
+ return {'ap':ap,'ap_norm':(ap-prevalence)/(1-prevalence),
27
+ 'prevalence':prevalence,'status':'ok'}
28
+
29
+
30
+ def delta_correlation(after, prior, silver):
31
+ after,prior = _pair(after,prior)
32
+ silver,_ = _pair(silver,prior)
33
+ # Fixed full edge universe, signed changes, same reference on both sides.
34
+ a,b = (after-prior).ravel(),(silver-prior).ravel()
35
+ if np.std(a) == 0 or np.std(b) == 0:
36
+ return {'r_delta':None,'status':'constant_delta'}
37
+ return {'r_delta':float(np.corrcoef(a,b)[0,1]),'status':'ok'}
38
+
39
+
40
+ def prediction_nmse(regulators, targets, weights, reference_target_variance):
41
+ r,x,w,v = map(lambda a:np.asarray(a,dtype=float),
42
+ [regulators,targets,weights,reference_target_variance])
43
+ if r.ndim != 2 or x.ndim != 2 or w.shape != (x.shape[1],r.shape[1]) or r.shape[0] != x.shape[0]:
44
+ raise ValueError('Expected sample x feature expression, target x TF weights')
45
+ if v.shape != (x.shape[1],) or np.any(v <= 0) or any(not np.isfinite(a).all() for a in [r,x,w,v]):
46
+ raise ValueError('Finite expression/weights and positive source variances required')
47
+ return float(np.mean((x-r@w.T)**2/v))
48
+
49
+ def edge_ranking_summary(weights, labels, k):
50
+ """Global AP, AUROC and expected precision under uniform tie resolution at K."""
51
+ labels = np.asarray(labels, dtype=bool).ravel()
52
+ scores = np.abs(np.asarray(weights)).ravel()
53
+ if scores.shape != labels.shape or not 0 < k <= scores.size:
54
+ raise ValueError('Expected aligned edge scores and an attainable edge budget')
55
+ cut = np.partition(scores, len(scores)-k)[-k]
56
+ above, tied = scores > cut, scores == cut
57
+ precision = (labels[above].sum() + (k-above.sum())*labels[tied].mean())/k
58
+ defined = labels.any() and not labels.all()
59
+ return dict(ap=float(average_precision_score(labels, scores)) if defined else None,
60
+ auroc=float(roc_auc_score(labels, scores)) if defined else None,
61
+ precision_k=float(precision), prevalence=float(labels.mean()), k=k)