forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inner.go
102 lines (97 loc) · 2.25 KB
/
inner.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
// Copyright ©2014 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat64
import (
"github.com/gonum/blas"
"github.com/gonum/internal/asm"
)
// Inner computes the generalized inner product
// x^T A y
// between vectors x and y with matrix A. This is only a true inner product if
// A is symmetric positive definite, though the operation works for any matrix A.
//
// Inner panics if x.Len != m or y.Len != n when A is an m x n matrix.
func Inner(x *Vector, A Matrix, y *Vector) float64 {
m, n := A.Dims()
if x.Len() != m {
panic(ErrShape)
}
if y.Len() != n {
panic(ErrShape)
}
if m == 0 || n == 0 {
return 0
}
var sum float64
switch b := A.(type) {
case RawSymmetricer:
bmat := b.RawSymmetric()
if bmat.Uplo != blas.Upper {
// Panic as a string not a mat64.Error.
panic(badSymTriangle)
}
for i := 0; i < x.Len(); i++ {
xi := x.at(i)
if xi != 0 {
if y.mat.Inc == 1 {
sum += xi * asm.DdotUnitary(
bmat.Data[i*bmat.Stride+i:i*bmat.Stride+n],
y.mat.Data[i:],
)
} else {
sum += xi * asm.DdotInc(
bmat.Data[i*bmat.Stride+i:i*bmat.Stride+n],
y.mat.Data[i*y.mat.Inc:], uintptr(n-i),
1, uintptr(y.mat.Inc),
0, 0,
)
}
}
yi := y.at(i)
if i != n-1 && yi != 0 {
if x.mat.Inc == 1 {
sum += yi * asm.DdotUnitary(
bmat.Data[i*bmat.Stride+i+1:i*bmat.Stride+n],
x.mat.Data[i+1:],
)
} else {
sum += yi * asm.DdotInc(
bmat.Data[i*bmat.Stride+i+1:i*bmat.Stride+n],
x.mat.Data[(i+1)*x.mat.Inc:], uintptr(n-i-1),
1, uintptr(x.mat.Inc),
0, 0,
)
}
}
}
case RawMatrixer:
bmat := b.RawMatrix()
for i := 0; i < x.Len(); i++ {
xi := x.at(i)
if xi != 0 {
if y.mat.Inc == 1 {
sum += xi * asm.DdotUnitary(
bmat.Data[i*bmat.Stride:i*bmat.Stride+n],
y.mat.Data,
)
} else {
sum += xi * asm.DdotInc(
bmat.Data[i*bmat.Stride:i*bmat.Stride+n],
y.mat.Data, uintptr(n),
1, uintptr(y.mat.Inc),
0, 0,
)
}
}
}
default:
for i := 0; i < x.Len(); i++ {
xi := x.at(i)
for j := 0; j < y.Len(); j++ {
sum += xi * A.At(i, j) * y.at(j)
}
}
}
return sum
}