| 
406
 | 
     1 import os
 | 
| 
 | 
     2 import csv
 | 
| 
 | 
     3 import cobra
 | 
| 
 | 
     4 import pickle
 | 
| 
 | 
     5 import argparse
 | 
| 
 | 
     6 import pandas as pd
 | 
| 
 | 
     7 import utils.general_utils as utils
 | 
| 
 | 
     8 import utils.rule_parsing  as rulesUtils
 | 
| 
 | 
     9 from typing import Optional, Tuple, Union, List, Dict
 | 
| 
 | 
    10 import utils.reaction_parsing as reactionUtils
 | 
| 
 | 
    11 
 | 
| 
 | 
    12 ARGS : argparse.Namespace
 | 
| 
 | 
    13 def process_args(args: List[str] = None) -> argparse.Namespace:
 | 
| 
 | 
    14     """
 | 
| 
 | 
    15     Parse command-line arguments for CustomDataGenerator.
 | 
| 
 | 
    16     """
 | 
| 
 | 
    17 
 | 
| 
 | 
    18     parser = argparse.ArgumentParser(
 | 
| 
 | 
    19         usage="%(prog)s [options]",
 | 
| 
 | 
    20         description="Generate custom data from a given model"
 | 
| 
 | 
    21     )
 | 
| 
 | 
    22 
 | 
| 
 | 
    23     parser.add_argument("--out_log", type=str, required=True,
 | 
| 
 | 
    24                         help="Output log file")
 | 
| 
 | 
    25 
 | 
| 
 | 
    26     parser.add_argument("--model", type=str,
 | 
| 
 | 
    27                         help="Built-in model identifier (e.g., ENGRO2, Recon, HMRcore)")
 | 
| 
 | 
    28     parser.add_argument("--input", type=str,
 | 
| 
 | 
    29                         help="Custom model file (JSON or XML)")
 | 
| 
 | 
    30     parser.add_argument("--name", type=str, required=True,
 | 
| 
 | 
    31                         help="Model name (default or custom)")
 | 
| 
 | 
    32     
 | 
| 
 | 
    33     parser.add_argument("--medium_selector", type=str, required=True,
 | 
| 
 | 
    34                         help="Medium selection option")
 | 
| 
 | 
    35 
 | 
| 
 | 
    36     parser.add_argument("--gene_format", type=str, default="Default",
 | 
| 
 | 
    37                         help="Gene nomenclature format: Default (original), ENSNG, HGNC_SYMBOL, HGNC_ID, ENTREZ")
 | 
| 
 | 
    38     
 | 
| 
 | 
    39     parser.add_argument("--out_tabular", type=str,
 | 
| 
 | 
    40                         help="Output file for the merged dataset (CSV or XLSX)")
 | 
| 
 | 
    41     
 | 
| 
 | 
    42     parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__),
 | 
| 
 | 
    43                         help="Tool directory (passed from Galaxy as $__tool_directory__)")
 | 
| 
 | 
    44 
 | 
| 
 | 
    45 
 | 
| 
 | 
    46     return parser.parse_args(args)
 | 
| 
 | 
    47 
 | 
| 
 | 
    48 ################################- INPUT DATA LOADING -################################
 | 
| 
 | 
    49 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
 | 
| 
 | 
    50     """
 | 
| 
 | 
    51     Loads a custom model from a file, either in JSON or XML format.
 | 
| 
 | 
    52 
 | 
| 
 | 
    53     Args:
 | 
| 
 | 
    54         file_path : The path to the file containing the custom model.
 | 
| 
 | 
    55         ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
 | 
| 
 | 
    56 
 | 
| 
 | 
    57     Raises:
 | 
| 
 | 
    58         DataErr : if the file is in an invalid format or cannot be opened for whatever reason.    
 | 
| 
 | 
    59     
 | 
| 
 | 
    60     Returns:
 | 
| 
 | 
    61         cobra.Model : the model, if successfully opened.
 | 
| 
 | 
    62     """
 | 
| 
 | 
    63     ext = ext if ext else file_path.ext
 | 
| 
 | 
    64     try:
 | 
| 
 | 
    65         if ext is utils.FileFormat.XML:
 | 
| 
 | 
    66             return cobra.io.read_sbml_model(file_path.show())
 | 
| 
 | 
    67         
 | 
| 
 | 
    68         if ext is utils.FileFormat.JSON:
 | 
| 
 | 
    69             return cobra.io.load_json_model(file_path.show())
 | 
| 
 | 
    70 
 | 
| 
 | 
    71     except Exception as e: raise utils.DataErr(file_path, e.__str__())
 | 
| 
 | 
    72     raise utils.DataErr(file_path,
 | 
| 
 | 
    73         f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
 | 
| 
 | 
    74 
 | 
| 
 | 
    75 
 | 
| 
 | 
    76 
 | 
| 
 | 
    77 
 | 
| 
 | 
    78 ###############################- FILE SAVING -################################
 | 
| 
 | 
    79 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
 | 
| 
 | 
    80     """
 | 
| 
 | 
    81     Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
 | 
| 
 | 
    82 
 | 
| 
 | 
    83     Args:
 | 
| 
 | 
    84         data : the data to be written to the file.
 | 
| 
 | 
    85         file_path : the path to the .csv file.
 | 
| 
 | 
    86         fieldNames : the names of the fields (columns) in the .csv file.
 | 
| 
 | 
    87     
 | 
| 
 | 
    88     Returns:
 | 
| 
 | 
    89         None
 | 
| 
 | 
    90     """
 | 
| 
 | 
    91     with open(file_path.show(), 'w', newline='') as csvfile:
 | 
| 
 | 
    92         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
 | 
| 
 | 
    93         writer.writeheader()
 | 
| 
 | 
    94 
 | 
| 
 | 
    95         for key, value in data.items():
 | 
| 
 | 
    96             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
 | 
| 
 | 
    97 
 | 
| 
 | 
    98 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
 | 
| 
 | 
    99     """
 | 
| 
 | 
   100     Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
 | 
| 
 | 
   101 
 | 
| 
 | 
   102     Args:
 | 
| 
 | 
   103         data : the data to be written to the file.
 | 
| 
 | 
   104         file_path : the path to the .csv file.
 | 
| 
 | 
   105         fieldNames : the names of the fields (columns) in the .csv file.
 | 
| 
 | 
   106     
 | 
| 
 | 
   107     Returns:
 | 
| 
 | 
   108         None
 | 
| 
 | 
   109     """
 | 
| 
 | 
   110     with open(file_path, 'w', newline='') as csvfile:
 | 
| 
 | 
   111         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
 | 
| 
 | 
   112         writer.writeheader()
 | 
| 
 | 
   113 
 | 
| 
 | 
   114         for key, value in data.items():
 | 
| 
 | 
   115             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
 | 
| 
 | 
   116 
 | 
| 
 | 
   117 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None:
 | 
| 
 | 
   118     try:
 | 
| 
 | 
   119         os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
 | 
| 
 | 
   120         df.to_csv(path, sep="\t", index=False)
 | 
| 
 | 
   121     except Exception as e:
 | 
| 
 | 
   122         raise utils.DataErr(path, f"failed writing tabular output: {e}")
 | 
| 
 | 
   123 
 | 
| 
 | 
   124 
 | 
| 
 | 
   125 ###############################- ENTRY POINT -################################
 | 
| 
 | 
   126 def main(args:List[str] = None) -> None:
 | 
| 
 | 
   127     """
 | 
| 
 | 
   128     Initializes everything and sets the program in motion based on the fronted input arguments.
 | 
| 
 | 
   129     
 | 
| 
 | 
   130     Returns:
 | 
| 
 | 
   131         None
 | 
| 
 | 
   132     """
 | 
| 
 | 
   133     # get args from frontend (related xml)
 | 
| 
 | 
   134     global ARGS
 | 
| 
 | 
   135     ARGS = process_args(args)
 | 
| 
 | 
   136 
 | 
| 
 | 
   137 
 | 
| 
 | 
   138     if ARGS.input:
 | 
| 
 | 
   139         # load custom model
 | 
| 
 | 
   140         model = load_custom_model(
 | 
| 
 | 
   141             utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
 | 
| 
 | 
   142     else:
 | 
| 
 | 
   143         # load built-in model
 | 
| 
 | 
   144 
 | 
| 
 | 
   145         try:
 | 
| 
 | 
   146             model_enum = utils.Model[ARGS.model]  # e.g., Model['ENGRO2']
 | 
| 
 | 
   147         except KeyError:
 | 
| 
 | 
   148             raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model)
 | 
| 
 | 
   149 
 | 
| 
 | 
   150         # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models)
 | 
| 
 | 
   151         try:
 | 
| 
 | 
   152             model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir)
 | 
| 
 | 
   153         except Exception as e:
 | 
| 
 | 
   154             # Wrap/normalize load errors as DataErr for consistency
 | 
| 
 | 
   155             raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}")
 | 
| 
 | 
   156 
 | 
| 
 | 
   157     # Determine final model name: explicit --name overrides, otherwise use the model id
 | 
| 
 | 
   158     
 | 
| 
 | 
   159     model_name = ARGS.name if ARGS.name else ARGS.model
 | 
| 
 | 
   160     
 | 
| 
 | 
   161     if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default":
 | 
| 
 | 
   162         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
 | 
| 
 | 
   163         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
 | 
| 
 | 
   164         medium = df_mediums[[ARGS.medium_selector]]
 | 
| 
 | 
   165         medium = medium[ARGS.medium_selector].to_dict()
 | 
| 
 | 
   166 
 | 
| 
 | 
   167         # Set all reactions to zero in the medium
 | 
| 
 | 
   168         for rxn_id, _ in model.medium.items():
 | 
| 
 | 
   169             model.reactions.get_by_id(rxn_id).lower_bound = float(0.0)
 | 
| 
 | 
   170         
 | 
| 
 | 
   171         # Set medium conditions
 | 
| 
 | 
   172         for reaction, value in medium.items():
 | 
| 
 | 
   173             if value is not None:
 | 
| 
 | 
   174                 model.reactions.get_by_id(reaction).lower_bound = -float(value)
 | 
| 
 | 
   175 
 | 
| 
 | 
   176     if ARGS.name == "ENGRO2" and ARGS.gene_format != "Default":
 | 
| 
 | 
   177 
 | 
| 
 | 
   178         model = utils.convert_genes(model, ARGS.gene_format.replace("HGNC_", "HGNC "))
 | 
| 
 | 
   179 
 | 
| 
 | 
   180     # generate data
 | 
| 
411
 | 
   181     rules = utils.generate_rules(model, asParsed = False)
 | 
| 
 | 
   182     reactions = utils.generate_reactions(model, asParsed = False)
 | 
| 
 | 
   183     bounds = utils.generate_bounds(model)
 | 
| 
 | 
   184     medium = utils.get_medium(model)
 | 
| 
406
 | 
   185     if ARGS.name == "ENGRO2":
 | 
| 
411
 | 
   186         compartments = utils.generate_compartments(model)
 | 
| 
406
 | 
   187 
 | 
| 
 | 
   188     df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
 | 
| 
 | 
   189     df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
 | 
| 
 | 
   190 
 | 
| 
 | 
   191     df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
 | 
| 
 | 
   192     df_medium = medium.rename(columns = {"reaction": "ReactionID"})
 | 
| 
 | 
   193     df_medium["InMedium"] = True # flag per indicare la presenza nel medium
 | 
| 
 | 
   194 
 | 
| 
 | 
   195     merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
 | 
| 
 | 
   196     merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
 | 
| 
 | 
   197     if ARGS.name == "ENGRO2": 
 | 
| 
 | 
   198         merged = merged.merge(compartments, on = "ReactionID", how = "outer")
 | 
| 
 | 
   199     merged = merged.merge(df_medium, on = "ReactionID", how = "left")
 | 
| 
 | 
   200 
 | 
| 
 | 
   201     merged["InMedium"] = merged["InMedium"].fillna(False)
 | 
| 
 | 
   202 
 | 
| 
 | 
   203     merged = merged.sort_values(by = "InMedium", ascending = False)
 | 
| 
 | 
   204 
 | 
| 
 | 
   205     #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data")
 | 
| 
 | 
   206 
 | 
| 
 | 
   207     #merged.to_csv(out_file, sep = '\t', index = False)
 | 
| 
 | 
   208 
 | 
| 
 | 
   209     ####
 | 
| 
 | 
   210 
 | 
| 
 | 
   211     if not ARGS.out_tabular:
 | 
| 
 | 
   212         raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular)
 | 
| 
 | 
   213     save_as_tabular_df(merged, ARGS.out_tabular)
 | 
| 
 | 
   214     expected = ARGS.out_tabular
 | 
| 
 | 
   215 
 | 
| 
 | 
   216     # verify output exists and non-empty
 | 
| 
 | 
   217     if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0:
 | 
| 
 | 
   218         raise utils.DataErr(expected, "Output non creato o vuoto")
 | 
| 
 | 
   219 
 | 
| 
 | 
   220     print("CustomDataGenerator: completed successfully")
 | 
| 
 | 
   221 
 | 
| 
 | 
   222 if __name__ == '__main__':
 | 
| 
 | 
   223     main() |