-
Notifications
You must be signed in to change notification settings - Fork 0
/
points_analysis_2D_freud.py
5383 lines (4916 loc) · 239 KB
/
points_analysis_2D_freud.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
import freud
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
from scipy.spatial import Voronoi
from scipy.spatial import Delaunay
from scipy.spatial import distance
import pandas as pd
import matplotlib
import os
R"""
CLASS list:
static_points_analysis_2d: old_class_name: PointsAnalysis2D
dynamic_points_analysis_2d: old_class_name: msd
"""
class static_points_analysis_2d: # old_class_name: PointsAnalysis2D
R"""
Introduction:
the class is designed to analyze the
geometric properties(listed as follows) of 2D points.
Parameters:
points: n rows of (x,y), coordinations of given particles.
---
voronoi: scipy.spatial.Voronoi
voronoi.ridge_length: num-of-ridges row of (ridge_length)
voronoi.cut_ridge_length: a length that
if a ridge whose length is smaller than which, the ridge will be cut.
voronoi.cluster_vertices: list the row indices of vertices that may form clusters.
---
delaunay: scipy.spatial.Delaunay
bond_length: n rows of (start_point_index, end_point_index, bond_length)
cutted_bonds: n rows of (start_point_index, end_point_index)
vertices_triangle: input row indices of vertices,
and get row indices of triangles which cover these vertices.[x]
count_coordination: record the count of the coordination number who has i neighbours [0n,1n,2n,...,9n]
that is, 0n is the count of coordination number 0, 1n is the count of coordination number 1,
5n is the count of coordination number 5,6n is the count of coordination number 6
count_coordination_ratio:[x]count_coordination whose sum is normalized to 1.
---
Psi_k: n rows of complex number, Bond Orientaional Order(k fold disclination)
for each particle.
Psi_k_global: arithmetic mean of absolute value of Psi_k s.
Psi_k_rate: A is the num of particles whose psi_k is larger than 0.9, while
B is the num of all the particles. Psi_k_rate = A/B.
Methods:
points_analysis: get the parameters listed before
get_ridge_length:
get_bond_length:
get_first_minima_bond_length_distribution:
get_coordination_number_conditional:
get_cluster_vertices:
get_vertices_triangle:[x]
get_bond_orientational_order: get bond orientational order, Psi_n, for each particle.
get_bond_orientational_order_selected:
get_neighbor_cloud: place all the neighbor particles into a plot
with the same position of central particles
----
draw_bonds_conditional_bond: given bond_length condition, draw bonds
draw_bonds_conditional_ridge: given ridge_length condition, draw bonds
draw_bond_length_distribution_and_first_minima
----
print_benchmark: print (min,median,max) data for bond or ridge
----
count_n_polygon_fast: vertices cluster method
Examples:
import points_analysis_2D
obj_of_simu_index = points_analysis_2D.PointsAnalysis2D(filename=data_filename)
"""
def __init__(self, points=None, filename=None, hide_figure=True, dis_edge_cut=None):
# load positions of particles
if points is None:
if filename is None:
print("Error: input points or file please!\n")
else:
self.filename = filename
self.points = np.loadtxt(filename)
self.points = self.points[:, 0:2]
else:
self.points = points[:, :2]
if dis_edge_cut is None:
self.basic_points_analysis()
else:
self.basic_points_analysis(dis_edge_cut)
# not show figures
if hide_figure:
# Backend agg is non-interactive backend. Turning interactive mode off. 'QtAgg' is interactive mode
matplotlib.use(backend="agg")
def basic_points_analysis(self, dis_edge_cut=None):
self.voronoi = Voronoi(self.points)
self.delaunay = Delaunay(self.points)
self.get_ridge_length()
self.get_bond_length()
# cut the edge of positions
if dis_edge_cut is None:
self.__cut_edge_of_positions() # effective lattice constant is given 3 defaultly
else:
self.__cut_edge_of_positions(dis_edge_cut)
def get_ridge_length(self):
# where the ridge length of vertex-i & vertex-j is ridge_length[i,j]
self.voronoi.ridge_vertices = np.array(
self.voronoi.ridge_vertices) # 选不了ridge_vertices,不是数组格式
self.voronoi.ridge_length = distance.cdist(
self.voronoi.vertices[self.voronoi.ridge_vertices[:, 0],
:],
self.voronoi.vertices[self.voronoi.ridge_vertices[:, 1],
:],
'euclidean')
self.voronoi.ridge_length = self.voronoi.ridge_length.diagonal()
def get_bond_length(self):
# self.bond_length: (start_point_index,end_point_index,bond_length)
shp = np.shape(self.voronoi.ridge_points)
self.bond_length = np.zeros((shp[0], shp[1]+1)) # (start_point,end_point,length)
self.bond_length_temp = distance.cdist(
self.voronoi.points[self.voronoi.ridge_points[:, 0],
:],
self.voronoi.points[self.voronoi.ridge_points[:, 1],
:],
'euclidean')
self.bond_length[:, 0:2] = self.voronoi.ridge_points
self.bond_length[:, 2] = self.bond_length_temp.diagonal()
# should I list point pair like small-to-large?
del self.bond_length_temp # delete temp data
def get_first_minima_bond_length_distribution(
self, lattice_constant=3.0, hist_cutoff=2, method="global_compare_method",
png_filename=None, x_unit='(1)'):
R"""
Introduction:
It's likely that bonds whose length are larger than 2A are not bonded.
Typical bond-lengths of honeycomb are A and 1.73A (bond_first_neighbour & bond_second_neighbour namely),
hence the range=[0,2] times of lattice constant should be set.
Parameters:
lattice_constant: particle diameter or lattice constant is recommended(also the unit A in x-axis in hist)
method:"local_compare_nethod" to get the 1st minima through comparing local minima,
suitable for continuous peak-valley hist;
"global_compare_method" to get the 1st minima through comparing all the peaks,
selecting the 1st main peak(ignoring tiny peak before which),
finding the 1st main minima just after the 1st main peak,
suitable systems with powerful perturbation.
hist_cutoff: plot hist of bond_length till n times lattice_constant where n is hist_cutoff.
png_filename="prefix/bond_hist_index1512"
bond_first_minima_left:the upper limit of 1st neighbour bonds comming from the first minima
of bond length distribution, with sigma as lower limit.
Warning:
[x]What if there is no minima found?
count_1st_max / count_1st_minima > 10 used to check the effective of minima?
Examples:
s = "/home/tplab/Downloads/"
index_num = 1387
index_name = "index"+str(int(index_num))
fname = s+index_name
bb = pa.PointsAnalysis2D(filename=fname)
oname1 = s+"bond_hist_"+index_name
bb.draw_bond_length_distribution_and_first_minima(png_filename=oname1)
oname2 = s+"bond_plot_"+index_name
bb.draw_bonds_conditional_bond(check=[0.9, bb.bond_first_minima_left], png_filename=oname2)
"""
self.lattice_constant = lattice_constant
# locate the 1st minima of bond-length distribution
plt.figure()
count_bins = plt.hist(
self.bond_length[:, 2]/self.lattice_constant, bins=20, range=[0, hist_cutoff])
self._count = count_bins[0]
self._bins = count_bins[1]
self.bond_sorted = np.sort(self.bond_length[:, 2]/self.lattice_constant)
# find the minimum bin, then set the left side as bond_first_neighbour
i_max = self._bins.size
i = 0
if method == "local_compare_method":
while i < i_max-3: # i start from 0, which have to -1;compares i,i+1 and i+2, which have to -2, hence -3
# np.where( self.bond_sorted[:]>res.bins[i] & self.bond_sorted[:]< res.bins[i+1] )
# print(self._count[i])
if self._count[i] > self._count[i+1]:
if self._count[i+1] <= self._count[i+2]:
if self._bins[i+1] > 1/self.lattice_constant:
# bond_length should be larger than sigma of particle
i += 1
break
i += 1
elif method == "global_compare_method":
R"""
scan the histogram of bond length distribution, get the highest two columns.
see the column whose bond length is shorter as 'first peak'.
search for local minima right after the 'first peak'.
"""
self._count = np.array(self._count)
self.count_sorted = np.sort(self._count)
"""
print(self.count_sorted)
print(self.count_sorted[-1])#max1
print(self.count_sorted[-2])#max2
"""
i_bins_for_count_peak_1 = np.where(self._count[:] == self.count_sorted[-1])
i_bins_for_count_peak_2 = np.where(self._count[:] == self.count_sorted[-2])
i_bins_for_count_peak_1 = i_bins_for_count_peak_1[0]
i_bins_for_count_peak_2 = i_bins_for_count_peak_2[0]
# if there are more than one bins share the same count, select the smallest bin number.
if np.shape(i_bins_for_count_peak_1)[0] > 1:
i_bins_for_count_peak_1 = min(i_bins_for_count_peak_1)
if np.shape(i_bins_for_count_peak_2)[0] > 1:
i_bins_for_count_peak_2 = min(i_bins_for_count_peak_2)
i_bins_for_count_1st_peak = min(i_bins_for_count_peak_1, i_bins_for_count_peak_2)
# force i be a simple data_type(int)
i_bins_for_count_1st_peak = int(i_bins_for_count_1st_peak)
"""
print(i_bins_for_count_peak_1)
print(i_bins_for_count_peak_2)
print(i_bins_for_count_1st_peak)
"""
# list_xy = np.logical_and(list_x,list_y)
# self.edge_cut_positions_list = np.where(==)
i = i_bins_for_count_1st_peak
while i < i_max-3: # i start from 0, which have to -1;compares i,i+1 and i+2, which have to -2, hence -3
if self._count[i] > self._count[i+1]:
if self._count[i+1] <= self._count[i+2]:
# even if jump, i+1 is still the minimum.edit for bug in index4323_8_2000
if self._bins[i+1] <= self._bins[i+3]:
if self._bins[i+1] > 1/self.lattice_constant:
# bond_length should be larger than sigma of particle
i += 1
break
i += 1
R"""
scan the histogram of bond length distribution, get the highest two columns which are not neighbors.
see the two columns as the first and second peak of bond length.
search for the minimum between the two peaks.
"""
"""
elif method=="first_two_peak_group_method":
self._count = np.array(self._count)
self.count_sorted=np.sort(self._count)
group = np.zeros(np.shape(self._count))
ncount = np.shape(self.count_sorted)[0]
group_rank = 0#count the num of groups
for i in range(ncount):
index1 = ncount-1-i
i_bins_for_count_peak_1 = np.where(self._count[:]==self.count_sorted[index1])
i_bins_for_count_peak_1 = i_bins_for_count_peak_1[0]
c1 = group[i_bins_for_count_peak_1]==0
c0 = group[i_bins_for_count_peak_1-1]==0
c2 = group[i_bins_for_count_peak_1+1]==0
if c1 and c0 and c2 :
group_rank = group_rank + 1
group[i_bins_for_count_peak_1] = group_rank
elif not c1:
print('error: bins are scaned twice!')
break
elif not c2:
"""
else:
print("Err: input 'local_compare_method' or 'global_compare_method', please!")
print("x")
self.bond_first_minima_left = self._bins[i]
self.bond_first_neighbour = self.bond_sorted[np.where(
self.bond_sorted[:] < self.bond_first_minima_left)]
self.bond_length_median = np.around(np.median(self.bond_first_neighbour), 2)
self.bond_length_std = np.around(np.std(self.bond_first_neighbour), 2)
if not png_filename is None:
# plot divide line
plt.plot(
[self.bond_first_minima_left, self.bond_first_minima_left],
[0, self._count[i]],
linestyle='--')
plt.title("1st peak:"+str(self.bond_length_median)+"+-"+str(self.bond_length_std)+x_unit)
plt.xlabel("bond length "+x_unit)
plt.ylabel("count (1)")
# plt.show()
# png_filename=prefix+"bond_hist_index"+str(index_num)
plt.savefig(png_filename)
plt.close()
# let bond_first_minima_left be a absolute length, not normalized one
self.bond_first_minima_left = self.bond_first_minima_left*self.lattice_constant
def get_first_minima_ridge_length_distribution(
self, hist_cutoff=5, method="median_minima_method", png_filename=None, x_unit='(1)'):
R"""
Introduction:
It's likely that bonds whose voronoi ridges are extremely small are not bonded.
Parameters:
lattice_constant: particle diameter or lattice constant is recommended(also the unit A in x-axis in hist)
method:"local_compare_method" to get the 1st minima through comparing local minima,
suitable for continuous peak-valley hist; given here exit several local minima, the method has been given up.
"global_compare_method" to get the 1st minima through comparing all the peaks,
selecting the 1st main peak(ignoring tiny peak before which),
finding the 1st main minima just after the 1st main peak,
suitable systems with powerful perturbation.
hist_cutoff: plot hist of ridge_length till n times lattice_constant where n is hist_cutoff.
png_filename="prefix/bond_hist_index1512"
bond_first_minima_left:the upper limit of 1st neighbour bonds comming from the first minima
of bond length distribution, with sigma as lower limit.
Warning:
[x]What if there is no minima found?
count_1st_max / count_1st_minima > 10 used to check the effective of minima?
Examples:
"""
# locate the 1st minima of bond-length distribution
plt.figure()
count_bins = plt.hist(self.voronoi.ridge_length[:], bins=20, range=[0, hist_cutoff])
_count = count_bins[0]
_bins = count_bins[1]
ridge_sorted = np.sort(self.voronoi.ridge_length[:])
# find the minimum bin, then set the left side as bond_first_neighbour
i_max = _bins.size
i = 0
"""1st half minimum count"""
if method == "local_compare_method":
while i < i_max-3: # i start from 0, which have to -1;compares i,i+1 and i+2, which have to -2, hence -3
# np.where( self.bond_sorted[:]>res.bins[i] & self.bond_sorted[:]< res.bins[i+1] )
# print(self._count[i])
if _count[i] > _count[i+1]:
if _count[i+1] <= _count[i+2]:
i += 1
break
i += 1
elif method == "median_minima_method":
R"""
n_ridges_half: it is believed that extremely short ridges are rare,
so the total number of short ridges should be less than half the num of ridges.
hence n_ridges_half is set as a limit.
"""
n_ridges_half = int(sum(_count)/2)
# i=1
count_ridges_half = _count[0]
count_min_i = 0
while i < i_max-3:
if count_ridges_half < n_ridges_half:
count_ridges_half = count_ridges_half + _count[i+1]
else:
i = count_min_i # +1
break
if _count[count_min_i] > _count[i+1]:
count_min_i = i+1
i += 1
elif method == "global_compare_method":
_count = np.array(_count)
count_sorted = np.sort(_count)
"""
print(count_sorted)
print(count_sorted[-1])#max1
print(count_sorted[-2])#max2
"""
i_bins_for_count_peak_1 = np.where(_count[:] == count_sorted[-1])
i_bins_for_count_peak_2 = np.where(_count[:] == count_sorted[-2])
i_bins_for_count_peak_1 = i_bins_for_count_peak_1[0]
i_bins_for_count_peak_2 = i_bins_for_count_peak_2[0]
# if there are more than one bins share the same count, select the smallest bin number.
if np.shape(i_bins_for_count_peak_1)[0] > 1:
i_bins_for_count_peak_1 = min(i_bins_for_count_peak_1)
if np.shape(i_bins_for_count_peak_2)[0] > 1:
i_bins_for_count_peak_2 = min(i_bins_for_count_peak_2)
i_bins_for_count_1st_peak = min(i_bins_for_count_peak_1, i_bins_for_count_peak_2)
# force i be a simple data_type(int)
i_bins_for_count_1st_peak = int(i_bins_for_count_1st_peak)
"""
print(i_bins_for_count_peak_1)
print(i_bins_for_count_peak_2)
print(i_bins_for_count_1st_peak)
"""
# list_xy = np.logical_and(list_x,list_y)
# edge_cut_positions_list = np.where(==)
i = i_bins_for_count_1st_peak
while i < i_max-3: # i start from 0, which have to -1;compares i,i+1 and i+2, which have to -2, hence -3
if _count[i] > _count[i+1]:
if _count[i+1] <= _count[i+2]:
i += 1
break
i += 1
else:
print("Err: input 'local_compare_method' or 'global_compare_method', please!")
print("x")
# check the length of ridge
R"""
short_ridge_rate: the variable is set to ensure that the ridge_length is not popular.
"""
n_ridges = sum(_count)
short_ridge_rate = _count[i-1]/n_ridges
if short_ridge_rate < 0.1: # short ridge must be rare
self.ridge_first_minima_left = _bins[i]
else:
print('short_ridge_rate is too large!\n')
print(short_ridge_rate)
self.ridge_first_minima_left = _bins[1]
if not png_filename is None:
# plot divide line
plt.plot(
[self.ridge_first_minima_left, self.ridge_first_minima_left],
[0, _count[i]],
linestyle='--')
plt.title("1st minima:"+str(self.ridge_first_minima_left)+x_unit)
plt.xlabel("ridge length "+x_unit)
plt.ylabel("count (1)")
plt.savefig(png_filename)
plt.close()
def scan_conditional_bonds_and_simplices_ml(self, png_filename=None, mode='global_scan'):
ml = polygon_analyzer_ml(self.voronoi, self.ridge_first_minima_left)
ml.scan_conditional_bonds_and_simplices_ml(mode, png_filename)
# long_bond_cutoff=6,
def get_conditional_bonds_and_simplices_vertex_length(self, ridge_first_minima_left=None):
R"""
return:
vertex_bonds_index: n rows of [start_point_index, end_point_index]
list_simplex_cluster: n_vertices rows of [simplex_id, cluster_id],
where delaunay.simplices[simplex_id],
and cluster_id is the cluster the simplex belonging to
method:
vertices cluster method: find the shortest ridges and link the related vertices.
"""
if ridge_first_minima_left is None:
ridge_first_minima_left = self.ridge_first_minima_left
list_short_ridge_bool = self.voronoi.ridge_length[:] <= ridge_first_minima_left
list_short_bonds = self.voronoi.ridge_points[np.logical_not(
list_short_ridge_bool)] # [start_point_index, end_point_index]
"""
select_short_bonds_bool = self.bond_length[list_short_bonds[:,0],2] < long_bond_cutoff
#select_short_bonds_bool = self.bond_length[list_short_bonds_index,2] < long_bond_cutoff
list_short_bonds = list_short_bonds[select_short_bonds_bool]
"""
list_ridge_vertices_index = self.voronoi.ridge_vertices[list_short_ridge_bool]
list_vertices_index = np.unique(list_ridge_vertices_index)
n_vertices = np.shape(list_vertices_index)[0]
'''
method2:
record_vertices_cluster = np.ones((n_vertices,10))
record_vertices_cluster[:]=-record_vertices_cluster[:]
'''
# record_vertices_cluster: n_vertices rows of [vertex_id, cluster_id],
# where vertex_id belongs to list_vertices
# when cluster_id=-1, the vertex has not been included by any cluster.
record_vertices_cluster = np.ones((n_vertices, 2), dtype=int)
# -1 has been marked as infinity point
record_vertices_cluster[:, 1] = -record_vertices_cluster[:, 1]
record_vertices_cluster[:, 0] = list_vertices_index
cluster_id = 0
for i in range(n_vertices):
vertex_id = list_vertices_index[i]
# print("cluster_id\n",cluster_id)
list_linked = np.where(list_ridge_vertices_index[:, :] == vertex_id)
list_linked_vertices_pair = list_ridge_vertices_index[list_linked[0]]
# print("vertices_pair\n",list_linked_vertices_pair)
list_vertex_id_of_cluster1 = np.unique(list_linked_vertices_pair)
for j in list_vertex_id_of_cluster1:
record_id = record_vertices_cluster[:, 0] == j # find the row_index for vertex_id
if record_vertices_cluster[record_id, 1] == -1:
record_vertices_cluster[record_id, 1] = cluster_id
elif record_vertices_cluster[record_id, 1] == cluster_id:
pass
else:
# new cluster merge old one by refreshing a list of vertices in old cluster
contradictory_cluster_id = record_vertices_cluster[record_id, 1]
list_bool_of_cluster_to_merge = (
record_vertices_cluster[:, 1] == contradictory_cluster_id)
record_vertices_cluster[list_bool_of_cluster_to_merge, 1] = cluster_id
cluster_id += 1
# remove the infinity points marked -1
list_vertices_index_bool = record_vertices_cluster[:, 0] >= 0
record_vertices_cluster = record_vertices_cluster[list_vertices_index_bool]
n_vertices = np.shape(record_vertices_cluster)[0]
# remove end
# statistics for clusters
list_cluster_id = np.unique(record_vertices_cluster[:, 1])
count_polygon = np.zeros((20, 2)) # (10,2)
for i in list_cluster_id.astype(int):
list_cluster_i = record_vertices_cluster[record_vertices_cluster[:, 1] == i, 0]
n_complex_i = np.shape(list_cluster_i)[0]
count_polygon[n_complex_i, 0] = n_complex_i+2 # [x]frame=1421,polygon=10;1609,12
count_polygon[n_complex_i, 1] += 1
count_polygon[1, 0] = 3
# record triangles in record_vertices_cluster too
list_vertices_index_all = np.unique(self.voronoi.ridge_vertices).astype(
int) # truly exist a vertex whose id is -1!
list_vertex_tri_bool = list_vertices_index_all[:] >= 0 # remove the infinity vertex
list_vertices_index_all = list_vertices_index_all[list_vertex_tri_bool]
for vid in record_vertices_cluster[:, 0]:
list_vertex_in_cluster_bool = list_vertices_index_all[:] == vid
list_vertices_index_all[list_vertex_in_cluster_bool] = -2
list_vertex_tri_bool = list_vertices_index_all[:] >= 0
list_vertices_index_tri = list_vertices_index_all[list_vertex_tri_bool]
n_tris = len(list_vertices_index_tri)
# print(n_tris)
# list_vertex_clust_bool = list_vertices_index_all[:]<0
# list_vertices_index_clust = list_vertices_index_all[list_vertex_clust_bool]
count_polygon[1, 1] = n_tris # [x]may be wrong, n_bond != n_simplex
# print("polygon_n, count\n",count_polygon)
#
count_polygon_relative = np.array(count_polygon)
count_polygon_relative[:, 1] = count_polygon_relative[:, 1]/sum(count_polygon_relative[:, 1]) \
* (count_polygon_relative[:, 0]-2)*100 # see one simplex as one weight
# print("polygon_n, count%\n",count_polygon_relative)
"""
nm = np.maximum(count_polygon[:,1])
np.shape(list_cluster_id)
list_polygon_simplex = -np.ones((10,nm))
for i in list_cluster_id:
list_cluster_i = record_vertices_cluster[record_vertices_cluster[:,1]==i,0]
list_polygon_simplex[]
"""
# record triangles in record_vertices_cluster too
list_vertices_index_tri_id = range(n_tris)
record_vertices_cluster[:, 1] = record_vertices_cluster[:,
1]+n_tris # ensure that ids are not overlapped
record_vertices_cluster_new = np.zeros((np.shape(list_vertices_index_all)[0], 2), dtype=int)
record_vertices_cluster_new[:n_tris, 0] = list_vertices_index_tri
record_vertices_cluster_new[:n_tris, 1] = list_vertices_index_tri_id
record_vertices_cluster_new[n_tris:] = record_vertices_cluster
self.vertex_bonds_index = list_short_bonds # short bonds index offered by ridge comapre method
self.list_simplex_cluster = record_vertices_cluster_new
return count_polygon_relative
def get_conditional_bonds_and_simplices_bond_length(self, bond_first_minima_left=None):
R"""
return:
self.list_simplex_cluster: n_vertices rows of [simplex_id, cluster_id],
where delaunay.simplices[simplex_id],
and cluster_id is the cluster the simplex belonging to.
if cluster_id = -1, the simplex is on boundary and should not be drawn.
count_polygon_relative: [polygon_n,share of total n of simplices]
method:
vertices cluster method: find the shortest ridges and link the related vertices.
"""
if bond_first_minima_left is None:
bond_first_minima_left = self.bond_first_minima_left
list_long_bond_bool = self.bond_length[:, 2] >= bond_first_minima_left
list_short_bonds = self.voronoi.ridge_points[np.logical_not(
list_long_bond_bool)] # [start_point_index, end_point_index]
# print(self.delaunay.simplices)#(n_simplex,3)[index_vertex1,index_vertex2,index_vertex3]
sz = self.delaunay.simplices.shape
list_simplex_cluster = np.zeros((sz[0], 2), dtype=int)
list_simplex_cluster[:, 0] = range(sz[0])
list_simplex_cluster[:, 1] = range(sz[0]) # initialize each simplex as independent cluster
list_simplices_points = np.array(self.delaunay.simplices, dtype=int)
n_bond = len(list_long_bond_bool)
for i in range(n_bond):
if list_long_bond_bool[i]:
index_p1 = int(self.bond_length[i, 0])
index_p2 = int(self.bond_length[i, 1])
loc1 = np.where(list_simplices_points == index_p1) # list_simplices with p1
loc2 = np.where(list_simplices_points == index_p2) # list_simplices with p2
# print(i,loc1[0],loc2[0])
# get the simplices with p1 and p2
list_simplices_with_p = np.concatenate((loc1[0], loc2[0]))
list_simplices_with_p = np.sort(list_simplices_with_p)
list_simplices_with_p_unique = np.unique(list_simplices_with_p)
count_cobond = np.zeros((len(list_simplices_with_p_unique),), dtype=int)
for j in range(len(list_simplices_with_p_unique)):
loc_repeat = np.where(list_simplices_with_p == list_simplices_with_p_unique[j])
n_loc_with_p = len(loc_repeat[0])
if n_loc_with_p == 2:
count_cobond[j] = n_loc_with_p
# print(list_simplices_with_p_unique[j],count_cobond[j])#index_simplices, n_repeat
# count_cobond = count_cobond + 1
list_simplices_cobond = np.where(count_cobond == 2)
n_simplices_cobond = len(list_simplices_cobond[0])
"""if n_simplices_cobond==1:
#ban a simplex by set whose cluster_id as -1
list_boundary_simplex = list_simplices_with_p_unique[list_simplices_cobond]
list_simplex_cluster[list_boundary_simplex,1] = -1"""
if n_simplices_cobond == 2:
# merge linked simplices into a cluster whose id is smaller.
list_boundary_simplex = list_simplices_with_p_unique[list_simplices_cobond]
cluster_id_min = min(list_simplex_cluster[list_boundary_simplex, 1])
cluster_id_max = max(list_simplex_cluster[list_boundary_simplex, 1])
list_simplex_cluster[list_simplex_cluster[:, 1]
== cluster_id_max, 1] = cluster_id_min
# print(list_simplices_with_p)
self.list_simplex_cluster = list_simplex_cluster
# get the distribution of cluster
list_cluster_id = np.unique(list_simplex_cluster[:, 1])
count_polygon = np.zeros((99, 2)) # (10,2)
for cluster_id in list_cluster_id:
if not cluster_id == -1:
list_simplex_ids_in_cluster_i = list_simplex_cluster[list_simplex_cluster[:, 1] ==
cluster_id, 0]
n_simplex_in_cluster_i = np.shape(list_simplex_ids_in_cluster_i)[0]
cluster_i_is_polygon_n = n_simplex_in_cluster_i+2
# [x]frame=1421,polygon=10;1609,12
count_polygon[n_simplex_in_cluster_i, 0] = cluster_i_is_polygon_n
count_polygon[n_simplex_in_cluster_i, 1] += n_simplex_in_cluster_i
"""p_valids = np.array([self.points[index_p1], self.points[index_p2]])
result = self.delaunay.find_simplex(p_valids)
if result.shape[0] == 1:
#not show the simplex
pass
elif result.shape[0] > 1:
#merge two clusters
pass"""
count_polygon_relative = np.array(count_polygon)
count_polygon_relative[:, 1] = count_polygon[:, 1]/sum(count_polygon[:, 1]) \
* 100 # see one simplex as one weight
return count_polygon_relative
def plot_bond_ridge_rank_idea(self):
R"""
bond plot, bond_length_rank vs ridge_length_rank,
to see if when bond be longer, the ridge be shorter.
"""
pass
def draw_polygon_patch_oop(self, fig=None, ax=None, polygon_color='r', polygon_n=6):
R"""
parameters:
vertex_bonds_index: n rows of [start_point_index, end_point_index]
list_simplex_cluster: n_vertices rows of [simplex_id, cluster_id],
where delaunay.simplices[simplex_id],
and cluster_id is the cluster the simplex belonging to
(from get_conditional_bonds_and_simplices())
is_polygon_n: mark the num n of edges of the polygon.
"""
if ax is None:
fig, ax = plt.subplots()
vertices_cluster = self.list_simplex_cluster
points = self.points
list_cluster_id = np.unique(vertices_cluster[:, 1])
# patches=[]
for cluster_id in list_cluster_id:
if cluster_id == -1:
pass
else:
list_simplex_ids_in_cluster_i = vertices_cluster[vertices_cluster[:, 1] ==
cluster_id, 0]
n_simplex_in_cluster_i = np.shape(list_simplex_ids_in_cluster_i)[0]
cluster_i_is_polygon_n = n_simplex_in_cluster_i+2
# print(cluster_i_is_polygon_n)
if cluster_i_is_polygon_n == polygon_n:
# patches=[]
for simplex_id in list_simplex_ids_in_cluster_i.astype(int):
list_points_ids_in_simplex = self.delaunay.simplices[simplex_id]
list_points_xy = points[list_points_ids_in_simplex]
"""
polygon = Polygon(list_points_xy, closed=True)
polygon.set(color='r')
patches.append(polygon)
p = PatchCollection(patches)#, alpha=0.4
ax.add_collection(p)
"""
ax.fill(list_points_xy[:, 0], list_points_xy[:, 1],
facecolor=polygon_color, edgecolor=polygon_color)
# plt.show()
"""
#rearrange points anti-clockwise
"""
return fig, ax
# [x]
def get_first_minima_radial_distribution_function(
self, rdf, lattice_constant=3.0, png_filename=None):
# print(rdf.bin_centers) print(rdf.bin_counts)
self.lattice_constant = lattice_constant
# locate the 1st minima of bond-length distribution
self._count = rdf.bin_counts
self._bins = rdf.bin_centers
self.bond_sorted = np.sort(self.bond_length[:, 2]/self.lattice_constant)
# find the minimum bin, then set the left side as bond_first_neighbour
"global_compare_method"
self._count = np.array(self._count)
self._bins = np.array(self._bins)
self.count_sorted = np.sort(self._count)
i_max = self._bins.size
i = 0
"""
print(self.count_sorted)
print(self.count_sorted[-1])#max1
print(self.count_sorted[-2])#max2
"""
# locate the 1st minima of bond-length distribution
plt.figure()
rdf.plot()
"""
print(self.count_sorted)
print(self.count_sorted[-1])#max1
print(self.count_sorted[-2])#max2
"""
i_bins_for_count_peak_1 = np.where(self._count[:] == self.count_sorted[-1])
i_bins_for_count_peak_2 = np.where(self._count[:] == self.count_sorted[-2])
i_bins_for_count_peak_1 = i_bins_for_count_peak_1[0]
i_bins_for_count_peak_2 = i_bins_for_count_peak_2[0]
# if there are more than one bins share the same count, select the smallest bin number.
if np.shape(i_bins_for_count_peak_1)[0] > 1:
i_bins_for_count_peak_1 = min(i_bins_for_count_peak_1)
if np.shape(i_bins_for_count_peak_2)[0] > 1:
i_bins_for_count_peak_2 = min(i_bins_for_count_peak_2)
i_bins_for_count_1st_peak = min(i_bins_for_count_peak_1, i_bins_for_count_peak_2)
# force i be a simple data_type(int)
i_bins_for_count_1st_peak = int(i_bins_for_count_1st_peak)
"""
print(i_bins_for_count_peak_1)
print(i_bins_for_count_peak_2)
print(i_bins_for_count_1st_peak)
"""
# list_xy = np.logical_and(list_x,list_y)
# self.edge_cut_positions_list = np.where(==)
i = i_bins_for_count_1st_peak
while i < i_max-3: # i start from 0, which have to -1;compares i,i+1 and i+2, which have to -2, hence -3
if self._count[i] > self._count[i+1]:
if self._count[i+1] <= self._count[i+2]:
if self._bins[i+1] > 1/self.lattice_constant:
# bond_length should be larger than sigma of particle
i += 1
break
i += 1
self.bond_first_minima_left = self._bins[i]
self.bond_first_neighbour = self.bond_sorted[np.where(
self.bond_sorted[:] < self.bond_first_minima_left)]
if not png_filename is None:
# plot divide line
plt.plot([self.bond_first_minima_left, self.bond_first_minima_left],
[0, 0.5], linestyle='--') # self._count[i]
plt.title("1st peak:"+str(np.around(np.median(self.bond_first_neighbour), 2)
)+"+-"+str(np.around(np.std(self.bond_first_neighbour), 2)))
plt.xlabel("interparticle distance (unit=A)")
plt.ylabel("count (1)")
# plt.show()
# png_filename=prefix+"bond_hist_index"+str(index_num)
plt.savefig(png_filename)
plt.close()
# let bond_first_minima_left be a absolute length, not normalized one
self.bond_first_minima_left = self.bond_first_minima_left*self.lattice_constant
def get_coordination_number_conditional(self, lattice_constant=3, method="bond_length_method"):
# cut edge to remove CN012
R"""
Introduction:
get_coordination_number_with given bond_length_limit [min,max].
CN0 % should be 0 for all the particles must be linked by bond.
CN1 % is likely to be edge?
CN2 % in body(edge-cutted) shows the mechanical unstability
CN3 % shows the proportion of honeycomb.
CN4 % shows the proportion of kagome.
CN6 % shows the proportion of hexagonal.
CN5/7 % shows the proportion of disclination.
parameters:
lattice_constant: 3 sigma in default.
method: 'bond_length_method','ridge_length_method'.
Variables:
__coordination_bond: n rows of (start_point_index, end_point_index, bond_length)
count_coordination: 10 rows of [count]. The i-th [count_i] represents the count
of points whose coordination number is i, where i from 0 to 9.
count_coordination_ratio: count_coordination whose sum is normalized to 1.
"""
if method == "bond_length_method":
# check whether bond_first_minima_left exist
try:
bond_length_limit = self.bond_first_minima_left
except AttributeError:
self.get_first_minima_bond_length_distribution(lattice_constant=lattice_constant)
bond_length_limit = self.bond_first_minima_left
# select the bonds within the limit(bond length of 1st neighbour)
self._bond_min = 0.0
self._bond_max = bond_length_limit
place = np.where(
(self.bond_length[:, 2] > self._bond_min) &
(self.bond_length[:, 2] < self._bond_max))
self.__coordination_bond = self.bond_length[place, 0:2]
self.__coordination_bond = self.__coordination_bond[0] # remove a [] in [[]] structure
elif method == "ridge_length_method":
self.get_first_minima_ridge_length_distribution()
self.get_conditional_bonds_and_simplices_vertex_length()
self.__coordination_bond = self.vertex_bonds_index
# self._particle_id_max=np.max(self.__coordination_bond[:])#get the largest id of particle to restrain while loop
# print(self.__coordination_bond)
cn_max = 12 # for honeycomb, cn10 truly appears in Index4340_seed9_frame2!
self.count_coordination = np.zeros([cn_max, 1])
for id in self.edge_cut_positions_list[0]:
place = np.where(self.__coordination_bond[:] == id)
"""
Exception has occurred: IndexError (note: full exception trace is shown but execution is paused at: <module>)
index 10 is out of bounds for axis 0 with size 10
File "/home/tplab/xiaotian_file/lxt_code_py/points_analysis_2D.py", line 340, in get_coordination_number_conditional
self.count_coordination[i]+=1
File "/home/tplab/xiaotian_file/lxt_code_py/data_analysis_cycle.py", line 1024, in save_from_gsd
a_frame.get_coordination_number_conditional()#cut edge to remove CN012
File "/home/tplab/xiaotian_file/lxt_code_py/workflow_part.py", line 1715, in workflow_simu_to_mysql_pin_hex_to_kagome_cycle_oop_kT
account=account)
File "/home/tplab/xiaotian_file/lxt_code_py/control_table_multi_thread.py", line 13, in <module> (Current frame)
index_end=tt.workflow_simu_to_mysql_pin_hex_to_kagome_cycle_oop_kT(index1=index1,lcr=lcr1,kT=kT,seed=seed)
"""
i = len(place[0])
# print(place[0])
self.count_coordination[i] += 1
# print(self.count_coordination)
self.count_coordination_ratio = self.count_coordination/sum(self.count_coordination)
def get_cairo_order_parameter(self, cn3, cn4):
R"""
output:
p: order_parameter_for_cairo
introduction:
p_cairo = (cn3 + cn4)*min(cn3/2cn4,2cn4/cn3)
"""
sca = show_cairo_order_parameter()
return sca.compute_cairo_order_parameter(cn3, cn4)
def get_radial_distribution_function_triu(self, box, dr=0.1):
R"""
box: [LX,LY]
dr: resolution of rdf
"""
num_particles = len(self.points)
r_max = np.min(box)
n_bins = int(r_max / dr)
rdf = np.zeros(n_bins)
bond_length_all = distance.cdist(self.points[:], self.points[:], 'euclidean')
bond_length_all_tu = np.triu(bond_length_all, k=1) # upper triangle
bond_length_all_dr_unit = np.divide(
bond_length_all_tu, dr, dtype=int) # discrete array with dr as unit
del bond_length_all, bond_length_all_tu
r_temp = dr
while r_temp < r_max:
nr_temp = r_temp/dr
inbox_positions_list, inbox_positions_bool = self.cut_edge_of_positions_by_box(
self.points, [box[0]-r_temp, box[1]-r_temp], True)
bond_length_select1 = bond_length_all_dr_unit[inbox_positions_bool]
bond_length_select2 = bond_length_all_dr_unit[:, inbox_positions_bool]
list_r_bool1 = bond_length_select1[:, :] == nr_temp
list_r_bool2 = bond_length_select2[:, :] == nr_temp
count = np.sum(np.array(list_r_bool1, dtype=int)
)+np.sum(np.array(list_r_bool2, dtype=int))
n_particle_inbox = np.sum(np.array(inbox_positions_bool, dtype=int))
n_ds = 2*np.pi*r_temp*dr*n_particle_inbox
for i in range(num_particles):
for j in range(i + 1, num_particles):
separation_vector = self.points[j] - self.points[i] # self.bond_length
separation_distance = np.linalg.norm(separation_vector)
bin_index = int(separation_distance / dr)
if bin_index < n_bins:
rdf[bin_index] += 2 # Count both particles in the pair
# Normalize RDF
particle_n_density = num_particles / (box[0]*box[1])
normalization_factor = np.pi * dr**2 * particle_n_density
rdf /= normalization_factor
distances = np.arange(dr / 2.0, r_max, dr)
return distances, rdf
def get_radial_distribution_function(
self, box, dr=0.1, r_max=None, png_filename=None, points=None, normalize_r0=None):
R"""
box: [LX,LY]
dr: resolution of rdf
points: if just trap a small box, this attribute is used to record the points in that small box.
normalize_r0: the mean 1st neighbor distance expected, to normalize the distance.
"""
if points is None:
points = self.points
num_particles = len(points)
if r_max is None:
r_max = np.min(box)/2
ndr_max = int(r_max/dr) # r:0-102.4 -> 0-102
data_count = ndr_max-1 # ndr:1-102 -> 1-101
rdf = np.zeros(data_count)
bond_length_all = distance.cdist(self.points[:], self.points[:], 'euclidean')
# discrete array with dr as unit, 0~0.99 -> 0
bond_length_all_dr_unit = np.array(bond_length_all/dr, dtype=int)
bond_length_all = None
for i in range(data_count):
ndr_temp = i+1
r_temp = ndr_temp*dr
inbox_positions_list, inbox_positions_bool = self.cut_edge_of_positions_by_box(
points, [box[0]-2*r_temp, box[1]-2*r_temp], True)
bond_length_select = bond_length_all_dr_unit[inbox_positions_bool]
list_ndr_bool = bond_length_select[:, :] == ndr_temp
count = np.sum(np.array(list_ndr_bool, dtype=int))
n_particle_inbox = np.sum(np.array(inbox_positions_bool, dtype=int))
n_ds = 2*np.pi*r_temp*dr*n_particle_inbox
rdf[i] = count/n_ds
particle_n_density_global = num_particles/(box[0]*box[1])
rdf_normalized = rdf/particle_n_density_global
distances = np.linspace(1, data_count, data_count)*dr+0.5*dr # ndr:1-101 -> 1.5-101.5
if not png_filename is None:
fig, ax = plt.subplots()
if normalize_r0 is None:
ax.plot(distances, rdf_normalized, c='k')
else:
distances_n = distances/normalize_r0
ax.plot(distances_n, rdf_normalized, c='k')
ax.set_xlabel('r($\sigma$)')
ax.set_ylabel('g(r)(1)')
plt.savefig(png_filename)
plt.close()
if normalize_r0 is None:
return distances, rdf_normalized
else:
return distances_n, rdf_normalized
def search_neighbor_id(self, id):
# cut edge to remove CN012
R"""
Introduction:
input a particle id and get the ids of whose neighbors
Variables:
__coordination_bond: n rows of (start_point_index, end_point_index)
place: (2,Nneighbors)[neighbor_id,column]
"""
place = np.where(self.__coordination_bond[:] == id)
n_nb = len(place[0]) # number of neighbors
place_nb = np.array(place, dtype=np.int32)
# print(place_nb)
place_nb[1] = 1-place_nb[1]
# print(place_nb)
id_nb = self.__coordination_bond[place_nb[0], place_nb[1]].astype(np.int32)
return id_nb
def get_nearest_neighbor_dispalcement(self):
R"""
Introduction:
lindemann_dispalcement: r(i,t)-<r(j,t)>
Return:
list_id_dxy_nb:
list[particle_id,num_neighbors, sum_id_neighbors,dx,dy],
id of center particles and their displacements relative to neighbors.
if the particle has new neighbors, unless inter-frame time is too long to
catch the event of breaking old bond and forming new bond, number of neighbors
will change together with the event.
dict_c_nb:
dict{'id_c':id_nb}, center particles and their neighbors.
To monitor the event of breaking old bond and forming new bond and hence
get the life span of a caging state.
"""
# check whether bond_first_minima_left exist
try:
bond_length_limit = self.bond_first_minima_left
except AttributeError:
self.get_first_minima_bond_length_distribution()
bond_length_limit = self.bond_first_minima_left
# select the bonds within the limit(bond length of 1st neighbour)
self._bond_min = 0.0
self._bond_max = bond_length_limit
place = np.where((self.bond_length[:, 2] > self._bond_min)
& (self.bond_length[:, 2] < self._bond_max))
self.__coordination_bond = self.bond_length[place, 0:2]
self.__coordination_bond = self.__coordination_bond[0] # remove a [] in [[]] structure