Test loading Magma results


In [ ]:
%load_ext autoreload
%autoreload 2
%matplotlib inline

import sys
basedir = '/home/joewandy/git/ms2ldaviz/ms2ldaviz/'
sys.path.append(basedir)

In [ ]:
import django
django.setup()
from django.db import transaction

from basicviz.models import Experiment, Mass2Motif, Document, FeatureInstance, MagmaSub, FeatureInstance2Sub

In [ ]:
experiment = 'massbank_binned_005'
e = Experiment.objects.get(name = experiment)

In [ ]:
documents = Document.objects.filter(experiment=e)

In [ ]:
len(documents)

In [ ]:
import json

In [ ]:
fname = '/home/joewandy/Documents/massbank_doc_annotation.json'
with open(fname) as f:
    data = json.load(f)

In [ ]:
with transaction.atomic():
    i = 0
    feature_map = {}
    for d in data:
        # update mol string in a document
        name = d['name']
        print '%d/%d %s' % (i, len(data), name)
        document = Document.objects.get(experiment=e, name=name)
        document.mol_string = d['mol']
        document.save()
        
        # lookup for existing feature instances in this document
        feature_instances = FeatureInstance.objects.filter(document=document)
        for f in feature_instances:
            feature_map[f.feature.name] = f
            
        # create a new substructure object
        for magma_annot in d['features']:
            name = magma_annot['name']
            feature = feature_map[name]
            for m in magma_annot['matches']:
                smiles = m['smiles']
                mol = m['mol'] if 'mol' in m else None
                fragatoms = m['fragatoms']
                mz = m['mz']
                sub_type = m['type'] if 'type' in m else None
                sub, _ = MagmaSub.objects.get_or_create(smiles=smiles, mol_string=mol)
                f2sub = FeatureInstance2Sub.objects.get_or_create(
                    feature=feature, sub=sub, fragatoms=fragatoms,
                    mz=mz, sub_type=sub_type
                )
        
        i+=1
        if i > 10:
            break