def plotQuantity(self, quantity, param_values): ''' Plot a simulated quantity vs its data points using Tellurium.''' from data import name_to_id_map, conc_indices quantity_id = name_to_id_map[quantity] iq = self.measured_quantities.index(quantity_id) reference_data = array(self.scaled_data[:, iq]) r = RoadRunner(self.sbml) self._setParameterVector(param_values, self.param_list, r) r.reset() t_now = 0. residuals = zeros((len(self.time_values), )) residuals[0] = r[quantity_id] - reference_data[0] for it_next in range(1, len(self.time_values)): self._setParameterVector(param_values, self.param_list, r) r.simulate(t_now, self.time_values[it_next], 100) t_now = self.time_values[it_next] residuals[it_next] = r[quantity_id] - reference_data[it_next] r.reset() s = r.simulate(0, float(self.time_values[-1]), 1000, ['time', quantity_id]) # print(quantity, sqrt(mean(residuals**2))/self.reference_value_means[iq]) import tellurium as te te.plot(self.time_values, reference_data, scatter=True, name=quantity + ' data', show=False, error_y_pos=maximum(residuals, 0), error_y_neg=-minimum(residuals, 0)) te.plot(s[:, 0], s[:, 1], name=quantity + ' sim')
def __init__(self, sbml, measured_quantities, param_list, reference_param_values, time_start, time_end, n): ''' Constructor. :param measured_quantities: A list of the measured quantities. :param reference_param_values: The vector of parameter values in the reference state. :param time_start: Start time of the simulation. :param time_end: End time of the simulation. :param n: Number of intervals/points in simulation. ''' self.sbml = sbml self.r = RoadRunner(sbml) self.time_start = time_start self.time_end = time_end self.n = n self.r.selections = ['time'] + measured_quantities self.measured_quantities = measured_quantities self.param_list = param_list self.setParameterVector(reference_param_values) sim = self.r.simulate(time_start, time_end, n) self.reference_time = array(sim[:, 0]) self.reference_quantities = array(sim[:, 1:]) self.reference_quantity_means_squared = mean(self.reference_quantities, axis=0)**2 # print(self.reference_quantity_means_squared) self.penalty_scale = 1.
def __init__(self, sbml, data_quantities, measurement_map): ''' Constructor. :param measurement_map: A dictionary that maps the names of quantities to measurements to their respective (numpy) arrays. ''' self.sbml = sbml self.r = RoadRunner(sbml) # self.r.integrator.stiff = False # self.r.integrator.minimum_time_step = 0.0001 # self.r.integrator.maximum_time_step = 1. # self.residuals = [] #print(self.r.getFloatingSpeciesIds()) self.timepoints = unique(hstack(a[:, 0] for a in data_quantities)) self.reset() self.measurement_map = measurement_map # map a quantity to its mean measured value self.mean_measurement_map = { quantity: mean(values[:, 1]) for quantity, values in self.measurement_map.items() } # keep track of the number of times a measurement is used # (check correct number of residuals) self.measurement_count = OrderedDict( (quantity, 0) for quantity in self.measurement_map) self.penalty_scale = 1.
def plotQuantity(self, identifier, param_values, n, bars=True): ''' Plot a simulated quantity vs its data points using Tellurium.''' i = self.measured_quantities.index(identifier) reference_quantity = self.reference_quantities[:, i] r = RoadRunner(self.sbml) if param_values is not None: self._setParameterVector(param_values, self.param_list, r) s = r.simulate(0, float(self.reference_time[-1]), n, ['time', identifier]) simulated_quantity = s[:, 1] residuals = simulated_quantity - reference_quantity # relative residuals # print('avg relative deviation for ', identifier, ': {:.1f}'.format(mean(abs(residuals/reference_quantity))*100.), '%') # residuals normalized to overall mean print( 'avg relative deviation for ', identifier, ': {:.1f}'.format( mean(abs(residuals)) / mean(abs(reference_quantity)) * 100.), '%') r.reset() s = r.simulate(0, float(self.reference_time[-1]), 1000, ['time', identifier]) import tellurium as te te.plot(self.reference_time, reference_quantity, scatter=True, name=identifier + ' data', show=False, error_y_pos=maximum(residuals, 0), error_y_neg=-minimum(residuals, 0)) te.plot(s[:, 0], s[:, 1], name=identifier + ' sim')
def __init__(self, sbml): self.sbml = sbml self.r = RoadRunner(sbml) from data import measured_quantity_ids, exp_data self.measured_quantity_ids = measured_quantity_ids self.reference_values = exp_data self.reference_value_means_squared = mean(self.reference_values, axis=0)**2 from params import new_param_ids as param_ids self.param_list = param_ids self.penalty_scale = 1.
def run(self, d, n, o, l, v): settings_file = join(d, n, '{n}-settings.txt'.format(n=n)) settings = SettingsParser.from_file(settings_file) sbml_file = join(d, n, '{n}-sbml-l{l}v{v}.xml'.format(n=n, l=l, v=v)) r = RoadRunner(sbml_file) r.selections = ['time'] + settings.amount + settings.concentration results = r.simulate(settings.start, settings.duration, settings.steps + 1) from pandas import DataFrame print(r.selections) DataFrame(results, columns=r.selections).to_csv(join(o, '.'.join([n, 'csv'])), index=False, encoding='utf-8')
def plotQuantity(self, quantity_id, param_values): ''' Plot a simulated quantity vs its data points using Tellurium.''' from data import measured_quantity_ids, measured_quantity_id_to_name_map from data import t1, t2, time_end, n1, n2, n3 quantity_name = measured_quantity_id_to_name_map.get(quantity_id,quantity_id) iq = measured_quantity_ids.index(quantity_id) reference_data = array(self.reference_values[:,iq]) r = RoadRunner(self.sbml) r.reset() r.resetAll() r.resetToOrigin() self._setParameterVector(param_values, self.param_list, r) # r.oneStep(0., 10) # print('plotQuantity OAA\' = {}'.format(r["OAA'"])) s1 = r.simulate(0., t1, n1, ['time', quantity_id]) s2 = r.simulate(t1, t2, n2, ['time', quantity_id]) # print(quantity_id) # if quantity_id == 'GLC': # print('BM before {}'.format(r['[BM]'])) # print(iq) # print(reference_data) s3 = r.simulate(t2, time_end, n3, ['time', quantity_id]) sim = vstack(( s1, s2, s3, )) assert sim.shape[0] == reference_data.shape[0] residuals = sim[:,1] - reference_data r.reset() r.resetAll() r.resetToOrigin() self._setParameterVector(param_values, self.param_list, r) # self._setParameterVector(param_values, self.param_list, r) s = r.simulate(0,time_end,1000,['time',quantity_id]) import tellurium as te te.plot(sim[:,0], reference_data, scatter=True, name=quantity_name+' data', show=False, title=quantity_name, error_y_pos=maximum(residuals,0), error_y_neg=-minimum(residuals,0)) te.plot(s[:,0], s[:,1], name=quantity_name+' sim')
def plotQuantity(self, identifier, bars=True): ''' Plot a simulated quantity vs its data points using Tellurium. The residuals should already be calculated.''' data = self.measurement_map[identifier] # data contains one column of time and one column of values import tellurium as te te.plot(data[:, 0], data[:, 1], scatter=True, name=identifier + ' data', show=False, error_y_pos=maximum(array(self.quantity_residuals[identifier]), 0), error_y_neg=-minimum( array(self.quantity_residuals[identifier]), 0)) # simulate and plot the model r = RoadRunner(self.sbml) s = r.simulate(0, self.timepoints[-1], 1000, ['time', identifier]) te.plot(s[:, 0], s[:, 1], name=identifier + ' sim')
def plotQuantity(self, quantity_id, param_values): ''' Plot a simulated quantity vs its data points using Tellurium.''' from data import time_values, measured_quantity_ids, measured_quantity_id_to_name_map quantity_name = measured_quantity_id_to_name_map[quantity_id] iq = measured_quantity_ids.index(quantity_id) reference_data = array(self.reference_values[:, iq]) r = RoadRunner(self.sbml) self._setParameterVector(param_values, self.param_list, r) r.reset() # r.resetAll() # r.resetToOrigin() # r.integrator = 'euler' # r.integrator = 'rk4' # r.integrator.subdivision_steps = 1000 # r.integrator.absolute_tolerance = 1e-10 # r.integrator.relative_tolerance = 1e-4 # r.integrator.initial_time_step = 0.001 # r.integrator.minimum_time_step = 0.0001 # r.integrator.maximum_time_step = 0.1 # print(r.integrator) sim = r.simulate(0., 119., 120, ['time', quantity_id]) assert sim.shape[0] == reference_data.shape[0] residuals = sim[:, 1] - reference_data r.reset() # r.resetAll() # r.resetToOrigin() s = r.simulate(0, float(time_values[-1]), 121, ['time', quantity_id]) # print('mse for {}: '.format(quantity_name), sqrt(mean((residuals**2)/(self.reference_norms[:,iq]**2)))) import tellurium as te te.plot(time_values, reference_data, scatter=True, name=quantity_name + ' data', show=False, title=quantity_name, error_y_pos=maximum(residuals, 0), error_y_neg=-minimum(residuals, 0)) te.plot(s[:, 0], s[:, 1], name=quantity_name + ' sim')
def __init__(self, sbml): self.sbml = sbml self.r = RoadRunner(sbml) # self.r.integrator = 'rk4' # print(self.r.integrator) # self.r.integrator.absolute_tolerance = 1e-10 # self.r.integrator.relative_tolerance = 1e-4 from data import measured_quantity_ids, exp_data, norm_data self.measured_quantity_ids = measured_quantity_ids self.reference_values = exp_data # self.reference_value_means_squared = mean(self.reference_values, axis=0)**2 self.reference_norms = maximum(norm_data, 0.0005) # self.reference_norms_squared = maximum(norm_data, 0.0005)**2 self.quantity_norms = array([ 0.0466906, 0.1666200, 0.1325631, 0.0757189, 0.1266561, 0.11634345, 0.1143341, 0.1104889, 0.2808254, 0.1275417, 0.1163108, 0.26822369, 0.1866278, 0.1555892, 0.4453806, 0.1598696, 0.1222940, 0.14366202, 0.1259413, 0.1473395, 0.1407897, 0.1246730, 0.1153060, 0.12375571, 0.1814630, 0.2199502, 0.1608888, 0.1903940, 0.1242392, 0.11704526, 0.1287076, 0.1319431, 0.1324937, 0.0690382, 0.1316586, 2.15109423, 0.1215476, 0.1414125, 0.1112873, 0.1297432, 0.1288462, 0.1155096, 0.1203922, 0.18807463 ])**2 # UDP-D-glucose excluded because it has buggy errors self.overall_norm = float( mean( array([ 0.0466906, 0.1666200, 0.1325631, 0.0757189, 0.1266561, 0.11634345, 0.1143341, 0.1104889, 0.2808254, 0.1275417, 0.1163108, 0.26822369, 0.1866278, 0.1555892, 0.4453806, 0.1598696, 0.1222940, 0.14366202, 0.1259413, 0.1473395, 0.1407897, 0.1246730, 0.1153060, 0.12375571, 0.1814630, 0.2199502, 0.1608888, 0.1903940, 0.1242392, 0.11704526, 0.1287076, 0.1319431, 0.1324937, 0.0690382, 0.1316586, 0.1215476, 0.1414125, 0.1112873, 0.1297432, 0.1288462, 0.1155096, 0.1203922, 0.18807463 ]))) from params import param_ids self.param_list = param_ids self.penalty_scale = 1.
def __init__(self, sbml, data_quantities, measurement_map): ''' Constructor. :param measurement_map: A dictionary that maps the names of quantities to measurements to their respective (numpy) arrays. ''' self.sbml = sbml self.r = RoadRunner(sbml) self.residuals = [] #print(self.r.getFloatingSpeciesIds()) self.timepoints = unique(hstack(a[:, 0] for a in data_quantities)) self.reset() self.measurement_map = measurement_map # keep track of the number of times a measurement is used # (check correct number of residuals) self.measurement_count = OrderedDict( (quantity, 0) for quantity in self.measurement_map) self.quantity_residuals = dict( (quantity, list()) for quantity in self.measurement_map)
def __init__(self, sbml): self.sbml = sbml self.r = RoadRunner(sbml) self.r.integrator.absolute_tolerance = 1e-15 self.r.integrator.relative_tolerance = 1e-9 self.r.integrator.stiff = True from observables import observables self.measured_quantity_ids = observables from json import load with open(join(dirname(realpath(__file__)), 'exp_data.json')) as f: self.reference_value_collection = [array(a) for a in load(f)] self.reference_value_means_squared_collection = [] for a in self.reference_value_collection: self.reference_value_means_squared_collection.append( mean(a, axis=0)**2) with open(join(dirname(realpath(__file__)), 'exp_y0.json')) as f: self.exp_y0_collection = [array(a) for a in load(f)] with open(join(dirname(realpath(__file__)), 'stimuli.json')) as f: self.stimuli_collection = [d for d in load(f)] from parameters import param_ids self.param_list = param_ids self.penalty_scale = 1.
def __init__(self, sbml): ''' Constructor. :param measured_quantities: A list of the measured quantities. :param scaled_data: The scaled reference data. :param scaled_error: The scaled reference error. ''' from params import param_ids from data import time_values, conc_ids, scaled_data, scaled_error self.sbml = sbml self.r = RoadRunner(sbml) self.r.selections = ['time'] + conc_ids self.time_values = time_values assert self.time_values[0] == 0. self.measured_quantities = conc_ids self.param_list = param_ids self.reference_values = scaled_data self.reference_value_means = mean(self.reference_values, axis=0) self.scaled_data = scaled_data self.scaled_error = scaled_error self.penalty_scale = 1.
def _worker(src, seeds, results, sim_args, sim_kwargs): # create a rr obj print("starting worker processes: " + str(os.getpid())) n = 0 r = RoadRunner(src) # remove and apply the selections # no sense in re-evaluating selection list each time. if 'sel' in sim_kwargs: r.selections = sim_kwargs['sel'] del sim_kwargs['sel'] if 'selections' in sim_kwargs: r.selections = sim_kwargs['selections'] del sim_kwargs['selections'] # might have forgot to reset sim, # default is to reset sim between each simulation. if not 'reset' in sim_kwargs: Logger.log( Logger.LOG_WARNING, "simulate args missing reset, defaulting to reset between simulations" ) sim_kwargs['reset'] = True # read until None, # blocks if queue is empty for seed in iter(seeds.get, None): sim_kwargs['seed'] = seed result = r.simulate(*sim_args, **sim_kwargs) results.put(result) n += 1 print("process {} finished with {} simulations".format(os.getpid(), n))
import arrow from roadrunner import RoadRunner r = RoadRunner('../../../../../sbml/b2.xml') class StalledSimulation(RuntimeError): pass # r.integrator.stiff = False # r.integrator.maximum_time_step = 1e-3 # r.integrator.minimum_time_step = 1e-9 r.integrator = 'rk4' print(r.integrator) time_start = arrow.utcnow() from interruptingcow import timeout try: with timeout(1, StalledSimulation): r.simulate(0,1000,10000) except (StalledSimulation): print('') print('timed out') time_end = arrow.utcnow() print('Total time: {}'.format(time_end-time_start))
from os.path import join, realpath, dirname from roadrunner import RoadRunner xmod = RoadRunner(join(realpath(dirname(__file__)), 'out-sbml.xml')) # xmod.reset() # xmod.integrator.relative_tolerance = 1e-12 # xmod.integrator.absolute_tolerance = 1e-20 # xmod.oneStep() # xmod.simulate(0,1000,1000,selections=['time']+xmod.getFloatingSpeciesIds()) # xmod.plot() # values = {s:xmod[s] for s in xmod.getFloatingSpeciesIds()} # block_rates = [xmod['block{}_Add10'.format(k)] for k in (range(len(wiring.blocks)))] # # pprint(block_rates) # r_block_indices = model.getReactionBlockIndices()
def benchmark_loading_time(): import arrow time_start = arrow.utcnow() r = RoadRunner('../../../../../sbml/b2.xml') delta_t = arrow.utcnow() - time_start print('Loading time:', delta_t)
import numpy as np from roadrunner import RoadRunner from timeit import default_timer r = RoadRunner('WolfGlycolysis.xml') #orders = 5 #for multiplier in np.logspace(0,orders,orders+1): ##print('multiplier = {}'.format(multiplier)) #t1 = default_timer() #r.reset() #r.simulate(0,2*int(multiplier),1000*int(multiplier)) #t2 = default_timer() #print('{} simulation, duration = {}'.format(2*int(multiplier), t2-t1)) ##r.plot() # COPASI 4:20 t1 = default_timer() r.reset() r.simulate(0,20000,200000) t2 = default_timer()
def test_delayed_choice(self): inpil = """ length a = 5 length b = 15 length c = 15 length d = 15 length e = 15 length z = 15 RC1 = d( e( z ) ) b*( a* + ) c( + ) d @i 1e-8 M RC1b = d e( z ) d*( b*( a* + ) c( + ) ) @i 1e-8 M R0 = a b c @i 1e-7 M R21 = b c( + ) d @i 0 M R22 = d( e( z ) ) b*( a*( + ) ) c @i 0 M R31 = b c @i 0 M RC32b = d e( z ) d*( b*( a*( + ) ) c( + ) ) @i 0 M RC32 = d( e( z ) ) b*( a*( + ) ) c( + ) d @i 0 M TC1 = a( b c + b( c( + ) d + d( e( z ) ) ) ) @i 0 M TC2 = a( b c + b( c( + ) d( + d e( z ) ) ) ) @i 0 M TC3 = a( b( c + b c( + ) d( + d e( z ) ) ) ) @i 0 M """ enum, out = enumerate_pil(inpil, is_file=False, condensed=True) xml = write_sbml(enum, condensed=True) rr = RoadRunner() rr.load(xml) ExecutableModel = rr.model RC32 = 'RC32' if 'RC32' in rr.model.getFloatingSpeciesIds( ) else 'RC32b' RC1 = 'RC1' if 'RC1' in rr.model.getFloatingSpeciesIds() else 'RC1b' # Compartment assert ExecutableModel.getCompartmentVolumes() == 1. assert ExecutableModel.getNumCompartments() == 1 assert ExecutableModel.getCompartmentIds() == ['TestTube'] # Species speciesIDs = ['R0', RC32, 'R22', 'R31', 'R21', RC1] ini_spIDs = sorted('init({})'.format(x) for x in speciesIDs) concIDs = [ '[R0]', '[' + RC32 + ']', '[R22]', '[R31]', '[R21]', '[' + RC1 + ']' ] ini_coIDs = sorted('init({})'.format(x) for x in concIDs) assert ExecutableModel.getNumFloatingSpecies() == len(speciesIDs) assert sorted( ExecutableModel.getFloatingSpeciesIds()) == sorted(speciesIDs) assert sorted( ExecutableModel.getFloatingSpeciesInitAmountIds()) == sorted( ini_spIDs) assert sorted(ExecutableModel.getFloatingSpeciesInitConcentrationIds() ) == sorted(ini_coIDs) #print(sorted(ini_coIDs)) #print(ExecutableModel.getFloatingSpeciesInitAmounts()) #print(ExecutableModel.getFloatingSpeciesInitConcentrations()) # Reactions rxnIDs = [ 'R0_' + RC1 + '__' + RC32 + '_R31', 'R0_' + RC1 + '__R22_R21' ] assert ExecutableModel.getNumReactions() == len(rxnIDs) assert sorted(ExecutableModel.getReactionIds()) == sorted(rxnIDs) assert rr.model[RC32] == 0 assert rr.model[RC1] == 2e-8 # simulate deterministic rr.model['init([R0])'] = 1e-8 assert rr.model['init(R0)'] == 1e-8 Vol = 1.66e-15 rr.model.setCompartmentVolumes([Vol]) rr.model['init([R0])'] = 1e-8 * Vol rr.model[f'init({RC1})'] = 2e-8 * Vol rr.integrator.absolute_tolerance = 1e-12 * Vol rr.integrator.relative_tolerance = 1e-12 * Vol rr.integrator.initial_time_step = 0.00001 result = rr.simulate(0, 500, steps=100) #print(result) #rr.plot() # look at it if you like! # NOTE: something is off with the units with stochastic simulations, weird... #print(rr.model.getCompartmentVolumes()) #print(rr.model.getFloatingSpeciesInitConcentrations()) #print(rr.model.getFloatingSpeciesInitAmounts()) #print(rr.model.getFloatingSpeciesConcentrations()) #print(rr.model.getFloatingSpeciesAmounts()) rr.reset()
from b3problem import B3Problem from os.path import join, dirname, abspath, realpath from numpy import allclose, isclose problem = B3Problem( abspath( join(dirname(realpath(__file__)), '..', '..', '..', '..', '..', 'sbml', 'b3.xml'))) from roadrunner import RoadRunner orig = RoadRunner( abspath( join(dirname(realpath(__file__)), '..', '..', '..', '..', '..', 'sbml', 'b3-original.xml'))) # print('Original OAA\' = {}'.format(orig["OAA'"])) new = RoadRunner( abspath( join(dirname(realpath(__file__)), '..', '..', '..', '..', '..', 'sbml', 'b3.xml'))) from data import GLC_ss_value_map for q in GLC_ss_value_map.keys(): if new[q] != GLC_ss_value_map[q]: print('discrepancy: {} = {} vs {}'.format(q, new[q], GLC_ss_value_map[q])) # for rxn_id in new.model.getReactionIds(): # if orig[rxn_id] != new[rxn_id]: # print('discrepancy: {} = {} vs {}'.format(rxn_id, orig[rxn_id], new[rxn_id])) # # quantities = ['[Emp]','e_Emp_kcat_f','FBP','e_Emp_Kfbp','e_Emp_kcat_r','PG3','e_Emp_Kpg3']
from roadrunner import RoadRunner, Logger #Logger.setLevel(Logger.LOG_DEBUG) # too verbose Logger.setLevel(Logger.LOG_WARNING) # Load model rr = RoadRunner('/tmp/tx.sbml') #rr = RoadRunner('/tmp/tx-reduced.sbml') #rr = RoadRunner('/tmp/antsbml.xml') # Simulate model results = rr.simulate(0, 10, 30, integrator='gillespie') print(results) # Write results to temp file with open('/tmp/sim_res.csv', 'w') as f: f.write(str(results)) # Plot rr.plot()