Esempio n. 1
0
def main():
    """
    Defines the equations for the sevenbar problem.
    """
    eqs = symbolic_equations()
    for equ in eqs:
        print equ
    T1, T2, T3, T4, T5, T6 = var('T1, T2, T3, T4, T5, T6')
    generic = generic_problem(eqs)
    for equ in generic:
        print equ
    from phcpy.solver import solve
    sols = solve(generic)
    print 'found', len(sols), 'solutions'
    raw_input('hit enter to continue')
    for sol in sols:
        print sol
    special = special_problem(eqs)
    for equ in special:
        print equ
    sols = solve(special)
    print 'found', len(sols), 'solutions'
    raw_input('hit enter to continue')
    for sol in sols:
        print sol
    raw_input('hit enter to continue')
    (embpols, sols0, sols1) = embed_and_cascade(special, 1)
    monodromy_factor(embpols, sols0)
Esempio n. 2
0
def main():
    """
    Defines the equations for the sevenbar problem.
    """
    eqs = symbolic_equations()
    for equ in eqs:
        print(equ)
    T1, T2, T3, T4, T5, T6 = var('T1, T2, T3, T4, T5, T6')
    generic = generic_problem(eqs)
    for equ in generic:
        print(equ)
    from phcpy.solver import solve
    sols = solve(generic)
    print('found', len(sols), 'solutions')
    input('hit enter to continue')
    for sol in sols:
        print(sol)
    special = special_problem(eqs)
    for equ in special:
        print(equ)
    sols = solve(special)
    print('found', len(sols), 'solutions')
    input('hit enter to continue')
    for sol in sols:
        print(sol)
    input('hit enter to continue')
    (embpols, sols0, sols1) = embed_and_cascade(special, 1)
    monodromy_factor(embpols, sols0)
Esempio n. 3
0
def test():
    """
    Solves the systems and tests on their number of solutions.
    """
    from phcpy.phcpy2c3 import py2c_set_seed
    py2c_set_seed(834798272)
    from phcpy import solver
    print('\nsolving a random binomial system...')
    pols = binomials()
    sols = solver.solve(pols)
    assert len(sols) == 20
    print('test on binomial system passed')
    print('\nsolving the cyclic 7-roots problem...')
    pols = cyclic7()
    sols = solver.solve(pols)
    assert len(sols) == 924
    print('test on cyclic 7-roots passed')
    print('\nsolving the benchmark problem D1...')
    pols = sysd1()
    sols = solver.solve(pols)
    assert len(sols) == 48
    print('test on benchmark problem D1 passed')
    print('\nsolving a generic 5-point 4-bar design problem...')
    pols = fbrfive4()
    sols = solver.solve(pols)
    assert len(sols) == 36
    print('test on 4-bar system passed')
    print('\ncomputing all Nash equilibria...')
    pols = game4two()
    sols = solver.solve(pols)
    assert len(sols) == 9
    print('test on Nash equilibria for 4 players passed')
    print('\nsolving a problem in magnetism...')
    pols = katsura6()
    sols = solver.solve(pols)
    assert len(sols) == 64
    print('test on a problem in magnetism passed')
    print('\nsolving a neural network model...')
    pols = noon3()
    sols = solver.solve(pols)
    assert len(sols) == 21
    print('test on a neural network model passed')
    print('\nsolving a mechanical design problem...')
    pols = rps10()
    sols = solver.solve(pols)
    assert len(sols) == 1024
    print('test on RPS serial chains problem passed')
    print('\nsolving a fully real Stewart-Gough platform...')
    pols = stewgou40()
    sols = solver.solve(pols)
    assert len(sols) == 40
    print('test on real Stewart-Gough platform passed')
    print('\ncomputing all tangent lines to 4 spheres...')
    pols = tangents()
    sols = solver.solve(pols)
    assert len(sols) == 6
    print('test on multiple tangent lines to spheres passed')
Esempio n. 4
0
def test():
    """
    Solves the systems and tests on their number of solutions.
    """
    from phcpy.phcpy2c3 import py2c_set_seed
    py2c_set_seed(834798272)
    from phcpy import solver
    print('\nsolving a random binomial system...')
    pols = binomials()
    sols = solver.solve(pols)
    assert len(sols) == 20
    print('test on binomial system passed')
    print('\nsolving the cyclic 7-roots problem...')
    pols = cyclic7()
    sols = solver.solve(pols)
    assert len(sols) == 924
    print('test on cyclic 7-roots passed')
    print('\nsolving the benchmark problem D1...')
    pols = sysd1()
    sols = solver.solve(pols)
    assert len(sols) == 48
    print('test on benchmark problem D1 passed')
    print('\nsolving a generic 5-point 4-bar design problem...')
    pols = fbrfive4()
    sols = solver.solve(pols)
    assert len(sols) == 36
    print('test on 4-bar system passed')
    print('\ncomputing all Nash equilibria...')
    pols = game4two()
    sols = solver.solve(pols)
    assert len(sols) == 9
    print('test on Nash equilibria for 4 players passed')
    print('\nsolving a problem in magnetism...')
    pols = katsura6()
    sols = solver.solve(pols)
    assert len(sols) == 64
    print('test on a problem in magnetism passed')
    print('\nsolving a neural network model...')
    pols = noon3()
    sols = solver.solve(pols)
    assert len(sols) == 21
    print('test on a neural network model passed')
    print('\nsolving a mechanical design problem...')
    pols = rps10()
    sols = solver.solve(pols)
    assert len(sols) == 1024
    print('test on RPS serial chains problem passed')
    print('\nsolving a fully real Stewart-Gough platform...')
    pols = stewgou40()
    sols = solver.solve(pols)
    assert len(sols) == 40
    print('test on real Stewart-Gough platform passed')
    print('\ncomputing all tangent lines to 4 spheres...')
    pols = tangents()
    sols = solver.solve(pols)
    assert len(sols) == 6
    print('test on multiple tangent lines to spheres passed')
Esempio n. 5
0
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]
Esempio n. 6
0
def main():


	v1,v2,v3,u1,u2,u3 = symbols(' v1 v2 v3 u1 u2 u3')

	a1 = 1
	a2 = 1
	a3 = 1
	b2 = 2
	b3 = 2
	c3 = 1
	r1 = 3
	r2 = 2
	r3 = 3

	p1 = str(v1**2 + v2**2 + v3**2 -1) + ';' 
	p2 = str(u1*v1 + u2*v2 + u3*v3) + ';'
	p3 = str(u1**2 + u2**2 + u3**2 - 1) + ';'
	p4 = str(-2*u1*a1 + v1**2*a1**2 + a1**2 - r1**2 + 1) + ';'
	p5 = str(-2*u1*a2 - 2*u2*b2 - v1**2*a2**2 - 2*v1*v2*a2*b2 - v2**2*b2**2 + a2**2 + b2**2 - r2**2 + 1) + ';'
	p6 = str(-2*u1*a3 - 2*u2*b3 - 2*u3*c3 - v1**2*a3**2 - 2*v1*v2*a3*b3 - 2*v1*v3*a3*c3 - v2**2*b3**2 - 2*v2*v3*b3*c3 - v3**2*c3**2 + a3**2 + b3**2 + c3**2 - r3**2 + 1) + ';'

	system = [p1,p2,p3,p4,p5,p6]

	s = solve(system, silent = True)

	print s[0]
	print s[1]
Esempio n. 7
0
def solve_general():
    """
    Defines the pivot and generates random coordinates,
    uniformly distributed in [-1, +1], for the five points
    through which the coupler must pass.
    Calls the blackbox solver to solve the system.
    In each run, the number of computed solutions should be 36.
    """
    from random import uniform as u
    pt0 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt1 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt2 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt3 = Matrix(2, 1, lambda i,j: u(-1,+1))
    pt4 = Matrix(2, 1, lambda i,j: u(-1,+1))
    # the pivot is a
    piv = Matrix([[1], [0]])
    equ = polynomials(pt0,pt1,pt2,pt3,pt4,piv)
    print 'the polynomial system :'
    for pol in equ:
        print pol
    from phcpy.solver import solve
    sols = solve(equ)
    print 'the solutions :'
    for sol in sols:
        print sol
    print 'computed', len(sols), 'solutions'
Esempio n. 8
0
def example4pade(prc='d'):
    """
    The function f(z) = ((1 + 1/2*z)/(1 + 2*z))^(1/2) is
    a solution x(s) of (1-s)*(x^2 - 1) + s*(3*x^2 - 3/2) = 0
    """
    pols = ['(x^2 - 1)*(1-s) + (3*x^2 - 3/2)*s;', 's;']
    from phcpy.solver import solve
    sols = solve(pols, silent=True, precision=prc)
    for sol in sols:
        print(sol)
    if prc == 'd':
        sers = standard_newton_series(pols[:1], sols, idx=2)
    else:
        sers = dobldobl_newton_series(pols[:1], sols, idx=2)
    print('the series solutions :')
    for ser in sers:
        print(ser)
    if prc == 'd':
        pade = standard_pade_approximants(pols[:1], sols, idx=2)
    elif prc == 'dd':
        pade = dobldobl_pade_approximants(pols[:1], sols, idx=2)
    elif prc == 'qd':
        pade = quaddobl_pade_approximants(pols[:1], sols, idx=2)
    else:
        print('wrong value for the precision')
    print('the Pade approximants :')
    for pad in pade:
        print(pad)
Esempio n. 9
0
def test_track(silent=True, precision='d', decimals=80):
    """
    Tests the path tracking on a small random system.
    Two random trinomials are generated and random constants
    are added to ensure there are no singular solutions
    so we can use this generated system as a start system.
    The target system has the same monomial structure as
    the start system, but with random real coefficients.
    Because all coefficients are random, the number of
    paths tracked equals the mixed volume of the system.
    """
    from phcpy.solver import random_trinomials, real_random_trinomials
    from phcpy.solver import solve, mixed_volume, newton_step
    pols = random_trinomials()
    real_pols = real_random_trinomials(pols)
    from random import uniform as u
    qone = pols[0][:-1] + ('%+.17f' % u(-1, +1)) + ';'
    qtwo = pols[1][:-1] + ('%+.17f' % u(-1, +1)) + ';'
    rone = real_pols[0][:-1] + ('%+.17f' % u(-1, +1)) + ';'
    rtwo = real_pols[1][:-1] + ('%+.17f' % u(-1, +1)) + ';'
    start = [qone, qtwo]
    target = [rone, rtwo]
    start_sols = solve(start, silent)
    sols = track(target, start, start_sols, precision, decimals)
    mixvol = mixed_volume(target)
    print 'mixed volume of the target is', mixvol
    print 'number of solutions found :', len(sols)
    newton_step(target, sols, precision, decimals)
Esempio n. 10
0
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
Esempio n. 11
0
def test_class():
    """
    Tests the methods in the class Solution.
    """
    from phcpy import solver
    pols = solver.random_trinomials()
    sols = solver.solve(pols)
    print 'sols[0] :'
    print sols[0]
    s = Solution(sols[0])
    print 'the first solution :'
    print s
    print 'its coordinates :'
    print s.coordinates()
    print 'its variable names :'
    print s.variables()
    print 'its numerical values :'
    print s.numerals()
    print 'its diagnostics :'
    print s.diagnostics()
    print 'its continuation parameter :', s.timevalue()
    print 'its multiplicity :', s.multiplicity()
    print 'the dictionary :'
    print s.dictionary()
    mysol = Solution({'x': complex(1,2), 'y': complex(-7,0)})
    print('my solution :')
    print(mysol)
    (errtab, rcotab, restab) = condition_tables(sols)
    print('The frequency tables for err, rco, and res:')
    print(errtab)
    print(rcotab)
    print(restab)
Esempio n. 12
0
def top_cascade(nvr, dim, pols, tol, nbtasks=0, prc='d', verbose=True):
    r"""
    Constructs an embedding of the polynomials in *pols*,
    with the number of variables in *pols* equal to *nvr*,
    where *dim* is the top dimension of the solution set.
    Applies the blackbox solver to the embedded system.
    The tolerance *tol* is used to split the solution list in the list
    of generic points and the nonsolutions for use in the cascade.
    Returns a tuple with three items:

    1. the embedded system,

    2. the solutions with zero last coordinate w.r.t. *tol*,

    3. the solutions with nonzero last coordinate w.r.t. *tol*.

    The three parameters are

    1. *nbtasks* is the number of tasks, 0 if no multitasking;

    2. the working precision *prc*, 'd' for double, 'dd' for double double,
       or 'qd' for quad double;

    3. if *verbose*, then some output is written to screen.
    """
    from phcpy.sets import embed
    from phcpy.solver import solve
    topemb = embed(nvr, dim, pols)
    if verbose:
        print 'solving the embedded system at the top ...'
    topsols = solve(topemb, verbose=verbose, tasks=nbtasks, precision=prc)
    if verbose:
        print 'number of solutions found :', len(topsols)
    (sols0, sols1) = split_filter(topsols, dim, tol, verbose=verbose)
    return (topemb, sols0, sols1)
Esempio n. 13
0
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
Esempio n. 14
0
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
Esempio n. 15
0
def test_track(silent=True, precision="d", decimals=80):
    """
    Tests the path tracking on a small random system.
    Two random trinomials are generated and random constants
    are added to ensure there are no singular solutions
    so we can use this generated system as a start system.
    The target system has the same monomial structure as
    the start system, but with random real coefficients.
    Because all coefficients are random, the number of
    paths tracked equals the mixed volume of the system.
    """
    from phcpy.solver import random_trinomials, real_random_trinomials
    from phcpy.solver import solve, mixed_volume, newton_step

    pols = random_trinomials()
    real_pols = real_random_trinomials(pols)
    from random import uniform as u

    qone = pols[0][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    qtwo = pols[1][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    rone = real_pols[0][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    rtwo = real_pols[1][:-1] + ("%+.17f" % u(-1, +1)) + ";"
    start = [qone, qtwo]
    target = [rone, rtwo]
    start_sols = solve(start, silent)
    sols = track(target, start, start_sols, precision, decimals)
    mixvol = mixed_volume(target)
    print "mixed volume of the target is", mixvol
    print "number of solutions found :", len(sols)
    newton_step(target, sols, precision, decimals)
Esempio n. 16
0
def top_cascade(nvr, dim, pols, tol, nbtasks=0, prc='d', verbose=True):
    r"""
    Constructs an embedding of the polynomials in *pols*,
    with the number of variables in *pols* equal to *nvr*,
    where *dim* is the top dimension of the solution set.
    Applies the blackbox solver to the embedded system.
    The tolerance *tol* is used to split the solution list in the list
    of generic points and the nonsolutions for use in the cascade.
    Returns a tuple with three items:

    1. the embedded system,

    2. the solutions with zero last coordinate w.r.t. *tol*,

    3. the solutions with nonzero last coordinate w.r.t. *tol*.

    The three parameters are

    1. *nbtasks* is the number of tasks, 0 if no multitasking;

    2. the working precision *prc*, 'd' for double, 'dd' for double double,
       or 'qd' for quad double;

    3. if *verbose*, then some output is written to screen.
    """
    from phcpy.sets import embed
    from phcpy.solver import solve
    topemb = embed(nvr, dim, pols)
    if verbose:
        print 'solving the embedded system at the top ...'
    topsols = solve(topemb, verbose=verbose, tasks=nbtasks, precision=prc)
    if verbose:
         print 'number of solutions found :', len(topsols)
    (sols0, sols1) = split_filter(topsols, dim, tol, verbose=verbose)
    return (topemb, sols0, sols1)
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
Esempio n. 18
0
def test_solve():
    """
    Runs a test on the solve() function.
    """
    pols = ['(x1-1)*(x1-2)*(x1-3)*(x1-4);', \
            '(x1-1)*(x2-1)*(x2-2)*(x2-3);', \
            '(x1-1)*(x1-2)*(x3-1)*(x3-2);', \
            '(x1-1)*(x2-1)*(x3-1)*(x4-1);']
    deco = solve(4, 3, pols)
Esempio n. 19
0
def testscroller():
    """
    Solves the cyclic 5-roots problems
    and launches the scroller.
    """
    from phcpy.families import cyclic
    from phcpy.solver import solve
    cyc5 = cyclic(5)
    sols = solve(cyc5, silent=True)
    scrollsols(sols)
Esempio n. 20
0
def testscroller():
    """
    Solves the cyclic 5-roots problems
    and launches the scroller.
    """
    from phcpy.families import cyclic
    from phcpy.solver import solve
    cyc5 = cyclic(5)
    sols = solve(cyc5, silent=True)
    scrollsols(sols)
Esempio n. 21
0
 def solve(self, nbtasks=0, verbose=True):
     """
     Applies the blackbox solver and returns a list of solutions.
     Multitasking is applied when the number of tasks in nbtasks
     is set to the number of tasks.
     By default, verbose is True, and root counts are written.
     """
     sols = solver.solve(self.pols, verbose=verbose, tasks=nbtasks)
     result = [Solution(sol) for sol in sols]
     return result
Esempio n. 22
0
def solve_system(pols):
    """
    Calls the black box solver of PHCpack
    for valid input lists pols.
    Returns the solution found.
    """
    if len(pols) > 0:
        from phcpy import solver
        return solver.solve(pols)
    else:
        return []
Esempio n. 23
0
def solve_system(pols):
    """
    Calls the black box solver of PHCpack
    for valid input lists pols.
    Returns the solution found.
    """
    if len(pols) > 0:
        from phcpy import solver
        return solver.solve(pols)
    else:
        return []
Esempio n. 24
0
def solve(pol):
    """
    Applies the blackbox solver of phcpy to the polynomial pol.
    """
    from phcpy.solver import solve
    try:
        sols = solve([pol], verbose=False)
        print sols
        return sols
    except:
        print 'an exception happened in the blackbox solver'
        return []
Esempio n. 25
0
def main():
    """
    Defines the equations for the sevenbar problem.
    """
    eqs = symbolic_equations()
    for equ in eqs:
        print equ
    T1, T2, T3, T4, T5, T6 = var('T1, T2, T3, T4, T5, T6')
    generic = generic_problem(eqs)
    for equ in generic:
        print equ
    from phcpy.solver import solve
    sols = solve(generic)
    for sol in sols:
        print sol
    special = special_problem(eqs)
    for equ in special:
        print equ
    sols = solve(special)
    for sol in sols:
        print sol
Esempio n. 26
0
def solve(pol):
    """
    Applies the blackbox solver of phcpy to the polynomial pol.
    """
    from phcpy.solver import solve
    try:
        sols = solve([pol], verbose=False)
        print sols
        return sols
    except:
        print 'an exception happened in the blackbox solver'
        return []
Esempio n. 27
0
def testcoordinateplot():
    """
    Solves the cyclic 5-roots problem,
    prompts the user for an index of a coordinate,
    and launches the plotcoordinate function.
    """
    from phcpy.families import cyclic
    from phcpy.solver import solve
    print 'solving the cyclic 5-roots problem ...'
    cyc5 = cyclic(5)
    sols = solve(cyc5, silent=True)
    idx = int(input('Give an index : '))
    plotcoordinate(sols, idx)
def main():
	'''this is a main function of the single problem solver code
	'''	
	f = ['x^2 + y^2 - 1 ;','(x-1)^2 + y^2 - 1 ;']
	s = solve(f, silent = True)
	print s
	#print s[0]
		
	list_of_dicts = convert_str2dict(s)

	real_sols_counter = counts_real(list_of_dicts, tol = 1e-7)

	print "For those two circles we get",real_sols_counter,"real solution(s)!"
Esempio n. 29
0
def solve_pieri_system(eqs):
    """
    Applies the black box solver of phcpy to solve the equations
    defined by the strings in the list eqs.  Note that, because
    of its particular structure, this will only work well if the 
    system is linear.
    """
    from phcpy.solver import solve
    sols = solve(eqs)
    print '-> the solutions :'
    for sol in sols:
        print sol
    return sols
Esempio n. 30
0
def testcoordinateplot():
    """
    Solves the cyclic 5-roots problem,
    prompts the user for an index of a coordinate,
    and launches the plotcoordinate function.
    """
    from phcpy.families import cyclic
    from phcpy.solver import solve
    print('solving the cyclic 5-roots problem ...')
    cyc5 = cyclic(5)
    sols = solve(cyc5, silent=True)
    idx = int(input('Give an index : '))
    plotcoordinate(sols, idx)
Esempio n. 31
0
def solve_pieri_system(eqs):
    """
    Applies the black box solver of phcpy to solve the equations
    defined by the strings in the list eqs.  Note that, because
    of its particular structure, this will only work well if the 
    system is linear.
    """
    from phcpy.solver import solve
    sols = solve(eqs)
    print '-> the solutions :'
    for sol in sols:
        print sol
    return sols
Esempio n. 32
0
def main():
    """
    Prompts the user for a degree and then computes the roots
    of the Wilkinson polynomial.
    """
    deg = int(raw_input("Give the degree : "))
    pol = wilkpol(deg)
    print pol
    ans = raw_input("Apply the blackbox solver ? (y/n) ")
    if(ans == 'y'):
        sols = solve(pol)
        for sol in sols:
            print sol
    track(pol)
def return_solns(c_i,c_f,r_i,r_f,step):

	my_sols_list = []
	for i in arange(c_i,c_f + step,step):
		for j in arange(r_i,r_f + step,step):
			x, y = symbols('x y')
			coeff = float(i)
			rad = float(j)
			f1 = str(x**2 + y**2 - 1) +';'
			f2 = str(x**2 - 2*coeff*x + coeff**2 + y**2 - rad**2) + ';'
			f = [f1, f2]
			s = solve(f, silent = True)
			my_sols_list.append(s)
	return my_sols_list
Esempio n. 34
0
def main():
    """
    Prompts the user for a degree and then computes the roots
    of the Wilkinson polynomial.
    """
    deg = int(raw_input("Give the degree : "))
    pol = wilkpol(deg)
    print pol
    ans = raw_input("Apply the blackbox solver ? (y/n) ")
    if (ans == 'y'):
        sols = solve(pol)
        for sol in sols:
            print sol
    track(pol)
Esempio n. 35
0
def test_solve():
    """
    Runs a test on the solve() function.
    """
    testpols = ['(x1-1)*(x1-2)*(x1-3)*(x1-4);', \
                '(x1-1)*(x2-1)*(x2-2)*(x2-3);', \
                '(x1-1)*(x1-2)*(x3-1)*(x3-2);', \
                '(x1-1)*(x2-1)*(x3-1)*(x4-1);']
    ans = input('Verbose ? (y/n) ')
    vrb = (ans == 'y')
    deco = solve(nvr=4, dim=3, pols=testpols, verbose=vrb)
    if not vrb:
        print('the decomposition :')
        write_decomposition(deco)
Esempio n. 36
0
def test_solve():
    """
    Runs a test on the solve() function.
    """
    testpols = ['(x1-1)*(x1-2)*(x1-3)*(x1-4);', \
                '(x1-1)*(x2-1)*(x2-2)*(x2-3);', \
                '(x1-1)*(x1-2)*(x3-1)*(x3-2);', \
                '(x1-1)*(x2-1)*(x3-1)*(x4-1);']
    ans = input('Verbose ? (y/n) ')
    vrb = (ans == 'y')
    deco = solve(nvr=4, dim=3, pols=testpols, verbose=vrb)
    if not vrb:
        print('the decomposition :')
        write_decomposition(deco)
Esempio n. 37
0
def test_cascade():
    """
    Does one cascade step on simple example.
    In the top embedding we first find the 2-dimensional
    solution set x = 1.  In the cascade step we compute
    the three witness points on the twisted cubic.
    """
    from phcpy import solver
    pols = ['(x - 1)*(y-x^2);', \
            '(x - 1)*(z-x^3);', \
            '(x^2 - 1)*(y-x^2);' ]
    print pols
    embpols = embed(3, 2, pols)
    print 'the embedded system :'
    print embpols
    raw_input('hit enter to continue...')
    sols = solver.solve(embpols, silent=True)
    for sol in sols:
        print sol
    print 'number of solutions :', len(sols)
    raw_input('hit enter to continue...')
    from phcpy.phcsols import filter_zero_coordinates, filter_regular
    sols0 = filter_zero_coordinates(sols, 'zz1', 1.0e-8, 'select')
    sols1 = filter_zero_coordinates(sols, 'zz1', 1.0e-8, 'remove')
    print 'solutions with zero slack variables :'
    for sol in sols0:
        print sol
    print 'solutions with nonzero slack variables :'
    for sol in sols1:
        print sol
    print len(sols), '=' , len(sols0), '+', len(sols1)
    rs1 = filter_regular(sols1, 1.0e-8, 'select')
    print 'number of nonsolutions :', len(rs1)
    raw_input('hit enter to continue...')
    print '... running cascade step ...'
    s2c = cascade_step(embpols, rs1, precision='d')
    print '... after running the cascade ...'
    for sol in s2c:
        print sol
    wp1 = drop_variable_from_polynomials(embpols, 'zz2')
    print 'the 1-dimensional embedding :'
    for pol in wp1:
        print pol
    ws1 = drop_coordinate_from_solutions(s2c, len(embpols), 'zz2')
    ws1f1 = filter_zero_coordinates(ws1, 'zz1', 1.0e-8, 'select')
    ws1f2 = filter_regular(ws1f1, 1.0e-8, 'select')
    print 'the witness points :'
    for sol in ws1f2:
        print sol
Esempio n. 38
0
def test_monodromy():
    """
    Runs a test on applying monodromy loops
    to factor a curve into irreducible components.
    """
    from phcpy import solver
    pols = ['(x^2 - y)*(x-y);', 'x^3 - z;']
    embsys = embed(3, 1, pols)
    # patch : make sure zz1 is last symbol!
    embsys[0] = 'x - x + y - y + z - z + ' + embsys[0]
    print embsys
    sols = solver.solve(embsys, silent=True)
    # for sol in sols: print sol
    print 'the degree is', len(sols)
    monodromy_breakup(embsys, sols, 1)
Esempio n. 39
0
def test_monodromy(prc='d'):
    """
    Runs a test on applying monodromy loops
    to factor a curve into irreducible components.
    """
    from phcpy.solver import solve
    from phcpy.sets import embed
    pols = ['(x^2 - y)*(x-y);', 'x^3 - z;']
    embsys = embed(3, 1, pols, prc)
    # patch : make sure zz1 is last symbol!
    embsys[0] = 'x - x + y - y + z - z + ' + embsys[0]
    print(embsys)
    sols = solve(embsys, verbose=False, precision=prc)
    # for sol in sols: print sol
    print('the degree is', len(sols))
    monodromy_breakup(embsys, sols, 1, islaurent=0, verbose=True, prec=prc)
Esempio n. 40
0
def test_monodromy(prc='d'):
    """
    Runs a test on applying monodromy loops
    to factor a curve into irreducible components.
    """
    from phcpy.solver import solve
    from phcpy.sets import embed
    pols = ['(x^2 - y)*(x-y);', 'x^3 - z;']
    embsys = embed(3, 1, pols, prc)
    # patch : make sure zz1 is last symbol!
    embsys[0] = 'x - x + y - y + z - z + ' + embsys[0]
    print(embsys)
    sols = solve(embsys, verbose=False, precision=prc)
    # for sol in sols: print sol
    print('the degree is', len(sols))
    monodromy_breakup(embsys, sols, 1, islaurent=0, verbose=True, prec=prc)
Esempio n. 41
0
def viviani(prc='d'):
    """
    Returns the system which stores the Viviani curve,
    with some solutions intersected with a plane,
    in double ('d'), double double ('dd'), or quad double('qd') precision.
    """
    from phcpy.solver import solve
    pols = ['(1-s)*y + s*(y-1);', \
            'x^2 + y^2 + z^2 - 4;' , \
            '(x-1)^2 + y^2 - 1;', \
            's;']
    sols = solve(pols, silent=True, precision=prc)
    print "The solutions on the Viviani curve :"
    for sol in sols:
        print sol
    return (pols[:3], sols)
Esempio n. 42
0
def viviani(prc='d'):
    """
    Returns the system which stores the Viviani curve,
    with some solutions intersected with a plane,
    in double ('d'), double double ('dd'), or quad double('qd') precision.
    """
    from phcpy.solver import solve
    pols = ['(1-s)*y + s*(y-1);', \
            'x^2 + y^2 + z^2 - 4;' , \
            '(x-1)^2 + y^2 - 1;', \
            's;']
    sols = solve(pols, silent=True, precision=prc)
    print("The solutions on the Viviani curve :")
    for sol in sols:
        print(sol)
    return (pols[:3], sols)
Esempio n. 43
0
def make_witness_set(pols, verbose=True):
    """
    We have two equations in three variables in pols
    and therefore we expect a one dimensional set.
    """
    from phcpy.sets import embed
    from phcpy.solver import solve
    embpols = embed(3, 1, pols)
    if verbose:
        print 'the embedded system :'
        for pol in embpols:
            print pol
    embsols = solve(embpols, silent=not verbose)
    if verbose:
        print 'the witness points :'
        for sol in embsols:
            print sol
    return (embpols, embsols)
Esempio n. 44
0
def test(precision="d"):
    """
    Tests the numerical computation of a tropism.
    """
    pols = ["x + x*y + y^3;", "x;"]
    from phcpy.solver import solve

    start = [
        "x + (-5.89219623474258E-02 - 9.98262591883082E-01*i)*y^2"
        + " + ( 5.15275165825429E-01 + 8.57024797472965E-01*i)*x*y;",
        "x+(-9.56176913648087E-01 - 2.92789531586119E-01*i);",
    ]
    startsols = solve(start, silent=True)
    print "computed", len(startsols), "start solutions"
    from phcpy.tuning import order_endgame_extrapolator_set as set

    set(4)
    if precision == "d":
        from phcpy.trackers import standard_double_track as track
    elif precision == "dd":
        from phcpy.trackers import double_double_track as track
    elif precision == "qd":
        from phcpy.trackers import quad_double_track as track
    else:
        print "wrong level of precision"
        return
    sols = track(pols, start, startsols)
    print "the solutions at the end :"
    for sol in sols:
        print sol
    if precision == "d":
        print "size of the tropisms container :", standard_size()
        (wnd, dirs, errs) = standard_retrieve(len(sols), len(pols))
    elif precision == "dd":
        print "size of the tropisms container :", dobldobl_size()
        (wnd, dirs, errs) = dobldobl_retrieve(len(sols), len(pols))
    else:
        print "size of the tropisms container :", quaddobl_size()
        (wnd, dirs, errs) = quaddobl_retrieve(len(sols), len(pols))
    print "the winding numbers :", wnd
    print "the directions :"
    for dir in dirs:
        print dir
    print "the errors :", errs
Esempio n. 45
0
def return_solns(my_random_list):


	a1,a2,a3,b2,b3,c3,r1,r2,r3 = my_random_list
	
	v1,v2,v3,u1,u2,u3 = symbols(' v1 v2 v3 u1 u2 u3')

        p1 = str(v1**2 + v2**2 + v3**2 -1) + ';'
        p2 = str(u1*v1 + u2*v2 + u3*v3) + ';'
        p3 = str(u1**2 + u2**2 + u3**2 - 1) + ';'
        p4 = str(-2*u1*a1 - v1**2*a1**2 + a1**2 - r1**2 + 1) + ';'
        p5 = str(-2*u1*a2 - 2*u2*b2 - v1**2*a2**2 - 2*v1*v2*a2*b2 - v2**2*b2**2 + a2**2 + b2**2 - r2**2 + 1) + ';'
        p6 = str(-2*u1*a3 - 2*u2*b3 - 2*u3*c3 - v1**2*a3**2 - 2*v1*v2*a3*b3 - 2*v1*v3*a3*c3 - v2**2*b3**2 - 2*v2*v3*b3*c3 - v3**2*c3**2 + a3**2 + b3**2 + c3**2 - r3**2 + 1) + ';'

        system = [p1,p2,p3,p4,p5,p6]

        s = solve(system, silent = True)
			
	return s
Esempio n. 46
0
 def solve(self):
     """
     Takes the data from the input text widget,
     places the data into a list of polynomials,
     calls the blackbox solver and displays the
     solutions in the output text widget.
     """
     self.output.delete(1.0, END)
     data = self.inputd.get(1.0, END)
     self.output.insert(END, data)
     psys = str2pols(data)
     from phcpy.solver import solve
     sols = solve(psys, silent=True)
     self.output.insert(END, 'Computed %d solutions.\n\n' % len(sols))
     cnt = 0
     for sol in sols:
         cnt = cnt + 1
         self.output.insert(END, 'solution %d :\n' % cnt)
         self.output.insert(END, sol + '\n')
Esempio n. 47
0
 def solve(self):
     """
     Takes the data from the input text widget,
     places the data into a list of polynomials,
     calls the blackbox solver and displays the
     solutions in the output text widget.
     """
     self.output.delete(1.0, END)
     data = self.inputd.get(1.0, END)
     self.output.insert(END, data)
     psys = str2pols(data)
     from phcpy.solver import solve
     sols = solve(psys, silent=True)
     self.output.insert(END, 'Computed %d solutions.\n\n' % len(sols))
     cnt = 0
     for sol in sols:
         cnt = cnt + 1
         self.output.insert(END, 'solution %d :\n' % cnt)
         self.output.insert(END, sol + '\n')
Esempio n. 48
0
def witset(pols, verbose=True):
    """
    We have three equations in pols in five variables:
    x, y, s, L1, and L2.
    Therefore we expect a two dimensional set.
    """
    from phcpy.sets import embed
    from phcpy.solver import solve
    embpols = embed(5, 2, pols)
    if verbose:
        print 'the embedded system :'
        for pol in embpols:
            print pol
    embsols = solve(embpols, silent=not verbose)
    if verbose:
	print 'the witness points :'
        for sol in embsols:
            print sol
    return (embpols, embsols)
Esempio n. 49
0
def generate_random_numbers(c_i,c_f,r_i,r_f):

	coeff = random.uniform(c_i,c_f)
	rad = random.uniform(r_i,r_f)
	x,y = symbols('x y')
	f1 = str(x**2 + y**2 - 1) +';'
	f2 = str(x**2 - 2*coeff*x + coeff**2 + y**2 - rad**2) +';'
	f = [f1,f2]
	sol = solve(f, silent = True)
	











	tuple_sols_list = return_solns(c_i,c_f,r_i,r_f,step)	

	print tuple_sols_list

	compound_sols_list = take_tuple_return_list(tuple_sols_list)
		
	print compound_sols_list	

	solution_list = []

	while compound_sols_list:
		solution_list.extend(compound_sols_list.pop(0))	

	
	

	list_of_dicts = convert_str2dict(solution_list)

	total_real_sols_counter = counts_real_total(list_of_dicts, tol = 1e-7)

	print "For those two circles we get a total of",total_real_sols_counter, "real solution(s)!"
Esempio n. 50
0
def test():
    """
    Generates a random trinomial system,
    solves it, converts the solutions,
    and then sums the multiplicities.
    """
    from phcpy import solver
    pols = solver.random_trinomials()
    sols = solver.solve(pols)
    dsols = [strsol2dict(sol) for sol in sols]
    mult = 0
    s0d = strsol2dict(sols[0])
    print('variables :', variables(s0d))
    print(evaluate(pols, s0d))
    for sol in dsols:
        mult = mult + sol['m']
    print('sum of multiplicities :', mult)
    print('sum of values at the solutions :')
    for sol in dsols:
        print(sum(evaluate(pols, sol)))
Esempio n. 51
0
def test():
    """
    Generates a random trinomial system,
    solves it, converts the solutions,
    and then sums the multiplicities.
    """
    from phcpy import solver
    pols = solver.random_trinomials()
    sols = solver.solve(pols)
    dsols = [strsol2dict(sol) for sol in sols]
    mult = 0
    s0d = strsol2dict(sols[0])
    print('variables :', variables(s0d))
    print(evaluate(pols, s0d))
    for sol in dsols:
        mult = mult + sol['m']
    print('sum of multiplicities :', mult)
    print('sum of values at the solutions :')
    for sol in dsols:
        print(sum(evaluate(pols, sol)))
Esempio n. 52
0
def client():
    """
    The client connects to a server and
    solves a system.
    """
    sock = socket(AF_INET, SOCK_STREAM)
    try:
        sock.connect(('localhost', PORTNUM))
    except:
        print('could not connect to server')
        return
    print('connected to server')
    from phcpy import solver
    while True:
        pols = recv_strings(sock, BUFSIZE)
        print('received ', pols)
        if pols == []:
            break
        sols = solver.solve(pols)
        send_strings(sock, BUFSIZE, sols)
    sock.close()
Esempio n. 53
0
def client():
    """
    The client connects to a server and
    solves a system.
    """
    sock = socket(AF_INET, SOCK_STREAM)
    try:
        sock.connect(('localhost', PORTNUM))
    except:
        print('could not connect to server')
        return
    print('connected to server')
    from phcpy import solver
    while True:
        pols = recv_strings(sock, BUFSIZE)
        print('received ', pols)
        if pols == []:
            break
        sols = solver.solve(pols)
        send_strings(sock, BUFSIZE, sols)
    sock.close()
Esempio n. 54
0
def test(precision='d'):
    """
    Tests the numerical computation of a tropism.
    """
    pols = ['x + x*y + y^3;', 'x;']
    from phcpy.solver import solve
    start = ['x + (-5.89219623474258E-02 - 9.98262591883082E-01*i)*y^2' \
         + ' + ( 5.15275165825429E-01 + 8.57024797472965E-01*i)*x*y;', \
        'x+(-9.56176913648087E-01 - 2.92789531586119E-01*i);']
    startsols = solve(start, verbose=False)
    print('computed', len(startsols), 'start solutions')
    from phcpy.tuning import order_endgame_extrapolator_set as set
    set(4)
    if precision == 'd':
        from phcpy.trackers import standard_double_track as track
    elif precision == 'dd':
        from phcpy.trackers import double_double_track as track
    elif precision == 'qd':
        from phcpy.trackers import quad_double_track as track
    else:
        print('wrong level of precision')
        return
    sols = track(pols, start, startsols)
    print('the solutions at the end :')
    for sol in sols:
        print(sol)
    if precision == 'd':
        print('size of the tropisms container :', standard_size())
        (wnd, dirs, errs) = standard_retrieve(len(sols), len(pols))
    elif precision == 'dd':
        print('size of the tropisms container :', dobldobl_size())
        (wnd, dirs, errs) = dobldobl_retrieve(len(sols), len(pols))
    else:
        print('size of the tropisms container :', quaddobl_size())
        (wnd, dirs, errs) = quaddobl_retrieve(len(sols), len(pols))
    print('the winding numbers :', wnd)
    print('the directions :')
    for dir in dirs:
        print(dir)
    print('the errors :', errs)
Esempio n. 55
0
def special_solutions(pols, slope):
    """
    Given in pols the polynomials for the line intersecting a circle
    for a general slope s, solves the problem for a special numerical
    value for s, given in the slope.
    The value of the slope is added as last coordinate to each solution.
    """
    from phcpy.solver import solve
    from phcpy.solutions import make_solution, coordinates
    special = []
    for pol in pols:
        rpl = pol.replace('s', '(' + str(slope) + ')')
        special.append(rpl)
    sols = solve(special, silent=True)
    result = []
    for sol in sols:
        (vars, vals) = coordinates(sol)
        vars.append('s')
        vals.append(slope)
        extsol = make_solution(vars, vals)
        result.append(extsol)
    return result