-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathchromosome_structure.py
1703 lines (1567 loc) · 70.4 KB
/
chromosome_structure.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
"""
====================
Chromosome Structure
====================
- Resolve collisions between molecules and replication forks on the chromosome.
- Remove and replicate promoters and motifs that are traversed by replisomes.
- Reset the boundaries and linking numbers of chromosomal segments.
"""
import numpy as np
import numpy.typing as npt
import warnings
from vivarium.core.process import Step
from vivarium.core.composer import Composer
from vivarium.core.engine import Engine
from ecoli.processes.global_clock import GlobalClock
from ecoli.processes.unique_update import UniqueUpdate
from ecoli.processes.registries import topology_registry
from ecoli.library.schema import (
listener_schema,
numpy_schema,
attrs,
bulk_name_to_idx,
get_free_indices,
)
from ecoli.library.json_state import get_state_from_file
from wholecell.utils.polymerize import buildSequences
# Register default topology for this process, associating it with process name
NAME = "ecoli-chromosome-structure"
TOPOLOGY = {
"bulk": ("bulk",),
"listeners": ("listeners",),
"active_replisomes": (
"unique",
"active_replisome",
),
"oriCs": (
"unique",
"oriC",
),
"chromosome_domains": (
"unique",
"chromosome_domain",
),
"active_RNAPs": ("unique", "active_RNAP"),
"RNAs": ("unique", "RNA"),
"active_ribosome": ("unique", "active_ribosome"),
"full_chromosomes": (
"unique",
"full_chromosome",
),
"promoters": ("unique", "promoter"),
"DnaA_boxes": ("unique", "DnaA_box"),
"genes": ("unique", "gene"),
"chromosomal_segments": ("unique", "chromosomal_segment"),
"global_time": ("global_time",),
"timestep": ("timestep",),
"next_update_time": ("next_update_time", "chromosome_structure"),
}
topology_registry.register(NAME, TOPOLOGY)
class ChromosomeStructure(Step):
"""Chromosome Structure Process"""
name = NAME
topology = TOPOLOGY
defaults = {
# Load parameters
"rna_sequences": [],
"protein_sequences": [],
"n_TUs": 1,
"n_TFs": 1,
"n_amino_acids": 1,
"n_fragment_bases": 1,
"replichore_lengths": [0, 0],
"relaxed_DNA_base_pairs_per_turn": 1,
"terC_index": -1,
"calculate_superhelical_densities": False,
# Get placeholder value for chromosome domains without children
"no_child_place_holder": -1,
# Load bulk molecule views
"inactive_RNAPs": [],
"fragmentBases": [],
"ppi": "ppi",
"active_tfs": [],
"ribosome_30S_subunit": "30S",
"ribosome_50S_subunit": "50S",
"amino_acids": [],
"water": "water",
"seed": 0,
"emit_unique": False,
"rna_ids": [],
"n_mature_rnas": 0,
"mature_rna_ids": [],
"mature_rna_end_positions": [],
"mature_rna_nt_counts": [],
"unprocessed_rna_index_mapping": {},
"time_step": 1.0,
}
# Constructor
def __init__(self, parameters=None):
super().__init__(parameters)
self.rna_sequences = self.parameters["rna_sequences"]
self.protein_sequences = self.parameters["protein_sequences"]
self.n_TUs = self.parameters["n_TUs"]
self.n_TFs = self.parameters["n_TFs"]
self.rna_ids = self.parameters["rna_ids"]
self.n_amino_acids = self.parameters["n_amino_acids"]
self.n_fragment_bases = self.parameters["n_fragment_bases"]
replichore_lengths = self.parameters["replichore_lengths"]
self.min_coordinates = -replichore_lengths[1]
self.max_coordinates = replichore_lengths[0]
self.relaxed_DNA_base_pairs_per_turn = self.parameters[
"relaxed_DNA_base_pairs_per_turn"
]
self.terC_index = self.parameters["terC_index"]
self.n_mature_rnas = self.parameters["n_mature_rnas"]
self.mature_rna_ids = self.parameters["mature_rna_ids"]
self.mature_rna_end_positions = self.parameters["mature_rna_end_positions"]
self.mature_rna_nt_counts = self.parameters["mature_rna_nt_counts"]
self.unprocessed_rna_index_mapping = self.parameters[
"unprocessed_rna_index_mapping"
]
# Load sim options
self.calculate_superhelical_densities = self.parameters[
"calculate_superhelical_densities"
]
# Get placeholder value for chromosome domains without children
self.no_child_place_holder = self.parameters["no_child_place_holder"]
self.inactive_RNAPs = self.parameters["inactive_RNAPs"]
self.fragmentBases = self.parameters["fragmentBases"]
self.ppi = self.parameters["ppi"]
self.active_tfs = self.parameters["active_tfs"]
self.ribosome_30S_subunit = self.parameters["ribosome_30S_subunit"]
self.ribosome_50S_subunit = self.parameters["ribosome_50S_subunit"]
self.amino_acids = self.parameters["amino_acids"]
self.water = self.parameters["water"]
self.inactive_RNAPs_idx = None
self.emit_unique = self.parameters.get("emit_unique", True)
def ports_schema(self):
ports = {
"listeners": {
"rnap_data": listener_schema(
{
"n_total_collisions": 0,
"n_headon_collisions": 0,
"n_codirectional_collisions": 0,
"headon_collision_coordinates": [],
"codirectional_collision_coordinates": [],
"n_removed_ribosomes": 0,
"incomplete_transcription_events": (
np.zeros(self.n_TUs, np.int64),
self.rna_ids,
),
"n_empty_fork_collisions": 0,
"empty_fork_collision_coordinates": [],
}
)
},
"bulk": numpy_schema("bulk"),
# Unique molecules
"active_replisomes": numpy_schema(
"active_replisomes", emit=self.parameters["emit_unique"]
),
"oriCs": numpy_schema("oriCs", emit=self.parameters["emit_unique"]),
"chromosome_domains": numpy_schema(
"chromosome_domains", emit=self.parameters["emit_unique"]
),
"active_RNAPs": numpy_schema(
"active_RNAPs", emit=self.parameters["emit_unique"]
),
"RNAs": numpy_schema("RNAs", emit=self.parameters["emit_unique"]),
"active_ribosome": numpy_schema(
"active_ribosome", emit=self.parameters["emit_unique"]
),
"full_chromosomes": numpy_schema(
"full_chromosomes", emit=self.parameters["emit_unique"]
),
"promoters": numpy_schema("promoters", emit=self.parameters["emit_unique"]),
"DnaA_boxes": numpy_schema(
"DnaA_boxes", emit=self.parameters["emit_unique"]
),
"chromosomal_segments": numpy_schema(
"chromosomal_segments", emit=self.parameters["emit_unique"]
),
"genes": numpy_schema("genes", emit=self.parameters["emit_unique"]),
"global_time": {"_default": 0.0},
"timestep": {"_default": self.parameters["time_step"]},
"next_update_time": {
"_default": self.parameters["time_step"],
"_updater": "set",
"_divider": "set",
},
}
return ports
def update_condition(self, timestep, states):
"""
See :py:meth:`~ecoli.processes.partition.Requester.update_condition`.
"""
if states["next_update_time"] <= states["global_time"]:
if states["next_update_time"] < states["global_time"]:
warnings.warn(
f"{self.name} updated at t="
f"{states['global_time']} instead of t="
f"{states['next_update_time']}. Decrease the "
"timestep for the global clock process for more "
"accurate timekeeping."
)
return True
return False
def next_update(self, timestep, states):
# At t=0, convert all strings to indices
if self.inactive_RNAPs_idx is None:
self.fragmentBasesIdx = bulk_name_to_idx(
self.fragmentBases, states["bulk"]["id"]
)
self.active_tfs_idx = bulk_name_to_idx(
self.active_tfs, states["bulk"]["id"]
)
self.ribosome_30S_subunit_idx = bulk_name_to_idx(
self.ribosome_30S_subunit, states["bulk"]["id"]
)
self.ribosome_50S_subunit_idx = bulk_name_to_idx(
self.ribosome_50S_subunit, states["bulk"]["id"]
)
self.amino_acids_idx = bulk_name_to_idx(
self.amino_acids, states["bulk"]["id"]
)
self.water_idx = bulk_name_to_idx(self.water, states["bulk"]["id"])
self.ppi_idx = bulk_name_to_idx(self.ppi, states["bulk"]["id"])
self.inactive_RNAPs_idx = bulk_name_to_idx(
self.inactive_RNAPs, states["bulk"]["id"]
)
self.mature_rna_idx = bulk_name_to_idx(
self.mature_rna_ids, states["bulk"]["id"]
)
# Read unique molecule attributes
(replisome_domain_indexes, replisome_coordinates, replisome_unique_indexes) = (
attrs(
states["active_replisomes"],
["domain_index", "coordinates", "unique_index"],
)
)
(all_chromosome_domain_indexes, child_domains) = attrs(
states["chromosome_domains"], ["domain_index", "child_domains"]
)
(
RNAP_domain_indexes,
RNAP_coordinates,
RNAP_is_forward,
RNAP_unique_indexes,
) = attrs(
states["active_RNAPs"],
["domain_index", "coordinates", "is_forward", "unique_index"],
)
(origin_domain_indexes,) = attrs(states["oriCs"], ["domain_index"])
(mother_domain_indexes,) = attrs(states["full_chromosomes"], ["domain_index"])
(RNA_TU_indexes, transcript_lengths, RNA_RNAP_indexes, RNA_unique_indexes) = (
attrs(
states["RNAs"],
["TU_index", "transcript_length", "RNAP_index", "unique_index"],
)
)
(ribosome_protein_indexes, ribosome_peptide_lengths, ribosome_mRNA_indexes) = (
attrs(
states["active_ribosome"],
["protein_index", "peptide_length", "mRNA_index"],
)
)
(
promoter_TU_indexes,
promoter_domain_indexes,
promoter_coordinates,
promoter_bound_TFs,
) = attrs(
states["promoters"], ["TU_index", "domain_index", "coordinates", "bound_TF"]
)
(gene_cistron_indexes, gene_domain_indexes, gene_coordinates) = attrs(
states["genes"], ["cistron_index", "domain_index", "coordinates"]
)
(DnaA_box_domain_indexes, DnaA_box_coordinates, DnaA_box_bound) = attrs(
states["DnaA_boxes"], ["domain_index", "coordinates", "DnaA_bound"]
)
# Build dictionary of replisome coordinates with domain indexes as keys
replisome_coordinates_from_domains = {
domain_index: replisome_coordinates[
replisome_domain_indexes == domain_index
]
for domain_index in np.unique(replisome_domain_indexes)
}
def get_removed_molecules_mask(domain_indexes, coordinates):
"""
Computes the boolean mask of unique molecules that should be
removed based on the progression of the replication forks.
"""
mask = np.zeros_like(domain_indexes, dtype=np.bool_)
# Loop through all domains
for domain_index in np.unique(domain_indexes):
# Domain has active replisomes
if domain_index in replisome_coordinates_from_domains:
domain_replisome_coordinates = replisome_coordinates_from_domains[
domain_index
]
# Get mask for molecules on this domain that are out of range
# It's rare but we have to remove molecules at the exact same
# coordinates as the replisomes as well so that they do not break
# the chromosome segment calculations if they are removed by a
# different process (hence, >= and <= instead of > and <)
domain_mask = np.logical_and.reduce(
(
domain_indexes == domain_index,
coordinates >= domain_replisome_coordinates.min(),
coordinates <= domain_replisome_coordinates.max(),
)
)
# Domain has no active replisomes
else:
children_of_domain = child_domains[
all_chromosome_domain_indexes == domain_index
]
# Child domains are full chromosomes (domain has finished replicating)
if np.all(np.isin(children_of_domain, mother_domain_indexes)):
# Remove all molecules on this domain
domain_mask = domain_indexes == domain_index
# Domain has not started replication or replication was interrupted
else:
continue
mask[domain_mask] = True
return mask
# Build mask for molecules that should be removed
removed_RNAPs_mask = get_removed_molecules_mask(
RNAP_domain_indexes, RNAP_coordinates
)
removed_promoters_mask = get_removed_molecules_mask(
promoter_domain_indexes, promoter_coordinates
)
removed_genes_mask = get_removed_molecules_mask(
gene_domain_indexes, gene_coordinates
)
removed_DnaA_boxes_mask = get_removed_molecules_mask(
DnaA_box_domain_indexes, DnaA_box_coordinates
)
# Build masks for head-on and co-directional collisions between RNAPs
# and replication forks
RNAP_headon_collision_mask = np.logical_and(
removed_RNAPs_mask, np.logical_xor(RNAP_is_forward, RNAP_coordinates > 0)
)
RNAP_codirectional_collision_mask = np.logical_and(
removed_RNAPs_mask, np.logical_not(RNAP_headon_collision_mask)
)
n_total_collisions = np.count_nonzero(removed_RNAPs_mask)
n_headon_collisions = np.count_nonzero(RNAP_headon_collision_mask)
n_codirectional_collisions = np.count_nonzero(RNAP_codirectional_collision_mask)
# Write values to listeners
update = {
"listeners": {
"rnap_data": {
"n_total_collisions": n_total_collisions,
"n_headon_collisions": n_headon_collisions,
"n_codirectional_collisions": n_codirectional_collisions,
"headon_collision_coordinates": RNAP_coordinates[
RNAP_headon_collision_mask
],
"codirectional_collision_coordinates": RNAP_coordinates[
RNAP_codirectional_collision_mask
],
}
},
"bulk": [],
"active_replisomes": {},
"oriCs": {},
"chromosome_domains": {},
"active_RNAPs": {},
"RNAs": {},
"active_ribosome": {},
"full_chromosomes": {},
"chromosomal_segments": {},
"promoters": {},
"genes": {},
"DnaA_boxes": {},
}
if self.calculate_superhelical_densities:
# Get attributes of existing segments
(
boundary_molecule_indexes,
boundary_coordinates,
segment_domain_indexes,
linking_numbers,
) = attrs(
states["chromosomal_segments"],
[
"boundary_molecule_indexes",
"boundary_coordinates",
"domain_index",
"linking_number",
],
)
# Initialize new attributes of chromosomal segments
all_new_boundary_molecule_indexes = np.empty((0, 2), dtype=np.int64)
all_new_boundary_coordinates = np.empty((0, 2), dtype=np.int64)
all_new_segment_domain_indexes = np.array([], dtype=np.int32)
all_new_linking_numbers = np.array([], dtype=np.float64)
# Iteratively tally RNAPs that were removed due to collisions with
# replication forks with or without replisomes on each domain
removed_RNAP_masks_all_domains = np.full_like(removed_RNAPs_mask, False)
for domain_index in np.unique(all_chromosome_domain_indexes):
# Skip domains that have completed replication
if np.all(domain_index < mother_domain_indexes):
continue
domain_spans_oriC = domain_index in origin_domain_indexes
domain_spans_terC = domain_index in mother_domain_indexes
# Parse attributes of remaining RNAPs in this domain
RNAPs_domain_mask = RNAP_domain_indexes == domain_index
RNAP_coordinates_this_domain = RNAP_coordinates[RNAPs_domain_mask]
RNAP_unique_indexes_this_domain = RNAP_unique_indexes[RNAPs_domain_mask]
domain_remaining_RNAPs_mask = ~removed_RNAPs_mask[RNAPs_domain_mask]
# Parse attributes of segments in this domain
segments_domain_mask = segment_domain_indexes == domain_index
boundary_molecule_indexes_this_domain = boundary_molecule_indexes[
segments_domain_mask, :
]
boundary_coordinates_this_domain = boundary_coordinates[
segments_domain_mask, :
]
linking_numbers_this_domain = linking_numbers[segments_domain_mask]
new_molecule_coordinates_this_domain = np.array([], dtype=np.int64)
new_molecule_indexes_this_domain = np.array([], dtype=np.int64)
# Append coordinates and indexes of replisomes on this domain,
# if any
if not domain_spans_oriC:
replisome_domain_mask = replisome_domain_indexes == domain_index
replisome_coordinates_this_domain = replisome_coordinates[
replisome_domain_mask
]
replisome_molecule_indexes_this_domain = replisome_unique_indexes[
replisome_domain_mask
]
# If one or more replisomes was removed in the last time step,
# use the last known location and molecule index.
if len(replisome_molecule_indexes_this_domain) != 2:
assert len(replisome_molecule_indexes_this_domain) < 2
(
replisome_coordinates_this_domain,
replisome_molecule_indexes_this_domain,
) = get_last_known_replisome_data(
boundary_coordinates_this_domain,
boundary_molecule_indexes_this_domain,
replisome_coordinates_this_domain,
replisome_molecule_indexes_this_domain,
)
# Assume that RNAPs that run into a replication fork
# are removed even if there is no replisome
RNAPs_on_forks = np.isin(
RNAP_coordinates_this_domain,
replisome_coordinates_this_domain,
)
domain_remaining_RNAPs_mask = np.logical_and(
domain_remaining_RNAPs_mask, ~RNAPs_on_forks
)
full_removed_RNAPs_mask = np.full_like(
removed_RNAPs_mask, False
)
full_removed_RNAPs_mask[RNAPs_domain_mask] = RNAPs_on_forks
removed_RNAP_masks_all_domains = np.logical_or(
removed_RNAP_masks_all_domains, full_removed_RNAPs_mask
)
new_molecule_coordinates_this_domain = np.concatenate(
(
new_molecule_coordinates_this_domain,
replisome_coordinates_this_domain,
)
)
new_molecule_indexes_this_domain = np.concatenate(
(
new_molecule_indexes_this_domain,
replisome_molecule_indexes_this_domain,
)
)
# Append coordinates and indexes of parent domain replisomes,
# if any
if not domain_spans_terC:
parent_domain_index = all_chromosome_domain_indexes[
np.where(child_domains == domain_index)[0][0]
]
replisome_parent_domain_mask = (
replisome_domain_indexes == parent_domain_index
)
replisome_coordinates_parent_domain = replisome_coordinates[
replisome_parent_domain_mask
]
replisome_molecule_indexes_parent_domain = replisome_unique_indexes[
replisome_parent_domain_mask
]
# If one or more replisomes was removed in the last time step,
# use the last known location and molecule index.
if len(replisome_molecule_indexes_parent_domain) != 2:
assert len(replisome_molecule_indexes_parent_domain) < 2
# Parse attributes of segments in parent domain
parent_segments_domain_mask = (
segment_domain_indexes == parent_domain_index
)
boundary_molecule_indexes_parent_domain = (
boundary_molecule_indexes[parent_segments_domain_mask, :]
)
boundary_coordinates_parent_domain = boundary_coordinates[
parent_segments_domain_mask, :
]
(
replisome_coordinates_parent_domain,
replisome_molecule_indexes_parent_domain,
) = get_last_known_replisome_data(
boundary_coordinates_parent_domain,
boundary_molecule_indexes_parent_domain,
replisome_coordinates_parent_domain,
replisome_molecule_indexes_parent_domain,
)
# Assume that RNAPs that run into a replication fork
# are removed even if there is no replisome
RNAPs_on_forks = np.isin(
RNAP_coordinates_this_domain,
replisome_coordinates_parent_domain,
)
domain_remaining_RNAPs_mask = np.logical_and(
domain_remaining_RNAPs_mask, ~RNAPs_on_forks
)
full_removed_RNAPs_mask = np.full_like(
removed_RNAPs_mask, False
)
full_removed_RNAPs_mask[RNAPs_domain_mask] = RNAPs_on_forks
removed_RNAP_masks_all_domains = np.logical_or(
removed_RNAP_masks_all_domains, full_removed_RNAPs_mask
)
new_molecule_coordinates_this_domain = np.concatenate(
(
new_molecule_coordinates_this_domain,
replisome_coordinates_parent_domain,
)
)
new_molecule_indexes_this_domain = np.concatenate(
(
new_molecule_indexes_this_domain,
replisome_molecule_indexes_parent_domain,
)
)
# Add remaining RNAPs in this domain after accounting for removals
# due to collisions with replication forks
new_molecule_coordinates_this_domain = np.concatenate(
(
new_molecule_coordinates_this_domain,
RNAP_coordinates_this_domain[domain_remaining_RNAPs_mask],
)
)
new_molecule_indexes_this_domain = np.concatenate(
(
new_molecule_indexes_this_domain,
RNAP_unique_indexes_this_domain[domain_remaining_RNAPs_mask],
)
)
# If there are no molecules left on this domain, continue
if len(new_molecule_indexes_this_domain) == 0:
continue
# Calculate attributes of new segments
new_segment_attrs = self._compute_new_segment_attributes(
boundary_molecule_indexes_this_domain,
boundary_coordinates_this_domain,
linking_numbers_this_domain,
new_molecule_indexes_this_domain,
new_molecule_coordinates_this_domain,
domain_spans_oriC,
domain_spans_terC,
)
# Append to existing array of new segment attributes
all_new_boundary_molecule_indexes = np.vstack(
(
all_new_boundary_molecule_indexes,
new_segment_attrs["boundary_molecule_indexes"],
)
)
all_new_boundary_coordinates = np.vstack(
(
all_new_boundary_coordinates,
new_segment_attrs["boundary_coordinates"],
)
)
all_new_segment_domain_indexes = np.concatenate(
(
all_new_segment_domain_indexes,
np.full(
len(new_segment_attrs["linking_numbers"]),
domain_index,
dtype=np.int32,
),
)
)
all_new_linking_numbers = np.concatenate(
(all_new_linking_numbers, new_segment_attrs["linking_numbers"])
)
# Delete all existing chromosomal segments
if len(boundary_molecule_indexes) > 0:
update["chromosomal_segments"].update(
{"delete": np.arange(len(boundary_molecule_indexes))}
)
# Add new chromosomal segments
update["chromosomal_segments"].update(
{
"add": {
"boundary_molecule_indexes": all_new_boundary_molecule_indexes,
"boundary_coordinates": all_new_boundary_coordinates,
"domain_index": all_new_segment_domain_indexes,
"linking_number": all_new_linking_numbers,
}
}
)
# Figure out if any additional RNAPs were removed due to collisions with
# replication forks where there were no replisomes
empty_fork_RNAP_collision_mask = np.logical_and(
removed_RNAP_masks_all_domains,
np.logical_not(
np.logical_or(
RNAP_headon_collision_mask, RNAP_codirectional_collision_mask
)
),
)
update["listeners"]["rnap_data"].update(
{
"n_empty_fork_collisions": empty_fork_RNAP_collision_mask.sum(),
"empty_fork_collision_coordinates": RNAP_coordinates[
empty_fork_RNAP_collision_mask
],
}
)
# Get mask for RNAs that are transcribed from removed RNAPs
removed_RNAs_mask = np.isin(
RNA_RNAP_indexes, RNAP_unique_indexes[removed_RNAPs_mask]
)
# Initialize counts of incomplete transcription events
incomplete_transcription_event = np.zeros(self.n_TUs)
# Remove RNAPs and RNAs that have collided with replisomes
if n_total_collisions > 0:
if removed_RNAPs_mask.sum() > 0:
update["active_RNAPs"].update(
{"delete": np.where(removed_RNAPs_mask)[0]}
)
if removed_RNAs_mask.sum() > 0:
update["RNAs"].update({"delete": np.where(removed_RNAs_mask)[0]})
# Increment counts of inactive RNAPs
update["bulk"].append((self.inactive_RNAPs_idx, n_total_collisions))
# Get sequences of incomplete transcripts
incomplete_sequence_lengths = transcript_lengths[removed_RNAs_mask]
n_initiated_sequences = np.count_nonzero(incomplete_sequence_lengths)
n_ppi_added = n_initiated_sequences
if n_initiated_sequences > 0:
incomplete_rna_indexes = RNA_TU_indexes[removed_RNAs_mask]
incomplete_transcription_event = np.bincount(
incomplete_rna_indexes, minlength=self.n_TUs
)
incomplete_sequences = buildSequences(
self.rna_sequences,
incomplete_rna_indexes,
np.zeros(n_total_collisions, dtype=np.int64),
np.full(n_total_collisions, incomplete_sequence_lengths.max()),
)
mature_rna_counts = np.zeros(self.n_mature_rnas, dtype=np.int64)
base_counts = np.zeros(self.n_fragment_bases, dtype=np.int64)
for ri, sl, seq in zip(
incomplete_rna_indexes,
incomplete_sequence_lengths,
incomplete_sequences,
):
# Check if incomplete RNA is an unprocessed RNA
if ri in self.unprocessed_rna_index_mapping:
# Find mature RNA molecules that would need to be added
# given the length of the incomplete RNA
mature_rna_end_pos = self.mature_rna_end_positions[
:, self.unprocessed_rna_index_mapping[ri]
]
mature_rnas_produced = np.logical_and(
mature_rna_end_pos != 0, mature_rna_end_pos < sl
)
# Increment counts of mature RNAs
mature_rna_counts += mature_rnas_produced
# Increment counts of fragment NTPs, but exclude bases
# that are part of the mature RNAs generated
base_counts += np.bincount(
seq[:sl], minlength=self.n_fragment_bases
) - self.mature_rna_nt_counts[mature_rnas_produced, :].sum(
axis=0
)
# Exclude ppi molecules that are part of mature RNAs
n_ppi_added -= mature_rnas_produced.sum()
else:
base_counts += np.bincount(
seq[:sl], minlength=self.n_fragment_bases
)
base_counts += np.bincount(
seq[:sl], minlength=self.n_fragment_bases
)
# Increment counts of mature RNAs, fragment NTPs and phosphates
update["bulk"].append((self.mature_rna_idx, mature_rna_counts))
update["bulk"].append((self.fragmentBasesIdx, base_counts))
update["bulk"].append((self.ppi_idx, n_ppi_added))
assert n_initiated_sequences == incomplete_transcription_event.sum()
update["listeners"]["rnap_data"]["incomplete_transcription_event"] = (
incomplete_transcription_event
)
# Get mask for ribosomes that are bound to nonexisting mRNAs
remaining_RNA_unique_indexes = RNA_unique_indexes[
np.logical_not(removed_RNAs_mask)
]
removed_ribosomes_mask = np.logical_not(
np.isin(ribosome_mRNA_indexes, remaining_RNA_unique_indexes)
)
n_removed_ribosomes = np.count_nonzero(removed_ribosomes_mask)
# Remove ribosomes that are bound to missing RNA molecules. This
# includes both RNAs removed by this function and RNAs removed
# by other processes (e.g. RNA degradation).
if n_removed_ribosomes > 0:
update["active_ribosome"].update(
{"delete": np.where(removed_ribosomes_mask)[0]}
)
# Increment counts of inactive ribosomal subunits
update["bulk"].extend(
[
(self.ribosome_30S_subunit_idx, n_removed_ribosomes),
(self.ribosome_50S_subunit_idx, n_removed_ribosomes),
]
)
# Get amino acid sequences of incomplete polypeptides
incomplete_sequence_lengths = ribosome_peptide_lengths[
removed_ribosomes_mask
]
n_initiated_sequences = np.count_nonzero(incomplete_sequence_lengths)
if n_initiated_sequences > 0:
incomplete_sequences = buildSequences(
self.protein_sequences,
ribosome_protein_indexes[removed_ribosomes_mask],
np.zeros(n_removed_ribosomes, dtype=np.int64),
np.full(n_removed_ribosomes, incomplete_sequence_lengths.max()),
)
amino_acid_counts = np.zeros(self.n_amino_acids, dtype=np.int64)
for sl, seq in zip(incomplete_sequence_lengths, incomplete_sequences):
amino_acid_counts += np.bincount(
seq[:sl], minlength=self.n_amino_acids
)
# Increment counts of free amino acids and decrease counts of
# free water molecules
update["bulk"].append((self.amino_acids_idx, amino_acid_counts))
update["bulk"].append(
(
self.water_idx,
(n_initiated_sequences - incomplete_sequence_lengths.sum()),
)
)
# Write to listener
update["listeners"]["rnap_data"]["n_removed_ribosomes"] = n_removed_ribosomes
def get_replicated_motif_attributes(old_coordinates, old_domain_indexes):
"""
Computes the attributes of replicated motifs on the chromosome,
given the old coordinates and domain indexes of the original motifs.
"""
# Coordinates are simply repeated
new_coordinates = np.repeat(old_coordinates, 2)
# Domain indexes are set to the child indexes of the original index
new_domain_indexes = child_domains[
np.array(
[
np.where(all_chromosome_domain_indexes == idx)[0][0]
for idx in old_domain_indexes
]
),
:,
].flatten()
return new_coordinates, new_domain_indexes
#######################
# Replicate promoters #
#######################
n_new_promoters = 2 * np.count_nonzero(removed_promoters_mask)
if n_new_promoters > 0:
# Delete original promoters
update["promoters"].update({"delete": np.where(removed_promoters_mask)[0]})
# Add freed active tfs
update["bulk"].append(
(
self.active_tfs_idx,
promoter_bound_TFs[removed_promoters_mask, :].sum(axis=0),
)
)
# Set up attributes for the replicated promoters
promoter_TU_indexes_new = np.repeat(
promoter_TU_indexes[removed_promoters_mask], 2
)
(promoter_coordinates_new, promoter_domain_indexes_new) = (
get_replicated_motif_attributes(
promoter_coordinates[removed_promoters_mask],
promoter_domain_indexes[removed_promoters_mask],
)
)
# Add new promoters with new domain indexes
update["promoters"].update(
{
"add": {
"TU_index": promoter_TU_indexes_new,
"coordinates": promoter_coordinates_new,
"domain_index": promoter_domain_indexes_new,
"bound_TF": np.zeros(
(n_new_promoters, self.n_TFs), dtype=np.bool_
),
}
}
)
# Replicate genes
n_new_genes = 2 * np.count_nonzero(removed_genes_mask)
if n_new_genes > 0:
# Delete original genes
update["genes"].update({"delete": np.where(removed_genes_mask)[0]})
# Set up attributes for the replicated genes
gene_cistron_indexes_new = np.repeat(
gene_cistron_indexes[removed_genes_mask], 2
)
gene_coordinates_new, gene_domain_indexes_new = (
get_replicated_motif_attributes(
gene_coordinates[removed_genes_mask],
gene_domain_indexes[removed_genes_mask],
)
)
# Add new genes with new domain indexes
update["genes"].update(
{
"add": {
"cistron_index": gene_cistron_indexes_new,
"coordinates": gene_coordinates_new,
"domain_index": gene_domain_indexes_new,
}
}
)
########################
# Replicate DnaA boxes #
########################
n_new_DnaA_boxes = 2 * np.count_nonzero(removed_DnaA_boxes_mask)
if n_new_DnaA_boxes > 0:
# Delete original DnaA boxes
if removed_DnaA_boxes_mask.sum() > 0:
update["DnaA_boxes"].update(
{"delete": np.where(removed_DnaA_boxes_mask)[0]}
)
# Set up attributes for the replicated boxes
(DnaA_box_coordinates_new, DnaA_box_domain_indexes_new) = (
get_replicated_motif_attributes(
DnaA_box_coordinates[removed_DnaA_boxes_mask],
DnaA_box_domain_indexes[removed_DnaA_boxes_mask],
)
)
# Add new DnaA boxes with new domain indexes
dict_dna = {
"add": {
"coordinates": DnaA_box_coordinates_new,
"domain_index": DnaA_box_domain_indexes_new,
"DnaA_bound": np.zeros(n_new_DnaA_boxes, dtype=np.bool_),
}
}
update["DnaA_boxes"].update(dict_dna)
update["next_update_time"] = states["global_time"] + states["timestep"]
return update
def _compute_new_segment_attributes(
self,
old_boundary_molecule_indexes: npt.NDArray[np.int64],
old_boundary_coordinates: npt.NDArray[np.int64],
old_linking_numbers: npt.NDArray[np.int64],
new_molecule_indexes: npt.NDArray[np.int64],
new_molecule_coordinates: npt.NDArray[np.int64],
spans_oriC: bool,
spans_terC: bool,
) -> dict[str, npt.NDArray[np.int64]]:
"""
Calculates the updated attributes of chromosomal segments belonging to
a specific chromosomal domain, given the previous and current
coordinates of molecules bound to the chromosome.
Args:
old_boundary_molecule_indexes: (N, 2) array of unique
indexes of molecules that formed the boundaries of each
chromosomal segment in the previous timestep.
old_boundary_coordinates: (N, 2) array of chromosomal
coordinates of molecules that formed the boundaries of each
chromosomal segment in the previous timestep.
old_linking_numbers: (N,) array of linking numbers of each
chromosomal segment in the previous timestep.
new_molecule_indexes: (N,) array of unique indexes of all
molecules bound to the domain at the current timestep.
new_molecule_coordinates: (N,) array of chromosomal
coordinates of all molecules bound to the domain at the current
timestep.
spans_oriC: True if the domain spans the origin.
spans_terC: True if the domain spans the terminus.
Returns:
Dictionary of the following format::
{
'boundary_molecule_indexes': (M, 2) array of unique
indexes of molecules that form the boundaries of new
chromosomal segments,
'boundary_coordinates': (M, 2) array of chromosomal
coordinates of molecules that form the boundaries of
new chromosomal segments,
'linking_numbers': (M,) array of linking numbers of new
chromosomal segments
}
"""
# Sort old segment arrays by coordinates of left boundary
old_coordinates_argsort = np.argsort(old_boundary_coordinates[:, 0])