| 491 | 1 """ | 
|  | 2 Scripts to generate a tabular file of a metabolic model (built-in or custom). | 
|  | 3 | 
|  | 4 This script loads a COBRA model (built-in or custom), optionally applies | 
|  | 5 medium and gene nomenclature settings, derives reaction-related metadata | 
|  | 6 (GPR rules, formulas, bounds, objective coefficients, medium membership, | 
|  | 7 and compartments for ENGRO2), and writes a tabular summary. | 
|  | 8 """ | 
|  | 9 | 
|  | 10 import os | 
|  | 11 import csv | 
|  | 12 import cobra | 
|  | 13 import argparse | 
|  | 14 import pandas as pd | 
|  | 15 import utils.general_utils as utils | 
|  | 16 from typing import Optional, Tuple, List | 
|  | 17 import utils.model_utils as modelUtils | 
|  | 18 import logging | 
|  | 19 from pathlib import Path | 
|  | 20 | 
|  | 21 | 
|  | 22 ARGS : argparse.Namespace | 
|  | 23 def process_args(args: List[str] = None) -> argparse.Namespace: | 
|  | 24     """ | 
|  | 25     Parse command-line arguments for metabolic_model_setting. | 
|  | 26     """ | 
|  | 27 | 
|  | 28     parser = argparse.ArgumentParser( | 
|  | 29         usage="%(prog)s [options]", | 
|  | 30         description="Generate custom data from a given model" | 
|  | 31     ) | 
|  | 32 | 
|  | 33     parser.add_argument("--out_log", type=str, required=True, | 
|  | 34                         help="Output log file") | 
|  | 35 | 
|  | 36     parser.add_argument("--model", type=str, | 
|  | 37                         help="Built-in model identifier (e.g., ENGRO2, Recon, HMRcore)") | 
|  | 38     parser.add_argument("--input", type=str, | 
|  | 39                         help="Custom model file (JSON or XML)") | 
| 496 | 40     parser.add_argument("--name", nargs='*', required=True, | 
| 491 | 41                         help="Model name (default or custom)") | 
|  | 42 | 
|  | 43     parser.add_argument("--medium_selector", type=str, required=True, | 
|  | 44                         help="Medium selection option") | 
|  | 45 | 
|  | 46     parser.add_argument("--gene_format", type=str, default="Default", | 
|  | 47                         help="Gene nomenclature format: Default (original), ENSNG, HGNC_SYMBOL, HGNC_ID, ENTREZ") | 
|  | 48 | 
|  | 49     parser.add_argument("--out_tabular", type=str, | 
|  | 50                         help="Output file for the merged dataset (CSV or XLSX)") | 
|  | 51 | 
|  | 52     parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__), | 
|  | 53                         help="Tool directory (passed from Galaxy as $__tool_directory__)") | 
|  | 54 | 
|  | 55 | 
|  | 56     return parser.parse_args(args) | 
|  | 57 | 
|  | 58 ################################- INPUT DATA LOADING -################################ | 
|  | 59 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model: | 
|  | 60     """ | 
|  | 61     Loads a custom model from a file, either in JSON, XML, MAT, or YML format. | 
|  | 62 | 
|  | 63     Args: | 
|  | 64         file_path : The path to the file containing the custom model. | 
|  | 65         ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour. | 
|  | 66 | 
|  | 67     Raises: | 
|  | 68         DataErr : if the file is in an invalid format or cannot be opened for whatever reason. | 
|  | 69 | 
|  | 70     Returns: | 
|  | 71         cobra.Model : the model, if successfully opened. | 
|  | 72     """ | 
|  | 73     ext = ext if ext else file_path.ext | 
|  | 74     try: | 
|  | 75         if ext is utils.FileFormat.XML: | 
|  | 76             return cobra.io.read_sbml_model(file_path.show()) | 
|  | 77 | 
|  | 78         if ext is utils.FileFormat.JSON: | 
|  | 79             return cobra.io.load_json_model(file_path.show()) | 
|  | 80 | 
|  | 81         if ext is utils.FileFormat.MAT: | 
|  | 82             return cobra.io.load_matlab_model(file_path.show()) | 
|  | 83 | 
|  | 84         if ext is utils.FileFormat.YML: | 
|  | 85             return cobra.io.load_yaml_model(file_path.show()) | 
|  | 86 | 
|  | 87     except Exception as e: raise utils.DataErr(file_path, e.__str__()) | 
|  | 88     raise utils.DataErr( | 
|  | 89         file_path, | 
|  | 90         f"Unrecognized format '{file_path.ext}'. Only JSON, XML, MAT, YML are supported." | 
|  | 91     ) | 
|  | 92 | 
|  | 93 | 
|  | 94 ###############################- FILE SAVING -################################ | 
|  | 95 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None: | 
|  | 96     """ | 
|  | 97     Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath. | 
|  | 98 | 
|  | 99     Args: | 
|  | 100         data : the data to be written to the file. | 
|  | 101         file_path : the path to the .csv file. | 
|  | 102         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 103 | 
|  | 104     Returns: | 
|  | 105         None | 
|  | 106     """ | 
|  | 107     with open(file_path.show(), 'w', newline='') as csvfile: | 
|  | 108         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 109         writer.writeheader() | 
|  | 110 | 
|  | 111         for key, value in data.items(): | 
|  | 112             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 113 | 
|  | 114 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None: | 
|  | 115     """ | 
|  | 116     Saves any dictionary-shaped data in a .csv file created at the given file_path as string. | 
|  | 117 | 
|  | 118     Args: | 
|  | 119         data : the data to be written to the file. | 
|  | 120         file_path : the path to the .csv file. | 
|  | 121         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 122 | 
|  | 123     Returns: | 
|  | 124         None | 
|  | 125     """ | 
|  | 126     with open(file_path, 'w', newline='') as csvfile: | 
|  | 127         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 128         writer.writeheader() | 
|  | 129 | 
|  | 130         for key, value in data.items(): | 
|  | 131             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 132 | 
|  | 133 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None: | 
|  | 134     """ | 
|  | 135     Save a pandas DataFrame as a tab-separated file, creating directories as needed. | 
|  | 136 | 
|  | 137     Args: | 
|  | 138         df: The DataFrame to write. | 
|  | 139         path: Destination file path (will be written as TSV). | 
|  | 140 | 
|  | 141     Raises: | 
|  | 142         DataErr: If writing the output fails for any reason. | 
|  | 143 | 
|  | 144     Returns: | 
|  | 145         None | 
|  | 146     """ | 
|  | 147     try: | 
|  | 148         os.makedirs(os.path.dirname(path) or ".", exist_ok=True) | 
|  | 149         df.to_csv(path, sep="\t", index=False) | 
|  | 150     except Exception as e: | 
|  | 151         raise utils.DataErr(path, f"failed writing tabular output: {e}") | 
|  | 152 | 
|  | 153 def is_placeholder(gid) -> bool: | 
|  | 154     """Return True if the gene id looks like a placeholder (e.g., 0/NA/NAN/empty).""" | 
|  | 155     if gid is None: | 
|  | 156         return True | 
|  | 157     s = str(gid).strip().lower() | 
|  | 158     return s in {"0", "", "na", "nan"}  # lowercase for simple matching | 
|  | 159 | 
|  | 160 def sample_valid_gene_ids(genes, limit=10): | 
|  | 161     """Yield up to `limit` valid gene IDs, skipping placeholders (e.g., the first 0 in RECON).""" | 
|  | 162     out = [] | 
|  | 163     for g in genes: | 
|  | 164         gid = getattr(g, "id", getattr(g, "gene_id", g)) | 
|  | 165         if not is_placeholder(gid): | 
|  | 166             out.append(str(gid)) | 
|  | 167             if len(out) >= limit: | 
|  | 168                 break | 
|  | 169     return out | 
|  | 170 | 
|  | 171 | 
|  | 172 ###############################- ENTRY POINT -################################ | 
|  | 173 def main(args:List[str] = None) -> None: | 
|  | 174     """ | 
|  | 175     Initialize and generate custom data based on the frontend input arguments. | 
|  | 176 | 
|  | 177     Returns: | 
|  | 178         None | 
|  | 179     """ | 
|  | 180     # Parse args from frontend (Galaxy XML) | 
|  | 181     global ARGS | 
|  | 182     ARGS = process_args(args) | 
|  | 183 | 
| 496 | 184     # Convert name from list to string (handles names with spaces) | 
|  | 185     if isinstance(ARGS.name, list): | 
|  | 186         ARGS.name = ' '.join(ARGS.name) | 
| 491 | 187 | 
|  | 188     if ARGS.input: | 
|  | 189         # Load a custom model from file | 
|  | 190         model = load_custom_model( | 
| 497 | 191             utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.input).ext) | 
| 491 | 192     else: | 
|  | 193         # Load a built-in model | 
| 495 | 194         if not ARGS.model: | 
|  | 195             raise utils.ArgsErr("model", "either --model or --input must be provided", "None") | 
| 491 | 196 | 
|  | 197         try: | 
|  | 198             model_enum = utils.Model[ARGS.model]  # e.g., Model['ENGRO2'] | 
|  | 199         except KeyError: | 
|  | 200             raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model) | 
|  | 201 | 
|  | 202         # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models) | 
|  | 203         try: | 
|  | 204             model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir) | 
|  | 205         except Exception as e: | 
|  | 206             # Wrap/normalize load errors as DataErr for consistency | 
|  | 207             raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}") | 
|  | 208 | 
|  | 209     # Determine final model name: explicit --name overrides, otherwise use the model id | 
|  | 210 | 
|  | 211     if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default": | 
|  | 212         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0) | 
|  | 213         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ") | 
|  | 214         medium = df_mediums[[ARGS.medium_selector]] | 
|  | 215         medium = medium[ARGS.medium_selector].to_dict() | 
|  | 216 | 
|  | 217         # Reset all medium reactions lower bound to zero | 
|  | 218         for rxn_id, _ in model.medium.items(): | 
|  | 219             model.reactions.get_by_id(rxn_id).lower_bound = float(0.0) | 
|  | 220 | 
|  | 221         # Apply selected medium uptake bounds (negative for uptake) | 
|  | 222         for reaction, value in medium.items(): | 
|  | 223             if value is not None: | 
|  | 224                 model.reactions.get_by_id(reaction).lower_bound = -float(value) | 
|  | 225 | 
|  | 226     # Initialize translation_issues dictionary | 
|  | 227     translation_issues = {} | 
|  | 228 | 
|  | 229     if (ARGS.name == "Recon" or ARGS.name == "ENGRO2") and ARGS.gene_format != "Default": | 
|  | 230         logging.basicConfig(level=logging.INFO) | 
|  | 231         logger = logging.getLogger(__name__) | 
|  | 232 | 
|  | 233         model, translation_issues = modelUtils.translate_model_genes( | 
|  | 234             model=model, | 
|  | 235             mapping_df= pd.read_csv(ARGS.tool_dir + "/local/mappings/genes_human.csv", dtype={'entrez_id': str}), | 
|  | 236             target_nomenclature=ARGS.gene_format, | 
|  | 237             source_nomenclature='HGNC_symbol', | 
|  | 238             logger=logger | 
|  | 239         ) | 
|  | 240 | 
|  | 241     if ARGS.name == "Custom_model" and ARGS.gene_format != "Default": | 
|  | 242         logging.basicConfig(level=logging.INFO) | 
|  | 243         logger = logging.getLogger(__name__) | 
|  | 244 | 
|  | 245         # Take a small, clean sample of gene IDs (skipping placeholders like 0) | 
|  | 246         ids_sample = sample_valid_gene_ids(model.genes, limit=10) | 
|  | 247         if not ids_sample: | 
|  | 248             raise utils.DataErr( | 
|  | 249                 "Custom_model", | 
|  | 250                 "No valid gene IDs found (many may be placeholders like 0)." | 
|  | 251             ) | 
|  | 252 | 
|  | 253         # Detect source nomenclature on the sample | 
|  | 254         types = [] | 
|  | 255         for gid in ids_sample: | 
|  | 256             try: | 
|  | 257                 t = modelUtils.gene_type(gid, "Custom_model") | 
|  | 258             except Exception as e: | 
|  | 259                 # Keep it simple: skip problematic IDs | 
|  | 260                 logger.debug(f"gene_type failed for {gid}: {e}") | 
|  | 261                 t = None | 
|  | 262             if t: | 
|  | 263                 types.append(t) | 
|  | 264 | 
|  | 265         if not types: | 
|  | 266             raise utils.DataErr( | 
|  | 267                 "Custom_model", | 
|  | 268                 "Could not detect a known gene nomenclature from the sample." | 
|  | 269             ) | 
|  | 270 | 
|  | 271         unique_types = set(types) | 
|  | 272         if len(unique_types) > 1: | 
|  | 273             raise utils.DataErr( | 
|  | 274                 "Custom_model", | 
|  | 275                 "Mixed or inconsistent gene nomenclatures detected. " | 
|  | 276                 "Please unify them before converting." | 
|  | 277             ) | 
|  | 278 | 
|  | 279         source_nomenclature = types[0] | 
|  | 280 | 
|  | 281         # Convert only if needed | 
|  | 282         if source_nomenclature != ARGS.gene_format: | 
|  | 283             model, translation_issues = modelUtils.translate_model_genes( | 
|  | 284                 model=model, | 
|  | 285                 mapping_df= pd.read_csv(ARGS.tool_dir + "/local/mappings/genes_human.csv", dtype={'entrez_id': str}), | 
|  | 286                 target_nomenclature=ARGS.gene_format, | 
|  | 287                 source_nomenclature=source_nomenclature, | 
|  | 288                 logger=logger | 
|  | 289             ) | 
|  | 290 | 
|  | 291     # generate data | 
|  | 292     rules = modelUtils.generate_rules(model, asParsed = False) | 
|  | 293     reactions = modelUtils.generate_reactions(model, asParsed = False) | 
|  | 294     bounds = modelUtils.generate_bounds(model) | 
|  | 295     medium = modelUtils.get_medium(model) | 
|  | 296     objective_function = modelUtils.extract_objective_coefficients(model) | 
|  | 297 | 
|  | 298     if ARGS.name == "ENGRO2": | 
|  | 299         compartments = modelUtils.generate_compartments(model) | 
|  | 300 | 
|  | 301     df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "GPR"]) | 
|  | 302     df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Formula"]) | 
|  | 303 | 
|  | 304     # Create DataFrame for translation issues | 
|  | 305     df_translation_issues = pd.DataFrame([ | 
|  | 306         {"ReactionID": rxn_id, "TranslationIssues": issues} | 
|  | 307         for rxn_id, issues in translation_issues.items() | 
|  | 308     ]) | 
|  | 309 | 
|  | 310     df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"}) | 
|  | 311     df_medium = medium.rename(columns = {"reaction": "ReactionID"}) | 
|  | 312     df_medium["InMedium"] = True | 
|  | 313 | 
|  | 314     merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer") | 
|  | 315     merged = merged.merge(df_bounds, on = "ReactionID", how = "outer") | 
|  | 316     merged = merged.merge(objective_function, on = "ReactionID", how = "outer") | 
|  | 317     if ARGS.name == "ENGRO2": | 
|  | 318         merged = merged.merge(compartments, on = "ReactionID", how = "outer") | 
|  | 319     merged = merged.merge(df_medium, on = "ReactionID", how = "left") | 
|  | 320 | 
|  | 321     # Add translation issues column | 
|  | 322     if not df_translation_issues.empty: | 
|  | 323         merged = merged.merge(df_translation_issues, on = "ReactionID", how = "left") | 
|  | 324         merged["TranslationIssues"] = merged["TranslationIssues"].fillna("") | 
|  | 325     else: | 
|  | 326         # Add empty TranslationIssues column if no issues found | 
|  | 327         #merged["TranslationIssues"] = "" | 
|  | 328         pass | 
|  | 329 | 
|  | 330     merged["InMedium"] = merged["InMedium"].fillna(False) | 
|  | 331 | 
|  | 332     merged = merged.sort_values(by = "InMedium", ascending = False) | 
|  | 333 | 
|  | 334     if not ARGS.out_tabular: | 
|  | 335         raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular) | 
|  | 336     save_as_tabular_df(merged, ARGS.out_tabular) | 
|  | 337     expected = ARGS.out_tabular | 
|  | 338 | 
|  | 339     # verify output exists and non-empty | 
|  | 340     if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0: | 
|  | 341         raise utils.DataErr(expected, "Output not created or empty") | 
|  | 342 | 
|  | 343     print("Metabolic_model_setting: completed successfully") | 
|  | 344 | 
|  | 345 if __name__ == '__main__': | 
|  | 346 | 
|  | 347     main() |