-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.py
636 lines (528 loc) · 21.4 KB
/
lib.py
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
#!/usr/bin/sage -python
# -*- coding: utf8 -*-
CYELLOW = '\33[33m'
CRED = '\033[91m'
CEND = '\033[0m'
import sys
import argparse
import csv
import tracemalloc
# SageMath imports
from sage.all import (
randint,
matrix,
identity_matrix,
random_matrix,
zero_matrix,
FiniteField,
PolynomialRing,
)
from timeit import default_timer as timer
import multiprocessing as mp
# -------------------------------
def is_monomial(input_matrix, n):
for i in range(0, n, 1):
if len(input_matrix.nonzero_positions_in_row(i)) != 1:
return False
return True
# ----------------
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return func(*args, **kwargs)
wrapper.count = 0
# Return the new decorated function
return wrapper
# ----------------------------------------------
def progress_bar(count_value, total, suffix=''):
bar_length = 100
filled_up_Length = int(round(bar_length* count_value / float(total)))
percentage = round(100.0 * count_value/float(total),1)
bar = '=' * filled_up_Length + '-' * (bar_length - filled_up_Length)
sys.stdout.write('[%s] %s%s ...%s\r' %(bar, percentage, '%', suffix))
sys.stdout.flush()
# -------------------------------
def arguments(args=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Parses command.")
parser.add_argument("-k", "--code_dimension", type=int, help="code dimension", required=False)
parser.add_argument("-m", "--code_size_m", type=int, help="code size (m)", required=False)
parser.add_argument("-n", "--code_size_n", type=int, help="code size (n)", required=True)
parser.add_argument("-q", "--prime", type=int, help="Field characteristic", required=True)
parser.add_argument('-b', '--benchmark', action='store_true', help='Benchmark')
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
options = parser.parse_args(args)
return options
# ------------------------------------------------------
def to_csv_file(file_name: str, data: list, label=True):
with open(file_name, 'a', newline='') as file:
writer = csv.writer(file)
if label:
field = ['n', 'q', '# vars of S_red', 'memory (gigabytes)', 'runtime (seconds)']
writer.writerow(field)
writer.writerow(data.values())
# ------------------------------------------------------
def to_csv_file_header(file_name: str, label=True):
with open(file_name, 'a', newline='') as file:
writer = csv.writer(file)
if label:
field = ['n', 'q', '# vars of S_red', 'memory (gigabytes)', 'runtime (seconds)']
writer.writerow(field)
# ---------------------------------
def sample_invertible_matrix(k, q):
while True:
# Generate a random n x n matrix with entries in Zq
A = random_matrix(FiniteField(q), k, k)
# Check if the matrix is invertible
if A.is_invertible():
return A
# ----------------------------------------
def sample_secret_tensor_product(m, n, q):
A = sample_invertible_matrix(m, q)
B = sample_invertible_matrix(n, q)
return (A.transpose()).tensor_product(B, subdivide=False)
# -------------------------------
def oracle_call_mce(M, mn, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, mn - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
while W.rank() < k :
A_rand = random_matrix(F, k, mn - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:mn]
return [A_rand,B]
# --------------------------------
def oracle_call_imce(M, mn, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, mn - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
while W.rank() < k or Z.rank() < k:
A_rand = random_matrix(F, k, mn - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:mn]
FSC_code = (Z.inverse())*C_code
C = FSC_code[0:k,k:mn]
return [A_rand,B,C]
# ----------------------------------
# sample permutation with fisher-yates
def sample_permutation_matrix(n, q):
P = zero_matrix(FiniteField(q), n, n)
a = [i for i in range(0, n)]
for i in range(n-1, 0, -1):
j = randint(0, i)
tmp = a[i]
a[i] = a[j]
a[j] = tmp
for i in range(0, n):
P[i,a[i]] = 1
return P
# -------------------------------
def sample_monomial_matrix(n, q):
M = zero_matrix(FiniteField(q), n, n)
for i in range(0, n):
M[i,i] = randint(1, q-1)
P = sample_permutation_matrix(n, q)
return M * P
# ------------------------------
def oracle_call_lce(M, n, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
while W.rank() < k :
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:n]
return [A_rand,B]
# -------------------------------
def oracle_call_ilce(M, n, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
while W.rank() < k or Z.rank() < k:
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:n]
FSC_code = (Z.inverse())*C_code
C = FSC_code[0:k,k:n]
return [A_rand,B,C]
# ------------------------------
def oracle_call_pce(M, n, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
while W.rank() < k :
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:n]
return [A_rand,B]
# -------------------------------
def oracle_call_ipce(M, n, k, q):
F = FiniteField(q)
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
while W.rank() < k or Z.rank() < k:
A_rand = random_matrix(F, k, n - k)
A_code = identity_matrix(F, k).augment(A_rand, subdivide=False)
B_code = A_code * M
W = B_code[0:k,0:k]
C_code = A_code*(M.inverse())
Z = C_code[0:k,0:k]
FSB_code = (W.inverse())*B_code
B = FSB_code[0:k,k:n]
FSC_code = (Z.inverse())*C_code
C = FSC_code[0:k,k:n]
return [A_rand,B,C]
# ----------------------------------------------------
def get_monomial_matrix_from_linear_system(n, system):
kernel = system.right_kernel().matrix()
for solution in kernel:
M_ = matrix(n, n, solution)
if (M_.transpose() * M_).is_diagonal():
return M_
return None
# ------------------------------
def permutation_equations(n, q):
idn = identity_matrix(FiniteField(q), n)
one = matrix(FiniteField(q), 1, n, [1] * n)
row_system = idn.tensor_product(one, subdivide=False)
column_system = one.tensor_product(idn, subdivide=False)
return row_system.augment(-one.transpose(), subdivide=False), column_system.augment(-one.transpose(), subdivide=False)
# --------------------------------------------------------------
def get_linear_system(prefix, g, g_, suffix):
return prefix.augment(g, subdivide=False).tensor_product((-g_.transpose()).augment(suffix, subdivide=False), subdivide=False)
# ------------------------------------------------------------------------
def get_linear_system_transpose(prefix, g, g_, suffix):
return (-g.transpose()).augment(suffix, subdivide=False).tensor_product(prefix.augment(g_, subdivide=False), subdivide=False)
# -----------------------------------------------------
def get_reduced_system(n, k, q , system_, column, row=0):
to_delete = [(i * n + j) for i in range(0, n) for j in range(0, n) if (i == row or j == column)]
system_ij = system_.delete_columns(to_delete).augment(system_[:,n*row + column], subdivide=False)
return system_ij
# -------------------------------------
def task(n, k, q, system, row, column):
mtrx = get_reduced_system(n, k, q , system, column, row=row)
# if mtrx.rank() == mtrx[:,:-1].rank(): # Rouché–Capelli Theorem
if mtrx.rank() < 2 * k * (n - k): # This equivalent to Rouché–Capelli Theorem but 2x faster
return column
else:
return None
# -------------------------------------------------------
def solve_reduced_system(n, k, q, M, M_, N, N_, columns):
# Concerning ILCE and 2LCE
assert(len(columns) == n)
size = sum([len(element) for element in columns])
assert(2 * k * (n - k) >= size)
PolyRing = PolynomialRing(FiniteField(q), size, names="x")
varsRing = [PolyRing.gen(i) for i in range(size)] + [1]
Q = zero_matrix(PolyRing, n, n)
element = -1
for row in range(0, n, 1):
for column in columns[row]:
element += 1
Q[row, column] = varsRing[element]
Q11 = Q[:k,:k]
Q12 = Q[:k,k:]
Q21 = Q[k:,:k]
Q22 = Q[k:,k:]
reduced_system_eqs = Q12 + M * Q22 - Q11 * M_ - M * Q21 * M_
reduced_system_eqs = reduced_system_eqs.stack(Q12 + N * Q22 - Q11 * N_ - N * Q21 * N_)
reduced_system = zero_matrix(FiniteField(q), 2 * k * (n - k) + 1, size + 1)
row = -1
for i in range(0, 2 * k, 1):
for j in range(0, n - k, 1):
row += 1
coefs = reduced_system_eqs[i,j].coefficients()
monos = reduced_system_eqs[i,j].monomials()
positions = [varsRing.index(monos_k) for monos_k in monos]
for pos in range(0, len(positions), 1):
reduced_system[row, positions[pos]] = coefs[pos]
# add one extra equation determined by normalized monomial (non-entry of the first row is 1)
row += 1
equation = sum(Q[0]) - 1
coefs = equation.coefficients()
monos = equation.monomials()
positions = [varsRing.index(monos_k) for monos_k in monos]
for pos in range(0, len(positions), 1):
reduced_system[row, positions[pos]] = coefs[pos]
# solve reduced system
solution = reduced_system[:,:-1].solve_right(-reduced_system[:,-1]).list()
element = -1
matrix_solution = zero_matrix(FiniteField(q), n, n)
for row in range(0, n, 1):
for column in columns[row]:
element += 1
matrix_solution[row, column] = solution[element]
G1 = identity_matrix(FiniteField(q), k).augment(M, subdivide=False)
G2 = identity_matrix(FiniteField(q), k).augment(N, subdivide=False)
assert(is_monomial(matrix_solution, n))
assert((G1 * matrix_solution).rref()[:k, k:n] == M_)
assert((G2 * matrix_solution).rref()[:k, k:n] == N_)
return matrix_solution
# ----------------------------------------------------------------
@counter
def algorithm(k, n, q, M, M_, N, N_, Parallel=False, bench=False):
print('\nPublic matrix code generators')
print(f'\nG₁ = (Iₖ | M) where M:\n{M}')
print(f'\nG₁\' = (Iₖ | M\') where M\':\n{M_}')
print(f'\nG₂ = (Iₖ | N) where N:\n{N}')
print(f'\nG₂\' = (Iₖ | N\') where N\':\n{N_}')
# starting the monitoring
tracemalloc.start()
prefix = identity_matrix(FiniteField(q), k)
suffix = identity_matrix(FiniteField(q), n - k)
# Procedure starts below
time_start = timer()
system = matrix(FiniteField(q), 0, n**2)
system = system.stack(get_linear_system(prefix, M, M_, suffix))
system = system.stack(get_linear_system(prefix, N, N_, suffix))
# system = system.augment(zero_matrix(FiniteField(q), 2 * k * (n - k), 1))
columns = []
time_middle_1 = timer()
if not Parallel:
# Sequential approach (this is useful for debugging)
for row in range(0, n, 1):
# add one extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
# system_ = system.stack(row_system[row])
columns.append([])
for guess in range(0, n, 1):
# add one extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
if not task(n, k, q, system, row, guess) is None:
columns[-1].append(guess)
print(f'{CYELLOW}[{row}]{CEND}: one column from the {CRED}{columns[-1]}{CEND}-th is different from zero')
else:
# Parallel approach
n_cores = mp.cpu_count()
print(f'\n#(total cores): {n_cores}')
with mp.Pool(n_cores // 2) as pool:
print(f'#(used cores): {pool._processes}\n')
for row in range(0, n, 1):
# prepare arguments for reach call to target function
# add two extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
inputs = [(n, k, q, system, row, guess) for guess in range(0, n, 1)]
# call the function for each item in parallel with multiple arguments
columns.append(list(filter(lambda input: not input is None, [result for result in pool.starmap(task, inputs)])))
print(f'{CYELLOW}[{row}]{CEND}: one column from the {CRED}{columns[-1]}{CEND}-th is different from zero')
time_middle_2 = timer()
number_of_guesses = sum([len(column) for column in columns])
number_of_guesses_per_row = number_of_guesses / n
if number_of_guesses > 2 * k * (n - k) or number_of_guesses == 0:
first = algorithm.count == 1
if bench:
to_csv_file_header(f'experiments/EXC_n{n}_q{q}.csv', label=first)
# stopping the library
tracemalloc.stop()
return None
R = solve_reduced_system(n, k, q, M, M_, N, N_, columns)
time_end = timer()
mem_start, mem_peak = tracemalloc.get_traced_memory()
memory = (mem_peak - mem_start) / (1024.0 * 1024.0)
print(f'\nMemory usage:\t\t\t{memory} gigabytes')
print(f'Average #(variables per row):\t{number_of_guesses_per_row}')
print(f'Total number of variables:\t{number_of_guesses} = {number_of_guesses_per_row}⋅n')
print(f'Elapsed time (get linear sys):\t{time_middle_1 - time_start} seconds')
print(f'Elapsed time (filter process):\t{time_middle_2 - time_middle_1} seconds')
print(f'Elapsed time (recover matrix):\t{time_end - time_middle_2} seconds')
print(f'Elapsed time (total):\t\t{time_end - time_start} seconds\n')
# stopping the library
tracemalloc.stop()
if bench:
runtime = time_end - time_start
first = algorithm.count == 1
to_csv_file(f'experiments/EXC_n{n}_q{q}.csv', {'n':n, 'q':q, '# variables':number_of_guesses, 'memory':memory, 'runtime':runtime}, label=first)
return R
##### Below code concerns solving self-dual 2-LCE/ILCE instances
# -----------------------------------------------------
def get_reduced_system_selfdual(n, k, q , system_, column, row=0):
to_delete = [(i * n + j) for i in range(0, n) for j in range(0, n) if (i == row or j == column)]
system_ij = system_[:,:-1].delete_columns(to_delete).augment(system_[:,-1] + system_[:,n*row + column], subdivide=False)
return system_ij
# -------------------------------------
def task_selfdual(n, k, q, system, row, column):
mtrx = get_reduced_system_selfdual(n, k, q , system, column, row=row)
# if mtrx.rank() < 2 * k * (n - k): # This equivalent to Rouché–Capelli Theorem but does not work for self-dual codes in general
if mtrx.rank() == mtrx[:,:-1].rank(): # Rouché–Capelli Theorem
return column
else:
return None
# -------------------------------------------------------
def solve_reduced_system_selfdual(n, k, q, M, M_, N, N_, columns):
# Concerning ILCE and 2LCE
assert(len(columns) == n)
size = sum([len(element) for element in columns])
assert(2 * k * (n - k) >= size)
PolyRing = PolynomialRing(FiniteField(q), size, names="x")
varsRing = [PolyRing.gen(i) for i in range(size)] + [1]
Q = zero_matrix(PolyRing, n, n)
element = -1
for row in range(0, n, 1):
for column in columns[row]:
element += 1
Q[row, column] = varsRing[element]
Q11 = Q[:k,:k]
Q12 = Q[:k,k:]
Q21 = Q[k:,:k]
Q22 = Q[k:,k:]
reduced_system_eqs = Q12 + M * Q22 - Q11 * M_ - M * Q21 * M_
reduced_system_eqs = reduced_system_eqs.stack(Q12 + N * Q22 - Q11 * N_ - N * Q21 * N_)
reduced_system = zero_matrix(FiniteField(q), 2 * k * (n - k) + 1, size + 1)
row = -1
for i in range(0, 2 * k, 1):
for j in range(0, n - k, 1):
row += 1
coefs = reduced_system_eqs[i,j].coefficients()
monos = reduced_system_eqs[i,j].monomials()
positions = [varsRing.index(monos_k) for monos_k in monos]
for pos in range(0, len(positions), 1):
reduced_system[row, positions[pos]] = coefs[pos]
# add one extra equation determined by normalized monomial (non-entry of the first row is 1)
row += 1
equation = sum(Q[0]) - 1
coefs = equation.coefficients()
monos = equation.monomials()
positions = [varsRing.index(monos_k) for monos_k in monos]
for pos in range(0, len(positions), 1):
reduced_system[row, positions[pos]] = coefs[pos]
# solve reduced system
kernel = reduced_system.right_kernel().matrix()
matrix_solution = zero_matrix(FiniteField(q), n, n)
for solution in kernel:
element = -1
matrix_solution = zero_matrix(FiniteField(q), n, n)
for row in range(0, n, 1):
for column in columns[row]:
element += 1
matrix_solution[row, column] = solution[element]
if is_monomial(matrix_solution, n):
break
return matrix_solution
# ----------------------------------------------------------------
@counter
def algorithm_selfdual(k, n, q, G1, G1_, G2, G2_, Parallel=False, bench=False):
# Instances analyzed are far from "truely" random (one one self-dual code).
# We can solve ILCE but 2-LCE we only infer some entries (with one guess). Probably two/[or more] guesses would allow the recovery for 2-LCE
print('\nPublic matrix code generators')
print(f'\nG₁:\n{G1}')
print(f'\nG₁\':\n{G1_}')
print(f'\nG₂:\n{G2}')
print(f'\nG₂\'\':\n{G2_}')
# Mapping to SF
T = sample_permutation_matrix(n, q)
A = [(Gi * T).rref() for Gi in [G1, G2 ]]
B = [(Gi_* T).rref() for Gi_ in [G1_,G2_]]
while False in [Ai[:k,:k] == identity_matrix(FiniteField(q), k) for Ai in A] or False in [Bi[:k,:k] == identity_matrix(FiniteField(q), k) for Bi in B]:
T = sample_permutation_matrix(n, q)
A = [(Gi * T).rref() for Gi in [G1, G2 ]]
B = [(Gi_* T).rref() for Gi_ in [G1_,G2_]]
M = A[0][:k,k:n]
N = A[1][:k,k:n]
M_= B[0][:k,k:n]
N_= B[1][:k,k:n]
# starting the monitoring
tracemalloc.start()
prefix = identity_matrix(FiniteField(q), k)
suffix = identity_matrix(FiniteField(q), n - k)
# Procedure starts below
time_start = timer()
system = matrix(FiniteField(q), 0, n**2)
system = system.stack(get_linear_system(prefix, M, M_, suffix))
system = system.stack(get_linear_system(prefix, N, N_, suffix))
# Add permutation equations
system = system.augment(zero_matrix(FiniteField(q), 2 * k * (n - k), 1))
row_system, col_system = permutation_equations(n, q)
system = system.stack(row_system)
system = system.stack(col_system)
columns = []
time_middle_1 = timer()
if not Parallel:
# Sequential approach (this is useful for debugging)
for row in range(0, n, 1):
# add one extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
# system_ = system.stack(row_system[row])
columns.append([])
for guess in range(0, n, 1):
# add one extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
if not task_selfdual(n, k, q, system, row, guess) is None:
columns[-1].append(guess)
print(f'{CYELLOW}[{row}]{CEND}: one column from the {CRED}{columns[-1]}{CEND}-th is different from zero')
else:
# Parallel approach
n_cores = mp.cpu_count()
print(f'\n#(total cores): {n_cores}')
with mp.Pool(n_cores // 2) as pool:
print(f'#(used cores): {pool._processes}\n')
for row in range(0, n, 1):
# prepare arguments for reach call to target function
# add two extra equation determined by normalized monomial (non-zero entry of the is assumed to be 1)
inputs = [(n, k, q, system, row, guess) for guess in range(0, n, 1)]
# call the function for each item in parallel with multiple arguments
columns.append(list(filter(lambda input: not input is None, [result for result in pool.starmap(task_selfdual, inputs)])))
print(f'{CYELLOW}[{row}]{CEND}: one column from the {CRED}{columns[-1]}{CEND}-th is different from zero')
time_middle_2 = timer()
number_of_guesses = sum([len(column) for column in columns])
number_of_guesses_per_row = number_of_guesses / n
if number_of_guesses > 2 * k * (n - k) or number_of_guesses == 0:
first = algorithm.count == 1
if bench:
to_csv_file_header(f'experiments/EXC_n{n}_q{q}.csv', label=first)
# stopping the library
tracemalloc.stop()
return None
R = solve_reduced_system_selfdual(n, k, q, M, M_, N, N_, columns)
# Map to original instance
R = T * R * (T.inverse())
time_end = timer()
mem_start, mem_peak = tracemalloc.get_traced_memory()
memory = (mem_peak - mem_start) / (1024.0 * 1024.0)
print(f'\nMemory usage:\t\t\t{memory} gigabytes')
print(f'Average #(variables per row):\t{number_of_guesses_per_row}')
print(f'Total number of variables:\t{number_of_guesses} = {number_of_guesses_per_row}⋅n')
print(f'Elapsed time (get linear sys):\t{time_middle_1 - time_start} seconds')
print(f'Elapsed time (filter process):\t{time_middle_2 - time_middle_1} seconds')
print(f'Elapsed time (recover matrix):\t{time_end - time_middle_2} seconds')
print(f'Elapsed time (total):\t\t{time_end - time_start} seconds\n')
# stopping the library
tracemalloc.stop()
if bench:
runtime = time_end - time_start
first = algorithm.count == 1
to_csv_file(f'experiments/EXC_n{n}_q{q}.csv', {'n':n, 'q':q, '# variables':number_of_guesses, 'memory':memory, 'runtime':runtime}, label=first)
return R