def det(self): # Check if the matrix is square if self.dim()[0] != self.dim()[1]: raise AttributeError( "Cannot take the determinant of a non-square matrix") # Take the determinant, recursively if self.dim() == (1, 1): return self.contents[0][0] elif self.dim() == (2, 2): total = Poly() total += self.contents[0][0] * self.contents[1][1] - self.contents[ 1][0] * self.contents[0][1] return total else: minors = [] for r in range(len(self.contents)): tmp_contents = [] for r2 in range(len(self.contents)): if r2 != r: tmp_contents.append(self.contents[r2][1:]) minors.append(Matrix(tmp_contents)) total = Poly() for r in range(len(self.contents)): total += minors[r].det() * self.contents[r][0] * (-1)**r return total
def eigenvectors(self, equal_matrix=None): # Make the polynomial matrix # [x - a b ] # [ c x - d] # from this matrix: # [ a b ] # [ c d ] x = Matrix.identity(self.dim()[0]) * Poly({1: 1}) mat = self - x # Find the eigenvalues of the matrix values = mat.det().roots() evaluated = [] for value in values: tmp_contents = [] for row in range(len(self.contents)): tmp_row = [] for col in range(len(self.contents[0])): tmp_row.append(mat.contents[row][col].evaluate(value)) tmp_contents.append(tmp_row) evaluated.append(Matrix(tmp_contents)) vector_mats = [] for m in evaluated: if not equal_matrix: o = Poly(0) m.augment(Matrix([[o], [o]])) else: m.augment(equal_matrix) m.rref() vector_mats.append(m) # TODO improve upon this after equations return vector_mats
def decode_poly(self, poly): syndrom_table = self.create_syndrom_table(poly) b = 0 b_1 = 1 sigma_coeff = [0 for i in range(0, self.t + 1)] sigma_coeff[0] = 1 sigma = Poly(self.t + 1, 0, sigma_coeff) sigma_1_coeff = [0 for i in range(0, self.t + 1)] sigma_1_coeff[0] = 1 sigma_1 = Poly(self.t + 1, 0, sigma_1_coeff) t = 0 t_1 = -1 tmp_coeff = [0 for i in range(0, self.d)] for j in range(0, self.d - 1): b = syndrom_table[j] for i in range(1, t + 1): x = self.F.Multiply(sigma.coeff_list[i], syndrom_table[j - i]) b = self.F.Add(b, x) if (b != 0): tmp = Poly(sigma.size, sigma.deg, sigma.coeff_list) tmp2 = sigma_1.shift_right_poly(j - t_1) c = self.F.Multiply(b, self.F.Inverse(b_1)) for k in range(0, len(tmp2.coeff_list)): tmp2.coeff_list[k] = self.F.Multiply(tmp2.coeff_list[k], c) for k in range(0, len(sigma.coeff_list)): sigma.coeff_list[k] = self.F.Add(sigma.coeff_list[k], tmp2.coeff_list[k]) if (j <= 2 * t): t = j + 1 - t t_1 = j b_1 = b sigma_1 = Poly(tmp.size, tmp.deg, tmp.coeff_list) return sigma
def create_verify_poly(self): ext_gen_poly = Poly(self.gen_poly.size + 1, self.gen_poly.deg, self.gen_poly.coeff_list) gen_field_coef = [0 for i in range(0, self.size + 1)] gen_field_coef[0] = 1 gen_field_coef[self.size] = 1 gen_field_poly = Poly(self.size + 1, self.size, gen_field_coef) [divider_poly, new_poly] = gen_field_poly.divide_polynomials(ext_gen_poly) return divider_poly
def poly_convert(self): tmp_contents = [] for row in range(len(self.contents)): tmp_row = [] for col in range(len(self.contents[0])): if type(self.contents[row][col]) != type(Poly()): tmp_row.append(Poly(self.contents[row][col])) else: tmp_row.append(self.contents[row][col]) tmp_contents.append(tmp_row) return Matrix(tmp_contents)
def __init__(self, lst2D=[[Poly(0)]]): length = len(lst2D[0]) for lst in lst2D: if len(lst) != length: raise AttributeError("Cannot have ragged matrix") # Convert everything to a polynomial for r in range(len(lst2D)): for c in range(len(lst2D[0])): if type(lst2D[r][c]) != type(Poly()): lst2D[r][c] = Poly(lst2D[r][c]) self.contents = lst2D
def identity(n=3): contents = [] tmp_row = [] for r in range(n): tmp_row = [] for c in range(n): if r == c: tmp_row.append(Poly(1)) else: tmp_row.append(Poly(0)) contents.append(tmp_row) return Matrix(contents)
def vandermonde(eta, p): """ Internal function to variable_projection Calculates the Vandermonde matrix using polynomial basis functions :param eta: ndarray, the affine transformed projected values of inputs in active subspace :param p: int, the maximum degree of polynomials :return: * **V (numpy array)**: The resulting Vandermode matrix * **Polybasis (Poly object)**: An instance of Poly object containing the polynomial basis derived """ _, n = eta.shape listing = [] for i in range(0, n): listing.append(p) Object = Basis('Total order', listing) #Establish n Parameter objects params = [] P = Parameter(order=p, lower=-1, upper=1, param_type='Uniform') for i in range(0, n): params.append(P) #Use the params list to establish the Poly object Polybasis = Poly(params, Object) V = Polybasis.getPolynomial(eta) V = V.T return V, Polybasis
def __sub__(self, other: Poly) -> Poly: """Return the difference of two polynomials.""" other_negative_coefs = list(map(lambda x: -x, other.coefs)) zipped_list = list( zip_longest(self.coefs, other_negative_coefs, fillvalue=0.0)) new_coefs: Coefficients = list(map(sum, zipped_list)) return Poly(new_coefs)
def convert_str_to_poly(self, coeff_str): coeff_list = list() last_one = 0 for i in range(0, len(coeff_str)): coeff_list.append(int(coeff_str[i])) if (coeff_str[i] == '1'): last_one = i return Poly(self.size, last_one, coeff_list)
def mult_poly(self, poly1, poly2): deg = poly1.deg + poly2.deg poly_coeff = [0 for i in range(0, self.size)] for i in range(0, deg + 1): curr_sum = 0 for j in range(0, i + 1): curr_elem = self.F.Multiply(poly1.coeff_list[j], poly2.coeff_list[i - j]) curr_sum = self.F.Add(curr_sum, curr_elem) poly_coeff[i] = curr_sum return Poly(self.size, deg, poly_coeff)
def solve_equation(self, sigma_coeff): locator_poly_coeff = [0 for j in range(0, len(sigma_coeff))] for i in range(0, len(sigma_coeff)): locator_poly_coeff[len(sigma_coeff) - 1 - i] = int(sigma_coeff[i]) locator_poly = Poly(self.t + 1, self.t, locator_poly_coeff) roots = list() for i in range(0, self.size): value = self.give_poly_value_for_power(locator_poly, i) if (value == 0): roots.append(i) return roots
def create_minimum_function(self, class_id): polynomials = list() for power in self.cyclomatic_classes[class_id]: curr_poly_coeff = [self.dig_table[power], 1] #print("curr_poly_coeff = ", curr_poly_coeff) curr_poly = Poly(self.size, 1, curr_poly_coeff) polynomials.append(curr_poly) poly = polynomials[0] for i in range(1, len(polynomials)): poly = self.mult_poly(poly, polynomials[i]) return poly
def print_basic() -> None: """ Function doing all that was needed for the checkpoint: print given polynomials, find an order of a polynomial, sum of two polynomials, the derivative and the antiderivative of the derivative. """ poly_a = Poly([2, 0, 4, -1, 0, 6]) poly_b = Poly([-1, -3, 0, 4.5]) print('BASIC'.center(20, '-')) print(f"""Polynomials are: P_a(x) = {poly_a}, P_b(x) = {poly_b}. The order of P_a(x) is {poly_a.order()}. The sum of two polynomials is {poly_a + poly_b}. The first derivative of P_a(x) is {poly_a.derivative()}. The antiderivative of d(P_a(x))/dx is {poly_a.derivative().antiderivative(2)}. """)
def eigenvalues(self): # Make the polynomial matrix # [x - a b ] # [ c x - d] # from this matrix: # [ a b ] # [ c d ] x = Matrix.identity(self.dim()[0]) * Poly({1: 1}) mat = self - x d = mat.det() return d.roots()
def encode_file(self, in_file): input_desc = open(in_file, "r") binary_str = str() for line in input_desc: for sym in line: sym_str = "{0:{fill}8b}".format(ord(sym), fill='0') binary_str += sym_str #print("binary_str = ", binary_str) count = len(binary_str) // self.k encode_str = str() for i in range(0, count): last_one = 0 coeff_list = list() for j in range(0, self.k): if (binary_str[i * self.k + j] == '1'): coeff_list.append(1) last_one = j else: coeff_list.append(0) curr_poly = Poly(self.size, last_one, coeff_list) encode_poly = self.gen_poly.mult_poly(curr_poly) #encode_poly.print_poly() encode_poly_str = encode_poly.convert_poly_to_str() encode_str += encode_poly_str coeff_list = [0 for i in range(0, self.k)] last_one = 0 for j in range(0, len(binary_str) - count * self.k): if (binary_str[count * self.k + j] == '1'): coeff_list[j] = 1 last_one = j curr_poly = Poly(self.size, last_one, coeff_list) encode_poly = self.gen_poly.mult_poly(curr_poly) #encode_poly.print_poly() encode_poly_str = encode_poly.convert_poly_to_str() encode_str += encode_poly_str return encode_str
def __init__(self, code_file): self.code_info_desc = open(code_file, "r") lines = self.code_info_desc.readlines() self.size = int(lines[0].split('=')[1]) self.m = int(lines[1].split('=')[1]) self.k = int(lines[2].split('=')[1]) self.r = int(lines[3].split('=')[1]) self.d = int(lines[4].split('=')[1]) self.t = int(lines[5].split('=')[1]) self.p = float(lines[6].split('=')[1]) deg = int(lines[7].split('=')[1]) coeff_list_lines = lines[8].split(' ') coeff_list = [int(elem) for elem in coeff_list_lines] self.gen_poly = Poly(self.size, deg, coeff_list) return
def convert_to_unicode(self, correct_line): unicode_str = str() count = len(correct_line) // self.size for i in range(0, count): last_one = 0 coeff_list = list() for j in range(0, self.size): if (correct_line[i * self.size + j] == '1'): coeff_list.append(1) last_one = j else: coeff_list.append(0) curr_poly = Poly(self.size, last_one, coeff_list) [divider_poly, rem_poly] = curr_poly.divide_polynomials(self.gen_poly) for r in range(0, self.k): unicode_str += str(divider_poly.coeff_list[r]) return unicode_str
def get_shape_by_name(shape_name, priors): import re if shape_name == 'sigmoid': from sigmoid import Sigmoid return Sigmoid(priors) if shape_name == 'sigslope': from sigslope import Sigslope return Sigslope(priors) elif shape_name.startswith('poly'): m = re.match('poly(\d)', shape_name) assert m, 'Illegal polynomial shape name' degree = int(m.group(1)) from poly import Poly return Poly(degree, priors) elif shape_name == 'spline': from spline import Spline return Spline() else: raise AssertionError('Unknown shape: {}'.format(shape_name))
def __init__(self, n, poly_type="list"): Monom.size = n if poly_type == "list": Poly.ring = self self.one = Poly.one self.zero = Poly.zero self.gens = [Poly([Monom(vars=[i])]) for i in range(n)] elif poly_type == "zdd": ZDD.ring = self one = ZDD() one.setOne() zero = ZDD() zero.setZero() self.one = one self.zero = zero self.gens = [ZDD(i) for i in range(n)]
#!/usr/bin/env python3 from poly import Poly def check_poly_consistancy(f): assert (isinstance(f._coefs, tuple)) assert (isinstance(f._var, str)) if f._coefs: assert f._coefs[-1] f1 = Poly(1, 1, 1, 0, 0, -1, -1, -2, -1, -1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, -1, -1, -2, -1, -1, 0, 0, 1, 1, 1) f2 = Poly(1, -1, 0, 0, 0, 1, -1, 1, -1, 0, 1, -1, 1, -1, 1, 0, -1, 1, -1, 1, 0, 0, 0, -1, 1) f3 = Poly(1, -1, 0, 1, -1, 0, 1, 0, -1, 1, 0, -1, 1) f4 = Poly(1, -1, 0, 1, -1, 1, 0, -1, 1) f5 = Poly(1, 1, 1, 1, 1, 1, 1) f6 = Poly(1, 1, 1, 1, 1) f7 = Poly(1, 1, 1) f8 = Poly(-1, 1) assert (f1 * f2 * f3 * f4 * f5 * f6 * f7 * f8 == (Poly.monomial(1, 105) - 1)) check_poly_consistancy(f1 * f2 * f3 * f4 * f5 * f6 * f7 * f8)
title_fail = f"\033[1;41m{title_fail}" + " "*spaces + "\033[m" print(title_pass + "\033[m") print(title_fail) for f in failed: print(f) else: msg2 = "100% SUCCESS" l = len(msg2) print(title_pass[:-spaces+5] + msg2 + " "*(spaces-5-l) + "\033[m") """TEST EXECUTION""" test_msg("Init Poly") try: M1 = Poly(X1, Y1) M2 = Poly(X2, Y2) except Exception as e: fail_msg(e) else: pass_msg() tests = ["M1.p == 1", "M2.p == 2", "M1.q == 1", "M2.q == 1", "M1.N == N1", "M2.N == N2**2"] for t in tests: test_msg(t) try: assert eval(t) except Exception as e: fail_msg(e)
# if verbose, dump to the terminal as well as the logfile. if dd.get('verbose') == 1: root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) outfile = dd.get('outfile') mod = 'action="modifiy"' poly = Poly() bbox = poly.getBBox(dd.get('poly')) #logging.info("Bounding box is %r" % bbox) # XAPI uses: # minimum latitude, minimum longitude, maximum latitude, maximum longitude xbox = "%s,%s,%s,%s" % (bbox[2], bbox[0], bbox[3], bbox[1]) #logging.info("Bounding xbox is %r" % xbox) print("------------------------") #xapi = "(\n way(%s);\n node(%s);\n rel(%s);\n <;\n >;\n);\nout meta;" % (box , xbox, xbox) #print(xapi) # osmc.createChanges() # osmc.applyChanges() #xapi = '[adiff: "2018-03-29T00:26:13Z","2019-05-13T17:27:18-06:00"];' + xapi
ns[i] = Star.n return ns Ms, Rs, Ls, As, ys = 1.98919e33, 6.9699e10, 3.846e33, .02857, .27 fh1 = .22 fh2 = .3 a1 = 10**(fh1) * As a2 = 10**(fh2) * As M1, R1, L1 = 1.105 * Ms, 1.225 * Rs, 1.47 * Ls M2, R2, L2 = .934 * Ms, .864 * Rs, .47 * Ls dM1, dR1, dL1 = .007 * Ms, .004 * Rs, .05 * Ls dM2, dR2, dL2 = .006 * Ms, .005 * Rs, .02 * Ls Sun = Poly(Ms, Rs, Ls, As, ys) Alpha_a = Poly(M1, R1, L1, a1, ys) Alpha_b = Poly(M2, R2, L2, a2, ys) #for Star in [Sun, Alpha_a, Alpha_b]: # Star.get_n(a = 2.5, b = 4.4) # Star.plot_L_vs_M() #plt.gca().legend(("Sun", r"$\alpha$ Centauri A", r"$\alpha$ Centauri B")) #plt.savefig("../figures/luminosities.pdf", dpi = 1000, transparent=True, bbox_inches="tight") #plt.show() N = 10000 ns = np.zeros(N) #dx = np.array([dM, dR, dL]) dx1 = np.array([dM1, dR1, dL1]) dx2 = np.array([dM2, dR2, dL2])
# if verbose, dump to the terminal as well as the logfile. if dd.get('verbose') == 1: root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) tm = TM() tm.dump() poly = Poly(dd.get('poly')) poly.dump() project = Project() query = project.create(id=tm.getNextProjectID(), comment="#tm-senecass", polygon=poly) #project.dump() print(query) tm.query(query) info = Info() query = info.create("Testy", tm.getNextProjectID()) #info.dump() print(query) tm.query(query) task = Task()
def poca(self): assert self.dim[0] == self.dim[1] X = Poly([0, 1]) #X*Id - M ksi = X*Mat(self.dim[0]) - self return ksi.det()
poly.installPackage() complex.installPackage() r1 = Rational(1, 5) r2 = Rational(2, 5) o1 = Ordinary(3) o2 = Ordinary(8) r3 = rational.add(r1, r2) print r3 o3 = ordinary.add(o1, o2) print o3 print 'Neg :', neg(r1) print 'Rev :', rev(r1) print 'Ord :', add(3, 4) p1 = Poly('x', (1, 1), (3, 3), (2, 2)) print 'Poly :', p1 p2 = Poly('x', (1, 1), (3, 3), (2, 2)) print 'ADD :', add(p1, p2) print 'MUL :', mul(p1, p2) # Complex numbers c1 = Complex(1, 2, 'rect') print 'C1 :', c1 c2 = Complex(2, 3, 'rect') print 'C2 :', c2 print 'C1 + C2 :', add(c1, c2)
def get_poly_result(self): '''Получение результата выполнения полинома''' values = self._get_input_values() poly = Poly(values) return poly.get_result()
formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) poly = dd.get('poly') title = dd.get('title') outfile = dd.get('outfile') infile = dd.get('infile') dbname = dd.get('database') kmz = outfile.replace(".kml", ".kmz") post = Postgis() if dd.get('poly') is not None: polyfilter = Poly(poly) wkt = polyfilter.getWkt() # post.addPolygon(polyfilter) if dd.get('xapi') is True: if dd.get('poly') is not None: # polyfilter = Poly() bbox = polyfilter.getBBox(poly) osm = outfile.replace('.kml', '.osm') xapi = OverpassXAPI(bbox, osm) if xapi.getData() is True: post.importOSM(osm, dbname) else: quit() else: logging.error("Need to specify a poly to download!")
# """Close the database so changes don't get lost""" # logging.debug("Closing the database %r" % self.db) # self.db.commit() # self.db.close() # # Main body # polyfile = dd.get('poly') if polyfile is None: logging.error("Need to specify a poly file to do anything!") dd.usage() poly = Poly(polyfile) bbox = poly.getBBox() logging.info("Bounding box for %r is %r" % (poly.getName(), bbox)) if dd.get('format') == "OSMAND": sqlite = dd.get('sqlite') osmand = Osmand(sqlite) # osmand.createDB() osmand.addFromFile(input) # osmand.addLevel(bbox, 15) # osmand.addLevel(bbox, 16) # This writes all the tiles in the sqlite db to disk # path = dd.get('outfile')