jipm 0.1.1__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.
- jipm/__init__.py +25 -0
- jipm/__main__.py +4 -0
- jipm/_parpi/__init__.py +1 -0
- jipm/_parpi/encoding.py +129 -0
- jipm/_parpi/engine.py +146 -0
- jipm/_parpi/kernels.py +49 -0
- jipm/_parpi/solver.py +180 -0
- jipm/atr.py +396 -0
- jipm/cli.py +105 -0
- jipm/comparison.py +72 -0
- jipm/correspondence.py +163 -0
- jipm/demo.py +57 -0
- jipm/direction.py +342 -0
- jipm/endpoints.py +350 -0
- jipm/nomination.py +261 -0
- jipm/parpi.py +233 -0
- jipm/profiles.py +121 -0
- jipm/resources/direction/jonikas_features.npz +0 -0
- jipm/resources/direction/jonikas_reference.npz +0 -0
- jipm/resources/endpoints/coefficients.npz +0 -0
- jipm/resources/endpoints/example.csv +5 -0
- jipm/resources/endpoints/index.json +1 -0
- jipm/resources/endpoints/measurement_map.json +35 -0
- jipm/system.py +136 -0
- jipm-0.1.1.dist-info/METADATA +86 -0
- jipm-0.1.1.dist-info/RECORD +30 -0
- jipm-0.1.1.dist-info/WHEEL +5 -0
- jipm-0.1.1.dist-info/entry_points.txt +2 -0
- jipm-0.1.1.dist-info/licenses/NOTICE.md +5 -0
- jipm-0.1.1.dist-info/top_level.txt +1 -0
jipm/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Joint Interpretation of Perturbation Measurements."""
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
|
|
4
|
+
__version__ = "0.1.1"
|
|
5
|
+
|
|
6
|
+
# Loading an estimator only imports the numerical routines for the requested task.
|
|
7
|
+
_EXPORTS = {
|
|
8
|
+
"JIPM": "system",
|
|
9
|
+
"PathwayDirection": "direction", "load_jonikas": "direction",
|
|
10
|
+
"EndpointModel": "endpoints", "fong_example": "endpoints",
|
|
11
|
+
"PARPiCorrespondence": "correspondence",
|
|
12
|
+
"ATRResponseModel": "atr", "PARPiRegressor": "parpi", "RNAProfiles": "profiles",
|
|
13
|
+
"nominate_pairs": "nomination", "rank_candidates": "nomination",
|
|
14
|
+
"score_nominations": "nomination", "evaluate_endpoints": "endpoints",
|
|
15
|
+
"compare_responses": "comparison",
|
|
16
|
+
}
|
|
17
|
+
__all__ = list(_EXPORTS)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def __getattr__(name):
|
|
21
|
+
if name not in _EXPORTS:
|
|
22
|
+
raise AttributeError(name)
|
|
23
|
+
value = getattr(import_module("." + _EXPORTS[name], __name__), name)
|
|
24
|
+
globals()[name] = value
|
|
25
|
+
return value
|
jipm/__main__.py
ADDED
jipm/_parpi/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal numerical routines for the PARPi response adapter."""
|
jipm/_parpi/encoding.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Training-only PARPi preprocessing for an arbitrary set of prediction rows."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
import warnings
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from sklearn.decomposition import PCA
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _median(x):
|
|
11
|
+
with warnings.catch_warnings():
|
|
12
|
+
warnings.simplefilter("ignore", RuntimeWarning)
|
|
13
|
+
result = np.nanmedian(x, axis=0)
|
|
14
|
+
return np.where(np.isfinite(result), result, 0.0)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _scale(x):
|
|
18
|
+
sd = x.std(axis=0)
|
|
19
|
+
return np.where(sd > 1.e-8, sd, 1.0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def coordinate_indices(rows, profiles):
|
|
23
|
+
ids = pd.Index(profiles.gene_ids)
|
|
24
|
+
a = ids.get_indexer(rows.hgnc_a)
|
|
25
|
+
b = ids.get_indexer(rows.hgnc_b)
|
|
26
|
+
if (a < 0).any() or (b < 0).any():
|
|
27
|
+
absent = set(rows.loc[a < 0, "hgnc_a"]) | set(rows.loc[b < 0, "hgnc_b"])
|
|
28
|
+
raise ValueError(f"Missing RNA profiles for parents: {sorted(absent)}")
|
|
29
|
+
return a, b
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _raw(profiles):
|
|
33
|
+
values = np.asarray(profiles.expression, dtype=float) - np.asarray(profiles.control_mean)[None, :]
|
|
34
|
+
q = np.array(profiles.quality, dtype=float, copy=True)
|
|
35
|
+
if (q[:, 0] < 0).any():
|
|
36
|
+
raise ValueError("Filtered cell counts must be nonnegative")
|
|
37
|
+
q[:, 0] = np.log1p(q[:, 0])
|
|
38
|
+
return values, q
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _direct(x, missing, targets, a, b):
|
|
42
|
+
def response(gene, transcript):
|
|
43
|
+
j = targets[transcript]
|
|
44
|
+
c = np.maximum(j, 0)
|
|
45
|
+
return np.where(j >= 0, x[gene, c], 0.0), ((j < 0) | missing[gene, c]).astype(float)
|
|
46
|
+
aa, maa = response(a, a)
|
|
47
|
+
ab, mab = response(a, b)
|
|
48
|
+
bb, mbb = response(b, b)
|
|
49
|
+
ba, mba = response(b, a)
|
|
50
|
+
return np.c_[aa, ab], np.c_[bb, ba], np.c_[maa, mab], np.c_[mbb, mba]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _functional(rows):
|
|
54
|
+
single_a = rows[["rep1_ut_a", "rep1_drug_a"]].to_numpy(float)
|
|
55
|
+
single_b = rows[["rep1_ut_b", "rep1_drug_b"]].to_numpy(float)
|
|
56
|
+
return single_a, single_b, rows.rep1_ut_ab.to_numpy(float)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Features:
|
|
61
|
+
e: np.ndarray
|
|
62
|
+
es: np.ndarray
|
|
63
|
+
d: np.ndarray
|
|
64
|
+
ds: np.ndarray
|
|
65
|
+
|
|
66
|
+
def take(self, idx):
|
|
67
|
+
return Features(self.e[idx], self.es[idx], self.d[idx], self.ds[idx])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Encoder:
|
|
71
|
+
"""Fit all standardization and PCA exclusively to the training parents/pairs."""
|
|
72
|
+
def __init__(self, n_components):
|
|
73
|
+
self.n_components = n_components
|
|
74
|
+
|
|
75
|
+
def fit(self, rows, profiles):
|
|
76
|
+
a, b = coordinate_indices(rows, profiles)
|
|
77
|
+
genes = np.unique(np.r_[a, b])
|
|
78
|
+
raw, quality = _raw(profiles)
|
|
79
|
+
missing = ~np.isfinite(raw)
|
|
80
|
+
self.rmed = _median(np.where(missing[genes], np.nan, raw[genes]))
|
|
81
|
+
x = np.where(missing, self.rmed, raw)
|
|
82
|
+
q = np.where(np.isfinite(quality), quality, np.nan)
|
|
83
|
+
self.qmed = _median(q[genes])
|
|
84
|
+
q = np.where(np.isfinite(q), q, self.qmed)
|
|
85
|
+
self.qmu, self.qsd = q[genes].mean(axis=0), _scale(q[genes])
|
|
86
|
+
k = min(self.n_components, len(genes), x.shape[1])
|
|
87
|
+
self.pca = PCA(n_components=k, svd_solver="randomized", random_state=20261128)
|
|
88
|
+
self.pca.fit(x[genes])
|
|
89
|
+
pc = self.pca.transform(x)
|
|
90
|
+
self.pcscale = max(float(np.sqrt(np.mean(np.sum(pc[genes] ** 2, axis=1)) / k)), 1.e-8)
|
|
91
|
+
da, db, _, _ = _direct(x, missing, np.asarray(profiles.target_transcript_indices), a, b)
|
|
92
|
+
both = np.r_[da, db]
|
|
93
|
+
self.directmu, self.directsd = both.mean(axis=0), _scale(both)
|
|
94
|
+
ra, rb, ab = _functional(rows)
|
|
95
|
+
both = np.r_[ra, rb]
|
|
96
|
+
self.dmu, self.dsd = both.mean(axis=0), _scale(both)
|
|
97
|
+
self.pmu, self.psd = float(ab.mean()), max(float(ab.std()), 1.e-8)
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def transform(self, rows, profiles):
|
|
101
|
+
a, b = coordinate_indices(rows, profiles)
|
|
102
|
+
raw, quality = _raw(profiles)
|
|
103
|
+
missing = ~np.isfinite(raw)
|
|
104
|
+
x = np.where(missing, self.rmed, raw)
|
|
105
|
+
pc = self.pca.transform(x) / self.pcscale
|
|
106
|
+
q = (np.where(np.isfinite(quality), quality, self.qmed) - self.qmu) / self.qsd
|
|
107
|
+
da, db, ma, mb = _direct(x, missing, np.asarray(profiles.target_transcript_indices), a, b)
|
|
108
|
+
ea = np.c_[pc[a], q[a], (da - self.directmu) / self.directsd, ma]
|
|
109
|
+
eb = np.c_[pc[b], q[b], (db - self.directmu) / self.directsd, mb]
|
|
110
|
+
ra, rb, ab = _functional(rows)
|
|
111
|
+
ra, rb = (ra-self.dmu)/self.dsd, (rb-self.dmu)/self.dsd
|
|
112
|
+
ab = (ab-self.pmu)/self.psd
|
|
113
|
+
return Features(np.c_[ea, eb].astype(np.float32), np.c_[eb, ea].astype(np.float32),
|
|
114
|
+
np.c_[ra, rb, ab].astype(np.float32), np.c_[rb, ra, ab].astype(np.float32))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class NativeBank:
|
|
118
|
+
"""Expose in-memory assay matrices to the manuscript's landmark and ridge routines."""
|
|
119
|
+
def __init__(self, rows, features, land):
|
|
120
|
+
self.rows = rows
|
|
121
|
+
self.rep = 1
|
|
122
|
+
self.fit_indices = np.arange(len(rows))
|
|
123
|
+
self.land = land
|
|
124
|
+
self.ref = land[:256]
|
|
125
|
+
self.features = features
|
|
126
|
+
self.d, self.ds = features.d, features.ds
|
|
127
|
+
|
|
128
|
+
def E(self, components):
|
|
129
|
+
return self.features.e, self.features.es
|
jipm/_parpi/engine.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Numerical routines from parpi_optimization_v2, used for native fitting parity."""
|
|
2
|
+
import gc
|
|
3
|
+
import time
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy.spatial.distance import cdist
|
|
6
|
+
from .kernels import natural_features
|
|
7
|
+
from .solver import prepare_background, fit_design_lowrank, predict_design_lowrank
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_background_state(rows,fit,rep,context=True):
|
|
11
|
+
fit=np.asarray(fit,int)
|
|
12
|
+
ids=np.asarray(sorted(set(rows.iloc[fit].hgnc_a)|set(rows.iloc[fit].hgnc_b)))
|
|
13
|
+
d=natural_features(rows,rep);mu=d[fit].mean(0);sd=np.maximum(d[fit].std(0),1e-8)
|
|
14
|
+
pa=rows[f'rep{rep}_drug_a'].to_numpy(float);pb=rows[f'rep{rep}_drug_b'].to_numpy(float)
|
|
15
|
+
pm=np.r_[pa[fit],pb[fit]].mean();ps=max(np.r_[pa[fit],pb[fit]].std(),1e-8)
|
|
16
|
+
return {'gene_ids':ids,'Dmean':mu,'Dstd':sd,'partner_mean':float(pm),'partner_std':float(ps),
|
|
17
|
+
'input_rep':int(rep),'context':bool(context)}
|
|
18
|
+
|
|
19
|
+
def gene_indices(rows,state):
|
|
20
|
+
lookup={str(g):i for i,g in enumerate(state['gene_ids'])}
|
|
21
|
+
a=rows.hgnc_a.map(lookup).fillna(-1).to_numpy(int)
|
|
22
|
+
b=rows.hgnc_b.map(lookup).fillna(-1).to_numpy(int)
|
|
23
|
+
return a,b
|
|
24
|
+
|
|
25
|
+
def background_design(rows,state):
|
|
26
|
+
rep=int(state['input_rep']);ids=state['gene_ids'];n=len(ids)
|
|
27
|
+
a,b=gene_indices(rows,state);ma=a>=0;mb=b>=0
|
|
28
|
+
d=(natural_features(rows,rep)-state['Dmean'])/state['Dstd']
|
|
29
|
+
context=bool(state['context']);dim=1+n+10+(2*n if context else 0)
|
|
30
|
+
design=np.zeros((len(rows),dim),float);design[:,0]=1.
|
|
31
|
+
ix=np.arange(len(rows));design[ix[ma],1+a[ma]]+=1.;design[ix[mb],1+b[mb]]+=1.
|
|
32
|
+
design[:,1+n:1+n+10]=d
|
|
33
|
+
if context:
|
|
34
|
+
pos=1+n+10
|
|
35
|
+
design[ix[ma],pos+a[ma]]=d[ma,9];design[ix[mb],pos+b[mb]]=d[mb,9]
|
|
36
|
+
pa=rows[f'rep{rep}_drug_a'].to_numpy(float);pb=rows[f'rep{rep}_drug_b'].to_numpy(float)
|
|
37
|
+
pos+=n
|
|
38
|
+
design[ix[ma],pos+a[ma]]=(pb[ma]-state['partner_mean'])/state['partner_std']
|
|
39
|
+
design[ix[mb],pos+b[mb]]=(pa[mb]-state['partner_mean'])/state['partner_std']
|
|
40
|
+
return design,a,b
|
|
41
|
+
|
|
42
|
+
def penalty_vector(state,gene_lambda,kernel_rank,kernel_alpha=.1):
|
|
43
|
+
n=len(state['gene_ids']);context=bool(state['context'])
|
|
44
|
+
parts=[np.array([0.]),np.full(n,gene_lambda),np.full(10,1e-4*gene_lambda)]
|
|
45
|
+
if context:parts.append(np.full(2*n,10*gene_lambda))
|
|
46
|
+
if kernel_rank:parts.append(np.full(kernel_rank,kernel_alpha))
|
|
47
|
+
return np.concatenate(parts)
|
|
48
|
+
|
|
49
|
+
def combine_kernel(ks,family):
|
|
50
|
+
if family=='J':return ks['J']
|
|
51
|
+
if family=='D':return ks['D']
|
|
52
|
+
if family=='additive':return .5*ks['E']+.5*ks['D']
|
|
53
|
+
if family=='PaD_mix':return .125*ks['E']+.125*ks['D']+.75*ks['J']
|
|
54
|
+
raise ValueError(family)
|
|
55
|
+
|
|
56
|
+
def fit_with_basis(rows,y,fit,bank,F,whitener,pars,*,gene_lambda=3.,rank=2,
|
|
57
|
+
factor_lambda=1.,family='J',context=True,seed=20281128):
|
|
58
|
+
start=time.perf_counter();fit=np.asarray(fit,int)
|
|
59
|
+
assert fit.ndim==1 and len(np.unique(fit))==len(fit) and len(fit)>0
|
|
60
|
+
assert fit.min()>=0 and fit.max()<len(rows) and np.isfinite(np.asarray(y)[fit]).all()
|
|
61
|
+
assert rows.row_id.is_unique and rows.pair_id.is_unique and (rows.hgnc_a!=rows.hgnc_b).all()
|
|
62
|
+
assert len({tuple(sorted((str(a),str(b)))) for a,b in zip(rows.hgnc_a,rows.hgnc_b)})==len(rows),'Duplicated unordered gene pair'
|
|
63
|
+
state=make_background_state(rows,fit,bank.rep,context=context)
|
|
64
|
+
B,a,b=background_design(rows.iloc[fit],state);assert (a>=0).all() and (b>=0).all()
|
|
65
|
+
base_dim=B.shape[1]
|
|
66
|
+
if F is not None:design=np.c_[B,F]
|
|
67
|
+
else:design=B
|
|
68
|
+
del B;gc.collect()
|
|
69
|
+
nr=0 if F is None else F.shape[1]
|
|
70
|
+
penalty=penalty_vector(state,gene_lambda,nr)
|
|
71
|
+
prepared=prepare_background(design,penalty)
|
|
72
|
+
learned=fit_design_lowrank(a,b,np.asarray(y)[fit],design,penalty,n_genes=len(state['gene_ids']),
|
|
73
|
+
rank=rank,lambda_factor=factor_lambda,loss_mode='directed',initialization='spectral',
|
|
74
|
+
seed=20261128,maxiter=800,prepared_background=prepared)
|
|
75
|
+
diag=learned['diagnostics']
|
|
76
|
+
assert diag['success'],diag
|
|
77
|
+
for name in ['final_objective','train_mse','gradient_inf_norm','background_stationarity_inf_norm']:
|
|
78
|
+
assert np.isfinite(diag[name]),(name,diag)
|
|
79
|
+
assert diag['gradient_inf_norm']<1e-3 and diag['background_stationarity_inf_norm']<1e-5,diag
|
|
80
|
+
direct=predict_design_lowrank(learned,a,b,design)
|
|
81
|
+
weight=learned['background_weights'];scale=learned['target_scale']
|
|
82
|
+
model={**state,'U':learned['U'],'V':learned['V'],'target_scale':scale,'target_center':learned['target_center'],
|
|
83
|
+
'background_weights':weight[:base_dim]*scale,'kernel_beta':np.zeros(0) if F is None else (whitener@weight[base_dim:])*scale,
|
|
84
|
+
'landmark_indices':np.array([],int) if F is None else bank.land.copy(),
|
|
85
|
+
'kernel_family':'none' if F is None else family,'kernel_pars':pars,
|
|
86
|
+
'config':{'gene_lambda':gene_lambda,'rank':rank,'factor_lambda':factor_lambda,'context':context,'kernel_family':'none' if F is None else family,
|
|
87
|
+
'kernel_alpha':.1,'context_penalty_ratio':10.,'D_penalty_ratio':1e-4,'we':.1,'wd':1.,'pca':64,'m':len(bank.land),
|
|
88
|
+
'landmark_seed':seed,'initialization':'spectral','optimizer_seed':20261128,'loss_mode':'directed','maxiter':800},
|
|
89
|
+
'fit_indices':fit.copy(),'diagnostics':learned['diagnostics']}
|
|
90
|
+
assert np.isfinite(direct).all()
|
|
91
|
+
del design,prepared;gc.collect()
|
|
92
|
+
replay=predict(model,rows.iloc[fit],bank,fit)
|
|
93
|
+
err=float(np.max(abs(direct-replay)))
|
|
94
|
+
if err>1e-8:raise AssertionError(('Collapsed inference differs from trained predictor',err))
|
|
95
|
+
model['diagnostics']['collapsed_prediction_max_abs']=err
|
|
96
|
+
model['diagnostics']['integrated_seconds']=time.perf_counter()-start
|
|
97
|
+
model['diagnostics']['cold_rule']='Unseen gene ID/background and free latent corrections are zero; functional background and continuous E,D kernel remain active.'
|
|
98
|
+
return model
|
|
99
|
+
|
|
100
|
+
def kernel_prediction(model,bank,indices,swap=False,chunk=1024):
|
|
101
|
+
if not len(model['kernel_beta']):return np.zeros(len(indices))
|
|
102
|
+
family = model['kernel_family']
|
|
103
|
+
if family not in ('J', 'D', 'additive', 'PaD_mix'):
|
|
104
|
+
raise ValueError(family)
|
|
105
|
+
p = model['kernel_pars']
|
|
106
|
+
landmarks = model['landmark_indices']
|
|
107
|
+
D, Ds = bank.d, bank.ds
|
|
108
|
+
Dl = D[landmarks]
|
|
109
|
+
if swap:
|
|
110
|
+
D, Ds = Ds, D
|
|
111
|
+
if family != 'D':
|
|
112
|
+
E, Es = bank.E(64)
|
|
113
|
+
El = E[landmarks]
|
|
114
|
+
if swap:
|
|
115
|
+
E, Es = Es, E
|
|
116
|
+
out=np.empty(len(indices))
|
|
117
|
+
for start in range(0,len(indices),chunk):
|
|
118
|
+
ix=np.asarray(indices[start:start+chunk],int)
|
|
119
|
+
dc=np.exp(-(cdist(D[ix],Dl,'sqeuclidean')/p['D_distance_median']).astype(np.float32))
|
|
120
|
+
ds=np.exp(-(cdist(Ds[ix],Dl,'sqeuclidean')/p['D_distance_median']).astype(np.float32))
|
|
121
|
+
ks = {}
|
|
122
|
+
if family != 'J':
|
|
123
|
+
ks['D'] = .5*(dc+ds)/p['D_norm']
|
|
124
|
+
if family != 'D':
|
|
125
|
+
ec=np.exp(-.1*(cdist(E[ix],El,'sqeuclidean')/p['E_distance_median']).astype(np.float32))
|
|
126
|
+
es=np.exp(-.1*(cdist(Es[ix],El,'sqeuclidean')/p['E_distance_median']).astype(np.float32))
|
|
127
|
+
if family in ('additive', 'PaD_mix'):
|
|
128
|
+
ks['E'] = .5*(ec+es)/p['E_norm']
|
|
129
|
+
if family in ('J', 'PaD_mix'):
|
|
130
|
+
ks['J'] = .5*(ec*dc+es*ds)/p['J_norm']
|
|
131
|
+
out[start:start+len(ix)]=combine_kernel(ks,family).astype(float)@model['kernel_beta']
|
|
132
|
+
return out
|
|
133
|
+
|
|
134
|
+
def predict(model,query_rows,bank,indices,swap_kernel=False):
|
|
135
|
+
expected=bank.rows.iloc[np.asarray(indices,int)]
|
|
136
|
+
assert np.array_equal(query_rows.row_id.to_numpy(),expected.row_id.to_numpy()),'Query indices misaligned'
|
|
137
|
+
for name,other in [('hgnc_a','hgnc_b'),('hgnc_b','hgnc_a')]:
|
|
138
|
+
assert np.array_equal(query_rows[name].to_numpy(),expected[other if swap_kernel else name].to_numpy()),'Query gene identity misaligned'
|
|
139
|
+
B,a,b=background_design(query_rows,model)
|
|
140
|
+
p=B@model['background_weights']+model['target_center'];del B
|
|
141
|
+
both=(a>=0)&(b>=0)
|
|
142
|
+
if model['U'].shape[0] and both.any():
|
|
143
|
+
u,v=model['U'],model['V'];aa=a[both];bb=b[both]
|
|
144
|
+
p[both]+=.5*model['target_scale']*(np.sum(u[:,aa]*v[:,bb],axis=0)+np.sum(u[:,bb]*v[:,aa],axis=0))
|
|
145
|
+
p+=kernel_prediction(model,bank,np.asarray(indices,int),swap=swap_kernel)
|
|
146
|
+
return p
|
jipm/_parpi/kernels.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Numerical routines from parpi_optimization_v2, used for native fitting parity."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy.spatial.distance import cdist, pdist
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def components_subset(bank,k,we,wd,m,indices,chunk=1024,*,joint_only=False):
|
|
7
|
+
"""Compute native kernel components, storing only the requested matrices."""
|
|
8
|
+
E,Es=bank.E(k);D,Ds=bank.d,bank.ds
|
|
9
|
+
em=max(float(np.median(pdist(np.r_[E[bank.ref],Es[bank.ref]],'sqeuclidean'))),1e-8)
|
|
10
|
+
dm=max(float(np.median(pdist(np.r_[D[bank.ref],Ds[bank.ref]],'sqeuclidean'))),1e-8)
|
|
11
|
+
ed=(np.sum((E-Es)**2,axis=1)/em).astype(np.float32)
|
|
12
|
+
dd=(np.sum((D-Ds)**2,axis=1)/dm).astype(np.float32)
|
|
13
|
+
ex=np.exp(-we*ed[bank.fit_indices]);dx=np.exp(-wd*dd[bank.fit_indices])
|
|
14
|
+
en=float(np.mean(.5*(1+ex)));dn=float(np.mean(.5*(1+dx)));jn=float(np.mean(.5*(1+ex*dx)))
|
|
15
|
+
pars={'E_distance_median':em,'D_distance_median':dm,'E_norm':en,'D_norm':dn,'J_norm':jn}
|
|
16
|
+
keys = ("J",) if joint_only else ("E", "D", "J")
|
|
17
|
+
ks={key:np.empty((len(indices),m),np.float32) for key in keys}
|
|
18
|
+
El=E[bank.land[:m]];Dl=D[bank.land[:m]]
|
|
19
|
+
for start in range(0,len(indices),chunk):
|
|
20
|
+
ix=indices[start:start+chunk];sl=slice(start,start+len(ix))
|
|
21
|
+
ec=np.exp(-we*(cdist(E[ix],El,'sqeuclidean')/em).astype(np.float32))
|
|
22
|
+
es=np.exp(-we*(cdist(Es[ix],El,'sqeuclidean')/em).astype(np.float32))
|
|
23
|
+
dc=np.exp(-wd*(cdist(D[ix],Dl,'sqeuclidean')/dm).astype(np.float32))
|
|
24
|
+
ds=np.exp(-wd*(cdist(Ds[ix],Dl,'sqeuclidean')/dm).astype(np.float32))
|
|
25
|
+
if not joint_only:
|
|
26
|
+
ks['E'][sl]=.5*(ec+es)/en
|
|
27
|
+
ks['D'][sl]=.5*(dc+ds)/dn
|
|
28
|
+
ks['J'][sl]=.5*(ec*dc+es*ds)/jn
|
|
29
|
+
return ks,pars
|
|
30
|
+
from scipy.linalg import eigh
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def natural_features(rows,rep):
|
|
34
|
+
a=rows[f"rep{rep}_ut_a"].to_numpy(float); b=rows[f"rep{rep}_ut_b"].to_numpy(float)
|
|
35
|
+
da=rows[f"rep{rep}_drug_a"].to_numpy(float); db=rows[f"rep{rep}_drug_b"].to_numpy(float)
|
|
36
|
+
ab=rows[f"rep{rep}_ut_ab"].to_numpy(float); sa,sb=da-a,db-b
|
|
37
|
+
return np.c_[a+b,abs(a-b),da+db,abs(da-db),(a-b)*(da-db),ab,
|
|
38
|
+
sa+sb,abs(sa-sb),ab+sa+sb,ab-a-b]
|
|
39
|
+
|
|
40
|
+
def nystrom(K,land):
|
|
41
|
+
W=K[land].astype(np.float64);W=.5*(W+W.T);val,vec=eigh(W,check_finite=False)
|
|
42
|
+
if val[0]<-1e-4:raise ValueError(("non_PSD_kernel",float(val[0])))
|
|
43
|
+
keep=val>max(float(val[-1])*1e-8,1e-10)
|
|
44
|
+
# Keep projection AND ridge inference in float64. Rounding projected
|
|
45
|
+
# features to float32 before multiplying by beta is not equivalent to
|
|
46
|
+
# collapsing the whitener into beta, especially at weak regularization.
|
|
47
|
+
inv=vec[:,keep]/np.sqrt(val[keep])[None,:]
|
|
48
|
+
F=K.astype(np.float64)@inv;assert np.isfinite(F).all()
|
|
49
|
+
return F,inv,{"rank":F.shape[1],"kernel_min_eigenvalue":float(val[0])}
|
jipm/_parpi/solver.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Numerical routines from parpi_optimization_v2, used for native fitting parity."""
|
|
2
|
+
import time
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy import sparse
|
|
5
|
+
from scipy.linalg import cho_factor, cho_solve, eigh
|
|
6
|
+
from scipy.optimize import minimize
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ProfileObjective:
|
|
10
|
+
"""0.5 SSE over unordered observed pairs + independent ridge penalties."""
|
|
11
|
+
def __init__(self, ia, ib, z, x, n_genes, rank, lambda_factor,
|
|
12
|
+
lambda_bias, lambda_functional,loss_mode='symmetric',
|
|
13
|
+
background_design=None,background_penalty=None,prepared_background=None):
|
|
14
|
+
self.ia=np.asarray(ia,int);self.ib=np.asarray(ib,int)
|
|
15
|
+
self.z=np.asarray(z,float);self.n=int(n_genes);self.rank=int(rank)
|
|
16
|
+
self.lambda_factor=float(lambda_factor)
|
|
17
|
+
self.lambda_bias=float(lambda_bias)
|
|
18
|
+
self.lambda_functional=float(lambda_functional)
|
|
19
|
+
if loss_mode not in ['symmetric','directed']:
|
|
20
|
+
raise ValueError('Unknown pair loss '+loss_mode)
|
|
21
|
+
self.loss_mode=loss_mode
|
|
22
|
+
m=len(z)
|
|
23
|
+
if any(ids.shape != (m,) or np.any(ids < 0) or np.any(ids >= self.n)
|
|
24
|
+
for ids in (self.ia, self.ib)):
|
|
25
|
+
raise ValueError('Each training pair requires two valid parent indices.')
|
|
26
|
+
if background_design is None:
|
|
27
|
+
incidence=sparse.csr_matrix((np.ones(2*m),
|
|
28
|
+
(np.r_[np.arange(m),np.arange(m)],np.r_[self.ia,self.ib])),shape=(m,self.n))
|
|
29
|
+
self.design=sparse.hstack([sparse.csr_matrix(np.ones((m,1))),incidence,
|
|
30
|
+
sparse.csr_matrix(x)],format='csr')
|
|
31
|
+
self.penalty=np.r_[0.,np.full(self.n,lambda_bias),
|
|
32
|
+
np.full(x.shape[1],lambda_functional)]
|
|
33
|
+
else:
|
|
34
|
+
self.design=(background_design if sparse.issparse(background_design)
|
|
35
|
+
else np.asarray(background_design,dtype=float))
|
|
36
|
+
self.penalty=np.asarray(background_penalty,float)
|
|
37
|
+
if self.design.shape[0]!=m or self.penalty.shape!=(self.design.shape[1],):
|
|
38
|
+
raise ValueError('Custom background/penalty dimensions differ.')
|
|
39
|
+
if np.any(self.penalty<0):raise ValueError('Negative background ridge.')
|
|
40
|
+
if prepared_background is None:
|
|
41
|
+
prepared_background=prepare_background(self.design,self.penalty)
|
|
42
|
+
else:
|
|
43
|
+
if prepared_background['design'].shape!=self.design.shape or not np.array_equal(prepared_background['penalty'],self.penalty):
|
|
44
|
+
raise ValueError('Prepared background shape/penalties differ.')
|
|
45
|
+
# Caller shares the same immutable design object between trials.
|
|
46
|
+
if prepared_background['design'] is not self.design:
|
|
47
|
+
raise ValueError('Prepared background must reference the identical design array.')
|
|
48
|
+
self.chol=prepared_background['chol']
|
|
49
|
+
self.background_condition_number=prepared_background['condition_number']
|
|
50
|
+
self.latest={}
|
|
51
|
+
|
|
52
|
+
def unpack(self,theta):
|
|
53
|
+
count=self.rank*self.n
|
|
54
|
+
return theta[:count].reshape(self.rank,self.n),theta[count:].reshape(self.rank,self.n)
|
|
55
|
+
|
|
56
|
+
def background(self,latent):
|
|
57
|
+
rhs=self.design.T@(self.z-latent)
|
|
58
|
+
w=cho_solve(self.chol,rhs,check_finite=False)
|
|
59
|
+
return w,np.asarray(self.design@w)
|
|
60
|
+
|
|
61
|
+
def evaluate(self,theta,remember=True):
|
|
62
|
+
u,v=self.unpack(np.asarray(theta,float))
|
|
63
|
+
oriented=u.T@v
|
|
64
|
+
latent_matrix=.5*(oriented+oriented.T)
|
|
65
|
+
latent=latent_matrix[self.ia,self.ib]
|
|
66
|
+
w,background=self.background(latent)
|
|
67
|
+
error=background+latent-self.z
|
|
68
|
+
residual=np.zeros((self.n,self.n))
|
|
69
|
+
antisymmetric=.5*(oriented[self.ia,self.ib]-oriented[self.ib,self.ia])
|
|
70
|
+
if self.loss_mode=='symmetric':
|
|
71
|
+
antisymmetric=np.zeros_like(error)
|
|
72
|
+
residual[self.ia,self.ib]=error+antisymmetric
|
|
73
|
+
residual[self.ib,self.ia]=error-antisymmetric
|
|
74
|
+
gu=.5*(v@residual.T)+self.lambda_factor*u
|
|
75
|
+
gv=.5*(u@residual)+self.lambda_factor*v
|
|
76
|
+
data_loss=.5*float(error@error)+.5*float(antisymmetric@antisymmetric)
|
|
77
|
+
factor_penalty=.5*self.lambda_factor*(float(np.sum(u*u))+float(np.sum(v*v)))
|
|
78
|
+
background_penalty=.5*float(np.dot(self.penalty,w*w))
|
|
79
|
+
loss=data_loss+factor_penalty+background_penalty
|
|
80
|
+
gradient=np.r_[gu.ravel(),gv.ravel()]
|
|
81
|
+
if remember:
|
|
82
|
+
self.latest=dict(theta=np.array(theta,copy=True),w=w.copy(),error=error,
|
|
83
|
+
objective=loss,data_loss=data_loss,factor_penalty=factor_penalty,
|
|
84
|
+
background_penalty=background_penalty,gradient=gradient,
|
|
85
|
+
antisymmetric_mse=float(np.mean(antisymmetric**2)))
|
|
86
|
+
return loss,gradient
|
|
87
|
+
|
|
88
|
+
def initialization(self,method,seed):
|
|
89
|
+
if self.rank==0:
|
|
90
|
+
return np.empty(0)
|
|
91
|
+
if method=='random':
|
|
92
|
+
rng=np.random.RandomState(seed)
|
|
93
|
+
return rng.normal(0,.1,size=2*self.rank*self.n)
|
|
94
|
+
if method!='spectral':
|
|
95
|
+
raise ValueError('Unknown initialization '+method)
|
|
96
|
+
_,base=self.background(np.zeros(len(self.z)))
|
|
97
|
+
residual=self.z-base
|
|
98
|
+
matrix=np.zeros((self.n,self.n))
|
|
99
|
+
matrix[self.ia,self.ib]=residual
|
|
100
|
+
matrix[self.ib,self.ia]=residual
|
|
101
|
+
density=2*len(residual)/(self.n*(self.n-1))
|
|
102
|
+
values,vectors=eigh(matrix/density,check_finite=False)
|
|
103
|
+
if self.loss_mode=='directed':
|
|
104
|
+
chosen=np.argsort(abs(values))[::-1][:self.rank]
|
|
105
|
+
u=np.sqrt(abs(values[chosen]))[:,None]*vectors[:,chosen].T
|
|
106
|
+
v=np.sign(values[chosen])[:,None]*u
|
|
107
|
+
return np.r_[u.ravel(),v.ravel()]
|
|
108
|
+
positive=np.flatnonzero(values>0)[::-1][:self.rank]
|
|
109
|
+
negative=np.flatnonzero(values<0)[:self.rank]
|
|
110
|
+
up=np.zeros((self.rank,self.n));vn=np.zeros_like(up)
|
|
111
|
+
for k,j in enumerate(positive):up[k]=np.sqrt(values[j])*vectors[:,j]
|
|
112
|
+
for k,j in enumerate(negative):vn[k]=np.sqrt(-values[j])*vectors[:,j]
|
|
113
|
+
# Sym((up+vn)^T(up-vn)) has the selected positive and negative modes.
|
|
114
|
+
u,v=up+vn,up-vn
|
|
115
|
+
return np.r_[u.ravel(),v.ravel()]
|
|
116
|
+
|
|
117
|
+
def prepare_background(design,penalty):
|
|
118
|
+
"""Cache one dense or sparse linear normal-equation factorization."""
|
|
119
|
+
penalty=np.asarray(penalty,float)
|
|
120
|
+
gram=design.T@design
|
|
121
|
+
if sparse.issparse(gram):gram=gram.toarray()
|
|
122
|
+
gram=np.asarray(gram,dtype=float)
|
|
123
|
+
gram.flat[::len(gram)+1]+=penalty
|
|
124
|
+
condition=float(np.linalg.cond(gram)) if len(gram)<=512 else None
|
|
125
|
+
chol=cho_factor(gram,lower=True,check_finite=False,overwrite_a=False)
|
|
126
|
+
return dict(design=design,penalty=penalty.copy(),chol=chol,condition_number=condition)
|
|
127
|
+
|
|
128
|
+
def fit_design_lowrank(ia,ib,y,background_design,background_penalty,*,rank=8,n_genes=None,
|
|
129
|
+
lambda_factor=.5,loss_mode='directed',initialization='spectral',
|
|
130
|
+
seed=20261128,maxiter=2500,ftol=1e-12,gtol=1e-6,
|
|
131
|
+
prepared_background=None):
|
|
132
|
+
"""Generic B+L interface for a caller-owned fitted background design.
|
|
133
|
+
|
|
134
|
+
Supply TRAINING rows/labels only. background_design includes its intercept;
|
|
135
|
+
background_penalty is a nonnegative diagonal ridge vector (intercept=0).
|
|
136
|
+
The caller owns feature scaling, column identities and prediction designs.
|
|
137
|
+
Returned factors and background coefficients are in normalized target units.
|
|
138
|
+
predict_design_lowrank restores the raw target scale. This function writes
|
|
139
|
+
no files and accesses no data paths.
|
|
140
|
+
"""
|
|
141
|
+
start=time.perf_counter()
|
|
142
|
+
ia=np.asarray(ia,int);ib=np.asarray(ib,int);y=np.asarray(y,float)
|
|
143
|
+
if not np.isfinite(y).all():raise ValueError('Training labels must be finite.')
|
|
144
|
+
if n_genes is None:n_genes=int(max(ia.max(),ib.max())+1)
|
|
145
|
+
center=float(y.mean());scale=float(y.std());scale=scale if scale>0 else 1.
|
|
146
|
+
obj=ProfileObjective(ia,ib,(y-center)/scale,np.empty((len(y),0)),n_genes,rank,
|
|
147
|
+
lambda_factor,1.,1.,loss_mode=loss_mode,background_design=background_design,
|
|
148
|
+
background_penalty=background_penalty,prepared_background=prepared_background)
|
|
149
|
+
theta0=obj.initialization(initialization,seed)
|
|
150
|
+
initial=obj.evaluate(theta0)[0]
|
|
151
|
+
if rank:
|
|
152
|
+
opt=minimize(obj.evaluate,theta0,jac=True,method='L-BFGS-B',
|
|
153
|
+
options=dict(maxiter=maxiter,ftol=ftol,gtol=gtol,maxls=50,maxcor=20))
|
|
154
|
+
theta=opt.x;success=bool(opt.success);message=str(opt.message)
|
|
155
|
+
iterations=int(opt.nit);evaluations=int(opt.nfev)
|
|
156
|
+
else:
|
|
157
|
+
theta=theta0;success=True;message='Exact background solve';iterations=0;evaluations=1
|
|
158
|
+
final,grad=obj.evaluate(theta)
|
|
159
|
+
u,v=obj.unpack(theta)
|
|
160
|
+
result=dict(U=u.copy(),V=v.copy(),background_weights=obj.latest['w'].copy(),
|
|
161
|
+
target_center=center,target_scale=scale)
|
|
162
|
+
result['diagnostics']=dict(rank=rank,n_genes=n_genes,n_train=len(y),loss_mode=loss_mode,
|
|
163
|
+
lambda_factor=lambda_factor,initialization=initialization,seed=seed,
|
|
164
|
+
initial_objective=float(initial),final_objective=float(final),
|
|
165
|
+
train_mse=float(np.mean(obj.latest['error']**2)*scale**2),
|
|
166
|
+
antisymmetric_training_mse=obj.latest['antisymmetric_mse']*scale**2,
|
|
167
|
+
gradient_inf_norm=float(np.max(abs(grad))) if len(grad) else 0.,
|
|
168
|
+
background_stationarity_inf_norm=float(np.max(abs(obj.design.T@obj.latest['error']+
|
|
169
|
+
obj.penalty*obj.latest['w']))),
|
|
170
|
+
success=success,message=message,iterations=iterations,function_evaluations=evaluations,
|
|
171
|
+
runtime_seconds=time.perf_counter()-start,normalization='training y mean/std',
|
|
172
|
+
no_file_access=True)
|
|
173
|
+
return result
|
|
174
|
+
|
|
175
|
+
def predict_design_lowrank(model,ia,ib,background_design):
|
|
176
|
+
ia=np.asarray(ia,int);ib=np.asarray(ib,int)
|
|
177
|
+
u,v=model['U'],model['V']
|
|
178
|
+
latent=.5*(np.sum(u[:,ia]*v[:,ib],axis=0)+np.sum(u[:,ib]*v[:,ia],axis=0))
|
|
179
|
+
base=np.asarray(background_design@model['background_weights']).ravel()
|
|
180
|
+
return model['target_center']+model['target_scale']*(base+latent)
|