-
Notifications
You must be signed in to change notification settings - Fork 0
/
plots.py
1570 lines (913 loc) · 50.5 KB
/
plots.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
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 10 13:04:08 2022
@author: asus
"""
import argparse
import configparser
from collections import namedtuple
import numpy as np
import pandas as pd
import scipy.interpolate as interp
import math
import matplotlib.pylab as plt
import seaborn as sns
from collections import Counter
import scipy.stats as st
import os
config = configparser.ConfigParser()
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="read configuration file.")
parser.add_argument("-theoretical_poisson", help="plot simulation states distribution and theoretical distribution of SSA results.", action = "store_true")
parser.add_argument("-distribution", help="plot simulation states distribution of SSA results.", action = "store_true")
parser.add_argument("-tauleap_distribution", help="plot simulation states distribution given by tauleap algorithm.", action = "store_true")
parser.add_argument("-ssa_tauleap_distribution", help="plot simulation states distribution given by SSA vs Tau-leap algorithms", action = "store_true")
parser.add_argument("-hybrid_distribution", help="plot simulation states distribution given by SSA/Tau-leap algorithm.", action = "store_true")
parser.add_argument("-ssa_hybrid_distribution", help="plot simulation states distribution of first model using SSA.", action = "store_true")
parser.add_argument("-all_distributions", help="plot simulation states distribution and theoretical distribution given by all algorithms.", action = "store_true")
parser.add_argument("-ssa_autorepressor_distribution", help="plot simulation states distribution of autorepressor model using SSA.", action = "store_true")
parser.add_argument("-ssa_hybrid_autorepressor_distribution", help="plot SSA simulation states distribution vs hybrid simulation states distribution of autorepressor model.", action = "store_true")
parser.add_argument("-time_plot", help="plot gene activity and number of molecules as function of time of SSA results.", action = "store_true")
parser.add_argument("-two_ind_genes_time_plot", help="plot number of molecules as function of time for two indipendent genes.", action = "store_true")
parser.add_argument("-autorepressor_time_plot", help="plot number of molecules as function of time for autorepressor system.", action = "store_true")
parser.add_argument("-hybrid_autorepressor_time_plot", help="plot number of molecules as function of time for autorepressor system using hybrid simulation results.", action = "store_true")
parser.add_argument("-hybrid_toggleswitch_time_plot", help="plot number of molecules as function of time for autorepressor system using hybrid simulation results.", action = "store_true")
parser.add_argument("-toggleswitch_time_plot", help="plot number of molecules as function of time for toggle switch system.", action = "store_true")
parser.add_argument("-tauleaptime_plot", help="plot gene activity and number of molecules as function of time of tauleap algorithm results.", action = "store_true")
parser.add_argument("-hybridtime_plot", help="plot gene activity and number of molecules as function of time of SSA/Tau-leap algorithm results.", action = "store_true")
parser.add_argument("-nfkb_timeplot", help="plot nfkb gene expression.", action = "store_true")
parser.add_argument("-plot_mean",help="plot mean of N simulations", action = "store_true")
parser.add_argument("-remove_warmup_time_plot", help="plot number of molecoles vs time given by SSA removing initial warmup period.", action = "store_true")
parser.add_argument("-remove_warmup_tauleaptime_plot", help="plot number of molecoles vs time given by tauleap removing initial warmup period", action = "store_true")
parser.add_argument("-remove_warmup", help="plot gene activity and number of molecules as function of time without warmup period.", action = "store_true")
parser.add_argument("-multiple_simulations", help="plot number of molecules as function of time for multiple simulations. It has to be called after one of the flags that refers to a time plot.", action = "store_true")
parser.add_argument("-remove_warmup_multiple_simulations", help="plot number of molecules as function of time for multiple simulations without warmup period.", action = "store_true")
#parser.add_argument("-all_plots", help="makes all possible plots provided by plots.py", action = "store_true")
args = parser.parse_args()
config.read(args.filename)
if args.two_ind_genes_time_plot or args.toggleswitch_time_plot or args.hybrid_toggleswitch_time_plot:
def read_k_values_2_ind_genes():
"""This function reads k parameters from configuration file
"""
k_value = dict(config["RATES"])
for key,value in k_value.items():
k_value[key] = float(value)
rates = namedtuple("Rates",['ka_1', 'ki_1', 'k1_1', 'k2_1', 'k3_1', 'k4_1', 'k5_1',
'ka_2', 'ki_2', 'k1_2', 'k2_2', 'k3_2', 'k4_2','k5_2'])
rate = rates(ka_1 = k_value['ka_1'],
ki_1 = k_value['ki_1'],
k1_1 = k_value['k1_1'],
k2_1 = k_value['k2_1'],
k3_1 = k_value['k3_1'],
k4_1 = k_value['k4_1'],
ka_2 = k_value['ka_2'],
ki_2 = k_value['ki_2'],
k1_2 = k_value['k1_2'],
k2_2 = k_value['k2_2'],
k3_2 = k_value['k3_2'],
k4_2 = k_value['k4_2'],
k5_1 = k_value['k5_1'],
k5_2 = k_value['k5_1'])
return rate
rate = read_k_values_2_ind_genes()
else:
def read_k_values():
"""This function reads k parameters from configuration file
"""
k_value = dict(config["RATES"])
for key,value in k_value.items():
k_value[key] = float(value)
rates = namedtuple("Rates",['ka', 'ki', 'k1', 'k2', 'k3', 'k4', 'k5'])
rate = rates(ka = k_value['ka'],
ki = k_value['ki'],
k1 = k_value['k1'],
k2 = k_value['k2'],
k3 = k_value['k3'],
k4 = k_value['k4'],
k5 = k_value['k5'])
return rate
rate = read_k_values()
def read_simulation_parameters():
"""This function reads simulation parameters from configuration file
"""
simulation = dict(config["SIMULATION"])
for key,value in simulation.items():
if key == 'dt':
simulation[key] = float(value)
else:
simulation[key] = int(value)
time_limit = simulation['time_limit']
N = simulation['n_simulations']
warmup_time = simulation['warmup_time']
seed_number = simulation['seed_number']
dt = simulation['dt']
return time_limit, N, warmup_time, seed_number, dt
time_limit, N, warmup_time, seed_number, dt = read_simulation_parameters()
#%%
#results = pd.read_csv('gillespiesimulation_results.csv', sep=" ")
#tauleap_results = pd.read_csv('tauleapsimulation_results.csv', sep=" ")
def MoleculesVsTimePlot(df, df_1=None):
"""This function plots gene activity, the number of RNA molecules
produced vs time and the number of proteins produced vs time
"""
fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(5, 10))
ax[0].plot(df['Time'], df['Gene activity'])
ax[0].set_ylabel('Gene Activity')
ax[0].set_xlabel('Time (a.u.)')
ax[0].set_yticks([0,1])
ax[0].set_yticklabels(['inactive','active'])
if args.tauleaptime_plot:
ax[0].text(0.9,0.3,r"$\tau$={}".format(dt),
ha='center', va='center', fontsize=9, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[0].transAxes)
ax[0].text(0.9,0.8,"$K_a$=$n_i${}\n $K_i$=$n_a${}".format(rate.ka,rate.ki),
ha='center', va='center', fontsize=9, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[0].transAxes)
ax[1].plot(df['Time'], df['Number of RNA molecules'])
ax[1].set_ylabel('# of RNA molecules')
ax[1].set_xlabel('Time (a.u.)')
ax[1].text(0.9,0.8,"$K_1$=$n_a${}\n $K_2$=m{}".format(rate.k1, rate.k2),
ha ='center', va = 'center', fontsize=9, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[1].transAxes)
ax[2].plot(df['Time'], df['Number of proteins'])
ax[2].set_ylabel('# of proteins')
ax[2].set_xlabel('Time (a.u.)')
ax[2].text(0.9,0.8,"$K_3$=m{}\n $K_4$=p{}".format(rate.k3, rate.k4),
ha='center', va='center', fontsize=9, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[2].transAxes)
sns.despine(fig, bottom=False, left=False)
plt.show()
def MoleculesVsTimePlot_nfkb(df):
"""This function plots gene activity, the number of RNA molecules
produced vs time and the number of proteins produced vs time
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5, 10))
#ax[0].plot(df['Time'], df['NFkB activity'])
#ax[0].set_ylabel('NFkB Activity')
#ax[0].set_xlabel('Time (a.u.)')
#ax[0].set_yticks([0,1])
#ax[0].set_yticklabels(['inactive','active'])
ax.plot(df['Time'], df['Number of RNA molecules'])
ax.set_ylabel('# of RNA molecules')
ax.set_xlabel('Time (a.u.)')
sns.despine(fig, bottom=False, left=False)
plt.show()
def MoleculesVsTimePlot_2_ind_genes(df):
"""This function plots gene activity, the number of RNA molecules
produced vs time and the number of proteins produced vs time in
the case of two indipendent genes.
"""
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(5, 10))
ax[0].plot(df['Time'], df['Number of RNAs gene1'], label = 'gene 1', color = 'blue')
ax[0].plot(df['Time'], df['Number of RNAs gene2'], label = 'gene 2', color = 'cyan')
ax[0].set_ylabel('# of RNA molecules')
ax[0].set_xlabel('Time')
ax[0].text(0.9,0.8,"$K_1$=$n_a${}\n $K_2$=m{}\n $K_1$=$n_a${}\n $K_2$=m{}".format(rate.k1_1, rate.k2_1, rate.k1_2, rate.k2_2),
ha ='center', va = 'center', fontsize=7, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[0].transAxes)
ax[0].legend(loc = 2, prop={'size': 7})
ax[1].plot(df['Time'], df['Number of proteins gene1'], color = 'blue')
ax[1].plot(df['Time'], df['Number of proteins gene2'], color = 'cyan')
ax[1].set_ylabel('# of proteins')
ax[1].set_xlabel('Time')
ax[1].text(0.9,0.8,"$K_3$=m{}\n $K_4$=p{}\n $K_3$=m{}\n $K_4$=p{}".format(rate.k3_1, rate.k4_1, rate.k3_2, rate.k4_2),
ha='center', va='center', fontsize=7, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[1].transAxes)
sns.despine(fig, bottom=False, left=False)
plt.show()
def MoleculesVsTimePlot_toggleswitch(df):
"""This function plots gene activity, the number of RNA molecules
produced vs time and the number of proteins produced vs time in
the case of two indipendent genes.
"""
fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(5, 10))
ax[0].plot(df['Time'], df['Gene1 activity'], label = 'gene 1', color = 'blue')
ax[0].plot(df['Time'], df['Gene2 activity'], label = 'gene 2', color = 'cyan', alpha = 0.5)
ax[0].set_yticks([0,1])
ax[0].set_yticklabels(['inactive','active'])
ax[0].set_ylabel('Genes activity')
ax[0].set_xlabel('Time (a.u.)')
ax[0].text(0.9,0.8,"$K_a$=$n_i${}\n $K_i$=$n_a${}".format(rate.ka_1, rate.ki_1),
ha ='center', va = 'center', fontsize=7, bbox=dict(facecolor='white', alpha=0.9, edgecolor = 'blue'),
transform = ax[0].transAxes)
ax[0].text(0.9,0.3,"$K_a$=$n_i${}\n $K_i$=$n_a${}".format(rate.ka_2, rate.ki_2),
ha ='center', va = 'bottom', fontsize=7, bbox=dict(facecolor='white', alpha=0.9, edgecolor = 'cyan'),
transform = ax[0].transAxes)
ax[0].legend(loc = 2, prop={'size': 7})
ax[1].plot(df['Time'], df['Number of RNAs gene1'], label = 'gene 1', color = 'blue')
ax[1].plot(df['Time'], df['Number of RNAs gene2'], label = 'gene 2', color = 'cyan')
ax[1].set_ylabel('# of RNA molecules')
ax[1].set_xlabel('Time (a.u.)')
ax[1].text(0.9,0.8,"$K_1$=$n_a${}\n $K_2$=m{}\n $K_1$=$n_a${}\n $K_2$=m{}".format(rate.k1_1, rate.k2_1, rate.k1_2, rate.k2_2),
ha ='center', va = 'center', fontsize=7, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[1].transAxes)
ax[2].plot(df['Time'], df['Number of proteins gene1'], color = 'blue')
ax[2].plot(df['Time'], df['Number of proteins gene2'], color = 'cyan')
ax[2].set_ylabel('# of proteins')
ax[2].set_xlabel('Time (a.u.)')
ax[2].text(0.9,0.8,"$K_3$=m{}\n $K_4$=p{}\n $K_3$=m{}\n $K_4$=p{}".format(rate.k3_1, rate.k4_1, rate.k3_2, rate.k4_2),
ha='center', va='center', fontsize=7, bbox=dict(facecolor='white', alpha=0.5),
transform = ax[2].transAxes)
sns.despine(fig, bottom=False, left=False)
plt.show()
def generate_RNA_distribution(df):
""" This function creates a Counter with RNA state values
as keys and normalized residency time as values
"""
RNA_distribution = Counter()
for state, residency_time in zip(df['Number of RNA molecules'], df['Residency Time']):
RNA_distribution[state] += residency_time
total_time_observed = sum(RNA_distribution.values())
for state in RNA_distribution:
RNA_distribution[state] /= total_time_observed
return RNA_distribution
def generate_protein_distribution(df):
""" This function creates a Counter with protein state values
as keys and normalized residency time as values
"""
protein_distribution = Counter()
for state, residency_time in zip(df['Number of proteins'], df['Residency Time']):
protein_distribution[state] += residency_time
total_time_observed = sum(protein_distribution.values())
for state in protein_distribution:
protein_distribution[state] /= total_time_observed
return protein_distribution
def find_warmup_methodI(data = 'gillespieresults_seed{}.csv'):
"""This function returns the first number of molecules of RNAs
and proteins to remove because in the warmup period"""
dataframes_list = []
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
dataframes_list.append(simulation_results)
RNAs_list = []
#Occorre interpolare perché i dati non sono stati presi tutti ad intervalli regolari
for dataframe in dataframes_list:
time = dataframe['Time']
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
RNAs = dataframe['Number of RNA molecules']
f_RNAs = interp.interp1d(time, RNAs, kind='previous')
yinterp_RNAs = f_RNAs(xvals)
RNAs_list.append(yinterp_RNAs)
RNAs_arrays = np.array(RNAs_list, dtype=object)
lengths = []
for a in RNAs_arrays:
lengths.append(len(a))
min_RNAs_arrays = [RNAs_array[:min(lengths)] for RNAs_array in RNAs_arrays]
mean_RNAs = np.mean(min_RNAs_arrays, axis=0)
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
min_time_array = xvals[:min(lengths)]
for i in np.arange(0,len(mean_RNAs)):
if math.isclose(mean_RNAs[i], mean_RNAs[i+800],abs_tol=0.4):
n_r = i
break
Proteins_list = []
for dataframe in dataframes_list:
Proteins_arrays = np.ascontiguousarray(dataframe['Number of proteins'])
Proteins_list.append(Proteins_arrays)
Proteins_arrays = np.array(Proteins_list, dtype=object)
lengths = []
for a in Proteins_arrays:
lengths.append(len(a))
min_Proteins_arrays = [Proteins_array[:min(lengths)] for Proteins_array in Proteins_arrays]
mean_Proteins = np.mean(min_Proteins_arrays, axis=0)
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
min_time_array = xvals[:min(lengths)]
for i in np.arange(0,len(mean_Proteins)):
if math.isclose(mean_Proteins[i], mean_Proteins[i+800],abs_tol=0.4):
n_p = i
break
return n_r, n_p
def find_warmupRNAS_methodI(data = 'gillespieresults_seed{}.csv'):
"""This function returns the first number of molecules of RNAs
and proteins to remove because in the warmup period"""
dataframes_list = []
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
dataframes_list.append(simulation_results)
RNAs_list = []
#Occorre interpolare perché i dati non sono stati presi tutti ad intervalli regolari
for dataframe in dataframes_list:
time = dataframe['Time']
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
RNAs = dataframe['Number of RNA molecules']
f_RNAs = interp.interp1d(time, RNAs, kind='previous')
yinterp_RNAs = f_RNAs(xvals)
RNAs_list.append(yinterp_RNAs)
RNAs_arrays = np.array(RNAs_list, dtype=object)
lengths = []
for a in RNAs_arrays:
lengths.append(len(a))
min_RNAs_arrays = [RNAs_array[:min(lengths)] for RNAs_array in RNAs_arrays]
mean_RNAs = np.mean(min_RNAs_arrays, axis=0)
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
min_time_array = xvals[:min(lengths)]
for i in np.arange(0,len(mean_RNAs)):
if math.isclose(mean_RNAs[i], mean_RNAs[i+800],abs_tol=0.4):
n_r = i
break
return n_r
def find_warmup_methodII(data = 'gillespieresults_seed{}.csv'):
"""This function returns the first number of molecules of RNAs
and proteins to remove because in the warmup period. The method
used calculates the number of molecules at t+dt, the number
of molecules at t+2dt and the number of molecules at t+3dt.
When the difference is lower than 0.4, the number of molecules are the
ones in the warmup period."""
dataframes_list = []
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
dataframes_list.append(simulation_results)
RNAs_list = []
#Occorre interpolare perché i dati non sono stati presi tutti ad intervalli regolari
for dataframe in dataframes_list:
time = dataframe['Time']
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
RNAs = dataframe['Number of RNA molecules']
f_RNAs = interp.interp1d(time, RNAs, kind='previous')
yinterp_RNAs = f_RNAs(xvals)
RNAs_list.append(yinterp_RNAs)
RNAs_arrays = np.array(RNAs_list, dtype=object)
lengths = []
for a in RNAs_arrays:
lengths.append(len(a))
min_RNAs_arrays = [RNAs_array[:min(lengths)] for RNAs_array in RNAs_arrays]
mean_RNAs = np.mean(min_RNAs_arrays, axis=0)
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
#min_time_array = xvals[:min(lengths)]
di = 5
for i in np.arange(0,len(mean_RNAs)):
if math.isclose(mean_RNAs[i], mean_RNAs[i+di],abs_tol=0.4) and math.isclose(mean_RNAs[i+di], mean_RNAs[i+2*di],abs_tol=0.4) and math.isclose(mean_RNAs[i+2*di], mean_RNAs[i+3*di],abs_tol=0.4):
n_r = i
break
Proteins_list = []
for dataframe in dataframes_list:
Proteins_arrays = np.ascontiguousarray(dataframe['Number of proteins'])
Proteins_list.append(Proteins_arrays)
Proteins_arrays = np.array(Proteins_list, dtype=object)
lengths = []
for a in Proteins_arrays:
lengths.append(len(a))
min_Proteins_arrays = [Proteins_array[:min(lengths)] for Proteins_array in Proteins_arrays]
mean_Proteins = np.mean(min_Proteins_arrays, axis=0)
xvals = np.arange(dataframe['Time'].iloc[0], dataframe['Time'].iloc[-1], 0.01)
#min_time_array = xvals[:min(lengths)]
for i in np.arange(0,len(mean_Proteins)):
if math.isclose(mean_Proteins[i], mean_Proteins[i+di],abs_tol=0.4) and math.isclose(mean_Proteins[i+di],mean_Proteins[i+2*di],abs_tol=0.4) and math.isclose(mean_Proteins[i+2*di],mean_Proteins[i+3*di],abs_tol=0.4):
n_p = i
break
return n_r, n_p
#========================================================
"""
#Remove warmup in case of first protein synthesis modeling ka 1 ki 0
N=64
data = 'ka1ki0gillespieresults_seed{}.csv'
#find warmup-period
n_r, n_p = find_warmup(data = data)
dataframes_list = []
#remove warmup
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
simulation_results = simulation_results.iloc[n_r:]
dataframes_list.append(simulation_results)
#prepare names of new data files
results_names = []
for n in range(1,N+1):
results_names.append("removed_warmup_ka1ki0gillespieresults_seed"+str(n))
#save removed warmup data
actual_dir = os.getcwd()
file_path = r'{}\{}.csv'
for dataframe, results in zip(dataframes_list, results_names):
dataframe.to_csv(file_path.format(actual_dir,results), sep=" ", index = None, header=True)
#df = pd.read_csv('ka1ki0gillespieresults_seed1.csv', sep=" ")
#df
#df.iloc[4:]
#Remove warmup in case of first protein synthesis modeling ka 1 ki 0.5
N=64
data = 'ka1ki0.5gillespieresults_seed{}.csv'
#find warmup-period
n_r, n_p = find_warmup(data = data)
dataframes_list = []
#remove warmup
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
simulation_results = simulation_results.iloc[n_r:]
dataframes_list.append(simulation_results)
#prepare names of new data files
results_names = []
for n in range(1,N+1):
results_names.append("removed_warmup_ka1ki0.5gillespieresults_seed"+str(n))
#save removed warmup data
actual_dir = os.getcwd()
file_path = r'{}\{}.csv'
for dataframe, results in zip(dataframes_list, results_names):
dataframe.to_csv(file_path.format(actual_dir,results), sep=" ", index = None, header=True)
#Remove warmup in case of NF-kB products in case of one simulation
df = pd.read_csv("nfkb_k20k2i0gillespiesimulation_results.csv", sep=" ")
df = df.iloc[100:]
df.to_csv(file_path.format(actual_dir,"removed_warmup_nfkb_k20k2i0gillespiesimulation_results"), sep =" ", index = None, header=True, mode = "w")
N=64
data = 'nfkb_k20k2i0gillespiesimulation_results_seed{}.csv'
#find warmup-period
#n_r = find_warmupRNAS(data = data)
dataframes_list = []
#remove warmup
for n in range(1,N+1):
simulation_results = pd.read_csv(data.format(n), sep=" ")
simulation_results = simulation_results.iloc[100:]
dataframes_list.append(simulation_results)
#prepare names of new data files
results_names = []
for n in range(1,N+1):
results_names.append("removed_warmup_nfkb_k20k2i0gillespiesimulation_results_seed"+str(n))
#save removed warmup data
actual_dir = os.getcwd()
file_path = r'{}\{}.csv'
for dataframe, results in zip(dataframes_list, results_names):
dataframe.to_csv(file_path.format(actual_dir,results), sep=" ", index = None, header=True)
"""
#results = pd.read_csv('gillespiesimulation_results.csv', sep=" ")
#results[0:10]
#results = results[:10]
#results = results.iloc[10:]
#results
"""
#===============================================================
n_r, n_p = find_warmup_method1(data='ka1ki0.5gillespieresults_seed{}.csv')
results = pd.read_csv('gillespiesimulation_results.csv', sep=" ")
results = results[n_r:]
plt.plot(results['Time'], results['Number of proteins'])
plt.plot(results['Time'],results['Number of RNA molecules'])
#Delete the first rows RNAs
results_RNAs = results.drop('Number of proteins',axis=1)
results_RNAs_ssa = results_RNAs[n_r:]
plt.plot(results_RNAs_ssa['Time'],results_RNAs_ssa['Number of RNA molecules'])
#Delete the first rows proteins
results_proteins = results.drop('Number of RNA molecules',axis=1)
results_proteins_ssa = results_proteins[n_p:]
#========================================================
n_r, n_p = remove_warmup(data = 'tauleapresults_seed{}.csv')
results = pd.read_csv('tauleapsimulation_results.csv', sep=" ")
#Delete the first rows RNAs
results_RNAs = results.drop('Number of proteins',axis=1)
results_RNAs_tauleap = results_RNAs[n_r:]
#Delete the first rows proteins
results_proteins = results.drop('Number of RNA molecules',axis=1)
results_proteins_tauleap = results_proteins[n_p:]
#========================================================
n_r, n_p = remove_warmup(data = 'hybridsimulation_results_seed{}.csv')
results = pd.read_csv('hybridsimulation_results.csv', sep=" ")
#Delete the first rows RNAs
results_RNAs = results.drop('Number of proteins',axis=1)
results_RNAs_hybrid = results_RNAs[n_r:]
#Delete the first rows proteins
results_proteins = results.drop('Number of RNA molecules',axis=1)
results_proteins_hybrid = results_proteins[n_p:]
#========================================================
"""
def StatesDistributionPlot(df_1=None, df_2=None, df_3=None,df_4=None):
""" This function plots the probability distribution of
observing each state
"""
RNA_distribution = generate_RNA_distribution(df_1)
protein_distribution = generate_protein_distribution(df_2)
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 15))
if args.hybrid_distribution or args.tauleap_distribution or args.distribution:
ax[0].bar(RNA_distribution.keys(), RNA_distribution.values())
ax[0].set_ylabel('Normalized residency time', fontsize=10)
ax[0].set_xlabel('Number of RNA molecules', fontsize=10)
if args.theoretical_poisson:
values = np.arange(20)
pmf = st.poisson(10).pmf(values)
ax[0].bar(values, pmf, alpha=0.5)
ax[0].set_title('First basic model (ka={},ki={})'.format(rate.ka,rate.ki), fontsize=10)
if args.hybrid_distribution:
simulation = "Hybrid Simulation"
elif args.tauleap_distribution:
simulation = "Tau-leap"
elif args.distribution:
simulation = "SSA"
ax[0].legend(["{} Simulation".format(simulation)], fontsize=10)
ax[1].bar(protein_distribution.keys(), protein_distribution.values())
ax[1].set_ylabel('Normalized residency time', fontsize=10)
ax[1].set_xlabel('Number of proteins', fontsize=10)
ax[1].legend(["{} Simulation".format(simulation)], fontsize=10)
if args.theoretical_poisson:
values = np.arange(20)
pmf = st.poisson(1).pmf(values)
ax[1].bar(values, pmf, alpha=0.5)
elif args.ssa_autorepressor_distribution:
simulation = "SSA"
ax[0].bar(RNA_distribution.keys(), RNA_distribution.values())
ax[0].set_ylabel('Normalized residency time', fontsize=10)
ax[0].set_xlabel('Number of RNA molecules', fontsize=10)
ax[0].set_title('Autorepressor (ka={}, ki={})'.format(rate.ka,rate.ki), fontsize=14)
ax[0].legend(["{} Simulation".format(simulation)], fontsize=10)
ax[1].bar(protein_distribution.keys(), protein_distribution.values())
ax[1].set_ylabel('Normalized residency time', fontsize=10)
ax[1].set_xlabel('Number of proteins', fontsize=10)
elif args.ssa_hybrid_autorepressor_distribution:
RNA_distribution_hybrid = generate_RNA_distribution(df_1)
protein_distribution_hybrid = generate_protein_distribution(df_1)
#simulation = "SSA vs Hybrid"
ax[0].bar(RNA_distribution.keys(), RNA_distribution.values())
ax[0].bar(RNA_distribution_hybrid.keys(), RNA_distribution_hybrid.values(), alpha=0.7)
ax[0].set_ylabel('Normalized residency time', fontsize=10)
ax[0].set_xlabel('Number of RNA molecules', fontsize=10)
ax[0].set_title('Autorepressor (ka={}, ki={})'.format(rate.ka,rate.ki), fontsize=14)
ax[0].legend(["SSA Simulation","Hybrid simulation"], fontsize=10)
ax[1].bar(protein_distribution.keys(), protein_distribution.values())
ax[1].bar(protein_distribution_hybrid.keys(), protein_distribution_hybrid.values(), alpha=0.7)
ax[1].set_ylabel('Normalized residency time', fontsize=10)
ax[1].set_xlabel('Number of proteins', fontsize=10)
elif args.ssa_hybrid_distribution or args.ssa_tauleap_distribution:
RNA_distribution_hybrid = generate_RNA_distribution(df_3)
protein_distribution_hybrid = generate_protein_distribution(df_4)
#simulation = "SSA vs Hybrid"
ax[0].bar(RNA_distribution.keys(), RNA_distribution.values())
ax[0].bar(RNA_distribution_hybrid.keys(), RNA_distribution_hybrid.values(), alpha=0.7)
ax[0].set_ylabel('Normalized residency time', fontsize=10)
ax[0].set_xlabel('Number of RNA molecules', fontsize=10)
ax[0].set_title('First protein synthesis model (ka={}, ki={})'.format(rate.ka,rate.ki), fontsize=14)
if args.ssa_hybrid_distribution:
ax[0].legend(["SSA simulation","Hybrid simulation"], fontsize=10)
elif args.ssa_tauleap_distribution:
ax[0].legend(["SSA simulation","Tauleap simulation \u03C4 = {}".format(dt)], fontsize=10)
ax[1].bar(protein_distribution.keys(), protein_distribution.values())
ax[1].bar(protein_distribution_hybrid.keys(), protein_distribution_hybrid.values(), alpha=0.7)
ax[1].set_ylabel('Normalized residency time', fontsize=10)
ax[1].set_xlabel('Number of proteins', fontsize=10)
sns.despine(fig, bottom=False, left=False)
plt.show()
def AllStatesDistributionPlot():
""" This function plots the probability distribution of
observing each state
"""
results = pd.read_csv('gillespiesimulation_results.csv', sep=" ")
RNA_distribution = generate_RNA_distribution(df = results)
protein_distribution = generate_protein_distribution(df = results)
tauleap_results = pd.read_csv('tauleapsimulation_results.csv', sep=" ")
RNA_distribution_tauleap = generate_RNA_distribution(df = tauleap_results)
protein_distribution_tauleap = generate_protein_distribution(df = tauleap_results)
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 15))
values = np.arange(20)
pmf = st.poisson(10).pmf(values)
ax[0].bar(RNA_distribution.keys(), RNA_distribution.values())
ax[0].bar(RNA_distribution_tauleap.keys(), RNA_distribution_tauleap.values(), alpha=0.9)
ax[0].set_ylabel('Normalized residency time', fontsize=10)
ax[0].set_xlabel('Number of RNA molecules', fontsize=10)
ax[0].bar(values, pmf, alpha=0.5)
ax[0].legend(["SSA","Tau-leap","Poisson distribution"], fontsize=10, loc = "upper right")
ax[1].bar(protein_distribution.keys(), protein_distribution.values())
ax[1].bar(protein_distribution_tauleap.keys(), protein_distribution_tauleap.values(), alpha=0.5)
ax[1].set_ylabel('Normalized residency time', fontsize=10)
ax[1].set_xlabel('Number of proteins', fontsize=10)
ax[1].bar(values, pmf, alpha=0.5)
sns.despine(fig, bottom=False, left=False)
plt.show()
"""
def ssa_gene_activity_distribution():
#This function plots the states of gene.
results = pd.read_csv('gillespiesimulation_results.csv', sep=" ")
gene_activity = results['Gene activity']
gene_activity = np.ascontiguousarray(gene_activity)
plt.hist(gene_activity)
gene_activity = gene_activity.tolist()
print("Number of times gene is active {}".format(gene_activity.count(1)))
print("Number of times gene is inactive {}".format(gene_activity.count(0)))
plt.show()
ssa_gene_activity_distribution()
def hybrid_gene_activity_distribution():
#This function plots the states of gene.
results = pd.read_csv('hybridsimulation_results.csv', sep=" ")
gene_activity = results['Gene activity']
gene_activity = np.ascontiguousarray(gene_activity)
plt.hist(gene_activity)
gene_activity = gene_activity.tolist()
print("Number of times gene is active {}".format(gene_activity.count(1)))
print("Number of times gene is inactive {}".format(gene_activity.count(0)))
plt.show()
hybrid_gene_activity_distribution()
#Nel caso dell'ibrido rimane più attivo quindi può essere la causa del fatto
#che quando dovremmo osservare degli stati a 0 questi non ci sono.
#35818-29977 = 5841 volte più attivo nell'ibrido nel caso ka=0.01 e ki=0.01.
#5914-4183 = 1731.
def generate_geneactivity_distribution(df):
#This function creates a Counter with active gene state values
#as keys and normalized residency time as values
activitygene_distribution = Counter()
for state, residency_time in zip(df['Gene activity'], df['Residency Time']):
activitygene_distribution[state] += residency_time
total_time_observed = sum(activitygene_distribution.values())
for state in activitygene_distribution:
activitygene_distribution[state] /= total_time_observed
return activitygene_distribution
def ssa_gene_activity_distribution_PLOT():