| 
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
 | 
| 
370
 | 
    11 import openpyxl
 | 
| 
93
 | 
    12 
 | 
| 
 | 
    13 ARGS : argparse.Namespace
 | 
| 
343
 | 
    14 def process_args(args: List[str] = None) -> argparse.Namespace:
 | 
| 
 | 
    15     """
 | 
| 
 | 
    16     Parse command-line arguments for CustomDataGenerator.
 | 
| 
93
 | 
    17     """
 | 
| 
343
 | 
    18 
 | 
| 
 | 
    19     parser = argparse.ArgumentParser(
 | 
| 
 | 
    20         usage="%(prog)s [options]",
 | 
| 
 | 
    21         description="Generate custom data from a given model"
 | 
| 
 | 
    22     )
 | 
| 
93
 | 
    23 
 | 
| 
343
 | 
    24     parser.add_argument("--out_log", type=str, required=True,
 | 
| 
 | 
    25                         help="Output log file")
 | 
| 
93
 | 
    26 
 | 
| 
343
 | 
    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)")
 | 
| 
93
 | 
    33     
 | 
| 
343
 | 
    34     parser.add_argument("--medium_selector", type=str, required=True,
 | 
| 
 | 
    35                         help="Medium selection option (default/custom)")
 | 
| 
 | 
    36     parser.add_argument("--medium", type=str,
 | 
| 
 | 
    37                         help="Custom medium file if medium_selector=Custom")
 | 
| 
 | 
    38     
 | 
| 
 | 
    39     parser.add_argument("--output_format", type=str, choices=["tabular", "xlsx"], required=True,
 | 
| 
 | 
    40                         help="Output format: CSV (tabular) or Excel (xlsx)")
 | 
| 
 | 
    41     
 | 
| 
375
 | 
    42     parser.add_argument("--out_tabular", type=str,
 | 
| 
 | 
    43                         help="Output file for the merged dataset (CSV or XLSX)")
 | 
| 
 | 
    44     
 | 
| 
 | 
    45     parser.add_argument("--out_xlsx", type=str,
 | 
| 
365
 | 
    46                         help="Output file for the merged dataset (CSV or XLSX)")
 | 
| 
343
 | 
    47     
 | 
| 
353
 | 
    48     parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__),
 | 
| 
363
 | 
    49                         help="Tool directory (passed from Galaxy as $__tool_directory__)")
 | 
| 
353
 | 
    50 
 | 
| 
93
 | 
    51 
 | 
| 
343
 | 
    52     return parser.parse_args(args)
 | 
| 
93
 | 
    53 
 | 
| 
 | 
    54 ################################- INPUT DATA LOADING -################################
 | 
| 
 | 
    55 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
 | 
| 
 | 
    56     """
 | 
| 
 | 
    57     Loads a custom model from a file, either in JSON or XML format.
 | 
| 
 | 
    58 
 | 
| 
 | 
    59     Args:
 | 
| 
 | 
    60         file_path : The path to the file containing the custom model.
 | 
| 
 | 
    61         ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
 | 
| 
 | 
    62 
 | 
| 
 | 
    63     Raises:
 | 
| 
 | 
    64         DataErr : if the file is in an invalid format or cannot be opened for whatever reason.    
 | 
| 
 | 
    65     
 | 
| 
 | 
    66     Returns:
 | 
| 
 | 
    67         cobra.Model : the model, if successfully opened.
 | 
| 
 | 
    68     """
 | 
| 
 | 
    69     ext = ext if ext else file_path.ext
 | 
| 
 | 
    70     try:
 | 
| 
 | 
    71         if ext is utils.FileFormat.XML:
 | 
| 
 | 
    72             return cobra.io.read_sbml_model(file_path.show())
 | 
| 
 | 
    73         
 | 
| 
 | 
    74         if ext is utils.FileFormat.JSON:
 | 
| 
 | 
    75             return cobra.io.load_json_model(file_path.show())
 | 
| 
 | 
    76 
 | 
| 
 | 
    77     except Exception as e: raise utils.DataErr(file_path, e.__str__())
 | 
| 
 | 
    78     raise utils.DataErr(file_path,
 | 
| 
 | 
    79         f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
 | 
| 
 | 
    80 
 | 
| 
 | 
    81 ################################- DATA GENERATION -################################
 | 
| 
 | 
    82 ReactionId = str
 | 
| 
 | 
    83 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]:
 | 
| 
 | 
    84     """
 | 
| 
 | 
    85     Generates a dictionary mapping reaction ids to rules from the model.
 | 
| 
 | 
    86 
 | 
| 
 | 
    87     Args:
 | 
| 
 | 
    88         model : the model to derive data from.
 | 
| 
 | 
    89         asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings.
 | 
| 
 | 
    90 
 | 
| 
 | 
    91     Returns:
 | 
| 
 | 
    92         Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules.
 | 
| 
 | 
    93         Dict[ReactionId, str] : the generated dictionary of raw rules.
 | 
| 
 | 
    94     """
 | 
| 
 | 
    95     # Is the below approach convoluted? yes
 | 
| 
 | 
    96     # Ok but is it inefficient? probably
 | 
| 
 | 
    97     # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane)
 | 
| 
 | 
    98     _ruleGetter   =  lambda reaction : reaction.gene_reaction_rule
 | 
| 
 | 
    99     ruleExtractor = (lambda reaction :
 | 
| 
 | 
   100         rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter
 | 
| 
 | 
   101 
 | 
| 
 | 
   102     return {
 | 
| 
 | 
   103         reaction.id : ruleExtractor(reaction)
 | 
| 
 | 
   104         for reaction in model.reactions
 | 
| 
 | 
   105         if reaction.gene_reaction_rule }
 | 
| 
 | 
   106 
 | 
| 
 | 
   107 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]:
 | 
| 
 | 
   108     """
 | 
| 
 | 
   109     Generates a dictionary mapping reaction ids to reaction formulas from the model.
 | 
| 
 | 
   110 
 | 
| 
 | 
   111     Args:
 | 
| 
 | 
   112         model : the model to derive data from.
 | 
| 
 | 
   113         asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are.
 | 
| 
 | 
   114 
 | 
| 
 | 
   115     Returns:
 | 
| 
 | 
   116         Dict[ReactionId, str] : the generated dictionary.
 | 
| 
 | 
   117     """
 | 
| 
 | 
   118 
 | 
| 
 | 
   119     unparsedReactions = {
 | 
| 
 | 
   120         reaction.id : reaction.reaction
 | 
| 
 | 
   121         for reaction in model.reactions
 | 
| 
 | 
   122         if reaction.reaction 
 | 
| 
 | 
   123     }
 | 
| 
 | 
   124 
 | 
| 
 | 
   125     if not asParsed: return unparsedReactions
 | 
| 
 | 
   126     
 | 
| 
 | 
   127     return reactionUtils.create_reaction_dict(unparsedReactions)
 | 
| 
 | 
   128 
 | 
| 
 | 
   129 def get_medium(model:cobra.Model) -> pd.DataFrame:
 | 
| 
 | 
   130     trueMedium=[]
 | 
| 
 | 
   131     for r in model.reactions:
 | 
| 
 | 
   132         positiveCoeff=0
 | 
| 
 | 
   133         for m in r.metabolites:
 | 
| 
 | 
   134             if r.get_coefficient(m.id)>0:
 | 
| 
 | 
   135                 positiveCoeff=1;
 | 
| 
 | 
   136         if (positiveCoeff==0 and r.lower_bound<0):
 | 
| 
 | 
   137             trueMedium.append(r.id)
 | 
| 
 | 
   138 
 | 
| 
 | 
   139     df_medium = pd.DataFrame()
 | 
| 
 | 
   140     df_medium["reaction"] = trueMedium
 | 
| 
 | 
   141     return df_medium
 | 
| 
 | 
   142 
 | 
| 
 | 
   143 def generate_bounds(model:cobra.Model) -> pd.DataFrame:
 | 
| 
 | 
   144 
 | 
| 
 | 
   145     rxns = []
 | 
| 
 | 
   146     for reaction in model.reactions:
 | 
| 
 | 
   147         rxns.append(reaction.id)
 | 
| 
 | 
   148 
 | 
| 
 | 
   149     bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns)
 | 
| 
 | 
   150 
 | 
| 
 | 
   151     for reaction in model.reactions:
 | 
| 
 | 
   152         bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound]
 | 
| 
 | 
   153     return bounds
 | 
| 
 | 
   154 
 | 
| 
 | 
   155 
 | 
| 
 | 
   156 ###############################- FILE SAVING -################################
 | 
| 
 | 
   157 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
 | 
| 
 | 
   158     """
 | 
| 
 | 
   159     Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
 | 
| 
 | 
   160 
 | 
| 
 | 
   161     Args:
 | 
| 
 | 
   162         data : the data to be written to the file.
 | 
| 
 | 
   163         file_path : the path to the .csv file.
 | 
| 
 | 
   164         fieldNames : the names of the fields (columns) in the .csv file.
 | 
| 
 | 
   165     
 | 
| 
 | 
   166     Returns:
 | 
| 
 | 
   167         None
 | 
| 
 | 
   168     """
 | 
| 
 | 
   169     with open(file_path.show(), 'w', newline='') as csvfile:
 | 
| 
 | 
   170         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
 | 
| 
 | 
   171         writer.writeheader()
 | 
| 
 | 
   172 
 | 
| 
 | 
   173         for key, value in data.items():
 | 
| 
 | 
   174             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
 | 
| 
 | 
   175 
 | 
| 
 | 
   176 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
 | 
| 
 | 
   177     """
 | 
| 
 | 
   178     Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
 | 
| 
 | 
   179 
 | 
| 
 | 
   180     Args:
 | 
| 
 | 
   181         data : the data to be written to the file.
 | 
| 
 | 
   182         file_path : the path to the .csv file.
 | 
| 
 | 
   183         fieldNames : the names of the fields (columns) in the .csv file.
 | 
| 
 | 
   184     
 | 
| 
 | 
   185     Returns:
 | 
| 
 | 
   186         None
 | 
| 
 | 
   187     """
 | 
| 
 | 
   188     with open(file_path, 'w', newline='') as csvfile:
 | 
| 
 | 
   189         writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
 | 
| 
 | 
   190         writer.writeheader()
 | 
| 
 | 
   191 
 | 
| 
 | 
   192         for key, value in data.items():
 | 
| 
 | 
   193             writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
 | 
| 
 | 
   194 
 | 
| 
377
 | 
   195 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None:
 | 
| 
 | 
   196     try:
 | 
| 
 | 
   197         os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
 | 
| 
 | 
   198         df.to_csv(path, sep="\t", index=False)
 | 
| 
 | 
   199     except Exception as e:
 | 
| 
 | 
   200         raise utils.DataErr(path, f"failed writing tabular output: {e}")
 | 
| 
 | 
   201 
 | 
| 
 | 
   202 def save_as_xlsx_df(df: pd.DataFrame, path: str) -> None:
 | 
| 
 | 
   203     try:
 | 
| 
 | 
   204         if not path.lower().endswith(".xlsx"):
 | 
| 
 | 
   205             path += ".xlsx"
 | 
| 
 | 
   206         os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
 | 
| 
 | 
   207         df.to_excel(path, index=False)
 | 
| 
 | 
   208     except Exception as e:
 | 
| 
 | 
   209         raise utils.DataErr(path, f"failed writing xlsx output: {e}")
 | 
| 
 | 
   210 
 | 
| 
93
 | 
   211 ###############################- ENTRY POINT -################################
 | 
| 
147
 | 
   212 def main(args:List[str] = None) -> None:
 | 
| 
93
 | 
   213     """
 | 
| 
 | 
   214     Initializes everything and sets the program in motion based on the fronted input arguments.
 | 
| 
 | 
   215     
 | 
| 
 | 
   216     Returns:
 | 
| 
 | 
   217         None
 | 
| 
 | 
   218     """
 | 
| 
 | 
   219     # get args from frontend (related xml)
 | 
| 
 | 
   220     global ARGS
 | 
| 
147
 | 
   221     ARGS = process_args(args)
 | 
| 
93
 | 
   222 
 | 
| 
343
 | 
   223 
 | 
| 
350
 | 
   224     if ARGS.input:
 | 
| 
343
 | 
   225         # load custom model
 | 
| 
 | 
   226         model = load_custom_model(
 | 
| 
 | 
   227             utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
 | 
| 
 | 
   228     else:
 | 
| 
 | 
   229         # load built-in model
 | 
| 
93
 | 
   230 
 | 
| 
343
 | 
   231         try:
 | 
| 
 | 
   232             model_enum = utils.Model[ARGS.model]  # e.g., Model['ENGRO2']
 | 
| 
 | 
   233         except KeyError:
 | 
| 
 | 
   234             raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model)
 | 
| 
 | 
   235 
 | 
| 
 | 
   236         # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models)
 | 
| 
 | 
   237         try:
 | 
| 
353
 | 
   238             model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir)
 | 
| 
343
 | 
   239         except Exception as e:
 | 
| 
 | 
   240             # Wrap/normalize load errors as DataErr for consistency
 | 
| 
 | 
   241             raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}")
 | 
| 
 | 
   242 
 | 
| 
 | 
   243     # Determine final model name: explicit --name overrides, otherwise use the model id
 | 
| 
 | 
   244     model_name = ARGS.name if ARGS.name else ARGS.model
 | 
| 
93
 | 
   245 
 | 
| 
 | 
   246     # generate data
 | 
| 
 | 
   247     rules = generate_rules(model, asParsed = False)
 | 
| 
 | 
   248     reactions = generate_reactions(model, asParsed = False)
 | 
| 
 | 
   249     bounds = generate_bounds(model)
 | 
| 
 | 
   250     medium = get_medium(model)
 | 
| 
 | 
   251 
 | 
| 
343
 | 
   252     df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
 | 
| 
 | 
   253     df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
 | 
| 
 | 
   254 
 | 
| 
 | 
   255     df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
 | 
| 
 | 
   256     df_medium = medium.rename(columns = {"reaction": "ReactionID"})
 | 
| 
 | 
   257     df_medium["InMedium"] = True # flag per indicare la presenza nel medium
 | 
| 
 | 
   258 
 | 
| 
 | 
   259     merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
 | 
| 
 | 
   260     merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
 | 
| 
 | 
   261 
 | 
| 
 | 
   262     merged = merged.merge(df_medium, on = "ReactionID", how = "left")
 | 
| 
 | 
   263 
 | 
| 
 | 
   264     merged["InMedium"] = merged["InMedium"].fillna(False)
 | 
| 
 | 
   265 
 | 
| 
 | 
   266     merged = merged.sort_values(by = "InMedium", ascending = False)
 | 
| 
 | 
   267 
 | 
| 
359
 | 
   268     #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data")
 | 
| 
343
 | 
   269 
 | 
| 
 | 
   270     #merged.to_csv(out_file, sep = '\t', index = False)
 | 
| 
 | 
   271 
 | 
| 
 | 
   272 
 | 
| 
 | 
   273     ####
 | 
| 
 | 
   274 
 | 
| 
377
 | 
   275     # write only the requested output
 | 
| 
343
 | 
   276     if ARGS.output_format == "xlsx":
 | 
| 
375
 | 
   277         if not ARGS.out_xlsx:
 | 
| 
 | 
   278             raise utils.ArgsErr("out_xlsx", "output path (--out_xlsx) is required when output_format == xlsx", ARGS.out_xlsx)
 | 
| 
377
 | 
   279         save_as_xlsx_df(merged, ARGS.out_xlsx)
 | 
| 
 | 
   280         expected = ARGS.out_xlsx
 | 
| 
343
 | 
   281     else:
 | 
| 
375
 | 
   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)
 | 
| 
377
 | 
   284         save_as_tabular_df(merged, ARGS.out_tabular)
 | 
| 
 | 
   285         expected = ARGS.out_tabular
 | 
| 
 | 
   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 
 | 
| 
367
 | 
   291 print("CustomDataGenerator: completed successfully")
 | 
| 
93
 | 
   292 
 | 
| 
 | 
   293 if __name__ == '__main__':
 | 
| 
 | 
   294     main() |