def test_lu_for_ints(self):
        rand_int_matrix = np.random.randint(-1000, 1000, size=(1000, 1000))
        rand_int_col = np.random.randint(-1000, 1000, size=(1000, 1))
        sp_solve2 = sp.solve(rand_int_matrix, rand_int_col)

        assert_array_almost_equal(sp_solve2, solve.solve(rand_int_matrix, rand_int_col, 1), decimal=9)
        assert_array_almost_equal(sp_solve2, solve.solve(rand_int_matrix, rand_int_col, 2), decimal=9)
        assert_array_almost_equal(sp_solve2, solve.solve(rand_int_matrix, rand_int_col, 3), decimal=9)
Beispiel #2
0
def anneal(h, J, g0, steps=50):
    '''Get ground state configuration of a circuit specified by h and J for
    gammas values from g_max to g_min'''

    time = np.linspace(0, 1, steps)
    spectrum = []
    ground = []
    excited = []
    for i in xrange(0, steps):
        fact = (i+1)*1./(steps+1)
        gamma = g0*(1-fact)
        if DUAL:
            _h, _J = fact*h, fact*J
        else:
            _h, _J = h, J
        gs, es, spec, sols = solve(_h, _J, gamma=gamma, full_output=True,
                                   minimal=False, exact=False)
        spectrum.append(np.array(spec[0::]))
        ground.append(np.abs(np.array(sols['eigsh']['vecs'][:, 0])))
        excited.append(np.abs(np.array(sols['eigsh']['vecs'][:, 1])))

    spectrum = np.array(spectrum)
    ground = np.array(ground)
    excited = np.array(excited)
    
    # identify ground state components
#    echo_comp(ground[int(.8*steps)])
#    echo_comp(excited[int(.8*steps)])
#    echo_comp(excited[int(.9*steps)])

    plt.figure('Spectrum')
    plt.clf()
    plt.plot(time, spectrum, linewidth=2)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Energy', fontsize=FS)
    plt.title('Low Energy Spectrum', fontsize=FS)
    plt.show(block=False)
    if SAVE:
        plt.savefig(ROOT+'spec.eps', bbox_inches='tight')

    plt.figure('Ground State Configuration')
    plt.clf()
    plt.plot(time, np.power(ground, 2), linewidth=2)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Basis state probabilities', fontsize=FS)
    plt.title('Ground state configuration', fontsize=FS)
    plt.show()
    if SAVE:
        plt.savefig(ROOT+'gr.eps', bbox_inches='tight')

    if True:
        plt.figure('Excited State Configuration')
        plt.clf()
        plt.plot(time, np.power(excited, 2), linewidth=2)
        plt.xlabel('Time', fontsize=FS)
        plt.ylabel('Basis state probabilities', fontsize=FS)
        plt.title('Excited State Configuration', fontsize=FS)
        plt.show()
        if SAVE:
            plt.savefig(ROOT+'ex.eps', bbox_inches='tight')
Beispiel #3
0
def b4click(event):
	global li1
	global li2
	f = open("puzzle.txt", "wb")
	#check for validity
	categories = categoriesList()
	topinfo = topInfo(categories)
	if topinfo == None:
		return
	#start building the list of items
	ls = [topinfo]
	#add all the category information
	for c in categories:
		ls.extend(c)
	#add all the relation information
	ls.extend(list(li2.get(0, END)))
	#save the file
	for l in ls:
		f.write(bytes(l + "\n", "UTF-8"))
	print("Saving to puzzle.txt")
	f.close()
	#solve the puzzle and print it
	print("Solving the puzzle")
	answer = sortedAnswer(list(solve(parse_file("puzzle.txt"))))
	#show the answer in a window
	response = Tk()
	#make a grid with each row being the entity
	for row in answer:
		r = Frame(response)
		r.pack()
		#each item belonging to the entity
		for item in row:
			l = Label(r, text=item + "\t", width=12)
			l.pack(side=LEFT)
	response.mainloop()
def main():
    for index, test in enumerate(get_tests()):
        array, target_sum = test
        print(
            "Test %d\nFor array %s\nSum %d\nPair found: %s\n\n" %
            (index, array.__repr__(), target_sum, solve(array, target_sum).__repr__())
        )
Beispiel #5
0
def main():
    args = docopt.docopt(__doc__)
    data = read_data(args['<in>'])
    score, result = solve(data)
    print(score)
    score2, result2 = optimize(result, data)
    print(score2)
    format_solution(args['<out>'], result2, prefix=str(score))
Beispiel #6
0
def main():
    board = [None for _ in range(64)]
    regs = {}
    read_regions(sys.stdin, regs)
    read_board(sys.stdin, regs)
    lregs = invert_regions(build_regions(regs))
    #list(map(print, enumerate(lregs)))
    for sol in solve(board, lregs):
        print_board(sol)
Beispiel #7
0
def main(lines):
    # for i, v in enumerate(lines):
    #     print("line[{0}]: {1}".format(i, v))

    H, W = map(int, lines[0].split())
    S = [list(l) for l in lines[1:-1]]
    T = lines[-1]
    ans = solve(H, W, S, T)
    print(ans)
Beispiel #8
0
def test_solve():
    arr = ['Begin on 3rd Blvd', 'Right on First Road', 'Left on 9th Dr']
    rev = ['Begin on 9th Dr', 'Right on First Road', 'Left on 3rd Blvd']
    assert solve(arr) == rev

    arr = [
        "Begin on Road A", "Right on Road B", "Right on Road C",
        "Left on Road D"
    ]
    rev = [
        'Begin on Road D', 'Right on Road C', 'Left on Road B',
        'Left on Road A'
    ]
    assert solve(arr) == rev

    arr = ["Begin on Road A"]
    rev = ["Begin on Road A"]
    assert solve(arr) == rev
Beispiel #9
0
def test_solve():
    assert solve("aaab") is False
    assert solve("abcabc") is False
    assert solve("4455") is True
    assert solve("zazcbaabc") is True
    assert solve("223456776543") is True
    assert solve("432612345665") is False
    assert solve("qponmlkjihgfeeiefghijklmnopqrsttsr") is False
Beispiel #10
0
def test_solve():
    assert solve("codewarriors") == 2
    assert solve("suoidea") == 3
    assert solve("ultrarevolutionariees") == 3
    assert solve("strengthlessnesses") == 1
    assert solve("cuboideonavicuare") == 2
    assert solve("chrononhotonthuooaos") == 5
    assert solve("iiihoovaeaaaoougjyaw") == 8
Beispiel #11
0
    def test_my_answer(self):
        for i in range(233):
            length = random.randint(1, 10**3)
            a_list = str()
            for j in range(length):
                a_list += "{} ".format(random.randint(0, 10**4))

            right_answer = "{} {}".format(*right(length, a_list))
            my_answer = solve(length, a_list)
            self.assertEqual(right_answer, my_answer)
Beispiel #12
0
def rfileext():
    pygame.quit()
    inputFile = input("Masukkan nama file input! ")
    outputFile = input("Masukkan nama file output! ")
    orig_stdout = sys.stdout
    orig_stdin = sys.stdin
    fin = open(inputFile, 'r')
    fout = open(outputFile, 'w')
    sys.stdin = fin
    sys.stdout = fout
    a, b, c, d = map(int, input().split())
    card = [a, b, c, d]
    solve(card)
    sys.stdout = orig_stdout
    sys.stdin = orig_stdin
    print("file telah di save di ", outputFile)
    fin.close()
    fout.close()
    quit()
def main():
    #fetching the sudoku
    path = os.path.abspath("sudoku.json")

    with open(path) as data_:
        data = json.load(data_)

    sudoku = data['sudoku']

    # validate the sudoku
    validation = (validate.run(sudoku)).Validate()
    if validation is False:
        print("Sudoku is invalid.")
    else:
        print("Sudoku valid. Solved:")
        solve.solve(sudoku)
        for list_ in sudoku:
            print(list_)
        return
def main():
    random.seed(int(sys.argv[-1]))
    n = int(cmdlinearg("n"))
    m = int(cmdlinearg("m"))
    onlyForward = cmdlinearg("onlyForward")=="True"
    
    g = random.randint(1,1e2)
    MAX_SPEED = 1e2

    band = []

    for i in range(n):
        a=0
        b=0
        while True:
            a = random.randint(0,m-1)
            b = random.randint(0,m-1)
            if a!=b:
                break
        band.append([min(a,b),max(a,b),random.randint(1,MAX_SPEED)])

    if onlyForward:


        dn = 1
        up = len(band)

        while dn+1<up:#binärsök efter minsta antalet band att ta bort så att det räcker att bara gå framåt
            mid = (dn+up)//2
            if solve(n,m,g,band[:mid],onlyForward=True)==solve(n,m,g,band[:mid]):
                dn = mid
            else:
                up = mid
        band = band[:dn]
        #assert(solve(n,m,g,band,onlyForward=True)==solve(n,m,g,band))

        #assert(solve(n,m,g,band,onlyForward=True)==solve(n,m,g,band))

    random.shuffle(band)
    print(len(band),m,g)
    for b in band:
        print(b[0]+1,b[1]+1,b[2])
Beispiel #15
0
def main():
    test_index = 1

    for array, rotations, element in get_tests():
        array = list(set(array))
        array.sort()
        array = rotate(array, rotations)

        print("Test %d: Array: %s\nSearching for %d\nFound at index %d\n\n" %
              (test_index, array.__repr__(), element, solve(array, element)))
        test_index += 1
def makeSamples(size):
    fixed_sample_0 = torch.zeros(1, 1, size, size)
    setBoundaries(fixed_sample_0, 100, 100, 0, 0)
    fixed_sample_0 = Variable(fixed_sample_0).cuda()

    fixed_sample_1 = torch.zeros(1, 1, size, size)
    setBoundaries(fixed_sample_1, 100, 100, 100, 100)
    fixed_sample_1 = Variable(fixed_sample_1).cuda()

    boundary = np.zeros((1, 1, size, size), dtype=np.bool)
    setBoundaries(boundary, 1, 1, 1, 1)

    fixed_solution_0 = solve(fixed_sample_0.cpu().data.numpy()[0, 0, :, :],
                             np.squeeze(boundary),
                             tol=1e-5)
    fixed_solution_1 = solve(fixed_sample_1.cpu().data.numpy()[0, 0, :, :],
                             np.squeeze(boundary),
                             tol=1e-5)

    return fixed_sample_0, fixed_solution_0, fixed_sample_1, fixed_solution_1
Beispiel #17
0
def main():
    parser = argparse.ArgumentParser(description='Nonogram runner')
    parser.add_argument('constraints_file', type=str,
                    help='.npy file containing constraints')
    args = parser.parse_args()
    nono = Nonogram(args.constraints_file)
    solution = solve(nono.constraints)
    if nono.isValidSolution(solution):
        print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
    else:
        print('\x1b[3;30;41m' + 'Failure.' + '\x1b[0m')
Beispiel #18
0
    def test_solve(self):
        test_data = "220422197205148440"
        right_answer = False
        my_answer = solve(test_data)
        self.assertEqual(right_answer, my_answer)

        test_data = "654201199306252458"
        right_answer = True
        my_answer = solve(test_data)
        self.assertEqual(right_answer, my_answer)

        test_data = "440407198504173971"
        right_answer = True
        my_answer = solve(test_data)
        self.assertEqual(right_answer, my_answer)

        test_data = "51312419920924287X"
        right_answer = True
        my_answer = solve(test_data)
        self.assertEqual(right_answer, my_answer)
Beispiel #19
0
def average_100(number):
    moves_no = []
    sln_moves = []
    demo_cube = cube.Cube()
    for i in range(100):
        demo_cube.scramble(int(number))
        sln_moves = solve.solve(demo_cube)
        moves_no.append(len(sln_moves))
    total = sum(moves_no)
    print("average number of moves used over 100 runs is: {}".format(total /
                                                                     100))
Beispiel #20
0
    def run(self):
        """
        Call this method to run the model with current SAS specification, options, solute parameters, and timeseries dataframe. Results can then be accessed through the `.result` property of the model object
        :return: None
        """
        # water fluxes
        J = self.data_df[self.options['influx']].values
        Q = self.data_df[self._fluxorder].values
        sT_init = self.options['sT_init']
        timeseries_length = self._timeseries_length
        numflux = self._numflux
        #
        # SAS lookup table
        SAS_args, P_list, weights, component_type, nC_list, nC_total, nargs_list, nargs_total = self._create_sas_lookup()
        SAS_args = np.asfortranarray(SAS_args)
        P_list = np.asfortranarray(P_list)
        weights = np.asfortranarray(weights)
        #
        # Solutes
        C_J, mT_init, C_old, alpha, k1, C_eq = self._create_solute_inputs()
        numsol = self._numsol
        #
        # options
        dt = self.options['dt']
        verbose = self.options['verbose']
        debug = self.options['debug']
        warning = self.options['warning']
        jacobian = self.options['jacobian']
        n_substeps = self.options['n_substeps']
        max_age = self.options['max_age']

        # call the Fortran code
        fresult = solve(
            J, Q, SAS_args, P_list, weights,
            sT_init, dt, verbose, debug, warning, jacobian,
            mT_init, np.asfortranarray(C_J), np.asfortranarray(alpha), np.asfortranarray(k1),
            np.asfortranarray(C_eq), C_old,
            n_substeps, component_type, nC_list, nargs_list, numflux, numsol, max_age, timeseries_length, nC_total, nargs_total)
        sT, pQ, WaterBalance, mT, mQ, mR, C_Q, dsTdSj, dmTdSj, dCdSj, SoluteBalance = fresult

        if numsol > 0:
            self._result = {'C_Q': C_Q}
            for isol, sol in enumerate(self._solorder):
                for iflux, flux in enumerate(self._fluxorder):
                    colname = sol + ' --> ' + flux
                    self._data_df[colname] = C_Q[:, iflux, isol]
        else:
            self._result = {}
        self._result.update({'sT': np.moveaxis(sT, -1, 0), 'pQ': np.moveaxis(pQ, -1, 0),
                             'WaterBalance': np.moveaxis(WaterBalance, -1, 0), 'dsTdSj':np.moveaxis(dsTdSj, -1, 0)})
        if numsol > 0:
            self._result.update({'mT': np.moveaxis(mT, -1, 0), 'mQ': np.moveaxis(mQ, -1, 0), 'mR': np.moveaxis(mR, -1, 0),
            'SoluteBalance': np.moveaxis(SoluteBalance, -1, 0),
                                 'dmTdSj':np.moveaxis(dmTdSj, -1, 0), 'dCdSj':dCdSj})
Beispiel #21
0
def solve(board, regs, pos=0):
    #print_board(board)
    if pos == 64:
        yield board
    else:
        for i in range(1, 9):
            #print(i)
            board[pos] = i
            if all(r.isvalid(board) for r in regs[pos]):
                yield from solve(board, regs, pos + 1)
        board[pos] = None
def test_unsolvables():
    test_paths = glob.glob(
        os.path.join(os.path.dirname(__file__), 'unsolvable/test??'))
    for test_path in test_paths:
        with open(test_path) as f:
            test = parse_state(f)

        check = lambda: nose.tools.assert_equals(solve(test), None)
        check.description = 'unsolvable/' + test_path.split('/')[-1]

        yield check
Beispiel #23
0
def main(file):
    """ The file handler. Reads all input files and passes the string to
    the solver. Write the solvers output string to the appropriate file.
    """
    with open(file[0], 'r') as inp, open(file[1], 'w') as out:
        # Call appropriate solver
        out_str = solve.solve(inp)
        # Copy string data to solver
        data = inp.read()
        # Create output file
        out.write(out_str)
        print(f'DONE: {file[0]}, SCORE: {score.score(data, out_str)}')
Beispiel #24
0
def main():
	if (len(sys.argv) != 4):
		error.error('python main.py [file] -h [0|1|2]')
	if (not isInt(sys.argv[3])):
		error.error('python main.py [file] -h [0|1|2]')
	sys.argv[3] = int(sys.argv[3])
	if (sys.argv[2] != '-h' or sys.argv[3] < 0 or sys.argv[3] > 2):
		error.error('python main.py [file] -h [0|1|2]')
	filename = sys.argv[1]
	content = ''
	try:
		f = open(filename, 'r')
		content = f.read()
		f.close()
	except:
		error.error('error opening file')
	content = cleanContent(content)
	puzzle = checkContent(content)
	goal = getGoalState(len(puzzle))
	checkSolvable(puzzle, goal)
	solve.solve(puzzle, goal)
Beispiel #25
0
def predict():

    content = request.get_json()
    target_cube = turn(content)
    if type(target_cube) == "str":
        return json.dumps([False, "Invalid input"])
    if target_cube.is_valid() == False:
        return json.dumps([False, "Invalid input"])

    is_solved, actions = solve(target_cube)
    results = [is_solved, actions]

    return json.dumps(results)
Beispiel #26
0
def main():
    while True:
        image = ImageGrab.grab(bbox = (left, upper, right, lower))
        tesstr = pytesseract.image_to_string( 
                    cv2.cvtColor(nm.array(image), cv2.COLOR_BGR2GRAY),  
                    lang ='eng') 
        if "Quick!" in tesstr:
            print(tesstr)
            prompt = "".join(char for char in detect_prompt(tesstr).lower() if char.isalpha())
            print(prompt)
            solution = solve.solve(prompt)
            time.sleep(delay)
            enter_solution(solution)
Beispiel #27
0
def do(data,stage):
    st = time.perf_counter()
    im = base64.decodebytes(data.encode())
    try:
        os.makedirs(base+("/temp/%d"%stage))
    except:
        pass
    name = base+"/temp/%d/%s.bmp" %(stage,''.join(random.choices(string.ascii_lowercase,k=10)))
    with open(name, "wb") as f:
        f.write(im)
    sol = solve.solve(name)
    #print((time.perf_counter()-st))
    return sol
Beispiel #28
0
    def place(self, val):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set(val)
            self.update_model()

            if valid(self.model, val, (row,col)) and solve(self.model):
                return True
            else:
                self.cubes[row][col].set(0)
                self.cubes[row][col].set_temp(0)
                self.update_model()
                return False
def runTest(net):
    files = glob(opt.experiment + "/*.pth")
    maximum = 0
    for file in files:
        maximum = max(int(file.split("_")[-1].split(".")[0]), maximum)
    file = glob(opt.experiment + "/*" + str(maximum) + ".pth")[0]
    print(file)

    state_dict = torch.load(file)
    # state_dict = torch.load(file, map_location=lambda storage, loc: storage.cuda(1))
    net.load_state_dict(state_dict)

    physical_loss = PhysicalLoss()

    boundary = np.zeros((opt.image_size, opt.image_size), dtype=np.bool)
    boundary[0, :] = True
    boundary[-1, :] = True
    boundary[:, 0] = True
    boundary[:, -1] = True

    data = torch.zeros(1, 1, opt.image_size, opt.image_size)
    error = []
    for i in range(opt.num_test):
        data[:, :, :, 0] = np.random.uniform(100)
        data[:, :, 0, :] = np.random.uniform(100)
        data[:, :, :, -1] = np.random.uniform(100)
        data[:, :, -1, :] = np.random.uniform(100)

        solution = solve(data.cpu().numpy()[0, 0, :, :], boundary, tol=1e-5)

        img = Variable(data).type(dtype)
        output = net(img)
        loss = physical_loss(output)

        output = output.cpu().data.numpy()[0, 0, :, :]

        error.append(np.mean(np.abs(output - solution)))
        print("%d Error: %.2f, Loss: %.2f" % (i, error[-1], loss.data[0]))

        # Plot
        imgs_comb = np.hstack(
            (boundaryPlot(data.cpu().numpy()[0, 0, :, :]), solution, output))
        plt.imsave(fname='%s/test_%d.png' % (opt.experiment, i),
                   arr=imgs_comb,
                   vmin=0,
                   vmax=100,
                   cmap=plt.cm.jet)

    error = np.array(error)
    print("error: ", np.mean(error))
    print("std dev: ", np.std(error))
Beispiel #30
0
def shpol(problem):
    if "from" in problem and "to" in problem:
        indexoffrom = problem.find("from")
        indexofto = problem.find("to")
        polname = problem[5:indexoffrom].strip()
        a = solve.solve(problem[indexoffrom + 4:indexofto])
        if a.isError:
            return a
        if not a.isConstant():
            a.isError = True
            a.errorCode = 9
            return a
        b = solve.solve(problem[indexofto + 2:])
        if b.isError:
            return b
        if not b.isConstant():
            b.isError = True
            b.errorCode = 9
            return b
        for canvas in CanvasArray:
            if canvas.name == polname:
                canvas.show(a.coefArr[0], b.coefArr[0])
                return False
        ret = polynomial.polynomial()
        ret.isError = True
        ret.errorCode = 6
        ret.errorStatement = polname
        return ret
    polname = problem[5:].strip()
    for canvas in CanvasArray:
        if canvas.name == polname:
            canvas.show()
            return False
    ret = polynomial.polynomial()
    ret.isError = True
    ret.errorCode = 6
    ret.errorStatement = polname
    return ret
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-m",
                        "--method",
                        nargs='?',
                        const=factory.DefaultMethod,
                        default=factory.DefaultMethod,
                        choices=factory.MethodChoices)
    parser.add_argument("--priority-queue",
                        nargs='?',
                        const=None,
                        default=None,
                        choices=factory.PriorityQueueChoices,
                        help="only used by the astar and dijkstra methods")
    parser.add_argument("width")
    parser.add_argument("height")
    parser.add_argument("maze_file")
    parser.add_argument("result_file")
    parser.add_argument("generate_bmp", nargs='?', default='no')
    args = parser.parse_args()
    generate_bmp_bool = str2bool(args.generate_bmp)
    width = 0
    height = 0
    try:
        width = int(args.width)
    except:
        raise argparse.ArgumentTypeError('Width must be an integer.')
    try:
        height = int(args.height)
    except:
        raise argparse.ArgumentTypeError('Height must be an integer.')

    #print(width, height, args.output_file, generate_bmp_bool)
    generatemaze(width, height, args.maze_file, generate_bmp_bool)
    solve(args.maze_file + '.png', args.result_file + '.png', args.method,
          args.priority_queue)
def run(a, ansarea):

    #global ansarea
    commands = a.split("\n")
    ret = "\nrun started"
    for command in commands:

        if command == "" or command == " " or command.strip().replace(
                "\n", "") == "":
            continue
        #print("command:" + command + "ans : " + str(solve.solve(command)))
        a = solve.solve(command)
        if type(a) != type(False):
            if str(a).strip() != "":
                ret += '\n' + str(a)
    #ret+="\nrun ended"
    ansarea.insert(END, ret)
Beispiel #33
0
    def execute(self, board, pents):
        self.initialize(board, pents)

        pygame.init()
        self.displaySurface = pygame.display.set_mode(
            (self.windowWidth, self.windowHeight), pygame.HWSURFACE)
        self.displaySurface.fill((255, 255, 255))
        self.draw_board()
        pygame.display.flip()
        pygame.display.set_caption(self.windowTitle)

        sol_list = solve(board, pents, self)
        self.draw_solution_and_sleep(sol_list, 0)
        pygame.display.flip()

        if check_correctness(sol_list, board, pents):
            print("PASSED!")
        else:
            print("FAILED...")

        clock = pygame.time.Clock()
        clock = pygame.time.Clock()

        while self.running:
            pygame.event.pump()
            keys = pygame.key.get_pressed()
            clock.tick(self.fps)

            if (keys[K_ESCAPE]):
                raise SystemExit

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    raise SystemExit

        while self.running:
            pygame.event.pump()
            keys = pygame.key.get_pressed()
            clock.tick(self.fps)

            if (keys[K_ESCAPE]):
                raise SystemExit

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    raise SystemExit
def test(num_students, num_seminars):
    data = Data.factory(num_students, num_seminars)
    
    solution = solve.solve(data)[0]

    # Verify the class sizes
    print "Class sizes: "
    seminar_ctr = Counter()
    for decision in solution:
        seminar_ctr[decision[1]] += 1
    sorted_sems = sorted(seminar_ctr.items())
    for name, count in sorted_sems:
        print '%s: %d' % (name, count)

    print "\nAdded seminars (class: popularity):"
    num_extra = num_students % num_seminars
    popular_seminars = sorted(data.popular_seminars[0:num_extra])
    for idx, count in popular_seminars:
        print '%s: %d' % (data.year_list[idx], count)
Beispiel #35
0
def profile():
    for m in methods:
        for i in inputs:
            with tempfile.NamedTemporaryFile(suffix='.png') as tmp:
                solve(SolverFactory(), m, "examples/%s.png" % i, tmp.name)
Beispiel #36
0
def sweep_gamma(h, J, gmin, gmax, steps=2, show=True):
    '''Sweep gamma values for circuit (h, J) from gmin to gmax in the given
    number of steps.'''

    gammas = np.linspace(gmin, gmax, steps)

    egaps = []
    Es = []
    exact = len(h) < 8
    for i in xrange(len(gammas)):
        gamma = gammas[i]
        sys.stdout.write('\r{0:.1f} %'.format(100*i/len(gammas)))
        sys.stdout.flush()
        gs, es, spec = solve(h, J, gamma=gamma,
                             more=True, minimal=False, exact=exact)
        egaps.append([spec[i]-spec[0] for i in xrange(1, len(spec))])
        Es.append(spec)

    egaps = np.array(egaps)
    Es = np.array(Es)

    Y = egaps if SHOW_GAPS else Es

    # correct for crossings
    Y = correct_crossings(Y)

    if show:
        plt.figure('Gamma sweep: egaps')
        if SHOW_GAPS:
            plt.plot(gammas, Y, 'x', markersize=MS, markeredgewidth=MEW)
            plt.xlabel('$\gamma$', fontsize=GFS)
            plt.ylabel('$E_{gap}$/$J$', fontsize=GFS)
            plt.ylim([0, plt.ylim()[1]])
        else:
            plt.plot(gammas, Y, 'x', markersize=MS, markeredgewidth=MEW)
            plt.xlabel('$\gamma$', fontsize=GFS)
            plt.ylabel('$E$/$J$', fontsize=GFS)
        plt.tick_params(axis='both', which='major', labelsize=16)
        plt.show(block=False)

    # fitting
#    for i in range(Y.shape[1]):
#        try:
#            popt, func = hyper_fit(gammas, Y[:, i])
#            plt.plot(gammas, func(gammas), '--')
#        except:
#            print('Fit failed...')

    # analytical solutions
    if True:
        E_an, eps_k = check_fermion_model(Y, h)
        plt.plot(gammas, E_an, 'k-', linewidth=2)
    else:
        if SHOW_GAPS:
            ground = np.zeros(gammas.shape, dtype=float)
        else:
            ground = analytical_ground(len(h), gammas)
        for n in xrange(0, N+1):
            gaps = analytical_gaps(len(h), n, gammas)
            for gap in gaps:
                plt.plot(gammas, ground+gap, 'k-', linewidth=2)

    # save figure
    if SAVE:
        plt.savefig('../img/wire_sol_{0}.eps'.format(len(h)),
                    bbox_inches='tight')
    # force show with block
    if show:
        plt.show(block=True)
Beispiel #37
0
damping = grid.zeros()
#wp.cosh_damping( grid, x1=grid.a1, x2=grid.b1, y1=grid.a2, y2=grid.b2, xs=50.0, ys=50.0, amp=1.0E4 )


k1 = 0.01*2.0*pi
k2 = 0.01*2.0*pi

u0 = lambda x1,x2: cos(x1*k1+x2*k2) 
#*(1.0+(1.15*(x1-1500.0)/2000.0)**48)**-1 *(1.0+(1.4*(x2-450)/750.0)**48)**-1

time_step=0.001

u0 = grid.evaluate( u0 )
u0 = u0 * exp( -damping * time_step )

results = solve(grid, initial_wave=u0, time_step=time_step, final_time=  1.0, damping=damping, velocity=velocity )


for step in range(len(results['files'])):
    data = scipy.io.loadmat( results['files'][step] )
    u1 = data['m'].copy('C')
    #data = scipy.io.loadmat( results2['files'][step] )
    #u2 = data['m'].copy('C')
    
    k=sqrt(k1*k1+k2*k2)
    t = float(step)*time_step
    u2 = grid.evaluate( lambda x1,x2: cos(x1*k1+x2*k2)*cos(c*t*k) )
    
    render( u1-u2, "/workspace/output/acoustic_propagation/" + "%05d.png"%step , major_scale=1E-1, center=0.0 )
    print step, norm( u1-u2 )/norm(u2)
Beispiel #38
0
def foo(pid):
    p = sil.Problem.read_by_pid(pid)
    print_info_about(p)
    ps = solve.solve(p)
    display_ps(ps)
Beispiel #39
0
# read board
# if we were supplied a file, read it
if board:
    print("Reading from file '{}'...".format(board.name))
    board = read.read_file(board)
# else we have to get it from the user
else:
    print("Enter the known numbers (leaving spaces for those you don't know)...")
    now = time.clock()
    board = read.read_stdin()
    duration -= time.clock() - now

# solve board
if not no_solve:
    print("Solving... ", end='')
    board = solve.solve(board)

    # check if we're done
    if solve.done(board):
        done = True
        print("Solved!")
    # else resort to guessing
    else:
        now = time.clock()
        while True:
            response = input("\nBoard couldn't be solved by logic alone. Start guessing? [y/n] ") \
                .strip().lower()[0]
            if response == 'y':
                print("Guessing... ", end='')

                start = time.clock()
      mem = Member(mem_name)
      cat.add(mem)
      helper[mem_name] = mem
    puzzle.categories.append(cat)
  # use reflection to read the rest of the lines as clues!
  # TODO fix it so it doesn't crash if there are empty lines at the end of the file
  for line in f.readlines():
    tokens = line.split()
    # special rules for Or. Hacky.
    if len(tokens) == 7 and tokens[3] == "Or":
      m1 = helper[tokens[0]]
      m2 = helper[tokens[2]]
      fun_string1 = tokens[1] + "(m1, m2)"
      m3 = helper[tokens[4]]
      m4 = helper[tokens[6]]
      fun_string2 = tokens[5] + "(m3, m4)"
      fun_string = "Or("+fun_string1+","+fun_string2+")"
    else: 
      m1=helper[tokens[0]]
      m2 = helper[tokens[2]]
      fun_string = tokens[1] + "(m1, m2)"
    puzzle.relationships.append(eval(fun_string))
  # return the puzzle object
  return puzzle

if __name__ == "__main__":
  # if called from the command line also solve the puzzle
  # intended for informed debugging only; may break in startling ways
  solve(parse_file(sys.argv[1]))

if __name__ == '__main__':
    choice = easygui.ccbox(msg='Start solving puzzle?\nChoose a puzzle first.', title='Puzzle Solver v1.0', choices=('Continue', 'Cancel'), image=None)
    if choice:
        inputpath = easygui.fileopenbox(title='Choose a puzzle', default=None, filetypes=['*.txt'])
    puzzlename = inputpath.split('/')[-1].split('.')[0]
    outputpath = os.getcwd() + '/results/' + puzzlename

    msg = "Enable flipping and rotation?"
    title = 'Puzzle Solver v1.0'
    fieldName = ["Flipping", "Rotation"]
    fieldValue = []
    fieldValue = easygui.multenterbox(msg, title, fieldName)
    FLIP = fieldValue[0]
    ROTATE = fieldValue[1]

    start = time.time()
    solve.solve(inputpath, FLIP, ROTATE)
    end = time.time()

    printstr = 'Total time: ' + str(end - start) + ' seconds'
    msg = "Solutions generated. Please choose one."
    fieldName = ["Solution number"]
    fieldValue = []
    fieldValue = easygui.multenterbox(msg, title, fieldName)
    imgpath = outputpath + '/' + str(fieldValue[0]) + '.png'
    if os.path.exists(outputpath) and os.listdir(outputpath):
        easygui.msgbox(printstr, title, image=imgpath)
    else:
        easygui.msgbox("nothing found")
Beispiel #42
0
def run():
    data = Data()
    
    with Timer('preparation'):
        #create element_table
        #data.tables.element_table = preparation.create_element_table(data.info) #unused?

        import build_backup as build
        #import build_viertel as build
        #import build_neumann as build
        #import build_ladung as build

        data.info.elements_per_line = -1


        data.info.number_of_elements = build.get_number_of_elements()
        data.info.nodes_per_element = build.get_nodes_per_element()
        data.info.number_of_nodes = build.get_number_of_nodes()

        


        #create local_to_global table
        #data.tables.local_to_global = preparation.create_local_to_global(data.info)
        data.tables.local_to_global = build.get_local_to_global().copy()
        
        #create nodes_to_coordinates
        #data.tables.nodes_to_coordinates = preparation.create_nodes_to_coordinates(data.info)
        data.tables.nodes_to_coordinates = build.get_nodes_to_coordinates().copy()
        #print data.tables.nodes_to_coordinates

        #neumann
        #data.tables.edge_to_global = build.get_edge_to_global().copy()

        


        #create boundary_table
        #data.tables.boundary_table = preparation.create_boundary_table(data.info)
        data.tables.boundary_table = build.get_boundary_table().copy()

        helper.write_matrix_to_file(data.tables.local_to_global, 'data/local_to_global.txt')
        helper.write_matrix_to_file(data.tables.nodes_to_coordinates, 'data/nodes_to_coordinates.txt')
        helper.write_matrix_to_file(data.tables.boundary_table, 'data/boundary_table.txt')


    with Timer('assembly'):
        #assemble equations
        data.equ = assembly.assemble_equations(data.info, data.tables)

        pass

    with Timer('solve'):
        #solve equations
        data.equ.u_h = solve.solve(data.equ)
        helper.write_matrix_to_file(data.equ.u_h, 'data/u_h.txt')
        print(data.equ.u_h)

    with Timer('plots'):
        #generate plot_data
        # data.plots.xx, data.plots.yy, data.plots.zz = plots.generate_plot_data(data.info, 
        #                             data.tables, data.plots, data.equ.u_h)

        #plots.contour_plot(data.info, data.tables, data.plots, data.equ.u_h)
        
        plots.contour_plot_new(data.info, 
                                     data.tables, data.plots, data.equ.u_h)

        #plots.fe_plot(data.info, data.tables, data.plots)
        pass
Beispiel #43
0
#End Configuration
############################################

numStates = 23 #(11 * 11 * 2 + 1 for terminal state)
if not SIMULATION:
    mt = RealMT(numberOfProblems, AWSAKID, AWSSAK, sandbox = SANDBOX)
else:
    mt = SimMT(numberOfProblems,workerPools,OFFSET)
(costs, answers) = solve(mt,
                         numStates,
                         numberOfProblems,
                         workerPools,
                         nameOfTask,
                         VALUE,
                         PRICE,
                         GAMMA,
                         SCALEFACTOR,
                         ZMDPPATH,
                         URL,
                         EMPATH,
                         fastLearning,
                         timeLearning,
                         taskDuration,
                         debug)

print "Average Cost:"
print average(costs)
print "Answers:"
print answers
for problemNumber in xrange(numberOfProblems):
    print "The answer to problem %d is %d and it cost %f." % (problemNumber,answers[problemNumber],costs[problemNumber])