def test_initial_state(self): model = load(join(dirname(__file__), "reprod_all.bnd"), join(dirname(__file__), "reprod_all.cfg")) i1 = model.get_initial_state() model = load(join(dirname(__file__), "reprod_all.bnd"), join(dirname(__file__), "reprod_joined_init.cfg")) i2 = model.get_initial_state() self.assertEqual(set(i1.keys()), set(i2.keys())) self.assertEqual(i2["p63"], 1) self.assertEqual(i2["p53"], 1) self.assertEqual(i2["GF"], [0,1])
def test_load_multiple_cfgs(self): sim = load(join(dirname(__file__), "reprod_all.bnd")) sim2 = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) sim3 = load(join(dirname(__file__), "cellcycle.bnd"), join(dirname(__file__), "cellcycle_runcfg.cfg"), join(dirname(__file__), "cellcycle_runcfg-thread_1.cfg"))
def test_uppmaboss_write(self): sim = load( "https://raw.githubusercontent.com/sysbio-curie/UPMaBoSS-docker/master/CellFate/CellFateModel_uppmaboss.bnd", "https://raw.githubusercontent.com/sysbio-curie/UPMaBoSS-docker/master/CellFate/CellFateModel_uppmaboss.cfg" ) uppmaboss_model = UpdatePopulation(sim) uppmaboss_model.setDivisionNode("Division") uppmaboss_model.setDeathNode("Death") uppmaboss_model.setExternalVariable( "$TNF_induc", "$ProdTNF_NFkB*p[(NFkB,Death) = (1,0)]") uppmaboss_model.setStepNumber(12) uppmaboss_sim = uppmaboss_model.run('defined') expected_pop_ratios = [ 1.0, 0.9218339999999924, 0.8467423241939606, 0.8180987248510877, 0.7990468417467085, 0.7717098511967935, 0.7300537251389624, 0.677575273214723, 0.6208988119113313, 0.5665235984581267, 0.5183656934475426, 0.4771136331972621, 0.4430243412189205 ] pop_ratios = uppmaboss_sim.get_population_ratios('WT').values.tolist() for i, pop_ratio in enumerate(pop_ratios): self.assertAlmostEqual(pop_ratio, expected_pop_ratios[i])
def test_load_reserved_names(self): with self.assertRaises(Exception) as context: sim = load(join(dirname(__file__), "reserved_names.bnd"), join(dirname(__file__), "reserved_names.cfg")) print(context.exception) self.assertTrue("Name NOT is reserved !" == str(context.exception))
def test_copy_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) sim_copy = sim.copy() self.assertEqual(str(sim.network), str(sim_copy.network)) self.assertEqual(sim.str_cfg(), sim_copy.str_cfg())
def test_modifications_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) sim.update_parameters(sample_count=100) sim.network.set_output(['Mdm2C', 'Mdm2N']) sim.mutate("Dam", "ON") res = sim.run() probas = res.get_last_states_probtraj().values[0] expected_probas = [0.442395, 0.018827, 0.157108, 0.381669] for i, proba in enumerate(probas): self.assertAlmostEqual(proba, expected_probas[i], delta=proba * 1e-6) if exists("saved_sim"): shutil.rmtree("saved_sim") res.save("saved_sim") self.assertTrue(exists("saved_sim")) self.assertTrue(exists("saved_sim/saved_sim.bnd")) self.assertTrue(exists("saved_sim/saved_sim.cfg")) self.assertTrue(exists("saved_sim/res_probtraj.csv")) self.assertTrue(exists("saved_sim/res_fp.csv")) self.assertTrue(exists("saved_sim/res_statdist.csv"))
def perform_MaBoSS_simulation(n_profile, fname, profile_name, list_drugs): path_fname = path_model + "_" + str(n_profile) for drug_id in list_drugs: path_fname_drug = path_fname + "_drug" + str(drug_id) #fname_drug=fname+"_drug"+str(drug_id) os.system("chmod +x " + path_fname_drug + ".bnd") os.system("chmod +x " + path_fname_drug + ".cfg") os.chdir(os.path.dirname(path_model)) simulation = maboss.load(path_fname_drug + ".bnd", path_fname_drug + ".cfg") result = simulation.run() nodes_traj = result.get_nodes_probtraj()[outputs] final_results = nodes_traj.tail(1).to_csv(header=0, index=1, sep=' ')[:-1] # add the number of the simulation to the line finally saved os.system("echo '" + str(n_profile) + " " + profile_name + " " + str(drug_id) + " " + final_results + "' >> " + save_file) #Remove temporary files #os.system("rm "+path_fname_drug+"/*") #os.system("rmdir "+path_fname_drug) #os.system("rm "+path_fname_drug+".bnd") #os.system("rm "+path_fname_drug+".cfg") previous.append(n_profile)
def test_probtraj_cellcycle_cmaboss(self): path = dirname(__file__) sim = load(join(path, "cellcycle.bnd"), join(path, "cellcycle_runcfg.cfg"), join(path, "cellcycle_runcfg-thread_1.cfg")) res = sim.run(cmaboss=True) res_states_probtraj = pandas.read_csv(join( path, "res", "cellcycle_states_probtraj.csv"), index_col=0, header=0) res_last_states_probtraj = pandas.read_csv(join( path, "res", "cellcycle_last_states_probtraj.csv"), index_col=0, header=0) res_nodes_probtraj = pandas.read_csv(join( path, "res", "cellcycle_nodes_probtraj.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose(res.get_states_probtraj().sort_index(axis=1), res_states_probtraj.sort_index(axis=1)).all()) self.assertTrue( numpy.isclose(res.get_last_states_probtraj().sort_index(axis=1), res_last_states_probtraj.sort_index(axis=1)).all()) self.assertTrue( numpy.isclose(res.get_nodes_probtraj().sort_index(axis=1), res_nodes_probtraj.sort_index(axis=1)).all())
def test_simulate_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) res = sim.run() res.plot_fixpoint() res.plot_trajectory(error=True) res.plot_node_trajectory(error=True) res.plot_entropy_trajectory() res.plot_piechart()
def test_load_confusedparser(self): sim = load( join(dirname(__file__), "confused_parser.bnd"), join(dirname(__file__), "confused_parser.cfg") ) self.assertEqual( list(sim.network.keys()), ['A', 'NOTH', 'B'] )
def test_uppmaboss_remote(self): sim = load( "https://raw.githubusercontent.com/sysbio-curie/UPMaBoSS-docker/master/CellFate/CellFateModel_uppmaboss.bnd", "https://raw.githubusercontent.com/sysbio-curie/UPMaBoSS-docker/master/CellFate/CellFateModel_uppmaboss.cfg" ) uppmaboss_model = UpdatePopulation( sim, "https://github.com/sysbio-curie/UPMaBoSS-docker/blob/master/CellFate/CellFateModel_uppmaboss.upp" ) uppmaboss_sim = uppmaboss_model.run('remote')
def test_type_istate(self): sim = load( join(dirname(__file__), "TregModel_InitPop.bnd"), join(dirname(__file__), "TregModel_InitPop_ActTCR2_TGFB.cfg") ) istate = sim.network.get_istate() self.assertEqual([type(value) for value in istate["PTEN"].values()], [float, float]) self.assertEqual([type(value) for value in istate[("TCR_b1", "TCR_b2", "CD28")].values()], [str, str, str]) self.assertEqual([type(value) for value in istate[("PI3K_b1", "PI3K_b2")].values()], [float, float, float]) self.assertEqual([type(value) for value in istate["TGFB"].values()], [str, str])
def test_convert_reprod_all_minibn(self): model = load(join(dirname(__file__), "reprod_all.bnd"), join(dirname(__file__), "reprod_all.cfg")) minibn_model = to_minibn(model) self.assertEqual( sorted(list(minibn_model.keys())), sorted([ 'ECMicroenv', 'DNAdamage', 'Migration', 'Metastasis', 'VIM', 'AKT2', 'ERK', 'miR200', 'AKT1', 'EMT', 'Invasion', 'p63', 'SMAD', 'CDH2', 'CTNNB1', 'CDH1', 'p53', 'p73', 'miR34', 'ZEB2', 'Apoptosis', 'miR203', 'p21', 'CellCycleArrest', 'GF', 'NICD', 'TGFbeta', 'TWIST1', 'SNAI2', 'ZEB1', 'SNAI1', 'DKK1' ]) )
def test_run_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) mbcli = MaBoSSClient(host="localhost", port=7777) res = mbcli.run(sim) self.assertEqual( res.getFP(), "Fixed Points (1)\n" + "FP\tProba\tState\tMdm2N\tp53_h\tp53\tMdm2C\tDam\n" + "#1\t0.90536\tMdm2N\t1\t0\t0\t0\t0\n") res.get_states_probtraj() res.get_statdist_clusters() mbcli.close()
def test_uppmaboss_cmaboss(self): sim = load(join(dirname(__file__), "CellFateModel.bnd"), join(dirname(__file__), "CellFateModel_1h.cfg")) uppmaboss_model = UpdatePopulation( sim, join(dirname(__file__), "CellFate_1h.upp")) uppmaboss_sim = uppmaboss_model.run('WT_cmaboss', cmaboss=True) pop_ratios = uppmaboss_sim.get_population_ratios('WT').values.tolist() expected_pop_ratios = [ 1.0, 0.6907820416914479, 0.6341903631891185, 0.612996053462505, 0.5996083687781087, 0.5788914827739509, 0.5466795703259922, 0.5075723301828101, 0.46462393081796144, 0.4237712222056809, 0.388072085864841, 0.35730025864566073, 0.3320260202532354 ] for i, pop_ratio in enumerate(pop_ratios): self.assertAlmostEqual(pop_ratio, expected_pop_ratios[i])
def test_uppmaboss_server(self): sim = load(join(dirname(__file__), "CellFateModel.bnd"), join(dirname(__file__), "CellFateModel_1h.cfg")) uppmaboss_model = UpdatePopulation( sim, join(dirname(__file__), "CellFate_1h.upp")) uppmaboss_sim = uppmaboss_model.run(host='localhost', port=7777) pop_ratios = uppmaboss_sim.get_population_ratios('WT').values.tolist() expected_pop_ratios = [ 1.0, 0.6907579999999945, 0.6341980442019741, 0.6126727283836865, 0.5992233366501704, 0.5788557354373725, 0.5473173595477481, 0.5081754112622799, 0.4654525962620004, 0.4247217704682538, 0.3886947462882363, 0.3581526679038661, 0.3328878624045683 ] for i, pop_ratio in enumerate(pop_ratios): self.assertAlmostEqual(pop_ratio, expected_pop_ratios[i])
def test_statdist_p53_Mdm2(self): path = dirname(__file__) sim = load(join(path, "p53_Mdm2.bnd"), join(path, "p53_Mdm2_runcfg.cfg")) res = sim.run() res_states_statdist = pandas.read_csv(join( path, "res", "p53_Mdm2_states_statdist.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose( res.get_states_statdist().sort_index(axis=1).dropna(), res_states_statdist.sort_index(axis=1).dropna()).all()) res_statdist_cluster0 = pandas.read_csv(join( path, "res", "p53_Mdm2_statdist_cluster0.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose(res.get_statdist_clusters()[0].sort_index(axis=1), res_statdist_cluster0.sort_index(axis=1)).all()) res_statdist_clusters_summary = pandas.read_csv(join( path, "res", "p53_Mdm2_statdist_clusters_summary.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose( res.get_statdist_clusters_summary().sort_index(axis=1), res_statdist_clusters_summary.sort_index(axis=1)).all()) res_statdist_clusters_summary_error = pandas.read_csv(join( path, "res", "p53_Mdm2_statdist_clusters_summary_error.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose( res.get_statdist_clusters_summary_error().sort_index(axis=1), res_statdist_clusters_summary_error.sort_index(axis=1)).all())
def test_toyexample_cmaboss(self): path = dirname(__file__) sim = load(join(path, "Four_cycle.bnd"), join(path, "Four_cycle_FEscape.cfg")) set_nodes_istate(sim, ["A", "B", "C"], [1, 0]) res = sim.run() self.assertEqual(list(res.get_nodes_probtraj().columns.values), ['A', 'B', 'C']) sim.network.set_output(['A', 'B']) res = sim.run(cmaboss=True) self.assertEqual(list(res.get_nodes_probtraj().columns.values), ['A', 'B']) with self.assertRaises(AssertionError, msg="Node(s) 'D' not defined !"): sim.network.set_output(['A', 'B', 'C', 'E'])
def test_uppmaboss_cmaboss_only_final_state(self): sim = load(join(dirname(__file__), "CellFateModel.bnd"), join(dirname(__file__), "CellFateModel_1h.cfg")) uppmaboss_model = UpdatePopulation( sim, join(dirname(__file__), "CellFate_1h.upp")) uppmaboss_sim = uppmaboss_model.run('WT_cmaboss_final', cmaboss=True, only_final_state=True) pop_ratios = uppmaboss_sim.get_population_ratios('WT').values.tolist() expected_pop_ratios = [ 1.0, 0.6778600000000088, 0.6279830611999899, 0.6097213137802712, 0.594362433886137, 0.5680084035675778, 0.5307981730498335, 0.4871453312981917, 0.4427225485370628, 0.4022798437281834, 0.367703891159712, 0.3393539211512898, 0.31562968852360135 ] for i, pop_ratio in enumerate(pop_ratios): self.assertAlmostEqual(pop_ratio, expected_pop_ratios[i])
def getBioLQMModel(self): if self.model.format == LogicalModel.MABOSS: maboss_sim = maboss.load( join(settings.MEDIA_ROOT, self.model.bnd_file.path), join(settings.MEDIA_ROOT, self.model.cfg_file.path)) biolqm_model = maboss.to_biolqm(maboss_sim) return biolqm_model elif self.model.format == LogicalModel.ZGINML: ginsim_model = ginsim.load( join(settings.MEDIA_ROOT, self.model.file.path)) return ginsim.to_biolqm(ginsim_model) elif self.model.format == LogicalModel.SBML: biolqm_model = biolqm.load( join(settings.MEDIA_ROOT, self.model.file.path)) return biolqm_model else: raise MethodNotAllowed()
def test_uppmaboss_overwrite(self): # Now again, but with a modified max_time, and with overwrite # Results should be different if overwriting indeed works sim = load(join(dirname(__file__), "CellFateModel.bnd"), join(dirname(__file__), "CellFateModel_1h.cfg")) sim.param["max_time"] = 2 expected_pop_ratios = [ 1.0, 0.6323979999999877, 0.5972195964539613, 0.5413299949589563, 0.4570216375540166, 0.3810664694790497, 0.3280296382569338, 0.29096852169701004, 0.26290169809410047, 0.23962359303974, 0.2201920366329486, 0.2039266710788974, 0.19007637943255015 ] uppmaboss_model = UpdatePopulation( sim, join(dirname(__file__), "CellFate_1h.upp")) uppmaboss_sim = uppmaboss_model.run('WT', overwrite=True) pop_ratios = uppmaboss_sim.get_population_ratios('WT').values.tolist() for i, pop_ratio in enumerate(pop_ratios): self.assertAlmostEqual(pop_ratio, expected_pop_ratios[i])
def test_probtraj_p53_Mdm2_cmaboss_v2(self): path = dirname(__file__) sim = load(join(path, "p53_Mdm2.bnd"), join(path, "p53_Mdm2_runcfg.cfg"), cmaboss=True) res = sim.run() res_states_probtraj = pandas.read_csv(join( path, "res", "p53_Mdm2_states_probtraj.csv"), index_col=0, header=0) res_last_states_probtraj = pandas.read_csv(join( path, "res", "p53_Mdm2_last_states_probtraj.csv"), index_col=0, header=0) res_nodes_probtraj = pandas.read_csv(join( path, "res", "p53_Mdm2_nodes_probtraj.csv"), index_col=0, header=0) self.assertTrue( numpy.isclose( res.get_states_probtraj().sort_index(axis=1), res_states_probtraj.sort_index(axis=1), ).all()) self.assertTrue( numpy.isclose( res.get_last_states_probtraj().sort_index(axis=1), res_last_states_probtraj.sort_index(axis=1), ).all()) self.assertTrue( numpy.isclose( res.get_nodes_probtraj().sort_index(axis=1), res_nodes_probtraj.sort_index(axis=1), ).all())
def main(argv): if len(argv) < 3 or len(argv) > 6: print( ("Bad arguments, MBSS_FormatTable.py <file.bnd> <file.cfg> " "<(optional)threshold> <(optional)-mb MaBoSS executable name>"), file=sys.stderr ) exit() bndFile = argv[1] cfgFile = argv[2] mabossCommand = None probCutoff = None if len(argv) > 3: index = 3 while index < len(argv): if argv[index].startswith("-mb"): mabossCommand = argv[index+1] index += 2 else: probCutoff = float(argv[index]) index += 1 simulationName = os.path.splitext(os.path.basename(argv[2]))[0] simulation = maboss.load(bndFile, cfgFile, command=mabossCommand) result = simulation.run(command=mabossCommand, prefix=simulationName) result.save(simulationName) table = result.get_states_probtraj_full() table.to_csv(os.path.join(simulationName, ("%s_probtraj_table.csv" % simulationName)), sep="\t") result.write_statdist_table( os.path.join(simulationName, "%s_statdist_table.csv" % simulationName), probCutoff )
def getMaBoSSModel(self): if self.model.format == LogicalModel.MABOSS: return maboss.load( join(settings.MEDIA_ROOT, self.model.bnd_file.path), join(settings.MEDIA_ROOT, self.model.cfg_file.path)) elif self.model.format == LogicalModel.ZGINML: ginsim_model = ginsim.load(self.model.file.path) return ginsim.to_maboss(ginsim_model) elif self.model.format == LogicalModel.SBML: t0 = time() biolqm_model = biolqm.load(self.model.file.path) t1 = time() print("Loaded sbml with biolqm : %.2gs" % (t1 - t0)) maboss_model = biolqm.to_maboss(biolqm_model) print("Converted to MaBoSS : %.2gs" % (time() - t1)) return maboss_model else: raise MethodNotAllowed()
def get(self, request, project_id, simulation_id): HasMaBoSSSimulation.load(self, request, project_id, simulation_id) model = maboss.load(self.getBNDFilePath(), self.getCFGFilePath()) if self.simulation.states_probtraj is not None: states_probtraj = loads(self.simulation.states_probtraj) states_lastprob = {} for state, values in states_probtraj.items(): list_values = list(values.values()) states_lastprob.update( {state: list_values[len(list_values) - 1]}) nodes = [ name for name, node in model.network.items() if not node.is_internal ] nb_nodes = len(nodes) nb_fp = len(states_lastprob.keys()) states = [] res = np.zeros((nb_nodes, 0)) for index, proba in states_lastprob.items(): if proba > 0.01: states.append(index) if index == "<nil>": res = np.append(res, np.zeros((nb_nodes, 1)), axis=1) else: t_res = np.zeros((nb_nodes, 1)) for node in [ t_node.strip() for t_node in index.split("--") ]: # print(node) t_res[nodes.index(node)] = 1 res = np.append(res, t_res, axis=1) columns = ["FP%d" % i for i in range(res.shape[1])] mat = np.transpose(res) pca = PCA() pca_res = pca.fit(mat) x_new = pca.transform(mat) res = {} for i, state in enumerate(states): res.update({state: list(x_new[i, 0:2])}) raw_arrows = np.transpose(pca_res.components_[0:2, :]) # Adjusting arrow length to fit in the graph max_x_arrows = max(raw_arrows[:, 0]) min_x_arrows = min(raw_arrows[:, 0]) max_x_values = max(x_new[:, 0]) min_x_values = min(x_new[:, 0]) min_x_ratio = abs(min_x_values / min_x_arrows) max_x_ratio = abs(max_x_values / max_x_arrows) x_ratio = min(min_x_ratio, max_x_ratio) max_y_arrows = max(raw_arrows[:, 1]) min_y_arrows = min(raw_arrows[:, 1]) max_y_values = max(x_new[:, 1]) min_y_values = min(x_new[:, 1]) min_y_ratio = abs(min_y_values / min_y_arrows) max_y_ratio = abs(max_y_values / max_y_arrows) y_ratio = min(min_y_ratio, max_y_ratio) from math import log10, floor def round_sig(x, sig=2): if x == 0.0: return x return round(x, sig - int(floor(log10(abs(x)))) - 1) values = [] names = [] for i, arrow_raw in enumerate(raw_arrows): as_list = [round(val, 2) for val in list(arrow_raw)] if as_list not in values: values.append(as_list) names.append([nodes[i]]) else: names[values.index(as_list)].append(nodes[i]) values = [[value[0] * x_ratio, value[1] * y_ratio] for value in values] return Response({ 'status': 'Finished', 'data': json.dumps(res), 'arrows': values, 'arrowlabels': names, 'explainedVariance': [ round_sig(value * 100, 4) for value in list(pca.explained_variance_ratio_[0:2]) ] }) else: return Response({'status': 'Busy'})
def test_load_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) self.assertEqual(sim.network['Mdm2C'].logExp, "$case_a ? p53_h : p53")
from maboss import load, UpdatePopulation from os.path import exists, splitext if __name__ == "__main__": if len(argv) < 4: print("Usage:\n") print("UpMaBoSS.py <file.bnd> <file.cfg> <file.upp>") exit(1) bnd_file = argv[1] cfg_file = argv[2] upp_file = argv[3] if not exists(bnd_file): print("Cannot find .bnd file") exit(1) if not exists(cfg_file): print("Cannot find .cfg file") exit(1) if not exists(upp_file): print("Cannot find .upp file") exit(1) workdir = splitext(cfg_file)[0] maboss_model = load(bnd_file, cfg_file) simulation = UpdatePopulation(maboss_model, upp_file, verbose=True) result = simulation.run(workdir=workdir) result.save(workdir)
def test_check_p53_Mdm2(self): sim = load(join(dirname(__file__), "p53_Mdm2.bnd"), join(dirname(__file__), "p53_Mdm2_runcfg.cfg")) errors = sim.check() self.assertEqual(len(errors), 0)
def post(self, request, project_id, model_id): # print("Entering post function") t0 = time() HasModel.load(self, request, project_id, model_id) t1 = time() # print("Model properties loaded (%.2gs)" % (t1-t0)) if self.model.format == LogicalModel.ZGINML: path = join(settings.MEDIA_ROOT, self.model.file.path) ginsim_model = ginsim.load(path) maboss_model = ginsim.to_maboss(ginsim_model) tmp_bnd_path = join(settings.TMP_ROOT, splitext(basename(self.model.file.path))[0] + ".bnd") bnd_file = open(tmp_bnd_path, 'w') maboss_model.print_bnd(out=bnd_file) bnd_file.close() tmp_cfg_path = join(settings.TMP_ROOT, splitext(basename(self.model.file.path))[0] + ".cfg") cfg_file = open(tmp_cfg_path, 'w') maboss_model.print_cfg(out=cfg_file) cfg_file.close() maboss_simulation = MaBoSSSimulation( project=self.project, model=self.model, name=request.POST['name'], bnd_file=File(open(tmp_bnd_path, 'rb'), name=basename(tmp_bnd_path)), cfg_file=File(open(tmp_cfg_path, 'rb'), name=basename(tmp_cfg_path)), status=MaBoSSSimulation.BUSY ) maboss_simulation.save() remove(tmp_bnd_path) remove(tmp_cfg_path) elif self.model.format == LogicalModel.MABOSS: bnd_path = join(settings.MEDIA_ROOT, self.model.bnd_file.path) cfg_path = join(settings.MEDIA_ROOT, self.model.cfg_file.path) maboss_simulation = MaBoSSSimulation( project=self.project, model=self.model, name=request.POST['name'], bnd_file=File(open(bnd_path, 'rb'), name=basename(bnd_path)), cfg_file=File(open(cfg_path, 'rb'), name=basename(cfg_path)), status=MaBoSSSimulation.BUSY ) maboss_simulation.save() maboss_model = maboss.load(bnd_path, cfg_path) elif self.model.format == LogicalModel.SBML: maboss_model = self.getMaBoSSModel() tmp_bnd_path = join(settings.TMP_ROOT, splitext(basename(self.model.file.path))[0] + ".bnd") bnd_file = open(tmp_bnd_path, 'w') maboss_model.print_bnd(out=bnd_file) bnd_file.close() tmp_cfg_path = join(settings.TMP_ROOT, splitext(basename(self.model.file.path))[0] + ".cfg") cfg_file = open(tmp_cfg_path, 'w') maboss_model.print_cfg(out=cfg_file) cfg_file.close() maboss_simulation = MaBoSSSimulation( project=self.project, model=self.model, name=request.POST['name'], bnd_file=File(open(tmp_bnd_path, 'rb'), name=basename(tmp_bnd_path)), cfg_file=File(open(tmp_cfg_path, 'rb'), name=basename(tmp_cfg_path)), status=MaBoSSSimulation.BUSY ) maboss_simulation.save() remove(tmp_bnd_path) remove(tmp_cfg_path) else: return HttpResponse(status=500) # t2 = time() # print("Model loaded (%.2gs)" % (t2-t1)) cfg_settings = loads(request.POST['settings']) maboss_model.param.update(cfg_settings) maboss_model.param['thread_count'] = 6 maboss_model.param['time_tick'] = float(maboss_model.param['max_time'])/100 mutations = loads(request.POST['mutations']) for var, mutation in mutations.items(): maboss_model.mutate(var, mutation) maboss_model.network.set_output( [key for key, value in loads(request.POST['outputVariables']).items() if value] ) for var, istate in parseIstates(request.POST['initialStates']).items(): maboss_model.network.set_istate(var, istate) maboss_simulation.update_model(maboss_model) server_host = request.POST.get('serverHost') server_port = request.POST.get('serverPort') thread = Thread(target=run_simulation, args=(maboss_model, maboss_simulation.id, server_host, server_port)) # t3 = time() # print("Thread built (%.2gs)" % (t3-t2)) thread.start() return Response({'simulation_id': maboss_simulation.id}, status=status.HTTP_200_OK)
def get(self, request, project_id, simulation_id): HasMaBoSSSimulation.load(self, request, project_id, simulation_id) model = maboss.load(self.getBNDFilePath(), self.getCFGFilePath()) if self.simulation.fixpoints is not None: fixed_points = loads(self.simulation.fixpoints) output_vars = [ label for label, node in model.network.items() if not node.is_internal ] nb_nodes = len(output_vars) res = np.zeros((nb_nodes, 0)) for i, proba in enumerate(fixed_points["Proba"]): t_res = np.zeros((nb_nodes, 1)) for node in output_vars: t_res[output_vars.index(node)] = fixed_points[node][str(i)] res = np.append(res, t_res, axis=1) mat = np.transpose(res) pca = PCA() pca_res = pca.fit(mat) x_new = pca.transform(mat) res = {} for i, state in enumerate(fixed_points["State"]): res.update({fixed_points["State"][state]: list(x_new[i, 0:2])}) raw_arrows = np.transpose(pca_res.components_[0:2, :]) # Adjusting arrow length to fit in the graph max_x_arrows = max(raw_arrows[:, 0]) min_x_arrows = min(raw_arrows[:, 0]) max_x_values = max(x_new[:, 0]) min_x_values = min(x_new[:, 0]) min_x_ratio = min_x_values / min_x_arrows max_x_ratio = max_x_values / max_x_arrows x_ratio = min(min_x_ratio, max_x_ratio) max_y_arrows = max(raw_arrows[:, 1]) min_y_arrows = min(raw_arrows[:, 1]) max_y_values = max(x_new[:, 1]) min_y_values = min(x_new[:, 1]) min_y_ratio = min_y_values / min_y_arrows max_y_ratio = max_y_values / max_y_arrows y_ratio = min(min_y_ratio, max_y_ratio) from math import log10, floor def round_sig(x, sig=2): if x == 0.0: return x return round(x, sig - int(floor(log10(abs(x)))) - 1) values = [] names = [] for i, arrow_raw in enumerate(raw_arrows): as_list = [round(val, 2) for val in list(arrow_raw)] if as_list not in values: values.append(as_list) names.append([output_vars[i]]) else: names[values.index(as_list)].append(output_vars[i]) values = [[value[0] * x_ratio, value[1] * y_ratio] for value in values] return Response({ 'status': 'Finished', 'data': json.dumps(res), 'arrows': values, 'arrowlabels': names, 'explainedVariance': [ round_sig(value * 100, 4) for value in list(pca.explained_variance_ratio_[0:2]) ] }) else: return Response({'status': 'Busy'})