-
Notifications
You must be signed in to change notification settings - Fork 0
/
disLocate.m
2937 lines (2278 loc) · 119 KB
/
disLocate.m
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
(* ::Package:: *)
(* ::Input::Initialization:: *)
BeginPackage["disLocate`"]
(* Step 1. - Merge All Cells Toghether *)
(* Step 2. - Convert To Initialization Cell *)
(* Step 3. - Save as .M *)
disLocateVersion:="1.2017-08-31."<>ToString["thesis-M.v11-final"];
If[$VersionNumber<10,Needs["ComputationalGeometry`"];];
(* Global Definiations of Colour Schemes *)
(* Voronoi Colour Schemes *)
TypeVoronoiQ[string_] :=Block[{},
If[ToUpperCase[string]==ToUpperCase["VORONOI"]||
ToUpperCase[string]==ToUpperCase["VOR"]||
ToUpperCase[string]==ToUpperCase["V"]||
ToUpperCase[string]==ToUpperCase["Voronoi"]
,True,False
]
];
AssignVoronoiColour[vor_]:=Block[{intensity,hexagonalVoronoi},
intensity=Length[vor]/Total[PolyArea[ # ]&/@vor];
hexagonalVoronoi = HexagonArea[Sqrt[2./(intensity*Sqrt[3.])]/2.];
(VoronoiHexagonAreaDeviationColour[#]&/@(Abs[PolyArea[ # ]-hexagonalVoronoi]/hexagonalVoronoi&/@vor))
];
VoronoiCellColourScheme:={
RGBColor[43/255,49/255,135/255] (* Deep Blue *),
RGBColor[26/255,117/255,188/255] (* Lighter Deep Blue *),
RGBColor[1/255,174/255,240/255], (* Light Blue *)
RGBColor[110/255,179/255,104/255], (* Light Green *)
RGBColor[254/255,205/255,6/255], (* Yellow *)
RGBColor[242/255,107/255,41/255], (* Orange *)
RGBColor[203/255,32/255,38/255], (* Red *)
RGBColor[203/255,32/255,38/255], (* Red *)
RGBColor[203/255,32/255,38/255], (* Red *)
RGBColor[203/255,32/255,38/255], (* Red *)
RGBColor[203/255,32/255,38/255], (* Red *)
RGBColor[203/255,32/255,38/255](* Red *)
};
VoronoiHexagonAreaDeviationColour[col_] := Which[
col<=0.05,VoronoiCellColourScheme[[1]],
col<=0.10,VoronoiCellColourScheme[[2]],
col<=0.15,VoronoiCellColourScheme[[3]],
col<=0.20,VoronoiCellColourScheme[[4]],
col<=0.25,VoronoiCellColourScheme[[5]],
col<= 0.30,VoronoiCellColourScheme[[6]],
col> 0.30,VoronoiCellColourScheme[[7]]
];
(* Bond Order Colour Schemes *)
TypeBondOrderQ[string_]:=Block[{},
If[ToUpperCase[string]==ToUpperCase["BOND ORDER"]||
ToUpperCase[string]==ToUpperCase["BONDORDER"]||
ToUpperCase[string]==ToUpperCase["BOND"]||
ToUpperCase[string]==ToUpperCase["BOOP"]||
ToUpperCase[string]==ToUpperCase["BOP"],
True,False]
];
BondOrderColourScheme[q_,l_Integer]:=
If[q>1,Blend[ {White,Blend[{RGBColor[147/255,3/255,46/255],Green},(0.5)]},10(q-1)], Blend[{Blend[{Blend[{Purple,Blue},0.25],White},0.25](*RGBColor[147/255,3/255,46/255]*),White},((*1.33*)q(*/BOPexp[l]*))]];
(* Bond Order Parameter - Expectation Values *)
SqrBopQ4:=0.8290387427498793;
HexBopQ6:=0.7408293494456062;
BopQ1One:=1.0;
BopQ2Two:=0.5;
BopQ3Tri:=0.7905688454904419;
BopQ4Sqr:=0.8290387427498793;
BopQ5Pent:=0.7015607600201141;
BopQ6Hex:=0.7408293494456062;
BopQ7Sept:=0.6472598492877493;
BopQ8Oct:=0.6837611402200334;
BOPexp[l_]:=Part[{BopQ1One,BopQ2Two,BopQ3Tri,BopQ4Sqr,BopQ5Pent,BopQ6Hex,BopQ7Sept,BopQ8Oct},l];
(* Coordination Number Colour Scheme *)
TypeCoordinationQ[string_] :=Block[{},
If[ToUpperCase[string]==ToUpperCase["coordination"]||
ToUpperCase[string]==ToUpperCase["coord"]||
ToUpperCase[string]==ToUpperCase["neighbours"]||
ToUpperCase[string]==ToUpperCase["neighbors"]||
ToUpperCase[string]==ToUpperCase["neighbour"]||
ToUpperCase[string]==ToUpperCase["neighbor"]||
ToUpperCase[string]==ToUpperCase["NN"]||
ToUpperCase[string]==ToUpperCase["contact"]
,True,False]
];
AssignCoordinationColour[vor_]:=Block[{},
CoordinationNumberColourScheme[Length[#]]&/@vor
];
(* Explicitly assumes a closed Voronoi Polygon (first point = last point) *)
(*CoordinationNumberColourScheme[in_]:= Which[
in\[LessEqual] 3,Black,
in\[Equal]4,Blend[{Blue,Purple},0.75],
in\[Equal]5,Blend[{Blue,Green},0.35],
in\[Equal]6,Blend[{Green,GrayLevel[0.46]},0.65],
in\[Equal]7,GrayLevel[0.85],
in\[Equal]8,Blend[{Orange,GrayLevel[0.95]},0.1],
in\[Equal]9,Blend[{Blend[{Purple,Blue},0.25],White},0.5] ,
in\[Equal]10,Blend[{Pink,Purple},0.6],
in\[Equal]11,Blend[{Purple,Red},0.75],
in\[GreaterEqual]12 , Blend[{Yellow,Black},(15-in)/5]];*)
CoordinationNumberColourScheme[in_]:= Which[
in==3,Purple,
in==4,Blend[{Blue,GrayLevel[0.5]},0.5],
in==5,Blend[{Blue,Green},0.45],
in==6, Blend[{Green,GrayLevel[0.3]},0.5],
in==7,GrayLevel[0.75],
in==8,Blend[{Orange,GrayLevel[0.5]},0.1],
in==9,Blend[{Red,GrayLevel[0.5]},0.5],
in==10,Blend[{Black,Red},0.5],
in>= 11,Black];
(* Angular Orientation Colour Scheme *)
TypeAngularDirectionQ[string_] :=Block[{},
If[ToUpperCase[string]==ToUpperCase["angle"] ||
ToUpperCase[string]==ToUpperCase["angular"] ||
ToUpperCase[string]==ToUpperCase["ang"] ||
ToUpperCase[string]==ToUpperCase["orientation"] ||
ToUpperCase[string]==ToUpperCase["direction"] ||
ToUpperCase[string]==ToUpperCase["direct"] ||
ToUpperCase[string]==ToUpperCase["orient"] ||
ToUpperCase[string]==ToUpperCase["cluster"]||
ToUpperCase[string]==ToUpperCase["clust"]||
ToUpperCase[string]==ToUpperCase["vector"] ||
ToUpperCase[string]==ToUpperCase["vec"]
,True,False]
];
BjornColourScheme:={
RGBColor[{255,51,51}/256],(*bjorn red*)
Yellow,
RGBColor[{0,153,51}/256], (*bjorn green*)
Blue
(*RGBColor[147/255,3/255,46/255]*)
(*Yellow*)
(*RGBColor[{51,51,153}/256]*)(*bjorn blue*)
(*RGBColor[0.545,0.0,0.8],*) (*bjorn orange*)
};
BjornAngleScheme[inTheta_,rot_]:=Block[{
modAngle,
angBin=Table[n/rot ,{n,(Pi/2)/2,2Pi,Pi/2}],
mod\[Theta]
},
modAngle[\[Theta]_]:= Mod[\[Theta],2.Pi/rot];
mod\[Theta]=modAngle@inTheta;
Which[
mod\[Theta]<= angBin[[1]]||mod\[Theta]> angBin[[4]],
BjornColourScheme[[1]],(*bjorn red*)
mod\[Theta]<= angBin[[2]]&& mod\[Theta]> angBin[[1]],
BjornColourScheme[[2]],(*bjorn purple*)
mod\[Theta]<= angBin[[3]]&& mod\[Theta]> angBin[[2]],
BjornColourScheme[[3]],(*bjorn green*)
mod\[Theta]<= angBin[[4]]&& mod\[Theta]> angBin[[3]],
BjornColourScheme[[4]](*bjorn blue*)
]
];
(* Regular Polygon Colour Code *)
RegularPolygonColourScheme:=
{RGBColor[95/255,128/255,181/255],RGBColor[225/255,156/255,37/255],RGBColor[142/255,176/255,63/255],RGBColor[234/255,97/255,51/255],RGBColor[134/255,121/255,177/255],Gray};
(* Scale Bars for Voronoi Visualizations *)
Options[ScaleBars]={sym->6,minmax-> {3,8}};
ScaleBars[type_, OptionsPattern[] ]:=Block[{
voronoiColourRange,bopColourRange,angleColourRange,coordColourRange,
coordOffset,
symmetryO=OptionValue[sym],
minmaxO=OptionValue[minmax]
},
Which[
(*---------------------*)
TypeVoronoiQ[type],
voronoiColourRange={5,10,20,30,40,100};
BarLegend[
{VoronoiCellColourScheme[[1;;7]],{0.0,100.}},
{0,5,10,15,20,25,30},
LegendMarkerSize->200,
LabelStyle->Directive[FontSize->14],
LegendMargins->0,
LegendLabel->" Percent (%) \n off Hexagonal"
],
(*---------------------*)
TypeBondOrderQ[type],
bopColourRange=Table[BondOrderColourScheme[x,symmetryO],{x,0,1.,0.1}];
BarLegend[
{bopColourRange,{0.0,1.0}},
Ticks->Table[i,{i,0.,1.1,0.2}],
LabelStyle->Directive[FontSize->14],
LegendMarkerSize->200,
LegendMargins->0,
LegendLabel->"Bond Order \nParameter"
],
(*---------------------*)
ToUpperCase[type]==ToUpperCase["OVER-BOP"],
bopColourRange=Table[BondOrderColourScheme[x,symmetryO],{x,0,1.1,0.1}];
BarLegend[
{bopColourRange,{0.0,1.1}},
Ticks->Table[i,{i,0.,1.1,0.2}],
LabelStyle->Directive[FontSize->14],
LegendMarkerSize->200,
LegendMargins->0,
LegendLabel->"Bond Order \nParameter"
],
(*---------------------*)
TypeCoordinationQ[type],
If[minmaxO[[2]]-minmaxO[[1]]<= 3, minmaxO= {minmaxO[[2]]-3,minmaxO[[2]]} ];
If[minmaxO[[1]]<= 3,minmaxO[[1]]=3;coordOffset=+1;,coordOffset=0;];
coordColourRange=(minmaxO[[1]]-1+Range[minmaxO[[2]]-1]);
BarLegend[{(CoordinationNumberColourScheme/@(coordColourRange+coordOffset)),{minmaxO[[1]]-0.5,minmaxO[[2]]+0.5}},coordColourRange-0.5,LegendMarkerSize->200,LabelStyle->Directive[FontSize->14],LegendMargins->10,
LegendLabel-> "Local Voronoi\nCoordination",
"Ticks"->({#,#}&/@coordColourRange),If[minmaxO[[2]]-minmaxO[[1]]>6,Unevaluated[Sequence[]],
"TickLabels"->(Style[#,14,CoordinationNumberColourScheme[#+1]]&/@(coordColourRange))]
],
(*---------------------*)
TypeAngularDirectionQ[type],
angleColourRange=Table[x,{x,0, 2 Pi/(symmetryO),2Pi/(4symmetryO)}];
BarLegend[{BjornColourScheme,{0.,2.Pi/symmetryO}},
angleColourRange,
"Ticks"->angleColourRange,
LegendMargins->0,
LegendLabel->"Angle"]
]
];
(* Usages of disLocate Private Functions *)
inPolyQ2::usage= "inPolyQ2[ polygon, x, y ]:
A simple method to determine if a point (x,y) lays inside a regular polygon. Returns 'True' if it does say inside, or 'False' if not. Taken from http://mathematica.stackexchange.com/questions/9405/how-to-check-if-a-2d-point-is-in-a-polygon
Example: inPolyQ2[Table[{Cos[x],Sin[x]},{x,2Pi,0,-2Pi/30}],0.5,0.5] \n"
PolyArea::usage= "PolyArea[ polygon]: Solves the Area of teh Polygon."
ExpectedDiameterFromLattice::usage="ExpectedDiameterFromLattice[data2d_ , OptionsPattern[]
]:= Returns the expected Lattice Diameter from Point Pattern. Options[ExpectedDiameterFromLattice]={ box\[Rule]{} ,lattice\[Rule]ToString[hex] or lattice-> ToString[square]};"
HexagonalDiameter::usage="HexagonalDiameter[numberOfPoints_, inBox_]:= returns the expected hexagonal diameter from number density. Need N and Box."
HexagonArea::usage="HexagonArea[R_]:= returns the area of a hexagon with an apothem of distance R. Useful with closed packed circles, where their radius is R."
Hexaticize::usage="Hexaticize[d_,dr_]:= Used to create the hexatic lattice - Randomly positions the List of points (d) by (dr) standard deviation. Code= d+RandomVariate[NormalDistribution[0.0,dr],{Length[d],Length[d[[1]]]}]"
negQ::usage="negQ[number]:= Test to see if it is negative, returns true if negative."
hexToRGB::usage="A function that takes a string of hex colour values and converts it to RGB. Make sure to include '#': ToString[#000000]"
standardPolygon::usage="standardPolygon[n_]:= Gives a polygon of n points. As the number n \[Rule] \[Infinity], this polygon becomes a circle."
ScaleBars::usage="ScaleBars[type_]: Returns the ScaleBar for a specific type of plot. Types incude: ToString[voronoi], ToString[bop], ToString[angle]."
closedBindingBox::usage="closedBindingBox:={{0.,0.},{1.,0.},{1.,1.},{0.,1.},{0.,0.}};"
bindingBox::usage="bindingBox:={{0.,0.},{1.,0.},{1.,1.},{0.,1.}};"
rectangleBindingBox::usage="rectangleBindingBox[a_,b_]:=Block[{},closedBindingBox.{{a,0},{0,b}}];"
standardGrowthRate::usage="standardGrowthRate:=\!\(\*SuperscriptBox[\(10\), \(-5\)]\);"
(*----------------------------------------------------------------------*)
ApplyPeriodicBoundary::usage = "ApplyPeriodicBoundary[inData2d_,box_, OptionsPattern[] ]: Positions particles outside the box by translating points from the other side. \!\(\*
StyleBox[\"Options\",\nFontWeight->\"Plain\"]\)\!\(\*
StyleBox[\":\",\nFontWeight->\"Plain\"]\)\!\(\*
StyleBox[\" \",\nFontWeight->\"Plain\"]\){SetDistance\[Rule]1,ReturnDim\[Rule]2}"
ApplyImageChargeBoundary::usage = "ApplyImageChargeBoundary[data2d_,box_,OptionsPattern[]]: Positions particles outside the box by placing it equidistant and perpindicular to the box wall. Returns the original list of points with mirror positions outside of a box appended to the end."
ApplyGeneralPBC::usage="ApplyGeneralPBC[data2d_,box_, numNN___]:= Creates a list (2d) of PBC points "
SolvePBCBoundary::usage="ApplyGeneralPBC[data2d_,box_, numNN___]: Solves for the convex hull that encapsulates all particles for Periodic Boundary Clipping."
(*----------------------------------------------------------------------*)
radialDistributionC::usage="radialDistributionC[{dlist,_Real,1},{r,_Real},{eps,_Real}]:= The function that bins the distances for the pair correlation function."
distancesWithEdgeCorrections::usage="distancesC[data2d_, NumberOfParticlesInBox_ ]:= Returns a list of point-to-point distances. Calculations are performed for only particles inside the box (i.e. Only the first NumberOfParticlesInBox are evaluated). Double counting and the self-to-self distance of zero are returned as distance=(-1)."
PairCorrelationFunction::usage="PairCorrelationFunction[ data2d , OptionsPattern[] ]=Given a set of data2d={{\!\(\*SubscriptBox[\(x\), \(1\)]\),\!\(\*SubscriptBox[\(y\), \(1\)]\)}...{\!\(\*SubscriptBox[\(x\), \(n\)]\),\!\(\*SubscriptBox[\(y\), \(n\)]\)}}, returns a table {g(r),r} from r=0.0 to r=(maxBins * binSpacing). This is an ensemble definition. Multiple data2d={{\!\(\*SubscriptBox[\(conf\), \(1\)]\)}...{\!\(\*SubscriptBox[\(conf\), \(n\)]\)}} with the same density can be input and will be averaged.
OptionsPattern=binSpacing\[Rule]1,maxBins\[Rule]1,box\[Rule]{},edge\[Rule]ToString[trunc],lattice\[Rule]ToString[none],hexNormalized\[Rule]False.
Select edge corrections (edge\[Rule] # ): ToString[pbc] || ToString[image] || ToString[noedge]
Choosing lattice\[Rule]ToString[hex] will Apply the proper Periodic Boundaries when using HexagonalLattice[periodic \[Rule] True]
"
SquareLattice::usage="Returns the square lattice. To select different spacing, define the intensity (N/Area): n\[Rule] NumberOfParticles, box\[Rule] BindingBoxPolygon."
HexagonalLattice::usage="Returns a set of points describing a hexagonal lattice with a certain intensity.
To select different spacing, define the intensity (N/Area): n\[Rule] NumberOfParticles, box\[Rule] BindingBoxPolygon.
Select periodic\[Rule] True for use with PairCorrelationFunction[].
Default OptionsPattern: Options[{n\[Rule] 400, box\[Rule] closedBindingBox, radius\[Rule] 1., periodic\[Rule] False};"
TranslationalOrderParameter::usage="TranslationalOrderParameter[g(r)_ , {min_, max_}, \[Rho]_]:= Returns the Translational Order Parameter by integrating the g(r)=PairCorrelationFunction[].
Note: g(r) function needs to have units of molecular radius (r=diameter/2).
The Size of the Shell can be set with \!\(\*SubscriptBox[\(r\), \(inner\)]\)=min and \!\(\*SubscriptBox[\(r\), \(outter\)]\)=max.
The Number Density is set as \[Rho] = N/Area.
"
TranslationalNumberOfNeighbours::usage="TranslationalNumberOfNeighbours[g(r)_ , {min_, max_}, \[Rho]_]:= Returns the Average Number of Neighbours by integrating the g(r)=PairCorrelationFunction[].
Note: g(r) function needs to have units of molecular radius (r=diameter/2).
The Size of the Shell can be set with \!\(\*SubscriptBox[\(r\), \(inner\)]\)=min and \!\(\*SubscriptBox[\(r\), \(outter\)]\)=max.
The Number Density is set as \[Rho] = N/Area "
TranslationalExcessEntropy::usage="TranslationalExcessEntropy[g(r)_,{xMin_,xMax_},\[Rho]_]:= Returns the Two Point Particle contribution towards the Excess Entropy obtained from integrating the g(r)=PairCorrelationFunction[].
Note: g(r) function needs to have units of molecular radius (r=diameter/2).
The Size of the Shell can be set with \!\(\*SubscriptBox[\(r\), \(inner\)]\)=min and \!\(\*SubscriptBox[\(r\), \(outter\)]\)=max.
The Number Density is set as \[Rho] = N/Area.
"
InterpolationFunctionDifference::usage="InterpolationFunctionDifference[reference_, diffFunct_ ,xMax___]:= Root Mean Square difference by Linear Interpolation of refernce and diffFunct.
If xMax===Null, the difference is taken between the maximum overlap.
Setting xMax will clip to an x-value inside the largest shared x-value
Returns the List containing:
{rms,differencedFunction,interpolatedReference,interpolatedComparing}
rms = Root Mean Square
differencedFunction = Residual from subtracting the diffFunct_ from reference_.
interpolatedReference = Linear Interpolation List of refernce_
interpolatedComparing = Linear Interpolation List of diffFunct_"
PlotPairCorrelationFunction::usage=""
PlotPcfDifference::usage="PlotPcfDifference[ PairCorrelationList , OptionsPattern[] ]=Difference Spectrum of PairCorrelationFunction[]. The values for: ref={g(r),r} and func={g(r),r} need to be lists.
OptionsPattern[]=(xmax\[Rule]0,normalized\[Rule]True,shapes\[Rule]{},stacked\[Rule]False,names\[Rule]{},xLabel\[Rule]{},refIndex\[Rule]1)
xmax \[Rule] 1 : Cut-off distance for g(r) where \!\(\*SubscriptBox[\(r\), \(max\)]\)=xmax.
normalized \[Rule] True : Automatic rescalling of the x-axis to
shapes \[Rule] {} : List of Polygons to be used as the Legend Markers where - shapes\[Rule]{\!\(\*SubscriptBox[\(polygon\), \(1\)]\), ... , \!\(\*SubscriptBox[\(polygon\), \(n\)]\)}
stacked \[Rule] False : Option to overlay curves, or to stack them with an offset. If stacked\[Rule]True, it will produce the stacked version. Multiple PairCorrelationFunction[] can be set with: func={g(r\!\(\*SubscriptBox[\()\), \(1\)]\) , ..., g(r\!\(\*SubscriptBox[\()\), \(n\)]\)};
xLabel \[Rule] {} : String used to label the distance axis. If xLabel\[Rule]ToString[Normalized Diameter], the function changes the gridlines to the expected positions of the hexagonal lattice.
refIndex \[Rule] 1 : Defines which PairCorrelation[] in the list is chosen as the reference for all others to be subtracted from. "
(*----------------------------------------------------------------------*)
AutoBoxTransform::usage="AutoBoxTransform[data2D_]:= {box polygon points}. Used to auto-detect edge particles for removal. Added to improve user experience - only 1 input is needed for PlotVoronoiTessellations[ ]"
MinMaxBox::usage=
"MinMaxBox[data2d_]:={box}. Returns a box that clips close to the data."
VoronoiCells::usage="VoronoiCells[data2Din_, OptionsPattern[]]=Provides all base information needed to calculate disorder metrics. Default OptionsPattens[] include: box\[Rule]{}, edge\[Rule]ToString[NOEDGE], full\[Rule]False, fast\[Rule]True, debug\[Rule]False.
Default Output={VoronoiPolygons, data2DinWithEdgeParticles, delaunayNearestNeighbours, commonVertex}
This set is needed when removing edge effects. Output (data2DinWithEdgeParticles) refers to a list {allParticles, insideQTruthList}. The Position[] of a (True) in the (insideQTruthList) represents the index of a particle in (allParticles) which is not removed from analysis. This information is used with (VoronoiPolygons) to remove cells outside. Variable (delaunayNearestNeighbours) is a set of indices points to which particles belong to the neighbour list. The (commonVertex) provides the xy coordinates of the shared Voronoi Edge associated with the particle to neighbour vector (used in BondOrderParameter[]).
box->{}=This parameter can be set to a polygon to remove the automatic detection of the box.:
edge->ToSting[NoEdge]=Applies the appropriate edge corrections to the image. The default option is ToString[NOEDGE], which automatically removes Voronoi Cells that lie on the box edge. Other implementations include: edge->ToString[pbc] which applies periodic boundary conditions, and edge->ToString[image] which generates virtual particles outside the box such that the resulting Voronoi cells are confined (or clipped) to the box.:
full->False=When used in conjuction with edge->(pbc/image), the returned list contains only the Voronoi Polyhedra for the input data2Din. Setting full->True is needed for many other applications. Functions that need Delaunary neighbours will over-ride the user setting if information is needed.:
fast->True=This option sets a quick parameter for solving virtual boundary particle. The default True limits the distance to which edge particles are periodically(imageodically) traslated to approximately 1.4 times the particle radius. Option fast->False, applies a full boundary estimation, resulting in Voronoi Tessellation of about 9*Length[data2Din] (making it much slower). Use only when the results show obviously improper boundary conditions or in low density systems.:
debug->False=Developer option - do not use - writes out specific messages when key routines are solved.
This based on Mathematica's VoronoiMesh[] and will NOT work if the $VersionNumber \[LessEqual] 9 ."
PlotVoronoiTessellations::usage="PlotVoronoiTessellations[ data2Din_, OptionsPattern[] ]:= Returns a Graphics of the VoronoiCells[] that has been colour coded to associate disorder metrics to the planar arrangements.
OptionsPattern=(type\[Rule]ToString[vor],symmetry\[Rule]6,cells\[Rule]{},points\[Rule]True,scalebar\[Rule]False,stats\[Rule]ToString[Count],boundary\[Rule]ToString[NOEDGE],box\[Rule]{})
type->ToString[voronoi]=The Main variable that changes the information provided. Option: type\[Rule]ToString[voronoi] Uses the areas of the Voronoi Cells to calculate an expected hexagonal spacing with the same intensity (shortname ToString[vor]). Option: type\[Rule]ToString[coordination] Uses the number of facets each individual Voronoi polygon has (shortname ToString[coord]). Option: type\[Rule]ToString[BondOrder] Uses the neighbours -as defined by the Delaunaly Triangulation- to calculate the BondOrderParameter[]. Default symmetry is (symmetry->6) but can be manually set to any variable.
symmetry -> 6 : Sets the symmetry number associated with the BondOrderParameter[]. No effect with any (type).
cells -> {} : This option provides a way to manually pass VoronoiCells[] that have been precalculated. It is meant to save time by passing the automatic VoronoiCells[] call for a large systems that might be run many times through this function.
points -> True : A graphics option that includes the centroids of the particles on the final plot. These can be turned off with this option.
scalebar -> False : An option to include the scalebar assocciated with the colour code of (type).
stats -> ToString[Count] : Sets the type of stats passed into VoronoiHistogram[]. Recommended settings - ToString[Count] or ToString[Probability]. See 'hspec' Option for Histogram[].
boundary -> ToString[NoEdge] : Settings for boundary corrections. Default boundary\[Rule]ToString[NoEdge] automatically removes any Voronoi Cells that lay on or outside of (box). Options include: boundary\[Rule]ToString[periodic] includes edge Voronoi polygons by adding periodically translated neighbours outside of the box (shortname pbc). boundary\[Rule]ToString[image] includes edge Voronoi polygons by adding virtual particles that produce Voronoi cells with facets exactly on the edge of (box). This effectively truncates or clips the edges of the Voronoi cells to the (box). (shortname img).
box -> {} : Explicitly defines the edges of a box. Note! - setting a polygon will not change the (boundary), as it will default boundary\[Rule]ToString[NoEdge] which autodetects the box from the data. Remember to set a (boundary) option."
VoronoiHistogram::usage="VoronoiHistogram[ inVoronoiCells, OptionsPattern[] ]=Returns a Histogram from the information in VoronoiCells[].
OptionsPattern=type\[Rule]ToString[vor], stats\[Rule]ToString[Probability], scalebar\[Rule]True, sym\[Rule]1, bopdata\[Rule]Null."
AverageFirstNeighbourDistance::usage="AverageFirstNeighbourDistance[data2d_,numberOfNN___]: Returns the average EuclideanDistance[] of numberOfNN neighbours. Default is set to 1 neighbour."
FirstPeakValue::usage="FirstPeakValue[ List{x,f[x]} ]=Finds the x-position of the first peak. Typically used with PairCorrelationFunction[]."
ExpectedHexagonalDiameter::usage="ExpectedHexagonalDiameter[data2d, OptionsPattern[]]=Solves the VoronoiCells[] for a system, the calculates the expected hexagonal diameter with the same number density. The Formula to calculate the radius of a particle: r[a_]:=Sqrt[a/(6 Tan[Pi/6])]. Output={2 Mean[ r[areaDistribution] ], Variance[ r[areaDistribution] ]}.
OptionsPattern[]=(boundary->ToString[NoEdge],box->{})"
ImageDiffractionPattern::usage="ImageDiffractionPattern[img]: Calculates the planar FFT on the image. Returns the diffraction pattern as a Graphic"
DiffractionPatternFromPosition::usage="DiffractionPatternFromPosition[data2d_]: Calculates the planar FFT from a set of coordinates. Makes no assumptions on boundary conditions."
BondOrderParameter::usage="BondOrderParameter[ unBoundedData2D , whichL , OptionsPattern[] ]= Calculates the Bond Order using Delaunay triangulation for neighbour definition. Defaults are to remove edge particles and apply weighting of (voronoiBondFacet/totalVoronoiPerimeter) to every bond.
OptionsPattern=passVor\[Rule]{},fast\[Rule]True,edge->ToString[NoEdge],vorbop\[Rule]True,box\[Rule]{},normalized\[Rule]False,debug\[Rule]False. "
BondOrderPointCloud::usage="BondOrderPointCloud[ data2D , OptionsPattern[] ]=Creates a 2d probability map of the relative angular separation and radial distance for all first neighbours of each particle. It is similar to a planar map of the pair correlation function [g(r)] where only the first neighbour shell is considered.
OptionsPattern=mod\[Theta]\[Rule]1,poly\[Rule]{},box\[Rule]{},simlist\[Rule]{},growthR\[Rule]{},debug\[Rule]False."
CoordinationNeighbourCloud::usage=" CoordinationNeighbourCloud[ data2D , OptionsPattern[] ]=Creates a 2d probability map of the relative angular separation and radial distance for only first neighbours for only the subsection of particles that share a similar coordination number. It is similar to a planar map of the pair correlation function [g(r)] where only the first neighbour shell is considered.
OptionsPattern=passVor\[Rule]{},fast\[Rule]True,coord\[Rule]1,mod\[Rule]1,poly\[Rule]{},simstepList\[Rule]{},growthR\[Rule]{}"
(*----------------------------------------------------------------------*)
PlotFinalConfiguration::usage= "PlotFinalConfiguration[ Configuration, polygon, SimStep, GrowthRate, box , ToString[Type], args___ ]: Takes a set of 2D
points {x,y,\[Theta]} of a polygon packing and generates the final configuration. Uses the size as SimStep * 10^-5. Type can be: Automatic, STM. If type = BOP or Angle, args can be specified as an integer that represents Q_arg or Mod[arg].
========================================================= \n \n"
colourFunction::usage="colourFunction[data2D_,type_,box_, OptionsPattern[]] and \n Options[colourFunction]={bop\[Rule]Null,voronoiArea\[Rule]Null,edge\[Rule]ToString[pbc],arg\[Rule]Null}"
PlotPointCloud::usage= "PlotPointCloud[ Ensemble ]: Takes a set of 2D points {x,y,\[Theta]} of ensembles. This auto-detects the rotation angle and removes it for proper plotting. The size of the points are also automatically generated.
========================================================= \n
\n"
PlotPlanarDensity::usage= "PlotPlanarDensity[ Ensemble ]: Takes an ensemble set of 2D points: {{x,y,\[Theta]},...,{{x,y,\[Theta]}}} of the final configurations and computes the probability map.
========================================================= \n
\n"
PlotRegistryMap::usage= "PlotRegistryMap[ Ensemble, VeiwingDimension ]: Takes a set of 2D points {x,y,\[Theta]} of the final configurations and computes the Registry Map of most common positions. For 2D planar view, use VeiwingDimension=2. For 3D histograms, use VeiwingDimension=3.
========================================================= \n
\n"
PackingFraction::usage="PackingFraction[ Configuration, polygon, SimStep, GrowthRate, box ]:
Takes a set of 2D points of a final configuration {x,y,\[Theta]}, and inflates the monodisperse polygons {poly} to a size of (1.E-5)*SimStep . The confining area is defined by the {box}. \n
Example: Packing Randomly Placed Circles inside a 1x1 box.
PackingFraction[RandomReal[1,{10,3}], Table[{Cos[x],Sin[x]},{x,2Pi,0,-2Pi/30}],RandomInteger[12345],\!\(\*SuperscriptBox[\(10\), \(-5\)]\),{{0,0},{1,0},{1,1},{0,1},{0,0}}]
========================================================= \n
\n"
OverlapNetwork::usage= "OverlapNetwork[ Configuration, polygon, SimStep, inflateRatio, box] -
is a set of functions that inflates the polygons past their final configuration and calculates the amount of overlap in the system. The networks are plotted overtop of the final configurations with the size and colour of the line being proportional to that amount of overlap.
Uses a series of Functions -> Inflate , FindNearestForOverlap, PolygonsThatOverlap
========================================================= \n
\n"
sortByAngle::usage= "sortByAngle[ polygon ] - takes a set of points and sorts them by angle to form a closed polygon.
========================================================= \n
\n"
Inflate::usage= "Inflate[ Configuration, polygon, SimStep, GrowthRate, OverlapScale ] -
takes a set of centroids {x,y} and inflates the polygons at those positions
a certain percentage starting at Simstep.
For example, OverlapScale = 1.30 inflates the objects by 130%.
========================================================= \n
\n"
FindNearestForOverlap::usage= "FindNearestForOverlap[ pointPattern2D ] -
takes a set of centroids {x,y} and finds the nearest N number of closest neighbours. If the number of centroids are less than 18, it sets that to the maximum number of neighbours. If it is higher than 18, then it sets 18 as the max neighbours.
========================================================= \n
\n"
PolygonsThatOverlap::usage= "PolygonsThatOverlap[ polys, nearestN ] :
takes a set of inflated polygon points and the nearest neighbour list and creates a list of all the particles that overlap. The nearest neighbour list is required to speed up the estimation, suggesting that only the closets neighbours overlap with eachother.
========================================================= \n
\n"
ADOsort::usage= "ADOsort[ Configuration ] - Sorts the configuration to allow for proper Pattern Matching. Returns a list degeneracy array map with the first entry being the begining parcel configuration, with an array
========================================================= \n
\n"
pcSize::usage="Used to select point size for PointClouds."
GeneralizedPBCLocalVoronoiBondOrder::usage="Test"
ApplyBoxSymmetryToEnsemble::usage="ApplyBoxSymmetryToEnsemble[Ensemble_,modNumber___]: Creates an ensemble by rotating/flipping according to the symmery of the 1x1 box. "
ParcelBySimilarity::usage="ParcelBySimilarity[Ensemble_,ConfidenceRange_,SymRot___]:= Leave SymRot out (or use Null to avoid)."
SortParcelPositions::usage="SortParcelPositions[Ensemble_,parcels_]:= Send the ensemble {{x,y,\[Theta]}..} with results from ParcelBySimilarity[] to sort the patterns into the same orientation. Will return a Table that is similar to Ensemble."
LoneNormCalc::usage="Used for Pattern Matching"
QuickDistanceSimilarityCheckQ::usage="Used for Pattern Matching"
QuickDistanceSimilarityCheckQuiet::usage="Used for Pattern Matching"
SimNormCalc::usage="Used for Pattern Matching"
QuickSimilarityCheckQ::usage="Used for Pattern Matching"
QuickSimilarityCheckQuiet::usage="Used for Pattern Matching"
QuickSimilarityMax::usage="Used for Pattern Matching"
FindMaxProbabilityFromList::usage="FindMaxProbabilityFromList[LIST, args___] := Possible args include 'all' and 'random' to return all found and a random choice"
PdfDensityDistribution::usage="PdfDensityDistribution[]:="
ParticleDensityDistribution::usage="ParticleDensityDistribution[pf_,pfNames_,args___]"
AreaFractionDistribution::usage="ParticleDensityDistribution[pf_,OptionsPattern[]] : Options[AreaFractionDistribution]={labels\[Rule]{},colours\[Rule] RegularPolygonColourScheme}=Generates Probability DistributionChart that is formatted to look nice."
RotationHistogram::usage="RotationHistogram[Ensemble_,Args___]"
RotationWheel::usage="RotationWheel[Ensemble_,Args___]"
PbcDelaunayNeighbours::usage="PbcDelaunayNeighbours[unBoundedData2D_,imagebox_,sym_]"
ApplyLimitedPBC::usage="ApplyLimitedPBC[data2d_, box_ ,extraArea___]"
Begin["`Private`"]
(* Generic Functions - Multipurpose *)
closedBindingBox:={{0.,0.},{1.,0.},{1.,1.},{0.,1.},{0.,0.}};
bindingBox:={{0.,0.},{1.,0.},{1.,1.},{0.,1.}};
rectangleBindingBox[a_,b_]:=Block[{},closedBindingBox.{{a,0},{0,b}}];
standardPolygon[numberOfSides_]:=Block[{},N@Table[{Cos[\[Theta]],Sin[\[Theta]]},{\[Theta],0,2Pi,2Pi/numberOfSides}]];
PolyArea=Compile[{ {poly,_Real,2}},
Block[{Xi,Yi,xR,yR},
{Xi,Yi}=Transpose@poly;
xR = RotateRight@Xi;
yR=RotateRight@Yi;
Abs[(Total[xR*Yi] - Total[Xi*yR])/2.] ],CompilationTarget->"C" ];
(*(* Returns "True" or "False" depending on if it is inside the polygon *)
(* http://mathematica.stackexchange.com/questions/9405/how-to-check-if-a-2d-point-is-in-a-polygon *)*)
inPolyQ2= Compile[{{poly,_Real,2},{x,_Real},{y,_Real}},
Block[{Xi,Yi,Xip1,Yip1,u,v,w},
{Xi,Yi}=Transpose@poly;
Xip1=RotateLeft@Xi;
Yip1=RotateLeft@Yi;
u=UnitStep[y-Yi];
v=RotateLeft@u;
w=UnitStep[-((Xip1-Xi)(y-Yi)-(x-Xi)(Yip1-Yi))];
Total[(u (1-v)(1-w) - (1-u) v w)] !=0],CompilationTarget->"C",RuntimeOptions->"Speed"];
negQ[num_]:= Block[{},If[num< 0,True,False]];
hexToRGB=RGBColor@@(IntegerDigits[#~StringDrop~1~FromDigits~16,256,3]/255.)&;
standardGrowthRate:=10^-5;
HexagonArea[r_]:= Block[{},(2 Sqrt[3])r^2];
HexagonalDiameter[n_, box_]:=Sqrt[2/((n/PolyArea[box]) Sqrt[3])];
(* This is the main function that moves the particle centroids! *)
Hexaticize[d_,dr_]:=d+RandomVariate[NormalDistribution[0.0,dr],{Length[d],Length[d[[1]]]}];
(* Boundary Conditions - Solving Boxes and Applying Virtual Particles *)
AutoBoxTransform[indata2D_]:=Block[{b,ba,data2D},
data2D=indata2D[[All,1;;2]];
b=rectangleBindingBox[Sequence@@(EuclideanDistance[Max[#],Min[#]]&/@Transpose[data2D])];
b=TranslationTransform[-RegionCentroid[Polygon[b]]][b];
ba=TranslationTransform[RegionCentroid[ConvexHullMesh[data2D[[;;,1;;2]]]]][(1.+(1/Sqrt[3./Sqrt[2.]]/Sqrt[Length[data2D]] )) b];
ba];
MinMaxBox[inPoints_ ] :=Block[{dh,minX,minY,maxX,maxY},
minX=Min[inPoints[[;;,1]]];
minY=Min[inPoints[[;;,2]]];
maxX=Max[inPoints[[;;,1]]];
maxY=Max[inPoints[[;;,2]]];
dh= ((maxX+minX) +(maxY+minY))/((maxX - minX) +(maxY- minY));
If[maxX <1||maxY<1, dh=dh-1];
{{minX,minY}-{dh,dh},{minX,maxY}+{-dh,dh},{maxX,maxY}+{dh,dh},{maxX,minY}+{dh,-dh}}
];
Options[ApplyPeriodicBoundary]= {SetDistance->1,ReturnDim->2};
ApplyPeriodicBoundary[inData2d_,box_, OptionsPattern[] ]:=Block[{dx= OptionValue[SetDistance],initPoints,pbcPoints,xLow,xHi,yLow,yHi,FullPbcPoints,np,xmin,xmax,ymin,ymax,SetDistance,Dim,ReturnDim=OptionValue[ReturnDim],data2d,dataInsideBox},
(* Reject any particles outside the box - for numerical accuracy *)
dataInsideBox=Pick[inData2d,
MapThread[inPolyQ2[box,#1,#2]&,Transpose[inData2d[[All,1;;2]]]]];
np=Length[dataInsideBox];
If[np!=Length[inData2d],Print["Warning! Data lies outside box region and will be clipped! (ApplyPeriodicBoundary[])"];];
(* Apply 3d scheme to 2d data - include zero rotation of particles *)
Dim = Last[Dimensions[inData2d]];
If[Dim==2,data2d=PadLeft[# ,3,0.,1] &/@dataInsideBox ];
If[Dim== 3,data2d=dataInsideBox[[;;,1;;Dim]];];
(* Periodic basis vectors assigned from box *)
xmin=Min[box[[All,1]] ];
xmax=Max[box[[All,1]] ];
ymin=Min[box[[All,2]] ];
ymax=Max[box[[All,2]] ];
(* Extented distance outside the box to include pbc effects *)
If[dx<0,dx=Sqrt[PolyArea[box]/np]];
xLow=xmin+dx;
xHi=xmax - dx;
yLow=ymin + dx;
yHi=ymax - dx;
(* Routines to append pbc virtual particles outside the box *)
pbcPoints={};
Do[If[data2d[[x,1]]<=xLow,AppendTo[pbcPoints,data2d[[x,1;;3]]+{xmax,ymin,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,2]]<=yLow,AppendTo[pbcPoints,data2d[[x,1;;3]]+{xmin,ymax,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= xHi,AppendTo[pbcPoints,data2d[[x,1;;3]]-{xmax,ymin,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,2]]>=yHi,AppendTo[pbcPoints,data2d[[x,1;;3]]-{xmin,ymax,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]<=xLow && data2d[[x,2]]<= yLow,AppendTo[pbcPoints,data2d[[x,1;;3]]+{xmax,ymax,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= xHi && data2d[[x,2]]>= yHi,AppendTo[pbcPoints,data2d[[x,1;;3]]-{xmax,ymax,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]<=xLow && data2d[[x,2]]>= yHi,AppendTo[pbcPoints,data2d[[x,1;;3]]+{xmax,-ymax,0.} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= xHi&& data2d[[x,2]]<= yLow,AppendTo[pbcPoints,data2d[[x,1;;3]]+{-xmax,ymax,0.} ]] ,{x,1,np}];
Flatten[{data2d[[All,1;;ReturnDim]],pbcPoints[[All,1;;ReturnDim]]},1]
];
Options[ApplyImageChargeBoundary]= {SetDistance->1,ReturnDim->2};
ApplyImageChargeBoundary[inData2d_,box_,OptionsPattern[]]:=Block[{dx=OptionValue[SetDistance],Dim=OptionValue[ReturnDim],icbPoints,FullIcbPoints,np,xmin,xmax,ymin,ymax,bMinX,bMaxX,bMinY,bMaxY,SetDistance,dataInsideBox,data2d},
(* Reject any particles outside the box - for numerical accuracy *)
dataInsideBox=Pick[inData2d,
MapThread[inPolyQ2[box,#1,#2]&,Transpose[inData2d[[All,1;;2]]]]];
np=Length[dataInsideBox];
If[np!=Length[inData2d],Print["Warning! Data lies outside box region and will be clipped! (ApplyImageChargeBoundary[])"];];
icbPoints ={};
np=Length[dataInsideBox];
(* Basis vectors for reflection trasformation at wall *)
xmin=Min[box[[All,1]] ];
xmax=Max[box[[All,1]] ];
ymin=Min[box[[All,2]] ];
ymax=Max[box[[All,2]] ];
bMinX=xmin+ dx;
bMaxX=xmax - dx;
bMinY=ymin + dx;
bMaxY=ymax - dx;
icbPoints=Flatten[ Reap[
MapThread[
(*-------------- Center Left *)
(If[#1<= bMinX,Sow[{xmin+(xmin-#1),#2} ]] ;
(*-------------- Center Right *)
If[#1>= bMaxX,Sow[{xmax+(xmax-#1),#2} ]] ;
(*-------------- Bottom Center *)
If[#2<=bMinY,Sow[{#1,ymin+(ymin-#2)} ]] ;
(*-------------- Top Center *)
If[#2>=bMaxY,Sow[{#1,ymax+(ymax-#2)} ]] ;
(*-------------- Bottom Left *)
If[#1<=bMinX &<= bMinY,Sow[{xmin-(#1-xmin),ymin-(#2-ymin)} ]] ;
(*-------------- Top Right *)
If[#1>= bMaxX && #2>= bMaxY,Sow[{xmax+(xmax-#1),ymax+(ymax-#2)} ]] ;
(*-------------- Top Left *)
If[#1<=bMinX && #2>= bMaxY,Sow[{xmin-(#1-xmin),ymax+(ymax-#2)} ]] ;
(*-------------- Bottom Right *)
If[#1>= bMaxX&& #2<= bMinY,Sow[{xmax+(xmax-#1),ymin-(#2-ymin)} ]];)& ,Transpose@dataInsideBox];][[2]],1];
FullIcbPoints=Flatten[{dataInsideBox[[;;,1;;2]],icbPoints},1]
];
ApplyGeneralPBC[data2d_,box_, numNN___]:=Block[{dx,pbcPoints,bmin,bmax,FullPbcPoints,np,xmin,xmax,ymin,ymax,Nnn},
pbcPoints ={};
np=Length[data2d];
xmin=Min[box[[All,1]] ];
xmax=Max[box[[All,1]] ];
ymin=Min[box[[All,2]] ];
ymax=Max[box[[All,2]] ];
dx= Sqrt[2./ (Sqrt[3.] (np / PolyArea[box]) )];
If[numNN=!=Null,Nnn=numNN];
If[numNN===Null,Nnn= 1.4 ];
If[ymax>= xmax, bmin= ymin+ Nnn dx ,bmin= xmin+Nnn dx ];
If[ymax>= xmax, bmax=ymax-Nnn dx,bmax=xmax-Nnn dx];
Do[If[data2d[[x,1]]<=bmin,AppendTo[pbcPoints,data2d[[x,1;;2]]+{xmax,ymin} ]] ,{x,1,np}];
Do[If[data2d[[x,2]]<=bmin,AppendTo[pbcPoints,data2d[[x,1;;2]]+{xmin,ymax} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= bmax,AppendTo[pbcPoints,data2d[[x,1;;2]]-{xmax,ymin} ]] ,{x,1,np}];
Do[If[data2d[[x,2]]>=bmax,AppendTo[pbcPoints,data2d[[x,1;;2]]-{xmin,ymax} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]<=bmin && data2d[[x,2]]<= bmin,AppendTo[pbcPoints,data2d[[x,1;;2]]+{xmax,ymax} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= bmax && data2d[[x,2]]>= bmax,AppendTo[pbcPoints,data2d[[x,1;;2]]-{xmax,ymax} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]<=bmin && data2d[[x,2]]>= bmax,AppendTo[pbcPoints,data2d[[x,1;;2]]+{xmax,-ymax} ]] ,{x,1,np}];
Do[If[data2d[[x,1]]>= bmax&& data2d[[x,2]]<= bmin,AppendTo[pbcPoints,data2d[[x,1;;2]]+{-xmax,ymax} ]] ,{x,1,np}];
FullPbcPoints=Flatten[{data2d[[;;,1;;2]],pbcPoints},1]
];
(* Building Lattices - Hexagonal and Square *)
Options[SquareLattice]={n->400,box-> closedBindingBox};
SetOptions[SquareLattice,n->400,box-> closedBindingBox];
SquareLattice[OptionsPattern[]]:=Block[
{ \[CapitalDelta],intensity,xmin,ymin, xmax,ymax,square,rot,f,\[Phi],\[Theta],b,ba,
nO= OptionValue[n],
boxO=OptionValue[box]
},
xmin=Min[boxO[[All,1]] ];
xmax=Max[boxO[[All,1]] ];
ymin=Min[boxO[[All,2]] ];
ymax=Max[boxO[[All,2]] ];
(*intensity=n/((xmax-xmin)*(ymax-ymin));*)
intensity= nO/ Area[ Polygon[boxO]];
\[CapitalDelta]=Sqrt[1./(intensity)];
square=(\[CapitalDelta])Flatten[Table[{x,y}, {x,0.5,Floor@Sqrt@nO},{y,0.5,Floor@Sqrt@nO}],1];
Pick[square,(inPolyQ2[boxO,#[[1]],#[[2]] ]&/@ square)]
(*square*)
];
Options[HexagonalLattice]={n->400,box-> closedBindingBox,radius->1.,periodic->False};
HexagonalLattice[OptionsPattern[]]:=Block[
{ \[CapitalDelta],x,y,pa,pb,xmin,ymin, xmax,ymax,hex,hexIn,hexPBC,rot,f,\[Phi],\[Theta],i=0,intensity,bigbox,
nO= OptionValue[n],
boxO=OptionValue[box],
radius=OptionValue[radius],
periodic=OptionValue[periodic]
},
xmin=Min[boxO[[All,1]] ];
xmax=Max[boxO[[All,1]] ];
ymin=Min[boxO[[All,2]] ];
ymax=Max[boxO[[All,2]] ];
intensity= nO / Area[ Polygon[boxO]];
\[CapitalDelta]=Sqrt[2./(intensity*Sqrt[3.])];
If[periodic==True,
bigbox={{xmin-Abs[xmax],ymin-Abs[ymax]},{xmax+Abs[xmax],ymin-Abs[ymax]},
{xmax+Abs[xmax],ymax+Abs[ymax]},{xmin-Abs[xmax],ymax+Abs[ymax]}};
(* Oblique Section of Hexagonal *)
x=Table[a,{a,xmin-Abs[xmax],xmax+Abs[xmax], \[CapitalDelta]}];
y=Table[a,{a,ymin-Abs[ymax],ymax+Abs[ymax],Sqrt[3.] \[CapitalDelta]}];
pa=Tuples[{x,y}];
(* Shifted Section *)
x=Table[a,{a,xmin+(\[CapitalDelta]/2.)-Abs[xmax],xmax+Abs[xmax], \[CapitalDelta]}];
y=Table[(\[CapitalDelta] Sqrt[3.]/2.)+(\[CapitalDelta] Sqrt[3.])a -Abs[xmax],{a,ymin,Ceiling[Length[x/2]]}];
pb=Tuples[{x,y}];
(* Assign Hexagonal Pattern *)
hex=Flatten[{pa,pb},1];
hex=Select[hex,inPolyQ2[bigbox,#[[1]],#[[2]] ]==True&];
hex=Sort[hex, inPolyQ2[boxO,#[[1]],#[[2]] ]==True& ];
];
If[periodic==False,
(* Oblique Section of Hexagonal *)
x=Table[a,{a,xmin,xmax, \[CapitalDelta]}];
y=Table[a,{a,ymin,ymax,Sqrt[3.] \[CapitalDelta]}];
pa=Tuples[{x,y}];
(* Shifted Section *)
x=Table[a,{a,xmin+(\[CapitalDelta]/2.),xmax, \[CapitalDelta]}];
y=Table[(\[CapitalDelta] Sqrt[3.]/2.)+(\[CapitalDelta] Sqrt[3.])a,{a,ymin,Ceiling[Length[x]/2]}];
pb=Tuples[{x,y}];
(* Assign Hexagonal Pattern *)
hex=Flatten[{pa,pb},1];
(* Redo If there is some kind of mis-alignment at the top *)
While[Length[hex]< nO,
i++;
x=Table[a,{a,xmin+(\[CapitalDelta]/2.),xmax+((\[CapitalDelta]/2.)), \[CapitalDelta]}];
y=Table[(\[CapitalDelta] Sqrt[3.]/2.)+(\[CapitalDelta] Sqrt[3.])a,{a,ymin,Ceiling[Length[x]/2]+i}];
pb=Tuples[{x,y}];hex=Flatten[{pa,pb},1];
];
(* Solve Optimization for Rotation of Lattice to obtain Best Estimate of points inside box *)
If[nO<200,
rot=RegionCentroid[Polygon[boxO]];
f[in\[Phi]_Real]:=
Abs[nO-Length[
Pick[hex,(inPolyQ2[boxO,#[[1]],#[[2]] ]&/@ (RotationTransform[in\[Phi],rot][hex]) ) ]]];
\[Phi]= NArgMin[f[\[Theta]],\[Theta]];
(* Returns the Lattice *)
Pick[hex,(inPolyQ2[boxO,#[[1]],#[[2]] ]&/@ (RotationTransform[\[Phi],rot][hex]))]
,hex]
(*hex*)
];
Pick[hex,(inPolyQ2[boxO,#[[1]],#[[2]] ]&/@ hex)]
];
(* Pair Correlation Function Routines *)
(*http://forums.wolfram.com/mathgroup/archive/2009/Apr/msg00533.html*)
distancesWithEdgeCorrections=Compile[{{ll,_Real,2},{np,_Integer}},
Sort[Flatten[Table[If[k<j,
Sqrt[#.#]&[(ll[[k]]-ll[[j]])],-1]
,{j,Length[ll]},{k,np}]]]
,"RuntimeOptions"->"Speed",CompilationTarget->"C",Parallelization->True];
(*http://forums.wolfram.com/mathgroup/archive/2009/Apr/msg00533.html*)
radialDistributionC=Compile[{{dlist,_Real,1},{r,_Real},{eps,_Real}},Catch[Module[{len=Length[dlist],bot=r-eps,top=r+eps,lo=1,mid,hi},hi=len;
If[dlist[[lo]]>top||dlist[[hi]]<bot,Throw[0]];
mid=Ceiling[(hi+lo)/2.];
While[dlist[[lo]]<bot&&mid>lo,If[dlist[[mid]]<bot,lo=mid;mid=Ceiling[(hi+lo)/2.],mid=Floor[(mid+lo)/2.];]];
mid=Ceiling[(hi+lo)/2.];
While[dlist[[hi]]>top&&mid<hi,If[dlist[[mid]]>top,hi=mid;mid=Floor[(hi+lo)/2.],mid=Ceiling[(mid+hi)/2.];]];
Round[(hi-lo+1)/2]]],"RuntimeOptions"->"Speed",CompilationTarget->"C",Parallelization->True];
Options[PairCorrelationFunction]= { box->{},boundary->"trunc",lattice->"none",shells->4.25,distance-> {}};
SetOptions[PairCorrelationFunction, box->{},boundary->"trunc",lattice->"none",shells->4.25,distance-> {}];
PairCorrelationFunction[data2d_, OptionsPattern[] ]:=Block[{d, dr,density,pcf,ensemblePCF,bins,spacing,confData,n,nconfs,rList,volume,td,truncBox,
autobox,autodistance,maxdist=Infinity,singlePCF,xBoxLength,yBoxLength,
boxO= OptionValue[box],
edgeO= OptionValue[boundary],
latticeO=OptionValue[lattice],
shellsO=OptionValue[shells],
distanceO=OptionValue[distance]
},
(* If only one configuration, make into ensemble of size=1 *)
If[TensorRank[data2d]==2,confData={data2d};,confData=data2d;];
nconfs=Length[confData];
If[boxO==={},autobox=True,autobox=False];
If[distanceO==={},autodistance=True,autodistance=False];
Do[
(* Default Options *)
(* -----------------------------------*)
(* Box Not Set - Auto Select Container *)
If[autobox==True,
boxO=AutoBoxTransform[confData[[conf]]];
n=Length[confData[[conf]]];
,
n= Length[Sort[confData[[conf,All,1;;2]],inPolyQ2[boxO,#[[1]],#[[2]] ]==True&]];
];
spacing =1./( Sqrt[n]);
(* Distance not set - Auto Select Shells *)
If[ autodistance==True||distanceO<= 0,
(*Print["d"];*)
distanceO=Sqrt[PolyArea@boxO] spacing shellsO;
(*Print[distanceO \[LessEqual] maxdist];*)
(*If[distanceO \[LessEqual] maxdist, maxdist= distanceO;Print[maxdist];];*)
];
dr=(( distanceO spacing /(2shellsO)));
(* -----------------------------------*)
(* Create List with normalized bins between configurations *)
rList=Table[r,{r,dr,( distanceO ),dr}];
If[Max[rList] < maxdist,maxdist= Max[rList];(*Print[ Max[rList]];*)];
volume=PolyArea[boxO];
(* Selection for Edge Corrections *)
Which[
(* Use Periodic Hexagonal Lattice *)
ToUpperCase[latticeO]==ToUpperCase["hex"]||ToUpperCase[latticeO]==ToUpperCase["square"],
n=Length[Select[confData[[conf]],inPolyQ2[boxO,#[[1]],#[[2]] ]==True&]];
td=confData[[conf,All,1;;2]];,
(* Periodic Boundaries *)
ToUpperCase[edgeO]==ToUpperCase["periodic"] || ToUpperCase[edgeO]==ToUpperCase["pbc"],
td=ApplyPeriodicBoundary[confData[[conf,All,1;;2]],boxO,SetDistance->(distanceO dr/2),ReturnDim->2];,
(* Image Charge Boundaries *)
ToUpperCase[edgeO]==ToUpperCase["image"]||ToUpperCase[edgeO]==ToUpperCase["hard"],
td=ApplyImageChargeBoundary[confData[[conf,All,1;;2]],boxO,SetDistance->(distanceO dr/2)];,
(* Apply -NO- Edge Corrections *)
ToUpperCase[edgeO]==ToUpperCase["none"]|| ToUpperCase[edgeO]==ToUpperCase["NoEdge"],
td=confData[[conf,All,1;;2]];,
(* Apply -NO- Edge Corrections *)
ToUpperCase[edgeO]==ToUpperCase["trunc"]|| ToUpperCase[edgeO]==ToUpperCase["Truncated"],
{xBoxLength,yBoxLength}=(EuclideanDistance@@@Partition[boxO,2,1])[[1;;2]];
truncBox=First[ScalingTransform[{( 2*distanceO-xBoxLength)/xBoxLength,(2*distanceO-yBoxLength)/yBoxLength}, RegionCentroid[Polygon[#]]][#]&/@{boxO}];
n=Length[Select[confData[[conf]],inPolyQ2[truncBox,#[[1]],#[[2]] ]==True&]];
volume=PolyArea[truncBox];
td=Sort[confData[[conf,All,1;;2]],inPolyQ2[truncBox,#[[1]],#[[2]] ]==True&];
];
d=Select[distancesWithEdgeCorrections[td,n ],#>0.0&];
pcf=Table[(volume) radialDistributionC[d,r,dr]/ ( Pi (n(n-1)) r dr),{r,dr,( distanceO ),dr}];
singlePCF=Interpolation[Prepend[Transpose[{rList,pcf}],{0.,First[pcf]}],InterpolationOrder->1];
If[conf==1, ensemblePCF=Interpolation[Prepend[Transpose[{rList,0.0pcf}],{0.,0.0}],InterpolationOrder->1];];
ensemblePCF=Interpolation[Table[{x,ensemblePCF[x]+singlePCF[x]},{x,0.,maxdist,maxdist/1024.}],InterpolationOrder->1];
,{conf,1,nconfs}];
(* Create Average of the Pair Correlation Functions *)
Table[{x,ensemblePCF[x]/nconfs},{x,0.,maxdist,maxdist/1024.}]
];
InterpolationFunctionDifference[reference_, diffFunct_ ,xMax___]:= Block[{interpdRef,interpdFunction,xMin,funct,dif,dx=1024,differencedFunction,interpolatedReference,interpolatedComparing,interpolationNumber=1,rms},
(* Interpolates the function to be subtracted from reference *)
interpdFunction=Interpolation[diffFunct,InterpolationOrder->interpolationNumber];
interpdRef= Interpolation[reference,InterpolationOrder->interpolationNumber];
(*interpdFunction=Interpolation[reference];*)
(* Builds the difference function at the x-positions of reference *)
(* Solves this function at the x-positions of the reference *)
xMin=Max[{Min@reference[[;;,1]],Min@diffFunct[[;;,1]] } ];
If[xMax===Null,
funct= Table[{reference[[x,1]],interpdFunction[reference[[x,1]]]-reference[[x,2]]},{x,Range@Length@diffFunct[[;;,1]]}];
,
differencedFunction= Table[{x,interpdFunction[x]-interpdRef[x]},{x,xMin,xMax,xMax/dx }];
interpolatedReference=Table[{x,interpdRef[x]},{x,xMin,xMax,xMax/dx }];
interpolatedComparing=Table[{x,interpdFunction[x]},{x,xMin,xMax,xMax/dx }];
rms=RootMeanSquare[differencedFunction[[;;,2]]];
];
{rms,differencedFunction,interpolatedReference,interpolatedComparing}
];
Options[PlotPairCorrelationFunction]={box-> {} ,boundary-> "trunc",lattice-> "",shells-> 4,distance->{} , normalized->False,absgr-> False,stacked->True, xLabel->"Distance (r)" ,names-> {}, boots-> 25};
SetOptions[PlotPairCorrelationFunction,box-> {} , boundary->"trunc" ,lattice-> "",shells-> 4,distance->{} ,normalized->False ,absgr-> False,stacked->True, xLabel->"Distance (r)" ,names-> {},boots-> 25];
PlotPairCorrelationFunction[inData2d_, OptionsPattern[]]:=
Block[{
xyDataList,xyData,xyLattice,r,dr,xyDataDisplaced,xyLatticeDisplaced,pcfData,pcfLattice,hexBox,
paddingA,paddingB,bstyle,normalizedRef, normalizedFunc, rmsMetric,differenceOfBoth,inRef,inFunc,maxDelta,minDelta,errorGrid,
nfuncts,gridLines,latticePeaks,colours,polys,lmsize,fullData,fullNames,diffRMSmetrics,diffLists,interpFullDataN,tempDelta,maxR,difPlots,stackedPlots,Func,funcNameList,returnedPlot,
ref,refName,func,
rmsList,
pcfDataList,pcfLatticeList,pcfResidualList,pcfFirstPeakList,
xMaxSaved,dataExpectedDiameterList,
npointsDataList,npointsLatticeList,
passedOptions,optionNames,optionNamesO,
boxO=OptionValue[box],
boundaryO = OptionValue[boundary],
shellsO=OptionValue[shells],
distanceO= OptionValue[distance],
normalizedO= OptionValue[normalized],
stackedO= OptionValue[stacked],
namesO=OptionValue[names],
xLabelO=OptionValue [xLabel],
bootsO=OptionValue[boots],
latticeO=OptionValue[lattice],
absgrO=OptionValue[absgr]
},
xMaxSaved=Infinity;
(* Smoothed *)
(* Remove any non-positional data that might be passed when called *)
optionNames={box,boundary,lattice,shells,distance};
optionNamesO:= {boxO,boundaryO,latticeO,shellsO,distanceO};
(* Autodetect if more than one dataset is input *)
If[TensorRank[inData2d]==2,xyDataList={inData2d};, xyDataList=inData2d;];
nfuncts= Length[xyDataList];
If[namesO==={},namesO=Table["Data: "<>ToString[x],{x,nfuncts}];,
Which[Length[namesO]==0,namesO={namesO};,Length[namesO]< nfuncts , Print["Number of Names NOT EQUAL to Number of Data Sets!"];
];
];
(* Initialize Arrays for PCFs *)
rmsList=ConstantArray[{},nfuncts];
pcfDataList=ConstantArray[{},nfuncts];
pcfLatticeList=ConstantArray[{},nfuncts];
pcfResidualList=ConstantArray[{},nfuncts];
dataExpectedDiameterList=ConstantArray[{},nfuncts];
pcfFirstPeakList = ConstantArray[{},nfuncts];
npointsDataList=ConstantArray[{},nfuncts];
npointsLatticeList=ConstantArray[{},nfuncts];
Do[
xyData=xyDataList[[nf]];
If[Length[xyData[[1]]]==3,xyData=xyData[[All,1;;2]]];