示例#1
0
def getFromXML(filename):
    """ 
    Returns the SBMLDocument object from XML file given 
    """
    reader = libsbml.SBMLReader()
    doc = reader.readSBML(filename)
    check(doc, 'reading from SBML file')
    return doc
示例#2
0
def parse_sbml_file(sbmlf):
    """Parse a sbml file and return a sbml object"""
    doc = libsbml.SBMLReader().readSBML(sbmlf)
    if doc.getNumErrors() > 0:
        sys.stderr.write("Errors occurred when reading the document\n")
        sys.exit(1)

    return doc
示例#3
0
def rxn_kegg2sbml():
    kict = get_kegg_data()
    sbml = libsbml.SBMLReader().readSBML("Gthg_2.2 (manual).xml")
    print('The model has ', sbml.getNumErrors(), ' errors')
    model = sbml.getModel()
    hypercount = defaultdict(Counter)
    for rxn in model.getListOfReactions():
        if rxn.getName() in kict:
            #Also should add: to RDF
            #http://www.kegg.jp/entry/R01090
            details = kict[rxn.getName()]
            for f in sorted(details):
                if f != 'ENTRY':
                    #How do I encode <=>?
                    #Unicode? HTML ascii?
                    #https://en.wikipedia.org/wiki/Arrow_(symbol)
                    #encode('ascii','xmlcharrefreplace'))
                    rxn.appendNotes(
                        '<html:p>' + f + ': ' +
                        '; '.join(details[f]).replace("<=>", "\u21cc").replace(
                            '=>', '\u2192').replace('<=', '\u2190') +
                        '</html:p>')
            #if 'DEFINITION' in details and 'EQUATION' in details:
            if 'EQUATION' in details:
                #Match the species.
                #prods=[model.getElementBySId(rxn.getProduct(n).getSpecies()) for n in range(rxn.getNumProducts())]
                #reacs=[model.getElementBySId(rxn.getReactant(n).getSpecies()) for n in range(rxn.getNumReactants())]
                #Split the def and eq lines and zip then
                #terms=list(zip([[re.search("([CG]\d+)",s2).group(0) for s2 in re.sub('\(.*?\)','',s).split('+')] for s in re.split('<?=>?',list(details['EQUATION'])[0])],[s.split('+') for s in re.split('<?=>?',list(details['DEFINITION'])[0])]))
                for k in [
                        re.search("([CG]\d+)", s2).group(0)
                        for s in re.split('<?=>?',
                                          list(details['EQUATION'])[0])
                        for s2 in re.sub('\(.*?\)', '', s).split('+')
                ]:
                    hypercount[k].update(['Σ'] + [
                        rxn.getProduct(n).getSpecies()
                        for n in range(rxn.getNumProducts())
                    ] + [
                        rxn.getReactant(n).getSpecies()
                        for n in range(rxn.getNumReactants())
                    ])
        else:
            print('Unknown ', rxn.getName())
    #print(hypercount)
    mapID = hyperwinner(hypercount)
    print('data:', mapID)
    for sp in model.getListOfSpecies():
        tag = sp.getId().replace('_e', '_c')
        if tag in mapID:
            if type(mapID[tag]) is str:
                sp.appendNotes('<html:p>KEGG: ' + mapID[tag] + '</html:p>')
            #else:
            # sp.appendNotes('<html:p>KEGG: either '+' or '.join(mapID[tag])+'</html:p>')
        else:
            sp.appendNotes('<html:p>KEGG: !!!!GOGGLE IT</html:p>')
            print(tag, ' not an id element')
    libsbml.writeSBMLToFile(sbml, "test enrich.xml")
示例#4
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))
示例#5
0
 def testIsSBMLModel(self):
     return
     self.assertFalse(util.isSBMLModel("dummy"))
     xml = util.getXML(cn.TEST_FILE2)
     reader = libsbml.SBMLReader()
     document = reader.readSBMLFromString(xml)
     util.checkSBMLDocument(document)
     model = document.getModel()
     self.assertTrue(util.isSBMLModel(model))
示例#6
0
    def from_files(
            sbml_file: str = None,
            condition_file: str = None,
            measurement_file: Union[str, Iterable[str]] = None,
            parameter_file: Union[str, List[str]] = None,
            visualization_files: Union[str, Iterable[str]] = None,
            observable_files: Union[str, Iterable[str]] = None) -> 'Problem':
        """
        Factory method to load model and tables from files.

        Arguments:
            sbml_file: PEtab SBML model
            condition_file: PEtab condition table
            measurement_file: PEtab measurement table
            parameter_file: PEtab parameter table
            visualization_files: PEtab visualization tables
            observable_files: PEtab observables tables
        """

        sbml_model = sbml_document = sbml_reader = None
        condition_df = measurement_df = parameter_df = visualization_df = None
        observable_df = None

        if condition_file:
            condition_df = conditions.get_condition_df(condition_file)

        if measurement_file:
            # If there are multiple tables, we will merge them
            measurement_df = core.concat_tables(
                measurement_file, measurements.get_measurement_df)

        if parameter_file:
            parameter_df = parameters.get_parameter_df(parameter_file)

        if sbml_file:
            sbml_reader = libsbml.SBMLReader()
            sbml_document = sbml_reader.readSBML(sbml_file)
            sbml_model = sbml_document.getModel()

        if visualization_files:
            # If there are multiple tables, we will merge them
            visualization_df = core.concat_tables(visualization_files,
                                                  core.get_visualization_df)

        if observable_files:
            # If there are multiple tables, we will merge them
            observable_df = core.concat_tables(observable_files,
                                               observables.get_observable_df)

        return Problem(condition_df=condition_df,
                       measurement_df=measurement_df,
                       parameter_df=parameter_df,
                       observable_df=observable_df,
                       sbml_model=sbml_model,
                       sbml_document=sbml_document,
                       sbml_reader=sbml_reader,
                       visualization_df=visualization_df)
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))
 def test_read_MathML_1(self):
     reader = libsbml.SBMLReader()
     filename = "../../sbml/math/test/test-data/"
     filename += "mathML_1-invalid.xml"
     d = reader.readSBML(filename)
     if (d == None):
         pass
     m = d.getModel()
     self.assert_(m != None)
     self.assert_(m.getNumFunctionDefinitions() == 2)
     self.assert_(m.getNumInitialAssignments() == 1)
     self.assert_(m.getNumRules() == 2)
     self.assert_(m.getNumReactions() == 1)
     fd = m.getFunctionDefinition(0)
     fd_math = fd.getMath()
     self.assert_(fd_math.getType() == libsbml.AST_LAMBDA)
     self.assert_(fd_math.getNumChildren() == 2)
     self.assert_(("lambda(x, )" == libsbml.formulaToString(fd_math)))
     self.assert_(fd_math.getParentSBMLObject() == fd)
     child = fd_math.getRightChild()
     self.assert_(child.getType() == libsbml.AST_UNKNOWN)
     self.assert_(child.getNumChildren() == 0)
     self.assert_(("" == libsbml.formulaToString(child)))
     fd = m.getFunctionDefinition(1)
     fd1_math = fd.getMath()
     self.assert_(fd1_math.getType() == libsbml.AST_LAMBDA)
     self.assert_(fd1_math.getNumChildren() == 2)
     self.assert_(("lambda(x, true)" == libsbml.formulaToString(fd1_math)))
     self.assert_(fd1_math.getParentSBMLObject() == fd)
     child1 = fd1_math.getRightChild()
     self.assert_(child1.getType() == libsbml.AST_CONSTANT_TRUE)
     self.assert_(child1.getNumChildren() == 0)
     self.assert_(("true" == libsbml.formulaToString(child1)))
     ia = m.getInitialAssignment(0)
     ia_math = ia.getMath()
     self.assert_(ia_math.getType() == libsbml.AST_UNKNOWN)
     self.assert_(ia_math.getNumChildren() == 0)
     self.assert_(("" == libsbml.formulaToString(ia_math)))
     self.assert_(ia_math.getParentSBMLObject() == ia)
     r = m.getRule(0)
     r_math = r.getMath()
     self.assert_(r_math.getType() == libsbml.AST_CONSTANT_TRUE)
     self.assert_(r_math.getNumChildren() == 0)
     self.assert_(("true" == libsbml.formulaToString(r_math)))
     self.assert_(r_math.getParentSBMLObject() == r)
     r = m.getRule(1)
     r1_math = r.getMath()
     self.assert_(r1_math.getType() == libsbml.AST_REAL)
     self.assert_(r1_math.getNumChildren() == 0)
     self.assert_(("INF" == libsbml.formulaToString(r1_math)))
     self.assert_(r1_math.getParentSBMLObject() == r)
     # kl = m.getReaction(0).getKineticLaw()
     # kl_math = kl.getMath()
     # self.assert_( kl_math == None )
     d = None
     pass
示例#9
0
    def test_file(self, filename):
        """
        Function for returning errors found in an SBML file.
        """
        import libsbml as lb

        reader = lb.SBMLReader()
        document = reader.readSBML(filename)
        if document.getNumErrors() != 0:
            document.printErrors()
def loadTranslator(fileName, jsonFile):
    reader = libsbml.SBMLReader()
    document = reader.readSBMLFromFile('XMLExamples/curated/BIOMD0000000' +
                                       fileName + '.xml')
    parser = libsbml2bngl.SBML2BNGL(document.getModel())
    database = structures.Databases()
    translator = m2c.transformMolecules(
        parser, database,
        'reactionDefinitions/reactionDefinition' + str(jsonFile) + '.json')
    return translator
示例#11
0
def check_for_groups(groups_sbml, sbo_term, group_type):
    doc = libsbml.SBMLReader().readSBMLFromFile(groups_sbml)
    groups_plugin = doc.getModel().getPlugin("groups")
    if groups_plugin:
        for group in groups_plugin.getListOfGroups():
            gr_sbo = group.getSBOTermID()
            gr_type = next(get_annotations(group, libsbml.BQB_IS_DESCRIBED_BY), None)
            if sbo_term == gr_sbo and group_type == gr_type:
                return True
    return False
示例#12
0
def main(fileName):
    reader = libsbml.SBMLReader()
    document = reader.readSBMLFromFile(fileName)
    model = document.getModel()
    speciesName = []

    for species in model.getListOfSpecies():
        speciesName.append(species.getName())

    return analyzeNamingConventions(speciesName, 'reactionDefinitions/namingConventions.json')
示例#13
0
文件: core.py 项目: cthoyt/PEtab
    def __setstate__(self, state):
        # load SBML model from pickled string
        sbml_string = state.pop('sbml_string', None)
        if sbml_string:
            self.sbml_reader = libsbml.SBMLReader()
            self.sbml_document = \
                self.sbml_reader.readSBMLFromString(sbml_string)
            self.sbml_model = self.sbml_document.getModel()

        self.__dict__.update(state)
示例#14
0
def main():
    args = docopt.docopt(__doc__)
    sbml_file = args["--sbml"]
    reader = libsbml.SBMLReader()
    sbml_document = reader.readSBML(sbml_file)
    for i in range(sbml_document.getNumErrors()):
        print(sbml_document.getError(i).getMessage())

    padmet = PadmetSpec(args["--padmet"])
    compare_sbml_padmet.compare_sbml_padmet(sbml_document, padmet)
示例#15
0
def main():

    if libsbml == None:
        return
    parser = OptionParser()
    parser.add_option(
        "-i",
        "--input",
        dest="input",
        default='',
        type="string",
        #default='/home/proto/Downloads/model.xml',type="string",
        help="The input SBML file in xml format. Default = 'input.xml'",
        metavar="FILE")
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      type="string",
                      help="the output JSON file. Default = <input>.py",
                      metavar="FILE")
    (options, args) = parser.parse_args()
    reader = libsbml.SBMLReader()
    nameStr = options.input
    if options.output == None:
        outputFile = nameStr + '.json'
    else:
        outputFile = options.output
    document = reader.readSBMLFromFile(nameStr)
    if document.getModel() == None:
        #logging.error('A model with path "{0}" could not be found'.format(nameStr))
        return
    #logging.info('An SBML file was found at {0}.Attempting import'.format(nameStr))
    parser = SBML2JSON(document.getModel())

    parameters, observables = parser.getParameters()

    #compartments = parser.getRawCompartments()
    molecules, release = parser.getMolecules()
    reactions, release2, molecules2 = parser.getReactions(parameters)
    molecules.extend(molecules2)
    release.extend(release2)
    #release.extend(release2)
    definition = {}
    definition['par_list'] = parameters
    definition['mol_list'] = molecules
    definition['rxn_list'] = reactions
    definition['rel_list'] = release
    definition['obs_list'] = observables
    #definition['comp_list'] = compartments
    with open(outputFile, 'w') as f:
        json.dump(definition,
                  f,
                  sort_keys=True,
                  indent=1,
                  separators=(',', ': '))
示例#16
0
def preprocess(inf,species,is_mmod):
    src_file = r'%s' % (my_constants.species_sbml[species])
    reader = libsbml.SBMLReader()
    doc = reader.readSBML(src_file)
    go_loaded_model = eval_util.GoLoadedModel(doc.getModel(), species)
    moredata_loaded_model = eval_util.MoreDataLoadedModel(species)
    sbml_file = r'%s/dataset/networks/%s' % (my_constants.basePath, my_constants.species_sbml[species])
    S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts \
        = importer.sbmlStoichiometricMatrix(sbml_file, True, read_species_compart=True)# remove_biomass=method_conf['remove_biomass'], normalize_stoich=method_conf['normalize_stoich'])
    go1=compute_coexpression_of_enzymes_aggregate(inf,species,is_mmod,True,S,mets,rxns,revs,go_loaded_model, moredata_loaded_model)
    return go1
示例#17
0
 def test_GetMultipleObjects_allElements(self):
     reader = libsbml.SBMLReader()
     filename = "../../sbml/test/test-data/"
     filename += "multiple-ids.xml"
     d = reader.readSBML(filename)
     if (d == None):
         pass
     list = d.getListOfAllElements()
     self.assert_(list.getSize() == 37)
     d = None
     pass
示例#18
0
 def testGetXMLFromAntimony(self):
     try:
         xml = util.getXMLFromAntimony(ANTIMONY_STG)
     except exceptions.MissingTelluriumError:
         return
     self.assertTrue(isinstance(xml, str))
     reader = libsbml.SBMLReader()
     libsbml_document = reader.readSBMLFromString(xml)
     util.checkSBMLDocument(libsbml_document)
     model = libsbml_document.getModel()
     self.assertTrue('Reaction' in str(type(model.getReaction(0))))
示例#19
0
def parse_sbml_file(sbmlfile):
    """
    Parse a sbml file and return a sbml object
    :param sbmlfile: The file to parse
    :return: the parsed lbsbml object
    """
    sbml_doc = libsbml.SBMLReader().readSBML(sbmlfile)
    if sbml_doc.getNumErrors() > 0:
        sys.stderr.write("Errors occurred when reading the document\n")
        sys.exit(1)
    return sbml_doc
示例#20
0
 def __init__(self, model_reference):
     """
     Initializes instance variables
     :param str model_reference: string or SBML file
     """
     ##### PUBLIC #####
     self.model = None  # libsbml object
     self.reactions = []  # Python wrapper for Reaction
     self.species = []  # libsbml Species
     self.assignment_rules = [
     ]  # rules for defining the values of variables
     self.initial_assignments = []  # list of initial assignments
     # Read the model
     if util.isSBMLModel(model_reference):
         self.model = model_reference
     else:
         xml = util.getXML(model_reference)
         reader = libsbml.SBMLReader()
         document = reader.readSBMLFromString(xml)
         util.checkSBMLDocument(document, model_reference=model_reference)
         self.model = document.getModel()
     # Do the initializations
     self.reactions = [
         Reaction(self.model.getReaction(nn))
         for nn in range(self.model.getNumReactions())
     ]
     self.species = [
         self.model.getSpecies(nn)
         for nn in range(self.model.getNumSpecies())
     ]
     self.parameters = [
         self.model.getParameter(nn)
         for nn in range(self.model.getNumParameters())
     ]
     for nn in range(self.model.getNumRules()):
         rule = self.model.getRule(nn)
         if rule.isAssignment():
             self.assignment_rules.append(rule)
     for nn in range(self.model.getNumInitialAssignments()):
         initial_assignment = self.model.getInitialAssignment(nn)
         self.initial_assignments.append(initial_assignment)
     # map for species -> species ref
     self.str_species = {}
     self.str_speciesref = {}
     # initialization for str_to_species
     for species in self.species:
         self.str_species[species.getId()] = species
     # initialization for str_to_speciesref
     for reaction in self.reactions:
         for reactant in reaction.reactants:
             self.str_speciesref[reactant.species] = reactant
         for product in reaction.products:
             self.str_speciesref[product.species] = product
示例#21
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)
示例#22
0
def check_ids(model_metabolic, model_faa, cutoff, verbose=False):
    """
    check if genes ids of model_metabolic = model_faa for a given cutoff
    faa genes ids are in the first line of each sequence: >GENE_ID ....
    metabolic netowkrs genes ids are in note section, GENE_ASSOCIATION: gene_id-1 or gene_id-2

    Parameters
    ----------
    model_metabolic: str
        path to sbml file
    model_faa: str
        path to fasta faa file
    cutoff: int
        cutoff genes ids from model found in faa
    verbose: bool
        verbose
        
    Returns
    -------
    bool    
        True if same ids, if verbose, print % of genes under cutoff
    """
    reader = libsbml.SBMLReader()
    document = reader.readSBML(model_metabolic)
    model = document.getModel()
    document.getNumErrors()
    listOfReactions = model.getListOfReactions()
    #convert to set
    model_metabolic_ids = set(itertools.chain.from_iterable([sp.parseGeneAssoc(geneAssoc) 
    for geneAssoc in (sp.parseNotes(r).get("GENE_ASSOCIATION",[None])[0] for r in listOfReactions)
    if geneAssoc is not None]))
    
    with open(model_faa, "r") as f:
        model_faa_ids = set([record.id for record in SeqIO.parse(f, "fasta")])

    diff_genes = model_metabolic_ids.difference(model_faa_ids)
    try:
        diff_genes_ratio = float(len(diff_genes))/float(len(model_metabolic_ids))
    except ZeroDivisionError:
        raise SystemExit("No genes found in model metabolic")
    #if all model_metabolic_ids are in model_faa_ids
    if diff_genes_ratio == 0:
        if verbose: print("all genes of the model_metabolic are in the model_faa")
        return True
    #if not check if the nb is sup-equal to the cutoff
    elif diff_genes_ratio <= float(1-cutoff):
        if verbose: print("Only %.2f%% genes of the model_metabolic are not in the model_faa" % (diff_genes_ratio*100))
        return True
    else:
        if verbose: 
            print("%s%% genes of the model_metabolic are not in the model_faa" % (diff_genes_ratio*100))
            print(";".join(diff_genes))
        return False
示例#23
0
def modelIterator(initial=0,
                  final=1000,
                  data_dir=cn.BIOMODELS_DIR,
                  zip_filename=cn.BIOMODELS_ZIP_FILENAME):
    """
  Iterates across all models in a data directory.
  :param int initial: initial file to process
  :param int final: final file to process
  :param str data_dir: absolute path of the directory containing
      the xml files
  :param str zip_filename: name of the zipfile to process. If
      None, then looks for XML files in the directory.
  :return IteratorItem:
  """
    # Handle zip vs. XML file
    if zip_filename is not None:
        files, zipper = getZipfilePaths(data_dir=data_dir,
                                        zip_filename=zip_filename)
    else:
        files = [f for f in os.listdir(data_dir) if f[-4:] == ".xml"]
    # Functions for file types
    def readXML(filename):
        path = os.path.join(data_dir, filename)
        with open(path, 'r') as fd:
            lines = ''.join(fd.readlines())
        return lines

    def readZip(filename):
        with zipper.open(filename, 'r') as fid:
            lines = fid.read()
        return lines

    #
    if zip_filename is not None:
        read_func = readZip
    else:
        read_func = readXML
    begin_num = max(initial, 0)
    num = begin_num - 1
    end_num = min(len(files), final)
    for filename in files[begin_num:end_num]:
        num += 1
        lines = read_func(filename)
        if isinstance(lines, bytes):
            lines = lines.decode("utf-8")
        reader = libsbml.SBMLReader()
        document = reader.readSBMLFromString(lines)
        model = document.getModel()
        iterator_item = IteratorItem(filename=filename,
                                     model=model,
                                     number=num)
        yield iterator_item
示例#24
0
def main():

    # command line arguments
    parser = OptionParser()
    parser.add_option(
        "-i",
        "--input",
        dest="input",
        default="bngl2mcell/rec_dim_sbml.xml",
        type="string",
        help="The input SBML file in xml format. Default = 'input.xml'",
        metavar="FILE",
    )
    parser.add_option(
        "-o",
        "--output",
        dest="output",
        type="string",
        help="the output JSON file. Default = <input>.py",
        metavar="FILE",
    )
    (options, args) = parser.parse_args()
    reader = libsbml.SBMLReader()
    nameStr = options.input
    if options.output == None:
        outputFile = nameStr + ".py"
    else:
        outputFile = options.output

    # libsbml initialization stuff
    document = reader.readSBMLFromFile(nameStr)
    if document.getModel() == None:
        print("No such input file")
        return
    # get data
    parser = SBML2JSON(document.getModel())
    parameters = parser.getParameters()
    molecules, release = parser.getMolecules()
    reactions = parser.getReactions(parameters)
    definition = {}
    definition["par_list"] = parameters
    definition["mol_list"] = molecules
    definition["rxn_list"] = reactions
    definition["rel_list"] = release
    print("Writing output to {0}".format(outputFile))
    # output
    with open(outputFile, "w") as f:
        json.dump(definition,
                  f,
                  sort_keys=True,
                  indent=1,
                  separators=(",", ": "))
def readFromString(inputString,reactionDefinitions,useID,speciesEquivalence=None,atomize=False, loggingStream=None):
    '''
    one of the library's main entry methods. Process data from a string
    '''

    console = None
    if loggingStream:
        console = logging.StreamHandler(loggingStream)
        console.setLevel(logging.DEBUG)

        setupStreamLog(console)

    reader = libsbml.SBMLReader()
    document = reader.readSBMLFromString(inputString)
    parser =SBML2BNGL(document.getModel(),useID)
    
    bioGrid = False
    pathwaycommons = True
    if bioGrid:
        loadBioGrid()

    database = structures.Databases()
    database.assumptions = defaultdict(set)
    database.document = document
    database.forceModificationFlag = True
    database.reactionDefinitions = reactionDefinitions
    database.useID = useID
    database.atomize = atomize
    database.speciesEquivalence = speciesEquivalence
    database.pathwaycommons = True
    database.isConversion = True
    #if pathwaycommons:
    #    database.pathwaycommons = True
    namingConventions = resource_path('config/namingConventions.json')
    
    if atomize:
        translator,onlySynDec = mc.transformMolecules(parser,database,reactionDefinitions,namingConventions,speciesEquivalence,bioGrid)
        database.species = translator.keys()
    else:    
        translator={} 
    #logging.getLogger().flush()
    if loggingStream:
        finishStreamLog(console)

    returnArray = analyzeHelper(document, reactionDefinitions,
                         useID,'', speciesEquivalence, atomize, translator, database)

    if atomize and onlySynDec:
        returnArray = list(returnArray)
    returnArray = AnalysisResults(*(list(returnArray[0:-2]) + [database] + [returnArray[-1]]))

    return returnArray
示例#26
0
 def __read_sbml_model(self):
     reader = libsbml.SBMLReader()
     sbml_doc = reader.readSBMLFromFile(self.__path)
     # This is just to warn user. Not considered as a failure at this point.
     if sbml_doc.validateSBML() > 0:
         warnings.warn(
             "Warning, SBML did not pass validation!\nProceeding anyway.")
     if sbml_doc.checkConsistency() > 0:
         warnings.warn(
             "Warning, SBML did not pass checking of consistency!\nProceeding anyway."
         )
     self.__sbml_model = sbml_doc.getModel()
     pass
示例#27
0
 def setUp(self):
     '''
     setup SBtabTable class with files from test directory
     '''
     self.sbml_names = [f for f in os.listdir('python/tests/sbml/') if os.path.isfile(os.path.join('sbml/', f))]
     
     self.sbml_docs = []
     reader = libsbml.SBMLReader()
     
     for i, s in enumerate(self.sbml_names):
         if s.startswith('_'): continue
         doc = reader.readSBML('python/tests/sbml/' + s)
         self.sbml_docs.append(doc)
示例#28
0
def size_warning(sbml_file):
    '''
    check whether a given sbml file has more than 250 reactions and 
    then yield a warning message for the online interface
    '''
    reader = libsbml.SBMLReader()
    sbml = reader.readSBMLFromString(sbml_file)
    sbml_model = sbml.getModel()
    if sbml_model.getNumReactions() > 250:
        return ('Warning: The model has more than 250 reactions, which may'\
                ' slow down the computation time significantly. Proceed'\
                ' with care.')
    else:
        return False
示例#29
0
    def setUp(self):
        '''
        setup SBtabTable class with files from test directory
        '''
        self.table_names = [
            f for f in os.listdir('python/tests/tables/')
            if os.path.isfile(os.path.join('python/tests/tables/', f))
        ]
        self.doc_names = [
            f for f in os.listdir('python/tests/docs/')
            if os.path.isfile(os.path.join('python/tests/docs/', f))
        ]
        self.sbml_names = [
            f for f in os.listdir('python/tests/sbml/')
            if os.path.isfile(os.path.join('python/tests/sbml/', f))
        ]

        self.sbtabs = []
        for t in self.table_names:
            if not t.startswith('_'):
                p = open('python/tests/tables/' + t, 'r')
                p_content = p.read()
                sbtab = SBtab.SBtabTable(p_content, t)
                self.sbtabs.append(sbtab)
                p.close()

        self.docs = []
        for i, d in enumerate(self.doc_names):
            if not d.startswith('_'):
                p = open('python/tests/docs/' + d, 'r')
                p_content = p.read()
                sbtab = SBtab.SBtabDocument('test_' + str(i),
                                            sbtab_init=p_content,
                                            filename=d)
                self.docs.append(sbtab)
                p.close()

        self.sbml_docs = []
        self.sbml_strings = []
        reader = libsbml.SBMLReader()
        for i, s in enumerate(self.sbml_names):
            if s.startswith('_'): continue
            # save SBML objects
            doc = reader.readSBML('python/tests/sbml/' + s)
            self.sbml_docs.append(doc)

            # also save the strings
            sbml = open('python/tests/sbml/' + s, 'r')
            self.sbml_strings.append(sbml.read())
            sbml.close()
示例#30
0
 def test_GetMultipleObjects_noUnits(self):
     reader = libsbml.SBMLReader()
     filename = "../../sbml/test/test-data/"
     filename += "multiple-ids.xml"
     d = reader.readSBML(filename)
     if (d == None):
         pass
     obj = d.getElementBySId("volume")
     self.assert_(obj == None)
     obj = d.getElementByMetaId("meta30")
     self.assert_(obj != None)
     self.assert_(obj.getTypeCode() == libsbml.SBML_UNIT_DEFINITION)
     d = None
     pass