COBRA-k API reference
COBRAk is a general COBRA/COBRA-k suite written as Python package. For more about it, visit its repository: https://github.com/klamt-lab/COBRAk
The init file of COBRAk initializes the rich text output & tracebacks as well as its logger. Furthermore, graceful shutdown of user-induced shutdowns is enabled.
exit_signal_handler(sig, frame)
Handles the exit signal by printing a shutdown message and exiting the program.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sig
|
int
|
The signal number. |
required |
frame
|
Optional[FrameType]
|
The current frame. |
required |
Source code in cobrak/__init__.py
21 22 23 24 25 26 27 28 29 30 31 |
|
set_logging_handler(show_path=False, show_time=False, show_level=True, keywords=['info', 'warning', 'error', 'critical'], **args)
Sets up the logging handler with the given options.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
show_path
|
bool
|
Whether to show the path. Defaults to False. |
False
|
show_time
|
bool
|
Whether to show the time. Defaults to False. |
False
|
show_level
|
bool
|
Whether to show the level. Defaults to True. |
True
|
keywords
|
Dict[str, str]
|
The keywords to highlight. Defaults to ["info", "warning", "error", "critical"] |
['info', 'warning', 'error', 'critical']
|
**args
|
Any
|
Additional Rich handler arguments. |
{}
|
Source code in cobrak/__init__.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
set_logging_level(level)
Sets the logging level.
E.g. INFO, ERROR, WARNING and CRITICAL from Python's logging module.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
level
|
int
|
The logging level. |
required |
Source code in cobrak/__init__.py
43 44 45 46 47 48 49 50 51 |
|
setup_rich_tracebacks(show_locals)
Sets up rich tracebacks with the given options.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
show_locals
|
bool
|
Whether to show local variables in the traceback. |
required |
Source code in cobrak/__init__.py
34 35 36 37 38 39 40 |
|
bigg_metabolites_functionality
bigg_parse_metabolites_file.py
This module contains a function which transforms a BIGG metabolites .txt list into an machine-readable JSON.
bigg_parse_metabolites_file(bigg_metabolites_txt_path, bigg_metabolites_json_path)
Parses a BIGG metabolites text file and returns a dictionary for this file.
As of Sep 14 2024, a BIGG metabolites list of all BIGG-included metabolites is retrievable under http://bigg.ucsd.edu/data_access
Arguments
- bigg_metabolites_file_path: str ~ The file path to the BIGG metabolites file. The usual file name (which has to be included too in this argument) is bigg_models_metabolites.txt
- output_folder: str ~ The folder in which the JSON including the parsed BIGG metabolites file data is stored with the name 'bigg_id_name_mapping.json'
Output
- A JSON file with the name 'bigg_id_name_mapping.json' in the given output folder, with the following structure:
{ "$BIGG_ID": "$CHEMICAL_OR_USUAL_NAME", (...), "$BIGG_ID": "$BIGG_ID", (...), }
The BIGG ID <-> BIGG ID mapping is done for models which already use the BIGG IDs.
Source code in cobrak/bigg_metabolites_functionality.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
|
brenda_functionality
Contains functions which allow one to create a model-specific and BRENDA-depending kinetic data database.
brenda_select_enzyme_kinetic_data_for_model(cobra_model, brenda_json_targz_file_path, bigg_metabolites_json_path, brenda_version, base_species, ncbi_parsed_json_path, kinetic_ignored_metabolites=[], kinetic_ignored_enzyme_ids=[], custom_enzyme_kinetic_data={}, min_ph=-float('inf'), max_ph=float('inf'), accept_nan_ph=True, min_temperature=-float('inf'), max_temperature=float('inf'), accept_nan_temperature=True, kcat_overwrite={}, transfered_ec_number_json='', max_taxonomy_level=float('inf'))
Select and assign enzyme kinetic data for each reaction in a COBRApy model based on BRENDA database entries and taxonomic similarity.
This function retrieves enzyme kinetic data from a compressed BRENDA JSON file, merges it with BiGG metabolite translation data and taxonomy information from NCBI. It then iterates over the reactions in the provided COBRApy model to:
- Filter reactions that have EC code annotations.
- Identify eligible EC codes (ignoring those with hyphens).
- Collect kinetic entries (e.g., turnover numbers, KM values, KI values) for each metabolite involved in the reaction.
- Choose the best kinetic parameters (k_cat, k_ms, k_is) based on taxonomic similarity to a base species.
- Apply conversion factors (e.g., s⁻¹ to h⁻¹ for k_cat, mM to M for KM and KI).
- Respect ignore lists for metabolites and enzymes.
- Override computed k_cat values if provided in the kcat_overwrite dictionary.
- Merge with any custom enzyme kinetic data provided.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobra_model
|
Model
|
A COBRApy model object representing the metabolic network. |
required |
brenda_json_targz_file_path
|
str
|
Path to the compressed JSON file containing BRENDA enzyme kinetic data. |
required |
bigg_metabolites_json_path
|
str
|
Path to the JSON file mapping metabolite IDs to BiGG identifiers. |
required |
brenda_version
|
str
|
String identifier for the BRENDA database version. |
required |
base_species
|
str
|
Species identifier used as the reference for taxonomic similarity. |
required |
ncbi_parsed_json_path
|
str
|
Path to the parsed JSON file containing NCBI taxonomy data. |
required |
kinetic_ignored_metabolites
|
list[str]
|
List of metabolite IDs to exclude from kinetic parameter selection. Defaults to an empty list. |
[]
|
kinetic_ignored_enzyme_ids
|
list[str]
|
List of enzyme identifiers to ignore when considering a reaction. Defaults to an empty list. |
[]
|
custom_enzyme_kinetic_data
|
dict[str, EnzymeReactionData | None]
|
Dictionary of custom enzyme kinetic data to override or supplement computed data. The keys are reaction IDs and the values are EnzymeReactionData instances or None. Defaults to an empty dictionary. |
{}
|
min_ph
|
float
|
The minimum pH value for kinetic data inclusion. Defaults to negative infinity. |
-float('inf')
|
max_ph
|
float
|
The maximum pH value for kinetic data inclusion. Defaults to positive infinity. |
float('inf')
|
accept_nan_ph
|
bool
|
If True, kinetic entries with NaN pH values are accepted. Defaults to True. |
True
|
min_temperature
|
float
|
The minimum temperature value (e.g., in Kelvin) for kinetic data inclusion. Defaults to negative infinity. |
-float('inf')
|
max_temperature
|
float
|
The maximum temperature value for kinetic data inclusion. Defaults to positive infinity. |
float('inf')
|
accept_nan_temperature
|
bool
|
If True, kinetic entries with NaN temperature values are accepted. Defaults to True. |
True
|
kcat_overwrite
|
dict[str, float]
|
Dictionary mapping reaction IDs to k_cat values that should override computed values. Defaults to an empty dictionary. |
{}
|
Returns:
Type | Description |
---|---|
dict[str, EnzymeReactionData | None]
|
dict[str, EnzymeReactionData | None]: A dictionary mapping reaction IDs (str) from the COBRApy model to their corresponding EnzymeReactionData instances. If no suitable kinetic data are found (or if the enzyme is in the ignore list), the value will be None for that reaction. |
Notes
- Kinetic values are converted to standardized units:
- k_cat values are converted from s⁻¹ to h⁻¹.
- KM and KI values are converted from mM to M.
- The function leverages taxonomic similarity (using NCBI TAXONOMY data) to select the most relevant kinetic values.
- Custom enzyme kinetic data and k_cat overrides will replace any computed values.
Source code in cobrak/brenda_functionality.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 |
|
cobrapy_model_functionality
Contains methods that directly apply on COBRApy models.
create_irreversible_cobrapy_model_from_stoichiometries(stoichiometries)
Create an irreversible COBRApy model out of the given dictionary.
E.g., if the following dict is the argument: { "EX_A": { "A": +1 }, "R1": { "A": -1, "B": +1 }, "EX_B": { "B": -1 }, } ...then, the following three irreversible (i.e, flux from 0 to 1_000) reactions are created and returned as a single COBRApy model: EX_A: -> A R1: A -> B EX_B: B ->
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stoichiometries
|
dict[str, dict[str, float]]
|
The model-describing dictionary |
required |
Returns:
Type | Description |
---|---|
Model
|
cobra.Model: The resulting COBRApy model with the given reactions and metabolites |
Source code in cobrak/cobrapy_model_functionality.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
|
get_fullsplit_cobra_model(cobra_model, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX, add_cobrak_sbml_annotation=False, cobrak_default_min_conc=1e-06, cobrak_default_max_conc=0.2, cobrak_extra_linear_constraints=[], cobrak_kinetic_ignored_metabolites=[], cobrak_no_extra_versions=False, reac_lb_ub_cap=float('inf'))
Return a COBRApy model where reactions are split according to reversibility and enzymes.
"Reversibility" means that, if a reaction i can run in both directions (α_i<0), then it is split as follows: Ri: A<->B [-50;100]=> Ri_FWD: A->B [0;100]; Ri_REV: B->A [0;50] where the ending "FWD" and "REV" are set in COBRAk's constants REAC_FWD_SUFFIX and REAC_REV_SUFFIX.
"enzymes" means that, if a reaction i can be catalyzed by multiple enzymes (i.e., at least one OR block in the reaction's gene-protein rule), then it is split for each reaction. Say, for example, Rj: A->B [0;100] has the following gene-protein rule: (E1 OR E2) ...then, Rj is split into: Rj_ENZ_E1: A->B [0;100] Rj_ENZ_E2: A->B [0;100] where the infix "ENZ" is set in COBRAk's constants REAC_ENZ_SEPARATOR.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobra_model
|
Model
|
The COBRApy model that shall be 'fullsplit'. |
required |
Returns:
Type | Description |
---|---|
Model
|
cobra.Model: The 'fullsplit' COBRApy model. |
Source code in cobrak/cobrapy_model_functionality.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
|
constants
This module contains all COBRAk constants that are used throughout its packages.
These constants are especially used for problem constructions (to determine prefixes, suffixes, names, ... for pyomo variables) as well as thermodynamic standard values.
ALL_OK_KEY = 'ALL_OK'
module-attribute
Shows that the result is optimal and the termination condition is ok
ALPHA_VAR_PREFIX = 'alpha_var_'
module-attribute
Prefix for variables representing the activation of a reaction (used in non-linear programs)
BIG_M = 10000
module-attribute
Big M value for MILPs
DF_VAR_PREFIX = 'f_var_'
module-attribute
Prefix for driving force problem variables
DG0_VAR_PREFIX = 'dG0_'
module-attribute
Prefix for Gibb's free energy problem variables
EC_INNER_TO_OUTER_COMPARTMENTS = ['c', 'p', 'e']
module-attribute
Inner to outer compartments in this order for E. coli models used here
EC_IONIC_STRENGTHS = {'c': 250, 'p': 250, 'e': 250}
module-attribute
Ionic strenghts (in mM) for E. coli model compartments used here
EC_PHS = {'c': 7.5, 'p': 7.5, 'e': 7.5}
module-attribute
pH values (unitless) for E. coli model compartments used here
EC_PMGS = {'c': 2.5, 'p': 2.5, 'e': 2.5}
module-attribute
pMg values (unitless) for E. coli model compartments used here
EC_POTENTIAL_DIFFERENCES = {('c', 'p'): 0.15, ('p', 'e'): 0.15}
module-attribute
Potential differences (in V) for E. coli model compartments used here
ENZYME_VAR_INFIX = '_of_'
module-attribute
Infix for separation of enzyme name and reaction name
ENZYME_VAR_PREFIX = 'enzyme_'
module-attribute
Prefix of problem variables which stand for enzyme concentrations
ERROR_BOUND_LOWER_CHANGE_PREFIX = 'bound_error_change_lower_'
module-attribute
Prefix for fixed variables that show how much affected lower variable bounds have to be changed
ERROR_BOUND_UPPER_CHANGE_PREFIX = 'bound_error_change_upper_'
module-attribute
Prefix for fixed variables that show how much affected lower variable bounds have to be changed
ERROR_CONSTRAINT_PREFIX = 'flux_error_'
module-attribute
Prefix for the constraint that defines a scenario flux constraint
ERROR_SUM_VAR_ID = 'error_sum'
module-attribute
Name for the variable that holds the sum of all error term variables
ERROR_VAR_PREFIX = 'error_'
module-attribute
Prefix for error term variables for feasibility-making optimizations
FLUX_SUM_VAR_ID = 'FLUX_SUM_VAR'
module-attribute
Name of optional variable that holds the sum of all reaction fluxes
GAMMA_VAR_PREFIX = 'gamma_var_'
module-attribute
Prefix for variables representing the thermodynamic restriction of a reaction (used in non-linear programs)
IOTA_VAR_PREFIX = 'iota_var_'
module-attribute
Prefix for variables representing the inhibition of a reaction (used in non-linear programs)
KAPPA_PRODUCTS_VAR_PREFIX = 'kappa_products_'
module-attribute
Prefix for variables representing the sum of logairthmized product concentration minus the logarithmized sum of km values
KAPPA_SUBSTRATES_VAR_PREFIX = 'kappa_substrates_'
module-attribute
Prefix for variables representing the sum of logairthmized substrate concentration minus the logarithmized sum of km values
KAPPA_VAR_PREFIX = 'kappa_var_'
module-attribute
Prefix for variables representing the thermodynamic restriction of a reaction (used in non-linear programs)
LNCONC_VAR_PREFIX = 'x_'
module-attribute
Prefix for logarithmized concentration problem variables
MDF_VAR_ID = 'var_B'
module-attribute
Name for minimally occuring driving force variable
OBJECTIVE_CONSTRAINT_NAME = 'objective_constraint'
module-attribute
Name for constraint that defines the objective function's term
OBJECTIVE_VAR_NAME = 'OBJECTIVE_VAR'
module-attribute
Name for variable that holds the objective value
PROT_POOL_MET_NAME = 'prot_pool'
module-attribute
Identifier of the protein pool representing pseudo-metabolite
PROT_POOL_REAC_NAME = PROT_POOL_MET_NAME + '_delivery'
module-attribute
Identifier of the pseudo-reaction which created the protein pool pseudo-metabolite
QUASI_INF = 100000
module-attribute
Big number (larger than big M) for values that would reach inf (thereby potentially causing solver problems)
REAC_ENZ_SEPARATOR = '_ENZ_'
module-attribute
Separator between enzyme-constrained reaction ID and attached enzyme name
REAC_FWD_SUFFIX = '_FWD'
module-attribute
Standard suffix for reaction IDs that represent forward directions of originally irreversible reactions
REAC_REV_SUFFIX = '_REV'
module-attribute
Standard suffix for reaction IDs that represent reverse directions of originally irreversible reactions
SOLVER_STATUS_KEY = 'SOLVER_STATUS'
module-attribute
Solver status optimization dict key
STANDARD_MIN_MDF = 0.001
module-attribute
Standard minimally ocurring driving force for active reactions in kJ⋅mol⁻¹
STANDARD_R = 0.008314
module-attribute
Standard gas constant in kJ⋅K⁻1⋅mol⁻1 (Attention: Standard value is often given in J⋅K⁻1⋅mol⁻1, but we need in kJ⋅K⁻1⋅mol⁻1)
STANDARD_T = 298.15
module-attribute
Standard temperature in Kelvin
TERMINATION_CONDITION_KEY = 'TERMINATION_CONDITION'
module-attribute
Solver termination condition key in optimization dict
USED_IDENTIFIERS_FOR_EQUILIBRATOR = ['inchi', 'inchi_key', 'metanetx.chemical', 'bigg.metabolite', 'kegg.compound', 'chebi', 'sabiork.compound', 'metacyc.compound', 'hmdb', 'swisslipid', 'reactome', 'lipidmaps', 'seed.compound']
module-attribute
Standard bunch of reaction identifier annotation names for E. coli models used here
ZB_VAR_PREFIX = 'zb_var_'
module-attribute
Extra zb variable prefix for thermodynamic bottleneck analyses
Z_VAR_PREFIX = 'z_var_'
module-attribute
Prefix of z variables (used with thermodynamic constraints in MI(N)LPs)
dataclasses
Contains all dataclasses (and enums) used by COBRAk to define a metabolic model and its extra constraints and optimization objective.
Dataclasses are similar to structs in C: They are not intended to have member functions, only other types of member variables. The main dataclass used by COBRAk is Model, which contains the full information about the metabolic model. As member variables, a Model contains further dataclasses (such as Reaction, Metabolite, ...). As dataclass_json is also invoked, it is possible to store and load the COBRAk dataclasses as JSON.
ErrorScenario = dict[str, tuple[float, float]]
module-attribute
A COBRAk error scenario type alias for a ConfigurationConfig; Is dict[str, tuple[float, float]]
OptResult = dict[str, float]
module-attribute
A COBRAk variability optimization result type alias; Is dict[str, float]
VarResult = dict[str, tuple[float | None, float | None]]
module-attribute
A COBRAk variability result type alias; Is dict[str, tuple[float | None, float | None]]
CorrectionConfig
Stores the configuration for corrections in a model (see parameter corrections chapter in documentation).
Source code in cobrak/dataclasses.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
add_dG0_error_term = False
class-attribute
instance-attribute
Indicates whether to add ΔG'° error terms. Defaults to False.
add_enzyme_conc_error_term = False
class-attribute
instance-attribute
Indicates whether to add enzyme concentration error terms. Defaults to False.
add_error_sum_term = True
class-attribute
instance-attribute
Whether to add an error sum term. Defaults to True.
add_flux_error_term = False
class-attribute
instance-attribute
Indicates whether to add flux error terms. Defaults to False.
add_kcat_times_e_error_term = False
class-attribute
instance-attribute
Indicates whether to add k_cat ⋅ [E] error terms. Defaults to False.
add_km_error_term = False
class-attribute
instance-attribute
Indicates whether to add a kappa error term. Defaults to False.
add_met_logconc_error_term = False
class-attribute
instance-attribute
Indicates whether to add metabolite log concentration error terms. Defaults to False.
dG0_error_cutoff = 1.0
class-attribute
instance-attribute
The cutoff value for the ΔG'° error terms. Defaults to 1.0.
error_scenario = Field(default_factory=list)
class-attribute
instance-attribute
A dictionary where keys are error scenarios and values are tuples representing the lower and upper bounds of the error. Defaults to {}.
error_sum_as_qp = False
class-attribute
instance-attribute
Indicates whether to use a quadratic programming approach for the error sum. Defaults to False.
extra_weights = Field(default_factory=dict)
class-attribute
instance-attribute
Dictionary to store extra weights for specific corrections. Defaults to {}.
kcat_times_e_error_cutoff = 1.0
class-attribute
instance-attribute
The cutoff value for the k_cat ⋅ [E] error term. Defaults to 1.0.
km_error_cutoff = 1.0
class-attribute
instance-attribute
Cutoff value for the κ error term. Defaults to 1.0.
max_abs_dG0_correction = QUASI_INF
class-attribute
instance-attribute
Maximal absolute correction for the dG0 error term. Defaults to QUASI_INF.
max_rel_kcat_times_e_correction = QUASI_INF
class-attribute
instance-attribute
Maximal relative correction for the k_cat ⋅ [E] error error term. Defaults to QUASI_INF.
max_rel_km_correction = 0.999
class-attribute
instance-attribute
Maximal relative correction for the κ error term. Defaults to 0.999.
use_weights = False
class-attribute
instance-attribute
Indicates whether to use weights for the corrections (otherwise, the weight is 1.0). Defaults to False.
var_lb_ub_application = ''
class-attribute
instance-attribute
The application method for variable lower and upper bounds. Either '' (x=x), 'exp' or 'log'. Defaults to ''.
weight_percentile = 90
class-attribute
instance-attribute
Percentile to use for weight calculation. Defaults to 90.
Enzyme
Represents an enzyme in a metabolic model.
Members
molecular_weight (float): The enzyme's molecular weight in kDa. min_conc (float | None): [Optional] If wanted, one can set a special minimal concentration for the enzyme. Defaults to None, i.e., no given concentration value (i.e., only the total enzyme pool is the limit). max_conc (float | None): [Optional] If wanted, one can set a special maximal concentration for the enzyme. Defaults to None, i.e., no given concentration value (i.e., only the total enzyme pool is the limit). annotation (dict[str, str | list[str]]): [Optional] Dictionary containing additional enzyme annotation, e.g., {"UNIPROT_ID": "b12345"}. Defaults to '{}'. name: str: [Optional] Colloquial name of enzyme
Source code in cobrak/dataclasses.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Any annotation data for the enzyme (e.g., references). Has no effect on calculations
max_conc = None
class-attribute
instance-attribute
[Optional] The enzyme's minimal concentration in mmol⋅gDW⁻¹
min_conc = None
class-attribute
instance-attribute
[Optional] The enzyme's minimal concentration in mmol⋅gDW⁻¹
molecular_weight
instance-attribute
The enzyme's molecular weight in kDa
name = ''
class-attribute
instance-attribute
Colloquial name of enzyme
EnzymeReactionData
Represents the enzymes used by a reaction.
Source code in cobrak/dataclasses.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
|
identifiers
instance-attribute
The identifiers (must be given in the associated Model enzymes instance) of the reaction's enzyme(s)
k_a_references = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] References showing the source(s) of the k_a values. Metabolite IDs are keys, the source lists values. Default is {}
k_as = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] The reaction's k_as (Activation constants) in M=mol⋅l⁻¹. Metabolite IDs are keys, k_ms values. Default is {}
k_cat
instance-attribute
The reaction's k_cat (turnover numbers) in h⁻¹
k_cat_references = Field(default_factory=list)
class-attribute
instance-attribute
[Optional] List of references showing the source(s) of the k_cat value
k_i_references = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] References showing the source(s) of the k_i values. Metabolite IDs are keys, the source lists values. Default is {}
k_is = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] The reaction's k_is (Inhibition constants) in M=mol⋅l⁻¹. Metabolite IDs are keys, k_ms values. Default is {}
k_m_references = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] References showing the source(s) of the k_m values. Metabolite IDs are keys, the source lists values. Default is {}
k_ms = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] The reaction's k_ms (Michaelis-Menten constants) in M=mol⋅l⁻¹. Metabolite IDs are keys, k_ms values. Default is {}
special_stoichiometries = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Special (non-1) stoichiometries of polypeptides in the reaction's enzyme. Default is {}
ExtraLinearConstraint
Represents a general linear Model constraint.
This can affect not only reactions, but also all other variables set in a COBRAk model. E.g., if one wants (for whatever reason) the following constraint: 0.5 <= [A] - 2 * r_R1 <= 2.1 the corresponding ExtraLinearConstraint instance would be: ExtraLinearConstraint( stoichiometries = { "x_A": 1.0, "R1": -2, }, lower_value = 0.5, upper_value = 2.1, ) lower_value or upper_value can be None if no such limit is desired.
Source code in cobrak/dataclasses.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
lower_value = None
class-attribute
instance-attribute
Minimal numeric constraint value. Either this and/or upper_value must be not None. Defaults to None.
stoichiometries
instance-attribute
Keys: Model variable names; Children: Multipliers of constraint
upper_value = None
class-attribute
instance-attribute
Maximal numeric constraint value. Either this and/or lower_value must be not None. Defaults to None.
Metabolite
Represents a Model's metabolite.
Source code in cobrak/dataclasses.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
|
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
Optional annotation (e.g., CHEBI numbers, ...); Default is {}
charge = 0
class-attribute
instance-attribute
Electron charge of metabolite
formula = ''
class-attribute
instance-attribute
Chemical formula of metabolite
log_max_conc = log(0.02)
class-attribute
instance-attribute
Maximal logarithmic concentration (only relevant for thermodynamic constraints); Default is log(0.02 M)
log_min_conc = log(1e-06)
class-attribute
instance-attribute
Maximal logarithmic concentration (only relevant for thermodynamic constraints); Default is log(1e-6 M)
name = ''
class-attribute
instance-attribute
Colloquial name of metabolite
Model
Represents a metabolic model in COBRAk.
This includes its Reaction instances (which define the reaction stoichiometries), its Metabolite instances (which are referenced in the mentioned stoichiometries), as well as optional enzymatic and thermodynamic data.
Source code in cobrak/dataclasses.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
R = Field(default=STANDARD_R)
class-attribute
instance-attribute
[Optional and only works with thermodynamic constraints] Gas constant reference for dG'° in kJ⋅K⁻¹⋅mol⁻¹; default is STANDARD_R
T = Field(default=STANDARD_T)
class-attribute
instance-attribute
[Optional and only works with thermodynamic constraints] Temperature reference for dG'° in K; default is STANDARD_T
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Any annotation for the model itself (e.g., its name or references). Has no effect on calculations.
conc_sum_ignore_prefixes = Field(default_factory=list)
class-attribute
instance-attribute
[Optional and only works with thermodynamic constraints]
conc_sum_include_suffixes = Field(default_factory=list)
class-attribute
instance-attribute
[Optional and only works with thermodynamic constraints]
conc_sum_max_rel_error = 0.05
class-attribute
instance-attribute
[Optional and only works with MILPs with thermodynamic constraints] Maximal relative concentration sum approximation error
conc_sum_min_abs_error = 1e-06
class-attribute
instance-attribute
[Optional and only works with MILPs with thermodynamic constraints] Maximal absolute concentration sum approximation error
enzymes = Field(default_factory=dict)
class-attribute
instance-attribute
[Only neccessary with enzymatic constraints] Keys: Enzyme IDs; Children: Enzyme instances; default is {}
extra_linear_constraints = Field(default_factory=list)
class-attribute
instance-attribute
[Optional] Extra linear constraints
fwd_suffix = REAC_FWD_SUFFIX
class-attribute
instance-attribute
[Optional] Reaction ID suffix of forward reaction variants (e.g. in a reversible reaction A→B, for the direction A→B). Default is '_FWD'
kinetic_ignored_metabolites = Field(default_factory=list)
class-attribute
instance-attribute
[Optional and only works with saturation term constraints] Metabolite IDs for which no k_m is neccessary
max_conc_sum = float('inf')
class-attribute
instance-attribute
[Optional and only works with thermodynamic constraints] Maximal allowed sum of concentrations (for MILPs: linear approximation; for NLPs: Exact value). Inactive if set to default value of float('inf')
max_prot_pool = Field(default=1000000000.0)
class-attribute
instance-attribute
[Only neccessary with enzymatic constraints] Maximal usable protein pool in g/gDW; default is 1e9, i.e. basically unrestricted
metabolites
instance-attribute
Keys: Metabolite IDs; Children: Metabolite instances
reac_enz_separator = REAC_ENZ_SEPARATOR
class-attribute
instance-attribute
[Optional] String infix that separated reaction IDs of reaction with multiple enzyme variants from their enzyme ID. Defaults to 'ENZ'
reactions
instance-attribute
Keys: Reaction IDs; Children: Reaction instances
rev_suffix = REAC_REV_SUFFIX
class-attribute
instance-attribute
[Optional] Reaction ID suffix of reverse reaction variants (e.g. in a reversible reaction A→B, for the direction B→A). Default is '_REV'
__enter__()
Method called when entering 'with' blocks
Source code in cobrak/dataclasses.py
244 245 246 247 |
|
__exit__(a, b, c)
Method called when leaving a 'with' block
Source code in cobrak/dataclasses.py
249 250 251 |
|
ParameterReference
Represents the database reference for a kinetic parameter.
Source code in cobrak/dataclasses.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
comment = '(no refs)'
class-attribute
instance-attribute
Any comment given for this value (e.g. literature)? Defaults to '(no refs)'.
database = ''
class-attribute
instance-attribute
(If given) The database from which this parameter was read. Defaults to ''.
pubs = Field(default_factory=list)
class-attribute
instance-attribute
species = ''
class-attribute
instance-attribute
Scientific name of the species where this value was measured. Defaults to ''.
substrate = ''
class-attribute
instance-attribute
The metabolite (or reaction substrate) for which this value was measured. Defaults to ''.
Reaction
Represents a Model's reaction.
E.g., a reaction A -> B [0; 1000], ΔG'°=12.1 kJ⋅mol⁻¹, catalyzed by E1 with k_cat=1000 h⁻¹ would be Reaction( stoichiometries: { "A": -1, "B": +1, }, min_flux: 0, max_flux: 1000, dG0=12.1, dG0_uncertainty=None, enzyme_reaction_data=EnzymeReactionData( identifiers=["E1"], k_cat=1000, k_ms=None, k_is=None, k_as=None, ), annotation={}, # Can be also ignored )
Source code in cobrak/dataclasses.py
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
|
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
Optional annotation (e.g., KEGG identifiers, ...)
dG0 = None
class-attribute
instance-attribute
If given, the Gibb's free energy of the reaction (only relevant for thermodynamic constraints); Default is None
dG0_uncertainty = None
class-attribute
instance-attribute
If given, the Gibb's free energy's uncertainty (only relevant for thermodynamic constraints); Default is None
enzyme_reaction_data = None
class-attribute
instance-attribute
If given, enzymatic data (only relevant for enzymatic constraints); Default is None
max_flux
instance-attribute
Maximal flux (must be >= min_flux)
min_flux
instance-attribute
Minimal flux (for COBRAk, this must be ≥ 0)
name = ''
class-attribute
instance-attribute
Colloquial name of reaction
stoichiometries
instance-attribute
Metabolite stoichiometries
Solver
Represents options for a pyomo-compatible solver
Source code in cobrak/dataclasses.py
298 299 300 301 302 303 304 305 306 307 308 309 |
|
name
instance-attribute
The solver's name. E.g. 'scip' for SCIP and 'cplex_direct' for CPLEX.
solve_extra_options = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Options set on pyomo's solve function.
solver_attrs = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Options set on the solver object in pyomo.
solver_options = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Options transmitted to the solver itself.
equilibrator_functionality
This script is a wrapper for the ΔG'° determination with the eQuilibrator API.
This wrapper intends to work with BiGG-styled cobrapy metabolic models.
equilibrator_get_model_dG0_and_uncertainty_values(sbml_path, inner_to_outer_compartments, phs, pmgs, ionic_strengths, potential_differences, exclusion_prefixes=[], exclusion_inner_parts=[], ignore_uncertainty=False, max_uncertainty=1000.0)
Cobrapy model wrapper for the ΔG'° determination of reactions using the eQuilibrator-API.
Reactions are identified according to all annotation (in the cobrapy reaction's annotation member variable) given in this modules global USED_IDENTIFIERS list.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sbml_path
|
str
|
The path to the SBML-encoded constraint-based metabolic model for which ΔG'° values are determined. |
required |
inner_to_outer_compartments
|
List[str]
|
A list with compartment IDs going from inner (e.g., in E. coli, the cytosol or 'c' in iML1515) to outer (e.g., the extracellular component or 'e' in iML1515). Used for the ΔG'° calculation in multi-compartmental reactions. |
required |
phs
|
Dict[str, float]
|
A dictionary with compartment IDs as keys and the compartment pHs as values. |
required |
pmgs
|
Dict[str, float]
|
A dictionary with compartment IDs as keys and the compartment pMgs as values. |
required |
ionic_strengths
|
Dict[str, float]
|
A dictionary with compartment IDs as keys and the ionic strengths as values. |
required |
potential_differences
|
Dict[Tuple[str, str], float]
|
A dictionary containing tuples with 2 elements describing the ID of an innter and outer compartment, and the potential difference between them. |
required |
max_uncertainty
|
float
|
The maximal accepted uncertainty value (defaults to 1000 kJ⋅mol⁻¹). If a calculated uncertainty is higher than this value, the associated ΔG'° is not used (i.e., the specific reaction gets no ΔG'°). |
1000.0
|
Returns:
Type | Description |
---|---|
tuple[dict[str, float], dict[str, float]]
|
Dict[str, Dict[str, float]]: A dictionary with the reaction IDs as keys, and dictionaries as values which, in turn, contain the ΔG'° of a reaction under the key 'dG0' and the calculated uncertainty as 'uncertainty'. |
Source code in cobrak/equilibrator_functionality.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
|
evolution
Includes functions for calling COBRA-k's genetic algorithm for global NLP-based optimization.
The actual genetic algorithm can be found in the module 'genetic'.
COBRAKProblem
Represents a problem to be solved using evolutionary optimization techniques.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The original COBRA-k model to optimize. |
required |
objective_target
|
dict[str, float]
|
The target values for the objectives. |
required |
objective_sense
|
int
|
The sense of the objective function (1 for maximization, -1 for minimization). |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
The variability data for each reaction. |
required |
nlp_dict_list
|
list[dict[str, float]]
|
A list of initial NLP solutions. |
required |
best_value
|
float
|
The best value found so far. |
required |
with_kappa
|
bool
|
Whether to use kappa parameter. Defaults to True. |
True
|
with_gamma
|
bool
|
Whether to use gamma parameter. Defaults to True. |
True
|
with_iota
|
bool
|
Whether to use iota parameter. Defaults to True. |
True
|
with_alpha
|
bool
|
Whether to use alpha parameter. Defaults to True. |
True
|
num_gens
|
int
|
The number of generations in the evolutionary algorithm. Defaults to 5. |
5
|
algorithm
|
Literal['pso', 'genetic']
|
The type of optimization algorithm to use. Defaults to "pso". |
'pso'
|
lp_solver
|
Solver
|
The linear programming solver to use. Defaults to SCIP. |
SCIP
|
nlp_solver
|
Solver
|
The nonlinear programming solver to use. Defaults to IPOPT. |
IPOPT
|
objvalue_json_path
|
str
|
The path to the JSON file for storing objective values. Defaults to "". |
''
|
max_rounds_same_objvalue
|
float
|
The maximum number of rounds with the same objective value before stopping. Defaults to float("inf"). |
float('inf')
|
correction_config
|
CorrectionConfig
|
Configuration for corrections during optimization. Defaults to CorrectionConfig(). |
CorrectionConfig()
|
min_abs_objvalue
|
float
|
The minimum absolute value of the objective function to consider as valid. Defaults to 1e-6. |
1e-06
|
pop_size
|
int | None
|
The population size for the evolutionary algorithm. Defaults to None. |
None
|
Attributes:
Name | Type | Description |
---|---|---|
original_cobrak_model |
Model
|
A deep copy of the original COBRA-k model. |
blocked_reacs |
list[str]
|
List of blocked reactions. |
initial_xs_list |
list[list[int | float]]
|
Initial list of solutions for each NLP. |
minimal_xs_dict |
dict[float, list[float]]
|
Dictionary to store minimal solutions. |
variability_data |
dict[str, tuple[float, float]]
|
A deep copy of the variability data. |
idx_to_reac_ids |
dict[int, tuple[str, ...]]
|
Mapping from index to reaction IDs. |
dim |
int
|
The dimension of the problem. |
lp_solver |
Solver
|
The linear programming solver. |
nlp_solver |
Solver
|
The nonlinear programming solver. |
temp_directory_name |
str
|
Name of the temporary directory for storing results. |
best_value |
float
|
The best value found so far. |
objvalue_json_path |
str
|
Path to the JSON file for objective values. |
max_rounds_same_objvalue |
float
|
Maximum number of rounds with same objective value. |
correction_config |
CorrectionConfig
|
Configuration for corrections. |
min_abs_objvalue |
float
|
Minimum absolute value of objective function to consider valid. |
Source code in cobrak/evolution.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
|
__init__(cobrak_model, objective_target, objective_sense, variability_dict, nlp_dict_list, best_value, with_kappa=True, with_gamma=True, with_iota=True, with_alpha=True, num_gens=5, algorithm='pso', lp_solver=SCIP, nlp_solver=IPOPT, objvalue_json_path='', max_rounds_same_objvalue=float('inf'), correction_config=CorrectionConfig(), min_abs_objvalue=1e-06, pop_size=None)
Initializes a COBRAKProblem object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The original COBRA-k model to optimize. |
required |
objective_target
|
dict[str, float]
|
The target values for the objectives. |
required |
objective_sense
|
int
|
The sense of the objective function (1 for maximization, -1 for minimization). |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
The variability data for each reaction. |
required |
nlp_dict_list
|
list[dict[str, float]]
|
A list of initial NLP solutions. |
required |
best_value
|
float
|
The best value found so far. |
required |
with_kappa
|
bool
|
Whether to use kappa parameter. Defaults to True. |
True
|
with_gamma
|
bool
|
Whether to use gamma parameter. Defaults to True. |
True
|
with_iota
|
bool
|
Whether to use iota parameter. Defaults to True. |
True
|
with_alpha
|
bool
|
Whether to use alpha parameter. Defaults to True. |
True
|
num_gens
|
int
|
The number of generations in the evolutionary algorithm. Defaults to 5. |
5
|
algorithm
|
Literal['pso', 'genetic']
|
The type of optimization algorithm to use. Defaults to "pso". |
'pso'
|
lp_solver
|
Solver
|
The linear programming solver to use. Defaults to SCIP. |
SCIP
|
nlp_solver
|
Solver
|
The nonlinear programming solver to use. Defaults to IPOPT. |
IPOPT
|
objvalue_json_path
|
str
|
The path to the JSON file for storing objective values. Defaults to "". |
''
|
max_rounds_same_objvalue
|
float
|
The maximum number of rounds with the same objective value before stopping. Defaults to float("inf"). |
float('inf')
|
correction_config
|
CorrectionConfig
|
Configuration for corrections during optimization. Defaults to CorrectionConfig(). |
CorrectionConfig()
|
min_abs_objvalue
|
float
|
The minimum absolute value of the objective function to consider as valid. Defaults to 1e-6. |
1e-06
|
pop_size
|
int | None
|
The population size for the evolutionary algorithm. Defaults to None. |
None
|
Source code in cobrak/evolution.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
|
fitness(x)
Calculates the fitness of a given solution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
list[float | int]
|
The solution to evaluate. |
required |
Returns:
Type | Description |
---|---|
list[tuple[float, list[float | int]]]
|
list[tuple[float, list[float | int]]]: A list of tuples, where each tuple contains the fitness value and the corresponding solution. |
Source code in cobrak/evolution.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
optimize()
Performs the optimization process.
Returns:
Type | Description |
---|---|
dict[float, list[dict[str, float]]]
|
dict[float, list[dict[str, float]]]: A dictionary containing the optimization results. |
Source code in cobrak/evolution.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
|
perform_nlp_evolutionary_optimization(cobrak_model, objective_target, objective_sense, variability_dict={}, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, sampling_wished_num_feasible_starts=3, sampling_max_metarounds=3, sampling_rounds_per_metaround=2, sampling_max_deactivated_reactions=5, sampling_always_deactivated_reactions=[], evolution_num_gens=5, algorithm='genetic', lp_solver=SCIP, nlp_solver=IPOPT, objvalue_json_path='', max_rounds_same_objvalue=float('inf'), correction_config=CorrectionConfig(), min_abs_objvalue=1e-13, pop_size=None, working_results=[])
Performs NLP evolutionary optimization on the given COBRA-k model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k model to optimize. |
required |
objective_target
|
str | dict[str, float]
|
Target value(s) for the objective function. |
required |
objective_sense
|
int
|
Sense of the objective function (1 for maximization, -1 for minimization). |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
Variability data for each reaction. Defaults to {}. |
{}
|
with_kappa
|
bool
|
Whether to use kappa parameter. Defaults to True. |
True
|
with_gamma
|
bool
|
Whether to use gamma parameter. Defaults to True. |
True
|
with_iota
|
bool
|
Whether to use iota parameter. Defaults to False. |
False
|
with_alpha
|
bool
|
Whether to use alpha parameter. Defaults to False. |
False
|
sampling_wished_num_feasible_starts
|
int
|
The number of wished feasible start solutions. Defaults to 3. |
3
|
sampling_max_metarounds
|
int
|
Maximum number of meta rounds for sampling. Defaults to 3. |
3
|
sampling_rounds_per_metaround
|
int
|
Number of rounds per meta round for sampling. Defaults to 2. |
2
|
sampling_max_deactivated_reactions
|
int
|
Maximum number of deactivated reactions allowed. Defaults to 5. |
5
|
sampling_always_deactivated_reactions
|
list[str]
|
List of reactions that should always be deactivated. Defaults to []. |
[]
|
evolution_num_gens
|
int
|
Number of generations for the evolutionary algorithm. Defaults to 5. |
5
|
algorithm
|
Literal['pso', 'genetic']
|
Type of optimization algorithm to use. Defaults to "genetic", which is also the only algorithm currently available. |
'genetic'
|
lp_solver
|
Solver
|
The linear programming solver to use. Defaults to SCIP. |
SCIP
|
nlp_solver
|
Solver
|
The nonlinear programming solver to use. Defaults to IPOPT. |
IPOPT
|
objvalue_json_path
|
str
|
Path to the JSON file for objective values. Defaults to "". |
''
|
max_rounds_same_objvalue
|
float
|
Maximum number of rounds with same objective value before stopping. Defaults to float("inf"). |
float('inf')
|
correction_config
|
CorrectionConfig
|
Configuration for corrections during optimization. Defaults to CorrectionConfig(). |
CorrectionConfig()
|
min_abs_objvalue
|
float
|
Minimum absolute value of objective function to consider valid. Defaults to 1e-13. |
1e-13
|
pop_size
|
int | None
|
Population size for the evolutionary algorithm. Defaults to None. |
None
|
working_results
|
list[dict[str, float]]
|
List of initial feasible results. Defaults to []. |
[]
|
Returns:
Type | Description |
---|---|
dict[float, list[dict[str, float]]]
|
dict[float, list[dict[str, float]]]: Dictionary of objective values and corresponding solutions. |
Source code in cobrak/evolution.py
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 |
|
postprocess(cobrak_model, opt_dict, objective_target, objective_sense, variability_data, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, lp_solver=SCIP, nlp_solver=IPOPT, verbose=False, correction_config=CorrectionConfig(), onlytested='')
Postprocesses the optimization results to find feasible switches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k model to optimize. |
required |
opt_dict
|
dict[str, float]
|
Optimization result dictionary. |
required |
objective_target
|
str | dict[str, float]
|
Target value(s) for the objective function. |
required |
objective_sense
|
int
|
Sense of the objective function (1 for maximization, -1 for minimization). |
required |
variability_data
|
dict[str, tuple[float, float]]
|
Variability data for each reaction. |
required |
with_kappa
|
bool
|
Whether to use kappa parameter. Defaults to True. |
True
|
with_gamma
|
bool
|
Whether to use gamma parameter. Defaults to True. |
True
|
with_iota
|
bool
|
Whether to use iota parameter. Defaults to False. |
False
|
with_alpha
|
bool
|
Whether to use alpha parameter. Defaults to False. |
False
|
lp_solver
|
Solver
|
The linear programming solver to use. Defaults to SCIP. |
SCIP
|
nlp_solver
|
Solver
|
The nonlinear programming solver to use. Defaults to IPOPT. |
IPOPT
|
verbose
|
bool
|
Whether to enable verbose output. Defaults to False. |
False
|
correction_config
|
CorrectionConfig
|
Configuration for corrections during optimization. Defaults to CorrectionConfig(). |
CorrectionConfig()
|
onlytested
|
str
|
Specific reactions to test during postprocessing. Defaults to "". |
''
|
Returns:
Type | Description |
---|---|
tuple[float, list[float | int]]
|
tuple[float, list[float | int]]: Best result and a list of feasible switches. |
Source code in cobrak/evolution.py
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
example_models
Currently just contains the toy model form COBRAk's documentation as example model
expasy_functionality
This module provides functionality to parse Expasy enzyme RDF files and extract EC number transfers.
get_ec_number_transfers(expasy_enzyme_rdf_path)
Parses an Expasy enzyme RDF file to extract enzyme EC number transfers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expasy_enzyme_rdf_path
|
str
|
Path to the Expasy enzyme RDF file. |
required |
Returns:
Type | Description |
---|---|
dict[str, str]
|
dict[str, str]: A dictionary where each key is an EC number, and its corresponding value is the EC number it is transferred to. The dictionary includes both directions of the transfer (old to new and new to old). |
Source code in cobrak/expasy_functionality.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
io
General (COBRAk-independent) helper functions, primarily for I/O tasks such as pickle and JSON file handlings.
convert_cobrak_model_to_annotated_cobrapy_model(cobrak_model, combine_base_reactions=False, add_enzyme_constraints=False)
Converts a COBRAk model to an annotated COBRApy model.
This function takes a COBRAk model and converts it to a COBRApy model, adding annotations and constraints as specified by the input parameters.
The function adds the following annotation keys to the COBRApy model:
cobrak_Cmin
: The minimum concentration of a metabolite.cobrak_Cmax
: The maximum concentration of a metabolite.cobrak_id_<version>
: The ID of the reaction in the COBRAk model.cobrak_dG0_<version>
: The standard Gibbs free energy change of a reaction.cobrak_dG0_uncertainty_<version>
: The uncertainty of the standard Gibbs free energy change of a reaction.cobrak_k_cat_<version>
: The turnover number of an enzyme.cobrak_k_ms_<version>
: The Michaelis constant of an enzyme.cobrak_k_is_<version>
: The inhibition constant of an enzyme.cobrak_k_as_<version>
: The activation constant of an enzyme.cobrak_special_stoichiometries_<version>
: Special stoichiometries of a reaction.cobrak_max_prot_pool
: The maximum protein pool size.cobrak_R
: The gas constant.cobrak_T
: The temperature.cobrak_kinetic_ignored_metabolites
: A list of metabolites that are ignored in kinetic simulations.cobrak_extra_linear_constraints
: A list of extra linear constraints.cobrak_mw
: The molecular weight of an enzyme.cobrak_min_conc
: The minimum concentration of an enzyme.cobrak_max_conc
: The maximum concentration of an enzyme.
The conversion process also involves the merging of forward and reverse reactions, as well as isomeric alternatives,
into a single reaction in the COBRApy model. When the combine_base_reactions parameter is set to True,
the function combines these reactions into a single entity, while still preserving the unique characteristics
of each original reaction. To achieve this, the function uses a versioning system, denoted by the
The conversion of a COBRAk model to a COBRApy model also includes the optional direct addition of enzyme constraints in the style of GECKO [1] (or expaned sMOMENT [2]), which can be enabled through the add_enzyme_constraints parameter. When this parameter is set to True, the function introduces new pseudo-metabolites and pseudo-reactions to the model, allowing for the simulation of enzyme kinetics and protein expression. Specifically, a protein pool pseudo-metabolite is added, which represents the total amount of protein available in the system. Additionally, pseudo-reactions are created to deliver enzymes to the protein pool, taking into account the molecular weight and concentration of each enzyme. The function also adds pseudo-reactions to form enzyme complexes, which are essential for simulating the k_cat-based kinetics of enzymatic reactions.
[1] https://doi.org/10.15252/msb.20167411 [2] https://doi.org/10.1186/s12859-019-3329-9
Parameters
cobrak_model : Model The COBRAk model to be converted. combine_base_reactions : bool, optional Whether to combine base reactions into a single reaction (default: False). add_enzyme_constraints : bool, optional Whether to add enzyme constraints to the model (default: False).
Returns
cobra.Model The converted COBRApy model.
Raises
ValueError If combine_base_reactions and add_enzyme_constraints are both True.
Source code in cobrak/io.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
|
ensure_folder_existence(folder)
Checks if the given folder exists. If not, the folder is created.
Argument
- folder: str ~ The folder whose existence shall be enforced.
Source code in cobrak/io.py
131 132 133 134 135 136 137 138 139 140 141 |
|
ensure_json_existence(path)
Ensures that a JSON file exists at the specified path.
If the file does not exist, it creates an empty JSON file with "{}" as its content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The file path where the JSON file should exist. |
required |
Source code in cobrak/io.py
144 145 146 147 148 149 150 151 152 153 154 155 |
|
get_base_id(reac_id, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX, reac_enz_separator=REAC_ENZ_SEPARATOR)
Extract the base ID from a reaction ID by removing specified suffixes and separators.
Processes a reaction ID to remove forward and reverse suffixes as well as any enzyme separators, to obtain the base reaction ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reac_id
|
str
|
The reaction ID to be processed. |
required |
fwd_suffix
|
str
|
The suffix indicating forward reactions. Defaults to REAC_FWD_SUFFIX. |
REAC_FWD_SUFFIX
|
rev_suffix
|
str
|
The suffix indicating reverse reactions. Defaults to REAC_REV_SUFFIX. |
REAC_REV_SUFFIX
|
reac_enz_separator
|
str
|
The separator used between reaction and enzyme identifiers. Defaults to REAC_ENZ_SEPARATOR. |
REAC_ENZ_SEPARATOR
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The base reaction ID with specified suffixes and separators removed. |
Source code in cobrak/io.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
|
get_files(path)
Returns the names of the files in the given folder as a list of strings.
Arguments
- path: str ~ The path to the folder of which the file names shall be returned
Source code in cobrak/io.py
514 515 516 517 518 519 520 521 522 523 524 |
|
get_folders(path)
Returns the names of the folders in the given folder as a list of strings.
Arguments
- path: str ~ The path to the folder whose folders shall be returned
Source code in cobrak/io.py
527 528 529 530 531 532 533 534 535 536 537 538 |
|
json_load(path, dataclass_type=Any)
Load JSON data from a file and validate it against a specified dataclass type.
This function reads the content of a JSON file located at the given path
, parses it,
and validates the parsed data against the provided dataclass_type
. If the data is valid
according to the dataclass schema, it returns an instance of the dataclass populated with
the data. Otherwise, it raises an exception.
Parameters:
path : str The file path to the JSON file that needs to be loaded.
Type[T]
A dataclass type against which the JSON data should be validated and deserialized.
Returns:
T
An instance of the specified dataclass_type
populated with the data from the JSON file.
Raises:
JSONDecodeError If the content of the file is not a valid JSON string.
ValidationError
If the parsed JSON data does not conform to the schema defined by dataclass_type
.
Examples:
@dataclass ... class Person: ... name: str ... age: int
person = json_load('person.json', Person) print(person.name, person.age) John Doe 30
Source code in cobrak/io.py
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
|
json_write(path, json_data)
Writes a JSON file at the given path with the given data as content.
Can be also used for any of COBRAk's dataclasses as well as any dictionary of the form dict[str, dict[str, T] | None] where T stands for a COBRAk dataclass or any other JSON-compatible object type.
Arguments
- path: str ~ The path of the JSON file that shall be written
- json_data: Any ~ The dictionary or list which shalll be the content of the created JSON file
Source code in cobrak/io.py
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 |
|
json_zip_load(path)
Loads the given zipped JSON file and returns it as json_data (a list or a dictionary).
Arguments
- path: str ~ The path of the JSON file without ".zip" at the end
Returns
dict or list ~ The loaded JSON data
Source code in cobrak/io.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
|
json_zip_write(path, json_data, zip_method=zipfile.ZIP_LZMA)
Writes a zipped JSON file at the given path with the given dictionary as content.
Arguments
- path: str ~ The path of the JSON file that shall be written without ".zip" at the end
- json_data: Any ~ The dictionary or list which shalll be the content of the created JSON file
Source code in cobrak/io.py
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 |
|
load_annotated_cobrapy_model_as_cobrak_model(cobra_model, exclude_enzyme_constraints=True)
Converts a COBRApy model with annotations into a COBRAk Model.
This function takes a COBRApy model, which may contain specific annotations for metabolites, reactions, and genes, and converts it into a COBRAk model. The conversion involves extracting relevant annotations and constructing COBRAk-specific data structures for metabolites, reactions, and enzymes.
- cobra_model (cobra.Model): The COBRApy model to be converted. This model should contain annotations that are compatible with the COBRAk model structure.
- exclude_enzyme_constraints (bool): Whether or not to exclude all stoichiometric enzyme constraint additions. Defaults to True.
- Model: A COBRAk model constructed from the annotated COBRApy model, including metabolites, reactions, and enzymes with their respective parameters and constraints.
Notes: - The function assumes that certain annotations (e.g., "cobrak_Cmin", "cobrak_dG0") are present in the COBRApy model. Missing annotations will result in default values being used. - Reactions with IDs like "prot_pool_delivery" and those starting with "enzyme_delivery_" are ignored. - Ensure that the COBRApy model is correctly annotated to fully leverage the conversion process.
Source code in cobrak/io.py
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 |
|
load_annotated_sbml_model_as_cobrak_model(filepath)
Load an annotated SBML model from a file and convert it into a COBRAk Model.
This function reads an SBML file containing a metabolic model with specific annotations
and converts it into a COBRAk Model. It uses the COBRApy library to read the SBML
file and then uses the load_annotated_cobrapy_model_as_cobrak_model
function to perform
the conversion.
Parameters: - filepath (str): The path to the SBML file containing the annotated metabolic model.
- Model: A COBRAk Model constructed from the annotated SBML model, ready for further kinetic and thermodynamic analyses.
Source code in cobrak/io.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 |
|
load_unannotated_sbml_as_cobrapy_model(path)
Loads an unannotated SBML model from a file into a COBRApy model.
This function reads an SBML file that contains a metabolic model without specific annotations
and loads it into a COBRApy model object. It utilizes the COBRApy library's read_sbml_model
function to perform the loading.
Parameters: - path (str): The file path to the SBML file containing the metabolic model.
Returns: - cobra.Model: A COBRApy model object representing the metabolic network described in the SBML file.
Source code in cobrak/io.py
929 930 931 932 933 934 935 936 937 938 939 940 941 942 |
|
pickle_load(path)
Returns the value of the given pickle file.
Arguments
- path: str ~ The path to the pickle file.
Source code in cobrak/io.py
945 946 947 948 949 950 951 952 953 |
|
pickle_write(path, pickled_object)
Writes the given object as pickled file with the given path
Arguments
- path: str ~ The path of the pickled file that shall be created
- pickled_object: Any ~ The object which shall be saved in the pickle file
Source code in cobrak/io.py
956 957 958 959 960 961 962 963 964 965 |
|
save_cobrak_model_as_annotated_sbml_model(cobrak_model, filepath, combine_base_reactions=False, add_enzyme_constraints=False)
Exports a COBRAk model to an annotated SBML file.
This function converts a Model
to a COBRApy model and writes it to an SBML file at the specified file path.
Optionally, stoichiometric GECKO [1]-like enzyme constraints can be added during the conversion.
[1] Sánchez et al. Molecular systems biology, 13(8), 935. https://doi.org/10.15252/msb.20167411
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The |
required |
filepath
|
str
|
The file path where the SBML file will be saved. |
required |
add_enzyme_constraints
|
bool
|
Whether to add enzyme constraints during the conversion. Defaults to False. |
False
|
Source code in cobrak/io.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 |
|
standardize_folder(folder)
Returns for the given folder path is returned in a more standardized way.
I.e., folder paths with potential \ are replaced with /. In addition, if a path does not end with / will get an added /. If the given folder path is empty (''), it returns just ''.
Argument
- folder: str ~ The folder path that shall be standardized.
Source code in cobrak/io.py
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 |
|
lps
COBRAk LPs and MILPs.
This file contains all linear program (LP) and mixed-integer linear program (MILP) functions that can be used with COBRAk models. With LP, one can integrate stoichiometric and enzymatic constraints. With MILP, one can additionally integrate thermodynamic constraints. For non-linear-programs (NLP), see nlps.py in the same folder.
add_flux_sum_var(model, cobrak_model)
Add a flux sum variable to a (N/MI)LP model.
This function introduces a flux sum variable to a given (N/MI)LP Pyomo model, which represents the total sum of absolute fluxes across all reactions in the COBRAk model. The methodology is based on the pFBA (Parsimonious Flux Balance Analysis) approach [1].
[1] Lewis et al. Molecular systems biology 6.1 (2010): 390. https://doi.org/10.1038/msb.2010.47
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ConcreteModel
|
The Pyomo instance of the (N/MI)LP model. |
required |
cobrak_model
|
Model
|
The associated metabolic model containing reaction data. |
required |
Returns:
Name | Type | Description |
---|---|---|
ConcreteModel |
ConcreteModel
|
The modified Pyomo model with the added flux sum variable and constraint. |
Source code in cobrak/lps.py
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
|
add_loop_constraints_to_lp(model, cobrak_model, only_nonthermodynamic, ignored_reacs=[])
Add mixed-integer loop constraints to a (N/MI)LP model to prevent thermodynamically infeasible cycles.
This function incorporates loop constraints into a given (N/MI)LP Pyomo model based on the COBRAk model's reaction data. It follows the ll-COBRA methodology described in [1] to prevent the formation of thermodynamically infeasible cycles in metabolic networks.
[1] Schellenberger et al. (2011). Biophysical journal, 100(3), 544-553. https://doi.org/10.1016/j.bpj.2010.12.3707
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ConcreteModel
|
The Pyomo instance of the (N/MI)LP model. |
required |
cobrak_model
|
Model
|
The associated metabolic model containing reaction data. |
required |
only_nonthermodynamic
|
bool
|
If True, only add constraints to reactions without thermodynamic data. |
required |
Returns:
Name | Type | Description |
---|---|---|
ConcreteModel |
ConcreteModel
|
The modified Pyomo model with added loop constraints. |
Source code in cobrak/lps.py
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 |
|
get_lp_from_cobrak_model(cobrak_model, with_enzyme_constraints, with_thermodynamic_constraints, with_loop_constraints, with_flux_sum_var=False, ignored_reacs=[], min_mdf=STANDARD_MIN_MDF, add_thermobottleneck_analysis_vars=False, strict_kappa_products_equality=False, add_extra_linear_constraints=True, correction_config=CorrectionConfig())
Construct a linear programming (LP) model from a COBRAk model with various constraints and configurations.
This function creates a steady-state LP model from the provided COBRAk Model and enhances it with different types of constraints and variables based on the specified parameters. It allows for the inclusion of enzyme constraints, thermodynamic constraints, loop constraints, and additional linear constraints. Furthermore, it supports the addition of flux sum variables and error handling configurations.
See the following chapters of COBRAk's documentation for more on these constraints:
- Steady-state and extra linear constraints ⇒ Chapter "Linear Programs"
- Enzyme constraints ⇒ Chapter "Linear Programs"
- Thermodynamic constraints ⇒ Chapter "Mixed-Integer Linear Programs"
Parameters
cobrak_model : Model The COBRAk Model from which to construct the LP model. with_enzyme_constraints : bool If True, adds enzyme-pool constraints to the model. with_thermodynamic_constraints : bool If True, adds thermodynamic MILP constraints to the model, ensuring that reaction fluxes are thermodynamically feasible by considering Gibbs free energy changes. with_loop_constraints : bool If True, adds loop constraints to prevent or control flux loops in the metabolic network. This constraint makes the LP a MILP as a binary variable controls whether either the forward or the reverse reaction is running. with_flux_sum_var : bool, optional If True, adds a flux sum variable to the model, which aggregates the total flux through all reactions for optimization or analysis purposes. Defaults to False. ignored_reacs : list[str], optional List of reaction IDs to ignore in the model, which will be excluded. Defaults to []. min_mdf : float, optional Minimum value for Max-Min Driving Force (MDF). Only relevant with thermodynamic constraints. Defaults to STANDARD_MIN_MDF. add_thermobottleneck_analysis_vars : bool, optional If True, adds variables for thermodynamic bottleneck analysis, helping to identify potential bottlenecks in the metabolic network where thermodynamic constraints might limit flux. Defaults to False. strict_kappa_products_equality : bool, optional If True, enforces strict equality for kappa products, ensuring consistency in thermodynamic parameters related to reaction products. Defaults to False. add_extra_linear_constraints : bool, optional If True, adds extra linear constraints from the COBRAk Mmodel, allowing for additional linear constraints. Defaults to True. correction_config : CorrectionConfig, optional Configuration for parameter correction handling in the model, allowing for the inclusion of error terms in constraints related to enzyme activity, thermodynamics, etc. Defaults to CorrectionConfig().
Returns
ConcreteModel The constructed LP model with the specified constraints and configurations.
Source code in cobrak/lps.py
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 |
|
perform_lp_min_active_reactions_analysis(cobrak_model, with_enzyme_constraints, variability_dict, min_mdf=0.0, verbose=False, solver=SCIP)
Run a mixed-integer linear program to determine the minimum number of active reactions.
This function constructs and solves a mixed-integer linear programming model to find the minimum number of reactions that need to be active to satisfy the given variability constraints. It uses a binary variable for each reaction to indicate whether it is active, and the objective is to minimize the sum of these binary variables. The model includes constraints based on enzyme data, thermodynamic feasibility, and loop prevention, depending on the specified parameters.
Parameters
cobrak_model : Model The COBRA-k model containing the metabolic network and reaction data. with_enzyme_constraints : bool If True, includes enzyme-pool constraints in the model. variability_dict : dict[str, tuple[float, float]] A dictionary where keys are reaction IDs and values are tuples specifying (lower bound, upper bound) for reaction fluxes. min_mdf : float, optional Minimum value for Min-Max Driving Force (MDF), setting a lower bound on fluxes. Defaults to 0.0. verbose : bool, optional If True, enables solver output. Defaults to False. solver: Solver The MILP solver used for this analysis. Defaults to SCIP.
Returns
float The minimum number of active reactions required to satisfy the constraints.
Source code in cobrak/lps.py
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 |
|
perform_lp_optimization(cobrak_model, objective_target, objective_sense, with_enzyme_constraints=False, with_thermodynamic_constraints=False, with_loop_constraints=False, variability_dict={}, ignored_reacs=[], min_mdf=STANDARD_MIN_MDF, verbose=False, with_flux_sum_var=False, solver=SCIP, correction_config=CorrectionConfig())
Perform linear programming optimization on a COBRAk model to determine flux distributions.
This function constructs and solves an LP problem for the given metabolic model using specified constraints, variables, and solver options. It supports various types of constraints such as enzyme constraints, thermodynamic constraints, and loop constraints. Additionally, it can handle variability dictionaries and ignored reactions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
A COBRAk Model object representing the metabolic network. |
required |
objective_target
|
str | dict[str, float]
|
The target for optimization. Can be a reaction ID if optimizing a single reaction or a dictionary specifying flux values for multiple reactions. |
required |
objective_sense
|
int
|
The sense of the optimization problem (+1: maximize, -1: minimize). |
required |
with_enzyme_constraints
|
bool
|
Whether to include enzyme constraints in the model. Defaults to False. |
False
|
with_thermodynamic_constraints
|
bool
|
Whether to include thermodynamic constraints in the model. Defaults to False. |
False
|
with_loop_constraints
|
bool
|
Whether to include loop closure constraints in the model. Defaults to False. |
False
|
variability_dict
|
dict[str, tuple[float, float]]
|
A dictionary specifying variable bounds for reactions or metabolites. Defaults to an empty dict. |
{}
|
ignored_reacs
|
list[str]
|
List of reaction IDs to deactivate during optimization. Defaults to an empty list. |
[]
|
min_mdf
|
float
|
Minimum metabolic distance factor threshold for thermodynamic constraints. Defaults to STANDARD_MIN_MDF. |
STANDARD_MIN_MDF
|
verbose
|
bool
|
Whether to print solver output information. Defaults to False. |
False
|
with_flux_sum_var
|
bool
|
Whether to include flux sum variable in the model. Defaults to False. |
False
|
solver
|
Solver
|
Solver used for LP. Default is SCIP. |
SCIP
|
correction_config
|
CorrectionConfig
|
Configuration for handling prameter corrections and scenarios during optimization. |
CorrectionConfig()
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
dict[str, float]: A dictionary containing the flux distribution results for each reaction in the model. |
Source code in cobrak/lps.py
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 |
|
perform_lp_thermodynamic_bottleneck_analysis(cobrak_model, with_enzyme_constraints=False, min_mdf=STANDARD_MIN_MDF, verbose=False, solver=SCIP)
Perform thermodynamic bottleneck analysis on a COBRAk model using mixed-integer linear programming.
This function identifies a minimal set of thermodynamic bottlenecks in a COBRAk model by minimizing the sum of newly introduced binary variables that indicate bottleneck reactions, i.e. reactions that do not allow the max-min driving force (MDF) to become at least the set min_mdf. This methology was first described in [1]. Keep in mind that results from this function are optimal, but not neccessarily unique!
[1] Bekiaris et al. (2023). Nature Communications, 14(1), 4660. https://doi.org/10.1038/s41467-023-40297-8
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model to analyze for thermodynamic bottlenecks. |
required |
with_enzyme_constraints
|
bool
|
Whether to include enzyme constraints in the analysis. |
False
|
min_mdf
|
float
|
Minimum max-min driving force (MDF) to be enforced. Defaults to STANDARD_MIN_MDF. |
STANDARD_MIN_MDF
|
verbose
|
bool
|
If True, print detailed information about identified bottlenecks. Defaults to False. |
False
|
solver_name
|
str
|
Name of the solver to use for optimization. Defaults to "scip". |
required |
solver_options
|
dict[str, float | int | str]
|
Options for the solver, such as number of threads and LP method. Defaults to an empty dictionary. |
required |
Returns:
Type | Description |
---|---|
tuple[list[str], dict[str, float]]
|
list[str], dict[str, float]: A list of reaction IDs identified as thermodynamic bottlenecks, and the associated solution dict. |
Source code in cobrak/lps.py
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 |
|
perform_lp_variability_analysis(cobrak_model, with_enzyme_constraints=False, with_thermodynamic_constraints=False, active_reactions=[], min_active_flux=0.001, calculate_reacs=True, calculate_concs=True, calculate_rest=True, further_tested_vars=[], min_mdf=STANDARD_MIN_MDF, min_flux_cutoff=1e-05, abs_df_cutoff=1e-05, min_enzyme_cutoff=1e-05, max_active_enzyme_cutoff=0.0001, solver=SCIP, parallel_verbosity_level=0)
Perform linear programming variability analysis on a COBRAk model.
This function conducts a variability analysis on a COBRAk model using linear programming (LP). It evaluates the range of possible flux values for each reaction and all other occuring variables in the model, considering optional enzyme and thermodynamic constraints. The methodology is based on the approach described by [1] and parallelized as outlined in [2].
[1] Mahadevan & Schilling. (2003). Metabolic engineering, 5(4), 264-276. https://doi.org/10.1016/j.ymben.2003.09.002 [2] Gudmundsson & Thiele. BMC Bioinformatics 11, 489 (2010). https://doi.org/10.1186/1471-2105-11-489
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model to analyze. |
required |
with_enzyme_constraints
|
bool
|
Whether to include enzyme constraints in the analysis. |
False
|
with_thermodynamic_constraints
|
bool
|
Whether to include thermodynamic constraints in the analysis. |
False
|
active_reactions
|
list[str]
|
List of reactions to be set as active with a minimum flux. Defaults to an empty list. |
[]
|
min_active_flux
|
float
|
Minimum flux value for active reactions. Defaults to 1e-5. |
0.001
|
calculate_reacs
|
bool
|
If True, analyze reaction fluxes. Default: True. |
True
|
calculate_concs
|
bool
|
If True, analyze concentrations. Default: True. |
True
|
calculate_rest
|
bool
|
If True, analyze all other parameters (e.g. kappa values and driving forces). Default: True. |
True
|
min_mdf
|
float
|
Minimum metabolic driving force (MDF) to be enforced. Defaults to 0.0. |
STANDARD_MIN_MDF
|
min_flux_cutoff
|
float
|
Minimum flux cutoff for considering a reaction active. Defaults to 1e-8. |
1e-05
|
solver
|
Solver
|
MILP solver used for variability analysis. Default is SCIP, recommended is CPLEX_FOR_VARIABILITY_ANALYSIS or GUROBI_FOR_VARIABILITY_ANALYSIS if you have a CPLEX or Gurobi license. |
SCIP
|
parallel_verbosity_level
|
int
|
Sets the verbosity level for the analysis parallelization. The higher, the value, the more is printed. Default: 0. |
0
|
Returns:
Type | Description |
---|---|
dict[str, tuple[float, float]]
|
dict[str, tuple[float, float]]: A dictionary mapping variable IDs to their minimum and maximum values determined by the variability analysis. |
Source code in cobrak/lps.py
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 |
|
model_instantiation
This module contains the most convenient ways to create new Model instances from COBRApy models.
delete_enzymatically_suboptimal_reactions_in_cobrak_model(cobrak_model)
Delete enzymatically suboptimal reactions in a COBRA-k model, similar to the idea in sMOMENT/AutoPACMEN [1].
This function processes each reaction in the provided COBRA-k model to determine if it is enzymatically suboptimal based on Molecular Weight by k_cat (MW/kcat). Suboptimal reactions are identified by comparing their MW/kcat value with that of other reactions sharing the same base identifier, retaining only those with the lowest MW/kcat. The function then removes these suboptimal reactions from the model and cleans up orphaned metabolites.
- The function assumes that the 'enzyme_reaction_data' attribute of each reaction includes identifiers and k_cat information for enzyme-catalyzed reactions. If not, those reactions are skipped.
- Reactions with identical base IDs (but different directional suffixes) are considered as variants of the same reaction.
- After removing suboptimal reactions, the function calls
delete_orphaned_metabolites_and_enzymes
to clean up any orphaned metabolites and enzymes that may have been left behind.
[1] https://doi.org/10.1186/s12859-019-3329-9
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
A COBRA-k model containing biochemical reactions. |
required |
Returns:
Type | Description |
---|---|
Model
|
cobra.Model: The updated COBRA-k model after removing enzymatically suboptimal reactions. |
Source code in cobrak/model_instantiation.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
|
delete_enzymatically_suboptimal_reactions_in_fullsplit_cobrapy_model(cobra_model, enzyme_reaction_data, enzyme_molecular_weights, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX, reac_enz_separator=REAC_ENZ_SEPARATOR, special_enzyme_stoichiometries={})
Removes enzymatically suboptimal reactions from a fullsplit COBRApy model.
This function identifies and deletes reactions in a COBRApy model that are enzymatically suboptimal based on enzyme reaction data and molecular weights. I.e., it retains only the reactions with the minimum molecular weight to k_cat (MW/k_cat) ratio for each base reaction. "base" reaction stands for any originally identical reaction, e.g., if there are somehow now multiple phosphoglucokinase (PGK) reactions due to an enzyme fullsplit, only one of these PGK variants will be retained in the returned model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobra_model
|
Model
|
The COBRA-k model from which suboptimal reactions will be removed. |
required |
enzyme_reaction_data
|
dict[str, EnzymeReactionData | None]
|
A dictionary mapping reaction IDs to
|
required |
enzyme_molecular_weights
|
dict[str, float]
|
A dictionary mapping enzyme identifiers to their molecular weights. |
required |
Returns:
Type | Description |
---|---|
Model
|
cobra.Model: The modified COBRA-k model with suboptimal reactions removed. |
Source code in cobrak/model_instantiation.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
get_cobrak_model_from_sbml_and_thermokinetic_data(sbml_path, extra_linear_constraints, dG0s, dG0_uncertainties, conc_ranges, enzyme_molecular_weights, enzyme_reaction_data, max_prot_pool, kinetic_ignored_metabolites, enzyme_conc_ranges={}, do_model_fullsplit=False, do_delete_enzymatically_suboptimal_reactions=True, R=STANDARD_R, T=STANDARD_T, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX, reac_enz_separator=REAC_ENZ_SEPARATOR, omitted_metabolites=[], keep_parameter_refs=False)
Creates a COBRAk model from an SBML and given further thermokinetic (thermodynamic and enzymatic) data.
This function constructs a Model
by integrating thermokinetic data and additional constraints
into an existing COBRA-k model. It allows for the specification of concentration ranges, enzyme molecular weights, and
reaction data, among other parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sbml_path
|
str
|
The SBML model to be converted. |
required |
extra_linear_constraints
|
list[ExtraLinearConstraint]
|
Additional linear constraints to be applied to the model. |
required |
dG0s
|
dict[str, float]
|
Standard Gibbs free energy changes for reactions. |
required |
dG0_uncertainties
|
dict[str, float]
|
Uncertainties in the standard Gibbs free energy changes. |
required |
conc_ranges
|
dict[str, tuple[float, float]]
|
Concentration ranges for metabolites. |
required |
enzyme_molecular_weights
|
dict[str, float]
|
Molecular weights of enzymes. |
required |
enzyme_reaction_data
|
dict[str, EnzymeReactionData | None]
|
Enzyme reaction data for reactions. |
required |
max_prot_pool
|
float
|
Maximum protein pool constraint. |
required |
kinetic_ignored_metabolites
|
list[str]
|
Metabolites to be ignored in kinetic calculations. |
required |
enzyme_conc_ranges
|
dict[str, tuple[float, float] | None]
|
Concentration ranges for enzymes. Defaults to {}. |
{}
|
do_model_fullsplit
|
bool
|
Whether to perform a full split of the model. Defaults to True. |
False
|
do_delete_enzymatically_suboptimal_reactions
|
bool
|
Whether to delete enzymatically suboptimal reactions. Defaults to True. |
True
|
R
|
float
|
Universal gas constant. Defaults to STANDARD_R. |
STANDARD_R
|
T
|
float
|
Temperature in Kelvin. Defaults to STANDARD_T. |
STANDARD_T
|
Raises:
Type | Description |
---|---|
ValueError
|
If a concentration range for a metabolite is not provided and no default is set. |
Returns:
Name | Type | Description |
---|---|---|
Model |
Model
|
The constructed |
Source code in cobrak/model_instantiation.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
|
get_cobrak_model_with_kinetic_data_from_sbml_model_alone(sbml_path, path_to_external_resources, folder_of_sabio_database, brenda_version, prefer_brenda, base_species, max_prot_pool, conc_ranges, inner_to_outer_compartments, phs, pmgs, ionic_strenghts, potential_differences, kinetic_ignored_enzymes, custom_kms_and_kcats, kinetic_ignored_metabolites, do_model_fullsplit=True, do_delete_enzymatically_suboptimal_reactions=True, ignore_dG0_uncertainty=True, enzyme_conc_ranges={}, dG0_exclusion_prefixes=[], dG0_exclusion_inner_parts=[], dG0_corrections={}, extra_linear_constraints=[], data_cache_folder='', R=STANDARD_R, T=STANDARD_T, keep_parameter_refs=False, enzymes_to_delete=[], max_taxonomy_level=float('inf'))
This functions creates a Model out of an SBML model and automatically collects kinetic and thermodynamic data.
To make this function work, the functions needs in the COBRApy model... ...for the reactions: An EC number annotation [for enzymatic constraints] ...for the metabolites: BiGG IDs ...and all the other non-optional data in its arguments
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sbml_path
|
str
|
The SBML model file path from which the Model and associated data retrieval shall be made |
required |
path_to_external_resources
|
str
|
description |
required |
brenda_version
|
str
|
description |
required |
base_species
|
str
|
description |
required |
max_prot_pool
|
float
|
description |
required |
conc_ranges
|
dict[str, tuple[float, float]]
|
description |
required |
inner_to_outer_compartments
|
list[str]
|
description |
required |
phs
|
dict[str, float]
|
description |
required |
pmgs
|
dict[str, float]
|
description |
required |
ionic_strenghts
|
dict[str, float]
|
description |
required |
potential_differences
|
dict[tuple[str, str], float]
|
description |
required |
kinetic_ignored_enzymes
|
list[str]
|
description |
required |
custom_kms_and_kcats
|
dict[str, EnzymeReactionData | None]
|
description |
required |
kinetic_ignored_metabolites
|
list[str]
|
description |
required |
do_model_fullsplit
|
bool
|
description. Defaults to True. |
True
|
do_delete_enzymatically_suboptimal_reactions
|
bool
|
description. Defaults to True. |
True
|
ignore_dG0_uncertainty
|
bool
|
description. Defaults to True. |
True
|
enzyme_conc_ranges
|
dict[str, tuple[float, float] | None]
|
description. Defaults to {}. |
{}
|
dG0_exclusion_prefixes
|
list[str]
|
description. Defaults to []. |
[]
|
dG0_exclusion_inner_parts
|
list[str]
|
description. Defaults to []. |
[]
|
extra_linear_constraints
|
list[ExtraLinearConstraint]
|
description. Defaults to []. |
[]
|
data_cache_folder
|
str
|
description. Defaults to "". |
''
|
R
|
float
|
description. Defaults to STANDARD_R. |
STANDARD_R
|
T
|
float
|
description. Defaults to STANDARD_T. |
STANDARD_T
|
Returns:
Name | Type | Description |
---|---|---|
Model |
Model
|
description |
Source code in cobrak/model_instantiation.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 |
|
ncbi_taxonomy_functionality
ncbi_taxonomy.py
This module contains functions which can access NCBI TAXONOMY.
get_taxonomy_dict_from_nbci_taxonomy(organisms, parsed_json_data)
Generates a taxonomy dictionary from NCBI taxonomy data.
This function constructs a dictionary mapping each organism to its taxonomy path based on the provided NCBI taxonomy data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
organisms
|
list[str]
|
A list of organism names for which taxonomy paths are to be retrieved. |
required |
parsed_json_data
|
dict[str, Any]
|
Parsed JSON data containing taxonomy information, including: - "number_to_names_dict": A dictionary mapping taxonomy numbers to names. - "names_to_number_dict": A dictionary mapping organism names to taxonomy numbers. - "nodes_dict": A dictionary representing the taxonomy tree structure. |
required |
Returns:
Type | Description |
---|---|
dict[str, list[str]]
|
dict[str, list[str]]: A dictionary where each key is an organism name and the value is a list of taxonomy names |
dict[str, list[str]]
|
representing the path from the organism to the root of the taxonomy tree. |
Source code in cobrak/ncbi_taxonomy_functionality.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
|
get_taxonomy_scores(base_species, taxonomy_dict)
Returns a dictionary with a taxonomic distance from the given organism.
e.g. if base_species is "Escherichia coli" and taxonomy_dict is
{ "Escherichia coli": ["Escherichia", "Bacteria", "Organism"], "Pseudomonas": ["Pseudomonas", "Bacteria", "Organism"], "Homo sapiens": ["Homo", "Mammalia", "Animalia", "Organism"], }
this function would return
{ "Escherichia coli": 0, "Pseudomonas": 1, "Homo sapiens": 4, }
Arguments
- base_species: str ~ The species to which a relation is made.
- taxonomy_dict: dict[str, list[str]] ~ A dictionary with organism names as keys and their taxonomic levels (sorted from nearest to farthest) as string list.
Source code in cobrak/ncbi_taxonomy_functionality.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
|
most_taxonomic_similar(base_species, taxonomy_dict)
Returns a dictionary with a score of taxonomic distance from the given organism.
e.g. if base_species is "Escherichia coli" and taxonomy_dict is
{ "Escherichia coli": ["Escherichia", "Bacteria", "Organism"], "Pseudomonas": ["Pseudomonas", "Bacteria", "Organism"], "Homo sapiens": ["Homo", "Mammalia", "Animalia", "Organism"], }
this function would return
{ "Escherichia coli": 0, "Pseudomonas": 1, "Homo sapiens": 2, }
Arguments
- base_species: str ~ The species to which a relation is made.
- taxonomy_dict: dict[str, list[str]] ~ A dictionary with organism names as keys and their taxonomic levels (sorted from nearest to farthest) as string list.
Source code in cobrak/ncbi_taxonomy_functionality.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
parse_ncbi_taxonomy(ncbi_taxdmp_zipfile_path, ncbi_parsed_json_path)
Parses NCBI taxonomy data from a taxdump zip file and saves it as a JSON file.
This function extracts the necessary files from the NCBI taxdump zip archive, parses the taxonomy data, and writes the parsed data to a JSON file. The parsed data includes mappings from taxonomy numbers to names and vice versa, as well as the taxonomy tree structure.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ncbi_taxdmp_zipfile_path
|
str
|
The file path to the NCBI taxdump zip archive. |
required |
ncbi_parsed_json_path
|
str
|
The file path where the parsed JSON data will be saved. |
required |
Source code in cobrak/ncbi_taxonomy_functionality.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
nlps
This file contains all non-linear programs (NLP) functions, including the evolutionary NLP optimization algorithm, that can be used with COBRAk models. With NLPs, all types of constraints (stoichiomnetric, enzymatic, κ, γ, ι, ...) can be integrated. However, NLPs can be very slow. For linear-programs (LP) and mixed-integer linear programs (MILP), see lps.py in the same folder.
add_loop_constraints_to_nlp(model, cobrak_model)
Adds loop constraints to a non-linear program (NLP) model.
The loop constraints are of the nonlinear form v_fwd * v_rev = 0.0 for any forward/reverse pair of split reversible reactions.
Parameters
* model
(ConcreteModel
): The NLP model to add constraints to.
* cobrak_model
(Model
): The COBRAk model associated with the NLP model.
Returns
* ConcreteModel
: The NLP model with added loop constraints.
Source code in cobrak/nlps.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
get_nlp_from_cobrak_model(cobrak_model, ignored_reacs=[], with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, approximation_value=0.0001, irreversible_mode=False, variability_data={}, strict_mode=False, irreversible_mode_min_mdf=STANDARD_MIN_MDF, with_flux_sum_var=False, correction_config=CorrectionConfig())
Creates a pyomo non-linear program (NLP) model instance from a COBRAk Model.
For more, see COBRAk's NLP documentation chapter.
Parameters
cobrak_model
(Model
): The COBRAk model to create the NLP model from.ignored_reacs
(list[str]
, optional): List of reaction IDs to ignore. Defaults to[]
.with_kappa
(bool
, optional): Whether to include κ saturation term terms. Defaults toTrue
.with_gamma
(bool
, optional): Whether to include γ thermodynamic terms. Defaults toTrue
.with_iota
(bool
, optional): Whether to include ι inhibition terms. Defaults toFalse
and untested!with_alpha
(bool
, optional): Whether to include α activation terms. Defaults toFalse
and untested!approximation_value
(float
, optional): Approximation value for κ, γ, ι, and α terms. Defaults to0.0001
. This value is the minimal value for κ, γ, ι, and α terms, and can lead to an overapproximation in this regard.irreversible_mode
(bool
, optional): Whether to use irreversible mode. Defaults toFalse
.variability_data
(dict[str, tuple[float, float]]
, optional): Variability data for reactions. Defaults to{}
.strict_mode
(bool
, optional): Whether to use strict mode. Defaults toFalse
.irreversible_mode_min_mdf
(float
, optional): Minimum MDF value for irreversible mode. Defaults toSTANDARD_MIN_MDF
.with_flux_sum_var
(bool
, optional): Whether to include a flux sum variable of namecobrak.constants.FLUX_SUM_VAR
. Defaults toFalse
.correction_config
(CorrectionConfig
, optional): Parameter correction configuration. Defaults toCorrectionConfig()
.
Returns
ConcreteModel
: The created NLP model.
Source code in cobrak/nlps.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 |
|
perform_nlp_irreversible_optimization(cobrak_model, objective_target, objective_sense, variability_dict, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, approximation_value=0.0001, verbose=False, strict_mode=False, min_mdf=STANDARD_MIN_MDF, solver=IPOPT, multistart_num_iterations=10, multistart_solver_name='ipopt', min_flux=0.0, with_flux_sum_var=False, correction_config=CorrectionConfig())
Performs an irreversible non-linear program (NLP) optimization on a COBRAk model.
For more about the NLP, see the COBRAk documentation's NLP chapter.
Parameters
cobrak_model
(Model
): The COBRAk model to optimize.objective_target
(str | dict[str, float]
): The objective target (reaction ID or dictionary of reaction IDs and coefficients).objective_sense
(int
): The objective sense (1 for maximization, -1 for minimization).variability_dict
(dict[str, tuple[float, float]]
): Dictionary of reaction IDs and their variability (lower and upper bounds).with_kappa
(bool
, optional): Whether to include κ saturation terms. Defaults toTrue
.with_gamma
(bool
, optional): Whether to include γ thermodynamic terms. Defaults toTrue
.with_iota
(bool
, optional): Whether to include ι inhibition terms. Defaults toFalse
and untested!with_alpha
(bool
, optional): Whether to include α activation terms. Defaults toFalse
and untested!approximation_value
(float
, optional): Approximation value for κ, γ, ι, and α terms. Defaults to0.0001
. This value is the minimal value for κ, γ, ι, and α terms, and can lead to an overapproximation in this regard.verbose
(bool
, optional): Whether to print solver output. Defaults toFalse
.strict_mode
(bool
, optional): Whether to use strict mode. Defaults toFalse
.min_mdf
(float
, optional): Minimum MDF value. Defaults toSTANDARD_MIN_MDF
.solver_name
(Solver, optional): Used NLP solver. Defaults to IPOPT.multistart_num_iterations
(int
, optional): Number of iterations for multistart solver. Defaults to10
.multistart_solver_name
(str
, optional): Solver name for multistart. Defaults to"ipopt"
.min_flux
(float
, optional): Minimum flux value. Defaults to0.0
.with_flux_sum_var
(bool
, optional): Whether to include a reaction flux sum variable of namecobrak.constants.FLUX_SUM_VAR
. Defaults toFalse
.correction_config
(CorrectionConfig
, optional): Parameter correction configuration. Defaults toCorrectionConfig()
.
Returns
dict[str, float]
: The optimization results.
Source code in cobrak/nlps.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
|
perform_nlp_irreversible_optimization_with_active_reacs_only(cobrak_model, objective_target, objective_sense, optimization_dict, variability_dict, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, approximation_value=0.0001, verbose=False, strict_mode=False, min_mdf=STANDARD_MIN_MDF, solver=IPOPT, multistart_num_iterations=10, do_not_delete_with_z_var_one=False, correction_config=CorrectionConfig())
Performs an irreversible non-linear program (NLP) optimization on a COBRAk model, considering only active reactions of the optimization dict.
For more about the NLP, see the COBRAk documentation's NLP chapter.
Parameters
cobrak_model
(Model
): The COBRAk model to optimize.objective_target
(str | dict[str, float]
): The objective target (reaction ID or dictionary of reaction IDs and coefficients).objective_sense
(int
): The objective sense (1 for maximization, -1 for minimization).optimization_dict
(dict[str, float]
): Dictionary of reaction IDs and their optimization values.variability_dict
(dict[str, tuple[float, float]]
): Dictionary of reaction IDs and their variability (lower and upper bounds).with_kappa
(bool
, optional): Whether to include κ terms. Defaults toTrue
.with_gamma
(bool
, optional): Whether to include γ terms. Defaults toTrue
.with_iota
(bool
, optional): Whether to include ι inhibition terms. Defaults toFalse
and untested!with_alpha
(bool
, optional): Whether to include α activation terms. Defaults toFalse
and untested!approximation_value
(float
, optional): Approximation value for κ, γ, ι, and α terms. Defaults to0.0001
. This value is the minimal value for κ, γ, ι, and α terms, and can lead to an overapproximation in this regard.verbose
(bool
, optional): Whether to print solver output. Defaults toFalse
.strict_mode
(bool
, optional): Whether to use strict mode. Defaults toFalse
.min_mdf
(float
, optional): Minimum MDF value. Defaults toSTANDARD_MIN_MDF
.solver
(Solver, optional): Used NLP solver. Defaults to IPOPT.multistart_num_iterations
(int
, optional): Number of iterations for multistart solver. Defaults to10
.do_not_delete_with_z_var_one
(bool
, optional): Whether to delete reactions with associated Z variables (in the optimization dics) equal to one. Defaults toFalse
.correction_config
(CorrectionConfig
, optional): Paramter correction configuration. Defaults toCorrectionConfig()
.
Returns
dict[str, float]
: The optimization results.
Source code in cobrak/nlps.py
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
|
perform_nlp_irreversible_variability_analysis_with_active_reacs_only(cobrak_model, optimization_dict, tfba_variability_dict, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, active_reactions=[], min_active_flux=1e-05, calculate_reacs=True, calculate_concs=True, calculate_rest=True, extra_tested_vars_max=[], extra_tested_vars_min=[], strict_mode=False, min_mdf=STANDARD_MIN_MDF, min_flux_cutoff=1e-08, solver=IPOPT, do_not_delete_with_z_var_one=False, parallel_verbosity_level=0, approximation_value=0.0001)
Performs an irreversible non-linear program (NLP) variability analysis on a COBRAk model, considering only active reactions.
This function calculates the minimum and maximum values of reaction fluxes, metabolite concentrations, and other variables in the model, given a set of active reactions and a variability dictionary. It uses a combination of NLP optimizations and parallel processing to efficiently compute the variability of the model.
Parameters
cobrak_model
(Model
): The COBRAk model to analyze.optimization_dict
(dict[str, float]
): Dictionary of reaction IDs and their optimization values.tfba_variability_dict
(dict[str, tuple[float, float]]
): Dictionary of reaction IDs and their TFBA variability (lower and upper bounds).with_kappa
(bool
, optional): Whether to include κ saturation terms. Defaults toTrue
.with_gamma
(bool
, optional): Whether to include γ thermodynamic terms. Defaults toTrue
.with_iota
(bool
, optional): Whether to include ι inhibition terms. Defaults toFalse
and untested!with_alpha
(bool
, optional): Whether to include α activation terms. Defaults toFalse
and untested!active_reactions
(list[str]
, optional): List of active reaction IDs. Defaults to[]
.min_active_flux
(float
, optional): Minimum flux value for active reactions. Defaults to1e-5
.calculate_reacs
(bool
, optional): Whether to calculate reaction flux variability. Defaults toTrue
.calculate_concs
(bool
, optional): Whether to calculate metabolite concentration variability. Defaults toTrue
.calculate_rest
(bool
, optional): Whether to calculate variability of other variables (e.g., enzyme delivery, κ, γ). Defaults toTrue
.strict_mode
(bool
, optional): Whether to use strict mode. Defaults toFalse
.min_mdf
(float
, optional): Minimum MDF value. Defaults toSTANDARD_MIN_MDF
.min_flux_cutoff
(float
, optional): Minimum flux cutoff value. Defaults to1e-8
.solver
(Solver, optional): Used NLP solver. Defaults to IPOPT.do_not_delete_with_z_var_one
(bool
, optional): Whether to delete reactions with Z variable equal to one. Defaults toFalse
.parallel_verbosity_level
(int
, optional): Verbosity level for parallel processing. Defaults to0
.approximation_value
(float
, optional): Approximation value for κ, γ, ι, and α terms. Defaults to0.0001
. This value is the minimal value for κ, γ, ι, and α terms, and can lead to an overapproximation in this regard.
Returns
dict[str, tuple[float, float]]
: A dictionary of variable IDs and their variability (lower and upper bounds).
Source code in cobrak/nlps.py
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 |
|
perform_nlp_reversible_optimization(cobrak_model, objective_target, objective_sense, variability_dict, with_kappa=True, with_gamma=True, with_iota=False, with_alpha=False, approximation_value=0.0001, strict_mode=False, verbose=False, solver=SCIP, with_flux_sum_var=False, correction_config=CorrectionConfig(), show_variable_count=False)
Performs a reversible MILP-based non-linear program (NLP) optimization on a COBRAk model.
For more on the MINLP, see the COBRAk documentation's NLP chapter.
Parameters
cobrak_model
(Model
): The COBRAk model to optimize.objective_target
(str | dict[str, float]
): The objective target (reaction ID or dictionary of reaction IDs and coefficients).objective_sense
(int
): The objective sense (1 for maximization, -1 for minimization).variability_dict
(dict[str, tuple[float, float]]
): Dictionary of reaction IDs and their variability (lower and upper bounds).with_kappa
(bool
, optional): Whether to include κ saturation terms. Defaults toTrue
.with_gamma
(bool
, optional): Whether to include γ thermodynamic terms. Defaults toTrue
.with_iota
(bool
, optional): Whether to include ι inhibition terms. Defaults toFalse
and untested!with_alpha
(bool
, optional): Whether to include α activation terms. Defaults toFalse
and untested!approximation_value
(float
, optional): Approximation value for κ, γ, ι, and α terms. Defaults to0.0001
. This value is the minimal value for κ, γ, ι, and α terms, and can lead to an overapproximation in this regard.strict_mode
(bool
, optional): Whether to use strict mode. Defaults toFalse
.verbose
(bool
, optional): Whether to print solver output. Defaults toFalse
.solver_name
(str
, optional): Used MINLP solver. Defaults to SCIP,with_flux_sum_var
(bool
, optional): Whether to include a reaction flux sum variable of namecobrak.constants.FLUX_SUM_VAR
. Defaults toFalse
.correction_config
(CorrectionConfig
, optional): Parameter correction configuration. Defaults toCorrectionConfig()
.
Returns
dict[str, float]
: The optimization results.
Source code in cobrak/nlps.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
plotting
Functions for plotting different types of data or reaction kinetics, all using matplotlib.
dual_axis_plot(xpoints, leftaxis_ypoints_list, rightaxis_ypoints_list, xaxis_caption='', leftaxis_caption='', rightaxis_caption='', leftaxis_colors=[], rightaxis_colors=[], leftaxis_titles=[], rightaxis_titles=[], extrapoints=[], has_legend=True, legend_direction='', legend_position=(), is_leftaxis_logarithmic=False, is_rightaxis_logarithmic=False, point_style='', line_style='-', max_digits_after_comma=4, savepath='', left_ylim=None, right_ylim=None, xlim=None, left_axis_in_front=True, left_legend_position=[], right_legend_position=[], figure_size_inches=None, special_figure_mode=False)
Creates a plot with a dual Y-axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
xpoints
|
list[float]
|
X-axis data points. |
required |
leftaxis_ypoints_list
|
list[list[float]]
|
List of Y-axis data points for the left axis. |
required |
rightaxis_ypoints_list
|
list[list[float]]
|
List of Y-axis data points for the right axis. |
required |
xaxis_caption
|
str
|
X-axis caption. Defaults to "". |
''
|
leftaxis_caption
|
str
|
Left Y-axis caption. Defaults to "". |
''
|
rightaxis_caption
|
str
|
Right Y-axis caption. Defaults to "". |
''
|
leftaxis_colors
|
list[str]
|
Colors for left axis lines. Defaults to []. |
[]
|
rightaxis_colors
|
list[str]
|
Colors for right axis lines. Defaults to []. |
[]
|
leftaxis_titles
|
list[str]
|
Legend titles for left axis lines. Defaults to []. |
[]
|
rightaxis_titles
|
list[str]
|
Legend titles for right axis lines. Defaults to []. |
[]
|
extrapoints
|
list[tuple[float, float, bool, str, str, str, float]]
|
List of single points, described by tuples with the content [x, y, is_left_axis, color, marker, label, yerr]. If yerr=0, no error bar is drawn at all. Defaults to []. |
[]
|
has_legend
|
bool
|
Whether to show the legend. Defaults to True. |
True
|
legend_direction
|
str
|
Legend direction. Defaults to "". |
''
|
legend_position
|
tuple[float, float]
|
Legend position. Defaults to (). |
()
|
is_leftaxis_logarithmic
|
bool
|
Whether to use a logarithmic scale for the left axis. Defaults to False. |
False
|
is_rightaxis_logarithmic
|
bool
|
Whether to use a logarithmic scale for the right axis. Defaults to False. |
False
|
point_style
|
str
|
Style for points. Defaults to "". |
''
|
line_style
|
str
|
Style for lines. Defaults to "-". |
'-'
|
max_digits_after_comma
|
int
|
Max digits after comma shown. Defaults to 4. |
4
|
savepath
|
str
|
If given, the plot is not shown but saved at the given path. Defaults to "" |
''
|
Returns:
Type | Description |
---|---|
None
|
None (displays the plot) |
Source code in cobrak/plotting.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
|
plot_combinations(func, min_values, max_values, num_subplots_per_window=18, num_subplots_per_row=6)
Plot all unique combinations of 2 variable arguments and constant values for the other arguments.
The plot is a scatter plot with different colors for each category in the hue column. The x-axis represents the x-data, the y-axis represents the y-data, and the hue axis represents the category.
The plot has the following features:
- A title at the top of the plot with the specified title.
- Labels for the x-axis and y-axis with the specified labels.
- A legend on the right side of the plot with the specified hue label.
- Different colors for each category in the hue column, specified by the palette.
- A scatter plot with points representing the data.
Example usage:
min_values = [-1.0, 0.0, 0.0] max_values = [10.0, 5.0, 10.0] def example_func(args: List[float]) -> float: return args[0] + args[1] + args[2]
plot_combinations(example_func, min_values, max_values)
Args: - func: The function to be plotted. It takes a list of floats and returns a float. - min_values: A list of minimum possible values for each argument. - max_values: A list of maximum possible values for each argument. - num_subplots_per_window: The maximum number of subplots per window. Defaults to 18. - num_subplots_per_row: The maximum number of subplots per row in a window. Defaults to 6.
Returns: - None
Source code in cobrak/plotting.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
plot_objvalue_evolution(json_path, output_path, ylabel='Objective value', objvalue_multiplicator=-1.0, with_legend=False, algorithm='genetic', precision=4)
Plots the evolution of the objective value over computational time.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_path
|
str
|
Path to the JSON file containing the data. |
required |
output_path
|
str
|
Path to save the plot. |
required |
ylabel
|
str
|
Label for the Y-axis. Defaults to "Objective value". |
'Objective value'
|
objvalue_multiplicator
|
float
|
Multiplier to apply to the objective value. Defaults to -1.0. |
-1.0
|
with_legend
|
bool
|
Whether to display the legend. Defaults to False. |
False
|
algorithm
|
Literal['pso', 'genetic']
|
The optimization algorithm used. Defaults to "genetic". |
'genetic'
|
precision
|
int
|
The number of decimal places to display on the Y-axis. Defaults to 4. |
4
|
Returns:
Type | Description |
---|---|
None
|
None. Saves the plot to the specified output path. |
Source code in cobrak/plotting.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
|
plot_variabilities(variabilities, variability_names, variability_titles, colors, xlabel='', ylabel='', yscale='log', plot_mean=True, save_path=None)
Plots the mean values and whisker bars for multiple variabilities.
This function generates a plot where each variability is represented by a series of points (triangles) and whisker bars. Each point (if plot_mean==True) represents the mean value of a data point in the variability, and the whisker bars represent the lower and upper bounds. The variabilities are grouped together for each data point, with a space between each group to clearly distinguish them.
Parameters:
variabilities : List[List[Tuple[float, float, float]]] A list of lists, where each inner list represents a variability. Each tuple in the inner list contains (lower_bound, upper_bound, mean_value) for each data point in the variability.
variability_names : List[str] A list of strings representing the names of the variabilities.
colors : List[str] A list of strings representing the colors for each variability, e.g. using names from https://matplotlib.org/stable/gallery/color/named_colors.html
plot_mean : bool, optional If True, the mean value is plotted as a triangle. If False, only the whisker bars are plotted. Default is True.
save_path : str, optional The file path where the plot should be saved. If None, the plot is displayed. Default is None.
Returns:
None The function either displays the plot or saves it to the specified path.
Example:
in_vivo = [(1.0, 3.0, 2.0), (2.0, 4.0, 3.0), (3.0, 5.0, 4.0)] in_silico = [(1.5, 3.5, 2.5), (2.5, 4.5, 3.5), (3.5, 5.5, 4.5)] another_variability = [(1.2, 3.2, 2.2), (2.2, 4.2, 3.2), (3.2, 5.2, 4.2)] variabilities = [in_vivo, in_silico, another_variability] variability_names = ['in_vivo', 'in_silico', 'another_variability'] colors = ['blue', 'orange', 'green'] plot_variabilities(variabilities, variability_names, colors) plot_variabilities(variabilities, variability_names, colors, plot_mean=False) plot_variabilities(variabilities, variability_names, colors, save_path='plot.png')
Source code in cobrak/plotting.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 |
|
scatterplot_with_labels(x_data, y_data, labels, x_label=None, y_label=None, y_log=True, x_log=True, add_labels=False, identical_axis_lims=True, xlim_overwrite=None, ylim_overwrite=None, ax=None, save_path=None, title=None, extratext=None, x_labelsize=13, y_labelsize=13)
Generates a scatter plot with error bars and optional point labels.
Can be used standalone ("one-off" plot with plt.show()), or for subplotting by passing an Axes object. Optionally saves the figure if save_path is provided.
Parameters
x_data : list[tuple[float, float, float]]
Each tuple is (lower bound, upper bound, drawn value) for x.
y_data : list[tuple[float, float, float]]
Each tuple is (lower bound, upper bound, drawn value) for y.
labels : list[str]
Labels for each point (used if add_labels is True).
x_label : str, optional
X-axis label.
y_label : str, optional
Y-axis label.
y_log : bool, default True
Use log scale for y-axis.
x_log : bool, default True
Use log scale for x-axis.
add_labels : bool, default False
Annotate points with corresponding label.
identical_axis_lims : bool, default True
Make x and y axis limits identical and auto-scale them.
ax : matplotlib.axes.Axes, optional
If provided, plot is drawn on this Axes (for subplotting).
save_path : str, optional
If provided and ax
is None (standalone plotting), save the figure at this path instead of showing.
Returns
ax : matplotlib.axes.Axes The axis object containing the plot.
Source code in cobrak/plotting.py
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 |
|
printing
Pretty-print summaries of optimization and variability results as well as COBRAk Model instances.
For results, its methods generate rich
tables that display flux values and variability information for each category.
For models, its methods generate rich
tables that display the model's structure and parameters.
print_dict(dictionary, indent=4)
Pretty-print a dictionary in a JSON formatted string with the specified indentation.
Args: dictionary (dict[Any, Any]): The dictionary to print. indent (int, optional): The number of spaces for indentation. Defaults to 4.
Source code in cobrak/printing.py
238 239 240 241 242 243 244 245 |
|
print_model(cobrak_model, print_reacs=True, print_enzymes=True, print_mets=True, print_extra_linear_constraints=True, print_settings=True, conc_rounding=6)
Pretty-print a detailed summary of the model, including reactions, enzymes, metabolites, and settings.
Args: cobrak_model (Model): The model to print. print_reacs (bool, optional): Whether to print reactions. Defaults to True. print_enzymes (bool, optional): Whether to print enzymes. Defaults to True. print_mets (bool, optional): Whether to print metabolites. Defaults to True. print_extra_linear_constraints (bool, optional): Whether to print extra linear constraints. Defaults to True. print_settings (bool, optional): Whether to print general settings. Defaults to True. conc_rounding (int, optional): Number of decimal places to round concentrations to. Defaults to 6.
Source code in cobrak/printing.py
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
|
print_optimization_result(cobrak_model, optimization_dict, print_exchanges=True, print_reactions=True, print_enzymes=True, print_mets=True, print_error_values_if_existing=True, add_stoichiometries=False, rounding=3, conc_rounding=6, ignore_unused=False, multiple_tables_per_line=True, unused_limit=0.0001)
Pretty-Print the results of an optimization, including exchanges, reactions, enzymes, and metabolites.
Args: cobrak_model (Model): The model used for optimization. optimization_dict (dict[str, float]): A dictionary containing the optimization results. print_exchanges (bool, optional): Whether to print exchange reactions. Defaults to True. print_reactions (bool, optional): Whether to print non-exchange reactions. Defaults to True. print_enzymes (bool, optional): Whether to print enzyme usage. Defaults to True. print_mets (bool, optional): Whether to print metabolite concentrations. Defaults to True. add_stoichiometries (bool, optional): Whether to include reaction stoichiometries. Defaults to False. rounding (int, optional): Number of decimal places to round to. Defaults to 3. conc_rounding (int, optional): Number of decimal places to round concentrations to. Defaults to 6. ignore_unused (bool, optional): Whether to ignore reactions with zero flux. Defaults to False. multiple_tables_per_line (bool, optional): Whether to display multiple tables side by side. Defaults to True.
Source code in cobrak/printing.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
|
print_strkey_dict_as_table(dictionary, table_title='', key_title='', value_title='')
Print a dictionary as a formatted table.
Args: dictionary (dict[str, Any]): The dictionary to print. table_title (str, optional): The title of the table. Defaults to "". key_title (str, optional): The title for the key column. Defaults to "". value_title (str, optional): The title for the value column. Defaults to "".
Source code in cobrak/printing.py
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 |
|
print_variability_result(cobrak_model, variability_dict, print_exchanges=True, print_reacs=True, print_enzymes=False, print_mets=True, ignore_unused=False, add_stoichiometries=False, rounding=3, multiple_tables_per_line=True)
Print the variability analysis results, including exchanges, reactions, enzymes, and metabolites.
Args: cobrak_model (Model): The model used for variability analysis. variability_dict (dict[str, tuple[float, float]]): A dictionary containing the variability results. print_exchanges (bool, optional): Whether to print exchange reactions. Defaults to True. print_reacs (bool, optional): Whether to print non-exchange reactions. Defaults to True. print_enzymes (bool, optional): Whether to print enzyme usage. Defaults to False. print_mets (bool, optional): Whether to print metabolite concentrations. Defaults to True. ignore_unused (bool, optional): Whether to ignore reactions with zero flux. Defaults to False. add_stoichiometries (bool, optional): Whether to include reaction stoichiometries. Defaults to False. rounding (int, optional): Number of decimal places to round to. Defaults to 3. multiple_tables_per_line (bool, optional): Whether to display multiple tables side by side. Defaults to True.
Source code in cobrak/printing.py
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 |
|
pyomo_functionality
Utilities to work with pyomo ConcreteModel instances directly.
ApproximationPoint
Represents a point in a linear approximation.
This dataclass is used to store the slope, intercept, and x-coordinate of a point in a linear approximation.
Attributes: - slope (float): The slope of the line passing through this point. - intercept (float): The y-intercept of the line passing through this point. - x_point (float): The x-coordinate of this point.
Source code in cobrak/pyomo_functionality.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
add_linear_approximation_to_pyomo_model(model, y_function, y_function_derivative, x_reference_var_id, new_y_var_name, min_x, max_x, max_rel_difference, max_num_segments=float('inf'), min_abs_error=1e-06)
Add a linear approximation of a given function to a Pyomo model.
This function approximates the provided function y_function
with a piecewise linear function
and adds the approximation to the given Pyomo model. The approximation is based on the derivative
of the function y_function_derivative
. The approximation is added as a new variable and a set
of constraints to the model.
Parameters: - model (ConcreteModel): The Pyomo model to which the approximation will be added. - y_function (Callable[[float], float]): The function to be approximated. - y_function_derivative (Callable[[float], float]): The derivative of the function to be approximated. - x_reference_var_id (str): The name of the variable in the model that will be used as the independent variable for the approximation. - new_y_var_name (str): The name of the new variable that will be added to the model to represent the approximation. - min_x (float): The minimum value of the independent variable for the approximation. - max_x (float): The maximum value of the independent variable for the approximation. - max_rel_difference (float): The maximum allowed relative difference between the approximation and the original function. - max_num_segments (int, optional): The maximum number of segments to use for the piecewise linear approximation. Defaults to infinity. - min_abs_error (float, optional): The minimum absolute error allowed between the approximation and the original function. Defaults to 1e-6.
Returns: - ConcreteModel: The Pyomo model with the added approximation.
Source code in cobrak/pyomo_functionality.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
|
add_objective_to_model(model, objective_target, objective_sense, objective_name, objective_var_name=OBJECTIVE_VAR_NAME)
Add an objective function to a Pyomo model.
This function adds an objective function to the given Pyomo model based on the provided target and sense. The target can be a single variable name or a dictionary of variable names with their corresponding multipliers. The sense can be either maximization (as int, value > 0) or minimization (as int, value < 0).
Parameters: - model (ConcreteModel): The Pyomo model to which the objective function will be added. - objective_target (str | dict[str, float]): The target for the objective function. It can be a single variable name or a dictionary of variable names with their corresponding multipliers. - objective_sense (int): The sense of the objective function. It can be an integer (positive for maximization, negative for minimization, zero for no objective). - objective_name (str): The name of the new objective function that will be added to the model. - objective_var_name (str, optional): The name of the new variable that will be added to the model to represent the objective function. Defaults to OBJECTIVE_VAR_NAME.
Returns: - ConcreteModel: The Pyomo model with the added objective function.
Source code in cobrak/pyomo_functionality.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
|
get_model_var_names(model)
Extracts and returns a list of names of all variable components from a Pyomo model.
This function iterates over all variable objects (Var
) defined in the given Pyomo concrete model instance.
It collects the name attribute of each variable object and returns these names as a list of strings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ConcreteModel
|
A Pyomo concrete model instance containing various components, including variables. |
required |
Returns:
Type | Description |
---|---|
list[str]
|
list[str]: A list of string names representing all variable objects in the provided Pyomo model. |
Examples:
>>> from pyomo.environ import ConcreteModel, Var
>>> m = ConcreteModel()
>>> m.x = Var(initialize=1.0)
>>> m.y = Var([1, 2], initialize=lambda m,i: i) # Creates two variables y[1] and y[2]
>>> var_names = get_model_var_names(m)
>>> print(var_names)
['x', 'y[1]', 'y[2]']
Source code in cobrak/pyomo_functionality.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
|
get_objective(model, objective_target, objective_sense, objective_var_name=OBJECTIVE_VAR_NAME)
Create and return a pyomo objective function for the given model.
Sets up an objective function based on the provided target and sense. The target can be a single variable or a weighted sum of multiple variables. The sense can be either maximization (as int, value > 0) or minimization (as int, value < 0).
Parameters: - model (ConcreteModel): The Pyomo model to which the objective function will be added. - objective_target (str | dict[str, float]): The target for the objective function. It can be a single variable name or a dictionary of variable names with their corresponding multipliers. - objective_sense (int): The sense of the objective function. It can be an integer (positive for maximization, negative for minimization, zero for no objective).
Returns: - Objective: The Pyomo Objective object representing the objective function.
Source code in cobrak/pyomo_functionality.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
get_solver(solver_name, solver_options, solver_attrs)
Create and configure a solver for the given solver name and options.
This function returns a Pyomo solver using the specified solver name and applies the provided options to it.
Parameters: - solver_name (str): The name of the solver to be used (e.g., 'glpk', 'cbc'). - solver_options (dict[str, float | int | str]): A dictionary of solver options where keys are option names and values are the corresponding option values. - solver_attrs (dict[str, float | int | str]): A dictionary of solver attributes where keys are attribute names and values are the corresponding attribute values.
Returns: - SolverFactoryClass: The configured solver instance.
Source code in cobrak/pyomo_functionality.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
|
set_target_as_var_and_value(model, target, var_name, constraint_name)
Set a target as a variable and its value in a Pyomo model.
This function adds a new variable to the given Pyomo model and sets its value to the provided target. The target can be either a single variable name or a dictionary of variable names with their corresponding multipliers.
Parameters: - model (ConcreteModel): The Pyomo model to which the variable and constraint will be added. - target (str | dict[str, float]): The target for the new variable. It can be a single variable name or a dictionary of variable names with their corresponding multipliers. - var_name (str): The name of the new variable that will be added to the model. - constraint_name (str): The name of the new constraint that will be added to the model to set the value of the new variable.
Returns: - tuple[ConcreteModel, Expression]: The Pyomo model with the added variable and constraint, and the expression representing the target.
Source code in cobrak/pyomo_functionality.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
|
sabio_rk_functionality
Functions and associated dataclasses for retrieving kinetic data from SABIO-RK
SabioDict
dataclass
Includes all retrieved SabioEntry instances and shows of which type they are
Source code in cobrak/sabio_rk_functionality.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
hill_entires
instance-attribute
Hill number entries
ka_entires
instance-attribute
Activation constant entries
kcat_entries
instance-attribute
Turnover number entries
ki_entires
instance-attribute
Inhibition constant entries
km_entries
instance-attribute
Michaelis-Menten constant entries
SabioEntry
dataclass
Represents the COBRAk-relevant data retrieved from a single SABIO-RK entry.
Of which type this entry is (k_cat, k_m, k_i) is not determined here. This is done in the dataclass SabioDict.
Source code in cobrak/sabio_rk_functionality.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
chebi_ids
instance-attribute
The list of all CHEBI IDs
entry_id
instance-attribute
The entry's ID number
is_recombinant
instance-attribute
Whether or not the entry is from a recombinant enzyme
kinetics_mechanism_type
instance-attribute
The reaction's kinetic mechanism (e.g., "Michaelis-Menten")
organism
instance-attribute
The organism (latin-greek name) associated with this entry
parameter_associated_species
instance-attribute
The species (metabolite) associated with the parameter
parameter_unit
instance-attribute
The unit of the value
parameter_value
instance-attribute
The value of the parameter
ph
instance-attribute
[None if not given] The measurement's pH
products
instance-attribute
The list of product names
substrates
instance-attribute
The list of substrate names
temperature
instance-attribute
[None if not given] The measurement's temperature in °C
SabioThread
Bases: Thread
Represents a single Sabio-RK connection, ready for multi-threading (on one CPU core) using the threading module
Source code in cobrak/sabio_rk_functionality.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
__init__(temp_folder, start_number, end_number)
Initializes a SabioThread instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
temp_folder
|
str
|
The path to the temporary folder where the results will be saved. |
required |
start_number
|
int
|
The starting number for the query range. |
required |
end_number
|
int
|
The ending number for the query range. |
required |
Source code in cobrak/sabio_rk_functionality.py
89 90 91 92 93 94 95 96 97 98 99 100 101 |
|
run()
Executes the thread's SABIO-RK data request
Constructs a query string, sends a POST request to the SABIO-RK web service, and writes the response to a file in the temporary folder.
Source code in cobrak/sabio_rk_functionality.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
get_full_sabio_dict(sabio_target_folder)
Parses a SABIO-RK web query TSV file from the target folder to create a SabioDict instance containing SABIO-RK entries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sabio_target_folder
|
str
|
The path to the folder containing the TSV file. |
required |
Returns:
Name | Type | Description |
---|---|---|
SabioDict |
SabioDict
|
A SabioDict instance whichm in turn, contains SabioEntry instances |
Source code in cobrak/sabio_rk_functionality.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
|
sabio_select_enzyme_kinetic_data_for_model(cobra_model, sabio_target_folder, base_species, ncbi_parsed_json_path, bigg_metabolites_json_path, kinetic_ignored_metabolites=[], kinetic_ignored_enzyme_ids=[], custom_enzyme_kinetic_data={}, min_ph=-float('inf'), max_ph=float('inf'), accept_nan_ph=True, min_temperature=-float('inf'), max_temperature=float('inf'), accept_nan_temperature=True, kcat_overwrite={}, transfered_ec_number_json='', max_taxonomy_level=float('inf'))
Selects enzyme kinetic data for a given COBRA-k model using SABIO-RK data.
If this data cannot be found, an internet connection is built to SABIO-RK and the relevant data is downloaded, which may take some time in the order of dozens of minutes. If you want to download the full SABIO-RK data beforehand, run get_full_sabio_dict() from this module beforehand, with the same sabio_target_folder.
Collected data includes k_cat, k_m, k_i, k_a and Hill coefficients for all EC numbers that occur in the model's BiGG-compliant EC number annotation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobra_model
|
Model
|
The COBRA-k model for which enzyme kinetic data is to be selected. |
required |
sabio_target_folder
|
str
|
The path to the folder containing SABIO-RK data. |
required |
base_species
|
str
|
The base species for taxonomy comparison. |
required |
ncbi_parsed_json_path
|
str
|
The path to the NCBI parsed JSON file. |
required |
bigg_metabolites_json_path
|
str
|
The path to the BIGG metabolites JSON file. |
required |
kinetic_ignored_metabolites
|
list[str]
|
List of metabolites to ignore. Defaults to []. |
[]
|
kinetic_ignored_enzyme_ids
|
list[str]
|
List of enzyme IDs to ignore. Defaults to []. |
[]
|
custom_enzyme_kinetic_data
|
dict[str, EnzymeReactionData | None]
|
Custom enzyme kinetic data. Defaults to {}. |
{}
|
min_ph
|
float
|
Minimum pH value for filtering. Defaults to -float("inf"). |
-float('inf')
|
max_ph
|
float
|
Maximum pH value for filtering. Defaults to float("inf"). |
float('inf')
|
accept_nan_ph
|
bool
|
Whether to accept entries with NaN pH values. Defaults to True. |
True
|
min_temperature
|
float
|
Minimum temperature value for filtering. Defaults to -float("inf"). |
-float('inf')
|
max_temperature
|
float
|
Maximum temperature value for filtering. Defaults to float("inf"). |
float('inf')
|
accept_nan_temperature
|
bool
|
Whether to accept entries with NaN temperature values. Defaults to True. |
True
|
kcat_overwrite
|
dict[str, float]
|
Dictionary to overwrite kcat values. Defaults to {}. |
{}
|
Returns:
Type | Description |
---|---|
dict[str, EnzymeReactionData | None]
|
dict[str, EnzymeReactionData | None]: A dictionary mapping reaction IDs to enzyme kinetic data. |
Example
cobra_model = cobra.io.read_sbml_model("model.xml") sabio_target_folder = "/path/to/sabio/data" base_species = "Escherichia coli" ncbi_parsed_json_path = "/path/to/ncbi.json" bigg_metabolites_json_path = "/path/to/bigg_metabolites.json" enzyme_kinetic_data = sabio_select_enzyme_kinetic_data_for_model( cobra_model, sabio_target_folder, base_species, ncbi_parsed_json_path, bigg_metabolites_json_path ) print(enzyme_kinetic_data)
Source code in cobrak/sabio_rk_functionality.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 |
|
spreadsheet_functionality
Functions for generating spreadsheet overviews of variability/optimization results
ABS_EPSILON = 1e-12
module-attribute
Lower absolute values are shown as 0 in the spreadsheet
EMPTY_CELL = SpreadsheetCell(None)
module-attribute
Represents an empty spreadsheeet cell without content
FONT_BOLD = Font(name='Calibri', bold=True)
module-attribute
Bold font for spreadsheet cells
FONT_BOLD_AND_UNDERLINED = Font(name='Calibri', bold=True, underline='single')
module-attribute
Bold and underlined font for spreadsheet cells
FONT_DEFAULT = Font(name='Calibri')
module-attribute
Default font for spreadsheet cells
WIDTH_DEFAULT = 12
module-attribute
Default spreadsheel column width
OptimizationDataset
dataclass
Represents an optimization result and which of its data shall be shown in the spreadsheet
Source code in cobrak/spreadsheet_functionality.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
data
instance-attribute
The optimization result
with_df = False
class-attribute
instance-attribute
Shall driving forces be shown in the spreadsheet?
with_error_corrections = False
class-attribute
instance-attribute
Shall error corrections be shown as their own sheet?
with_gamma = False
class-attribute
instance-attribute
Shall gamma values be shown in the spreadsheet?
with_iota = False
class-attribute
instance-attribute
Shall iota values (inhibition terms) be shown in the spreadsheet?
with_kappa = False
class-attribute
instance-attribute
Shall saturation term values be shown in the spreadsheet?
with_kinetic_differences = False
class-attribute
instance-attribute
Shall differences between NLP fluxes and 'real' fluxes from kinetics be shown in the spreadsheet?
with_vplus = False
class-attribute
instance-attribute
Shall V+ values be shown in the spreadsheet?
SpreadsheetCell
dataclass
Represents the content of a spreadsheet cell.
Includes the shown value, background color, font style and border setting.
Source code in cobrak/spreadsheet_functionality.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
bg_color = field(default=BG_COLOR_DEFAULT)
class-attribute
instance-attribute
The cell's background color (default: BG_COLOR_DEFAULT)
border = field(default=None)
class-attribute
instance-attribute
The cell's border style (None if no style given; default: None)
font = field(default=FONT_DEFAULT)
class-attribute
instance-attribute
The cell's font style (default: FONT_DEFAULT)
value
instance-attribute
The cell's shown content value (if None, nothing is shown)
Title
dataclass
Represents a title or metatitle used in visualizations.
Source code in cobrak/spreadsheet_functionality.py
136 137 138 139 140 141 142 143 144 145 |
|
is_metatitle = field(default=False)
class-attribute
instance-attribute
If True, the title is shown under a the major title line in a second line. Defaults to False.
text
instance-attribute
Title text content
width
instance-attribute
With of column
VariabilityDataset
dataclass
Represents a dataset with variability for plotting, including error bars or ranges.
Source code in cobrak/spreadsheet_functionality.py
148 149 150 151 152 153 154 155 |
|
data
instance-attribute
The variability data dict, as returned by COBRAk's variability functions
with_df = False
class-attribute
instance-attribute
Shall driving force variabilities be shown?
create_cobrak_spreadsheet(path, cobrak_model, variability_datasets, optimization_datasets, is_maximization=True, sheet_description=[], min_var_value=1e-06, min_rel_correction=0.01, kinetic_difference_precision=6, objective_overwrite=None, extra_optstatistics_data={})
Generates a comprehensive Excel spreadsheet summarizing variability and optimization results for a COBRAk model.
This function creates an Excel file that organizes and visualizes various aspects of the model's reactions, metabolites, enzymes, and optimization results. It includes multiple sheets, each focusing on different components of the model and their corresponding data.
In particular, the generated Excel workbook includes the following sheets:
- Index: Provides an overview of the different sections in the spreadsheet.
- A) Optimization statistics: Displays statistical summaries of the optimization results, including objective values, solver status, and flux comparisons.
- B) Model settings: Lists the model's parameters such as protein pool, gas constant, temperature, and annotations.
- C) Reactions: Details each reaction's properties, including reaction strings, ΔG'° values, enzyme associations, and kinetic parameters.
- D) Metabolites: Shows metabolite concentrations, their ranges, and annotations.
- E) Enzymes: Lists individual enzymes with their molecular weights and concentration ranges.
- F) Complexes: Provides information on enzyme complexes, including associated reactions and molecular weights.
- G) Corrections (optional): If error corrections are included in the optimization datasets, this sheet displays the corrections applied.
Each sheet is populated with data from the provided variability and optimization datasets, formatted for readability with appropriate styling, including background colors and borders to highlight important information.
The function also handles various edge cases, such as missing data and low-flux reactions, ensuring that the spreadsheet remains organized and informative.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The file path where the Excel workbook will be saved. |
required |
cobrak_model
|
Model
|
The COBRAk model containing reactions, metabolites, and enzymes. |
required |
variability_datasets
|
dict[str, VariabilityDataset]
|
A dictionary of variability datasets, where each key is a dataset name and the value contains the data and flags for what to display. |
required |
optimization_datasets
|
dict[str, OptimizationDataset]
|
A dictionary of optimization results, where each key is a dataset name and the value contains the optimization data and flags for what to display. |
required |
is_maximization
|
bool
|
Indicates whether the optimization is a maximization problem. Defaults to True. |
True
|
sheet_description
|
list[str]
|
A list of description lines to include in the index sheet. Defaults to an empty list. |
[]
|
min_var_value
|
float
|
Where applicable (e.g. for fluxes), the minimum value to display a variable's value. Does not apply for error correction value (see next argument for that. Defaults to 1e-6. |
1e-06
|
min_rel_correction
|
float
|
Minimal relative change to associated original value for which an error correction value is shown. |
0.01
|
kinetic_difference_precision
|
int
|
The number of decimal places to round kinetic differences. Defaults to 6. |
6
|
Returns:
Name | Type | Description |
---|---|---|
None |
None
|
The function does not return any value but saves the Excel workbook to the specified path. |
Source code in cobrak/spreadsheet_functionality.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 |
|
standard_solvers
Includes definitions of some (MI)LP and NLP solvers.
Instead of these pre-definitions, you can also use pyomo's solver definitions.
tellurium_functionality
Functions for exporting COBRA-k model and solution to a kinetic model.
uniprot_functionality
get_protein_mass_mapping.py
Functions for the generation of a model's mapping of its proteins and their masses.
uniprot_get_enzyme_molecular_weights(model, cache_basepath, multiplication_factor=1 / 1000)
Returns a JSON with a mapping of protein IDs as keys, and as values the protein mass in kDa.
The protein masses are taken from UniProt (retrieved using UniProt's REST API).
Arguments
- model: cobra.Model ~ The model in the cobrapy format
Output
A JSON file with the path project_folder+project_name+'_protein_id_mass_mapping.json' and the following structure:
{ "$PROTEIN_ID": $PROTEIN_MASS_IN_KDA, (...), }
Source code in cobrak/uniprot_functionality.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
|
utilities
General utility functions for COBRAk dataclasses and more.
This module does not include I/O functions which are found in COBRAk's "io" module.
add_objective_value_as_extra_linear_constraint(cobrak_model, objective_value, objective_target, objective_sense)
Adds a linear constraint to a COBRA-k model that enforces the objective value.
This function creates an extra linear constraint that limits the objective value to be within a small range around the original objective value. This can be useful for enforcing constraints during model manipulation or optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object to be modified. |
required |
objective_value
|
float
|
The original objective value. |
required |
objective_target
|
str | dict[str, float]
|
A string representing the objective variable or a dictionary mapping variables to their coefficients in the objective function. |
required |
objective_sense
|
int
|
The sense of the objective function (1 for maximization, -1 for minimization). |
required |
Returns:
Type | Description |
---|---|
Model
|
The modified COBRA-k Model object with the extra linear constraint added. |
Source code in cobrak/utilities.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
|
add_statuses_to_optimziation_dict(optimization_dict, pyomo_results)
Adds solver statuses to the optimization dict.
This includes: * SOLVER_STATUS_KEY's value, which is 0 for ok, 1 for warning and higher values for problems. * TERMINATION_CONDITION_KEY's value, which is 0.1 for globally optimal, 0.2 for optimal, 0.3 for locally optimal and >=1 for any result with problems. * ALL_OK_KEY's value, which is True if SOLVER_STATUS_KEY's value < 0 and TERMINATION_CONDITION_KEY's value < 1.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
optimization_dict
|
dict[str, float]
|
The optimization dict |
required |
pyomo_results
|
SolverResults
|
The pyomo results object |
required |
Raises:
Type | Description |
---|---|
ValueError
|
Unknown pyomo_results.solver.status or termination_condition |
Returns:
Type | Description |
---|---|
dict[str, float]
|
dict[str, float]: The pyomo results dict with the added statuses. |
Source code in cobrak/utilities.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
|
apply_error_correction_on_model(cobrak_model, correction_result, min_abs_error_value=0.01, min_rel_error_value=0.01, verbose=False)
Applies error corrections to a COBRAl model based on a correction result dictionary.
This function iterates through the correction_result
dictionary and applies corrections
to reaction k_cat values, Michaelis-Menten constants (k_M), and Gibbs free energy changes (ΔᵣG'°).
The corrections are applied only if the (for all parameters except ΔᵣG'°) relative or (for ΔᵣG'°) absolute
error exceeds specified thresholds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAl model to be corrected. |
required |
correction_result
|
dict[str, float]
|
A dictionary containing error correction values. Keys are expected to contain information about the reaction, metabolite or other variable value being corrected. |
required |
min_abs_error_value
|
float
|
The minimum absolute error value for applying corrections. |
0.01
|
min_rel_error_value
|
float
|
The minimum relative error value for applying corrections. |
0.01
|
verbose
|
bool
|
If True, prints details of the corrections being applied. |
False
|
Returns:
Type | Description |
---|---|
Model
|
A deep copy of the COBRAk model with the error corrections applied. |
Source code in cobrak/utilities.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
|
apply_variability_dict(model, cobrak_model, variability_dict, error_scenario={}, abs_epsilon=1e-05)
Applies the variability data as new variable bounds in the pyomo model
I.e., if the variaility of a variable A is [-10;10], A is now set to be -10 <= A <= 10 by changing its lower and upper bound.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ConcreteModel
|
The pyomo model |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
The variability data |
required |
abs_epsilon
|
_type_
|
Under this value, the given value is assumed to be 0.0. Defaults to 1e-9. |
1e-05
|
Returns:
Name | Type | Description |
---|---|---|
ConcreteModel |
ConcreteModel
|
The pyomo model with newly set variable bounds |
Source code in cobrak/utilities.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
combine_enzyme_reaction_datasets(datasets)
Combines the enzyme reaction data from the given sources
The first given dataset has precedence, meaning that its data (k_cats, k_ms, ...) will be set first. For any reaction/metabolite where data is missing, it is then looked up in the second given dataset, then in the third and so on.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datasets
|
list[dict[str, EnzymeReactionData | None]]
|
The enzyme reaction datasets |
required |
Returns:
Type | Description |
---|---|
dict[str, EnzymeReactionData | None]
|
dict[str, EnzymeReactionData | None]: The combined enzyme reaction data |
Source code in cobrak/utilities.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
|
compare_multiple_results_to_best(cobrak_model, results, is_maximization, min_reac_flux=1e-08)
Compares multiple optimization results to the best result and returns a dictionary with statistics and comparisons.
This function first identifies the best result based on the objective value. It then compares each result to the best result and calculates statistics and comparisons. The comparisons include the difference between the objective values and the reaction fluxes. Reactions with fluxes below the minimum reaction flux threshold are ignored.
Args: cobrak_model (Model): The COBRA-k model used for the optimization. results (list[dict[str, float]]): A list of optimization results. is_maximization (bool): Whether the optimization is a maximization problem. min_reac_flux (float, optional): The minimum reaction flux to consider. Defaults to 1e-8.
Returns: dict[int, tuple[dict[str, float], dict[int, list[str]]]]: A dictionary where each key is the index of a result and each value is a tuple containing: - A dictionary with reaction statistics, including: - "min": The minimum absolute flux difference. - "max": The maximum absolute flux difference. - "sum": The sum of all absolute flux differences. - "mean": The mean of all absolute flux differences. - "median": The median of all absolute flux differences. - "obj_difference": The difference between the objective value of the current result and the best result. - A dictionary with reaction comparisons, where each key is an integer indicating which result has a higher flux: - 0: The best result has a higher flux. - 1: The current result has a higher flux.
Source code in cobrak/utilities.py
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
|
compare_optimization_result_fluxes(cobrak_model, result_1, result_2, min_reac_flux=1e-08)
Compares the fluxes of two optimization results and returns a dictionary with the absolute differences and indicators of which result has a higher flux.
This function first corrects the fluxes of the two results by considering the forward and reverse reactions. It then calculates the absolute differences between the corrected fluxes and determines which result has a higher flux for each reaction. Reactions with fluxes below the minimum reaction flux threshold are ignored.
Args: cobrak_model (Model): The COBRA-k model used for the optimization. result_1 (dict[str, float]): The first optimization result. result_2 (dict[str, float]): The second optimization result. min_reac_flux (float, optional): The minimum reaction flux to consider. Defaults to 1e-8.
Returns: dict[str, tuple[float, int]]: A dictionary where each key is a reaction ID and each value is a tuple containing: - The absolute difference between the fluxes of the two results. - An indicator of which result has a higher flux: - 0: Both results have the same flux. - 1: The first result has a higher flux. - 2: The second result has a higher flux.
Source code in cobrak/utilities.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 |
|
compare_optimization_result_reaction_uses(cobrak_model, results, min_abs_flux=1e-06)
Compares the usage of reactions across multiple optimization (e.g. FBA) results.
This function analyzes the frequency of reaction usage in a set of optimization results from a COBRAk Model. It identifies which reactions are used in each solution and prints the number of solutions in which each reaction is active, considering a minimum absolute flux threshold.
Parameters: - cobrak_model (Model): The COBRAk model containing the reactions to be analyzed. - results (list[dict[str, float]]): A list of dictionaries, each representing an optimization result with reaction IDs as keys and their corresponding flux values as values. - min_abs_flux (float, optional): The minimum absolute flux value to consider a reaction as used. Reactions with absolute flux values below this threshold are ignored. Defaults to 1e-6.
- None: This function does not return a value. It prints the number of solutions in which each reaction is used, grouped by the number of solutions.
Source code in cobrak/utilities.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
|
count_last_equal_elements(lst)
Counts the number of consecutive equal elements from the end of the list.
Parameters: lst (list[Any]): A Python list.
Returns: int: The number of consecutive equal elements from the end of the list.
Examples:
count_last_equal_elements([1.0, 2.0, 1.0, 3.0, 3.0, 3.0]) 3 count_last_equal_elements([1.0, 2.0, 2.0, 1.0]) 1 count_last_equal_elements([1.0, 1.0, 1.0, 1.0]) 4 count_last_equal_elements([]) 0
Source code in cobrak/utilities.py
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
create_cnapy_scenario_out_of_optimization_dict(path, cobrak_model, optimization_dict, desplit_reactions=True)
Create a CNApy scenario file from an optimization dictionary and a COBRAk Model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The file path where the CNApy scenario will be saved. |
required |
cobrak_model
|
Model
|
The COBRAk Model. |
required |
optimization_dict
|
dict[str, float]
|
An optimization result dict. |
required |
desplit_reactions
|
bool
|
bool: Whether or not the fluxes of split reversible reaction shall be recombined. Defaults to True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
None |
None
|
The function saves the CNApy scenario to the specified path. |
Source code in cobrak/utilities.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
|
create_cnapy_scenario_out_of_variability_dict(path, cobrak_model, variability_dict, desplit_reactions=True)
Create a CNApy scenario file from a variability dictionary and a COBRAk model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The file path where the CNApy scenario file will be saved. |
required |
cobrak_model
|
Model
|
The COBRA-k model containing reactions. |
required |
variability_dict
|
dict[str, list[float]]
|
A dictionary mapping reaction IDs to their minimum and maximum flux values. |
required |
desplit_reactions
|
bool
|
bool: Whether or not the fluxes of split reversible reaction shall be recombined. Defaults to True. |
True
|
Returns: None: The function saves the CNApy scenario to the specified path.
Source code in cobrak/utilities.py
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 |
|
delete_orphaned_metabolites_and_enzymes(cobrak_model)
Removes orphaned metabolites and enzymes from a COBRAk model.
This function cleans up a COBRAk model by deleting metabolites and enzymes that are not used in any reactions. A metabolite is considered orphaned if it does not appear in the stoichiometries of any reactions. Similarly, an enzyme is considered orphaned if it is not associated with any enzyme reaction data in the model's reactions.
- cobrak_model (Model): The COBRAk model to be cleaned. This model contains reactions, metabolites, and enzymes that may include unused entries.
Returns: - Model: The cleaned COBRAk model with orphaned metabolites and enzymes removed.
Source code in cobrak/utilities.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
|
delete_unused_reactions_in_optimization_dict(cobrak_model, optimization_dict, exception_prefix='', delete_missing_reactions=True, min_abs_flux=1e-15, do_not_delete_with_z_var_one=True)
Delete unused reactions in a COBRAk model based on an optimization dictionary.
This function creates a deep copy of the provided COBRAk model and removes reactions that are either not present in the optimization dictionary or have flux values below a specified threshold. Optionally, reactions with a specific prefix can be excluded from deletion. Additionally, orphaned metabolites (those not used in any remaining reactions) are also removed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
COBRAk model containing reactions and metabolites. |
required |
optimization_dict
|
dict[str, float]
|
Dictionary mapping reaction IDs to their optimized flux values. |
required |
exception_prefix
|
str
|
A prefix for reaction IDs that should not be deleted. Defaults to "". |
''
|
delete_missing_reactions
|
bool
|
Whether to delete reactions not present in the optimization dictionary. Defaults to True. |
True
|
min_abs_flux
|
float
|
The minimum absolute flux value below which reactions are considered unused. Defaults to 1e-10. |
1e-15
|
Returns:
Name | Type | Description |
---|---|---|
Model |
Model
|
A new COBRAk model with unused reactions and orphaned metabolites removed. |
Source code in cobrak/utilities.py
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
|
delete_unused_reactions_in_variability_dict(cobrak_model, variability_dict, extra_reacs_to_delete=[])
Delete unused reactions in a COBRAk model based on a variability dictionary.
This function creates a deep copy of the provided COBRA-k model and removes reactions that have both minimum and maximum flux values
equal to zero, as indicated in the variability dictionary.
Additionally, any extra reactions specified in the extra_reacs_to_delete
list are also removed.
Orphaned metabolites (those not used in any remaining reactions) are subsequently deleted, too.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and metabolites. |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
A dictionary mapping reaction IDs to their minimum and maximum flux values. |
required |
extra_reacs_to_delete
|
list[str]
|
A list of additional reaction IDs to be deleted. Defaults to an empty list. |
[]
|
Returns:
Name | Type | Description |
---|---|---|
Model |
Model
|
A new COBRAk model with unused reactions and orphaned metabolites removed. |
Source code in cobrak/utilities.py
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 |
|
get_active_reacs_from_optimization_dict(cobrak_model, fba_dict)
Get a list of active reactions from an optimization (e.g. FBA (Flux Balance Analysis)) dictionary.
This function iterates through the reactions in a COBRAk model and identifies those that have a positive flux value in the provided FBA dictionary. Only reactions present in the optimization dictionary and with a flux greater than zero are considered active.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions. |
required |
fba_dict
|
dict[str, float]
|
A dictionary mapping reaction IDs to their flux values from an optimization. |
required |
Returns:
Type | Description |
---|---|
list[str]
|
list[str]: A list of reaction IDs that are active (i.e., have a positive flux) according to the optimization dictionary. |
Source code in cobrak/utilities.py
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 |
|
get_base_id(reac_id, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX, reac_enz_separator=REAC_ENZ_SEPARATOR)
Extract the base ID from a reaction ID by removing specified suffixes and separators.
Processes a reaction ID to remove forward and reverse suffixes as well as any enzyme separators, to obtain the base reaction ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reac_id
|
str
|
The reaction ID to be processed. |
required |
fwd_suffix
|
str
|
The suffix indicating forward reactions. Defaults to REAC_FWD_SUFFIX. |
REAC_FWD_SUFFIX
|
rev_suffix
|
str
|
The suffix indicating reverse reactions. Defaults to REAC_REV_SUFFIX. |
REAC_REV_SUFFIX
|
reac_enz_separator
|
str
|
The separator used between reaction and enzyme identifiers. Defaults to REAC_ENZ_SEPARATOR. |
REAC_ENZ_SEPARATOR
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The base reaction ID with specified suffixes and separators removed. |
Source code in cobrak/utilities.py
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 |
|
get_base_id_optimzation_result(cobrak_model, optimization_dict)
Converts an optimization result to a base reaction ID format in a COBRAk model.
This function processes an optimization result dictionary, which contains reaction IDs with their corresponding flux values, and consolidates these fluxes into base reaction IDs. It accounts for forward and reverse reaction suffixes to ensure that the net flux for each base reaction ID is calculated correctly.
Parameters: - cobrak_model (Model): The COBRAk model containing the reactions to be processed. - optimization_dict (dict[str, float]): A dictionary mapping reaction IDs to their flux values from an optimization result.
- dict[str, float]: A dictionary mapping base reaction IDs to their net flux values, consolidating forward and reverse reactions.
Source code in cobrak/utilities.py
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
|
get_cobrak_enzyme_reactions_string(cobrak_model, enzyme_id)
Get string of reaction IDs associated with a specific enzyme in the COBRAk model.
This function iterates through the reactions in a COBRAk model and collects the IDs of reaction that involve the specified enzyme. The collected reaction IDs are then concatenated into a single string, separated by semicolons.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and enzyme data. |
required |
enzyme_id
|
str
|
The ID of the enzyme for which associated reactions are to be found. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A semicolon-separated string of reaction IDs that involve the specified enzyme. |
Source code in cobrak/utilities.py
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 |
|
get_df_kappa_and_gamma_sorted_lists(cobrak_model, result, min_flux=0.0)
Extracts and sorts lists of flux values (df), kappa values, and gamma values from a result dictionary.
This function processes a dictionary of results ( a COBRA-k optimization) to extract and sort lists of flux values (df), kappa values, and gamma values. It filters these values based on a minimum flux threshold and returns them as sorted dictionaries. The function also calculates and returns a dictionary of kappa times gamma values, along with a status indicator representing the number of these values present for each reaction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA Model object. |
required |
result
|
dict[str, float]
|
A dictionary containing the simulation or optimization results. Keys are expected to start with prefixes like 'DF_VAR_PREFIX', 'KAPPA_VAR_PREFIX', and 'GAMMA_VAR_PREFIX'. |
required |
min_flux
|
float
|
The minimum flux value to consider when filtering the results. Values below this threshold are excluded. Defaults to 0.0. |
0.0
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
A tuple containing four dictionaries: |
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, tuple[float, int]]
|
|
tuple[dict[str, float], dict[str, float], dict[str, float], dict[str, tuple[float, int]]]
|
|
Source code in cobrak/utilities.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 |
|
get_elementary_conservation_relations(cobrak_model)
Calculate and return the elementary conservation relations (ECRs) of a COBRAk model as a string.
Computes the null space of the stoichiometric matrix of a COBRAk model to determine the elementary conservation relations. It then formats these relations into a human-readable string such as "1 ATP * 1 ADP"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and metabolites. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A string representation of the elementary conservation relations, where each relation is expressed as a linear combination of metabolites. |
Source code in cobrak/utilities.py
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 |
|
get_enzyme_usage_by_protein_pool_fraction(cobrak_model, result, min_conc=1e-12, rounding=5)
Return enzyme usage as a fraction of the total protein pool in a COBRAk model.
This function computes the fraction of the total protein pool used by each enzyme based on the given result dictionary. It filters out enzymes with concentrations below a specified minimum and groups the reactions by their protein pool fractions. The dictionary is sorted, i.e., low fractions occur first and high fractions last as keys.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and enzyme data. |
required |
result
|
dict[str, float]
|
A dictionary mapping variable names to their values, typically from an optimization result. |
required |
min_conc
|
float
|
The minimum concentration threshold for considering enzyme usage. Defaults to 1e-12. |
1e-12
|
rounding
|
int
|
The number of decimal places to round the protein pool fractions. Defaults to 5. |
5
|
Returns:
Type | Description |
---|---|
dict[float, list[str]]
|
dict[float, list[str]]: A dictionary where the keys are protein pool fractions and the values are lists of reaction IDs that use that fraction of the protein pool. |
Source code in cobrak/utilities.py
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 |
|
get_extra_linear_constraint_string(extra_linear_constraint)
Returns a string representation of an extra linear constraint.
The returned format is: "lower_value ≤ stoichiometry * var_id + ... ≤ upper_value"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
extra_linear_constraint
|
ExtraLinearConstraint
|
The extra linear constraint to convert to a string. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A string representation of the extra linear constraint |
Source code in cobrak/utilities.py
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
|
get_full_enzyme_id(identifiers)
Generate a full enzyme ID by concatenating the list of enzyme identifiers with a specific separator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
identifiers
|
list[str]
|
A list of enzyme identifiers. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A single string representing the full enzyme ID, with single identifiers separated by "AND". |
Source code in cobrak/utilities.py
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 |
|
get_full_enzyme_mw(cobrak_model, reaction)
Calculate the full molecular weight of enzymes (in kDa) involved in a given reaction.
This function computes the total molecular weight of all enzymes associated with a specified reaction in the COBRAk model. If the reaction does not have any enzyme reaction data, a ValueError is raised.
- If special (i.e. non-1) stoichiometries are provided in the reaction's
enzyme_reaction_data
, they are used to scale the molecular weights accordingly. - If no special stoichiometry is provided for an enzyme, a default stoichiometry of 1 is assumed.
- The function sums up the molecular weights of all enzymes, multiplied by their respective stoichiometries, to compute the total.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k model containing enzyme data. |
required |
reaction
|
Reaction
|
The reaction for which the full enzyme molecular weight is to be calculated. |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The total molecular weight of all enzymes involved in the reaction in kDa |
Raises:
Type | Description |
---|---|
ValueError
|
If the reaction does not have any enzyme reaction data. |
Source code in cobrak/utilities.py
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 |
|
get_fwd_rev_corrected_flux(reac_id, usable_reac_ids, result, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX)
Calculates the direction-corrected flux for a reaction, taking into account the flux of its reverse reaction.
If the reverse reaction exists and its flux is greater than the flux of the forward reaction, the corrected flux is set to 0.0. Otherwise, the corrected flux is calculated as the difference between the flux of the forward reaction and the flux of the reverse reaction. If the reverse reaction does not exist or is not usable, the corrected flux is set to the flux of the forward reaction.
Args: reac_id (str): The ID of the reaction. usable_reac_ids (list[str] | set[str]): A list or set of IDs of reactions that can be used for correction. result (dict[str, float]): A dictionary containing the flux values for each reaction. fwd_suffix (str, optional): The suffix used to identify forward reactions. Defaults to REAC_FWD_SUFFIX. rev_suffix (str, optional): The suffix used to identify reverse reactions. Defaults to REAC_REV_SUFFIX.
Returns: float: The corrected flux value for the reaction.
Source code in cobrak/utilities.py
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 |
|
get_metabolite_consumption_and_production(cobrak_model, met_id, optimization_dict)
Calculate the consumption and production rates of a metabolite in a COBRAk model.
This function computes the total consumption and production of a specified metabolite based on the flux values provided in an optimization dictionary. It iterates through the reactions in the COBRAk model, checking the stoichiometries to determine the metabolite's consumption or production in each reaction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and metabolites. |
required |
met_id
|
str
|
The ID of the metabolite for which consumption and production rates are to be calculated. |
required |
optimization_dict
|
dict[str, float]
|
A dictionary mapping reaction IDs to their optimized flux values. |
required |
Returns:
Type | Description |
---|---|
tuple[float, float]
|
tuple[float, float]: A tuple containing the total consumption and production rates of the specified metabolite. |
Source code in cobrak/utilities.py
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 |
|
get_metabolites_in_elementary_conservation_relations(cobrak_model)
Identify metabolites involved in elementary conservation relations (ECRs) in a COBRAk model.
Calculates the null space of the stoichiometric matrix of a COBRAk model to determine the elementary conservation relations. It then identifies the metabolites that are part of these relations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and metabolites. |
required |
Returns:
Type | Description |
---|---|
list[str]
|
list[str]: A list of metabolite IDs that are involved in elementary conservation relations. |
Source code in cobrak/utilities.py
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 |
|
get_model_dG0s(cobrak_model, abs_values=False)
Extracts standard Gibbs free energy changes (dG0) from reactions in the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions with thermodynamic data. |
required |
abs_values
|
bool
|
If True, returns absolute values of dG0. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
list[float]
|
list[float]: A list of dG0 values, possibly as absolute values if specified. |
Source code in cobrak/utilities.py
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 |
|
get_model_kcats(cobrak_model)
Extracts k_cat values from reactions with enzyme data in the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions with enzyme data. |
required |
Returns:
Type | Description |
---|---|
list[float]
|
list[float]: A list of k_cat values for reactions with available enzyme data. |
Source code in cobrak/utilities.py
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 |
|
get_model_kms(cobrak_model)
Extracts k_m values from reactions with enzyme data in the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions with enzyme data. |
required |
Returns:
Type | Description |
---|---|
list[float]
|
list[float]: A flat list of k_m values from all reactions with available enzyme data. |
Source code in cobrak/utilities.py
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
|
get_model_kms_by_usage(cobrak_model)
Collects k_M values from a COBRA-k model, separating them into substrate and product lists.
This function iterates through the reactions in a COBRA-k model and extracts the k_M values associated with each metabolite. It distinguishes between substrates (metabolites with negative stoichiometry) and products (metabolites with positive stoichiometry) and separates the corresponding Kms values into two lists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
Returns:
Type | Description |
---|---|
list[float]
|
A tuple containing two lists: the first list contains k_M values for substrates, |
list[float]
|
and the second list contains k_M values for products. |
Source code in cobrak/utilities.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 |
|
get_model_max_kcat_times_e_values(cobrak_model)
Calculates the maximum k_cat * E (enzyme concentration in terms of its molecular weight) for each reaction with enzyme data and returns these values.
The maximal k_catE is Ωk_cat/W, with Ω as protein pool and W as enzyme molecular weight.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
A metabolic model instance that includes enzymatic constraints, which must contain Reaction instances with enzyme_reaction_data. |
required |
Returns:
Type | Description |
---|---|
list[float]
|
List[float]: A list containing the calculated maximum k_cat * E values for reactions having enzyme reaction data. |
Notes
- The function requires 'reaction.enzyme_reaction_data.k_cat' and 'get_full_enzyme_mw(cobrak_model, reaction)' to be non-zero.
- If a reaction lacks enzyme reaction data, it is skipped in the calculation.
Source code in cobrak/utilities.py
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 |
|
get_model_mws(cobrak_model)
Extracts molecular weights of enzymes from the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing enzyme data. |
required |
Returns:
Type | Description |
---|---|
list[float]
|
list[float]: A list of molecular weights for each enzyme in the model. |
Source code in cobrak/utilities.py
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 |
|
get_model_with_filled_missing_parameters(cobrak_model, add_dG0_extra_constraints=False, param_percentile=90, ignore_prefixes=['EX_'], use_median_for_kms=True, use_median_for_kcats=True)
Fills missing parameters in a COBRA-k model, including dG0, k_cat, and k_ms values.
This function iterates through the reactions in a COBRA-k model and fills in missing parameters based on percentile values from the entire model. Missing dG0 values are filled using a percentile of the absolute dG0 values. Missing k_cat values are filled using a percentile or median of the k_cat values. Missing k_ms values are filled using a percentile or median of the k_ms values, depending on whether the metabolite is a substrate or a product. Optionally, extra linear constraints can be added to enforce consistency between the dG0 values of coupled reversible reactions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object to be modified. |
required |
add_dG0_extra_constraints
|
bool
|
Whether to add extra linear constraints for reversible reactions. Defaults to False. |
False
|
param_percentile
|
int
|
The percentile to use for filling missing parameters. Defaults to 90. |
90
|
ignore_prefixes
|
list[str]
|
List of prefixes to ignore when processing reactions. Defaults to ["EX_"] (i.e. exchange reactions). |
['EX_']
|
use_median_for_kms
|
bool
|
Whether to use the median instead of the percentile for k_ms values. Defaults to True. |
True
|
use_median_for_kcats
|
bool
|
Whether to use the median instead of the percentile for k_cat values. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Model
|
A deep copy of the input COBRA-k model with missing parameters filled. |
Source code in cobrak/utilities.py
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 |
|
get_model_with_varied_parameters(model, max_km_variation=None, max_kcat_variation=None, max_ki_variation=None, max_ka_variation=None, max_dG0_variation=None)
Generates a modified copy of the input Model with varied reaction parameters.
This function creates a deep copy of the input Model and introduces random variations
to several reaction parameters, including dG0, k_cat, k_ms, k_is, and k_as. The
magnitude of the variation is controlled by the provided max_..._variation
parameters. If a max_..._variation
parameter is not provided (i.e., is None),
the corresponding parameter will not be varied. Variations are applied randomly
using a uniform distribution. For reactions with a reverse reaction, the dG0 values
of the forward and reverse reactions are updated to maintain thermodynamic consistency.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Model
|
The Model object to be modified. |
required |
max_km_variation
|
float | None
|
Maximum factor by which to vary Kms. Defaults to None. |
None
|
max_kcat_variation
|
float | None
|
Maximum factor by which to vary k_cat. Defaults to None. |
None
|
max_ki_variation
|
float | None
|
Maximum factor by which to vary k_is. Defaults to None. |
None
|
max_ka_variation
|
float | None
|
Maximum factor by which to vary k_as. Defaults to None. |
None
|
max_dG0_variation
|
float | None
|
Maximum factor by which to vary dG0. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Model
|
A deep copy of the input model with varied reaction parameters. |
Source code in cobrak/utilities.py
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 |
|
get_potentially_active_reactions_in_variability_dict(cobrak_model, variability_dict)
Identify potentially active reactions in a COBRAk model based on a variability dictionary.
This function returns a list of reaction IDs that are present in both the COBRAk model and the variability dictionary, and have a maximum flux greater than zero while having a minimum flux equal to zero. These reactions are considered potentially active.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions. |
required |
variability_dict
|
dict[str, tuple[float, float]]
|
A dictionary mapping reaction IDs to their minimum and maximum flux values. |
required |
Returns:
Type | Description |
---|---|
list[str]
|
list[str]: A list of reaction IDs that are potentially active. |
Source code in cobrak/utilities.py
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 |
|
get_pyomo_solution_as_dict(model)
Returns the pyomo solution as a dictionary of { "\(VAR_NAME": "\)VAR_VALUE", ... }
Value is None for all uninitialized variables.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ConcreteModel
|
The pyomo model |
required |
Returns:
Type | Description |
---|---|
dict[str, float]
|
dict[str, float]: The solution dictionary |
Source code in cobrak/utilities.py
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 |
|
get_reaction_enzyme_var_id(reac_id, reaction)
Returns the pyomo model name of the reaction's enzyme
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reac_id
|
str
|
Reaction ID |
required |
reaction
|
Reaction
|
Reaction instance |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Reaction enzyme's name |
Source code in cobrak/utilities.py
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 |
|
get_reaction_string(cobrak_model, reac_id)
Generate a string representation of a reaction in a COBRAk model.
This function constructs a string that represents the stoichiometry of a specified reaction, including the direction of the reaction based on its flux bounds. E.g., a reaction R1: A ⇒ B, [0, 1000] is returned as "1 A ⇒ 1 B"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing the reaction. |
required |
reac_id
|
str
|
The ID of the reaction to be represented as a string. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A string representation of the reaction, showing educts, products, and the reaction direction. |
Source code in cobrak/utilities.py
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 |
|
get_reverse_reac_id_if_existing(reac_id, fwd_suffix=REAC_FWD_SUFFIX, rev_suffix=REAC_REV_SUFFIX)
Returns the ID of the reverse reaction if it exists, otherwise returns an empty string.
Args: reac_id (str): The ID of the reaction. fwd_suffix (str, optional): The suffix used to identify forward reactions. Defaults to REAC_FWD_SUFFIX. rev_suffix (str, optional): The suffix used to identify reverse reactions. Defaults to REAC_REV_SUFFIX.
Returns: str: The ID of the reverse reaction if it exists, otherwise an empty string.
Source code in cobrak/utilities.py
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 |
|
get_solver_status_from_pyomo_results(pyomo_results)
Returns the solver status from the pyomo results as an integer code.
This function interprets the solver status from a SolverResults
object and returns a corresponding integer code.
The mapping is as follows:
- 0 for SolverStatus.ok
- 1 for SolverStatus.warning
- 2 for SolverStatus.error
- 3 for SolverStatus.aborted
- 4 for SolverStatus.unknown
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pyomo_results
|
SolverResults
|
The results object from a Pyomo solver containing the solver status. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the solver status is not recognized. |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
An integer code representing the solver status. |
Source code in cobrak/utilities.py
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 |
|
get_stoichiometric_matrix(cobrak_model)
Returns the model's stoichiometric matrix.
The matrix is returned as a list of float lists, where each float list stands for a reaction and each entry in the float list for a metabolite.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The model |
required |
Returns:
Type | Description |
---|---|
list[list[float]]
|
list[list[float]]: The stoichiometric matrix |
Source code in cobrak/utilities.py
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 |
|
get_stoichiometrically_coupled_reactions(cobrak_model, rounding=10)
Returns stoichiometrically coupled reactions.
The returned format is as follows: Say that reactions (R1 & R2) as well as (R5 & R6 & R7) are stoichiometrically coupled (i.e, their fluxes are in a strict linear relationship to each other), then this function returns [["R1", "R2"], ["R5", "R6", "R7"].
The identification of stoichiometrically coupled reactions happens through the calculation of the model's stoichiometric matrix nullspace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The model |
required |
rounding
|
int
|
Precision for the calculation of the nullspace. Defaults to 10. |
10
|
Returns:
Type | Description |
---|---|
list[list[str]]
|
list[list[str]]: The stoichiometrically coupled reactions |
Source code in cobrak/utilities.py
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 |
|
get_substrate_and_product_exchanges(cobrak_model, optimization_dict={})
Identifies and categorizes reactions as substrate or product exchanges based on reaction stoichiometries.
This function analyzes each reaction in the provided COBRAk model to determine whether it primarily represents substrate consumption or product formation. It categorizes reactions into substrate reactions (where all stoichiometries are positive, indicating metabolite consumption) and product reactions (where all stoichiometries are negative, indicating metabolite production).
- A reaction is classified as a substrate reaction if all its stoichiometries are positive, indicating that all metabolites involved are being consumed.
- A reaction is classified as a product reaction if all its stoichiometries are negative, indicating that all metabolites involved are being produced.
- If the
optimization_dict
is provided, only the reactions listed in this dictionary are considered for classification. - The function returns tuples of reaction IDs, which can be used for further processing or analysis of substrate and product reactions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions to be analyzed. |
required |
optimization_dict
|
dict[str, Any]
|
An optional dictionary to filter reactions. Only reactions whose IDs are present in this dictionary will be considered. |
{}
|
Returns:
Type | Description |
---|---|
tuple[tuple[str, ...], tuple[str, ...]]
|
tuple[tuple[str, ...], tuple[str, ...]]: A tuple containing two elements: - The first element is a tuple of reaction IDs identified as substrate reactions. - The second element is a tuple of reaction IDs identified as product reactions. |
Source code in cobrak/utilities.py
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 |
|
get_termination_condition_from_pyomo_results(pyomo_results)
Returns the termination condition from the pyomo results as a float code.
This function interprets the termination condition from a SolverResults
object and returns a corresponding float code.
The mapping is as follows:
- 0.1 for TerminationCondition.globallyOptimal
- 0.2 for TerminationCondition.optimal
- 0.3 for TerminationCondition.locallyOptimal
- 1 for TerminationCondition.maxTimeLimit
- 2 for TerminationCondition.maxIterations
- 3 for TerminationCondition.minFunctionValue
- 4 for TerminationCondition.minStepLength
- 5 for TerminationCondition.maxEvaluations
- 6 for TerminationCondition.other
- 7 for TerminationCondition.unbounded
- 8 for TerminationCondition.infeasible
- 9 for TerminationCondition.invalidProblem
- 10 for TerminationCondition.solverFailure
- 11 for TerminationCondition.internalSolverError
- 12 for TerminationCondition.error
- 13 for TerminationCondition.userInterrupt
- 14 for TerminationCondition.resourceInterrupt
- 15 for TerminationCondition.licensingProblem
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pyomo_results
|
SolverResults
|
The results object from a Pyomo solver containing the termination condition. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the termination condition is not recognized. |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
A float code representing the termination condition. |
Source code in cobrak/utilities.py
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 |
|
get_unoptimized_reactions_in_nlp_solution(cobrak_model, solution, verbose=False)
Identify unoptimized reactions in the NLP (Non-Linear Programming) solution.
This function checks each reaction in the COBRAk model to determine if the flux values in the provided NLP solution match the expected values based on enzyme kinetics and thermodynamics. Reactions with discrepancies are considered unoptimized and are returned in a dictionary.
Discrepancies occur because, in COBRAk, the saturation term and the thermodynamic restriction are set as maximal values (<=), they are not fixed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions and enzyme data. |
required |
solution
|
dict[str, float]
|
A dictionary mapping variable names to their values from an NLP solution. |
required |
verbose
|
bool
|
bool: Whether or not to print the discrepancies for each reaction |
False
|
Returns:
Type | Description |
---|---|
dict[str, tuple[float, float]]
|
dict[str, tuple[float, float]]: Dictionary where the keys are reaction IDs and the values are tuples containing the NLP solution flux and the real flux for unoptimized reactions. |
Source code in cobrak/utilities.py
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 |
|
have_all_unignored_km(reaction, kinetic_ignored_metabolites)
Check if all non-ignored metabolites in a reaction have associated Michaelis-Menten constants (k_m).
This function checks whether all substrates and products of a reaction, excluding those specified in the kinetically ignored metabolites list, have associated Km values. It also ensures that there is at least one substrate and one product with a k_m value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reaction
|
Reaction
|
The reaction to be checked. |
required |
kinetic_ignored_metabolites
|
list[str]
|
A list of metabolite IDs to be ignored in the k_m check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if all non-ignored metabolites have Km values and there is at least one substrate and one product with Km values, False otherwise. |
Source code in cobrak/utilities.py
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 |
|
is_any_error_term_active(correction_config)
Checks if any error term is active in the correction configuration.
This function determines whether any of the error terms specified in the
CorrectionConfig
object are enabled. It sums the boolean values of the
flags indicating whether each error term is active. If the sum is greater
than zero, it means at least one error term is active.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
correction_config
|
CorrectionConfig
|
The CorrectionConfig object to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if at least one error term is active, False otherwise. |
Source code in cobrak/utilities.py
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 |
|
is_objsense_maximization(objsense)
Checks if the objective sense is maximization.
Args: objsense (int): The objective sense, where in this function's definition: - >0: Maximization - ≤0: Minimization
Returns: bool: True if the objective sense is maximization, False otherwise.
Source code in cobrak/utilities.py
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 |
|
last_n_elements_equal(lst, n)
Check if the last n elements of a list are equal.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lst
|
list[Any]
|
The list to check. |
required |
n
|
int
|
The number of elements from the end of the list to compare. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the last n elements are equal, False otherwise. |
Example
last_n_elements_equal([1, 2, 3, 4, 4, 4], 3) True last_n_elements_equal([1, 2, 3, 4, 5, 6], 3) False
Source code in cobrak/utilities.py
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 |
|
make_kms_better_by_factor(cobrak_model, reac_id, factor)
Adjusts the Michaelis constants (Km) for substrates and products of a specified reaction in the metabolic model.
- Substrate's Michaelis constants are divided by 'factor'.
- Product's Michaelis constants are multiplied by 'factor'.
- Only affects metabolites with existing enzyme reaction data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The metabolic model containing enzymatic constraints. |
required |
reac_id
|
str
|
The ID of the reaction to adjust the Km values for. |
required |
factor
|
float
|
The multiplication/division factor used to modify the Michaelis constants. |
required |
Returns:
Name | Type | Description |
---|---|---|
None |
None
|
This function modifies the input Model object in place and does not return any value. |
Source code in cobrak/utilities.py
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 |
|
parse_external_resources(path, brenda_version)
Parse and verify the presence of external resource files required for a COBRAk model.
This function checks if the necessary external resource files are present in the specified directory. If any required files are missing, it provides instructions on where to download them. Additionally, it processes certain files if their parsed versions are not found.
The particular files that are lloked after are the NCBI TAXONOMY taxdump file and the BRENDA JSON TAR GZ as wel as the bigg_models_metabolites.txt file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The directory path where the external resource files are located. |
required |
brenda_version
|
str
|
The version of the BRENDA database to be used. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If the specified path is not a directory. |
FileNotFoundError
|
If any required files are missing from the specified directory. |
Source code in cobrak/utilities.py
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 |
|
print_model_parameter_statistics(cobrak_model)
Prints statistics about reaction parameters (kcats and kms) in a COBRA-k model.
This function calculates and prints statistics about the kcat and Km values associated with reactions in a COBRA-k model. It groups these values by their taxonomic distance (as indicated by references) and prints the counts for each distance group. It also prints the median kcat and the median Km values for substrates and products separately.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cobrak_model
|
Model
|
The COBRA Model object. |
required |
Returns:
Type | Description |
---|---|
None
|
None. Prints statistics to the console. |
Source code in cobrak/utilities.py
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 |
|
sort_dict_keys(dictionary)
Sorts all keys in a dictionary alphabetically.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dictionary
|
dict
|
The dictionary to sort. |
required |
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, T]
|
A new dictionary with the keys sorted alphabetically. |
Source code in cobrak/utilities.py
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 |
|
split_list(lst, n)
Split a list into n
nearly equal parts.
This function divides a given list into n
sublists, distributing the elements as evenly as possible.
Parameters: - lst (list[Any]): The list to be split. - n (int): The number of sublists to create.
Returns:
- list[list[Any]]: A list of n
sublists, each containing a portion of the original list's elements.
Example:
result = _split_list([1, 2, 3, 4, 5], 3)
# result: [[1, 2], [3, 4], [5]]
Raises:
- ValueError: If n
is less than or equal to 0.
Source code in cobrak/utilities.py
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 |
|