-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMatrices.cpp
More file actions
806 lines (674 loc) · 28.8 KB
/
Copy pathMatrices.cpp
File metadata and controls
806 lines (674 loc) · 28.8 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
#include "Matrices.h"
ostringstream MatricesSizesNotMatch::cnvt;
/* ----- some helping functions ------ */
long myModulu(long num, long mod)
//the regular modulo operator on minus numbers make trouble when trying to calculate enteries in the diagonal matrices.
//for example, -7%3=-1, but I want it to be 2 (-7+3=-4, -4+3=-1, -1+3= 2)
{
//adding "mod" to "num" until it positive
while(num<0)
num+=mod;
return num%mod;
}
unsigned int numDigit(long num){ return (num/10)==0 ? 1:numDigit(num/10)+1; } //How much digits in the input number. Uses for a "nice" printing
unsigned int largestNumInMatrixDigits(vector<vector<long> > matrix) //Find the longest number in a matrix and returns it length (in digits). Uses for a "nice" printing
{
int largest = 0;
long temp;
for(unsigned int i=0; i < matrix.size(); i++)
for(unsigned int j=0; j<matrix[i].size(); j++)
if((temp = numDigit(matrix[i][j])) > largest)
largest = temp;
return largest;
}
void printNum(long num, int size){
int len = numDigit(num);
cout << num;
for(int i=len; i < size; i++)
cout << " ";
}
Ctxt getNotVector(const EncryptedArray& ea, const FHEPubKey& publicKey){
vector<long> not_vec(ea.size(), 1); //vectors of 1, uses for NOT
Ctxt not_ctxt(publicKey);
ea.encrypt(not_ctxt, publicKey, not_vec);
return not_ctxt;
}
/* --------------------- MatSize (matrices size operations) class --------------------*/
MatSize::MatSize(unsigned int first, unsigned int second): rows(first), columns(second) {}
//MatSize::MatSize(unsigned int sz): rows(sz), columns(sz) {}
MatSize MatSize::operator*(const MatSize& other) const{
if(!canMultiply(other)){
cout << "Sizes not accepted! first: ("<<rows<<"x"<<columns<<"), second: ("<<other.rows<<"x"<<other.columns<<"). return empty MatSize (0x0)" << endl;
return MatSize();
}
return MatSize(rows, other.columns);
}
MatSize MatSize::transpose() { return ((*this) = MatSize(this->columns, this->rows)); }
MatSize MatSize::getTransposed() const { return MatSize(this->columns, this->rows); }
MatSize MatSize::operator*=(const MatSize& other) { return ((*this) = (*this)*other); }
bool MatSize::operator==(const MatSize& other) const { return (rows == other.rows && columns == other.columns); }
bool MatSize::operator!=(const MatSize& other) const { return !(*this==other); }
bool MatSize::canMultiply(const MatSize& other) const { return columns == other.rows; }
bool MatSize::canAdd(const MatSize& other) const { return *(this) == other; }
void MatSize::print() const { cout << "Rows: " << rows << ", Columns: " << columns << endl; }
unsigned int MatSize::size() const { return rows*columns; }
bool MatSize::isSquare() const { return rows==columns; }
/* --------------------- PTMatrix (Plain Text Matrix) class --------------------------*/
PTMatrix::PTMatrix(vector<vector<long> > _matrix, bool diagonal)
{
if(diagonal)
matrix = _matrix;
else{ //transform from regular (rows order) representation to diagonal
matrix = vector<vector<long> >(_matrix[0].size(), vector<long>(_matrix.size(),0));
for(unsigned int i=0, sz1 = matrix.size(); i < sz1; i++)
for(unsigned int j=0, sz2 = matrix[i].size(); j < sz2; j++)
matrix[i][j] = _matrix[j][(i+j)%sz1];
}
}
PTMatrix::PTMatrix(MatSize sizes, unsigned int numbersLimit)
/*this constructor create a random matrix
params:
sizes: - the size of the matrix
numbersLimit = the values limit, that means that all the values in the matrix would be between 0 to numbersLimit (not included), default : 10
*/
{
matrix = vector<vector<long> >(sizes.columns, vector<long>(sizes.rows));
for(unsigned int i=0; i < matrix.size(); i++)
for(unsigned int j=0; j< matrix[i].size(); j++)
matrix[i][j] = rand() % numbersLimit;
}
PTMatrix::PTMatrix(ifstream& file)
/*read a matrix from a file
the file format should be
num_of_rows num_of_columns
the matrix
for example:
2 3
5 3 7
1 4 6
*/
{
string line, temp;
int rows, cols;
if (file.is_open())
{
getline(file, line); //get number of rows
temp = line.substr(0, line.find(' '));
rows = stoi(temp);
temp = line.substr(line.find(' ')+1);
cols = stoi(temp);
matrix = vector<vector<long> >(cols, vector<long>(rows,0));
for(int i=0; i < rows; i++)
{
getline(file,line);
for(int j=0; j < cols; j++){
temp = line.substr(0, line.find(' '));
matrix[myModulu(j-i,matrix.size())][i] = stoi(temp);
line = line.substr(line.find(' ')+1);
}
}
file.close();
}
else
cout << "Unable to open file";
}
bool PTMatrix::save(ofstream& file) const{
if (file.is_open())
{
unsigned int rows = getRows(), cols = getColumns();
file << rows << " " << cols << "\n";
for(unsigned int i=0; i < rows; i++){
for(unsigned int j=0; j < cols; j++)
file << (*this)(i,j) << " ";
file << "\n";
}
file.close();
}
else{
cout << "Unable to open file";
return false;
}
return true;
}
vector<vector<long> > PTMatrix::getMatrix() const{
unsigned int rows = getRows(), cols = getColumns();
vector<vector<long> > ret(rows, vector<long>(cols,0));
for(unsigned int i=0; i < rows ; i++)
for(unsigned int j=0; j < cols; j++)
ret[i][j] = (*this)(i,j);
return ret;
}
EncryptedMatrix PTMatrix::encrypt(const EncryptedArray& ea, const FHEPubKey& publicKey) const{
vector<Ctxt> encMat(size(), Ctxt(publicKey));
unsigned int nslots = ea.size();
for(unsigned int i=0; i< size(); i++){
vector<long> temp = matrix[i];
temp.resize(nslots,0);
ea.encrypt(encMat[i], publicKey, temp);
}
return EncryptedMatrix(encMat, MatSize(getRows(), getColumns()));
}
EncryptedMatrix PTMatrix::encrypt(const FHEPubKey& publicKey) const{
EncryptedArray ea(publicKey.getContext());
return encrypt(ea, publicKey);
}
long& PTMatrix::operator()(unsigned int row, unsigned int column){
if(row >= getRows() || column >= getColumns())
{
cout << "Error, indices out of bound! MatSize: " << getRows() << "*" << getColumns() <<", indices: " << row << "*" << column << endl;
throw out_of_range("Error, indices out of bound!");
}
int i = row, j = column; //casting to int so the subtraction be ok
return matrix[myModulu(j-i,matrix.size())][row];
}
const long& PTMatrix::operator()(unsigned int row, unsigned int column) const{
if(row >= getRows() || column >= getColumns())
{
cout << "Error, indices out of bound! MatSize: " << getRows() << "*" << getColumns() <<", indices: " << row << "*" << column << endl;
throw out_of_range("Error, indices out of bound!");
}
int i = row, j = column; //casting to int so the subtraction be ok
return matrix[myModulu(j-i,matrix.size())][row];
}
unsigned int PTMatrix::getRows() const { return matrix[0].size(); }
unsigned int PTMatrix::getColumns() const { return matrix.size(); }
void PTMatrix::print(string label) const{
if(label.compare("")!=0)
cout << label << endl;
unsigned int primarySize = getRows();
unsigned int secondarySize = getColumns();
unsigned int cellSize = largestNumInMatrixDigits(matrix)+1; //+1 for space
cout << " ";
for(unsigned int i=0; i< secondarySize*cellSize; i++)
cout << "-";
cout << endl;
for(unsigned int i=0; i< primarySize; i++)
{
cout << "|";
for(unsigned int j=0; j< secondarySize; j++)
printNum((*this)(i,j), cellSize);
cout << "|" << endl;
}
cout << " ";
for(unsigned int i=0; i< secondarySize*cellSize; i++)
cout << "-";
cout << endl;
}
PTMatrix PTMatrix::getSubMatrix(unsigned int i, unsigned int j, MatSize blockSize) const{
unsigned int numRows = blockSize.rows, numCols = blockSize.columns;
if(getRows() < i + numRows)
numRows = getRows()-i;
if(getColumns() < j + numCols)
numCols = getColumns()-j;
vector<vector<long> > result(numRows, vector<long>(numCols,0));
for(unsigned int x=0; x < numRows; x++)
for(unsigned int y=0; y < numCols; y++)
result[x][y] = (*this)(i+x,j+y);
return PTMatrix(result, false);
}
vector<long>& PTMatrix::operator[](unsigned int i) { return matrix[i]; }
const vector<long>& PTMatrix::operator[](unsigned int i) const { return matrix[i]; }
unsigned int PTMatrix::size() const { return matrix.size(); }
MatSize PTMatrix::getMatrixSize() const { return MatSize(getRows(), getColumns()); }
//operators
PTMatrix PTMatrix::operator*(const PTMatrix& other) const{
//check sizes
if(getColumns() != other.getRows())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
vector<vector<long> > res(getRows(), vector<long>(other.getColumns(),0));
for(unsigned int i=0; i < res.size(); i++)
for(unsigned int j=0; j < res[i].size(); j++)
for(unsigned int k = 0; k < other.getRows(); k++)
res[i][j] += (*this)(i,k)*other(k,j);
return PTMatrix(res, false);
}
PTMatrix PTMatrix::operator*=(const PTMatrix& other){ return (*this) = (*this)*other; }
//mult by constant
PTMatrix PTMatrix::operator*(unsigned int num) const {
PTMatrix copy = *this;
for(unsigned int i=0, sz1 = matrix.size(); i < sz1; i++)
for(unsigned int j=0, sz2 = matrix[i].size(); j < sz2; j++)
copy[i][j] *= num;
return copy;
}
PTMatrix PTMatrix::operator*=(unsigned int num) { return ((*this) = (*this)*num); }
PTMatrix PTMatrix::operator+(const PTMatrix& other) const{
//check sizes
if(matrix.size() != other.matrix.size() || matrix[0].size() != other.matrix[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned int rows = getRows(), cols = getColumns();
vector<vector<long> > res = matrix;
for(unsigned int i=0; i < rows; i++)
for(unsigned int j=0; j < cols; j++)
res[j][i] += other[j][i];
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator+=(const PTMatrix& other){ return (*this) = (*this)+other; }
PTMatrix PTMatrix::operator-(const PTMatrix& other) const{
//check sizes
if(matrix.size() != other.matrix.size() || matrix[0].size() != other.matrix[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned int rows = getRows(), cols = getColumns();
vector<vector<long> > res = matrix;
for(unsigned int i=0; i < rows; i++)
for(unsigned int j=0; j < cols; j++)
res[j][i] -= other[j][i];
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator-=(const PTMatrix& other){ return (*this) = (*this)-other; }
PTMatrix PTMatrix::transpose() const{
MatSize transposedSize = this->getMatrixSize().getTransposed();
vector<vector<long>> transposedMatrix(transposedSize.rows, vector<long>(transposedSize.columns, 0));
for(int i = 0; i < transposedSize.rows; i++)
for(int j = 0; j < transposedSize.columns; j++)
transposedMatrix[i][j] = (*this)(j,i);
return PTMatrix(transposedMatrix, false);
}
PTMatrix PTMatrix::operator>(const PTMatrix& other) const {
//check sizes
if(matrix.size() != other.size() || matrix[0].size() != other[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned sz1 = matrix[0].size(), sz2 = matrix.size();
vector<vector<long> > res(sz1, vector<long>(sz2));
for(unsigned int i=0; i < sz1; i++)
for(unsigned int j=0; j < sz2; j++)
res[j][i] = matrix[j][i] > other[j][i];
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator<(const PTMatrix& other) const {
//check sizes
if(matrix.size() != other.size() || matrix[0].size() != other[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned sz1 = matrix[0].size(), sz2 = matrix.size();
vector<vector<long> > res(sz1, vector<long>(sz2));
for(unsigned int i=0; i < sz1; i++)
for(unsigned int j=0; j < sz2; j++)
res[j][i] = matrix[j][i] < other[j][i];
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator>=(const PTMatrix& other) const {
//check sizes
if(matrix.size() != other.size() || matrix[0].size() != other[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned sz1 = matrix[0].size(), sz2 = matrix.size();
vector<vector<long> > res(sz1, vector<long>(sz2));
for(unsigned int i=0; i < sz1; i++)
for(unsigned int j=0; j < sz2; j++)
res[j][i] = matrix[j][i] >= other[j][i];
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator<=(const PTMatrix& other) const {
//check sizes
if(matrix.size() != other.size() || matrix[0].size() != other[0].size())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
unsigned sz1 = matrix[0].size(), sz2 = matrix.size();
vector<vector<long> > res(sz1, vector<long>(sz2));
for(unsigned int i=0; i < sz1; i++)
for(unsigned int j=0; j < sz2; j++)
res[j][i] = matrix[j][i] <= other[j][i];
return PTMatrix(res, true);
}
bool PTMatrix::operator==(const PTMatrix& other) const{
if(matrix.size() != other.size() || matrix[0].size() != other[0].size())
return false;
for(unsigned int i=0, sz1 = getRows() ; i < sz1; i++)
for(unsigned int j=0, sz2 = getColumns(); j < sz2; j++)
if((*this)(i,j) != other(i,j))
return false;
return true;
}
bool PTMatrix::operator!=(const PTMatrix& other) const { return !(*this == other); }
PTMatrix PTMatrix::operator%(unsigned int p) const{
vector<vector<long> > res = matrix;
for(unsigned int i=0; i< size(); i++)
for(unsigned int j=0; j < matrix[i].size(); j++)
res[i][j] %= p;
return PTMatrix(res, true);
}
PTMatrix PTMatrix::operator%=(unsigned int p) { return (*this) = (*this)%p; }
PTMatrix PTMatrix::mulWithMod(const PTMatrix& other, long p) const {
//check sizes
if(getColumns() != other.getRows())
throw MatricesSizesNotMatch(getMatrixSize(), other.getMatrixSize());
vector<vector<long> > res(getRows(), vector<long>(other.getColumns(),0));
for(unsigned int i=0; i < res.size(); i++)
for(unsigned int j=0; j < res[i].size(); j++)
for(unsigned int k = 0; k < other.getRows(); k++){
res[i][j] += (*this)(i,k)*other(k,j);
res[i][j] %= p;
}
return PTMatrix(res, false);
}
void PTMatrix::debugPrintDiagonalMatrixVector(){
for(int i = 0; i < this->size(); i++)
{
vector<long> vec = this->matrix[i];
cout << "vec #" << i << ": [";
for(int j=0; j < vec.size(); j++)
cout << vec[j] << " ";
cout << "]" << endl;
}
}
/* --------------------- EncryptedMatrix class -------------*/
EncryptedMatrix::EncryptedMatrix(const vector<Ctxt>& encMatrix, const MatSize& origSize): matrix(encMatrix), matrixSize(origSize) {}
PTMatrix EncryptedMatrix::decrypt(const EncryptedArray& ea, const FHESecKey& secretKey) const {
vector<vector<long> > ret(matrix.size());
for(unsigned int i=0; i < matrix.size(); i++){
ea.decrypt(matrix[i], secretKey, ret[i]);
ret[i].resize(matrixSize.rows, 0);
}
return PTMatrix(ret, true);
}
PTMatrix EncryptedMatrix::decrypt(const FHESecKey& secretKey) const {
EncryptedArray ea(secretKey.getContext());
return decrypt(ea, secretKey);
}
//matrix multyplcation!
EncryptedMatrix EncryptedMatrix::operator*(const EncryptedMatrix& other) const
{
//check sizes
if(!matrixSize.canMultiply(other.matrixSize))
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop
EncryptedArray ea(vec.getContext());
bool squares = getMatrixSize().isSquare() && other.getMatrixSize().isSquare() && getRows()==ea.size(); //Use the square matrices formula (much faster)
vector<Ctxt> res;
int n = getRows(), m = getColumns(), k = other.getColumns(); //sizes: A(this):n*m, B(other):m*k
for(int i=0; i < k; i++){
Ctxt C(vec.getPubKey());
for(int j=0; j< m; j++){
//work by my formula: C_i = Sig j= 0 to n-1 [ A_i * (B_i-j%n <<< j) ]
Ctxt B = other[myModulu(i-j,k)]; //B_i-j%n
if(squares)
ea.rotate(B, -j); //rotate j left, B_i-j%n <<< j (or -j right)
else{
//The general formula
ea.shift(B, -j); //shift j left
int length = m-j;
for(int itter=1;length < n; itter++){
Ctxt toChain = other[myModulu(i-j+(itter*m),k)];
ea.shift(toChain, length); //shift length to right
B += toChain;
length+=m;
}
}
B *= matrix[j]; //* A_j
C += B;
}
res.push_back(C);
}
return EncryptedMatrix(res, matrixSize*other.matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator*=(const EncryptedMatrix& other){ return ((*this) = (*this)*other); }
//mult by constant
EncryptedMatrix EncryptedMatrix::operator*(unsigned int num) const {
if(num == 1)
return *this;
if(num == 0) //return 0's matrix in the same size
return EncryptedMatrix(vector<Ctxt>(matrix.size(), Ctxt(matrix[0].getPubKey())), getMatrixSize());
EncryptedMatrix res = *this;
for(unsigned int i=0, sz = matrix.size(); i < sz; i++)
res[i].multByConstant(to_ZZX(num));
return res;
}
EncryptedMatrix EncryptedMatrix::operator*=(unsigned int num) { return ((*this) = (*this)*num); }
//matrices addition
EncryptedMatrix EncryptedMatrix::operator+(const EncryptedMatrix& other) const{
if(!matrixSize.canAdd(other.getMatrixSize()))
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
vector<Ctxt> ret = matrix;
for(unsigned int i=0, len = matrix.size(); i < len; i++)
ret[i] += other[i];
return EncryptedMatrix(ret, matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator+=(const EncryptedMatrix& other){ return ((*this) = (*this)+other); }
EncryptedMatrix EncryptedMatrix::operator-(const EncryptedMatrix& other) const{
if(!matrixSize.canAdd(other.matrixSize))
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
vector<Ctxt> ret = matrix;
for(unsigned int i=0, len = matrix.size(); i < len; i++)
ret[i] -= other.matrix[i];
return EncryptedMatrix(ret, matrixSize);
}
/*
* Square Formula : B_i = A_(-i mod n) <<< i
* NonSquare Formula : TODO: formile the formula
*/
EncryptedMatrix EncryptedMatrix::transpose() const{
EncryptedArray ea(matrix[0].getContext());
const int fullSize = (int)ea.size();
int gap = fullSize - (int)this->matrixSize.rows;
bool isSquare = this->matrixSize.isSquare();
vector<Ctxt> result;
for(int i = 0; i < this->matrixSize.rows; i++){
Ctxt b_i(this->matrix[myModulu(-i,this->matrixSize.columns)]);
if(isSquare){
if(gap){
Ctxt rightPart(b_i);
ea.shift(b_i, -i);
ea.shift(rightPart, fullSize - i);
ea.shift(rightPart, -gap);
b_i += rightPart;
}
else{
ea.rotate(b_i, -i); //rotate i left
}
}
else{
ea.shift(b_i, -i); //shift i left
int countItems = this->matrixSize.rows - i;
for(int j = 1 ; countItems < this->matrixSize.columns; j++){ //Probably one of these parameters wrong
Ctxt addition(this->matrix[myModulu(-i + j*this->matrixSize.rows,this->matrixSize.columns)]);
ea.shift(addition, countItems); //shift countItems right
b_i += addition;
countItems += this->matrixSize.rows;
}
}
result.push_back(b_i);
}
return EncryptedMatrix(result, this->matrixSize.getTransposed());
}
//comparison operator (>, <, >= and <=)
/*NOTE: WORKING ONLY FOR BINARY FIELD (p=2)
Concept: For any 2 binary encrypted vectors A and B, A[i] > B[i] for any i iff A[i] = 1 and B[i] =0
The operators in binary fields are:
operator* === AND
operator+ === XOR
+ 1 === NOT
*/
EncryptedMatrix EncryptedMatrix::operator>(const EncryptedMatrix& other) const
//A[i] > B[i] ==> A[i] == 1 && B[i] == 0 ==> A[i] & !B[i] ===> A*(B+1)
{
if(!matrixSize.canAdd(other.matrixSize)) //check sizes
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop
if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field
throw NotBinaryField();
EncryptedArray ea(vec.getContext());
Ctxt not_ctxt = getNotVector(ea, vec.getPubKey());
vector<Ctxt> res = other.matrix;
for(unsigned int i=0, sz = res.size(); i < sz; i++){
res[i] += not_ctxt;
res[i] *= matrix[i];
}
return EncryptedMatrix(res, matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator<(const EncryptedMatrix& other) const
//A[i] < B[i] ==> A[i] == 0 && B[i] == 1 ==> !A[i] & B[i] ===> (A+1)*B
{
if(!matrixSize.canAdd(other.matrixSize)) //check sizes
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop
if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field
throw NotBinaryField();
EncryptedArray ea(vec.getContext());
Ctxt not_ctxt = getNotVector(ea, vec.getPubKey());
vector<Ctxt> res = matrix;
for(unsigned int i=0, sz = res.size(); i < sz; i++){
res[i] += not_ctxt;
res[i] *= other[i];
}
return EncryptedMatrix(res, matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator>=(const EncryptedMatrix& other) const
//A[i] >= B[i] ==> !(A[i] < B[i]) => !(!A[i] & B[i]) ===> ((A+1)*B)+1
{
if(!matrixSize.canAdd(other.matrixSize)) //check sizes
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop
if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field
throw NotBinaryField();
EncryptedArray ea(vec.getContext());
Ctxt not_ctxt = getNotVector(ea, vec.getPubKey());
vector<Ctxt> res = matrix;
for(unsigned int i=0, sz = res.size(); i < sz; i++){
res[i] += not_ctxt;
res[i] *= other[i];
res[i] += not_ctxt;
}
return EncryptedMatrix(res, matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator<=(const EncryptedMatrix& other) const
//A[i] <= B[i] ==> !(A[i] > B[i]) => !(A[i] & !B[i]) ===> (A*(B+1))+1
{
if(!matrixSize.canAdd(other.matrixSize)) //check sizes
throw MatricesSizesNotMatch(matrixSize, other.matrixSize);
Ctxt vec = matrix[0]; //save it for faster vec.getPubKey() in the loop
if(vec.getPtxtSpace()!= 2) //check that the computations is on binary field
throw NotBinaryField();
EncryptedArray ea(vec.getContext());
Ctxt not_ctxt = getNotVector(ea, vec.getPubKey());
vector<Ctxt> res = other.matrix;
for(unsigned int i=0, sz = res.size(); i < sz; i++){
res[i] += not_ctxt;
res[i] *= matrix[i];
res[i] += not_ctxt;
}
return EncryptedMatrix(res, matrixSize);
}
EncryptedMatrix EncryptedMatrix::operator-=(const EncryptedMatrix& other){ return ((*this) = (*this)-other); }
bool EncryptedMatrix::operator==(const EncryptedMatrix& other) const{
if(matrixSize != matrixSize)
return false;
for(unsigned int i=0, len= matrix.size(); i < len; i++)
if(matrix[i] != other.matrix[i]) //base on Ctxt::operator==
return false;
return true;
}
bool EncryptedMatrix::operator!=(const EncryptedMatrix& other) const { return !(*this == other); }
//matrix multyplication by vector. NOTE: this return a column vector! so don't use it to create a matrix (unless you want it to be column vectors matrix)
Ctxt EncryptedMatrix::operator*(const Ctxt& vec) const{
EncryptedArray ea(vec.getContext());
Ctxt result(vec.getPubKey());
int len = matrix.size();
//TODO: Still not perfectlly working
Ctxt fixedVec = vec;
if(ea.size() != getRows()) //Fix the problem that if the size of the vector is not nslots, the zero padding make the rotation push zeros to the begining of the vector
{
//replicate the vector to fill instead of zero padding
for(unsigned int length =getRows(); length < ea.size(); length*=2){
Ctxt copyVec = fixedVec;
ea.shift(copyVec, length); //shift length to right
fixedVec+=copyVec;
}
}
for(int i=0; i < len; i++)
{
Ctxt rotatedVec(fixedVec); //copy vec
ea.rotate(rotatedVec, -i); //rotate it i right (-i left)
rotatedVec *= matrix[i];
result += rotatedVec;
}
return result;
}
Ctxt& EncryptedMatrix::operator[](unsigned int i) { return matrix[i]; }
const Ctxt& EncryptedMatrix::operator[](unsigned int i) const { return matrix[i]; }
unsigned int EncryptedMatrix::getRows() const{ return getMatrixSize().rows; }
unsigned int EncryptedMatrix::getColumns() const { return getMatrixSize().columns; }
MatSize EncryptedMatrix::getMatrixSize() const { return matrixSize; }
//Debug operations
EncryptedMatrix EncryptedMatrix::debugMul(const EncryptedMatrix& other, bool logFile, bool relinearation) const{
//check sizes
if(!matrixSize.canMultiply(other.matrixSize)){
cout << "ERROR! The matrices must be with suitable sizes!" << endl;
return *this; //return this
}
ofstream* log = NULL;
if(logFile)
log = new ofstream("logFile.txt");
Ctxt vec(matrix[0]); //save it for faster vec.getPubKey() in the loop
EncryptedArray ea(vec.getContext());
bool squares = getMatrixSize().isSquare() && other.getMatrixSize().isSquare() && getRows()==ea.size(); //Use the square matrices formula (much faster)
cout << "Square matrices? " << squares << endl;
if(logFile)
(*log) << "Square matrices? " << squares << endl;
int n = getRows(), m = getColumns(), k = other.getColumns(); //sizes: A(this):n*m, B(other):m*k
vector<Ctxt> res(m, Ctxt(vec.getPubKey()));
for(int i=0; i < k; i++){
for(int j=0; j< m; j++){
if(logFile)
(*log) << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << endl;
//work by my formula: C_i = Sig j= 0 to n-1 [ A_i * (B_i-j%n <<< j) ]
Ctxt B(other[myModulu(i-j,k)]); //B_i-j%n
cout.flush();
cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - rotate \r";
if(squares)
ea.rotate(B, n-j); //rotate j left, B_i-j%n <<< j (or -j right)
else{
//The general formula
ea.shift(B, -j); //shift j left
int length = m-j;
for(int itter=1;length < n; itter++){
Ctxt toChain(other[myModulu(i-j+(itter*m),k)]);
ea.shift(toChain, length); //shift length to right
B += toChain;
length+=m;
}
}
cout.flush();
cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - mul \r";
if(relinearation)
B.multiplyBy(matrix[j]); //* A_j using relinearation
else
B *= matrix[j]; //* A_j
cout.flush();
cout << "i: " << i+1 << " of " << k << ", j: " << j+1 << " of " << m << " - add \r";
res[i] += B;
}
if(logFile)
(*log) << "Done with i=" << i+1 << endl;
}
cout.flush();
if(logFile){
(*log) << "DONE!!!!";
(*log).close();
delete log;
}
return EncryptedMatrix(res, matrixSize*other.matrixSize);
}
EncryptedMatrix EncryptedMatrix::debugAdd(const EncryptedMatrix& other, bool logFile) const{
//check sizes
if(matrixSize != other.matrixSize){
cout << "ERROR! The matrices must be with suitable sizes!" << endl;
return *this; //return this
}
ofstream* log = NULL;
if(logFile)
log = new ofstream("logFile.txt");
vector<Ctxt> res = matrix;
for(unsigned int i=0, sz = matrix.size(); i < sz; i++){
if(logFile)
(*log) << "i: " << i+1 << endl;
cout << "i: " << i+1 << " \r";
res[i] += other[i];
cout.flush();
if(logFile)
(*log) << "Done with i=" << i+1 << endl;
}
if(logFile){
(*log) << "DONE!!!!";
(*log).close();
delete log;
}
return EncryptedMatrix(res, matrixSize);
}