165 lines
5.4 KiB
Python
165 lines
5.4 KiB
Python
import molfoundry as mf
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import requests, shutil
|
|
from tqdm import tqdm
|
|
|
|
from graph import Graph
|
|
from reaction import Reaction
|
|
|
|
|
|
def clear_folder(folder):
|
|
folder = Path(folder)
|
|
for item in folder.iterdir():
|
|
if item.is_dir() and not item.is_symlink():
|
|
shutil.rmtree(item) # remove subfolders and their contents
|
|
else:
|
|
item.unlink() # remove files and symlinks
|
|
|
|
|
|
def parse_rules():
|
|
rules = {}
|
|
folder = Path("../2026-OverlayGraphs/learning_exports/aams/ogs")
|
|
MAX = 800
|
|
count = 0
|
|
for p in folder.glob("*.gml"):
|
|
if count>=MAX: break
|
|
count+=1 # only .gml files in this folder
|
|
text = p.read_text()
|
|
rule_gml = text
|
|
m = re.search(r"https?://[^\s<>\"')\]]+", text)
|
|
url = m.group(0).rstrip(".,;:!?") if m else None
|
|
m = re.search(r"/entry/(\d+)", url)
|
|
mcsa_id = m.group(1) if m else None
|
|
m = re.search(r"ruleID \"(.*)\"", text)
|
|
rule_id = m.group(1) if m else None
|
|
filename = Path(p).name
|
|
rules[int(mcsa_id)] = {'mcsa_id': mcsa_id, 'rule_id': rule_id, 'url': url, 'gml_string': rule_gml, 'filename': filename}
|
|
return rules
|
|
|
|
def get_compounds_mcsa(mcsa_id):
|
|
BASE = "https://www.ebi.ac.uk/thornton-srv/m-csa/api"
|
|
try:
|
|
r = requests.get(f"{BASE}/entries/{mcsa_id}/", params={"format": "json"}, timeout=60)
|
|
r.raise_for_status()
|
|
except requests.exceptions.RequestException as e:
|
|
return ([],[])
|
|
entry = r.json()
|
|
reaction = entry.get("reaction")
|
|
compounds = reaction["compounds"]
|
|
|
|
reactants=[]
|
|
products = []
|
|
for comp in compounds:
|
|
cnt = comp['count']
|
|
comp_type = comp['type']
|
|
name = comp['name']
|
|
mol_url = comp['mol_file']
|
|
if "reactant" in comp_type:
|
|
reactants.append(comp)
|
|
else:
|
|
products.append(comp)
|
|
|
|
return (reactants, products)
|
|
|
|
def compare_compounds(rule):
|
|
mcsa_id = rule['mcsa_id']
|
|
gml_string = rule['gml_string']
|
|
|
|
(reactants,products) = get_compounds_mcsa(mcsa_id)
|
|
if not reactants and not products: return False
|
|
mcsa_educts = {}
|
|
mcsa_products = {}
|
|
mcsa_reactants = []
|
|
# store what MCSA thinks the reactants and products are
|
|
for r in reactants:
|
|
molfile = r['mol_file']
|
|
url = f"https://{molfile}"
|
|
req = requests.get(url, timeout=60)
|
|
req.raise_for_status()
|
|
molblock = req.text
|
|
count = r['count']
|
|
name = r['name']
|
|
chebi = r['chebi_id']
|
|
mfGraph = mf.Graph.fromMolfile(molblock)
|
|
mcsa_reactants.append(mfGraph)
|
|
mcsa_educts[mfGraph.canonKey] = int(count)
|
|
|
|
for p in products:
|
|
molfile = p['mol_file']
|
|
url = f"https://{molfile}"
|
|
req = requests.get(url, timeout=60)
|
|
req.raise_for_status()
|
|
molblock = req.text
|
|
count = p['count']
|
|
name = p['name']
|
|
chebi = p['chebi_id']
|
|
mfGraph = mf.Graph.fromMolfile(molblock)
|
|
mcsa_products[mfGraph.canonKey] = int(count)
|
|
|
|
# apply rule to the reactants
|
|
mfRule = mf.Rule.fromGMLString(gml_string)
|
|
|
|
# get reactants from full OG rule
|
|
og_rule = mf.Rule.fromGMLFile(f"../2026-OverlayGraphs/learning_exports/aams/ogs/{rule['filename']}")
|
|
reac = Reaction(rule=og_rule)
|
|
reactants = [mf.Graph.fromGMLString(x.gml) for x in reac.educts]
|
|
dg = mf.DG()
|
|
#print(f"mf execute call: {mfRule.name}")
|
|
dg.build().execute(mf.addSubset(reactants) >> mfRule)
|
|
if dg.numEdges == 0:
|
|
print("RULE DID NOT APPLY!!!")
|
|
return False
|
|
edge_count = 0
|
|
|
|
for edge in dg.edges:
|
|
targets = edge.targets
|
|
mf_products = [t.graph.canonKey for t in targets]
|
|
mf_products = {k: mf_products.count(k) for k in mf_products}
|
|
# write all mf products as svgs for app use
|
|
Path(f"output/mf_products/{mcsa_id}/{edge_count}").mkdir(parents=True, exist_ok=True)
|
|
with open(f"output/mf_products/{mcsa_id}/{edge_count}/reaction.json", 'w') as f:
|
|
json.dump(mf_products, f)
|
|
for p in targets:
|
|
with open(f"output/mf_products/{mcsa_id}/{edge_count}/{p.graph.name}.svg", 'w') as f:
|
|
f.write(p.graph.svg())
|
|
edge_count+=1
|
|
|
|
diff_products = []
|
|
for prod in mcsa_products:
|
|
if prod in mf_products and (mf_products[prod]==mcsa_products[prod]): continue
|
|
diff_products.append(prod)
|
|
|
|
if len(diff_products)>0:
|
|
with open(f"output/mf_products/{mcsa_id}/match.txt", 'w') as f:
|
|
f.write("FALSE\n")
|
|
f.write(str(mcsa_products))
|
|
f.write(str(mf_products))
|
|
return False
|
|
with open(f"output/mf_products/{mcsa_id}/match.txt", 'w') as f:
|
|
f.write("TRUE\n")
|
|
return True
|
|
|
|
def draw_og_reaction(rule):
|
|
mcsa_id = rule['mcsa_id']
|
|
gml_string = rule['gml_string']
|
|
r = mf.Rule.fromGMLString(gml_string)
|
|
Path(f"output/mf_products/{mcsa_id}").mkdir(parents=True, exist_ok=True)
|
|
with open(f"output/mf_products/{mcsa_id}/reaction.svg", 'w') as f:
|
|
f.write(r.svg())
|
|
|
|
|
|
def main():
|
|
rules = parse_rules()
|
|
for rule in tqdm(rules):
|
|
if '71' not in rules[rule]['mcsa_id']: continue
|
|
print(rules[rule]['filename'])
|
|
if Path(f"output/mf_products/{rules[rule]['mcsa_id']}").exists():
|
|
clear_folder(f"output/mf_products/{rules[rule]['mcsa_id']}")
|
|
draw_og_reaction(rules[rule])
|
|
compare_compounds(rules[rule])
|
|
|
|
|
|
if __name__=="__main__":
|
|
main() |