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