Ejemplo n.º 1
0
 def test_linsolve_5(self):
     pm = gf.gen_pow_matrix(19)
     A1 = np.array([[3, 7], [12, 1]])
     A2 = np.array([[3, 7], [12, 15]])
     b = np.array([8, 13])
     assert_array_equal(np.array([13, 14]), gf.linsolve(A1, b, pm))
     self.assertTrue(gf.linsolve(A2, b, pm) is np.nan)
Ejemplo n.º 2
0
 def decode(self, W, method='euclid'):
     alpha = np.array([2], np.int)
     curr_deg = alpha
     alpha_list_t = [alpha[0]]
     for i in range(2 * self.t - 1):
         curr_deg = gf.prod(curr_deg, alpha, self.pm)
         alpha_list_t.append(curr_deg[0])
     alpha_list_n = alpha_list_t.copy()
     for i in range(self.n - 2 * self.t):
         curr_deg = gf.prod(curr_deg, alpha, self.pm)
         alpha_list_n.append(curr_deg[0])
     alpha_list_t = np.array(alpha_list_t)
     alpha_list_n = np.array(alpha_list_n)
     result = np.zeros(W.shape, np.int)
     if method == 'pgz':
         for row in range(W.shape[0]):
             deg_list = gf.polyval(W[row], alpha_list_t, self.pm)
             if np.all(deg_list == 0):
                 result[row] = W[row]
             else:
                 curr_dim = self.t
                 while (curr_dim > 0):
                     A = np.zeros((curr_dim, curr_dim), np.int)
                     for i in range(curr_dim):
                         A[i] = deg_list[i:curr_dim + i]
                     b = deg_list[curr_dim:2 * curr_dim]
                     value = gf.linsolve(A, b, self.pm)
                     if value is not np.nan:
                         value = np.concatenate((value, np.ones(1, np.int)))
                         break
                     curr_dim -= 1
                 if curr_dim == 0:
                     result[row] = np.nan
                 else:
                     roots = gf.polyval(value, alpha_list_n, self.pm)
                     roots = np.nonzero(np.logical_not(roots))
                     err_pos = (roots[0]) % self.n
                     result[row] = W[row]
                     result[row, err_pos] = np.logical_not(
                         result[row, err_pos]).astype(np.int)
                     if np.any(
                             gf.polyval(result[row], alpha_list_t, self.pm)
                             != 0):
                         result[row, :] = np.nan
     elif method == 'euclid':
         alpha_list_t = alpha_list_t[::-1]
         for row in range(W.shape[0]):
             S = gf.polyval(W[row], alpha_list_t, self.pm)
             S = np.concatenate((S, np.ones(1, np.int)))
             z = np.array([1] + [0 for x in range(2 * self.t + 1)], np.int)
             r, A, Lambda = gf.euclid(z, S, self.pm, self.t)
             roots = gf.polyval(Lambda, alpha_list_n, self.pm)
             roots = np.nonzero(np.logical_not(roots))
             err_pos = (roots[0]) % self.n
             result[row] = W[row]
             result[row, err_pos] = np.logical_not(
                 result[row, err_pos]).astype(np.int)
             if np.any(gf.polyval(result[row], alpha_list_t, self.pm) != 0):
                 result[row, :] = np.nan
     return result
Ejemplo n.º 3
0
 def test_linsolve_4(self):
     pm = gf.gen_pow_matrix(87341)
     A = np.array([[pm[20, 1], pm[-20, 1], pm[10, 1], pm[8, 1]],
                   [pm[198, 1], pm[30, 1], pm[89, 1], pm[-30, 1]],
                   [pm[298, 1], pm[32, 1], pm[86, 1], pm[-24, 1]],
                   [pm[5, 1], pm[-67, 1], pm[94, 1], pm[43, 1]]])
     b = np.array([pm[67, 1], pm[-39, 1], pm[49, 1], pm[87, 1]])
     assert_array_equal([35048, 24262, 65502, 26384], gf.linsolve(A, b, pm))
Ejemplo n.º 4
0
 def test_linsolve_7_with_zero(self):
     pm = gf.gen_pow_matrix(87341)
     A = np.array([[0, pm[-20, 1], pm[10, 1], pm[8, 1]],
                   [pm[198, 1], pm[30, 1], pm[89, 1], pm[-30, 1]],
                   [pm[298, 1], pm[32, 1], pm[86, 1], pm[-24, 1]],
                   [pm[5, 1], pm[-67, 1], pm[94, 1], pm[43, 1]]])
     b = np.array([pm[67, 1], pm[-39, 1], pm[49, 1], pm[87, 1]])
     assert_array_equal([21320, 18899, 5953, 57137], gf.linsolve(A, b, pm))
Ejemplo n.º 5
0
 def test_linsolve_8_with_zero(self):
     pm = gf.gen_pow_matrix(87341)
     A = np.array([[1, pm[-20, 1], pm[10, 1], pm[8, 1]],
                   [1, pm[-20, 1], pm[89, 1], pm[-30, 1]],
                   [pm[298, 1], pm[32, 1], pm[86, 1], pm[-24, 1]],
                   [pm[5, 1], pm[-67, 1], pm[94, 1], pm[43, 1]]])
     b = np.array([pm[67, 1], pm[-39, 1], pm[49, 1], pm[87, 1]])
     assert_array_equal([49980, 29479, 12587, 62413], gf.linsolve(A, b, pm))
Ejemplo n.º 6
0
 def test_linsolve(self):
     pm = gf.gen_pow_matrix(130207)
     A = np.array([[pm[5, 1], pm[20, 1], pm[6, 1]], [0, 0, 0],
                   [pm[-1, 1], pm[2, 1], pm[9, 1]]])
     self.assertTrue(
         gf.linsolve(A, np.array([pm[1, 1], pm[5,
                                               1], pm[-3,
                                                      1]]), pm) is np.nan)
Ejemplo n.º 7
0
 def test_linsolve_3(self):
     pm = gf.gen_pow_matrix(108851)
     A = np.array([[pm[5, 1], pm[20, 1], pm[6, 1]],
                   [pm[8, 1], pm[1, 1], pm[6, 1]],
                   [pm[-1, 1], pm[2, 1], pm[9, 1]]])
     assert_array_equal([3009, 23136, 63822],
                        gf.linsolve(
                            A, np.array([pm[1, 1], pm[5, 1], pm[-3, 1]]),
                            pm))
Ejemplo n.º 8
0
 def decode(self, W, method='euclid'):
     num_of_message = W.shape[0]
     answ = numpy.empty(W.shape, dtype=int)
     double_t = 2 * self.t
     for i in range(num_of_message):
         if method == 'euclid':
             syndrome_arr = gf.polyval(W[i], self.R, self.pm)
             if not any(syndrome_arr):
                 answ[i] = W[i]
                 continue
             syndrome_arr = numpy.hstack(
                 (syndrome_arr, numpy.array([1], dtype=int)))
             z_in_pow_poly = numpy.zeros(double_t + 2, dtype=int)
             z_in_pow_poly[0] = 1
             zero_counter = 0
             for x in syndrome_arr:
                 if x == 0:
                     zero_counter += 1
                 else:
                     break
             Lambda = gf.euclid(z_in_pow_poly, syndrome_arr[zero_counter:],
                                self.pm, self.t)[2]
             Lambda_pow = Lambda.shape[0] - 1
             answ[i], num_of_root = self.correction(Lambda, W[i])
             if Lambda_pow != num_of_root:
                 answ[i] = numpy.nan
                 #answ[i] = 2 Программы со сбором статистики, построением графиков, ожидают,
                 #что при отказах будет возвращаться строка двоек из-за проблем со сравнением numpy.nan находящегося в целочисленном массиве
                 continue
         else:
             syndrome_arr = gf.polyval(W[i], self.R_for_pgz, self.pm)
             if not any(syndrome_arr):
                 answ[i] = W[i]
                 continue
             arr = numpy.empty((self.t, self.t), dtype=int)
             for k in range(self.t):
                 arr[k] = syndrome_arr[k:k + self.t]
             b_arr = numpy.array(syndrome_arr[self.t:])
             j = 0
             while j != self.t:
                 Lambda = gf.linsolve(arr[:self.t - j, :self.t - j], b_arr,
                                      self.pm)
                 if not numpy.array_equal(Lambda, Lambda):
                     j += 1
                     b_arr = syndrome_arr[self.t - j:2 * (self.t - j)]
                 else:
                     break
             if j == self.t:
                 answ[i] = numpy.nan
                 #answ[i] = 2
                 continue
             Lambda = numpy.hstack((Lambda, numpy.array([1])))
             answ[i] = self.correction(Lambda, W[i])[0]
             if any(gf.polyval(answ[i], self.R_for_pgz, self.pm)):
                 answ[i] = numpy.nan
                 #answ[i] = 2
     return answ
Ejemplo n.º 9
0
 def decode(self, w, method='euclid'):
     f = open(method + '.txt', 'a')
     u = np.zeros((w.shape[0], w.shape[1]), int)
     for i in range(w.shape[0]):
         s = gf.polyval(w[i], self.R, self.pm)
         if np.count_nonzero(s) == 0:
             u[i] = w[i]
             continue
         if method == 'pgz':
             t = time.clock()
             A, b = build_m(s, self.t)
             L = gf.linsolve(A, b, self.pm)
             step = self.t - 1
             while type(L) == type(np.nan) and step > 0:
                 A, b = build_m(s, step)
                 L = gf.linsolve(A, b, self.pm)
                 step -= 1
             if type(L) == type(np.nan):
                 u[i] = -1
                 continue
             L = np.concatenate((L, [1]))
             t = time.clock() - t
         if method == 'euclid':
             t = time.clock()
             s = np.concatenate((s[::-1], [1]))
             z = np.zeros(2 * self.t + 2, int)
             z[0] = 1
             L = gf.euclid(z, s, self.pm, self.t)[2]
             t = time.clock() - t
         f.write(str(t) + '\n')
         val = gf.polyval(L, self.pm[:, 1].reshape((self.pm.shape[0])),
                          self.pm)
         pos = []
         for a in range(val.size):
             if val[a] == 0:
                 pos.append(a)
         if len(pos) != L.size - 1:
             u[i] = -1
             continue
         u[i] = w[i]
         for j in pos:
             u[i, j] = (u[i, j] + 1) % 2
     f.close()
     return u
Ejemplo n.º 10
0
    def decode(self, W, method='euclid'):
        message_number, n = W.shape
        # res - результат
        res = np.zeros(W.shape).astype('int')

        # PGZ
        for i in range(message_number):
            # s - синдром
            # для принятоо слова W вычислим синдром
            s = gf.polyval(W[i, :], self.R, self.pm)
            # если все s = 0, то возвращаем W в качестве ответа
            if np.all(s == 0):
                res[i] = W[i].copy()
                continue
            # вычислим коэффициенты полинома локаторов ошибок путем решения СЛАУ
            if method == 'pgz':
                for j in range(self.t, 0, -1):
                    # составим матрицу A для СЛАУ
                    A = np.zeros((j, j)).astype('int')
                    for k in range(j):
                        A[k, :] = s[k:k + j]
                    b = s[j:2 * j]
                    # решаем СЛАУ
                    Lambda = gf.linsolve(A, b, self.pm)
                    if not np.any(np.isnan(Lambda)):
                        break
                if np.any(np.isnan(Lambda)):
                    res[i] = np.nan
                    continue
                Lambda = np.append(Lambda, np.array([1]))

            elif method == 'euclid':
                s = np.append(s[::-1], np.array([1]))
                # z^(2t + 1)
                z = np.zeros(((self.R.size + 1) + 1), dtype=np.int)
                z[0] = 1
                # алгоритм евклида
                # z^(2t + 1) * A(z) + S(z)L(z) = r(z)
                # находим L(z)
                Lambda = gf.euclid(z, s, self.pm, max_deg=self.t)[2]

            # получаем позиции ошибок
            roots = gf.polyval(Lambda, self.pm[:, 1], self.pm)
            pos_error = np.nonzero(roots.reshape(-1) == 0)[0]

            # инвертируем биты в позициях ошибок
            tmp = W[i].copy()
            tmp[pos_error] = 1 - tmp[pos_error].astype(np.int)
            res[i] = tmp

            s = gf.polyval(res[i].astype(int), self.R, self.pm)
            if not np.all(s == 0):
                res[i, :] = np.ones(self.n) * np.nan
                continue
        return res
Ejemplo n.º 11
0
 def decode(self, W, method='euclid'):
     assert method == 'euclid' or method == 'pgz'
     t = self.R.shape[0] // 2
     n = W.shape[1]
     is_nan = False
     assert n == self.pm.shape[0]
     res = np.zeros_like(W, dtype=object)
     for i in range(W.shape[0]):
         w = W[i]
         s = gf.polyval(w, self.R, self.pm)
         if (s == 0).all():
             res[i] = w
             continue
         if method == 'euclid':
             s = s[::-1]
             z = np.zeros(2 * t + 2, dtype=np.int64)
             z[0] = 1
             s = np.concatenate((s, np.array([1])))
             r, a, lam = gf.euclid(z, s, self.pm, max_deg=t)
         else:
             lam = np.nan
             for errors in range(t, 0, -1):
                 A = [[s[k] for k in range(j, j + errors)]
                      for j in range(errors)]
                 A = np.array(A)
                 b = [s[k] for k in range(errors, errors * 2)]
                 b = np.array(b)
                 lam = gf.linsolve(A, b, self.pm)
                 if lam is not np.nan:
                     break
             if lam is np.nan:
                 res[i] = np.nan
                 is_nan = True
                 continue
             lam = np.concatenate((lam, np.array([1])))
         values = gf.polyval(lam, self.pm[:, 1], self.pm)
         num_roots = 0
         #res[i] = w
         for j in range(values.shape[0]):
             if values[j] == 0:
                 root = self.pm[j, 1]
                 alpha = gf.divide(1, root, self.pm)
                 index = self.pm[alpha - 1, 0]
                 w[n - index - 1] = 1 - w[n - index - 1]
                 num_roots += 1
         if num_roots != lam.shape[0] - 1:
             res[i] = np.nan
             is_nan = True
             continue
         res[i] = w
     if not is_nan:
         res = res.astype(np.int64)
     return res
Ejemplo n.º 12
0
 def test_linsolve_6(self):
     pm = gf.gen_pow_matrix(87341)
     A = np.array([[pm[20, 1], pm[-20, 1], 0, pm[8, 1]],
                   [pm[298, 1], pm[30, 1], 0, pm[-30, 1]],
                   [pm[20, 1], pm[32, 1], 0, pm[-24, 1]],
                   [pm[20, 1], pm[-67, 1], 0, pm[43, 1]]])
     self.assertTrue(
         gf.linsolve(
             A, np.array([pm[67, 1], pm[-39,
                                        1], pm[87,
                                               1], pm[49,
                                                      1]]), pm) is np.nan)
Ejemplo n.º 13
0
Archivo: bch.py Proyecto: garx0/pa
 def decoder_pgz(w, syndromes):
     *A, b = (syndromes[i:i + self.t] for i in range(self.t + 1))
     A = _np.array(A)
     for n_err in range(self.t, 0, -1):
         sol = gf.linsolve(A, b, pm=self.pm)
         if sol is not _np.nan:
             break
         b = A[-1, :-1]
         A = A[:-1, :-1]
     else:
         return _np.nan
     errloc_poly = _lstrip0(_np.concatenate((sol, [1])))
     return errloc_poly
Ejemplo n.º 14
0
	def decode(self, W, method='euclid'):
		V = W.astype(object)
		for i in range(len(V)):
			
			s = gf.polyval(V[i], self.R, self.pm)
			for j in s:
				if j != 0:
					break
			else:
				continue
			
			if method == 'pgz':
				e = s.size//2
				while e > 0:
					S = np.empty((e,e),int)
					for j in range(e):
						S[j] = s[j:j+e]
					x = gf.linsolve(S,s[e:2*e],self.pm)
					if not np.any(np.isnan(x)):
						break
					e -= 1
				else:
					V[i,:] = np.nan
					continue
				x = np.append(x, [1])
			
			if method == 'euclid':
				S = np.append(s[::-1], [1])
				x = np.zeros(s.size + 2,int)
				x[0] = 1
				x = gf.euclid(x, S, self.pm, max_deg=s.size//2)[2]
				e = x.size - 1
			
			x = gf.polyval(x, self.pm[:,1], self.pm)
			x = self.pm[np.flatnonzero(x==0), 1]
			
			if method == 'euclid' and x.size != e:
				V[i,:] = np.nan
				continue
			
			x = self.pm[x-1,0] - 1
			V[i,x] = V[i,x]^1
			
			if method == 'pgz':
				s = gf.polyval(V[i], self.R, self.pm)
				for j in s:
					if j != 0:
						V[i,:] = np.nan
						break
			
		return V
Ejemplo n.º 15
0
def test_linsolve():
    pm = gf.gen_pow_matrix(37)
    A = np.array([[30, 15, 13,  2, 17, 10, 27, 16,  7, 12],
               [ 1, 15, 30,  2, 17,  4, 19,  9,  1, 11],
               [29, 26,  7,  1, 27,  2,  2, 15, 15, 18],
               [29, 12,  5,  6, 26, 18, 23, 15, 24,  4],
               [10, 24, 22, 19,  3, 31, 18, 29, 24, 30],
               [15,  8,  7,  3,  8, 22, 13,  1, 16,  4],
               [19, 25, 31,  3, 14, 29, 27,  1, 29, 12],
               [ 8, 25, 20, 17,  5, 13, 31,  7, 23,  1],
               [14, 15,  7, 26, 14,  3, 31, 16,  5,  7],
               [19, 28,  9, 11, 30,  7, 25,  2,  3, 26]])
    b = np.array([19, 2, 3, 11, 8, 27, 9, 4, 21, 5])
    right_answer = np.array([ 6, 22, 14,  8, 20, 21, 20, 23, 30, 27])
    
    assert_equal(right_answer, gf.linsolve(A, b, pm))
Ejemplo n.º 16
0
Archivo: bch.py Proyecto: Daulbaev/GM1
def decoding(W, R, pm, method='euclid'):
    n_mes = W.shape[0]
    n = W.shape[1]
    V = np.zeros((n_mes, n))
    t = int(R.size / 2)
    for mes_idx in range(n_mes):
        # Step 1. Computing syndrome polynomials:
        s = gf.polyval(W[mes_idx, :], R, pm)
        if np.count_nonzero(s) == 0:
            V[mes_idx, :] = W[mes_idx, :]
            continue
        # Step 2. Computing Lambda(z) coefficients:
        # PGZ decoder:
        if method == 'pgz':
            for nu in range(t, 0, -1):
                A = hankel(s[:nu], s[(nu - 1):(2 * nu - 1)])
                b = s[nu:(2 * nu)]
                x = gf.linsolve(A, b, pm)
                if np.all(np.isnan(x) == False):
                    break
            if np.any(np.isnan(x) == True):
                W[mes_idx, :] = np.nan
                continue
            Lambda = np.append(x, [1])
        # Euclid decoder:
        elif method == 'euclid':
            S = np.append(s[::-1], [1])
            z_pow_d = np.zeros((2 * t + 2), dtype=int)
            z_pow_d[0] = 1
            Lambda = gf.euclid(z_pow_d, S, pm, max_deg=t)[2]
        else:
            raise ValueError("Unknown method name")
        # Step 3 and 4. Finding all roots of Lambda(z) and
        # Computing error positions:
        error_positions = np.where(gf.polyval(Lambda, pm[:, 1], pm) == 0)[0]
        # Step 5. Computing decoded message:
        v = W[mes_idx, :].copy()
        v[error_positions] = np.abs(v[error_positions] - 1)
        # Step 6. Checking decoded message:
        if np.count_nonzero(gf.polyval(v, R, pm)) == 0:
            V[mes_idx, :] = v.copy()
        else:
            V[mes_idx, :] = np.nan
    return V
Ejemplo n.º 17
0
 def test_linsolve_random(self):
     while True:
         pm = gf.gen_pow_matrix(92127)
         pm_len = len(pm)
         n = 50
         A = np.array(
             [[pm[random.randint(0, pm_len - 1), 1] for _ in range(n)]
              for _ in range(n)])
         b = np.array(
             [pm[random.randint(0, pm_len - 1), 1] for _ in range(n)])
         solution = gf.linsolve(A, b, pm)
         if not (solution is np.nan):
             subst = [
                 gf.sum(
                     gf.prod(A[i].reshape(A[i].size, 1),
                             solution.reshape(solution.size, 1), pm))[0][0]
                 for i in range(n)
             ]
             assert_array_equal(subst, b)
             break
Ejemplo n.º 18
0
 def PGZ(self, s):
     matrix = np.zeros((self.t, self.t))
     nu = self.t
     answer = np.zeros(self.t)
     r = np.zeros(self.t)
     while nu != 0:
         for i in range(nu):
             for j in range(nu):
                 matrix[i][j] = s[i + j]
             answer[i] = s[nu + i]
         m = np.array(matrix[:nu, :nu]).astype(int)
         ans = answer[:nu].astype(int)
         r = gf.linsolve(m, ans, self.pm)
         if not(r is np.nan):
             n = np.ones(r.shape[0] + 1)
             for i in range(r.shape[0]):
                 n[i] = r[i]  
             return n
         nu = nu - 1
     return np.nan
Ejemplo n.º 19
0
 def decode(self, W, method='euclid'):
     result = np.empty(W.shape)
     for index, w in enumerate(W):
         result[index] = w
         s = gf.polyval(w, self.R, self.pm)
         if np.all(s == 0):
             continue
         if method == 'euclid':
             s = np.hstack((s[::-1], np.array([1], int)))
             i = 0
             while s[i] == 0:
                 i += 1
             loc = gf.euclid(
                 np.hstack((np.array([1],
                                     int), np.zeros(self.R.size + 1, int))),
                 s[i:], self.pm, self.R.size >> 1)[2]
         else:
             t = self.R.size >> 1
             A = np.empty((t, t), int)
             for i in range(t):
                 A[i] = s[i:i + t]
             for v in range(t, 0, -1):
                 loc = gf.linsolve(A[:v, :v], s[v:2 * v], self.pm)
                 if np.array_equal(loc, loc):
                     loc = np.hstack((loc, np.array([1], int)))
                     break
             if not np.array_equal(loc, loc):
                 result[index].fill(np.nan)
                 continue
         roots_count = 0
         for i, val in enumerate(self.pm[:, 1]):
             if gf.polyval(loc, val.reshape(1), self.pm)[0] == 0:
                 roots_count += 1
                 result[index][i] = int(result[index][i]) ^ 1
         if method == 'euclid' and roots_count != loc.size - 1:
             result[index].fill(np.nan)
         elif method == 'pgz':
             s = gf.polyval(result[index].astype(int), self.R, self.pm)
             if np.any(s != 0):
                 result[index].fill(np.nan)
     return result
Ejemplo n.º 20
0
    def _decode(self, w, method):
        t = self.R.shape[0] // 2
        syndromes = gf.polyval(w, self.R, self.pm)
        if np.sum(syndromes != 0) == 0:
            return w

        if method == 'pgz':
            lambda_ = np.nan
            for nu in range(t, 0, -1):
                a = np.array([[syndromes[j] for j in range(i, nu + i)]
                              for i in range(nu)],
                             dtype=np.int)
                b = np.array([syndromes[i] for i in range(nu, 2 * nu)],
                             dtype=np.int)
                lambda_ = gf.linsolve(a, b, self.pm)
                if lambda_ is not np.nan:
                    break
            if lambda_ is np.nan:
                return np.full(self.n, np.nan, dtype=np.int)
            lambda_ = np.concatenate([lambda_, [1]])
        elif method == 'euclid':
            z = np.zeros([2 * t + 2], dtype=np.int)
            z[0] = 1
            syndromic_polynom = np.concatenate([syndromes[::-1], [1]])
            _, _, lambda_ = gf.euclid(z, syndromic_polynom, self.pm, max_deg=t)
        else:
            raise ValueError

        n_roots = 0
        locators_values = gf.polyval(lambda_, np.arange(1, self.n + 1),
                                     self.pm)
        for idx in range(1, self.n + 1):
            if not locators_values[idx - 1]:
                position = self.n - self.pm[gf.divide(1, idx, self.pm) - 1,
                                            0] - 1
                w[position] = 1 - w[position]
                n_roots += 1
        if n_roots != lambda_.shape[0] - 1:
            return np.full(self.n, np.nan, dtype=np.int)
        return w
Ejemplo n.º 21
0
 def decode(self, W, method='euclid'):
     
     sindrom = np.zeros((W.shape[0], 2*self.t)).astype('int')
     V_hat = np.zeros((W.shape)).astype('int')
     error = []
     
     
     for i in range(W.shape[0]):
         sindrom[i, :] = gf.polyval(W[i, :], self.R, self.pm)
         if np.all(sindrom[i, :] == 0):
             V_hat[i, :] = W[i, :]
         else:
             error.append(i)
     
     
     for i in error:
         if method == 'euclid':
             # sindrom polynom
             sindrom_poly = np.zeros(2*self.t + 1).astype('int')
             s = sindrom[i, :]
             s = s[::-1]
             sindrom_poly[: -1] = s
             sindrom_poly[-1] = 1
             
             # z^(2t + 1)
             z = np.zeros(2*self.t + 2).astype('int')
             z[0] = 1
             
             #euclid algorithm
             r, A, loc_poly_coef = gf.euclid(z, sindrom_poly, 
                                             self.pm, max_deg=self.t)
             
         elif method == 'pgz':
             s = sindrom[i, :]
             for errors_n in range(self.t, 0, -1):
                 
                 # matrix for linear solve
                 S = np.zeros((errors_n, errors_n)).astype('int')
                 for j in range(errors_n):
                     S[j, :] = s[j: j + errors_n]
                 b = s[errors_n: 2 * errors_n]
                 lambda_ = gf.linsolve(S, b,self.pm)
                 if np.all(np.isnan(lambda_)):
                     continue
                 else:
                     break
                     
             # decode error
             if (errors_n == 1) and np.all(np.isnan(lambda_)):
                 V_hat[i, :] = np.ones(self.n) * np.nan
                 continue
                 
             # coef of locator polynoms
             loc_poly_coef = np.zeros(lambda_.shape[0] + 1).astype('int')
             loc_poly_coef[-1] = 1
             loc_poly_coef[: -1] = lambda_
                 
         # find root
         locator_val = gf.polyval(loc_poly_coef, self.pm[:, 1], self.pm)
         roots = self.pm[np.where(locator_val == 0)[0], 1]
         pos_error = (-self.pm[roots - 1, 0]) % self.pm.shape[0]
         pos_error = self.n - pos_error - 1
         #error polynom
         error_poly = np.zeros(self.n).astype('int')
         error_poly[pos_error] = 1
             
         #decode
         v_hat = W[i, :] ^ error_poly
         s_v_hat = gf.polyval(v_hat, self.R, self.pm)
         
         if not np.all(s_v_hat == 0):
             V_hat[i, :] = np.ones(self.n) * np.nan
             continue
             
         if (roots.shape[0] != loc_poly_coef.shape[0] - 1):
             V_hat[i, :] = np.ones(self.n) * np.nan
             continue
         V_hat[i, :] = v_hat
             
     return V_hat
Ejemplo n.º 22
0
    def decode(self, W, method="euclid"):
        """Декодирование БЧХ"""
        fi = []
        for w in W:
            synd = polyval(w, self.R, self.pm)
            t = 0
            for i in synd:
                if i != 0:
                    t = -1
                    break
            if t == 0:
                fi.append(w)
                continue
            if method == "pgz":
                v = self.t
                while v > 0:
                    synd_m = np.empty([v, v], dtype=int)
                    for i in range(synd_m.shape[0]):
                        for j in range(synd_m.shape[1]):
                            synd_m[i][j] = synd[i + j]
                    synd_b = np.empty([v], dtype=int)
                    for i in range(synd_b.shape[0]):
                        synd_b[i] = synd[v + i]

                    L = linsolve(synd_m, synd_b, self.pm)

                    if np.isnan(L[0]):
                        v -= 1
                        continue

                    L = np.hstack([L, np.asarray(1)])

                    L_roots = set()
                    for i in range(self.pm.shape[0]):
                        x = polyval(L, np.asarray([self.pm[i][1]]), self.pm)
                        if (x[0] == 0):
                            L_roots.add(self.pm[i][1])
                    for i in L_roots:
                        j = self.pm[i - 1][0]
                        w[j - 1] ^= 1
                    synd = polyval(w, self.R, self.pm)
                    t = 0
                    for i in synd:
                        if i != 0:
                            t = -1
                            break
                    if t == 0:
                        fi.append(w)
                        break
                    else:
                        fi.append(np.nan)
                        break
                if v == 0:
                    fi.append(np.nan)
            else:
                synd = np.concatenate((np.flip(synd), np.asarray([1])))
                x = np.concatenate((np.asarray([1]), np.zeros(2 * self.t + 1, dtype=int)))
                a, b, L = euclid(x, synd, self.pm, self.t)
                L_roots = set()
                for i in range(self.pm.shape[0]):
                    x = polyval(L, np.asarray([self.pm[i][1]]), self.pm)
                    if x[0] == 0:
                        L_roots.add(self.pm[i][1])
                power = L.size - 1
                i = 0
                while L[i] == 0:
                    power -= 1
                    i += 1
                if len(L_roots) != power:  # количество корней не совпадает
                    fi.append(np.nan)
                    continue
                for i in L_roots:
                    j = self.pm[i - 1][0]
                    w[j - 1] ^= 1
                synd = polyval(w, self.R, self.pm)
                t = 0
                for i in synd:
                    if i != 0:
                        t = -1
                        break
                if t == 0:
                    fi.append(w)
                    continue
                else:
                    fi.append(np.nan)
                    continue
        return np.asarray(fi)