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 32 33 34 | |
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
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 | |
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
46 47 48 49 50 51 52 53 54 | |
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
37 38 39 40 41 42 43 | |
alphafold_db_functionality
Functionality to retrieve PDB files from the AlphaFold Protein Structure Database
Link to database (as of December 2, 2025): https://alphafold.ebi.ac.uk/
download_alphafold_pdb(uniprot_id, output_dir='.', as_gzip=False)
Downloads the predicted Protein Data Bank (PDB) file for a given UniProt ID from the AlphaFold Protein Structure Database (AlphaFold DB).
This function queries the AlphaFold API, identifies the most complete/latest PDB URL (specifically by finding the highest numbered entry in fragmented predictions), and downloads the file to the specified directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uniprot_id
|
str
|
The UniProt accession ID (e.g., "P00520") for the target protein. |
required |
output_dir
|
str
|
The directory path where the PDB file should be saved.
Defaults to the current directory ( |
'.'
|
as_gzip
|
bool
|
Whether or not the file shall be compressed through gzip (.gz is added to the file name). Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
The function prints status messages and saves the file to disk. |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If the initial API request fails due to an HTTP error (e.g., 404, 500). |
Notes
- The download file is named using the format:
<uniprot_id>__<original_filename>(e.g.,P00520__AF-P00520-F1-model_v4.pdb). - The AlphaFold DB API is used to handle multi-fragment predictions (for proteins over ~2700 residues) by attempting to select the final fragment or the entry with the highest numerical identifier in the URL path.
Source code in cobrak/alphafold_db_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 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 | |
download_alphafold_pdb_for_all_enzymes(cobrak_model, uniprot_annotation_id='uniprot', output_dir='.', sleep_time=1.0, as_gzip=False)
Downloads AlphaFold PDB files for all enzymes in a COBRA-k Model that have a given UniProt ID annotation.
It iterates through the reactions in the COBRA-k Model, extracts the UniProt ID
from the reaction's annotation, and calls download_alphafold_pdb for each.
A delay is introduced between downloads to respect API rate limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
A COBRA-k Model instance. |
required |
uniprot_annotation_id
|
str
|
The key used in the reaction's |
'uniprot'
|
output_dir
|
str
|
The directory path where the PDB files should be saved.
Defaults to the current directory ( |
'.'
|
sleep_time
|
float
|
The time in seconds to pause between consecutive downloads to cool down the AlphaFold API server. Defaults to 1.0 second. |
1.0
|
as_gzip
|
bool
|
Whether or not the file shall be compressed through gzip (.gz is added to the file name). Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
The function manages file downloads and prints status messages. |
Source code in cobrak/alphafold_db_functionality.py
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 | |
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
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 77 78 79 | |
brenda_functionality
Contains functions which allow one to create a model-specific and BRENDA-depending kinetic data database.
brenda_select_enzyme_kinetic_data_for_sbml(sbml_path, 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=1000000000.0, kis_and_kas_only_for_same_compartments=True)
Select and assign enzyme kinetic data for each reaction in an SBML 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 SBML 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 |
|---|---|---|---|
sbml_path
|
str
|
Path to SBML model. |
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. |
{}
|
kis_and_kas_only_for_same_compartments
|
bool
|
bool, default False If True, kis and kas can only be attributed to a reaction if the affected metabolite has shares one of the reaction metabolite's compartments |
True
|
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 use the unit h⁻¹.
- KM, KA and KI values use the unit M=mol⋅l⁻¹.
- 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
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 | |
cobrapy_model_functionality
Contains methods that directly apply on COBRApy models.
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'), delete_old_cobrak_id_annotations=False)
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
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 | |
get_fullsplit_cobra_model_from_sbml(sbml_path, 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 (loaded from the SBML) 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
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 | |
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)
BIGG_COMPARTMENTS = ['c', 'e', 'p', 'm', 'x', 'r', 'v', 'n', 'g', 'u', 'l', 'h', 'f', 's', 'im', 'cx', 'um', 'cm', 'i', 'mm', 'w', 'y']
module-attribute
List of BiGG compartment suffixes (without _) as defined in http://bigg.ucsd.edu/compartments/
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)
GENERALIZED_SUM_CONSTRAINT_NAME = 'generalized_sum_constraint'
module-attribute
Name of constraint for generalized sum (protein pool + metabolite concentrations)
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_CONC_RANGES = {'DEFAULT': (1e-06, 0.2), 'h_c': (1.0, 1.0), 'h_p': (1.0, 1.0), 'h_e': (1.0, 1.0), 'h20_c': (1.0, 1.0), 'h20_p': (1.0, 1.0), 'h20_e': (1.0, 1.0)}
module-attribute
Standard concentration ranges applicable to models with BiGG IDs; water and protons are set to one as their effect is directly included in the ΔG'° calculation (see the eQuilibrator FAQ), while the rest is set to wide ranges.
STANDARD_MAX_PROT_POOL = 0.25
module-attribute
Just a (for E. coli) quite high pool of metabolic enzymes on the total dry weight mass (in g⋅gDW⁻¹).
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
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 | |
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_ka_error_term = False
class-attribute
instance-attribute
Indicates whether to add an α error term. 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_ki_error_term = False
class-attribute
instance-attribute
Indicates whether to add a ι error term. 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=dict)
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 {}.
ka_error_cutoff = 1.0
class-attribute
instance-attribute
Cutoff value for the α error term. Defaults to 1.0.
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.
ki_error_cutoff = 1.0
class-attribute
instance-attribute
Cutoff value for the ι 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_ka_correction = 0.999
class-attribute
instance-attribute
Maximal relative correction for the α error term. Defaults to 0.999.
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_ki_correction = 0.999
class-attribute
instance-attribute
Maximal relative correction for the ι error term. Defaults to 0.999.
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 (note: 'enzyme' stands for a single polypeptide).
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 sequence: str: [Optional] Protein sequence of enzyme (note: 'enzyme' stands for a single polypeptide)
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 63 64 65 66 | |
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
Any annotation data for the enzyme (e.g., references). Has no effect on calculations
max_conc = None
class-attribute
instance-attribute
The enzyme's minimal concentration in mmol⋅gDW⁻¹
min_conc = None
class-attribute
instance-attribute
The enzyme's minimal concentration in mmol⋅gDW⁻¹
molecular_weight = 1e+20
class-attribute
instance-attribute
The enzyme's molecular weight in kDa. Defaults to 1e20 (a very high value that shall be replaced with a real molecular weight).
name = ''
class-attribute
instance-attribute
Colloquial name of enzyme
sequence = ''
class-attribute
instance-attribute
Protein sequence of enzyme (note: 'enzyme' stands for a single polypeptide)
EnzymeReactionData
Represents the enzymes used by a reaction.
Source code in cobrak/dataclasses.py
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 | |
hill_coefficient_references = Field(default_factory=HillParameterReferences)
class-attribute
instance-attribute
[Optional] References showing the source(s) of the Hill coefficients. Metabolite IDs are keys, the source lists values. Default is {}
hill_coefficients = Field(default_factory=HillCoefficients)
class-attribute
instance-attribute
[Optional] If given, the reaction's Hill coefficients. Metabolite IDs are keys, coefficients the in form of HillCoefficients instances. Default is empty HillCoefficients().
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_as the values. Default is {}
k_cat = 1e+20
class-attribute
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_is the 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 the values. Default is {}
special_stoichiometries = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Special (non-1) stoichiometries of polypeptides/enzymes 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 (including watches) 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
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 | |
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.
ExtraLinearWatch
Represents a linear 'watch', i.e. a variable that shows the linear sum of other variables.
A watch can be not only about reactions, but also all other variables (except of watches that are defined after this one in the Model's extra_linear_watches member variable) set in a COBRAk model. E.g., if one wants (for whatever reason) a variable for the following constraint: [A] - 2 * r_R1, we set ExtraLinearWatch( stoichiometries = { "x_A": 1.0, "R1": -2, }, )
The name of the watch is set in as dictionary key for the model's extra_linear_watches member variable.
Source code in cobrak/dataclasses.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
ExtraNonlinearConstraint
Represents a general non-linear Model constraint.
Important note: Setting such a non-linear watch makes any optimization non-linear and thus incompatible with linear solvers and computationally much more expensive!
This can affect not only reactions, but also all other variables (including watches) set in a COBRA-k model. E.g., if one wants (for whatever reason) the following constraint: 0.5 <= log([A]^2 - 2 * exp(r_R1)) <= 2.1 the corresponding ExtraNonlinearConstraint instance would be: ExtraNonlinearConstraint( stoichiometries = { "x_A": (1.0, "power2"), "R1": (-2, "exp"), }, full_application = "log", lower_value = 0.5, upper_value = 2.1, ) Allowed non-linear functions are currently 'powerX' (with X as float-readable exponent), 'exp' and 'log'. If you just want the normal value, 'same' can be used (i.e. multiply with 1). lower_value or upper_value can be None if no such limit is desired. Also, full_application is by default 'same', which is to be set if no function on the full term is wished.
Source code in cobrak/dataclasses.py
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 | |
full_application = 'same'
class-attribute
instance-attribute
Either function name 'same' (multiply with 1), 'powerX' (with X as float-readable exponent), 'exp' or 'log'). Defaults to 'same'.
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, function name 'same' (multiply with 1), 'powerX' (with X as float-readable exponent), 'exp' or 'log')
upper_value = None
class-attribute
instance-attribute
Maximal numeric constraint value. Either this and/or lower_value must be not None. Defaults to None.
ExtraNonlinearWatch
Represents a non-linear 'watch', i.e. a variable that shows the linear sum of other variables.
Important note: Setting such a non-linear watch makes any optimization non-linear and thus incompatible with linear solvers and computationally much more expensive!
A watch can be not only about reactions, but also all other variables (except of watches that are defined after this one in the Model's extra_linear_watches member variable) set in a COBRAk model. E.g., if one wants (for whatever reason) a variable for the following constraint: exp([A]) - 2 * r_R1^3, we set ExtraLinearWatch( stoichiometries = { "x_A": (1.0, "exp"), "R1": (-2, "power3"), }, )
Allowed non-linear functions are currently 'powerX' (with X as float-readable exponent), 'exp' and 'log'. If you just want the normal value, 'same' can be used (i.e. multiply with 1). The name of the watch is set in as dictionary key for the model's extra_linear_watches member variable.
Source code in cobrak/dataclasses.py
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 | |
HillCoefficients
Represents the Hill coefficients of a reactions, seperated according to efficiency terms
Source code in cobrak/dataclasses.py
99 100 101 102 103 104 105 106 107 108 | |
alpha = Field(default_factory=dict)
class-attribute
instance-attribute
Hill coefficients affecting the α activation term. Metabolite IDs are keys, coefficients values. Defaults to {}.
iota = Field(default_factory=dict)
class-attribute
instance-attribute
Hill coefficients affecting the ι inhibition term. Metabolite IDs are keys, coefficients values. Defaults to {}.
kappa = Field(default_factory=dict)
class-attribute
instance-attribute
Hill coefficients affecting the κ saturation term. Metabolite IDs are keys, coefficients values. Defaults to {}.
HillParameterReferences
Represents the database reference for the ι, α and κ Hill coefficients.
Source code in cobrak/dataclasses.py
87 88 89 90 91 92 93 94 95 96 | |
alpha = Field(default_factory=dict)
class-attribute
instance-attribute
References for α Hill coefficients.
iota = Field(default_factory=dict)
class-attribute
instance-attribute
References for ι Hill coefficients.
kappa = Field(default_factory=dict)
class-attribute
instance-attribute
References for κ Hill coefficients.
Metabolite
Represents a Model's metabolite.
Source code in cobrak/dataclasses.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
annotation = Field(default_factory=dict)
class-attribute
instance-attribute
Annotation (e.g., CHEBI numbers, ...); Default is {}
charge = 0
class-attribute
instance-attribute
Electron charge of metabolite
compartment = ''
class-attribute
instance-attribute
Identifier for a metabolite's compartment
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)
molar_mass = None
class-attribute
instance-attribute
Molar mass of metaobolite (g⋅mol⁻¹)
name = ''
class-attribute
instance-attribute
Colloquial name of metabolite
smiles = ''
class-attribute
instance-attribute
SMILES string 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
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 | |
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
extra_linear_watches = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Extra non-linear watches. Keys are watch names, children the watch definition.
extra_nonlinear_constraints = Field(default_factory=list)
class-attribute
instance-attribute
[Optional] Extra non-linear constraints
extra_nonlinear_watches = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Extra non-linear watches. Keys are watch names, children the watch definition.
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'
include_mets_in_prot_pool = False
class-attribute
instance-attribute
[Experimental! Optional and only works with MILPs with enzyme and thermodynamic constraints] Whether or not metabolite masses are included in the protein (now generalized mass) pool (makes the problem non-linear!)
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, and overridden with float("inf") when include_met_concs_sum_in_prot_pool==True] 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
385 386 387 388 | |
__exit__(a, b, c)
Method called when leaving a 'with' block
Source code in cobrak/dataclasses.py
390 391 392 | |
ParameterReference
Represents the database reference for a kinetic parameter.
Source code in cobrak/dataclasses.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
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, hill_coefficients=None, ), annotation={}, # Can be also ignored )
Source code in cobrak/dataclasses.py
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 | |
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 = 1000.0
class-attribute
instance-attribute
Maximal flux (must be >= min_flux). Defaults to 1_000.0.
min_flux = 0.0
class-attribute
instance-attribute
Minimal flux (for COBRA-k, this must be ≥ 0). Defaults to 0.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
451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
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_factory_args = Field(default_factory=dict)
class-attribute
instance-attribute
[Optional] Arguments for pyomo's SolverFactory function
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_for_sbml(sbml_path, inner_to_outer_compartments, phs, pmgs, ionic_strengths, potential_differences, exclusion_prefixes=[], exclusion_inner_parts=[], ignore_uncertainty=False, max_uncertainty=1000.0, calculate_multicompartmental=True, ignored_metabolites=[])
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
|
calculate_multicompartmental
|
bool
|
If True, multicompartmental reactions also get a ΔG'° using the eQuilibrator's special routine for them. Defaults to True. |
True
|
ignored_metabolites
|
list[str]
|
List of metabolites that shall be ignored in reaction stoichiometries (e.g., for pseudo-metabolites) such as enzyme_pool in certain enzyme-constrained models. Defaults to []. |
[]
|
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
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 247 248 249 250 251 252 253 254 255 256 | |
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['genetic']
|
The type of optimization algorithm to use. Defaults to "genetic", the only available algorithm right now. |
'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
|
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
|
ignore_nonlinear_extra_terms_in_ectfbas
|
bool
|
(bool, optional): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. Defaults to True. |
True
|
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
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 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 | |
__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='genetic', lp_solver=SCIP, nlp_solver=IPOPT, nlp_strict_mode=False, nlp_single_strict_reacs=[], objvalue_json_path='', max_rounds_same_objvalue=float('inf'), correction_config=CorrectionConfig(), min_abs_objvalue=1e-06, pop_size=None, ignore_nonlinear_extra_terms_in_ectfbas=True)
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['genetic']
|
The type of optimization algorithm to use. Defaults to "genetic", 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
|
nlp_strict_mode
|
bool
|
Whether or not the <= heuristic (True) or not (False; i.e. setting all equations to ==) shall be used. Defaults to False. |
False
|
nlp_single_strict_reacs
|
list[str]
|
List of single reactions that shall be in strict mode (see |
[]
|
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
|
ignore_nonlinear_extra_terms_in_ectfbas
|
bool
|
(bool, optional): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. Defaults to True. |
True
|
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 213 214 215 216 217 218 219 220 221 222 223 224 | |
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
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 | |
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
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 | |
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, nlp_strict_mode=False, nlp_single_strict_reacs=[], objvalue_json_path='', max_rounds_same_objvalue=float('inf'), correction_config=CorrectionConfig(), min_abs_objvalue=1e-13, pop_size=None, working_results=[], ignore_nonlinear_extra_terms_in_ectfbas=True)
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['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
|
nlp_strict_mode
|
bool
|
Whether or not the <= heuristic (True) or not (False; i.e. setting all equations to ==) shall be used. Defaults to False. |
False
|
nlp_single_strict_reacs
|
list[str]
|
List of single reactions that shall be in strict mode (see |
[]
|
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 []. |
[]
|
ignore_nonlinear_extra_terms_in_ectfbas
|
bool
|
(bool, optional): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. Defaults to True. |
True
|
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
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 | |
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, nlp_strict_mode=False, nlp_single_strict_reacs=[], verbose=False, correction_config=CorrectionConfig(), onlytested='', ignore_nonlinear_extra_terms_in_ectfbas=True)
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
|
nlp_strict_mode
|
bool
|
Whether or not the <= heuristic (True) or not (False; i.e. setting all equations to ==) shall be used. Defaults to False. |
False
|
nlp_single_strict_reacs
|
list[str]
|
List of single reactions that shall be in strict mode (see |
[]
|
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 "". |
''
|
ignore_nonlinear_extra_terms_in_ectfbas
|
bool
|
(bool, optional): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. |
True
|
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
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 | |
example_models
Contains the toy model from COBRAk's documentation and publication as example model as well as iCH360_cobrak.
__getattr__(name)
Called by Python when an attribute that does not yet exist in the module namespace is requested.
We use it to load the JSON the first time iCH360_cobrak is asked
for, then store the result in globals() so the load happens only
once.
Source code in cobrak/example_models.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
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
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
genetic
Methods for COBRA-k's genetic algorithm used in the COBRA-k evolutionary algorithm
COBRAKGENETIC
A class for performing genetic algorithm optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
fitness_function |
Callable
|
A function that takes a list of integers/floats and returns a tuple containing the fitness score and a list of integers/floats. |
xs_dim |
int
|
The dimensionality of the search space. |
gen |
int
|
The number of generations to run the algorithm for. |
seed |
int | None
|
The seed for the random number generator. |
objvalue_json_path |
str
|
The path to a JSON file to store objective values. |
max_rounds_same_objvalue |
float
|
The maximum number of rounds with the same objective value before stopping the algorithm. |
pop_size |
int | None
|
The size of the population. If None, defaults to the number of CPUs. |
Source code in cobrak/genetic.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 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 | |
__init__(fitness_function, xs_dim, gen, extra_xs=[], seed=None, objvalue_json_path='', max_rounds_same_objvalue=float('inf'), pop_size=None)
Initializes the COBRAKGENETIC object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fitness_function
|
Callable
|
The fitness function to evaluate solutions. |
required |
xs_dim
|
int
|
The dimensionality of the search space. |
required |
gen
|
int
|
The number of generations to run. |
required |
extra_xs
|
list[list[int]]
|
Extra particles to initialize the population. Defaults to []. |
[]
|
seed
|
int | None
|
Seed for the random number generator. Defaults to None. |
None
|
objvalue_json_path
|
str
|
Path to a JSON file to store objective values. Defaults to "". |
''
|
max_rounds_same_objvalue
|
float
|
Maximum rounds with the same objective value before stopping. Defaults to infinity. |
float('inf')
|
pop_size
|
int | None
|
Population size. Defaults to None. |
None
|
Source code in cobrak/genetic.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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
run()
Runs the genetic algorithm optimization.
Returns:
| Type | Description |
|---|---|
float
|
tuple[float, tuple[int, ...]]: A tuple containing the best fitness score and the |
tuple[int, ...]
|
corresponding solution. |
Source code in cobrak/genetic.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 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 | |
update_particle(chosen_x, num_rounds_without_best_change)
Updates a single particle by introducing mutations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chosen_x
|
list[int]
|
The current solution represented as a list of integers. |
required |
num_rounds_without_best_change
|
int
|
The number of rounds without a change in the best fitness score. |
required |
Returns:
| Type | Description |
|---|---|
float
|
tuple[list[list[float]], list[int]]: A tuple containing a list of fitness scores |
list[int]
|
and the mutated solution. |
Source code in cobrak/genetic.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 | |
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
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 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 | |
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
200 201 202 203 204 205 206 207 208 209 210 211 | |
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
214 215 216 217 218 219 220 221 222 223 224 225 226 | |
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
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 | |
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
609 610 611 612 613 614 615 616 617 618 619 620 | |
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
623 624 625 626 627 628 629 630 631 632 633 634 635 | |
gzip_load_file(filepath, remove_newlines=True)
Loads a gzipped file and returns its content as a list of strings,
where each string is a line from the file.
This function uses gzip.open in text mode ('rt') and readlines() to efficiently
load the file content.
Args:
filepath: The path to the compressed (.tsv.gz) file.
remove_newlines: Whether or not newlines (
) shall be removed or not. Defaults to True.
Returns:
A list of strings, where each string is a line from the file.
Returns an empty list if the file is not found or an error occurs.
Source code in cobrak/io.py
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 | |
gzip_write_file(filepath, lines)
Write a gzipped (.gz) file out from the given content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
The path of the gzipped file (.gz ending has to be added) |
required |
lines
|
list[str]
|
A list of stringswith the file content. Newlines have to be added. |
required |
Source code in cobrak/io.py
673 674 675 676 677 678 679 680 681 682 | |
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
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 | |
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
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 | |
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
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 | |
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
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
load_annotated_cobrapy_model_as_cobrak_model(cobra_model, exclude_enzyme_constraints=True, mw_for_enzymes_without_cobrak_mw_annotation=1000000.0, deactivate_mw_warning=False)
Converts a COBRApy model with (and also without :-) 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
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 | |
load_annotated_sbml_model_as_cobrak_model(filepath, do_model_fullsplit=True, exclude_enzyme_constraints=True, mw_for_enzymes_without_cobrak_mw_annotation=1000000.0, deactivate_mw_warning=False)
Load an annotated (and also plain un-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. - do_model_fullsplit (bool, optional): Whether or not the model shall be "fullsplit" (i.e., any reversible reaction and enzyme reaction variant becomes its own )
- Model: A COBRAk Model constructed from the annotated SBML model, ready for further kinetic and thermodynamic analyses.
Source code in cobrak/io.py
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 | |
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
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 | |
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
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 | |
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
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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(), ignore_nonlinear_terms=False)
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(). ignore_nonlinear_terms: bool, optional Whether or not non-linear extra watches and constraints shall not be included. Defaults to False. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver!
Returns
ConcreteModel The constructed LP model with the specified constraints and configurations.
Source code in cobrak/lps.py
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 1547 1548 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 | |
perform_lp_dG0_varying_thermodynamic_bottleneck_analysis(cobrak_model, dG0_variation=-100, min_mdf_advantage=1e-06, with_enzyme_constraints=False, solver=SCIP, ignore_nonlinear_terms=False, verbose=False, parallel_verbosity_level=0)
Perform thermodynamic bottleneck analysis on a COBRA-k model using mixed-integer linear programming with ΔG'° variations.
This is an alternative to perform_lp_thermodynamic_bottleneck_analysis.
This function identifies the current set of thermodynamic bottlenecks in a COBRAk model by lowering the ΔG'° of each one reaction by the given factor (in kJ/mol). Typically, the minimal MDF to be reached would be a previously calculated optimal network-wide MDF (also called OptMDF). The basic methology was first described in [1]. To prevent thermodynamic cycles, the ΔG'° of potential reverse reactions is raised by the amount the one ΔG'° was lowered. To speed up calculations, this bottleneck analysis is performed in a parallelized fashion.
[1] Bekiaris et al. (2021). PLOS Computational Biology, 14(1), https://doi.org/10.1371/journal.pcbi.1009093
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model to analyze for thermodynamic bottlenecks. |
required |
dG0_variation
|
float
|
The amount in kJ/mol by which a reaction's ΔG'° is lowered. Defaults to -100. |
-100
|
min_mdf_advantage
|
float
|
The minimal OptMDF advantage through weakening tbhis bottleneck. Defaults to 1e-6. |
1e-06
|
with_enzyme_constraints
|
bool
|
Whether to include enzyme constraints in the analysis. |
False
|
verbose
|
bool
|
If True, print immediate information about identified bottlenecks. Defaults to False. |
False
|
solver
|
Solver
|
The COBRA-k Solver instance describing the used MILP solver. Defaults to SCIP. |
SCIP
|
parallel_verbosity_level
|
int
|
Sets the verbosity level for the analysis parallelization. The higher, the value, the more is printed. Default: 0. |
0
|
ignore_nonlinear_terms
|
bool
|
bool, optional Whether or not non-linear extra watches and constraints shall not be included. Defaults to False. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver! |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of reaction IDs identified as thermodynamic bottlenecks. |
Source code in cobrak/lps.py
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 2079 2080 2081 2082 2083 | |
perform_lp_min_active_reactions_analysis(cobrak_model, with_enzyme_constraints, variability_dict, min_mdf=0.0, verbose=False, solver=SCIP, ignore_nonlinear_terms=False)
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 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. ignore_nonlinear_terms: bool, optional Whether or not non-linear extra watches and constraints shall not be included. Defaults to False. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver!
Returns
float The minimum number of active reactions required to satisfy the constraints.
Source code in cobrak/lps.py
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 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 | |
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, ignore_nonlinear_terms=False, correction_config=CorrectionConfig(), var_data_abs_epsilon=1e-05)
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
|
ignore_nonlinear_terms
|
bool
|
(bool): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. Defaults to True. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver! |
False
|
correction_config
|
CorrectionConfig
|
Configuration for handling prameter corrections and scenarios during optimization. |
CorrectionConfig()
|
var_data_abs_epsilon
|
float
|
(float, optional): Under this value, any data given by the variability dict is considered to be 0. Defaults to 1e-5. |
1e-05
|
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
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 | |
perform_lp_thermodynamic_bottleneck_analysis(cobrak_model, with_enzyme_constraints=False, min_mdf=STANDARD_MIN_MDF, verbose=False, solver=SCIP, ignore_nonlinear_terms=False)
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
|
Solver
|
The COBRA-k Solver instance of the MILP solver. Defaults to "SCIP". |
SCIP
|
ignore_nonlinear_terms
|
bool
|
bool, optional Whether or not non-linear extra watches and constraints shall not be included. Defaults to False. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver! |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of reaction IDs identified as thermodynamic bottlenecks. |
dict[str, float]
|
tuple[str, float]: The MILP solution of this bottleneck search process. |
Source code in cobrak/lps.py
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 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 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 | |
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, ignore_nonlinear_terms=False, verbose=False)
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
|
ignore_nonlinear_terms
|
bool
|
(bool): Whether or not non-linear watches/constraints shall be ignored in ecTFBAs. Defaults to True. Note: If such non-linear values exist and are included, the whole problem becomes non-linear, making it incompatible with any purely linear solver! |
False
|
verbose
|
bool
|
If True, the objective values of solved problems are shown, together with computation time in s. Defaults to False. |
False
|
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
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 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 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 2218 2219 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 2271 2272 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 2338 2339 2340 2341 2342 | |
metanetx_functionality
Functionalities for reading out MetaNetX files.
add_smiles_annotation_to_metabolites(cobrak_model, chem_prop_json_filepath, chem_xref_json_filepath, print_found_smiles=False, print_not_found_smiles=False, allowed_annotation_keys=[])
Annotates metabolites in a COBRA-k model with SMILES strings using preprocessed MetaNetX files.
The function reads two gzipped JSON files (produced by COBRA-k's
clean_and_compress_mnx_files function - see there):
1. chem_xref.json
2. chem_prop.json
Note: The JSON's producedby COBRA-k's clean_and_compress_mnx_files are zipped, but
you must not add the .zip suffix to the given file paths.
It iterates through the model's metabolites, uses their existing annotations to find a matching MetaNetX ID, and then uses the MetaNetX ID to retrieve the SMILES string. The SMILES string is then added to the metabolite's annotation dictionary under the specified key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k |
required |
chem_prop_json_filepath
|
str
|
Path to the zipped JSON file containing MetaNetX chemical properties (MetaNetX ID to properties), without the .zip file ending. |
required |
chem_xref_json_filepath
|
str
|
Path to the zipped JSON file containing MetaNetX cross-references (External ID to MetaNetX ID), without the .zip file ending. |
required |
print_found_smiles
|
bool
|
If True, prints a message for every metabolite where a SMILES string was successfully added. |
False
|
print_not_found_smiles
|
bool
|
If True, prints a message for every metabolite where no SMILES string could be found. |
False
|
allowed_annotation_keys
|
list[str]
|
An optional list of annotation keys (e.g., 'chebi', 'bigg.metabolite') to be considered only. If empty, all existing annotation keys are checked. Note: If a metabolite has multiple eligible annotations, the very first read out annotation with MetaNetX cross-reference is used. Thereby, the first annotation key in this list has the highest precedence. (default: [], i.e. all keys are considered) |
[]
|
smiles_annotation_key
|
The key under which the SMILES string should be stored in the metabolite's annotation dictionary (default: 'smiles'). |
required |
Returns:
| Type | Description |
|---|---|
Model
|
The updated COBRA-k |
Model
|
the metabolites. |
Source code in cobrak/metanetx_functionality.py
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 | |
clean_and_compress_mnx_files(chem_prop_filepath, chem_xref_filepath, output_dir)
Cleans data from two MetaNetX TSV files (chem_prop and chem_xref) and saves the cleaned versions as compressed JSON (.json.zip) files in a specified output directory.
These cleaned versions are small enough to be stored in a GitHub repository :-) and can be directly used with COBRA-k's other MetaNetX functions to add SMILES to metabolites.
The two files can be found here (as of Dec 2, 2025): https://www.metanetx.org/mnxdoc/mnxref.html
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chem_prop_filename
|
The path to the 'chem_prop.tsv' file. |
required | |
chem_xref_filename
|
The path to the 'chem_xref.tsv' file. |
required | |
output_dir
|
str
|
The path to the directory where the cleaned, compressed files will be saved. |
required |
Source code in cobrak/metanetx_functionality.py
11 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 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 | |
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, ignored_ids=['s0001'], enz_reacs_to_keep=[])
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_enzymesto 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
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 | |
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
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 | |
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=STANDARD_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=[], ignored_enzyme_ids=['s0001'], remove_enzyme_reaction_data_if_no_kcat_set=False, sequences={}, add_molar_masses=True)
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. |
STANDARD_MAX_PROT_POOL
|
kinetic_ignored_metabolites
|
list[str]
|
Metabolites to be ignored in kinetic calculations. |
[]
|
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
|
omitted_metabolites
|
list[str]
|
Metabolites that shall not be included in the model. Their stoichiometries will be jsut deleted. Useful to e.g. delete enzyme-constraint pseudo-metabolites. Defauls to []. |
[]
|
ignored_enzyme_ids
|
list[str]
|
Enzymes that shall not be included if their ID occurs in any identifiers part. Defaults to ["s0001"], i.e. spontaneously occurring reactions. |
['s0001']
|
remove_enzyme_reaction_data_if_no_kcat_set
|
bool
|
If no \(k_{cat}\) is set for a reaction, shall its EnzymeReactionData be set to None? If False, the default EnzymeReactionData with a very high (effectively non-existing) \(k_{cat}\) is used. Defaults to False. sequences (dict[str, str], optional): Data for protein sequences |
False
|
add_molar_masses
|
bool
|
bool, default True Whether or not to calculate molar masses for all metabolites through their formula member variable |
True
|
Raises: 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
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 | |
get_cobrak_model_with_kinetic_data_from_sbml_model_alone(sbml_path, database_data_folder, brenda_version, base_species, prefer_brenda=False, use_ec_number_transfers=True, max_prot_pool=STANDARD_MAX_PROT_POOL, conc_ranges=STANDARD_CONC_RANGES, inner_to_outer_compartments=EC_INNER_TO_OUTER_COMPARTMENTS, phs=EC_PHS, pmgs=EC_PMGS, ionic_strenghts=EC_IONIC_STRENGTHS, potential_differences=EC_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=[], R=STANDARD_R, T=STANDARD_T, enzymes_to_delete=[], max_taxonomy_level=1000.0, add_hill_coefficients=True, add_protein_sequences=False, kis_and_kas_only_for_same_compartments=False, add_molar_masses=True)
Build a fully-featured :class:~cobrak.Model from an SBML file and automatically
retrieve all required kinetic and thermodynamic data from the local
database_data_folder (or download it on-the-fly if missing).
The function orchestrates a multi-step pipeline:
- Load the SBML as an un-annotated COBRApy model and optionally delete user-specified enzymes (genes) from the model.
- Prepare the external data cache – ensure that the folder structure exists, locate cached JSON files, and (re)generate missing caches.
- Parse EC-number transfers (optional) to allow cross-species mapping of enzyme identifiers.
- Create a “full-split” model where each enzyme-specific reaction variant
is represented as a separate COBRApy reaction (controlled by
do_model_fullsplit). - Collect enzyme kinetic parameters from BRENDA and SABIO-RK, optionally preferring one source over the other, and combine the two datasets.
- Fetch enzyme molecular weights from UniProt (cached for future runs).
- Optionally prune sub-optimal enzyme reactions based on the
- Compute standard Gibbs free energies (ΔG⁰) and their uncertainties using eQuilibrator, applying user-defined compartment, pH, ionic-strength, and membrane-potential settings, as well as any exclusion rules.
- Apply user-provided ΔG⁰ corrections (e.g. literature adjustments).
- Assemble the final COBRA-k model by calling
:func:
get_cobrak_model_from_sbml_and_thermokinetic_datawith all gathered data, then clean up orphaned metabolites/enzymes.
Parameters
sbml_path : str
Path to the SBML file that will be converted into a COBRA-k model.
database_data_folder : str
Root folder containing cached kinetic, thermodynamic and annotation data.
The function will create the folder if it does not exist.
brenda_version : str
Version identifier of the BRENDA JSON archive (e.g. "2023.1").
base_species : str
NCBI taxonomy identifier (or scientific name) of the organism for which
kinetic data should be retrieved.
prefer_brenda : bool, optional
If True BRENDA data are used preferentially when both BRENDA and
SABIO-RK contain information for the same reaction; otherwise SABIO-RK
is preferred. Default: False.
use_ec_number_transfers : bool, optional
Enable mapping of EC numbers between organisms using the
enzyme.rdf file from Expasy. Default: True.
max_prot_pool : float, optional
Upper bound on the total protein mass (g·gDW⁻¹) that can be allocated to
enzymes. Default: :data:STANDARD_MAX_PROT_POOL.
conc_ranges : dict[str, tuple[float, float]], optional
Log-linear concentration bounds for metabolites (in M). Keys are metabolite
IDs; the special key "DEFAULT" provides a fallback range. Default:
:data:STANDARD_CONC_RANGES.
inner_to_outer_compartments : list[str], optional
Mapping of inner to outer compartments required by eQuilibrator for
ΔG⁰ calculations. Default: :data:EC_INNER_TO_OUTER_COMPARTMENTS.
phs : dict[str, float], optional
pH values for each compartment. Default: :data:EC_PHS.
pmgs : dict[str, float], optional
Magnesium concentrations (M) for each compartment. Default: :data:EC_PMGS.
ionic_strenghts : dict[str, float], optional
Ionic strength (M) for each compartment. Default: :data:EC_IONIC_STRENGTHS.
potential_differences : dict[tuple[str, str], float], optional
Membrane potential differences (V) between compartment pairs. Default:
:data:EC_POTENTIAL_DIFFERENCES.
kinetic_ignored_enzymes : list[str], optional
Enzyme identifiers that should be ignored when extracting kinetic data.
Default: [].
custom_kms_and_kcats : dict[str, EnzymeReactionData | None], optional
User-provided kinetic parameters that override any database values.
Default: {}.
kinetic_ignored_metabolites : list[str], optional
Metabolite IDs that shall be excluded from kinetic calculations
(e.g., pseudo-metabolites). Default: [].
do_model_fullsplit : bool, optional
Whether to split reactions per enzyme before further processing.
Default: True.
do_delete_enzymatically_suboptimal_reactions : bool, optional
If True remove reactions that are not optimal with respect to the
MW/k_cat criterion. Default: True.
ignore_dG0_uncertainty : bool, optional
When True discard ΔG⁰ uncertainty values after they have been computed.
Default: True.
enzyme_conc_ranges : dict[str, tuple[float, float] | None], optional
Optional concentration bounds for enzymes (in M). None means no bound.
Default: {}.
dG0_exclusion_prefixes : list[str], optional
Reaction IDs starting with any of these prefixes are removed from the
ΔG⁰ dataset. Default: [].
dG0_exclusion_inner_parts : list[str], optional
Sub-strings that, if present anywhere in a reaction ID, cause its ΔG⁰
entry to be removed. Default: [].
dG0_corrections : dict[str, float], optional
Additive corrections (in kJ·mol⁻¹) to specific ΔG⁰ values after they have
been computed. Default: {}.
extra_linear_constraints : list[ExtraLinearConstraint], optional
Additional linear constraints (e.g., flux bounds) to be added to the model.
Default: [].
R : float, optional
Universal gas constant (kJ·mol⁻¹·K⁻¹). Default: :data:STANDARD_R.
T : float, optional
Temperature in Kelvin for thermodynamic calculations. Default:
:data:STANDARD_T.
enzymes_to_delete : list[str], optional
Gene identifiers that should be removed from the initial COBRApy model
before any further processing. Default: [].
max_taxonomy_level : float, optional
Upper bound on the NCBI taxonomy distance used when selecting kinetic
data from related organisms. Default: 1_000.0.
add_hill_coefficients : bool, optional
If True include Hill coefficients from SABIO-RK where available.
Default: True.
add_protein_sequences: bool, optional
Whether to add protein sequences or not to Enzyme instances. Default: False
kis_and_kas_only_for_same_compartments: bool, default False
If True, kis and kas can only be attributed to a reaction if the affected metabolite has
shares one of the reaction metabolite's compartments
add_molar_masses: bool, default True
Whether or not to calculate molar masses for all metabolites through their formula member variable
Returns
Model
A fully populated :class:~cobrak.Model instance containing e.g.:
* Metabolite objects with concentration bounds,
* Reaction objects with flux bounds, ΔG⁰ values, and enzyme reaction data,
* Enzyme objects with molecular weights and concentration bounds,
* Any extra linear constraints supplied by the user,
* The global protein pool constraint.
Raises
FileNotFoundError
If sbml_path does not exist or required external files (e.g.
enzyme.rdf when use_ec_number_transfers is True) are missing.
ValueError
When a required concentration range for a metabolite is not provided and
no "DEFAULT" range exists.
RuntimeError
If any of the external data retrieval steps (BRENDA, SABIO-RK,
UniProt, eQuilibrator) fail unexpectedly.
Notes
- The function heavily relies on caching to avoid repeated expensive web
queries. Cache files are stored alongside
database_data_folderwith_cache_prefixes. - The returned model is already cleaned of orphaned metabolites and enzymes
via :func:
delete_orphaned_metabolites_and_enzymes. - Users can bypass the full pipeline by providing pre-computed cache files; in that case the function will simply load the cached data.
Source code in cobrak/model_instantiation.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 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 | |
molmass_functionality
Functionality for using molmass
add_molar_masses_to_model_metabolites(model, verbose=False)
Calculates and assigns molar masses to metabolites in a Model instance.
This function iterates through all metabolites in the provided model, parses
their chemical formulas using the molmass library, and updates the
molar_mass attribute for each metabolite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
A COBRA-k Model instance. |
required |
verbose
|
bool
|
If True, prints status messages regarding missing formulas, successful calculations, or parsing errors. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Model |
Model
|
The modified model object with updated 'molar_mass' attributes. |
Raises:
| Type | Description |
|---|---|
Note
|
molmass's FormulaError (e.g. a wrong formula with unknown symbols) is handled internally |
Source code in cobrak/molmass_functionality.py
9 10 11 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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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, single_strict_reacs=[], 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 toFalseand untested!with_alpha(bool, optional): Whether to include α activation terms. Defaults toFalseand 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 (i.e. all <= heuristics become == relations). Defaults toFalse.single_strict_reacs(list[str], optional): If 'strict_mode==False', only reactions with an ID in this list are set to strict mode.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
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 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 | |
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, single_strict_reacs=[], min_mdf=STANDARD_MIN_MDF, solver=IPOPT, min_flux=0.0, with_flux_sum_var=False, correction_config=CorrectionConfig(), var_data_abs_epsilon=1e-05)
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 toFalseand untested!with_alpha(bool, optional): Whether to include α activation terms. Defaults toFalseand 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 (i.e. all <= heuristics become == relations). Defaults toFalse.single_strict_reacs(list[str], optional): If 'strict_mode==False', only reactions with an ID in this list are set to strict mode.min_mdf(float, optional): Minimum MDF value. Defaults toSTANDARD_MIN_MDF.solver_name(Solver, optional): Used NLP solver. 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().- var_data_abs_epsilon: (
float, optional): Under this value, any data given by the variability dict is considered to be 0. Defaults to 1e-5.
Returns
dict[str, float]: The optimization results.
Source code in cobrak/nlps.py
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 | |
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, single_strict_reacs=[], min_mdf=STANDARD_MIN_MDF, solver=IPOPT, do_not_delete_with_z_var_one=False, correction_config=CorrectionConfig(), var_data_abs_epsilon=1e-05)
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 toFalseand untested!with_alpha(bool, optional): Whether to include α activation terms. Defaults toFalseand 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 (i.e. all <= heuristics become == relations). Defaults toFalse.single_strict_reacs(list[str], optional): If 'strict_mode==False', only reactions with an ID in this list are set to strict mode.min_mdf(float, optional): Minimum MDF value. Defaults toSTANDARD_MIN_MDF.solver(Solver, optional): Used NLP solver. Defaults to IPOPT.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().- var_data_abs_epsilon: (
float, optional): Under this value, any data given by the variability dict is considered to be 0. Defaults to 1e-5.
Returns
dict[str, float]: The optimization results.
Source code in cobrak/nlps.py
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 | |
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, single_strict_reacs=[], 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 toFalseand untested!with_alpha(bool, optional): Whether to include α activation terms. Defaults toFalseand 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 (i.e. all <= heuristics become == relations). Defaults toFalse.single_strict_reacs(list[str], optional): If 'strict_mode==False', only reactions with an ID in this list are set to strict mode.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
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 | |
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, single_strict_reacs=[], verbose=False, solver=SCIP, with_flux_sum_var=False, correction_config=CorrectionConfig(), show_variable_count=False, var_data_abs_epsilon=1e-05)
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 toFalseand untested!with_alpha(bool, optional): Whether to include α activation terms. Defaults toFalseand 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 (i.e. all <= heuristics become == relations). Defaults toFalse.single_strict_reacs(list[str], optional): If 'strict_mode==False', only reactions with an ID in this list are set to strict mode.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().- var_data_abs_epsilon: (
float, optional): Under this value, any data given by the variability dict is considered to be 0. Defaults to 1e-5.
Returns
dict[str, float]: The optimization results.
Source code in cobrak/nlps.py
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 | |
plotting
Functions for plotting different types of data or reaction kinetics, all using matplotlib.
distinct_colors(n)
Produce n distinct Matplotlib colour specifications.
Parameters
n : int Number of colours required (must be > 0).
Returns
List[str]
A list of n colour strings. The list is deterministic:
calling distinct_colors(5) today and tomorrow returns
exactly the same five colours.
Notes
- The first 10 colours are the Tableau palettetab:orange`` …) – the same palette that Matplotlib uses for its default colour cycle.
- If
n> 10 the function continues with the CSS-4 colour dictionary, sorted by hue (HSV) so that successive colours are as dissimilar as possible * All colours are returned as hex strings (e.g.'#1f77b4') because hex codes are universally accepted by Matplotlib.
Source code in cobrak/plotting.py
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 | |
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, axistitle_labelsize=14, axisticks_labelsize=13, legend_labelsize=13, extrahlines=[])
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
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 | |
multi_step_histogram(data, *, bins=10, range_=None, density=False, labels=None, colors=None, linewidth=1.5, alpha=1.0, linestyle='-', title=None, xlabel='Value', ylabel=None, legend_loc='best', ax=None, logmode=False, **hist_kwargs)
Plot several 1-D data sets as step histograms on a single Axes.
Parameters
data : sequence of iterables
Each element is a collection of numbers (list, np.ndarray, pd.Series …).
bins : int, sequence of scalars, or str, default 10
Passed straight to np.histogram / plt.hist.
Use e.g. 'auto' or an explicit array of bin edges for full control.
range_ : (float, float), optional
Lower and upper range_ of the bins. If None the range_ is
inferred from the data.
density : bool, default False
If True, the histogram is normalized to form a probability density,
i.e. the integral of the histogram is 1.
labels : sequence of str, optional
Human-readable names for the data sets. If omitted, generic names
Dataset 0, Dataset 1 … are used.
colors : sequence of str, optional
Matplotlib colour specifications. If omitted, the default colour cycle
is used.
linewidth : float, default 1.5
Width of the step lines.
alpha : float in [0,1], default 1.0
Transparency of the lines.
linestyle : str, default '-'
Any valid matplotlib line style ('-', '--', ':' …).
title, xlabel, ylabel : str, optional
Axis titles.
legend_loc : str or None, default 'best'
Location of the legend; set to None to suppress the legend.
ax : matplotlib.axes.Axes, optional
Provide an existing Axes to plot into; otherwise a new figure/axes
pair is created.
**hist_kwargs
Additional keyword arguments forwarded to plt.hist (e.g.
log=True for a log-scale y-axis).
Returns
matplotlib.axes.Axes The Axes object containing the plot (useful for further tweaking).
Example
import numpy as np from cobrak.plotting import multi_step_histogram rng = np.random.default_rng() d1 = rng.normal(size=1000) d2 = rng.exponential(scale=2, size=1000) multi_step_histogram([d1, d2], bins=40, density=True, labels=['Normal', 'Exp'], colors=['tab:blue', 'tab:red'], title='Density step-histograms')
Source code in cobrak/plotting.py
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 | |
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: from cobrak.plotting import plot_combinations 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
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 | |
plot_objvalue_evolution(json_path, output_path, ylabel='Objective value', objvalue_multiplicator=-1.0, with_legend=False, 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
|
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
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 | |
plot_range_bars(data_captions, data_labels, data_ranges, data_colors, *, cap_len=0.2, line_width=3.0, figsize=(10, 6), title='Range.Bar Plot', ylabel='Label', xlabel='Value', ax=None, highlight_means=None, log_y=False, legend_pos=None, marker_size=80, title_labelsize=16, axes_labelsize=13, ticks_labelsize=13, legend_labelsize=11, legend_bbox_to_anchor=None, ylim=None)
Plot vertical range bars with categorical labels on the x‑axis.
Parameters
data_captions: list[str]
Labels for the legend. List length must equal the one from e.g. data_colors.
data_labels : list[str]
Labels for the x axis. The same strings are also
used as the x‑axis tick labels after alphabetical sorting.
data_ranges : list[list[tuple[float, float]]]
Outer list length = number of groups (must equal len(data_colors)).
Each inner list must have the same length as data_labels.
(low, high) defines the numeric range for the corresponding label.
data_colors : list[str]
Colour for each group; length must match the outer dimension of
data_ranges.
cap_len : float, optional
Half‑width of the horizontal caps at each end of a bar (default 0.2).
line_width : float, optional
Thickness of the vertical bars and caps (default 3.0).
figsize : tuple[float, float], optional
Figure size passed to plt.subplots (default (10, 6)).
title, ylabel, xlabel : str, optional
Plot title and axis labels.
ax : matplotlib.axes.Axes, optional
Axes to draw on; if None a new figure and axes are created.
highlight_means : list[bool] | None, optional
True for a group means that the mean of each range
(low+high)/2 is highlighted with a larger circular marker.
Length must equal len(data_ranges). If None no means are
highlighted.
log_y : bool, optional
If True the y‑axis is set to a logarithmic scale.
legend_pos: str | None, optional.
If not None, the given matplotlib legend position is used.
Returns
matplotlib.axes.Axes The axes containing the generated plot.
Raises
ValueError If the lengths of the input sequences are inconsistent.
Source code in cobrak/plotting.py
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 | |
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:
from cobrak.plotting import plot_variabilities 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
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 | |
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, major_tick_labelsize=13, minor_tick_labelsize=10, legend_labelsize=13, title_labelsize=16, extratext_labelsize=14, label_fontsize=13, labelcoords=(0, 10))
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
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 | |
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 richtables 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
249 250 251 252 253 254 255 256 257 | |
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
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 | |
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
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 | |
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
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | |
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
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 | |
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
23 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)
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: The COBRA-k Solver instance.
Returns: - SolverFactory: 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 | |
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
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
hill_entries
instance-attribute
Hill number entries
ka_entries
instance-attribute
Activation constant entries
kcat_entries
instance-attribute
Turnover number entries
ki_entries
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
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 | |
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
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 | |
__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
94 95 96 97 98 99 100 101 102 103 104 105 106 | |
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
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 | |
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
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 | |
sabio_select_enzyme_kinetic_data_for_sbml(sbml_path, 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'), add_hill_coefficients=True, kis_and_kas_only_for_same_compartments=True)
Selects enzyme kinetic data for a given SBML 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 |
|---|---|---|---|
sbml_path
|
str
|
Path to the SBML file. |
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 {}. |
{}
|
add_hill_coefficients
|
bool
|
Whether Hill coefficeints shall be collected (True) or not (False). Defaults to True. |
True
|
Returns: dict[str, EnzymeReactionData | None]: A dictionary mapping reaction IDs to enzyme kinetic data.
Source code in cobrak/sabio_rk_functionality.py
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 | |
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
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
data
instance-attribute
The optimization result
with_alpha = False
class-attribute
instance-attribute
Shall alpha values (activation terms) be shown in the spreadsheet?
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
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
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
140 141 142 143 144 145 146 147 148 149 | |
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
152 153 154 155 156 157 158 159 | |
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={}, show_regulation_coefficients=True)
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
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 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 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 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 1547 1548 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 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 1676 1677 1678 1679 1680 1681 1682 1683 | |
sum_concs(result, conc_sum_include_suffixes, conc_sum_ignore_prefixes)
Returns the exponentiated concentration of all metabolites in the result.
Source code in cobrak/spreadsheet_functionality.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
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 with the help of Tellurium.
Note: Tellurium's description language for kinetic models is called 'Antimony'.
get_tellurium_string_from_cobrak_model_and_solution(cobrak_model, cell_density, e_concs, met_concs, nlp_results)
Convert a complete COBRA‑k model and its optimisation solution into an Antimony string that can be loaded by Tellurium.
The function iterates over all reactions, skips those with negligible net
flux, and concatenates the Antimony fragments produced by
:func:_get_reaction_string_of_cobrak_reaction. After processing reactions,
it adds definitions for metabolites (either user‑provided concentrations or
concentrations inferred from the NLP solution) and the global constants
R and T.
Parameters
cobrak_model : Model
The COBRA‑k model containing reactions, metabolites, and model‑wide
parameters.
cell_density : float
Cell density (g L⁻¹) used to convert between substance‑only and molar
concentrations.
e_concs : dict[str, float]
Optional enzyme concentrations keyed by reaction ID. Missing entries
default to 1.0.
met_concs : dict[str, float]
Optional metabolite concentrations (mol L⁻¹) keyed by metabolite ID.
nlp_results : dict[str, float]
Optimisation variables returned by the NLP solver (log‑concentrations,
fluxes, etc.).
Returns
str
A complete Antimony model string ready for tellurium.loada.
Source code in cobrak/tellurium_functionality.py
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 | |
write_kinetic_sbml_model_from_cobrak_model_and_solution(sbml_path, cobrak_model, cell_density, e_concs, met_concs, nlp_results)
Export a kinetic model derived from a COBRA‑k model to an SBML file.
The function first builds an Antimony string via
:func:get_tellurium_string_from_cobrak_model_and_solution, loads it into a
Tellurium RoadRunner instance, and then writes the model to the specified
SBML file path.
Parameters
sbml_path : str
Destination file path for the SBML document (e.g. "model.xml").
cobrak_model : Model
The source COBRA‑k model.
cell_density : float
Cell density used for concentration conversions.
e_concs : dict[str, float]
Enzyme concentrations per reaction.
met_concs : dict[str, float]
Metabolite concentrations per species.
nlp_results : dict[str, float]
NLP optimisation results (log‑concentrations, fluxes, etc.).
Returns
None The function writes the SBML file as a side effect.
Source code in cobrak/tellurium_functionality.py
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 | |
thermokinetic_data_retrieval
Functions for directly retrieving thermokinetic data for and into a COBRA-k Model instance.
add_enzyme_reaction_data_to_cobrak_model(cobrak_model, enzyme_reaction_data, delete_old_enzyme_reaction_data=False, overwrite_existing_enzyme_reaction_data=True)
Insert pre‑computed :class:EnzymeReactionData objects into a model
Model The model to be updated. enzyme_reaction_data : dict[str, EnzymeReactionData] Mapping from reaction IDs to enzyme reaction data objects. delete_old_enzyme_reaction_data : bool, default False If True, remove any existing data before inserting new data. overwrite_existing_enzyme_reaction_data : bool, default True Overwrite existing data when a matching reaction ID is found.
Returns
Model The model with updated enzyme reaction data.
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
add_thermokinetic_data_to_cobrak_model(cobrak_model, mws={}, sequences={}, kcats={}, kms={}, kis={}, kas={}, dG0s={}, dG0_uncertainties={}, conc_ranges={}, delete_old_dG0s=False, overwrite_existing_dG0s=True, overwrite_existing_enzyme_reaction_data=True)
Populate a COBRA-k model with thermodynamic and kinetic parameters.
Parameters
cobrak_model : Model The model to be updated. mws : dict[str, float], optional Molecular weights for enzymes keyed by enzyme ID. sequences: dict[str, str], optional Protein sequences kcats : dict[str, float], optional kcat values keyed by reaction ID. kms : dict[str, dict[str, float]], optional Michaelis‑Menten constants keyed by reaction ID then metabolite ID. kis : dict[str, dict[str, float]], optional Inhibition constants keyed by reaction ID then metabolite ID. kas : dict[str, dict[str, float]], optional Activation constants keyed by reaction ID then metabolite ID. dG0s : dict[str, float], optional Standard Gibbs free energies keyed by reaction ID. conc_ranges : dict[str, tuple[float, float]], optional Log‑concentration bounds for metabolites keyed by metabolite ID. delete_old_dG0s : bool, default False If True, remove any existing dG0 values before adding new ones. overwrite_existing_dG0s : bool, default True Overwrite existing dG0 values when a new value is supplied. overwrite_existing_enzyme_reaction_data : bool, default True Overwrite existing enzyme reaction data when new data is supplied.
Returns
Model The updated model instance.
Source code in cobrak/thermokinetic_data_retrieval.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 | |
automatically_add_database_thermokinetic_data_to_cobrak_model(cobrak_model, database_data_path, brenda_version, base_species, do_delete_enzymatically_suboptimal_reactions=True, use_brenda=True, use_sabio_rk=True, prefer_brenda=False, use_ec_number_transfers=True, max_taxonomy_level=1000, kinetic_ignored_enzyme_ids=['s0001'], inner_to_outer_compartments=EC_INNER_TO_OUTER_COMPARTMENTS, phs=EC_PHS, pmgs=EC_PMGS, ionic_strenghts=EC_IONIC_STRENGTHS, potential_differences=EC_POTENTIAL_DIFFERENCES, calculate_multicompartmental_dG0s=True, dG0_exclusion_prefixes=[], dG0_exclusion_inner_parts=[], ignore_dG0_uncertainty=False, max_dG0_uncertainty=1000.0, add_dG0_uncertainties=True, add_hill_coefficients=True, add_protein_sequences=False, kis_and_kas_only_for_same_compartments=False, add_molar_masses=True)
Retrieve kinetic and thermodynamic data from external databases and add them to a model.
Parameters
cobrak_model : Model The model to be enriched. database_data_path : str Path to the folder containing the required database files. use_brenda : bool, default True Include BRENDA data if True. use_sabio_rk : bool, default True Include SABIO-RK data if True. prefer_brenda : bool, default True When both databases provide data, give precedence to BRENDA. use_ec_number_transfers : bool, default True Use EC-number transfer mappings when searching for data. max_taxonomy_level : int, default 1000 Maximum taxonomic distance allowed for data transfer. kinetic_ignored_enzyme_ids : list[str], default ["s0001"] Enzyme IDs to be ignored during kinetic data retrieval. add_protein_sequences: bool, default False Whether or not protein sequences shall be read out kis_and_kas_only_for_same_compartments: bool, default False If True, kis and kas can only be attributed to a reaction if the affected metabolite has shares one of the reaction metabolite's compartments add_molar_masses: bool, default True Whether or not to calculate molar masses for all metabolites through their formula member variable
Returns
Model The model populated with database-derived thermokinetic data.
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
get_database_dG0s_for_cobrak_model(cobrak_model, inner_to_outer_compartments=EC_INNER_TO_OUTER_COMPARTMENTS, phs=EC_PHS, pmgs=EC_PMGS, ionic_strenghts=EC_IONIC_STRENGTHS, potential_differences=EC_POTENTIAL_DIFFERENCES, calculate_multicompartmental=True, exclusion_prefixes=[], exclusion_inner_parts=[], ignore_uncertainty=False, max_uncertainty=1000.0)
Compute standard Gibbs free energies (and uncertainties) for all reactions in a model.
Parameters
cobrak_model : Model The model for which dG⁰ values are to be calculated. inner_to_outer_compartments : list[str], optional Mapping of inner to outer compartments for multi‑compartment calculations. phs : dict[str, float], optional pH values per compartment. pmgs : dict[str, float], optional Proton‑motives per compartment. ionic_strenghts : dict[str, float], optional Ionic strength per compartment. potential_differences : dict[str, float], optional Electrical potential differences per compartment. calculate_multicompartmental : bool, default True Whether to compute dG⁰ for reactions spanning multiple compartments. exclusion_prefixes : list[str], optional Reaction ID prefixes to exclude from calculation. exclusion_inner_parts : list[str], optional Inner compartment identifiers to exclude. ignore_uncertainty : bool, default False If True, uncertainties are not calculated. max_uncertainty : float, default 1000.0 Upper bound for acceptable uncertainty; reactions exceeding this are omitted.
Returns
tuple[dict[str, float], dict[str, float]] Two dictionaries mapping reaction IDs to dG⁰ values and to uncertainties, respectively.
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
get_database_kcats_kms_kis_and_kas_for_cobrak_model(cobrak_model, database_data_path, brenda_version, base_species, use_brenda=True, use_sabio_rk=True, prefer_brenda=False, use_ec_number_transfers=True, max_taxonomy_level=1000, kinetic_ignored_enzyme_ids=['s0001'], add_hill_coefficients=True, kis_and_kas_only_for_same_compartments=False)
Query BRENDA and/or SABIO‑RK for kinetic parameters and return (if given) a unified dataset.
Parameters
cobrak_model : Model The model for which kinetic data are required. database_data_path : str Directory containing the database files. use_brenda : bool, default True Retrieve data from BRENDA if True. use_sabio_rk : bool, default True Retrieve data from SABIO‑RK if True. prefer_brenda : bool, default False When both sources contain data for a reaction, keep BRENDA's values. use_ec_number_transfers : bool, default True Apply EC‑number transfer mappings when searching for data. max_taxonomy_level : NonNegativeInt, default 1000 Maximum allowed taxonomic distance for data transfer. kinetic_ignored_enzyme_ids : list[str], default ["s0001"] Enzyme IDs to be excluded from kinetic data retrieval. kis_and_kas_only_for_same_compartments: bool, default False If True, kis and kas can only be attributed to a reaction if the affected metabolite has shares one of the reaction metabolite's compartments
Returns
dict[str, EnzymeReactionData]
Mapping from reaction IDs to populated :class:EnzymeReactionData objects.
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
get_database_mws_for_cobrak_model(cobrak_model, base_species, database_data_path='')
Retrieve enzyme molecular weights from UniProt for a given model.
Parameters
cobrak_model : Model The model whose enzymes require molecular weights. database_data_path : str, optional Base path for caching UniProt queries (default empty string).
Returns
dict[str, float] Mapping from enzyme IDs to molecular weight values (Daltons).
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
get_database_protein_sequences_for_cobrak_model(cobrak_model, base_species, database_data_path='')
Retrieve enzyme sequences from UniProt for a given model.
Parameters
cobrak_model : Model The model whose enzymes require molecular weights. database_data_path : str, optional Base path for caching UniProt queries (default empty string).
Returns
dict[str, str] Mapping from enzyme IDs to sequences.
Source code in cobrak/thermokinetic_data_retrieval.py
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 | |
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_for_sbml(sbml_path, cache_basepath, base_species, 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
- sbml_path: str ~ The SBML's file path
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
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 | |
uniprot_get_enzyme_sequences_for_sbml(sbml_path, cache_basepath, base_species)
Returns a JSON with a mapping of protein IDs as keys, and as values the protein sequences.
The sequences are taken from UniProt (retrieved using UniProt's REST API).
Arguments
- sbml_path: str ~ The SBML's file path
Output
A JSON file with the path project_folder+project_name+'_protein_id_sequence_mapping.json' and the following structure:
{
"$PROTEIN_ID": $PROTEIN_SEQUENCE_AS_STRING,
(...),
}
Source code in cobrak/uniprot_functionality.py
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 | |
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
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 | |
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
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 | |
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), Gibbs free energy changes (ΔᵣG'°)
as well as the inhibition terms (k_I) and activation terms (k_A).
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
|
NonNegativeFloat
|
The minimum absolute error value for applying corrections. |
0.01
|
min_rel_error_value
|
NonNegativeFloat
|
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 | |
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
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 | |
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
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 | |
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
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 | |
get_df_and_efficiency_factors_sorted_lists(cobrak_model, result, min_flux=0.0)
Extracts and sorts lists of flux values (df) and κ, γ, ι, α, κ⋅γ⋅ι⋅α values from a result.
This function processes a dictionary of results of a COBRA-k optimization to extract and sort lists of flux values (df) and κ, γ, ι, α values 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-k Model object. |
required |
result
|
dict[str, float]
|
A dictionary containing optimization results. Keys are expected to start with prefixes like 'DF_VAR_PREFIX', 'KAPPA_VAR_PREFIX', and 'GAMMA_VAR_PREFIX'. |
required |
min_flux
|
NonNegativeFloat
|
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 six dictionaries: |
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, tuple[float, int]]
|
|
tuple[dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, tuple[float, int]]]
|
|
tuple[dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, tuple[float, int]]]
|
one or more of these efficiency factors is missing, the respective factor is assumed to be 1.0 |
tuple[dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, float], dict[str, tuple[float, int]]]
|
thus having no effect on the multiplied value. |
Source code in cobrak/utilities.py
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 | |
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
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 | |
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[NonNegativeFloat, list[str]]
|
dict[NonNegativeFloat, 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
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 | |
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
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 | |
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
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 | |
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
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 | |
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
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 | |
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
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 | |
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
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 | |
get_model_dG0s(cobrak_model, abs_values=False, exclude_bw_reacs=True)
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
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 | |
get_model_hill_coefficients(cobrak_model, return_only_values_with_reference=False)
Collects k_A values from a COBRA-k model.
This function iterates through the reactions in a COBRA-k model and extracts the k_A values associated with each metabolite
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[PositiveFloat]
|
A tuple containing three lists: the first list contains κ Hill coefficients, the second |
list[PositiveFloat]
|
ι Hill coefficients, the third α Hill coefficients. |
Source code in cobrak/utilities.py
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 | |
get_model_kas(cobrak_model, return_only_values_with_reference=False)
Collects k_A values from a COBRA-k model.
This function iterates through the reactions in a COBRA-k model and extracts the k_A values associated with each metabolite
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[PositiveFloat]
|
A list containing the k_A values |
Source code in cobrak/utilities.py
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 | |
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
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 | |
get_model_kis(cobrak_model, return_only_values_with_reference=False)
Collects k_I values from a COBRA-k model.
This function iterates through the reactions in a COBRA-k model and extracts the k_I values associated with each metabolite
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[PositiveFloat]
|
A list containing the k_I values |
Source code in cobrak/utilities.py
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 | |
get_model_kms(cobrak_model, return_only_values_with_reference=False)
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
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 | |
get_model_kms_by_usage(cobrak_model, return_only_values_with_reference=False)
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 |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[PositiveFloat]
|
A tuple containing two lists: the first list contains k_M values for substrates, |
list[PositiveFloat]
|
and the second list contains k_M values for products. |
Source code in cobrak/utilities.py
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 | |
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[NonNegativeFloat]
|
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
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 | |
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[PositiveFloat]
|
list[PositiveFloat]: A list of molecular weights for each enzyme in the model. |
Source code in cobrak/utilities.py
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 | |
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, ignored_enzyme_ids=['s0001'], exclude_bw_reac_ids_for_dG0s=False, verbose=False, ignore_nameparts=['diffusion'], ignore_infixes=[])
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
|
conint(ge=0, le=100)
|
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
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 1880 1881 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 1956 1957 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 | |
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, varied_reacs=[], change_unknown_values=True, change_known_values=True, use_shuffling_instead_of_uniform_random=False, use_shuffling_with_putting_back=False, shuffle_using_distribution_of_values_with_reference=True)
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
|
NonNegativeFloat | None
|
Maximum factor by which to vary Kms. Defaults to None.
No effect (except if it is None, then nothing happens) if |
None
|
max_kcat_variation
|
NonNegativeFloat | None
|
Maximum factor by which to vary k_cat. Defaults to None.
No effect (except if it is None, then nothing happens) if |
None
|
max_ki_variation
|
NonNegativeFloat | None
|
Maximum factor by which to vary k_is. Defaults to None.
No effect (except if it is None, then nothing happens) if |
None
|
max_ka_variation
|
NonNegativeFloat | None
|
Maximum factor by which to vary k_as. Defaults to None.
No effect (except if it is None, then nothing happens) if |
None
|
max_dG0_variation
|
NonNegativeFloat | None
|
Maximum factor by which to vary dG0. Defaults to None.
No effect (except if it is None, then nothing happens) if |
None
|
varied_reacs
|
list[str]
|
If not [], only reactions with IDs in this list are varied. Defaults to []. |
[]
|
change_known_values
|
bool
|
Change values if they are set with a taxonomic distance in their reference. Defaults to True. |
True
|
change_unknown_values
|
bool
|
Change values if they are not set with a taxonomic distance in their reference. Defaults to True. |
True
|
use_shuffling_instead_of_uniform_random
|
bool
|
Overwrites max variation parameters, and switches to shuffling inside the known kcats, educt kms, product kms and so on. |
False
|
shuffle_using_distribution_of_values_with_reference
|
bool
|
If True (the default), the shuffling will only
choose values with a reference for the shuffling; note that if |
True
|
Returns:
| Type | Description |
|---|---|
Model
|
A deep copy of the input model with varied reaction parameters. |
Source code in cobrak/utilities.py
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 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 2218 2219 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 2271 2272 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 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 | |
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
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 | |
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
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 | |
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
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 | |
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
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 | |
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
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 | |
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 |
NonNegativeInt
|
An integer code representing the solver status. |
Source code in cobrak/utilities.py
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 | |
get_sorted_model_dG0s(cobrak_model, abs_values=False, exclude_bw_reacs=True)
Extracts standard Gibbs free energy changes (dG0) from reactions in the model and returns them, with reaction IDs, in ascending order.
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[tuple[str, float]]
|
list[tuple[str, float]]: A list of (reac_id, dG0) values, possibly as absolute values if specified. |
Source code in cobrak/utilities.py
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 | |
get_sorted_model_kas(cobrak_model, return_only_values_with_reference=False)
Collects k_A values from a COBRA-k model, in ascending order together with associated reaction and metabolite IDs.
This function iterates through the reactions in a COBRA-k model and extracts the k_A values associated with each metabolite
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, PositiveFloat]]
|
A list containing the (reac_id, met_id, k_A) values |
Source code in cobrak/utilities.py
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 | |
get_sorted_model_kcats(cobrak_model)
Extracts k_cat values from reactions with enzyme data in the model, in ascending order together with the associated reaction ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRAk model containing reactions with enzyme data. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, float]]
|
list[tuple[str, float]]: A list of (reac_id, k_cat) values for reactions with available enzyme data. |
Source code in cobrak/utilities.py
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 | |
get_sorted_model_kis(cobrak_model, return_only_values_with_reference=False)
Collects k_I values from a COBRA-k model and returns them, with reaction and metabolite IDs, in ascending order.
This function iterates through the reactions in a COBRA-k model and extracts the k_I values associated with each metabolite
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cobrak_model
|
Model
|
The COBRA-k Model object. |
required |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, PositiveFloat]]
|
A list containing the (reac_id, k_I) values |
Source code in cobrak/utilities.py
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 | |
get_sorted_model_kms_by_usage(cobrak_model, return_only_values_with_reference=False)
Collects k_M values from a COBRA-k model, separating them into substrate and product lists, and returns them in ascending order, together with their associated metabolite and reaction IDs.
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 |
return_only_values_with_reference
|
bool
|
Returns only values with a given database reference. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, PositiveFloat]]
|
A tuple containing two lists: the first list contains tuples of (reac_id, met_id, k_m) substrates, |
list[tuple[str, str, PositiveFloat]]
|
and the second list contains the same for products. |
Source code in cobrak/utilities.py
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 | |
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
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 | |
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
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 | |
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_dictis 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
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 | |
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 |
NonNegativeFloat
|
A float code representing the termination condition. |
Source code in cobrak/utilities.py
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 | |
get_unoptimized_reactions_in_nlp_solution(cobrak_model, solution, verbose=False, regard_iota=False, regard_alpha=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
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 | |
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
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 | |
in_out_fluxes(cobrak_model, opt_dict, met_id)
Return consumption and production fluxes for a metabolite.
Parameters
cobrak_model : Model COBRA-k model instance. opt_dict : dict[str, float] Reaction‑id → optimal flux (e.g., FBA solution). met_id : str Metabolite identifier to analyse.
Returns
tuple[dict[str, float], dict[str, float]]
(cons_dict, prod_dict) where each maps reaction ids to the absolute
flux contributed to consumption (negative stoichiometry) or production
(positive stoichiometry) of met_id. All is returned as absolute values.
Source code in cobrak/utilities.py
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 | |
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
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 | |
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
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 | |
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
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 | |
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
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 | |
parse_external_resources(path, brenda_version, parse_brenda=True)
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
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 | |
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
3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 | |
sort_dict_keys(dictionary, reverse=False)
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[T, U]
|
A new dictionary with the keys sorted alphabetically. |
Source code in cobrak/utilities.py
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 | |
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
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 | |