Example #1
0
def save_sbml_model(model, filename, flavor=None):
    """ Save a model to an SBML file.
    
    Arguments:
        model (Model): model
        filename (str): file path
        flavor (str): adapt to different modeling conventions (optional, currently available: 'cobra', 'fbc2')
    """

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

    if flavor in {Flavor.BIGG, Flavor.FBC2}:
        document.enablePackage(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)
    if isinstance(model, CBModel):
        _save_cb_parameters(model, sbml_model, flavor)
        _save_gpr_associations(model, sbml_model, flavor)
    if isinstance(model, ODEModel):
        _save_concentrations(model, sbml_model)
        _save_global_parameters(model, sbml_model)
        _save_kineticlaws(model, sbml_model)
        _save_assignment_rules(model, sbml_model)
    _save_metadata(model, sbml_model)
    writer = SBMLWriter()
    writer.writeSBML(document, filename)
Example #2
0
    def toXMLString(self, enzmldoc):
        '''
        Converts EnzymeMLDocument to XML string.
        
        Args:
            EnzymeMLDocument enzmldoc: Previously created instance of an EnzymeML document
        '''
        doc = SBMLDocument()
        doc.setLevelAndVersion(enzmldoc.getLevel(), enzmldoc.getVersion())

        model = doc.createModel()
        model.setName(enzmldoc.getName())
        model.setId(enzmldoc.getName())

        # Add references
        self.__addRefs(model, enzmldoc)

        # Add units
        self.__addUnits(model, enzmldoc)

        # Add Vessel
        self.__addVessel(model, enzmldoc)

        # Add protein
        self.__addProteins(model, enzmldoc)

        # Add reactants
        self.__addReactants(model, enzmldoc)

        # Add reactions
        self.__addReactions(model, enzmldoc, csv=False)

        # Write to EnzymeML
        writer = SBMLWriter()
        return writer.writeToString(doc)
Example #3
0
def save_sbml_model(model, filename, flavor=None):
    """ Save a model to an SBML file.
    
    Arguments:
        model (Model): model
        filename (str): file path
        flavor (str): adapt to different modeling conventions (optional, currently available: 'cobra', 'fbc2')
    """

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

    if flavor in {Flavor.BIGG, Flavor.FBC2}:
        document.enablePackage(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)
    if isinstance(model, CBModel):
        _save_cb_parameters(model, sbml_model, flavor)
        _save_gpr_associations(model, sbml_model, flavor)
    if isinstance(model, ODEModel):
        _save_concentrations(model, sbml_model)
        _save_global_parameters(model, sbml_model)
        _save_kineticlaws(model, sbml_model)
        _save_assignment_rules(model, sbml_model)
    _save_metadata(model, sbml_model)
    writer = SBMLWriter()
    writer.writeSBML(document, filename)
Example #4
0
    def writeSBML(self, filepath=None, validate=True):
        if not filepath:
            filepath = self.sbml_default_path()

        print 'Write : {}\n'.format(self.id, filepath)
        writer = SBMLWriter()
        writer.writeSBMLToFile(self.doc, filepath)

        # validate the model with units (only for small models)
        if validate:
            validator = SBMLValidator(ucheck=(self.Nc < 4))
            validator.validate(filepath)
        return filepath
Example #5
0
    def toFile(self, enzmldoc, path):
        '''
        Writes EnzymeMLDocument object to an .omex container
        
        Args:
            EnzymeMLDocument enzmldoc: Previously created instance of an EnzymeML document
            String path: EnzymeML file is written to this destination
        '''

        self.path = path + '/' + enzmldoc.getName()

        try:
            os.makedirs(self.path + '/data')
        except FileExistsError:
            pass

        doc = SBMLDocument()
        doc.setLevelAndVersion(enzmldoc.getLevel(), enzmldoc.getVersion())

        model = doc.createModel()
        model.setName(enzmldoc.getName())
        model.setId(enzmldoc.getName())

        # Add references
        self.__addRefs(model, enzmldoc)

        # Add units
        self.__addUnits(model, enzmldoc)

        # Add Vessel
        self.__addVessel(model, enzmldoc)

        # Add protein
        self.__addProteins(model, enzmldoc)

        # Add reactants
        self.__addReactants(model, enzmldoc)

        # Add reactions
        self.__addReactions(model, enzmldoc)

        # Write to EnzymeML
        writer = SBMLWriter()
        writer.writeSBMLToFile(doc, self.path + '/experiment.xml')

        # Write to OMEX
        self.__createArchive(enzmldoc, doc)

        os.remove(self.path + '/experiment.xml')
        os.remove(self.path + '/data/data.csv')
        os.rmdir(self.path + '/data')
Example #6
0
def save_sbml_model(model, filename):
    """ Save a model to an SBML file.
    
    Arguments:
        model : StoichiometricModel (or any subclass) -- Stoichiometric model (or subclass)
        filename : String -- SBML file path
    """

    document = 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)
    _save_stoichiometry(model, sbml_model)
    if isinstance(model, ConstraintBasedModel):
        _save_cb_parameters(model, sbml_model)
    if isinstance(model, GPRConstrainedModel):
        _save_gpr(model, sbml_model)
    writer = SBMLWriter()
    writer.writeSBML(document, filename)
Example #7
0
def save_sbml(model, filename):
    """docstring for save_model"""

    sbml_document = SBMLDocument(2, 1)
    sbml_model    = sbml_document.createModel(model.id)

    sbml_model.getNamespaces().add("http://www.w3.org/1999/xhtml", "html")

    if model.name:
        sbml_model.setName(model.name)

    for compartment in model.compartments():
        sbml_compartment = sbml_model.createCompartment()
        sbml_compartment.setId(compartment.id)
        sbml_compartment.setName(compartment.name)

    for unit_definition in model.unit_definitions():
        sbml_unitDefinition = sbml_model.createUnitDefinition()
        sbml_unitDefinition.setId(unit_definition.id)
        for unit in unit_definition.units:
            sbml_unit = sbml_unitDefinition.createUnit()
            sbml_unit.setKind(UnitKind_forName(unit.kind))
            sbml_unit.setMultiplier(unit.multiplier)
            sbml_unit.setOffset(unit.offset)
            sbml_unit.setExponent(unit.exponent)
            sbml_unit.setScale(unit.scale)

    for metabolite in model.metabolites():
        species = sbml_model.createSpecies()
        species.setId(metabolite.id)
        species.setName(metabolite.name)
        if metabolite.charge:
            species.setCharge(metabolite.charge)
        species.setCompartment(metabolite.compartment)
        species.setBoundaryCondition(metabolite.boundaryCondition)
        if metabolite.notes:
            for (key, value) in metabolite.notes.items():
                species.appendNotes('\n<html:p>%s: %s</html:p>' % (key, value))
            species.appendNotes('\n')

    for reaction in model.reactions():
        sbml_reaction = sbml_model.createReaction()
        sbml_reaction.setId(reaction.id)
        sbml_reaction.setName(reaction.name)
        sbml_reaction.setReversible(reaction.reversible)

        for (key, value) in reaction.notes.items():
            sbml_reaction.appendNotes('\n<html:p>%s: %s</html:p>' % (key, value))
        sbml_reaction.appendNotes('\n')

        kineticLaw = sbml_reaction.createKineticLaw()
        kineticLaw.setFormula('FLUX_VALUE')

        sbml_lower = kineticLaw.createParameter()
        sbml_lower.setId('LOWER_BOUND')
        sbml_lower.setValue(reaction.lower_bound)

        sbml_upper = kineticLaw.createParameter()
        sbml_upper.setId('UPPER_BOUND')
        sbml_upper.setValue(reaction.upper_bound)

        sbml_upper = kineticLaw.createParameter()
        sbml_upper.setId('OBJECTIVE_COEFFICIENT')
        sbml_upper.setValue(reaction.objective_coefficient)

        if reaction.flux_value:
            sbml_upper = kineticLaw.createParameter()
            sbml_upper.setId('FLUX_VALUE')
            sbml_upper.setValue(reaction.flux_value)

        for (metabolite, coefficient) in reaction.participants.items():
            if coefficient < 0:
                speciesReference = sbml_reaction.createReactant()
                coefficient      = abs(coefficient)
            else:
                speciesReference = sbml_reaction.createProduct()
            speciesReference.setSpecies(metabolite.id)
            speciesReference.setStoichiometry(float(coefficient))

    writer = SBMLWriter()
    writer.writeSBML(sbml_document, filename)
    def export_en_sbml(self,
                       file_path,
                       gemtractor,
                       model_id,
                       model_name=None,
                       filter_species=None,
                       filter_reactions=None,
                       filter_genes=None,
                       filter_gene_complexes=None,
                       remove_reaction_enzymes_removed=True,
                       remove_ghost_species=False,
                       discard_fake_enzymes=False,
                       remove_reaction_missing_species=False,
                       removing_enzyme_removes_complex=True):
        """
    export the enzyme-centric network in SBML format
    
    will attach the trimming-settings as SBML note
    
    writes the document using the `libsbml:SBMLWriter <http://sbml.org/Special/Software/libSBML/docs/python-api/class_s_b_m_l_writer.html>` -- returns the result of `libsbml:SBMLWriter.writeSBML <http://sbml.org/Special/Software/libSBML/docs/python-api/class_s_b_m_l_writer.html#a02d1998aee7656d7b9c3ac69d62bb66f>`_
    
    :param file_path: where to store the exported format?
    :param model_id: the model's identifier, will be postfixed with a greeting from us
    :param model_name: the model's name, will be prefixed with a greeting from us
    :param filter_species: species identifiers to get rid of
    :param filter_reactions: reaction identifiers to get rid of
    :param filter_genes: enzyme identifiers to get rid of
    :param filter_gene_complexes: enzyme-complex identifiers to get rid of, every list-item should be of format: 'A + B + gene42'
    :param remove_reaction_enzymes_removed: should we remove a reaction if all it's genes were removed?
    :param remove_ghost_species: should species be removed, that do not participate in any reaction anymore - even though they might be required in other entities?
    :param discard_fake_enzymes: should fake enzymes (implicitly assumes enzymes, if no enzymes are annotated to a reaction) be removed?
    :param remove_reaction_missing_species: remove a reaction if one of the participating genes was removed?
    :param removing_enzyme_removes_complex: if an enzyme is removed, should also all enzyme complexes be removed in which it participates?
    
    :type file_path: str
    :type model_id: str
    :type model_name: str
    :type filter_species: list of str
    :type filter_reactions: list of str
    :type filter_genes: list of str
    :type filter_gene_complexes: list of str
    :type remove_reaction_enzymes_removed: bool
    :type remove_ghost_species: bool
    :type discard_fake_enzymes: bool
    :type remove_reaction_missing_species: bool
    :type removing_enzyme_removes_complex: bool
    
    :return: true on success, otherwise false
    :rtype: bool
    """
        if not self.have_gene_net:
            self.calc_genenet()

        sbml = SBMLDocument()
        model = sbml.createModel()
        #TODO dc modified?
        if model is None:
            self.__logger.error("could not create model...")
            return False
        model.setId(model_id + "_GEMtracted_EnzymeNetwork")
        if model_name is None:
            model_name = model_id
        model.setName("GEMtracted EnzymeNetwork of " + model_name)

        # print ("adding note to en sbml")
        Utils.add_model_note(model, filter_species, filter_reactions,
                             filter_genes, filter_gene_complexes,
                             remove_reaction_enzymes_removed,
                             remove_ghost_species, discard_fake_enzymes,
                             remove_reaction_missing_species,
                             removing_enzyme_removes_complex)

        nodemap = {}

        compartment = model.createCompartment()
        compartment.setId('compartment')
        compartment.setConstant(True)

        num = 0
        for gene in self.genes:
            num += 1
            nodemap[gene] = self.__create_sbml_gene(model, 'g' + str(num),
                                                    gene, compartment,
                                                    gemtractor)
            # TODO: add other information if available

        for gene in self.gene_complexes:
            num += 1
            nodemap[gene] = self.__create_sbml_gene_complex(
                model, 'gc' + str(num), gene, compartment, gemtractor,
                self.gene_complexes[gene].genes, nodemap)
            # TODO: add other information if available

        num = 0
        for gene in self.genes:
            for associated in self.genes[gene].links["g"]:
                num += 1
                Network.create_sbml_reaction(model, 'r' + str(num),
                                             nodemap[gene],
                                             nodemap[associated.identifier])
            for associated in self.genes[gene].links["gc"]:
                num += 1
                Network.create_sbml_reaction(model, 'r' + str(num),
                                             nodemap[gene],
                                             nodemap[associated.identifier])
        for gene in self.gene_complexes:
            for associated in self.gene_complexes[gene].links["g"]:
                num += 1
                Network.create_sbml_reaction(model, 'r' + str(num),
                                             nodemap[gene],
                                             nodemap[associated.identifier])
            for associated in self.gene_complexes[gene].links["gc"]:
                num += 1
                Network.create_sbml_reaction(model, 'r' + str(num),
                                             nodemap[gene],
                                             nodemap[associated.identifier])

        return SBMLWriter().writeSBML(sbml, file_path)