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