456
|
1 """
|
|
2 Utilities for generating and manipulating COBRA models and related metadata.
|
|
3
|
|
4 This module includes helpers to:
|
|
5 - extract rules, reactions, bounds, objective coefficients, and compartments
|
|
6 - build a COBRA model from a tabular file
|
|
7 - set objective and medium from dataframes
|
|
8 - validate a model and convert gene identifiers
|
|
9 - translate model GPRs using mapping tables
|
|
10 """
|
418
|
11 import os
|
|
12 import cobra
|
|
13 import pandas as pd
|
419
|
14 import re
|
426
|
15 import logging
|
419
|
16 from typing import Optional, Tuple, Union, List, Dict, Set
|
426
|
17 from collections import defaultdict
|
418
|
18 import utils.rule_parsing as rulesUtils
|
419
|
19 import utils.reaction_parsing as reactionUtils
|
|
20 from cobra import Model as cobraModel, Reaction, Metabolite
|
490
|
21 import sys
|
|
22
|
|
23
|
|
24 ############################ check_methods ####################################
|
|
25 def gene_type(l :str, name :str) -> str:
|
|
26 """
|
|
27 Determine the type of gene ID.
|
|
28
|
|
29 Args:
|
|
30 l (str): The gene identifier to check.
|
|
31 name (str): The name of the dataset, used in error messages.
|
|
32
|
|
33 Returns:
|
|
34 str: The type of gene ID ('hugo_id', 'ensembl_gene_id', 'symbol', or 'entrez_id').
|
|
35
|
|
36 Raises:
|
|
37 sys.exit: If the gene ID type is not supported, the execution is aborted.
|
|
38 """
|
|
39 if check_hgnc(l):
|
|
40 return 'hugo_id'
|
|
41 elif check_ensembl(l):
|
|
42 return 'ensembl_gene_id'
|
|
43 elif check_symbol(l):
|
|
44 return 'symbol'
|
|
45 elif check_entrez(l):
|
|
46 return 'entrez_id'
|
|
47 else:
|
|
48 sys.exit('Execution aborted:\n' +
|
|
49 'gene ID type in ' + name + ' not supported. Supported ID'+
|
|
50 'types are: HUGO ID, Ensemble ID, HUGO symbol, Entrez ID\n')
|
|
51
|
|
52 def check_hgnc(l :str) -> bool:
|
|
53 """
|
|
54 Check if a gene identifier follows the HGNC format.
|
|
55
|
|
56 Args:
|
|
57 l (str): The gene identifier to check.
|
|
58
|
|
59 Returns:
|
|
60 bool: True if the gene identifier follows the HGNC format, False otherwise.
|
|
61 """
|
|
62 if len(l) > 5:
|
|
63 if (l.upper()).startswith('HGNC:'):
|
|
64 return l[5:].isdigit()
|
|
65 else:
|
|
66 return False
|
|
67 else:
|
|
68 return False
|
|
69
|
|
70 def check_ensembl(l :str) -> bool:
|
|
71 """
|
|
72 Check if a gene identifier follows the Ensembl format.
|
|
73
|
|
74 Args:
|
|
75 l (str): The gene identifier to check.
|
|
76
|
|
77 Returns:
|
|
78 bool: True if the gene identifier follows the Ensembl format, False otherwise.
|
|
79 """
|
|
80 return l.upper().startswith('ENS')
|
|
81
|
|
82
|
|
83 def check_symbol(l :str) -> bool:
|
|
84 """
|
|
85 Check if a gene identifier follows the symbol format.
|
|
86
|
|
87 Args:
|
|
88 l (str): The gene identifier to check.
|
|
89
|
|
90 Returns:
|
|
91 bool: True if the gene identifier follows the symbol format, False otherwise.
|
|
92 """
|
|
93 if len(l) > 0:
|
|
94 if l[0].isalpha() and l[1:].isalnum():
|
|
95 return True
|
|
96 else:
|
|
97 return False
|
|
98 else:
|
|
99 return False
|
|
100
|
|
101 def check_entrez(l :str) -> bool:
|
|
102 """
|
|
103 Check if a gene identifier follows the Entrez ID format.
|
|
104
|
|
105 Args:
|
|
106 l (str): The gene identifier to check.
|
|
107
|
|
108 Returns:
|
|
109 bool: True if the gene identifier follows the Entrez ID format, False otherwise.
|
|
110 """
|
|
111 if len(l) > 0:
|
|
112 return l.isdigit()
|
|
113 else:
|
|
114 return False
|
418
|
115
|
|
116 ################################- DATA GENERATION -################################
|
|
117 ReactionId = str
|
419
|
118 def generate_rules(model: cobraModel, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]:
|
418
|
119 """
|
456
|
120 Generate a dictionary mapping reaction IDs to GPR rules from the model.
|
418
|
121
|
|
122 Args:
|
456
|
123 model: COBRA model to derive data from.
|
|
124 asParsed: If True, parse rules into a nested list structure; otherwise keep raw strings.
|
418
|
125
|
|
126 Returns:
|
456
|
127 Dict[ReactionId, rulesUtils.OpList]: Parsed rules by reaction ID.
|
|
128 Dict[ReactionId, str]: Raw rules by reaction ID.
|
418
|
129 """
|
|
130 _ruleGetter = lambda reaction : reaction.gene_reaction_rule
|
|
131 ruleExtractor = (lambda reaction :
|
|
132 rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter
|
|
133
|
|
134 return {
|
|
135 reaction.id : ruleExtractor(reaction)
|
|
136 for reaction in model.reactions
|
|
137 if reaction.gene_reaction_rule }
|
|
138
|
419
|
139 def generate_reactions(model :cobraModel, *, asParsed = True) -> Dict[ReactionId, str]:
|
418
|
140 """
|
456
|
141 Generate a dictionary mapping reaction IDs to reaction formulas from the model.
|
418
|
142
|
|
143 Args:
|
456
|
144 model: COBRA model to derive data from.
|
|
145 asParsed: If True, convert formulas into a parsed representation; otherwise keep raw strings.
|
418
|
146
|
|
147 Returns:
|
456
|
148 Dict[ReactionId, str]: Reactions by reaction ID (parsed if requested).
|
418
|
149 """
|
|
150
|
|
151 unparsedReactions = {
|
|
152 reaction.id : reaction.reaction
|
|
153 for reaction in model.reactions
|
|
154 if reaction.reaction
|
|
155 }
|
|
156
|
|
157 if not asParsed: return unparsedReactions
|
|
158
|
|
159 return reactionUtils.create_reaction_dict(unparsedReactions)
|
|
160
|
419
|
161 def get_medium(model:cobraModel) -> pd.DataFrame:
|
456
|
162 """
|
|
163 Extract the uptake reactions representing the model medium.
|
|
164
|
|
165 Returns a DataFrame with a single column 'reaction' listing exchange reactions
|
|
166 with negative lower bound and no positive stoichiometric coefficients (uptake only).
|
|
167 """
|
418
|
168 trueMedium=[]
|
|
169 for r in model.reactions:
|
|
170 positiveCoeff=0
|
|
171 for m in r.metabolites:
|
|
172 if r.get_coefficient(m.id)>0:
|
|
173 positiveCoeff=1;
|
|
174 if (positiveCoeff==0 and r.lower_bound<0):
|
|
175 trueMedium.append(r.id)
|
|
176
|
|
177 df_medium = pd.DataFrame()
|
|
178 df_medium["reaction"] = trueMedium
|
|
179 return df_medium
|
|
180
|
426
|
181 def extract_objective_coefficients(model: cobraModel) -> pd.DataFrame:
|
|
182 """
|
456
|
183 Extract objective coefficients for each reaction.
|
|
184
|
426
|
185 Args:
|
456
|
186 model: COBRA model
|
|
187
|
426
|
188 Returns:
|
456
|
189 pd.DataFrame with columns: ReactionID, ObjectiveCoefficient
|
426
|
190 """
|
|
191 coeffs = []
|
456
|
192 # model.objective.expression is a linear expression
|
426
|
193 objective_expr = model.objective.expression.as_coefficients_dict()
|
|
194
|
|
195 for reaction in model.reactions:
|
|
196 coeff = objective_expr.get(reaction.forward_variable, 0.0)
|
|
197 coeffs.append({
|
|
198 "ReactionID": reaction.id,
|
|
199 "ObjectiveCoefficient": coeff
|
|
200 })
|
|
201
|
|
202 return pd.DataFrame(coeffs)
|
|
203
|
419
|
204 def generate_bounds(model:cobraModel) -> pd.DataFrame:
|
456
|
205 """
|
|
206 Build a DataFrame of lower/upper bounds for all reactions.
|
|
207
|
|
208 Returns:
|
|
209 pd.DataFrame indexed by reaction IDs with columns ['lower_bound', 'upper_bound'].
|
|
210 """
|
418
|
211
|
|
212 rxns = []
|
|
213 for reaction in model.reactions:
|
|
214 rxns.append(reaction.id)
|
|
215
|
|
216 bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns)
|
|
217
|
|
218 for reaction in model.reactions:
|
|
219 bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound]
|
|
220 return bounds
|
|
221
|
|
222
|
|
223
|
419
|
224 def generate_compartments(model: cobraModel) -> pd.DataFrame:
|
418
|
225 """
|
|
226 Generates a DataFrame containing compartment information for each reaction.
|
|
227 Creates columns for each compartment position (Compartment_1, Compartment_2, etc.)
|
|
228
|
|
229 Args:
|
|
230 model: the COBRA model to extract compartment data from.
|
|
231
|
|
232 Returns:
|
|
233 pd.DataFrame: DataFrame with ReactionID and compartment columns
|
|
234 """
|
|
235 pathway_data = []
|
|
236
|
|
237 # First pass: determine the maximum number of pathways any reaction has
|
|
238 max_pathways = 0
|
|
239 reaction_pathways = {}
|
|
240
|
|
241 for reaction in model.reactions:
|
|
242 # Get unique pathways from all metabolites in the reaction
|
503
|
243 if 'pathways' in reaction.annotation:
|
|
244 if type(reaction.annotation['pathways']) == list:
|
|
245 reaction_pathways[reaction.id] = reaction.annotation['pathways']
|
|
246 max_pathways = max(max_pathways, len(reaction.annotation['pathways']))
|
|
247 else:
|
|
248 reaction_pathways[reaction.id] = [reaction.annotation['pathways']]
|
418
|
249 else:
|
503
|
250 # No pathway annotation - use empty list
|
|
251 reaction_pathways[reaction.id] = []
|
418
|
252
|
|
253 # Create column names for pathways
|
|
254 pathway_columns = [f"Pathway_{i+1}" for i in range(max_pathways)]
|
|
255
|
|
256 # Second pass: create the data
|
|
257 for reaction_id, pathways in reaction_pathways.items():
|
|
258 row = {"ReactionID": reaction_id}
|
|
259
|
|
260 # Fill pathway columns
|
|
261 for i in range(max_pathways):
|
|
262 col_name = pathway_columns[i]
|
|
263 if i < len(pathways):
|
|
264 row[col_name] = pathways[i]
|
|
265 else:
|
|
266 row[col_name] = None # or "" if you prefer empty strings
|
|
267
|
|
268 pathway_data.append(row)
|
|
269
|
419
|
270 return pd.DataFrame(pathway_data)
|
|
271
|
|
272
|
|
273
|
|
274 def build_cobra_model_from_csv(csv_path: str, model_id: str = "new_model") -> cobraModel:
|
|
275 """
|
456
|
276 Build a COBRApy model from a tabular file with reaction data.
|
|
277
|
419
|
278 Args:
|
456
|
279 csv_path: Path to the tab-separated file.
|
|
280 model_id: ID for the newly created model.
|
|
281
|
419
|
282 Returns:
|
456
|
283 cobra.Model: The constructed COBRApy model.
|
419
|
284 """
|
|
285
|
501
|
286 # Try to detect separator
|
|
287 with open(csv_path, 'r') as f:
|
|
288 first_line = f.readline()
|
|
289 sep = '\t' if '\t' in first_line else ','
|
|
290
|
|
291 df = pd.read_csv(csv_path, sep=sep)
|
|
292
|
|
293 # Check required columns
|
|
294 required_cols = ['ReactionID', 'Formula']
|
|
295 missing_cols = [col for col in required_cols if col not in df.columns]
|
|
296 if missing_cols:
|
|
297 raise ValueError(f"Missing required columns: {missing_cols}. Available columns: {list(df.columns)}")
|
419
|
298
|
|
299 model = cobraModel(model_id)
|
|
300
|
|
301 metabolites_dict = {}
|
|
302 compartments_dict = {}
|
|
303
|
456
|
304 print(f"Building model from {len(df)} reactions...")
|
419
|
305
|
|
306 for idx, row in df.iterrows():
|
448
|
307 reaction_formula = str(row['Formula']).strip()
|
419
|
308 if not reaction_formula or reaction_formula == 'nan':
|
|
309 continue
|
|
310
|
|
311 metabolites = extract_metabolites_from_reaction(reaction_formula)
|
|
312
|
|
313 for met_id in metabolites:
|
|
314 compartment = extract_compartment_from_metabolite(met_id)
|
|
315
|
|
316 if compartment not in compartments_dict:
|
|
317 compartments_dict[compartment] = compartment
|
|
318
|
|
319 if met_id not in metabolites_dict:
|
|
320 metabolites_dict[met_id] = Metabolite(
|
|
321 id=met_id,
|
|
322 compartment=compartment,
|
|
323 name=met_id.replace(f"_{compartment}", "").replace("__", "_")
|
|
324 )
|
|
325
|
|
326 model.compartments = compartments_dict
|
|
327
|
|
328 model.add_metabolites(list(metabolites_dict.values()))
|
|
329
|
456
|
330 print(f"Added {len(metabolites_dict)} metabolites and {len(compartments_dict)} compartments")
|
419
|
331
|
|
332 reactions_added = 0
|
|
333 reactions_skipped = 0
|
|
334
|
|
335 for idx, row in df.iterrows():
|
|
336
|
|
337 reaction_id = str(row['ReactionID']).strip()
|
427
|
338 reaction_formula = str(row['Formula']).strip()
|
419
|
339
|
|
340 if not reaction_formula or reaction_formula == 'nan':
|
456
|
341 raise ValueError(f"Missing reaction formula for {reaction_id}")
|
419
|
342
|
|
343 reaction = Reaction(reaction_id)
|
|
344 reaction.name = reaction_id
|
|
345
|
|
346 reaction.lower_bound = float(row['lower_bound']) if pd.notna(row['lower_bound']) else -1000.0
|
|
347 reaction.upper_bound = float(row['upper_bound']) if pd.notna(row['upper_bound']) else 1000.0
|
|
348
|
427
|
349 if pd.notna(row['GPR']) and str(row['GPR']).strip():
|
|
350 reaction.gene_reaction_rule = str(row['GPR']).strip()
|
419
|
351
|
|
352 try:
|
|
353 parse_reaction_formula(reaction, reaction_formula, metabolites_dict)
|
|
354 except Exception as e:
|
456
|
355 print(f"Error parsing reaction {reaction_id}: {e}")
|
419
|
356 reactions_skipped += 1
|
|
357 continue
|
|
358
|
|
359 model.add_reactions([reaction])
|
|
360 reactions_added += 1
|
|
361
|
|
362
|
456
|
363 print(f"Added {reactions_added} reactions, skipped {reactions_skipped} reactions")
|
419
|
364
|
430
|
365 # set objective function
|
|
366 set_objective_from_csv(model, df, obj_col="ObjectiveCoefficient")
|
|
367
|
419
|
368 set_medium_from_data(model, df)
|
|
369
|
456
|
370 print(f"Model completed: {len(model.reactions)} reactions, {len(model.metabolites)} metabolites")
|
419
|
371
|
|
372 return model
|
|
373
|
|
374
|
|
375 # Estrae tutti gli ID metaboliti nella formula (gestisce prefissi numerici + underscore)
|
499
|
376 #def extract_metabolites_from_reaction(reaction_formula: str) -> Set[str]:
|
|
377 # """
|
|
378 # Extract metabolite IDs from a reaction formula.
|
|
379 # Robust pattern: tokens ending with _<compartment> (e.g., _c, _m, _e),
|
|
380 # allowing leading digits/underscores.
|
|
381 # """
|
|
382 # metabolites = set()
|
|
383 # # optional coefficient followed by a token ending with _<letters>
|
|
384 # if reaction_formula[-1] == ']' and reaction_formula[-3] == '[':
|
|
385 # pattern = r'(?:\d+(?:\.\d+)?\s+)?([A-Za-z0-9_]+[[A-Za-z0-9]]+)'
|
|
386 # else:
|
|
387 # pattern = r'(?:\d+(?:\.\d+)?\s+)?([A-Za-z0-9_]+_[A-Za-z0-9]+)'
|
|
388 # matches = re.findall(pattern, reaction_formula)
|
|
389 # metabolites.update(matches)
|
|
390 # return metabolites
|
|
391
|
|
392
|
419
|
393 def extract_metabolites_from_reaction(reaction_formula: str) -> Set[str]:
|
|
394 """
|
500
|
395 Extract metabolite IDs from a reaction formula.
|
|
396
|
|
397 Handles:
|
|
398 - optional stoichiometric coefficients (integers or decimals)
|
|
399 - compartment tags at the end of the metabolite, either [c] or _c
|
|
400
|
|
401 Returns the IDs including the compartment suffix exactly as written.
|
419
|
402 """
|
499
|
403 pattern = re.compile(
|
500
|
404 r'(?:^|(?<=\s)|(?<=\+)|(?<=,)|(?<==)|(?<=:))' # left boundary (start, space, +, comma, =, :)
|
501
|
405 r'(?:\d+(?:\.\d+)?\s+)?' # optional coefficient (requires space after)
|
|
406 r'([A-Za-z0-9][A-Za-z0-9_]*(?:\[[A-Za-z0-9]+\]|_[A-Za-z0-9]+))' # metabolite + compartment (can start with number)
|
499
|
407 )
|
|
408 return {m.group(1) for m in pattern.finditer(reaction_formula)}
|
419
|
409
|
|
410
|
500
|
411
|
419
|
412 def extract_compartment_from_metabolite(metabolite_id: str) -> str:
|
456
|
413 """Extract the compartment from a metabolite ID."""
|
500
|
414 if '_' == metabolite_id[-2]:
|
419
|
415 return metabolite_id.split('_')[-1]
|
493
|
416 if metabolite_id[-1] == ']' and metabolite_id[-3] == '[':
|
|
417 return metabolite_id[-2]
|
419
|
418 return 'c' # default cytoplasm
|
|
419
|
|
420
|
|
421 def parse_reaction_formula(reaction: Reaction, formula: str, metabolites_dict: Dict[str, Metabolite]):
|
456
|
422 """Parse a reaction formula and set metabolites with their coefficients."""
|
419
|
423
|
|
424 if '<=>' in formula:
|
501
|
425 parts = formula.split('<=>')
|
419
|
426 reversible = True
|
|
427 elif '<--' in formula:
|
501
|
428 parts = formula.split('<--')
|
419
|
429 reversible = False
|
|
430 elif '-->' in formula:
|
501
|
431 parts = formula.split('-->')
|
419
|
432 reversible = False
|
|
433 elif '<-' in formula:
|
501
|
434 parts = formula.split('<-')
|
419
|
435 reversible = False
|
|
436 else:
|
456
|
437 raise ValueError(f"Unrecognized reaction format: {formula}")
|
419
|
438
|
501
|
439 # Handle cases where one side might be empty (exchange reactions)
|
|
440 if len(parts) != 2:
|
|
441 raise ValueError(f"Invalid reaction format, expected 2 parts: {formula}")
|
|
442
|
|
443 left, right = parts[0].strip(), parts[1].strip()
|
|
444
|
|
445 reactants = parse_metabolites_side(left) if left else {}
|
|
446 products = parse_metabolites_side(right) if right else {}
|
419
|
447
|
|
448 metabolites_to_add = {}
|
|
449
|
|
450 for met_id, coeff in reactants.items():
|
|
451 if met_id in metabolites_dict:
|
|
452 metabolites_to_add[metabolites_dict[met_id]] = -coeff
|
|
453
|
|
454 for met_id, coeff in products.items():
|
|
455 if met_id in metabolites_dict:
|
|
456 metabolites_to_add[metabolites_dict[met_id]] = coeff
|
|
457
|
|
458 reaction.add_metabolites(metabolites_to_add)
|
|
459
|
|
460
|
|
461 def parse_metabolites_side(side_str: str) -> Dict[str, float]:
|
456
|
462 """Parse one side of a reaction and extract metabolites with coefficients."""
|
419
|
463 metabolites = {}
|
|
464 if not side_str or side_str.strip() == '':
|
|
465 return metabolites
|
|
466
|
|
467 terms = side_str.split('+')
|
|
468 for term in terms:
|
|
469 term = term.strip()
|
|
470 if not term:
|
|
471 continue
|
|
472
|
501
|
473 # First check if term has space-separated coefficient and metabolite
|
|
474 parts = term.split()
|
|
475 if len(parts) == 2:
|
|
476 # Two parts: potential coefficient + metabolite
|
|
477 try:
|
|
478 coeff = float(parts[0])
|
|
479 met_id = parts[1]
|
|
480 # Verify the second part looks like a metabolite with compartment
|
|
481 if re.match(r'[A-Za-z0-9_]+(?:\[[A-Za-z0-9]+\]|_[A-Za-z0-9]+)', met_id):
|
|
482 metabolites[met_id] = coeff
|
|
483 continue
|
|
484 except ValueError:
|
|
485 pass
|
|
486
|
|
487 # Single term - check if it's a metabolite (no coefficient)
|
|
488 # Updated pattern to include metabolites starting with numbers
|
|
489 if re.match(r'[A-Za-z0-9][A-Za-z0-9_]*(?:\[[A-Za-z0-9]+\]|_[A-Za-z0-9]+)', term):
|
|
490 metabolites[term] = 1.0
|
|
491 else:
|
|
492 print(f"Warning: Could not parse metabolite term: '{term}'")
|
419
|
493
|
|
494 return metabolites
|
|
495
|
|
496
|
|
497
|
430
|
498 def set_objective_from_csv(model: cobra.Model, df: pd.DataFrame, obj_col: str = "ObjectiveCoefficient"):
|
419
|
499 """
|
430
|
500 Sets the model's objective function based on a column of coefficients in the CSV.
|
|
501 Can be any reaction(s), not necessarily biomass.
|
419
|
502 """
|
430
|
503 obj_dict = {}
|
419
|
504
|
430
|
505 for idx, row in df.iterrows():
|
|
506 reaction_id = str(row['ReactionID']).strip()
|
|
507 coeff = float(row[obj_col]) if pd.notna(row[obj_col]) else 0.0
|
|
508 if coeff != 0:
|
|
509 if reaction_id in model.reactions:
|
|
510 obj_dict[model.reactions.get_by_id(reaction_id)] = coeff
|
|
511 else:
|
|
512 print(f"Warning: reaction {reaction_id} not found in model, skipping for objective.")
|
|
513
|
|
514 if not obj_dict:
|
|
515 raise ValueError("No reactions found with non-zero objective coefficient.")
|
|
516
|
|
517 model.objective = obj_dict
|
|
518 print(f"Objective set with {len(obj_dict)} reactions.")
|
|
519
|
|
520
|
419
|
521
|
|
522
|
|
523 def set_medium_from_data(model: cobraModel, df: pd.DataFrame):
|
456
|
524 """Set the medium based on the 'InMedium' column in the dataframe."""
|
501
|
525 if 'InMedium' not in df.columns:
|
|
526 print("No 'InMedium' column found, skipping medium setup")
|
|
527 return
|
|
528
|
419
|
529 medium_reactions = df[df['InMedium'] == True]['ReactionID'].tolist()
|
|
530
|
|
531 medium_dict = {}
|
|
532 for rxn_id in medium_reactions:
|
|
533 if rxn_id in [r.id for r in model.reactions]:
|
|
534 reaction = model.reactions.get_by_id(rxn_id)
|
501
|
535 if reaction.lower_bound < 0:
|
419
|
536 medium_dict[rxn_id] = abs(reaction.lower_bound)
|
|
537
|
|
538 if medium_dict:
|
|
539 model.medium = medium_dict
|
456
|
540 print(f"Medium set with {len(medium_dict)} components")
|
501
|
541 else:
|
|
542 print("No medium components found")
|
419
|
543 def validate_model(model: cobraModel) -> Dict[str, any]:
|
456
|
544 """Validate the model and return basic statistics."""
|
419
|
545 validation = {
|
|
546 'num_reactions': len(model.reactions),
|
|
547 'num_metabolites': len(model.metabolites),
|
|
548 'num_genes': len(model.genes),
|
|
549 'num_compartments': len(model.compartments),
|
|
550 'objective': str(model.objective),
|
|
551 'medium_size': len(model.medium),
|
|
552 'reversible_reactions': len([r for r in model.reactions if r.reversibility]),
|
|
553 'exchange_reactions': len([r for r in model.reactions if r.id.startswith('EX_')]),
|
|
554 }
|
|
555
|
|
556 try:
|
456
|
557 # Growth test
|
419
|
558 solution = model.optimize()
|
|
559 validation['growth_rate'] = solution.objective_value
|
|
560 validation['status'] = solution.status
|
|
561 except Exception as e:
|
|
562 validation['growth_rate'] = None
|
|
563 validation['status'] = f"Error: {e}"
|
|
564
|
|
565 return validation
|
|
566
|
456
|
567 def convert_genes(model, annotation):
|
|
568 """Rename genes using a selected annotation key in gene.notes; returns a model copy."""
|
419
|
569 from cobra.manipulation import rename_genes
|
|
570 model2=model.copy()
|
|
571 try:
|
|
572 dict_genes={gene.id:gene.notes[annotation] for gene in model2.genes}
|
|
573 except:
|
|
574 print("No annotation in gene dict!")
|
|
575 return -1
|
|
576 rename_genes(model2,dict_genes)
|
|
577
|
426
|
578 return model2
|
|
579
|
|
580 # ---------- Utility helpers ----------
|
|
581 def _normalize_colname(col: str) -> str:
|
|
582 return col.strip().lower().replace(' ', '_')
|
|
583
|
|
584 def _choose_columns(mapping_df: 'pd.DataFrame') -> Dict[str, str]:
|
|
585 """
|
456
|
586 Find useful columns and return a dict {ensg: colname1, hgnc_id: colname2, ...}.
|
|
587 Raise ValueError if no suitable mapping is found.
|
426
|
588 """
|
|
589 cols = { _normalize_colname(c): c for c in mapping_df.columns }
|
|
590 chosen = {}
|
456
|
591 # candidate names for each category
|
426
|
592 candidates = {
|
|
593 'ensg': ['ensg', 'ensembl_gene_id', 'ensembl'],
|
|
594 'hgnc_id': ['hgnc_id', 'hgnc', 'hgnc:'],
|
444
|
595 'hgnc_symbol': ['hgnc_symbol', 'hgnc symbol', 'symbol'],
|
455
|
596 'entrez_id': ['entrez', 'entrez_id', 'entrezgene'],
|
|
597 'gene_number': ['gene_number']
|
426
|
598 }
|
|
599 for key, names in candidates.items():
|
|
600 for n in names:
|
|
601 if n in cols:
|
|
602 chosen[key] = cols[n]
|
|
603 break
|
|
604 return chosen
|
|
605
|
|
606 def _validate_target_uniqueness(mapping_df: 'pd.DataFrame',
|
|
607 source_col: str,
|
|
608 target_col: str,
|
|
609 model_source_genes: Optional[Set[str]] = None,
|
|
610 logger: Optional[logging.Logger] = None) -> None:
|
|
611 """
|
456
|
612 Check that, within the filtered mapping_df, each target maps to at most one source.
|
|
613 Log examples if duplicates are found.
|
426
|
614 """
|
|
615 if logger is None:
|
|
616 logger = logging.getLogger(__name__)
|
|
617
|
|
618 if mapping_df.empty:
|
|
619 logger.warning("Mapping dataframe is empty for the requested source genes; skipping uniqueness validation.")
|
|
620 return
|
|
621
|
456
|
622 # normalize temporary columns for grouping (without altering the original df)
|
426
|
623 tmp = mapping_df[[source_col, target_col]].copy()
|
503
|
624 tmp['_src_norm'] = tmp[source_col].astype(str).apply(_normalize_gene_id)
|
426
|
625 tmp['_tgt_norm'] = tmp[target_col].astype(str).str.strip()
|
|
626
|
456
|
627 # optionally filter to the set of model source genes
|
426
|
628 if model_source_genes is not None:
|
|
629 tmp = tmp[tmp['_src_norm'].isin(model_source_genes)]
|
|
630
|
|
631 if tmp.empty:
|
|
632 logger.warning("After filtering to model source genes, mapping table is empty — nothing to validate.")
|
|
633 return
|
|
634
|
456
|
635 # build reverse mapping: target -> set(sources)
|
426
|
636 grouped = tmp.groupby('_tgt_norm')['_src_norm'].agg(lambda s: set(s.dropna()))
|
456
|
637 # find targets with more than one source
|
426
|
638 problematic = {t: sorted(list(s)) for t, s in grouped.items() if len(s) > 1}
|
|
639
|
|
640 if problematic:
|
456
|
641 # prepare warning message with examples (limited subset)
|
455
|
642 sample_items = list(problematic.items())
|
426
|
643 msg_lines = ["Mapping validation failed: some target IDs are associated with multiple source IDs."]
|
|
644 for tgt, sources in sample_items:
|
|
645 msg_lines.append(f" - target '{tgt}' <- sources: {', '.join(sources)}")
|
|
646 full_msg = "\n".join(msg_lines)
|
456
|
647 # log warning
|
455
|
648 logger.warning(full_msg)
|
426
|
649
|
456
|
650 # if everything is fine
|
426
|
651 logger.info("Mapping validation passed: no target ID is associated with multiple source IDs (within filtered set).")
|
|
652
|
|
653
|
|
654 def _normalize_gene_id(g: str) -> str:
|
456
|
655 """Normalize a gene ID for use as a key (removes prefixes like 'HGNC:' and strips)."""
|
426
|
656 if g is None:
|
|
657 return ""
|
|
658 g = str(g).strip()
|
|
659 # remove common prefixes
|
|
660 g = re.sub(r'^(HGNC:)', '', g, flags=re.IGNORECASE)
|
|
661 g = re.sub(r'^(ENSG:)', '', g, flags=re.IGNORECASE)
|
|
662 return g
|
|
663
|
493
|
664 def _is_or_only_expression(expr: str) -> bool:
|
|
665 """
|
|
666 Check if a GPR expression contains only OR operators (no AND operators).
|
|
667
|
|
668 Args:
|
|
669 expr: GPR expression string
|
|
670
|
|
671 Returns:
|
|
672 bool: True if expression contains only OR (and parentheses) and has multiple genes, False otherwise
|
|
673 """
|
|
674 if not expr or not expr.strip():
|
|
675 return False
|
|
676
|
|
677 # Normalize the expression
|
|
678 normalized = expr.replace(' AND ', ' and ').replace(' OR ', ' or ')
|
|
679
|
|
680 # Check if it contains any AND operators
|
|
681 has_and = ' and ' in normalized.lower()
|
|
682
|
|
683 # Check if it contains OR operators
|
|
684 has_or = ' or ' in normalized.lower()
|
|
685
|
|
686 # Must have OR operators and no AND operators
|
|
687 return has_or and not has_and
|
|
688
|
|
689
|
|
690 def _flatten_or_only_gpr(expr: str) -> str:
|
|
691 """
|
|
692 Flatten a GPR expression that contains only OR operators by:
|
|
693 1. Removing all parentheses
|
|
694 2. Extracting unique gene names
|
|
695 3. Joining them with ' or '
|
|
696
|
|
697 Args:
|
|
698 expr: GPR expression string with only OR operators
|
|
699
|
|
700 Returns:
|
|
701 str: Flattened GPR expression
|
|
702 """
|
|
703 if not expr or not expr.strip():
|
|
704 return expr
|
|
705
|
|
706 # Extract all gene tokens (exclude logical operators and parentheses)
|
|
707 gene_pattern = r'\b[A-Za-z0-9:_.-]+\b'
|
|
708 logical = {'and', 'or', 'AND', 'OR', '(', ')'}
|
|
709
|
|
710 tokens = re.findall(gene_pattern, expr)
|
|
711 genes = [t for t in tokens if t not in logical]
|
|
712
|
|
713 # Create set to remove duplicates, then convert back to list to maintain some order
|
|
714 unique_genes = list(dict.fromkeys(genes)) # Preserves insertion order
|
|
715
|
|
716 if len(unique_genes) == 0:
|
|
717 return expr
|
|
718 elif len(unique_genes) == 1:
|
|
719 return unique_genes[0]
|
|
720 else:
|
|
721 return ' or '.join(unique_genes)
|
|
722
|
|
723
|
455
|
724 def _simplify_boolean_expression(expr: str) -> str:
|
|
725 """
|
490
|
726 Simplify a boolean expression by removing duplicates while strictly preserving semantics.
|
|
727 This function handles simple duplicates within parentheses while being conservative about
|
|
728 complex expressions that could change semantics.
|
455
|
729 """
|
|
730 if not expr or not expr.strip():
|
|
731 return expr
|
|
732
|
490
|
733 # Normalize operators and whitespace
|
455
|
734 expr = expr.replace(' AND ', ' and ').replace(' OR ', ' or ')
|
490
|
735 expr = ' '.join(expr.split()) # Normalize whitespace
|
455
|
736
|
490
|
737 def simplify_parentheses_content(match_obj):
|
|
738 """Helper function to simplify content within parentheses."""
|
|
739 content = match_obj.group(1) # Content inside parentheses
|
455
|
740
|
490
|
741 # Only simplify if it's a pure OR or pure AND chain
|
|
742 if ' or ' in content and ' and ' not in content:
|
|
743 # Pure OR chain - safe to deduplicate
|
|
744 parts = [p.strip() for p in content.split(' or ') if p.strip()]
|
|
745 unique_parts = []
|
|
746 seen = set()
|
|
747 for part in parts:
|
|
748 if part not in seen:
|
|
749 unique_parts.append(part)
|
|
750 seen.add(part)
|
455
|
751
|
490
|
752 if len(unique_parts) == 1:
|
|
753 return unique_parts[0] # Remove unnecessary parentheses for single items
|
|
754 else:
|
|
755 return '(' + ' or '.join(unique_parts) + ')'
|
|
756
|
|
757 elif ' and ' in content and ' or ' not in content:
|
|
758 # Pure AND chain - safe to deduplicate
|
|
759 parts = [p.strip() for p in content.split(' and ') if p.strip()]
|
|
760 unique_parts = []
|
|
761 seen = set()
|
|
762 for part in parts:
|
|
763 if part not in seen:
|
|
764 unique_parts.append(part)
|
|
765 seen.add(part)
|
455
|
766
|
490
|
767 if len(unique_parts) == 1:
|
|
768 return unique_parts[0] # Remove unnecessary parentheses for single items
|
|
769 else:
|
|
770 return '(' + ' and '.join(unique_parts) + ')'
|
|
771 else:
|
|
772 # Mixed operators or single item - return with parentheses as-is
|
|
773 return '(' + content + ')'
|
|
774
|
|
775 def remove_duplicates_simple(parts_str: str, separator: str) -> str:
|
|
776 """Remove duplicates from a simple chain of operations."""
|
|
777 parts = [p.strip() for p in parts_str.split(separator) if p.strip()]
|
455
|
778
|
490
|
779 # Remove duplicates while preserving order
|
|
780 unique_parts = []
|
|
781 seen = set()
|
|
782 for part in parts:
|
|
783 if part not in seen:
|
|
784 unique_parts.append(part)
|
|
785 seen.add(part)
|
455
|
786
|
490
|
787 if len(unique_parts) == 1:
|
|
788 return unique_parts[0]
|
455
|
789 else:
|
490
|
790 return f' {separator} '.join(unique_parts)
|
455
|
791
|
|
792 try:
|
490
|
793 import re
|
|
794
|
|
795 # First, simplify content within parentheses
|
|
796 # This handles cases like (A or A) -> A and (B and B) -> B
|
|
797 expr_simplified = re.sub(r'\(([^()]+)\)', simplify_parentheses_content, expr)
|
|
798
|
|
799 # Check if the resulting expression has mixed operators
|
|
800 has_and = ' and ' in expr_simplified
|
|
801 has_or = ' or ' in expr_simplified
|
|
802
|
|
803 # Only simplify top-level if it's pure AND or pure OR
|
|
804 if has_and and not has_or and '(' not in expr_simplified:
|
|
805 # Pure AND chain at top level - safe to deduplicate
|
|
806 return remove_duplicates_simple(expr_simplified, 'and')
|
|
807 elif has_or and not has_and and '(' not in expr_simplified:
|
|
808 # Pure OR chain at top level - safe to deduplicate
|
|
809 return remove_duplicates_simple(expr_simplified, 'or')
|
|
810 else:
|
|
811 # Mixed operators or has parentheses - return the simplified version (with parentheses content cleaned)
|
|
812 return expr_simplified
|
|
813
|
455
|
814 except Exception:
|
490
|
815 # If anything goes wrong, return the original expression
|
455
|
816 return expr
|
|
817
|
492
|
818
|
426
|
819 def translate_model_genes(model: 'cobra.Model',
|
|
820 mapping_df: 'pd.DataFrame',
|
|
821 target_nomenclature: str,
|
|
822 source_nomenclature: str = 'hgnc_id',
|
455
|
823 allow_many_to_one: bool = False,
|
490
|
824 logger: Optional[logging.Logger] = None) -> Tuple['cobra.Model', Dict[str, str]]:
|
426
|
825 """
|
456
|
826 Translate model genes from source_nomenclature to target_nomenclature using a mapping table.
|
|
827 mapping_df should contain columns enabling mapping (e.g., ensg, hgnc_id, hgnc_symbol, entrez).
|
|
828
|
455
|
829 Args:
|
456
|
830 model: COBRA model to translate.
|
|
831 mapping_df: DataFrame containing the mapping information.
|
|
832 target_nomenclature: Desired target key (e.g., 'hgnc_symbol').
|
|
833 source_nomenclature: Current source key in the model (default 'hgnc_id').
|
|
834 allow_many_to_one: If True, allow many-to-one mappings and handle duplicates in GPRs.
|
|
835 logger: Optional logger.
|
490
|
836
|
|
837 Returns:
|
|
838 Tuple containing:
|
|
839 - Translated COBRA model
|
|
840 - Dictionary mapping reaction IDs to translation issue descriptions
|
426
|
841 """
|
|
842 if logger is None:
|
|
843 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
844 logger = logging.getLogger(__name__)
|
|
845
|
|
846 logger.info(f"Translating genes from '{source_nomenclature}' to '{target_nomenclature}'")
|
|
847
|
|
848 # normalize column names and choose relevant columns
|
|
849 chosen = _choose_columns(mapping_df)
|
|
850 if not chosen:
|
|
851 raise ValueError("Could not detect useful columns in mapping_df. Expected at least one of: ensg, hgnc_id, hgnc_symbol, entrez.")
|
|
852
|
|
853 # map source/target to actual dataframe column names (allow user-specified source/target keys)
|
|
854 # normalize input args
|
|
855 src_key = source_nomenclature.strip().lower()
|
|
856 tgt_key = target_nomenclature.strip().lower()
|
|
857
|
|
858 # try to find the actual column names for requested keys
|
|
859 col_for_src = None
|
|
860 col_for_tgt = None
|
|
861 # first, try exact match
|
|
862 for k, actual in chosen.items():
|
|
863 if k == src_key:
|
|
864 col_for_src = actual
|
|
865 if k == tgt_key:
|
|
866 col_for_tgt = actual
|
|
867
|
|
868 # if not found, try mapping common names
|
|
869 if col_for_src is None:
|
|
870 possible_src_names = {k: v for k, v in chosen.items()}
|
|
871 # try to match by contained substring
|
|
872 for k, actual in possible_src_names.items():
|
|
873 if src_key in k:
|
|
874 col_for_src = actual
|
|
875 break
|
|
876
|
|
877 if col_for_tgt is None:
|
|
878 for k, actual in chosen.items():
|
|
879 if tgt_key in k:
|
|
880 col_for_tgt = actual
|
|
881 break
|
|
882
|
|
883 if col_for_src is None:
|
|
884 raise ValueError(f"Source column for '{source_nomenclature}' not found in mapping dataframe.")
|
|
885 if col_for_tgt is None:
|
|
886 raise ValueError(f"Target column for '{target_nomenclature}' not found in mapping dataframe.")
|
|
887
|
|
888 model_source_genes = { _normalize_gene_id(g.id) for g in model.genes }
|
|
889 logger.info(f"Filtering mapping to {len(model_source_genes)} source genes present in model (normalized).")
|
|
890
|
|
891 tmp_map = mapping_df[[col_for_src, col_for_tgt]].dropna().copy()
|
503
|
892 tmp_map[col_for_src + "_norm"] = tmp_map[col_for_src].astype(str).apply(_normalize_gene_id)
|
426
|
893
|
|
894 filtered_map = tmp_map[tmp_map[col_for_src + "_norm"].isin(model_source_genes)].copy()
|
|
895
|
|
896 if filtered_map.empty:
|
|
897 logger.warning("No mapping rows correspond to source genes present in the model after filtering. Proceeding with empty mapping (no translation will occur).")
|
|
898
|
455
|
899 if not allow_many_to_one:
|
|
900 _validate_target_uniqueness(filtered_map, col_for_src, col_for_tgt, model_source_genes=model_source_genes, logger=logger)
|
426
|
901
|
455
|
902 # Crea il mapping
|
426
|
903 gene_mapping = _create_gene_mapping(filtered_map, col_for_src, col_for_tgt, logger)
|
|
904
|
|
905 # copy model
|
|
906 model_copy = model.copy()
|
|
907
|
|
908 # statistics
|
493
|
909 stats = {'translated': 0, 'one_to_one': 0, 'one_to_many': 0, 'not_found': 0, 'simplified_gprs': 0, 'flattened_or_gprs': 0}
|
426
|
910 unmapped = []
|
|
911 multi = []
|
490
|
912
|
|
913 # Dictionary to store translation issues per reaction
|
|
914 reaction_translation_issues = {}
|
426
|
915
|
|
916 original_genes = {g.id for g in model_copy.genes}
|
|
917 logger.info(f"Original genes count: {len(original_genes)}")
|
|
918
|
|
919 # translate GPRs
|
|
920 for rxn in model_copy.reactions:
|
|
921 gpr = rxn.gene_reaction_rule
|
|
922 if gpr and gpr.strip():
|
490
|
923 new_gpr, rxn_issues = _translate_gpr(gpr, gene_mapping, stats, unmapped, multi, logger, track_issues=True)
|
|
924 if rxn_issues:
|
|
925 reaction_translation_issues[rxn.id] = rxn_issues
|
|
926
|
426
|
927 if new_gpr != gpr:
|
493
|
928 # Check if this GPR has translation issues and contains only OR operators
|
|
929 if rxn_issues and _is_or_only_expression(new_gpr):
|
|
930 # Flatten the GPR: remove parentheses and create set of unique genes
|
|
931 flattened_gpr = _flatten_or_only_gpr(new_gpr)
|
|
932 if flattened_gpr != new_gpr:
|
|
933 stats['flattened_or_gprs'] += 1
|
|
934 logger.debug(f"Flattened OR-only GPR with issues for {rxn.id}: '{new_gpr}' -> '{flattened_gpr}'")
|
|
935 new_gpr = flattened_gpr
|
|
936
|
455
|
937 simplified_gpr = _simplify_boolean_expression(new_gpr)
|
|
938 if simplified_gpr != new_gpr:
|
|
939 stats['simplified_gprs'] += 1
|
|
940 logger.debug(f"Simplified GPR for {rxn.id}: '{new_gpr}' -> '{simplified_gpr}'")
|
|
941 rxn.gene_reaction_rule = simplified_gpr
|
|
942 logger.debug(f"Reaction {rxn.id}: '{gpr}' -> '{simplified_gpr}'")
|
426
|
943
|
|
944 # update model genes based on new GPRs
|
|
945 _update_model_genes(model_copy, logger)
|
|
946
|
|
947 # final logging
|
|
948 _log_translation_statistics(stats, unmapped, multi, original_genes, model_copy.genes, logger)
|
|
949
|
|
950 logger.info("Translation finished")
|
490
|
951 return model_copy, reaction_translation_issues
|
426
|
952
|
|
953
|
|
954 # ---------- helper functions ----------
|
|
955 def _create_gene_mapping(mapping_df, source_col: str, target_col: str, logger: logging.Logger) -> Dict[str, List[str]]:
|
|
956 """
|
|
957 Build mapping dict: source_id -> list of target_ids
|
|
958 Normalizes IDs (removes prefixes like 'HGNC:' etc).
|
|
959 """
|
|
960 df = mapping_df[[source_col, target_col]].dropna().copy()
|
|
961 # normalize to string
|
503
|
962 df[source_col] = df[source_col].astype(str).apply(_normalize_gene_id)
|
426
|
963 df[target_col] = df[target_col].astype(str).str.strip()
|
|
964
|
|
965 df = df.drop_duplicates()
|
|
966
|
|
967 logger.info(f"Creating mapping from {len(df)} rows")
|
|
968
|
|
969 mapping = defaultdict(list)
|
|
970 for _, row in df.iterrows():
|
|
971 s = row[source_col]
|
|
972 t = row[target_col]
|
|
973 if t not in mapping[s]:
|
|
974 mapping[s].append(t)
|
|
975
|
|
976 # stats
|
|
977 one_to_one = sum(1 for v in mapping.values() if len(v) == 1)
|
|
978 one_to_many = sum(1 for v in mapping.values() if len(v) > 1)
|
|
979 logger.info(f"Mapping: {len(mapping)} source keys, {one_to_one} 1:1, {one_to_many} 1:many")
|
|
980 return dict(mapping)
|
|
981
|
|
982
|
|
983 def _translate_gpr(gpr_string: str,
|
|
984 gene_mapping: Dict[str, List[str]],
|
|
985 stats: Dict[str, int],
|
|
986 unmapped_genes: List[str],
|
|
987 multi_mapping_genes: List[Tuple[str, List[str]]],
|
490
|
988 logger: logging.Logger,
|
|
989 track_issues: bool = False) -> Union[str, Tuple[str, str]]:
|
426
|
990 """
|
|
991 Translate genes inside a GPR string using gene_mapping.
|
490
|
992 Returns new GPR string, and optionally translation issues if track_issues=True.
|
426
|
993 """
|
|
994 # Generic token pattern: letters, digits, :, _, -, ., (captures HGNC:1234, ENSG000..., symbols)
|
|
995 token_pattern = r'\b[A-Za-z0-9:_.-]+\b'
|
|
996 tokens = re.findall(token_pattern, gpr_string)
|
|
997
|
|
998 logical = {'and', 'or', 'AND', 'OR', '(', ')'}
|
|
999 tokens = [t for t in tokens if t not in logical]
|
|
1000
|
|
1001 new_gpr = gpr_string
|
490
|
1002 issues = []
|
426
|
1003
|
|
1004 for token in sorted(set(tokens), key=lambda x: -len(x)): # longer tokens first to avoid partial replacement
|
|
1005 norm = _normalize_gene_id(token)
|
|
1006 if norm in gene_mapping:
|
|
1007 targets = gene_mapping[norm]
|
|
1008 stats['translated'] += 1
|
|
1009 if len(targets) == 1:
|
|
1010 stats['one_to_one'] += 1
|
|
1011 replacement = targets[0]
|
|
1012 else:
|
|
1013 stats['one_to_many'] += 1
|
|
1014 multi_mapping_genes.append((token, targets))
|
|
1015 replacement = "(" + " or ".join(targets) + ")"
|
490
|
1016 if track_issues:
|
|
1017 issues.append(f"{token} -> {' or '.join(targets)}")
|
426
|
1018
|
|
1019 pattern = r'\b' + re.escape(token) + r'\b'
|
|
1020 new_gpr = re.sub(pattern, replacement, new_gpr)
|
|
1021 else:
|
|
1022 stats['not_found'] += 1
|
|
1023 if token not in unmapped_genes:
|
|
1024 unmapped_genes.append(token)
|
|
1025 logger.debug(f"Token not found in mapping (left as-is): {token}")
|
|
1026
|
490
|
1027 # Check for many-to-one cases (multiple source genes mapping to same target)
|
|
1028 if track_issues:
|
|
1029 # Build reverse mapping to detect many-to-one cases from original tokens
|
|
1030 original_to_target = {}
|
|
1031
|
|
1032 for orig_token in tokens:
|
|
1033 norm = _normalize_gene_id(orig_token)
|
|
1034 if norm in gene_mapping:
|
|
1035 targets = gene_mapping[norm]
|
|
1036 for target in targets:
|
|
1037 if target not in original_to_target:
|
|
1038 original_to_target[target] = []
|
|
1039 if orig_token not in original_to_target[target]:
|
|
1040 original_to_target[target].append(orig_token)
|
|
1041
|
|
1042 # Identify many-to-one mappings in this specific GPR
|
|
1043 for target, original_genes in original_to_target.items():
|
|
1044 if len(original_genes) > 1:
|
|
1045 issues.append(f"{' or '.join(original_genes)} -> {target}")
|
|
1046
|
|
1047 issue_text = "; ".join(issues) if issues else ""
|
|
1048
|
|
1049 if track_issues:
|
|
1050 return new_gpr, issue_text
|
|
1051 else:
|
|
1052 return new_gpr
|
426
|
1053
|
|
1054
|
|
1055 def _update_model_genes(model: 'cobra.Model', logger: logging.Logger):
|
|
1056 """
|
|
1057 Rebuild model.genes from gene_reaction_rule content.
|
|
1058 Removes genes not referenced and adds missing ones.
|
|
1059 """
|
|
1060 # collect genes in GPRs
|
|
1061 gene_pattern = r'\b[A-Za-z0-9:_.-]+\b'
|
|
1062 logical = {'and', 'or', 'AND', 'OR', '(', ')'}
|
|
1063 genes_in_gpr: Set[str] = set()
|
|
1064
|
|
1065 for rxn in model.reactions:
|
|
1066 gpr = rxn.gene_reaction_rule
|
|
1067 if gpr and gpr.strip():
|
|
1068 toks = re.findall(gene_pattern, gpr)
|
|
1069 toks = [t for t in toks if t not in logical]
|
|
1070 # normalize IDs consistent with mapping normalization
|
|
1071 toks = [_normalize_gene_id(t) for t in toks]
|
|
1072 genes_in_gpr.update(toks)
|
|
1073
|
|
1074 # existing gene ids
|
|
1075 existing = {g.id for g in model.genes}
|
|
1076
|
|
1077 # remove obsolete genes
|
|
1078 to_remove = [gid for gid in existing if gid not in genes_in_gpr]
|
|
1079 removed = 0
|
|
1080 for gid in to_remove:
|
|
1081 try:
|
|
1082 gene_obj = model.genes.get_by_id(gid)
|
|
1083 model.genes.remove(gene_obj)
|
|
1084 removed += 1
|
|
1085 except Exception:
|
|
1086 # safe-ignore
|
|
1087 pass
|
|
1088
|
|
1089 # add new genes
|
|
1090 added = 0
|
|
1091 for gid in genes_in_gpr:
|
|
1092 if gid not in existing:
|
|
1093 new_gene = cobra.Gene(gid)
|
|
1094 try:
|
|
1095 model.genes.add(new_gene)
|
|
1096 except Exception:
|
|
1097 # fallback: if model.genes doesn't support add, try append or model.add_genes
|
|
1098 try:
|
|
1099 model.genes.append(new_gene)
|
|
1100 except Exception:
|
|
1101 try:
|
|
1102 model.add_genes([new_gene])
|
|
1103 except Exception:
|
|
1104 logger.warning(f"Could not add gene object for {gid}")
|
|
1105 added += 1
|
|
1106
|
|
1107 logger.info(f"Model genes updated: removed {removed}, added {added}")
|
|
1108
|
|
1109
|
|
1110 def _log_translation_statistics(stats: Dict[str, int],
|
|
1111 unmapped_genes: List[str],
|
|
1112 multi_mapping_genes: List[Tuple[str, List[str]]],
|
|
1113 original_genes: Set[str],
|
|
1114 final_genes,
|
|
1115 logger: logging.Logger):
|
|
1116 logger.info("=== TRANSLATION STATISTICS ===")
|
|
1117 logger.info(f"Translated: {stats.get('translated', 0)} (1:1 = {stats.get('one_to_one', 0)}, 1:many = {stats.get('one_to_many', 0)})")
|
|
1118 logger.info(f"Not found tokens: {stats.get('not_found', 0)}")
|
455
|
1119 logger.info(f"Simplified GPRs: {stats.get('simplified_gprs', 0)}")
|
493
|
1120 logger.info(f"Flattened OR-only GPRs with issues: {stats.get('flattened_or_gprs', 0)}")
|
426
|
1121
|
|
1122 final_ids = {g.id for g in final_genes}
|
|
1123 logger.info(f"Genes in model: {len(original_genes)} -> {len(final_ids)}")
|
|
1124
|
|
1125 if unmapped_genes:
|
|
1126 logger.warning(f"Unmapped tokens ({len(unmapped_genes)}): {', '.join(unmapped_genes[:20])}{(' ...' if len(unmapped_genes)>20 else '')}")
|
|
1127 if multi_mapping_genes:
|
|
1128 logger.info(f"Multi-mapping examples ({len(multi_mapping_genes)}):")
|
|
1129 for orig, targets in multi_mapping_genes[:10]:
|
490
|
1130 logger.info(f" {orig} -> {', '.join(targets)}")
|
493
|
1131
|
|
1132 # Log summary of flattened GPRs if any
|
|
1133 if stats.get('flattened_or_gprs', 0) > 0:
|
|
1134 logger.info(f"Flattened {stats['flattened_or_gprs']} OR-only GPRs that had translation issues (removed parentheses, created unique gene sets)")
|
490
|
1135
|
|
1136 |