-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviral_clustering.py
2448 lines (1633 loc) · 115 KB
/
viral_clustering.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
"""
CLUSTERS AND TRACKS VIRAL LINEAGES FROM TIME SNAPSHOTS. SAVE A FILE WITH LINEAGES TRACKING IN OUTPUT, TO BE USED BY DOWNSTREAM SCRIPTS
* Copyright (C) 2021 Jacopo Marchi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
"""
import matplotlib
matplotlib.use('Agg')
import os
import glob
import sys
sys.path.append('..')
from lib.mppaper import *
import lib.mpsetup as mpsetup
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm
from scipy.optimize import fsolve
from scipy.special import factorial
from scipy.spatial.distance import pdist
import itertools
from scipy.spatial.distance import squareform
import shutil
from sklearn.cluster import DBSCAN
from sklearn.cluster import KMeans
from sklearn import metrics
from scipy.cluster.hierarchy import dendrogram, linkage, cophenet, fcluster
from sklearn.preprocessing import StandardScaler
import gc
import math
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import IncrementalPCA
import matplotlib.colors as colors
from matplotlib.mlab import bivariate_normal
from scipy import interpolate
from scipy.interpolate import splrep, splev, griddata, SmoothBivariateSpline
from scipy import stats
from sklearn.neighbors import KDTree
from scipy.optimize import curve_fit
import matplotlib.ticker as mticker
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
def get_cmap(N):
''' Returns a function that maps each index in 0, 1, ...
N-1 to a distinct RGB color.'''
color_norm = colors.Normalize(vmin=0, vmax=N-1)
#scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
scalar_map = cm.ScalarMappable(norm=color_norm, cmap='jet')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color
col_dict=colors.cnames
def label_line(line, label, x, y, color='0.5'):
"""Add a label to a line, at the proper angle.
Arguments
---------
line : matplotlib.lines.Line2D object,
label : str
x : float
x-position to place center of text (in data coordinated
y : float
y-position to place center of text (in data coordinates)
color : str
size : float
"""
xdata, ydata = line.get_data()
x1 = xdata[0]
x2 = xdata[-1]
y1 = ydata[0]
y2 = ydata[-1]
ax = line.get_axes()
# text = ax.annotate(label, xy=(x, y), xytext=(-10, 0),
# textcoords='offset points',
# color=color,
# horizontalalignment='left',
# verticalalignment='bottom')
text = ax.annotate(label, xy=(x, y), xytext=(1, -6),
textcoords='offset points',
color=color,
horizontalalignment='right',
verticalalignment='bottom')
sp1 = ax.transData.transform_point((x1, y1))
sp2 = ax.transData.transform_point((x2, y2))
rise = (sp2[1] - sp1[1])
run = (sp2[0] - sp1[0])
slope_degrees = np.degrees(np.arctan2(rise, run))
text.set_rotation(slope_degrees)
return text
# #ax.annotate(r'$\propto r^2$',
# #xy=(powlaw_x[powlaw_x.size/2], powlaw_y[powlaw_y.size/2]*4./3), xycoords='data', rotation= np.angle((powlaw_x[-1]/powlaw_x[0])*(xmin1/xmax1) + 1j * (powlaw_y[-1]/powlaw_y[0])*(ymin1/ymax1), deg=True),
# ax.annotate(r'$\propto r^2$',
# xy=(powlaw_x[powlaw_x.size/2], 2*powlaw_y[powlaw_y.size/2]*4./3), xycoords='data', rotation= np.angle((powlaw_x[-1]/powlaw_x[0])**(1./(xmax1- xmin1)) + 1j * (powlaw_y[-1]/powlaw_y[0])**(1./(ymax1- ymin1)), deg=True), rotation_mode='anchor',
# horizontalalignment='right', verticalalignment='bottom', color='grey')
# #
def rw_msd_fct_time(x, diff):
return diff*x
def mean_dispersion(X, labels): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
squared_dists=np.linalg.norm(points_in_clust - np.mean(points_in_clust, axis=0)[None,:], axis=1)**2
#print clust, points_in_clust.shape, squared_dists.shape
mean_squared_dist=np.mean(squared_dists)
#print mean_squared_dist
clust_dispersions.append(mean_squared_dist)
if len(labels_unique)>0:
return [sum(clust_dispersions)/float(len(labels_unique)), sum(clust_dispersions)]
else:
return [-1., sum(clust_dispersions)]
def clusters_size(X, labels): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
densities=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
num=points_in_clust.shape[0]
dists=np.linalg.norm(points_in_clust - np.mean(points_in_clust, axis=0)[None,:], axis=1)
#print clust, points_in_clust.shape, squared_dists.shape
mean_dist=np.mean(dists)
#print mean_squared_dist
clust_dispersions.append(np.pi*(mean_dist**2))
if mean_dist>0.1 and num>=2:
densities.append(num/(np.pi*(mean_dist**2)))
else:
densities.append(0.)
if len(labels_unique)>0:
return [sum(clust_dispersions)/float(len(labels_unique)), sum(densities)/float(len(labels_unique))]
else:
return [-1., -1.]
def clusters_dist_vars_all(X, clust_dir): # returns three floats: the variance of distances from the centroid , parrallel to the direction of motion, perpendicular, and total
#~ print "cluster rotation"
points_in_clust=X[:,:2]
#~ print np.mean(points_in_clust, axis=0)
#~ print np.average(points_in_clust, weights=X[:,3], axis=0)
#points_in_clust=points_in_clust - np.mean(points_in_clust, axis=0)[None,:] # regularize
points_in_clust=points_in_clust - np.average(points_in_clust, weights=X[:,3], axis=0)[None,:] # regularize
#~ print points_in_clust.shape
#~ print np.average(points_in_clust, weights=X[:,3], axis=0)
clust_perpdir=np.array([clust_dir[1], -clust_dir[0]])
Q = np.squeeze(np.array([clust_dir, clust_perpdir])).T
#~ print 'Transformed to original system with \n Q={}'.format(Q)
#~ print 'Orthogonality check \n {}'.format(Q.dot(Q.T))
#~ print 'Orthogonality check \n {}'.format(np.dot(Q.T, X[0,:2]) == np.linalg.solve(Q, X[0,:2]))
#~ print np.dot(Q.T, points_in_clust[0,:])
#~ print np.linalg.solve(Q, points_in_clust[0,:])
points_in_clust_newbasis=np.dot(Q.T, points_in_clust.T).T
#~ print "transformed direction of motion ", np.dot(Q.T, clust_dir)
#~ print "transformed direction perpendicular to motion ", np.dot(Q.T, clust_perpdir)
#~ print points_in_clust_newbasis.shape, np.mean(points_in_clust_newbasis, axis=0)
# v_ = np.linalg.solve(Q, v)
# print('The vector in the new coordinates \n v_={}'.format(v_))
#dists_sq=np.linalg.norm(points_in_clust_newbasis - np.mean(points_in_clust_newbasis, axis=0)[None,:], axis=1)**2
dists_sq=np.linalg.norm(points_in_clust_newbasis , axis=1)**2
#~ print points_in_clust.shape, dists_sq.shape
#var_dist=np.mean(dists_sq)
var_dist=np.average(dists_sq, weights=X[:,3])
#~ print var_dist
dists_sq_x=points_in_clust_newbasis[:,0]**2
#~ print dists_sq_x.shape
var_dist_x=np.average(dists_sq_x, weights=X[:,3])
#~ print var_dist_x
dists_sq_y=points_in_clust_newbasis[:,1]**2
#~ print dists_sq_y.shape
var_dist_y=np.average(dists_sq_y, weights=X[:,3]) # direction of motion
#~ print var_dist_y
return [var_dist_x, var_dist_y, var_dist]
def clusters_dist_vars(X, labels, clust, clust_dir, num_vir): # returns three floats: the variance of distances from the centroid , parrallel to the direction of motion, perpendicular, and total
#~ print "cluster rotation"
points_in_clust=X[labels==clust,:]
num_in_clust=num_vir[labels==clust]
#~ print np.average(points_in_clust, weights=num_in_clust, axis=0)
points_in_clust=points_in_clust - np.average(points_in_clust, weights=num_in_clust, axis=0)[None,:] # regularize
#~ print points_in_clust.shape
#~ print np.mean(points_in_clust, axis=0)
#~ print np.average(points_in_clust, weights=num_in_clust, axis=0)
clust_perpdir=np.array([clust_dir[1], -clust_dir[0]])
Q = np.array([clust_dir, clust_perpdir]).T
#~ print 'Transformed to original system with \n Q={}'.format(Q)
#~ print 'Orthogonality check \n {}'.format(Q.dot(Q.T))
#~ print 'Orthogonality check \n {}'.format(np.dot(Q.T, X[0,:]) == np.linalg.solve(Q, X[0,:]))
#~ print np.dot(Q.T, points_in_clust[0,:])
#~ print np.linalg.solve(Q, points_in_clust[0,:])
points_in_clust_newbasis=np.dot(Q.T, points_in_clust.T).T
#~ print "transformed direction of motion ", np.dot(Q.T, clust_dir)
#~ print "transformed direction perpendicular to motion ", np.dot(Q.T, clust_perpdir)
#~ print points_in_clust_newbasis.shape, np.mean(points_in_clust_newbasis, axis=0)
# v_ = np.linalg.solve(Q, v)
# print('The vector in the new coordinates \n v_={}'.format(v_))
#dists_sq=np.linalg.norm(points_in_clust_newbasis - np.mean(points_in_clust_newbasis, axis=0)[None,:], axis=1)**2
dists_sq=np.linalg.norm(points_in_clust_newbasis , axis=1)**2
#~ print clust, points_in_clust.shape, dists_sq.shape
#var_dist=np.mean(dists_sq)
var_dist=np.average(dists_sq, weights=num_in_clust)
#~ print var_dist
dists_sq_x=points_in_clust_newbasis[:,0]**2
#~ print clust, dists_sq_x.shape
var_dist_x=np.average(dists_sq_x, weights=num_in_clust)
#~ print var_dist_x
dists_sq_y=points_in_clust_newbasis[:,1]**2
#~ print clust, dists_sq_y.shape
var_dist_y=np.average(dists_sq_y, weights=num_in_clust) # direction of motion
#~ print var_dist_y
return [var_dist_x, var_dist_y, var_dist]
def inter_clusters_distance(X, labels): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
centroids=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
num=points_in_clust.shape[0]
centroid=np.mean(points_in_clust, axis=0)
#print mean_squared_dist
centroids.append(centroid)
#print len(centroids), len(labels_unique)
if len(centroids)<2:
inter_cl=0.
inter_cl_max=0.
else:
centroids=np.asarray(centroids)
#print centroids.shape
dists=pdist(centroids)
#print dists.shape
inter_cl=dists.mean()
inter_cl_max=np.amax(dists)
return [inter_cl, inter_cl_max]
def recluster_split(X, labels, core_samples_mask, num_vir): # resets the clustering labels so that splits are identified only when I see clusters splitted in the frame.
#Returns new labels and the corresponding centroids, and all basic cluster characteristics: number ppl inside, size
labels_unique=set(labels)
labels_unique.discard(-1)
labels_clust=[]
centroids=[]
max_centroid_dists=[]
max_centroid_dists=[]
nums =[]
sizes=[]
clusts=[]
coords=[]
#print labels[core_samples_mask]
#~ print "reclustering"
#print labels.shape
#print core_samples_mask.shape
#~ print len(labels_unique)
for clust in labels_unique:
#print clust
#print core_samples_mask[labels==clust].sum()
#print core_samples_mask[:20]
#print (labels==clust)[:20]
#print (core_samples_mask & (labels==clust)).sum()
#print (core_samples_mask[:20] & (labels==clust)[:20])
points_in_clust=X[labels==clust,:]
coord=points_in_clust.shape[0]
num=num_vir[labels==clust]
#centroid=np.mean(points_in_clust, axis=0)
centroid=np.average(points_in_clust, weights=num, axis=0)
core_points_in_clust=X[(labels==clust) & core_samples_mask,:]
core_dists=core_points_in_clust - np.average(points_in_clust, weights=num, axis=0)[None,:]
#
#k=num
#if num>10:
# k=10
dists=np.linalg.norm(points_in_clust - np.average(points_in_clust, weights=num, axis=0)[None,:], axis=1)
#print clust, points_in_clust.shape, squared_dists.shape
#mean_dist=np.mean(dists)
mean_dist=np.average(dists, weights=num)
#print mean_squared_dist
size=np.pi*(mean_dist**2)
modulo_dists=np.linalg.norm(core_dists, axis=1)
#ind = np.argpartition(modulo_dists, -k)[-k:] # average the 6 biggest distances to baricenter of core samples
if modulo_dists.size<2:
modulo_dists=dists
maxdist=np.amax(modulo_dists)
#maxdist=np.mean(modulo_dists[ind])
#~ print maxdist
#~ print centroid
#print core_points_in_clust[np.argmax(modulo_dists),:]
#print num, np.argmax(modulo_dists)
#print mean_squared_dist
centroids.append(centroid)
max_centroid_dists.append(maxdist)
labels_clust.append(clust)
nums.append(np.sum(num) )
sizes.append(size)
clusts.append(clust)
coords.append(coord)
#~ print len(centroids), len(labels_unique)
if len(centroids)<2:
labels_split=labels
centroids_split=centroids
nums_split=nums
sizes_split=sizes
clust_labels_split=clusts
nums_coords_split=coords
return [labels_split, centroids_split, nums_split, sizes_split, clust_labels_split, nums_coords_split]
else:
#merge=np.zeros((len(labels_clust),len(labels_clust)), dtype=bool) # all false by default, do not merge unless...
tuples_to_merge=[] # list of tuple of indexes to merge.
cm=0
for (lab1_idx, lab2_idx) in itertools.combinations(range(len(labels_clust)), r=2): # check which original clusters are to merge
lab1 =labels_clust[lab1_idx]
centroid1=centroids[lab1_idx]
max_centroid_dist1=max_centroid_dists[lab1_idx]
lab2 =labels_clust[lab2_idx]
centroid2=centroids[lab2_idx]
max_centroid_dist2=max_centroid_dists[lab2_idx]
#print centroid1
#print centroid2
#
#
#print max_centroid_dist1, max_centroid_dist2
#max_centroid_dist_both=2*max([max_centroid_dist1, max_centroid_dist2])
max_centroid_dist_both=max_centroid_dist1 + max_centroid_dist2
dist_centroids=np.linalg.norm(centroid1 - centroid2)
#merge[lab1_idx, lab2_idx]= merge[lab2_idx, lab1_idx]= (dist_centroids<2*max_centroid_dist_both) # merge condition as square matrix
#print dist_centroids, max_centroid_dist_both
if (dist_centroids<max_centroid_dist_both + max([max_centroid_dist1, max_centroid_dist2])/2.):
tuples_to_merge.append((lab1_idx, lab2_idx))
#~ print "tuples to merge"
#~ print len(tuples_to_merge)
#~ print tuples_to_merge
list_merges_tot=[]
if len(tuples_to_merge)==0:
labels_split=labels
centroids_split=centroids
nums_split=nums
sizes_split=sizes
clust_labels_split=clusts
nums_coords_split=coords
return [labels_split, centroids_split, nums_split, sizes_split, clust_labels_split, nums_coords_split]
elif len(tuples_to_merge)==1:
(lab1_idx, lab2_idx) = tuples_to_merge[0]
lab1 =labels_clust[lab1_idx]
lab2 =labels_clust[lab2_idx]
list_merges_tot.append(set([lab1, lab2]))
else:
#for lab_idx, lab in enumerate(labels_clust): # build a list of clusters to merge all together
for tup_idx1 in range(len(tuples_to_merge)):
(lab1_idx, lab2_idx) = tuples_to_merge[tup_idx1]
lab1 =labels_clust[lab1_idx]
lab2 =labels_clust[lab2_idx]
set_loop=set([lab1, lab2])
if tup_idx1 < len(tuples_to_merge) -1:
for tup_idx2 in range(tup_idx1 +1,len(tuples_to_merge)):
(lab1_idx2, lab2_idx2) = tuples_to_merge[tup_idx2]
lab1_sec =labels_clust[lab1_idx2]
lab2_sec =labels_clust[lab2_idx2]
set_tmp=set([lab1_sec, lab2_sec])
if len(set_loop.intersection(set_tmp))>0:
set_loop |= set_tmp
if len(list_merges_tot)==0:
list_merges_tot.append(set_loop)
else:
idxs_intersect=[i for i in range(len(list_merges_tot)) if set_loop.intersection(list_merges_tot[i])>0]
if len(idxs_intersect)==0:
list_merges_tot.append(set_loop)
elif len(idxs_intersect)==1:
list_merges_tot[idxs_intersect[0]] |= set_loop
else:
list_merges_tot[idxs_intersect[0]] |= set_loop
for idx_intersect in idxs_intersect[1:]:
list_merges_tot[idxs_intersect[0]] |= list_merges_tot[idx_intersect]
list_merges_tot[:]=[list_merges_tot[i] for i in range(len(list_merges_tot)) if i not in idxs_intersect[1:]]
labels_split=labels.copy()
#~ print len(list_merges_tot)
#~ print list_merges_tot
for i_merge, set_merge in enumerate(list_merges_tot):
if len(list_merges_tot)>1:
list_merges_tot_others=list_merges_tot.copy()
list_merges_tot_others.pop(i_merge)
list_merges_tot_others=[list_merges_tot_others[0].update(merge) for merge in list_merges_tot_others]
list_merges_tot_others=list_merges_tot_others[0]
if set_merge.intersection(list_merges_tot_others)>0:
print "ERROR WITH SET WHEN MERGING CLUSTERS"
sys.exit()
to_be_called=min(set_merge)
idxs_change_label=[i for i in range(labels.size) if labels[i] in set_merge]
labels_split[idxs_change_label] = to_be_called
labels_unique=set(labels_split)
labels_unique.discard(-1)
centroids_split=[]
nums_split=[]
sizes_split=[]
clust_labels_split=[]
nums_coords_split=[]
for clust in labels_unique:
points_in_clust=X[labels_split==clust,:]
num=num_vir[labels_split==clust]
coord=points_in_clust.shape[0]
#centroid=np.mean(points_in_clust, axis=0)
centroid=np.average(points_in_clust, weights=num, axis=0)
#dists=np.linalg.norm(points_in_clust - np.mean(points_in_clust, axis=0)[None,:], axis=1)
dists=np.linalg.norm(points_in_clust - np.average(points_in_clust, weights=num, axis=0)[None,:], axis=1)
#print clust, points_in_clust.shape, squared_dists.shape
mean_dist=np.average(dists, weights=num)
#print mean_squared_dist
size=np.pi*(mean_dist**2)
centroids_split.append(centroid)
nums_split.append(np.sum(num))
sizes_split.append(size)
clust_labels_split.append(clust)
nums_coords_split.append(coord)
#~ print "reclustered"
return [labels_split, centroids_split, nums_split, sizes_split, clust_labels_split, nums_coords_split]
def mean_dispersion_renorm(X, labels, core_samples_mask): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
core_points_in_clust=X[(labels==clust) & core_samples_mask,:]
dists=points_in_clust - np.mean(points_in_clust, axis=0)[None,:]
core_dists=core_points_in_clust - np.mean(points_in_clust, axis=0)[None,:]
squared_dists=np.linalg.norm(dists, axis=1)**2
num=core_points_in_clust.shape[0]
k=num
if num>10:
k=10
modulo_dists=np.linalg.norm(core_dists, axis=1)
ind = np.argpartition(modulo_dists, -k)[-k:] # average the 6 biggest distances to baricenter of core samples
#maxdist=np.amax(np.linalg.norm(core_dists, axis=1))
maxdist=np.mean(modulo_dists[ind])
#print clust, points_in_clust.shape, squared_dists.shape
#renorm_squared_dist=np.sum(squared_dists)/(maxdist**2)
renorm_squared_dist=np.mean(squared_dists)/(maxdist**2)
#print mean_squared_dist
clust_dispersions.append(renorm_squared_dist)
#return sum(clust_dispersions)/float(labels[labels!=-1].size)
if len(labels_unique)>0:
return sum(clust_dispersions)/float(len(labels_unique))
else:
return -1.
def mean_dispersion_renorm_other(X, labels): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
dists=points_in_clust - np.mean(points_in_clust, axis=0)[None,:]
squared_dists=np.linalg.norm(dists, axis=1)**2
meandist=np.mean(np.linalg.norm(dists, axis=1))
#print clust, points_in_clust.shape, squared_dists.shape
#renorm_squared_dist=np.sum(squared_dists)/(meandist**2)
renorm_squared_dist=np.mean(squared_dists)/(meandist**2) - 1.
#print mean_squared_dist
clust_dispersions.append(renorm_squared_dist)
#return sum(clust_dispersions)/float(labels[labels!=-1].size)
if len(labels_unique)>0:
return sum(clust_dispersions)/float(len(labels_unique))
else:
return -1.
def kth_dist_distr(X, labels): # returns a float: the CV of pdf of the 10th nearest neighbor within cluster
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
variances=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
num=points_in_clust.shape[0]
k=num
if num>10:
k=10
nbrs = NearestNeighbors(n_neighbors=k).fit(points_in_clust)
distances, indices = nbrs.kneighbors(points_in_clust)
#print distances.shape
kth_dist=distances[:,-1]
kth_dist_CV=np.std(kth_dist)/np.mean(kth_dist)
clust_dispersions.append(kth_dist_CV)
variances.append(np.std(kth_dist))
#return sum(clust_dispersions)/float(labels[labels!=-1].size)
if len(labels_unique)>0:
return [sum(clust_dispersions)/float(len(labels_unique)), sum(variances)/float(len(labels_unique)), sum(variances)]
else:
return [-1., -1., sum(variances)]
def banfeld(X, labels): # returns a float: the mean dispersion averaged over all the clusters
labels_unique=set(labels)
labels_unique.discard(-1)
clust_dispersions=[]
for clust in labels_unique:
points_in_clust=X[labels==clust,:]
squared_dists=np.linalg.norm(points_in_clust - np.mean(points_in_clust, axis=0)[None,:], axis=1)**2
#print clust, points_in_clust.shape, squared_dists.shape
num=points_in_clust.shape[0]
if num>0:
banfeld=num*np.log(np.mean(squared_dists))
else:
banfeld=0
#print mean_squared_dist
clust_dispersions.append(banfeld)
return sum(clust_dispersions)
def vtau_fromparams(recog_width, mem_points, F_0):
return (recog_width/(np.exp(F_0/mem_points)-1.))
#dir_in='data/1d_{progr_tol}_{maxiters}_{algo}/opt.dat'.format(progr_tol=intra_host_neut.progr_tol, maxiters=int(intra_host_neut.maxiters), algo=intra_host_neut.algo)
#dir_in=intra_host_neut.file_o
#dir_io='../../contagion_simulation_results/data_neutral/DIM_2_people_number_10000_maxinfections_500001_alpha_4d000000_mu_1d000000_recog_width_5d000000_sigma_0d500000_f_m_0d100000_Rnot_mode_rec_force' # directory with input files
dir_io=sys.argv[1] # directory with input files
dir_in_tot='{inp}/realizations'.format(inp=dir_io) # directory with input files
#dir_in = dir_in.replace(".", "d")
dir_out_plots_tot='{inp}/plots'.format(inp=dir_io) # directory with output plots
#dir_out_plots = dir_out_plots.replace(".", "d")
def get_cmap(N):
''' Returns a function that maps each index in 0, 1, ...
N-1 to a distinct RGB color.'''
color_norm = colors.Normalize(vmin=0, vmax=N-1)
#scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
scalar_map = cm.ScalarMappable(norm=color_norm, cmap='jet')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color
param_file='{inp}/parameters_backup.dat'.format(inp=dir_io)
params = np.genfromtxt(param_file, dtype="f8,f8,f8,i8,i8,i8,i8, |S10, |S10, |S10, i8, i8, f8", names=['mu','rec_width','jump_size', 'ppl_num', 'maxinfections','save_full_time','n_real','initial_condition','fake_initial_condition','phylo_subsample','mem_points','t_init','F0'])
in_cond=params['initial_condition']
t_init=params['t_init']
print params
print params.shape
n_real=params['n_real']
num_ppl=params['ppl_num']
recog_width=params['rec_width']
mem_points=params['mem_points']
F0=params['F0']
latt_sp=1
vtau=vtau_fromparams(recog_width, mem_points, F0)
#if n_real >10:
# n_real=10
print n_real
thisfigsize = figsize
thisfigsize[1] *= 0.75
# get data
for real in np.arange(1,n_real+1):
dir_in='{inp}/realization_{real}'.format(inp=dir_in_tot,real=real) # directory with input files
dir_out_plots='{inp}/realization_{real}/clust'.format(inp=dir_out_plots_tot,real=real) # directory with output plots
dir_out_frames_subs='{inp}/frames_subs'.format(inp=dir_out_plots) # directory with output plots
dir_out_frames_zoom='{inp}/frames_zoom'.format(inp=dir_out_plots) # directory with output plots
#dir_in_frames='{inp}/frames_npz_compr'.format(inp=dir_in,real=real) # directory with input files
dir_in_frames='{inp}/frames/'.format(inp=dir_in) # directory with input files
file_exploded='{inp}/expl_file.txt'.format(inp=dir_in)
file_extinct='{inp}/extinct_file.txt'.format(inp=dir_in)
file_in_avg_npz_compr='{inp}/evo_mean_stats_real_{real}.dat'.format(inp=dir_in, real=real)
data=[]
time_ss=[]
if os.path.isfile(file_in_avg_npz_compr):
with open(file_in_avg_npz_compr) as f:
lines=f.readlines()
for line in lines:
if not line.startswith("#"):
line=line.decode('utf-8','ignore').encode("utf-8")
myarray = np.fromstring(line, dtype=float, sep=' ')
data.append(myarray)
#print(myarray)
print len(data)
data = np.asarray(data)
print data.shape
print data
print data.ndim
if data.ndim > 1:
time = data[:,0]
time_mod=time[time>10000] # throw first 100 years
sec_thr=min(100000, time_mod[time_mod.size/4])
time_mod=time_mod[time_mod>sec_thr]
print sec_thr, time.size
num_vir_tot = data[:,7]
num_vir_tot_thr=np.mean(num_vir_tot)
if os.path.isfile(file_exploded):
ind_times_notexpl=num_vir_tot.size - np.argmax(num_vir_tot[::-1] < num_vir_tot_thr)
elif os.path.isfile(file_extinct):
ind_times_notexpl=num_vir_tot.size - np.argmax(num_vir_tot[::-1] > num_vir_tot_thr)
else:
ind_times_notexpl=num_vir_tot.size
print ind_times_notexpl, num_vir_tot.size
time_all = time[:ind_times_notexpl]
time_ss=time_all[time_all>sec_thr]
survival=np.amax(time_ss)
#time_ss=time[(time> t_init/365.) & (time <= survival)]
#
#print survival, t_init/365.
print time_ss.size
#if time_ss.size > 30000:
#
# data= data[:ind_times_notexpl,:]
# data= data[time_all>sec_thr,:]
# if os.path.exists(dir_in_frames):
if os.path.exists(dir_in_frames) and data.ndim > 1 and time_ss.size > 3000:
if not os.path.exists(dir_out_plots):
os.makedirs(dir_out_plots)
if os.path.exists(dir_out_frames_subs):
shutil.rmtree(dir_out_frames_subs, ignore_errors=False, onerror=None)
if not os.path.exists(dir_out_frames_subs):
os.makedirs(dir_out_frames_subs)
xs = []
ys = []
fs = []
nums = []
times = []
avg_xs = []
avg_ys = []
#centroids_dict={}
######################################## LOAD DATA
for file_in_frames_npz_compr in glob.glob("{inp}/antigenic_space_time_*.dat".format(inp=dir_in_frames, real=real)):
filename, _ = os.path.splitext(file_in_frames_npz_compr)
time=os.path.basename(filename).split('_')[-1]
time=int(time)
data_space = np.loadtxt(file_in_frames_npz_compr)
# outstream<<"# 1 x"<<setw(30)<<" 2 y "<<setw(30)<<" 3 number IS"<<setw(30)<<"4 number viruses"<<setw(30)<<"5 viral fitness" <<endl;
#~ print data_space.ndim
if data_space.ndim >1 and data_space[data_space[:,3]>0,:].ndim >1:
data_space = data_space[data_space[:,3]>0,:]
#print data_space
#~ print data_space.shape
if data_space.ndim == 1:
vir_x = data_space[0] #
vir_y = data_space[1] #
num_vir = data_space[3] #
else:
#dim_reshape=min(13, data_space.shape[1])
#data_space=data_space[:,:dim_reshape]
vir_x = data_space[:,0] #
vir_y = data_space[:,1] #
num_vir = data_space[:,3]
fitn = data_space[:,4] #
if int(time)>sec_thr and int(time)<=survival and data_space.ndim > 1:
#vir_y=vir_y[vir_x<31]
#vir_x=vir_x[vir_x<31]
#vir_x =vir_x[num_vir>0]
#vir_y =vir_y[num_vir>0]
xs.extend([np.amin(vir_x),np.amax(vir_x)])
ys.extend([np.amin(vir_y),np.amax(vir_y)])
fs.extend([np.amin(fitn),np.amax(fitn)])
nums.extend([np.amax(num_vir)])
times.append(time)
vir_x_marginal= np.unique(vir_x)
num_vir_x_marginal= np.asarray([ np.sum(num_vir[x==vir_x]) for x in vir_x_marginal])
avg_x=np.average(vir_x_marginal, weights=num_vir_x_marginal) # lazy way to compute distribution average
avg_xs.append(avg_x)
vir_y_marginal= np.unique(vir_y)
num_vir_y_marginal= np.asarray([ np.sum(num_vir[y==vir_y]) for y in vir_y_marginal])
avg_y=np.average(vir_y_marginal, weights=num_vir_y_marginal) # lazy way to compute distribution average
avg_ys.append(avg_y)
#times.sort()
times, avg_xs, avg_ys= zip(*sorted(zip(times, avg_xs, avg_ys)))
times =np.asarray(times)
avg_xs=np.asarray(avg_xs)
avg_ys=np.asarray(avg_ys)
#~ print times
print times.shape
xmin=min(xs)
xmax=max(xs)
ymin=min(ys)
ymax=max(ys)
fmin=min(fs)
fmax=max(fs)
N_lev=20
fit_cont_lev= np.linspace(fmin, fmax, N_lev)[1:-1]
ind0 = np.searchsorted(fit_cont_lev, 0., side='left')
if fit_cont_lev[ind0] !=0:
fit_cont_lev=np.insert(fit_cont_lev, ind0, 0.)
num_max=max(nums)
normalize = matplotlib.colors.LogNorm(vmin=0.1, vmax=num_max)
#if real<=10:
var_parall_cloud = np.zeros((times.shape))
var_perp_cloud = np.zeros((times.shape))
var_tot_cloud = np.zeros((times.shape))
xs = [] # to print in all times
ys = []
times_printed= []
#ind_times=np.arange(0, 10)* (times_stat.size-1)/10
#print ind_times
#print ind_times.shape
#times_print=times_stat[ind_times] # every 5 years
##times_print=times_stat[::5] # every 5 years
file_in_trw='{inp}/IC_trav_wave.txt'.format(inp=dir_in)
if os.path.isfile(file_in_trw):
data_trw = np.loadtxt(file_in_trw)
sigma=data_trw[4]
tau=data_trw[1]
else:
sigma=3
tau=1000
c=0
data_viruses_list =[]
labels_clusters_opt_list =[]
core_samples_mask_opt_list=[]
min_considered_list =[]