<commit_before>#cobra/sbml.py: Tools for reading / writing SBML now contained in
#this module
#System modules
from .. import Model, Reaction, Metabolite
from os.path import isfile
from os import name as __name
from warnings import warn
import re
from math import isnan, isinf

from six import iteritems

#
if __name == 'java':
    from org.sbml.jsbml import SBMLDocument, SpeciesReference, KineticLaw, Parameter
    from org.sbml.jsbml import SBMLReader, SBMLWriter
    __tmp_reader = SBMLReader()
    __tmp_writer = SBMLWriter()
    readSBML = __tmp_reader.readSBMLFromFile
    writeSBML = __tmp_writer.writeSBMLToFile
    from org.sbml.jsbml.Unit import Kind as __Kind
    UNIT_KIND_MOLE = __Kind.MOLE
    UNIT_KIND_GRAM = __Kind.GRAM
    UNIT_KIND_SECOND = __Kind.SECOND
    UNIT_KIND_DIMENSIONLESS = __Kind.DIMENSIONLESS
else:
    from libsbml import SBMLDocument, SpeciesReference, KineticLaw, Parameter
    from libsbml import readSBML, writeSBML
    from libsbml import UNIT_KIND_MOLE, UNIT_KIND_GRAM, UNIT_KIND_SECOND, UNIT_KIND_DIMENSIONLESS
def parse_legacy_id(the_id, the_compartment=None, the_type='metabolite',
                    use_hyphens=False):
    """Deals with a bunch of problems due to bigg.ucsd.edu not following SBML standards

    the_id: String.

    the_compartment: String.

    the_type: String.  Currently only 'metabolite' is supported

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens
    
    """
    if use_hyphens:
        the_id = the_id.replace('__','-')
    if the_type == 'metabolite':
        if the_id.split('_')[-1] == the_compartment:
            #Reformat Ids to match convention in Palsson Lab.
            the_id = the_id[:-len(the_compartment)-1]
        the_id += '[%s]'%the_compartment
    return the_id
def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_metabolite=False,
                                      print_time=False, use_hyphens=False):
    """convert an SBML XML file into a cobra.Model object.  Supports
    SBML Level 2 Versions 1 and 4.  The function will detect if the SBML fbc package is used in the file
    and run the converter if the fbc package is used.

    sbml_filename: String.

    old_sbml:  Boolean. Set to True if the XML file has metabolite
    formula appended to metabolite names.  This was a poorly designed
    artifact that persists in some models.

    legacy_metabolite: Boolean.  If True then assume that the metabolite id has
    the compartment id appended after an underscore (e.g. _c for cytosol).  This
    has not been implemented but will be soon.

    print_time: deprecated

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens

    """
    __default_lower_bound = -1000
    __default_upper_bound = 1000
    __default_objective_coefficient = 0
     # Ensure that the file exists
    if not isfile(sbml_filename):
        raise IOError('Your SBML file is not found: %s'%sbml_filename)
    #Expressions to change SBML Ids to Palsson Lab Ids
    metabolite_re = re.compile('^M_')
    reaction_re = re.compile('^R_')
    compartment_re = re.compile('^C_')
    if print_time:
        warn("print_time is deprecated")
    model_doc = readSBML(sbml_filename)
    if (model_doc.getPlugin("fbc") != None):
        from libsbml import ConversionProperties, LIBSBML_OPERATION_SUCCESS
        conversion_properties = ConversionProperties()
        conversion_properties.addOption("convert fbc to cobra", True, "Convert FBC model to Cobra model")
        result = model_doc.convert(conversion_properties)
        if result != LIBSBML_OPERATION_SUCCESS:
            raise(Exception("Conversion of SBML+fbc to COBRA failed"))
    sbml_model = model_doc.getModel()
    sbml_model_id = sbml_model.getId()
    sbml_species = sbml_model.getListOfSpecies()
    sbml_reactions = sbml_model.getListOfReactions()
    sbml_compartments = sbml_model.getListOfCompartments()
    compartment_dict = dict([(compartment_re.split(x.getId())[-1], x.getName())
                             for x in sbml_compartments])
    if legacy_metabolite:
        #Deal with the palsson lab appending the compartment id to the metabolite id
        new_dict = {}
        for the_id, the_name in compartment_dict.items():
            if the_name == '':
                new_dict[the_id[0].lower()] = the_id
            else:
                new_dict[the_id] = the_name
        compartment_dict = new_dict
        legacy_compartment_converter = dict([(v,k)
                                             for k, v in compartment_dict.items()])

    cobra_model = Model(sbml_model_id)
    metabolites = []
    metabolite_dict = {}
    #Convert sbml_metabolites to cobra.Metabolites
    for sbml_metabolite in sbml_species:
        #Skip sbml boundary species
        if sbml_metabolite.getBoundaryCondition():
            continue

        if (old_sbml or legacy_metabolite) and \
               sbml_metabolite.getId().endswith('_b'):
            #Deal with incorrect sbml from bigg.ucsd.edu
            continue
        tmp_metabolite = Metabolite()
        metabolite_id = tmp_metabolite.id = sbml_metabolite.getId()
        tmp_metabolite.compartment = compartment_re.split(sbml_metabolite.getCompartment())[-1]
        if legacy_metabolite:
            if tmp_metabolite.compartment not in compartment_dict:
                tmp_metabolite.compartment = legacy_compartment_converter[tmp_metabolite.compartment]
            tmp_metabolite.id = parse_legacy_id(tmp_metabolite.id, tmp_metabolite.compartment,
                                                use_hyphens=use_hyphens)
        if use_hyphens:
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('__','-')
        else:
            #Just in case the SBML ids are ill-formed and use -
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('-','__')
        tmp_metabolite.name = sbml_metabolite.getName()
        tmp_formula = ''
        tmp_metabolite.notes = parse_legacy_sbml_notes(sbml_metabolite.getNotesString())
        if sbml_metabolite.isSetCharge():
            tmp_metabolite.charge = sbml_metabolite.getCharge()
        if "CHARGE" in tmp_metabolite.notes:
            note_charge = tmp_metabolite.notes["CHARGE"][0]
            try:
                note_charge = float(note_charge)
                if note_charge == int(note_charge):
                    note_charge = int(note_charge)
            except:
                warn("charge of %s is not a number (%s)" % (tmp_metabolite.id, str(note_charge)))
            else:
                if tmp_metabolite.charge is None or tmp_metabolite.charge == note_charge:
                    tmp_metabolite.notes.pop("CHARGE")
                else:  # tmp_metabolite.charge != note_charge
                    msg = "different charges specified for %s (%d and %d)"
                    msg = msg % (tmp_metabolite.id, tmp_metabolite.charge, note_charge)
                    warn(msg)

        for the_key in tmp_metabolite.notes.keys():
            if the_key.lower() == 'formula':
                tmp_formula = tmp_metabolite.notes.pop(the_key)[0]
                break
        if tmp_formula == '' and old_sbml:
            tmp_formula = tmp_metabolite.name.split('_')[-1]
            tmp_metabolite.name = tmp_metabolite.name[:-len(tmp_formula)-1]
        tmp_metabolite.formula = tmp_formula
        metabolite_dict.update({metabolite_id: tmp_metabolite})
        metabolites.append(tmp_metabolite)
    cobra_model.add_metabolites(metabolites)

    #Construct the vectors and matrices for holding connectivity and numerical info
    #to feed to the cobra toolbox.
    #Always assume steady state simulations so b is set to 0
    cobra_reaction_list = []
    for sbml_reaction in sbml_reactions:
        if use_hyphens:
            #Change the ids to match conventions used by the Palsson lab.
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('__','-'))
        else:
            #Just in case the SBML ids are ill-formed and use -
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('-','__'))
        cobra_reaction_list.append(reaction)
        #reaction.exchange_reaction = 0<commit_msg>sbml2 conflicting charge precedence chagned<commit_after>#cobra/sbml.py: Tools for reading / writing SBML now contained in
#this module
#System modules
from .. import Model, Reaction, Metabolite
from os.path import isfile
from os import name as __name
from warnings import warn
import re
from math import isnan, isinf

from six import iteritems

#
if __name == 'java':
    from org.sbml.jsbml import SBMLDocument, SpeciesReference, KineticLaw, Parameter
    from org.sbml.jsbml import SBMLReader, SBMLWriter
    __tmp_reader = SBMLReader()
    __tmp_writer = SBMLWriter()
    readSBML = __tmp_reader.readSBMLFromFile
    writeSBML = __tmp_writer.writeSBMLToFile
    from org.sbml.jsbml.Unit import Kind as __Kind
    UNIT_KIND_MOLE = __Kind.MOLE
    UNIT_KIND_GRAM = __Kind.GRAM
    UNIT_KIND_SECOND = __Kind.SECOND
    UNIT_KIND_DIMENSIONLESS = __Kind.DIMENSIONLESS
else:
    from libsbml import SBMLDocument, SpeciesReference, KineticLaw, Parameter
    from libsbml import readSBML, writeSBML
    from libsbml import UNIT_KIND_MOLE, UNIT_KIND_GRAM, UNIT_KIND_SECOND, UNIT_KIND_DIMENSIONLESS
def parse_legacy_id(the_id, the_compartment=None, the_type='metabolite',
                    use_hyphens=False):
    """Deals with a bunch of problems due to bigg.ucsd.edu not following SBML standards

    the_id: String.

    the_compartment: String.

    the_type: String.  Currently only 'metabolite' is supported

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens
    
    """
    if use_hyphens:
        the_id = the_id.replace('__','-')
    if the_type == 'metabolite':
        if the_id.split('_')[-1] == the_compartment:
            #Reformat Ids to match convention in Palsson Lab.
            the_id = the_id[:-len(the_compartment)-1]
        the_id += '[%s]'%the_compartment
    return the_id
def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_metabolite=False,
                                      print_time=False, use_hyphens=False):
    """convert an SBML XML file into a cobra.Model object.  Supports
    SBML Level 2 Versions 1 and 4.  The function will detect if the SBML fbc package is used in the file
    and run the converter if the fbc package is used.

    sbml_filename: String.

    old_sbml:  Boolean. Set to True if the XML file has metabolite
    formula appended to metabolite names.  This was a poorly designed
    artifact that persists in some models.

    legacy_metabolite: Boolean.  If True then assume that the metabolite id has
    the compartment id appended after an underscore (e.g. _c for cytosol).  This
    has not been implemented but will be soon.

    print_time: deprecated

    use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens

    """
    __default_lower_bound = -1000
    __default_upper_bound = 1000
    __default_objective_coefficient = 0
     # Ensure that the file exists
    if not isfile(sbml_filename):
        raise IOError('Your SBML file is not found: %s'%sbml_filename)
    #Expressions to change SBML Ids to Palsson Lab Ids
    metabolite_re = re.compile('^M_')
    reaction_re = re.compile('^R_')
    compartment_re = re.compile('^C_')
    if print_time:
        warn("print_time is deprecated")
    model_doc = readSBML(sbml_filename)
    if (model_doc.getPlugin("fbc") != None):
        from libsbml import ConversionProperties, LIBSBML_OPERATION_SUCCESS
        conversion_properties = ConversionProperties()
        conversion_properties.addOption("convert fbc to cobra", True, "Convert FBC model to Cobra model")
        result = model_doc.convert(conversion_properties)
        if result != LIBSBML_OPERATION_SUCCESS:
            raise(Exception("Conversion of SBML+fbc to COBRA failed"))
    sbml_model = model_doc.getModel()
    sbml_model_id = sbml_model.getId()
    sbml_species = sbml_model.getListOfSpecies()
    sbml_reactions = sbml_model.getListOfReactions()
    sbml_compartments = sbml_model.getListOfCompartments()
    compartment_dict = dict([(compartment_re.split(x.getId())[-1], x.getName())
                             for x in sbml_compartments])
    if legacy_metabolite:
        #Deal with the palsson lab appending the compartment id to the metabolite id
        new_dict = {}
        for the_id, the_name in compartment_dict.items():
            if the_name == '':
                new_dict[the_id[0].lower()] = the_id
            else:
                new_dict[the_id] = the_name
        compartment_dict = new_dict
        legacy_compartment_converter = dict([(v,k)
                                             for k, v in compartment_dict.items()])

    cobra_model = Model(sbml_model_id)
    metabolites = []
    metabolite_dict = {}
    #Convert sbml_metabolites to cobra.Metabolites
    for sbml_metabolite in sbml_species:
        #Skip sbml boundary species
        if sbml_metabolite.getBoundaryCondition():
            continue

        if (old_sbml or legacy_metabolite) and \
               sbml_metabolite.getId().endswith('_b'):
            #Deal with incorrect sbml from bigg.ucsd.edu
            continue
        tmp_metabolite = Metabolite()
        metabolite_id = tmp_metabolite.id = sbml_metabolite.getId()
        tmp_metabolite.compartment = compartment_re.split(sbml_metabolite.getCompartment())[-1]
        if legacy_metabolite:
            if tmp_metabolite.compartment not in compartment_dict:
                tmp_metabolite.compartment = legacy_compartment_converter[tmp_metabolite.compartment]
            tmp_metabolite.id = parse_legacy_id(tmp_metabolite.id, tmp_metabolite.compartment,
                                                use_hyphens=use_hyphens)
        if use_hyphens:
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('__','-')
        else:
            #Just in case the SBML ids are ill-formed and use -
            tmp_metabolite.id = metabolite_re.split(tmp_metabolite.id)[-1].replace('-','__')
        tmp_metabolite.name = sbml_metabolite.getName()
        tmp_formula = ''
        tmp_metabolite.notes = parse_legacy_sbml_notes(sbml_metabolite.getNotesString())
        if sbml_metabolite.isSetCharge():
            tmp_metabolite.charge = sbml_metabolite.getCharge()
        if "CHARGE" in tmp_metabolite.notes:
            note_charge = tmp_metabolite.notes["CHARGE"][0]
            try:
                note_charge = float(note_charge)
                if note_charge == int(note_charge):
                    note_charge = int(note_charge)
            except:
                warn("charge of %s is not a number (%s)" % (tmp_metabolite.id, str(note_charge)))
            else:
                if tmp_metabolite.charge is None or tmp_metabolite.charge == note_charge:
                    tmp_metabolite.notes.pop("CHARGE")
                else:  # tmp_metabolite.charge != note_charge
                    msg = "different charges specified for %s (%d and %d)"
                    msg = msg % (tmp_metabolite.id, tmp_metabolite.charge, note_charge)
                    warn(msg)
                    # Chances are a 0 note charge was written by mistake. We
                    # will default to the note_charge in this case.
                    if tmp_metabolite.charge == 0:
                        tmp_metabolite.charge = note_charge

        for the_key in tmp_metabolite.notes.keys():
            if the_key.lower() == 'formula':
                tmp_formula = tmp_metabolite.notes.pop(the_key)[0]
                break
        if tmp_formula == '' and old_sbml:
            tmp_formula = tmp_metabolite.name.split('_')[-1]
            tmp_metabolite.name = tmp_metabolite.name[:-len(tmp_formula)-1]
        tmp_metabolite.formula = tmp_formula
        metabolite_dict.update({metabolite_id: tmp_metabolite})
        metabolites.append(tmp_metabolite)
    cobra_model.add_metabolites(metabolites)

    #Construct the vectors and matrices for holding connectivity and numerical info
    #to feed to the cobra toolbox.
    #Always assume steady state simulations so b is set to 0
    cobra_reaction_list = []
    for sbml_reaction in sbml_reactions:
        if use_hyphens:
            #Change the ids to match conventions used by the Palsson lab.
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('__','-'))
        else:
            #Just in case the SBML ids are ill-formed and use -
            reaction = Reaction(reaction_re.split(sbml_reaction.getId())[-1].replace('-','__'))
        cobra_reaction_list.append(reaction)
        #reaction.exchange_reaction = 0
{'fraction_non_alphanumeric': 0.0797778040420754, 'fraction_numerical': 0.003368396170665406, 'mean_word_length': 2.6845199216198563, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6110136', 'n_tokens_mistral': 5389, 'n_tokens_neox': 5182, 'n_words': 1307}