Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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
Exemplo n.º 5
0
 def decode(self, W, method='euclid'):
     d = self.g.shape[0] - 1
     ans = np.zeros((W.shape[0], self.k))
     for j in range(W.shape[0]):
         w = W[j]
         s = np.array(gf.polyval(w, self.pm.T[1][:2*self.t], self.pm))
         b = 0
         for i in s:
             if(i != 0):
                 b = 1
         if (b == 0):
             ans[j] = w[:self.k]
         else:
             n = np.array([0])
             r = w.copy()
             self.time = 0
             b = 0
             if (method == 'PGZ'):
                 start_time = time.time()
                 n = np.array(self.PGZ(s))
                 self.time += time.time() - start_time
             if (method == 'euclid'):
                 start_time = time.time()
                 n = self.EVCL(s)
                 self.time += time.time() - start_time
             if (n is np.nan):
                 b = 1
                 ans[j] = np.nan
                 continue
             else:
                 n = n.astype(int) 
             a = gf.polyval(n, self.pm.T[1], self.pm)
             an = []
             for i in range(a.shape[0]):
                 if a[i] == 0:
                     an = an + [i]
             rr = np.array(an)
             for i in rr:
                 r[i] = (r[i] + 1) % 2
             s = np.array(gf.polyval(r, self.pm.T[1][:2*self.t], self.pm))
             for i in s:
                 if(i != 0):
                     b = 1
             if (b == 1):
                 ans[j] = np.nan
             else:
                 ans[j] = r[:self.k]
     return ans
Exemplo n.º 6
0
def test_polyval():
    pm = gf.gen_pow_matrix(37)
    p = np.array([11, 29, 26, 31, 3])
    x = np.array([19, 25, 31, 3, 14, 29])
    right_answer = np.array([ 3, 12, 19, 26, 22,  1])
    
    assert_equal(right_answer, gf.polyval(p, x, pm))
Exemplo n.º 7
0
Arquivo: bch.py Projeto: garx0/pa
 def decode_msg(w):
     syndromes = gf.polyval(_lstrip0(w), self.R, pm=self.pm)
     if (syndromes == 0).all():
         return _np.copy(w)
     errloc_poly = decoder(w, syndromes)
     if errloc_poly is _np.nan:
         return _np.full(self.n, _np.nan)
     vals = gf.polyval(errloc_poly, pm_powsfrom0, pm=self.pm)
     roots_degs = _np.where(vals == 0)[0]
     v = _np.copy(w)
     v[roots_degs - 1] ^= 1
     _, r = gf.binpolydiv(_lstrip0(v), self.g)
     if not gf.isnull(r):
         return _np.full(self.n, _np.nan)
     v_syndromes = gf.polyval(_lstrip0(v), self.R, pm=self.pm)
     if (v_syndromes != 0).any():
         return _np.full(self.n, _np.nan)
     return v
Exemplo n.º 8
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
Exemplo n.º 9
0
Arquivo: bch.py Projeto: 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
Exemplo n.º 10
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
Exemplo n.º 11
0
 def correction(self, Lambda, Q):
     lambda_val_in_alpha = gf.polyval(Lambda, self.all_roots, self.pm)
     num_of_lambda_root = 0
     root_position = []
     for j in range(self.n):
         if lambda_val_in_alpha[j] == 0:
             num_of_lambda_root += 1
             root_position.append(j)
     e_row = numpy.zeros(self.n, dtype=int)
     for k in root_position:
         e_row[k] = 1
     return Q ^ e_row, num_of_lambda_root
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
0
def test(n, t, errors):
    result_euc = list()
    #result_pgz = list()
    code = bch.BCH(n, t)
    polynom = np.zeros(n + 1, int)
    polynom[0] = 1
    polynom[-1] = 1
    if gf.polydiv(polynom, code.g, code.pm)[1] != []:
        print('Error!!!')
    U = np.random.randint(0, 2, (100, n - code.g.size + 1))
    V = code.encode(U)
    for v in V:
        if gf.polydiv(v, code.g, code.pm)[1] != []:
            print('Error!!!')
        if gf.polyval(v, code.R, code.pm).any():
            print('Error!!!')
    for k in code.g:
        if k != 0 and k != 1:
            print('Error!!!')
    for err in errors:
        correct = 0
        wrong = 0
        detected = 0
        W = noise(V, err)
        Vx = code.decode(W, 'euclid')
        for i in range(V.shape[0]):
            if np.array_equal(V[i], Vx[i]):
                correct += 1
            elif not np.array_equal(Vx[i], Vx[i]):
                detected += 1
            else:
                wrong += 1
        print(correct, detected, wrong)
        result_euc.append([correct / 100, detected / 100, wrong / 100])
        '''correct = 0
        wrong = 0
        detected = 0
        Vx = code.decode(W, 'pgz')
        for i in range(V.shape[0]):
            if np.array_equal(V[i], Vx[i]):
                correct += 1
            elif not np.array_equal(Vx[i], Vx[i]):
                detected += 1
            else:
                wrong += 1
        print(correct, detected, wrong)
        result_pgz.append((correct / 100, detected / 100, wrong / 100))'''
    return result_euc  #, result_pgz
Exemplo n.º 15
0
    def do_correctness_test(self, q, t, get_msg=None):
        pbar = tqdm(total=8)
        n = 2 ** q - 1
        code = BCH(n, t)
        pbar.update(1)
        self.assertTrue(np.logical_or((code.g == [0]), (code.g == [1])).all())
        self.assertRaises(BaseException, lambda it: code.decode([np.zeros(n + 1).astype(int)]))
        pbar.update(1)
        x = np.zeros(n + 1).astype(int)
        x[0] = 1
        x[-1] = 1
        assert_array_equal(gf.polydiv(x, code.g, code.pm)[1], [0])
        pbar.update(1)

        m = code.g.shape[0] - 1 #gf.polydeg(code.g)
        k = n - m
        self.assertRaises(BaseException, lambda it: code.encode([np.zeros(k + 1).astype(int)]))
        if get_msg is None:
            msg = [random.randint(0, 1) for _ in range(0, k)]
        else:
            msg = get_msg(k)
        coded = code.encode(np.array([msg]))[0]
        assert_array_equal(coded[0:k], msg)
        pbar.update(1)
        self.assertTrue((gf.polyval(coded, code.R, code.pm) == [0]).all())
        pbar.update(1)
        assert_array_equal(gf.polydiv(coded, code.g, code.pm)[1], [0])
        pbar.update(1)
        assert_array_equal(code.decode(np.array([coded]))[0], coded)
        pbar.update(1)
        if t >= 1:
            broken = np.array(coded)
            goig_to_make_count_mistakes = random.randint(0, t)
            mistakes = 0
            i = 0
            while mistakes < goig_to_make_count_mistakes and i < len(broken):
                if random.randint(0, 1) == 1:
                    broken[i] = 1 - broken[i]
                    mistakes += 1
                i += 1
            assert_array_equal(code.decode(np.array([broken]), method='pgz')[0], coded)
            assert_array_equal(code.decode(np.array([broken]), method='euclid')[0], coded)
            assert_array_equal(code.decode(np.array([broken]))[0], coded)
        pbar.update(1)
        pbar.close()
Exemplo n.º 16
0
	def dist(self, check=False):
		k = len(self.pm) - self.g.size + 1
		d = len(self.pm)
		u = np.arange(k - 1, -1, -1).reshape(1,-1)
		for i in range(2**k):
			v = self.encode((i >> u) & 1).reshape(-1)
			if check:
				r = gf.polydiv(v, self.g, self.pm)[1]
				if r.size != 1 or r[0] != 0:
					return False
				s = gf.polyval(v, self.R, self.pm)
				for j in s:
					if j != 0:
						return False
			b = np.sum(v)
			if b < d and b != 0:
				d = b
		if check:
			return d >= self.R.size + 1
		else:
			return d
Exemplo n.º 17
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
Exemplo n.º 18
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)