def test_mass_delta(self): r = self.create_reacts([('methylation', '[N,O:1]>>[*:1]-[#6]') ])['methylation'] m = Molecule.load_from_smiles('CCO') self.assertIsNone(r.mass_delta()) r.run_reaction([m]) self.assertEqual(round(r.mass_delta(), 6), 14.01565)
def test_fs_gen_mgf(self): smiles = FragCommonTests.test_data['smiles'] m = Molecule.load_from_smiles(smiles) fs = FragCommonTests.new_frag_sim() fm = fs.frag_molecule(m, adduct='M+') #'PEPMASS=45.0447245801' #'MOLECULAR_FORMULA=CH5N2+' exp_res = '\n'.join([\ 'BEGIN IONS',\ 'PEPMASS=45.0447245801',\ 'CHARGE=1+',\ 'FILENAME=METWORK_' + str(m.id), \ 'SMILES=N=C[NH3+]',\ 'INCHI=InChI=1S/CH4N2/c2-1-3/h1H,(H3,2,3)/p+1',\ 'INCHIAUX=PNKUSGQVOMIXLU-UHFFFAOYSA-O',\ 'SCANS=' + str(m.id), \ #'18.033826 0.397148', #'28.018175 0.993644', #'45.044725 98.609208', '18.0338255500 0.3971478062', '28.0181754800 0.9936442241', '45.0447245800 98.6092079700', 'END IONS', ]) + u'\n' self.assertEqual(fm.gen_mgf(energy=0, decimal=10), exp_res)
def load_smiles(self, request, pk=None): data = JSONParser().parse(request) mols = Molecule.load_from_smiles(data["smiles"].replace("\n", ".")) if mols != False: return JsonResponse({"success": [mols.chemdoodle_json]}) else: return JsonResponse({"error": "unable to load smiles"})
def load_smiles(self, request, pk=None): data = JSONParser().parse(request) mols = Molecule.load_from_smiles(data['smiles'].replace('\n', '.')) if mols != False: return JsonResponse({'success': [mols.chemdoodle_json]}) else: return JsonResponse({'error': 'unable to load smiles'})
def test_frag_mol(self): fs = FragCommonTests.new_frag_sim() smiles = FragCommonTests.test_data['smiles'] m = Molecule.load_from_smiles(smiles) self.assertFalse(fs.get_frag_mol(m)) fs.frag_molecule(m) self.assertTrue(fs.get_frag_mol(m))
def test_mass_delta(self): r = self.create_reacts([("methylation", "[N,O:1]>>[*:1]-[#6]") ])["methylation"] m = Molecule.load_from_smiles("CCO") self.assertIsNone(r.mass_delta()) r.run_reaction([m]) self.assertEqual(round(r.mass_delta(), 6), 14.01565)
def test_fs_gen_mgf(self): smiles = FragCommonTests.test_data["smiles"] m = Molecule.load_from_smiles(smiles) fs = FragCommonTests.new_frag_sim() fm = fs.frag_molecule(m, adduct="M+") #'PEPMASS=45.0447245801' #'MOLECULAR_FORMULA=CH5N2+' exp_res = ( "\n".join([ "BEGIN IONS", "PEPMASS=45.0447245801", "CHARGE=1+", "FILENAME=METWORK_" + str(m.id), "SMILES=N=C[NH3+]", "INCHI=InChI=1S/CH4N2/c2-1-3/h1H,(H3,2,3)/p+1", "INCHIAUX=PNKUSGQVOMIXLU-UHFFFAOYSA-O", "SCANS=" + str(m.id), #'18.033826 0.397148', #'28.018175 0.993644', #'45.044725 98.609208', "18.0338255500 0.3971478062", "28.0181754800 0.9936442241", "45.0447245800 98.6092079700", "END IONS", ]) + "\n") self.assertEqual(fm.gen_mgf(energy=0, decimal=10), exp_res)
def test_reset_react_process(self): # reset react process if not ACTIVE r = self.create_reacts([('methylation', '[N,O:1]>>[*:1]-[#6]-[#6]') ])['methylation'] co = Molecule.load_from_smiles('CO') cco = Molecule.load_from_smiles('CCO') self.assertEqual(r.reactprocess_set.count(), 0) r.run_reaction([cco]) self.assertEqual(r.reactprocess_set.count(), 1) r.smarts = '[N,O:1]>>[*:1]-[#6]' r.save() r.run_reaction([co]) self.assertEqual(r.reactprocess_set.count(), 1) r.status_code = Reaction.status.ACTIVE r.save() r.run_reaction([cco]) self.assertEqual(r.reactprocess_set.count(), 2)
def test_reset_react_process(self): # reset react process if not ACTIVE r = self.create_reacts([("methylation", "[N,O:1]>>[*:1]-[#6]-[#6]")], activate=False)["methylation"] co = Molecule.load_from_smiles("CO") cco = Molecule.load_from_smiles("CCO") self.assertEqual(r.reactprocess_set.count(), 0) r.run_reaction([cco]) self.assertEqual(r.reactprocess_set.count(), 1) r.smarts = "[N,O:1]>>[*:1]-[#6]" r.save() r.run_reaction([co]) self.assertEqual(r.reactprocess_set.count(), 1) r.status_code = Reaction.status.ACTIVE r.save() r.run_reaction([cco]) self.assertEqual(r.reactprocess_set.count(), 2)
def json_to_mol(self, json_data): from base.models import Molecule mol_rdkit = self.json_to_rdkit(json_data) smiles = Chem.MolToSmiles(mol_rdkit) smiles = RDKit.mol_to_smiles(mol_rdkit) # return Molecule.load_from_rdkit(mol_rdkit) return Molecule.load_from_smiles(Chem.MolToSmiles(mol_rdkit))
def test_frag_mol(self): fs = FragCommonTests.new_frag_sim() smiles = FragCommonTests.test_data["smiles"] m = Molecule.load_from_smiles(smiles) adduct = "M+" self.assertFalse(fs.get_frag_mol(m, adduct=adduct)) fs.frag_molecule(m, adduct=adduct) self.assertTrue(fs.get_frag_mol(m, adduct=adduct))
def add_annotation(self, ion_id, smiles, db_source='', db_id=''): # ===> Add ion_name ! from fragmentation.models import FragAnnotationDB fms = self.fragmolsample_set.get(ion_id=int(ion_id)) return FragAnnotationDB.objects.create( frag_mol_sample=fms, molecule=Molecule.load_from_smiles(smiles), db_source=db_source, db_id=db_id)
def test_mol_to_json(self): smiles = 'C/C(F)=C/[C@@](C)(N)c1ccc(O)cc1' mol = Molecule.load_from_smiles(smiles) json_path = 'base/tests/files/chemdoodle_mol_1.json' cd = ChemDoodle() with open(json_path, 'r') as fjson: json_str = '[{0}]'.format(fjson.readline()) json_mol = json.loads(json_str)[0]['m'][0] json_res = cd.mol_to_json(mol) self.assertEqual(cd.json_to_mol(json_res).smiles(), smiles)
def test_get_adduct(self): PARENT_MASS = 382.32800 SMILES = 'OCC(OC/C=C(C)/CC/C=C(C)/CC/C=C(C)/CC/C=C(C)/C)CO' ION_CHARGE = 'positive' ADDUCT_TARGET = 'M+NH4' fms = FragMolSample(parent_mass=PARENT_MASS) m = Molecule.load_from_smiles(SMILES) ad = AdductManager(ION_CHARGE) self.assertEqual(ad.get_adduct(m, fms), ADDUCT_TARGET)
def import_annotation_file(self, file_object, file_format="default"): from fragmentation.models import FragMolSample, FragAnnotationDB delimiter_by_format = {"GNPS": "\t"} quotechar_by_format = {"GNPS": None} data = [row.decode() for row in file_object.readlines()] data = list( csv.reader( data, delimiter=delimiter_by_format.get(file_format, ","), quotechar=quotechar_by_format.get(file_format, '"'), )) errors = {} col_titles = data[0] for idx, line in enumerate(data[1:]): try: status_id = AnnotationStatus.VALIDATED if file_format == "default": ion_id, name, smiles, db_source, db_id = line if file_format == "level": ion_id, name, smiles, db_source, db_id, level = line status_id = STATUS_LEVEL_MAPPING.get( int(level), AnnotationStatus.UNRATED) elif file_format == "GNPS": ion_id = line[col_titles.index("#Scan#")] name = line[col_titles.index("Compound_Name")] smiles = line[col_titles.index("Smiles")] db_source = "GNPS : {0}, {1}".format( line[col_titles.index("Compound_Source")], line[col_titles.index("Data_Collector")], ) db_id = line[col_titles.index("CAS_Number")] if int(ion_id) > 0: molecule = Molecule.load_from_smiles(smiles) fms = self.fragmolsample_set.get(ion_id=ion_id) self.add_annotation( frag_mol_sample=fms, molecule=molecule, name=name, db_source=db_source, db_id=db_id, status_id=status_id, ) except Exception as err: # print(err) errors[idx] = {"err": str(err), "idx": idx} return { "success": "Annotations successfully imported", "errors": errors }
def test_frag_mol_neg(self): fsc = FragSimConf.objects.create( param_path="param/param_output0_neg.log", conf_path="conf/param_config_neg.txt", ) fs = FragSim(fsc) smiles = "CCC(C)O" m = Molecule.load_from_smiles(smiles) adduct = "M-" assert not fs.get_frag_mol(m, adduct=adduct) fs.frag_molecule(m, adduct=adduct, ion_charge="negative") fms = fs.get_frag_mol(m, adduct=adduct) assert fms spectrum = fms.fragmolspectrum_set.filter(energy=0).first().spectrum assert spectrum[0][0] == 17.00328823
def import_annotation_file(self, file_object, file_format='default'): from fragmentation.models import FragMolSample, FragAnnotationDB am = AdductManager(ion_charge=self.ion_charge) fls = [l.decode('utf-8') for l in file_object.readlines()] errors = {} col_titles = fls[0].split("\t") for i, fl in enumerate(fls[1:]): try: if file_format == 'default': ion_id, name, smiles, db_source, db_id = fl.split( "\n")[0].split(",") elif file_format == 'GNPS': data = fl.split("\t") ion_id = data[col_titles.index('#Scan#')] name = data[col_titles.index('Compound_Name')] smiles = data[col_titles.index('Smiles')] db_source = 'GNPS : {0}, {1}'.format( data[col_titles.index('Compound_Source')], data[col_titles.index('Data_Collector')]) db_id = data[col_titles.index('CAS_Number')] if int(ion_id) > 0: m = Molecule.load_from_smiles(smiles) fms = self.fragmolsample_set.get(ion_id=ion_id) adduct = am.get_adduct(m, fms) if adduct is not None: if fms.adduct is None: fms.adduct = adduct fms.save() if fms.adduct == adduct: fa = FragAnnotationDB.objects.create( frag_mol_sample=fms, molecule=m, name=name, db_source=db_source, db_id=db_id) except Exception as err: # print(err) errors[i] = {'err': str(err), 'smiles': smiles} return { 'success': 'Annotations successfully imported', 'errors': errors }
def test_cosine_mgf_sim(self): # user = get_user_model().objects.create() fc = self.new_frag_compare() with open(self.TEST_FILES_PATH + "cosine_4.mgf", "rb") as fr: fsample = FragSample.import_sample( fr, FragCompareModelTests.user, "name", "file_name" ) fsample.wait_import_done() sm = "N=C(N)NCC/C=C1/N=C(O)N(/C=C/c2ccc(O)cc2)C1=O" m = Molecule.load_from_smiles(sm) fsim = FragCommonTests.new_frag_sim() fms = fsim.frag_molecule(m) fmc = fc.compare_frag_mols([fsample.fragmolsample_set.first(), fms]) # print(fmc.cosine)#, fmc.num_frag_match self.assertTrue(fmc.cosine >= 0.2, fmc.cosine)
def test_process_reaction_double_reactants(self): r = self.create_reacts([("diels_alder", None)])["diels_alder"] smiles = ["C=Cc1c[nH]c(N)n1", "C=CCC"] expected_smiles = ["CCC1CCC=C2N=C(N)NC12", "CCC1CC=C2N=C(N)NC2C1"] ml = [Molecule.load_from_smiles(sm) for sm in smiles] smarts = "[#6:1]=,:[#6:2]-[#6:3]=,:[#6:4].[#6:5]=,:[#6:6]>>[#6:1]1-[#6:2]=,:[#6:3]-[#6:4]-[#6:6]-[#6:5]-1" r.load_smarts(smarts) for i in range(2): rp = ReactProcess.objects.create(reaction=r) for m in ml: rp.reactants.add(m) rp.save() rp.run_reaction() # Check if molecule has been created expected_mols = { Molecule.find_from_smiles(sm) for sm in expected_smiles } self.assertEqual(set(rp.products.all()), expected_mols) ml.reverse()
def add_annotation_from_smiles( self, ion_id, smiles, name="", db_source="", db_id="", status_id=AnnotationStatus.UNDEFINED, ): molecule = Molecule.load_from_smiles(smiles) fms = self.fragmolsample_set.get(ion_id=int(ion_id)) self.add_annotation( frag_mol_sample=fms, molecule=molecule, name=name, db_source=db_source, db_id=db_id, status_id=status_id, )
def test_process_reaction_single_reactant(self): r = self.create_reacts([("methylation", "[N,O:1]>>[*:1]-[#6]") ])["methylation"] sm = "NC=C(N)C" expected_smiles = ["CNC=C(C)N", "CNC(C)=CN"] m = Molecule.load_from_smiles(sm) m.save() # Reaction.reactions_update() r = Reaction.objects.get(name="methylation") rp = ReactProcess.objects.create(reaction=r) rp.reactants.add(m) rp.run_reaction() # Check if molecule has been created expected_mols = { Molecule.find_from_smiles(sm) for sm in expected_smiles } self.assertTrue(not False in expected_mols) # Check if reaction_product has been created self.assertEqual(rp.products.count(), 2) for m_exp in expected_mols: self.assertTrue(m_exp in rp.products.all())
def run_reaction(self, request, pk=None): data = JSONParser().parse(request) chemdoodle_json = data['reactants']['chemdoodle_json'] if 'm' in chemdoodle_json: cd = ChemDoodle() reactants = [ cd.json_to_mol(mol_json) for mol_json in chemdoodle_json['m'] ] reactants_smiles = reactants[0].smiles() if '.' in reactants_smiles: reactants = [ Molecule.load_from_smiles(sm) \ for sm in reactants_smiles.split('.')] r = self.get_object() rp = r.run_reaction(reactants) response = { 'reactants': [r.chemdoodle_json for r in rp.reactants.all()], 'products': [p.chemdoodle_json for p in rp.products.all()] } return JsonResponse(response) else: return JsonResponse({'error': 'test'})
def run_reaction(self, request, pk=None): data = JSONParser().parse(request) chemdoodle_json = data["reactants"]["chemdoodle_json"] if "m" in chemdoodle_json: cd = ChemDoodle() reactants = [ cd.json_to_mol(mol_json) for mol_json in chemdoodle_json["m"] ] reactants_smiles = reactants[0].smiles() if "." in reactants_smiles: reactants = [ Molecule.load_from_smiles(sm) for sm in reactants_smiles.split(".") ] r = self.get_object() rp = r.run_reaction(reactants) response = { "reactants": [r.chemdoodle_json for r in rp.reactants.all()], "products": [p.chemdoodle_json for p in rp.products.all()], } return JsonResponse(response) else: return JsonResponse({"error": "test"})
def test_load_from_smiles(self): m = Molecule.create_from_smiles('CCC') self.assertIsNot(Molecule.load_from_smiles('CCC'), False) self.assertIsNot(Molecule.load_from_smiles('CCCC'), False) self.assertFalse(Molecule.load_from_smiles('HHOHH'))
def test_mass_selection(self): u = get_user_model().objects.create(email='*****@*****.**') methylation = Reaction.objects.create(user=u, name='methylation', smarts='[N,O:1]>>[*:1]-[#6]') methylation.run_reaction([Molecule.load_from_smiles('CCO')]) methylation_modified = Reaction.objects.create( user=u, name='methylation_modified', smarts='[N,O:1]>>IC(I)C[*:1]') methylation_modified.run_reaction([Molecule.load_from_smiles('CCO')]) diels_alder = Reaction.objects.create( user=u, name='diels_alder', smarts= '[#6:1]=,:[#6:2]-[#6:3]=,:[#6:4].[#6:5]=,:[#6:6]>>[#6:1]1-[#6:2]=,:[#6:3]-[#6:4]-[#6:6]-[#6:5]-1' ) diels_alder.run_reaction([ Molecule.load_from_smiles('C=Cc1c[nH]c(N)n1'), Molecule.load_from_smiles('C=C') ]) diels_alder_modified = Reaction.objects.create( user=u, name='diels_alder_modified', smarts= '[#6:1]=,:[#6:2]-[#6:3]=,:[#6:4]-[H].[#6:5]=,:[#6:6]>>[#6]-[#6:2]-1=,:[#6:3]-[#6:4]-[#6:6]-[#6:5]-[#6:1]-1' ) diels_alder_modified.run_reaction([ Molecule.load_from_smiles('C=Cc1c[nH]c(N)n1'), Molecule.load_from_smiles('C=C') ]) for r in [methylation, diels_alder, diels_alder_modified]: r.status_code = Reaction.status.ACTIVE r.save() sample_folder = 'fragmentation/tests/files/test_annotation_project/' sample_file_path = sample_folder + 'test_annotation_project.mgf' anno_file_path = sample_folder + 'anno_1.csv' with open(sample_file_path, 'rb') as fss: fs = FragSample.import_sample(fss, u, energy=2) # Import annotation with open(anno_file_path, 'rb') as f_annot: fs.import_annotation_file(f_annot) p = SampleAnnotationProject.objects.create(\ user = u, depth_total = 3, depth_last_match = 0) p.save() p.update_frag_sample(fs) p.select_reactions_by_mass() self.assertIn(methylation, p.reactions()) self.assertNotIn(methylation_modified, p.reactions()) self.assertIn(diels_alder, p.reactions()) self.assertNotIn(diels_alder_modified, p.reactions()) # test frag_sample.gen_mass_delta reevaluation # when new reaction added methylation_modified.status_code = Reaction.status.ACTIVE methylation_modified.save() self.assertNotIn(methylation_modified, p.reactions()) p.select_reactions_by_mass() self.assertIn(methylation_modified, p.reactions())
def new_frag_mol_sim(self, smiles='N=C([NH3+])', adduct='M+'): fs = FragCommonTests.new_frag_sim() m = Molecule.load_from_smiles(smiles) return fs.create_frag_mol_sim(molecule=m, adduct=adduct), fs
def test_load_from_smiles(self): m = Molecule.create_from_smiles("CCC") self.assertIsNot(Molecule.load_from_smiles("CCC"), False) self.assertIsNot(Molecule.load_from_smiles("CCCC"), False) self.assertFalse(Molecule.load_from_smiles("HHOHH"))