def get_Ptolemy_relations(t, N, cohomology_class = None): if cohomology_class: cohomology_coefficients = ( cohomology_2_rel_boundary_class_to_coeffs(t, cohomology_class)) eqns = [] for tet in t.tet_list: i = tet.index if cohomology_class: signs = cohomology_coefficients[tet.index] sign_01 = Z2_to_sign(signs[2] + signs[3]) sign_12 = Z2_to_sign(signs[0] + signs[3]) else: sign_01 = +1 sign_12 = +1 sign_01 = Polynomial.constantPolynomial(sign_01) sign_12 = Polynomial.constantPolynomial(sign_12) for coord in simplex_coords_with_fixed_sum(4, N-2): eqns.append( - sign_01 * c_parameter(coord+(1,0,0,1),i) * c_parameter(coord+(0,1,1,0),i) - sign_12 * c_parameter(coord+(1,1,0,0),i) * c_parameter(coord+(0,0,1,1),i) + c_parameter(coord+(1,0,1,0),i) * c_parameter(coord+(0,1,0,1),i)) return eqns
def polynomialNonZeroCondition(eqns, var, andNonOne = False): variables = get_all_variables(eqns) prod = Polynomial.fromVariableName(var) for i in variables: prod = prod * Polynomial.fromVariableName(i) if andNonOne: prod = prod * (Polynomial.constantPolynomial(1) - Polynomial.fromVariableName(i)) return prod - Polynomial.constantPolynomial(1)
def _convertToMonicNf(nf, timeout): pariStr = "PRIVATEconvertToMonicNf = nfinit(%s, 3)" % nf.printMagma() print pariStr print timeout r = pari.pari_eval(pariStr, timeout = timeout) nf = Polynomial.parseFromMagma( pari.pari_eval("PRIVATEconvertToMonicNf[1].pol", timeout = timeout)) newExpressionForX = Polynomial.parseFromMagma( pari.pari_eval("PRIVATEconvertToMonicNf[2].pol", timeout = timeout)) return nf, newExpressionForX
def _setValueInPolynomials(polys, variable, value, nf = None): res = [ poly.substitute( {variable:Polynomial.constantPolynomial(value)}) for poly in polys] if nf: res = [poly.convertCoefficients(lambda x: x % nf) for poly in res] return res
def computeNumeric( p, substituteDict = {'x' : Polynomial.constantPolynomial( nfSolution)}): c = p.substitute(substituteDict) assert c.isConstant() return c.getConstant()
def parse_primary_decomposition(s_with_backslash): """ >>> p = parse_primary_decomposition(_magma_sample) >>> len(p) 1 >>> p = p[0] >>> len(p) 3 >>> str(p[0]) '- 1 + c_01_0' >>> str(p[1]) '1 + c_02_0 + t' >>> str(p[2]) '1 + t + t^2' """ s = re.search( "PRIMARY=DECOMPOSITION=BEGINS=HERE\s*" "(" "\[\s*" "(([^\]]*\[[^\]]*\],?\s*)*)" "\]\s*" ")+" "PRIMARY=DECOMPOSITION=ENDS=HERE", s_with_backslash,re.DOTALL) if not s: raise Exception, "Invalid Primary Decomposition" s_with_backslash = s.group(2) s = processEndOfLineBackslashes(s_with_backslash) components = re.findall( "Ideal of Polynomial ring.*?" "Dimension (\d+).*?" "(Size of variety over algebraically closed field: (\d+).*?)?" "Groebner basis:\s*" "\[([^\]]*)\]", s) def parseNumberOfPoints(s): if s == '': return None else: return int(s) components= [ PrimeIdeal( [ Polynomial.parseFromMagma(p) for p in polys.split(',') ], dimension = int(dimension), numberOfPoints = parseNumberOfPoints(numberOfPoints)) for dimension, tmp, numberOfPoints, polys in components] return components
def get_additional_eqns_independent(t, N): # make sure cusps have indices # dictionary associating the decoration change vectors to Ptolemy coordinates d = {} for i, tet in zip(range(len(t.tet_list)), t.tet_list): for coord in simplex_coords_with_fixed_sum(4, N): if not N in coord: v = [0 for x in range((N-1) * t.num_or_cusps)] for j, k in zip(range(4), coord): for p in range(k): v[ tet.cusp_index[j] + p * t.num_or_cusps ] += 1 d[c_parameter_var(coord, i)] = v variables = find_independent_integer_vectors(d) return [ Polynomial.fromVariableName(var) - Polynomial.constantPolynomial(1) for var in variables]
def _solveExactlyOverNumberField(univariatePoly, nf, timeout): variable = univariatePoly.variables()[0] def convertXtoY(p): return p.substitute({'x' : Polynomial.fromVariableName('y')}) univariatePoly = univariatePoly.convertCoefficients(convertXtoY) univariatePoly = univariatePoly.substitute( { variable : Polynomial.constantPolynomial( Polynomial.fromVariableName('x'))}) if not nf: assert univariatePoly.isConstant() newSolution = Polynomial.fromVariableName('x') newNf = univariatePoly.getConstant() newExpressionForX = Polynomial.constantPolynomial(0) else: nf = convertXtoY(nf) pariStr = "PRIAVTEsEONF = rnfequation(nfinit(%s), %s, 1)" % ( nf, univariatePoly) print pariStr print timeout r = pari.pari_eval(pariStr, timeout = timeout) # print r newNf = Polynomial.parseFromMagma(pari.pari_eval( "PRIAVTEsEONF[1]", timeout = timeout)) newExpressionForX = Polynomial.parseFromMagma(pari.pari_eval( "PRIAVTEsEONF[2].pol", timeout = timeout)) factor = int(pari.pari_eval( "PRIAVTEsEONF[3]", timeout = timeout)) newSolution = ( Polynomial.fromVariableName('x') - Polynomial.constantPolynomial(factor) * newExpressionForX) return newSolution, newNf, newExpressionForX
def toPolynomial(self): def processOneSide(origLeftMonomial): newLeft = Monomial.constantMonomial(origLeftMonomial.getCoefficient()) newRight = Monomial.constantMonomial(1) for var, expo in origLeftMonomial.getVars(): switch_sides = 'Inv' in var var = var.replace('Inv','') if 'zpprime' in var: newLeftMultiply = ( Monomial.constantMonomial(-1) * Monomial.fromVariableName( var.replace('zpprime','OneMinusz'))) newRightMultiply = ( Monomial.fromVariableName( var.replace('zpprime','z'))) elif 'zprime' in var: newLeftMultiply = ( Monomial.constantMonomial(1)) newRightMultiply = ( Monomial.fromVariableName( var.replace('zprime','OneMinusz'))) else: newLeftMultiply = ( Monomial.fromVariableName(var)) newRightMultiply = ( Monomial.constantMonomial(1)) if switch_sides: newLeft = newLeft * newRightMultiply**expo newRight = newRight * newLeftMultiply**expo else: newLeft = newLeft * newLeftMultiply**expo newRight = newRight * newRightMultiply**expo return newLeft, newRight l1, r1 = processOneSide(self.left) l2, r2 = processOneSide(self.right) newLeft = Polynomial((l1*r2,)) newRight = Polynomial((l2*r1,)) substDict = dict( [ (var, Polynomial( ( Monomial.constantMonomial(1), Monomial.constantMonomial(-1)* Monomial.fromVariableName( var.replace('OneMinusz','z'))))) for var in newLeft.variables() + newRight.variables() if 'OneMinusz' in var]) return ( newLeft.substitute(substDict) - newRight.substitute(substDict))
def turn_pair_to_Polynomial(p): if p[0] == +1: return Polynomial.fromVariableName(p[1]) else: return -Polynomial.fromVariableName(p[1])
def c_parameter(coords, tet_index): """ Same as c_parameter_var but returns it as Polynomial type. """ return Polynomial.fromVariableName( c_parameter_var(coords, tet_index))
def convertXtoY(p): return p.substitute({'x' : Polynomial.fromVariableName('y')})
def conversionFunction(c): return Polynomial.constantPolynomial(c)
def solvePolynomialEquations(polys, polynomialSolver, free_dim = 0, with_poly_history = False, poly_history="", variable_dict = { }, non_linear_equation_encountered=False): # polys = [polynomial.convertCoefficients(number) for polynomial in polys] if globalsettings.getSetting("solvePolynomialEquationsLog"): poly_history += '\n\n\n\n'+'\n'.join(map(_printPoly,polys))+'\n\n============\n' if not polys: assert free_dim == 0 if with_poly_history: return [(variable_dict,poly_history)] else: return [variable_dict] solutions=[] for i in polys: assert isinstance(i,Polynomial) univariate_polys = [ poly for poly in polys if poly.isUnivariate() ] if globalsettings.getSetting("solvePolynomialEquationsLog"): poly_history=poly_history+'\n\n'+str(map(_printPoly,univariate_polys))+'\n' if univariate_polys: univariate_poly = univariate_polys[0] # print univariate_poly variable_name = univariate_poly.variables()[0] if globalsettings.getSetting("solvePolynomialEquationsLog"): poly_history = poly_history + '\n\nSolving for %s\n' % variable_name try: sol = polynomialSolver(univariate_poly) if globalsettings.getSetting("solvePolynomialEquationsLog"): poly_history = poly_history+'\n'+str(sol)+'\n' except Exception as e: raise SolverException("Error in find_complex_roots when solving: " + str(univariate_poly) + " " + repr(e), poly_history) assert len(sol)==univariate_poly.degree() #if not len(sol)==1: # if non_linear_equation_encountered: # raise SolverException( # "Encountered second non linear equation: " + # str(univariate_poly), # poly_history) # # non_linear_equation_encountered = True else: if free_dim == 0: raise SolverException("No univariate polynomial left", poly_history) else: univariate_poly = None variable_name = polys[-1].variables()[0] sol = [random_complex_modulos()] if globalsettings.getSetting("solvePolynomialEquationsLog"): poly_history += "In pick random solution for %s:\n %s\n\n" % (variable_name, sol) free_dim = free_dim - 1 for value in sol: new_variable_dict = dict(variable_dict) new_variable_dict[variable_name] = value new_polys = [ poly.substitute( { variable_name : Polynomial.constantPolynomial(value) }) for poly in polys if not poly is univariate_poly] new_solutions = solvePolynomialEquations( new_polys, polynomialSolver = polynomialSolver, free_dim = free_dim, with_poly_history = with_poly_history, poly_history = poly_history, variable_dict = new_variable_dict) solutions = solutions + new_solutions return solutions
def _inverseOfConstantPolynomial(p): assert p.isConstant() constant = p.getConstant() invConstant = Fraction(1,1) / constant return Polynomial.constantPolynomial(invConstant)
def process_file(trig_file): d,in_filename = tempfile.mkstemp() tmp_in_file = open(in_filename, 'wb') tmp_in_file.write("r f %s\n" % trig_file) tmp_in_file.write("set precision 15\n") tmp_in_file.write("set digits_printed 120 f\n") tmp_in_file.write("print solution_type\n") tmp_in_file.write("print volume\n") #tmp_in_file.write("print complex_volume\n") tmp_in_file.write("quit\n") tmp_in_file.close() l = subprocess.Popen("ulimit -t 1; snap <" + in_filename, shell=True, stdout = subprocess.PIPE) s = l.stdout.read() if not ("solution type: geometric" in s or "solution type: nongeometric" in s): return None try: os.unlink(in_filename) except: pass d,in_filename = tempfile.mkstemp() tmp_in_file = open(in_filename, 'wb') tmp_in_file.write("r f %s\n" % trig_file) tmp_in_file.write("set degree 7\n") tmp_in_file.write("set precision 15\n") tmp_in_file.write("set digits_printed 120 f\n") tmp_in_file.write("compute invariant_trace_field\n") tmp_in_file.write("quit\n") tmp_in_file.close() l = subprocess.Popen("ulimit -t 20; snap <" + in_filename, shell=True, stdout = subprocess.PIPE) s2 = l.stdout.read() try: os.unlink(in_filename) except: pass r = re.search("Complex volume: (.*)",s) rcvol = '"-"' icvol = '"-"' if r: cvol = number(r.group(1)) rcvol = str(cvol.real()) icvol = str(cvol.imag()) r = re.search("Volume is: (.*)", s) if r: rcvol = r.group(1) f = re.search("Invariant trace field: (.*) \[",s2) fp = '-' fdeg = '-' if f: fp = f.group(1) fdeg = str(Polynomial.parseFromMagma(fp).degree()) if re.search(r"\(-?\d+,-?\d+\)", trig_file): if "(0,0)" in trig_file: # manifold is cusped if there is an unfilled cusped oc = "cusped" else: oc = "closed" else: oc = "cusped" t = read_triangulation_from_file(trig_file) return ('"%s",%s,%d,%s,%s,"%s",%s' % (trig_file.split('/')[-1].replace('.trig',''), oc, t.num_tets, rcvol, icvol, fp, fdeg))