-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.h
568 lines (492 loc) · 15.1 KB
/
utils.h
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
/*
* utils.h
*
* Created on: 14 Dec 2023
* Author: massimiliano
*/
#ifndef UTILS_H_
#define UTILS_H_
#include <vector>
#include <random>
#include <iomanip>
#include <limits>
#include "seal/seal.h"
using namespace std;
using namespace seal;
/*
* function to generate vector of random double
* with size len (default 100) and items between
* low (default -100) and up (default 100)
*/
inline vector<double> generate_random_data(int len = 100, double low = -100.0, double up = 100.0) {
vector<double> vec(len);
uniform_real_distribution<double> unif(low,up);
default_random_engine re(clock());
for(int i=0; i<vec.size();i++){
vec[i] = unif(re);
}
return vec;
}
/*
* function to generate vector of random int
* with size len (default 100) and items between
* low (default -100) and up (default 100)
*/
inline vector<int> generate_random_data(int len = 100, int low = -100, int up = 100) {
vector<int> vec(len);
uniform_int_distribution<int> unii(low,up);
default_random_engine re(clock());
for(int i=0; i<vec.size();i++){
vec[i] = unii(re);
}
return vec;
}
/*
* function to find the maximum element within the vector
*/
template <typename T>
inline T max_val(vector<T> vec){
return *max_element(vec.begin(), vec.end());
}
/*
* function to find the minimum element within the vector
*/
template <typename T>
inline T min_val(vector<T> vec){
return *min_element(vec.begin(), vec.end());
}
/*
* function to calculate the average value of the vector elements >0
*/
//template <typename T>
//inline double average(vector<T> vec) {
//
// double acc = 0.0;
// int cnt = 0;
// for(int i=0;i<vec.size();i++){
// if(vec[i]>0){
// acc += (double)vec[i];
// cnt++;
// }
// }
// return (double)acc/(double)cnt;
//}
/*
* function to calculate the average value of the vector elements
* greater than low and lower than up bounds (inclusive)
*/
template <typename T>
inline double average(
vector<T> vec,
double low = std::numeric_limits<double>::lowest(),
double up = std::numeric_limits<double>::max()) {
double acc = 0.0;
int cnt = 0;
for(int i=0;i<vec.size();i++){
if((double)vec[i]>=low && (double)vec[i]<=up){
acc += (double)vec[i];
cnt++;
}
}
return (double)acc/(double)cnt;
}
/*
* function to calculate the standard deviation value of the vector elements >0
*/
//template <typename T>
//inline double std_deviation(vector<T> vec) {
//
// double s_dev = 0.0;
// double avg = average(vec);
// int cnt = 0;
// for(int i=0; i<vec.size();i++){
// if(vec[i]>0){
// s_dev += pow(vec[i] - avg, 2);
// cnt++;
// }
// }
// return sqrt(s_dev / (double)cnt);
//}
/*
* function to calculate the standard deviation value of the vector elements
* greater than low and lower that up bounds (inclusive)
*/
template <typename T>
inline double std_deviation(
vector<T> vec,
double low = std::numeric_limits<double>::lowest(),
double up = std::numeric_limits<double>::max()) {
double s_dev = 0.0;
double avg = average(vec);
int cnt = 0;
for(int i=0; i<vec.size();i++){
if((double)vec[i]>=low && (double)vec[i]<=up){
s_dev += pow(vec[i] - avg, 2);
cnt++;
}
}
return sqrt(s_dev / (double)cnt);
}
/*
* function to count the elements within a vector
* greater than low and lower than up bounds (inclusive)
*/
template <typename T>
inline int count_value(
vector<T> vec,
double low = std::numeric_limits<double>::lowest(),
double up = std::numeric_limits<double>::max()) {
int cnt = 0;
for(int i=0;i<vec.size();i++){
if(vec[i]>=low && vec[i]<=up){
cnt++;
}
}
return cnt;
}
/*
* function to calculate percentile p of a vector
*/
template <typename T>
inline T percentile(vector<T> vec, double p) {
// sort vector
std::sort(vec.begin(), vec.end());
// calculate index
uint32_t k = vec.size() * p;
return vec[k];
}
/*
* check the ciphertext against the expected result
*/
inline bool check_chiphertext(
Decryptor *decryptor,
CKKSEncoder *encoder,
const Ciphertext chiphertext,
const vector<double> expected,
const double max_error_perc = 2.0) {
bool check = true;
Plaintext plaintext;
vector<double> result;
// decrypt
decryptor->decrypt(chiphertext, plaintext);
// decode
encoder->decode(plaintext, result);
// check considering error percent
for(int i=0; i<expected.size(); i++){
// if(expected[i] != result[i]){
// check = false;
// cout << "expected[" << i << "]=" << expected[i] << " vs result[" << i << "]=" << result[i] << endl;
// }
double real_error_perc = 100 * (abs(1.0 - (expected[i] / result[i])));
cout << "\texpected[" << i << "]=" << expected[i] << " vs result[" << i << "]=" << result[i] << " error=" << real_error_perc << "%" << endl;
if(real_error_perc > max_error_perc){
check = false;
}
}
cout << "\tCHECK " << check << endl << endl;
return check;
}
/*
* check the plaintext against the expected result
*/
inline bool check_plaintext(
CKKSEncoder *encoder,
const Plaintext plaintext,
const vector<double> expected,
const double max_error_perc = 2.0) {
bool check = true;
vector<double> result;
// decode
encoder->decode(plaintext, result);
// check considering error percent
for(int i=0; i<expected.size(); i++){
double real_error_perc = 100 * (abs(1.0 - (expected[i] / result[i])));
cout << "\texpected[" << i << "]=" << expected[i] << " vs result[" << i << "]=" << result[i] << " error=" << real_error_perc << "%" << endl;
if(real_error_perc > max_error_perc){
check = false;
}
}
cout << "\tCHECK " << check << endl << endl;
return check;
}
/*
* check the cleartext against the expected result
*/
inline bool check_cleartext(
const vector<double> cleartext,
const vector<double> expected,
const double max_error_perc = 2.0) {
bool check = true;
// check considering error percent
for(int i=0; i<expected.size(); i++){
double real_error_perc = 100 * (abs(1.0 - (expected[i] / cleartext[i])));
cout << "\texpected[" << i << "]=" << expected[i] << " vs result[" << i << "]=" << cleartext[i] << " error=" << real_error_perc << "%" << endl;
if(real_error_perc > max_error_perc){
check = false;
}
}
cout << "\tCHECK " << check << endl << endl;
return check;
}
/*
* function to print vector. It prints the first and the last print_size elements (default 4)
* with precision of prec digits (default 3).
* Taken from example.h in SEAL library code.
*/
template <typename T>
inline void print_vector(std::vector<T> vec, std::size_t print_size = 4, int prec = 3)
{
/*
Save the formatting information for std::cout.
*/
std::ios old_fmt(nullptr);
old_fmt.copyfmt(std::cout);
std::size_t slot_count = vec.size();
std::cout << std::fixed << std::setprecision(prec);
std::cout << std::endl;
if (slot_count <= 2 * print_size)
{
std::cout << "[";
for (std::size_t i = 0; i < slot_count; i++)
{
std::cout << " " << vec[i] << ((i != slot_count - 1) ? "," : " ]\n");
}
}
else
{
vec.resize(std::max(vec.size(), 2 * print_size));
std::cout << "[";
for (std::size_t i = 0; i < print_size; i++)
{
std::cout << " " << vec[i] << ",";
}
if (vec.size() > 2 * print_size)
{
std::cout << " ...,";
}
for (std::size_t i = slot_count - print_size; i < slot_count; i++)
{
std::cout << " " << vec[i] << ((i != slot_count - 1) ? "," : " ]\n");
}
}
std::cout << std::endl;
/*
Restore the old std::cout formatting.
*/
std::cout.copyfmt(old_fmt);
}
/*
* function to print parameters in a SEALContext.
* Taken from example.h in SEAL library code.
*/
inline void print_parameters(const seal::SEALContext &context)
{
auto &context_data = *context.key_context_data();
/*
Which scheme are we using?
*/
std::string scheme_name;
switch (context_data.parms().scheme())
{
case seal::scheme_type::bfv:
scheme_name = "BFV";
break;
case seal::scheme_type::ckks:
scheme_name = "CKKS";
break;
case seal::scheme_type::bgv:
scheme_name = "BGV";
break;
default:
throw std::invalid_argument("unsupported scheme");
}
std::cout << "/" << std::endl;
std::cout << "| Encryption parameters :" << std::endl;
std::cout << "| scheme: " << scheme_name << std::endl;
std::cout << "| poly_modulus_degree: " << context_data.parms().poly_modulus_degree() << std::endl;
/*
Print the size of the true (product) coefficient modulus.
*/
std::cout << "| coeff_modulus size: ";
std::cout << context_data.total_coeff_modulus_bit_count() << " (";
auto coeff_modulus = context_data.parms().coeff_modulus();
std::size_t coeff_modulus_size = coeff_modulus.size();
for (std::size_t i = 0; i < coeff_modulus_size - 1; i++)
{
std::cout << coeff_modulus[i].bit_count() << " + ";
}
std::cout << coeff_modulus.back().bit_count();
std::cout << ") bits" << std::endl;
//std::cout << "| max coeff size: " << CoeffModulus::MaxBitCount(context_data.parms().poly_modulus_degree()) << " bits" << std::endl;
std::cout << "| using_keyswitching: " << context.using_keyswitching() << endl;
/*
For the BFV scheme print the plain_modulus parameter.
*/
if (context_data.parms().scheme() == seal::scheme_type::bfv)
{
std::cout << "| plain_modulus: " << context_data.parms().plain_modulus().value() << std::endl;
}
std::cout << "\\" << std::endl << endl;
}
/*
* function to print the `parms_id' to std::ostream.
* Taken from example.h in SEAL library code.
*/
/*
Helper function: Prints the `parms_id' to std::ostream.
*/
inline std::ostream &operator<<(std::ostream &stream, seal::parms_id_type parms_id)
{
/*
Save the formatting information for std::cout.
*/
std::ios old_fmt(nullptr);
old_fmt.copyfmt(std::cout);
stream << std::hex << std::setfill('0') << std::setw(16) << parms_id[0] << " " << std::setw(16) << parms_id[1]
<< " " << std::setw(16) << parms_id[2] << " " << std::setw(16) << parms_id[3] << " ";
/*
Restore the old std::cout formatting.
*/
std::cout.copyfmt(old_fmt);
return stream;
}
/*
* function to print the modulus switching chain.
* It is a part of 3_levels.cpp in SEAL library code.
*/
inline void print_modulus_switching_chain(SEALContext context) {
/*
First print the key level parameter information.
*/
auto context_data = context.key_context_data();
cout << "----> Level (chain index): " << context_data->chain_index();
cout << " ...... key_context_data()" << endl;
cout << " parms_id: " << context_data->parms_id() << endl;
cout << " coeff_modulus primes: ";
cout << hex;
for (const auto &prime : context_data->parms().coeff_modulus())
{
cout << prime.value() << " ";
}
cout << dec << endl;
cout << "\\" << endl;
cout << " \\-->";
/*
Next iterate over the remaining (data) levels.
*/
context_data = context.first_context_data();
while (context_data)
{
cout << " Level (chain index): " << context_data->chain_index();
if (context_data->parms_id() == context.first_parms_id())
{
cout << " ...... first_context_data()" << endl;
}
else if (context_data->parms_id() == context.last_parms_id())
{
cout << " ...... last_context_data()" << endl;
}
else
{
cout << endl;
}
cout << " parms_id: " << context_data->parms_id() << endl;
cout << " coeff_modulus primes: ";
cout << hex;
for (const auto &prime : context_data->parms().coeff_modulus())
{
cout << prime.value() << " ";
}
cout << dec << endl;
cout << "\\" << endl;
cout << " \\-->";
/*
Step forward in the chain.
*/
context_data = context_data->next_context_data();
}
cout << " End of chain reached" << endl << endl;
}
/*
* print plaintext params and info
*/
inline void print_plaintext_info(const Plaintext plain, const SEALContext context){
cout << "\tplaintext parms_id() " << plain.parms_id() << endl;
cout << "\tplaintext modulus chain index " << context.get_context_data(plain.parms_id())->chain_index() << endl;
cout << "\tplaintext parameter coeff_count() " << plain.coeff_count() << endl;
cout << "\tplaintext parameter significant_coeff_count() " << plain.significant_coeff_count() << endl;
ios old_fmt(nullptr);
old_fmt.copyfmt(cout);
cout << fixed << setprecision(10);
cout << "\tplaintext scale() " << plain.scale() << endl;
cout.copyfmt(old_fmt);
cout << "\tplaintext scale() " << log2(plain.scale()) << " bit" << endl;
cout << "\tplaintext parameter is_ntt_form() " << plain.is_ntt_form() << endl << endl;
}
/*
* print ciphertext params and info
*/
inline void print_ciphertext_info(const Ciphertext encrypted, const SEALContext context){
cout << "\tciphertext parms_id() " << encrypted.parms_id() << endl;
cout << "\tciphetext modulus chain index " << context.get_context_data(encrypted.parms_id())->chain_index() << endl;
cout << "\tciphertext coeff_modulus_size() " << encrypted.coeff_modulus_size() << endl;
cout << "\tciphertext size() " << encrypted.size() << endl;
cout << "\tciphertext size_capacity() " << encrypted.size_capacity()<< endl;
cout << "\tciphertext poly_modulus_degree() " << encrypted.poly_modulus_degree()<< endl;
ios old_fmt(nullptr);
old_fmt.copyfmt(cout);
cout << fixed << setprecision(10);
cout << "\tciphertext scale() " << encrypted.scale() << endl;
cout.copyfmt(old_fmt);
cout << "\tciphertext scale() " << log2(encrypted.scale()) << " bit" << endl;
cout << "\tciphertext is_ntt_form() " << encrypted.is_ntt_form() << endl << endl;
}
/**
* function to check if the scale of the operands is the same
*/
inline bool check_operand_scale(Ciphertext op1, Ciphertext op2){
if(op1.scale() == op2.scale()){
cout << "\tCheck scale OK" << endl;
return true;
} else {
ios old_fmt(nullptr);
old_fmt.copyfmt(cout);
cout << fixed << setprecision(10);
cout << "\tCheck scale " << op1.scale() << " vs " << op2.scale() << endl;
cout.copyfmt(old_fmt);
return false;
}
}
/**
* function to check if the scale of the operands is the same
*/
inline bool check_operand_scale(Ciphertext op1, Plaintext op2){
if(op1.scale() == op2.scale()){
cout << "\tCheck scale OK" << endl;
return true;
} else {
ios old_fmt(nullptr);
old_fmt.copyfmt(cout);
cout << fixed << setprecision(10);
cout << "\tCheck scale " << op1.scale() << " vs " << op2.scale() << endl;
cout.copyfmt(old_fmt);
return false;
}
}
/**
* function to check if the scale of the operand is equal to the desired scale
*/
inline bool check_operand_scale(Ciphertext op, double scale){
if(op.scale() == scale){
cout << "\tCheck scale OK" << endl;
return true;
} else {
ios old_fmt(nullptr);
old_fmt.copyfmt(cout);
cout << fixed << setprecision(10);
cout << "\tCheck scale " << op.scale() << " vs " << scale << endl;
cout.copyfmt(old_fmt);
return false;
}
}
#endif /* UTILS_H_ */