| 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 | 
| 414 | 75 ################################- DATA GENERATION -################################ | 
|  | 76 ReactionId = str | 
|  | 77 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]: | 
|  | 78     """ | 
|  | 79     Generates a dictionary mapping reaction ids to rules from the model. | 
| 406 | 80 | 
| 414 | 81     Args: | 
|  | 82         model : the model to derive data from. | 
|  | 83         asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings. | 
|  | 84 | 
|  | 85     Returns: | 
|  | 86         Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules. | 
|  | 87         Dict[ReactionId, str] : the generated dictionary of raw rules. | 
|  | 88     """ | 
|  | 89     # Is the below approach convoluted? yes | 
|  | 90     # Ok but is it inefficient? probably | 
|  | 91     # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane) | 
|  | 92     _ruleGetter   =  lambda reaction : reaction.gene_reaction_rule | 
|  | 93     ruleExtractor = (lambda reaction : | 
|  | 94         rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter | 
|  | 95 | 
|  | 96     return { | 
|  | 97         reaction.id : ruleExtractor(reaction) | 
|  | 98         for reaction in model.reactions | 
|  | 99         if reaction.gene_reaction_rule } | 
|  | 100 | 
|  | 101 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]: | 
|  | 102     """ | 
|  | 103     Generates a dictionary mapping reaction ids to reaction formulas from the model. | 
|  | 104 | 
|  | 105     Args: | 
|  | 106         model : the model to derive data from. | 
|  | 107         asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are. | 
|  | 108 | 
|  | 109     Returns: | 
|  | 110         Dict[ReactionId, str] : the generated dictionary. | 
|  | 111     """ | 
|  | 112 | 
|  | 113     unparsedReactions = { | 
|  | 114         reaction.id : reaction.reaction | 
|  | 115         for reaction in model.reactions | 
|  | 116         if reaction.reaction | 
|  | 117     } | 
|  | 118 | 
|  | 119     if not asParsed: return unparsedReactions | 
|  | 120 | 
|  | 121     return reactionUtils.create_reaction_dict(unparsedReactions) | 
|  | 122 | 
|  | 123 def get_medium(model:cobra.Model) -> pd.DataFrame: | 
|  | 124     trueMedium=[] | 
|  | 125     for r in model.reactions: | 
|  | 126         positiveCoeff=0 | 
|  | 127         for m in r.metabolites: | 
|  | 128             if r.get_coefficient(m.id)>0: | 
|  | 129                 positiveCoeff=1; | 
|  | 130         if (positiveCoeff==0 and r.lower_bound<0): | 
|  | 131             trueMedium.append(r.id) | 
|  | 132 | 
|  | 133     df_medium = pd.DataFrame() | 
|  | 134     df_medium["reaction"] = trueMedium | 
|  | 135     return df_medium | 
|  | 136 | 
|  | 137 def generate_bounds(model:cobra.Model) -> pd.DataFrame: | 
|  | 138 | 
|  | 139     rxns = [] | 
|  | 140     for reaction in model.reactions: | 
|  | 141         rxns.append(reaction.id) | 
|  | 142 | 
|  | 143     bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns) | 
|  | 144 | 
|  | 145     for reaction in model.reactions: | 
|  | 146         bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound] | 
|  | 147     return bounds | 
|  | 148 | 
|  | 149 | 
|  | 150 | 
|  | 151 def generate_compartments(model: cobra.Model) -> pd.DataFrame: | 
|  | 152     """ | 
|  | 153     Generates a DataFrame containing compartment information for each reaction. | 
|  | 154     Creates columns for each compartment position (Compartment_1, Compartment_2, etc.) | 
|  | 155 | 
|  | 156     Args: | 
|  | 157         model: the COBRA model to extract compartment data from. | 
|  | 158 | 
|  | 159     Returns: | 
|  | 160         pd.DataFrame: DataFrame with ReactionID and compartment columns | 
|  | 161     """ | 
|  | 162     pathway_data = [] | 
|  | 163 | 
|  | 164     # First pass: determine the maximum number of pathways any reaction has | 
|  | 165     max_pathways = 0 | 
|  | 166     reaction_pathways = {} | 
|  | 167 | 
|  | 168     for reaction in model.reactions: | 
|  | 169         # Get unique pathways from all metabolites in the reaction | 
|  | 170         if type(reaction.annotation['pathways']) == list: | 
|  | 171             reaction_pathways[reaction.id] = reaction.annotation['pathways'] | 
|  | 172             max_pathways = max(max_pathways, len(reaction.annotation['pathways'])) | 
|  | 173         else: | 
|  | 174             reaction_pathways[reaction.id] = [reaction.annotation['pathways']] | 
|  | 175 | 
|  | 176     # Create column names for pathways | 
|  | 177     pathway_columns = [f"Pathway_{i+1}" for i in range(max_pathways)] | 
|  | 178 | 
|  | 179     # Second pass: create the data | 
|  | 180     for reaction_id, pathways in reaction_pathways.items(): | 
|  | 181         row = {"ReactionID": reaction_id} | 
|  | 182 | 
|  | 183         # Fill pathway columns | 
|  | 184         for i in range(max_pathways): | 
|  | 185             col_name = pathway_columns[i] | 
|  | 186             if i < len(pathways): | 
|  | 187                 row[col_name] = pathways[i] | 
|  | 188             else: | 
|  | 189                 row[col_name] = None  # or "" if you prefer empty strings | 
|  | 190 | 
|  | 191         pathway_data.append(row) | 
|  | 192 | 
|  | 193     return pd.DataFrame(pathway_data) | 
| 406 | 194 | 
|  | 195 | 
|  | 196 ###############################- FILE SAVING -################################ | 
|  | 197 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None: | 
|  | 198     """ | 
|  | 199     Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath. | 
|  | 200 | 
|  | 201     Args: | 
|  | 202         data : the data to be written to the file. | 
|  | 203         file_path : the path to the .csv file. | 
|  | 204         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 205 | 
|  | 206     Returns: | 
|  | 207         None | 
|  | 208     """ | 
|  | 209     with open(file_path.show(), 'w', newline='') as csvfile: | 
|  | 210         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 211         writer.writeheader() | 
|  | 212 | 
|  | 213         for key, value in data.items(): | 
|  | 214             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 215 | 
|  | 216 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None: | 
|  | 217     """ | 
|  | 218     Saves any dictionary-shaped data in a .csv file created at the given file_path as string. | 
|  | 219 | 
|  | 220     Args: | 
|  | 221         data : the data to be written to the file. | 
|  | 222         file_path : the path to the .csv file. | 
|  | 223         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 224 | 
|  | 225     Returns: | 
|  | 226         None | 
|  | 227     """ | 
|  | 228     with open(file_path, 'w', newline='') as csvfile: | 
|  | 229         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 230         writer.writeheader() | 
|  | 231 | 
|  | 232         for key, value in data.items(): | 
|  | 233             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 234 | 
|  | 235 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None: | 
|  | 236     try: | 
|  | 237         os.makedirs(os.path.dirname(path) or ".", exist_ok=True) | 
|  | 238         df.to_csv(path, sep="\t", index=False) | 
|  | 239     except Exception as e: | 
|  | 240         raise utils.DataErr(path, f"failed writing tabular output: {e}") | 
|  | 241 | 
|  | 242 | 
|  | 243 ###############################- ENTRY POINT -################################ | 
|  | 244 def main(args:List[str] = None) -> None: | 
|  | 245     """ | 
|  | 246     Initializes everything and sets the program in motion based on the fronted input arguments. | 
|  | 247 | 
|  | 248     Returns: | 
|  | 249         None | 
|  | 250     """ | 
|  | 251     # get args from frontend (related xml) | 
|  | 252     global ARGS | 
|  | 253     ARGS = process_args(args) | 
|  | 254 | 
|  | 255 | 
|  | 256     if ARGS.input: | 
|  | 257         # load custom model | 
|  | 258         model = load_custom_model( | 
|  | 259             utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext) | 
|  | 260     else: | 
|  | 261         # load built-in model | 
|  | 262 | 
|  | 263         try: | 
|  | 264             model_enum = utils.Model[ARGS.model]  # e.g., Model['ENGRO2'] | 
|  | 265         except KeyError: | 
|  | 266             raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model) | 
|  | 267 | 
|  | 268         # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models) | 
|  | 269         try: | 
|  | 270             model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir) | 
|  | 271         except Exception as e: | 
|  | 272             # Wrap/normalize load errors as DataErr for consistency | 
|  | 273             raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}") | 
|  | 274 | 
|  | 275     # Determine final model name: explicit --name overrides, otherwise use the model id | 
|  | 276 | 
|  | 277     model_name = ARGS.name if ARGS.name else ARGS.model | 
|  | 278 | 
|  | 279     if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default": | 
|  | 280         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0) | 
|  | 281         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ") | 
|  | 282         medium = df_mediums[[ARGS.medium_selector]] | 
|  | 283         medium = medium[ARGS.medium_selector].to_dict() | 
|  | 284 | 
|  | 285         # Set all reactions to zero in the medium | 
|  | 286         for rxn_id, _ in model.medium.items(): | 
|  | 287             model.reactions.get_by_id(rxn_id).lower_bound = float(0.0) | 
|  | 288 | 
|  | 289         # Set medium conditions | 
|  | 290         for reaction, value in medium.items(): | 
|  | 291             if value is not None: | 
|  | 292                 model.reactions.get_by_id(reaction).lower_bound = -float(value) | 
|  | 293 | 
|  | 294     if ARGS.name == "ENGRO2" and ARGS.gene_format != "Default": | 
|  | 295 | 
|  | 296         model = utils.convert_genes(model, ARGS.gene_format.replace("HGNC_", "HGNC ")) | 
|  | 297 | 
|  | 298     # generate data | 
| 414 | 299     rules = generate_rules(model, asParsed = False) | 
|  | 300     reactions = generate_reactions(model, asParsed = False) | 
|  | 301     bounds = generate_bounds(model) | 
|  | 302     medium = get_medium(model) | 
| 406 | 303     if ARGS.name == "ENGRO2": | 
| 414 | 304         compartments = generate_compartments(model) | 
| 406 | 305 | 
|  | 306     df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"]) | 
|  | 307     df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"]) | 
|  | 308 | 
|  | 309     df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"}) | 
|  | 310     df_medium = medium.rename(columns = {"reaction": "ReactionID"}) | 
|  | 311     df_medium["InMedium"] = True # flag per indicare la presenza nel medium | 
|  | 312 | 
|  | 313     merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer") | 
|  | 314     merged = merged.merge(df_bounds, on = "ReactionID", how = "outer") | 
|  | 315     if ARGS.name == "ENGRO2": | 
|  | 316         merged = merged.merge(compartments, on = "ReactionID", how = "outer") | 
|  | 317     merged = merged.merge(df_medium, on = "ReactionID", how = "left") | 
|  | 318 | 
|  | 319     merged["InMedium"] = merged["InMedium"].fillna(False) | 
|  | 320 | 
|  | 321     merged = merged.sort_values(by = "InMedium", ascending = False) | 
|  | 322 | 
|  | 323     #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data") | 
|  | 324 | 
|  | 325     #merged.to_csv(out_file, sep = '\t', index = False) | 
|  | 326 | 
|  | 327     #### | 
|  | 328 | 
|  | 329     if not ARGS.out_tabular: | 
|  | 330         raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular) | 
|  | 331     save_as_tabular_df(merged, ARGS.out_tabular) | 
|  | 332     expected = ARGS.out_tabular | 
|  | 333 | 
|  | 334     # verify output exists and non-empty | 
|  | 335     if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0: | 
|  | 336         raise utils.DataErr(expected, "Output non creato o vuoto") | 
|  | 337 | 
|  | 338     print("CustomDataGenerator: completed successfully") | 
|  | 339 | 
|  | 340 if __name__ == '__main__': | 
|  | 341     main() |