VectorLib.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.oblivm.backend.circuits.arithmetic;
  2. import com.oblivm.backend.flexsc.CompEnv;
  3. public class VectorLib<T> {
  4. ArithmeticLib<T> lib;
  5. CompEnv<T> env;
  6. public VectorLib(CompEnv<T> e, ArithmeticLib<T> lib) {
  7. env = e;
  8. this.lib = lib;
  9. }
  10. public T[][] xor(T[][] a, T[][] b) {
  11. IntegerLib<T> ilib = new IntegerLib<T>(lib.getEnv());
  12. T[][] res = env.newTArray(a.length, 1);
  13. for (int i = 0; i < a.length; ++i)
  14. res[i] = ilib.xor(a[i], b[i]);
  15. return res;
  16. }
  17. public T[][] add(T[][] a, T[][] b) {
  18. T[][] res = env.newTArray(a.length, 1);
  19. for (int i = 0; i < a.length; ++i)
  20. res[i] = lib.add(a[i], b[i]);
  21. return res;
  22. }
  23. public T[][] sub(T[][] a, T[][] b) {
  24. T[][] res = env.newTArray(a.length, 1);
  25. for (int i = 0; i < a.length; ++i)
  26. res[i] = lib.sub(a[i], b[i]);
  27. return res;
  28. }
  29. public T[] innerProduct(T[][] a, T[][] b) {
  30. T[] res = lib.publicValue(0);
  31. for (int i = 0; i < a.length; ++i)
  32. res = lib.add(res, lib.multiply(a[i], b[i]));
  33. return res;
  34. }
  35. public T[][] scalarProduct(T[] scalar, T[][] v) {
  36. T[][] res = env.newTArray(v.length, 1);
  37. for (int i = 0; i < v.length; ++i)
  38. res[i] = lib.multiply(scalar, v[i]);
  39. return res;
  40. }
  41. public T[][] projection(T[][] a, T[][] e) {
  42. T[] ea = innerProduct(e, a);
  43. T[] ee = innerProduct(e, e);
  44. T[] scalar = lib.div(ea, ee);
  45. return scalarProduct(scalar, e);
  46. }
  47. public T[][] normalize(T[][] vec) {
  48. T[] scalar = innerProduct(vec, vec);
  49. scalar = lib.sqrt(scalar);
  50. scalar = lib.div(lib.publicValue(1), scalar);
  51. return scalarProduct(scalar, vec);
  52. }
  53. }