-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprivateQTL_cp.cpp
More file actions
1507 lines (1442 loc) · 54.1 KB
/
privateQTL_cp.cpp
File metadata and controls
1507 lines (1442 loc) · 54.1 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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "privateQTL_cp.h"
const static Eigen::IOFormat TSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, "\t", "\n");
void mpc::writeEigenToTSV(Eigen::Matrix <double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& mat, const string& name)
{
trace("mpc::writeEigenToTSV");
string filename = "/gpfs/commons/groups/gursoy_lab/aychoi/eqtl/mpc/securesort/output/" + name + ".tsv";
ofstream file(filename);
if (file.is_open()) {
file << mat.format(TSVFormat);
file.close();
std::cout << name + " matrix successfully written to TSV file.\n";
} else {
std::cout << "Error opening the file." << std::endl;
}
}
double cal_accuracy(vector<double>& predicted, string& filename, int N)
{
trace("cal_accuracy");
vector<double> actual = getRowFromMatrixFile(filename,N);
// vector<double> actual = CSVtoVector(filename);
// cout << string("row: "+to_string(N)+", numCol: "+to_string(numCol)+"\n");
if (predicted.size() != actual.size()) {
cout << "predicted size: " + to_string(predicted.size()) << endl;
cout << "actual size: " + to_string(actual.size()) << endl;
// throw runtime_error("Vector sizes do not match");
}
double sumSquaredDiff = 0.0;
for (size_t i = 0; i < predicted.size(); ++i) {
double diff = predicted[i] - actual[i];
sumSquaredDiff += diff * diff;
}
double mse = sumSquaredDiff / predicted.size();
double rmse = sqrt(mse);
// cout << string("RMSE: " + to_string(rmse)) << endl;
auto max = max_element(actual.begin(), actual.end());
auto min = min_element(actual.begin(), actual.end());
double normalized = *max - *min;
return 1.0 - rmse/normalized;
}
bool mpc::initialize(int pid, string ownerIP, int ownerPort, int toOwnerPort, string address1, int recPort1, int sendPort1, string address2, int recPort2, int sendPort2)
{
trace("mpc::initialize");
this->pid = pid;
globalprng.SetSeed(commonSeed);
if (!setupChannels(ownerIP, ownerPort, toOwnerPort, address1, recPort1, sendPort1, address2, recPort2, sendPort2))
{
cout << "Network channel failed.\n";
}
if (!setupSeeds())
{
cout << "PRNG setup failed.\n";
}
this->dataowner.recv(this->p);
if (this->pid == 0){
cout << "P: " << this->p << endl;
}
ZZ_p::init(to_ZZ(this->p));
this->p = p;
return true;
}
bool mpc::setupChannels(string ownerIP, int ownerPort, int toOwnerPort, string address1, int recPort1, int sendPort1, string address2, int recPort2, int sendPort2)
{
trace("mpc::setupChannels");
Endpoint p_owner(ios, ownerIP, ownerPort, EpMode::Client);
Endpoint ownersend(ios, ownerIP, toOwnerPort, EpMode::Server);
Endpoint eprec1(ios, address1, recPort1, EpMode::Client);
Endpoint eprec2(ios, address2, recPort2, EpMode::Client);
Endpoint epsend1(ios, address1, sendPort1, EpMode::Server);
Endpoint epsend2(ios, address2, sendPort2, EpMode::Server);
this->dataowner = p_owner.addChannel();
this->toOwner = ownersend.addChannel();
this->fromPlus = eprec1.addChannel();
this->fromMinus = eprec2.addChannel();
this->toPlus = epsend1.addChannel();
this->toMinus = epsend2.addChannel();
// cout << "Established channels with the computing parties and data owner.\n";
// p_owner.stop();
// ownersend.stop();
// eprec1.stop();
// eprec2.stop();
// epsend1.stop();
// epsend2.stop();
// ios.stop();
return true;
}
bool mpc::setupSeeds()
{
trace("mpc::setupSeeds");
// cout << "setting up shared seeds within parties..\n";
// lower number pid party sends prng seed to higher number pid party
// Check if they already share a prng
auto it = this->seedpair.find((this->pid + 1) % 3);
auto it2 = this->seedpair.find((this->pid + 2) % 3);
if (it != this->seedpair.end())
{
cout << "Party " << this->pid << " already share a prng with party " << (this->pid + 1) % 3 << endl;
return false;
}
if (it2 != this->seedpair.end())
{
cout << "Party " << this->pid << " already share a prng with party " << (this->pid + 2) % 3 << endl;
return false;
}
try
{
// this->localprng = new PRNG(oc::toBlock(this->pid)); //NEEDS CHANGE
this->localprng = std::make_unique<PRNG>(oc::toBlock(this->pid));
uint64_t plusSeed = this->localprng->get<uint64_t>();
this->toPlus.send(plusSeed);
uint64_t minusSeed;
this->fromMinus.recv(minusSeed);
// PRNG *wPlus = new PRNG(oc::toBlock(plusSeed));
// PRNG *wMinus = new PRNG(oc::toBlock(minusSeed));
this->seedpair.insert({(this->pid + 1) % 3, std::make_unique<PRNG>(oc::toBlock(plusSeed))});
this->seedpair.insert({(this->pid + 2) % 3, std::make_unique<PRNG>(oc::toBlock(minusSeed))});
/// add prng to each party map
// this->seedpair.insert({(this->pid + 1) % 3, wPlus});
// this->seedpair.insert({(this->pid + 2) % 3, wMinus});
}
catch (const std::exception &e)
{
cout << "except\n";
cout << e.what() << std::endl;
}
return true;
}
void mpc::ready()
{
trace("mpc::ready");
bool empty = areVectorsEmpty();
// if (empty)
// cout << string(to_string(this->pid) + " ready to receive.\n");
int ready = static_cast<int>(empty);
this->toOwner.send(ready);
}
void mpc::receiveSecrets()
{
trace("mpc::receiveSecrets");
vector<uint64_t> dest;
this->dataowner.recv(dest);
this->n = dest[0]; //number of secrets
this->lk = dest[1]; //number of bits
this->inv = dest[3]; //inv
vector<uint64_t> result;
try
{
// receiving shares;
this->dataowner.recv(result);
vector<ZZ_p> temp(result.size());
temp = convVec(result);
// vector<ZZ_p> temp(result.begin(), result.end());
swap(this->shares, temp);
// cout <<"secrets received.\n";
bool prelim = this->identity.empty() && this->zscores.empty();
int ready = static_cast<int>(prelim);
this->toOwner.send(ready);
if(prelim)
{
// cout << string(to_string(this->pid) + " ready to receive identity and zscores.\n");
//receiving identity shares
vector<uint64_t> identity_result;
this->dataowner.recv(identity_result);
vector<ZZ_p> identity_temp(identity_result.begin(), identity_result.end());
swap(this->identity, identity_temp);
// receiving zscore shares
double shiftsize;
this->dataowner.recv(shiftsize);
this->shiftsize=shiftsize;
vector<uint64_t> zscore_result;
this->dataowner.recv(zscore_result);
vector<ZZ_p> zscore_temp(zscore_result.begin(), zscore_result.end());
swap(this->zscores, zscore_temp);
}
}
catch (const exception &e)
{
cout << "except\n";
cout << e.what() << endl;
}
// cout <<this->pid <<endl;
// print_vector(this->identity);
// cout << string(to_string(this->pid) + " Secrets received.\n");
}
// template class std::vector<ZZ_p>;
void mpc::assertSize(vector<ZZ_p> pi, string tag) {
// trace("mpc::assertSize");
for (ZZ_p z : pi) {
uint64_t value = conv<uint64_t>(z);
if (value > pi.size() || value < 1) {
string output = string("[" + to_string(this->pid) + "][" + tag + "] Error! value: " + to_string(value) + " size: " + to_string(pi.size()) + "\n");
cout << output;
throw logic_error("["+tag+"]: permutation is bigger than vector size.");
}
}
}
vector<uint64_t> mpc::apply_plaintext_perm(vector<uint64_t> rho, vector<uint64_t> sigma)
{
trace("mpc::apply_plaintext_perm");
//Applying rho on sigma rho o sigma
if (rho.size() != sigma.size())
throw invalid_argument("This is regular apply permutation; both pis should be same size.");
vector<uint64_t> appliedvec(rho.size());
for (int i=0; i < sigma.size(); i++)
{
appliedvec[rho[i]-1] = sigma[i];
}
return appliedvec;
}
vector<ZZ_p> mpc::Frand(uint64_t bufferSize)
{
// trace("mpc::Frand");
if (bufferSize <= 1)
{
throw std::invalid_argument("bufferSize must be positive");
}
auto plus_it = this->seedpair.find((this->pid + 1) % 3);
PRNG &plus_PRNG = *(plus_it->second);
auto minus_it = this->seedpair.find((this->pid + 2) % 3);
PRNG &minus_PRNG = *(minus_it->second);
vector<uint64_t> pi(2*bufferSize);
for (uint64_t i = 0; i < bufferSize; i++)
{
pi[i*2+0] = i + 1;
pi[i*2+1] = i + 1;
}
for (uint64_t i = bufferSize - 1; i >= 1; i--)
{
// random index chosen to be swapped
uint64_t j = minus_PRNG.get<uint64_t>() % (i + 1);
uint64_t temp = pi[i*2+0];
pi[i*2+0] = pi[j*2+0];
pi[j*2+0] = temp;
uint64_t k = plus_PRNG.get<uint64_t>() % (i + 1);
uint64_t temp2 = pi[i*2+1];
pi[i*2+1] = pi[k*2+1];
pi[k*2+1] = temp2;
}
vector<ZZ_p> ZZ_pi(pi.begin(), pi.end());
assertSize(ZZ_pi, "Frand");
return ZZ_pi;
}
vector<ZZ_p> mpc::reveal(vector<ZZ_p>& pi, bool isperm)
{
// cout <<"reveal entered.\n";
vector<uint64_t> share1;
vector<uint64_t> share2;
for (int i=0; i<pi.size(); i+=2)
{
uint64_t r = conv<uint64_t>(pi[i]);
uint64_t q = conv<uint64_t>(pi[i+1]);
if(r >= this->p) {
cout << "r too big: " << r << endl;
}
if(q >= this->p) {
cout << "q too big: " << q << endl;
}
share1.push_back(r);
share2.push_back(q);
}
this->toPlus.send(share1);
this->toMinus.send(share2);
vector<uint64_t> receivedMinus, receivedPlus;
this->fromMinus.recv(receivedMinus);
this->fromPlus.recv(receivedPlus);
if (receivedMinus != receivedPlus)
{
cout << "error! in " << this->pid << endl;
print_vector(receivedMinus);
print_vector(receivedPlus);
try
{
throw logic_error("received inputs do not match."); // <-- THIS IS SOMETIMES THROWN BUT NOT CAUGHT
}
catch (const std::string& ex) {
std::cerr << "Exception occurred: " << ex << std::endl;
}
close();
}
vector<ZZ_p> reconstructed;
vector<uint64_t> final(share1.size());
vector<uint64_t> temp(share1.size());
if (isperm)
{
if (this->pid==0)
{
temp = apply_plaintext_perm(share2, share1);
final = apply_plaintext_perm(receivedMinus, temp);
}
else if (this->pid==1)
{
temp=apply_plaintext_perm(share1, receivedMinus);
final=apply_plaintext_perm(share2, temp);
}
else
{
temp=apply_plaintext_perm(receivedMinus,share2);
final=apply_plaintext_perm(share1, temp);
}
reconstructed = convVec(final);
}
else
{
for (int i=0; i<receivedMinus.size(); i++)
{
if (receivedMinus[i] >= this->p) {
cout << "too big! Minus: " << receivedMinus[i] << endl;
}
reconstructed.push_back(conv<ZZ_p>(receivedMinus[i])+conv<ZZ_p>(share1[i])+conv<ZZ_p>(share2[i]));
// reconstructed.push_back(conv<ZZ_p>(receivedMinus[i]));
uint64_t result = conv<uint64_t>(reconstructed[i]);
if (result >= this->p) {
cout << "too big! Result: " << result << endl;
}
}
}
return reconstructed;
}
void mpc::reshare(vector<ZZ_p>& shares, int reshareID)
{
// trace("mpc::reshare");
vector<ZZ_p> randoms(3);
vector<uint64_t> sendvec;
if (reshareID == (this->pid + 1) % 3) // share to plus
{
auto minus_it = this->seedpair.find((this->pid + 2) % 3);
PRNG &minus_PRNG = *(minus_it->second);
for (int i=0; i<2; i++)
{
randoms[i] = to_ZZ_p(minus_PRNG.get<uint64_t>());
}
randoms[2] = -randoms[0]-randoms[1];
for (int j=0; j<shares.size()/2; j++)
{
shares[2*j]+=randoms[this->pid];
shares[2*j+1]+=randoms[(this->pid +1)%3];
sendvec.push_back(conv<uint64_t>(shares[2*j+1]));
// this->toPlus.send(conv<uint64_t>(shares[2*j+1]));
}
this->toPlus.send(sendvec);
}
else if (reshareID == (this->pid + 2) % 3) //share to minus
{
auto plus_it = this->seedpair.find((this->pid + 1) % 3);
PRNG &plus_PRNG = *(plus_it->second);
for (int i=0; i<2; i++)
{
randoms[i] = to_ZZ_p(plus_PRNG.get<uint64_t>());
}
randoms[2] = -randoms[0]-randoms[1];
for (int j=0; j<shares.size()/2; j++)
{
shares[2*j]+=randoms[this->pid];
shares[2*j+1]+=randoms[(this->pid +1)%3];
sendvec.push_back(conv<uint64_t>(shares[2*j]));
}
this->toMinus.send(sendvec);
}
else
{
vector<ZZ_p> newshare(shares.size());
vector<uint64_t> minus(shares.size()/2), plus(shares.size()/2);
this->fromMinus.recv(minus);
this->fromPlus.recv(plus);
for (int i=0; i<shares.size()/2; i++)
{
newshare[2*i] = to_ZZ_p(minus[i]);
newshare[2*i+1] = to_ZZ_p(plus[i]);
// this->fromMinus.recv(newshare[2*i]);
// this->fromPlus.recv(newshare[2*i+1]);
}
// vector<ZZ_p> temp(newshare.begin(), newshare.end());
shares.swap(newshare);
}
}
void mpc::reshareM(vector<vector<ZZ_p>>& shares, int reshareID)
{
trace("mpc::reshareM");
vector<ZZ_p> randoms(3);
vector<vector<uint64_t>> sendvec(shares.size(), vector<uint64_t>(shares[0].size()));
if (reshareID == (this->pid + 1) % 3) // share to plus
{
auto minus_it = this->seedpair.find((this->pid + 2) % 3);
PRNG &minus_PRNG = *(minus_it->second);
for (int i=0; i<2; i++)
{
randoms[i] = to_ZZ_p(minus_PRNG.get<uint64_t>());
}
randoms[2] = -randoms[0]-randoms[1];
for (int i=0; i<shares.size(); i++)
{
for (int j=0; j<shares[0].size()/2; j++)
{
shares[i][2*j]+=randoms[this->pid];
shares[i][2*j+1]+=randoms[(this->pid +1)%3];
sendvec[i][j] = conv<uint64_t>(shares[i][2*j+1]);
}
this->toPlus.send(sendvec[i]);
}
}
else if (reshareID == (this->pid + 2) % 3) //share to minus
{
auto plus_it = this->seedpair.find((this->pid + 1) % 3);
PRNG &plus_PRNG = *(plus_it->second);
for (int i=0; i<2; i++)
{
randoms[i] = to_ZZ_p(plus_PRNG.get<uint64_t>());
}
randoms[2] = -randoms[0]-randoms[1];
for (int i=0; i<shares.size(); i++)
{
for (int j=0; j<shares[0].size()/2; j++)
{
shares[i][2*j]+=randoms[this->pid];
shares[i][2*j+1]+=randoms[(this->pid +1)%3];
sendvec[i][j] = conv<uint64_t>(shares[i][2*j]);
}
this->toMinus.send(sendvec[i]);
}
}
else
{
vector<vector<ZZ_p>> newshare(shares.size(), vector<ZZ_p>(shares[0].size()));
for(int i=0; i<shares.size(); i++)
{
vector<uint64_t> minus(shares[0].size());
vector<uint64_t> plus(shares[0].size());
this->fromMinus.recv(minus);
this->fromPlus.recv(plus);
for(int j=0; j<shares[0].size()/2; j++)
{
newshare[i][2*j] = to_ZZ_p(minus[j]);
newshare[i][2*j+1] = to_ZZ_p(plus[j]);
}
}
// vector<vector<ZZ_p>> temp(newshare.begin(), newshare.end());
shares.swap(newshare);
}
}
//is adding alpha beta gamma necessary?
vector<ZZ_p> mpc::Fmult(vector<ZZ_p> k_i, vector<ZZ_p> s_i)
{
trace("mpc::Fmult");
auto minus_it = this->seedpair.find((this->pid + 2) % 3);
auto plus_it = this->seedpair.find((this->pid + 1) % 3);
PRNG &minus_PRNG = *(minus_it->second);
PRNG &plus_PRNG = *(plus_it->second);
vector<ZZ_p> t_i(2);
ZZ_p ri = k_i[0]*s_i[0] + k_i[1]*s_i[0] + k_i[0]*s_i[1];
ri+=to_ZZ_p(minus_PRNG.get<uint64_t>()); // result + r1 - r2;
ri-=to_ZZ_p(plus_PRNG.get<uint64_t>());
t_i[0]=ri;
this->toMinus.send(conv<uint64_t>(ri));
uint64_t received_data;
this->fromPlus.recv(received_data);
conv(t_i[1], received_data);
return t_i;
}
vector<ZZ_p> mpc::genbitperm(vector<ZZ_p> &keybit)
{
trace("mpc::genbitperm");
vector<ZZ_p> f0(keybit.size()), f1(keybit.size()), s0(keybit.size()), s1(keybit.size());
vector<ZZ_p> s(2, to_ZZ_p(0));
vector<ZZ_p> p;
f1 = keybit;
for (int i=0; i<keybit.size()/2; i++)
{
f0[2*i] = this->inv-keybit[2*i];
f0[2*i+1] = this->inv-keybit[2*i+1];
s[0]+=f0[2*i];
s[1]+=f0[2*i+1];
s0[2*i] = s[0];
s0[2*i+1] = s[1];
}
for (int i=0; i<keybit.size()/2; i++)
{
s[0]+=f1[2*i];
s[1]+=f1[2*i+1];
s1[2*i] = s[0];
s1[2*i+1] = s[1];
}
vector<ZZ_p> t;
for (int i=0; i <keybit.size()/2; i++)
{
vector<ZZ_p> sminus(2);
vector<ZZ_p> ti(2);
sminus[0] = s1[2*i] - s0[2*i];
sminus[1] = s1[2*i+1] - s0[2*i+1];
vector<ZZ_p> ki(keybit.begin()+2*i, keybit.begin()+2*(i+1));
ti = Fmult(ki, sminus);
t.insert(t.end(), ti.begin(), ti.end());
}
for (int m=0; m<keybit.size(); m++)
{
p.push_back(s0[m]+t[m]);
}
return p;
}
vector<ZZ_p> mpc::inversePerm(vector<ZZ_p> pi)
{
trace("mpc::inversePerm");
assertSize(pi, "inversePerm");
vector<uint64_t> arr2(pi.size());
vector<ZZ_p> inverse(pi.size());
for (uint64_t i = 0; i < pi.size(); i++)
arr2[conv<uint64_t>(pi[i]) - 1] = i + 1;
for (uint64_t i = 0; i < pi.size(); i++)
{
inverse[i] = conv<ZZ_p>(arr2[i]);
}
return inverse;
}
void mpc::apply_perm_local(bool participate, vector<ZZ_p> &v, vector<ZZ_p> &pi)
{
if (participate)
{
for (ZZ_p z : pi)
{
uint64_t value = conv<uint64_t>(z);
if (value > pi.size())
{
cout << "apply_perm_local." << endl;
cout << "value: " << value << endl;
cout << "size of vector: " << pi.size() << endl;
throw logic_error("permutation is bigger than vector size.");
}
}
if (pi.size() != v.size()/2)
throw std::invalid_argument("local permutation should be half the size of shared vector");
if (v.size() % 2 != 0)
throw invalid_argument("v size is not divisible by 2.");
vector<ZZ_p> v2(v.size());
for (uint64_t i = 0; i < v.size()/2; i++)
{
if (2 * i + 1 >= v.size())
{
cout << "i too high" << i << "size: " << v.size() << endl;
}
try
{
uint64_t idx1 = conv<uint64_t>((pi[i])-1)*2;
uint64_t idx2 = conv<uint64_t>((pi[i])-1)*2+1;
v2[idx1] =v[2*i];
v2[idx2]=v[2*i+1];
}
catch (const std::exception &e)
{
cerr << "Exception caught: " << e.what() << std::endl;
}
}
// return v2;
v = std::move(v2);
}
}
void mpc::apply_perm_localM(bool participate, vector<vector<ZZ_p>> &v, vector<ZZ_p> &pi)
{
trace("mpc::apply_perm_localM");
if (participate)
{
for (ZZ_p z : pi)
{
uint64_t value = conv<uint64_t>(z);
if (value > pi.size())
{
cout << "apply_perm_local." << endl;
cout << "value: " << value << endl;
cout << "size of vector: " << pi.size() << endl;
throw logic_error("permutation is bigger than vector size.");
}
}
if (pi.size() != v.size())
throw std::invalid_argument("local permutation should be half the size of shared vector");
// if (v.size() % 2 != 0)
// throw invalid_argument("v size is not divisible by 2.");
vector<vector<ZZ_p>> v2(v.size(), vector<ZZ_p>(v[0].size()));
for (size_t i=0; i<v.size(); i++)
{
uint64_t idx = conv<uint64_t>(pi[i]-1);
v2[idx] = v[i];
}
v = std::move(v2);
}
}
void mpc::center_normalize_pheno() {
trace("mpc::center_normalize_pheno");
double pheno_sum=0.0;
double sq_error_sum = 0.0;
if(this->pid == 0){
double recv_sum, sq_error;
this->dataowner.recv(recv_sum); //CP1 aggregates sum from each data owner
pheno_sum += recv_sum;
this->toOwner.send(pheno_sum);
this->dataowner.recv(sq_error);
sq_error_sum += sq_error; //CP1 aggregates sum of squared error
this->toOwner.send(sq_error_sum);
}
}
void mpc::permutPheno(int permut)
{
trace("mpc::permutPheno");
vector<uint64_t> normalized_pheno;
this->dataowner.recv(normalized_pheno);
vector<ZZ_p> pheno = convVec(normalized_pheno);
// ZZ_p mean = center_normalize_pheno(pheno);
this->permutMat.push_back(pheno);
for (size_t i=0; i<permut; i++)
{
vector<ZZ_p> permuted(pheno);
vector<ZZ_p> pi=Frand(pheno.size()/2);
shuffle(pi,permuted);
this->permutMat.push_back(permuted);
}
if (this->pid == 0)
{
cout << "permutation matrix complete.\n";
}
// reveal_matrix(this->permutMat, this->permutMat, "permutpheno");
}
void mpc::shuffle(vector<ZZ_p> &pi, vector<ZZ_p> &a)
{
// trace("mpc::shuffle");
assertSize(pi, "Shuffle");
if (pi.size() != a.size())
throw std::invalid_argument("Your shares and pi size are different");
vector<ZZ_p> pi_m(pi.size()/2), pi_p(pi.size()/2);
for (int i=0; i<pi.size()/2; i++)
{
pi_m[i] = pi[2*i];
pi_p[i] = pi[2*i+1];
}
if (this->pid == 0)
{
apply_perm_local(true, a, pi_m);
reshare(a, 1);
apply_perm_local(true, a, pi_p);
reshare(a, 2);
apply_perm_local(false, a, pi);
reshare(a, 0);
}
else if (this->pid == 1)
{
apply_perm_local(false, a, pi);
reshare(a, 1);
apply_perm_local(true,a, pi_m);
reshare(a, 2);
apply_perm_local(true,a, pi_p);
reshare(a, 0);
}
else
{
apply_perm_local(true, a, pi_p);
reshare(a, 1);
apply_perm_local(false, a, pi);
reshare(a, 2);
apply_perm_local(true, a, pi_m);
reshare(a, 0);
}
}
void mpc::unshuffle(vector<ZZ_p> &pi, vector<ZZ_p> &b)
{
trace("mpc::unshuffle");
assertSize(pi, "unshuffle");
vector<ZZ_p> pi_m, pi_p;
for (size_t i=0; i<pi.size()/2; i++)
{
pi_m.push_back(pi[2*i]);
pi_p.push_back(pi[2*i+1]);
}
vector<ZZ_p> inv_m(pi_m.size()), inv_p(pi_p.size());
inv_m = inversePerm(pi_m);
inv_p = inversePerm(pi_p);
if (this->pid == 0)
{
apply_perm_local(false,b,inv_p);
reshare(b,0);
apply_perm_local(true,b,inv_p);
reshare(b,2);
apply_perm_local(true,b,inv_m);
reshare(b,1);
}
else if (this->pid == 1)
{
apply_perm_local(true,b,inv_p);
reshare(b, 0);
apply_perm_local(true,b,inv_m);
reshare(b, 2);
apply_perm_local(false,b,inv_p);
reshare(b, 1);
}
else
{
apply_perm_local(true,b,inv_m);
reshare(b, 0);
apply_perm_local(false,b,inv_p);
reshare(b, 2);
apply_perm_local(true,b,inv_p);
reshare(b, 1);
}
}
void mpc::shuffleM(vector<ZZ_p> &pi, vector<vector<ZZ_p>> &a)
{
// trace("mpc::shuffleM");
assertSize(pi, "Shuffle");
// if (pi.size() != a.size())
// throw std::invalid_argument("Your shares and pi size are different");
vector<ZZ_p> pi_m(pi.size()/2), pi_p(pi.size()/2);
for (int i=0; i<pi.size()/2; i++)
{
pi_m[i] = pi[2*i];
pi_p[i] = pi[2*i+1];
}
if (this->pid == 0)
{
apply_perm_localM(true, a, pi_m);
reshareM(a, 1);
apply_perm_localM(true, a, pi_p);
reshareM(a, 2);
apply_perm_localM(false, a, pi);
reshareM(a, 0);
}
else if (this->pid == 1)
{
apply_perm_localM(false, a, pi);
reshareM(a, 1);
apply_perm_localM(true,a, pi_m);
reshareM(a, 2);
apply_perm_localM(true,a, pi_p);
reshareM(a, 0);
}
else
{
apply_perm_localM(true, a, pi_p);
reshareM(a, 1);
apply_perm_localM(false, a, pi);
reshareM(a, 2);
apply_perm_localM(true, a, pi_m);
reshareM(a, 0);
}
}
void mpc::reveal_matrix(vector<vector<ZZ_p>>& geno, vector<vector<ZZ_p>>& pheno,string name)
{
trace("mpc::reveal_matrix");
// vector<vector<double>> sliced_geno;
Eigen::Matrix <double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> sliced_geno;
sliced_geno.resize(geno.size(), geno[0].size()/2);
for (size_t i=0; i<geno.size(); i++)
{
vector<ZZ_p> row = reveal(geno[i], false);
vector<double> unscaledrow;
for (size_t j=0; j<row.size(); j++)
{
int64_t unshifted;
if (conv<uint64_t>(row[j]) > this->p/2)
unshifted = conv<int64_t>(row[j]) - this->p;
else
unshifted = conv<int64_t>(row[j]);
double r_nom = static_cast<double>(unshifted)/pow(10,6);
unscaledrow.push_back(r_nom);
// r2row.push_back(r_nom*r_nom);
}
// sliced_geno.push_back(unscaledrow);
Eigen::Map<Eigen::VectorXd>(sliced_geno.row(i).data(), unscaledrow.size()) =
Eigen::VectorXd::Map(unscaledrow.data(), unscaledrow.size());
}
Eigen::Matrix <double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> pheno_mat;
pheno_mat.resize(pheno.size(), pheno[0].size()/2);
for (size_t i=0; i<pheno.size(); i++)
{
vector<ZZ_p> row = reveal(pheno[i], false);
vector<double> unscaledrow;
for (size_t j=0; j<row.size(); j++)
{
int64_t unshifted;
if (conv<uint64_t>(row[j]) > this->p/2)
unshifted = conv<int64_t>(row[j]) - this->p;
else
unshifted = conv<int64_t>(row[j]);
double r_nom = static_cast<double>(unshifted)/pow(10,6);
unscaledrow.push_back(r_nom);
// r2row.push_back(r_nom*r_nom);
}
// pheno_mat.push_back(unscaledrow);
Eigen::Map<Eigen::VectorXd>(pheno_mat.row(i).data(), unscaledrow.size()) =
Eigen::VectorXd::Map(unscaledrow.data(), unscaledrow.size());
}
Eigen::Matrix <double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> mult_res;
mult_res.resize(sliced_geno.rows(), pheno_mat.rows());
auto start = chrono::high_resolution_clock::now();
mult_res = sliced_geno*pheno_mat.transpose();
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> totalduration = end - start;
double totaldurationInminutes = totalduration.count()/60.0;
if (this->pid ==0)
{
cout << string("\nPlaintext Eigen matmult took " + to_string(totaldurationInminutes)+" minutes.") << endl;
// writeEigenToTSV(sliced_geno, string(name + "_pQTL_geno"));
// writeEigenToTSV(pheno_mat, string(name + "_pQTL_pheno"));
// writeEigenToTSV(mult_res, string(name + "_pQTL_mmresult"));
}
}
vector<string> intersect_vectors(const vector<string>& one,
const vector<string>& two,
const vector<string>& three) {
trace("intersect_vectors");
// Sort the vectors to prepare for set intersection
vector<string> sorted_one = one;
vector<string> sorted_two = two;
vector<string> sorted_three = three;
sort(sorted_one.begin(), sorted_one.end());
sort(sorted_two.begin(), sorted_two.end());
sort(sorted_three.begin(), sorted_three.end());
// Get the intersection of gene1 and gene2
vector<string> temp_intersection;
std::set_intersection(sorted_one.begin(), sorted_one.end(),
sorted_two.begin(), sorted_two.end(),
back_inserter(temp_intersection));
// Get the intersection of temp_intersection with gene3
vector<string> final_intersection;
std::set_intersection(temp_intersection.begin(), temp_intersection.end(),
sorted_three.begin(), sorted_three.end(),
back_inserter(final_intersection));
return final_intersection;
}
void mpc::recv_string(vector<string>& stringvec)
{
trace("mpc::recv_string");
// this->dataowner.recv(snps);
int buffersize;
this->dataowner.recv(buffersize);
cout <<"mpc received buffer size" << endl;
vector<char> buffer(buffersize);
this->dataowner.recv(buffer.data(), buffersize);
cout <<"mpc received buffer" << endl;
string serializedVar(buffer.data(), buffersize);
// vector<string> cisVar;
istringstream iss(serializedVar);
string token;
while (getline(iss, token, ';')) {
stringvec.push_back(token);
}
}
void mpc::send_string(vector<string>& tosend)
{
trace("mpc::send_string");
string serializedvariants="";
for (const std::string& str : tosend) {
serializedvariants += str + ";"; // Use a suitable delimiter
}
int estimatedSize = static_cast<int>(serializedvariants.size());
int bufferSize = estimatedSize;
// Send the serialized data over the channel
this->toOwner.send(bufferSize);
this->toOwner.send(serializedvariants.data(), serializedvariants.size());
}
void mpc::find_common() // Code written for one data owner
{
trace("mpc::find_common");
// cout << "mpc in find common" << endl;
if(this->pid == 0)
{
vector<string> genes, snps;
recv_string(snps);
// cout << "Snps size: " << snps.size() << endl;
//vector<string> snpset = intersect_vectors(this->snpset, snps);
send_string(snps);
recv_string(genes);
// cout << "Genes size: " << genes.size() << endl;
//vector<string> geneset = intersect_vectors(this->snpset, snps);
send_string(genes);
}
}
void mpc::calc_corr(Logger& cislogger, Logger& nominalLogger)
{
trace("mpc::calc_corr");
if (this->permutMat.empty())
{
throw invalid_argument("permutation matrix has not been made.");
}
if (this->pid ==0)
cout << "Matmult execution... " << flush;
auto start = chrono::high_resolution_clock::now();
// reveal_matrix(this->geno, this->permutMat, "plaintext");
// reveal_matrix(this->permutMat, "permutMat");
vector<vector<ZZ_p>> matmultresult = matmult(this->geno, this->permutMat);
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> totalduration = end - start;
double totaldurationInSeconds = totalduration.count();
double totaldurationInminutes = totaldurationInSeconds/60.0;
if (this->pid==0)
cout << totaldurationInminutes << " minutes" << endl;
vector<vector<double>> matcorr, r2_nominal;
// retrieving r_nominal and r2_nominal
for (size_t i=0; i<matmultresult.size(); i++)
{
vector<ZZ_p> row = reveal(matmultresult[i], false);
vector<double> unscaledrow, r2row;
for (size_t j=0; j<row.size(); j++)
{
int64_t unshifted;
if (conv<uint64_t>(row[j]) > this->p/2)
unshifted = conv<int64_t>(row[j]) - this->p;
else
unshifted = conv<int64_t>(row[j]);
double r_nom = static_cast<double>(unshifted)/pow(10,12);
unscaledrow.push_back(r_nom);
r2row.push_back(r_nom*r_nom);
}
matcorr.push_back(unscaledrow);
r2_nominal.push_back(r2row);
}
//calculating statistics
int dof = this->zscores.size()-2;
if (this->pid ==0)
{
// cout << "WHOP"<< endl;
vector<double> std_ratio;
// writematrixToTSV(matpheno, int startrow, int endrow, const string& name)
// writematrixToTSV(matpheno, "bloodpheno");
// writematrixToTSV(matgeno, "bloodgeno");
// writematrixToTSV(matcorr, "bloodcorr");
this->dataowner.recv(std_ratio);
// writeVectorToTSV(std_ratio, "blood_stdratio");
int buffersize;
this->dataowner.recv(buffersize);
char buffer[buffersize];
this->dataowner.recv(buffer, buffersize);
string serializedVar(buffer, sizeof(buffer) - 1);
vector<string> cisVar;
istringstream iss(serializedVar);
string token;
while (getline(iss, token, ';')) {
cisVar.push_back(token);
}
// cout <<string("received number of cis variants: "+ to_string(cisVar.size()-1)+"\n");
// cout << string("\nreceived std_ratio first: "+to_string(std_ratio[0])+ ", 752: "+to_string(std_ratio[752])+"\n");
// cout <<string("received std ratio size: "+to_string(std_ratio.size())+"\n");
// cout << string("Matmult shape: "+to_string(matcorr.size())+","+to_string(matcorr[0].size())+"\n");
// cout << "WHOP2"<< endl;
//Writing nominal pass
for (int v=0; v<cisVar.size()-1; v++)
{
string message = string(cisVar[0]+"\t"+cisVar[v+1]+"\t"+to_string(v)+"\t");
// logger.log(string(cisVar[0]+"\t"+cisVar[v]+"\t"+to_string(v)+"\t"));
double dof = this->permutMat[0].size()/2 - 2;
double slope = matcorr[v][0]*std_ratio[v];
double tstat2 = dof * r2_nominal[v][0] / (1- r2_nominal[v][0]);
double slope_se = abs(slope)/sqrt(tstat2);
double r2_nom = r2_nominal[v][0];
double r_nom = matcorr[v][0];
double pval = getPvalueFromTstat2(tstat2, dof);
message += string(to_string(dof)+"\t"+to_string(r_nom)+"\t"+to_string(r2_nom)+"\t"+to_string(sqrt(tstat2))+
"\t"+to_string(pval)+"\t"+to_string(slope)+"\t"+to_string(slope_se));
nominalLogger.log(message);
}
// cout << "WHOP3"<< endl;
vector<vector<double>> transposed(matcorr[0].size(), vector<double>(matcorr.size()));
for (size_t i = 0; i < matcorr.size(); ++i) {
for (size_t j = 0; j < matcorr[i].size(); ++j) {
transposed[j][i] = matcorr[i][j];
}
}
cout << string("transposed R2 matrix shape: " + to_string(transposed.size()) + ", "+to_string(transposed[0].size())+"\n");
// Getting r2_perm (maximum corr for each permutation)
vector<double> r_perm;