Ejemplo n.º 1
0
def write_sbml(doc,
               filepath,
               validate=True,
               program_name=None,
               program_version=None,
               show_errors=True):
    """
    Write SBMLDocument to file.

    :param doc: SBMLDocument to write
    :param filepath: output file to write
    :param validate: flag for validation (True: full validation, False: no validation)
    :param program_name: Program name for SBML file
    :param program_version: Program version for SBML file
    :return:
    """
    writer = libsbml.SBMLWriter()
    if program_name:
        writer.setProgramName(program_name)
    if program_version:
        writer.setProgramVersion(program_version)
    writer.writeSBMLToFile(doc, filepath)

    # validate the model with units (only for small models)
    # This validates the written file
    if validate:
        if validate is True:
            validation.check_sbml(filepath)
        elif validate is validation.VALIDATION_NO_UNITS:
            validation.check_sbml(filepath,
                                  units_consistency=False,
                                  log_errors=True)
Ejemplo n.º 2
0
 def test_SBMLWriter_L3_create(self):
     w = libsbml.SBMLWriter()
     self.assert_(w != None)
     _dummyList = [w]
     _dummyList[:] = []
     del _dummyList
     pass
Ejemplo n.º 3
0
def save_cbmodel(model, filename, flavor=Flavor.FBC2.value):
    """ Save a constraint-based model to an SBML file.

    Arguments:
        model (Model): model
        filename (str): file path
        flavor (str): (optional, currently available: 'cobra', 'fbc2', 'bigg')
    """

    document = sb.SBMLDocument(DEFAULT_SBML_LEVEL, DEFAULT_SBML_VERSION)
    sbml_model = document.createModel(model.id)

    if flavor in {Flavor.BIGG.value, Flavor.FBC2.value}:
        document.enablePackage(sb.FbcExtension.getXmlnsL3V1V2(), 'fbc', True)
        fbc_model = sbml_model.getPlugin('fbc')
        fbc_model.setStrict(True)
        document.setPackageRequired('fbc', False)

    save_compartments(model, sbml_model)
    save_metabolites(model, sbml_model, flavor)
    save_reactions(model, sbml_model)
    save_cb_parameters(model, sbml_model, flavor)
    save_gpr_associations(model, sbml_model, flavor)

    save_metadata(model, sbml_model)
    writer = sb.SBMLWriter()
    writer.writeSBML(document, filename)
Ejemplo n.º 4
0
def write_sbml(sbml, filename):
    """
    Write an SBML object to the specified path.
    """
    change_modified_date(sbml)
    writer = libsbml.SBMLWriter()
    writer.writeSBMLToFile(sbml, filename)
Ejemplo n.º 5
0
def main(args):
    """usage: echoSBML.py input-filename output-filename
  """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % infile)
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] Echoed %s to %s" % (infile, outfile))
def main():
    sbml_file_template = 'ERBB_RAS_AKT_Drugs_r389936_withObs_withSigma.sbml'
    sbml_file_new = 'CS_Signalling_ERBB_RAS_AKT_CCLE_petab.xml'

    sbml_reader = libsbml.SBMLReader()
    sbml_document = sbml_reader.readSBML(sbml_file_template)
    sbml_model = sbml_document.getModel()

    petab.log_sbml_errors(sbml_document)

    # fix units
    set_species_unit_to_nanomole(sbml_model)

    # Add observable and sigma
    add_observables(sbml_model)

    petab.globalize_parameters(sbml_model)

    gene_specific_scaling_non_const(sbml_model)

    # Write updated model
    sbml_writer = libsbml.SBMLWriter()
    sbml_writer.writeSBMLToFile(sbml_document, sbml_file_new)

    # Load and check for errors
    sbml_reader = libsbml.SBMLReader()
    sbml_document = sbml_reader.readSBML(sbml_file_new)
    petab.is_sbml_consistent(sbml_document)
Ejemplo n.º 7
0
def convert_workflow(path, archive, archive_dir, sedml_doc=None):
    with open(os.path.join(path, "info.json"), "r") as info_file:
        wkfl_info = json.load(info_file)
        model_path = os.path.join("/home/jovyan", wkfl_info['wkfl_model'])

    # add model to archive as sbml file with .xml extension
    sbml_document = convert_to_sbml(model_path.replace("/home/jovyan/", ""), write_to_file=False)
    sbml_path, _ = get_unique_file_name(model_path.split('/').pop().split('.')[0]+".xml",
                                        archive_dir.name)
    with open(sbml_path, "w") as sbml_file:
        sbml_file.write(libsbml.SBMLWriter().writeSBMLToString(sbml_document))
    model_file = sbml_path.split('/').pop()
    archive.addFile(sbml_path, "./{0}".format(model_file),
                    libcombine.KnownFormats.lookupFormat('sbml'), False)

    # create Sed-ML document, name, and path
    if sedml_doc is None:
        sedml_doc = libsedml.SedDocument(1, 3)
        sedml_document = convert_workflow_to_sedml(path, wkfl_info, model_file, sedml_doc)
        sedml_name = os.path.dirname(path).split('/').pop().replace(".wkgp", ".xml")
        sedml_path, _ = get_unique_file_name(sedml_name, archive_dir.name)

        return {"doc":sedml_document, "name":sedml_name, "path":sedml_path}

    return convert_workflow_to_sedml(path, wkfl_info, model_file, sedml_doc)
Ejemplo n.º 8
0
def main (args):
  """usage: flattenModel.py [-p] input-filename output-filename
      -p : list unused ports
  """
  if len(args) != 4 and len(args) != 3 :
    print(main.__doc__)
    sys.exit(1)

  leavePorts = False

  if len(args) == 3:
    infile  = args[1]
    outfile = args[2]
  elif len(args) == 4:
    if args[1] != "-p":
      print(main.__doc__)
      sys.exit(1)
    else:
      leavePorts = True
      infile  = args[2]
      outfile = args[3]



  if not os.path.exists(infile):
    print("[Error] %s : No such file." % (infile))
    sys.exit(1)

  reader  = libsbml.SBMLReader()
  writer  = libsbml.SBMLWriter()
  sbmldoc = reader.readSBML(infile)

  if sbmldoc.getNumErrors() > 0:
    if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
      # Handle case of unreadable file here.
      sbmldoc.printErrors()
    elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
      # Handle case of other file error here.
      sbmldoc.printErrors()
    else:
      # Handle other error cases here.
      sbmldoc.printErrors()

    sys.exit(1)

  # Create the converter options
  props = libsbml.ConversionProperties()
  props.addOption("flatten comp", True, "flatten comp")
  props.addOption("leavePorts", leavePorts, "unused ports should be listed in the flattened model")

  # do conversion
  result = sbmldoc.convert(props)
  if (result != libsbml.LIBSBML_OPERATION_SUCCESS):
    sbmldoc.printErrors()
    print("[Error] Conversion failed... ("+ str(result) + ")")
    sys.exit(1)

  writer.writeSBML(sbmldoc, outfile)
  print("Flat model written to %s" % (outfile))
Ejemplo n.º 9
0
 def write_sbmldoc_to_file(self, filename):
     """ Writes the libsbml object as an SBML file. 
     
     Parameters
         filename: a string with the name of the file to be written.
     """
     writer = libsbml.SBMLWriter()
     writer.writeSBML(self.sbml_obj, filename)
def main(args):
    """usage: convertFbcToCobra.py input-filename output-filename
    """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % infile)
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

            # sys.exit(1)

    # strip non-FBC plugins
    for p_ in range(sbmldoc.getNumPlugins()):
        if sbmldoc.getPlugin(p_).getPackageName() != 'fbc':
            props = libsbml.ConversionProperties()
            props.addOption(
                "stripPackage", True,
                "Strip SBML Level 3 package constructs from the model")
            props.addOption("package",
                            sbmldoc.getPlugin(p_).getPackageName(),
                            "Name of the SBML Level 3 package to be stripped")
            if sbmldoc.convert(props) != libsbml.LIBSBML_OPERATION_SUCCESS:
                print("[Error] Failed to remove package: {}".format(
                    sbmldoc.getPlugin(p_).getPackageName()))

    # convert to L2
    props = libsbml.ConversionProperties()
    props.addOption("convert fbc to cobra", True,
                    "Convert FBC model to Cobra model")
    result = sbmldoc.convert(props)

    if result != libsbml.LIBSBML_OPERATION_SUCCESS:
        print("[Error] Conversion failed... (%d)" % result)
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] converted file %s to %s" % (infile, outfile))
Ejemplo n.º 11
0
 def test_WriteL3SBML_error(self):
   d = libsbml.SBMLDocument()
   w = libsbml.SBMLWriter()
   self.assertEqual( False, w.writeSBML(d, "/tmp/impossible/path/should/fail") )
   self.assert_( d.getNumErrors() == 1 )
   self.assert_( d.getError(0).getErrorId() == libsbml.XMLFileUnwritable )
   d = None
   w = None
   pass  
Ejemplo n.º 12
0
 def test_SBMLWriter_L3_setProgramVersion(self):
   w = libsbml.SBMLWriter()
   self.assert_( w != None )
   i = w.setProgramVersion( "sss")
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   i = w.setProgramVersion("")
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   _dummyList = [ w ]; _dummyList[:] = []; del _dummyList
   pass  
Ejemplo n.º 13
0
def modifyReleaseNumber(fileName):
    print('modifying {0}'.format(fileName))
    reader = libsbml.SBMLReader()
    document = reader.readSBMLFromFile(fileName)
    model = document.getModel()

    species = model.getSpecies('S4')
    species.setInitialAmount(species.getInitialConcentration())
    species.unsetInitialConcentration()

    writer = libsbml.SBMLWriter()
    writer.writeSBMLToFile(document, fileName)
Ejemplo n.º 14
0
def reduceAnnotations(fileName):

    sct, database, sbmlDocument = obtainSCT(fileName,
                                            'config/reactionDefinitions.json',
                                            False,
                                            'config/namingConventions.json')
    annotationDict, speciesNameDict = buildAnnotationDict(sbmlDocument)
    buildAnnotationTree(annotationDict, sct, database)
    speciesAnnotationsToSBML(sbmlDocument, annotationDict, speciesNameDict)

    writer = libsbml.SBMLWriter()
    return writer.writeSBMLToString(sbmlDocument)
Ejemplo n.º 15
0
def write_sbml(sbml_doc: libsbml.SBMLDocument, filename: str) -> None:
    """Write PEtab visualization table

    Arguments:
        sbml_doc: SBML document containing the SBML model
        filename: Destination file name
    """
    sbml_writer = libsbml.SBMLWriter()
    ret = sbml_writer.writeSBMLToFile(sbml_doc, filename)
    if not ret:
        raise RuntimeError(f"libSBML reported error {ret} when trying to "
                           f"create SBML file {filename}.")
Ejemplo n.º 16
0
def write_sbml(
    doc: libsbml.SBMLDocument,
    filepath: Union[Path] = None,
    program_name: str = None,
    program_version: str = None,
    validate: bool = False,
    log_errors: bool = True,
    units_consistency: bool = True,
    modeling_practice: bool = True,
    internal_consistency: bool = True,
) -> str:
    """Write SBMLDocument to file or string.

    To write the SBML to string use 'filepath=None', which returns the SBML string.

    Optional validation with validate flag.

    :param doc: SBMLDocument to write
    :param filepath: output file to write
    :param validate: flag for validation (True: full validation, False: no validation)
    :param program_name: Program name for SBML file
    :param program_version: Program version for SBML file
    :param log_errors: validation flag
    :param units_consistency: validation flag
    :param modeling_practice: validation flag
    :param internal_consistency: validation flag

    :return: None or SBML string
    """
    writer = libsbml.SBMLWriter()
    if program_name:
        writer.setProgramName(program_name)
    if program_version:
        writer.setProgramVersion(program_version)

    if filepath is None:
        sbml_str = writer.writeSBMLToString(doc)
        source = sbml_str
    else:
        writer.writeSBMLToFile(doc, str(filepath))
        sbml_str = None
        source = filepath

    if validate:
        validate_sbml(
            source=source,
            name=source,
            log_errors=log_errors,
            units_consistency=units_consistency,
            modeling_practice=modeling_practice,
            internal_consistency=internal_consistency,
        )
    return sbml_str  # type: ignore
Ejemplo n.º 17
0
def writeModelToSBML(model, filepath):
    """
    Write SBML Model to output file.
    An empty SBMLDocument is created for the model.

    :param model: SBML Model
    :param filepath: output file path
    :return:
    """
    writer = libsbml.SBMLWriter()
    doc = libsbml.SBMLDocument()
    doc.setModel(model)
    writer.writeSBMLToFile(doc, filepath)
Ejemplo n.º 18
0
Archivo: core.py Proyecto: cthoyt/PEtab
    def __getstate__(self):
        state = self.__dict__.copy()

        # libsbml stuff cannot be serialized directly
        if self.sbml_model:
            sbml_document = self.sbml_model.getSBMLDocument()
            sbml_writer = libsbml.SBMLWriter()
            state['sbml_string'] = sbml_writer.writeSBMLToString(sbml_document)

        exclude = ['sbml_reader', 'sbml_document', 'sbml_model']
        for key in exclude:
            state.pop(key)

        return state
Ejemplo n.º 19
0
def save_model(model, filename):
    """ Save a model to an SBML file.

    Arguments:
        model (Model): model
        filename (str): file path
    """

    document = sb.SBMLDocument(DEFAULT_SBML_LEVEL, DEFAULT_SBML_VERSION)
    sbml_model = document.createModel(model.id)
    save_compartments(model, sbml_model)
    save_metabolites(model, sbml_model)
    save_reactions(model, sbml_model)
    writer = sb.SBMLWriter()
    writer.writeSBML(document, filename)
Ejemplo n.º 20
0
def expandAnnotation(fileName, bnglFile):

    sct, database, sbmlDocument, _ = obtainSCT(
        fileName, 'config/reactionDefinitions.json', False,
        'config/namingConventions.json')
    annotationDict, speciesNameDict = buildAnnotationDict(sbmlDocument)
    buildAnnotationTree(annotationDict, sct, database)
    speciesAnnotationsToSBML(sbmlDocument, annotationDict, speciesNameDict)
    #species, rules, par = createDataStructures(bnglFile)
    #reactionAnnotationDict = buildReactionAnnotationDict(rules)
    #reactionAnnotationsToSBML(sbmlDocument,reactionAnnotationDict)
    #reactionAnnotationsToSBML(sbmlDocument,reactionAnnotation)

    #reactionAnnotationsToSBML(sbmlDocument)
    writer = libsbml.SBMLWriter()
    return writer.writeSBMLToString(sbmlDocument)
Ejemplo n.º 21
0
    def compile_model(self):
        """
        Compile the model. If the output folder exists already, it is first
        deleted.
        """

        # check prerequisites
        if not petab.condition_table_is_parameter_free(
                self.petab_problem.condition_df):
            raise AssertionError(
                "Parameter dependent conditions in the condition file "
                "are not yet supported.")

        # delete output directory
        if os.path.exists(self.output_folder):
            shutil.rmtree(self.output_folder)

        # constant parameters
        condition_columns = self.petab_problem.condition_df.columns.values
        constant_parameter_ids = list(
            set(condition_columns) - {'conditionId', 'conditionName'})

        # observables
        observables = self.petab_problem.get_observables()

        # sigmas
        sigmas = self.petab_problem.get_sigmas(remove=True)

        # noise distributions
        noise_distrs = _to_amici_noise_distributions(
            self.petab_problem.get_noise_distributions())

        # model to string
        sbml_string = libsbml.SBMLWriter().writeSBMLToString(
            self.petab_problem.sbml_document)
        # init sbml importer
        sbml_importer = amici.SbmlImporter(sbml_string, from_file=False)

        # convert
        sbml_importer.sbml2amici(modelName=self.model_name,
                                 output_dir=self.output_folder,
                                 observables=observables,
                                 constantParameters=constant_parameter_ids,
                                 sigmas=sigmas,
                                 noise_distributions=noise_distrs)
Ejemplo n.º 22
0
def main(args):
    """usage: stripPackage.py input-filename package-to-strip output-filename
  """
    if len(args) != 4:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    package = args[2]
    outfile = args[3]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % (infile))
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        sys.exit(1)

    props = libsbml.ConversionProperties()
    props.addOption("stripPackage", True,
                    "Strip SBML Level 3 package constructs from the model")
    props.addOption("package", package,
                    "Name of the SBML Level 3 package to be stripped")
    if (sbmldoc.convert(props) != libsbml.LIBSBML_OPERATION_SUCCESS):
        print("[Error] Conversion failed...")
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] stripped package '%s' from %s to %s" %
          (package, infile, outfile))
Ejemplo n.º 23
0
def main(args):
    """usage: flattenArrays.py input-filename output-filename
    """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] {} : No such file.".format(infile))
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        sys.exit(1)

    props = libsbml.ConversionProperties()
    props.addOption("flatten arrays", True, "flatten arrays")
    # Optional: validate flattened file ... may take some time
    # props.addOption("performValidation", True, "perform validation before and after trying to flatten")

    result = sbmldoc.convert(props)
    if (result != libsbml.LIBSBML_OPERATION_SUCCESS):
        print("[Error] Array flattening failed... ({})".format(result))
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] Flattened arrays file {} to {}".format(infile, outfile))
def main(args):
    """usage: convertFbcToCobra.py input-filename output-filename
  """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % (infile))
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        #sys.exit(1)

    props = libsbml.ConversionProperties()
    props.addOption("convert fbc to cobra", True,
                    "Convert FBC model to Cobra model")
    result = sbmldoc.convert(props)
    if (result != libsbml.LIBSBML_OPERATION_SUCCESS):
        print("[Error] Conversion failed... (%d)" % (result))
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] converted file %s to %s" % (infile, outfile))
Ejemplo n.º 25
0
def main(args):
    """usage: promoteParameters.py input-filename output-filename
  """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % (infile))
        sys.exit(1)

    reader = libsbml.SBMLReader()
    writer = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        sys.exit(1)

    props = libsbml.ConversionProperties()
    props.addOption("promoteLocalParameters", True,
                    "Promotes all Local Parameters to Global ones")
    if (sbmldoc.convert(props) != libsbml.LIBSBML_OPERATION_SUCCESS):
        print("[Error] Conversion failed...")
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] wrote %s" % (package, infile, outfile))
def main (args):
    """usage: inlineFunctionDefinitions.py input-filename output-filename
    """
    if len(args) != 3:
        print(main.__doc__)
        sys.exit(1)

    infile  = args[1]
    outfile = args[2]

    if not os.path.exists(infile):
        print("[Error] %s : No such file." % infile)
        sys.exit(1)

    reader  = libsbml.SBMLReader()
    writer  = libsbml.SBMLWriter()
    sbmldoc = reader.readSBML(infile)

    if sbmldoc.getNumErrors() > 0:
        if sbmldoc.getError(0).getErrorId() == libsbml.XMLFileUnreadable:
            # Handle case of unreadable file here.
            sbmldoc.printErrors()
        elif sbmldoc.getError(0).getErrorId() == libsbml.XMLFileOperationError:
            # Handle case of other file error here.
            sbmldoc.printErrors()
        else:
            # Handle other error cases here.
            sbmldoc.printErrors()

        sys.exit(1)

    props = libsbml.ConversionProperties()
    props.addOption("expandFunctionDefinitions", True)
    if sbmldoc.convert(props) != libsbml.LIBSBML_OPERATION_SUCCESS:
        print("[Error] Conversion failed...")
        sys.exit(1)

    writer.writeSBML(sbmldoc, outfile)
    print("[OK] wrote {}".format(outfile))
Ejemplo n.º 27
0
 def save_network_to_file(net, filename):
     sbml_document = SbmlSaver.network_to_sbml(net)
     s = libsbml.SBMLWriter()
     s.writeSBMLToFile(sbml_document, filename)
Ejemplo n.º 28
0
    def save(self, outfile):
        """
        Save the current working SPN to a file of a given name
        in the current dir. vdict contains the labels and data 
        of the vector vars, mdict is the matrices.
        (Note on SBML version compatibility:
        SBML output is written for Level 3 Version 1, but has no
        errors with any Level 2 versions. 6 Errors occur with an L1
        compatibility check if non-integer rates are used.)
        """
        import re
        import libsbml as lb

        # build SBML document and header
        f = open(outfile, 'w') 
        lev = 3
        ver = 1
        out = lb.SBMLDocument(lev,ver)
        model = out.createModel()
        model.setId('StochasticPetriNet')
        
        # Build file body
        cell = model.createCompartment()
        cell.setId('Cell')
        # Causes an error if omitted in earlier levels of SBML
        cell.setSpatialDimensions(3)
        model.addCompartment(cell)
        c1 = 0 # places count
        pdict = {}
        c2 = 0 # trans count? 
        for spe in self.vdict['p']:
            s = model.createSpecies()
            s.setId(spe)
            pdict[c1] = spe
            s.setCompartment(cell.getId())
            s.setInitialAmount(int(self.vdict['m'][c1]))
            model.addSpecies(s)
            c1 += 1
        for reac in self.vdict['t']:
            r = model.createReaction()
            r.setId(reac)
            kl = r.createKineticLaw()
            # Get 'rate' params, insert into KineticLaw local param field
            lp = kl.createLocalParameter()
            lp.setValue(self.vdict['r'][c2])
            lp.setId('rate' + str(c2))
            model.addReaction(r) 
            # Use pre matrix to write named reactants & stoichiometries
            for bin in self.mdict['pre'][c2]:
                # For each place
                for q in range(0, c1):
                    if bin[0,q] != 0 :
                        t = model.createReactant()
                        t.setSpecies(self.vdict['p'][q])
                        # Convert type numpy.int64 -> int
                        t.setStoichiometry(int(bin[0,q]))
            # Same for post matrix
            for bon in self.mdict['post'][c2]:
                # For each place
                for t in range(0, c1):
                    if bon[0,t] != 0 :
                        p = model.createProduct()
                        p.setSpecies(self.vdict['p'][t])
                        # Convert type numpy.int64 -> int
                        p.setStoichiometry(int(bon[0,t]))
            c2+=1
        
        ## Compatibility checks
        # Uncomment print statements to view errors
        print '\t1.0 err: ',  out.checkL1Compatibility()
        # print out.printErrors()
        print '\t2.1 err: ', out.checkL2v1Compatibility()
        # print out.printErrors()
        print '\t2.2 err: ', out.checkL2v2Compatibility()
        # print out.printErrors()
        print '\t2.3 err: ', out.checkL2v3Compatibility()
        # print out.printErrors()
        print '\t2.4 err: ', out.checkL2v4Compatibility()
        # print out.printErrors()
        print '\t3.1 err: ', out.checkL3v1Compatibility()
 
        # write to file
        w = lb.SBMLWriter()
        w.setProgramName('SPNlib')
        w.setProgramVersion('1.0')
        w.writeSBML(out, outfile)
Ejemplo n.º 29
0
def writeSBML(document, fileName):
    writer = libsbml.SBMLWriter()
    writer.writeSBMLToFile(document, fileName)
Ejemplo n.º 30
0
for idx, row in enumerate(species_sheet[1:]):
    Annot = ""
    for col in range(4, (len(row))):
        aa = str(row[col].strip())
        if aa == "nan" or aa == "":
            break
        else:
            Annot = Annot + " " + row[col]
    sbml_model.getSpecies(row[0]).setAnnotation(Annot)

# Set compartment annotations
for row in compartment_sheet[1:]:
    sbml_model.getCompartment(row[0]).setAnnotation(row[2])

# Write with the same name or use the next section instead of below lines
writer = libsbml.SBMLWriter()
writer.writeSBML(sbml_doc, sbml_file)

# # Change model name and write with a new name
# sbml_model.setName(model_name+'_Annot')
# sbml_model.setId(model_name+'_Annot')
# sbml_filewAnnot = model_name+'_Annot.xml'
# writer = libsbml.SBMLWriter()
# writer.writeSBML(sbml_doc, sbml_filewAnnot)

# sbml_file = sbml_filewAnnot # Comment-out to use the file name  w/t annotations
model_name = sbml_file[0:-4]
model_output_dir = model_name

sbml_reader = libsbml.SBMLReader()
sbml_doc = sbml_reader.readSBML(sbml_file)