Esempio n. 1
0
def capitulo_5():
    file = open("resultados_capitulo_5.txt", "w")
    cobra_model = cobra.test.create_test_model("textbook")
    ecoli_model = cobra.test.create_test_model("ecoli")
    file.write(str(cobra_model.optimize()))
    file.write("\n")
    with cobra_model:
        cobra_model.reactions.PFK.knock_out()
        file.write(str(cobra_model.optimize()))
        file.write("\n")
    file.write(str(cobra_model.optimize()))
    file.write("\n")
    with cobra_model:
        cobra_model.genes.b1723.knock_out()
        file.write(str(cobra_model.optimize()))
        file.write("\n")
        cobra_model.genes.b3916.knock_out()
        file.write(str(cobra_model.optimize()))
        file.write("\n")
    deletion_results = single_gene_deletion(cobra_model)
    single_gene_deletion(cobra_model, cobra_model.genes[:20])
    single_reaction_deletion(cobra_model, cobra_model.reactions[:20])
    double_gene_deletion(cobra_model,
                         cobra_model.genes[-5:],
                         return_frame=True).round(4)
    start = time()
    double_gene_deletion(ecoli_model,
                         ecoli_model.genes[:300],
                         number_of_processes=2)
    t1 = time() - start
    file.write("Double gene deletions for 200 genes completed in "
               "%.2f sec with 2 cores" % t1)
    file.write("\n")
    start = time()
    double_gene_deletion(ecoli_model,
                         ecoli_model.genes[:300],
                         number_of_processes=1)
    t2 = time() - start
    file.write("Double gene deletions for 200 genes completed in "
               "%.2f sec with 1 core" % t2)
    file.write("\n")
    file.write("Speedup of %.2fx" % (t2 / t1))
    file.write("\n")
    double_reaction_deletion(cobra_model,
                             cobra_model.reactions[2:7],
                             return_frame=True).round(4)

    file.close()
Esempio n. 2
0
def simulatingDels():
    import pandas
    from time import time
    import cobra.test
    from cobra.flux_analysis import (single_gene_deletion,
                                     single_reaction_deletion,
                                     double_gene_deletion,
                                     double_reaction_deletion)
    cobra_model = cobra.test.create_test_model("textbook")
    ecoli_model = cobra.test.create_test_model("ecoli")

    print('complete model: ', cobra_model.optimize())
    with cobra_model:
        cobra_model.reactions.PFK.knock_out()
        print('pfk knocked out: ', cobra_model.optimize())

    print('complete model: ', cobra_model.optimize())
    with cobra_model:
        cobra_model.genes.b1723.knock_out()
        print('pfkA knocked out: ', cobra_model.optimize())
        cobra_model.genes.b3916.knock_out()
        print('pfkB knocked out: ', cobra_model.optimize())

    deletion_results = single_gene_deletion(cobra_model)

    print(single_gene_deletion(cobra_model, cobra_model.genes[:20]))  #subset
    print(single_reaction_deletion(cobra_model, cobra_model.reactions[:20]))
    print('Hello world!')
Esempio n. 3
0
def list_excluded_reactions(model):
    """
	Define a list of reactions that can be knocked-out. It excludes
	exchange reactions, reactions with no genes, essential reactions and reactions
	with essential genes. Objective function is set for biomass production to study if there
	is growth after single deletion strategy
	
	Input: model,  cobrapy model structure
	
	Output: list of reactions to be knocked-out
	"""

    essential_reactions = []
    essential_genes = []
    possible_reactions = []
    possible_reactionsygenes = []
    null_genes = []
    model.objective = 'EX_biomass'
    model.reactions.EX_glyc.lower_bound = -1
    model.reactions.EX_glc.lower_bound = 0
    # #model.reactions.get_by_id('EX_o2').lower_bound=0.
    # #smodel.reactions.get_by_id('EX_o2').upper_bound=0.

    # Calculating essential reactions
    reaction = single_reaction_deletion(model, model.reactions[0:])
    for x in reaction:
        for i in range(len(reaction[x])):
            if reaction.growth[i] < 10E-06:
                essential_reactions.append(model.reactions[i])
    gene = single_gene_deletion(model,
                                model.genes[0:])  #Calculate essential genes
    for x in gene:
        for i in range(len(gene[x])):
            if gene.growth[i] < 10E-06:
                essential_genes.append(model.genes[i])

    #print(essential_reactions,essential_genes)
    for i in range(len(model.reactions)):
        if model.reactions[i] not in essential_reactions:
            possible_reactions.append(model.reactions[i])

    for i in range(len(possible_reactions)):
        if possible_reactions[i].genes != frozenset(
            []):  #checks If there is no associated gene
            if possible_reactions[
                    i].genes not in essential_genes:  # Exclude the essential genes
                possible_reactionsygenes.append(possible_reactions[i].id)

    return possible_reactionsygenes
    def reaction_deletion(self) -> pd.DataFrame:
        """Create pd.DataFramewith results of reaction deletion.

        https://cobrapy.readthedocs.io/en/latest/deletions.html
        :return: pandas.
        """
        model = self.read_model()
        df = single_reaction_deletion(model, model.reactions)
        return pd.DataFrame({
            "model": self.model_path.name,
            "objective": self.objective_id,
            "reaction": [set(ids).pop() for ids in df.ids],
            "status": df.status,
            "value": df.growth,
        })
Esempio n. 5
0
def ensemble_single_reaction_deletion(ensemble,
                                      num_models=None,
                                      specific_models=[]):
    '''
    Performs single reaction deletions on models within an ensemble and
    returns the objective value after optimization with each reaction removed.

    Parameters
    ----------
    ensemble: medusa.core.Ensemble
        The ensemble with which to perform reaction deletions
    num_models: int, optional
        Number of models for which reaction deletions will be performed. The
        number of models indicated will be randomly sampled and reaction
        deletions will be performed on the sampled models. If None, all models
        will be selected (default), or the models specified by specific_models
        will be selected. Cannot be passed concurrently with specific_models.
    specific_models: list of str, optional
        List of member.id corresponding to the models for which reaction
        deletions will be performed. If None, all models will be selected
        (default), or num_models will be randomly sampled and selected.
        Cannot be passed concurrently with num_models.

    Returns
    -------
    pandas.DataFrame
        A dataframe in which each row (index) represents a model within the
        ensemble, and each column represents a reaction for which values of
        objective when the reaction is deleted are returned.
    '''
    if not num_models:
        num_models = len(ensemble.members)

    if specific_models:
        model_list = specific_models
    else:
        model_list = sample(ensemble.members, num_models)

    deletion_results = {}
    with ensemble.base_model:
        for model in model_list:
            print('performing deletions for ' + model.id)
            ensemble.set_state(model)
            deletion_result = single_reaction_deletion(ensemble.base_model)
            deletion_results[model.id] = deletion_result

    return deletion_results
Esempio n. 6
0
def do_deletions(rxn_data,
                 model,
                 rxn_to_genes,
                 do_double_ko=False,
                 obj_fraction=0.0):
    fraction_epsilon = 0.0001
    orig_f = float(model.optimize().f)
    s_rates, s_stats = single_reaction_deletion(model,
                                                list(rxn_to_genes.keys()))
    print('Original objective %.1f; %i reactions knocked out.' %
          (orig_f, len(s_stats)))
    print('Calculating model deficiencies for each knockout...')
    for r_id, new_f in s_rates.items():
        if abs(new_f) < fraction_epsilon:
            new_f = 0.0
        stat = s_stats[r_id]
        if new_f / orig_f <= obj_fraction + fraction_epsilon:
            if stat == 'optimal':
                deficiencies = find_model_deficiencies(model, orig_f, new_f,
                                                       r_id)
            else:
                deficiencies = 'infeasible'
            rxn_data[r_id] = {
                'objective': round(new_f / orig_f * 100, 1),
                'deficiencies': deficiencies,
                'genes': rxn_to_genes[r_id]
            }
    if do_double_ko:
        double_rxn_ids = [
            r for r in list(rxn_to_genes.keys()) if r not in rxn_data
        ]
        print('Performing double knockouts on %i candidates...' %
              len(double_rxn_ids))
        double_ko_data = double_reaction_deletion(model,
                                                  double_rxn_ids[:5],
                                                  number_of_processes=3)
        d_r1, d_r2, d_rates = double_ko_data['y'], double_ko_data[
            'x'], double_ko_data['data']
Esempio n. 7
0
 def run_single_reaction_deletion(self, selected_solver):
     solution = single_reaction_deletion(self.model)
     solution.method = "single_reaction_deletion"
     self.add_solution(solution)
# Step 1: Take the model as input from the command line.

if len(argv) != 2:
    print("Please provide a genome scale model in sbml format.")
    exit(0)
    
model_name = argv[1]
#print(model_name)

# Step 2: Read in the model.

model = cobra.io.read_sbml_model(model_name)
#print(model.summary())

# Perform single reaction deletion analysis
result = single_reaction_deletion(model)
#print(result)

# Write the result to a csv file.
out_file = model_name + "_srd_result"
print(out_file)
isfile = os.path.isfile(out_file)
print(isfile)

if isfile:
    print("The result file already exists in the current directory; aborting process.")
    exit(0)
    
result.to_csv(out_file)

Esempio n. 9
0
#1. Before starting activate the cobra.py environment
#source python-virtual-environments/cobra_py/bin/activate

#2. Run the script
import cobra
import pandas

from cobra.flux_analysis import (
    single_gene_deletion, single_reaction_deletion, double_gene_deletion,
    double_reaction_deletion)

model=cobra.io.read_sbml_model('/Users/catalina/Dropbox/UVA/CareyLab/gf_no_ortho_CparvumIowaII.xml')

#3. Analysis exchange reactions one by one to see if the model is viable after their removal
print(single_reaction_deletion(model, model.exchanges[:60]))
print(single_reaction_deletion(model, model.exchanges[61:120]))
print(single_reaction_deletion(model, model.exchanges[121:180]))

#4. Analyzing single delections with the knockout option
print('complete model: ', model.optimize())
with model:
    model.reactions.PFKhc.knock_out()
    print('pyrophosphate-dependent phosphofructokinase knocked out: ', model.optimize())

#5. Analyzing doble delections with the knockout option
print('complete model: ', model.optimize())
with model:
	model.reactions.GLCt1.knock_out()
	model.reactions.EX_glc__D_e.knock_out()
	model.optimize()
Esempio n. 10
0
def singleReactionKO(model,
                     reaction_id,
                     objective_reaction,
                     exchange_prefix=None,
                     tol=1E-08):
    set_objective_function(model, reaction_id)

    initial_sol = model.optimize(objective_sense=objective_reaction)

    if not evalSol(initial_sol, tol):
        raise ValueError(
            "Objective value is zero. Model must have a valid solution objective value"
        )

    # exchange reactions to remove
    if exchange_prefix is not None:

        reactions_remove = [
            i.id for i in model.reactions if exchange_prefix in i.name
        ]

    else:

        reactions_remove = [
            i.id for i in model.reactions
            if 'Drainfor' in i.name or 'EX_' in i.id
        ]

    for i in model.exchanges:

        if i.id not in reactions_remove:
            reactions_remove.append(i.id)

    reactions_remove.append(reaction_id)

    with model as m:
        reac_list = [
            get_reaction(m, i.id) for i in m.reactions
            if i.id not in reactions_remove
        ]

    solution = single_reaction_deletion(model, reaction_list=reac_list)

    solution.iloc[:, 0] = list(map(lambda x: list(x)[0], solution.iloc[:, 0]))

    solution.loc[:, 'growth'][np.isnan(solution.loc[:, 'growth'])] = float(0)
    solution.loc[:, 'growth'] = solution.loc[:, 'growth'].apply(
        lambda x: float(abs(x)))

    sr_lethal = solution[solution.loc[:, 'growth'] <= tol]

    if sr_lethal.shape[0] == 0:
        print(reaction_id, " failed", " since there is no KO available")
        print(reaction_id, " trying exchange reactions")

        reactions_remove = [reaction_id]

        with model as m:
            reac_list = [
                get_reaction(m, i.id) for i in m.reactions
                if i.id not in reactions_remove
            ]

        solution = single_reaction_deletion(model, reaction_list=reac_list)

        solution.iloc[:,
                      0] = list(map(lambda x: list(x)[0], solution.iloc[:, 0]))

        solution.loc[:, 'growth'][np.isnan(solution.loc[:,
                                                        'growth'])] = float(0)
        solution.loc[:, 'growth'] = solution.loc[:, 'growth'].apply(
            lambda x: float(abs(x)))

        sr_lethal = solution[solution.loc[:, 'growth'] <= tol]

    if sr_lethal.shape[0] == 0:
        raise ValueError(
            "{} failed since there is no KO available".format(reaction_id))

    all_kos = list(sr_lethal.iloc[:, 0])
    random.shuffle(all_kos)

    if len(all_kos) > 5:
        # n_kos = math.ceil(len(all_kos) * 0.1)
        n_kos = 5
    else:
        n_kos = len(all_kos)

    kos = []

    for i in range(n_kos):

        ko = all_kos[i]

        with model as m:

            m.reactions.get_by_id(ko).bounds = (0.0, 0.0)

            set_objective_function(m, reaction_id)

            last_sol = m.optimize(objective_sense=objective_reaction)

            if evalSol(last_sol, tol):

                raise ValueError(
                    "{} failed since the KO {} is not lethal, "
                    "so cobrapy single reaction deletion solution is "
                    "somehow incorrect".format(reaction_id, ko))

            else:
                kos.append(ko)

    return kos, all_kos
Esempio n. 11
0
import pandas
from time import time

import cobra.test
from cobra.flux_analysis import \
    single_gene_deletion, single_reaction_deletion, \
    double_gene_deletion, double_reaction_deletion

cobra_model = cobra.test.create_test_model("textbook")
ecoli_model = cobra.test.create_test_model("ecoli")

f = open('geneDeletionOutput.txt','w')

gr, s = single_reaction_deletion(cobra_model, cobra_model.reactions[:20])
f.write(str(pandas.DataFrame.from_dict({"growth_rates" : gr, "status" : s})))
#
# gr, s  = single_gene_deletion(cobra_model, cobra_model.genes[:5])
# print(pandas.DataFrame.from_dict({"growth_rates": gr, "status": s}))
#
# gr, st = single_gene_deletion(cobra_model)
# f.write(str(pandas.DataFrame.from_dict({"growth_rates": gr,
#                             "status": st}).round(5)))
#
# gr, st = single_reaction_deletion(cobra_model)
# f.write(str(pandas.DataFrame.from_dict({"growth_rates": gr,
#                                   "status": st}).round(5)))
# f.write(str(double_gene_deletion(cobra_model,cobra_model.genes[-5:],
#                      return_frame=True)))
#
# f.write(str(double_reaction_deletion(cobra_model, cobra_model.reactions[:5],
#                                      return_frame=True).round(4)))