-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathold.py
More file actions
177 lines (139 loc) · 4.19 KB
/
old.py
File metadata and controls
177 lines (139 loc) · 4.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import sympy as sp
import numpy as np
import random as rnd
from pprint import pprint
# Genera bits da un intero
def get_bits(value, bitsize = 2):
result = []
for i in range(bitsize):
result.append((value >> i) & 0b1)
return list(reversed(result))
# Genera matrice A da una serie di espressioni booleane e un numero di variabili
def gen_A(bexprs, vars_num = 2):
A = []
for bexp in bexprs:
R = []
for bits in [ get_bits(i) for i in range(0, pow(2, vars_num))]:
R.append(bexp[0](bits))
A.append(R)
return sp.Matrix(A).transpose()
def calculate(MBA, bits):
res = 0
for (coeff, bexp) in MBA:
res += coeff * bexp[0](bits)
return res
def mba_print(MBA):
for (coeff, bexp) in MBA:
sign = '-' if coeff < 0 else '+'
print(f"{sign} {abs(coeff)} * ({bexp[1]}) ", end='')
# Controlla che la MBA sia un'identità
def assert_identity(MBA):
for bits in [ get_bits(i) for i in range(pow(2, VARS_NUM))]:
assert(calculate(MBA, bits) == 0)
# Estrae termini dalla MBA
def extract(MBA, terms):
sol = []
eeq = []
for (coeff, bexp) in MBA:
found = False
for term in terms:
if bexp[1] == term[1] and coeff == term[0]:
found = True
break
if found:
sol.append((-coeff, bexp))
else:
eeq.append((coeff, bexp))
return sol, eeq
# Numero di variabili
VARS_NUM = 2
# Numero di espressioni booleane
BEXP_NUM = 4
BEXPS = [
(lambda vars: vars[0], "x"), # Identità di x
(lambda vars: vars[1], "y"), # Identità di y
(lambda vars: vars[0] & vars[1], "x & y"),
(lambda vars: vars[0] | ~vars[1], "x | ~y"),
(lambda vars: vars[0] ^ vars[1], "x ^ y"),
(lambda vars: ~vars[0] & ~vars[1], "~x & ~y"),
(lambda vars: ~vars[0], "~x"),
(lambda vars: ~vars[1], "~y"),
(lambda vars: ~vars[0] ^ ~vars[1], "~x ^ ~y"),
(lambda vars: 1, "1")
]
A = gen_A(BEXPS)
pprint(A)
# ============================================================
# IDENTITA'
print("Identità trovate:")
for generator in A.nullspace():
MBA = []
for i, bexp in enumerate(BEXPS):
coeff = generator[(i, 0)]
if coeff != 0:
MBA.append((coeff, bexp))
assert_identity(MBA)
print("\t0 == ", end='')
mba_print(MBA)
print("")
vars, terms = extract(MBA, [(-1, "x"), (-1, "y")])
if len(vars) == 2:
print("\tRegola di riscrittura per x + y: ", end='')
mba_print(terms)
print("")
exit(0)
# ============================================================
# ESPRESSIONI LOGICHE GENERICHE
# Funzione logica da rappresentare come MBA lineare
f = (lambda vars: ~(vars[0] & ~vars[1]) | (~vars[0] ^ vars[1]), "~(x & ~y) | (~x ^ y)")
# Ottiene rappresentazione binaria della funzione f
# F = [
# f(00)
# f(01)
# f(10)
# f(11)
# ]
F = sp.zeros(pow(2, VARS_NUM), 1)
for input in range(pow(2, VARS_NUM)):
F[input] = (f[0])(get_bits(input))
#pprint(F)
#x = A.LDLsolve(F)
#pprint(x)
#exit(0)
# Pseudo inversa
K = A.pinv()
# Controlla che esistano soluzioni
assert(A * K * F == F)
w = sp.Matrix(8, 1, [0, 1, 0, 1, 0, 1, 0, 1])
x = K * F + (sp.eye(8, 8) - K * A) * w
# pprint(x)
# Ottiene una forma migliore della MBA
g = sp.gcd([ e for e in x[:, 0]])
x = x * (1 / g)
# pprint(x)
MBA = []
for i, bexp in enumerate(BEXPS):
coeff = x[(i, 0)]
if coeff != 0:
MBA.append((coeff, bexp))
# Visualizza MBA
print("Conversione di funzioni logiche:")
print(f"\t[ {f[1]} ] <=> [ ", end='')
for (coeff, bexp) in MBA:
sign = '-' if coeff < 0 else '+'
print(f"{sign} {abs(coeff)} * ({bexp[1]}) ", end='')
print("]")
# Controlla che il risultato sia uguale per f è la mba lineare
for bits in [ get_bits(i) for i in range(pow(2, VARS_NUM))]:
res1 = f[0](bits)
res2 = calculate(MBA, bits)
if res1 != res2:
print(f"Failed check at {bits}, f = {res1}, mba = {res2}")
exit(-1)
# Controlla per valori superiori a 2
for i in range(100):
values = np.random.randint(1, 100, 2)
# print(f"check {values}")
assert(f[0](values) == calculate(MBA, values))
# ============================================================
# ESPRESSIONI AFFINI GENERICHE