def findErrors(self, forney_syndromes: Polynomial, length_message: int) -> list: """ Berlekamp-Massey + Chien search to find the 0s of the error locator polynomial :param forney_syndromes: the polynomial representation of the Forney syndromes :param length_message: the length of the message + parity bits :return: the error locator polynomial """ error_loc_polynomial = Polynomial([1]) last_known = Polynomial([1]) # generate the error locator polynomial # - Berklekamp-Massey algorithm for i in range(0, len(forney_syndromes)): # d = S[k] + C[1]*S[k-1] + C[2]*S[k-2] + ... + C[l]*S[k-L] # This is the discrepancy delta delta = forney_syndromes[i] for j in range(1, len(error_loc_polynomial)): delta ^= self.GF.gfMul(error_loc_polynomial[-(j + 1)], forney_syndromes[i - j]) # Calculate the next degree of the polynomial last_known.append(0) # If delta is not 0, correct for it if delta != 0: if len(last_known) > len(error_loc_polynomial): new_polynomial = last_known.scale(delta) last_known = error_loc_polynomial.scale( self.GF.gfInv(delta)) error_loc_polynomial = new_polynomial error_loc_polynomial += last_known.scale(delta) error_loc_polynomial = error_loc_polynomial[::-1] # Stop if too many errors error_count = len(error_loc_polynomial) - 1 if error_count * 2 > len(forney_syndromes): raise ReedSolomonError("Too many errors to correct") # Find the zeros of the polynomial using Chien search error_list = [] for i in range(self.GF.lowSize): error_z = error_loc_polynomial.eval(self.GF.gfPow(2, i)) if error_z == 0: error_list.append(length_message - i - 1) # Sanity checking if len(error_list) != error_count: raise ReedSolomonError("Too many errors to correct") else: return error_list
def findErrors(self, forney_syndromes: Polynomial, length_message: int) -> list: """ BM算法和Chien钱搜索找到0的错误定位多项式 :param forney_syndromes: 表示forney伴随式的多项式 :param length_message: 信息长度和校验位长度之和 :return: 错误定位多项式 """ error_loc_polynomial = Polynomial([1]) last_known = Polynomial([1]) # 生成错误定位多项式 # BM算法 for i in range(0, len(forney_syndromes)): # d = S[k] + C[1]*S[k-1] + C[2]*S[k-2] + ... + C[l]*S[k-L] # 偏差delta delta = forney_syndromes[i] for j in range(1, len(error_loc_polynomial)): delta ^= self.GF.gfMul(error_loc_polynomial[-(j+1)], forney_syndromes[i - j]) # 计算多项式次幂 last_known.append(0) # 如果偏差delta不为0 改正 if delta != 0: if len(last_known) > len(error_loc_polynomial): new_polynomial = last_known.scale(delta) last_known = error_loc_polynomial.scale(self.GF.gfInv(delta)) error_loc_polynomial = new_polynomial error_loc_polynomial += last_known.scale(delta) error_loc_polynomial = error_loc_polynomial[::-1] # 如果错误太多 停止 error_count = len(error_loc_polynomial) - 1 if error_count * 2 > len(forney_syndromes): raise ReedSolomonError("Too many errors to correct") # 用钱(Chien)搜索找到多项式的零点 error_list = [] for i in range(self.GF.lowSize): error_z = error_loc_polynomial.eval(self.GF.gfPow(2, i)) if error_z == 0: error_list.append(length_message - i - 1) # 完整性检查 if len(error_list) != error_count: raise ReedSolomonError("Too many errors to correct") else: return error_list
def generate_shadow_images(self, store_shadows = True): print ("Encryption begins!") img_info = self.img_info n, t, k = self.n, self.t, self.k alpha = self.alpha e = self.e poly_q = self.poly_q shadow_image_size = None shadow_images = [] for i in range(n): print ("Shadow Image no :- {}".format(i)) x_secrets = [] y_secrets = [] lagrange = get_Lagrange_Polynomials(e) prod_fun = get_prod_funs(e) temp_poly = Polynomial(poly_q) temp_poly = temp_poly.multiply(prod_fun) if self.debug == True: #For debugging whether the first term of the generated polynomial is correct for mmm in range(len(e)): value = temp_poly.eval(e[mmm]) if value != 0: raise ValueError("First term of the encrypting polynomial is wrong") quit() #For debugging whether the generated Lagrange Polynomial is correct for nnn in range(len(e)): for j in range(len(lagrange)): if nnn != j: if (lagrange[j].eval(e[nnn]) != 0): raise ValueError("Lagrange Polynmial is wrong") else: if (lagrange[j].eval(e[nnn]) != 1): raise ValueError("Lagrange Polynomial is wrong") for x in img_info.keys(): for y in range(len(img_info[x][1])): bar = img_info[x][1][y] sum_polyx = Polynomial([0]) sum_polyy = Polynomial([0]) for u in range(k): s_x = img_info[x][1][y][u][0] s_y = img_info[x][1][y][u][1] tempx = (lagrange[u]).multiply(Polynomial([s_x])) tempy = (lagrange[u]).multiply(Polynomial([s_y])) sum_polyx = sum_polyx.add(tempx) sum_polyy = sum_polyy.add(tempy) x_poly = temp_poly.add(sum_polyx) y_poly = temp_poly.add(sum_polyy) x_secrets += [x_poly.eval(alpha[i])] y_secrets += [y_poly.eval(alpha[i])] temp_shadow = x_secrets + y_secrets if (shadow_image_size is None): temp_size = len(temp_shadow) while(1): if (floor(sqrt(temp_size)) == ceil(sqrt(temp_size))): break else: temp_size += 1 shadow_image_size = temp_size temp_shadow = temp_shadow + [np.random.randint(0, 256) for u in range(len(x_secrets + y_secrets), shadow_image_size)] temp_shadow = np.array(temp_shadow).astype(int) temp_shadow = temp_shadow.reshape((int(sqrt(shadow_image_size)), int(sqrt(shadow_image_size)))) invalid_positions = [] for x in range(temp_shadow.shape[0]): for y in range(temp_shadow.shape[1]): if temp_shadow[x, y] == 256: invalid_positions += [(x, y)] temp_shadow[x, y] = 255 if store_shadows == True: cv2.imwrite("Shadows/{}.jpg".format(i), temp_shadow) shadow_images += [(temp_shadow, invalid_positions)] print ("Encryption ends!") return shadow_images
p2 = ((x + y) * 10) p3 = (y * x) ** 10 p = p1 * p2 + p3 expectedString = "((((y*2)+x)*(x+y)*10)+((y*x)^10))" compare(expectedString, str(p)) p = 2 + x + 4 + y q = 2 + x + (4 * y) r = (2 + x) * (4 * y) compare("(x+2+4+y)", str(p)) compare("(x+2+(y*4))", str(q)) compare("((x+2)*y*4)", str(r)) q1 = q.eval({"x": 10, "y": 0}) compare(q1, 2) q2 = q.eval({"x": 10, "y": -3}) compare(q2, 1) po = (2 + x) * (4 + x) simplified = po.simplify() comparePoly(po, simplified) po = ((x * 2) + (y * (-4))) * (x + (x * y)) * ((20 * y) + (x * x) + (y * x * y)) simplified = po.simplify() comparePoly(po, simplified)
from Polynomial import Polynomial # = TheClass() coefficients = [10, 3, 3, 4] coefficients1 = [1, 5, 2] coefficients2 = [1, 5] c = Polynomial(coefficients) d = Polynomial(coefficients1) e = Polynomial(coefficients2) print(c.tostr()) print(d.tostr()) print("_________________") print("Eval: " + str(c.eval(2))) print("Sum :" + str(c.addition(d).tostr())) print("Sub: " + c.substraction(d).tostr()) print("Mult: " + c.multiplication(d).tostr()) #print("Div: " + c.division(d).tostr()) print("Deri: " + e.differentiate().tostr())
def polynomialFunctions(PolExpr): newpoli = 0 for c in PolExpr: if c == '[': newpoli = 1 elif c == ']': newpoli = 0 if c == '+' and newpoli == 0: operation = PolExpr.split('+', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("+__________________") return (polynomial1.addition(polynomial2).tostr() + "\n") elif c == '-' and newpoli == 0: operation = PolExpr.split('-', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("-__________________") return (polynomial1.substraction(polynomial2).tostr() + "\n") elif c == '*' and newpoli == 0: operation = PolExpr.split('*', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("*__________________") return (polynomial1.multiplication(polynomial2).tostr() + "\n") elif c == '/' and newpoli == 0: operation = PolExpr.split('/', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("/__________________") if polynomial1.degree() < polynomial2.degree(): return "Numerator must have a higher or equal degree compare with the denominator to be able divide both" if polynomial2.degree() == 0: return "Division by 0 error" result = [] result = polynomial1.division(polynomial2) if len(result) == 3: return result[0].tostr() + " + " + result[2].tostr() + "/" + "(" + result[1].tostr() + ")" + "\n" return (result[0].tostr() + "\n") elif c == '#' and newpoli == 0: operation = PolExpr.split('#', 1) pol1 = strtoPolynomialArray(operation[0]) polynomial1 = Polynomial(pol1) print (polynomial1.tostr()) print ("#__________________") return (polynomial1.differentiate().tostr() + "\n") elif c == '@' and newpoli == 0: operation = PolExpr.split('@', 1) pol1 = strtoPolynomialArray(operation[0]) evalnum = (operation[1].replace("(", "")).replace(")", "") polynomial1 = Polynomial(pol1) print (polynomial1.tostr()) print ("@__________________") return (str(polynomial1.eval(int(evalnum)))+ "\n")
class Polynomial4D: def __init__(self, duration, px, py, pz, pyaw): self.duration = duration self.px = Polynomial(px) self.py = Polynomial(py) self.pz = Polynomial(pz) self.pyaw = Polynomial(pyaw) # compute and return derivative def derivative(self): return Polynomial4D(self.duration, self.px.derivative().p, self.py.derivative().p, self.pz.derivative().p, self.pyaw.derivative().p) @staticmethod def normalize(v): norm = np.linalg.norm(v) assert norm > 0 return v / norm def eval(self, t): result = TrajectoryOutput() # flat variables result.pos = np.array( [self.px.eval(t), self.py.eval(t), self.pz.eval(t)]) result.yaw = self.pyaw.eval(t) # 1st derivative derivative = self.derivative() result.vel = np.array([ derivative.px.eval(t), derivative.py.eval(t), derivative.pz.eval(t) ]) dyaw = derivative.pyaw.eval(t) # 2nd derivative derivative2 = derivative.derivative() result.acc = np.array([ derivative2.px.eval(t), derivative2.py.eval(t), derivative2.pz.eval(t) ]) # 3rd derivative derivative3 = derivative2.derivative() jerk = np.array([ derivative3.px.eval(t), derivative3.py.eval(t), derivative3.pz.eval(t) ]) thrust = result.acc + np.array([0, 0, 9.81]) # add gravity z_body = self.normalize(thrust) x_world = np.array([np.cos(result.yaw), np.sin(result.yaw), 0]) y_body = self.normalize(np.cross(z_body, x_world)) x_body = np.cross(y_body, z_body) jerk_orth_zbody = jerk - (np.dot(jerk, z_body) * z_body) h_w = jerk_orth_zbody / np.linalg.norm(thrust) result.omega = np.array( [-np.dot(h_w, y_body), np.dot(h_w, x_body), z_body[2] * dyaw]) return result