AcidGNet_HCT116 / src /build_knowledge_graph.py
xuyun's picture
Upload folder using huggingface_hub
a521a25 verified
Raw History Blame Contribute Delete
2.27 kB
"""Build a bounded, evidence-preserving acid-adaptation knowledge graph.
Inputs must be local source tables. The script never queries an undocumented live API and never expands
beyond configured hops/neighbour caps. Expected edge columns: source,target,edge_type,database,evidence_id,score.
"""
from __future__ import annotations
import argparse,csv,pathlib
def build(seed_file:pathlib.Path,edge_files:list[pathlib.Path],outdir:pathlib.Path,max_hops=1,max_neighbors=20,min_score=.7):
seeds={r['gene'] for r in csv.DictReader(seed_file.open(encoding='utf-8')) if float(r.get('evidence_score',0))>=1}
all_edges=[]
for path in edge_files:
with path.open(encoding='utf-8') as f:
for r in csv.DictReader(f):
if float(r.get('score',1))>=min_score: all_edges.append(r)
selected=[];front=set(seeds);seen=set(seeds)
for _ in range(max_hops):
degree={x:0 for x in front};next_front=set()
for r in sorted(all_edges,key=lambda x:float(x.get('score',1)),reverse=True):
a,b=r['source'],r['target']; anchor=a if a in front else b if b in front else None
if anchor and degree[anchor]<max_neighbors:
selected.append(r);degree[anchor]+=1;next_front|={a,b}
next_front-=seen;seen|=next_front;front=next_front
outdir.mkdir(parents=True,exist_ok=True)
fields=['source','target','edge_type','database','evidence_id','score']
with (outdir/'knowledge_graph_edges.csv').open('w',newline='',encoding='utf-8') as f:w=csv.DictWriter(f,fieldnames=fields,extrasaction='ignore');w.writeheader();w.writerows(selected)
with (outdir/'knowledge_graph_nodes.csv').open('w',newline='',encoding='utf-8') as f:w=csv.DictWriter(f,fieldnames=['node_id','is_seed']);w.writeheader();w.writerows({'node_id':x,'is_seed':int(x in seeds)} for x in sorted(seen))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--seeds',required=True);p.add_argument('--edges',nargs='+',required=True);p.add_argument('--outdir',required=True);p.add_argument('--max-hops',type=int,default=1);p.add_argument('--max-neighbors',type=int,default=20);a=p.parse_args();build(pathlib.Path(a.seeds),list(map(pathlib.Path,a.edges)),pathlib.Path(a.outdir),a.max_hops,a.max_neighbors)