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