kcelia commited on
Commit
dbdd71f
·
unverified ·
1 Parent(s): 550707a

chore: add relevent files

Browse files
Files changed (3) hide show
  1. app.py +1014 -0
  2. server.py +335 -0
  3. utils.py +179 -0
app.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import io
3
+ import random
4
+ import subprocess
5
+ import threading
6
+ import time
7
+ from glob import glob
8
+ from pathlib import Path
9
+
10
+ import gradio as gr
11
+ import matplotlib.pyplot as plt
12
+ import numpy
13
+ import requests
14
+ from PIL import Image
15
+ from scipy import stats
16
+ from server import *
17
+ from tqdm import tqdm
18
+ from utils import *
19
+
20
+ from concrete.ml.deployment import FHEModelClient
21
+
22
+ CURRENT_DIR = Path(__file__).parent
23
+
24
+ subprocess.Popen(["uvicorn", "server:app"], cwd=CURRENT_DIR)
25
+ time.sleep(3)
26
+
27
+ numpy.set_printoptions(threshold=numpy.inf)
28
+
29
+ USER_ID = numpy.random.randint(0, 2**32)
30
+
31
+ # Define client-specific directories
32
+ CLIENT_DIR = ROOT_DIR / f"user_{USER_ID}/client"
33
+ CLIENT_KEY_SMOOTHER_MODULE_DIR = CLIENT_DIR / KEY_SMOOTHER_MODULE_DIR
34
+ CLIENT_KEY_BASE_MODULE_DIR = CLIENT_DIR / KEY_BASE_MODULE_DIR
35
+ CLIENT_ENCRYPTED_INPUT_DIR = CLIENT_DIR / ENCRYPTED_INPUT_DIR
36
+ CLIENT_ENCRYPTED_OUTPUT_DIR = CLIENT_DIR / ENCRYPTED_OUTPUT_DIR
37
+
38
+ # Define server-specific directories
39
+ SERVER_DIR = ROOT_DIR / f"user_{USER_ID}/server"
40
+ SERVER_KEY_SMOOTHER_MODULE_DIR = SERVER_DIR / KEY_SMOOTHER_MODULE_DIR
41
+ SERVER_KEY_BASE_MODULE_DIR = SERVER_DIR / KEY_BASE_MODULE_DIR
42
+ SERVER_ENCRYPTED_INPUT_DIR = SERVER_DIR / ENCRYPTED_INPUT_DIR
43
+ SERVER_ENCRYPTED_OUTPUT_DIR = SERVER_DIR / ENCRYPTED_OUTPUT_DIR
44
+
45
+ ALL_DIRECTORIES = [
46
+ CLIENT_KEY_SMOOTHER_MODULE_DIR,
47
+ CLIENT_KEY_BASE_MODULE_DIR,
48
+ CLIENT_ENCRYPTED_INPUT_DIR,
49
+ CLIENT_ENCRYPTED_OUTPUT_DIR,
50
+ SERVER_KEY_SMOOTHER_MODULE_DIR,
51
+ SERVER_KEY_BASE_MODULE_DIR,
52
+ SERVER_ENCRYPTED_INPUT_DIR,
53
+ SERVER_ENCRYPTED_OUTPUT_DIR,
54
+ ]
55
+
56
+ # Load test dataset
57
+
58
+ print("Load data ...")
59
+ UNIQUE_FOUNDERS = load_pickle_from_zip("./data/unique_founders.pkl")
60
+ OTHER_TEST_FOUNDERS = load_pickle_from_zip("./data/hf_test_founders.pkl")
61
+ OTHER_TRAIN_FOUNDERS = load_pickle_from_zip("./data/hf_train_founders.pkl")
62
+ UNIQUE_MIXED_FOUNDERS = load_pickle_from_zip("./data/unique_mixed_founders.pkl")
63
+
64
+ DESCENDANT_PATH = Path("./data/Child.pkl")
65
+ PREDICTION_IMG_PATH = Path("output.npg")
66
+ FAMILY_TREE_IMG_PATH = Path("simulated_family_tree.png")
67
+
68
+ ALL_GENERATED_PATHS = [
69
+ DESCENDANT_PATH,
70
+ FAMILY_TREE_IMG_PATH,
71
+ PREDICTION_IMG_PATH,
72
+ FHE_COMPUTATION_TIMELINE,
73
+ ]
74
+
75
+
76
+ def reset():
77
+ """Reset the environment.
78
+
79
+ Clean the root directory, recreating necessary directories and removing any generated files.
80
+ """
81
+ print("Cleaning ...")
82
+
83
+ clean_dir(ROOT_DIR)
84
+
85
+ for directory in ALL_DIRECTORIES:
86
+ directory.mkdir(parents=True, exist_ok=True)
87
+
88
+ for file_path in ALL_GENERATED_PATHS:
89
+ if file_path.exists():
90
+ file_path.unlink()
91
+ print(f"File: {file_path} has been removed.")
92
+
93
+
94
+ def simulate_allele_fn():
95
+
96
+ yield {
97
+ simulate_btn: gr.update(visible=True, value="🔄 Processing... Please wait."),
98
+ ethnicity_simulation_img: gr.update(visible=False),
99
+ simulate_text: gr.update(visible=False),
100
+ }
101
+
102
+ start_time = time.time()
103
+ n_generations = random.randint(1, 3)
104
+
105
+ individuals = random.sample(UNIQUE_MIXED_FOUNDERS, 2 + n_generations)
106
+
107
+ num_snps = META["C"]
108
+ print(f"Simulating family tree with: {n_generations} generations ...")
109
+
110
+ first_founder = individuals.pop(0)
111
+ second_founder = individuals.pop(0)
112
+
113
+ assert len(first_founder) == 4
114
+ assert len(second_founder) == 4
115
+ assert (
116
+ sum([numpy.array_equal(arr1, arr2) for arr1, arr2 in zip(first_founder, second_founder)])
117
+ == 0
118
+ )
119
+
120
+ lineages = []
121
+ labels = []
122
+ admix = []
123
+
124
+ for gen in range(n_generations + 1):
125
+
126
+ print(f"Generation_{gen}:")
127
+
128
+ # Initialize the child for this generation
129
+ if gen == 0:
130
+ # Use the specified founders for the first generation
131
+ founder_1 = first_founder
132
+ founder_2 = second_founder
133
+ labels.append(["Ancestor 1", "Ancestor 2", "Progeny (Generation 1)"])
134
+ else:
135
+ # Use the last child from the previous generation as founder 1
136
+ founder_1 = admix[-1]
137
+ founder_2 = individuals.pop(0)
138
+ labels.append(
139
+ [labels[-1][-1], f"Ancestor {len(labels) + 2}", f"Progeny (Generation {gen + 1})"]
140
+ )
141
+
142
+ assert len(founder_1) == 4
143
+ assert len(founder_2) == 4
144
+
145
+ # Prepare new admix entry for this generation's child
146
+ admix.append([None, None, None, None])
147
+
148
+ snp_1, snp_2, label_1, label_2 = copy.deepcopy(founder_1)
149
+ _snp_1, _snp_2, _label_1, _label_2 = copy.deepcopy(founder_2)
150
+
151
+ lineage = []
152
+ for j in range(2): # Two haplotypes
153
+
154
+ # Select one haplotype from each founder
155
+ snp, label = (snp_1, label_1) if random.random() < 0.5 else (snp_2, label_2)
156
+ _snp, _label = (_snp_1, _label_1) if random.random() < 0.5 else (_snp_2, _label_2)
157
+
158
+ lineage.append(
159
+ [compute_distribution(label.flatten()), compute_distribution(_label.flatten())]
160
+ )
161
+
162
+ breakpoints = numpy.random.choice(
163
+ range(1, num_snps),
164
+ # size=int(sum(numpy.random.poisson(0.75, size=gen))) + 1,
165
+ size=int(sum(numpy.random.poisson(0.1, size=gen)))
166
+ + 1, # Fewer breakpoints, less mixed
167
+ replace=False,
168
+ )
169
+
170
+ breakpoints = numpy.concatenate(([0], numpy.sort(breakpoints), [num_snps]))
171
+
172
+ for k in range(len(breakpoints) - 1):
173
+
174
+ snp[breakpoints[k] : breakpoints[k + 1]] = _snp[
175
+ breakpoints[k] : breakpoints[k + 1]
176
+ ].copy()
177
+ label[breakpoints[k] : breakpoints[k + 1]] = _label[
178
+ breakpoints[k] : breakpoints[k + 1]
179
+ ].copy()
180
+
181
+ yield {
182
+ simulate_btn: gr.update(
183
+ visible=True,
184
+ value=f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({(gen + 1)/(n_generations + 1):.0%})",
185
+ )
186
+ }
187
+
188
+ admix[-1][j], admix[-1][j + 2] = snp, label
189
+
190
+ lineages.append([(lineage[0][0] + lineage[1][0]) / 2, (lineage[0][1] + lineage[1][1]) / 2])
191
+
192
+ print(f"Ascendant_1: {lineages[-1][0]} + Ascendant_2 {lineages[-1][0]}")
193
+
194
+ last_child = admix[-1]
195
+ snp_1, snp_2, label_1, label_2 = last_child[0], last_child[1], last_child[2], last_child[3]
196
+ snp, label_full = (snp_1, label_1) if random.random() < 0.5 else (snp_2, label_2)
197
+
198
+ # We are prediction on one allele, so we plot the right allele
199
+ lineages[-1][-1] = compute_distribution(label_full)
200
+
201
+ l1 = label_full.reshape(1, -1)
202
+ N, L = l1.shape
203
+ y = l1[:, 0 : L // META["M"] * META["M"]].reshape(N, L // META["M"], META["M"])
204
+ y = stats.mode(y, axis=2)[0].squeeze()
205
+
206
+ write_pickle(path="./data/Child.pkl", data=[snp.reshape(1, -1), y])
207
+ snp = numpy.array(snp).reshape(1, -1)
208
+ yield {
209
+ simulate_btn: gr.update(
210
+ visible=True,
211
+ value=f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({(gen + 1)/(n_generations + 1):.0%})",
212
+ )
213
+ }
214
+
215
+ print("Plot the simulated allele.")
216
+ print(f"{snp.shape=} - {y.shape=}")
217
+ print(
218
+ f"{any(snp.flatten()[12343 : 12343 + 1000] == 1)=} - {any(snp.flatten()[12343 : 12343 + 1000] == 0)=}"
219
+ )
220
+
221
+ yield {
222
+ simulate_btn: gr.update(
223
+ visible=True,
224
+ value=f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({(gen + 1)/(n_generations + 1):.0%})",
225
+ )
226
+ }
227
+
228
+ _ = pie_ethnicity_simulation_plot_img(copy.copy(lineages), copy.copy(labels))
229
+
230
+ sorted_indices = numpy.argsort(lineages[-1][0])[::-1][:2]
231
+ top_percentages = [lineages[-1][0][i] for i in sorted_indices]
232
+ top_labels = [LABELS[i] for i in sorted_indices]
233
+
234
+ # items = [f'{p:.0%} {l}' for p, l in zip(top_percentages, top_labels)]
235
+ # items = [f'{p:.0%} {l}' for p, l in zip(lineages[-1][0], LABELS)]
236
+
237
+ yield {
238
+ simulate_btn: gr.update(
239
+ visible=True,
240
+ value=f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({(gen + 1)/(n_generations + 1):.0%})",
241
+ )
242
+ }
243
+
244
+ yield {
245
+ clear_input_box: gr.update(visible=True, value=list(snp.flatten())[:321]),
246
+ simulate_btn: gr.update(value="Data simulated ✅"),
247
+ ethnicity_simulation_img: gr.update(
248
+ value=Image.open(FAMILY_TREE_IMG_PATH),
249
+ visible=True,
250
+ show_label=False,
251
+ show_download_button=True,
252
+ container=True,
253
+ ),
254
+ simulate_text: gr.update(
255
+ value=f"Given the genetic lineage simulation above, the origin of two predominant genes, for the last progeny are: {top_labels[-2]} and {top_labels[-1]}. Now, we proceed with ***DNA testing*** using **FHE** on this final descendant.",
256
+ visible=True,
257
+ ),
258
+ }
259
+
260
+ return
261
+
262
+
263
+ def key_gen_fn(user_id):
264
+ """Generate keys for a given user on the Client Side."""
265
+
266
+ print("\n------------ Step 1: Key Generation:")
267
+
268
+ yield gr.update(visible=True, value="🔄 Processing... Please wait.")
269
+
270
+ print(f"Your user ID is: {user_id:.0f}....")
271
+
272
+ ## Generate one key for all models since they share the same crypto params
273
+ # Stage1: Base modules
274
+
275
+ base_modules_path = sorted(glob(f"{SHARED_BASE_MODULE_DIR}/model_*"), key=extract_model_number)
276
+
277
+ print(f"{len(base_modules_path)=} {META['NW']=}")
278
+
279
+ if len(base_modules_path) != META["NW"]:
280
+ yield gr.update(visible=True, value="❌ Error in key generation", interactive=False)
281
+
282
+ base_client = FHEModelClient(path_dir=base_modules_path[0], key_dir=CLIENT_KEY_BASE_MODULE_DIR)
283
+ base_client.generate_private_and_evaluation_keys()
284
+ serialized_evaluation_base_modules_keys = base_client.get_serialized_evaluation_keys()
285
+ assert isinstance(serialized_evaluation_base_modules_keys, bytes)
286
+ print(f"Stage1: {len(glob(f'{CLIENT_KEY_BASE_MODULE_DIR}/eval_key'))} key has been generated")
287
+
288
+ # Stage2: Smoother module
289
+ smoother_client = FHEModelClient(
290
+ path_dir=SHARED_SMOOTHER_MODULE_DIR, key_dir=CLIENT_KEY_SMOOTHER_MODULE_DIR
291
+ )
292
+ smoother_client.generate_private_and_evaluation_keys()
293
+ serialized_evaluation_smoother_module_keys = smoother_client.get_serialized_evaluation_keys()
294
+ assert isinstance(serialized_evaluation_smoother_module_keys, bytes)
295
+ print(
296
+ f"Stage2: {len(glob(f'{CLIENT_KEY_SMOOTHER_MODULE_DIR}/eval_key'))} key has been generated"
297
+ )
298
+
299
+ # Save the keys
300
+ base_evaluation_key_path = Path(base_client.key_dir) / "eval_key"
301
+ smoother_evaluation_key_path = Path(smoother_client.key_dir) / "eval_key"
302
+
303
+ write_bytes(base_evaluation_key_path, serialized_evaluation_base_modules_keys)
304
+ write_bytes(smoother_evaluation_key_path, serialized_evaluation_smoother_module_keys)
305
+
306
+ if not base_evaluation_key_path.is_file():
307
+ msg = "❌ Error encountered while generating the base modules key evaluation"
308
+ elif not smoother_evaluation_key_path.is_file():
309
+ msg = "❌ Error encountered while generating the smoother module key evaluation"
310
+ else:
311
+ msg = "Secret and public keys have been generated ✅"
312
+
313
+ print(msg)
314
+
315
+ yield gr.update(visible=True, value=msg, interactive=False)
316
+ return
317
+
318
+
319
+ def encrypt_fn(user_id):
320
+ """Encrypt input on the Client Side using the secret key."""
321
+
322
+ print("\n------------ Step 2: Encrypt the input")
323
+
324
+ if (
325
+ is_none(int(user_id))
326
+ or (len(glob(f"{CLIENT_KEY_BASE_MODULE_DIR}/*")) == 0)
327
+ or not DESCENDANT_PATH.is_file()
328
+ ):
329
+
330
+ print("Error in encryption step: Provide your chromosome and generate the evaluation keys.")
331
+
332
+ yield {
333
+ encrypt_btn: gr.update(
334
+ visible=True,
335
+ value="❌ Ensure your have simulated an allele and the evaluation key has been generated.",
336
+ )
337
+ }
338
+ return
339
+
340
+ allele, _ = read_pickle(path=DESCENDANT_PATH)
341
+
342
+ yield {
343
+ encrypt_btn: gr.update(visible=True, value="🔄 Processing... Please wait."),
344
+ send_btn: gr.update(interactive=False),
345
+ run_fhe_btn: gr.update(interactive=False),
346
+ get_output_btn: gr.update(interactive=False),
347
+ decrypt_btn: gr.update(interactive=False),
348
+ simulate_btn: gr.update(interactive=False),
349
+ }
350
+
351
+ base_modules_path = sorted(glob(f"{SHARED_BASE_MODULE_DIR}/model_*"), key=extract_model_number)
352
+ assert len(base_modules_path) == META["NW"]
353
+
354
+ print(f"{len(base_modules_path)} models have been loaded")
355
+
356
+ client_fhemodels = []
357
+ for i, base_module_path in enumerate(tqdm(base_modules_path)):
358
+ base_client = FHEModelClient(path_dir=base_module_path, key_dir=CLIENT_KEY_BASE_MODULE_DIR)
359
+ client_fhemodels.append(base_client)
360
+ base_serialized_evaluation_keys = read_bytes(base_client.key_dir / "eval_key")
361
+ assert isinstance(base_serialized_evaluation_keys, bytes)
362
+
363
+ X_p, _, M_, rem = process_data_for_base_modules(META, allele)
364
+ base_args = tuple(zip(client_fhemodels[:-1], numpy.swapaxes(X_p, 0, 1)))
365
+ base_args += ((client_fhemodels[-1], allele[:, allele.shape[1] - (M_ + rem) :]),)
366
+
367
+ start_time = time.time()
368
+ for i, (client, window) in enumerate(base_args):
369
+ encrypted_input = client.quantize_encrypt_serialize(window)
370
+ write_bytes(CLIENT_ENCRYPTED_INPUT_DIR / f"window_{i}", encrypted_input)
371
+ yield {
372
+ encrypt_btn: gr.update(
373
+ visible=True,
374
+ value=f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({i/META['NW']:.0%}).",
375
+ )
376
+ }
377
+ # f"⏳ Time elapsed: {time.time() - start_time:.0f} seconds ({(gen + 1)/(n_generations + 1):.0%})")
378
+ exec_time = time.time() - start_time
379
+
380
+ msg = f"Encryption completed in {exec_time: .2f} seconds."
381
+
382
+ print(msg)
383
+
384
+ enc_quant_input_shorten_hex = encrypted_input.hex()[:INPUT_BROWSER_LIMIT]
385
+
386
+ yield {
387
+ encrypt_input_box: gr.update(visible=True, value=enc_quant_input_shorten_hex),
388
+ encrypt_btn: gr.update(interactive=False, value=msg),
389
+ simulate_btn: gr.update(interactive=False),
390
+ send_btn: gr.update(interactive=True),
391
+ run_fhe_btn: gr.update(interactive=True),
392
+ get_output_btn: gr.update(interactive=True),
393
+ decrypt_btn: gr.update(interactive=True),
394
+ }
395
+ return
396
+
397
+
398
+ def send_input_fn(user_id):
399
+ """Send the encrypted data and the evaluation key to the server."""
400
+
401
+ print("\n------------ Step 3.1: Send encrypted_data to the Server")
402
+
403
+ errors = []
404
+ if not (CLIENT_KEY_BASE_MODULE_DIR / "eval_key").is_file():
405
+ errors.append("Stage 1 evaluation keys are missing.")
406
+
407
+ if not (CLIENT_KEY_SMOOTHER_MODULE_DIR / "eval_key").is_file():
408
+ errors.append("Stage 2 evaluation keys are missing. ")
409
+
410
+ if len(glob(str(CLIENT_ENCRYPTED_INPUT_DIR / "window_*"))) != META["NW"]:
411
+ errors.append("The input has not been successfully encrypted.")
412
+
413
+ if errors:
414
+ error_message = "❌ Error during data transmission:\n" + "\n".join(errors)
415
+ print(error_message)
416
+
417
+ yield {send_btn: gr.update(value=error_message)}
418
+ return
419
+
420
+ yield {
421
+ send_btn: gr.update(value="🔄 Processing... Please wait."),
422
+ run_fhe_btn: gr.update(interactive=False),
423
+ get_output_btn: gr.update(interactive=False),
424
+ decrypt_btn: gr.update(interactive=False),
425
+ }
426
+
427
+ # Define the data and files to post
428
+ data = {"user_id": f"user_{user_id:.0f}", "root_dir": str(ROOT_DIR)}
429
+ n_w = glob(f"{CLIENT_ENCRYPTED_INPUT_DIR}/window_*")
430
+
431
+ files = [
432
+ ("files", open(f"{CLIENT_KEY_BASE_MODULE_DIR}/eval_key", "rb")),
433
+ ("files", open(f"{CLIENT_KEY_SMOOTHER_MODULE_DIR}/eval_key", "rb")),
434
+ ] + [("files", open(f"{CLIENT_ENCRYPTED_INPUT_DIR}/window_{i}", "rb")) for i in range(len(n_w))]
435
+
436
+ # Send the encrypted input and evaluation key to the server
437
+ url = SERVER_URL + "send_input"
438
+ print(f"{url=}")
439
+
440
+ with requests.post(url=url, data=data, files=files) as resp:
441
+ print(f"{resp.ok=}")
442
+ msg = "Data sent to the Server ✅" if resp.ok else "❌ Error in sending data to the Server"
443
+
444
+ yield {
445
+ send_btn: gr.update(value=msg, interactive=False if "✅" in msg else True),
446
+ run_fhe_btn: gr.update(interactive=True),
447
+ get_output_btn: gr.update(interactive=True),
448
+ decrypt_btn: gr.update(interactive=True),
449
+ }
450
+
451
+ return
452
+
453
+
454
+ def run_fhe_fn(user_id):
455
+ """Run the FHE execution on the Server Side."""
456
+
457
+ print("\n------------ Step 4.1: Run in FHE on the Server Side")
458
+
459
+ if FHE_COMPUTATION_TIMELINE.exists():
460
+ FHE_COMPUTATION_TIMELINE.unlink()
461
+ print(f"File {FHE_COMPUTATION_TIMELINE} removed successfully.")
462
+
463
+
464
+ if is_none(int(user_id)) or len(glob(f"{SERVER_ENCRYPTED_INPUT_DIR}/encrypted_window_*")) == 0:
465
+ yield {
466
+ run_fhe_btn: gr.update(
467
+ visible=True,
468
+ value="❌ Check your connectivity. Ensure the input has been submitted, the keys have been generated, and the server has received the data.",
469
+ )
470
+ }
471
+ return
472
+
473
+ yield {
474
+ run_fhe_btn: gr.update(
475
+ visible=True, value="🔄 Processing... Please wait. This may take up to 500 seconds."
476
+ ),
477
+ get_output_btn: gr.update(interactive=False),
478
+ decrypt_btn: gr.update(interactive=False),
479
+ }
480
+
481
+ data = {
482
+ "user_id": f"user_{user_id:.0f}",
483
+ "root_dir": str(ROOT_DIR),
484
+ }
485
+
486
+ url = SERVER_URL + "run_fhe"
487
+
488
+ # Function to run FHE on the server in a separate thread
489
+ def run_fhe_on_server():
490
+ nonlocal server_response
491
+ with requests.post(url=url, data=data) as resp:
492
+ if not resp.ok:
493
+ server_response = "error"
494
+ else:
495
+ server_response = resp.json()
496
+
497
+ server_response = None
498
+
499
+ # Start the FHE process in a separate thread
500
+ server_thread = threading.Thread(target=run_fhe_on_server)
501
+ server_thread.start()
502
+
503
+ # While the server is processing, check the timing file for updates
504
+ while server_thread.is_alive():
505
+ try:
506
+ with FHE_COMPUTATION_TIMELINE.open("r", encoding="utf-8") as f:
507
+ timing = f.read().strip()
508
+ yield {
509
+ run_fhe_btn: gr.update(visible=True, value=f"⏳ Time elapsed: {timing}"),
510
+ }
511
+ except FileNotFoundError:
512
+ yield {
513
+ run_fhe_btn: gr.update(visible=True, value="⏳ Waiting for the server to start..."),
514
+ }
515
+
516
+ time.sleep(5) # Wait a few seconds before reading again
517
+
518
+ # Wait for the thread to finish
519
+ server_thread.join()
520
+
521
+ # Handle server response after completion
522
+ if server_response == "error":
523
+ yield {
524
+ run_fhe_btn: gr.update(
525
+ visible=True,
526
+ value="❌ Error occurred on the Server Side. Please check your connectivity.",
527
+ ),
528
+ }
529
+ else:
530
+ final_time = server_response
531
+ yield {
532
+ run_fhe_btn: gr.update(
533
+ visible=True, interactive=False, value=f"FHE executed in {final_time:.2f} seconds"
534
+ ),
535
+ get_output_btn: gr.update(interactive=True),
536
+ decrypt_btn: gr.update(interactive=True),
537
+ }
538
+
539
+
540
+ def get_output_fn(user_id):
541
+ """Retreive the encrypted data from the server."""
542
+
543
+ print("\n------------ Step 5.1: Get output")
544
+
545
+ if is_none(int(user_id)) or len(glob(f"{SERVER_ENCRYPTED_INPUT_DIR}/encrypted_window_*")) == 0:
546
+ msg = "❌ Error during data transmission: The server did not receive the data, so the FHE process could not be performed."
547
+ print(msg)
548
+ yield {get_output_btn: gr.update(visible=True, value=msg)}
549
+ return
550
+
551
+ yield {
552
+ get_output_btn: gr.update(value="🔄 Processing... Please wait."),
553
+ decrypt_btn: gr.update(interactive=False),
554
+ }
555
+
556
+ data = {
557
+ "user_id": f"user_{user_id:.0f}",
558
+ "root_dir": str(ROOT_DIR),
559
+ }
560
+
561
+ # Retrieve the encrypted output
562
+ url = SERVER_URL + "get_output"
563
+ print(f"{url=}")
564
+
565
+ with requests.post(url=url, data=data) as response:
566
+ if response.ok:
567
+ msg = (
568
+ "Data sent to the Client ✅"
569
+ if response.ok
570
+ else "❌ Error in receiving data from the server"
571
+ )
572
+ yhat_encrypted = load_pickle_from_zip(CLIENT_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl")
573
+ assert len(yhat_encrypted) == META["NW"]
574
+
575
+ yield {
576
+ get_output_btn: gr.update(value=msg, interactive=False if "✅" in msg else True),
577
+ decrypt_btn: gr.update(interactive=True),
578
+ }
579
+ return
580
+
581
+
582
+ def decrypt_fn(user_id):
583
+ """Dencrypt the data on the Client Side."""
584
+
585
+ print("\n------------ Step 6: Decrypt output")
586
+
587
+ if (
588
+ is_none(int(user_id))
589
+ or not (CLIENT_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl").is_file()
590
+ ):
591
+ print("Error in decryption step: Please run the FHE execution, first.")
592
+ yield {
593
+ decrypt_btn: gr.update(
594
+ visible=True,
595
+ value="❌ Ensure the input is precessed and retrieved from the server",
596
+ ),
597
+ }
598
+
599
+ return
600
+
601
+ yield {decrypt_btn: gr.update(visible=True, value="🔄 Processing... Please wait.")}
602
+
603
+ yhat_encrypted = load_pickle_from_zip(CLIENT_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl")
604
+
605
+ # Retrieve the client API
606
+ client = FHEModelClient(path_dir=SHARED_SMOOTHER_MODULE_DIR, key_dir=SHARED_SMOOTHER_MODULE_DIR)
607
+ client.load()
608
+
609
+ yhat = []
610
+ for encrypted_i in yhat_encrypted:
611
+ # Deserialize, decrypt and post-process the encrypted output
612
+ output = client.deserialize_decrypt_dequantize(encrypted_i)
613
+ y_pred = numpy.argmax(output, axis=-1)[0]
614
+ yhat.append(y_pred)
615
+
616
+ yhat = numpy.array(yhat)
617
+
618
+ proportion = compute_distribution(yhat.flatten())
619
+ _ = pie_output_plot_img(copy.copy(proportion))
620
+
621
+ yield {
622
+ decrypt_btn: gr.update(value="Output decrypted ✅", interactive=False),
623
+ pie_plot_output: gr.update(
624
+ value=Image.open(PREDICTION_IMG_PATH),
625
+ visible=True,
626
+ show_label=False,
627
+ show_download_button=False,
628
+ container=False,
629
+ ),
630
+ user_id_btn: gr.update(value=None),
631
+ }
632
+ return
633
+
634
+
635
+ def create_pie_chart(ax, data, title, highlight=False, largest_piece=False, simulation=True):
636
+
637
+ sorted_indices = numpy.argsort(data)[::-1]
638
+ if data[sorted_indices[0]] == 1:
639
+ sorted_indices = [sorted_indices[0]]
640
+
641
+ sorted_data = data[sorted_indices]
642
+ sorted_labels = [LABELS[i] for i in sorted_indices]
643
+ sorted_colors = [COLORS[i] for i in sorted_indices]
644
+
645
+ ## Keep only the 2 biggest parts
646
+ if simulation and not data[sorted_indices[0]] == 1:
647
+ top_data = sorted_data[:2] # First two largest proportions
648
+ others_data = sorted_data[2:].sum() # Sum of the rest
649
+ sorted_data = numpy.concatenate([top_data, [others_data]]) # Include "others"
650
+
651
+ sorted_labels = sorted_labels[:2] + ["Others"] # First two labels + "Others"
652
+ sorted_colors = sorted_colors[:2] + ["#D3D3D3"] # Gray color for "Others"
653
+
654
+ if highlight:
655
+ explode = [0.15 for _ in range(len(sorted_data))]
656
+ else:
657
+ explode = [0.09 if i == 0 else 0 for i in range(len(sorted_data))]
658
+
659
+ wedges, _, _ = ax.pie(
660
+ sorted_data,
661
+ labels=sorted_labels,
662
+ colors=sorted_colors,
663
+ autopct=lambda x: f"{round(x)}%",
664
+ pctdistance=0.7,
665
+ labeldistance=1.1,
666
+ shadow=True,
667
+ explode=explode,
668
+ radius=1.9 if highlight else 1.0,
669
+ )
670
+
671
+ if largest_piece:
672
+ # Highlight the largest wedge with a black edge
673
+ wedges[0].set_edgecolor("black")
674
+ wedges[0].set_linewidth(2)
675
+
676
+ ax.set_title(title, fontsize=10, weight="bold")
677
+
678
+ if highlight:
679
+ for wedge in wedges:
680
+ wedge.set_edgecolor("black")
681
+ wedge.set_linewidth(3)
682
+
683
+ ax.set_title(title, fontsize=14, weight="bold")
684
+
685
+ ax.axis("equal") # Ensure the pie chart is drawn as a circle
686
+
687
+
688
+ def pie_ethnicity_simulation_plot_img(lineages, labels):
689
+ """Generates a pie chart for genetic lineage simulation across multiple generations."""
690
+
691
+ n_generations = len(lineages) - 1
692
+
693
+ fig, axes = plt.subplots(n_generations, 3, figsize=(10, 4 * n_generations))
694
+
695
+ fig.suptitle("Genetic Lineage Simulator", fontsize=16, weight="bold", x=1)
696
+
697
+ for gen in range(n_generations):
698
+ parent1, parent2 = lineages.pop(0)
699
+ descendant = lineages[0][0]
700
+ label = labels.pop(0)
701
+
702
+ print(f"Generation {gen}: Parent 1: {parent1} + Parent 2 {parent2} = Child {descendant}")
703
+
704
+ ax_gen = axes[gen] if n_generations > 1 else axes
705
+
706
+ create_pie_chart(ax_gen[0], parent1, label[0])
707
+ create_pie_chart(ax_gen[1], parent2, label[1])
708
+
709
+ # Check if it's the last descendant, highlight it
710
+ is_last = gen == n_generations - 1
711
+ create_pie_chart(
712
+ ax_gen[2],
713
+ descendant,
714
+ f"Last progeny (Generation {n_generations + 1})" if is_last else label[2],
715
+ highlight=is_last,
716
+ )
717
+
718
+ plt.subplots_adjust(right=2)
719
+
720
+ plt.savefig(FAMILY_TREE_IMG_PATH, format="png", bbox_inches="tight")
721
+
722
+ buf = io.BytesIO()
723
+ plt.savefig(buf, format="png")
724
+ buf.seek(0)
725
+ plt.close(fig)
726
+
727
+ return Image.open(buf)
728
+
729
+
730
+ def pie_output_plot_img(data, simulation=False):
731
+ """Generates a pie chart based on the ethnic proportions."""
732
+
733
+ fig, ax = plt.subplots(figsize=(10, 8))
734
+
735
+ create_pie_chart(
736
+ ax,
737
+ data,
738
+ "Predicted ethnicity distribution using FHE",
739
+ highlight=True,
740
+ largest_piece=True,
741
+ simulation=simulation,
742
+ )
743
+
744
+ plt.savefig(PREDICTION_IMG_PATH, format="png", bbox_inches="tight")
745
+
746
+ buf = io.BytesIO()
747
+ plt.savefig(buf, format="png")
748
+ buf.seek(0)
749
+ plt.close(fig) # Close the plot to free memory
750
+ return Image.open(buf)
751
+
752
+
753
+ CSS = """
754
+ #accordion-label { /* Custom styling for the Accordion title */
755
+ background-color: #f0f0f0 !important; /* Set the background color to gray */
756
+ }
757
+
758
+
759
+ #ie_plot_output { /* Target the image output container */
760
+ align-items: center;
761
+ justify-content: center;
762
+ margin: auto; /* Ensure it is centered */
763
+ }
764
+ """
765
+
766
+ if __name__ == "__main__":
767
+
768
+ print("Starting demo ...")
769
+
770
+ print(META)
771
+
772
+ reset()
773
+
774
+ with gr.Blocks(css=CSS) as demo:
775
+
776
+ gr.Markdown()
777
+ gr.Markdown(
778
+ """
779
+ <p align="center">
780
+ <img width=200 src="https://user-images.githubusercontent.com/5758427/197816413-d9cddad3-ba38-4793-847d-120975e1da11.png">
781
+ </p>
782
+ """
783
+ )
784
+ gr.Markdown()
785
+ gr.Markdown(
786
+ """<h2 align="center">Encrypted DNA Testing Using Fully Homomorphic Encryption</h2>"""
787
+ )
788
+ gr.Markdown()
789
+ gr.Markdown(
790
+ """
791
+ <p align="center">
792
+ <a href="https://github.com/zama-ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197972109-faaaff3e-10e2-4ab6-80f5-7531f7cfb08f.png">Concrete-ML</a>
793
+
794
+ <a href="https://docs.zama.ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197976802-fddd34c5-f59a-48d0-9bff-7ad1b00cb1fb.png">Documentation</a>
795
+
796
+ <a href="https://zama.ai/community"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197977153-8c9c01a7-451a-4993-8e10-5a6ed5343d02.png">Community</a>
797
+
798
+ <a href="https://twitter.com/zama_fhe"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197975044-bab9d199-e120-433b-b3be-abd73b211a54.png">@zama_fhe</a>
799
+ </p>
800
+ """
801
+ )
802
+
803
+ gr.Markdown()
804
+
805
+ gr.Markdown(
806
+ """
807
+ <p align='center'> DNA testing platforms analyze your genetic data in the clear, leaving it vulnerable to hacks. With Fully Homomorphic Encryption (FHE), they could perform this analysis on encrypted data, ensuring your sensitive information remains safe, even during processing, allowing to get the knowledge without the risks.</p>
808
+
809
+ <p align='center'> In this demo, we show you how to perform encrypted DNA analysis using FHE and Zama's Concrete ML <a href='https://github.com/zama-ai/concrete-ml' target=library</a>library</p>
810
+ """
811
+ )
812
+
813
+ gr.Markdown()
814
+ gr.Markdown(
815
+ """
816
+ <p align="center">
817
+ <img width="75%" height="30%" src="https://raw.githubusercontent.com/kcelia/Img/main/dna_banner.png">
818
+ </p>
819
+ """
820
+ )
821
+
822
+ with gr.Accordion("How does it work?", elem_id="accordion-label", open=False):
823
+ gr.Markdown(
824
+ """
825
+ **In FHE, two special keys are created to make secure, private DNA analysis possible:**
826
+
827
+ - Secret key (your personal lock and key): This is like your own unique lock and key. You use it to encrypt (lock up) your DNA
828
+ data so that no one else can read it. You also use it to decrypt (unlock) the results after they've been processed.
829
+ - Evaluation key (a safe tool for the DNA company): This is a special key you provide to the DNA analysis company. It allows
830
+ them to perform their analyses on your encrypted DNA data without decrypting it. Think of it as giving them specialized tools
831
+ that let them work on your locked box without needing to open it.
832
+
833
+ **How it works:**
834
+
835
+ 1. You encrypt your DNA data: Using your secret key, you lock up your DNA information so it's unreadable to anyone else.
836
+ 2. You send the encrypted DNA data and evaluation key to the DNA company: The company receives your encrypted DNA data
837
+ along with the evaluation key. They can't see your actual genetic information because it's securely locked.
838
+ 3. The DNA company processes data without seeing it: Using the evaluation key, the company runs their genetic analysis
839
+ algorithms on your encrypted data. They might assess health risks, ancestry information, or genetic traits—all without ever
840
+ unlocking your DNA data.
841
+ 4. You decrypt the results: After processing, the company sends back the encrypted results of their analysis. You use your
842
+ secret key to decrypt and view the findings.
843
+
844
+ **In simple terms:**
845
+
846
+ FHE allows you to get your DNA analyzed without the DNA company ever seeing your actual genetic code. You keep your DNA
847
+ data securely locked with your secret key and give the company a special tool (the evaluation key) that lets them perform the
848
+ analysis without unlocking your data. This way, you receive personalized genetic insights while keeping your most sensitive
849
+ information private.
850
+ """
851
+ )
852
+
853
+ gr.Markdown("<hr />")
854
+ gr.Markdown("# Step 1: Generate Genetic Lineage Simulator")
855
+
856
+ gr.Markdown(
857
+ """
858
+ To start this demo, the simulation randomly picks *N* individuals over *G* generations, from a genetic dataset.
859
+
860
+ Each individual is represented by two alleles from chromosome *22*, which is particularly relevent for tracing human evolutionary history and migration patterns across the world. By analyzing specific markers known as Single Nucleotide Polymorphisms (SNPs) at key positions on this chromosome, valuable insights can be gained.
861
+
862
+ Each ancestor transmits half of their genetic material, with *50%* of our genes coming from the mother and *50%* from the father.
863
+ These genes are organized into pairs of alleles, one from each parent.
864
+
865
+ A gene can be dominant, meaning it is expressed and determines a visible trait, or recessive, remaining unexpressed but still present in the genome.
866
+ A recessive allele may manifest in future generations if both parents pass it on.
867
+
868
+ Five distinct genetic populations will be used in this simulation: **Americas, African, European, East Asian** and **South Asian**.
869
+
870
+ If you're curious to learn more about this simulation algorithm, you can refer to the code [here](https://github.com/Soptq/encDNA).
871
+ """
872
+ )
873
+
874
+ simulate_btn = gr.Button("Generate a random genetic allele", elem_id="input-box")
875
+
876
+ ethnicity_simulation_img = gr.Image(
877
+ visible=False,
878
+ container=False,
879
+ show_download_button=False,
880
+ mirror_webcam=False,
881
+ elem_id="img",
882
+ )
883
+
884
+ gr.Markdown(
885
+ """
886
+ The percentages you see above represent the two predominant genes transmitted to a progeny. Whether they are expressed or not is beyond the scope of this demo.
887
+ Below is the vector representing the allele, generated above.
888
+ """
889
+ )
890
+
891
+ clear_input_box = gr.Textbox(label="Unencrypted Allele:", visible=True)
892
+
893
+ gr.Markdown(
894
+ """
895
+ In practice, each individual is represented as a binary vector of size **1,059,079**,
896
+ where each value corresponds to a genetic variation at a specific position on the chromosome: 1 represents the presence of a particular SNP, while 0 indicates its absence.
897
+ """
898
+ )
899
+
900
+ simulate_text = gr.Markdown(visible=False)
901
+
902
+ gr.Markdown("# Step 2: Encrypt the DNA on the Client Side")
903
+
904
+ gr.Markdown(
905
+ """
906
+ ⚠️ Important note: Encrypting an allele with more than a million values in FHE may take some time.
907
+ """
908
+ )
909
+
910
+ gen_key_btn = gr.Button("Generate the secret and public keys")
911
+ user_id_btn = gr.Number(value=USER_ID, visible=False)
912
+
913
+ # gr.HTML("<div style='height: 24px;'></div>")
914
+ encrypt_btn = gr.Button("Encrypt the data using the secret key")
915
+ encrypt_input_box = gr.Textbox(label="Encrypted Allele:", max_lines=15, visible=True)
916
+ send_btn = gr.Button("Send data to the server")
917
+
918
+ gr.Markdown("<hr />")
919
+ gr.Markdown("# Step 3: FHE Computation on the Server Side ")
920
+ gr.Markdown(
921
+ """
922
+ ⚠️ Important note: Processing such a large input in FHE may take some time, potentially up to 5 minutes for one allele of size *1,059,079*.
923
+ To learn more about the selected ML model, check out this detailed [blog post](https://www.zama.ai/post/build-an-end-to-end-encrypted-23andme-genetic-testing-application-using-concrete-ml-fully-homomorphic-encryption).
924
+ """
925
+ )
926
+
927
+ run_fhe_btn = gr.Button("Run FHE on the server")
928
+ get_output_btn = gr.Button("Send data to the client")
929
+
930
+ gr.Markdown("<hr />")
931
+ gr.Markdown("# Step 4: Decrypt the Result on the Client Side")
932
+
933
+ decrypt_btn = gr.Button("Decrypt the data using the secret key")
934
+
935
+ pie_plot_output = gr.Image(
936
+ visible=False,
937
+ height=600,
938
+ width=600,
939
+ container=False,
940
+ show_download_button=False,
941
+ mirror_webcam=False,
942
+ elem_id="ie_plot_output",
943
+ )
944
+
945
+ gr.Markdown(
946
+ """
947
+ With FHE, the entire process remains encrypted end-to-end. Hence, you do not have to worry about data misuse, unauthorized analysis on your DNA, or data leaks.
948
+ Using FHE, privacy is guaranteed, and trusting the server is no longer a concern.
949
+ """,
950
+ visible=False,
951
+ )
952
+
953
+ gr.Markdown("<hr />")
954
+ gr.Markdown(
955
+ """
956
+ The app was built with [Concrete ML](https://github.com/zama-ai/concrete-ml), a Privacy-Preserving Machine Learning (PPML) open-source set of tools by Zama.
957
+ Try it yourself and don't forget to star on [Github](https://github.com/zama-ai/concrete-ml) ⭐.
958
+ """
959
+ )
960
+ gr.Markdown()
961
+ gr.Markdown(
962
+ """
963
+ **Note that:** This space and the results produced by this simulation are for educational and illustrative purposes only.
964
+ They are not intended to provide actual genetic analysis or be used as a substitute for a professional genetic testing.
965
+ """
966
+ )
967
+
968
+ ############################################################################# Click buttons
969
+
970
+ simulate_btn.click(
971
+ fn=simulate_allele_fn,
972
+ outputs=[clear_input_box, ethnicity_simulation_img, simulate_btn, simulate_text],
973
+ )
974
+
975
+ gen_key_btn.click(
976
+ key_gen_fn,
977
+ inputs=[user_id_btn],
978
+ outputs=[gen_key_btn],
979
+ )
980
+
981
+ encrypt_btn.click(
982
+ fn=encrypt_fn,
983
+ inputs=[user_id_btn],
984
+ outputs=[
985
+ encrypt_btn,
986
+ encrypt_input_box,
987
+ simulate_btn,
988
+ send_btn,
989
+ run_fhe_btn,
990
+ get_output_btn,
991
+ decrypt_btn,
992
+ ],
993
+ )
994
+
995
+ send_btn.click(
996
+ fn=send_input_fn,
997
+ inputs=[user_id_btn],
998
+ outputs=[send_btn, run_fhe_btn, get_output_btn, decrypt_btn],
999
+ )
1000
+
1001
+ run_fhe_btn.click(
1002
+ fn=run_fhe_fn, inputs=[user_id_btn], outputs=[run_fhe_btn, get_output_btn, decrypt_btn]
1003
+ )
1004
+
1005
+ get_output_btn.click(
1006
+ fn=get_output_fn, inputs=[user_id_btn], outputs=[get_output_btn, decrypt_btn]
1007
+ )
1008
+
1009
+ decrypt_btn.click(
1010
+ fn=decrypt_fn, inputs=[user_id_btn], outputs=[decrypt_btn, pie_plot_output, user_id_btn]
1011
+ )
1012
+
1013
+ demo.queue()
1014
+ demo.launch()
server.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from glob import glob
3
+ from pathlib import Path
4
+ from typing import List
5
+
6
+ from fastapi import FastAPI, File, Form, UploadFile
7
+ from fastapi.responses import JSONResponse, Response
8
+ from tqdm import tqdm
9
+ from utils import *
10
+
11
+ from concrete.ml.deployment import FHEModelClient, FHEModelServer
12
+
13
+ # Load the FHE server
14
+
15
+ # Initialize an instance of FastAPI
16
+ app = FastAPI()
17
+
18
+
19
+ # Define the default route
20
+ @app.get("/")
21
+ def root():
22
+ """
23
+ Root endpoint of the health prediction API.
24
+ Returns:
25
+ dict: The welcome message.
26
+ """
27
+ return {"message": "Welcome to your encrypted DNA testing use-case with FHE!"}
28
+
29
+
30
+ @app.post("/send_input")
31
+ def send_input(
32
+ user_id: str = Form(...), root_dir: str = Form(...), files: List[UploadFile] = File(...)
33
+ ):
34
+ """Send the inputs to the server."""
35
+
36
+ print("------------ Step 3.2: Send the data to the server")
37
+
38
+ print(f"{user_id=}, {root_dir=}, {len(files)=}")
39
+
40
+ SERVER_DIR = Path(root_dir) / f"{user_id}/server"
41
+
42
+ SERVER_KEY_SMOOTHER_MODULE_DIR = SERVER_DIR / KEY_SMOOTHER_MODULE_DIR
43
+ SERVER_KEY_BASE_MODULE_DIR = SERVER_DIR / KEY_BASE_MODULE_DIR
44
+ SERVER_ENCRYPTED_INPUT_DIR = SERVER_DIR / ENCRYPTED_INPUT_DIR
45
+
46
+ # Save the files using the above paths
47
+ with (SERVER_KEY_BASE_MODULE_DIR / "eval_key").open("wb") as eval_key_1:
48
+ eval_key_1.write(files[0].file.read())
49
+
50
+ with (SERVER_KEY_SMOOTHER_MODULE_DIR / "eval_key").open("wb") as eval_key_2:
51
+ eval_key_2.write(files[1].file.read())
52
+
53
+ print(f"{len(files)=}")
54
+ for i in tqdm(range(2, len(files))):
55
+ with (SERVER_ENCRYPTED_INPUT_DIR / f"encrypted_window_{i}").open("wb") as eval_key_2:
56
+ eval_key_2.write(files[i].file.read())
57
+
58
+
59
+ @app.post("/run_fhe")
60
+ def run_fhe(
61
+ user_id: str = Form(),
62
+ root_dir: str = Form(...),
63
+ ):
64
+ """Inference in FHE."""
65
+ print("------------ Step 4.2: Run in FHE on the Server Side")
66
+ print(f"{user_id=}, {root_dir=}")
67
+
68
+ SERVER_DIR = Path(root_dir) / f"{user_id}/server"
69
+
70
+ SERVER_KEY_SMOOTHER_MODULE_DIR = SERVER_DIR / KEY_SMOOTHER_MODULE_DIR
71
+ SERVER_KEY_BASE_MODULE_DIR = SERVER_DIR / KEY_BASE_MODULE_DIR
72
+ SERVER_ENCRYPTED_INPUT_DIR = SERVER_DIR / ENCRYPTED_INPUT_DIR
73
+ SERVER_ENCRYPTED_OUTPUT_DIR = SERVER_DIR / ENCRYPTED_OUTPUT_DIR
74
+
75
+ with (SERVER_KEY_BASE_MODULE_DIR / "eval_key").open("rb") as eval_key_1:
76
+ eval_key_base_module = eval_key_1.read()
77
+ assert isinstance(eval_key_base_module, bytes)
78
+
79
+ with (SERVER_KEY_SMOOTHER_MODULE_DIR / "eval_key").open("rb") as eval_key_2:
80
+ eval_key_smoother_module = eval_key_2.read()
81
+ assert isinstance(eval_key_smoother_module, bytes)
82
+
83
+ shared_base_modules_path = glob(f"{SHARED_BASE_MODULE_DIR}/model_*")
84
+ shared_base_modules_path = sorted(shared_base_modules_path, key=extract_model_number)
85
+ print(f"{len(shared_base_modules_path)=}")
86
+ assert len(shared_base_modules_path) == META["NW"]
87
+
88
+ client_encrypted_input_path = glob(f"{SERVER_ENCRYPTED_INPUT_DIR}/encrypted_window_*")
89
+ client_encrypted_input_path = sorted(client_encrypted_input_path, key=extract_model_number)
90
+ print(f"{len(client_encrypted_input_path)=}")
91
+ assert len(shared_base_modules_path) == META["NW"]
92
+
93
+ nb_total_iterations = META["NW"] * 2
94
+
95
+ start_time = time.time()
96
+ y_proba = []
97
+ for i, (model_path, encrypted_window_path) in tqdm(
98
+ enumerate(zip(shared_base_modules_path, client_encrypted_input_path))
99
+ ):
100
+ server = FHEModelServer(model_path)
101
+ with open(encrypted_window_path, "rb") as f:
102
+ encrypted_window = f.read()
103
+
104
+ encrypted_output = server.run(
105
+ encrypted_window, serialized_evaluation_keys=eval_key_base_module
106
+ )
107
+ assert isinstance(encrypted_output, bytes)
108
+
109
+ client = FHEModelClient(model_path, key_dir=model_path)
110
+ decrypted_output = client.deserialize_decrypt_dequantize(encrypted_output)
111
+
112
+ with (SERVER_ENCRYPTED_OUTPUT_DIR / f"decrypted_window_{i}").open("wb") as f:
113
+ f.write(encrypted_window)
114
+
115
+ y_proba.append(decrypted_output)
116
+
117
+ with open(FHE_COMPUTATION_TIMELINE, "w", encoding="utf-8") as f:
118
+ f.write(f"{time.time() - start_time:.2f} seconds ({(i + 1)/nb_total_iterations:.0%})")
119
+
120
+ client = FHEModelClient(SHARED_SMOOTHER_MODULE_DIR, key_dir=SHARED_SMOOTHER_MODULE_DIR)
121
+ server = FHEModelServer(SHARED_SMOOTHER_MODULE_DIR)
122
+
123
+ y_proba = numpy.transpose(numpy.array(y_proba), (1, 0, 2))
124
+ y_proba = y_proba.astype(numpy.int8)
125
+ print(f"{y_proba.shape=}, {type(y_proba)}")
126
+
127
+ X_slide, _ = slide_window(y_proba, META["SS"])
128
+
129
+ yhat_encrypted = []
130
+ for i in tqdm(range(len(X_slide))):
131
+ input = X_slide[i].reshape(1, -1)
132
+ encrypted_input = client.quantize_encrypt_serialize(input)
133
+ encrypted_output = server.run(
134
+ encrypted_input, serialized_evaluation_keys=eval_key_smoother_module
135
+ )
136
+ # output = client.deserialize_decrypt_dequantize(encrypted_output)
137
+ # y_pred = numpy.argmax(output, axis=-1)[0]
138
+ yhat_encrypted.append(encrypted_output)
139
+
140
+ with open(FHE_COMPUTATION_TIMELINE, "w", encoding="utf-8") as f:
141
+ f.write(f"{time.time() - start_time:.2f} seconds ({(i + 1)/nb_total_iterations:.0%})")
142
+
143
+ write_pickle(SERVER_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl", yhat_encrypted)
144
+
145
+ fhe_execution_time = round(time.time() - start_time, 2)
146
+
147
+ return JSONResponse(content=fhe_execution_time)
148
+
149
+
150
+ @app.post("/run_fhe_stage1")
151
+ def run_fhe_stage1(
152
+ user_id: str = Form(),
153
+ root_dir: str = Form(...),
154
+ ):
155
+ """Inference in FHE."""
156
+ print("------------ Step 4.2: Run in FHE on the Server Side")
157
+ print(f"{user_id=}, {root_dir=}")
158
+
159
+ SERVER_DIR = Path(root_dir) / f"{user_id}/server"
160
+
161
+ SERVER_KEY_SMOOTHER_MODULE_DIR = SERVER_DIR / KEY_SMOOTHER_MODULE_DIR
162
+ SERVER_KEY_BASE_MODULE_DIR = SERVER_DIR / KEY_BASE_MODULE_DIR
163
+ SERVER_ENCRYPTED_INPUT_DIR = SERVER_DIR / ENCRYPTED_INPUT_DIR
164
+ SERVER_ENCRYPTED_OUTPUT_DIR = SERVER_DIR / ENCRYPTED_OUTPUT_DIR
165
+
166
+ with (SERVER_KEY_BASE_MODULE_DIR / "eval_key").open("rb") as eval_key_1:
167
+ eval_key_base_module = eval_key_1.read()
168
+ assert isinstance(eval_key_base_module, bytes)
169
+
170
+ with (SERVER_KEY_SMOOTHER_MODULE_DIR / "eval_key").open("rb") as eval_key_2:
171
+ eval_key_smoother_module = eval_key_2.read()
172
+ assert isinstance(eval_key_smoother_module, bytes)
173
+
174
+ shared_base_modules_path = glob(f"{SHARED_BASE_MODULE_DIR}/model_*")
175
+ shared_base_modules_path = sorted(shared_base_modules_path, key=extract_model_number)
176
+ print(f"{len(shared_base_modules_path)=}")
177
+ assert len(shared_base_modules_path) == META["NW"]
178
+
179
+ client_encrypted_input_path = glob(f"{SERVER_ENCRYPTED_INPUT_DIR}/encrypted_window_*")
180
+ client_encrypted_input_path = sorted(client_encrypted_input_path, key=extract_model_number)
181
+ print(f"{len(client_encrypted_input_path)=}")
182
+ assert len(shared_base_modules_path) == META["NW"]
183
+
184
+ start = time.time()
185
+ y_proba = []
186
+ for i, (model_path, encrypted_window_path) in tqdm(
187
+ enumerate(zip(shared_base_modules_path, client_encrypted_input_path))
188
+ ):
189
+ server = FHEModelServer(model_path)
190
+ with open(encrypted_window_path, "rb") as f:
191
+ encrypted_window = f.read()
192
+
193
+ encrypted_output = server.run(
194
+ encrypted_window, serialized_evaluation_keys=eval_key_base_module
195
+ )
196
+ assert isinstance(encrypted_output, bytes)
197
+
198
+ client = FHEModelClient(model_path, key_dir=model_path)
199
+ decrypted_output = client.deserialize_decrypt_dequantize(encrypted_output)
200
+
201
+ with (SERVER_ENCRYPTED_OUTPUT_DIR / f"decrypted_window_{i}").open("wb") as f:
202
+ f.write(encrypted_window)
203
+
204
+ y_proba.append(decrypted_output)
205
+
206
+ client = FHEModelClient(SHARED_SMOOTHER_MODULE_DIR, key_dir=SHARED_SMOOTHER_MODULE_DIR)
207
+ server = FHEModelServer(SHARED_SMOOTHER_MODULE_DIR)
208
+
209
+ y_proba = numpy.transpose(numpy.array(y_proba), (1, 0, 2))
210
+ y_proba = y_proba.astype(numpy.int8)
211
+ print(f"{y_proba.shape=}, {type(y_proba)}")
212
+
213
+ X_slide, _ = slide_window(y_proba, META["SS"])
214
+
215
+ yhat_encrypted = []
216
+ for i in tqdm(range(len(X_slide))):
217
+ input = X_slide[i].reshape(1, -1)
218
+ encrypted_input = client.quantize_encrypt_serialize(input)
219
+ encrypted_output = server.run(
220
+ encrypted_input, serialized_evaluation_keys=eval_key_smoother_module
221
+ )
222
+ # output = client.deserialize_decrypt_dequantize(encrypted_output)
223
+ # y_pred = numpy.argmax(output, axis=-1)[0]
224
+ yhat_encrypted.append(encrypted_output)
225
+
226
+ write_pickle(SERVER_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl", yhat_encrypted)
227
+
228
+ fhe_execution_time = round(time.time() - start, 2)
229
+
230
+ return JSONResponse(content=fhe_execution_time)
231
+
232
+
233
+ @app.post("/run_fhe_stage2")
234
+ def run_fhe_stage2(
235
+ user_id: str = Form(),
236
+ root_dir: str = Form(...),
237
+ ):
238
+ """Inference in FHE."""
239
+ print("------------ Step 4.2: Run in FHE on the Server Side")
240
+ print(f"{user_id=}, {root_dir=}")
241
+
242
+ SERVER_DIR = Path(root_dir) / f"{user_id}/server"
243
+
244
+ SERVER_KEY_SMOOTHER_MODULE_DIR = SERVER_DIR / KEY_SMOOTHER_MODULE_DIR
245
+ SERVER_KEY_BASE_MODULE_DIR = SERVER_DIR / KEY_BASE_MODULE_DIR
246
+ SERVER_ENCRYPTED_INPUT_DIR = SERVER_DIR / ENCRYPTED_INPUT_DIR
247
+ SERVER_ENCRYPTED_OUTPUT_DIR = SERVER_DIR / ENCRYPTED_OUTPUT_DIR
248
+
249
+ with (SERVER_KEY_BASE_MODULE_DIR / "eval_key").open("rb") as eval_key_1:
250
+ eval_key_base_module = eval_key_1.read()
251
+ assert isinstance(eval_key_base_module, bytes)
252
+
253
+ with (SERVER_KEY_SMOOTHER_MODULE_DIR / "eval_key").open("rb") as eval_key_2:
254
+ eval_key_smoother_module = eval_key_2.read()
255
+ assert isinstance(eval_key_smoother_module, bytes)
256
+
257
+ shared_base_modules_path = glob(f"{SHARED_BASE_MODULE_DIR}/model_*")
258
+ shared_base_modules_path = sorted(shared_base_modules_path, key=extract_model_number)
259
+ print(f"{len(shared_base_modules_path)=}")
260
+ assert len(shared_base_modules_path) == META["NW"]
261
+
262
+ client_encrypted_input_path = glob(f"{SERVER_ENCRYPTED_INPUT_DIR}/encrypted_window_*")
263
+ client_encrypted_input_path = sorted(client_encrypted_input_path, key=extract_model_number)
264
+ print(f"{len(client_encrypted_input_path)=}")
265
+ assert len(shared_base_modules_path) == META["NW"]
266
+
267
+ start = time.time()
268
+ y_proba = []
269
+ for i, (model_path, encrypted_window_path) in tqdm(
270
+ enumerate(zip(shared_base_modules_path, client_encrypted_input_path))
271
+ ):
272
+ server = FHEModelServer(model_path)
273
+ with open(encrypted_window_path, "rb") as f:
274
+ encrypted_window = f.read()
275
+
276
+ encrypted_output = server.run(
277
+ encrypted_window, serialized_evaluation_keys=eval_key_base_module
278
+ )
279
+ assert isinstance(encrypted_output, bytes)
280
+
281
+ client = FHEModelClient(model_path, key_dir=model_path)
282
+ decrypted_output = client.deserialize_decrypt_dequantize(encrypted_output)
283
+
284
+ with (SERVER_ENCRYPTED_OUTPUT_DIR / f"decrypted_window_{i}").open("wb") as f:
285
+ f.write(encrypted_window)
286
+
287
+ y_proba.append(decrypted_output)
288
+
289
+ client = FHEModelClient(SHARED_SMOOTHER_MODULE_DIR, key_dir=SHARED_SMOOTHER_MODULE_DIR)
290
+ server = FHEModelServer(SHARED_SMOOTHER_MODULE_DIR)
291
+
292
+ y_proba = numpy.transpose(numpy.array(y_proba), (1, 0, 2))
293
+ y_proba = y_proba.astype(numpy.int8)
294
+ print(f"{y_proba.shape=}, {type(y_proba)}")
295
+
296
+ X_slide, _ = slide_window(y_proba, META["SS"])
297
+
298
+ yhat_encrypted = []
299
+ for i in tqdm(range(len(X_slide))):
300
+ input = X_slide[i].reshape(1, -1)
301
+ encrypted_input = client.quantize_encrypt_serialize(input)
302
+ encrypted_output = server.run(
303
+ encrypted_input, serialized_evaluation_keys=eval_key_smoother_module
304
+ )
305
+ # output = client.deserialize_decrypt_dequantize(encrypted_output)
306
+ # y_pred = numpy.argmax(output, axis=-1)[0]
307
+ yhat_encrypted.append(encrypted_output)
308
+
309
+ write_pickle(SERVER_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl", yhat_encrypted)
310
+
311
+ fhe_execution_time = round(time.time() - start, 2)
312
+
313
+ return JSONResponse(content=fhe_execution_time)
314
+
315
+
316
+ @app.post("/get_output")
317
+ def get_output(user_id: str = Form(), root_dir: str = Form()):
318
+ """Retrieve the encrypted output from the server."""
319
+
320
+ print("\nStep 5.2: Get the output from the server ............\n")
321
+ SERVER_DIR = Path(root_dir) / f"{user_id}/server"
322
+ SERVER_ENCRYPTED_OUTPUT_DIR = SERVER_DIR / ENCRYPTED_OUTPUT_DIR
323
+
324
+ yhat_encrypted = load_pickle(SERVER_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl")
325
+
326
+ CLIENT_DIR = Path(root_dir) / f"{user_id}/client"
327
+ CLIENT_ENCRYPTED_OUTPUT_DIR = CLIENT_DIR / ENCRYPTED_OUTPUT_DIR
328
+
329
+ write_pickle(CLIENT_ENCRYPTED_OUTPUT_DIR / "encrypted_final_output.pkl", yhat_encrypted)
330
+ assert len(yhat_encrypted) == META["NW"]
331
+
332
+ time.sleep(1)
333
+
334
+ # Send the encrypted output
335
+ return Response("OK")
utils.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import random
3
+ import shutil
4
+ from collections import Counter
5
+ from pathlib import Path
6
+
7
+ import numpy
8
+
9
+ import zipfile
10
+
11
+
12
+ SERVER_URL = "http://localhost:8000/"
13
+
14
+ INPUT_BROWSER_LIMIT = 550
15
+
16
+ DATA_DIR = Path("./data")
17
+ DEPLOYMENT_DIR = Path("./deployment")
18
+ ROOT_DIR = DEPLOYMENT_DIR / "users"
19
+
20
+ SHARED_BASE_MODULE_DIR = DEPLOYMENT_DIR / "base_modules"
21
+ SHARED_SMOOTHER_MODULE_DIR = DEPLOYMENT_DIR / "smoother_module"
22
+
23
+ KEY_SMOOTHER_MODULE_DIR = "EvaluationKey_Smoother"
24
+ KEY_BASE_MODULE_DIR = "EvaluationKey_Base_Modules"
25
+ ENCRYPTED_INPUT_DIR = "Encrypt_Input"
26
+ ENCRYPTED_OUTPUT_DIR = "Encrypt_Output"
27
+ FHE_COMPUTATION_TIMELINE = Path("server_fhe_computation_timeline.txt")
28
+
29
+ LABELS = ["European", "African", "Americas", "East Asian", "South Asian"]
30
+
31
+ ID_POPULATION = {0: "European", 3: "African", 2: "Americas", 1: "East Asian", 4: "South Asian"}
32
+
33
+ POPULATION_ID = {"European": 0, "African": 3, "Americas": 2, "East Asian": 1, "South Asian": 4}
34
+
35
+ COLORS = ["#FFD208", "#FFE46C", "#FFED9C", "#FFF6CE", "#FFD9A0"]
36
+
37
+ # load_pickle("data/meta_dict.pkl")
38
+ META = {"A": 5, "C": 1059079, "M": 10589, "NW": 100, "CT": 1059, "CTR": 0.1, "WSCM": 0.2, "SS": 75}
39
+
40
+ BUILD_GENS = [1, 2, 4, 6, 8, 12, 16, 24, 32, 48]
41
+
42
+
43
+ def load_pickle_from_zip(zip_path, file_name):
44
+ """
45
+ Load a pickle file from within a zip archive.
46
+ """
47
+ with zipfile.ZipFile(zip_path, 'r') as z:
48
+ with z.open(file_name) as f:
49
+ return pickle.load(f)
50
+
51
+
52
+ def generate_weighted_percentages():
53
+ dominant_percentage = random.randint(50, 70)
54
+ remaining_percentage = 100 - dominant_percentage
55
+ other_percentages = [random.random() for _ in range(4)]
56
+
57
+ total = sum(other_percentages)
58
+ other_percentages = [round(p / total * remaining_percentage, 2) for p in other_percentages]
59
+
60
+ percentages = [dominant_percentage] + other_percentages
61
+
62
+ # Adjust the total to be exactly 100 (if rounding errors occurred)
63
+ diff = round(100 - sum(percentages), 2)
64
+ if diff != 0:
65
+ percentages[0] += diff # Adjust the dominant percentage to make the total 100
66
+
67
+ return percentages
68
+
69
+
70
+ def select_random_ancestors():
71
+ ancestors = list(ID_POPULATION.keys())
72
+ random.shuffle(ancestors)
73
+ return ancestors
74
+
75
+
76
+ def read_pickle(path):
77
+ with open(path, "rb") as f:
78
+ data = pickle.load(f)
79
+ return data
80
+
81
+
82
+ def compute_distribution(y, size=5):
83
+ y_pred = numpy.zeros(size)
84
+ for k, v in Counter(y).items():
85
+ y_pred[k] = v / len(y)
86
+ return y_pred
87
+
88
+
89
+ def slide_window(data, smooth_win_size, y=None):
90
+ N, W, A = data.shape
91
+
92
+ pad = (smooth_win_size + 1) // 2
93
+ data_padded = numpy.pad(data, ((0, 0), (pad, pad), (0, 0)), mode="reflect")
94
+ X_slide = numpy.lib.stride_tricks.sliding_window_view(data_padded, (1, smooth_win_size, A))
95
+ X_slide = X_slide[:, :W, :].reshape(N * W, -1)
96
+ y_slide = None if y is None else y.reshape(N * W)
97
+
98
+ return X_slide, y_slide
99
+
100
+
101
+ # def read_vcf(vcf_file):
102
+ # return allel.read_vcf(vcf_file, region=None, fields="*")
103
+
104
+
105
+ def clean_dir(directory):
106
+ """Remove the specified directory if it exists."""
107
+ if directory.exists() and directory.is_dir():
108
+ print(f"Removing existing model directory: {directory}")
109
+ shutil.rmtree(directory)
110
+
111
+
112
+ def process_data_for_base_modules(meta, X_t):
113
+
114
+ n_windows = meta["NW"] # meta["C"] // meta["M"]
115
+ context = meta["CT"] # int(meta["M"] * meta['CTR'])
116
+
117
+ if context != 0.0:
118
+ pad_left = numpy.flip(X_t[:, 0:context], axis=1)
119
+ pad_right = numpy.flip(X_t[:, -context:], axis=1)
120
+ X_t = numpy.concatenate([pad_left, X_t, pad_right], axis=1)
121
+
122
+ M_ = meta["M"] + 2 * context
123
+ idx = numpy.arange(0, meta["C"], meta["M"])[:-2]
124
+ X_b = numpy.lib.stride_tricks.sliding_window_view(X_t, M_, axis=1)[:, idx, :]
125
+ rem = meta["C"] - meta["M"] * n_windows
126
+
127
+ # print(f"{X_t.shape=} -> {X_b.shape=} | {n_windows=}, {context=}, {M_=}, {rem=}")
128
+
129
+ return X_b, n_windows, M_, rem
130
+
131
+
132
+ def extract_model_number(path):
133
+ try:
134
+ return int(path.split("_")[-1])
135
+ except (ValueError, IndexError):
136
+ print(f"Error: Unable to extract model number from path: {path}")
137
+ return None
138
+
139
+
140
+ def is_none(obj) -> bool:
141
+ """
142
+ Check if the object is None.
143
+ Args:
144
+ obj (any): The input to be checked.
145
+ Returns:
146
+ bool: True if the object is None or empty, False otherwise.
147
+ """
148
+ return obj is None or (obj is not None and (hasattr(obj, "__len__") and len(obj) == 0))
149
+
150
+
151
+ def load_pickle(path: str) -> numpy.array:
152
+ """Load data.
153
+
154
+ Args:
155
+ path (str):
156
+
157
+ Returns:
158
+ Dict: The genome.
159
+ """
160
+ with open(path, "rb") as f:
161
+ data = pickle.load(f)
162
+ return data
163
+
164
+
165
+ def write_pickle(path: str, data) -> numpy.array:
166
+ with open(path, "wb") as f:
167
+ pickle.dump(data, f)
168
+
169
+
170
+ def write_bytes(path, data):
171
+ """Save binary data."""
172
+ with path.open("wb") as f:
173
+ f.write(data)
174
+
175
+
176
+ def read_bytes(path):
177
+ """Load data from a binary file."""
178
+ with path.open("rb") as f:
179
+ return f.read()