def test_scale_1(self): one = Polynomial([2,4,7,3]) scalar = 12 r = one.scale(12) self.assertEqual(list(r.coefficients), [24, 48, 84, 36])
def test_scale(self): one = Polynomial(map(GF2int, [2,14,7,3])) scalar = 12 r = one.scale(12) self.assertEqual(list(r.coefficients), [24, 72, 36, 20])
def test_mul_at(self): one = Polynomial(map(GF2int, [2,4,7,3])) two = Polynomial(map(GF2int, [5,2,4,2])) k = 3 r1 = one * two r2 = one.mul_at(two, k) self.assertEqual(r1.get_coefficient(k), r2)
def polynomialbasin(coeffs, vw, auto=False, n=10, dots=True, mode=1, filename=None, save=True): p = Polynomial(*coeffs) rootlist = list(p.roots()) rootlist.sort(cmp=argcmp) if auto: vw.autocomplex(*rootlist) if filename is None: filename = "polynomialbasin {poly} {n} {dots} {time}".format(poly=p, n=n, dots=dots, time=str(int(time()))) return globals()["basin" + str(mode) * (mode in (2, 3))](p, rootlist, Color.colors(len(rootlist)), vw, p.deriv(), n, dots, filename, save)
def test_div_fast(self): one = Polynomial(map(GF2int, [8,3,5,1])) two = Polynomial(map(GF2int, [5,3,1,1,6,8])) q, r = two._fastdivmod(one) self.assertEqual(list(q.coefficients), [101, 152, 11]) self.assertEqual(list(r.coefficients), [183, 185, 3]) # Make sure they multiply back out okay self.assertEqual(q*one + r, two)
def test_div_fast_1(self): # no remander one = Polynomial([1,0,0,2,2,0,1,-2,-4]) two = Polynomial([1,0,-1]) q, r = one._fastdivmod(two) self.assertEqual(q, one._fastfloordiv(two)) self.assertEqual(r, one._fastmod(two)) self.assertEqual(list(q.coefficients), [1,0,1,2,3,2,4]) self.assertEqual(list(r.coefficients), [0])
def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'single.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'single.py -i <inputfile> -o <outputfile> ' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg try: fi = open(inputfile,"r") fl = open(outputfile,"a") except IOError: print 'main.py -i <inputfile> -o <outputfile>' sys.exit(2) l = [] for i in fi: p = Polynomial(i) l.append(p) name = outputfile name = name + ".xlsx" name = "" + name workbook = xlsxwriter.Workbook(name) worksheet = workbook.add_worksheet("irredutiveis") worksheet.write(0,0, "Polynomials") worksheet.write(0,1, "m") worksheet.write(0,2, "a") worksheet.write(0,3, "b") worksheet.write(0,4, "c") worksheet.write(0,5, "d") row = 1 colum = 0 for p in l: colum = 0 worksheet.write(row,colum, str(p.coefs())) colum = 1 j = sorted(p.coefs(), reverse=True) for num in j: worksheet.write(row,colum, num) colum = colum+1 row = row + 1 workbook.close()
def main(argv): inputfile = '' outputfile = '' debug = False try: opts, args = getopt.getopt(argv,"hi:o:d",["ifile=","ofile="]) except getopt.GetoptError: print 'single.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'single.py -i <inputfile> -o <outputfile> -d for debug' sys.exit() elif opt in ("-d", "--debug"): debug = True elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg try: fi = open(inputfile,"r") fl = open(outputfile,"a") except IOError: print 'main.py -i <inputfile> -o <outputfile>' sys.exit(2) l = [] pols = [] files = [inputfile] for fileName in files: save = outputfile f = open(fileName,'r') #read, pols = recoverfile(save, f) if True: for line in f: try: pol = Polynomial(line) pols.append(pol) except Exception as e: print line sys.exit(2) result = defaultdict(list) print len(pols) for pol in pols: if len(pol.coefs()) > 1: red = Reduction(debug) count = red.reduction(pol.coefs()) result = str(pol.coefs()) + ":" + str(count) print result fl.write(result + "\n")
def test_simple_operations(self): """tests with some specific polynomials""" p1 = Polynomial([2.,0,3.,0]) # 2 + 3x^2 self.assertEqual(str(p1), '2.0 + 3.0X^2') self.assertEqual(repr(p1), 'Polynomial([2.0, 0.0, 3.0])') p2 = Polynomial([3.,2.]) #3 + 2x self.assertEqual(str(p2), '3.0 + 2.0X') self.assertEqual(p1.degree(), 2) self.assertEqual(p1[4], 0, "Index out of range should return zero") self.assertEqual(p1[0], 2) self.assertEqual(p1+p2, Polynomial([5,2,3])) self.assertEqual(p1.differentiate(), Polynomial([0,6])) self.assertEqual(p1(2), 14) self.assertEqual(p1*p2, Polynomial([6., 4., 9., 6.]))
def recover(shares, pword=""): #Intial Stuff intmod.set_base(59) #Construct key, If no password is provided, default password of "" is used seclen=len(shares[0])-1 if pword: key=genpad(seclen,pword) else: key=[intmod(0) for c in xrange(seclen)] #Catch errors Two keys for the same point lsh=len(shares) xs=[intmod(b58conv(shares[i][-1])) for i in xrange(lsh)] todel=[] for i in xrange(lsh-1): for j in xrange(i+1,lsh): if xs[i]==xs[j]: if j not in todel: todel.append(j) d=0 todel=sorted(todel,reverse=True) for i in todel: del xs[i] del shares[i] d=d+1 lsh=lsh-d #Construct the Lagrange Polynomials (These are the same for all elements) l=[] for i in xrange(lsh): lt=Polynomial(x0=intmod(1)) for j in xrange(lsh): if i != j: if (xs[i]-xs[j])==intmod(0): raise ValueError("Two of your keys are for identical points please remedy this") lt=lt*(Polynomial(x1=intmod(1),x0=-xs[j])) lt=lt//Polynomial(x0=(xs[i]-xs[j])) l.append(lt) #Reconstruct Secret (To best knowledge), Completes Lagrange integration for each character #Evaluates at 0 and converts into a base 58 character rect=[] for i in xrange(seclen): p=Polynomial(x0=intmod(0)) for j in xrange(lsh): p=p+Polynomial(x0=(b58conv(shares[j][i])))*l[j] rect.append(r58conv(p.evaluate(intmod(0))-key[i%64])) return "".join(rect)
def test_div_gffast(self): one = Polynomial(map(GF2int, [1,3,5,1])) # must be monic! (because the function is optimized for monic divisor polynomial) two = Polynomial(map(GF2int, [5,3,1,1,6,8])) q, r = two._gffastdivmod(one) # optimized for monic divisor polynomial q2, r2 = two._fastdivmod(one) self.assertEqual(q, q2) self.assertEqual(r, r2) self.assertEqual(list(q.coefficients), [5, 12, 4]) self.assertEqual(list(r.coefficients), [52, 30, 12]) # Make sure they multiply back out okay self.assertEqual(q*one + r, two)
def test_orientation_reprojection(self): true_s = np.array([.1, .2, -.3]) true_r = utils.cayley(true_s) true_k = 1. / (1. + np.dot(true_s, true_s)) true_vars = np.r_[true_s, true_k] xs = np.random.rand(8, 3) true_ys = np.dot(xs, true_r.T) sym_vars = Polynomial.coordinates(4, ctype=float) x, y, z, w = sym_vars sym_s = sym_vars[:3] sym_k = sym_vars[3] sym_r = utils.cayley_mat(sym_s) sym_rd = utils.cayley_denom(sym_s) residuals = (np.dot(xs, sym_r.T) - true_ys * sym_rd).flatten() cost = sum(r**2 for r in residuals) gradients = cost.partial_derivatives() constraint = sym_k * (1 + np.dot(sym_s, sym_s)) - 1 print 'Cost:', cost print 'Constraint:', constraint print 'At ground truth:' print ' Cost = ', cost(*true_vars) print ' Constraint = ', constraint(*true_vars) print ' Gradients = ', [p(*true_vars) for p in gradients] expansions = [solvers.all_monomials(sym_vars, 2) for _ in range(cost.num_vars)] for a in expansions: a.extend([z*z*w, x*x*w, y*y*w, z*z*w*w, z*w*w]) minima = optimize.minimize_globally(cost, [constraint], expansions=expansions, diagnostic_solutions=[true_vars]) print 'Minima: ', minima
def test_ntt_mul(): global w,wInv print "test_ntt_mul" powers2 = [pow(2,i) for i in range(1,19)] for N in powers2: print N k = (P-1)/(2*N) assert (P-1)%(2*N) == 0 wN = pow(7,k,P) assert pow(wN,(2*N),P) == 1 w = [] for j in range(2*N): w.append(pow(wN,j,P)) wInv = [] for j in range(2*N): wInv.append(pow(w[j],P-2,P)) a = [randint(0,2**16) for _ in xrange(N)]+[0]*N b = [randint(0,2**16) for _ in xrange(N)]+[0]*N polynomial_a = Polynomial() polynomial_a.coef = a polynomial_b = Polynomial() polynomial_b.coef = b polynomial_c = polynomial_a*polynomial_b my_ntt_a = CPU_NTT(a) my_ntt_b = CPU_NTT(b) my_ntt_c = [x[0]*x[1] % P for x in zip(my_ntt_a,my_ntt_b)] ntt_intt_c = CPU_INTT(my_ntt_c) # assert len(ntt_intt_c) == len(polynomial_c.coef) for i,v in enumerate(polynomial_c.coef): v2 = ntt_intt_c[i]/(2*N) assert v == v2 print "We are good"
def test_two_vars(self): x, y = Polynomial.coordinates(2) equations = [x**2 + y**2 - 1, x-y] expansion_monomials = [ [x, y], [x, y, x*y, x*x, y*y] ] result = solvers.solve_via_basis_selection(equations, expansion_monomials, x+y+1) expected_solutions = [np.sqrt([.5, .5]), -np.sqrt([.5, .5])] self.assert_solutions_found(result, expected_solutions)
def test_estimate_pose_and_depths(self): np.random.seed(0) num_landmarks = 5 # Generate ground truth true_cayleys = np.array([.1, .2, -.3]) true_orientation = utils.cayley(true_cayleys) true_position = np.array([2., 3., 10.]) # Generate observed quantities true_landmarks = np.random.randn(num_landmarks, 3) true_pfeatures = np.dot(true_landmarks - true_position, true_orientation.T) true_depths = np.sqrt(np.sum(np.square(true_pfeatures), axis=1)) true_features = true_pfeatures / true_depths[:, None] true_vars = np.hstack((true_orientation.flatten(), true_position, true_depths)) # Create symbolic quantities sym_vars = Polynomial.coordinates(12 + num_landmarks, ctype=float) sym_orientation = np.reshape(sym_vars[:9], (3, 3)) sym_position = np.array(sym_vars[9:12]) sym_depths = np.array(sym_vars[12:]) residuals = [] for i, (landmark, feature, sym_depth) in enumerate(zip(true_landmarks, true_features, sym_depths)): residual = np.dot(sym_orientation, landmark - sym_position) - sym_depth * feature residuals.extend(residual) constraints = (np.dot(sym_orientation.T, sym_orientation) - np.eye(3)).flatten() cost = sum(r**2 for r in residuals) gradients = cost.partial_derivatives() print 'Cost:', cost print 'Constraints:' for constraint in constraints: print ' ', constraint print 'At ground truth:' print ' Cost = ', cost(*true_vars) print ' Constraints = ', utils.evaluate_array(constraints, *true_vars) print ' Gradients = ', [p(*true_vars) for p in gradients] expansions = solvers.all_monomials(sym_vars, 2) minima = optimize.minimize_globally(cost, constraints, expansions=expansions, #diagnostic_solutions=[true_vars], ) estimated_r = np.reshape(minima, (3, 3)) error = np.linalg.norm(estimated_r - true_orientation) print 'Minima:\n', estimated_r print 'Ground truth:\n', true_orientation print 'Error:', error
def test_synthetic_ideal(self): zeros = [[-2., -3., 5., 6.], [4.5, 5., -1., 8.]] equations = ideal_from_variety(zeros, ctype=float) coords = Polynomial.coordinates(len(zeros[0])) expansion_monomials = solvers.all_monomials(coords, degree=1) lambda_poly = sum(xi * (i + 1) for i, xi in enumerate(coords)) + 1 result = solvers.solve_via_basis_selection( equations, expansion_monomials, lambda_poly, diagnostic_solutions=[zeros[0]]) self.assert_solutions_found(result, zeros)
def main(argv): inputfile = '' outputfile = '' ka = '' try: opts, args = getopt.getopt(argv,"hi:o:k:",["ifile=","ofile=",]) except getopt.GetoptError: print 'extract.py -i <inputfile> -o <outputfile> -k 1,2,3,4,5,...' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'extract.py -k 1,2,3,4,5,... -i <inputfile> -o <outputfile> ' sys.exit() elif opt in ("-i", "--ifile"): print "-i", arg inputfile = arg elif opt in ("-o", "--ofile"): print "-o", arg + "_" + str(ka) outputfile = arg + "_" + str(ka) elif opt in ("-k"): print "ka = ", arg ka = arg try: f = open(inputfile,'r') except IOError: print 'Error to open the file' print 'ka.py -i <inputfile> -o <outputfile> -k 1,2,3,4,5,6,...' sys.exit(2) to_save = open(outputfile,"a") for line in f: pol = Polynomial(line) l = sorted(pol.coefs(), reverse=True) k = math.floor((l[0]-2)/(l[0]-l[1])) if k == int(ka): to_save.write(line)
def test_two_circles(self): x, y = Polynomial.coordinates(2) equations = [ (x+2)**2 + (y+2)**2 - 25, (x-6)**2 + (y+2)**2 - 25, ] expansion_monomials = [x, y, x*y, x*x, y*y, x*x*y] expected_solutions = [(2, 1), (2, -5)] result = solvers.solve_via_basis_selection(equations, expansion_monomials, x+2*y-3, diagnostic_solutions=expected_solutions) self.assert_solutions_found(result, expected_solutions)
def find_critical_points(polynomial, constraints=None, expansions=2, lambda_poly=None, seed=0, **kwargs): """Find all local minima, local maxima, and saddle points of the given polynomial by solving the first order conditions.""" system = polynomial.astype(float).partial_derivatives() system = filter(lambda p: p.total_degree > 0, system) if constraints is not None: system.extend(constraints) coords = Polynomial.coordinates(polynomial.num_vars, ctype=float) if lambda_poly is None: rng = random.Random(seed) # use this rng for repeatability lambda_poly = sum(p * rng.random() for p in coords) + rng.random() if isinstance(expansions, numbers.Integral): expansions = [solvers.all_monomials(coords, expansions)] * len(system) return solvers.solve_via_basis_selection(system, expansions, lambda_poly, **kwargs)
def main(argv): inputfile = '' outputfile = '' debug = False try: opts, args = getopt.getopt(argv,"hi:o:d",["ifile=","ofile="]) except getopt.GetoptError: print 'single.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'single.py -i <inputfile> -o <outputfile> -d for debug' sys.exit() elif opt in ("-d", "--debug"): debug = True elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg try: fi = open(inputfile,"r") fl = open(outputfile,"a") except IOError: print 'main.py -i <inputfile> -o <outputfile>' sys.exit(2) pols = [] for line in fi: try: pol = Polynomial(line) pols.append(pol) except Exception as e: print line sys.exit(2) for pol in pols: st = str(pol.coefs()) + ":0" + "\n" fl.write(st) fl.close()
def test_three_circles(self): x, y, z = Polynomial.coordinates(3) equations = [ (x-6)**2 + (y-1)**2 + (z-1)**2 - 25, (x-1)**2 + (y-6)**2 + (z-1)**2 - 25, (x-1)**2 + (y-1)**2 + (z-6)**2 - 25, ] expansion_monomials = solvers.all_monomials((x, y, z), degree=2) expected_solutions = [(1, 1, 1)] lambda_poly = x + 2*y + 3*z + 4 result = solvers.solve_via_basis_selection(equations, expansion_monomials, lambda_poly, diagnostic_solutions=expected_solutions) self.assert_solutions_found(result, expected_solutions)
def test_three_vars(self): x, y, z = Polynomial.coordinates(3) equations = [ x**2 + y**2 + z**2 - 1, x - y, x - z ] expansion_monomials = [ [], [x, y, z], [x, y, z] ] result = solvers.solve_via_basis_selection(equations, expansion_monomials, x) point = np.sqrt(np.ones(3) / 3.) expected_solutions = [point, -point] self.assert_solutions_found(result, expected_solutions)
def test_range_optimization_2d(self): np.random.seed(0) bases = np.round(np.random.randn(2, 3) * 6.) true_position = np.array([-2., 1., 3.]) true_ranges = np.array([np.linalg.norm(base - true_position) for base in bases]) true_vars = np.hstack((true_position, true_ranges)) sym_vars = Polynomial.coordinates(3 + len(bases), float) sym_position = sym_vars[:3] sym_ranges = sym_vars[3:] cost = sum((zz - z)**2 for zz, z in zip(sym_ranges, true_ranges)) constraints = [np.sum(np.square(base - sym_position)) - sym_range*sym_range for base, sym_range in zip(bases, sym_ranges)] lagrangian = make_langrangian(-cost, constraints) gradients = lagrangian.partial_derivatives() print 'Cost:', cost print 'Lagrangian:', lagrangian print 'Constraints:' for constraint in constraints: print ' ', constraint print 'Gradients:' for gradient in gradients: print ' ', gradient print 'At ground truth:' print ' Cost = ', cost(*true_vars) print ' Constraints = ', utils.evaluate_array(constraints, *true_vars) #print ' Gradients = ', [p(*true_vars) for p in gradients] expansions = 3 # solvers.all_monomials(sym_vars, 2) + [sym_vars[2]**3, sym_vars[0]**2*sym_vars[2]] minima = optimize.minimize_globally(-lagrangian, [], expansions=expansions, verbosity=2, diagnostic_solutions=[], include_grobner=False) error = np.linalg.norm(minima - true_position) print minima print true_position print 'Error:', error
def test_estimate_orientation_9params(self): np.random.seed(0) true_s = np.array([.1, .2, -.3]) true_r = utils.cayley(true_s) true_vars = true_r.flatten() observed_xs = np.random.rand(8, 3) observed_ys = np.dot(observed_xs, true_r.T) sym_vars = Polynomial.coordinates(9, ctype=float) sym_r = np.reshape(sym_vars, (3, 3)) residuals = (np.dot(observed_xs, sym_r.T) - observed_ys).flatten() constraints = (np.dot(sym_r.T, sym_r) - np.eye(3)).flatten() cost = sum(r**2 for r in residuals) gradients = cost.partial_derivatives() print 'Cost:', cost print 'Constraints:' for constraint in constraints: print ' ', constraint print 'At ground truth:' print ' Cost = ', cost(*true_vars) print ' Constraints = ', utils.evaluate_array(constraints, *true_vars) print ' Gradients = ', [p(*true_vars) for p in gradients] expansions = [solvers.all_monomials(sym_vars, 2) for _ in range(cost.num_vars)] minima = optimize.minimize_globally(cost, constraints, expansions=expansions, #diagnostic_solutions=[true_vars], ) estimated_r = np.reshape(minima, (3, 3)) error = np.linalg.norm(estimated_r - true_r) print 'Minima:\n', estimated_r print 'Ground truth:\n', true_r print 'Error:', error
def test_optimize_2d(self): np.random.seed(0) x, y = Polynomial.coordinates(2, float) fs = [ x+1, y+1, x*x, ] true_solution = np.array([2., 5.]) cost = sum((f(x, y) - f(*true_solution)) ** 2 for f in fs) import matplotlib.pyplot as plt dX, dY = np.meshgrid(np.linspace(-.1, .1, 50), np.linspace(-.1, .1, 50)) X = true_solution[0] + dX Y = true_solution[1] + dY * 1j Z = np.abs(cost(X, Y)) print np.min(Z), np.max(Z) plt.contourf(dX, dY, Z, levels=np.logspace(np.log10(np.min(Z)), np.log10(np.max(Z)), 16)) plt.plot(0, 0, 'mx') plt.show() return gradients = cost.partial_derivatives() print 'Cost:', cost print 'Residuals:' for f in fs: print f(x, y) - f(*true_solution) print 'Gradients:' for gradient in gradients: print ' ', gradient(*true_solution) print 'Jacobian:' print polynomial_jacobian(fs)(*true_solution) expansions = 3 # solvers.all_monomials(sym_vars, 2) + [sym_vars[2]**3, sym_vars[0]**2*sym_vars[2]] minima = optimize.minimize_globally(cost, expansions=expansions, verbosity=2, constraints=fs[:2], #diagnostic_solutions=[true_vars] ) np.testing.assert_array_almost_equal(minima, true_solution)
def test_approx_equal(self): # test non-polynomial returns False self.assertFalse(Polynomial([1, 1]).approx_equal('Not A Polynomial')) # test exact match returns true p1 = Polynomial([1, 1]) p2 = Polynomial([1, 1]) self.assertTrue(p1.approx_equal(p2)) # test "large difference" returns false p1 = Polynomial([1, 1]) p2 = Polynomial([1, 2]) self.assertFalse(p1.approx_equal(p2)) p1 = Polynomial([1, 1]) p2 = Polynomial([1, 1.000001]) self.assertTrue(p1.approx_equal(p2, abs_tol=0.00001, rel_tol=1e-50)) self.assertFalse(p1.approx_equal(p2, abs_tol=0.00000001, rel_tol=1e-50)) p1 = Polynomial([2, 1.0, 1, 1.0, 0, 1.1]) p2 = Polynomial([2, 1.001, 1, 1.01, 0, 1.101]) self.assertTrue(p1.approx_equal(p2, abs_tol=0.011)) self.assertFalse(p1.approx_equal(p2, abs_tol=0.01))
def test_when_polynomial_is_constant(self): polynomial = Polynomial('8') expected_derivative = '0' self.assertEqual(polynomial.find_derivative(), expected_derivative)
def test_when_polynomial_is_shuffled(self): polynomial = Polynomial('0-5x^2+2x-x^3') expected_derivative = '-3x^2-10x+2' self.assertEqual(polynomial.find_derivative(), expected_derivative)
def _lazy_get_scale_(self, ig, cosp=Polynomial.fromSeq((1,0,-1))): return (self**2 * cosp**self.__q).integral(-1, 0)(1) ** .5
def extend(self, element): """Opposite of project - returns a representation of @element in the extended field""" assert element in self._gf, "%r not in field %r" % (element, self._gf) pol = Polynomial(self._gf, [element]) return self(pol)
def test_polynomial_negate(): f = Polynomial([1, 2, 3]) assert_that((-f).coefficients).is_equal_to([-1, -2, -3])
def test_mul_with_number(self): self.assertEqual(Polynomial([3, 6, -12]), Polynomial([1, 2, -4]) * 3)
def test_find_derivative(self): polynomial = Polynomial('5x^2-7x+0') expected_derivative = '10x-7' self.assertEqual(polynomial.find_derivative(), expected_derivative)
from polynomial import Polynomial poly1 = Polynomial() poly2 = Polynomial() data_file = open("data1.txt", "r") data_list = data_file.readlines() data_file.close() for line in data_list: degree, coefficient = line.strip().split() poly1._appendTerm(float(degree), float(coefficient)) data_file = open("data2.txt", "r") data_list = data_file.readlines() data_file.close() for line in data_list: degree, coefficient = line.strip().split() poly2._appendTerm(float(degree), float(coefficient)) print(poly1) print(poly2) print(poly1.degree()) print(poly2.degree()) print(poly2[2.0]) new_p = poly1 + poly2 print(new_p[3.0], new_p[2.0], new_p[1.0], new_p[0.0])
import crt from polynomial import Polynomial from random import random q = 987587 M, primes = crt.get_primes(8, q, 10) P = Polynomial() P.coef = [int(q * random()) for i in xrange(8)] residues = crt.crt(P, primes) assert crt.icrt(residues, M, primes) == P residuesP2 = [x * x for x in residues] assert crt.icrt(residuesP2) == (P * P % q)
def _calc_one(self): """Return field's one""" return self(Polynomial(self._gf, [self._gf.one()]))
def _calc_zero(self): """Return field's zero""" return self(Polynomial(self._gf, []))
def _rand(self, nonzero): """Return a random field element""" pol = Polynomial.rand(self._gf, self._ext - 1) while nonzero and pol.is_zero(): pol = Polynomial.rand(self._gf, self._ext - 1) return self(pol)
def _berlekamp_massey(self, s): """Вычисляет и возвращает в полином описывающий положение ошибки (sigma) и в полином оценивающий ошибку (omega) Параметр s является синдромом многочлена (синдром кодируется в функциональном генераторе) который возвращает _синдромов. Не путать с другим s = (n-k)/2 Примечания: Полином описывающий ошибку: E(x) = E_0 + E_1 x + ... + E_(n-1) x^(n-1) j_1, j_2, ..., j_s позиция ошибки. (Есть в большинсвте s ошибках) Положение ошибки X_i определяется: X_i = α^(j_i) то есть, мощность α соответствующая положению ошибки Величина ошибки Y_i определяется: E_(j_i) то есть, коэффициент в полиноме описывающем ошибку j_i Полином описывающий положение ошибки: sigma(z) = Product( 1 - X_i * z, i=1..s ) корни обратные местам ошибок ( 1/X_1, 1/X_2, ...) полином оценивающий ошибку omega(z) здесь не описывается """ n = self.n k = self.k # Инициализация: sigma = [Polynomial((GF256int(1), ))] omega = [Polynomial((GF256int(1), ))] tao = [Polynomial((GF256int(1), ))] gamma = [Polynomial((GF256int(0), ))] D = [0] B = [0] # Константы: ONE = Polynomial(z0=GF256int(1)) ZERO = Polynomial(z0=GF256int(0)) Z = Polynomial(z1=GF256int(1)) # Итеративно вычисляем полиномы до 2s раз. # Последний из них будет правильными. for l in xrange(0, n - k): # Цель для каждой итерации: вычисляем sigma[l+1] и omega[l+1] что # (1 + s)*sigma[l] == omega[l] в mod z^(l+1) # Для этой конкретной итерации, мы имеем sigma[l] и omega[l], # и вычисления sigma[l+1] и omega[l+1] # Первым находим Delta, с ненулевыми коэффицентами z^(l+1) в # (1 + s) * sigma[l] # Эта Delta действительна для l (в этой итерации) только Delta = ((ONE + s) * sigma[l]).get_coefficient(l + 1) # Делаем этот полином в степени 0 Delta = Polynomial(x0=Delta) # Теперь можем вычислить sigma[l+1] и omega[l+1] для # sigma[l], omega[l], tao[l], gamma[l], и Delta sigma.append(sigma[l] - Delta * Z * tao[l]) omega.append(omega[l] - Delta * Z * gamma[l]) # Далее вычисляем tao и gamma # Есть два способа сделать это if Delta == ZERO or 2 * D[l] > (l + 1): # Сбособ 1 D.append(D[l]) B.append(B[l]) tao.append(Z * tao[l]) gamma.append(Z * gamma[l]) elif Delta != ZERO and 2 * D[l] < (l + 1): # Способ 2 D.append(l + 1 - D[l]) B.append(1 - B[l]) tao.append(sigma[l] // Delta) gamma.append(omega[l] // Delta) elif 2 * D[l] == (l + 1): if B[l] == 0: # Способ 1 (как указанно выше) D.append(D[l]) B.append(B[l]) tao.append(Z * tao[l]) gamma.append(Z * gamma[l]) else: # Способ 2 (как указанно выше) D.append(l + 1 - D[l]) B.append(1 - B[l]) tao.append(sigma[l] // Delta) gamma.append(omega[l] // Delta) else: raise Exception("Код не должен быть получен здесь") return sigma[-1], omega[-1]
def test_polynomial_evaluate_at(): f = Polynomial([1, 2, 3]) assert_that((f(2))).is_equal_to(1 + 4 + 12)
def decode(self, r, nostrip=False): """Принимаем полученную строку или массив байт r и пытаемся расшифровать. Если это действующее кодовое слово, или если не содержит более (n-k)/2 ошибок, сообщение возвращается. Сообщение всегда имеет k байт, если сообщение меньше то оно дополняется нулевыми байтами. При декодировании отделим эти ведущие нулевые байты но это может вывать проблемы при декодировании двоичных данных. Когда nostrip истина, сообщение всегда возвращает k байт. Это полезно и позволяет убедиться, что нету потерянных данных при декодировании. """ n = self.n k = self.k if self.verify(r): # Последние n-k байты четности if nostrip: return r[:-(n - k)] else: return r[:-(n - k)].lstrip("\0") #### Возвращаем r в полином r = Polynomial(GF256int(ord(x)) for x in r) # Вычисляем синдромы: sz = self._syndromes(r) # Найдем полином описывающий положение ошибки и полином оценивающий # ошибку используя алгоритм Берлекампа-Месси sigma, omega = self._berlekamp_massey(sz) # Now use Chien's procedure для нахождения позиции ошибки # j это массив целых чисел, представляющий позиции ошибок, 0 # означает самый правый байт # X соответствует значению массива GF(2^8) значений, # где X_i = alpha^(j_i) X, j = self._chien_search(sigma) # Найдем велинины ошибок с помощью метода Форни # Y в массиве GF(2^8) это значение, соответствующей величины ошибки # с позицией заданной массивом j Y = self._forney(omega, X) # Поставим ошибку и ее положение вместе, в полином ошибок Elist = [] for i in xrange(255): if i in j: Elist.append(Y[j.index(i)]) else: Elist.append(GF256int(0)) E = Polynomial(reversed(Elist)) # Получаем наше кодовое слово c = r - E # Формируем его обратно в строку и возвращаем все последние n-k байт ret = "".join(chr(x) for x in c.coefficients[:-(n - k)]) if nostrip: # Полиномиальные объекты не хранят ведущие нулевые коэффициенты, # поэтому мы на самом деле должны дополнить это до k байт return ret.rjust(k, "\0") else: return ret
def test_polynomial_multiply(): f = Polynomial([1, 2, 3]) g = Polynomial([4, 5, 6]) assert_that((f * g).coefficients).is_equal_to([4, 13, 28, 27, 18])
def test_create_polynomial_with_empty_monomials(self): polynomial = Polynomial('5x+0x+9+0x') expected_monomials = [Monomial(5, 1), Monomial(9, 0)] self.assertEqual(polynomial.get_polynomial(), expected_monomials)
def test_create_polynomial(self): polynomial = Polynomial('5x^2-x-7') expected_monomials = [Monomial(5, 2), Monomial(-1, 1), Monomial(-7, 0)] self.assertEqual(polynomial.get_polynomial(), expected_monomials)
def test_create_empty_polynomial(self): polynomial = Polynomial('0x') expected_monomials = [] self.assertEqual(polynomial.get_polynomial(), expected_monomials)
def run_epipolar(): # Construct symbolic problem num_landmarks = 10 num_frames = 3 true_landmarks = np.random.randn(num_landmarks, 3) true_positions = np.vstack((np.zeros(3), np.random.rand(num_frames-1, 3))) true_cayleys = np.vstack((np.zeros(3), np.random.rand(num_frames-1, 3))) true_qs = map(cayley_mat, true_cayleys) true_rotations = map(cayley, true_cayleys) true_uprojections = [[np.dot(R, x-p) for x in true_landmarks] for R,p in zip(true_rotations, true_positions)] true_projections = [[normalized(zu) for zu in row] for row in true_uprojections] p0 = true_positions[0] q0 = true_qs[0] for i in range(1, num_frames): p = true_positions[i] q = true_qs[i] E = essential_matrix(q0, p0, q, p) for j in range(num_landmarks): z = true_projections[i][j] z0 = true_projections[0][j] print np.dot(z, np.dot(E, z0)) # construct symbolic versions of the above s_offs = 0 p_offs = s_offs + (num_frames-1)*3 num_vars = p_offs + (num_frames-1)*3 sym_vars = [Polynomial.coordinate(i, num_vars, Fraction) for i in range(num_vars)] sym_cayleys = np.reshape(sym_vars[s_offs:s_offs+(num_frames-1)*3], (num_frames-1, 3)) sym_positions = np.reshape(sym_vars[p_offs:p_offs+(num_frames-1)*3], (num_frames-1, 3)) true_vars = np.hstack((true_cayleys[1:].flatten(), true_positions[1:].flatten())) residuals = [] p0 = np.zeros(3) R0 = np.eye(3) for i in range(1, num_frames): sym_p = sym_positions[i-1] sym_s = sym_cayleys[i-1] sym_q = cayley_mat(sym_s) sym_E = essential_matrix(R0, p0, sym_q, sym_p) for j in range(num_landmarks): z = true_projections[i][j] z0 = true_projections[0][j] residual = np.dot(z, np.dot(sym_E, z0)) print 'Residual poly: ',len(residual), residual.total_degree residuals.append(residual) print 'Num sym_vars:',num_vars print 'Num residuals:',len(residuals) print 'Residuals:', len(residuals) cost = Polynomial(num_vars) for residual in residuals: #cost += np.dot(residual, residual) print ' ',residual(*true_vars) #ri.num_vars, len(true_vars) print '\nGradients:' gradient = [cost.partial_derivative(i) for i in range(num_vars)] for gi in gradient: print ' ',gi(*true_vars) J = np.array([[r.partial_derivative(i)(*true_vars) for i in range(num_vars)] for r in residuals]) print '\nJacobian singular values:' print J.shape U,S,V = np.linalg.svd(J) print S print V[-1] print V[-2] print '\nHessian eigenvalues:' H = np.dot(J.T, J) print H.shape print np.linalg.eigvals(H)
def run_spline_epipolar(): # Construct symbolic problem num_landmarks = 10 num_frames = 3 num_imu_readings = 8 bezier_degree = 4 out = 'out/epipolar_accel_bezier3' if not os.path.isdir(out): os.mkdir(out) # Both splines should start at 0,0,0 frame_times = np.linspace(0, .9, num_frames) imu_times = np.linspace(0, 1, num_imu_readings) true_rot_controls = np.random.rand(bezier_degree-1, 3) true_pos_controls = np.random.rand(bezier_degree-1, 3) true_landmarks = np.random.randn(num_landmarks, 3) true_cayleys = np.array([zero_offset_bezier(true_rot_controls, t) for t in frame_times]) true_positions = np.array([zero_offset_bezier(true_pos_controls, t) for t in frame_times]) true_accels = np.array([zero_offset_bezier_second_deriv(true_pos_controls, t) for t in imu_times]) true_qs = map(cayley_mat, true_cayleys) true_rotations = map(cayley, true_cayleys) true_uprojections = [[np.dot(R, x-p) for x in true_landmarks] for R,p in zip(true_rotations, true_positions)] true_projections = [[normalized(zu) for zu in row] for row in true_uprojections] p0 = true_positions[0] q0 = true_qs[0] for i in range(1, num_frames): p = true_positions[i] q = true_qs[i] E = essential_matrix(q0, p0, q, p) for j in range(num_landmarks): z = true_projections[i][j] z0 = true_projections[0][j] #print np.dot(z, np.dot(E, z0)) # construct symbolic versions of the above s_offs = 0 p_offs = s_offs + (bezier_degree-1)*3 num_vars = p_offs + (bezier_degree-1)*3 sym_vars = [Polynomial.coordinate(i, num_vars, Fraction) for i in range(num_vars)] sym_rot_controls = np.reshape(sym_vars[s_offs:s_offs+(bezier_degree-1)*3], (bezier_degree-1, 3)) sym_pos_controls = np.reshape(sym_vars[p_offs:p_offs+(bezier_degree-1)*3], (bezier_degree-1, 3)) true_vars = np.hstack((true_rot_controls.flatten(), true_pos_controls.flatten())) residuals = [] # Accel residuals for i in range(num_imu_readings): sym_a = zero_offset_bezier_second_deriv(sym_pos_controls, imu_times[i]) residual = sym_a - true_accels[i] residuals.extend(residual) # Epipolar residuals p0 = np.zeros(3) R0 = np.eye(3) for i in range(1, num_frames): sym_s = zero_offset_bezier(sym_rot_controls, frame_times[i]) sym_p = zero_offset_bezier(sym_pos_controls, frame_times[i]) sym_q = cayley_mat(sym_s) #sym_q = np.eye(3) * (1. - np.dot(sym_s, sym_s)) + 2.*skew(sym_s) + 2.*np.outer(sym_s, sym_s) sym_E = essential_matrix(R0, p0, sym_q, sym_p) for j in range(num_landmarks): z = true_projections[i][j] z0 = true_projections[0][j] residual = np.dot(z, np.dot(sym_E, z0)) residuals.append(residual) print 'Num vars:',num_vars print 'Num residuals:',len(residuals) print 'Residuals:', len(residuals) cost = Polynomial(num_vars) for r in residuals: cost += r*r print ' %f (degree=%d, length=%d)' % (r(*true_vars), r.total_degree, len(r)) print '\nCost:' print ' Num terms: %d' % len(cost) print ' Degree: %d' % cost.total_degree print '\nGradients:' gradients = cost.partial_derivatives() for gradient in gradients: print ' %d (degree=%d, length=%d)' % (gradient(*true_vars), gradient.total_degree, len(gradient)) jacobians = [r.partial_derivatives() for r in residuals] J = np.array([[J_ij(*true_vars) for J_ij in row] for row in jacobians]) U, S, V = np.linalg.svd(J) print '\nJacobian singular values:' print J.shape print S null_space_dims = sum(np.abs(S) < 1e-5) if null_space_dims > 0: print '\nNull space:' for i in null_space_dims: print V[-i] print V[-2] print '\nHessian eigenvalues:' H = np.dot(J.T, J) print H.shape print np.linalg.eigvals(H) # Output to file write_polynomials(cost, out+'/cost.txt') write_polynomials(residuals, out+'/residuals.txt') write_polynomials(gradients, out+'/gradients.txt') write_polynomials(jacobians, out+'/jacobians.txt') write_solution(true_vars, out+'/solution.txt')
def test_polynomial_sub(): f = Polynomial([1, 2, 3]) g = Polynomial([4, 5, 6]) assert_that((f - g).coefficients).is_equal_to([-3, -3, -3])
def test_init_by_tuple(self): self.assertEqual([1, 2, -4], Polynomial((1, 2, -4)).coeffs)
def test_when_polynomial_is_linear_function(self): polynomial = Polynomial('-5x-9') expected_derivative = '-5' self.assertEqual(polynomial.find_derivative(), expected_derivative)
def test_polynomial_add_zero(): f = Polynomial([1, 2, 3]) g = Polynomial([0]) assert_that((f + g).coefficients).is_equal_to([1, 2, 3])
def test_mul_with_polynomial2(self): self.assertEqual(Polynomial([1, 4, 0, -8]), Polynomial([1, 2, -4]) * Polynomial([1, 2]))
def run_sfm(): # Construct symbolic problem num_landmarks = 4 num_frames = 2 print 'Num observations: ', num_landmarks * num_frames * 2 print 'Num vars: ', num_frames*6 + num_landmarks*3 + num_frames*num_landmarks true_landmarks = np.random.randn(num_landmarks, 3) true_positions = np.random.rand(num_frames, 3) true_cayleys = np.random.rand(num_frames, 3) true_qs = map(cayley_mat, true_cayleys) true_betas = map(cayley_denom, true_cayleys) true_rotations = [(q/b) for (q,b) in zip(true_qs, true_betas)] true_uprojections = [[np.dot(R, x-p) for x in true_landmarks] for R,p in zip(true_rotations, true_positions)] true_projections = [[normalized(zu) for zu in row] for row in true_uprojections] true_alphas = [[np.linalg.norm(zu) for zu in row] for row in true_uprojections] true_vars = np.hstack((true_cayleys.flatten(), true_positions.flatten(), true_landmarks.flatten(), np.asarray(true_alphas).flatten())) #true_projection_mat = np.reshape(true_projections, (num_frames, num_landmarks, 2)) for i in range(num_frames): p = true_positions[i] q = true_qs[i] beta = true_betas[i] for j in range(num_landmarks): x = true_landmarks[j] z = true_projections[i][j] alpha = true_alphas[i][j] print alpha * beta * z - np.dot(q, x-p) # construct symbolic versions of the above s_offs = 0 p_offs = s_offs + num_frames*3 x_offs = p_offs + num_frames*3 a_offs = x_offs + num_landmarks*3 num_vars = a_offs + num_landmarks*num_frames sym_vars = [Polynomial.coordinate(i, num_vars, Fraction) for i in range(num_vars)] sym_cayleys = np.reshape(sym_vars[s_offs:s_offs+num_frames*3], (num_frames, 3)) sym_positions = np.reshape(sym_vars[p_offs:p_offs+num_frames*3], (num_frames, 3)) sym_landmarks = np.reshape(sym_vars[x_offs:x_offs+num_landmarks*3], (num_landmarks, 3)) sym_alphas = np.reshape(sym_vars[a_offs:], (num_frames, num_landmarks)) residuals = [] for i in range(num_frames): sym_p = sym_positions[i] sym_s = sym_cayleys[i] for j in range(num_landmarks): sym_x = sym_landmarks[j] sym_a = sym_alphas[i,j] true_z = true_projections[i][j] residual = np.dot(cayley_mat(sym_s), sym_x-sym_p) - sym_a * cayley_denom(sym_s) * true_z residuals.extend(residual) print 'Residuals:' cost = Polynomial(num_vars) for residual in residuals: cost += np.dot(residual, residual) print ' ',residual(*true_vars) #ri.num_vars, len(true_vars) print '\nGradients:' gradient = [cost.partial_derivative(i) for i in range(num_vars)] for gi in gradient: print gi(*true_vars) j = np.array([[r.partial_derivative(i)(*true_vars) for i in range(num_vars)] for r in residuals]) print '\nJacobian singular values:' print j.shape u, s, v = np.linalg.svd(j) print s print '\nHessian eigenvalues:' h = np.dot(j.T, j) print h.shape print np.linalg.eigvals(h)
def test_mul_with_zero(self): self.assertEqual(Polynomial([0]), Polynomial([1, 2, -4]) * 0)
def run_position_only_spline_epipolar(): # # Construct ground truth # num_landmarks = 50 num_frames = 4 num_imu_readings = 80 bezier_degree = 4 out = 'out/position_only_bezier3' print 'Num landmarks:', num_landmarks print 'Num frames:', num_frames print 'Num IMU readings:', num_imu_readings print 'Bezier curve degree:', bezier_degree if not os.path.isdir(out): os.mkdir(out) # Both splines should start at 0,0,0 frame_times = np.linspace(0, .9, num_frames) imu_times = np.linspace(0, 1, num_imu_readings) true_rot_controls = np.random.rand(bezier_degree-1, 3) true_pos_controls = np.random.rand(bezier_degree-1, 3) true_landmarks = np.random.randn(num_landmarks, 3) true_positions = np.array([zero_offset_bezier(true_pos_controls, t) for t in frame_times]) true_cayleys = np.array([zero_offset_bezier(true_rot_controls, t) for t in frame_times]) true_rotations = map(cayley, true_cayleys) true_imu_cayleys = np.array([zero_offset_bezier(true_rot_controls, t) for t in imu_times]) true_imu_rotations = map(cayley, true_imu_cayleys) true_gravity = normalized(np.random.rand(3)) * 9.8 true_accel_bias = np.random.rand(3) true_global_accels = np.array([zero_offset_bezier_second_deriv(true_pos_controls, t) for t in imu_times]) true_accels = [np.dot(R, a + true_gravity) + true_accel_bias for R, a in zip(true_imu_rotations, true_global_accels)] true_uprojections = [[np.dot(R, x-p) for x in true_landmarks] for R, p in zip(true_rotations, true_positions)] true_projections = [[normalized(zu) for zu in row] for row in true_uprojections] # # Construct symbolic versions of the above # position_offs = 0 accel_bias_offset = position_offs + (bezier_degree-1)*3 gravity_offset = accel_bias_offset + 3 num_vars = gravity_offset + 3 sym_vars = [Polynomial.coordinate(i, num_vars, Fraction) for i in range(num_vars)] sym_pos_controls = np.reshape(sym_vars[position_offs:position_offs+(bezier_degree-1)*3], (bezier_degree-1, 3)) sym_accel_bias = np.asarray(sym_vars[accel_bias_offset:accel_bias_offset+3]) sym_gravity = np.asarray(sym_vars[gravity_offset:gravity_offset+3]) true_vars = np.hstack((true_pos_controls.flatten(), true_accel_bias, true_gravity)) assert len(true_vars) == len(sym_vars) residuals = [] # # Accel residuals # print '\nAccel residuals:' for i in range(num_imu_readings): true_R = true_imu_rotations[i] sym_global_accel = zero_offset_bezier_second_deriv(sym_pos_controls, imu_times[i]) sym_accel = np.dot(true_R, sym_global_accel + sym_gravity) + sym_accel_bias residual = sym_accel - true_accels[i] for i in range(3): print ' Degree of global accel = %d, local accel = %d, residual = %d' % \ (sym_global_accel[i].total_degree, sym_accel[i].total_degree, residual[i].total_degree) residuals.extend(residual) # # Epipolar residuals # p0 = np.zeros(3) R0 = np.eye(3) for i in range(1, num_frames): true_s = true_cayleys[i] true_R = cayley_mat(true_s) sym_p = zero_offset_bezier(sym_pos_controls, frame_times[i]) sym_E = essential_matrix(R0, p0, true_R, sym_p) for j in range(num_landmarks): z = true_projections[i][j] z0 = true_projections[0][j] residual = np.dot(z, np.dot(sym_E, z0)) residuals.append(residual) print '\nNum vars:', num_vars print 'Num residuals:', len(residuals) print '\nResiduals:', len(residuals) cost = Polynomial(num_vars) for r in residuals: cost += r*r print ' %f (degree=%d, length=%d)' % (r(*true_vars), r.total_degree, len(r)) print '\nCost:' print ' Num terms: %d' % len(cost) print ' Degree: %d' % cost.total_degree for term in cost: print ' ',term print '\nGradients:' gradients = cost.partial_derivatives() for gradient in gradients: print ' %d (degree=%d, length=%d)' % (gradient(*true_vars), gradient.total_degree, len(gradient)) jacobians = np.array([r.partial_derivatives() for r in residuals]) J = evaluate_array(jacobians, *true_vars) U, S, V = np.linalg.svd(J) print '\nJacobian singular values:' print J.shape print S print '\nHessian eigenvalues:' H = np.dot(J.T, J) print H.shape print np.linalg.eigvals(H) null_space_dims = sum(np.abs(S) < 1e-5) print '\nNull space dimensions:', null_space_dims if null_space_dims > 0: for i in range(null_space_dims): print ' ',V[-i] null_monomial = (0,) * num_vars coordinate_monomials = [list(var.monomials)[0] for var in sym_vars] A, _ = matrix_form(gradients, coordinate_monomials) b, _ = matrix_form(gradients, [null_monomial]) b = np.squeeze(b) AA, bb, kk = quadratic_form(cost) estimated_vars = np.squeeze(numpy.linalg.solve(AA*2, -b)) print '\nEstimated:' print estimated_vars print '\nGround truth:' print true_vars print '\nError:' print np.linalg.norm(estimated_vars - true_vars) # Output to file write_polynomials(cost, out+'/cost.txt') write_polynomials(residuals, out+'/residuals.txt') write_polynomials(gradients, out+'/gradients.txt') write_polynomials(jacobians.flat, out+'/jacobians.txt') write_solution(true_vars, out+'/solution.txt')
def test_mul_fail_incorrect_type(self): with self.assertRaises(TypeError): Polynomial([1, 2, -4]) * 'test'
def test_expression(self): self.assertEqual( Polynomial([-1, 7, 4, -14]), -(Polynomial([1, -4]) * Polynomial([1, -2, -4])) + Polynomial([1, 8, 2]))
def test_eq_polynomials(self): self.assertTrue(Polynomial([1, 4, 0, -8]) == Polynomial([1, 4, 0, -8]))
def __call__(self, x): """Return an element with the value x""" if isinstance(x, (list, tuple)): x = Polynomial(self._gf, x) return FF.__call__(self, x)
def test_scale(self): p = Polynomial('3 1 2 1 1 1') self.assertEqual(p.scale(0.0), Polynomial('0 0')) p = Polynomial('3 1 2 1 1 1') self.assertEqual(p.scale(2.5), Polynomial('3 2.5 2 2.5 1 2.5'))