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