| 93 | 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 | 
| 147 | 9 from typing import Optional, Tuple, Union, List, Dict | 
| 93 | 10 import utils.reaction_parsing as reactionUtils | 
|  | 11 | 
|  | 12 ARGS : argparse.Namespace | 
| 343 | 13 def process_args(args: List[str] = None) -> argparse.Namespace: | 
|  | 14     """ | 
|  | 15     Parse command-line arguments for CustomDataGenerator. | 
| 93 | 16     """ | 
| 343 | 17 | 
|  | 18     parser = argparse.ArgumentParser( | 
|  | 19         usage="%(prog)s [options]", | 
|  | 20         description="Generate custom data from a given model" | 
|  | 21     ) | 
| 93 | 22 | 
| 343 | 23     parser.add_argument("--out_log", type=str, required=True, | 
|  | 24                         help="Output log file") | 
| 93 | 25 | 
| 343 | 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)") | 
| 93 | 32 | 
| 343 | 33     parser.add_argument("--medium_selector", type=str, required=True, | 
| 393 | 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") | 
| 343 | 38 | 
| 375 | 39     parser.add_argument("--out_tabular", type=str, | 
|  | 40                         help="Output file for the merged dataset (CSV or XLSX)") | 
|  | 41 | 
| 353 | 42     parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__), | 
| 363 | 43                         help="Tool directory (passed from Galaxy as $__tool_directory__)") | 
| 353 | 44 | 
| 93 | 45 | 
| 343 | 46     return parser.parse_args(args) | 
| 93 | 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 ################################- 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. | 
|  | 80 | 
|  | 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 ###############################- FILE SAVING -################################ | 
|  | 151 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None: | 
|  | 152     """ | 
|  | 153     Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath. | 
|  | 154 | 
|  | 155     Args: | 
|  | 156         data : the data to be written to the file. | 
|  | 157         file_path : the path to the .csv file. | 
|  | 158         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 159 | 
|  | 160     Returns: | 
|  | 161         None | 
|  | 162     """ | 
|  | 163     with open(file_path.show(), 'w', newline='') as csvfile: | 
|  | 164         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 165         writer.writeheader() | 
|  | 166 | 
|  | 167         for key, value in data.items(): | 
|  | 168             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 169 | 
|  | 170 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None: | 
|  | 171     """ | 
|  | 172     Saves any dictionary-shaped data in a .csv file created at the given file_path as string. | 
|  | 173 | 
|  | 174     Args: | 
|  | 175         data : the data to be written to the file. | 
|  | 176         file_path : the path to the .csv file. | 
|  | 177         fieldNames : the names of the fields (columns) in the .csv file. | 
|  | 178 | 
|  | 179     Returns: | 
|  | 180         None | 
|  | 181     """ | 
|  | 182     with open(file_path, 'w', newline='') as csvfile: | 
|  | 183         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab") | 
|  | 184         writer.writeheader() | 
|  | 185 | 
|  | 186         for key, value in data.items(): | 
|  | 187             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | 
|  | 188 | 
| 377 | 189 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None: | 
|  | 190     try: | 
|  | 191         os.makedirs(os.path.dirname(path) or ".", exist_ok=True) | 
|  | 192         df.to_csv(path, sep="\t", index=False) | 
|  | 193     except Exception as e: | 
|  | 194         raise utils.DataErr(path, f"failed writing tabular output: {e}") | 
|  | 195 | 
|  | 196 | 
| 93 | 197 ###############################- ENTRY POINT -################################ | 
| 147 | 198 def main(args:List[str] = None) -> None: | 
| 93 | 199     """ | 
|  | 200     Initializes everything and sets the program in motion based on the fronted input arguments. | 
|  | 201 | 
|  | 202     Returns: | 
|  | 203         None | 
|  | 204     """ | 
|  | 205     # get args from frontend (related xml) | 
|  | 206     global ARGS | 
| 147 | 207     ARGS = process_args(args) | 
| 93 | 208 | 
| 343 | 209 | 
| 350 | 210     if ARGS.input: | 
| 343 | 211         # load custom model | 
|  | 212         model = load_custom_model( | 
|  | 213             utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext) | 
|  | 214     else: | 
|  | 215         # load built-in model | 
| 93 | 216 | 
| 343 | 217         try: | 
|  | 218             model_enum = utils.Model[ARGS.model]  # e.g., Model['ENGRO2'] | 
|  | 219         except KeyError: | 
|  | 220             raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model) | 
|  | 221 | 
|  | 222         # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models) | 
|  | 223         try: | 
| 353 | 224             model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir) | 
| 343 | 225         except Exception as e: | 
|  | 226             # Wrap/normalize load errors as DataErr for consistency | 
|  | 227             raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}") | 
|  | 228 | 
|  | 229     # Determine final model name: explicit --name overrides, otherwise use the model id | 
| 393 | 230 | 
| 343 | 231     model_name = ARGS.name if ARGS.name else ARGS.model | 
| 393 | 232 | 
|  | 233 | 
|  | 234     if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default": | 
|  | 235         df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0) | 
|  | 236         ARGS.medium_selector = ARGS.medium_selector.replace("_", " ") | 
|  | 237         medium = df_mediums[[ARGS.medium_selector]] | 
|  | 238         medium = medium[ARGS.medium_selector].to_dict() | 
|  | 239 | 
|  | 240         # Set all reactions to zero in the medium | 
|  | 241         for rxn_id, _ in model.medium.items(): | 
|  | 242             model.reactions.get_by_id(rxn_id).lower_bound = float(0.0) | 
|  | 243 | 
|  | 244         # Set medium conditions | 
|  | 245         for reaction, value in medium.items(): | 
|  | 246             if value is not None: | 
|  | 247                 model.reactions.get_by_id(reaction).lower_bound = -float(value) | 
|  | 248 | 
|  | 249     if ARGS.name == "ENGRO2" and ARGS.gene_format != "Default": | 
|  | 250         utils.convert_genes(model, ARGS.gene_format) | 
| 93 | 251 | 
|  | 252     # generate data | 
|  | 253     rules = generate_rules(model, asParsed = False) | 
|  | 254     reactions = generate_reactions(model, asParsed = False) | 
|  | 255     bounds = generate_bounds(model) | 
|  | 256     medium = get_medium(model) | 
|  | 257 | 
| 343 | 258     df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"]) | 
|  | 259     df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"]) | 
|  | 260 | 
|  | 261     df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"}) | 
|  | 262     df_medium = medium.rename(columns = {"reaction": "ReactionID"}) | 
|  | 263     df_medium["InMedium"] = True # flag per indicare la presenza nel medium | 
|  | 264 | 
|  | 265     merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer") | 
|  | 266     merged = merged.merge(df_bounds, on = "ReactionID", how = "outer") | 
|  | 267 | 
|  | 268     merged = merged.merge(df_medium, on = "ReactionID", how = "left") | 
|  | 269 | 
|  | 270     merged["InMedium"] = merged["InMedium"].fillna(False) | 
|  | 271 | 
|  | 272     merged = merged.sort_values(by = "InMedium", ascending = False) | 
|  | 273 | 
| 359 | 274     #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data") | 
| 343 | 275 | 
|  | 276     #merged.to_csv(out_file, sep = '\t', index = False) | 
|  | 277 | 
|  | 278 | 
|  | 279     #### | 
|  | 280 | 
| 384 | 281 | 
|  | 282     if not ARGS.out_tabular: | 
|  | 283         raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular) | 
|  | 284     save_as_tabular_df(merged, ARGS.out_tabular) | 
|  | 285     expected = ARGS.out_tabular | 
| 377 | 286 | 
|  | 287     # verify output exists and non-empty | 
|  | 288     if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0: | 
|  | 289         raise utils.DataErr(expected, "Output non creato o vuoto") | 
| 343 | 290 | 
| 386 | 291     print("CustomDataGenerator: completed successfully") | 
| 93 | 292 | 
|  | 293 if __name__ == '__main__': | 
|  | 294     main() |