-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencrypted_comparation.py
More file actions
112 lines (83 loc) · 2.39 KB
/
encrypted_comparation.py
File metadata and controls
112 lines (83 loc) · 2.39 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
from eva import EvaProgram, Input, Output, evaluate
from eva.ckks import CKKSCompiler
from eva.seal import generate_keys
from eva.metric import valuation_mse
from PIL import Image
import math
'''
def read_input_image():
data = [x/128 for x in range(-dim//2, dim//2, 1)]
#data = [x/129 for x in range(1, dim+1)]
lower, upper = 1/2, 3/4
l_norm = [lower + (upper - lower) * x for x in data]
return {'data': l_norm}
'''
def read_input_image():
data = [x/256 for x in range(-dim//2, dim//2, 1)]
return {'data': data}
def non_taylor_comp(input):
ans = []
for x in input:
tmp = x**2
tmp = math.sqrt(tmp)
ans.append(tmp)
return {'data': ans}
def exponential_expansion(x, limit):
sum = 0
prod = 1
fact = 1
for i in range(limit):
sum = sum + prod * (1/fact)
prod = prod * x
fact = fact * (i + 1)
return sum
def logarithm(x, limit):
a = 0.5
sum = math.log(a)
prod = 1
pow = 1
for i in range(1, limit):
prod = prod * (x - a)
pow = pow * a
if i%2 == 1:
sum = sum + prod * (1/(i * pow))
else:
sum = sum - prod * (1/(i * pow))
return sum
def exponentiation(base, exp, limit):
exp_int = int(exp)
exp_frac = exp - exp_int
if exp_int == 0:
ans = 1
else:
ans = base**exp_int
log = logarithm(base, limit)
tmp = exponential_expansion(exp_frac*log, limit)
ans = ans * tmp
return ans
def abs(data):
data = data ** 2
data = exponentiation(data, 1 / 2, 4)
return data
dim = 256
encrypted_comparation = EvaProgram('encrypted_comparation', vec_size=dim)
with encrypted_comparation:
data = Input('data')
data = abs(data)
Output('data', data)
encrypted_comparation.set_input_scales(40)
encrypted_comparation.set_output_ranges(30)
input = read_input_image()
compiler = CKKSCompiler()
compiled, params, signature = compiler.compile(encrypted_comparation)
public_ctx, secret_ctx = generate_keys(params)
enc_inputs = public_ctx.encrypt(input, signature)
enc_outputs = public_ctx.execute(compiled, enc_inputs)
outputs = secret_ctx.decrypt(enc_outputs, signature)
reference = evaluate(compiled, input)
non_taylor = non_taylor_comp(input['data'])
print(input['data'])
print(non_taylor['data'])
print(outputs['data'])
print(reference['data'])
print('MSE', valuation_mse(outputs, non_taylor))