-
Notifications
You must be signed in to change notification settings - Fork 79
/
utils.rs
340 lines (270 loc) · 8.14 KB
/
utils.rs
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
use std::iter::{zip, Sum};
use std::ops::{Add, Deref, Mul, Neg, Sub};
use num_traits::{One, Zero};
use crate::core::fields::qm31::SecureField;
use crate::core::fields::{ExtensionOf, Field};
/// Univariate polynomial stored as coefficients in the monomial basis.
#[derive(Debug, Clone)]
pub struct UnivariatePoly<F: Field>(Vec<F>);
impl<F: Field> UnivariatePoly<F> {
pub fn new(coeffs: Vec<F>) -> Self {
let mut polynomial = Self(coeffs);
polynomial.truncate_leading_zeros();
polynomial
}
pub fn eval_at_point(&self, x: F) -> F {
horner_eval(&self.0, x)
}
// <https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Polynomial_interpolation>
pub fn interpolate_lagrange(xs: &[F], ys: &[F]) -> Self {
assert_eq!(xs.len(), ys.len());
let mut coeffs = Self::zero();
for (i, (&xi, &yi)) in zip(xs, ys).enumerate() {
let mut prod = yi;
for (j, &xj) in xs.iter().enumerate() {
if i != j {
prod /= xi - xj;
}
}
let mut term = Self::new(vec![prod]);
for (j, &xj) in xs.iter().enumerate() {
if i != j {
term = term * (Self::x() - Self::new(vec![xj]));
}
}
coeffs = coeffs + term;
}
coeffs.truncate_leading_zeros();
coeffs
}
pub fn degree(&self) -> usize {
let mut coeffs = self.0.iter().rev();
let _ = (&mut coeffs).take_while(|v| v.is_zero());
coeffs.len().saturating_sub(1)
}
fn x() -> Self {
Self(vec![F::zero(), F::one()])
}
fn truncate_leading_zeros(&mut self) {
while self.0.last() == Some(&F::zero()) {
self.0.pop();
}
}
}
impl<F: Field> From<F> for UnivariatePoly<F> {
fn from(value: F) -> Self {
Self::new(vec![value])
}
}
impl<F: Field> Mul<F> for UnivariatePoly<F> {
type Output = Self;
fn mul(mut self, rhs: F) -> Self {
self.0.iter_mut().for_each(|coeff| *coeff *= rhs);
self
}
}
impl<F: Field> Mul for UnivariatePoly<F> {
type Output = Self;
fn mul(mut self, mut rhs: Self) -> Self {
if self.is_zero() || rhs.is_zero() {
return Self::zero();
}
self.truncate_leading_zeros();
rhs.truncate_leading_zeros();
let mut res = vec![F::zero(); self.0.len() + rhs.0.len() - 1];
for (i, coeff_a) in self.0.into_iter().enumerate() {
for (j, &coeff_b) in rhs.0.iter().enumerate() {
res[i + j] += coeff_a * coeff_b;
}
}
Self::new(res)
}
}
impl<F: Field> Add for UnivariatePoly<F> {
type Output = Self;
fn add(self, rhs: Self) -> Self {
let n = self.0.len().max(rhs.0.len());
let mut res = Vec::new();
for i in 0..n {
res.push(match (self.0.get(i), rhs.0.get(i)) {
(Some(&a), Some(&b)) => a + b,
(Some(&a), None) | (None, Some(&a)) => a,
_ => unreachable!(),
})
}
Self(res)
}
}
impl<F: Field> Sub for UnivariatePoly<F> {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
self + (-rhs)
}
}
impl<F: Field> Neg for UnivariatePoly<F> {
type Output = Self;
fn neg(self) -> Self {
Self(self.0.into_iter().map(|v| -v).collect())
}
}
impl<F: Field> Zero for UnivariatePoly<F> {
fn zero() -> Self {
Self(vec![])
}
fn is_zero(&self) -> bool {
self.0.iter().all(F::is_zero)
}
}
impl<F: Field> Deref for UnivariatePoly<F> {
type Target = [F];
fn deref(&self) -> &[F] {
&self.0
}
}
/// Evaluates univariate polynomial using [Horner's method].
///
/// [Horner's method]: https://en.wikipedia.org/wiki/Horner%27s_method
pub fn horner_eval<F: Field>(coeffs: &[F], x: F) -> F {
coeffs
.iter()
.rfold(F::zero(), |acc, &coeff| acc * x + coeff)
}
/// Returns `v_0 + alpha * v_1 + ... + alpha^(n-1) * v_{n-1}`.
pub fn random_linear_combination(v: &[SecureField], alpha: SecureField) -> SecureField {
horner_eval(v, alpha)
}
/// Evaluates the lagrange kernel of the boolean hypercube.
///
/// The lagrange kernel of the boolean hypercube is a multilinear extension of the function that
/// when given `x, y` in `{0, 1}^n` evaluates to 1 if `x = y`, and evaluates to 0 otherwise.
pub fn eq<F: Field>(x: &[F], y: &[F]) -> F {
assert_eq!(x.len(), y.len());
zip(x, y)
.map(|(&xi, &yi)| xi * yi + (F::one() - xi) * (F::one() - yi))
.product()
}
/// Computes `eq(0, assignment) * eval0 + eq(1, assignment) * eval1`.
pub fn fold_mle_evals<F>(assignment: SecureField, eval0: F, eval1: F) -> SecureField
where
F: Field,
SecureField: ExtensionOf<F>,
{
assignment * (eval1 - eval0) + eval0
}
/// Projective fraction.
#[derive(Debug, Clone, Copy)]
pub struct Fraction<N, D> {
pub numerator: N,
pub denominator: D,
}
impl<N, D> Fraction<N, D> {
pub fn new(numerator: N, denominator: D) -> Self {
Self {
numerator,
denominator,
}
}
}
impl<N, D: Add<Output = D> + Add<N, Output = D> + Mul<N, Output = D> + Mul<Output = D> + Copy> Add
for Fraction<N, D>
{
type Output = Fraction<D, D>;
fn add(self, rhs: Self) -> Fraction<D, D> {
Fraction {
numerator: rhs.denominator * self.numerator + self.denominator * rhs.numerator,
denominator: self.denominator * rhs.denominator,
}
}
}
impl<N: Zero, D: One + Zero> Zero for Fraction<N, D>
where
Self: Add<Output = Self>,
{
fn zero() -> Self {
Self {
numerator: N::zero(),
denominator: D::one(),
}
}
fn is_zero(&self) -> bool {
self.numerator.is_zero() && !self.denominator.is_zero()
}
}
impl<N, D> Sum for Fraction<N, D>
where
Self: Zero,
{
fn sum<I: Iterator<Item = Self>>(mut iter: I) -> Self {
let first = iter.next().unwrap_or_else(Self::zero);
iter.fold(first, |a, b| a + b)
}
}
/// Represents the fraction `1 / x`
pub struct Reciprocal<T> {
x: T,
}
impl<T> Reciprocal<T> {
pub fn new(x: T) -> Self {
Self { x }
}
}
impl<T: Add<Output = T> + Mul<Output = T> + Copy> Add for Reciprocal<T> {
type Output = Fraction<T, T>;
fn add(self, rhs: Self) -> Fraction<T, T> {
// `1/a + 1/b = (a + b)/(a * b)`
Fraction {
numerator: self.x + rhs.x,
denominator: self.x * rhs.x,
}
}
}
#[cfg(test)]
mod tests {
use std::iter::zip;
use num_traits::{One, Zero};
use super::{horner_eval, UnivariatePoly};
use crate::core::fields::m31::BaseField;
use crate::core::fields::qm31::SecureField;
use crate::core::fields::FieldExpOps;
use crate::core::lookups::utils::eq;
#[test]
fn lagrange_interpolation_works() {
let xs = [5, 1, 3, 9].map(BaseField::from);
let ys = [1, 2, 3, 4].map(BaseField::from);
let poly = UnivariatePoly::interpolate_lagrange(&xs, &ys);
for (x, y) in zip(xs, ys) {
assert_eq!(poly.eval_at_point(x), y, "mismatch for x={x}");
}
}
#[test]
fn horner_eval_works() {
let coeffs = [BaseField::from(9), BaseField::from(2), BaseField::from(3)];
let x = BaseField::from(7);
let eval = horner_eval(&coeffs, x);
assert_eq!(eval, coeffs[0] + coeffs[1] * x + coeffs[2] * x.square());
}
#[test]
fn eq_identical_hypercube_points_returns_one() {
let zero = SecureField::zero();
let one = SecureField::one();
let a = &[one, zero, one];
let eq_eval = eq(a, a);
assert_eq!(eq_eval, one);
}
#[test]
fn eq_different_hypercube_points_returns_zero() {
let zero = SecureField::zero();
let one = SecureField::one();
let a = &[one, zero, one];
let b = &[one, zero, zero];
let eq_eval = eq(a, b);
assert_eq!(eq_eval, zero);
}
#[test]
#[should_panic]
fn eq_different_size_points() {
let zero = SecureField::zero();
let one = SecureField::one();
eq(&[zero, one], &[zero]);
}
}