| 
93
 | 
     1 import argparse
 | 
| 
 | 
     2 import utils.general_utils as utils
 | 
| 
 | 
     3 from typing import Optional, List
 | 
| 
 | 
     4 import os
 | 
| 
 | 
     5 import numpy as np
 | 
| 
 | 
     6 import pandas as pd
 | 
| 
 | 
     7 import cobra
 | 
| 
 | 
     8 import sys
 | 
| 
 | 
     9 import csv
 | 
| 
 | 
    10 from joblib import Parallel, delayed, cpu_count
 | 
| 
 | 
    11 
 | 
| 
 | 
    12 ################################# process args ###############################
 | 
| 
 | 
    13 def process_args(args :List[str]) -> argparse.Namespace:
 | 
| 
 | 
    14     """
 | 
| 
 | 
    15     Processes command-line arguments.
 | 
| 
 | 
    16 
 | 
| 
 | 
    17     Args:
 | 
| 
 | 
    18         args (list): List of command-line arguments.
 | 
| 
 | 
    19 
 | 
| 
 | 
    20     Returns:
 | 
| 
 | 
    21         Namespace: An object containing parsed arguments.
 | 
| 
 | 
    22     """
 | 
| 
 | 
    23     parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
 | 
| 
 | 
    24                                      description = 'process some value\'s')
 | 
| 
 | 
    25     
 | 
| 
 | 
    26     parser.add_argument(
 | 
| 
 | 
    27         '-ms', '--model_selector', 
 | 
| 
 | 
    28         type = utils.Model, default = utils.Model.ENGRO2, choices = [utils.Model.ENGRO2, utils.Model.Custom],
 | 
| 
 | 
    29         help = 'chose which type of model you want use')
 | 
| 
 | 
    30     
 | 
| 
 | 
    31     parser.add_argument("-mo", "--model", type = str,
 | 
| 
 | 
    32         help = "path to input file with custom rules, if provided")
 | 
| 
 | 
    33     
 | 
| 
 | 
    34     parser.add_argument("-mn", "--model_name", type = str, help = "custom mode name")
 | 
| 
 | 
    35 
 | 
| 
 | 
    36     parser.add_argument(
 | 
| 
 | 
    37         '-mes', '--medium_selector', 
 | 
| 
 | 
    38         default = "allOpen",
 | 
| 
 | 
    39         help = 'chose which type of medium you want use')
 | 
| 
 | 
    40     
 | 
| 
 | 
    41     parser.add_argument("-meo", "--medium", type = str,
 | 
| 
 | 
    42         help = "path to input file with custom medium, if provided")
 | 
| 
 | 
    43 
 | 
| 
 | 
    44     parser.add_argument('-ol', '--out_log', 
 | 
| 
 | 
    45                         help = "Output log")
 | 
| 
 | 
    46     
 | 
| 
 | 
    47     parser.add_argument('-td', '--tool_dir',
 | 
| 
 | 
    48                         type = str,
 | 
| 
 | 
    49                         required = True,
 | 
| 
 | 
    50                         help = 'your tool directory')
 | 
| 
 | 
    51     
 | 
| 
 | 
    52     parser.add_argument('-ir', '--input_ras',
 | 
| 
 | 
    53                         type=str,
 | 
| 
 | 
    54                         required = False,
 | 
| 
 | 
    55                         help = 'input ras')
 | 
| 
 | 
    56     
 | 
| 
98
 | 
    57     parser.add_argument('-rn', '--name',
 | 
| 
94
 | 
    58                 type=str,
 | 
| 
 | 
    59                 help = 'ras class names')
 | 
| 
 | 
    60     
 | 
| 
93
 | 
    61     parser.add_argument('-rs', '--ras_selector',
 | 
| 
 | 
    62                         required = True,
 | 
| 
 | 
    63                         type=utils.Bool("using_RAS"),
 | 
| 
 | 
    64                         help = 'ras selector')
 | 
| 
 | 
    65 
 | 
| 
 | 
    66     parser.add_argument('-cc', '--cell_class',
 | 
| 
 | 
    67                     type = str,
 | 
| 
 | 
    68                     help = 'output of cell class')
 | 
| 
 | 
    69     
 | 
| 
94
 | 
    70     
 | 
| 
93
 | 
    71     ARGS = parser.parse_args()
 | 
| 
 | 
    72     return ARGS
 | 
| 
 | 
    73 
 | 
| 
 | 
    74 ########################### warning ###########################################
 | 
| 
 | 
    75 def warning(s :str) -> None:
 | 
| 
 | 
    76     """
 | 
| 
 | 
    77     Log a warning message to an output log file and print it to the console.
 | 
| 
 | 
    78 
 | 
| 
 | 
    79     Args:
 | 
| 
 | 
    80         s (str): The warning message to be logged and printed.
 | 
| 
 | 
    81     
 | 
| 
 | 
    82     Returns:
 | 
| 
 | 
    83       None
 | 
| 
 | 
    84     """
 | 
| 
 | 
    85     with open(ARGS.out_log, 'a') as log:
 | 
| 
 | 
    86         log.write(s + "\n\n")
 | 
| 
 | 
    87     print(s)
 | 
| 
 | 
    88 
 | 
| 
 | 
    89 ############################ dataset input ####################################
 | 
| 
 | 
    90 def read_dataset(data :str, name :str) -> pd.DataFrame:
 | 
| 
 | 
    91     """
 | 
| 
 | 
    92     Read a dataset from a CSV file and return it as a pandas DataFrame.
 | 
| 
 | 
    93 
 | 
| 
 | 
    94     Args:
 | 
| 
 | 
    95         data (str): Path to the CSV file containing the dataset.
 | 
| 
 | 
    96         name (str): Name of the dataset, used in error messages.
 | 
| 
 | 
    97 
 | 
| 
 | 
    98     Returns:
 | 
| 
 | 
    99         pandas.DataFrame: DataFrame containing the dataset.
 | 
| 
 | 
   100 
 | 
| 
 | 
   101     Raises:
 | 
| 
 | 
   102         pd.errors.EmptyDataError: If the CSV file is empty.
 | 
| 
 | 
   103         sys.exit: If the CSV file has the wrong format, the execution is aborted.
 | 
| 
 | 
   104     """
 | 
| 
 | 
   105     try:
 | 
| 
 | 
   106         dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
 | 
| 
 | 
   107     except pd.errors.EmptyDataError:
 | 
| 
 | 
   108         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   109     if len(dataset.columns) < 2:
 | 
| 
 | 
   110         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   111     return dataset
 | 
| 
 | 
   112 
 | 
| 
 | 
   113 
 | 
| 
 | 
   114 def apply_ras_bounds(model, ras_row, rxns_ids):
 | 
| 
 | 
   115     """
 | 
| 
 | 
   116     Adjust the bounds of reactions in the model based on RAS values.
 | 
| 
 | 
   117 
 | 
| 
 | 
   118     Args:
 | 
| 
 | 
   119         model (cobra.Model): The metabolic model to be modified.
 | 
| 
 | 
   120         ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
 | 
| 
 | 
   121         rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
 | 
| 
 | 
   122     
 | 
| 
 | 
   123     Returns:
 | 
| 
 | 
   124         None
 | 
| 
 | 
   125     """
 | 
| 
 | 
   126     for reaction in rxns_ids:
 | 
| 
 | 
   127         if reaction in ras_row.index:
 | 
| 
 | 
   128             scaling_factor = ras_row[reaction]
 | 
| 
 | 
   129             lower_bound=model.reactions.get_by_id(reaction).lower_bound
 | 
| 
 | 
   130             upper_bound=model.reactions.get_by_id(reaction).upper_bound
 | 
| 
 | 
   131             valMax=float((upper_bound)*scaling_factor)
 | 
| 
 | 
   132             valMin=float((lower_bound)*scaling_factor)
 | 
| 
 | 
   133             if upper_bound!=0 and lower_bound==0:
 | 
| 
 | 
   134                 model.reactions.get_by_id(reaction).upper_bound=valMax
 | 
| 
 | 
   135             if upper_bound==0 and lower_bound!=0:
 | 
| 
 | 
   136                 model.reactions.get_by_id(reaction).lower_bound=valMin
 | 
| 
 | 
   137             if upper_bound!=0 and lower_bound!=0:
 | 
| 
 | 
   138                 model.reactions.get_by_id(reaction).lower_bound=valMin
 | 
| 
 | 
   139                 model.reactions.get_by_id(reaction).upper_bound=valMax
 | 
| 
 | 
   140     pass
 | 
| 
 | 
   141 
 | 
| 
 | 
   142 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder):
 | 
| 
 | 
   143     """
 | 
| 
 | 
   144     Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
 | 
| 
 | 
   145 
 | 
| 
 | 
   146     Args:
 | 
| 
 | 
   147         cellName (str): The name of the RAS cell (used for naming the output file).
 | 
| 
 | 
   148         ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
 | 
| 
 | 
   149         model (cobra.Model): The metabolic model to be modified.
 | 
| 
 | 
   150         rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
 | 
| 
 | 
   151         output_folder (str): Folder path where the output CSV file will be saved.
 | 
| 
 | 
   152     
 | 
| 
 | 
   153     Returns:
 | 
| 
 | 
   154         None
 | 
| 
 | 
   155     """
 | 
| 
 | 
   156     model_new = model.copy()
 | 
| 
 | 
   157     apply_ras_bounds(model_new, ras_row, rxns_ids)
 | 
| 
 | 
   158     bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model_new.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
 | 
| 
 | 
   159     bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
 | 
| 
 | 
   160     pass
 | 
| 
 | 
   161 
 | 
| 
 | 
   162 def generate_bounds(model: cobra.Model, medium: dict, ras=None, output_folder='output/') -> pd.DataFrame:
 | 
| 
 | 
   163     """
 | 
| 
 | 
   164     Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
 | 
| 
 | 
   165     
 | 
| 
 | 
   166     Args:
 | 
| 
 | 
   167         model (cobra.Model): The metabolic model for which bounds will be generated.
 | 
| 
 | 
   168         medium (dict): A dictionary where keys are reaction IDs and values are the medium conditions.
 | 
| 
 | 
   169         ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
 | 
| 
 | 
   170         output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
 | 
| 
 | 
   171 
 | 
| 
 | 
   172     Returns:
 | 
| 
 | 
   173         pd.DataFrame: DataFrame containing the bounds of reactions in the model.
 | 
| 
 | 
   174     """
 | 
| 
 | 
   175     rxns_ids = [rxn.id for rxn in model.reactions]
 | 
| 
 | 
   176     
 | 
| 
 | 
   177     # Set medium conditions
 | 
| 
 | 
   178     for reaction, value in medium.items():
 | 
| 
 | 
   179         if value is not None:
 | 
| 
110
 | 
   180             warning(str(reaction) + " " + str(value))
 | 
| 
107
 | 
   181             if(reaction != "EX_thbpt_e" and reaction != "EX_lac__L_e"):
 | 
| 
 | 
   182                 model.reactions.get_by_id(reaction).lower_bound = -float(value)
 | 
| 
 | 
   183             if(reaction == "EX_lac__L_e"):
 | 
| 
 | 
   184                 model.reactions.get_by_id(reaction).lower_bound = float(0.0)
 | 
| 
 | 
   185             
 | 
| 
93
 | 
   186     
 | 
| 
 | 
   187     # Perform Flux Variability Analysis (FVA)
 | 
| 
 | 
   188     df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
 | 
| 
 | 
   189     
 | 
| 
 | 
   190     # Set FVA bounds
 | 
| 
 | 
   191     for reaction in rxns_ids:
 | 
| 
102
 | 
   192         model.reactions.get_by_id(reaction).lower_bound = float(df_FVA.loc[reaction, "minimum"])
 | 
| 
 | 
   193         model.reactions.get_by_id(reaction).upper_bound = float(df_FVA.loc[reaction, "maximum"])
 | 
| 
93
 | 
   194 
 | 
| 
 | 
   195     if ras is not None:
 | 
| 
106
 | 
   196         #Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(cellName, ras_row, model, rxns_ids, output_folder) for cellName, ras_row in ras.iterrows())
 | 
| 
 | 
   197         for cellName, ras_row in ras.iterrows():
 | 
| 
 | 
   198             process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder)
 | 
| 
107
 | 
   199             break #just one cell for testing
 | 
| 
93
 | 
   200     else:
 | 
| 
 | 
   201         model_new = model.copy()
 | 
| 
 | 
   202         apply_ras_bounds(model_new, pd.Series([1]*len(rxns_ids), index=rxns_ids), rxns_ids)
 | 
| 
 | 
   203         bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model_new.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
 | 
| 
 | 
   204         bounds.to_csv(output_folder + "bounds.csv", sep='\t', index=True)
 | 
| 
 | 
   205     pass
 | 
| 
 | 
   206 
 | 
| 
 | 
   207 
 | 
| 
 | 
   208 
 | 
| 
 | 
   209 ############################# main ###########################################
 | 
| 
 | 
   210 def main() -> None:
 | 
| 
 | 
   211     """
 | 
| 
 | 
   212     Initializes everything and sets the program in motion based on the fronted input arguments.
 | 
| 
 | 
   213 
 | 
| 
 | 
   214     Returns:
 | 
| 
 | 
   215         None
 | 
| 
 | 
   216     """
 | 
| 
 | 
   217     if not os.path.exists('ras_to_bounds'):
 | 
| 
 | 
   218         os.makedirs('ras_to_bounds')
 | 
| 
 | 
   219 
 | 
| 
 | 
   220 
 | 
| 
 | 
   221     global ARGS
 | 
| 
 | 
   222     ARGS = process_args(sys.argv)
 | 
| 
 | 
   223 
 | 
| 
 | 
   224     ARGS.output_folder = 'ras_to_bounds/'
 | 
| 
 | 
   225 
 | 
| 
 | 
   226     if(ARGS.ras_selector == True):
 | 
| 
 | 
   227         ras_file_list = ARGS.input_ras.split(",")
 | 
| 
98
 | 
   228         ras_file_names = ARGS.name.split(",")
 | 
| 
94
 | 
   229         ras_class_names = []
 | 
| 
 | 
   230         for file in ras_file_names:
 | 
| 
 | 
   231             ras_class_names.append(file.split(".")[0])
 | 
| 
93
 | 
   232         ras_list = []
 | 
| 
 | 
   233         class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
 | 
| 
 | 
   234         for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
 | 
| 
 | 
   235             ras = read_dataset(ras_matrix, "ras dataset")
 | 
| 
 | 
   236             ras.replace("None", None, inplace=True)
 | 
| 
 | 
   237             ras.set_index("Reactions", drop=True, inplace=True)
 | 
| 
 | 
   238             ras = ras.T
 | 
| 
 | 
   239             ras = ras.astype(float)
 | 
| 
 | 
   240             ras_list.append(ras)
 | 
| 
 | 
   241             for patient_id in ras.index:
 | 
| 
94
 | 
   242                 class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
 | 
| 
 | 
   243         
 | 
| 
93
 | 
   244         
 | 
| 
 | 
   245         # Concatenate all ras DataFrames into a single DataFrame
 | 
| 
94
 | 
   246         ras_combined = pd.concat(ras_list, axis=0)
 | 
| 
93
 | 
   247         # Normalize the RAS values by max RAS
 | 
| 
 | 
   248         ras_combined = ras_combined.div(ras_combined.max(axis=0))
 | 
| 
 | 
   249         ras_combined = ras_combined.fillna(0)
 | 
| 
 | 
   250 
 | 
| 
 | 
   251 
 | 
| 
 | 
   252     
 | 
| 
 | 
   253     model_type :utils.Model = ARGS.model_selector
 | 
| 
 | 
   254     if model_type is utils.Model.Custom:
 | 
| 
 | 
   255         model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(ARGS.model), customExtension = utils.FilePath.fromStrPath(ARGS.model_name).ext)
 | 
| 
 | 
   256     else:
 | 
| 
 | 
   257         model = model_type.getCOBRAmodel(toolDir=ARGS.tool_dir)
 | 
| 
 | 
   258 
 | 
| 
 | 
   259     if(ARGS.medium_selector == "Custom"):
 | 
| 
 | 
   260         medium = read_dataset(ARGS.medium, "medium dataset")
 | 
| 
 | 
   261         medium.set_index(medium.columns[0], inplace=True)
 | 
| 
 | 
   262         medium = medium.astype(float)
 | 
| 
 | 
   263         medium = medium[medium.columns[0]].to_dict()
 | 
| 
 | 
   264     else:
 | 
| 
 | 
   265         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
 | 
| 
 | 
   266         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
 | 
| 
 | 
   267         medium = df_mediums[[ARGS.medium_selector]]
 | 
| 
 | 
   268         medium = medium[ARGS.medium_selector].to_dict()
 | 
| 
 | 
   269 
 | 
| 
 | 
   270     if(ARGS.ras_selector == True):
 | 
| 
 | 
   271         generate_bounds(model, medium, ras = ras_combined, output_folder=ARGS.output_folder)
 | 
| 
94
 | 
   272         class_assignments.to_csv(ARGS.cell_class, sep = '\t', index = False)
 | 
| 
93
 | 
   273     else:
 | 
| 
 | 
   274         generate_bounds(model, medium, output_folder=ARGS.output_folder)
 | 
| 
 | 
   275 
 | 
| 
 | 
   276     pass
 | 
| 
 | 
   277         
 | 
| 
 | 
   278 ##############################################################################
 | 
| 
 | 
   279 if __name__ == "__main__":
 | 
| 
 | 
   280     main() |