예제 #1
0
파일: bch.py 프로젝트: garx0/pa
 def decoder_euclid(w, syndromes):
     s_poly = _lstrip0(_np.concatenate((syndromes[::-1], [1])))
     _, _, errloc_poly = gf.euclid(gf.polyshift([1], 2 * self.t + 1),
                                   s_poly,
                                   pm=self.pm,
                                   max_deg=self.t + 1)
     return errloc_poly
예제 #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
예제 #3
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
예제 #4
0
파일: bch.py 프로젝트: maloyan/Algebra
    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
예제 #5
0
def test_euclid():
    pm = gf.gen_pow_matrix(37)
    p1 = np.array([2, 14, 22, 23, 8, 17, 31, 11, 26, 3])
    p2 = np.array([31, 23, 30, 31, 11, 9])
    right_answer = (np.array([24, 8, 11]), np.array([1, 23, 14]),
                    np.array([19, 14, 2, 21, 7, 12, 11]))
    max_deg = 2
    result = gf.euclid(p1, p2, pm, max_deg=max_deg)
    assert_equal(right_answer[0], result[0])
    assert_equal(right_answer[1], result[1])
    assert_equal(right_answer[2], result[2])
예제 #6
0
파일: bch.py 프로젝트: BykovDmitrii/pa
 def EVCL(self, s):
     arr = np.ones(s.shape[0] + 1)
     for i in range(s.shape[0]):
         arr[i] = s[s.shape[0] - i - 1]
     arr2 = np.zeros(self.t * 2 + 2)
     arr2[0] = 1
     #print(arr, arr2, self.pm, self.t)
     n = gf.euclid(arr, arr2, self.pm, self.t+1)
     #print(n)
     n = n[1]
     return n
예제 #7
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
예제 #8
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
예제 #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
예제 #10
0
파일: bch.py 프로젝트: 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
예제 #11
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
예제 #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
예제 #13
0
파일: bch.py 프로젝트: t3kashi/BCH-Decoding
    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)
예제 #14
0
파일: bch.py 프로젝트: anuartask/MLpractice
 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