| 
542
 | 
     1 """
 | 
| 
 | 
     2 Apply RAS-based scaling to reaction bounds and optionally save updated models.
 | 
| 
 | 
     3 
 | 
| 
 | 
     4 Workflow:
 | 
| 
 | 
     5 - Read one or more RAS matrices (patients/samples x reactions)
 | 
| 
 | 
     6 - Normalize and merge them, optionally adding class suffixes to sample IDs
 | 
| 
 | 
     7 - Build a COBRA model from a tabular CSV
 | 
| 
 | 
     8 - Run FVA to initialize bounds, then scale per-sample based on RAS values
 | 
| 
 | 
     9 - Save bounds per sample and optionally export updated models in chosen formats
 | 
| 
 | 
    10 """
 | 
| 
 | 
    11 import argparse
 | 
| 
 | 
    12 from typing import Optional, Dict, Set, List, Tuple, Union
 | 
| 
 | 
    13 import os
 | 
| 
 | 
    14 import numpy as np
 | 
| 
 | 
    15 import pandas as pd
 | 
| 
 | 
    16 import cobra
 | 
| 
 | 
    17 from cobra import Model
 | 
| 
 | 
    18 import sys
 | 
| 
 | 
    19 from joblib import Parallel, delayed, cpu_count
 | 
| 
 | 
    20 
 | 
| 
 | 
    21 try:
 | 
| 
 | 
    22     from .utils import general_utils as utils
 | 
| 
 | 
    23     from .utils import model_utils as modelUtils
 | 
| 
 | 
    24 except:
 | 
| 
 | 
    25     import utils.general_utils as utils
 | 
| 
 | 
    26     import utils.model_utils as modelUtils
 | 
| 
 | 
    27 
 | 
| 
 | 
    28 ################################# process args ###############################
 | 
| 
 | 
    29 def process_args(args :List[str] = None) -> argparse.Namespace:
 | 
| 
 | 
    30     """
 | 
| 
 | 
    31     Processes command-line arguments.
 | 
| 
 | 
    32 
 | 
| 
 | 
    33     Args:
 | 
| 
 | 
    34         args (list): List of command-line arguments.
 | 
| 
 | 
    35 
 | 
| 
 | 
    36     Returns:
 | 
| 
 | 
    37         Namespace: An object containing parsed arguments.
 | 
| 
 | 
    38     """
 | 
| 
 | 
    39     parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
 | 
| 
 | 
    40                                      description = 'process some value\'s')
 | 
| 
 | 
    41     
 | 
| 
 | 
    42     
 | 
| 
 | 
    43     parser.add_argument("-mo", "--model_upload", type = str,
 | 
| 
 | 
    44         help = "path to input file with custom rules, if provided")
 | 
| 
 | 
    45 
 | 
| 
 | 
    46     parser.add_argument('-ol', '--out_log', 
 | 
| 
 | 
    47                         help = "Output log")
 | 
| 
 | 
    48     
 | 
| 
 | 
    49     parser.add_argument('-td', '--tool_dir',
 | 
| 
 | 
    50                         type = str,
 | 
| 
 | 
    51                         default = os.path.dirname(os.path.abspath(__file__)),
 | 
| 
 | 
    52                         help = 'your tool directory (default: auto-detected package location)')
 | 
| 
 | 
    53     
 | 
| 
 | 
    54     parser.add_argument('-ir', '--input_ras',
 | 
| 
 | 
    55                         type=str,
 | 
| 
 | 
    56                         required = False,
 | 
| 
 | 
    57                         help = 'input ras')
 | 
| 
 | 
    58     
 | 
| 
 | 
    59     parser.add_argument('-rn', '--name',
 | 
| 
 | 
    60                 type=str,
 | 
| 
 | 
    61                 help = 'ras class names')
 | 
| 
 | 
    62 
 | 
| 
 | 
    63     parser.add_argument('-cc', '--cell_class',
 | 
| 
 | 
    64                     type = str,
 | 
| 
 | 
    65                     help = 'output of cell class')
 | 
| 
 | 
    66     parser.add_argument(
 | 
| 
 | 
    67         '-idop', '--output_path', 
 | 
| 
 | 
    68         type = str,
 | 
| 
 | 
    69         default='ras_to_bounds/',
 | 
| 
 | 
    70         help = 'output path for maps')
 | 
| 
 | 
    71     
 | 
| 
 | 
    72     parser.add_argument('-sm', '--save_models',
 | 
| 
 | 
    73                     type=utils.Bool("save_models"),
 | 
| 
 | 
    74                     default=False,
 | 
| 
 | 
    75                     help = 'whether to save models with applied bounds')
 | 
| 
 | 
    76     
 | 
| 
 | 
    77     parser.add_argument('-smp', '--save_models_path',
 | 
| 
 | 
    78                         type = str,
 | 
| 
 | 
    79                         default='saved_models/',
 | 
| 
 | 
    80                         help = 'output path for saved models')
 | 
| 
 | 
    81     
 | 
| 
 | 
    82     parser.add_argument('-smf', '--save_models_format',
 | 
| 
 | 
    83                         type = str,
 | 
| 
 | 
    84                         default='csv',
 | 
| 
 | 
    85                         help = 'format for saved models (csv, xml, json, mat, yaml, tabular)')
 | 
| 
 | 
    86 
 | 
| 
 | 
    87     
 | 
| 
 | 
    88     ARGS = parser.parse_args(args)
 | 
| 
 | 
    89     return ARGS
 | 
| 
 | 
    90 
 | 
| 
 | 
    91 ########################### warning ###########################################
 | 
| 
 | 
    92 def warning(s :str) -> None:
 | 
| 
 | 
    93     """
 | 
| 
 | 
    94     Log a warning message to an output log file and print it to the console.
 | 
| 
 | 
    95 
 | 
| 
 | 
    96     Args:
 | 
| 
 | 
    97         s (str): The warning message to be logged and printed.
 | 
| 
 | 
    98     
 | 
| 
 | 
    99     Returns:
 | 
| 
 | 
   100       None
 | 
| 
 | 
   101     """
 | 
| 
 | 
   102     if ARGS.out_log:
 | 
| 
 | 
   103         with open(ARGS.out_log, 'a') as log:
 | 
| 
 | 
   104             log.write(s + "\n\n")
 | 
| 
 | 
   105     print(s)
 | 
| 
 | 
   106 
 | 
| 
 | 
   107 ############################ dataset input ####################################
 | 
| 
 | 
   108 def read_dataset(data :str, name :str) -> pd.DataFrame:
 | 
| 
 | 
   109     """
 | 
| 
 | 
   110     Read a dataset from a CSV file and return it as a pandas DataFrame.
 | 
| 
 | 
   111 
 | 
| 
 | 
   112     Args:
 | 
| 
 | 
   113         data (str): Path to the CSV file containing the dataset.
 | 
| 
 | 
   114         name (str): Name of the dataset, used in error messages.
 | 
| 
 | 
   115 
 | 
| 
 | 
   116     Returns:
 | 
| 
 | 
   117         pandas.DataFrame: DataFrame containing the dataset.
 | 
| 
 | 
   118 
 | 
| 
 | 
   119     Raises:
 | 
| 
 | 
   120         pd.errors.EmptyDataError: If the CSV file is empty.
 | 
| 
 | 
   121         sys.exit: If the CSV file has the wrong format, the execution is aborted.
 | 
| 
 | 
   122     """
 | 
| 
 | 
   123     try:
 | 
| 
 | 
   124         dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
 | 
| 
 | 
   125     except pd.errors.EmptyDataError:
 | 
| 
 | 
   126         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   127     if len(dataset.columns) < 2:
 | 
| 
 | 
   128         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   129     return dataset
 | 
| 
 | 
   130 
 | 
| 
 | 
   131 
 | 
| 
 | 
   132 def apply_ras_bounds(bounds, ras_row):
 | 
| 
 | 
   133     """
 | 
| 
 | 
   134     Adjust the bounds of reactions in the model based on RAS values.
 | 
| 
 | 
   135 
 | 
| 
 | 
   136     Args:
 | 
| 
 | 
   137         bounds (pd.DataFrame): Model bounds.
 | 
| 
 | 
   138         ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
 | 
| 
 | 
   139     Returns:
 | 
| 
 | 
   140         new_bounds (pd.DataFrame): integrated bounds.
 | 
| 
 | 
   141     """
 | 
| 
 | 
   142     new_bounds = bounds.copy()
 | 
| 
 | 
   143     for reaction in ras_row.index:
 | 
| 
 | 
   144         scaling_factor = ras_row[reaction]
 | 
| 
 | 
   145         if not np.isnan(scaling_factor):
 | 
| 
 | 
   146             lower_bound=bounds.loc[reaction, "lower_bound"]
 | 
| 
 | 
   147             upper_bound=bounds.loc[reaction, "upper_bound"]
 | 
| 
 | 
   148             valMax=float((upper_bound)*scaling_factor)
 | 
| 
 | 
   149             valMin=float((lower_bound)*scaling_factor)
 | 
| 
 | 
   150             if upper_bound!=0 and lower_bound==0:
 | 
| 
 | 
   151                 new_bounds.loc[reaction, "upper_bound"] = valMax
 | 
| 
 | 
   152             if upper_bound==0 and lower_bound!=0:
 | 
| 
 | 
   153                 new_bounds.loc[reaction, "lower_bound"] = valMin
 | 
| 
 | 
   154             if upper_bound!=0 and lower_bound!=0:
 | 
| 
 | 
   155                 new_bounds.loc[reaction, "lower_bound"] = valMin
 | 
| 
 | 
   156                 new_bounds.loc[reaction, "upper_bound"] = valMax
 | 
| 
 | 
   157     return new_bounds
 | 
| 
 | 
   158 
 | 
| 
 | 
   159 
 | 
| 
 | 
   160 def save_model(model, filename, output_folder, file_format='csv'):
 | 
| 
 | 
   161     """
 | 
| 
 | 
   162     Save a COBRA model to file in the specified format.
 | 
| 
 | 
   163     
 | 
| 
 | 
   164     Args:
 | 
| 
 | 
   165         model (cobra.Model): The model to save.
 | 
| 
 | 
   166         filename (str): Base filename (without extension).
 | 
| 
 | 
   167         output_folder (str): Output directory.
 | 
| 
 | 
   168         file_format (str): File format ('xml', 'json', 'mat', 'yaml', 'tabular', 'csv').
 | 
| 
 | 
   169     
 | 
| 
 | 
   170     Returns:
 | 
| 
 | 
   171         None
 | 
| 
 | 
   172     """
 | 
| 
 | 
   173     if not os.path.exists(output_folder):
 | 
| 
 | 
   174         os.makedirs(output_folder)
 | 
| 
 | 
   175     
 | 
| 
 | 
   176     try:
 | 
| 
 | 
   177         if file_format == 'tabular' or file_format == 'csv':
 | 
| 
 | 
   178             # Special handling for tabular format using utils functions
 | 
| 
 | 
   179             filepath = os.path.join(output_folder, f"{filename}.csv")
 | 
| 
 | 
   180             
 | 
| 
 | 
   181             # Use unified function for tabular export
 | 
| 
 | 
   182             merged = modelUtils.export_model_to_tabular(
 | 
| 
 | 
   183                 model=model,
 | 
| 
 | 
   184                 output_path=filepath,
 | 
| 
 | 
   185                 include_objective=True  
 | 
| 
 | 
   186             )
 | 
| 
 | 
   187             
 | 
| 
 | 
   188         else:
 | 
| 
 | 
   189             # Standard COBRA formats
 | 
| 
 | 
   190             filepath = os.path.join(output_folder, f"{filename}.{file_format}")
 | 
| 
 | 
   191             
 | 
| 
 | 
   192             if file_format == 'xml':
 | 
| 
 | 
   193                 cobra.io.write_sbml_model(model, filepath)
 | 
| 
 | 
   194             elif file_format == 'json':
 | 
| 
 | 
   195                 cobra.io.save_json_model(model, filepath)
 | 
| 
 | 
   196             elif file_format == 'mat':
 | 
| 
 | 
   197                 cobra.io.save_matlab_model(model, filepath)
 | 
| 
 | 
   198             elif file_format == 'yaml':
 | 
| 
 | 
   199                 cobra.io.save_yaml_model(model, filepath)
 | 
| 
 | 
   200             else:
 | 
| 
 | 
   201                 raise ValueError(f"Unsupported format: {file_format}")
 | 
| 
 | 
   202         
 | 
| 
 | 
   203         print(f"Model saved: {filepath}")
 | 
| 
 | 
   204         
 | 
| 
 | 
   205     except Exception as e:
 | 
| 
 | 
   206         warning(f"Error saving model {filename}: {str(e)}")
 | 
| 
 | 
   207 
 | 
| 
 | 
   208 def apply_bounds_to_model(model, bounds):
 | 
| 
 | 
   209     """
 | 
| 
 | 
   210     Apply bounds from a DataFrame to a COBRA model.
 | 
| 
 | 
   211     
 | 
| 
 | 
   212     Args:
 | 
| 
 | 
   213         model (cobra.Model): The metabolic model to modify.
 | 
| 
 | 
   214         bounds (pd.DataFrame): DataFrame with reaction bounds.
 | 
| 
 | 
   215     
 | 
| 
 | 
   216     Returns:
 | 
| 
 | 
   217         cobra.Model: Modified model with new bounds.
 | 
| 
 | 
   218     """
 | 
| 
 | 
   219     model_copy = model.copy()
 | 
| 
 | 
   220     for reaction_id in bounds.index:
 | 
| 
 | 
   221         try:
 | 
| 
 | 
   222             reaction = model_copy.reactions.get_by_id(reaction_id)
 | 
| 
 | 
   223             reaction.lower_bound = bounds.loc[reaction_id, "lower_bound"]
 | 
| 
 | 
   224             reaction.upper_bound = bounds.loc[reaction_id, "upper_bound"]
 | 
| 
 | 
   225         except KeyError:
 | 
| 
 | 
   226             # Reaction not found in model, skip
 | 
| 
 | 
   227             continue
 | 
| 
 | 
   228     return model_copy
 | 
| 
 | 
   229 
 | 
| 
 | 
   230 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder, save_models=False, save_models_path='saved_models/', save_models_format='csv'):
 | 
| 
 | 
   231     """
 | 
| 
 | 
   232     Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
 | 
| 
 | 
   233 
 | 
| 
 | 
   234     Args:
 | 
| 
 | 
   235         cellName (str): The name of the RAS cell (used for naming the output file).
 | 
| 
 | 
   236         ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
 | 
| 
 | 
   237         model (cobra.Model): The metabolic model to be modified.
 | 
| 
 | 
   238         rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
 | 
| 
 | 
   239         output_folder (str): Folder path where the output CSV file will be saved.
 | 
| 
 | 
   240         save_models (bool): Whether to save models with applied bounds.
 | 
| 
 | 
   241         save_models_path (str): Path where to save models.
 | 
| 
 | 
   242         save_models_format (str): Format for saved models.
 | 
| 
 | 
   243     
 | 
| 
 | 
   244     Returns:
 | 
| 
 | 
   245         None
 | 
| 
 | 
   246     """
 | 
| 
 | 
   247     bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
 | 
| 
 | 
   248     new_bounds = apply_ras_bounds(bounds, ras_row)
 | 
| 
 | 
   249     new_bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
 | 
| 
 | 
   250     
 | 
| 
 | 
   251     # Save model if requested
 | 
| 
 | 
   252     if save_models:
 | 
| 
 | 
   253         modified_model = apply_bounds_to_model(model, new_bounds)
 | 
| 
 | 
   254         save_model(modified_model, cellName, save_models_path, save_models_format)
 | 
| 
 | 
   255     
 | 
| 
 | 
   256     return
 | 
| 
 | 
   257 
 | 
| 
 | 
   258 def generate_bounds_model(model: cobra.Model, ras=None, output_folder='output/', save_models=False, save_models_path='saved_models/', save_models_format='csv') -> pd.DataFrame:
 | 
| 
 | 
   259     """
 | 
| 
 | 
   260     Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
 | 
| 
 | 
   261     
 | 
| 
 | 
   262     Args:
 | 
| 
 | 
   263         model (cobra.Model): The metabolic model for which bounds will be generated.
 | 
| 
 | 
   264         ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
 | 
| 
 | 
   265         output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
 | 
| 
 | 
   266         save_models (bool): Whether to save models with applied bounds.
 | 
| 
 | 
   267         save_models_path (str): Path where to save models.
 | 
| 
 | 
   268         save_models_format (str): Format for saved models.
 | 
| 
 | 
   269 
 | 
| 
 | 
   270     Returns:
 | 
| 
 | 
   271         pd.DataFrame: DataFrame containing the bounds of reactions in the model.
 | 
| 
 | 
   272     """
 | 
| 
 | 
   273     rxns_ids = [rxn.id for rxn in model.reactions]            
 | 
| 
 | 
   274             
 | 
| 
 | 
   275     # Perform Flux Variability Analysis (FVA) on this medium
 | 
| 
 | 
   276     df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
 | 
| 
 | 
   277     
 | 
| 
 | 
   278     # Set FVA bounds
 | 
| 
 | 
   279     for reaction in rxns_ids:
 | 
| 
 | 
   280         model.reactions.get_by_id(reaction).lower_bound = float(df_FVA.loc[reaction, "minimum"])
 | 
| 
 | 
   281         model.reactions.get_by_id(reaction).upper_bound = float(df_FVA.loc[reaction, "maximum"])
 | 
| 
 | 
   282 
 | 
| 
 | 
   283     if ras is not None:
 | 
| 
 | 
   284         Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(
 | 
| 
 | 
   285             cellName, ras_row, model, rxns_ids, output_folder, 
 | 
| 
 | 
   286             save_models, save_models_path, save_models_format
 | 
| 
 | 
   287         ) for cellName, ras_row in ras.iterrows())
 | 
| 
 | 
   288     else:
 | 
| 
 | 
   289         raise ValueError("RAS DataFrame is None. Cannot generate bounds without RAS data.")
 | 
| 
 | 
   290     return
 | 
| 
 | 
   291 
 | 
| 
 | 
   292 ############################# main ###########################################
 | 
| 
 | 
   293 def main(args:List[str] = None) -> None:
 | 
| 
 | 
   294     """
 | 
| 
 | 
   295     Initialize and execute RAS-to-bounds pipeline based on the frontend input arguments.
 | 
| 
 | 
   296 
 | 
| 
 | 
   297     Returns:
 | 
| 
 | 
   298         None
 | 
| 
 | 
   299     """
 | 
| 
 | 
   300     if not os.path.exists('ras_to_bounds'):
 | 
| 
 | 
   301         os.makedirs('ras_to_bounds')
 | 
| 
 | 
   302 
 | 
| 
 | 
   303     global ARGS
 | 
| 
 | 
   304     ARGS = process_args(args)
 | 
| 
 | 
   305 
 | 
| 
 | 
   306 
 | 
| 
 | 
   307     ras_file_list = ARGS.input_ras.split(",")
 | 
| 
 | 
   308     ras_file_names = ARGS.name.split(",")
 | 
| 
 | 
   309     if len(ras_file_names) != len(set(ras_file_names)):
 | 
| 
 | 
   310         error_message = "Duplicated file names in the uploaded RAS matrices."
 | 
| 
 | 
   311         warning(error_message)
 | 
| 
 | 
   312         raise ValueError(error_message)
 | 
| 
 | 
   313         
 | 
| 
 | 
   314     ras_class_names = []
 | 
| 
 | 
   315     for file in ras_file_names:
 | 
| 
 | 
   316         ras_class_names.append(file.rsplit(".", 1)[0])
 | 
| 
 | 
   317     ras_list = []
 | 
| 
 | 
   318     class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
 | 
| 
 | 
   319     for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
 | 
| 
 | 
   320         ras = read_dataset(ras_matrix, "ras dataset")
 | 
| 
 | 
   321         ras.replace("None", None, inplace=True)
 | 
| 
 | 
   322         ras.set_index("Reactions", drop=True, inplace=True)
 | 
| 
 | 
   323         ras = ras.T
 | 
| 
 | 
   324         ras = ras.astype(float)
 | 
| 
 | 
   325         if(len(ras_file_list)>1):
 | 
| 
 | 
   326             # Append class name to patient id (DataFrame index)
 | 
| 
 | 
   327             ras.index = [f"{idx}_{ras_class_name}" for idx in ras.index]
 | 
| 
 | 
   328         else:
 | 
| 
 | 
   329             ras.index = [f"{idx}" for idx in ras.index]
 | 
| 
 | 
   330         ras_list.append(ras)
 | 
| 
 | 
   331         for patient_id in ras.index:
 | 
| 
 | 
   332             class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
 | 
| 
 | 
   333     
 | 
| 
 | 
   334         
 | 
| 
 | 
   335     # Concatenate all RAS DataFrames into a single DataFrame
 | 
| 
 | 
   336         ras_combined = pd.concat(ras_list, axis=0)
 | 
| 
 | 
   337     # Normalize RAS values column-wise by max RAS
 | 
| 
 | 
   338         ras_combined = ras_combined.div(ras_combined.max(axis=0))
 | 
| 
 | 
   339         ras_combined.dropna(axis=1, how='all', inplace=True)
 | 
| 
 | 
   340 
 | 
| 
 | 
   341     model = modelUtils.build_cobra_model_from_csv(ARGS.model_upload)
 | 
| 
 | 
   342 
 | 
| 
 | 
   343     validation = modelUtils.validate_model(model)
 | 
| 
 | 
   344 
 | 
| 
 | 
   345     print("\n=== MODEL VALIDATION ===")
 | 
| 
 | 
   346     for key, value in validation.items():
 | 
| 
 | 
   347         print(f"{key}: {value}")
 | 
| 
 | 
   348 
 | 
| 
 | 
   349 
 | 
| 
 | 
   350     generate_bounds_model(model, ras=ras_combined, output_folder=ARGS.output_path,
 | 
| 
 | 
   351                     save_models=ARGS.save_models, save_models_path=ARGS.save_models_path,
 | 
| 
 | 
   352                     save_models_format=ARGS.save_models_format)
 | 
| 
 | 
   353     class_assignments.to_csv(ARGS.cell_class, sep='\t', index=False)
 | 
| 
 | 
   354 
 | 
| 
 | 
   355 
 | 
| 
 | 
   356     return
 | 
| 
 | 
   357         
 | 
| 
 | 
   358 ##############################################################################
 | 
| 
 | 
   359 if __name__ == "__main__":
 | 
| 
539
 | 
   360     main() |