AcidGNet_HCT116 / src /run_strict_validation.py
xuyun's picture
Upload folder using huggingface_hub
a521a25 verified
Raw History Blame Contribute Delete
12.8 kB
from __future__ import annotations
import argparse, gzip, hashlib, io, json, math, pathlib, random, tarfile
import numpy as np, pandas as pd, requests, torch
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score, roc_curve, precision_recall_curve
from torch import nn
from torch_geometric.data import Data, Batch
from torch_geometric.nn import GATv2Conv, GCNConv, global_mean_pool
import matplotlib as mpl; mpl.use('Agg')
import matplotlib.pyplot as plt
ROOT=pathlib.Path(__file__).resolve().parents[1]; SEED=20260809; NGENES=300
def load_discovery():
df=pd.read_csv(ROOT/'data/raw/GSE253054_Normalized_counts_Acidosis.csv.gz',sep=';',decimal=',',index_col=0,compression='gzip')
x=np.log2(df.astype(float)+1).T; meta=pd.DataFrame(index=x.index)
c=pd.Series(meta.index.str.extract(r'^(Fadu|HCT|Siha)',expand=False),index=meta.index)
meta['cell_line']=c.replace({'Fadu':'FaDu','HCT':'HCT116','Siha':'SiHa'});meta['acid']=meta.index.str.contains('65').astype(int)
return x,meta
def load_external():
path=ROOT/'data/raw/GSE200546_RAW.tar'; cols={}
with tarfile.open(path) as t:
for m in t.getmembers():
name=m.name
if ('pH6.6' not in name and 'pH7.4' not in name) or '24H' in name: continue
raw=gzip.decompress(t.extractfile(m).read()); d=pd.read_csv(io.BytesIO(raw),sep='\t').set_index('gene_id')['expected_count'];cols[name.replace('.txt.gz','')]=d
x=np.log2(pd.DataFrame(cols).fillna(0).T+1);meta=pd.DataFrame(index=x.index);meta['acid']=meta.index.str.contains('pH6.6').astype(int);meta['cell_line']='CLS1_lung'
return x,meta
def sample_rank(a):
return pd.DataFrame(a,index=a.index,columns=a.columns).rank(axis=1,pct=True).sub(.5).values.astype('float32')
def string_graph(genes,tag):
cache=ROOT/'data/raw/string_strict';cache.mkdir(parents=True,exist_ok=True);h=hashlib.sha1(('\n'.join(genes)).encode()).hexdigest()[:12];mf=cache/f'{tag}_{h}_map.tsv';ef=cache/f'{tag}_{h}_edges.tsv';ids='\r'.join(genes)
if not mf.exists():
r=requests.post('https://string-db.org/api/tsv/get_string_ids',data={'identifiers':ids,'species':9606,'limit':1,'echo_query':1},timeout=180);r.raise_for_status();mf.write_text(r.text,encoding='utf-8')
mp=pd.read_csv(mf,sep='\t').drop_duplicates('queryItem');mapd=mp.set_index('queryItem')['preferredName'].to_dict();mapped=[g for g in genes if g in mapd]
if not ef.exists():
r=requests.post('https://string-db.org/api/tsv/network',data={'identifiers':'\r'.join(mapped),'species':9606,'required_score':700,'network_type':'functional'},timeout=180);r.raise_for_status();ef.write_text(r.text,encoding='utf-8')
ed=pd.read_csv(ef,sep='\t');sym2g={mapd[g]:g for g in mapped};pairs=[]
for _,r in ed.iterrows():
a=sym2g.get(r['preferredName_A']);b=sym2g.get(r['preferredName_B'])
if a and b and a!=b:pairs.extend([(a,b),(b,a)])
nodes=mapped;idx={g:i for i,g in enumerate(nodes)};pairs=list(dict.fromkeys(p for p in pairs if p[0] in idx and p[1] in idx));ei=torch.tensor([[idx[a] for a,b in pairs],[idx[b] for a,b in pairs]],dtype=torch.long) if pairs else torch.empty((2,0),dtype=torch.long)
return nodes,ei,pd.DataFrame({'gene_id':nodes,'symbol':[mapd[g] for g in nodes]}),pd.DataFrame(pairs,columns=['source','target'])
class GraphModel(nn.Module):
def __init__(self,kind='gat'):
super().__init__();Conv=GATv2Conv if kind=='gat' else GCNConv
self.a=Conv(1,16,heads=2,concat=False,dropout=.2) if kind=='gat' else Conv(1,16)
self.b=Conv(16,16,heads=2,concat=False,dropout=.2) if kind=='gat' else Conv(16,16);self.out=nn.Linear(16,1)
def forward(self,b):
z=torch.relu(self.a(b.x,b.edge_index));z=torch.relu(self.b(z,b.edge_index));e=global_mean_pool(z,b.batch);return self.out(e).squeeze(1),e
class MLP(nn.Module):
def __init__(self,n):super().__init__();self.m=nn.Sequential(nn.Linear(n,32),nn.ReLU(),nn.Dropout(.2),nn.Linear(32,1))
def forward(self,x):return self.m(x).squeeze(1)
def batch(a,ei,device):return Batch.from_data_list([Data(x=torch.tensor(r[:,None]),edge_index=ei) for r in a]).to(device)
def fit_predict(kind,xtr,ytr,xte,ei,seed,device,return_model=False):
torch.manual_seed(seed);random.seed(seed);np.random.seed(seed);y=torch.tensor(ytr,dtype=torch.float32,device=device)
if kind=='MLP':
m=MLP(xtr.shape[1]).to(device);xt=torch.tensor(xtr,device=device);xe=torch.tensor(xte,device=device)
opt=torch.optim.AdamW(m.parameters(),lr=.003,weight_decay=1e-4)
for _ in range(200):m.train();opt.zero_grad();loss=nn.functional.binary_cross_entropy_with_logits(m(xt),y);loss.backward();opt.step()
m.eval();p=torch.sigmoid(m(xe)).detach().cpu().numpy();return (p,m,xe) if return_model else p
graph_kind='gcn' if kind=='GCN' else 'gat';use_ei=torch.empty((2,0),dtype=torch.long) if kind=='SelfLoopGAT' else ei
if kind=='PermutedGraphGAT' and ei.numel():
perm=torch.randperm(xtr.shape[1]);use_ei=perm[ei]
tr=batch(xtr,use_ei,device);te=batch(xte,use_ei,device);m=GraphModel(graph_kind).to(device);opt=torch.optim.AdamW(m.parameters(),lr=.005,weight_decay=1e-4)
for _ in range(200):m.train();opt.zero_grad();logit,_=m(tr);loss=nn.functional.binary_cross_entropy_with_logits(logit,y);loss.backward();opt.step()
m.eval();p=torch.sigmoid(m(te)[0]).detach().cpu().numpy();return (p,m,te) if return_model else p
def metrics(y,p):return {'auroc':roc_auc_score(y,p),'auprc':average_precision_score(y,p),'brier':brier_score_loss(y,p)}
def run_cv(x,meta,device):
methods=['ExprLogReg','MLP','GCN','AcidGNet','SelfLoopGAT','PermutedGraphGAT'];pred=[];fm=[];graphrows=[]
for held in ['FaDu','HCT116','SiHa']:
tr=meta.cell_line.ne(held);te=~tr;top=x.loc[tr].var().nlargest(NGENES).index.tolist();nodes,ei,nd,ed=string_graph(top,'cv_'+held);A=sample_rank(x.loc[tr,nodes]);B=sample_rank(x.loc[te,nodes]);ytr=meta.loc[tr,'acid'].values;yte=meta.loc[te,'acid'].values;graphrows.append({'fold':held,'nodes':len(nodes),'directed_edges':ei.shape[1]})
lr=LogisticRegression(C=.1,max_iter=2000,random_state=SEED).fit(A,ytr);pp=lr.predict_proba(B)[:,1]
for s in meta.index[te]:pass
for sample,y,p in zip(meta.index[te],yte,pp):pred.append({'sample':sample,'held_out':held,'y':y,'prob':p,'method':'ExprLogReg','seed':'ensemble'})
fm.append({'held_out':held,'method':'ExprLogReg','n':len(yte),**metrics(yte,pp)})
for method in methods[1:]:
ps=[]
for seed in [SEED,SEED+1,SEED+2]:ps.append(fit_predict(method,A,ytr,B,ei,seed,device))
q=np.mean(ps,axis=0)
for sample,y,p in zip(meta.index[te],yte,q):pred.append({'sample':sample,'held_out':held,'y':y,'prob':p,'method':method,'seed':'3-seed-mean'})
fm.append({'held_out':held,'method':method,'n':len(yte),**metrics(yte,q)})
return pd.DataFrame(pred),pd.DataFrame(fm),pd.DataFrame(graphrows)
def run_external(x,meta,xe,me,device):
top=x.var().nlargest(NGENES).index.tolist();nodes,ei,nd,ed=string_graph(top,'external');id2sym=nd.set_index('gene_id')['symbol'].to_dict();pairs=[(g,id2sym[g]) for g in nodes if id2sym[g] in xe.columns];nodes=[g for g,s in pairs];symbols=[s for g,s in pairs]
oldidx={g:i for i,g in enumerate(nd.gene_id)};keep=[oldidx[g] for g in nodes];imap={old:i for i,old in enumerate(keep)};pairs_e=[]
for a,b in ei.T.tolist():
if a in imap and b in imap:pairs_e.append((imap[a],imap[b]))
e2=torch.tensor(pairs_e,dtype=torch.long).T.contiguous() if pairs_e else torch.empty((2,0),dtype=torch.long)
A=sample_rank(x[nodes]);B=sample_rank(xe[symbols]);ytr=meta.acid.values;yte=me.acid.values;methods=['ExprLogReg','MLP','GCN','AcidGNet','SelfLoopGAT','PermutedGraphGAT'];records=[];mm=[];ablation=[]
lr=LogisticRegression(C=.1,max_iter=2000,random_state=SEED).fit(A,ytr);pp=lr.predict_proba(B)[:,1]
for sample,y,p in zip(me.index,yte,pp):records.append({'sample':sample,'y':y,'prob':p,'method':'ExprLogReg'})
mm.append({'method':'ExprLogReg','n':len(yte),**metrics(yte,pp)})
acid_idx=np.where(yte==1)[0]
for method in methods[1:]:
ps=[]
for seed in [SEED,SEED+1,SEED+2]:
if method=='AcidGNet':
p,m,bt=fit_predict(method,A,ytr,B,e2,seed,device,True);ps.append(p)
base=p.copy()
for j,(g,sym) in enumerate(zip(nodes,symbols)):
ba=B.copy();ba[:,j]=0;pb=torch.sigmoid(m(batch(ba,e2,device))[0]).detach().cpu().numpy();ablation.append({'seed':seed,'gene_id':g,'symbol':sym,'ars_mean_acid':float(np.mean(base[acid_idx]-pb[acid_idx])),'abs_effect_all':float(np.mean(np.abs(base-pb)))})
else:ps.append(fit_predict(method,A,ytr,B,e2,seed,device))
q=np.mean(ps,axis=0)
for sample,y,p in zip(me.index,yte,q):records.append({'sample':sample,'y':y,'prob':p,'method':method})
mm.append({'method':method,'n':len(yte),**metrics(yte,q)})
return pd.DataFrame(records),pd.DataFrame(mm),pd.DataFrame(ablation),nd,ed
def figures(cvmet,extpred,extmet,abl):
mpl.rcParams.update({'font.family':'sans-serif','font.sans-serif':['Arial','DejaVu Sans'],'svg.fonttype':'none','pdf.fonttype':42,'font.size':7,'axes.spines.top':False,'axes.spines.right':False})
order=['ExprLogReg','MLP','GCN','AcidGNet','SelfLoopGAT','PermutedGraphGAT'];cols=['#4B78A8','#83A6C8','#7AAE9B','#C65D4B','#D9A66C','#9A8CB3']
fig,axs=plt.subplots(1,2,figsize=(7.2,2.7));
for k,metric in enumerate(['auroc','auprc']):
dat=[cvmet.loc[cvmet.method==m,metric].values for m in order];axs[k].boxplot(dat,labels=order,showmeans=True);axs[k].set_ylim(-.05,1.05);axs[k].set_ylabel(metric.upper());axs[k].tick_params(axis='x',rotation=45);axs[k].set_title('Strict leave-one-cell-line-out')
fig.tight_layout();
for ext in ['png','pdf','svg']:fig.savefig(ROOT/f'figures/Fig4_strict_ablation.{ext}',dpi=600 if ext=='png' else None,bbox_inches='tight');plt.close(fig)
fig,axs=plt.subplots(1,3,figsize=(7.2,2.4));
for m,c in zip(order,cols):
d=extpred[extpred.method==m];fpr,tpr,_=roc_curve(d.y,d.prob);pr,re,_=precision_recall_curve(d.y,d.prob);axs[0].plot(fpr,tpr,label=f'{m} {roc_auc_score(d.y,d.prob):.2f}',color=c);axs[1].plot(re,pr,label=f'{m} {average_precision_score(d.y,d.prob):.2f}',color=c)
axs[0].plot([0,1],[0,1],'--',c='.7');axs[0].set(xlabel='FPR',ylabel='TPR',title='External ROC');axs[1].set(xlabel='Recall',ylabel='Precision',title='External PR');axs[0].legend(fontsize=5);axs[1].legend(fontsize=5)
vals=[extmet.loc[extmet.method==m,'auroc'].iloc[0] for m in order];axs[2].bar(range(len(order)),vals,color=cols);axs[2].set_xticks(range(len(order)),order,rotation=45,ha='right');axs[2].set_ylim(0,1.05);axs[2].set(ylabel='AUROC',title='GSE200546 CLS1')
fig.tight_layout();
for ext in ['png','pdf','svg']:fig.savefig(ROOT/f'figures/Fig5_external_validation.{ext}',dpi=600 if ext=='png' else None,bbox_inches='tight');plt.close(fig)
a=abl.groupby('symbol').agg(ars=('ars_mean_acid','mean'),sd=('ars_mean_acid','std'),stability=('abs_effect_all','mean')).sort_values('stability').tail(20)
fig,ax=plt.subplots(figsize=(4.8,3.5));ax.barh(a.index,a.stability,xerr=a.sd.fillna(0),color='#C65D4B');ax.set(xlabel='Mean absolute probability change',title='External node-ablation sensitivity');fig.tight_layout()
for ext in ['png','pdf','svg']:fig.savefig(ROOT/f'figures/Fig6_node_ablation.{ext}',dpi=600 if ext=='png' else None,bbox_inches='tight');plt.close(fig)
def main():
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu');x,m=load_discovery();xe,me=load_external();cvp,cvm,graphs=run_cv(x,m,device);ep,em,abl,nd,ed=run_external(x,m,xe,me,device)
cvp.to_csv(ROOT/'results/strict_cv_predictions.csv',index=False);cvm.to_csv(ROOT/'results/strict_cv_metrics.csv',index=False);graphs.to_csv(ROOT/'results/strict_cv_graphs.csv',index=False);ep.to_csv(ROOT/'results/external_GSE200546_predictions.csv',index=False);em.to_csv(ROOT/'results/external_GSE200546_metrics.csv',index=False);abl.to_csv(ROOT/'results/external_node_ablation.csv',index=False);nd.to_csv(ROOT/'data/processed/external_graph_nodes.csv',index=False);ed.to_csv(ROOT/'data/processed/external_graph_edges.csv',index=False);figures(cvm,ep,em,abl)
summary={'device':str(device),'strict_cv_mean':cvm.groupby('method')[['auroc','auprc','brier']].mean().round(4).to_dict('index'),'external':em.set_index('method')[['auroc','auprc','brier']].round(4).to_dict('index'),'external_n':len(me)};(ROOT/'logs/strict_validation_summary.json').write_text(json.dumps(summary,indent=2),encoding='utf-8');print(json.dumps(summary))
if __name__=='__main__':main()