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