-
Notifications
You must be signed in to change notification settings - Fork 23
/
modMath.bas
7530 lines (6780 loc) · 229 KB
/
modMath.bas
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
Attribute VB_Name = "modMath"
Option Explicit
'====================================================
'This module contains commonly used functions like sorting,
'matrix decompositions, random number generator etc. In most cases
'arrays are assumed to be 1-based, unless otherwise specified.
'=====================================================
'========================================
'Sorting & Searching Algorithms
'========================================
'Search for target integer in sorted array x(1 to N), returns positon index if found, -1 if not found
Function Binary_Search(x() As Long, tgt As Long) As Long
Dim i As Long, n As Long, m As Long
Dim iL As Long, iR As Long
n = UBound(x)
iL = 1
iR = n
Binary_Search = -1
Do
If iL > iR Then
Binary_Search = -1 'target not found
Exit Do
ElseIf x(iL) = tgt Then
Binary_Search = iL
Exit Do
ElseIf x(iR) = tgt Then
Binary_Search = iR
Exit Do
Else
m = Int((iL + iR) / 2)
If x(m) = tgt Then
Binary_Search = m
Exit Do
ElseIf x(m) < tgt Then
iL = m + 1
ElseIf x(m) > tgt Then
iR = m - 1
End If
End If
Loop
End Function
'if x(1:N) is sorted in ascending order:
'Returns interger i s.t. x(i) <= tgt < x(i+1), -1 is return if tgt<x(1) or x(n)<tgt
'if x(1:N) is sorted in descending order:
'Returns interger i s.t. x(i) >= tgt > x(i+1), -1 is return if tgt>x(1) or x(n)>tgt
Function Binary_Search_Db(x As Variant, tgt As Variant) As Long
Dim n As Long, m As Long, iL As Long, iR As Long
n = UBound(x): iL = 1: iR = n
If x(1) < x(n) Then
If tgt < x(1) Or tgt > x(n) Then
Binary_Search_Db = -1
ElseIf tgt >= x(1) And tgt < x(2) Then
Binary_Search_Db = 1
ElseIf tgt = x(n) Then
Binary_Search_Db = n
Else
Do While (iR - iL) > 1
m = (iR + iL) \ 2
If tgt >= x(m) Then
iL = m
Else
iR = m
End If
Loop
Binary_Search_Db = iL
End If
Else
If tgt > x(1) Or tgt < x(n) Then
Binary_Search_Db = -1
ElseIf tgt <= x(1) And tgt > x(2) Then
Binary_Search_Db = 1
ElseIf tgt = x(n) Then
Binary_Search_Db = n
Else
Do While (iR - iL) > 1
m = (iR + iL) \ 2
If tgt <= x(m) Then
iL = m
Else
iR = m
End If
Loop
Binary_Search_Db = iL
End If
End If
End Function
'Return the k-th smallest value and its respective postion
'Input: x() and k
'Output: x_min and i_min, single value if output_list is FALSE.
'If output_list is set to TRUE, x_min and i_min return vector of values holding all k values.
Sub Smallest_k(x As Variant, k As Long, x_min As Variant, i_min As Variant, Optional output_list As Boolean = False)
Dim i As Long, j As Long, m As Long, n As Long, minIndex As Long
Dim minValue As Variant, swap As Variant, y As Variant, iArr() As Long
n = UBound(x)
y = x
ReDim iArr(1 To n)
For i = 1 To n
iArr(i) = i
Next i
For i = 1 To k
minIndex = i
minValue = y(i)
For j = i + 1 To n
If y(j) < minValue Then
minIndex = j
minValue = y(j)
swap = y(i)
y(i) = y(minIndex)
y(minIndex) = swap
m = iArr(i)
iArr(i) = iArr(minIndex)
iArr(minIndex) = m
End If
Next j
Next i
ReDim Preserve y(1 To k)
ReDim Preserve iArr(1 To k)
If output_list = True Then
x_min = y
i_min = iArr
Else
x_min = y(k)
i_min = iArr(k)
End If
Erase y, iArr
End Sub
Sub Sort_Bubble(x As Variant)
Dim i As Long, n As Long, swap As Long
Dim temp As Variant
n = UBound(x)
Do
swap = 0
For i = 1 To n - 1
If x(i + 1) < x(i) Then
swap = i
temp = x(i)
x(i) = x(i + 1)
x(i + 1) = temp
End If
Next i
n = swap
Loop Until swap = 0
End Sub
Sub Sort_Bubble_A(x As Variant, sort_index() As Long, Optional first_run As Long = 1)
Dim i As Long, j As Long, n As Long, swap As Long
Dim temp As Variant
n = UBound(x)
If first_run = 1 Then
ReDim sort_index(1 To n)
For i = 1 To n
sort_index(i) = i
Next i
End If
Do
swap = 0
For i = 1 To n - 1
If x(i + 1) < x(i) Then
swap = i
temp = x(i)
x(i) = x(i + 1)
x(i + 1) = temp
j = sort_index(i)
sort_index(i) = sort_index(i + 1)
sort_index(i + 1) = j
End If
Next i
n = swap
Loop Until swap = 0
End Sub
Sub Sort_Quick(vArray As Variant, inLow As Long, inHi As Long)
Dim pivot As Double
Dim tmpSwap As Variant
Dim tmpLow As Long, tmpHi As Long
tmpLow = inLow
tmpHi = inHi
pivot = vArray((inLow + inHi) \ 2)
While (tmpLow <= tmpHi)
While (vArray(tmpLow) < pivot And tmpLow < inHi)
tmpLow = tmpLow + 1
Wend
While (pivot < vArray(tmpHi) And tmpHi > inLow)
tmpHi = tmpHi - 1
Wend
If (tmpLow <= tmpHi) Then
tmpSwap = vArray(tmpLow)
vArray(tmpLow) = vArray(tmpHi)
vArray(tmpHi) = tmpSwap
tmpLow = tmpLow + 1
tmpHi = tmpHi - 1
End If
Wend
If (inLow < tmpHi) Then Sort_Quick vArray, inLow, tmpHi
If (tmpLow < inHi) Then Sort_Quick vArray, tmpLow, inHi
End Sub
Sub Sort_Quick_A(vArray As Variant, inLow As Long, inHi As Long, sort_index() As Long, Optional first_run As Long = 1)
Dim pivot As Double
Dim tmpSwap As Variant
Dim tmpLow As Long, tmpHi As Long, i As Long
If first_run = 1 Then
ReDim sort_index(LBound(vArray) To UBound(vArray))
For i = LBound(vArray) To UBound(vArray)
sort_index(i) = i
Next i
End If
tmpLow = inLow
tmpHi = inHi
pivot = vArray((inLow + inHi) \ 2)
While (tmpLow <= tmpHi)
While (vArray(tmpLow) < pivot And tmpLow < inHi)
tmpLow = tmpLow + 1
Wend
While (pivot < vArray(tmpHi) And tmpHi > inLow)
tmpHi = tmpHi - 1
Wend
If (tmpLow <= tmpHi) Then
tmpSwap = vArray(tmpLow)
vArray(tmpLow) = vArray(tmpHi)
vArray(tmpHi) = tmpSwap
i = sort_index(tmpLow)
sort_index(tmpLow) = sort_index(tmpHi)
sort_index(tmpHi) = i
tmpLow = tmpLow + 1
tmpHi = tmpHi - 1
End If
Wend
If (inLow < tmpHi) Then Sort_Quick_A vArray, inLow, tmpHi, sort_index, 0
If (tmpLow < inHi) Then Sort_Quick_A vArray, tmpLow, inHi, sort_index, 0
End Sub
Sub Sort_Merge(x As Variant)
Dim x1 As Variant, x2 As Variant
Dim i As Long, j As Long, n_raw As Long, n_mid As Long
n_raw = UBound(x, 1)
If n_raw = 1 Then Exit Sub
n_mid = Int(n_raw / 2)
ReDim x1(1 To n_mid)
ReDim x2(1 To n_raw - n_mid)
For i = 1 To n_mid
x1(i) = x(i)
Next i
For i = 1 To (n_raw - n_mid)
x2(i) = x(n_mid + i)
Next i
Call Sort_Merge(x1)
Call Sort_Merge(x2)
Call Merge(x1, x2, x)
End Sub
Private Sub Merge(xA As Variant, xB As Variant, xc As Variant)
Dim i As Long, j As Long, k As Long
Dim nA As Long, nB As Long, nc As Long
Dim sA As Long, Sb As Long
nA = UBound(xA)
nB = UBound(xB)
nc = nA + nB
ReDim xc(1 To nc)
sA = 1
Sb = 1
Do While sA <= nA And Sb <= nB
If xA(sA) > xB(Sb) Then
k = k + 1
xc(k) = xB(Sb)
Sb = Sb + 1
Else
k = k + 1
xc(k) = xA(sA)
sA = sA + 1
End If
Loop
Do While sA <= nA
k = k + 1
xc(k) = xA(sA)
sA = sA + 1
Loop
Do While Sb <= nB
k = k + 1
xc(k) = xB(Sb)
Sb = Sb + 1
Loop
End Sub
'Heap sort as implemented in "Numerical Recipes in FORTAN77"
Sub Sort_Heap(x As Variant)
Dim i As Long, j As Long, k As Long, n As Long, iR As Long
Dim tmp_x As Variant
n = UBound(x, 1)
If n < 2 Then Exit Sub
If n Mod 2 = 0 Then
k = n / 2 + 1
Else
k = (n - 1) / 2 + 1
End If
iR = n
Do
If k > 1 Then
k = k - 1
tmp_x = x(k)
Else
tmp_x = x(iR)
x(iR) = x(1)
iR = iR - 1
If iR = 1 Then
x(k) = tmp_x
Exit Sub
End If
End If
i = k
j = k + k
Do While j <= iR
If j < iR Then
If x(j) < x(j + 1) Then j = j + 1
End If
If tmp_x < x(j) Then
x(i) = x(j)
i = j
j = j + j
Else
j = iR + 1
End If
Loop
x(i) = tmp_x
Loop
End Sub
Sub Sort_Heap_A(x As Variant, sort_idx() As Long, Optional init_sort_idx As Long = 1)
Dim i As Long, j As Long, k As Long, m As Long, n As Long, iR As Long
Dim tmp_x As Variant
n = UBound(x, 1)
If init_sort_idx = 1 Then
ReDim sort_idx(1 To n)
For i = 1 To n
sort_idx(i) = i
Next i
End If
If n < 2 Then Exit Sub
If n Mod 2 = 0 Then
k = n / 2 + 1
Else
k = (n - 1) / 2 + 1
End If
iR = n
Do
If k > 1 Then
k = k - 1
tmp_x = x(k)
m = k
Else
tmp_x = x(iR)
x(iR) = x(1)
m = sort_idx(iR)
sort_idx(iR) = sort_idx(1)
iR = iR - 1
If iR = 1 Then
x(k) = tmp_x
sort_idx(k) = m
Exit Sub
End If
End If
i = k
j = k + k
Do While j <= iR
If j < iR Then
If x(j) < x(j + 1) Then j = j + 1
End If
If tmp_x < x(j) Then
x(i) = x(j)
sort_idx(i) = sort_idx(j)
i = j
j = j + j
Else
j = iR + 1
End If
Loop
x(i) = tmp_x
sort_idx(i) = m
Loop
End Sub
'========================================
'Percentile Functions
'========================================
Function fmedian(ByVal x As Variant) As Double
Dim n As Long, k As Long
n = UBound(x, 1)
Call Sort_Quick(x, 1, n)
If n Mod 2 = 0 Then
fmedian = (x(n / 2) + x(n / 2 + 1)) / 2
Else
fmedian = x((n + 1) / 2)
End If
End Function
'Intput: vector x(1 to N)
'Output: vector PercentileScore(1 to N)
Function PercentileScore(ByVal x As Variant) As Double()
Dim i As Long, j As Long, k As Long, n As Long
Dim iArr() As Long
Dim p() As Double
n = UBound(x)
Call Sort_Quick_A(x, 1, n, iArr, 1)
ReDim p(1 To n)
p(iArr(1)) = 0
k = 0
For i = 2 To n
j = iArr(i)
If x(i) > x(i - 1) Then k = i - 1
p(j) = k * 1# / (n - 1)
Next i
PercentileScore = p
Erase p, iArr
End Function
'Intput: vector x(1 to N)
'Output: vector fQuartile(0 to 4)
Function fQuartile(ByVal x As Variant) As Double()
Dim i As Long, j As Long, k As Long, n As Long
Dim tmp_y As Double
Dim iArr() As Long
Dim p() As Double
n = UBound(x)
Call Sort_Quick_A(x, 1, n, iArr, 1)
ReDim p(0 To 4)
p(0) = x(1)
p(4) = x(n)
For k = 1 To 3
tmp_y = (n - 1) * k * 0.25
i = Int(tmp_y)
p(k) = x(i + 1) + (x(i + 2) - x(i + 1)) * (tmp_y - i)
Next k
fQuartile = p
Erase p, iArr
End Function
'========================================
' Array manipulation
'========================================
'Return subset of an array A()
'Input: A(), 1D or 2D array
' idx1, index positions of the first dimension to return
' idx2, index positions of the second dimension to return
'Output: B()
Sub Filter_Array(ByVal A As Variant, B As Variant, Optional idx1 As Variant, Optional idx2 As Variant)
Dim i As Long, j As Long, k As Long
k = getDimension(A)
If k = 1 Then
ReDim B(1 To UBound(idx1))
For i = 1 To UBound(idx1)
B(i) = A(idx1(i))
Next i
ElseIf k = 2 Then
If IsMissing(idx1) = False And IsMissing(idx2) = False Then
If IsArray(idx1) = True And IsArray(idx2) = True Then
ReDim B(1 To UBound(idx1), 1 To UBound(idx2))
For i = 1 To UBound(idx1)
For j = 1 To UBound(idx2)
B(i, j) = A(idx1(i), idx2(j))
Next j
Next i
ElseIf IsArray(idx1) = True And IsArray(idx2) = False Then
ReDim B(1 To UBound(idx1))
For i = 1 To UBound(idx1)
B(i) = A(idx1(i), idx2)
Next i
ElseIf IsArray(idx1) = False And IsArray(idx2) = True Then
ReDim B(1 To UBound(idx2))
For i = 1 To UBound(idx2)
B(i) = A(idx1, idx2(i))
Next i
End If
ElseIf IsMissing(idx1) = False And IsMissing(idx2) = True Then
If IsArray(idx1) = True Then
ReDim B(1 To UBound(idx1), 1 To UBound(A, 2))
For i = 1 To UBound(idx1)
For j = 1 To UBound(A, 2)
B(i, j) = A(idx1(i), j)
Next j
Next i
Else
ReDim B(1 To UBound(A, 2))
For i = 1 To UBound(A, 2)
B(i) = A(idx1, i)
Next i
End If
ElseIf IsMissing(idx1) = True And IsMissing(idx2) = False Then
If IsArray(idx2) = True Then
ReDim B(1 To UBound(A, 1), 1 To UBound(idx2))
For i = 1 To UBound(A, 1)
For j = 1 To UBound(idx2)
B(i, j) = A(i, idx2(j))
Next j
Next i
Else
ReDim B(1 To UBound(A, 1))
For i = 1 To UBound(A, 1)
B(i) = A(i, idx2)
Next i
End If
End If
End If
End Sub
'return y(1:n-m+1) with the elements of x(m:n)
Sub MidArray(x As Variant, m As Long, n As Long, y As Variant)
Dim i As Long
ReDim y(1 To n - m + 1)
For i = m To n
y(i - m + 1) = x(i)
Next i
End Sub
'Append tgt to the end of a 1D vector x(0 to n)
Sub Append_1D(x As Variant, tgt As Variant)
Dim n As Long
n = UBound(x) + 1
ReDim Preserve x(LBound(x) To n)
x(n) = tgt
End Sub
'Remove the i-th element from vector x(0 to n)
Sub Erase_1D(x As Variant, i As Long)
Dim j As Long, n As Long
n = UBound(x)
If i = 0 Then Debug.Print "Erase_1D: error: cannot remove 0-th element"
If i = n Then
ReDim Preserve x(LBound(x) To n - 1)
ElseIf i < n Then
For j = i To n - 1
x(j) = x(j + 1)
Next j
ReDim Preserve x(LBound(x) To n - 1)
End If
End Sub
'Input: x(1 to M, 1 to N), 2D Matrix
'Output: y(), vector from the k-th row/column of x()
Sub get_vector(x As Variant, k As Long, idim As Long, y As Variant)
Dim i As Long, n As Long
If idim = 1 Then
n = UBound(x, 2)
ReDim y(1 To n)
For i = 1 To n
y(i) = x(k, i)
Next i
ElseIf idim = 2 Then
n = UBound(x, 1)
ReDim y(1 To n)
For i = 1 To n
y(i) = x(i, k)
Next i
End If
End Sub
'Combine multple vectors column-wise into a single array
'Syntax: Combine_Vec(vArr, x,y,z,...), where x,y,z,... are arrays of dimension
'either(1:N) or (1:N, 1:M), output will be as saved as an array in vArr. Each
'input must have the same number of rows N.
Sub Combine_Vec(vArr As Variant, ParamArray vecs() As Variant)
Dim i As Long, j As Long, k As Long, m As Long, n As Long, n_vec As Long, jj As Long
Dim uArr As Variant
n = UBound(vecs(LBound(vecs)))
n_vec = 0
ReDim vArr(1 To n, 1 To 1)
For k = LBound(vecs) To UBound(vecs)
uArr = vecs(k)
If modMath.getDimension(uArr) = 1 Then
n_vec = n_vec + 1
ReDim Preserve vArr(1 To n, 1 To n_vec)
If UBound(uArr) = n Then
For i = 1 To n
vArr(i, n_vec) = uArr(i)
Next i
Else
Debug.Print "Combine_vec: " & k & "-th item does not match in dimension."
End If
Else
m = UBound(uArr, 2)
n_vec = n_vec + m
ReDim Preserve vArr(1 To n, 1 To n_vec)
If UBound(uArr, 1) = n Then
For j = 1 To m
jj = n_vec - m + j
For i = 1 To n
vArr(i, jj) = uArr(i, j)
Next i
Next j
Else
Debug.Print "Combine_vec: " & k & "-th item does not match in dimension."
End If
End If
Erase uArr
Next k
End Sub
'Generate an integer array from m to n
Function index_array(m As Long, n As Long) As Long()
Dim i As Long
Dim intArray() As Long
ReDim intArray(m To n)
For i = m To n
intArray(i) = i
Next i
index_array = intArray
End Function
'Transpose when printing array to Excel worksheet
Function wkshtTranspose(A As Variant) As Variant
wkshtTranspose = Application.WorksheetFunction.Transpose(A)
End Function
'For the k-th step during a k-fold cross validation, return the index of training set and validation set
Sub CrossValidate_set(k As Long, k_fold As Long, iList() As Long, i_validate() As Long, i_train() As Long)
Dim i As Long, j As Long, m As Long, n As Long, n_train As Long, n_validate As Long
n = UBound(iList, 1)
n_validate = n \ k_fold
n_train = n - n_validate
ReDim i_validate(1 To n_validate)
ReDim i_train(1 To n_train)
'Validation set
For i = 1 To n_validate
i_validate(i) = iList((k - 1) * n_validate + i)
Next i
'Training set
j = 0
If k > 1 Then
For i = 1 To (k - 1) * n_validate
j = j + 1
i_train(j) = iList(i)
Next i
End If
For i = k * n_validate + 1 To n
j = j + 1
i_train(j) = iList(i)
Next i
'If there are unused data at the last step add them to the validation set
If k = k_fold And (k * n_validate) < n Then
m = n - (k * n_validate)
ReDim Preserve i_validate(1 To n_validate + m)
ReDim Preserve i_train(1 To n_train - m)
For i = 1 To m
i_validate(n_validate + i) = iList(k * n_validate + i)
Next i
End If
End Sub
'========================================
' Random Numbers
'========================================
'Returns a 1D array of Sample(1:n_required)
'Alias method copied from:
'https://www.keithschwarz.com/darts-dice-coins/
'x_in either a 1D array or a single integer, in latter case outputs are sampled from an integer sequence 1:n
'n_required number of samples to draw
'isReplace sample without replacement when set to False, default is True
'x_prob discrete prob dists as 1D arary of same length as x_in, assumed uniform if missing
Function Sample(x_in, n_required As Long, Optional isReplace As Boolean = True, Optional x_prob As Variant)
Dim i As Long, j As Long, k As Long, m As Long, n As Long, ii As Long, jj As Long
Dim x_idx() As Long, x_sample As Variant
Dim x_acceptance() As Double, x_alias() As Long
Dim q_small As cQueue, q_large As cQueue
Dim p() As Double
Dim tmp_x As Double, tmp_y As Double
Dim x As Variant
If Not IsArray(x_in) Then
n = Int(x_in)
ReDim x(1 To n)
For i = 1 To n
x(i) = i
Next i
Else
n = UBound(x, 1)
ReDim x(1 To n)
For i = 1 To n
x(i) = x_in(i)
Next i
End If
If isReplace = False Then
If n_required > n Then
Debug.Print "Sample: n_required (" & n_required & ") cannot be larger than n (" & n & ") when isReplace is False."
End
End If
End If
ReDim x_sample(1 To n_required)
If IsMissing(x_prob) Then
If isReplace Then
For i = 1 To n_required
k = Int(Rnd() * n) + 1
x_sample(i) = x(k)
Next i
Else
ReDim x_idx(1 To n)
ReDim p(1 To n)
For i = 1 To n
x_idx(i) = i
p(i) = Rnd()
Next i
Call Sort_Quick_A(p, 1, n, x_idx, 1)
For i = 1 To n_required
x_sample(i) = x(x_idx(i))
Next i
End If
Sample = x_sample
Exit Function
End If
If isReplace Then
If n_required <= 50 Then
ReDim p(1 To n)
p(1) = x_prob(1)
For i = 2 To n
p(i) = p(i - 1) + x_prob(i)
Next i
For i = 1 To n_required
x_sample(i) = x(Random_Integer_Prob(p, True))
Next i
Else
'for larger numbers use alias method
ReDim p(1 To n)
ReDim x_acceptance(1 To n)
ReDim x_alias(1 To n)
For i = 1 To n
p(i) = x_prob(i) * n
Next i
Set q_small = New cQueue
Set q_large = New cQueue
Call q_small.Init(n)
Call q_large.Init(n)
For i = 1 To n
If p(i) < 1 Then
Call q_small.Add(i)
Else
Call q_large.Add(i)
End If
Next i
Do While q_small.size > 0 And q_large.size > 0
i = q_small.Pop
j = q_large.Pop
x_acceptance(i) = p(i)
x_alias(i) = j
p(j) = p(j) + p(i) - 1
If p(j) < 1 Then
Call q_small.Add(j)
Else
Call q_large.Add(j)
End If
Loop
Do While q_large.size > 0
j = q_large.Pop
x_acceptance(j) = 1
Loop
Do While q_small.size > 0
j = q_small.Pop
x_acceptance(j) = 1
Loop
For i = 1 To n_required
tmp_x = Rnd()
k = Int(tmp_x * n) + 1
tmp_y = tmp_x * n + 1 - k
If tmp_y < x_acceptance(k) Then
x_sample(i) = x(k)
Else
x_sample(i) = x(x_alias(k))
End If
Next i
End If
Sample = x_sample
Exit Function
End If
If n_required <= 50 Then
ReDim p(1 To n)
For i = 1 To n
p(i) = x_prob(i)
Next i
ReDim x_sample(1 To n_required)
For i = 1 To n_required
k = Random_Integer_Prob(p, False)
x_sample(i) = x(k)
tmp_x = 1 - p(k)
p(k) = 0
For j = 1 To n
p(j) = p(j) / tmp_x
Next j
Next i
Else
'Exponential-sort trick from
'https://timvieira.github.io/blog/post/2019/09/16/algorithms-for-sampling-without-replacement/
ReDim p(1 To n)
ReDim x_idx(i)
For i = 1 To n
If x_prob(i) > 0 Then
tmp_x = Rnd()
If tmp_x < 0.000000001 Then
p(i) = Exp(70)
Else
p(i) = -Log(tmp_x) / x_prob(i)
End If
Else
p(i) = Exp(70)
End If
x_idx(i) = i
Next i
Call Sort_Quick_A(p, 1, n, x_idx, 1)
For i = 1 To n_required
x_sample(i) = x(x_idx(i))
Next i
End If
Sample = x_sample
End Function
'A Random integer between lower to upper, including end points
Function Random_Integer(lower As Long, upper As Long) As Long
Random_Integer = Int(Rnd() * (upper - lower + 1)) + lower
End Function
'Pick a random integer between 1 to N with given probablity distribution
'Input: Prob(), real vector of size (1:N) holding the probability of each integer
' isCumulative, set to TRUE if Prob() is already giving the cumulative prob.
Function Random_Integer_Prob(Prob() As Double, Optional isCumulative As Boolean = False) As Long
Dim i As Long, n As Long
Dim tmp_x As Double
Dim prob_C() As Double
n = UBound(Prob)
If isCumulative = False Then
ReDim prob_C(1 To n)
prob_C(1) = Prob(1)
For i = 2 To n
prob_C(i) = prob_C(i - 1) + Prob(i)
Next i
Else
prob_C = Prob
End If
tmp_x = Rnd()
If tmp_x <= prob_C(1) Then
Random_Integer_Prob = 1
Else
Random_Integer_Prob = Binary_Search_Db(prob_C, tmp_x) + 1
If Random_Integer_Prob > n Then Random_Integer_Prob = n
' For i = 2 To n
' If prob_C(i - 1) < tmp_x And tmp_x <= prob_C(i) Then
' Random_Integer_Prob = i
' Exit For
' End If
' Next i
End If
Erase prob_C
End Function
'Randomly shuffle elements of x()
Sub Shuffle(x As Variant)
Dim i As Long, j As Long, n As Long
Dim k As Long
Dim vtmp As Variant
n = UBound(x)
Randomize
For i = n To 2 Step -1
j = Int(Rnd() * i) + 1 'Random_Integer(1, i)
vtmp = x(j)
x(j) = x(i)
x(i) = vtmp
Next i
End Sub
'Radomly pick k-elements from vector x(1 to n) and output as y(1 to k)
Sub Random_Pick(x As Variant, k As Long, y As Variant)
Dim i As Long, j As Long, n As Long
n = UBound(x)
ReDim y(1 To k)
For i = 1 To k
y(i) = x(i)
Next i
Randomize
For i = k + 1 To n
j = Random_Integer(1, i)
If j <= k Then y(j) = x(i)
Next i
End Sub
'Heap's algorithm
'Generate all possible permuations of N objects
'Input: n, number of elements
' A(1:n), vector of n elements
'Output: pList(1:n, 1:number of permutations), matrix where each row is a permuation of A
Sub Permute(n As Long, A As Variant, pList As Variant, Optional first_run As Long = 0)
Dim i As Long, j As Long, swap As Variant
DoEvents
If first_run = 0 Then
ReDim pList(1 To n, 0 To 0)
first_run = 1
End If
If n = 1 Then
If UBound(pList, 2) = 0 Then
j = 1
ReDim Preserve pList(1 To UBound(pList, 1), 1 To 1)
Else
j = UBound(pList, 2) + 1
ReDim Preserve pList(1 To UBound(pList, 1), 1 To j)
End If
For i = 1 To UBound(pList, 1)
pList(i, j) = A(i)
Next i
Exit Sub
Else
For i = 1 To n - 1
Call Permute(n - 1, A, pList, first_run)
If n Mod 2 = 0 Then
swap = A(i)
A(i) = A(n)
A(n) = swap
Else
swap = A(1)
A(1) = A(n)
A(n) = swap
End If
Next i
Call Permute(n - 1, A, pList, first_run)
End If
End Sub
Function nCk(n As Long, k As Long) As Double
Dim i As Long
nCk = 1
For i = 1 To k
nCk = (n + 1 - i) * nCk / i
Next i
End Function
'Return all combinations k elements from n, i.e. nCk
Function Combinations(n As Long, k As Long, Output() As Long) As Long
Dim i As Long