-
Notifications
You must be signed in to change notification settings - Fork 3
/
polypeptide_elongation.py
2530 lines (2304 loc) · 92.8 KB
/
polypeptide_elongation.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
"""
======================
Polypeptide Elongation
======================
This process models the polymerization of amino acids into polypeptides
by ribosomes using an mRNA transcript as a template. Elongation terminates
once a ribosome has reached the end of an mRNA transcript. Polymerization
occurs across all ribosomes simultaneously and resources are allocated to
maximize the progress of all ribosomes within the limits of the maximum ribosome
elongation rate, available amino acids and GTP, and the length of the transcript.
"""
from typing import Any, Callable, Optional, Tuple
from numba import njit
import numpy as np
import numpy.typing as npt
from scipy.integrate import solve_ivp
from unum import Unum
# wcEcoli imports
from wholecell.utils.polymerize import buildSequences, polymerize, computeMassIncrease
from wholecell.utils.random import stochasticRound
from wholecell.utils import units
# vivarium imports
from vivarium.core.composition import simulate_process
from vivarium.library.dict_utils import deep_merge
from vivarium.library.units import units as vivunits
from vivarium.plots.simulation_output import plot_variables
# vivarium-ecoli imports
from ecoli.library.schema import (
listener_schema,
numpy_schema,
counts,
attrs,
bulk_name_to_idx,
)
from ecoli.processes.registries import topology_registry
from ecoli.processes.partition import PartitionedProcess
MICROMOLAR_UNITS = units.umol / units.L
"""Units used for all concentrations."""
REMOVED_FROM_CHARGING = {"L-SELENOCYSTEINE[c]"}
"""Amino acids to remove from charging when running with
``steady_state_trna_charging``"""
# Register default topology for this process, associating it with process name
NAME = "ecoli-polypeptide-elongation"
TOPOLOGY = {
"environment": ("environment",),
"boundary": ("boundary",),
"listeners": ("listeners",),
"active_ribosome": ("unique", "active_ribosome"),
"bulk": ("bulk",),
"polypeptide_elongation": ("process_state", "polypeptide_elongation"),
# Non-partitioned counts
"bulk_total": ("bulk",),
"timestep": ("timestep",),
}
topology_registry.register(NAME, TOPOLOGY)
DEFAULT_AA_NAMES = [
"L-ALPHA-ALANINE[c]",
"ARG[c]",
"ASN[c]",
"L-ASPARTATE[c]",
"CYS[c]",
"GLT[c]",
"GLN[c]",
"GLY[c]",
"HIS[c]",
"ILE[c]",
"LEU[c]",
"LYS[c]",
"MET[c]",
"PHE[c]",
"PRO[c]",
"SER[c]",
"THR[c]",
"TRP[c]",
"TYR[c]",
"L-SELENOCYSTEINE[c]",
"VAL[c]",
]
class PolypeptideElongation(PartitionedProcess):
"""Polypeptide Elongation PartitionedProcess
defaults:
proteinIds: array length n of protein names
"""
name = NAME
topology = TOPOLOGY
defaults = {
"time_step": 1,
"max_time_step": 2.0,
"n_avogadro": 6.02214076e23 / units.mol,
"proteinIds": np.array([]),
"proteinLengths": np.array([]),
"proteinSequences": np.array([[]]),
"aaWeightsIncorporated": np.array([]),
"endWeight": np.array([2.99146113e-08]),
"variable_elongation": False,
"make_elongation_rates": (
lambda random, rate, timestep, variable: np.array([])
),
"next_aa_pad": 1,
"ribosomeElongationRate": 17.388824902723737,
"translation_aa_supply": {"minimal": np.array([])},
"import_threshold": 1e-05,
"aa_from_trna": np.zeros(21),
"gtpPerElongation": 4.2,
"aa_supply_in_charging": False,
"adjust_timestep_for_charging": False,
"mechanistic_translation_supply": False,
"mechanistic_aa_transport": False,
"ppgpp_regulation": False,
"disable_ppgpp_elongation_inhibition": False,
"trna_charging": False,
"translation_supply": False,
"mechanistic_supply": False,
"ribosome30S": "ribosome30S",
"ribosome50S": "ribosome50S",
"amino_acids": DEFAULT_AA_NAMES,
"aa_exchange_names": DEFAULT_AA_NAMES,
"basal_elongation_rate": 22.0,
"ribosomeElongationRateDict": {
"minimal": 17.388824902723737 * units.aa / units.s
},
"uncharged_trna_names": np.array([]),
"aaNames": DEFAULT_AA_NAMES,
"aa_enzymes": [],
"proton": "PROTON",
"water": "H2O",
"cellDensity": 1100 * units.g / units.L,
"elongation_max": 22 * units.aa / units.s,
"aa_from_synthetase": np.array([[]]),
"charging_stoich_matrix": np.array([[]]),
"charged_trna_names": [],
"charging_molecule_names": [],
"synthetase_names": [],
"ppgpp_reaction_names": [],
"ppgpp_reaction_metabolites": [],
"ppgpp_reaction_stoich": np.array([[]]),
"ppgpp_synthesis_reaction": "GDPPYPHOSKIN-RXN",
"ppgpp_degradation_reaction": "PPGPPSYN-RXN",
"aa_importers": [],
"amino_acid_export": None,
"synthesis_index": 0,
"aa_exporters": [],
"get_pathway_enzyme_counts_per_aa": None,
"import_constraint_threshold": 0,
"unit_conversion": 0,
"elong_rate_by_ppgpp": 0,
"amino_acid_import": None,
"degradation_index": 1,
"amino_acid_synthesis": None,
"rela": "RELA",
"spot": "SPOT",
"ppgpp": "ppGpp",
"kS": 100.0,
"KMtf": 1.0,
"KMaa": 100.0,
"krta": 1.0,
"krtf": 500.0,
"KD_RelA": 0.26,
"k_RelA": 75.0,
"k_SpoT_syn": 2.6,
"k_SpoT_deg": 0.23,
"KI_SpoT": 20.0,
"aa_supply_scaling": lambda aa_conc, aa_in_media: 0,
"seed": 0,
"emit_unique": False,
}
def __init__(self, parameters=None):
super().__init__(parameters)
self.max_time_step = self.parameters["max_time_step"]
# Simulation options
self.aa_supply_in_charging = self.parameters["aa_supply_in_charging"]
self.adjust_timestep_for_charging = self.parameters[
"adjust_timestep_for_charging"
]
self.mechanistic_translation_supply = self.parameters[
"mechanistic_translation_supply"
]
self.mechanistic_aa_transport = self.parameters["mechanistic_aa_transport"]
self.ppgpp_regulation = self.parameters["ppgpp_regulation"]
self.disable_ppgpp_elongation_inhibition = self.parameters[
"disable_ppgpp_elongation_inhibition"
]
self.variable_elongation = self.parameters["variable_elongation"]
self.variable_polymerize = self.ppgpp_regulation or self.variable_elongation
translation_supply = self.parameters["translation_supply"]
trna_charging = self.parameters["trna_charging"]
# Load parameters
self.n_avogadro = self.parameters["n_avogadro"]
self.proteinIds = self.parameters["proteinIds"]
self.protein_lengths = self.parameters["proteinLengths"]
self.proteinSequences = self.parameters["proteinSequences"]
self.aaWeightsIncorporated = self.parameters["aaWeightsIncorporated"]
self.endWeight = self.parameters["endWeight"]
self.make_elongation_rates = self.parameters["make_elongation_rates"]
self.next_aa_pad = self.parameters["next_aa_pad"]
self.ribosome30S = self.parameters["ribosome30S"]
self.ribosome50S = self.parameters["ribosome50S"]
self.amino_acids = self.parameters["amino_acids"]
self.aa_exchange_names = self.parameters["aa_exchange_names"]
self.aa_environment_names = [aa[:-3] for aa in self.aa_exchange_names]
self.aa_enzymes = self.parameters["aa_enzymes"]
self.ribosomeElongationRate = self.parameters["ribosomeElongationRate"]
# Amino acid supply calculations
self.translation_aa_supply = self.parameters["translation_aa_supply"]
self.import_threshold = self.parameters["import_threshold"]
# Used for figure in publication
self.trpAIndex = np.where(self.proteinIds == "TRYPSYN-APROTEIN[c]")[0][0]
self.elngRateFactor = 1.0
# Data structures for charging
self.aa_from_trna = self.parameters["aa_from_trna"]
# Set modeling method
# TODO: Test that these models all work properly
if trna_charging:
self.elongation_model = SteadyStateElongationModel(self.parameters, self)
elif translation_supply:
self.elongation_model = TranslationSupplyElongationModel(
self.parameters, self
)
else:
self.elongation_model = BaseElongationModel(self.parameters, self)
# Growth associated maintenance energy requirements for elongations
self.gtpPerElongation = self.parameters["gtpPerElongation"]
# Need to account for ATP hydrolysis for charging that has been
# removed from measured GAM (ATP -> AMP is 2 hydrolysis reactions)
# if charging reactions are not explicitly modeled
if not trna_charging:
self.gtpPerElongation += 2
# basic molecule names
self.proton = self.parameters["proton"]
self.water = self.parameters["water"]
self.rela = self.parameters["rela"]
self.spot = self.parameters["spot"]
self.ppgpp = self.parameters["ppgpp"]
self.aa_importers = self.parameters["aa_importers"]
self.aa_exporters = self.parameters["aa_exporters"]
# Numpy index for bulk molecule
self.proton_idx = None
# Names of molecules associated with tRNA charging
self.ppgpp_reaction_metabolites = self.parameters["ppgpp_reaction_metabolites"]
self.uncharged_trna_names = self.parameters["uncharged_trna_names"]
self.charged_trna_names = self.parameters["charged_trna_names"]
self.charging_molecule_names = self.parameters["charging_molecule_names"]
self.synthetase_names = self.parameters["synthetase_names"]
self.seed = self.parameters["seed"]
self.random_state = np.random.RandomState(seed=self.seed)
self.zero_aa_exchange_rates = (
MICROMOLAR_UNITS / units.s * np.zeros(len(self.amino_acids))
)
def ports_schema(self):
return {
"environment": {
"media_id": {"_default": "", "_updater": "set"},
"exchange": {"*": {"_default": 0}},
},
"boundary": {
"external": {
aa: {"_default": 0} for aa in sorted(self.aa_environment_names)
}
},
"listeners": {
"mass": listener_schema({"cell_mass": 0.0, "dry_mass": 0.0}),
"growth_limits": listener_schema(
{
"fraction_trna_charged": (
[0.0] * len(self.uncharged_trna_names),
self.uncharged_trna_names,
),
"aa_allocated": ([0] * len(self.amino_acids), self.amino_acids),
"aa_pool_size": ([0] * len(self.amino_acids), self.amino_acids),
"aa_request_size": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"active_ribosome_allocated": 0,
"net_charged": (
[0] * len(self.uncharged_trna_names),
self.uncharged_trna_names,
),
"aas_used": ([0] * len(self.amino_acids), self.amino_acids),
"aa_count_diff": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
# Below only if trna_charging enbaled
"original_aa_supply": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_in_media": (
[False] * len(self.amino_acids),
self.amino_acids,
),
"synthetase_conc": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"uncharged_trna_conc": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"charged_trna_conc": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_conc": ([0.0] * len(self.amino_acids), self.amino_acids),
"ribosome_conc": 0.0,
"fraction_aa_to_elongate": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_supply": ([0.0] * len(self.amino_acids), self.amino_acids),
"aa_synthesis": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_import": ([0.0] * len(self.amino_acids), self.amino_acids),
"aa_export": ([0.0] * len(self.amino_acids), self.amino_acids),
"aa_importers": (
[0] * len(self.aa_importers),
self.aa_importers,
),
"aa_exporters": (
[0] * len(self.aa_exporters),
self.aa_exporters,
),
"aa_supply_enzymes_fwd": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_supply_enzymes_rev": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_supply_aa_conc": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_supply_fraction_fwd": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"aa_supply_fraction_rev": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"ppgpp_conc": 0.0,
"rela_conc": 0.0,
"spot_conc": 0.0,
"rela_syn": ([0.0] * len(self.amino_acids), self.amino_acids),
"spot_syn": 0.0,
"spot_deg": 0.0,
"spot_deg_inhibited": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"trna_charged": ([0] * len(self.amino_acids), self.amino_acids),
}
),
"ribosome_data": listener_schema(
{
"translation_supply": (
[0.0] * len(self.amino_acids),
self.amino_acids,
),
"effective_elongation_rate": 0.0,
"aa_count_in_sequence": (
[0] * len(self.amino_acids),
self.amino_acids,
),
"aa_counts": ([0.0] * len(self.amino_acids), self.amino_acids),
"actual_elongations": 0,
"actual_elongation_hist": [0] * 22,
"elongations_non_terminating_hist": [0] * 22,
"did_terminate": 0,
"termination_loss": 0,
"num_trpA_terminated": 0,
"process_elongation_rate": 0.0,
}
),
},
"bulk": numpy_schema("bulk"),
"bulk_total": numpy_schema("bulk"),
"active_ribosome": numpy_schema(
"active_ribosome", emit=self.parameters["emit_unique"]
),
"polypeptide_elongation": {
"aa_count_diff": {
"_default": {},
"_emit": True,
"_updater": "set",
"_divider": "empty_dict",
},
"gtp_to_hydrolyze": {
"_default": 0.0,
"_emit": True,
"_updater": "set",
"_divider": "zero",
},
"aa_exchange_rates": {
"_default": [0.0],
"_emit": True,
"_updater": "set",
"_divider": "zero",
},
},
"timestep": {"_default": self.parameters["time_step"]},
}
def calculate_request(self, timestep, states):
"""
Set ribosome elongation rate based on simulation medium environment and elongation rate factor
which is used to create single-cell variability in growth rate
The maximum number of amino acids that can be elongated in a single timestep is set to 22
intentionally as the minimum number of padding values on the protein sequence matrix is set to 22.
If timesteps longer than 1.0s are used, this feature will lead to errors in the effective ribosome
elongation rate.
"""
if self.proton_idx is None:
bulk_ids = states["bulk"]["id"]
self.proton_idx = bulk_name_to_idx(self.proton, bulk_ids)
self.water_idx = bulk_name_to_idx(self.water, bulk_ids)
self.rela_idx = bulk_name_to_idx(self.rela, bulk_ids)
self.spot_idx = bulk_name_to_idx(self.spot, bulk_ids)
self.ppgpp_idx = bulk_name_to_idx(self.ppgpp, bulk_ids)
self.monomer_idx = bulk_name_to_idx(self.proteinIds, bulk_ids)
self.amino_acid_idx = bulk_name_to_idx(self.amino_acids, bulk_ids)
self.aa_enzyme_idx = bulk_name_to_idx(self.aa_enzymes, bulk_ids)
self.ppgpp_rxn_metabolites_idx = bulk_name_to_idx(
self.ppgpp_reaction_metabolites, bulk_ids
)
self.uncharged_trna_idx = bulk_name_to_idx(
self.uncharged_trna_names, bulk_ids
)
self.charged_trna_idx = bulk_name_to_idx(self.charged_trna_names, bulk_ids)
self.charging_molecule_idx = bulk_name_to_idx(
self.charging_molecule_names, bulk_ids
)
self.synthetase_idx = bulk_name_to_idx(self.synthetase_names, bulk_ids)
self.ribosome30S_idx = bulk_name_to_idx(self.ribosome30S, bulk_ids)
self.ribosome50S_idx = bulk_name_to_idx(self.ribosome50S, bulk_ids)
self.aa_importer_idx = bulk_name_to_idx(self.aa_importers, bulk_ids)
self.aa_exporter_idx = bulk_name_to_idx(self.aa_exporters, bulk_ids)
# MODEL SPECIFIC: get ribosome elongation rate
self.ribosomeElongationRate = self.elongation_model.elongation_rate(states)
# If there are no active ribosomes, return immediately
if states["active_ribosome"]["_entryState"].sum() == 0:
return {"listeners": {"ribosome_data": {}, "growth_limits": {}}}
# Build sequences to request appropriate amount of amino acids to
# polymerize for next timestep
(
proteinIndexes,
peptideLengths,
) = attrs(states["active_ribosome"], ["protein_index", "peptide_length"])
self.elongation_rates = self.make_elongation_rates(
self.random_state,
self.ribosomeElongationRate,
states["timestep"],
self.variable_elongation,
)
sequences = buildSequences(
self.proteinSequences, proteinIndexes, peptideLengths, self.elongation_rates
)
sequenceHasAA = sequences != polymerize.PAD_VALUE
aasInSequences = np.bincount(sequences[sequenceHasAA], minlength=21)
# Calculate AA supply for expected doubling of protein
dryMass = states["listeners"]["mass"]["dry_mass"] * units.fg
current_media_id = states["environment"]["media_id"]
translation_supply_rate = (
self.translation_aa_supply[current_media_id] * self.elngRateFactor
)
mol_aas_supplied = (
translation_supply_rate * dryMass * states["timestep"] * units.s
)
self.aa_supply = units.strip_empty_units(mol_aas_supplied * self.n_avogadro)
# MODEL SPECIFIC: Calculate AA request
fraction_charged, aa_counts_for_translation, requests = (
self.elongation_model.request(states, aasInSequences)
)
# Write to listeners
listeners = requests.setdefault("listeners", {})
ribosome_data_listener = listeners.setdefault("ribosome_data", {})
ribosome_data_listener["translation_supply"] = (
translation_supply_rate.asNumber()
)
growth_limits_listener = requests["listeners"].setdefault("growth_limits", {})
growth_limits_listener["fraction_trna_charged"] = np.dot(
fraction_charged, self.aa_from_trna
)
growth_limits_listener["aa_pool_size"] = counts(
states["bulk_total"], self.amino_acid_idx
)
growth_limits_listener["aa_request_size"] = aa_counts_for_translation
return requests
def evolve_state(self, timestep, states):
"""
Set ribosome elongation rate based on simulation medium environment and elongation rate factor
which is used to create single-cell variability in growth rate
The maximum number of amino acids that can be elongated in a single timestep is set to 22
intentionally as the minimum number of padding values on the protein sequence matrix is set to 22.
If timesteps longer than 1.0s are used, this feature will lead to errors in the effective ribosome
elongation rate.
"""
update = {
"listeners": {"ribosome_data": {}, "growth_limits": {}},
"polypeptide_elongation": {},
"active_ribosome": {},
"bulk": [],
}
# Begin wcEcoli evolveState()
# Set values for metabolism in case of early return
update["polypeptide_elongation"]["gtp_to_hydrolyze"] = 0
update["polypeptide_elongation"]["aa_count_diff"] = {}
# Get number of active ribosomes
n_active_ribosomes = states["active_ribosome"]["_entryState"].sum()
update["listeners"]["growth_limits"]["active_ribosome_allocated"] = (
n_active_ribosomes
)
update["listeners"]["growth_limits"]["aa_allocated"] = counts(
states["bulk"], self.amino_acid_idx
)
# If there are no active ribosomes, return immediately
if n_active_ribosomes == 0:
return update
# Polypeptide elongation requires counts to be updated in real-time
# so make a writeable copy of bulk counts to do so
states["bulk"] = counts(states["bulk"], range(len(states["bulk"])))
# Build amino acids sequences for each ribosome to polymerize
protein_indexes, peptide_lengths, positions_on_mRNA = attrs(
states["active_ribosome"],
["protein_index", "peptide_length", "pos_on_mRNA"],
)
all_sequences = buildSequences(
self.proteinSequences,
protein_indexes,
peptide_lengths,
self.elongation_rates + self.next_aa_pad,
)
sequences = all_sequences[:, : -self.next_aa_pad].copy()
if sequences.size == 0:
return update
# Calculate elongation resource capacity
aaCountInSequence = np.bincount(sequences[(sequences != polymerize.PAD_VALUE)])
total_aa_counts = counts(states["bulk"], self.amino_acid_idx)
charged_trna_counts = counts(states["bulk"], self.charged_trna_idx)
# MODEL SPECIFIC: Get amino acid counts
aa_counts_for_translation = self.elongation_model.final_amino_acids(
total_aa_counts, charged_trna_counts
)
# Using polymerization algorithm elongate each ribosome up to the limits
# of amino acids, sequence, and GTP
result = polymerize(
sequences,
aa_counts_for_translation,
10000000, # Set to a large number, the limit is now taken care of in metabolism
self.random_state,
self.elongation_rates[protein_indexes],
variable_elongation=self.variable_polymerize,
)
sequence_elongations = result.sequenceElongation
aas_used = result.monomerUsages
nElongations = result.nReactions
next_amino_acid = all_sequences[
np.arange(len(sequence_elongations)), sequence_elongations
]
next_amino_acid_count = np.bincount(
next_amino_acid[next_amino_acid != polymerize.PAD_VALUE], minlength=21
)
# Update masses of ribosomes attached to polymerizing polypeptides
added_protein_mass = computeMassIncrease(
sequences, sequence_elongations, self.aaWeightsIncorporated
)
updated_lengths = peptide_lengths + sequence_elongations
updated_positions_on_mRNA = positions_on_mRNA + 3 * sequence_elongations
didInitialize = (sequence_elongations > 0) & (peptide_lengths == 0)
added_protein_mass[didInitialize] += self.endWeight
# Write current average elongation to listener
currElongRate = (sequence_elongations.sum() / n_active_ribosomes) / states[
"timestep"
]
# Ribosomes that reach the end of their sequences are terminated and
# dissociated into 30S and 50S subunits. The polypeptide that they are
# polymerizing is converted into a protein in BulkMolecules
terminalLengths = self.protein_lengths[protein_indexes]
didTerminate = updated_lengths == terminalLengths
terminatedProteins = np.bincount(
protein_indexes[didTerminate], minlength=self.proteinSequences.shape[0]
)
(protein_mass,) = attrs(states["active_ribosome"], ["massDiff_protein"])
update["active_ribosome"].update(
{
"delete": np.where(didTerminate)[0],
"set": {
"massDiff_protein": protein_mass + added_protein_mass,
"peptide_length": updated_lengths,
"pos_on_mRNA": updated_positions_on_mRNA,
},
}
)
update["bulk"].append((self.monomer_idx, terminatedProteins))
states["bulk"][self.monomer_idx] += terminatedProteins
nTerminated = didTerminate.sum()
nInitialized = didInitialize.sum()
update["bulk"].append((self.ribosome30S_idx, nTerminated))
update["bulk"].append((self.ribosome50S_idx, nTerminated))
states["bulk"][self.ribosome30S_idx] += nTerminated
states["bulk"][self.ribosome50S_idx] += nTerminated
# MODEL SPECIFIC: evolve
net_charged, aa_count_diff, evolve_update = self.elongation_model.evolve(
states,
total_aa_counts,
aas_used,
next_amino_acid_count,
nElongations,
nInitialized,
)
evolve_bulk_update = evolve_update.pop("bulk")
update = deep_merge(update, evolve_update)
update["bulk"].extend(evolve_bulk_update)
update["polypeptide_elongation"]["aa_count_diff"] = aa_count_diff
# GTP hydrolysis is carried out in Metabolism process for growth
# associated maintenance. This is passed to metabolism.
update["polypeptide_elongation"]["gtp_to_hydrolyze"] = (
self.gtpPerElongation * nElongations
)
# Write data to listeners
update["listeners"]["growth_limits"]["net_charged"] = net_charged
update["listeners"]["growth_limits"]["aas_used"] = aas_used
update["listeners"]["growth_limits"]["aa_count_diff"] = [
aa_count_diff.get(id_, 0) for id_ in self.amino_acids
]
ribosome_data_listener = update["listeners"].setdefault("ribosome_data", {})
ribosome_data_listener["effective_elongation_rate"] = currElongRate
ribosome_data_listener["aa_count_in_sequence"] = aaCountInSequence
ribosome_data_listener["aa_counts"] = aa_counts_for_translation
ribosome_data_listener["actual_elongations"] = sequence_elongations.sum()
ribosome_data_listener["actual_elongation_hist"] = np.histogram(
sequence_elongations, bins=np.arange(0, 23)
)[0]
ribosome_data_listener["elongations_non_terminating_hist"] = np.histogram(
sequence_elongations[~didTerminate], bins=np.arange(0, 23)
)[0]
ribosome_data_listener["did_terminate"] = didTerminate.sum()
ribosome_data_listener["termination_loss"] = (
terminalLengths - peptide_lengths
)[didTerminate].sum()
ribosome_data_listener["num_trpA_terminated"] = terminatedProteins[
self.trpAIndex
]
ribosome_data_listener["process_elongation_rate"] = (
self.ribosomeElongationRate / states["timestep"]
)
return update
def isTimeStepShortEnough(self, inputTimeStep, timeStepSafetyFraction):
model_specific = self.elongation_model.isTimeStepShortEnough(
inputTimeStep, timeStepSafetyFraction
)
max_time_step = inputTimeStep <= self.max_time_step
return model_specific and max_time_step
class BaseElongationModel(object):
"""
Base Model: Request amino acids according to upcoming sequence, assuming
max ribosome elongation.
"""
def __init__(self, parameters, process):
self.parameters = parameters
self.process = process
self.basal_elongation_rate = self.parameters["basal_elongation_rate"]
self.ribosomeElongationRateDict = self.parameters["ribosomeElongationRateDict"]
def elongation_rate(self, states):
"""
Sets ribosome elongation rate accordint to the media; returns
max value of 22 amino acids/second.
"""
current_media_id = states["environment"]["media_id"]
rate = self.process.elngRateFactor * self.ribosomeElongationRateDict[
current_media_id
].asNumber(units.aa / units.s)
return np.min([self.basal_elongation_rate, rate])
def amino_acid_counts(self, aasInSequences):
return aasInSequences
def request(self, states, aasInSequences):
aa_counts_for_translation = self.amino_acid_counts(aasInSequences)
requests = {"bulk": [(self.process.amino_acid_idx, aa_counts_for_translation)]}
# Not modeling charging so set fraction charged to 0 for all tRNA
fraction_charged = np.zeros(len(self.process.amino_acid_idx))
return fraction_charged, aa_counts_for_translation, requests
def final_amino_acids(self, total_aa_counts, charged_trna_counts):
return total_aa_counts
def evolve(
self,
states,
total_aa_counts,
aas_used,
next_amino_acid_count,
nElongations,
nInitialized,
):
# Update counts of amino acids and water to reflect polymerization
# reactions
net_charged = np.zeros(len(self.parameters["uncharged_trna_names"]))
return (
net_charged,
{},
{
"bulk": [
(self.process.amino_acid_idx, -aas_used),
(self.process.water_idx, nElongations - nInitialized),
]
},
)
def isTimeStepShortEnough(self, inputTimeStep, timeStepSafetyFraction):
return True
class TranslationSupplyElongationModel(BaseElongationModel):
"""
Translation Supply Model: Requests minimum of 1) upcoming amino acid
sequence assuming max ribosome elongation (ie. Base Model) and 2)
estimation based on doubling the proteome in one cell cycle (does not
use ribosome elongation, computed in Parca).
"""
def __init__(self, parameters, process):
super().__init__(parameters, process)
def elongation_rate(self, states):
"""
Sets ribosome elongation rate accordint to the media; returns
max value of 22 amino acids/second.
"""
return self.basal_elongation_rate
def amino_acid_counts(self, aasInSequences):
# Check if this is required. It is a better request but there may be
# fewer elongations.
return np.fmin(self.process.aa_supply, aasInSequences)
class SteadyStateElongationModel(TranslationSupplyElongationModel):
"""
Steady State Charging Model: Requests amino acids based on the
Michaelis-Menten competitive inhibition model.
"""
def __init__(self, parameters, process):
super().__init__(parameters, process)
# Cell parameters
self.cellDensity = self.parameters["cellDensity"]
# Names of molecules associated with tRNA charging
self.charged_trna_names = self.parameters["charged_trna_names"]
self.charging_molecule_names = self.parameters["charging_molecule_names"]
self.synthetase_names = self.parameters["synthetase_names"]
# Data structures for charging
self.aa_from_synthetase = self.parameters["aa_from_synthetase"]
self.charging_stoich_matrix = self.parameters["charging_stoich_matrix"]
self.charging_molecules_not_aa = np.array(
[
mol not in set(self.parameters["amino_acids"])
for mol in self.charging_molecule_names
]
)
# ppGpp synthesis
self.ppgpp_reaction_metabolites = self.parameters["ppgpp_reaction_metabolites"]
self.elong_rate_by_ppgpp = self.parameters["elong_rate_by_ppgpp"]
# Parameters for tRNA charging, ribosome elongation and ppGpp reactions
self.charging_params = {
"kS": self.parameters["kS"],
"KMaa": self.parameters["KMaa"],
"KMtf": self.parameters["KMtf"],
"krta": self.parameters["krta"],
"krtf": self.parameters["krtf"],
"max_elong_rate": float(
self.parameters["elongation_max"].asNumber(units.aa / units.s)
),
"charging_mask": np.array(
[
aa not in REMOVED_FROM_CHARGING
for aa in self.parameters["amino_acids"]
]
),
"unit_conversion": self.parameters["unit_conversion"],
}
self.ppgpp_params = {
"KD_RelA": self.parameters["KD_RelA"],
"k_RelA": self.parameters["k_RelA"],
"k_SpoT_syn": self.parameters["k_SpoT_syn"],
"k_SpoT_deg": self.parameters["k_SpoT_deg"],
"KI_SpoT": self.parameters["KI_SpoT"],
"ppgpp_reaction_stoich": self.parameters["ppgpp_reaction_stoich"],
"synthesis_index": self.parameters["synthesis_index"],
"degradation_index": self.parameters["degradation_index"],
}
# Amino acid supply calculations
self.aa_supply_scaling = self.parameters["aa_supply_scaling"]
# Manage unstable charging with too long time step by setting
# time_step_short_enough to False during updates. Other variables
# manage when to trigger an adjustment and how quickly the time step
# increases after being reduced
self.time_step_short_enough = True
self.max_time_step = self.process.max_time_step
self.time_step_increase = 1.01
self.max_amino_acid_adjustment = 0.05
self.amino_acid_synthesis = self.parameters["amino_acid_synthesis"]
self.amino_acid_import = self.parameters["amino_acid_import"]
self.amino_acid_export = self.parameters["amino_acid_export"]
self.get_pathway_enzyme_counts_per_aa = self.parameters[
"get_pathway_enzyme_counts_per_aa"
]
# Comparing two values with units is faster than converting units
# and comparing magnitudes
self.import_constraint_threshold = (
self.parameters["import_constraint_threshold"] * vivunits.mM
)
def elongation_rate(self, states):
if (
self.process.ppgpp_regulation
and not self.process.disable_ppgpp_elongation_inhibition
):
cell_mass = states["listeners"]["mass"]["cell_mass"] * units.fg
cell_volume = cell_mass / self.cellDensity
counts_to_molar = 1 / (self.process.n_avogadro * cell_volume)
ppgpp_count = counts(states["bulk"], self.process.ppgpp_idx)
ppgpp_conc = ppgpp_count * counts_to_molar
rate = self.elong_rate_by_ppgpp(
ppgpp_conc, self.basal_elongation_rate
).asNumber(units.aa / units.s)
else:
rate = super().elongation_rate(states)
return rate
def request(self, states, aasInSequences):
self.max_time_step = min(
self.process.max_time_step, self.max_time_step * self.time_step_increase
)
# Conversion from counts to molarity
cell_mass = states["listeners"]["mass"]["cell_mass"] * units.fg
dry_mass = states["listeners"]["mass"]["dry_mass"] * units.fg
cell_volume = cell_mass / self.cellDensity
self.counts_to_molar = 1 / (self.process.n_avogadro * cell_volume)
# ppGpp related concentrations
ppgpp_conc = self.counts_to_molar * counts(
states["bulk_total"], self.process.ppgpp_idx
)
rela_conc = self.counts_to_molar * counts(
states["bulk_total"], self.process.rela_idx
)
spot_conc = self.counts_to_molar * counts(
states["bulk_total"], self.process.spot_idx
)
# Get counts and convert synthetase and tRNA to a per AA basis
synthetase_counts = np.dot(
self.aa_from_synthetase,
counts(states["bulk_total"], self.process.synthetase_idx),
)
aa_counts = counts(states["bulk_total"], self.process.amino_acid_idx)
uncharged_trna_array = counts(
states["bulk_total"], self.process.uncharged_trna_idx
)
charged_trna_array = counts(states["bulk_total"], self.process.charged_trna_idx)
uncharged_trna_counts = np.dot(self.process.aa_from_trna, uncharged_trna_array)
charged_trna_counts = np.dot(self.process.aa_from_trna, charged_trna_array)
ribosome_counts = states["active_ribosome"]["_entryState"].sum()
# Get concentration
f = aasInSequences / aasInSequences.sum()
synthetase_conc = self.counts_to_molar * synthetase_counts
aa_conc = self.counts_to_molar * aa_counts
uncharged_trna_conc = self.counts_to_molar * uncharged_trna_counts
charged_trna_conc = self.counts_to_molar * charged_trna_counts
ribosome_conc = self.counts_to_molar * ribosome_counts
# Calculate amino acid supply
aa_in_media = np.array(
[
states["boundary"]["external"][aa] > self.import_constraint_threshold
for aa in self.process.aa_environment_names
]
)
fwd_enzyme_counts, rev_enzyme_counts = self.get_pathway_enzyme_counts_per_aa(
counts(states["bulk_total"], self.process.aa_enzyme_idx)
)
importer_counts = counts(states["bulk_total"], self.process.aa_importer_idx)
exporter_counts = counts(states["bulk_total"], self.process.aa_exporter_idx)
synthesis, fwd_saturation, rev_saturation = self.amino_acid_synthesis(
fwd_enzyme_counts, rev_enzyme_counts, aa_conc
)
import_rates = self.amino_acid_import(
aa_in_media,
dry_mass,
aa_conc,
importer_counts,
self.process.mechanistic_aa_transport,
)
export_rates = self.amino_acid_export(
exporter_counts, aa_conc, self.process.mechanistic_aa_transport
)
exchange_rates = import_rates - export_rates
supply_function = get_charging_supply_function(