def main(): """ Excerpt from the user manual of phcpy. """ from phcpy.phcpy2c3 import py2c_set_seed py2c_set_seed(2019) p = ['x^2 + y - 3;', 'x + 0.125*y^2 - 1.5;'] print('constructing a total degree start system ...') from phcpy.solver import total_degree_start_system as tds q, qsols = tds(p) print('number of start solutions :', len(qsols)) from phcpy.trackers import initialize_standard_tracker from phcpy.trackers import initialize_standard_solution from phcpy.trackers import next_standard_solution initialize_standard_tracker(p, q, False) # True) # initialize_standard_tracker(p, q, True) from phcpy.solutions import strsol2dict import matplotlib.pyplot as plt plt.ion() fig = plt.figure() for k in range(len(qsols)): if(k == 0): axs = fig.add_subplot(221) elif(k == 1): axs = fig.add_subplot(222) elif(k == 2): axs = fig.add_subplot(223) elif(k == 3): axs = fig.add_subplot(224) startsol = qsols[k] initialize_standard_solution(len(p),startsol) dictsol = strsol2dict(startsol) xpoints = [dictsol['x']] ypoints = [dictsol['y']] for k in range(300): ns = next_standard_solution() dictsol = strsol2dict(ns) xpoints.append(dictsol['x']) ypoints.append(dictsol['y']) tval = dictsol['t'].real # tval = eval(dictsol['t'].lstrip().split(' ')[0]) if(tval == 1.0): break print(ns) xre = [point.real for point in xpoints] yre = [point.real for point in ypoints] axs.set_xlim(min(xre)-0.3, max(xre)+0.3) axs.set_ylim(min(yre)-0.3, max(yre)+0.3) dots, = axs.plot(xre,yre,'r-') fig.canvas.draw() fig.canvas.draw() ans = input('hit return to exit')
def solve4circles(syst, verbose=True): """ Given in syst is a list of polynomial systems. Returns a list of tuples. Each tuple in the list of return consists of the coordinates of the center and the radius of a circle touching the three given circles. """ from phcpy.solver import solve from phcpy.solutions import strsol2dict, is_real (circle, eqscnt) = (0, 0) result = [] for eqs in syst: eqscnt = eqscnt + 1 if verbose: print('solving system', eqscnt, ':') for pol in eqs: print(pol) sols = solve(eqs, silent=True) if verbose: print('system', eqscnt, 'has', len(sols), 'solutions') for sol in sols: if is_real(sol, 1.0e-8): soldic = strsol2dict(sol) if soldic['r'].real > 0: circle = circle + 1 ctr = (soldic['x'].real, soldic['y'].real) rad = soldic['r'].real result.append((ctr, rad)) if verbose: print('solution circle', circle) print('center =', ctr) print('radius =', rad) return result
def straight_line(verbose=True): """ This function solves an instance where the five precision points lie on a line. The coordinates are taken from Problem 7 of the paper by A.P. Morgan and C.W. Wampler. Returns a list of solution dictionaries for the real solutions. """ from phcpy.solutions import strsol2dict, is_real pt0 = Matrix([[ 0.50], [ 1.06]]) pt1 = Matrix([[-0.83], [-0.27]]) pt2 = Matrix([[-0.34], [ 0.22]]) pt3 = Matrix([[-0.13], [ 0.43]]) pt4 = Matrix([[ 0.22], [ 0.78]]) piv = Matrix([[1], [0]]) equ = polynomials(pt0,pt1,pt2,pt3,pt4,piv) if verbose: print 'the polynomial system :' for pol in equ: print pol from phcpy.solver import solve sols = solve(equ) if verbose: print 'the solutions :' for sol in sols: print sol print 'computed', len(sols), 'solutions' result = [] for sol in sols: if is_real(sol, 1.0e-8): soldic = strsol2dict(sol) result.append(soldic) return result
def eqs(ip): #x1 -> omega_s #x2 -> ns #x3 -> np eq1 = "{0:+.16f}*x1{1:+.16f}*x2{2:+.16f}*x3{3:+.16f};" .format((-gi - gs)/(gi*xs**2), -alpha**2 + 1, -2*alpha + 2, (-ei*gs + es*gi + 2*gs*omega_p_chosen)/(gi*xs**2)) eq2 = "{0:.16f}*x1^2{1:+.16f}*x1*x2{2:+.16f}*x1*x3{3:+.16f}*x1{4:+.16f}*x2^2{5:+.16f}*x2*x3{6:+.16f}*x2{7:+.16f}*x3^2{8:+.16f}*x3{9:+.16f};" .format(xs**(-4), (-4*alpha - 2)/xs**2, -4/xs**2, -2*es/xs**4, 4*alpha**2 + 4*alpha + 1, 8*alpha + 4, (4*alpha*es + 2*es)/xs**2, -alpha + 4, 4*es/xs**2, (4*es**2 + gs**2)/(4*xs**4)) eq3 = "{0:.16f}*x1^2*x2^2{1:+.16f}*x1*x2^3{2:+.16f}*x1*x2^2*x3{3:+.16f}*x1*x2^2{4:+.16f}*x1*x2*x3^2{5:+.16f}*x1*x2*x3{6:+.16f}*x2^4{7:+.16f}*x2^3*x3{8:+.16f}*x2^3{9:+.16f}*x2^2*x3^2{10:+.16f}*x2^2*x3{11:+.16f}*x2^2{12:+.16f}*x2*x3^3{13:+.16f}*x2*x3^2{14:+.16f}*x2*x3{15:+.16f}*x3^4{16:+.16f}*x3^3{17:+.16f}*x3^2{18:+.16f}*x3;" .format(4.0/xs**4, 1.0*(-16.0*alpha - 8.0)/xs**2, 1.0*(8.0*alpha - 8.0)/xs**2, -8.0*es/xs**4, 4.0/xs**2, 1.0*(4.0*ep - 4.0*omega_p_chosen)/(xp**2*xs**2), 16.0*alpha**2 + 16.0*alpha + 4.0, -16.0*alpha**2 + 8.0*alpha + 8.0, 1.0*(16.0*alpha*es + 8.0*es)/xs**2, 4.0*alpha**2 - 16.0*alpha, 1.0*(-8.0*alpha*ep*xs**2 - 8.0*alpha*es*xp**2 + 8.0*alpha*omega_p_chosen*xs**2 - 4.0*ep*xs**2 + 8.0*es*xp**2 + 4.0*omega_p_chosen*xs**2)/(xp**2*xs**2), 1.0*(4.0*es**2 + 1.0*gs**2)/xs**4, 4.0*alpha - 4.0, 1.0*(4.0*alpha*ep*xs**2 - 4.0*alpha*omega_p_chosen*xs**2 - 4.0*ep*xs**2 - 4.0*es*xp**2 + 4.0*omega_p_chosen*xs**2)/(xp**2*xs**2), 1.0*(-4.0*ep*es + 4.0*es*omega_p_chosen + 1.0*gs)/(xp**2*xs**2), 1.00000000000000, 1.0*(2.0*ep - 2.0*omega_p_chosen)/xp**2, 1.0*(1.0*ep**2 - 2.0*ep*omega_p_chosen + 1.0*omega_p_chosen**2 + 0.25)/xp**4, -1.0*ip) f = [eq1, eq2, eq3] #seeding random number generator for reproducible results py2c_set_seed(130683) s = solve(f,silent=True) ns = len(s) #number of solutions R = [] for k in range(ns): d = strsol2dict(s[k]) x123 = np.array([d['x1'], d['x2'], d['x3']]) real = np.real(x123) imag = np.fabs(np.imag(x123)) sol = np.empty((real.size + imag.size,), dtype=real.dtype) sol[0::2] = real sol[1::2] = imag if np.allclose(imag, np.zeros(3)): if real[1] > 1e-7: R.append((sol[0], sol[2], sol[4], ip)) return R
def phcpy(line, cell=None): "Solve a system of polynomials formatted for phcpy." # TODO: progress bar from phcpy.solver import solve from phcpy.solutions import strsol2dict if cell is None: with open(line, 'r') as poly: sys = ' '.join([f.rstrip() for f in poly]) else: # jupyter uses unix newlines sys = ' '.join([f.rstrip() for f in cell.split('\n')]) # cell.replace('\n',' ').lstrip() # discard equation count (and undeterminate count) if present while sys.split(' ')[0].isdigit(): sys = sys.split(' ', 1)[1] # convert to list with delimiters intact sys = [f+';' for f in sys.split(';')[:-1]] # for l in sys: print(l) ret = solve(sys) return [strsol2dict(s) for s in ret]
def findEmbeddings_dist(syst, interval): global prevSystem global usePrev global prevSolutions # i = 0 y1_left, y1_right, y4_left, y4_right = interval # print fileNamePref while True: if prevSystem and usePrev: sols = track(syst, prevSystem, prevSolutions, tasks=tasks_num) else: sols = solve(syst, verbose=0, tasks=tasks_num) result_real = [] for sol in sols: soldic = strsol2dict(sol) if is_real(sol, tolerance) and soldic['y1'].real>=y1_left and soldic['y1'].real<=y1_right and soldic['y4'].real>=y4_left and soldic['y4'].real<=y4_right: result_real.append(soldic) num_real = len(result_real) if num_real%2==0 and len(sols)==numAll: prevSystem = syst prevSolutions = sols return num_real
def coordinates_and_slopes(sol): """ Given a solution, return the 3-tuple with the x and y coordinates of the tangent point and the slope of the tangent line. The real parts of the coordinates are selected. """ from phcpy.solutions import strsol2dict sdc = strsol2dict(sol) return (sdc['x'].real, sdc['y'].real, sdc['s'].real)
def run_tracker(start, sols, target, sol_num, gamma, min_step, max_step, num_steps): set_homotopy_continuation_gamma(gamma.real, gamma.imag) set_homotopy_continuation_parameter(5, min_step) set_homotopy_continuation_parameter(4, max_step) set_homotopy_continuation_parameter(12, num_steps) dim = number_of_symbols(start) result = [[], [], [], [], [], [], []] for i in range(dim): result[2].append([]) standard_set_homotopy(target, start, False) idx = 0 choice_sol = sol_num solution = sols[choice_sol - 1] idx = idx + 1 standard_set_solution(dim, solution, False) solution = standard_get_solution(False) solution_dict = strsol2dict(solution) var_names = variables(solution_dict) var_names.sort() result[0].append(standard_t_value()) result[1].append(standard_step_size()) for i in range(len(var_names)): result[2][i].append(solution_dict[var_names[i]]) result[3].append(standard_closest_pole()) result[4].append(standard_pole_radius()) result[5].append(standard_series_coefficients(dim)) result[6].append(standard_pade_vector(dim)) for i in range(num_steps): standard_predict_correct(False) solution = standard_get_solution(False) solution_dict = strsol2dict(solution) result[0].append(standard_t_value()) result[1].append(standard_step_size()) for j in range(len(var_names)): result[2][j].append(solution_dict[var_names[j]]) result[3].append(standard_closest_pole()) result[4].append(standard_pole_radius()) result[5].append(standard_series_coefficients(dim)) result[6].append(standard_pade_vector(dim)) for i in range(len(result[2])): for j in range(len(result[2][i])): result[2][i][j] = (result[2][i][j].real, result[2][i][j].imag) return result
def verify(pols, sols): """ Verifies whether the solutions in sols satisfy the polynomials of the system in pols. """ from phcpy.solutions import strsol2dict, evaluate dictsols = [strsol2dict(sol) for sol in sols] checksum = 0 for sol in dictsols: sumeval = sum(evaluate(pols, sol)) print(sumeval) checksum = checksum + sumeval print('the total check sum :', checksum)
def find_more_points(self, num_points, return_complex=False): """ We find additional points on the variety. """ points = [] failure = 0 while (len(points) < num_points): phcsystem = self._system() phcsolutions = track(phcsystem, self._startsystem, self._startsol) # Parsing the output of solutions for sol in phcsolutions: solutiondict = strsol2dict(sol) point = [solutiondict[variable] for variable in self.varlist] if return_complex: points.append(tuple(point)) else: closeness = True for component in point: # choses the points we want if self._is_close(component.imag) \ and self._in_bounds(component.real): # sometimes phcpy gives more points than we # ask, thus the additional check if component == point[-1] \ and closeness \ and len(points) < num_points: points.append( tuple([ component.real for component in point ])) assert len(points) <= num_points failure = 0 else: closeness = False failure = failure + 1 if self._failure <= failure: raise RuntimeError( "equation has too many complex solutions in a row") self.points = points + self.points
def extend_solutions(sols, dim, pivots): """ Adds one extra zero coordinate to all solutions in sols, corresponding to the rightmost nonfull pivot. """ from phcpy.solutions import strsol2dict, variables, make_solution piv = rightmost_nonfull_pivot(dim, pivots) print '-> in extend_solutions, piv =', piv if (piv < 0): result = sols else: rown = pivots[piv] + 1 # row number of new variable name = 'x_' + str(rown + 1) + '_' + str(piv + 1) print '-> the name of the new variable :', name result = [] for sol in sols: dicsol = strsol2dict(sol) solvar = variables(dicsol) solval = [dicsol[var] for var in solvar] solvar.append(name) solval.append(complex(0.0)) result.append(make_solution(solvar, solval)) return result
def extend_solutions(sols, dim, pivots): """ Adds one extra zero coordinate to all solutions in sols, corresponding to the rightmost nonfull pivot. """ from phcpy.solutions import strsol2dict, variables, make_solution piv = rightmost_nonfull_pivot(dim, pivots) print '-> in extend_solutions, piv =', piv if(piv < 0): result = sols else: rown = pivots[piv] + 1 # row number of new variable name = 'x_' + str(rown+1) + '_' + str(piv+1) print '-> the name of the new variable :', name result = [] for sol in sols: dicsol = strsol2dict(sol) solvar = variables(dicsol) solval = [dicsol[var] for var in solvar] solvar.append(name) solval.append(complex(0.0)) result.append(make_solution(solvar, solval)) return result
def findEmbeddings(syst): global prevSystem global usePrev global prevSolutions i = 0 while True: if prevSystem and usePrev: sols = track(syst, prevSystem, prevSolutions, tasks=tasks_num) else: sols = solve(syst, verbose=0, tasks=tasks_num) result_real = [] for sol in sols: soldic = strsol2dict(sol) if is_real(sol, tolerance): result_real.append(soldic) num_real = len(result_real) if num_real%4==0 and len(sols)==numAll: prevSystem = syst prevSolutions = sols return num_real elif numAllowedMissing and len(sols)==numAll: print 'The number of real embeddings was not divisible by 4. ', return num_real elif numAllowedMissing and len(sols)>=numAll-numAllowedMissing: print 'Continuing although there were '+str(numAll-len(sols))+' solutions missing. ', return num_real else: usePrev = False i += 1 # print 'PHC failed, trying again: '+str(i) if i>=3: print 'PHC failed 3 times', return -1
""" Get the x and y coordinates of a solution path. First we take two quadrics and construct a start system based on the total degree applying the theorem of Bezout. To extract the coordinates of the points on a solution path, we convert the string representation into a dictionary. """ f = ['x*y + y^2 - 8;', 'x^2 - 3*y + 4;'] print 'the polynomials in the target system :' for pol in f: print pol from phcpy.solver import total_degree_start_system as tds (g, gsols) = tds(f) print 'the polynomials in the start system :' for pol in g: print pol print 'number of start solutions :', len(gsols) from phcpy.trackers import initialize_standard_tracker from phcpy.trackers import initialize_standard_solution from phcpy.trackers import next_standard_solution as nxtsol initialize_standard_tracker(f, g) initialize_standard_solution(len(g), gsols[0]) points = [nxtsol() for k in range(10)] from phcpy.solutions import strsol2dict dicpts = [strsol2dict(sol) for sol in points] coords = [(sol['x'].real, sol['y'].real) for sol in dicpts] print 'the real parts of the first ten points on the path :' for point in coords: print point
Get the x and y coordinates of a solution path. First we take two quadrics and construct a start system based on the total degree applying the theorem of Bezout. To extract the coordinates of the points on a solution path, we convert the string representation into a dictionary. """ f = ['x*y + y^2 - 8;', 'x^2 - 3*y + 4;'] print 'the polynomials in the target system :' for pol in f: print pol from phcpy.solver import total_degree_start_system as tds (g, gsols) = tds(f) print 'the polynomials in the start system :' for pol in g: print pol print 'number of start solutions :', len(gsols) from phcpy.trackers import initialize_standard_tracker from phcpy.trackers import initialize_standard_solution from phcpy.trackers import next_standard_solution as nxtsol initialize_standard_tracker(f, g) initialize_standard_solution(len(g), gsols[0]) points = [nxtsol() for k in range(10)] from phcpy.solutions import strsol2dict dicpts = [strsol2dict(sol) for sol in points] coords = [(sol['x'].real, sol['y'].real) for sol in dicpts] print 'the real parts of the first ten points on the path :' for point in coords: print point