| 
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
 | 
| 
 | 
   126             valMax=float((upper_bound)*scaling_factor)
 | 
| 
 | 
   127             valMin=float((lower_bound)*scaling_factor)
 | 
| 
 | 
   128             if upper_bound!=0 and lower_bound==0:
 | 
| 
 | 
   129                 model.reactions.get_by_id(reaction).upper_bound=valMax
 | 
| 
 | 
   130             if upper_bound==0 and lower_bound!=0:
 | 
| 
 | 
   131                 model.reactions.get_by_id(reaction).lower_bound=valMin
 | 
| 
 | 
   132             if upper_bound!=0 and lower_bound!=0:
 | 
| 
 | 
   133                 model.reactions.get_by_id(reaction).lower_bound=valMin
 | 
| 
 | 
   134                 model.reactions.get_by_id(reaction).upper_bound=valMax
 | 
| 
 | 
   135     pass
 | 
| 
4
 | 
   136 
 | 
| 
 | 
   137 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder):
 | 
| 
 | 
   138     """
 | 
| 
 | 
   139     Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
 | 
| 
 | 
   140 
 | 
| 
 | 
   141     Args:
 | 
| 
 | 
   142         cellName (str): The name of the RAS cell (used for naming the output file).
 | 
| 
 | 
   143         ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
 | 
| 
 | 
   144         model (cobra.Model): The metabolic model to be modified.
 | 
| 
 | 
   145         rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
 | 
| 
 | 
   146         output_folder (str): Folder path where the output CSV file will be saved.
 | 
| 
 | 
   147     
 | 
| 
 | 
   148     Returns:
 | 
| 
 | 
   149         None
 | 
| 
 | 
   150     """
 | 
| 
 | 
   151     model_new = model.copy()
 | 
| 
 | 
   152     apply_ras_bounds(model_new, ras_row, rxns_ids)
 | 
| 
 | 
   153     bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model_new.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
 | 
| 
 | 
   154     bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
 | 
| 
48
 | 
   155     pass
 | 
| 
4
 | 
   156 
 | 
| 
 | 
   157 def generate_bounds(model: cobra.Model, medium: dict, ras=None, output_folder='output/') -> pd.DataFrame:
 | 
| 
 | 
   158     """
 | 
| 
 | 
   159     Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
 | 
| 
 | 
   160     
 | 
| 
 | 
   161     Args:
 | 
| 
 | 
   162         model (cobra.Model): The metabolic model for which bounds will be generated.
 | 
| 
 | 
   163         medium (dict): A dictionary where keys are reaction IDs and values are the medium conditions.
 | 
| 
48
 | 
   164         ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
 | 
| 
4
 | 
   165         output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
 | 
| 
 | 
   166 
 | 
| 
 | 
   167     Returns:
 | 
| 
 | 
   168         pd.DataFrame: DataFrame containing the bounds of reactions in the model.
 | 
| 
 | 
   169     """
 | 
| 
 | 
   170     rxns_ids = [rxn.id for rxn in model.reactions]
 | 
| 
 | 
   171     
 | 
| 
 | 
   172     # Set medium conditions
 | 
| 
 | 
   173     for reaction, value in medium.items():
 | 
| 
 | 
   174         if value is not None:
 | 
| 
 | 
   175             model.reactions.get_by_id(reaction).lower_bound = -float(value)
 | 
| 
 | 
   176     
 | 
| 
 | 
   177     # Perform Flux Variability Analysis (FVA)
 | 
| 
 | 
   178     df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
 | 
| 
 | 
   179     
 | 
| 
 | 
   180     # Set FVA bounds
 | 
| 
 | 
   181     for reaction in rxns_ids:
 | 
| 
 | 
   182         rxn = model.reactions.get_by_id(reaction)
 | 
| 
 | 
   183         rxn.lower_bound = float(df_FVA.loc[reaction, "minimum"])
 | 
| 
 | 
   184         rxn.upper_bound = float(df_FVA.loc[reaction, "maximum"])
 | 
| 
 | 
   185 
 | 
| 
 | 
   186     if ras is not None:
 | 
| 
 | 
   187         Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(cellName, ras_row, model, rxns_ids, output_folder) for cellName, ras_row in ras.iterrows())
 | 
| 
 | 
   188     else:
 | 
| 
 | 
   189         model_new = model.copy()
 | 
| 
 | 
   190         apply_ras_bounds(model_new, pd.Series([1]*len(rxns_ids), index=rxns_ids), rxns_ids)
 | 
| 
 | 
   191         bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model_new.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
 | 
| 
 | 
   192         bounds.to_csv(output_folder + "bounds.csv", sep='\t', index=True)
 | 
| 
48
 | 
   193     pass
 | 
| 
 | 
   194 
 | 
| 
4
 | 
   195 
 | 
| 
 | 
   196 
 | 
| 
 | 
   197 ############################# main ###########################################
 | 
| 
 | 
   198 def main() -> None:
 | 
| 
 | 
   199     """
 | 
| 
 | 
   200     Initializes everything and sets the program in motion based on the fronted input arguments.
 | 
| 
 | 
   201 
 | 
| 
 | 
   202     Returns:
 | 
| 
 | 
   203         None
 | 
| 
 | 
   204     """
 | 
| 
 | 
   205     if not os.path.exists('ras_to_bounds'):
 | 
| 
 | 
   206         os.makedirs('ras_to_bounds')
 | 
| 
 | 
   207 
 | 
| 
 | 
   208 
 | 
| 
 | 
   209     global ARGS
 | 
| 
 | 
   210     ARGS = process_args(sys.argv)
 | 
| 
 | 
   211 
 | 
| 
 | 
   212     ARGS.output_folder = 'ras_to_bounds/'
 | 
| 
 | 
   213 
 | 
| 
 | 
   214     if(ARGS.ras_selector == True):
 | 
| 
54
 | 
   215         ras_file_list = ARGS.input_ras.split(",")
 | 
| 
60
 | 
   216         ras_class_names = []
 | 
| 
 | 
   217         for file in ras_file_list:
 | 
| 
 | 
   218             ras_class_names.append(file.split(".")[0])
 | 
| 
48
 | 
   219         ras_list = []
 | 
| 
 | 
   220         class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
 | 
| 
56
 | 
   221         for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
 | 
| 
48
 | 
   222             ras = read_dataset(ras_matrix, "ras dataset")
 | 
| 
 | 
   223             ras.replace("None", None, inplace=True)
 | 
| 
 | 
   224             ras.set_index("Reactions", drop=True, inplace=True)
 | 
| 
 | 
   225             ras = ras.T
 | 
| 
 | 
   226             ras = ras.astype(float)
 | 
| 
 | 
   227             ras_list.append(ras)
 | 
| 
 | 
   228             for patient_id in ras.index:
 | 
| 
61
 | 
   229                 class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
 | 
| 
58
 | 
   230         
 | 
| 
48
 | 
   231         
 | 
| 
 | 
   232         # Concatenate all ras DataFrames into a single DataFrame
 | 
| 
 | 
   233         ras_combined = pd.concat(ras_list, axis=1)
 | 
| 
 | 
   234         # Normalize the RAS values by max RAS
 | 
| 
 | 
   235         ras_combined = ras_combined.div(ras_combined.max(axis=0))
 | 
| 
 | 
   236         ras_combined = ras_combined.fillna(0)
 | 
| 
 | 
   237 
 | 
| 
 | 
   238 
 | 
| 
4
 | 
   239     
 | 
| 
 | 
   240     model_type :utils.Model = ARGS.model_selector
 | 
| 
 | 
   241     if model_type is utils.Model.Custom:
 | 
| 
 | 
   242         model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(ARGS.model), customExtension = utils.FilePath.fromStrPath(ARGS.model_name).ext)
 | 
| 
 | 
   243     else:
 | 
| 
 | 
   244         model = model_type.getCOBRAmodel(toolDir=ARGS.tool_dir)
 | 
| 
 | 
   245 
 | 
| 
 | 
   246     if(ARGS.medium_selector == "Custom"):
 | 
| 
 | 
   247         medium = read_dataset(ARGS.medium, "medium dataset")
 | 
| 
 | 
   248         medium.set_index(medium.columns[0], inplace=True)
 | 
| 
 | 
   249         medium = medium.astype(float)
 | 
| 
 | 
   250         medium = medium[medium.columns[0]].to_dict()
 | 
| 
 | 
   251     else:
 | 
| 
 | 
   252         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
 | 
| 
 | 
   253         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
 | 
| 
 | 
   254         medium = df_mediums[[ARGS.medium_selector]]
 | 
| 
 | 
   255         medium = medium[ARGS.medium_selector].to_dict()
 | 
| 
 | 
   256 
 | 
| 
 | 
   257     if(ARGS.ras_selector == True):
 | 
| 
48
 | 
   258         generate_bounds(model, medium, ras = ras_combined, output_folder=ARGS.output_folder)
 | 
| 
 | 
   259         if(len(ras_list)>1):
 | 
| 
 | 
   260             class_assignments.to_csv(ARGS.cell_class, sep = '\t', index = False)
 | 
| 
4
 | 
   261     else:
 | 
| 
 | 
   262         generate_bounds(model, medium, output_folder=ARGS.output_folder)
 | 
| 
 | 
   263 
 | 
| 
 | 
   264     pass
 | 
| 
 | 
   265         
 | 
| 
 | 
   266 ##############################################################################
 | 
| 
 | 
   267 if __name__ == "__main__":
 | 
| 
 | 
   268     main() |