-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathpolynomial.go.tmpl
364 lines (301 loc) · 8.44 KB
/
polynomial.go.tmpl
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
import (
"errors"
"{{.FieldPackagePath}}"
"github.com/consensys/gnark-crypto/utils"
"strconv"
"strings"
"sync"
)
// Polynomial represented by coefficients in the field.
type Polynomial []{{.ElementType}}
// Degree returns the degree of the polynomial, which is the length of Data.
func (p *Polynomial) Degree() uint64 {
return uint64(len(*p) - 1)
}
// Eval evaluates p at v
// returns a {{.ElementType}}
func (p *Polynomial) Eval(v *{{.ElementType}}) {{.ElementType}} {
res := (*p)[len(*p) - 1]
for i := len(*p) - 2; i >= 0; i-- {
res.Mul(&res, v)
res.Add(&res, &(*p)[i])
}
return res
}
// Clone returns a copy of the polynomial
func (p *Polynomial) Clone() Polynomial {
_p := make(Polynomial, len(*p))
copy(_p, *p)
return _p
}
// Set to another polynomial
func (p *Polynomial) Set(p1 Polynomial) {
if len(*p) != len(p1) {
*p = p1.Clone()
return
}
for i := 0; i < len(p1); i++ {
(*p)[i].Set(&p1[i])
}
}
// AddConstantInPlace adds a constant to the polynomial, modifying p
func (p *Polynomial) AddConstantInPlace(c *{{.ElementType}}) {
for i := 0; i < len(*p); i++ {
(*p)[i].Add(&(*p)[i], c)
}
}
// SubConstantInPlace subs a constant to the polynomial, modifying p
func (p *Polynomial) SubConstantInPlace(c *{{.ElementType}}) {
for i := 0; i < len(*p); i++ {
(*p)[i].Sub(&(*p)[i], c)
}
}
// ScaleInPlace multiplies p by v, modifying p
func (p *Polynomial) ScaleInPlace(c *{{.ElementType}}) {
for i := 0; i < len(*p); i++ {
(*p)[i].Mul(&(*p)[i], c)
}
}
// Scale multiplies p0 by v, storing the result in p
func (p *Polynomial) Scale(c *{{.ElementType}}, p0 Polynomial) {
if len(*p) != len(p0) {
*p = make(Polynomial, len(p0))
}
for i := 0; i < len(p0); i++ {
(*p)[i].Mul(c, &p0[i])
}
}
// Add adds p1 to p2
// This function allocates a new slice unless p == p1 or p == p2
func (p *Polynomial) Add(p1, p2 Polynomial) *Polynomial {
bigger := p1
smaller := p2
if len(bigger) < len(smaller) {
bigger, smaller = smaller, bigger
}
if len(*p) == len(bigger) && (&(*p)[0] == &bigger[0]) {
for i:=0; i < len(smaller); i++ {
(*p)[i].Add(&(*p)[i], &smaller[i])
}
return p
}
if len(*p) == len(smaller) && (&(*p)[0] == &smaller[0]) {
for i:=0; i < len(smaller); i++ {
(*p)[i].Add(&(*p)[i], &bigger[i])
}
*p = append(*p, bigger[len(smaller):]...)
return p
}
res := make(Polynomial, len(bigger))
copy(res, bigger)
for i:=0; i < len(smaller); i++ {
res[i].Add(&res[i], &smaller[i])
}
*p = res
return p
}
// Sub subtracts p2 from p1
// TODO make interface more consistent with Add
func (p *Polynomial) Sub(p1, p2 Polynomial) *Polynomial {
if len(p1) != len(p2) || len(p2) != len(*p) {
return nil
}
for i := 0; i < len(*p); i++ {
(*p)[i].Sub(&p1[i], &p2[i])
}
return p
}
// Equal checks equality between two polynomials
func (p *Polynomial) Equal(p1 Polynomial) bool {
if (*p == nil) != (p1 == nil) {
return false
}
if len(*p) != len(p1) {
return false
}
for i := range p1 {
if !(*p)[i].Equal(&p1[i]) {
return false
}
}
return true
}
func (p Polynomial) SetZero() {
for i := 0; i < len(p); i++ {
p[i].SetZero()
}
}
func (p Polynomial) Text(base int) string {
var builder strings.Builder
first := true
for d := len(p) - 1; d >= 0; d-- {
if p[d].IsZero() {
continue
}
pD := p[d]
pDText := pD.Text(base)
initialLen := builder.Len()
if pDText[0] == '-' {
pDText = pDText[1:]
if first {
builder.WriteString("-")
} else {
builder.WriteString(" - ")
}
} else if !first {
builder.WriteString(" + ")
}
first = false
if !pD.IsOne() || d == 0 {
builder.WriteString(pDText)
}
if builder.Len()-initialLen > 10 {
builder.WriteString("×")
}
if d != 0 {
builder.WriteString("X")
}
if d > 1 {
builder.WriteString(
utils.ToSuperscript(strconv.Itoa(d)),
)
}
}
if first {
return "0"
}
return builder.String()
}
// InterpolateOnRange maps vector v to polynomial f
// such that f(i) = v[i] for 0 ≤ i < len(v).
// len(f) = len(v) and deg(f) ≤ len(v) - 1
func InterpolateOnRange(v []{{.ElementType}}) Polynomial {
nEvals := uint8(len(v))
if int(nEvals) != len(v) {
panic("interpolation method too inefficient for nEvals > 255")
}
lagrange := getLagrangeBasis(nEvals)
var res Polynomial
res.Scale(&v[0], lagrange[0])
temp := make(Polynomial, nEvals)
for i := uint8(1); i < nEvals; i++ {
temp.Scale(&v[i], lagrange[i])
res.Add(res, temp)
}
return res
}
// lagrange bases used by InterpolateOnRange
var lagrangeBasis sync.Map
func getLagrangeBasis(domainSize uint8) []Polynomial {
if res, ok := lagrangeBasis.Load(domainSize); ok {
return res.([]Polynomial)
}
// not found. compute
var res []Polynomial
if domainSize >= 2 {
res = computeLagrangeBasis(domainSize)
} else if domainSize == 1 {
res = []Polynomial{make(Polynomial, 1)}
res[0][0].SetOne()
}
lagrangeBasis.Store(domainSize, res)
return res
}
// computeLagrangeBasis precomputes in explicit coefficient form for each 0 ≤ l < domainSize the polynomial
// pₗ := X (X-1) ... (X-l-1) (X-l+1) ... (X - domainSize + 1) / ( l (l-1) ... 2 (-1) ... (l - domainSize +1) )
// Note that pₗ(l) = 1 and pₗ(n) = 0 if 0 ≤ l < domainSize, n ≠ l
func computeLagrangeBasis(domainSize uint8) []Polynomial {
constTerms := make([]{{.ElementType}}, domainSize)
for i := uint8(0); i < domainSize; i++ {
constTerms[i].SetInt64(-int64(i))
}
res := make([]Polynomial, domainSize)
multScratch := make(Polynomial, domainSize-1)
// compute pₗ
for l := uint8(0); l < domainSize; l++ {
// TODO @Tabaie Optimize this with some trees? O(log(domainSize)) polynomial mults instead of O(domainSize)? Then again it would be fewer big poly mults vs many small poly mults
d := uint8(0) //d is the current degree of res
for i := uint8(0); i < domainSize; i++ {
if i == l {
continue
}
if d == 0 {
res[l] = make(Polynomial, domainSize)
res[l][domainSize-2] = constTerms[i]
res[l][domainSize-1].SetOne()
} else {
current := res[l][domainSize-d-2:]
timesConst := multScratch[domainSize-d-2:]
timesConst.Scale(&constTerms[i], current[1:]) //TODO: Directly double and add since constTerms are tiny? (even less than 4 bits)
nonLeading := current[0 : d+1]
nonLeading.Add(nonLeading, timesConst)
}
d++
}
}
// We have pₗ(i≠l)=0. Now scale so that pₗ(l)=1
// Replace the constTerms with norms
for l := uint8(0); l < domainSize; l++ {
constTerms[l].Neg(&constTerms[l])
constTerms[l] = res[l].Eval(&constTerms[l])
}
constTerms = {{.FieldPackageName}}.BatchInvert(constTerms)
for l := uint8(0); l < domainSize; l++ {
res[l].ScaleInPlace(&constTerms[l])
}
return res
}
// Interpolate fits a polynomial of degree len(X) - 1 = len(Y) - 1 to the points (X[i], Y[i])
// Returns the evaluation at r
//
// Note that this runs in O(len(X)²).
// When possible, it is better to exploit any structure in the domain
// (i.e. the values in X) to compute the polynomial in linear time.
func Interpolate(X, Y []{{.ElementType}}, r {{.ElementType}}) {{.ElementType}} {
if len(X) != len(Y) {
panic("X and Y must have the same length")
}
switch len(X) {
case 0:
return {{.ElementType}}{}
case 1:
return Y[0]
}
// weights[i] = 1 / [(X[i] - X[0]) * (X[i] - X[1]) * ... * (X[i] - X[i-1]) * (X[i] - X[i+1]) * ... * (X[i] - X[n-1])]
weights := make([]{{.ElementType}}, len(X))
for i := range weights {
weights[i].SetOne()
for j := range weights {
if i == j {
continue
}
var t {{.ElementType}}
t.Sub(&X[i], &X[j])
weights[i].Mul(&weights[i], &t)
}
}
weights = {{.FieldPackageName}}.BatchInvert(weights)
// prods[i] = (r-X[i+1]) * (r-X[i+2]) * ... (r-X[n-1])
prods := make([]{{.ElementType}}, len(X))
prods[len(X)-1].SetOne()
prods[len(X)-2].Sub(&r, &X[len(X)-1])
for i := len(X) - 3; i >= 0; i-- {
var t {{.ElementType}}
t.Sub(&r, &X[i+1])
prods[i].Mul(&prods[i+1], &t)
}
// at iteration i, prod = (r-X[0]) * (r-X[1]) * ... * (r-X[i-1])
prod := {{.FieldPackageName}}.One()
var res {{.ElementType}}
for i := range X {
var t {{.ElementType}}
t.Mul(&prod, &prods[i]) // t = (r-X[0]) * (r-X[1]) * ... * (r-X[i-1]) * (r-X[i+1]) * ... * (r-X[n-1])
t.Mul(&t, &weights[i]) // t = (r-X[0]) * (r-X[1]) * ... * (r-X[i-1]) * (r-X[i+1]) * ... * (r-X[n-1]) / [(X[i] - X[0]) * (X[i] - X[1]) * ... * (X[i] - X[i-1]) * (X[i] - X[i+1]) * ... * (X[i] - X[n-1])]
// t is now the evaluation of the i'th Lagrange basis at r
t.Mul(&t, &Y[i])
res.Add(&res, &t)
t.Sub(&r, &X[i])
prod.Mul(&prod, &t)
}
return res
}