Browse Source

init

main
arnaucube 8 months ago
commit
989bc9a358
6 changed files with 797 additions and 0 deletions
  1. +1
    -0
      .gitignore
  2. +548
    -0
      Cargo.lock
  3. +23
    -0
      Cargo.toml
  4. +11
    -0
      README.md
  5. +113
    -0
      src/lib.rs
  6. +101
    -0
      src/utils.rs

+ 1
- 0
.gitignore

@ -0,0 +1 @@
/target

+ 548
- 0
Cargo.lock

@ -0,0 +1,548 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "ahash"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42cd52102d3df161c77a887b608d7a4897d7cc112886a9537b738a887a03aaff"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "ark-ec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "defd9a439d56ac24968cca0571f598a61bc8c55f71d50a89cda591cb750670ba"
dependencies = [
"ark-ff",
"ark-poly",
"ark-serialize",
"ark-std",
"derivative",
"hashbrown",
"itertools",
"num-traits",
"zeroize",
]
[[package]]
name = "ark-ff"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba"
dependencies = [
"ark-ff-asm",
"ark-ff-macros",
"ark-serialize",
"ark-std",
"derivative",
"digest",
"itertools",
"num-bigint",
"num-traits",
"paste",
"rustc_version",
"zeroize",
]
[[package]]
name = "ark-ff-asm"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348"
dependencies = [
"quote",
"syn 1.0.109",
]
[[package]]
name = "ark-ff-macros"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565"
dependencies = [
"num-bigint",
"num-traits",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "ark-pallas"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "760ecac12a00211188c9101b63bd284b80da5abcc5d97d9d2b3803bca1f63a52"
dependencies = [
"ark-ec",
"ark-ff",
"ark-r1cs-std",
"ark-std",
]
[[package]]
name = "ark-poly"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d320bfc44ee185d899ccbadfa8bc31aab923ce1558716e1997a1e74057fe86bf"
dependencies = [
"ark-ff",
"ark-serialize",
"ark-std",
"derivative",
"hashbrown",
]
[[package]]
name = "ark-r1cs-std"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de1d1472e5cb020cb3405ce2567c91c8d43f21b674aef37b0202f5c3304761db"
dependencies = [
"ark-ec",
"ark-ff",
"ark-relations",
"ark-std",
"derivative",
"num-bigint",
"num-integer",
"num-traits",
"tracing",
]
[[package]]
name = "ark-relations"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00796b6efc05a3f48225e59cb6a2cda78881e7c390872d5786aaf112f31fb4f0"
dependencies = [
"ark-ff",
"ark-std",
"tracing",
]
[[package]]
name = "ark-serialize"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5"
dependencies = [
"ark-serialize-derive",
"ark-std",
"digest",
"num-bigint",
]
[[package]]
name = "ark-serialize-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae3281bc6d0fd7e549af32b52511e1302185bd688fd3359fa36423346ff682ea"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "ark-snark"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d3cc6833a335bb8a600241889ead68ee89a3cf8448081fb7694c0fe503da63"
dependencies = [
"ark-ff",
"ark-relations",
"ark-serialize",
"ark-std",
]
[[package]]
name = "ark-std"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185"
dependencies = [
"num-traits",
"rand",
]
[[package]]
name = "ark-vesta"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "534dddabcd5017dca22582d25bf6946fadab04aa6cf15af243a126f27f6632f9"
dependencies = [
"ark-ec",
"ark-ff",
"ark-pallas",
"ark-r1cs-std",
"ark-std",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "derivative"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"crypto-common",
]
[[package]]
name = "either"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
dependencies = [
"ahash",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "libc"
version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
name = "mat-vec-prod-exp"
version = "0.1.0"
dependencies = [
"ark-ec",
"ark-ff",
"ark-pallas",
"ark-poly",
"ark-r1cs-std",
"ark-relations",
"ark-serialize",
"ark-snark",
"ark-std",
"ark-vesta",
"num-bigint",
"rand",
"thiserror",
]
[[package]]
name = "num-bigint"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "paste"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
[[package]]
name = "pin-project-lite"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro2"
version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
]
[[package]]
name = "tracing"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
]
[[package]]
name = "tracing-core"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"
[[package]]
name = "typenum"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "zerocopy"
version = "0.7.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.7.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
]
[[package]]
name = "zeroize"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
]

+ 23
- 0
Cargo.toml

@ -0,0 +1,23 @@
[package]
name = "mat-vec-prod-exp"
version = "0.1.0"
edition = "2021"
[dependencies]
ark-ec = "^0.4.0"
ark-ff = "^0.4.0"
ark-poly = "^0.4.0"
ark-std = "^0.4.0"
ark-relations = { version = "^0.4.0", default-features = false }
ark-r1cs-std = { version = "0.4.0", default-features = false } # this is patched at the workspace level
ark-snark = { version = "^0.4.0"}
ark-serialize = "^0.4.0"
thiserror = "1.0"
num-bigint = "0.4"
[dev-dependencies]
ark-pallas = {version="0.4.0", features=["r1cs"]}
ark-vesta = {version="0.4.0", features=["r1cs"]}
rand = "0.8.5"

+ 11
- 0
README.md

@ -0,0 +1,11 @@
# mat-vec-prod-exp
*Matrix vector product experiments*
Instructions:
- Just run `cargo test -- --nocapture` and the number of constraints will be printed
- Can comment & uncomment `lib.rs` lines `71` & `72` to test the different approaches:
```rust
let Az = mat_vec_mul_sparse_gadget(A, z);
// let Az = handcrafted_A_by_z(cs, z)?;
```

+ 113
- 0
src/lib.rs

@ -0,0 +1,113 @@
#![allow(non_snake_case)]
#![allow(unused_doc_comments)]
#![allow(dead_code)]
use ark_ff::PrimeField;
use ark_r1cs_std::fields::nonnative::NonNativeFieldVar;
use ark_r1cs_std::{alloc::AllocVar, eq::EqGadget, fields::FieldVar, R1CSVar};
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError};
use core::marker::PhantomData;
use std::ops::Mul;
mod utils;
use utils::*;
/// - F stands for the field that we represent
/// - CF stands for the ConstraintField over which we do the operations
/// Implements the A * z matrix-vector-product by fixing the combinations of 'z'.
fn handcrafted_A_by_z<F: PrimeField, CF: PrimeField>(
cs: ConstraintSystemRef<CF>,
z: Vec<NonNativeFieldVar<F, CF>>,
) -> Result<Vec<NonNativeFieldVar<F, CF>>, SynthesisError> {
let five = NonNativeFieldVar::<F, CF>::new_constant(cs.clone(), F::from(5u32))?;
// directly hand-craft the output vector containing the operations in-place:
Ok(vec![
z[1].clone() + five.clone() * z[4].clone(),
z[1].clone() + z[3].clone(),
z[1].clone() + z[4].clone(),
five * z[0].clone() + z[4].clone() + z[5].clone(),
]
.clone())
}
/// Implements the A * z matrix-vector-product by doing the sparse matrix by vector algorithm, and
/// assuming that the elements of the matrix A are constants of the system.
pub fn mat_vec_mul_sparse_gadget<F: PrimeField, CF: PrimeField>(
m: SparseMatrixVar<F, CF>,
v: Vec<NonNativeFieldVar<F, CF>>,
) -> Vec<NonNativeFieldVar<F, CF>> {
let mut res = vec![NonNativeFieldVar::<F, CF>::zero(); m.n_rows];
for (row_i, row) in m.coeffs.iter().enumerate() {
for (value, col_i) in row.iter() {
if value.value().unwrap() == F::one() {
res[row_i] += v[*col_i].clone(); // when value==1, no need to multiply by it
continue;
}
res[row_i] += value.clone().mul(&v[*col_i].clone());
}
}
res
}
/// Circuit that takes as constants the sparse matrix A, and as inputs the vectors z and y. It
/// computes the matrix by vector product between A and z, and checks that is equal to y
/// (ie. y == A*z)
struct MatrixVectorCircuit<F: PrimeField, CF: PrimeField> {
_cf: PhantomData<CF>,
pub A: SparseMatrix<F>,
pub z: Vec<F>,
pub y: Vec<F>,
}
impl<F: PrimeField, CF: PrimeField> ConstraintSynthesizer<CF> for MatrixVectorCircuit<F, CF> {
fn generate_constraints(self, cs: ConstraintSystemRef<CF>) -> Result<(), SynthesisError> {
// set A as circuit constants
let A = SparseMatrixVar::<F, CF>::new_constant(cs.clone(), self.A)?;
// set z and y as witness (private inputs)
let z: Vec<NonNativeFieldVar<F, CF>> = Vec::new_witness(cs.clone(), || Ok(self.z.clone()))?;
let y: Vec<NonNativeFieldVar<F, CF>> = Vec::new_witness(cs.clone(), || Ok(self.y.clone()))?;
/// The next two lines are the ones that can be swapped to see the number of constraints
/// taken by the two approaches:
let Az = mat_vec_mul_sparse_gadget(A, z);
// let Az = handcrafted_A_by_z(cs, z)?;
Az.enforce_equal(&y)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use ark_pallas::{Fq, Fr};
use ark_relations::r1cs::ConstraintSystem;
#[test]
fn test_relaxed_r1cs_nonnative_matrix_vector_product() {
let A = to_F_matrix::<Fq>(vec![
vec![0, 1, 0, 0, 5, 0],
vec![0, 1, 0, 1, 0, 0],
vec![0, 1, 0, 0, 1, 0],
vec![5, 0, 0, 0, 1, 1],
]);
let z = to_F_vec(vec![1, 123, 35, 53, 80, 30]);
let y = mat_vec_mul_sparse(&A, &z); // y = A*z
println!("Matrix of size {} x {}", A.n_rows, A.n_cols);
println!("Vector of size {}", z.len());
println!(
"Build the circuit that computes the matrix-vector-product over a non-native field"
);
let cs = ConstraintSystem::<Fr>::new_ref();
let circuit = MatrixVectorCircuit::<Fq, Fr> {
_cf: PhantomData,
A,
z,
y,
};
circuit.generate_constraints(cs.clone()).unwrap();
println!("Number of constraints: {}", cs.num_constraints());
assert!(cs.is_satisfied().unwrap());
}
}

+ 101
- 0
src/utils.rs

@ -0,0 +1,101 @@
use ark_ff::PrimeField;
use ark_r1cs_std::{
alloc::{AllocVar, AllocationMode},
fields::nonnative::NonNativeFieldVar,
};
use ark_relations::r1cs::{Matrix as R1CSMatrix, Namespace, SynthesisError};
use core::{borrow::Borrow, marker::PhantomData};
pub struct SparseMatrix<F: PrimeField> {
pub n_rows: usize,
pub n_cols: usize,
/// coeffs = R1CSMatrix = Vec<Vec<(F, usize)>>, which contains each row and the F is the value
/// of the coefficient and the usize indicates the column position
pub coeffs: R1CSMatrix<F>,
}
#[derive(Debug, Clone)]
pub struct SparseMatrixVar<F: PrimeField, CF: PrimeField> {
_f: PhantomData<F>,
_cf: PhantomData<CF>,
pub n_rows: usize,
pub n_cols: usize,
// same format as the native SparseMatrix (which follows ark_relations::r1cs::Matrix format
pub coeffs: Vec<Vec<(NonNativeFieldVar<F, CF>, usize)>>,
}
impl<F, CF> AllocVar<SparseMatrix<F>, CF> for SparseMatrixVar<F, CF>
where
F: PrimeField,
CF: PrimeField,
{
fn new_variable<T: Borrow<SparseMatrix<F>>>(
cs: impl Into<Namespace<CF>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
f().and_then(|val| {
let cs = cs.into();
let mut coeffs: Vec<Vec<(NonNativeFieldVar<F, CF>, usize)>> = Vec::new();
for row in val.borrow().coeffs.iter() {
let mut rowVar: Vec<(NonNativeFieldVar<F, CF>, usize)> = Vec::new();
for &(value, col_i) in row.iter() {
let coeffVar =
NonNativeFieldVar::<F, CF>::new_variable(cs.clone(), || Ok(value), mode)?;
rowVar.push((coeffVar, col_i));
}
coeffs.push(rowVar);
}
Ok(Self {
_f: PhantomData,
_cf: PhantomData,
n_rows: val.borrow().n_rows,
n_cols: val.borrow().n_cols,
coeffs,
})
})
}
}
pub fn mat_vec_mul_sparse<F: PrimeField>(M: &SparseMatrix<F>, z: &[F]) -> Vec<F> {
assert_eq!(M.n_cols, z.len());
let mut res = vec![F::zero(); M.n_rows];
for (row_i, row) in M.coeffs.iter().enumerate() {
for &(value, col_i) in row.iter() {
res[row_i] += value * z[col_i];
}
}
res
}
pub fn dense_matrix_to_sparse<F: PrimeField>(m: Vec<Vec<F>>) -> SparseMatrix<F> {
let mut r = SparseMatrix::<F> {
n_rows: m.len(),
n_cols: m[0].len(),
coeffs: Vec::new(),
};
for m_row in m.iter() {
let mut row: Vec<(F, usize)> = Vec::new();
for (col_i, value) in m_row.iter().enumerate() {
if !value.is_zero() {
row.push((*value, col_i));
}
}
r.coeffs.push(row);
}
r
}
// just some helpers to define matrices and vectors by hand
pub fn to_F_matrix<F: PrimeField>(M: Vec<Vec<usize>>) -> SparseMatrix<F> {
dense_matrix_to_sparse(to_F_dense_matrix(M))
}
pub fn to_F_dense_matrix<F: PrimeField>(M: Vec<Vec<usize>>) -> Vec<Vec<F>> {
M.iter()
.map(|m| m.iter().map(|r| F::from(*r as u64)).collect())
.collect()
}
pub fn to_F_vec<F: PrimeField>(z: Vec<usize>) -> Vec<F> {
z.iter().map(|c| F::from(*c as u64)).collect()
}

Loading…
Cancel
Save