-
Notifications
You must be signed in to change notification settings - Fork 3
/
fit_sim_data_1.py
4430 lines (3735 loc) · 172 KB
/
fit_sim_data_1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
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
"""
The parca, aka parameter calculator.
TODO: establish a controlled language for function behaviors (i.e. create* set* fit*)
TODO: functionalize so that values are not both set and returned from some methods
"""
import binascii
import functools
import itertools
import os
import pickle
import time
import traceback
from typing import Callable
from stochastic_arrow import StochasticSystem
from cvxpy import Variable, Problem, Minimize, norm
import numpy as np
import scipy.optimize
import scipy.sparse
from ecoli.library.initial_conditions import create_bulk_container
from ecoli.library.schema import bulk_name_to_idx, counts
from reconstruction.ecoli.simulation_data import SimulationDataEcoli
from wholecell.utils import filepath, parallelization, units
from wholecell.utils.fitting import normalize, masses_and_counts_for_homeostatic_target
# Fitting parameters
# NOTE: This threshold is arbitrary and was relaxed from 1e-9
# to 1e-8 to fix failure to converge after scipy/scipy#20168
FITNESS_THRESHOLD = 1e-8
MAX_FITTING_ITERATIONS = 150
N_SEEDS = 10
# Parameters used in fitPromoterBoundProbability()
PROMOTER_PDIFF_THRESHOLD = 0.06 # Minimum difference between binding probabilities of a TF in conditions where TF is active and inactive
PROMOTER_REG_COEFF = 1e-3 # Optimization weight on how much probability should stay close to original values
PROMOTER_SCALING = 10 # Multiplied to all matrices for numerical stability
PROMOTER_NORM_TYPE = 1 # Matrix 1-norm
PROMOTER_MAX_ITERATIONS = 100
PROMOTER_CONVERGENCE_THRESHOLD = 1e-9
ECOS_0_TOLERANCE = 1e-10 # Tolerance to adjust solver output to 0
BASAL_EXPRESSION_CONDITION = "M9 Glucose minus AAs"
VERBOSE = 1
COUNTS_UNITS = units.dmol
VOLUME_UNITS = units.L
MASS_UNITS = units.g
TIME_UNITS = units.s
functions_run = []
def fitSimData_1(raw_data, **kwargs):
"""
Fits parameters necessary for the simulation based on the knowledge base
Inputs:
raw_data (KnowledgeBaseEcoli) - knowledge base consisting of the
necessary raw data
cpus (int) - number of processes to use (if > 1, use multiprocessing)
debug (bool) - if True, fit only one arbitrarily-chosen transcription
factor in order to speed up a debug cycle (should not be used for
an actual simulation)
save_intermediates (bool) - if True, save the state (sim_data and cell_specs)
to disk in intermediates_directory after each Parca step
intermediates_directory (str) - path to the directory to save intermediate
sim_data and cell_specs files to
load_intermediate (str) - the function name of the Parca step to load
sim_data and cell_specs from; functions prior to and including this
will be skipped but all following functions will run
variable_elongation_transcription (bool) - enable variable elongation
for transcription
variable_elongation_translation (bool) - enable variable elongation for
translation
disable_ribosome_capacity_fitting (bool) - if True, ribosome expression
is not fit to protein synthesis demands
disable_rnapoly_capacity_fitting (bool) - if True, RNA polymerase
expression is not fit to protein synthesis demands
"""
sim_data = SimulationDataEcoli()
cell_specs = {}
# Functions to modify sim_data and/or cell_specs
# Functions defined below should be wrapped by @save_state to allow saving
# and loading sim_data and cell_specs to skip certain functions while doing
# development for faster testing and iteration of later functions that
# might not need earlier functions to be rerun each time.
sim_data, cell_specs = initialize(sim_data, cell_specs, raw_data=raw_data, **kwargs)
sim_data, cell_specs = input_adjustments(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = basal_specs(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = tf_condition_specs(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = fit_condition(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = promoter_binding(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = adjust_promoters(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = set_conditions(sim_data, cell_specs, **kwargs)
sim_data, cell_specs = final_adjustments(sim_data, cell_specs, **kwargs)
if sim_data is None:
raise ValueError(
'sim_data is not specified. Check that the'
f' load_intermediate function ({kwargs.get("load_intermediate")})'
' is correct and matches a function to be run.'
)
return sim_data
def save_state(func):
"""
Wrapper for functions called in fitSimData_1() to allow saving and loading
of sim_data and cell_specs at different points in the parameter calculation
pipeline. This is useful for development in order to skip time intensive
steps that are not required to recalculate in order to work with the desired
stage of parameter calculation.
This wrapper expects arguments in the kwargs passed into a wrapped function:
save_intermediates (bool): if True, the state (sim_data and cell_specs)
will be saved to disk in intermediates_directory
intermediates_directory (str): path to the directory to save intermediate
sim_data and cell_specs files to
load_intermediate (str): the name of the function to load sim_data and
cell_specs from, functions prior to and including this will be
skipped but all following functions will run
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
func_name = func.__name__
load_intermediate = kwargs.get("load_intermediate")
intermediates_dir = kwargs.get("intermediates_directory", "")
# Files to save to or load from
sim_data_file = os.path.join(intermediates_dir, f"sim_data_{func_name}.cPickle")
cell_specs_file = os.path.join(
intermediates_dir, f"cell_specs_{func_name}.cPickle"
)
# Run the wrapped function if the function to load is not specified or was already loaded
if load_intermediate is None or load_intermediate in functions_run:
start = time.time()
sim_data, cell_specs = func(*args, **kwargs)
end = time.time()
print(f"Ran {func_name} in {end - start:.0f} s")
# Load the saved results from the wrapped function if it is set to be loaded
elif load_intermediate == func_name:
if not os.path.exists(sim_data_file) or not os.path.exists(cell_specs_file):
raise IOError(
f"Could not find intermediate files ({sim_data_file}"
f" or {cell_specs_file}) to load. Make sure to save intermediates"
" before trying to load them."
)
with open(sim_data_file, "rb") as f:
sim_data = pickle.load(f)
with open(cell_specs_file, "rb") as f:
cell_specs = pickle.load(f)
print(f"Loaded sim_data and cell_specs for {func_name}")
# Skip running or loading if a later function will be loaded
else:
print(f"Skipped {func_name}")
sim_data = None
cell_specs = {}
# Save the current state of the parameter calculator after the function to disk
if (
kwargs.get("save_intermediates", False)
and intermediates_dir != ""
and sim_data is not None
):
os.makedirs(intermediates_dir, exist_ok=True)
with open(sim_data_file, "wb") as f:
pickle.dump(sim_data, f, protocol=pickle.HIGHEST_PROTOCOL)
with open(cell_specs_file, "wb") as f:
pickle.dump(cell_specs, f, protocol=pickle.HIGHEST_PROTOCOL)
print(f"Saved data for {func_name}")
# Record which functions have been run to know if the loaded function has run
functions_run.append(func_name)
return sim_data, cell_specs
return wrapper
@save_state
def initialize(sim_data, cell_specs, raw_data=None, **kwargs):
sim_data.initialize(
raw_data=raw_data,
basal_expression_condition=BASAL_EXPRESSION_CONDITION,
)
return sim_data, cell_specs
@save_state
def input_adjustments(sim_data, cell_specs, debug=False, **kwargs):
# Limit the number of conditions that are being fit so that execution time decreases
if debug:
print(
"Warning: Running the Parca in debug mode - not all conditions will be fit"
)
key = list(sim_data.tf_to_active_inactive_conditions.keys())[0]
sim_data.tf_to_active_inactive_conditions = {
key: sim_data.tf_to_active_inactive_conditions[key]
}
# Make adjustments for metabolic enzymes
setTranslationEfficiencies(sim_data)
set_balanced_translation_efficiencies(sim_data)
setRNAExpression(sim_data)
setRNADegRates(sim_data)
setProteinDegRates(sim_data)
return sim_data, cell_specs
@save_state
def basal_specs(
sim_data,
cell_specs,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
variable_elongation_transcription=True,
variable_elongation_translation=False,
**kwargs,
):
cell_specs = buildBasalCellSpecifications(
sim_data,
variable_elongation_transcription,
variable_elongation_translation,
disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting,
)
# Set expression based on ppGpp regulation from basal expression
sim_data.process.transcription.set_ppgpp_expression(sim_data)
# TODO (Travis): use ppGpp expression in condition fitting
# Modify other properties
# Compute Km's
Km = setKmCooperativeEndoRNonLinearRNAdecay(
sim_data, cell_specs["basal"]["bulkContainer"]
)
n_transcribed_rnas = len(sim_data.process.transcription.rna_data)
sim_data.process.transcription.rna_data["Km_endoRNase"] = Km[:n_transcribed_rnas]
sim_data.process.transcription.mature_rna_data["Km_endoRNase"] = Km[
n_transcribed_rnas:
]
## Calculate and set maintenance values
# ----- Growth associated maintenance -----
fitMaintenanceCosts(sim_data, cell_specs["basal"]["bulkContainer"])
return sim_data, cell_specs
@save_state
def tf_condition_specs(
sim_data,
cell_specs,
cpus=1,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
variable_elongation_transcription=True,
variable_elongation_translation=False,
**kwargs,
):
# Limit the number of CPUs before printing it to stdout.
cpus = parallelization.cpus(cpus)
# Apply updates to cell_specs from buildTfConditionCellSpecifications for each TF condition
conditions = list(sorted(sim_data.tf_to_active_inactive_conditions))
args = [
(
sim_data,
tf,
variable_elongation_transcription,
variable_elongation_translation,
disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting,
)
for tf in conditions
]
apply_updates(
buildTfConditionCellSpecifications, args, conditions, cell_specs, cpus
)
for conditionKey in cell_specs:
if conditionKey == "basal":
continue
sim_data.process.transcription.rna_expression[conditionKey] = cell_specs[
conditionKey
]["expression"]
sim_data.process.transcription.rna_synth_prob[conditionKey] = cell_specs[
conditionKey
]["synthProb"]
sim_data.process.transcription.cistron_expression[conditionKey] = cell_specs[
conditionKey
]["cistron_expression"]
sim_data.process.transcription.fit_cistron_expression[conditionKey] = (
cell_specs[conditionKey]["fit_cistron_expression"]
)
buildCombinedConditionCellSpecifications(
sim_data,
cell_specs,
variable_elongation_transcription,
variable_elongation_translation,
disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting,
)
return sim_data, cell_specs
@save_state
def fit_condition(sim_data, cell_specs, cpus=1, **kwargs):
# Apply updates from fitCondition to cell_specs for each fit condition
conditions = list(sorted(cell_specs))
args = [(sim_data, cell_specs[condition], condition) for condition in conditions]
apply_updates(fitCondition, args, conditions, cell_specs, cpus)
for condition_label in sorted(cell_specs):
nutrients = sim_data.conditions[condition_label]["nutrients"]
if nutrients not in sim_data.translation_supply_rate:
sim_data.translation_supply_rate[nutrients] = cell_specs[condition_label][
"translation_aa_supply"
]
return sim_data, cell_specs
@save_state
def promoter_binding(sim_data, cell_specs, **kwargs):
if VERBOSE > 0:
print("Fitting promoter binding")
# noinspection PyTypeChecker
fitPromoterBoundProbability(sim_data, cell_specs)
return sim_data, cell_specs
@save_state
def adjust_promoters(sim_data, cell_specs, **kwargs):
# noinspection PyTypeChecker
fitLigandConcentrations(sim_data, cell_specs)
calculateRnapRecruitment(sim_data, cell_specs)
return sim_data, cell_specs
@save_state
def set_conditions(sim_data, cell_specs, **kwargs):
sim_data.process.transcription.rnaSynthProbFraction = {}
sim_data.process.transcription.rnapFractionActiveDict = {}
sim_data.process.transcription.rnaSynthProbRProtein = {}
sim_data.process.transcription.rnaSynthProbRnaPolymerase = {}
sim_data.process.transcription.rnaPolymeraseElongationRateDict = {}
sim_data.expectedDryMassIncreaseDict = {}
sim_data.process.translation.ribosomeElongationRateDict = {}
sim_data.process.translation.ribosomeFractionActiveDict = {}
for condition_label in sorted(cell_specs):
condition = sim_data.conditions[condition_label]
nutrients = condition["nutrients"]
if VERBOSE > 0:
print("Updating mass in condition {}".format(condition_label))
spec = cell_specs[condition_label]
concDict = sim_data.process.metabolism.concentration_updates.concentrations_based_on_nutrients(
media_id=nutrients
)
concDict.update(
sim_data.mass.getBiomassAsConcentrations(
sim_data.condition_to_doubling_time[condition_label]
)
)
avgCellDryMassInit, fitAvgSolublePoolMass = rescaleMassForSolubleMetabolites(
sim_data,
spec["bulkContainer"],
concDict,
sim_data.condition_to_doubling_time[condition_label],
)
if VERBOSE > 0:
print("{} to {}".format(spec["avgCellDryMassInit"], avgCellDryMassInit))
spec["avgCellDryMassInit"] = avgCellDryMassInit
spec["fitAvgSolublePoolMass"] = fitAvgSolublePoolMass
mRnaSynthProb = sim_data.process.transcription.rna_synth_prob[condition_label][
sim_data.process.transcription.rna_data["is_mRNA"]
].sum()
tRnaSynthProb = sim_data.process.transcription.rna_synth_prob[condition_label][
sim_data.process.transcription.rna_data["is_tRNA"]
].sum()
rRnaSynthProb = sim_data.process.transcription.rna_synth_prob[condition_label][
sim_data.process.transcription.rna_data["is_rRNA"]
].sum()
if len(condition["perturbations"]) == 0:
if nutrients not in sim_data.process.transcription.rnaSynthProbFraction:
sim_data.process.transcription.rnaSynthProbFraction[nutrients] = {
"mRna": mRnaSynthProb,
"tRna": tRnaSynthProb,
"rRna": rRnaSynthProb,
}
if nutrients not in sim_data.process.transcription.rnaSynthProbRProtein:
prob = sim_data.process.transcription.rna_synth_prob[condition_label][
sim_data.process.transcription.rna_data[
"includes_ribosomal_protein"
]
]
sim_data.process.transcription.rnaSynthProbRProtein[nutrients] = prob
if (
nutrients
not in sim_data.process.transcription.rnaSynthProbRnaPolymerase
):
prob = sim_data.process.transcription.rna_synth_prob[condition_label][
sim_data.process.transcription.rna_data["includes_RNAP"]
]
sim_data.process.transcription.rnaSynthProbRnaPolymerase[nutrients] = (
prob
)
if nutrients not in sim_data.process.transcription.rnapFractionActiveDict:
frac = sim_data.growth_rate_parameters.get_fraction_active_rnap(
spec["doubling_time"]
)
sim_data.process.transcription.rnapFractionActiveDict[nutrients] = frac
if (
nutrients
not in sim_data.process.transcription.rnaPolymeraseElongationRateDict
):
rate = sim_data.growth_rate_parameters.get_rnap_elongation_rate(
spec["doubling_time"]
)
sim_data.process.transcription.rnaPolymeraseElongationRateDict[
nutrients
] = rate
if nutrients not in sim_data.expectedDryMassIncreaseDict:
sim_data.expectedDryMassIncreaseDict[nutrients] = spec[
"avgCellDryMassInit"
]
if nutrients not in sim_data.process.translation.ribosomeElongationRateDict:
rate = sim_data.growth_rate_parameters.get_ribosome_elongation_rate(
spec["doubling_time"]
)
sim_data.process.translation.ribosomeElongationRateDict[nutrients] = (
rate
)
if nutrients not in sim_data.process.translation.ribosomeFractionActiveDict:
frac = sim_data.growth_rate_parameters.get_fraction_active_ribosome(
spec["doubling_time"]
)
sim_data.process.translation.ribosomeFractionActiveDict[nutrients] = (
frac
)
return sim_data, cell_specs
@save_state
def final_adjustments(sim_data, cell_specs, **kwargs):
# Adjust expression for RNA attenuation
sim_data.process.transcription.calculate_attenuation(sim_data, cell_specs)
# Adjust ppGpp regulated expression after conditions have been fit for physiological constraints
sim_data.process.transcription.adjust_polymerizing_ppgpp_expression(sim_data)
sim_data.process.transcription.adjust_ppgpp_expression_for_tfs(sim_data)
# Set supply constants for amino acids based on condition supply requirements
average_basal_container = create_bulk_container(sim_data, n_seeds=5)
average_with_aa_container = create_bulk_container(
sim_data, condition="with_aa", n_seeds=5
)
sim_data.process.metabolism.set_phenomological_supply_constants(sim_data)
sim_data.process.metabolism.set_mechanistic_supply_constants(
sim_data, cell_specs, average_basal_container, average_with_aa_container
)
sim_data.process.metabolism.set_mechanistic_export_constants(
sim_data, cell_specs, average_basal_container
)
sim_data.process.metabolism.set_mechanistic_uptake_constants(
sim_data, cell_specs, average_with_aa_container
)
# Set ppGpp reaction parameters
sim_data.process.transcription.set_ppgpp_kinetics_parameters(
average_basal_container, sim_data.constants
)
return sim_data, cell_specs
def apply_updates(
func: Callable[..., dict],
args: list[tuple],
labels: list[str],
dest: dict,
cpus: int,
):
"""
Use multiprocessing (if cpus > 1) to apply args to a function to get
dictionary updates for a destination dictionary.
Args:
func: function to call with args
args: list of args to apply to func
labels: label for each set of args for exception information
dest: destination dictionary that will be updated with results
from each function call
cpus: number of cpus to use
"""
if cpus > 1:
print("Starting {} Parca processes".format(cpus))
# Apply args to func
pool = parallelization.pool(cpus)
results = {label: pool.apply_async(func, a) for label, a in zip(labels, args)}
pool.close()
pool.join()
# Check results from function calls and update dest
failed = []
for label, result in results.items():
if result.successful():
dest.update(result.get())
else:
# noinspection PyBroadException
try:
result.get()
except Exception:
traceback.print_exc()
failed.append(label)
# Cleanup
if failed:
raise RuntimeError(
"Error(s) raised for {} while using multiple processes".format(
", ".join(failed)
)
)
pool = None
print("End parallel processing")
else:
for a in args:
dest.update(func(*a))
def buildBasalCellSpecifications(
sim_data,
variable_elongation_transcription=True,
variable_elongation_translation=False,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
):
"""
Creates cell specifications for the basal condition by fitting expression.
Relies on expressionConverge() to set the expression and update masses.
Inputs
------
- disable_ribosome_capacity_fitting (bool) - if True, ribosome expression
is not fit
- disable_rnapoly_capacity_fitting (bool) - if True, RNA polymerase
expression is not fit
Requires
--------
- Metabolite concentrations based on 'minimal' nutrients
- 'basal' RNA expression
- 'basal' doubling time
Modifies
--------
- Average mass values of the cell
- cistron expression
- RNA expression and synthesis probabilities
Returns
--------
- dict {'basal': dict} with the following keys in the dict from key 'basal':
'concDict' {metabolite_name (str): concentration (float with units)} -
dictionary of concentrations for each metabolite with a concentration
'fit_cistron_expression' (array of floats) - hypothetical expression for
each RNA cistron post-fit, total normalized to 1, if all
transcription units were monocistronic
'expression' (array of floats) - expression for each RNA, total normalized to 1
'doubling_time' (float with units) - cell doubling time
'synthProb' (array of floats) - synthesis probability for each RNA,
total normalized to 1
'avgCellDryMassInit' (float with units) - average initial cell dry mass
'fitAvgSolubleTargetMolMass' (float with units) - the adjusted dry mass
of the soluble fraction of a cell
- bulkContainer (np.ndarray object) - Two columns: 'id' for name and 'count'
for expected counts based on expression of all bulk molecules
Notes
-----
- TODO - sets sim_data attributes and returns values - change to only return values
"""
# Create dictionary for basal condition
cell_specs = {}
cell_specs["basal"] = {
"concDict": sim_data.process.metabolism.concentration_updates.concentrations_based_on_nutrients(
media_id="minimal"
),
"expression": sim_data.process.transcription.rna_expression["basal"].copy(),
"doubling_time": sim_data.condition_to_doubling_time["basal"],
}
# Determine expression and synthesis probabilities
(
expression,
synthProb,
fit_cistron_expression,
avgCellDryMassInit,
fitAvgSolubleTargetMolMass,
bulkContainer,
_,
) = expressionConverge(
sim_data,
cell_specs["basal"]["expression"],
cell_specs["basal"]["concDict"],
cell_specs["basal"]["doubling_time"],
conditionKey="basal",
variable_elongation_transcription=variable_elongation_transcription,
variable_elongation_translation=variable_elongation_translation,
disable_ribosome_capacity_fitting=disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting=disable_rnapoly_capacity_fitting,
)
# Store calculated values
cell_specs["basal"]["expression"] = expression
cell_specs["basal"]["synthProb"] = synthProb
cell_specs["basal"]["fit_cistron_expression"] = fit_cistron_expression
cell_specs["basal"]["avgCellDryMassInit"] = avgCellDryMassInit
cell_specs["basal"]["fitAvgSolubleTargetMolMass"] = fitAvgSolubleTargetMolMass
cell_specs["basal"]["bulkContainer"] = bulkContainer
# Modify sim_data mass
sim_data.mass.avg_cell_dry_mass_init = avgCellDryMassInit
sim_data.mass.avg_cell_dry_mass = (
sim_data.mass.avg_cell_dry_mass_init
* sim_data.mass.avg_cell_to_initial_cell_conversion_factor
)
sim_data.mass.avg_cell_water_mass_init = (
sim_data.mass.avg_cell_dry_mass_init
/ sim_data.mass.cell_dry_mass_fraction
* sim_data.mass.cell_water_mass_fraction
)
sim_data.mass.fitAvgSolubleTargetMolMass = fitAvgSolubleTargetMolMass
# Modify sim_data expression
sim_data.process.transcription.rna_expression["basal"][:] = cell_specs["basal"][
"expression"
]
sim_data.process.transcription.rna_synth_prob["basal"][:] = cell_specs["basal"][
"synthProb"
]
sim_data.process.transcription.fit_cistron_expression["basal"] = cell_specs[
"basal"
]["fit_cistron_expression"]
return cell_specs
def buildTfConditionCellSpecifications(
sim_data,
tf,
variable_elongation_transcription=True,
variable_elongation_translation=False,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
):
"""
Creates cell specifications for a given transcription factor by
fitting expression. Will set for the active and inactive TF condition.
Relies on expressionConverge() to set the expression and masses.
Uses fold change data relative to the 'basal' condition to determine
expression for a given TF.
Inputs
------
- tf (str) - label for the transcription factor to fit (eg. 'CPLX-125')
- disable_ribosome_capacity_fitting (bool) - if True, ribosome expression
is not fit
- disable_rnapoly_capacity_fitting (bool) - if True, RNA polymerase
expression is not fit
Requires
--------
- Metabolite concentrations based on nutrients for the TF
- Adjusted 'basal' cistron expression
- Doubling time for the TF
- Fold changes in expression for each gene given the TF
Returns
--------
- dict {tf + '__active'/'__inactive': dict} with the following keys in each dict:
'concDict' {metabolite_name (str): concentration (float with units)} -
dictionary of concentrations for each metabolite with a concentration
'expression' (array of floats) - expression for each RNA, total normalized to 1
'doubling_time' (float with units) - cell doubling time
'synthProb' (array of floats) - synthesis probability for each RNA,
total normalized to 1
'cistron_expression' (array of floats) - hypothetical expression for
each RNA cistron, calculated from basal cistron expression levels
and fold change data
'fit_cistron_expression' (array of floats) - hypothetical expression for
each RNA cistron post-fit, total normalized to 1, if all
transcription units were monocistronic
'avgCellDryMassInit' (float with units) - average initial cell dry mass
'fitAvgSolubleTargetMolMass' (float with units) - the adjusted dry mass
of the soluble fraction of a cell
- bulkContainer (np.ndarray object) - Two columns: 'id' for name and 'count'
for expected counts based on expression of all bulk molecules
"""
cell_specs = {}
for choice in ["__active", "__inactive"]:
conditionKey = tf + choice
conditionValue = sim_data.conditions[conditionKey]
# Get expression for the condition based on fold changes over 'basal'
# condition if the condition is not the same as 'basal'
fcData = {}
if choice == "__active" and conditionValue != sim_data.conditions["basal"]:
fcData = sim_data.tf_to_fold_change[tf]
if choice == "__inactive" and conditionValue != sim_data.conditions["basal"]:
fcDataTmp = sim_data.tf_to_fold_change[tf].copy()
for key, value in fcDataTmp.items():
fcData[key] = 1.0 / value
expression, cistron_expression = expressionFromConditionAndFoldChange(
sim_data.process.transcription,
conditionValue["perturbations"],
fcData,
)
# Get metabolite concentrations for the condition
concDict = sim_data.process.metabolism.concentration_updates.concentrations_based_on_nutrients(
media_id=conditionValue["nutrients"]
)
concDict.update(
sim_data.mass.getBiomassAsConcentrations(
sim_data.condition_to_doubling_time[conditionKey]
)
)
# Create dictionary for the condition
cell_specs[conditionKey] = {
"concDict": concDict,
"expression": expression,
"doubling_time": sim_data.condition_to_doubling_time.get(
conditionKey, sim_data.condition_to_doubling_time["basal"]
),
}
# Determine expression and synthesis probabilities
(
expression,
synthProb,
fit_cistron_expression,
avgCellDryMassInit,
fitAvgSolubleTargetMolMass,
bulkContainer,
concDict,
) = expressionConverge(
sim_data,
cell_specs[conditionKey]["expression"],
cell_specs[conditionKey]["concDict"],
cell_specs[conditionKey]["doubling_time"],
sim_data.process.transcription.rna_data["Km_endoRNase"],
conditionKey=conditionKey,
variable_elongation_transcription=variable_elongation_transcription,
variable_elongation_translation=variable_elongation_translation,
disable_ribosome_capacity_fitting=disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting=disable_rnapoly_capacity_fitting,
)
# Store calculated values
cell_specs[conditionKey]["expression"] = expression
cell_specs[conditionKey]["synthProb"] = synthProb
cell_specs[conditionKey]["cistron_expression"] = cistron_expression
cell_specs[conditionKey]["fit_cistron_expression"] = fit_cistron_expression
cell_specs[conditionKey]["avgCellDryMassInit"] = avgCellDryMassInit
cell_specs[conditionKey]["fitAvgSolubleTargetMolMass"] = (
fitAvgSolubleTargetMolMass
)
cell_specs[conditionKey]["bulkContainer"] = bulkContainer
return cell_specs
def buildCombinedConditionCellSpecifications(
sim_data,
cell_specs,
variable_elongation_transcription=True,
variable_elongation_translation=False,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
):
"""
Creates cell specifications for sets of transcription factors being active.
These sets include conditions like 'with_aa' or 'no_oxygen' where multiple
transcription factors will be active at the same time.
Inputs
------
- cell_specs {condition (str): dict} - information about each individual
transcription factor condition
- disable_ribosome_capacity_fitting (bool) - if True, ribosome expression
is not fit
- disable_rnapoly_capacity_fitting (bool) - if True, RNA polymerase
expression is not fit
Requires
--------
- Metabolite concentrations based on nutrients for the condition
- Adjusted 'basal' RNA expression
- Doubling time for the combined condition
- Fold changes in expression for each gene given the TF
Modifies
--------
- cell_specs dictionary for each combined condition
- RNA expression and synthesis probabilities for each combined condition
Notes
-----
- TODO - determine how to handle fold changes when multiple TFs change the
same gene because multiplying both fold changes together might not be
appropriate
"""
for conditionKey in sim_data.condition_active_tfs:
# Skip adjustments if 'basal' condition
if conditionKey == "basal":
continue
# Get expression from fold changes for each TF in the given condition
fcData = {}
conditionValue = sim_data.conditions[conditionKey]
for tf in sim_data.condition_active_tfs[conditionKey]:
for gene, fc in sim_data.tf_to_fold_change[tf].items():
fcData[gene] = fcData.get(gene, 1) * fc
for tf in sim_data.condition_inactive_tfs[conditionKey]:
for gene, fc in sim_data.tf_to_fold_change[tf].items():
fcData[gene] = fcData.get(gene, 1) / fc
expression, cistron_expression = expressionFromConditionAndFoldChange(
sim_data.process.transcription,
conditionValue["perturbations"],
fcData,
)
# Get metabolite concentrations for the condition
concDict = sim_data.process.metabolism.concentration_updates.concentrations_based_on_nutrients(
media_id=conditionValue["nutrients"]
)
concDict.update(
sim_data.mass.getBiomassAsConcentrations(
sim_data.condition_to_doubling_time[conditionKey]
)
)
# Create dictionary for the condition
cell_specs[conditionKey] = {
"concDict": concDict,
"expression": expression,
"doubling_time": sim_data.condition_to_doubling_time.get(
conditionKey, sim_data.condition_to_doubling_time["basal"]
),
}
# Determine expression and synthesis probabilities
(
expression,
synthProb,
fit_cistron_expression,
avgCellDryMassInit,
fitAvgSolubleTargetMolMass,
bulkContainer,
concDict,
) = expressionConverge(
sim_data,
cell_specs[conditionKey]["expression"],
cell_specs[conditionKey]["concDict"],
cell_specs[conditionKey]["doubling_time"],
sim_data.process.transcription.rna_data["Km_endoRNase"],
conditionKey=conditionKey,
variable_elongation_transcription=variable_elongation_transcription,
variable_elongation_translation=variable_elongation_translation,
disable_ribosome_capacity_fitting=disable_ribosome_capacity_fitting,
disable_rnapoly_capacity_fitting=disable_rnapoly_capacity_fitting,
)
# Modify cell_specs for calculated values
cell_specs[conditionKey]["expression"] = expression
cell_specs[conditionKey]["synthProb"] = synthProb
cell_specs[conditionKey]["cistron_expression"] = cistron_expression
cell_specs[conditionKey]["fit_cistron_expression"] = fit_cistron_expression
cell_specs[conditionKey]["avgCellDryMassInit"] = avgCellDryMassInit
cell_specs[conditionKey]["fitAvgSolubleTargetMolMass"] = (
fitAvgSolubleTargetMolMass
)
cell_specs[conditionKey]["bulkContainer"] = bulkContainer
# Modify sim_data expression
sim_data.process.transcription.rna_expression[conditionKey] = cell_specs[
conditionKey
]["expression"]
sim_data.process.transcription.rna_synth_prob[conditionKey] = cell_specs[
conditionKey
]["synthProb"]
sim_data.process.transcription.cistron_expression[conditionKey] = cell_specs[
conditionKey
]["cistron_expression"]
sim_data.process.transcription.fit_cistron_expression[conditionKey] = (
cell_specs[conditionKey]["fit_cistron_expression"]
)
def expressionConverge(
sim_data,
expression,
concDict,
doubling_time,
Km=None,
conditionKey=None,
variable_elongation_transcription=True,
variable_elongation_translation=False,
disable_ribosome_capacity_fitting=False,
disable_rnapoly_capacity_fitting=False,
):
"""
Iteratively fits synthesis probabilities for RNA. Calculates initial
expression based on gene expression data and makes adjustments to match
physiological constraints for ribosome and RNAP counts. Relies on
fitExpression() to converge
Inputs
------
- expression (array of floats) - expression for each RNA, normalized to 1
- concDict {metabolite (str): concentration (float with units of mol/volume)} -
dictionary for concentrations of each metabolite with location tag
- doubling_time (float with units of time) - doubling time
- Km (array of floats with units of mol/volume) - Km for each RNA associated
with RNases
- disable_ribosome_capacity_fitting (bool) - if True, ribosome expression
is not fit
- disable_rnapoly_capacity_fitting (bool) - if True, RNA polymerase
expression is not fit
Requires
--------
- MAX_FITTING_ITERATIONS (int) - number of iterations to adjust expression
before an exception is raised
- FITNESS_THRESHOLD (float) - acceptable change from one iteration to break
the fitting loop
Returns
--------
- expression (array of floats) - adjusted expression for each RNA,
normalized to 1
- synthProb (array of floats) - synthesis probability for each RNA which
accounts for expression and degradation rate, normalized to 1
- avgCellDryMassInit (float with units of mass) - expected initial dry cell mass
- fitAvgSolubleTargetMolMass (float with units of mass) - the adjusted dry mass
of the soluble fraction of a cell
- bulkContainer (np.ndarray object) - Two columns: 'id' for name and 'count'
for expected counts based on expression of all bulk molecules
"""
if VERBOSE > 0:
print(
f"Fitting RNA synthesis probabilities for condition {conditionKey} ...",
end="",
)
for iteration in range(MAX_FITTING_ITERATIONS):
if VERBOSE > 1:
print("Iteration: {}".format(iteration))