-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
209 lines (160 loc) · 5.79 KB
/
utils.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
"""Conversion tools."""
import math
import numbers
import numpy as np
import scipy
from scipy.stats import norm
pi = math.pi
def int2bitarray(n, k):
"""Change an array's base from int (base 10) to binary (base 2)."""
binary_string = bin(n)
length = len(binary_string)
bitarray = np.zeros(k, 'int')
for i in range(length - 2):
bitarray[k - i - 1] = int(binary_string[length - i - 1])
return bitarray
def bitarray2int(bitarray):
"""Change array's base from binary (base 2) to int (base 10)."""
bitstring = "".join([str(i) for i in bitarray])
return int(bitstring, 2)
def binaryproduct(X, Y):
"""Compute a matrix-matrix / vector product in Z/2Z."""
A = X.dot(Y)
try:
A = A.toarray()
except AttributeError:
pass
return A % 2
def gaussjordan(X, change=0):
"""Compute the binary row reduced echelon form of X.
Parameters
----------
X: array (m, n)
change : boolean (default, False). If True returns the inverse transform
Returns
-------
if `change` == 'True':
A: array (m, n). row reduced form of X.
P: tranformations applied to the identity
else:
A: array (m, n). row reduced form of X.
"""
A = np.copy(X)
m, n = A.shape
if change:
P = np.identity(m).astype(int)
pivot_old = -1
for j in range(n):
filtre_down = A[pivot_old+1:m, j]
pivot = np.argmax(filtre_down)+pivot_old+1
if A[pivot, j]:
pivot_old += 1
if pivot_old != pivot:
aux = np.copy(A[pivot, :])
A[pivot, :] = A[pivot_old, :]
A[pivot_old, :] = aux
if change:
aux = np.copy(P[pivot, :])
P[pivot, :] = P[pivot_old, :]
P[pivot_old, :] = aux
for i in range(m):
if i != pivot_old and A[i, j]:
if change:
P[i, :] = abs(P[i, :]-P[pivot_old, :])
A[i, :] = abs(A[i, :]-A[pivot_old, :])
if pivot_old == m-1:
break
if change:
return A, P
return A
def binaryrank(X):
"""Compute rank of a binary Matrix using Gauss-Jordan algorithm."""
A = np.copy(X)
m, n = A.shape
A = gaussjordan(A)
return sum([a.any() for a in A])
def f1(y, sigma):
"""Compute normal density N(1,sigma)."""
f = norm.pdf(y, loc=1, scale=sigma)
return f
def fm1(y, sigma):
"""Compute normal density N(-1,sigma)."""
f = norm.pdf(y, loc=-1, scale=sigma)
return f
def _bitsandnodes(H):
"""Return bits and nodes of a parity-check matrix H."""
if type(H) != scipy.sparse.csr_matrix:
bits_indices, bits = np.where(H)#这里只返回非0元素索引,两个数组,记录坐标
nodes_indices, nodes = np.where(H.T)#其实直接 nodes_indices = bits, nodes = bits_indices也可以达到类似的效果,只不过虽然记录下坐标,但是顺序不对
else:
bits_indices, bits = scipy.sparse.find(H)[:2]
nodes_indices, nodes = scipy.sparse.find(H.T)[:2]
bits_histogram = np.bincount(bits_indices)#基本作用是记录数组中出现的值的频数,从低到高排列
nodes_histogram = np.bincount(nodes_indices)#但因为传递的是索引,某个出现的索引出现的次数,就是这一行的1的个数,或者这一行的列的个数。这是一个记录行重列重的方法。
return bits_histogram, bits, nodes_histogram, nodes
def bits2i(H, i):
"""Compute list of variables (bits) connected to Parity node i."""
if type(H) != scipy.sparse.csr_matrix:
m, n = H.shape
return list(np.where(H[i])[0])
indj = H.indptr
indi = H.indices
return [indi[a] for a in range(indj[i], indj[i+1])]
def nodes2j(H, j):
"""Compute list of nodes (PC equations) connecting variable j."""
return bits2i(H.T, j)
def bitsandnodes(H):
"""Return bits and nodes of a parity-check matrix H."""
m, n = H.shape
bits = [bits2i(H, i) for i in range(m)]
nodes = [nodes2j(H, j) for j in range(n)]
bits = np.array(bits)
nodes = np.array(nodes)
return bits, nodes
def incode(H, x):
"""Compute Binary Product of H and x."""
return (binaryproduct(H, x) == 0).all()
def gausselimination(A, b):
"""Solve linear system in Z/2Z via Gauss Gauss elimination."""
if type(A) == scipy.sparse.csr_matrix:
A = A.toarray().copy()
else:
A = A.copy()
b = b.copy()
n, k = A.shape
for j in range(min(k, n)):
listedepivots = [i for i in range(j, n) if A[i, j]]
if len(listedepivots):
pivot = np.min(listedepivots)
else:
continue
if pivot != j:
aux = (A[j, :]).copy()
A[j, :] = A[pivot, :]
A[pivot, :] = aux
aux = b[j].copy()
b[j] = b[pivot]
b[pivot] = aux
for i in range(j+1, n):
if A[i, j]:
A[i, :] = abs(A[i, :]-A[j, :])
b[i] = abs(b[i]-b[j])
return A, b
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, numbers.Integral):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)