Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
polynomial.hpp
Go to the documentation of this file.
1// === AUDIT STATUS ===
2// internal: { status: not started, auditors: [], date: YYYY-MM-DD }
3// external_1: { status: not started, auditors: [], date: YYYY-MM-DD }
4// external_2: { status: not started, auditors: [], date: YYYY-MM-DD }
5// =====================
6
7#pragma once
16#include "evaluation_domain.hpp"
18#include <cstddef>
19#include <fstream>
20#include <ranges>
21namespace bb {
22
23/* Span class with a start index offset.
24 * We conceptually have a span like a_0 + a_1 x ... a_n x^n and then multiply by x^start_index.
25 * This allows more efficient representation than a fully defined span for 'islands' of zeroes. */
26template <typename Fr> struct PolynomialSpan {
33 size_t end_index() const { return start_index + size(); }
34 Fr* data() { return span.data(); }
35 size_t size() const { return span.size(); }
36 Fr& operator[](size_t index)
37 {
39 BB_ASSERT_LT(index, end_index());
40 return span[index - start_index];
41 }
42 const Fr& operator[](size_t index) const
43 {
45 BB_ASSERT_LT(index, end_index());
46 return span[index - start_index];
47 }
49 {
50 if (offset > span.size()) { // Return a null span
51 return { 0, span.subspan(span.size()) };
52 }
53 size_t new_length = std::min(length, span.size() - offset);
54 return { start_index + offset, span.subspan(offset, new_length) };
55 }
57};
58
74template <typename Fr> class Polynomial {
75 public:
76 using FF = Fr;
77 enum class DontZeroMemory { FLAG };
78
79 Polynomial(size_t size, size_t virtual_size, size_t start_index = 0);
80 // Intended just for plonk, where size == virtual_size always
82 : Polynomial(size, size) {};
83
84 // Constructor that does not initialize values, use with caution to save time.
92 Polynomial(const Polynomial& other);
93 Polynomial(const Polynomial& other, size_t target_size);
94
95 Polynomial(Polynomial&& other) noexcept = default;
96
97 Polynomial(std::span<const Fr> coefficients, size_t virtual_size);
98
100 : Polynomial(coefficients, coefficients.size())
101 {}
102
110 {
111 return Polynomial(/*actual size*/ virtual_size - 1, virtual_size, /*shiftable offset*/ 1);
112 }
113 // Allow polynomials to be entirely reset/dormant
114 Polynomial() = default;
115
124
125 // move assignment
126 Polynomial& operator=(Polynomial&& other) noexcept = default;
128 ~Polynomial() = default;
129
133 Polynomial share() const;
134
136
141 bool is_zero() const
142 {
143 if (is_empty()) {
144 throw_or_abort("Checking is_zero on an empty Polynomial!");
145 }
146 for (size_t i = 0; i < size(); i++) {
147 if (coefficients_.data()[i] != 0) {
148 return false;
149 }
150 }
151 return true;
152 }
153
154 bool operator==(Polynomial const& rhs) const;
155
163 const Fr& get(size_t i, size_t virtual_padding = 0) const { return coefficients_.get(i, virtual_padding); };
164
165 bool is_empty() const { return coefficients_.size() == 0; }
166
173 Polynomial shifted() const;
174
179 Polynomial right_shifted(const size_t magnitude) const;
180
188 Polynomial reverse() const;
189
204 Fr evaluate_mle(std::span<const Fr> evaluation_points, bool shift = false) const;
205
224 Polynomial partial_evaluate_mle(std::span<const Fr> evaluation_points) const;
225
230
242
243 Fr evaluate(const Fr& z, size_t target_size) const;
244 Fr evaluate(const Fr& z) const;
245
253
260
267
274
280 void mask()
281 {
282 // Ensure there is sufficient space to add masking and also that we have memory allocated up to the virtual_size
283 BB_ASSERT_GTE(virtual_size(), NUM_MASKED_ROWS);
285
286 for (size_t i = virtual_size() - NUM_MASKED_ROWS; i < virtual_size(); ++i) {
288 }
289 }
290
291 std::size_t size() const { return coefficients_.size(); }
292 std::size_t virtual_size() const { return coefficients_.virtual_size(); }
293 void increase_virtual_size(const size_t size_in) { coefficients_.increase_virtual_size(size_in); };
294
295 Fr* data() { return coefficients_.data(); }
296 const Fr* data() const { return coefficients_.data(); }
297
306 Fr& at(size_t index) { return coefficients_[index]; }
307 const Fr& at(size_t index) const { return coefficients_[index]; }
308
309 const Fr& operator[](size_t i) { return get(i); }
310 const Fr& operator[](size_t i) const { return get(i); }
311
312 static Polynomial random(size_t size, size_t start_index = 0)
313 {
314 PROFILE_THIS_NAME("generate random polynomial");
315
317 }
318
319 static Polynomial random(size_t size, size_t virtual_size, size_t start_index)
320 {
323 size,
324 [&](size_t i) { p.coefficients_.data()[i] = Fr::random_element(); },
326 return p;
327 }
328
336
343 Polynomial expand(const size_t new_start_index, const size_t new_end_index) const;
344
350 void shrink_end_index(const size_t new_end_index);
351
358 Polynomial full() const;
359
360 // The extents of the actual memory-backed polynomial region
361 size_t start_index() const { return coefficients_.start_; }
362 size_t end_index() const { return coefficients_.end_; }
363
372 std::span<Fr> coeffs(size_t offset = 0) { return { data() + offset, data() + size() }; }
373 std::span<const Fr> coeffs(size_t offset = 0) const { return { data() + offset, data() + size() }; }
378 operator PolynomialSpan<Fr>() { return { start_index(), coeffs() }; }
379
384 operator PolynomialSpan<const Fr>() const { return { start_index(), coeffs() }; }
385
386 auto indices() const { return std::ranges::iota_view(start_index(), end_index()); }
387 auto indexed_values() { return zip_view(indices(), coeffs()); }
388 auto indexed_values() const { return zip_view(indices(), coeffs()); }
392 bool is_valid_set_index(size_t index) const { return (index >= start_index() && index < end_index()); }
396 void set_if_valid_index(size_t index, const Fr& value)
397 {
399 if (is_valid_set_index(index)) {
400 at(index) = value;
401 }
402 }
403
416 template <typename T> void copy_vector(const std::vector<T>& vec)
417 {
418 BB_ASSERT_LTE(vec.size(), end_index());
419 BB_ASSERT_LTE(vec.size() - start_index(), size());
420 for (size_t i = start_index(); i < vec.size(); i++) {
421 at(i) = vec[i];
422 }
423 }
424
425 /*
426 * @brief For quick and dirty comparisons. ONLY for development and log use!
427 */
429 {
430 Fr result{ 0 };
431 for (size_t i = start_index(); i < end_index(); i++) {
432 result += (*this)[i] * i;
433 }
434 return result;
435 }
436
437 private:
438 // allocate a fresh memory pointer for backing memory
439 // DOES NOT initialize memory
440 void allocate_backing_memory(size_t size, size_t virtual_size, size_t start_index);
441
442 // safety check for in place operations
443 bool in_place_operation_viable(size_t domain_size) { return (size() >= domain_size); }
444
445 // The underlying memory, with a bespoke (but minimal) shared array struct that fits our needs.
446 // Namely, it supports polynomial shifts and 'virtual' zeroes past a size up until a 'virtual' size.
448};
449// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
450template <typename Fr> std::shared_ptr<Fr[]> _allocate_aligned_memory(size_t n_elements)
451{
452 // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)
453 return std::static_pointer_cast<Fr[]>(get_mem_slab(sizeof(Fr) * n_elements));
454}
455
460template <typename Fr_>
462 const SharedShiftedVirtualZeroesArray<Fr_>& coefficients,
463 bool shift)
464{
465 constexpr bool is_native = IsAnyOf<Fr_, bb::fr, grumpkin::fr>;
466 // shift ==> native
467 ASSERT(!shift || is_native);
468
469 if (coefficients.size() == 0) {
470 return Fr_(0);
471 }
472
473 const size_t n = evaluation_points.size();
474 const size_t dim = numeric::get_msb(coefficients.end_ - 1) + 1; // Round up to next power of 2
475
476 // To simplify handling of edge cases, we assume that the index space is always a power of 2
477 BB_ASSERT_EQ(coefficients.virtual_size(), static_cast<size_t>(1 << n));
478
479 // We first fold over dim rounds l = 0,...,dim-1.
480 // in round l, n_l is the size of the buffer containing the Polynomial partially evaluated
481 // at u₀,..., u_l.
482 // In round 0, this is half the size of dim
483 size_t n_l = 1 << (dim - 1);
484
485 // temporary buffer of half the size of the Polynomial
486 // TODO(https://github.com/AztecProtocol/barretenberg/issues/1096): Make this a Polynomial with
487 // DontZeroMemory::FLAG
488 auto tmp_ptr = _allocate_aligned_memory<Fr_>(sizeof(Fr_) * n_l);
489 auto tmp = tmp_ptr.get();
490
491 size_t offset = 0;
492 if constexpr (is_native) {
493 if (shift) {
494 BB_ASSERT_EQ(coefficients.get(0), Fr_::zero());
495 offset++;
496 }
497 }
498
499 Fr_ u_l = evaluation_points[0];
500
501 // Note below: i * 2 + 1 + offset might equal virtual_size. This used to subtlely be handled by extra capacity
502 // padding (and there used to be no assert time checks, which this constant helps with).
503 const size_t ALLOW_ONE_PAST_READ = 1;
504 for (size_t i = 0; i < n_l; ++i) {
505 // curr[i] = (Fr(1) - u_l) * prev[i * 2] + u_l * prev[(i * 2) + 1];
506 tmp[i] = coefficients.get(i * 2 + offset) +
507 u_l * (coefficients.get(i * 2 + 1 + offset, ALLOW_ONE_PAST_READ) - coefficients.get(i * 2 + offset));
508 }
509
510 // partially evaluate the dim-1 remaining points
511 for (size_t l = 1; l < dim; ++l) {
512 n_l = 1 << (dim - l - 1);
513 u_l = evaluation_points[l];
514 for (size_t i = 0; i < n_l; ++i) {
515 tmp[i] = tmp[i * 2] + u_l * (tmp[(i * 2) + 1] - tmp[i * 2]);
516 }
517 }
518 auto result = tmp[0];
519
520 // We handle the "trivial" dimensions which are full of zeros.
521 for (size_t i = dim; i < n; i++) {
522 result *= (Fr_(1) - evaluation_points[i]);
523 }
524
525 return result;
526}
527
531template <typename Fr_>
533 const SharedShiftedVirtualZeroesArray<Fr_>& coefficients)
534{
535 return _evaluate_mle(evaluation_points, coefficients, false);
536}
537
538template <typename Fr> inline std::ostream& operator<<(std::ostream& os, const Polynomial<Fr>& p)
539{
540 if (p.size() == 0) {
541 return os << "[]";
542 }
543 if (p.size() == 1) {
544 return os << "[ data " << p[0] << "]";
545 }
546 return os << "[ data\n"
547 << " " << p[0] << ",\n"
548 << " " << p[1] << ",\n"
549 << " ... ,\n"
550 << " " << p[p.size() - 2] << ",\n"
551 << " " << p[p.size() - 1] << ",\n"
552 << "]";
553}
554
555template <typename Poly, typename... Polys> auto zip_polys(Poly&& poly, Polys&&... polys)
556{
557 // Ensure all polys have the same start_index() and end_index() as poly
558 // Use fold expression to check all polys exactly match our size
559 // Wrap BB_ASSERT_EQ_RELEASE in a lambda to make it usable in a fold expression
560 auto check_indices = [&](const auto& other) {
561 BB_ASSERT_EQ(poly.start_index(), other.start_index());
562 BB_ASSERT_EQ(poly.end_index(), other.end_index());
563 };
564 // Apply the lambda to each poly in the parameter pack
565 (check_indices(polys), ...);
566 return zip_view(poly.indices(), poly.coeffs(), polys.coeffs()...);
567}
568} // namespace bb
#define BB_ASSERT_GTE(left, right,...)
Definition assert.hpp:101
#define BB_ASSERT_EQ(actual, expected,...)
Definition assert.hpp:59
#define BB_ASSERT_LTE(left, right,...)
Definition assert.hpp:129
#define BB_ASSERT_LT(left, right,...)
Definition assert.hpp:115
#define ASSERT(expression,...)
Definition assert.hpp:49
Structured polynomial class that represents the coefficients 'a' of a_0 + a_1 x .....
Polynomial(size_t size, size_t virtual_size, DontZeroMemory flag)
Polynomial & operator=(Polynomial &&other) noexcept=default
Polynomial shifted() const
Returns a Polynomial the left-shift of self.
size_t start_index() const
Polynomial & operator*=(Fr scaling_factor)
sets this = p(X) to s⋅p(X)
Polynomial(Polynomial &&other) noexcept=default
bool is_empty() const
Polynomial partial_evaluate_mle(std::span< const Fr > evaluation_points) const
Partially evaluates in the last k variables a polynomial interpreted as a multilinear extension.
static Polynomial random(size_t size, size_t start_index=0)
Polynomial()=default
Polynomial expand(const size_t new_start_index, const size_t new_end_index) const
Expands the polynomial with new start_index and end_index The value of the polynomial remains the sam...
Fr compute_kate_opening_coefficients(const Fr &z)
std::size_t virtual_size() const
Fr evaluate(const Fr &z, size_t target_size) const
SharedShiftedVirtualZeroesArray< Fr > coefficients_
Polynomial(const Polynomial &other)
void increase_virtual_size(const size_t size_in)
std::span< Fr > coeffs(size_t offset=0)
Strictly iterates the defined region of the polynomial. We keep this explicit, instead of having an i...
void copy_vector(const std::vector< T > &vec)
Copy over values from a vector that is of a convertible type.
auto indices() const
auto indexed_values() const
bool in_place_operation_viable(size_t domain_size)
Polynomial & operator=(const Polynomial &other)
void mask()
Add random values to the coefficients of a polynomial. In practice, this is used for ensuring the com...
Fr evaluate_mle(std::span< const Fr > evaluation_points, bool shift=false) const
evaluate multi-linear extension p(X_0,…,X_{n-1}) = \sum_i a_i*L_i(X_0,…,X_{n-1}) at u = (u_0,...
Polynomial(const Polynomial &other, size_t target_size)
size_t end_index() const
Fr debug_hash() const
const Fr & get(size_t i, size_t virtual_padding=0) const
Retrieves the value at the specified index.
Polynomial(size_t size)
Polynomial & operator-=(PolynomialSpan< const Fr > other)
subtracts the polynomial q(X) 'other'.
Polynomial share() const
static Polynomial random(size_t size, size_t virtual_size, size_t start_index)
Polynomial reverse() const
Returns the polynomial equal to the reverse of self.
Polynomial right_shifted(const size_t magnitude) const
Returns a Polynomial equal to the right-shift-by-magnitude of self.
Fr compute_barycentric_evaluation(const Fr &z, const EvaluationDomain< Fr > &domain)
Fr & at(size_t index)
Our mutable accessor, unlike operator[]. We abuse precedent a bit to differentiate at() and operator[...
void add_scaled(PolynomialSpan< const Fr > other, Fr scaling_factor) &
adds the polynomial q(X) 'other', multiplied by a scaling factor.
bool operator==(Polynomial const &rhs) const
void shrink_end_index(const size_t new_end_index)
The end_index of the polynomial is decreased without any memory de-allocation. This is a very fast wa...
Polynomial & operator+=(PolynomialSpan< const Fr > other)
adds the polynomial q(X) 'other'.
const Fr & at(size_t index) const
~Polynomial()=default
static Polynomial shiftable(size_t virtual_size)
Utility to efficiently construct a shift from the original polynomial.
const Fr * data() const
Polynomial(size_t size, DontZeroMemory flag)
static Polynomial create_non_parallel_zero_init(size_t size, size_t virtual_size)
A factory to construct a polynomial where parallel initialization is not possible (e....
void factor_roots(const Fr &root)
Divides p(X) by (X-r) in-place. Assumes that p(rⱼ)=0 for all j.
void allocate_backing_memory(size_t size, size_t virtual_size, size_t start_index)
void set_if_valid_index(size_t index, const Fr &value)
Like setting with at(), but allows zeroes to result in no set.
std::size_t size() const
bool is_zero() const
Check whether or not a polynomial is identically zero.
std::span< const Fr > coeffs(size_t offset=0) const
bool is_valid_set_index(size_t index) const
Is this index valid for a set? i.e. calling poly.at(index) = value.
const Fr & operator[](size_t i) const
Polynomial full() const
Copys the polynomial, but with the whole address space usable. The value of the polynomial remains th...
auto indexed_values()
const Fr & operator[](size_t i)
Polynomial(std::span< const Fr > coefficients)
uint8_t const size_t length
Definition data_store.hpp:9
ssize_t offset
Definition engine.cpp:36
std::ostream & operator<<(std::ostream &os, uint256_t const &a)
Definition uint256.hpp:246
constexpr T get_msb(const T in)
Definition get_msb.hpp:47
void factor_roots(std::span< Fr > polynomial, const Fr &root)
Divides p(X) by (X-r) in-place.
constexpr size_t ALWAYS_MULTITHREAD
Definition thread.hpp:148
Entry point for Barretenberg command-line interface.
std::shared_ptr< Fr[]> _allocate_aligned_memory(size_t n_elements)
std::shared_ptr< void > get_mem_slab(size_t size)
auto zip_polys(Poly &&poly, Polys &&... polys)
void parallel_for_heuristic(size_t num_points, const std::function< void(size_t, size_t, size_t)> &func, size_t heuristic_cost)
Split a loop into several loops running in parallel based on operations in 1 iteration.
Definition thread.cpp:132
Fr_ _evaluate_mle(std::span< const Fr_ > evaluation_points, const SharedShiftedVirtualZeroesArray< Fr_ > &coefficients, bool shift)
Internal implementation to support both native and stdlib circuit field types.
Fr_ generic_evaluate_mle(std::span< const Fr_ > evaluation_points, const SharedShiftedVirtualZeroesArray< Fr_ > &coefficients)
Static exposed implementation to support both native and stdlib circuit field types.
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
#define PROFILE_THIS_NAME(name)
Definition op_count.hpp:16
Curve::ScalarField Fr
A shared pointer array template that represents a virtual array filled with zeros up to virtual_size_...
const T & get(size_t index, size_t virtual_padding=0) const
Retrieves the value at the specified index, or 'zero'. Optimizes for e.g. 256-bit fields by storing a...
size_t end_
The ending index of the memory-backed range.
PolynomialSpan subspan(size_t offset, size_t length)
size_t size() const
Fr & operator[](size_t index)
std::span< Fr > span
size_t end_index() const
PolynomialSpan(size_t start_index, std::span< Fr > span)
const Fr & operator[](size_t index) const
static field random_element(numeric::RNG *engine=nullptr) noexcept
BB_INLINE constexpr bool is_zero() const noexcept
void throw_or_abort(std::string const &err)