<commit_before>from os.path import isfile
import csv
import re
from warnings import warn
try:
    from cPickle import load, dump
except ImportError:
    from pickle import load, dump
# Because OrderedDict is not implemented on all systems
try:
    from collections import OrderedDict as _dicttype
except ImportError:
    _dicttype = dict
from numpy import array as _array, object as _object
from scipy.io import loadmat as _loadmat, savemat as _savemat
from scipy.sparse import coo_matrix as _coo_matrix
import cobra
from cobra.io.sbml import create_cobra_model_from_sbml_file as _sbml_import


# function to help translate an array to a MATLAB cell array
_cell = lambda x: _array(x, dtype=_object)


def load_pickle(pickle_file):
    """Read in a pickle file.

    Parameters
    ----------
    pickle_file : str
        The path to the pickle to load.

    Returns
    -------
    contents : the contents of the pickle

    """
    # if the user does not add the .pickle extension
    if not isfile(pickle_file) and not pickle_file.endswith(".pickle") \
            and isfile("pickle_file" + ".pickle"):
        pickle_file += ".pickle"
    with open(pickle_file, "rb") as infile:
        contents = load(infile)
    return contents


def export_flux_distribution(model, filepath):
    """Export flux distribution to import into Simpheny.

    Parameters
    ----------
    model : cobra.Model
    filepath: str

    """
    from simphenyMapping import mapping
    outfile = open(filepath, "w")
    outcsv = csv.writer(outfile, delimiter="\t", lineterminator="\n")
    outcsv.writerow(["Reaction Number", "Flux Value",
                     "Lower Bound", "Upper Bound"])
    for reaction_name, reaction_flux in model.solution.x_dict.iteritems():
        reaction = model.reactions.get_by_id(reaction_name)
        try:
            outcsv.writerow([mapping[reaction_name], reaction_flux,
                reaction.lower_bound, reaction.upper_bound])
        except KeyError, e:
            print "Simpheny id number not found for", e
    outfile.close()


def load_matlab_model(infile_path, variable_name=None):
    """Load a cobra model stored as a .mat file
    NOTE: INCOMPLETE, does not load GPR's

    Parameters
    ----------
    infile_path : str
    variable_name : str, optional
        The variable name of the model in the .mat file. If this is not
        specified, then the first MATLAB variable which looks like a COBRA
        model will be used

    """
    data = _loadmat(infile_path)
    if variable_name is not None:
        possible_names = [variable_name]
    else:
        # will try all of the variables in the dict
        possible_names = {}
        for key in data.keys():
            possible_names[key] = None
        # skip meta variables
        to_remove = ["__globals__", "__header__", "__version__"]
        to_pop = []
        for name in possible_names:
            if name in to_remove:
                to_pop.append(name)
        for i in to_pop:
            possible_names.pop(i)
        possible_names = possible_names.keys()
    for possible_name in possible_names:
        m = data[possible_name]  # TODO: generalize
        if not set(["rxns", "mets", "S", "lb", "ub"]) \
                <= set(m.dtype.names):
            continue
        model = cobra.Model()
        model.id = m["description"][0, 0][0]
        model.description = model.id
        for i, name in enumerate(m["mets"][0, 0]):
            new_metabolite = cobra.Metabolite()
            new_metabolite.id = name[0][0]#.encode("ascii", "replace")
            new_metabolite.name = m["metNames"][0, 0][i][0][0]
            new_metabolite.formula = m["metFormulas"][0][0][i][0][0]
            model.add_metabolites([new_metabolite])
        for i, name in enumerate(m["rxns"][0, 0]):
            new_reaction = cobra.Reaction()
            new_reaction.id = name[0][0]#.encode("ascii", "replace")
            new_reaction.name = m["rxnNames"][0, 0][i][0][0]
            new_reaction.lower_bound = m["lb"][0, 0][i][0]
            new_reaction.upper_bound = m["ub"][0, 0][i][0]<commit_msg>bug where legacyIO unnecessarily requires libsbml to be installed<commit_after>from os.path import isfile
import csv
import re
from warnings import warn
try:
    from cPickle import load, dump
except ImportError:
    from pickle import load, dump
# Because OrderedDict is not implemented on all systems
try:
    from collections import OrderedDict as _dicttype
except ImportError:
    _dicttype = dict
from numpy import array as _array, object as _object
from scipy.io import loadmat as _loadmat, savemat as _savemat
from scipy.sparse import coo_matrix as _coo_matrix
import cobra
try:
    from cobra.io.sbml import create_cobra_model_from_sbml_file as _sbml_import
except ImportError:
    _sbml_import = None


# function to help translate an array to a MATLAB cell array
_cell = lambda x: _array(x, dtype=_object)


def load_pickle(pickle_file):
    """Read in a pickle file.

    Parameters
    ----------
    pickle_file : str
        The path to the pickle to load.

    Returns
    -------
    contents : the contents of the pickle

    """
    # if the user does not add the .pickle extension
    if not isfile(pickle_file) and not pickle_file.endswith(".pickle") \
            and isfile("pickle_file" + ".pickle"):
        pickle_file += ".pickle"
    with open(pickle_file, "rb") as infile:
        contents = load(infile)
    return contents


def export_flux_distribution(model, filepath):
    """Export flux distribution to import into Simpheny.

    Parameters
    ----------
    model : cobra.Model
    filepath: str

    """
    from simphenyMapping import mapping
    outfile = open(filepath, "w")
    outcsv = csv.writer(outfile, delimiter="\t", lineterminator="\n")
    outcsv.writerow(["Reaction Number", "Flux Value",
                     "Lower Bound", "Upper Bound"])
    for reaction_name, reaction_flux in model.solution.x_dict.iteritems():
        reaction = model.reactions.get_by_id(reaction_name)
        try:
            outcsv.writerow([mapping[reaction_name], reaction_flux,
                reaction.lower_bound, reaction.upper_bound])
        except KeyError, e:
            print "Simpheny id number not found for", e
    outfile.close()


def load_matlab_model(infile_path, variable_name=None):
    """Load a cobra model stored as a .mat file
    NOTE: INCOMPLETE, does not load GPR's

    Parameters
    ----------
    infile_path : str
    variable_name : str, optional
        The variable name of the model in the .mat file. If this is not
        specified, then the first MATLAB variable which looks like a COBRA
        model will be used

    """
    data = _loadmat(infile_path)
    if variable_name is not None:
        possible_names = [variable_name]
    else:
        # will try all of the variables in the dict
        possible_names = {}
        for key in data.keys():
            possible_names[key] = None
        # skip meta variables
        to_remove = ["__globals__", "__header__", "__version__"]
        to_pop = []
        for name in possible_names:
            if name in to_remove:
                to_pop.append(name)
        for i in to_pop:
            possible_names.pop(i)
        possible_names = possible_names.keys()
    for possible_name in possible_names:
        m = data[possible_name]  # TODO: generalize
        if m.dtype.names is None:
            continue
        if not set(["rxns", "mets", "S", "lb", "ub"]) \
                <= set(m.dtype.names):
            continue
        model = cobra.Model()
        model.id = m["description"][0, 0][0]
        model.description = model.id
        for i, name in enumerate(m["mets"][0, 0]):
            new_metabolite = cobra.Metabolite()
            new_metabolite.id = name[0][0]#.encode("ascii", "replace")
            new_metabolite.name = m["metNames"][0, 0][i][0][0]
            try:
                new_metabolite.formula = m["metFormulas"][0][0][i][0][0]
            except:
                pass
            model.add_metabolites([new_metabolite])
        for i, name in enumerate(m["rxns"][0, 0]):
            new_reaction = cobra.Reaction()
            new_reaction.id = name[0][0]#.encode("ascii", "replace")
            new_reaction.name = m["rxnNames"][0, 0][i][0][0]
            new_reaction.lower_bound = m["lb"][0, 0][i][0]
            new_reaction.upper_bound = m["ub"][0, 0][i][0]
{'fraction_non_alphanumeric': 0.10715134236160609, 'fraction_numerical': 0.00688999762413875, 'mean_word_length': 2.4803637866887143, 'pattern_counts': {'":': 0, '<': 5, '<?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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5965460', 'n_tokens_mistral': 2658, 'n_tokens_neox': 2542, 'n_words': 754}