def antimonyToSBML(self, sb_str, SBO=False): """ Converts an Antimony string to raw SBML. :param sb_str: The raw Antimony string :returns: A 2-tuple (module_name, raw_sbml) """ import antimony as sb if not SBO: sbo_parser = antimonySBOParser(sb_str) try: sb_str = sbo_parser.elideSBOTerms() except: pass # try to load the Antimony code` code = sb.loadAntimonyString(sb_str) # if errors, bail if self.checkAntimonyReturnCode(code): errors = sb.getLastError() raise RuntimeError('Errors encountered when trying to load model into Antimony:\n{}'.format(errors)) module = sb.getMainModuleName() sbml = sb.getSBMLString(module) if not SBO: sbml = sbo_parser.addSBOsToSBML(sbml) return (module, sbml)
def antimonyToSBML(self, sb_str, SBO=False): """ Converts an Antimony string to raw SBML. :param sb_str: The raw Antimony string :returns: A 2-tuple (module_name, raw_sbml) """ import antimony as sb if not SBO: sbo_parser = antimonySBOParser(sb_str) try: sb_str = sbo_parser.elideSBOTerms() except: pass # try to load the Antimony code` code = sb.loadAntimonyString(sb_str) # if errors, bail if self.checkAntimonyReturnCode(code): errors = sb.getLastError() raise RuntimeError( 'Errors encountered when trying to load model into Antimony:\n{}' .format(errors)) module = sb.getMainModuleName() sbml = sb.getSBMLString(module) if not SBO: sbml = sbo_parser.addSBOsToSBML(sbml) return (module, sbml)
def flattenMotif(combined): #flatten the combined model by converting it to sbml and then converting back to Antimony antimony.clearPreviousLoads() code = antimony.loadAntimonyString(combined) if code <= 0: textfile = open('combined.txt', 'w') textfile.write(combined) textfile.close() raise AssertionError( 'combined model is not flattenable. Are you using the right species names? ' + 'Combined model saved as: ' + str(os.getcwd()) + '\\combined.txt') sbmlStr = antimony.getSBMLString('combined') antimony.loadSBMLString(sbmlStr) flatComb = antimony.getAntimonyString('combined') ####TODO #Delete extraneous mRNA -> Protein reactions at P_c connections #look for p_c#, regex #delete second equation with occurance of p_c#curr, regex #todo: remove extraneous species + parameters in the removed equation ####TODO return (flatComb)
def loada(sbstr): import antimony as sb r = sb.loadAntimonyString(sbstr) if r < 0: raise RuntimeError('Failed to load Antimony model: {}'.format( sb.getLastError())) return roadrunner.RoadRunner(sb.getSBMLString(sb.getModuleNames()[-1]))
def __antimony_to_sbml(ant): try: isfile = os.path.isfile(ant) except ValueError: isfile = False if isfile: code = antimony.loadAntimonyFile(ant) else: code = antimony.loadAntimonyString(ant) __check_antimony_return_code(code) mid = antimony.getMainModuleName() return antimony.getSBMLString(mid)
def antimonyTosbml(antStr): """Convert an antimony string into SBML: sbmlStr = antimonyTosbml (antimonyStr) """ err = antimony.loadAntimonyString(antStr) if err < 0: raise Exception("Antimony: " + antimony.getLastError()) Id = antimony.getMainModuleName() return antimony.getSBMLString(Id)
def antimonyToCellML(ant): """ Convert Antimony to CellML string. :param ant: Antimony string or file :type ant: str | file :return: CellML :rtype: str """ if os.path.isfile(ant): code = antimony.loadAntimonyFile(ant) else: code = antimony.loadAntimonyString(ant) _checkAntimonyReturnCode(code) mid = antimony.getMainModuleName() return antimony.getCellMLString(mid)
def __init__(self, model_contents: str, content_type: str) -> None: if content_type == "ModelString": er_code = sb.loadAntimonyString(model_contents) elif content_type == "ModelFile": er_code = sb.loadAntimonyFile(model_contents) else: raise KeyError(f"Unsupported content_type: {content_type}") self.er_code = er_code if self.er_code == -1: error_msg = "Error while parsing model. Model variable names " error_msg += "might be antimony keywords (see docs at https://" error_msg += "cayenne.readthedocs.io/en/latest/tutorial.html)." raise ModelError(error_msg) self.sb_module = sb.getMainModuleName() self._parse_model()
def loadAntimonyModel(antStr): """Load an Antimony string: r = loadAntModel (antimonyStr) """ err = antimony.loadAntimonyString(antStr) if err < 0: raise Exception("Antimony: " + antimony.getLastError()) Id = antimony.getMainModuleName() sbmlStr = antimony.getSBMLString(Id) rr = roadrunner.RoadRunner(sbmlStr) antimony.clearPreviousLoads() return rr
def antimonyToSBML(self, sb_str): """ Converts an Antimony string to raw SBML. :param sb_str: The raw Antimony string :returns: A 2-tuple (module_name, raw_sbml) """ import antimony as sb # try to load the Antimony code` code = sb.loadAntimonyString(sb_str) # if errors, bail if self.checkAntimonyReturnCode(code): errors = sb.getLastError() raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors)) module = sb.getMainModuleName() sbml = sb.getSBMLString(module) return (module, sbml)
def antimonyToSBML(ant): """ Convert Antimony to SBML string. :param ant: Antimony string or file :type ant: str | file :return: SBML :rtype: str """ try: isfile = os.path.isfile(ant) except ValueError: isfile = False if isfile: code = antimony.loadAntimonyFile(ant) else: code = antimony.loadAntimonyString(ant) _checkAntimonyReturnCode(code) mid = antimony.getMainModuleName() return antimony.getSBMLString(mid)
""" Create the SBML model. """ import antimony model_id = 'vanderpol' # ---------------------------- model_str = ''' model {} var species x = -2; var species y = 0; const mu = 1; J1: -> x; y J2: -> y; mu *(1-x^2)*y - x end '''.format(model_id) # ---------------------------- antimony.setBareNumbersAreDimensionless(True) antimony.loadAntimonyString(model_str) model_file = './vanderpol-sbml.xml' antimony.writeSBMLFile(model_file, model_id) print(model_file)
def generateNetworkFromAntimony(ant_str): """ Generate network matrix from Antimony string :param ant_str: Antimony string :rtype: array """ import antimony import tellurium as te antimony.clearPreviousLoads() antimony.loadAntimonyString(ant_str) module = antimony.getModuleNames()[-1] num_rxn = int(antimony.getNumReactions(module)) rct = antimony.getReactantNames(module) rct = [list(i) for i in rct] rct_flat = [item for sublist in rct for item in sublist] prd = antimony.getProductNames(module) prd = [list(i) for i in prd] prd_flat = [item for sublist in prd for item in sublist] ratelaw = antimony.getReactionRates(module) r = te.loada(ant_str) bnd = r.getBoundarySpeciesIds() flt = r.getFloatingSpeciesIds() s_arr = np.array(sorted(bnd + flt)) ref_list = generateCombinationOfSpecies(s_arr) net_mat = np.zeros([len(ref_list), len(ref_list)]) for i in range(num_rxn): if len(rct[i]) == 1 and len(prd[i]) == 1: r_s = rct[i][0] p_s = prd[i][0] r_s_i = ref_list.index(r_s) p_s_i = ref_list.index(p_s) net_mat[r_s_i][p_s_i] = 1 elif len(rct[i]) == 2 and len(prd[i]) == 1: r_s1 = rct[i][0] r_s2 = rct[i][1] p_s = prd[i][0] r_s_i = ref_list.index(tuple(sorted((r_s1, r_s2)))) p_s_i = ref_list.index(p_s) net_mat[r_s_i][p_s_i] = 1 elif len(rct[i]) == 1 and len(prd[i]) == 2: r_s = rct[i][0] p_s1 = prd[i][0] p_s2 = prd[i][1] r_s_i = ref_list.index(r_s) p_s_i = ref_list.index(tuple(sorted((p_s1, p_s2)))) net_mat[r_s_i][p_s_i] = 1 elif len(rct[i]) == 2 and len(prd[i]) == 2: r_s1 = rct[i][0] r_s2 = rct[i][1] p_s1 = prd[i][0] p_s2 = prd[i][1] r_s_i = ref_list.index(tuple(sorted((r_s1, r_s2)))) p_s_i = ref_list.index(tuple(sorted((p_s1, p_s2)))) if '/' in ratelaw[i]: # Inhibition net_mat[r_s_i][p_s_i] = 2 else: net_mat[r_s_i][p_s_i] = 1 antimony.clearPreviousLoads() return net_mat, ref_list
timePoints = [1.0, 2.0, 3.0] #zu welchen Zeitpunkten soll die Konfiguration gespeichert werden? tStart = 0 #Start- und Endzeit der Simulation tEnd = 3.01 doplot = True #plotten? plotlegend = True #Legende plotten? verbose = 2 #Verbose level: 0 = garnicht, 1 = Statistik 1x je outerLoop, 2 = Statistik nach jedem N, 3 = +Schleifenzaehler (Haengt sich die Simulation auf?) Nscale=100 #Produkt der naechsten 3 Variablen ist die Anzahl der insg. simulierten Pfade outerLoop = 1 #Anzahl Wiederholungen festlegen (multipliziert sich mit AnzahlPfade zur Anzahl der simulierten Pfade je N) Nrange= range(3) #Bereich von N festlegen. range(5) == 0,1,2,3,4. Daher Multiplikator N = (N+1)*Nscale AnzahlPfade = 40 #Anzahl Wiederholungen festlegen (multipliziert sich mit outerLoop). Fuer schoene Plots hier Wert 40-100. Fuer grosse N: doplot=False, hier 1, dafuer bei outerLoop gewuenschte Werte eintragen. #--------------stay-above-this-line----- #Modell laden, kann auch URL sein z.B. von www.biomodels.net--------- if os.path.isfile(antStr): #----------- start copy&paste from tellurium.py code = antimony.loadAntimonyFile(antStr) else: code = antimony.loadAntimonyString(antStr) if code < 0: raise Exception('Antimony: {}'.format(antimony.getLastError())) mid = antimony.getMainModuleName() sbml = antimony.getSBMLString(mid) r = roadrunner.RoadRunner(sbml) #----------- end copy&paste from tellurium.py #----------------the-next-three-lines-should-be-user-adapted-------- r.setIntegrator('gillespie') #Integrator auswaehlen. Andere unterstuetzen z.B. ODEs r.getIntegrator().setValue('variable_step_size', True) #Parameter fuer Integrator setzen, anderer Integrator unterstuetzt andere Parameter Config.setValue(Config.MAX_OUTPUT_ROWS,pow(10,7)) #bei 64-bit pow(10,11) oder weniger bei wenig Arbeitsspeicher #-----------end-user-parameters----------- Reactions = 0 start_time = time.time() selectToSave = ['N'] + selectToPlot form=(1,len(selectToSave)) r.selections = selectToSave
# file for export f_matlab = tempfile.NamedTemporaryFile(suffix=".m") # export current model state r.exportToMatlab(f_matlab.name) # to export the initial state when the model was loaded # set the current argument to False r.exportToMatlab(f_matlab.name, current=False) # The string representations of the current model are available via str_matlab = r.getCurrentMatlab() # and of the initial state when the model was loaded via str_matlab = r.getMatlab() print(str_matlab) # In[5]: import antimony antimony.loadAntimonyString('''S1 -> S2; k1*S1; k1 = 0.1; S1 = 10''') ant_str = antimony.getCellMLString(antimony.getMainModuleName()) print(ant_str) # In[6]:
import tellurium as te import tempfile # load model r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10') # file for export f_matlab = tempfile.NamedTemporaryFile(suffix=".m") # export current model state r.exportToMatlab(f_matlab.name) # to export the initial state when the model was loaded # set the current argument to False r.exportToMatlab(f_matlab.name, current=False) # The string representations of the current model are available via str_matlab = r.getCurrentMatlab() # and of the initial state when the model was loaded via str_matlab = r.getMatlab() print(str_matlab) # In[5]: import antimony antimony.loadAntimonyString('''S1 -> S2; k1*S1; k1 = 0.1; S1 = 10''') ant_str = antimony.getCellMLString(antimony.getMainModuleName()) print(ant_str) # In[6]:
tEnd = 3.01 doplot = True #plotten? plotlegend = True #Legende plotten? verbose = 2 #Verbose level: 0 = garnicht, 1 = Statistik 1x je outerLoop, 2 = Statistik nach jedem N, 3 = +Schleifenzaehler (Haengt sich die Simulation auf?) Nscale = 100 #Produkt der naechsten 3 Variablen ist die Anzahl der insg. simulierten Pfade outerLoop = 1 #Anzahl Wiederholungen festlegen (multipliziert sich mit AnzahlPfade zur Anzahl der simulierten Pfade je N) Nrange = range( 3 ) #Bereich von N festlegen. range(5) == 0,1,2,3,4. Daher Multiplikator N = (N+1)*Nscale AnzahlPfade = 40 #Anzahl Wiederholungen festlegen (multipliziert sich mit outerLoop). Fuer schoene Plots hier Wert 40-100. Fuer grosse N: doplot=False, hier 1, dafuer bei outerLoop gewuenschte Werte eintragen. #--------------stay-above-this-line----- #Modell laden, kann auch URL sein z.B. von www.biomodels.net--------- if os.path.isfile(antStr): #----------- start copy&paste from tellurium.py code = antimony.loadAntimonyFile(antStr) else: code = antimony.loadAntimonyString(antStr) if code < 0: raise Exception('Antimony: {}'.format(antimony.getLastError())) mid = antimony.getMainModuleName() sbml = antimony.getSBMLString(mid) r = roadrunner.RoadRunner(sbml) #----------- end copy&paste from tellurium.py #----------------the-next-three-lines-should-be-user-adapted-------- r.setIntegrator( 'gillespie') #Integrator auswaehlen. Andere unterstuetzen z.B. ODEs r.getIntegrator().setValue( 'variable_step_size', True ) #Parameter fuer Integrator setzen, anderer Integrator unterstuetzt andere Parameter Config.setValue(Config.MAX_OUTPUT_ROWS, pow( 10, 7)) #bei 64-bit pow(10,11) oder weniger bei wenig Arbeitsspeicher #-----------end-user-parameters----------- Reactions = 0
#model combined # #repeat for n-1 modules # #!!module names have to be identical to model names from imported models!! # A : model1(); # B : model2(); # #repeat for all models I have # #specify a global input node # var species p_c; # A.p_input is p_c; # B.p_output is p_c; # #repeat for n-1 modules # end # ''' #properly flatten the combined model antimony.loadAntimonyString(combined) sbmlstr = antimony.getSBMLString('combined') antimony.loadSBMLString(sbmlstr) flatcomb = antimony.getAntimonyString('combined') r = te.loada(flatcomb) r.exportToAntimony('combined.txt') r.draw(layout='dot') #combined = reads + ''' #model combined # var species p_c; # #!!module names have to be identical to model names from imported models!! # A : ffl1(); # B : ffl1(); # A.p_input is p_c;
import antimony ant = ''' model stoch() species A,B,C,D,E A -> B; k1 B -> C; k2 C -> D; k3 D -> C; k4 E -> C; k5 A = 100000 B = 1000 C = 1000 D = 1000 E = 100000 k1 = 0.2 k2 = 0.05 k3 = 0.1 k4 = 0.01 k5 = 0.05 end ''' antimony.loadAntimonyString(ant) sbmlstr = antimony.getSBMLString(antimony.getMainModuleName()) #print(sbmlstr) with open('stoch_l3.xml', 'w') as f: f.write(sbmlstr)