def open_simulation(file_name_or_url): if file_name_or_url.startswith('https://'): return oc.open_simulation(file_name_or_url) original_directory = os.getcwd() os.chdir(os.path.dirname(__file__) + '/../../../../../../models/') simulation = oc.open_simulation(file_name_or_url) os.chdir(original_directory) return simulation
def run(mode, level): simulation = oc.open_simulation( 'https://models.physiomeproject.org/e/568/HumanSAN_Fabbri_Fantini_Wilders_Severi_2017.cellml' ) data = simulation.data() data.set_ending_point(3.0) data.set_point_interval(0.001) if mode != 0: constants = data.constants() constants['Rate_modulation_experiments/Iso_1_uM'] = 1.0 if mode == 1: constants['Rate_modulation_experiments/ACh'] = (1.0 - level) * 22.0e-6 else: # Vagal stimulation. constants['Rate_modulation_experiments/ACh'] = 22.0e-6 + \ level * (38.0e-6 - 22.0e-6) simulation.run() results = simulation.results() print( json.dumps([{ 'x': results.voi().values().tolist(), 'y': results.states()['Membrane/V_ode'].values().tolist(), }], indent=4)) oc.close_simulation(simulation)
def __init__(self): # Create (i.e. open) our SEIR simulation. self.__simulation = oc.open_simulation(os.path.dirname(__file__) + '/models/seir.sedml') # Initialise (i.e. reset) our simulation. self.reset()
def __isValid(self, path): try: sim = oc.open_simulation(path) defStat = True if len(sim.issues())==0 and sim.valid() else False issues = sim.issues() oc.close_simulation(sim) return defStat,issues except ValueError as e: return False, [str(e)] except: return False, []
def __getResults(self, path, cellml): sim = oc.open_simulation(path) try: sim.run() except: pass # error in running still may have results # get variables and value using opencor results = sim.results() variables = results.dataStore().voi_and_variables() compsT2Id, modelVars = {}, [] varKeys = list(variables.keys()) varKeys.sort(key=lambda x: x.count('/')) # init type of variables voi algebraic, constants, states, rates, voi = [], [], [], [], [] # iterate for each variable for variable in varKeys: compId = self.sysComps.add(cellml['id'], variable, compsT2Id) if compId != None: varId = self.sysVars.getNewId() self.sysComps.addVariable(compId,varId) modelVars += [varId] varValue = results.dataStore().voi_and_variables()[variable].values()[0] if variable in results.algebraic().keys(): varType = 'algebraic' algebraic += [varId] elif variable in results.constants().keys(): varType = 'constant' constants += [varId] elif variable in results.states().keys(): varType = 'state' states += [varId] elif variable in results.rates().keys(): varType = 'rate' rates += [varId] else: varType = 'voi' voi += [varId] self.sysVars.add(varId, varValue, variable, compId, varType) oc.close_simulation(sim) cellml['components'] = list(compsT2Id.values()) cellml['variables'] = modelVars cellml['algebraic'] = algebraic cellml['constants'] = constants cellml['states'] = states cellml['rates'] = rates cellml['voi'] = voi
def __isValid(self, path): # check if omex file if path.endswith('omex'): defStat = False kss = omex.listContents(path) for ks in kss: for k in ks: if isinstance(k,str): defStat = True if k.endswith('sedml') else defStat if not defStat: return False,[] # check all sedml and omex try: sim = oc.open_simulation(path) defStat = True if len(sim.issues())==0 and sim.valid() else False issues = sim.issues() oc.close_simulation(sim) return defStat,issues except ValueError as e: return False, [str(e)]
def main(stimulation_mode_parameter, stimulation_level_parameter): return_code = 0 s = opencor.open_simulation( '/home/opencor/models/HumanSAN_Fabbri_Fantini_Wilders_Severi_2017.sedml' ) d = s.data() c = d.constants() stimulation_level_parameter = max(0.0, min(1.0, stimulation_level_parameter)) c['Rate_modulation_experiments/Iso_1_uM'] = 1.0 # dimensionless if stimulation_mode_parameter == 1: # Stellate stimulation 0 - 1 :: 22 - 0 c['Rate_modulation_experiments/ACh'] = ( 1.0 - stimulation_level_parameter) * 22.0e-6 elif stimulation_mode_parameter == 2: # Vagus stimulation 0 - 1 :: 22 - 38 c['Rate_modulation_experiments/ACh'] = 22.0e-6 + stimulation_level_parameter * ( 38.0e-6 - 22.0e-6) else: return_code = 4 # Run the simulation try: if return_code == 0 and s.run(): r = s.results() output_data = { 'membrane': { 'v': r.algebraic()['Membrane/V'].values().tolist() } } peaks = find_peaks(output_data['membrane']['v'])[0] output_data['heart_rate'] = len(peaks) json_format = json.dumps(output_data) print(json_format) else: return_code = 5 except RuntimeError: return_code = 6 return return_code
def main(modelpath, servicename): return_code = 0 if modelpath.endswith("cellml") or modelpath.endswith("sedml"): model = opencor.open_simulation(modelpath) else: print('Invalid file type: only .cellml and .sedml accepted') return_code=3 try: print('try getting simulation') c = model.results().constants() s = model.results().states() num_inputs = len(s)+len(c) if num_inputs<1: print('this model has no editable input values') else: numinputs = open("num_params.txt","w") numinputs.write(str(num_inputs)) numinputs.close() model_inputs =c.copy() for entry in c: model_inputs[entry]=[c[entry].value(), c[entry].unit()] s_copy =s.copy() for entry in s: s_copy[entry]=[s[entry].value(), s[entry].unit()] model_inputs.update(s_copy) with open('model_inputs.json', 'w') as f: json.dump(model_inputs, f, indent=4) except: print('Error during model loading') return_code = 2 return return_code
def main(url, config): # Open the simulation. try: s = oc.open_simulation(url) except: error('the URL does not point to a valid CellML / SED-ML file') # Configure the simulation. r = s.results() rv = r.voi() rs = r.states() rr = r.rates() rc = r.constants() ra = r.algebraic() strack = [] rtrack = [] ctrack = [] atrack = [] if config is not None: d = s.data() for key, value in config.items(): if key == 'simulation': for sim_key, sim_value in value.items(): if sim_key == 'Starting point': d.set_starting_point(sim_value) elif sim_key == 'Ending point': d.set_ending_point(sim_value) elif sim_key == 'Point interval': d.set_point_interval(sim_value) else: error_config('\'' + sim_key + '\' is not a valid simulation parameter') elif key == 'parameters': ds = d.states() dc = d.constants() for param_key, param_value in value.items(): if param_key in ds: ds[param_key] = param_value elif param_key in dc: dc[param_key] = param_value else: error_config( '\'' + param_key + '\' is not a valid state or constant variable identifier' ) elif key == 'output': for out_key in value: if out_key == rv.uri(): continue # Since we automatically track the variable of integration. elif out_key in rs: strack.append(out_key) elif out_key in rr: rtrack.append(out_key) elif out_key in rc: ctrack.append(out_key) elif out_key in ra: atrack.append(out_key) else: error_config( '\'' + out_key + '\' is not a valid state, rate, constant or algebraic variable ' 'identifier') else: error_config('\'' + key + '\' is not a valid key') # If nothing is tracked then track all the state variables. if not strack and not rtrack and not ctrack and not atrack: for key in rs: strack.append(key) # Run the simulation. s.run() # Output the variable of integration and all the data that we want tracked. output = {rv.uri(): rv.values().tolist()} for key in strack: output[key] = rs[key].values().tolist() for key in rtrack: output[key] = rr[key].values().tolist() for key in ctrack: output[key] = rc[key].values().tolist() for key in atrack: output[key] = ra[key].values().tolist() print(json.dumps(output, indent=2))
def main(): # Open and run the SEIR simulation. simulation = oc.open_simulation( 'https://raw.githubusercontent.com/ABI-Covid-19/seir/master/models/seir.sedml') simulation.reset() # In case another simulation had already been run. simulation.run() # Retrieve the results of the simulation. results = simulation.results() voi = results.voi() states = results.states() algebraic = results.algebraic() s = states['main/S'] e = states['main/E'] i_c = states['main/I_c'] i_p = states['main/I_p'] i_u = states['main/I_u'] r_c = states['main/R_c'] r_u = states['main/R_u'] i = algebraic['main/I'] r = algebraic['main/R'] d = algebraic['main/D'] ifr = algebraic['main/IFR'] # Plot the results. import matplotlib.pyplot as plt plt.clf() # In case there is already a Matplotlib window. plt.gcf().canvas.set_window_title('SEIR model') plt.subplot(4, 1, 1) plt.plot(voi.values(), s.values(), label=s.name()) plt.plot(voi.values(), e.values(), label=e.name()) plt.plot(voi.values(), i_p.values(), label=i_p.name()) plt.plot(voi.values(), i.values(), label=i.name()) plt.plot(voi.values(), r.values(), label=r.name()) plt.plot(voi.values(), d.values(), label=d.name()) plt.legend(loc='center left') plt.subplot(4, 1, 2) plt.plot(voi.values(), i.values(), label=i.name()) plt.plot(voi.values(), i_c.values(), label=i_c.name()) plt.plot(voi.values(), i_u.values(), label=i_u.name()) plt.legend(loc='center left') plt.subplot(4, 1, 3) plt.plot(voi.values(), r.values(), label=r.name()) plt.plot(voi.values(), r_c.values(), label=r_c.name()) plt.plot(voi.values(), r_u.values(), label=r_u.name()) plt.legend(loc='center left') plt.subplot(4, 1, 4) plt.plot(voi.values(), ifr.values(), label=ifr.name()) plt.legend(loc='center left') plt.xlabel('time (day)') plt.show()
mapfilepath = Path(mapfile) with mapfilepath.open("r") as fp: inputkeymap = json.load(fp) inputdata = { newkey: inputdata_unmapped[oldkey] for (oldkey, newkey) in inputkeymap.items() } print(inputdata) starttime = float(inputdata["starttime"]) endtime = float(inputdata["endtime"]) timeincr = float(inputdata["timeincr"]) # some basic verification if modelpath.endswith('cellml') or modelpath.endswith('sedml'): model = opencor.open_simulation(modelpath) else: sys.exit('Invalid file type: only .cellml and .sedml accepted') if endtime < starttime: print( 'ending time must be greater than starting time, using 1000s after start instead' ) endtime = starttime + 1000 if timeincr <= 0: print('time increment should be greater than 0s. Setting to 1s') timeincr = 1 else: print('inputs are valid.') try:
def __getSedmlData(self, k, v): path = os.path.join(CURRENT_PATH,WORKSPACE_DIR,v['workingDir'],v['sedml']) # extract simulations, results sim = oc.open_simulation(path) # simulations simulations = sim.data().odeSolverProperties() try: sim.run() rst = sim.results().data_store().voi_and_variables() # create result name map, because variable name can be shorter resKeyMap = {'/'.join(key.rsplit('/',2)[-2:]):key for key in rst.keys()} except RuntimeError as e: print(e, v['id']) v['issues'] = [str(e)] v['status'] = self.statusC['invalid'] # don't continue if simulation run failed oc.close_simulation(sim) return # extract from sedml file parser = etree.XMLParser(recover=True) results = {} # Load sedml or omex if path.endswith('sedml'): # sedml file root = etree.parse(path, parser).getroot() elif path.endswith('omex'): # omex file omex.listContents(path) lsts = omex.listContents(path) for lst in lsts: for l in lst: if not isinstance(l, str): continue if '<sedml' in l.lower(): root = etree.fromstring(l.encode('utf-8'), parser) break # Exit if root is not available if 'root' not in locals(): oc.close_simulation(sim) return # initialisation simulations, models, tasks, variables, outputs = {}, {}, {}, {}, {} # get simulations, models, variables, and outputs for child in root: # extract simulations if child.tag.endswith('listOfSimulations'): pass # extract models elif child.tag.endswith('listOfModels'): for model in child: if model.tag.endswith('model'): modelPath = os.path.relpath(os.path.join(os.path.dirname(k), model.attrib['source'])) cellmlId = self.sysCellmls.getId(url=modelPath) # the case that the cellml file extension is using xml rather than cellml, then it will not found if cellmlId is None: v['status'] = self.statusC['invalid'] return models[model.attrib['id']] = cellmlId cellml = self.sysCellmls.getObjData(id=cellmlId) self.sysCellmls.addSedml(cellmlId, v['id']) elif child.tag.endswith('listOfTasks'): pass # extract variables from data generators elif child.tag.endswith('listOfDataGenerators'): for dataGenerator in child: if dataGenerator.tag.endswith('dataGenerator'): id = dataGenerator.attrib['id'] for listOfVariables in dataGenerator: if listOfVariables.tag.endswith('listOfVariables'): for variable in listOfVariables: var = variable.attrib['target'] var = var[var.find('@name=') + 7:].replace("']/cellml:variable[@name='", '/')[:-2] compName, varName = var.split('/') if var in resKeyMap: varId = self.sysCellmls.getVarId(cellml,compName,varName) variables[id] = resKeyMap[var] results[varId] = rst[resKeyMap[var]].values() # extract outputs (curves) elif child.tag.endswith('listOfOutputs'): for plot in child: plotType = plot.attrib['id'] for listOfCurves in plot: if listOfCurves.tag.endswith('listOfCurves'): for curve in listOfCurves: if curve.attrib['xDataReference'] in variables and curve.attrib['yDataReference'] in variables: xVar, yVar = variables[curve.attrib['xDataReference']], variables[curve.attrib['yDataReference']] xVar = xVar if not xVar.endswith('/prime') else xVar[:xVar.rfind('/prime')] yVar = yVar if not xVar.endswith('/prime') else yVar[:xVar.rfind('/prime')] xCompName, xVarName = xVar.split('/')[-2], xVar.split('/')[-1] yCompName, yVarName = yVar.split('/')[-2], yVar.split('/')[-1] curve.attrib.pop('xDataReference') curve.attrib.pop('yDataReference') curve.attrib['x'] = self.sysCellmls.getVarId(cellml,xCompName,xVarName) curve.attrib['y'] = self.sysCellmls.getVarId(cellml,yCompName,yVarName) outputs[plotType] = [dict(curve.attrib)] if plotType not in outputs else outputs[plotType] + [dict(curve.attrib)] # save simulation result to file if len(results) > 0: dumpPickle(results, RESOURCE_DIR, 'sedmlResults', str(v['id']) + '.gz') # modify sedml dictionary initVars = {k:v[0] for k,v in results.items()} v['status'] = self.statusC['current'] v['simulations'], v['models'], v['tasks'], v['variables'], v['outputs'] = simulations, models, tasks, initVars, outputs # generate plot images: self.__generatePlotImages(v['id'], results, outputs) oc.close_simulation(sim)