Example #1
0
def simplex_step(A, b, c, R_square, show_bases=False):
    if show_bases: print("basis: ", R_square)
    R = A.D[0]
    # Extract the subsystem
    A_square = Mat((R_square, A.D[1]), {(r,c):A[r,c] for r,c in A.f if r in R_square})
    b_square = Vec(R_square, {k:b[k] for k in R_square})
    # Compute the current vertex
    x = solve(A_square, b_square)
    print("(value: ",c*x,") ",end="")
    # Compute a possibly feasible dual solution
    y_square = solve(A_square.transpose(), c) #compute entries with labels in R_square
    y = Vec(R, y_square.f) #Put in zero for the other entries
    if min(y.values()) >= -1e-10: return ('OPTIMUM', x) #found optimum!
    R_leave = {i for i in R if y[i]< -1e-10} #labels at which y is negative
    r_leave = min(R_leave, key=hash) #choose first label at which y is negative
    # Compute the direction to move
    d = Vec(R_square, {r_leave:1})
    w = solve(A_square, d)
    # Compute how far to move
    Aw = A*w # compute once because we use it many times
    R_enter = {r for r in R if Aw[r] < -1e-10}
    if len(R_enter)==0: return ('UNBOUNDED', None)
    Ax = A*x # compute once because we use it many times
    delta_dict = {r:(b[r] - Ax[r])/(Aw[r]) for r in R_enter}
    delta = min(delta_dict.values())
    # Compute the new tight constraint
    r_enter = min({r for r in R_enter if delta_dict[r] == delta}, key=hash)[0]
    # Update the set representing the basis
    R_square.discard(r_leave)
    R_square.add(r_enter)
    return ('STEP', None)
Example #2
0
 def energy(self):
     grid = self.get_grid()
     try:
         solver.solve(self.width, self.height, grid)
     except Exception:
         return self.size + 1
     return self.shown.count(True)
Example #3
0
def test():
    """
    Solves the systems and tests on their number of solutions.
    """
    from phcpy2c import py2c_set_seed
    py2c_set_seed(234798272)
    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'
def test():
    problem = Problem(
        id='6nXC7iyndcldO1dvKHbBmDHv',
        size=6, operators=frozenset(['not', 'shr4', 'shr16', 'shr1']))
    problem.solution = '(lambda (x_5171) (shr4 (shr16 (shr1 (not x_5171)))))'

    server = Server([problem])

    solve(problem, server)
def find_hole(expression,lower,upper): #Finds the holes of a function in a range
    x = Symbol("x")
    y = sympify(expression)
    forward_open = ['[','('] #List of 'open' separators
    forward_close = [']',')'] #List of 'closed' separators
    separators = ['+','-'] # Neutral separators
    exists = 0 
    found = []
    term_list = []
    holes = []
    while exists != -1: #Finds all division signs in the expression
        exists = expression.find('/',exists)
        if exists != -1:
            found.append(exists)
            exists=exists+1
    for a in found: #For each division sign, find denominator
        counter = 0
        term_indexes = [a+1]#List of indexes of denominator and numerator
        index = a+1 #Starting index of denominator
        while len(term_indexes) < 2: #This loop finds the end of the denomninator
            if index >= len(expression): #If end of expression is reached, append index for end of expression
                term_indexes.append(len(expression))
            elif expression[index] in forward_open: #If open separator found, add to counter
                counter += 1
            elif expression[index] in forward_close: #If closed separator found, subtract from counter
                counter -= 1
                if counter <= 0:# If end of term reached, append current index
                    term_indexes.append(index)
            elif expression[index] in separators and counter == 0: #If neutral separator found, and separators are paired, append current index
                term_indexes.append(index)
            index += 1 #Move forward one index
        index = a-1 #Ending index of numerator
        counter = 0
        while len(term_indexes) < 3: #This loop finds the beginning of the numerator
            if index < 0: #If beginning of expression reached, append index for beginning
                term_indexes.append(0)
            elif expression[index] in forward_close: #If closed separator found, add to counter
                counter += 1
            elif expression[index] in forward_open: #if open separator found, subtract form counter.
                counter -= 1
                if counter <= 0: #If end of term reached, append current index
                    term_indexes.append(index+1)
            elif expression[index] in separators and counter == 0: #If neutral separator found and separators are paired, append current index
                term_indexes.append(index)
            index -= 1 #Move back one index
        term_indexes.append(a) #Append endpoint of numerator
        term_list.append(term_indexes) 
    for b in term_list: #Solves numerator and denominator to find holes
        denominator = expression[b[0]:b[1]] #Slice denominator
        numerator = expression[b[2]:b[3]] #Slice numerator
        d_solution = solv.solve(denominator,0) #Solve denominator
        n_solution = solv.solve(numerator,0) #Solve numerator
        for c in d_solution: #Find matching solutions in given range
            if c in n_solution and c >= lower and c<= upper:
                holes.append([c,limit(y,x,c)])
    return holes
Example #6
0
def problem2():
    T = Mat((set([0, 1, 2, 3]), set([0, 1, 2, 3])), {(0, 1): 0.25, (1, 2): 0.0, (3, 2): 0, (0, 0): 1, (3, 3): 1, (3, 0): 0, (3, 1): 0, (2, 1): 0, (0, 2): 0.75, (2, 0): 0, (1, 3): -0.25, (2, 3): 0, (2, 2): 1, (1, 0): 0, (0, 3): 0.5, (1, 1): 1})
    b1 = Vec({0, 1, 2, 3}, {2: 1})
    b2 = Vec({0, 1, 2, 3}, {3: 1})
    print(T)
    print(b1)
    print(b2)
    x1 = solve(T, b1)
    x2 = solve(T, b2)
    
    print([x1,x2])
Example #7
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    assert i in range(len(L))
    if len(L) > 1:
        colVecs = coldict2mat({ x : L[x] for x in range(len(L)) if x != i })
        u = solve(colVecs, L[i])
        residual = L[i] - colVecs * u
    else:
        residual = 1
    return residual * residual < 10e-14
Example #8
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    if len(L) <= 1:
        return False
    
    # remove L[i] without changing the list (i.e. w/o using L.pop())
    b = L[i] # RHS of A*u = b
    A = coldict2mat(L[:i] + L[i+1:]) # coefficient matrix L w/o L[i]
    u = solve(A, b)
    e = b - A*u
    
    return e*e < 1e-14
Example #9
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    assert(len(L) > 0)
    assert(i < len(L))

    if len(L) == 1:
        return True

    mtx = coldict2mat([ L[j] for j in range(len(L)) if j != i ])
    u = solve(mtx,L[i])

    residual = mtx * u - L[i]
    return residual * residual < 10e-14
Example #10
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    if len(L) == 1:
    	return False
    copyL = L[:]	
    b = copyL[i]
    del copyL[i]
    matrix = coldict2mat(copyL)
    u = solve(matrix, b)
    residual = b - matrix*u
    return (residual * residual) < 10e-14 
Example #11
0
def direct_sum_decompose(U_basis, V_basis, w):
    """
    input:  A list of Vecs, U_basis, containing a basis for a vector space, U.
    A list of Vecs, V_basis, containing a basis for a vector space, V.
    A Vec, w, that belongs to the direct sum of these spaces.
    output: A pair, (u, v), such that u+v=w and u is an element of U and
    v is an element of V.
    
    >>> U_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 1, 2: 0, 3: 0, 4: 6, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 11, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 3, 1: 1.5, 2: 0, 3: 0, 4: 7.5, 5: 0})]
    >>> V_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 7, 3: 0, 4: 0, 5: 1}), Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 15, 3: 0, 4: 0, 5: 2})]
    >>> w = Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0})
    >>> direct_sum_decompose(U_basis, V_basis, w) == (Vec({0, 1, 2, 3, 4, 5},{0: 2.0, 1: 4.999999999999972, 2: 0.0, 3: 0.0, 4: 1.0, 5: 0.0}), Vec({0, 1, 2, 3, 4, 5},{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}))
    True
    """
    testMat = coldict2mat(U_basis + V_basis)
    coef = solve(testMat, w)
    Nu = len(U_basis)
    Nv = len(V_basis)
    retU = Vec(U_basis[0].D, {})
    retV = Vec(V_basis[0].D, {})
    for i in range(Nu):
        retU += coef[i] * U_basis[i]
    for i in range(Nv):
        retV += coef[i + Nu] * V_basis[i]

    return (retU, retV)
Example #12
0
File: hw4.py Project: pcp135/C-CtM
def is_superfluous(L, i):
    """
		Input:
				- L: list of vectors as instances of Vec class
				- i: integer in range(len(L))
		Output:
				True if the span of the vectors of L is the same
				as the span of the vectors of L, excluding L[i].

				False otherwise.
		Examples:
				>>> a0 = Vec({'a','b','c','d'}, {'a':1})
				>>> a1 = Vec({'a','b','c','d'}, {'b':1})
				>>> a2 = Vec({'a','b','c','d'}, {'c':1})
				>>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
				>>> is_superfluous(L, 3)
				True
				>>> is_superfluous([a0,a1,a2,a3], 3)
				True
				>>> is_superfluous([a0,a1,a2,a3], 0)
				True
				>>> is_superfluous([a0,a1,a2,a3], 1)
				False
		"""
    if len(L) > 1:
        l = L.copy()
        b = l.pop(i)
        M = coldict2mat(l)
        solution = solve(M, b)
        residual = M * solution - b
        if residual * residual < 10e-14:
            return True
    return False
Example #13
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    if len(L) == 1:
        return False

    Li = L.pop(i)
    mL = coldict2mat(L)
    sol = solve(mL,Li)
    res = Li - mL * sol
    if abs(res*res) < 10**-14:
        return True
    else:
        return False
Example #14
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    dist= len(L)
    if dist == 1: return False
    A= coldict2mat([L[j] for j in range(dist) if i != j])
    b= L[i]
    u= solve(A,b)
    residual= b - A*u
    return (residual*residual) < 1E-14
Example #15
0
def testFromFile(data, inputfile):
	f = open(inputfile, 'r')
	delays = map(float, list(f))
	f.close()

	delayedProblem = data['pos'].clone()
	for (index, act) in enumerate(delayedProblem.activities):
		act.time *= delays[index]
	
	toSolve = {'options':{'solver':"noResources"},'instance':delayedProblem}
	delayedSolution = solve(toSolve)

	(numDelays, totalDelay) = getTaskDelays(data['solution'], delayedSolution)
	
	horizon = float(data['instance'].getHorizon())
	delayedMakespan = delayedSolution.getMakespan()
	originalMakespan = data['solution'].getMakespan()
	
	result = {}
	result['numDelays'] = numDelays
	result['totalDelay'] = totalDelay
	result['delayedPortion'] = float(numDelays) / float(len(data['instance'].activities))
	result['normTaskDelay'] = float(totalDelay) / horizon
	result['mksInc'] = delayedMakespan - originalMakespan
	result['relMksInc'] = float(delayedMakespan - originalMakespan) / float(originalMakespan)
	result['normMksInc'] = float(delayedMakespan - originalMakespan) / horizon
	return result
Example #16
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    if len(L) == 1:
        return False
    tList = copy.deepcopy(L)
    v_i = tList.pop(i)
    x = solve(coldict2mat(tList),v_i)
    res = v_i - coldict2mat(tList) * x
    if res * res < pow(10,-14) : 
        return True
    return False 
    pass
Example #17
0
def is_superfluous(L, i):
    """
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    """
    if len(L) > 1:
        b = L.pop(i)
        A = coldict2mat(L)
        u = solve(A, b)
        residual = b - (A * u)
        condition = u != Vec(A.D[1], {}) and residual * residual < 10 ** -14
        L.insert(i, b)
    else:
        return False
    return condition
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([ a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    b = L.pop(i)
    u = solve(coldict2mat(L),b)
    residual = b - coldict2mat(L)*u
    if residual * residual < 10e-14:
        return True
    else:
        return False
def solve():
    line = request.args.get('line', '', type=str)
    sort = request.args.get('sortby', 'scoreD', type=str)
    words = solver.solve(line, sort)
    data = { 'words': [ x.__dict__ for x in words], }

    return jsonify(data)
Example #20
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    assert i in range(len(L))
    A = coldict2mat({c:L[c] for c in range(len(L)) if c!=i})
    residual = L[i] - A*solve(A, L[i])
    if residual * residual < 1e-14:
        return True
    return False
Example #21
0
def example4():
  '''Modified problem without the final statement by Albert.'''
  dialogue = '''
    Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
    Bernard: At first I don't know when Cheryl's birthday is, but I know now.
  '''
  return solver.solve(Cheryl.possibilities, Cheryl.projections, dialogue, Cheryl.goal)
Example #22
0
def is_superfluous(L, i):
    '''
    Input:
        - L: list of vectors as instances of Vec class
        - i: integer in range(len(L))
    Output:
        True if the span of the vectors of L is the same
        as the span of the vectors of L, excluding L[i].

        False otherwise.
    Examples:
        >>> a0 = Vec({'a','b','c','d'}, {'a':1})
        >>> a1 = Vec({'a','b','c','d'}, {'b':1})
        >>> a2 = Vec({'a','b','c','d'}, {'c':1})
        >>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
        >>> is_superfluous(L, 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 3)
        True
        >>> is_superfluous([a0,a1,a2,a3], 0)
        True
        >>> is_superfluous([a0,a1,a2,a3], 1)
        False
    '''
    coldict_i = {k:L[k] for k in range(len(L)) if  k!=i }
    mat_i = coldict2mat(coldict_i)
    v = solve(mat_i, L[i])
    res = mat_i * v - L[i]
    res_2 = res*res
    ##print(res_2)
    return res_2 < 1e-14
Example #23
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 solver import random_trinomials, real_random_trinomials
    from 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)
Example #24
0
File: hw5.py Project: varren/matrix
def direct_sum_decompose(U_basis, V_basis, w):
    '''
    input:  A list of Vecs, U_basis, containing a basis for a vector space, U.
    A list of Vecs, V_basis, containing a basis for a vector space, V.
    A Vec, w, that belongs to the direct sum of these spaces.
    output: A pair, (u, v), such that u+v=w and u is an element of U and
    v is an element of V.
    
    >>> U_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 1, 2: 0, 3: 0, 4: 6, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 11, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 3, 1: 1.5, 2: 0, 3: 0, 4: 7.5, 5: 0})]
    >>> V_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 7, 3: 0, 4: 0, 5: 1}), Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 15, 3: 0, 4: 0, 5: 2})]
    >>> w = Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0})
    >>> direct_sum_decompose(U_basis, V_basis, w) == (Vec({0, 1, 2, 3, 4, 5},{0: 2.0, 1: 4.999999999999972, 2: 0.0, 3: 0.0, 4: 1.0, 5: 0.0}), Vec({0, 1, 2, 3, 4, 5},{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}))
    True
    '''

    UV = coldict2mat(U_basis + V_basis)
    W  = solve(UV, w)

    U  = coldict2mat(U_basis)
    V  = coldict2mat(V_basis)
    
    Wu = Vec(set(range(len(U_basis))),{x: W[x]                for x in range(len(U_basis))})
    Wv = Vec(set(range(len(V_basis))),{x: W[len(U_basis) + x] for x in range(len(V_basis))})
    
    u = U * Wu
    v = V * Wv
    
    return (u,v) 
Example #25
0
def QR_solve(A, b):
    '''
    Input:
        - A: a Mat
        - b: a Vec
    Output:
        - vector x that minimizes norm(b - A*x)
    Example:
        >>> domain = ({'a','b','c'},{'A','B'})
        >>> A = Mat(domain,{('a','A'):-1, ('a','B'):2,('b','A'):5, ('b','B'):3,('c','A'):1,('c','B'):-2})
        >>> Q, R = QR.factor(A)
        >>> b = Vec(domain[0], {'a': 1, 'b': -1})
        >>> x = QR_solve(A, b)
        >>> result = A.transpose()*(b-A*x)
        >>> result * result < 1E-10
        True

I used the following as args to triangular_solve() and the grader was happy:
rowlist = mat2rowdict(R) (mentioned in the pdf)
label_list = sorted(A.D[1], key=repr) (mentioned in the pdf)
b = c vector b = Vec(domain[0], {'a': 1, 'b': -1})(mentioned above and on slide 1 of orthogonalization 8)        
    '''

    Q, R = QR.factor(A)
    rowlist = mat2rowdict(R)
    label_list = sorted(A.D[1], key = repr)
    return solve(A,b)
def direct_sum_decompose(U_basis, V_basis, w):
    '''
    input:  A list of Vecs, U_basis, containing a basis for a vector space, U.
    A list of Vecs, V_basis, containing a basis for a vector space, V.
    A Vec, w, that belongs to the direct sum of these spaces.
    output: A pair, (u, v), such that u+v=w and u is an element of U and
    v is an element of V.
    
    >>> U_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 1, 2: 0, 3: 0, 4: 6, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 11, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 3, 1: 1.5, 2: 0, 3: 0, 4: 7.5, 5: 0})]
    >>> V_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 7, 3: 0, 4: 0, 5: 1}), Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 15, 3: 0, 4: 0, 5: 2})]
    >>> w = Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0})
    >>> direct_sum_decompose(U_basis, V_basis, w) == (Vec({0, 1, 2, 3, 4, 5},{0: 2.0, 1: 4.999999999999972, 2: 0.0, 3: 0.0, 4: 1.0, 5: 0.0}), Vec({0, 1, 2, 3, 4, 5},{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}))
    True
    '''
    sum_base = U_basis + V_basis
    # find coefficients
    composed_result = solve(coldict2mat(sum_base),w)
    # calculate u
    u = Vec(U_basis[0].D,{})
    for i in range(len(U_basis)):
        u += composed_result[i] * U_basis[i]
    # calculate v
    v = Vec(V_basis[0].D,{})
    for i in range(len(U_basis), len(sum_base)):
        v += composed_result[i] * V_basis[i-len(U_basis)]
    return (u,v)  
Example #27
0
def exchange(S, A, z):
    '''
    Input:
        - S: a list of vectors, as instances of your Vec class
        - A: a list of vectors, each of which are in S, with len(A) < len(S)
        - z: an instance of Vec such that A+[z] is linearly independent
    Output: a vector w in S but not in A such that Span S = Span ({z} U S - {w})
    Example:
        >>> S = [list2vec(v) for v in [[0,0,5,3],[2,0,1,3],[0,0,1,0],[1,2,3,4]]]
        >>> A = [list2vec(v) for v in [[0,0,5,3],[2,0,1,3]]]
        >>> z = list2vec([0,2,1,1])
        >>> exchange(S, A, z) == Vec({0, 1, 2, 3},{0: 0, 1: 0, 2: 1, 3: 0})
        True
    '''
    for i in range(len(S)):
        w = S[i]
        if w not in A:
            tmpL = list(S)
            tmpV = tmpL.pop(i)
            tmpL.insert(i,z)
            tmpMat = coldict2mat(tmpL)
            sol = solve(tmpMat,tmpV)
            residual = tmpV - tmpMat * sol
            if residual * residual < 1.0e-14:
                return w
    return None
Example #28
0
def is_superfluous(L, i):
    '''
Input:
- L: list of vectors as instances of Vec class
- i: integer in range(len(L))
Output:
True if the span of the vectors of L is the same
as the span of the vectors of L, excluding L[i].

False otherwise.
Examples:
>>> a0 = Vec({'a','b','c','d'}, {'a':1})
>>> a1 = Vec({'a','b','c','d'}, {'b':1})
>>> a2 = Vec({'a','b','c','d'}, {'c':1})
>>> a3 = Vec({'a','b','c','d'}, {'a':1,'c':3})
>>> is_superfluous(L, 3)
True
>>> is_superfluous([a0,a1,a2,a3], 3)
True
>>> is_superfluous([a0,a1,a2,a3], 0)
True
>>> is_superfluous([a0,a1,a2,a3], 1)
False
'''
    if len(L) > 1:
        A = coldict2mat(L[:i] + L[i + 1:])
        v = solve(A, L[i])
        r = L[i] - A * v
        if r * r < 10 ** -14:
            return True
    return False
Example #29
0
def direct_sum_decompose(U_basis, V_basis, w):
    '''
    input:  A list of Vecs, U_basis, containing a basis for a vector space, U.
    A list of Vecs, V_basis, containing a basis for a vector space, V.
    A Vec, w, that belongs to the direct sum of these spaces.
    output: A pair, (u, v), such that u+v=w and u is an element of U and
    v is an element of V.
    
    >>> U_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 1, 2: 0, 3: 0, 4: 6, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 11, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0}), Vec({0, 1, 2, 3, 4, 5},{0: 3, 1: 1.5, 2: 0, 3: 0, 4: 7.5, 5: 0})]
    >>> V_basis = [Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 7, 3: 0, 4: 0, 5: 1}), Vec({0, 1, 2, 3, 4, 5},{0: 0, 1: 0, 2: 15, 3: 0, 4: 0, 5: 2})]
    >>> w = Vec({0, 1, 2, 3, 4, 5},{0: 2, 1: 5, 2: 0, 3: 0, 4: 1, 5: 0})
    >>> direct_sum_decompose(U_basis, V_basis, w) == (Vec({0, 1, 2, 3, 4, 5},{0: 2.0, 1: 4.999999999999972, 2: 0.0, 3: 0.0, 4: 1.0, 5: 0.0}), Vec({0, 1, 2, 3, 4, 5},{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}))
    True
    '''
    combined = U_basis + V_basis
    separation_boundary = len(U_basis)
    soln = solve(coldict2mat(combined), w)

    u = Vec(w.D, {})
    v = Vec(w.D, {})

    for key, val in soln.f.items():
        if key < separation_boundary:
            u += val * U_basis[key]
        else:
            v += val * combined[key]

    return (u, v)
def timeitWithPre():
	import solver
	import GenerateChars
	chars = GenerateChars.generate()
	chars = ['i', 'u', 'e', 'z', 't', 'w', 'd', 'j', 'u']
	wordmap = solver.preprocessing()
	result = solver.solve(wordmap, chars)	
def client_thread(conn):
    while True:  # infinite loop only necessary for telnet client
        # Receiving from client
        data = []
        while not (ord('\n') in data or ord('\r') in data):
            try:
                a = conn.recv(1024).upper()
                if len(a) == 0:
                    conn.close()
                    print('Connection closed', flush=True)
                    return
            except:
                print('Connection closed', flush=True)
                conn.close()
                return
            for i in range(len(a)):
                if a[i] in [ord('\n'), ord('\r'), ord('G'), ord('E'), ord('T'),  ord('U'), ord('R'), ord('F'), ord('D'),
                            ord('L'), ord('B')]:
                    data.append(a[i])
        if data[0] == ord('X'):
            break
        defstr = ''.join(chr(i) for i in data if chr(i) > chr(32))
        qpos = defstr.find('GET')
        if qpos >= 0:  # in this case we suppose the client is a webbrowser
            defstr = defstr[qpos+3:qpos+27]
            reply = 'HTTP/1.1 200 OK' + '\n\n' + '<html><head><title>Answer from Cubesolver</title></head><body>' + '\n'
            maneuverlist = solver.solve(defstr).split('\r\n')
            for m in maneuverlist:
                reply += m +'<br>\n'
            reply += '</body></html>\n'
            conn.sendall(reply.encode())
            conn.close()
        else:  # other client, for example the GUI client or telnet
            reply = (solver.solve(defstr)+'\n').encode()
            print(defstr)
            try:
                conn.sendall(reply)
            except:
                print('Error while sending data. Connection closed', flush=True)
                conn.close()
                return
    conn.close()
Example #32
0
def generateSudoku(diff):
    new_Sudoku = copy.deepcopy(blank_board)

    # Create a random valid filled Sudoku
    random_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    random.shuffle(random_list)
    for i in range(9):
        new_Sudoku[i][random.randrange(9)] = random_list[i]
    solver.solve(new_Sudoku)

    # Replace cells with 0 according to difficulty
    counter = 0
    while counter < difficulty[diff]:
        a = random.randrange(9)
        b = random.randrange(9)
        if new_Sudoku[a][b] != 0:
            new_Sudoku[a][b] = 0
            counter += 1

    return new_Sudoku
Example #33
0
def matrix_inverse(M):
	L = []
	if is_invertible(M):
		print('yayyy')
		for e in M.D[0]:
			w = [0]*len(M.D[0])
			w[e] = one
			w = list2vec(w)
			L.append(solve(M,w))
	#print(L)
	return coldict2mat(L)
Example #34
0
def find_matrix_inverse(A):
    if (not is_invertible(A)):
        raise ValueError("Non Invertible Matrix")

    cols = []
    for i in A.D[1]:
        cols.append(solve(A, Vec(A.D[1], {i: 1})))

    res = coldict2mat(cols)
    print(res * A)
    return res
Example #35
0
def verify_unsat():
    for filename in listdir(UNSAT_TESTS_PATH):
        rel_path = path.join(UNSAT_TESTS_PATH, filename)
        variables, formula = read_input(rel_path)

        assignment = solve(variables, formula)
        if assignment is not None:
            raise ValueError(
                f"UNSAT file {filename} had a non-None assignment")

    print("UNSAT examples were all verified to be UNSAT")
Example #36
0
def find_matrix_inverse(A):
    '''
    input: An invertible matrix, A, over GF(2)
    output: Inverse of A

    >>> M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (1, 2): 0, (0, 0): 0, (2, 0): 0, (1, 0): one, (2, 2): one, (0, 2): 0, (2, 1): 0, (1, 1): 0})
    >>> find_matrix_inverse(M) == Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (2, 0): 0, (0, 0): 0, (2, 2): one, (1, 0): one, (1, 2): 0, (1, 1): 0, (2, 1): 0, (0, 2): 0})
    True
    '''
    ret = [solve(A, Vec(A.D[0], {i: one})) for i in A.D[0]]
    return coldict2mat(ret)
Example #37
0
def main():
    limit = int(os.environ['LIMIT']) if 'LIMIT' in os.environ else None

    xtc_dir = os.environ['DATA_DIR']
    ds = DataSource(exp='xpptut13',
                    run=1,
                    dir=xtc_dir,
                    max_events=limit,
                    det_name='xppcspad')

    n_runs = 0
    for run in ds.runs():
        # FIXME: must epoch launch
        data_collector.load_run_data(run)
        # Right now, we assume one run or a serie of runs with the same
        # experimental configuration.

        n_runs += 1

    solver.solve(n_runs)
Example #38
0
def solve_control(x, t, I, X=None):
    if X is None:
        X = cutoff(x, a=1, b=2)

    u = solve(x, t, I=I)
    v = X * u
    v = v[::-1] # flip because v(x, t) = X(x) * u(x, T-t)

    dx = x[1] - x[0]
    dt = t[1] - t[0]
    return box(v, dx, dt)
Example #39
0
def test_board_solve_intersections():
    a = {1, 2, 3}
    b = {2, 3}
    z = set()

    brd = sudoku.Board.from_array([
        [b, b, z, z, z, z, z, z, z],
        [b, a, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
    ])

    solver.solve(brd, strategies={solver.intersections})

    assert set(next(iter(brd.get(row=1, col=1)))) == a - b
Example #40
0
def option_solve(filename):
    board = fman.read(argv[2])
    bprint.draw_board(board)
    t1 = time.time()
    if not solver.validate(board):
        print 'Invalid board. No solutions.'
    elif solver.solve(board):
        bprint.draw_board(board)
    else:
        print 'Found no solutions for this board.'
    print_time(t1)
Example #41
0
def solve():
    """Connect to the server and return the solving maneuver."""
    display.delete(1.0, END)  # clear output window
    try:
        defstr = get_definition_string()
    except:
        show_text('Invalid facelet configuration.\nWrong or missing colors.')
        return
    show_text(defstr + '\n')
    show_text('\n')
    show_text(solver.solve(defstr, 20, 2))
Example #42
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:
        import solver
        return solver.solve(pols)
    else:
        return []
Example #43
0
def auto_solve(window, board):
    board.update_model()

    if solve(board.model):
        for i in range(board.rows):
            for j in range(board.cols):
                board.cubes[i][j].value = board.model[i][j]
                board.auto = True
        return True
    else:
        return False
Example #44
0
    def __init__(self, custom_file=None, trace_mod=False):
        super().__init__()    
        if trace_mod:
            print("Initializing the app window")
        
        # If custom file is not specified, use puzzle scraper to gather data from NYT Mini Crossword webpage
        if custom_file is None:
            ps = PuzzleScraper(trace_mod=trace_mod)
            ps.click_button()
            grid = ps.get_grid()
            across, down = ps.get_clues()
            grid_numbers = ps.get_grid_numbers()
            ps.reveal_puzzle()
            answer = ps.extract_answers()
            time.sleep(3.5)
            ps.close_driver()
            official_sol = {
                "grid": grid,
                "across": across,
                "down": down,
                "grid_numbers": grid_numbers,
                "answer": answer
            }
            
            our_answer = solve(grid, across, down, grid_numbers, trace_mod=trace_mod)
            self.central_widget = MainWidget(official_sol, our_answer, trace_mod=trace_mod)
        
        # Use data from given .json file in PuzzleDatabases folder
        else:
            json_file = open("./PuzzleDatabases/" + custom_file + ".json", 'r')
            data = json.load(json_file)
            date = data["date"]
            our_answer = solve(data["grid"], data["across"], data["down"], data["grid_numbers"], trace_mod)
            self.central_widget = MainWidget(data, our_answer, date=date)

        self.setCentralWidget(self.central_widget)
        self.setWindowTitle("PROMINI NYT Mini CrossWord Solver")
        self.setWindowIcon(QIcon('Resources/nytimes.png')) 
        self.setFixedSize(QSize(*APP_SIZE))
        self.setStyleSheet("background-color: white;") 
        self.center()
Example #45
0
def time_warp(meshF, meshC, E_0=None, K_0=None, seconds=1, timestep=1e-3):
    time_in_secs = 0
    E_i = solver.solve(meshF, meshC, E_0=E_0)
    some_epsilon = 2
    Vf = igl.eigen.MatrixXd()
    Ff = igl.eigen.MatrixXi()
    for i in range(int(seconds / timestep)):
        meshC.step()
        time_in_secs = timestep * i
        if (i % 100):
            #Check meshes and re-solve
            name = "checkmeshes/mesh@" + str(
                GV.Global_Youngs) + "E@" + str(time_in_secs) + "s.obj"
            igl.readOBJ(name, Vf, Ff)
            n = np.linalg.norm(meshC.get_embedded_mesh() -
                               np.delete(Vf, -1, 1))
            print("n", n, "DOF", meshC.nonDupSize, "elem",
                  len(meshC.activeElems))
            exit()
            if (n > some_epsilon):
                E_i = solver.solve(meshF, meshC, E_0=E_i)
Example #46
0
def test_board_solve_hidden_tuples():
    a = {2, 3}
    b = {4, 5, 6}
    c = {7, 8, 9}
    z = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    brd = sudoku.Board.from_array([
        [z, a, a, b, b, b, c, c, c],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
    ])

    solver.solve(brd, strategies={solver.hidden_tuples})

    assert set(next(iter(brd.get(row=0, col=0)))) == z - (a | b | c)
Example #47
0
        def button_resolution(
        ):  # Função para preencher cada quadrado do sudoku com os valores totais do sudoku proposto
            sudoku_grid_as_string = sudoku

            sudoku_queue = fetch_sudokus(sudoku_grid_as_string)

            for index, sudoku_grid in enumerate(sudoku_queue):
                solve(sudoku_grid, index, len(sudoku_queue))

            f_sudoku = value
            button_clear()
            for c in colunas:
                for l in range(1, 10):
                    canvas_id = eval(c + str(l)).create_text(25,
                                                             20,
                                                             anchor="nw")
                    eval(c + str(l)).itemconfig(canvas_id,
                                                text=f_sudoku[0],
                                                tag=(c + str(l)))
                    f_sudoku = f_sudoku[1:]
                    eval(c + str(l)).update()
Example #48
0
def find_triangular_matrix_inverse(A):
    '''
    input: An upper triangular Mat, A, with nonzero diagonal elements
    output: Inverse of A
    >>> A = listlist2mat([[1, .5, .2, 4],[0, 1, .3, .9],[0,0,1,.1],[0,0,0,1]])
    >>> find_triangular_matrix_inverse(A) == Mat(({0, 1, 2, 3}, {0, 1, 2, 3}), {(0, 1): -0.5, (1, 2): -0.3, (3, 2): 0.0, (0, 0): 1.0, (3, 3): 1.0, (3, 0): 0.0, (3, 1): 0.0, (2, 1): 0.0, (0, 2): -0.05000000000000002, (2, 0): 0.0, (1, 3): -0.87, (2, 3): -0.1, (2, 2): 1.0, (1, 0): 0.0, (0, 3): -3.545, (1, 1): 1.0})
    True
    '''
    D = A.D[0]
    I = Mat((D, D), {(d, d): 1 for d in D})
    target_cols = mat2coldict(I)
    return coldict2mat({d: solve(A, target_cols[d]) for d in target_cols})
Example #49
0
def find_matrix_inverse(A):
    '''
    input: An invertible matrix, A, over GF(2)
    output: Inverse of A

    >>> M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (1, 2): 0, (0, 0): 0, (2, 0): 0, (1, 0): one, (2, 2): one, (0, 2): 0, (2, 1): 0, (1, 1): 0})
    >>> find_matrix_inverse(M) == Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (2, 0): 0, (0, 0): 0, (2, 2): one, (1, 0): one, (1, 2): 0, (1, 1): 0, (2, 1): 0, (0, 2): 0})
    True
    '''
    solution = identity(A.D[0],one)
    solutionrowdict = mat2rowdict(solution)
    return coldict2mat({key:solve(A,vec) for key,vec in solutionrowdict.items()})
Example #50
0
 def __init__(self, board, board_width=600, board_height=700):
     self.board = board
     self.rows = len(board)
     self.cols = len(board[0])
     self.board_width = board_width
     self.board_height = board_height
     self.selected = None
     self.squares = [[
         Square(self.board[r][c], r, c, self.board_width)
         for c in range(self.cols)
     ] for r in range(self.rows)]
     self.solution = solver.solve(board)
Example #51
0
def find_matrix_inverse(A):
    '''
    input: An invertible matrix, A, over GF(2)
    output: Inverse of A

    >>> M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (1, 2): 0, (0, 0): 0, (2, 0): 0, (1, 0): one, (2, 2): one, (0, 2): 0, (2, 1): 0, (1, 1): 0})
    >>> find_matrix_inverse(M) == Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (2, 0): 0, (0, 0): 0, (2, 2): one, (1, 0): one, (1, 2): 0, (1, 1): 0, (2, 1): 0, (0, 2): 0})
    True
    '''

    R = mat2rowdict(identity(A.D[0], one))
    return coldict2mat([solve(A, R[i]) for i in range(len(R))])
Example #52
0
    def test_solve_output_type(self):
        solution = solver.solve(test_data.solved)

        self.assertEquals(len(solution), 9)
        self.assertIsInstance(solution, list)

        for line in solution:
            self.assertEquals(len(line), 9)
            self.assertIsInstance(line, list)

            for cell in line:
                self.assertIsInstance(cell, int)
 def test_95_hard_puzzles(self):
     """List of 95 difficult puzzles from http://magictour.free.fr."""
     total_time = 0
     with open(os.path.join(PUZZLE_DIR, '95_hard_sudoku.txt'), 'r') as f:
         for line in f:
             if len(line.strip()) == 81:
                 start = time.time()
                 self.assertEqual(
                     solver.validate_sudoku(solver.solve(line.strip())),
                     True)
                 total_time += (time.time() - start)
     print('Average (Hard): %s' % (total_time / 95))
Example #54
0
def lambda_handler(event, _context):

    grid = event['queryStringParameters']['data'] # now it's a string: '012345...'
    grid = list(map(int, grid)) # now it's 1d array

    solution = solve(grid)
    print(grid)
    print(solution)
    return {
        'statusCode': 200,
        'body': str(solution)
    }
Example #55
0
    def _act_solve(self):
        """Returns a solution of the puzzle if there is one or 'There are no solutions.' if no solutions exist, and
        tells the program to end.

        @type self: Controller
        @rtype: (str, bool)
        """
        solution = solve(self._puzzle)
        if solution is not None:
            return str(solution), True
        else:
            return 'There are no solutions.', True
Example #56
0
def find_triangular_matrix_inverse(A): 
    '''
    input: An upper triangular Mat, A, with nonzero diagonal elements
    output: Inverse of A
    >>> A = listlist2mat([[1, .5, .2, 4],[0, 1, .3, .9],[0,0,1,.1],[0,0,0,1]])
    >>> find_triangular_matrix_inverse(A) == Mat(({0, 1, 2, 3}, {0, 1, 2, 3}), {(0, 1): -0.5, (1, 2): -0.3, (3, 2): 0.0, (0, 0): 1.0, (3, 3): 1.0, (3, 0): 0.0, (3, 1): 0.0, (2, 1): 0.0, (0, 2): -0.05000000000000002, (2, 0): 0.0, (1, 3): -0.87, (2, 3): -0.1, (2, 2): 1.0, (1, 0): 0.0, (0, 3): -3.545, (1, 1): 1.0})
    True
    '''
    I = identity(A.D[0], 1)
    #B = coldict2mat({key:triangular_solve(A,value) for key, value in mat2coldict(I).items()})
    B = coldict2mat({key:solve(A,value) for key, value in mat2coldict(I).items()})
    return B
Example #57
0
def benchmark_from_file(file_path):
    i = 0

    with open(file_path, 'r') as f:
        for line in f.readlines():
            line = line.strip()
            if len(line) == 81:
                i += 1
                start = time.time()
                solution = solver.solve(line)
                elapsed = time.time() - start
                yield i, solution, elapsed
Example #58
0
def find_matrix_inverse(A):
    '''
    input: An invertible matrix, A, over GF(2)
    output: Inverse of A

    >>> M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (1, 2): 0, (0, 0): 0, (2, 0): 0, (1, 0): one, (2, 2): one, (0, 2): 0, (2, 1): 0, (1, 1): 0})
    >>> find_matrix_inverse(M) == Mat(({0, 1, 2}, {0, 1, 2}), {(0, 1): one, (2, 0): 0, (0, 0): 0, (2, 2): one, (1, 0): one, (1, 2): 0, (1, 1): 0, (2, 1): 0, (0, 2): 0})
    True
    '''
    I = identity(A.D[0], one)
    B = coldict2mat({key:solve(A,value) for key, value in mat2coldict(I).items()})
    return B
Example #59
0
def test_board_solve_swordfish():
    a = {1, 2, 3, 4}
    b = {1, 2, 3}
    z = set()

    brd = sudoku.Board.from_array([
        [z, z, z, z, z, z, z, a, z],
        [z, b, z, z, b, z, z, b, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, b, z, z, b, z, z, b, z],
        [z, z, z, z, a, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, b, z, z, b, z, z, b, z],
        [z, a, z, z, z, z, z, z, z],
    ])

    solver.solve(brd, strategies={solver.swordfish})

    assert set(next(iter(brd.get(row=8, col=1)))) == a - b
    assert set(next(iter(brd.get(row=5, col=4)))) == a - b
    assert set(next(iter(brd.get(row=0, col=7)))) == a - b

    brd = sudoku.Board.from_array([
        [z, z, z, z, z, z, z, a, z],
        [z, b, z, z, z, z, z, b, z],
        [z, z, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, b, z, z, b, z, z, b, z],
        [z, a, z, z, z, z, z, z, z],
        [z, z, z, z, z, z, z, z, z],
        [z, b, z, z, b, z, z, z, z],
        [z, z, z, z, a, z, z, z, z],
    ])

    solver.solve(brd, strategies={solver.swordfish})

    assert set(next(iter(brd.get(row=5, col=1)))) == a - b
    assert set(next(iter(brd.get(row=8, col=4)))) == a - b
    assert set(next(iter(brd.get(row=0, col=7)))) == a - b
    def test_easy_puzzles(self):
        """Specific test cases used in development or that are otherwise uniquely interesting."""
        # Easy puzzle
        puzzle1 = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
        self.assertTrue(solver.validate_sudoku(solver.solve(puzzle1)))

        # Hard puzzle (requires brute-force search)
        puzzle2 = '4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'
        self.assertTrue(solver.validate_sudoku(solver.solve(puzzle2)))

        # Arto Inkala's 2006 Tough Sodokou
        puzzle3 = '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.'
        self.assertTrue(solver.validate_sudoku(solver.solve(puzzle3)))

        # Arto Inkala's 2010 "Toughest Sudoku"
        puzzle4 = '..53.....8......2..7..1.5..4....53...1..7...6..32...8..6.5....9..4....3......97..'
        solved4 = solver.solve(puzzle4)
        self.assertTrue(solver.validate_sudoku(solved4))

        # Arto Inkala's 2012 "Even Tougher Sudoku"
        puzzle5 = '8..........36......7..9.2...5...7.......457.....1...3...1....68..85...1..9....4..'
        solved5 = solver.solve(puzzle5)
        self.assertTrue(solver.validate_sudoku(solved5))

        # Difficult for backtracking brute force algorithms
        puzzle6 = '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9'
        solved6 = solver.solve(puzzle6)
        self.assertTrue(solver.validate_sudoku(solved6))