Beispiel #1
0
def main (args):
  """Usage: print_sedml input-filename
  """
  if len(args) != 2:
    print(main.__doc__)
    sys.exit(1)

  doc = libsedml.readSedML(args[1]);
  if ( doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):  
    print doc.getErrorLog().toString();
    sys.exit(2); 
  
  print 'The document has {0}" simulation(s).'.format(doc.getNumSimulations());
  for i  in range(0, doc.getNumSimulations()):
    current = doc.getSimulation(i);
    if (current.getTypeCode() == libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE):
      tc = current;
      kisaoid="none"
      if tc.isSetAlgorithm():
		kisaoid=tc.getAlgorithm().getKisaoID()
      print "\tTimecourse id=", tc.getId()," start=",tc.getOutputStartTime()," end=",tc.getOutputEndTime()," numPoints=",tc.getNumberOfPoints()," kisao=",kisaoid,"\n";
    else:
	  print "\tUncountered unknown simulation. ",current.getId(),"\n";
  
  print "\n"
  print "The document has ",doc.getNumModels() , " model(s)." , "\n";
  for i in range(0,doc.getNumModels()):
    current = doc.getModel(i);
    print "\tModel id=" , current.getId() , " language=" , current.getLanguage() , " source=" , current.getSource() , " numChanges=" , current.getNumChanges() , "\n";
  
  print "\n";
  print "The document has " , doc.getNumTasks() , " task(s)." , "\n";
  for i in range(0,doc.getNumTasks()):
    current = doc.getTask(i);
    print "\tTask id=" , current.getId() , " model=" , current.getModelReference() , " sim=" , current.getSimulationReference() , "\n";

  print "\n";
  print "The document has " , doc.getNumDataGenerators() , " datagenerators(s)." , "\n";
  for i in range( 0,  doc.getNumDataGenerators()):
    current = doc.getDataGenerator(i);
    print "\tDG id=" , current.getId() , " math=" , libsedml.formulaToString(current.getMath()) , "\n";
  
  print "\n";
  print "The document has " , doc.getNumOutputs() , " output(s)." , "\n";
  for i in range (0, doc.getNumOutputs()):
    current = doc.getOutput(i);
    tc = current.getTypeCode();
    if tc == libsedml.SEDML_OUTPUT_REPORT:
      r = (current);
      print "\tReport id=" , current.getId() , " numDataSets=" , r.getNumDataSets() , "\n";
    elif tc == libsedml.SEDML_OUTPUT_PLOT2D:
      p = (current);
      print "\tPlot2d id=" , current.getId() , " numCurves=" , p.getNumCurves() , "\n";
    elif tc == libsedml.SEDML_OUTPUT_PLOT3D:
      p = (current);
      print "\tPlot3d id=" , current.getId() , " numSurfaces=" , p.getNumSurfaces() , "\n";
    else: 
      print "\tEncountered unknown output " , current.getId() , "\n";
Beispiel #2
0
    def read(file_name):
        """ Imports simulation configuration from SED-ML file

        Args:
            file_name (:obj:`str`): path to SED-ML file from which to import simulation configuration

        Returns:
            :obj:`WCSimulationConfig`: simulation configuration
        """

        # initialize optional configuration
        opt_config = {}
        """ read SED-ML """
        # read XML file
        cfg_ml = libsedml.readSedML(file_name)
        """ validate SED-ML """
        # one model with
        # - zero or more attribute changes
        if cfg_ml.getNumModels() != 1:
            raise SedMlError('SED-ML configuration must have one model')

        mdl = cfg_ml.getModel(0)
        if mdl.getId() or mdl.getName() or mdl.getLanguage() or mdl.getSource(
        ):
            warnings.warn(
                'SED-ML import ignoring all model metadata (id, name, language, source)',
                SedMlWarning)

        for change_ml in mdl.getListOfChanges():
            if not isinstance(change_ml, libsedml.SedChangeAttribute):
                raise SedMlError(
                    'Cannot import model changes except attribute changes')

        # 1 simulation with
        #- Initial time = 0
        #- Output start time = 0
        #- Algorithm = KISAO_0000352 (hybrid)
        #- 1 algorithm parameters
        #  - random_seed (KISAO_0000488): int
        if cfg_ml.getNumSimulations() != 1:
            raise SedMlError('SED-ML configuration must have 1 simulation')

        sim_ml = cfg_ml.getSimulation(0)
        if sim_ml.getInitialTime() != sim_ml.getOutputStartTime():
            raise SedMlError(
                'Simulation initial time and output start time must be equal')

        alg_ml = sim_ml.getAlgorithm()
        if alg_ml.getKisaoID() != 'KISAO_0000352':
            raise SedMlError(
                'Unsupported algorithm. The only supported algorithm is KISAO_0000352 (hybrid)'
            )

        param_kisao_ids = set(
            param_ml.getKisaoID()
            for param_ml in alg_ml.getListOfAlgorithmParameters())
        if len(param_kisao_ids) < alg_ml.getNumAlgorithmParameters():
            raise SedMlError('Algorithm parameter KISAO ids must be unique')
        unsupported_param_kisao_ids = param_kisao_ids - set(['KISAO_0000488'])
        if unsupported_param_kisao_ids:
            raise SedMlError(
                'Algorithm parameters ({}) are not supported'.format(
                    ', '.join(unsupported_param_kisao_ids)))

        # zero or more repeated tasks each with
        # - 1 set value task change
        #   - math equal to constant floating point value
        # - 1 uniform or vector range of 1 value
        # - no subtasks
        for task_ml in cfg_ml.getListOfTasks():
            if isinstance(task_ml, libsedml.SedRepeatedTask):
                if task_ml.getNumTaskChanges() != 1:
                    raise SedMlError(
                        'Each repeated task must have one task change')
                change_ml = task_ml.getTaskChange(0)
                try:
                    float(libsedml.formulaToString(change_ml.getMath()))
                except ValueError:
                    raise SedMlError(
                        'Set value maths must be floating point values')

                if task_ml.getNumRanges() != 1:
                    raise SedMlError('Each repeated task must have one range')
                range_ml = task_ml.getRange(0)
                if not isinstance(
                        range_ml,
                    (libsedml.SedUniformRange, libsedml.SedVectorRange)):
                    raise SedMlError(
                        'Task ranges must be uniform or vector ranges')
                if isinstance(range_ml, libsedml.SedUniformRange
                              ) and range_ml.getNumberOfPoints() != 2**31 - 1:
                    raise SedMlError('Cannot import number of points')
                if isinstance(range_ml, libsedml.SedUniformRange
                              ) and range_ml.getType() != 'linear':
                    raise SedMlError('Only linear ranges are supported')
                if isinstance(range_ml, libsedml.SedVectorRange) and len(
                        list(range_ml.getValues())) != 1:
                    raise SedMlError('Task vector ranges must have length 1')

                if task_ml.getNumSubTasks() > 0:
                    raise SedMlError('Cannot import subtasks')
            else:
                raise SedMlError('Cannot import tasks except repeated tasks')

        # no data generators
        if cfg_ml.getNumDataGenerators() > 0:
            raise SedMlError('Cannot import data generator information')

        # no data descriptions
        if cfg_ml.getNumDataDescriptions() > 0:
            raise SedMlError('Cannot import data description information')

        # no outputs
        if cfg_ml.getNumOutputs() > 0:
            raise SedMlError('Cannot import output information')
        """ Read simulation configuration information from SED-ML document """

        # changes
        changes = []
        mdl = cfg_ml.getModel(0)
        for change_ml in mdl.getListOfChanges():
            target = change_ml.getTarget()
            change = Change()
            change.attr_path = Change.attr_path_from_str(change_ml.getTarget())
            change.value = float(change_ml.getNewValue())
            changes.append(change)

        # perturbations
        perturbations = []
        for task_ml in cfg_ml.getListOfTasks():
            change_ml = task_ml.getTaskChange(0)

            change = Change()
            change.attr_path = Change.attr_path_from_str(change_ml.getTarget())
            change.value = float(libsedml.formulaToString(change_ml.getMath()))

            range_ml = task_ml.getRange(0)
            if isinstance(range_ml, libsedml.SedUniformRange):
                start_time = range_ml.getStart()
                end_time = range_ml.getEnd()
            else:
                start_time = range_ml.getValues()[0]
                end_time = float('nan')

            perturbations.append(Perturbation(change, start_time, end_time))

        # time
        sim = cfg_ml.getSimulation(0)
        time_init = sim.getOutputStartTime()
        time_max = sim.getOutputEndTime()
        ode_time_step = (time_max - time_init) / sim.getNumberOfPoints()

        # algorithm parameters
        alg = sim.getAlgorithm()
        for param in alg.getListOfAlgorithmParameters():
            if param.getKisaoID() == 'KISAO_0000488':
                try:
                    opt_config['random_seed'] = float(param.getValue())
                except ValueError:
                    raise SedMlError('random_seed must be an integer')

                if opt_config['random_seed'] != math.ceil(
                        opt_config['random_seed']):
                    raise SedMlError('random_seed must be an integer')

                opt_config['random_seed'] = int(opt_config['random_seed'])
        """ build simulation configuration object """
        de_simulation_config = SimulationConfig(time_max=time_max,
                                                time_init=time_init)
        cfg = WCSimulationConfig(de_simulation_config=de_simulation_config,
                                 ode_time_step=ode_time_step,
                                 changes=changes,
                                 perturbations=perturbations,
                                 **opt_config)

        return cfg
Beispiel #3
0
def getAllObservables(iSEDML, core_iSbml):

    # list of all directories + SBML files
    #list_directory_sedml = sorted(os.listdir(base_path_sedml))

    # create new sbml file with observables
    #for iSEDML in list_directory_sedml:

    # iSEDML = 'kouril2017_fig1a'

    #   list_files = sorted(os.listdir(base_path_sedml + '/' + iSEDML + '/sbml_models'))

    #  for iSBML in list_files:

    # split iSBML
    #core_iSbml, XML = iSBML.split('.')

    #iSEDML = 'bachmann2011'
    #core_iSbml = 'bachmann'

    # important paths
    base_path_sedml = './sedml_models'
    sedml_path = './sedml_models/' + iSEDML + '/' + iSEDML + '.sedml'
    sbml_path = './sedml_models/' + iSEDML + '/sbml_models/' + core_iSbml + '.sbml'
    new_sbml_path = base_path_sedml + '/' + iSEDML + '/sbml_models_with_observables/' + core_iSbml + '_with_observabels.xml'
    if not os.path.exists(sedml_path):
        print('No Observables!')
    else:
        # new folder for all sbml models with observables
        if not os.path.exists(base_path_sedml + '/' + iSEDML +
                              '/sbml_models_with_observables'):
            os.makedirs(base_path_sedml + '/' + iSEDML +
                        '/sbml_models_with_observables')
        # read in sedml file
        sedml_file = libsedml.readSedML(sedml_path)
        # get number of tasks and observables
        num_task = sedml_file.getNumTasks()
        num_obs = sedml_file.getNumDataGenerators()
        # read in sbml model
        reader = libsbml.SBMLReader()
        sbml_file = reader.readSBML(sbml_path)
        sbml_model = sbml_file.getModel()
        for iTask in range(0, num_task):
            task_id = sedml_file.getTask(iTask).getId()

            # create list with all parameter-ids to check for uniqueness
            # all_par_id = []
            almost_all_par_id = []
            '''
            # get all species-Ids
            num_spec = len(model.getListOfSpecies())
            list_spec = []
            for iSpec in range(0, num_spec):
                spec_Id = model.getSpecies(iSpec).getId()
                list_spec.append(spec_Id)

            # get all parameter-Ids
            num_par_old = len(model.getListOfParameters())
            list_par_old = []
            for iPar in range(0, num_par_old):
                par_Id = model.getParameter(iPar).getId()
                list_par_old.append(par_Id)
            '''

            for iObservable in range(0, num_obs):
                # get important formula
                obs_Formula = libsedml.formulaToString(
                    sedml_file.getDataGenerator(iObservable).getMath())
                obs_Id = sedml_file.getDataGenerator(iObservable).getId()
                # SBML_model_Id,Observable_Id = obs_Id.split('_',1)
                new_obs_Id = 'observable_' + obs_Id
                # get variables
                num_var = sedml_file.getDataGenerator(
                    iObservable).getNumVariables()
                list_var_id = []
                for iVar in range(0, num_var):
                    var_Id = sedml_file.getDataGenerator(
                        iObservable).getVariable(iVar).getId()
                    target_Id = sedml_file.getDataGenerator(
                        iObservable).getVariable(iVar).getTarget()
                    if not target_Id == '':
                        try:
                            _, new_var_Id, _ = target_Id.split("'")
                            if var_Id in obs_Formula:
                                obs_Formula = obs_Formula.replace(
                                    var_Id, new_var_Id)
                        except:
                            print(
                                'target_Id can not be splitted / does not need to be splitted!'
                            )
                    else:
                        print('target_Id does not exists!')
                    # only if it was not defined earlier
                    #if not var_Id in list_spec:
                    #   if not var_Id in list_par_old:
                    #      if not var_Id in list_var_id:
                    #         list_var_id.append(var_Id)
                # get right compartment
                #compartment = model.getCompartment(0).getId()
                # get list of parameters
                list_par_id = []
                list_par_value = []
                num_par = sedml_file.getDataGenerator(
                    iObservable).getNumParameters()
                if num_par == 0:
                    print(obs_Id + ' has no parameters as observables!')

                else:
                    for iCount in range(0, num_par):
                        list_par_id.append(
                            sedml_file.getDataGenerator(
                                iObservable).getParameter(iCount).getId())
                        # list_par_value.append(sedml_file.getDataGenerator(iObservable).getParameter(iCount).getValue())
                        # all_par_id.append(sedml_file.getDataGenerator(iObservable).getParameter(iCount).getId())
                        list_par_value.append(
                            sedml_file.getDataGenerator(
                                iObservable).getParameter(iCount).getValue())
                        almost_all_par_id.append(
                            sedml_file.getDataGenerator(
                                iObservable).getParameter(iCount).getId())

                        # check for uniqueness of parameter-ids
                        # for iNum in range(0, len(all_par_id)):
                        #   almost_all_par_id = all_par_id.remove(all_par_id[len(all_par_id) - 1])
                        for iNum in range(0, len(almost_all_par_id)):
                            all_par_id = almost_all_par_id[iNum]
                            almost_all_par_id.remove(
                                almost_all_par_id[len(almost_all_par_id) - 1])
                            last_element = list(all_par_id[len(all_par_id) -
                                                           1])
                            intersection = [
                                i for i in last_element
                                if i in almost_all_par_id
                            ]
                            if len(intersection) != 0:
                                print(
                                    'Two or more parameters have the same Id!')
                                # sys.exit(1)
                # look for correct observables: with target and with task_id == task_ref
                if sedml_file.getDataGenerator(iObservable).getVariable(
                        0).getTarget() != '':
                    # get task reference
                    task_target = sedml_file.getDataGenerator(
                        iObservable).getVariable(0).getTarget()
                    task_ref = sedml_file.getDataGenerator(
                        iObservable).getVariable(0).getTaskReference()
                    if task_id == task_ref:
                        # create formula
                        assignmentRule = sbml_model.createAssignmentRule()
                        assignmentRule.setId(new_obs_Id)
                        assignmentRule.setVariable(new_obs_Id)
                        assignmentRule.setFormula(obs_Formula)
                        # create parameter to formula for observables
                        obs_parameter = sbml_model.createParameter()
                        obs_parameter.setId(new_obs_Id)
                        obs_parameter.setConstant(False)
                        # create parameter to formula for parameters
                        for iCount in range(0, num_par):
                            iPar_id = list_par_id[iCount]
                            iPar_value = list_par_value[iCount]
                            parameter = sbml_model.createParameter()
                            parameter.setId(iPar_id)
                            parameter.setConstant(False)
                            parameter.setValue(iPar_value)
                        # create species to formula
                        #for iCount in range(0, len(list_var_id)):
                        #   iVar_id = list_var_id[iCount]
                        #   variable = model.createSpecies()
                        #   variable.setId(iVar_id)
                        #   variable.setCompartment(compartment)
                        #   variable.setHasOnlySubstanceUnits(False)
                        #   variable.setBoundaryCondition(False)
                        #   variable.setConstant(False)
        libsbml.writeSBMLToFile(sbml_file, new_sbml_path)
Beispiel #4
0
    def build(self, sedml, base_location):
        """
        Build this experiment manifest from the provided SED-ML document. We assume that the SED-ML document
        has been checked for errors prior to its use here.

        :param sedml: The SED-ML document as parsed by libsedml.
        :param base_location: The base location to use in resolving relative model locations.
        """

        for i in range(0, sedml.getNumSimulations()):
            current = sedml.getSimulation(i)
            if current.getTypeCode(
            ) == libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE:
                tc = current
                kisaoid = "none"
                if tc.isSetAlgorithm():
                    kisaoid = tc.getAlgorithm().getKisaoID()
                sId = tc.getId()
                self._simulations[sId] = {
                    'type': libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE,
                    'initial': tc.getInitialTime(),
                    'start': tc.getOutputStartTime(),
                    'end': tc.getOutputEndTime(),
                    'numPoints': tc.getNumberOfPoints(),
                    'kisao': kisaoid
                }
                print_simulation(sId, self._simulations[sId])
            else:
                print("\tEncountered unknown simulation type. ",
                      current.getId(), "\n")

        for i in range(0, sedml.getNumModels()):
            current = sedml.getModel(i)
            if current.getLanguage() != 'urn:sedml:language:cellml.2_0':
                print("\tEncountered unknown model format (" +
                      current.getLanguage() + ") for model: " +
                      current.getId())
                continue  # assume there are other useful models so continue?
            # resolve the model file name
            model_file = os.path.join(base_location, current.getSource())
            model_tree = etree.parse(model_file)
            # handle changes
            for c in range(0, current.getNumChanges()):
                change = current.getChange(c)
                target = change.getTarget()
                xmlns = get_xpath_namespaces(change)
                if change.getTypeCode() == libsedml.SEDML_CHANGE_ATTRIBUTE:
                    new_value = change.getNewValue()
                    result = model_tree.xpath(target, namespaces=xmlns)
                    attribute = result[0]
                    attribute.getparent().attrib[
                        attribute.attrname] = new_value
                else:
                    print("\tEncountered unknown model change for model: " +
                          current.getId())
                    continue  # ignore for now...

            # the final string representation of the model
            model_string = str(etree.tostring(model_tree, pretty_print=True),
                               'utf-8')

            # quick test to make sure we can use this model - should be removed.
            parser = libcellml.Parser()
            parser.parseModel(model_string)
            if parser.errorCount():
                for e in range(0, parser.errorCount()):
                    print(parser.error(e).description())
                    print(parser.error(e).referenceHeading())
            else:
                mId = current.getId()
                self._models[mId] = {
                    'location': model_file,
                    'tree': model_tree,
                    'cellml': model_string
                }
                print_model(mId, self._models[mId])

        for i in range(0, sedml.getNumTasks()):
            current = sedml.getTask(i)
            if current.getTypeCode() != libsedml.SEDML_TASK:
                print("\tEncountered unknown task type: " +
                      libsedml.SedTypeCode_toString(current.getTypeCode()) +
                      "; for task: " + current.getId())
                continue
            tId = current.getId()
            m = current.getModelReference()
            s = current.getSimulationReference()
            if not m in self._models:
                print("\tEncountered a non-existing model reference: " + m +
                      "; for task: " + tId)
                continue
            if not s in self._simulations:
                print("\tEncountered a non-existing simulation reference: " +
                      s + "; for task: " + tId)
                continue
            self._tasks[tId] = {'model': m, 'simulation': s}
            print_task(tId, self._tasks[tId])

        for i in range(0, sedml.getNumDataGenerators()):
            current = sedml.getDataGenerator(i)
            variables = {}
            for v in range(0, current.getNumVariables()):
                cv = current.getVariable(v)
                t = cv.getTaskReference()
                if not t in self._tasks:
                    print("\tEncountered a non-existing task reference: " + t +
                          "; for data generator: " + current.getId())
                    continue
                xmlns = get_xpath_namespaces(cv)
                model_tree = self._models[self._tasks[t]['model']]['tree']
                variable_element = model_tree.xpath(cv.getTarget(),
                                                    namespaces=xmlns)[0]
                variables[cv.getId()] = {
                    'name': variable_element.attrib['name'],
                    'component': variable_element.getparent().attrib['name'],
                    'task': t,
                    'array': -1,
                    'index': 0
                }
            dgId = current.getId()
            self._data_generators[dgId] = {
                'variables': variables,
                'math': libsedml.formulaToString(current.getMath())
            }
            print_datagenerator(dgId, self._data_generators[dgId])

        for i in range(0, sedml.getNumOutputs()):
            current = sedml.getOutput(i)
            tc = current.getTypeCode()
            if tc == libsedml.SEDML_OUTPUT_REPORT:
                r = current
                dss = []
                for d in range(0, r.getNumDataSets()):
                    ds = r.getDataSet(d)
                    label = ds.getLabel()
                    if label == '':
                        label = ds.getId()
                    dg = r.getDataReference()
                    if not dg in self._data_generators:
                        print(
                            "\tEncountered a non-existing dataGenerator reference: "
                            + dg + "; for data set: " + ds.getId())
                        continue
                    dss.append({'label': label, 'dg': dg})
                self._outputs[r.getId()] = {
                    'type': libsedml.SEDML_OUTPUT_REPORT,
                    'data-sets': dss
                }
            elif tc == libsedml.SEDML_OUTPUT_PLOT2D:
                p = current
                curves = []
                for c in range(0, p.getNumCurves()):
                    curve = p.getCurve(c)
                    label = curve.getName()
                    if label == '':
                        label = curve.getId()
                    dgX = curve.getXDataReference()
                    if not dgX in self._data_generators:
                        print(
                            "\tEncountered a non-existing X dataGenerator reference: "
                            + dgX + "; for curve: " + curve.getId())
                        continue
                    dgY = curve.getYDataReference()
                    if not dgY in self._data_generators:
                        print(
                            "\tEncountered a non-existing Y dataGenerator reference: "
                            + dgY + "; for curve: " + curve.getId())
                        continue
                    curves.append({'label': label, 'dgX': dgX, 'dgY': dgY})
                self._outputs[p.getId()] = {
                    'type': libsedml.SEDML_OUTPUT_PLOT2D,
                    'curves': curves
                }
            else:
                print("\tEncountered unknown output ", current.getId(), "\n")
Beispiel #5
0
def generateDataLoop(sedmlDoc,
                     currentModel,
                     task1,
                     variablesList,
                     variablesDictionary,
                     repeatedTaskIndex,
                     repeatedTask=None,
                     dataGeneratorsList=None):

    # Each dataGenerator is calculated from the resulting output
    for s in range(0, sedmlDoc.getNumSimulations()):
        currentSimulation = sedmlDoc.getSimulation(s)
        if task1.getSimulationReference() == currentSimulation.getId():
            break
            # we found the simulation referred to by this task (can't be more than one)

    dataGeneratorOutputList = []
    dataGeneratorTemp = str()

    for j in range(0, len(variablesDictionary)):
        m = variablesDictionary[j]
        current = sedmlDoc.getDataGenerator(m.datagenID)
        dataGeneratorResult = libsedml.formulaToString(current.getMath())

        if current.getId() == m.datagenID:
            stringToReplace = m.sedmlID
            position = m.sbmlID
            for k in range(0, len(variablesList)):
                if position == variablesList[k]:
                    position = k
                    break
            if repeatedTaskIndex == -1:
                taskId = task1.getId()
            else:
                taskId = repeatedTask.getId() + "_" + str(repeatedTaskIndex)
            if currentSimulation.getTypeCode(
            ) == libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE:
                tc = currentSimulation
                totNumPoints = tc.getOutputEndTime() * tc.getNumberOfPoints(
                ) / (tc.getOutputEndTime() - tc.getOutputStartTime())
                replacementString = taskId + "[" + str(
                    totNumPoints - currentSimulation.getNumberOfPoints()
                ) + ":," + str(position) + "]"
            elif currentSimulation.getTypeCode(
            ) == libsedml.SEDML_SIMULATION_STEADYSTATE:
                replacementString = taskId + "[0:," + str(position) + "]"
            elif currentSimulation.getTypeCode(
            ) == libsedml.SEDML_SIMULATION_ONESTEP:
                replacementString = taskId + "[0:," + str(position) + "]"
            else:
                print "# Unsupported type " + str(
                    currentSimulation.getTypeCode(
                    )) + " for simulation " + currentSimulation.getName()

            if dataGeneratorResult != dataGeneratorTemp:
                if stringToReplace in dataGeneratorResult:
                    dataGeneratorReplaced = dataGeneratorResult.replace(
                        stringToReplace, replacementString)
                else:
                    dataGeneratorReplaced = stringToReplace.replace(
                        stringToReplace, replacementString)
                dataGeneratorId = current.getId(
                )  # we expand the datagen id because they need to be flattened for repeated tasks
                if repeatedTaskIndex != -1:
                    dataGeneratorId += "_" + str(repeatedTaskIndex)
                dataGeneratorElement = dataGeneratorId + " = " + dataGeneratorReplaced
                dataGeneratorOutputList.append(dataGeneratorElement)
                dataGeneratorTemp = dataGeneratorResult

            else:
                dataGeneratorOutputList[-1] = dataGeneratorOutputList[
                    -1].replace(stringToReplace, replacementString)

            if repeatedTaskIndex != -1:  # list of data generators flattening (when part of a range)
                position = -1
                for i in range(0, len(dataGeneratorsList)):
                    rtdg = dataGeneratorsList[i]
                    if rtdg.datagenID == current.getId():  # already present
                        position = i
                        break
                if position == -1:  # create it
                    rtdg = MatchingSetsOfRepeatedTasksDataGenerators(
                        current.getId(), repeatedTaskIndex + 1)
                    dataGeneratorsList.append(rtdg)
                else:
                    rtdg = MatchingSetsOfRepeatedTasksDataGenerators(
                        current.getId(), repeatedTaskIndex + 1)
                    dataGeneratorsList[position] = rtdg

    dataGeneratorOutput = '\n'.join(dataGeneratorOutputList)
    for k, v in mapping:
        dataGeneratorOutput = dataGeneratorOutput.replace(k, v)
    print dataGeneratorOutput
Beispiel #6
0
def generateDataLoop(sedmlDoc, currentModel, task1, variablesList, variablesDictionary, repeatedTaskIndex, repeatedTask = None, dataGeneratorsList = None):

    # Each dataGenerator is calculated from the resulting output
    for s in range(0, sedmlDoc.getNumSimulations()):
        currentSimulation = sedmlDoc.getSimulation(s)
        if task1.getSimulationReference() == currentSimulation.getId():
            break;            # we found the simulation referred to by this task (can't be more than one)
    
    dataGeneratorOutputList = []
    dataGeneratorTemp = str()
    
    for j in range(0, len(variablesDictionary)):
        m = variablesDictionary[j]
        current = sedmlDoc.getDataGenerator(m.datagenID)
        dataGeneratorResult = libsedml.formulaToString(current.getMath())
       
        if current.getId() == m.datagenID:
            stringToReplace = m.sedmlID
            position = m.sbmlID
            for k in range(0, len(variablesList)):
                if position == variablesList[k]:
                    position = k
                    break
            if repeatedTaskIndex == -1:
                taskId = task1.getId()
            else:
                taskId = repeatedTask.getId() + "_" + str(repeatedTaskIndex)
            if currentSimulation.getTypeCode() == libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE:
                tc = currentSimulation
                totNumPoints = tc.getOutputEndTime() * tc.getNumberOfPoints() / (tc.getOutputEndTime() - tc.getOutputStartTime())
                replacementString = taskId + "[" + str(totNumPoints - currentSimulation.getNumberOfPoints()) + ":," + str(position) + "]"
            elif currentSimulation.getTypeCode() == libsedml.SEDML_SIMULATION_STEADYSTATE:
                replacementString = taskId + "[0:," + str(position) + "]"
            elif currentSimulation.getTypeCode() == libsedml.SEDML_SIMULATION_ONESTEP:                
                replacementString = taskId + "[0:," + str(position) + "]"
            else:
                print "# Unsupported type " + str(currentSimulation.getTypeCode()) + " for simulation " + currentSimulation.getName()
            
            if dataGeneratorResult != dataGeneratorTemp:
                if stringToReplace in dataGeneratorResult:
                    dataGeneratorReplaced = dataGeneratorResult.replace(stringToReplace, replacementString)
                else:
                    dataGeneratorReplaced = stringToReplace.replace(stringToReplace, replacementString)
                dataGeneratorId = current.getId()       # we expand the datagen id because they need to be flattened for repeated tasks
                if repeatedTaskIndex != -1:
                    dataGeneratorId += "_" + str(repeatedTaskIndex)
                dataGeneratorElement = dataGeneratorId + " = " + dataGeneratorReplaced
                dataGeneratorOutputList.append(dataGeneratorElement)
                dataGeneratorTemp = dataGeneratorResult

            else:
                dataGeneratorOutputList[-1] = dataGeneratorOutputList[-1].replace(stringToReplace, replacementString)

            if repeatedTaskIndex != -1:      # list of data generators flattening (when part of a range)
                position = -1
                for i in range(0, len(dataGeneratorsList)):
                    rtdg = dataGeneratorsList[i]
                    if rtdg.datagenID == current.getId():   # already present
                        position = i
                        break
                if position == -1:        # create it
                    rtdg = MatchingSetsOfRepeatedTasksDataGenerators(current.getId(), repeatedTaskIndex+1 )
                    dataGeneratorsList.append(rtdg)
                else:
                    rtdg = MatchingSetsOfRepeatedTasksDataGenerators(current.getId(), repeatedTaskIndex+1 )
                    dataGeneratorsList[position] = rtdg
                    
    dataGeneratorOutput = '\n'.join(dataGeneratorOutputList)
    for k, v in mapping:
        dataGeneratorOutput = dataGeneratorOutput.replace(k, v)
    print dataGeneratorOutput
Beispiel #7
0
                almost_all_par_id = []

                # check if parameter in data generators even exist + if not, write pd.Series(NaN)
                all_observables = []
                for iObservable in range(0, num_obs):
                    num_par_all = sedml_file.getDataGenerator(iObservable).getNumParameters()
                    all_observables.append(num_par_all)

                if sum(all_observables) == 0:
                    for iNan in range(0, len(new_species)):
                        new_observables.append('NaN')
                else:

                    for iObservable in range(0, num_obs):                                                               # each observable from data generator
                        # get important formula
                        obs_Formula = libsedml.formulaToString(sedml_file.getDataGenerator(iObservable).getMath())
                        obs_Id = sedml_file.getDataGenerator(iObservable).getId()
                        # SBML_model_Id,Observable_Id = obs_Id.split('_',1)
                        new_obs_Id = 'observable_' + obs_Id

                        # get list of parameters
                        list_par_id = []
                        list_par_value = []
                        num_par = sedml_file.getDataGenerator(iObservable).getNumParameters()

                        # get observable name
                        data_generator_name = sedml_file.getDataGenerator(iObservable).getName()

                        if num_par == 0:                                                                                # parameter from each observable
                            print(iModel + '_' + iData + '_' + obs_Id + ' has no parameters as observables!')
                            new_observables.append(pd.Series('NaN'))
def main(args):
    """Usage: print_sedml input-filename
  """
    if len(args) != 2:
        print(main.__doc__)
        sys.exit(1)

    doc = libsedml.readSedML(args[1])
    if (doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR)
            > 0):
        print doc.getErrorLog().toString()
        sys.exit(2)

    print 'The document has {0}" simulation(s).'.format(
        doc.getNumSimulations())
    for i in range(0, doc.getNumSimulations()):
        current = doc.getSimulation(i)
        if (current.getTypeCode() ==
                libsedml.SEDML_SIMULATION_UNIFORMTIMECOURSE):
            tc = current
            kisaoid = "none"
            if tc.isSetAlgorithm():
                kisaoid = tc.getAlgorithm().getKisaoID()
            print "\tTimecourse id=", tc.getId(
            ), " start=", tc.getOutputStartTime(
            ), " end=", tc.getOutputEndTime(
            ), " numPoints=", tc.getNumberOfPoints(), " kisao=", kisaoid, "\n"
        else:
            print "\tUncountered unknown simulation. ", current.getId(), "\n"

    print "\n"
    print "The document has ", doc.getNumModels(), " model(s).", "\n"
    for i in range(0, doc.getNumModels()):
        current = doc.getModel(i)
        print "\tModel id=", current.getId(
        ), " language=", current.getLanguage(), " source=", current.getSource(
        ), " numChanges=", current.getNumChanges(), "\n"

    print "\n"
    print "The document has ", doc.getNumTasks(), " task(s).", "\n"
    for i in range(0, doc.getNumTasks()):
        current = doc.getTask(i)
        print "\tTask id=", current.getId(
        ), " model=", current.getModelReference(
        ), " sim=", current.getSimulationReference(), "\n"

    print "\n"
    print "The document has ", doc.getNumDataGenerators(
    ), " datagenerators(s).", "\n"
    for i in range(0, doc.getNumDataGenerators()):
        current = doc.getDataGenerator(i)
        print "\tDG id=", current.getId(), " math=", libsedml.formulaToString(
            current.getMath()), "\n"

    print "\n"
    print "The document has ", doc.getNumOutputs(), " output(s).", "\n"
    for i in range(0, doc.getNumOutputs()):
        current = doc.getOutput(i)
        tc = current.getTypeCode()
        if tc == libsedml.SEDML_OUTPUT_REPORT:
            r = (current)
            print "\tReport id=", current.getId(
            ), " numDataSets=", r.getNumDataSets(), "\n"
        elif tc == libsedml.SEDML_OUTPUT_PLOT2D:
            p = (current)
            print "\tPlot2d id=", current.getId(
            ), " numCurves=", p.getNumCurves(), "\n"
        elif tc == libsedml.SEDML_OUTPUT_PLOT3D:
            p = (current)
            print "\tPlot3d id=", current.getId(
            ), " numSurfaces=", p.getNumSurfaces(), "\n"
        else:
            print "\tEncountered unknown output ", current.getId(), "\n"