-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
1701 lines (1471 loc) · 40.6 KB
/
main.go
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 main
import (
"fmt"
tf "github.com/galeone/tensorflow/tensorflow/go"
tg "github.com/galeone/tfgo"
"github.com/sbinet/npyio"
"gocv.io/x/gocv"
"gonum.org/v1/gonum/blas/blas64"
"gonum.org/v1/gonum/lapack"
"gonum.org/v1/gonum/lapack/lapack64"
"image"
"math"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
)
func sliceIndex(number int) []int {
indexes := make([]int, number)
for i := 0; i < number; i++ {
indexes[i] = i
}
return indexes
}
func removeIndex(s []int, idx []int) []int {
sort.Ints(idx)
offset := 0
for _, i := range idx {
i -= offset
s = append(s[:i], s[i+1:]...)
offset++
}
return s
}
func nms(boxes [][]float32, overlapThreshold float64, mode string) []int {
if len(boxes) == 0 {
return []int{}
}
// initialize the list of picked indexes
pick := []int{}
// grab the coordinates of the bounding boxes
var x1, y1, x2, y2, score []float32
for _, box := range boxes {
x1 = append(x1, box[0])
y1 = append(y1, box[1])
x2 = append(x2, box[2])
y2 = append(y2, box[3])
score = append(score, box[4])
}
area := make([]float32, len(boxes))
for i := range boxes {
area[i] = (x2[i] - x1[i] + 1) * (y2[i] - y1[i] + 1)
}
idxs := make([]int, len(score))
for i := 0; i < len(score); i++ {
idxs[i] = i
}
sort.Slice(idxs, func(i, j int) bool { return score[idxs[i]] < score[idxs[j]] })
// keep looping while some indexes still remain in the indexes list
for len(idxs) > 0 {
// grab the last index in the indexes list and add the index value to the list of picked indexes
last := len(idxs) - 1
i := idxs[last]
pick = append(pick, i)
xx1 := make([]float64, last)
yy1 := make([]float64, last)
xx2 := make([]float64, last)
yy2 := make([]float64, last)
for j := 0; j < last; j++ {
xx1[j] = math.Max(float64(x1[i]), float64(x1[idxs[j]]))
yy1[j] = math.Max(float64(y1[i]), float64(y1[idxs[j]]))
xx2[j] = math.Min(float64(x2[i]), float64(x2[idxs[j]]))
yy2[j] = math.Min(float64(y2[i]), float64(y2[idxs[j]]))
}
// compute the width and height of the bounding box
w := make([]float64, last)
h := make([]float64, last)
for j := 0; j < last; j++ {
w[j] = math.Max(0, xx2[j]-xx1[j]+1)
h[j] = math.Max(0, yy2[j]-yy1[j]+1)
}
inter := make([]float64, last)
overlap := make([]float64, last)
for j := 0; j < last; j++ {
inter[j] = w[j] * h[j]
if mode == "Min" {
overlap[j] = inter[j] / math.Min(float64(area[i]), float64(area[idxs[j]]))
} else {
overlap[j] = inter[j] / (float64(area[i]) + float64(area[idxs[j]]) - inter[j])
}
}
// delete all indexes from the index list that have
toDelete := []int{}
for j := 0; j < last; j++ {
if overlap[j] > overlapThreshold {
toDelete = append(toDelete, j)
}
}
toDelete = append(toDelete, last)
deleteIdxs := make([]int, len(toDelete))
for j := 0; j < len(toDelete); j++ {
deleteIdxs[j] = idxs[toDelete[j]]
}
idxs = removeIndex(idxs, toDelete)
}
return pick
}
func extractData(npArray [][][]float32, index int) [][]float32 {
// Assuming the dimensions of your slice are as follows:
var dim1, dim2 = len(npArray), len(npArray[0])
// Creating a 2D slice to store the extracted values
var extractedData = make([][]float32, dim1)
for i := 0; i < dim1; i++ {
extractedData[i] = make([]float32, dim2)
}
// Extracting the desired values
for i := 0; i < dim1; i++ {
for j := 0; j < dim2; j++ {
extractedData[i][j] = npArray[i][j][index]
}
}
return extractedData
}
func fix(val float32) float32 {
if val < 0 {
return float32(math.Ceil(float64(val)))
} else {
return float32(math.Floor(float64(val)))
}
}
func computeQ1(bb [][]float32, stride, scale float32) [][]float32 {
q1 := make([][]float32, len(bb))
for i, pair := range bb {
q1[i] = make([]float32, len(pair))
for j, val := range pair {
q1[i][j] = fix((stride*val + 1) / scale)
}
}
return q1
}
func computeQ2(bb [][]float32, stride, scale, cellsize float32) [][]float32 {
q2 := make([][]float32, len(bb))
for i, pair := range bb {
q2[i] = make([]float32, len(pair))
for j, val := range pair {
q2[i][j] = fix((stride*val + cellsize) / scale)
}
}
return q2
}
func generateBBox(imap [][]float32, reg [][][]float32, scale float64, t float32) [][]float32 {
stride := 2
cellsize := 12
imap = transpose2D(imap)
dx1 := transpose2D(extractData(reg, 0))
dy1 := transpose2D(extractData(reg, 1))
dx2 := transpose2D(extractData(reg, 2))
dy2 := transpose2D(extractData(reg, 3))
var ys []int
var xs []int
for i := range imap {
for j := range imap[i] {
if imap[i][j] >= t {
ys = append(ys, i)
xs = append(xs, j)
}
}
}
if len(ys) == 1 {
dx1 = flip2D(dx1)
dy1 = flip2D(dy1)
dx2 = flip2D(dx2)
dy2 = flip2D(dy2)
}
scores := make([]float32, len(ys))
for i, y := range ys {
scores[i] = imap[y][xs[i]]
}
regResult := make([][]float32, len(ys))
for i := range regResult {
regResult[i] = []float32{
dx1[ys[i]][xs[i]],
dy1[ys[i]][xs[i]],
dx2[ys[i]][xs[i]],
dy2[ys[i]][xs[i]],
}
}
if len(regResult) == 0 {
regResult = make([][]float32, 0)
}
bb := make([][]float32, len(xs))
for i := 0; i < len(xs); i++ {
bb[i] = []float32{float32(ys[i]), float32(xs[i])}
}
q1 := computeQ1(bb, float32(stride), float32(scale))
q2 := computeQ2(bb, float32(stride), float32(scale), float32(cellsize))
boundingbox := make([][]float32, len(ys))
for i := range boundingbox {
boundingbox[i] = append(append(q1[i], q2[i]...), append([]float32{scores[i]}, regResult[i]...)...)
}
return boundingbox
}
func transpose2D(matrix [][]float32) [][]float32 {
rows := len(matrix)
if rows == 0 {
return matrix
}
cols := len(matrix[0])
result := make([][]float32, cols)
for i := range result {
result[i] = make([]float32, rows)
}
for i, row := range matrix {
for j, val := range row {
result[j][i] = val
}
}
return result
}
func transpose3D(slice [][][]float32) [][][]float32 {
var (
x = len(slice)
y = len(slice[0])
z = len(slice[0][0])
)
newSlice := make([][][]float32, z)
for i := range newSlice {
newSlice[i] = make([][]float32, x)
for j := range newSlice[i] {
newSlice[i][j] = make([]float32, y)
}
}
for i, s := range slice {
for j, ss := range s {
for k, v := range ss {
newSlice[k][i][j] = v
}
}
}
return newSlice
}
func flip2D(matrix [][]float32) [][]float32 {
for i := 0; i < len(matrix)/2; i++ {
matrix[i], matrix[len(matrix)-1-i] = matrix[len(matrix)-1-i], matrix[i]
}
return matrix
}
func flatten4DTo2D(data [][][][]float32) [][]float32 {
var dim2, dim3 = len(data[0]), len(data[0][0])
var extractedData = make([][]float32, dim2)
for i := 0; i < dim2; i++ {
extractedData[i] = make([]float32, dim3)
}
for i := 0; i < dim2; i++ {
for j := 0; j < dim3; j++ {
extractedData[i][j] = data[0][i][j][1]
}
}
return extractedData
}
func transpose(x [][][][]float32, order []int) [][][][]float32 {
if len(order) != 4 {
panic("order must have a length of 4")
}
dims := []int{len(x), len(x[0]), len(x[0][0]), len(x[0][0][0])}
newDims := []int{dims[order[0]], dims[order[1]], dims[order[2]], dims[order[3]]}
// Create output slice with transposed dimensions
out := make([][][][]float32, newDims[0])
for i := range out {
out[i] = make([][][]float32, newDims[1])
for j := range out[i] {
out[i][j] = make([][]float32, newDims[2])
for k := range out[i][j] {
out[i][j][k] = make([]float32, newDims[3])
}
}
}
// Transpose elements
for i := 0; i < dims[0]; i++ {
for j := 0; j < dims[1]; j++ {
for k := 0; k < dims[2]; k++ {
for l := 0; l < dims[3]; l++ {
xIndex := []int{i, j, k, l}
outIndex := []int{xIndex[order[0]], xIndex[order[1]], xIndex[order[2]], xIndex[order[3]]}
out[outIndex[0]][outIndex[1]][outIndex[2]][outIndex[3]] = x[xIndex[0]][xIndex[1]][xIndex[2]][xIndex[3]]
}
}
}
}
return out
}
func initializeExtremeValue(operation string) float32 {
switch operation {
case "min":
return float32(math.Inf(1)) // Initialize with positive infinity for min operation
case "max":
return float32(math.Inf(-1)) // Initialize with negative infinity for max operation
default:
return 0
}
}
func isBetter(candidate float32, currentExtreme float32, operation string) bool {
switch operation {
case "min":
return candidate < currentExtreme
case "max":
return candidate > currentExtreme
default:
return false
}
}
func flattenSlice(slice interface{}) ([]interface{}, error) {
value := reflect.ValueOf(slice)
kind := value.Kind()
// Ensure the input is a slice
if kind != reflect.Slice {
return nil, fmt.Errorf("input is not a slice")
}
// Flatten the slice recursively
var flattened []interface{}
for i := 0; i < value.Len(); i++ {
element := value.Index(i)
elementKind := element.Kind()
if elementKind == reflect.Slice {
subSlice, err := flattenSlice(element.Interface())
if err != nil {
return nil, err
}
flattened = append(flattened, subSlice...)
} else {
flattened = append(flattened, element.Interface())
}
}
return flattened, nil
}
func detectFirstStage(img gocv.Mat, net *tg.Model, scale float64, threshold float32) [][]float32 {
height, width := img.Size()[0], img.Size()[1]
ws := int(math.Ceil(float64(width) * scale))
hs := int(math.Ceil(float64(height) * scale))
imData := gocv.NewMat()
defer imData.Close()
gocv.Resize(img, &imData, image.Point{X: ws, Y: hs}, 0, 0, gocv.InterpolationLinear)
inputBuf := adjustInput(imData)
inputBufTensor, _ := tf.NewTensor(inputBuf)
newShape := []int64{1, int64(ws), int64(hs), 3}
inputBufTensor.Reshape(newShape)
netOutput := net.Exec([]tf.Output{
net.Op("PartitionedCall", 0),
net.Op("PartitionedCall", 1),
}, map[tf.Output]*tf.Tensor{
net.Op("serving_default_input_1", 0): inputBufTensor,
})
reg, ok := netOutput[0].Value().([][][][]float32)
if !ok {
fmt.Println("Failed to convert reg to [][][][]float64")
}
heatmap, ok := netOutput[1].Value().([][][][]float32)
if !ok {
fmt.Println("Failed to convert heatmap to [][]float64")
}
order := []int{0, 2, 1, 3}
reg = transpose(reg, order)
heatmap2d := flatten4DTo2D(transpose(heatmap, order))
boxes := generateBBox(heatmap2d, reg[0], scale, threshold)
if len(boxes) == 0 {
return nil
}
// nms
pick := nms(boxes, 0.5, "Union")
var pickedBoxes [][]float32
for _, index := range pick {
pickedBoxes = append(pickedBoxes, boxes[index])
}
return pickedBoxes
}
func convertToSquare(bbox [][]float32) [][]float32 {
squareBbox := make([][]float32, len(bbox))
for i := 0; i < len(bbox); i++ {
squareBbox[i] = make([]float32, len(bbox[i]))
copy(squareBbox[i], bbox[i])
h := bbox[i][3] - bbox[i][1] + 1
w := bbox[i][2] - bbox[i][0] + 1
maxSide := float32(math.Max(float64(h), float64(w)))
squareBbox[i][0] = bbox[i][0] + w*0.5 - maxSide*0.5
squareBbox[i][1] = bbox[i][1] + h*0.5 - maxSide*0.5
squareBbox[i][2] = squareBbox[i][0] + maxSide - 1
squareBbox[i][3] = squareBbox[i][1] + maxSide - 1
}
return squareBbox
}
func pad(bboxes [][]float32, w float32, h float32) ([]float32, []float32, []float32, []float32, []float32, []float32, []float32, []float32, []float32, []float32) {
numBox := len(bboxes)
tmpw := make([]float32, numBox)
tmph := make([]float32, numBox)
for i := range bboxes {
tmpw[i] = bboxes[i][2] - bboxes[i][0] + 1
tmph[i] = bboxes[i][3] - bboxes[i][1] + 1
}
dx := make([]float32, numBox)
dy := make([]float32, numBox)
edx := make([]float32, numBox)
edy := make([]float32, numBox)
x := make([]float32, numBox)
y := make([]float32, numBox)
ex := make([]float32, numBox)
ey := make([]float32, numBox)
for i := range bboxes {
dx[i], dy[i] = 0, 0
edx[i], edy[i] = tmpw[i]-1, tmph[i]-1
x[i], y[i], ex[i], ey[i] = bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][3]
if ex[i] > w-1 {
edx[i] = tmpw[i] + w - 2 - ex[i]
ex[i] = w - 1
}
if ey[i] > h-1 {
edy[i] = tmph[i] + h - 2 - ey[i]
ey[i] = h - 1
}
if x[i] < 0 {
dx[i] = 0 - x[i]
x[i] = 0
}
if y[i] < 0 {
dy[i] = 0 - y[i]
y[i] = 0
}
}
return dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph
}
func adjustInput(inData gocv.Mat) [][][][]float32 {
width := inData.Cols()
height := inData.Rows()
channels := inData.Channels()
outData := make([][][][]float32, 1)
outData[0] = make([][][]float32, width)
// Scale the data and expand dimensions
for w := 0; w < width; w++ {
outData[0][w] = make([][]float32, height)
for h := 0; h < height; h++ {
outData[0][w][h] = make([]float32, channels)
val := inData.GetVecbAt(h, w)
for c := 0; c < channels; c++ {
outData[0][w][h][c] = (float32(val[c]) - 127.5) * 0.0078125
}
}
}
return outData
}
func matToSlice(inData gocv.Mat) [][][]float32 {
width := inData.Rows()
height := inData.Cols()
channels := inData.Channels()
outData := make([][][]float32, width)
for w := 0; w < width; w++ {
outData[w] = make([][]float32, height)
for h := 0; h < height; h++ {
outData[w][h] = make([]float32, channels)
val := inData.GetVecbAt(w, h)
for c := 0; c < channels; c++ {
outData[w][h][c] = float32(val[c]) / 255
}
}
}
return outData
}
func CalibrateBox(bbox [][]float32, reg [][]float32) [][]float32 {
n := len(bbox)
w := make([]float32, n)
h := make([]float32, n)
for i := 0; i < n; i++ {
w[i] = bbox[i][2] - bbox[i][0] + 1
h[i] = bbox[i][3] - bbox[i][1] + 1
}
regM := make([][]float32, n)
for i := range regM {
regM[i] = make([]float32, 4)
regM[i][0] = w[i]
regM[i][1] = h[i]
regM[i][2] = w[i]
regM[i][3] = h[i]
}
aug := make([][]float32, n)
for i := range aug {
aug[i] = make([]float32, 4)
aug[i][0] = regM[i][0] * reg[i][0]
aug[i][1] = regM[i][1] * reg[i][1]
aug[i][2] = regM[i][2] * reg[i][2]
aug[i][3] = regM[i][3] * reg[i][3]
}
for i := 0; i < n; i++ {
bbox[i][0] += aug[i][0]
bbox[i][1] += aug[i][1]
bbox[i][2] += aug[i][2]
bbox[i][3] += aug[i][3]
}
return bbox
}
func preprocessMat(img gocv.Mat, bbox []float32, landmark [][]float32) gocv.Mat {
var M [][]float64 = nil
var det, bb []float32 = nil, nil
if landmark != nil {
src := [][]float64{
{30.2946, 51.6963},
{65.5318, 51.5014},
{48.0252, 71.7366},
{33.5493, 92.3655},
{62.7299, 92.2041},
}
for i := 0; i < len(src); i++ {
src[i][0] += 8.0
}
dst := float32ToFloat64(landmark)
M = umeyama(dst, src, true)
M = M[:len(M)-1]
fmt.Printf("Matrix M: %v\n", M)
}
if M == nil {
if bbox == nil {
det = make([]float32, 4)
det[0] = float32(img.Cols()) * 0.0625
det[1] = float32(img.Rows()) * 0.0625
det[2] = float32(img.Cols()) - det[0]
det[3] = float32(img.Rows()) - det[1]
} else {
det = bbox
}
bb = make([]float32, 4)
bb[0] = float32(math.Max(float64(det[0])-float64(44.0/2), 0))
bb[1] = float32(math.Max(float64(det[1])-float64(44.0/2), 0))
bb[2] = float32(math.Min(float64(det[2])+float64(44.0/2), float64(img.Cols())))
bb[3] = float32(math.Min(float64(det[3])+float64(44.0/2), float64(img.Rows())))
ret := img.Region(image.Rect(int(bb[0]), int(bb[1]), int(bb[2]), int(bb[3])))
gocv.Resize(ret, &ret, image.Point{X: 112, Y: 112}, 0, 0, gocv.InterpolationLinear)
return ret
} else {
warped := gocv.NewMat()
mMat := float64ToMat(M)
val := img.GetVecbAt(0, 0)
fmt.Printf("img[0,0]: %v\n", val)
val = img.GetVecbAt(24, 10)
fmt.Printf("img[24,10]: %v\n", val)
gocv.WarpAffine(img, &warped, mMat, image.Point{X: 112, Y: 112})
val = warped.GetVecbAt(0, 0)
fmt.Printf("warped[0,0]: %v\n", val)
val = warped.GetVecbAt(0, 1)
fmt.Printf("warped[0,1]: %v\n", val)
return warped
}
}
func umeyama(src, dst [][]float64, estimateScale bool) [][]float64 {
num := len(src)
dim := len(src[0])
// Compute mean of src and dst.
srcMean := make([]float64, dim)
dstMean := make([]float64, dim)
for i := 0; i < num; i++ {
for j := 0; j < dim; j++ {
srcMean[j] += src[i][j]
dstMean[j] += dst[i][j]
}
}
for j := 0; j < dim; j++ {
srcMean[j] /= float64(num)
dstMean[j] /= float64(num)
}
// Subtract mean from src and dst.
srcDemean := make([][]float64, num)
dstDemean := make([][]float64, num)
for i := range srcDemean {
srcDemean[i] = make([]float64, dim)
dstDemean[i] = make([]float64, dim)
}
for i := 0; i < num; i++ {
for j := 0; j < dim; j++ {
srcDemean[i][j] = src[i][j] - srcMean[j]
dstDemean[i][j] = dst[i][j] - dstMean[j]
}
}
fmt.Printf("src: %v\n", src)
fmt.Printf("srcMean: %v\n", srcMean)
fmt.Printf("srcDemean: %v\n", srcDemean)
// Eq. (38).
A := make([][]float64, dim)
for i := range A {
A[i] = make([]float64, dim)
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
for k := 0; k < num; k++ {
A[i][j] += dstDemean[k][i] * srcDemean[k][j]
}
A[i][j] /= float64(num)
}
}
// Eq. (39).
d := make([]float64, dim)
for i := range d {
d[i] = 1.0
}
if determinant(A) < 0 {
d[dim-1] = -1
}
T := make([][]float64, dim+1)
for i := range T {
T[i] = make([]float64, dim+1)
for j := range T[i] {
if i == j {
T[i][j] = 1.0
}
}
}
V, S, U := svd(A)
fmt.Printf("Matrix A: %v\n", A)
fmt.Printf("Matrix U: %v\n", U)
fmt.Printf("Matrix V: %v\n", V)
fmt.Printf("Vector d: %v\n", d)
fmt.Printf("Matrix S: %v\n", S)
// Eq. (40) and (43).
rank := matrixRank(A)
if rank == 0 {
for i := range T {
for j := range T[i] {
T[i][j] = math.NaN()
}
}
return T
} else if rank == dim-1 {
if determinant(U)*determinant(V) > 0 {
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
T[i][j] = 0
for k := 0; k < dim; k++ {
T[i][j] += U[i][k] * V[k][j]
}
}
}
} else {
s := d[dim-1]
d[dim-1] = -1
Temp := make([][]float64, dim)
for i := range Temp {
Temp[i] = make([]float64, dim)
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
if i == j {
Temp[i][j] = d[i]
}
}
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
T[i][j] = 0
for k := 0; k < dim; k++ {
T[i][j] += U[i][k] * Temp[k][j]
}
}
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
Temp[i][j] = 0
for k := 0; k < dim; k++ {
Temp[i][j] += T[i][k] * V[k][j]
}
}
}
T = Temp
d[dim-1] = s
}
} else {
Temp := make([][]float64, dim)
for i := range Temp {
Temp[i] = make([]float64, dim)
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
if i == j {
Temp[i][j] = d[i]
}
}
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
T[i][j] = 0
for k := 0; k < dim; k++ {
T[i][j] += U[i][k] * Temp[k][j]
}
}
}
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
Temp[i][j] = 0
for k := 0; k < dim; k++ {
Temp[i][j] += T[i][k] * V[k][j]
}
}
}
T = Temp
}
fmt.Printf("Matrix T 0: %v\n", T)
var scale float64
if estimateScale {
// Eq. (41) and (42).
var srcVar float64
for i := 0; i < dim; i++ {
var temp float64
for j := 0; j < num; j++ {
temp += (src[j][i] - srcMean[i]) * (src[j][i] - srcMean[i])
}
srcVar += temp / float64(num)
}
var sumSD float64
for i := 0; i < dim; i++ {
sumSD += S[0][i] * d[i]
}
scale = 1.0 / srcVar * sumSD
fmt.Printf("srcVar: %v\n", srcVar)
fmt.Printf("sumSD: %v\n", sumSD)
} else {
scale = 1.0
}
fmt.Printf("Scale: %v\n", scale)
for i := 0; i < dim; i++ {
var temp float64
for j := 0; j < dim; j++ {
temp += T[i][j] * srcMean[j]
}
T[i][dim] = dstMean[i] - scale*temp
}
fmt.Printf("Matrix T 1: %v\n", T)
for i := 0; i < dim; i++ {
for j := 0; j < dim; j++ {
T[i][j] *= scale
}
}
fmt.Printf("Matrix T 2: %v\n", T)
return T
}
func matrixRank(A [][]float64) int {
U, _, _ := svd(A)
rank := 0
for i := range U {
if U[i][i] > 1e-10 {
rank++
}
}
return rank
}
func determinant(A [][]float64) float64 {
n := len(A)
if n == 2 {
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
}
det := 0.0
for i := 0; i < n; i++ {
subMatrix := make([][]float64, n-1)
for j := range subMatrix {
subMatrix[j] = make([]float64, n-1)
copy(subMatrix[j], A[j+1])
subMatrix[j] = append(subMatrix[j][:i], subMatrix[j][i+1:]...)
}
det += math.Pow(-1, float64(i)) * A[0][i] * determinant(subMatrix)
}
return det
}
func svd(A [][]float64) (U, S, Vt [][]float64) {
m := len(A)
n := len(A[0])
// Convert A to column-major order.
data := make([]float64, m*n)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
data[i*m+j] = A[j][i]
}
}
U = make([][]float64, m)
for i := range U {
U[i] = make([]float64, m)
}
S = make([][]float64, m)
for i := range S {
S[i] = make([]float64, n)
}
Vt = make([][]float64, n)
for i := range Vt {
Vt[i] = make([]float64, n)
}
// Compute SVD using gonum/lapack.
blasData := blas64.General{
Rows: m,
Cols: n,
Stride: n,
Data: data,
}
blasU := blas64.General{
Rows: m,
Cols: m,
Stride: m,
Data: make([]float64, m*m),
}
blasVt := blas64.General{
Rows: n,
Cols: n,
Stride: n,
Data: make([]float64, n*n),
}
work := make([]float64, 1)
lwork := -1
// Compute work size.
ok := lapack64.Gesvd(lapack.SVDAll, lapack.SVDAll, blasData, blasU, blasVt, S[0], work, lwork)
if !ok {
panic("SVD failed")
}
// Allocate work with the correct size.
lwork = int(work[0])
work = make([]float64, lwork)
// Compute SVD.
ok = lapack64.Gesvd(lapack.SVDAll, lapack.SVDAll, blasData, blasU, blasVt, S[0], work, lwork)
if !ok {
panic("SVD failed")
}
// Convert U, S, Vt back to row-major order.
for i := 0; i < m; i++ {
for j := 0; j < m; j++ {
U[i][j] = blasU.Data[j*m+i]
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
S[i][j] = S[i][j]
}
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
Vt[i][j] = blasVt.Data[j*n+i]
}
}
return U, S, Vt
}
func eigen(A [][]float64) (values, vectors [][]float64) {
// Perform eigenvalue decomposition using QR algorithm with shifts.
n := len(A)
values = make([][]float64, n)
vectors = make([][]float64, n)
for i := range values {
values[i] = make([]float64, 1)
vectors[i] = make([]float64, n)
}
B := make([][]float64, n)
for i := range B {
B[i] = make([]float64, n)
copy(B[i], A[i])
}
for iter := 0; iter < 50; iter++ {
// Check if B is diagonal.
sumOffDiagonal := 0.0
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i != j {
sumOffDiagonal += B[i][j] * B[i][j]
}
}
}
if sumOffDiagonal <= 1e-12 {
break
}
// QR decomposition of B.
Q, R := qr(B)
// B = R * Q
B = matmul(R, Q)
}
for i := 0; i < n; i++ {
values[i][0] = B[i][i]
for j := 0; j < n; j++ {
vectors[i][j] = B[i][j]
}
}