Пример #1
0
def t_tester(solver_a, solver_b, verbose=False, difficulty='easy', trials=10):
    board = get_sugoku_board(difficulty)

    solvers = [solver_a, solver_b]
    timers = [Timer(f.__name__) for f in solvers]

    for timer, solver in zip(timers, solvers):
        solver_guesses = []
        for _ in range(trials):
            game = Sudoku(board)
            empty = game.number_empty()

            timer.start()
            done, guesses = solver(game)
            timer.stop(verbose=verbose)

            if not done:
                print('unsolved')
            else:
                solver_guesses.append(guesses / empty)
        print("{:50}: Avg Number of Percentage Guess: {:.5f}".format(
            solver.__name__, stat.mean(solver_guesses)))

    for timer in timers:
        timer.summary()

    print(sci_stats.ttest_rel(timers[0].times, timers[1].times))

    return 0
Пример #2
0
def constant(Nx, Ny, version):
    """Exact discrete solution of the scheme."""

    def exact_solution(x, y, t): return 5
    def I(x, y): return 5
    def V(x, y): return 0
    def f(x, y, t): return 0
    def q(x,y): return 1

    Lx = 5;  Ly = 2
    b = 1.5; dt = -1 # use longest possible steps
    T = 4

    def assert_no_error(u, x, xv, y, yv, t, n):
        u_e = exact_solution(xv, yv, t[n])
        diff = abs(u - u_e).max()
        error.append(diff)
        tol = 1E-12
        msg = 'diff=%g, step %d, time=%g' % (diff, n, t[n])
        assert diff < tol, msg

    new_dt, u = solver(
        I, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
        user_action=assert_no_error, version=version)
    print(u)
Пример #3
0
 def __init__(self, game):
     self.game = game
     self.solver = solver(self.game)
     self.database = None
     self.player1 = None
     self.player2 = None
     self.name1 = None
     self.name2 = None
Пример #4
0
 def test_solve_1(self):
     solution = [[3, 9, 6, 5, 2, 4, 8, 7, 1], [8, 2, 7, 1, 3, 6, 5, 9, 4],
                 [5, 1, 4, 8, 9, 7, 6, 2, 3], [4, 5, 3, 7, 6, 1, 9, 8, 2],
                 [1, 7, 8, 9, 5, 2, 4, 3, 6], [9, 6, 2, 4, 8, 3, 7, 1, 5],
                 [7, 4, 5, 3, 1, 9, 2, 6, 8], [6, 8, 1, 2, 7, 5, 3, 4, 9],
                 [2, 3, 9, 6, 4, 8, 1, 5, 7]]
     self.assertEquals(solver(self.problem1, []), solution,
                       "I felt a disturbance in the force")
Пример #5
0
def test_manufactured_solution():
    Lx = 1; Ly = 1
    dt = -1;  T = 0.4
    b  = 4
    mx = 4; my = 2
    kx = (mx*np.pi)/Lx
    ky = (my*np.pi)/Ly
    w = np.sqrt(kx**2 + ky**2);
    A = 1.5; B = 3

    def u_e(x, y, t): return (A*np.cos(w*t) + B*np.sin(w*t))*(np.exp(-c(x,y)*t))*np.cos(kx*x)*np.cos(ky*y)
    def I(x, y): return A*np.cos(kx*x)*np.cos(ky*y)
    def V(x, y): return (w*B - c(x,y)*A)*np.cos(kx*x)*np.cos(ky*y)
    def q(x,y): return 1
    def c(x,y): return np.sqrt(q(x,y))
    f = source_term(A, B, kx, ky, w, b)

    N_values = [5,10,20,40,80,160,320]
    E_values = []   # Contains largest error for different Nx values
    h_values = []
    error = Error(u_e)

    for N in N_values: # Run all experiments
        print('Running Nx=Ny:', N)
        Nx = Ny = N
        dt = -1

        solver(I, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
            user_action=error, version='vectorized')

        E_values.append(error.E)
        h_values.append(error.h)

    r = [(np.log(E_values[i]/E_values[i-1]))/np.log(h_values[i]/h_values[i-1]) for i in range(1, len(N_values))]


    print("\n            CONVERGENCE RATES WITH DETAILS            ")
    print(" N(i) | N(i+1) |   dt(i)   |  dt(i+1)  |  r(i)  | \n")
    for i in range(len(N_values)-1):
        print(" %-3i      %-4i     %-9.3E   %-9.3E   %-5.4f" \
            %(N_values[i], N_values[i+1], h_values[i], h_values[i+1], r[i]))
    print('')

    tol = 0.05
    assert r[-1]-2 < tol and r[-1]-2 > 0  #Test to check that r converges to two
Пример #6
0
def test_undamped_waves():
    Lx = 1; Ly = 1
    dt = -1;  T = 0.4
    b  = 0
    mx = 2; my = 3
    kx = (mx*np.pi)/Lx
    ky = (my*np.pi)/Ly
    w = np.sqrt(kx**2 + ky**2); A = 1.5

    def u_e(x, y, t): return A*np.cos(kx*x)*np.cos(ky*y)*np.cos(w*t)
    def I(x, y): return A*np.cos(kx*x)*np.cos(ky*y)
    def V(x, y): return 0
    def f(x, y, t): return 0
    def q(x,y): return 1
    def c(x,y): return np.sqrt(q(x,y))

    N_values = [5,10,20,40,80,160,320]
    E_values = []   # Contains largest error for different Nx values
    h_values = []
    error = Error(u_e)

    for N in N_values: # Run all experiments
        print('Running Nx=Ny:', N)
        Nx = Ny = N
        dt = -1

        solver(I, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
            user_action=error, version='vectorized')

        E_values.append(error.E)
        h_values.append(error.h)

    r = [(np.log(E_values[i]/E_values[i-1]))/np.log(h_values[i]/h_values[i-1]) for i in range(1, len(N_values))]


    print("\n            CONVERGENCE RATES WITH DETAILS            ")
    print(" N(i) | N(i+1) |   dt(i)   |  dt(i+1)  |  r(i)  | \n")
    for i in range(len(N_values)-1):
        print(" %-3i      %-4i     %-9.3E   %-9.3E   %-5.4f" \
            %(N_values[i], N_values[i+1], h_values[i], h_values[i+1], r[i]))
    print('')
Пример #7
0
	def test_filter_reads1(self):
		reads1 = ["ACTG", "TGCA", "ACAC", "TTTT", "GGGG"]
		solver1 = solver(reads1)
		solver1.reads = reads1
		solver1.main()
		solver1.print_nodes()
		for read in reads1:
			good = False
			for node in solver1.nodes:
				if node.read == read:
					good = True
			self.assertTrue(good)
Пример #8
0
    def tree_fitness(self,tree): # use full test set this is defined here because we want to change to use partial test for other GPs
        fitness = 0
        for test in self.test_set:
            if tree.evaluate(test) == solver(test):
                fitness = fitness + 1
        
        if tree.num_of_nodes > self.node_limit and fitness != len(self.test_set):
            fitness = fitness - (tree.num_of_nodes - self.node_limit)//100 

        tree.fitness = fitness

        return fitness
Пример #9
0
def q():
    value = request.forms.get('value')
    vals_dict = parser(value)
    print vals_dict
    vals_list = get_vals(vals_dict)
    values = solver(vals_list[0], vals_list[1], vals_list[2], vals_list[3], vals_list[4], vals_list[5], vals_list[6], vals_list[7], vals_list[8], vals_list[9], vals_list[10])
    new_dict = {}
    for key in values:
        if values[key] is not None:
            new_dict[key] = values[key]
    steps = []
    steps = oursteps()
    return dict(values=new_dict, steps=steps)
Пример #10
0
def run_model(data, hidden_dims, input_dims, num_classes, weight_scale,
              learning_rate):
    model = fullyConnectedNet(hidden_dims,
                              input_dims,
                              num_classes,
                              weight_scale=weight_scale,
                              dtype=np.float64)
    Solver = solver(model,
                    data,
                    print_every=10,
                    num_epochs=20,
                    batch_size=25,
                    update_rule='sgd',
                    optim_config={
                        'learning_rate': learning_rate,
                    })
    Solver.train()
    return Solver.loss_history, Solver.train_err_history
Пример #11
0
    def tree_fitness(self,tree): # use full test set this is defined here because we want to change to use partial test for other GPs
        fitness = 0
        if self.cur_iter >= self.max_iters: # this means do full evaluation for the last iteration
            proportion = 1.0
        else:
            proportion = 1.0
        index = 0
        for test in self.test_set:
            if random.random() < proportion :
                if tree.evaluate(test) == solver(test):
                    fitness = fitness + 1
            index = index + 1
        
        if tree.num_of_nodes > self.node_limit and fitness != len(self.test_set):
            fitness = fitness - (tree.num_of_nodes - self.node_limit)//100 

        tree.fitness = fitness

        return fitness
Пример #12
0
def main():
    ai = matlabarray(zeros (10,10,dtype=int),dtype=int)
    af = copy(ai)

    ai[1,1]=2
    ai[2,2]=3
    ai[3,3]=4
    ai[4,4]=5
    ai[5,5]=1

    af[9,9]=1
    af[8,8]=2
    af[7,7]=3
    af[6,6]=4
    af[10,10]=5

    t0 = time.clock()
    mv = solver(ai,af,0)
    t1 = time.clock()
    print t1-t0
    print mv.shape
Пример #13
0
def tester(solvers, verbose=False, difficulty='easy', trials=1):
    boards = get_test_boards(difficulty=difficulty)

    timers = [Timer(f.__name__) for f in solvers]
    for timer, solver in zip(timers, solvers):
        solver_guesses = []
        for board in boards:
            for _ in range(trials):
                game = Sudoku(board)
                empty = game.number_empty()
                timer.start()
                done, guesses = solver(game)
                timer.stop(verbose=verbose)
                if not done:
                    print('unsolved')
                else:
                    solver_guesses.append(guesses / empty)
        print("{:50}: Avg Number of Percentage Guess: {:.5f}".format(
            solver.__name__, stat.mean(solver_guesses)))
    for timer in timers:
        timer.summary()

    return 0
Пример #14
0
                filePath = '{}_test.csv'.format(config.load_from)
                if os.path.exists(filePath):
                    os.remove(filePath)

                for batch in tqdm(range(config.batch_size)):

                    hPlacement, hEnergy, hCst_occupancy, hCst_bandwidth, hCcst_latency = first_fit(
                        networkServices.state[batch],
                        networkServices.service_length[batch], env)

                    hPenalty = agent.lambda_occupancy * hCst_occupancy + agent.lambda_bandwidth * hCst_bandwidth + agent.lambda_latency * hCcst_latency
                    hLagrangian = hEnergy + hPenalty


                    sPlacement, sSvc_bandwidth, sSvc_net_latency, sSvc_cpu_latency, sEnergy, sOccupancy, sLink_used = \
                        solver(networkServices.state[batch], networkServices.service_length[batch], env)

                    if sPlacement == None:
                        sReward[batch] = 0
                    else:
                        env.clear()
                        env.step(networkServices.service_length[batch],
                                 networkServices.state[batch], sPlacement)

                        assert sSvc_bandwidth == env.bandwidth
                        assert sSvc_net_latency == env.link_latency
                        assert sSvc_cpu_latency == env.cpu_latency
                        assert sEnergy == env.reward
                        assert sOccupancy == list(env.cpu_used)
                        assert sLink_used == list(env.link_used)
Пример #15
0
        'X_val': data['X_val'],
        'y_val': data['y_val'],
    }

    weight_scale = 2e-2
    bn_model = fullyConnectedNet(input_dims = 32 * 32 * 3, hidden_dims = hidden_dims, num_classes = 10, \
       weight_scale=weight_scale, use_batch_normal=True)

    model = fullyConnectedNet(input_dims = 32 * 32 * 3, hidden_dims = hidden_dims, num_classes = 10, \
       weight_scale=weight_scale, use_batch_normal=False)

    bn_solver = solver(bn_model,
                       small_data,
                       num_epochs=10,
                       batch_size=50,
                       update_rule='adam',
                       optim_config={
                           'learning_rate': 1e-3,
                       },
                       verbose=True,
                       print_every=200)
    bn_solver.train()

    solver = solver(model,
                    small_data,
                    num_epochs=10,
                    batch_size=50,
                    update_rule='adam',
                    optim_config={
                        'learning_rate': 1e-3,
                    },
                    verbose=True,
Пример #16
0
def test():
    pygame.init()
    pygame.display.set_caption("reversed pendulum")
    viewport = (1800, 600)
    hx = viewport[0] / 2
    hy = viewport[1] / 2
    screen = pygame.display.set_mode(viewport, OPENGL | DOUBLEBUF)

    mat_specular = [1.0, 1.0, 1.0, 1.0]
    mat_shininess = [50.0]
    light_position = [0.0, 1.0, 1.0, 0.0]
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glShadeModel(GL_SMOOTH)

    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular)
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess)
    glLightfv(GL_LIGHT0, GL_AMBIENT, (0.6, 0.6, 0.6, 1.0))
    glLightfv(GL_LIGHT0, GL_POSITION, light_position)

    glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 45.0)

    spot_direction = [-1.0, -1.0, 0.0]
    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spot_direction)
    position = [1.0, 1.0, 1.0, 1.0]
    glLightfv(GL_LIGHT1, GL_POSITION, position)

    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    #glEnable(GL_LIGHT1)
    glEnable(GL_DEPTH_TEST)

    revPend = Mecanism()

    table = Table()

    clock = pygame.time.Clock()

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    width, height = viewport
    gluPerspective(90.0, width / float(height), 1, 400.0)
    glEnable(GL_DEPTH_TEST)
    glMatrixMode(GL_MODELVIEW)

    rx, ry = (0, 0)
    tx, ty = (0, 0)
    zpos = 200
    rotate = move = False

    alfa = theta = 0
    x = 0
    dx = 1
    step = 5

    appliedForce = 0

    while 1:
        #clock.tick(20)
        for e in pygame.event.get():
            if e.type == QUIT:
                #print(revPend.w, revPend.W)
                pygame.quit()
                sys.exit()
                #glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            elif e.type == KEYDOWN and e.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

            elif e.type == KEYDOWN:
                pressed_keys = pygame.key.get_pressed()
                if pressed_keys[K_LEFT]:
                    oldT = revPend.theta
                    revPend.theta += -15
                    if revPend.theta < -revPend.tMax:
                        revPend.theta = -revPend.tMax
                        revPend.dtheta = oldT - revPend.theta

                if pressed_keys[K_RIGHT]:
                    oldT = revPend.theta
                    revPend.theta += 15
                    if revPend.theta > revPend.tMax:
                        revPend.theta = revPend.tMax
                        revPend.dtheta = oldT - revPend.theta

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        # RENDER OBJECT
        glTranslate(tx / 20. - 50, ty / 20. - 50, -zpos)
        glRotate(ry, 1, 0, 0)
        glRotate(rx, 0, 1, 0)

        # se deseneaza masa
        table.draw(2000)

        # se aplica modelul fizic
        t, w = revPend.dynamics(appliedForce)

        #se calculeaza raspunsul
        newForce = solver(t, w)
        if newForce != None:
            appliedForce = newForce
        print(t, w, appliedForce)
        # se deseneaza pendulul
        revPend.draw()

        pygame.display.flip()

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    pygame.quit()
Пример #17
0
v = lambda t: 2 * t  # velocity function

# Displacement Function
from solver import *

m = 2  # mass of the system
b = 0.8  # friction parameter
k = 2  # spring parameter
V = 1.5
t = linspace(0, 25, 41)
s = lambda u: k * u  # restoring force of spring
F = lambda t: -m * ddh(v(t) * t)

# solver function --> you can change damping mode from 'linear'
# to 'quadratic' the result would be changed
u, t = solver(I=0, V=V, m=m, b=b, s=s, F=F, t=t, damping="linear")

"""
# if you want to see plot of solver function,turn me on
import matplotlib.pyplot as plt
plt.plot(t, u)
plt.show()
"""

# My figure
over = Rectangle(lower_left_corner=(-1.5 * R, 2 * H), width=3 * R, height=0.75 * H)

tire = Composition(
    {
        "wheel": Circle(center=(0, 0), radius=R),
        "cross": Composition({"cross1": Line((0, -1), (0, R)), "cross2": Line((-R, 0), (R, 0))}),
Пример #18
0
import json
import numpy as np
from solver import *

with open("model.json") as jfile:
    data = json.load(jfile)

print("\n-----------------")
# Convert input - Solver2
title = data["TITLE"]
print("\n", title)
dimensions = data["DIMENSIONS"]
coords = np.array(data["COORDS"])
connectedges = np.array(data["CONNECTEDGE"])
edgesElem = np.array(data["EDGESELEM"])
connect = np.array(data["CONNECTELEM"])
temp = np.array(data["TEMP"])
flux = np.array(data["FLUX"])
prop = np.array(data["PROPERTIES"])
solver(coords, connectedges, edgesElem, connect, temp, flux, prop)
print("-----------------\n")
Пример #19
0
        test_data_loader = get_loader(
            sentences=load_pickle(test_config.sentences_path),
            labels=load_pickle(test_config.label_path),
            conversation_length=load_pickle(
                test_config.conversation_length_path),
            sentence_length=load_pickle(test_config.sentence_length_path),
            batch_size=test_config.eval_batch_size,
            shuffle=False)

        # for testing
        solver = Solver

        solver = solver(config,
                        train_data_loader,
                        eval_data_loader,
                        test_data_loader,
                        is_train=True)

        solver.build()

        best_test_loss, best_test_f1_w, best_epoch = solver.train()

        print(f"Current RUN: {run+1}")

        print("\n\nBest test loss")
        print(best_test_loss)
        print("Best test f1 weighted")
        print(best_test_f1_w)
        print("Best epoch")
        print(best_epoch)
Пример #20
0
def main():
    param = def_param()

    for method in param.method_list:
        param.method = method
        for name in param.list_data:
            param.name_data = name
            """
            creat result file
            """
            direct = '/Users/messi/Documents/Year1/summer18/results_auc/result_' + param.method + '_test2/'
            file_name = direct + 'result_' + param.name_data + '.csv'
            if not os.path.exists(direct):
                os.makedirs(direct)
            auc_final = 0
            auc_init = 0
            time_final = 0
            with open(file_name, 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                row_new = [[
                    'run', 'auc_init', 'auc_final', 'num. iters', 'soltime',
                    'moment_time'
                ]]
                a.writerows(row_new)
            m_accuracy_init = 0
            m_accuracy = 0
            m_num_iters = 0
            m_sol_time = 0
            m_moment = 0

            for run in range(param.num_run):

                data = dataReader(param, run + 1)

                start_time = timeit.default_timer()
                w_final, num_iters = solver(param, data)
                end_time = timeit.default_timer()
                soltime_time = end_time - start_time

                print('solution time is: {}'.format(soltime_time))

                fval_auc_init = computeAUC(param, data, data.initw)
                print('auc value with initial w is: {}'.format(fval_auc_init))

                fval_auc = computeAUC(param, data, w_final)
                sol_time = soltime_time
                print('auc value for this run is : {} with solution time :{}'.
                      format(fval_auc, sol_time))

                row_new = [[
                    run, fval_auc_init, fval_auc, num_iters, sol_time,
                    data.soltime_time_mom
                ]]
                m_accuracy_init += fval_auc_init / param.num_run
                m_accuracy += fval_auc / param.num_run
                m_num_iters += num_iters / param.num_run
                m_sol_time += sol_time / param.num_run
                m_moment += data.soltime_time_mom / param.num_run
                auc_init += fval_auc_init
                auc_final += fval_auc
                time_final += sol_time
                if run == 0:
                    row_new_0 = row_new
                """
                write result file
                """
                with open(file_name, 'a', newline="") as fp:
                    a = csv.writer(fp, delimiter=',')
                    a.writerows(row_new)
                if run == param.num_run - 1:
                    with open(file_name, 'a', newline="") as fp:
                        a = csv.writer(fp, delimiter=',')
                        row_new = [[
                            'average', m_accuracy_init, m_accuracy,
                            m_num_iters, m_sol_time, m_moment
                        ]]
                        a.writerows(row_new)

            print('this is ', param.name_data)
            print('initial auc is: {}'.format(float(auc_init) / param.num_run))
            print('final auc is: {}'.format(float(auc_final) / param.num_run))
            print('final solution time is: {}'.format(
                float(time_final) / param.num_run))
Пример #21
0
            positions = sess.run(agent.ptr.positions, feed_dict=feed)

            reward = np.zeros(config.batch_size)

            # Compute environment
            for batch in range(config.batch_size):
                env.clear()
                env.step(positions[batch], services.state[batch], services.serviceLength[batch])
                reward[batch] = env.reward

                # Render some batch services
                if batch % max(1, int(config.batch_size / 5)) == 0:
                    print("\n Rendering batch ", batch, "...")
                    env.render(batch)

            # Calculate performance
            if config.enable_performance:

                print("\n Calculating optimal solutions... ")
                optReward = np.zeros(config.batch_size)

                for batch in tqdm(range(config.batch_size)):
                    optPlacement = solver(services.state[batch], services.serviceLength[batch], env)
                    env.clear()
                    env.step(optPlacement, services.state[batch], services.serviceLength[batch])
                    optReward[batch] = env.reward
                    assert optReward[batch] + 0.1 > reward[batch]  # Avoid inequalities in the last decimal...

                performance = np.sum(reward) / np.sum(optReward)
                print("\n Performance: ", performance)
Пример #22
0
            'bg':
            colored,
            'fg':
            'black'
        })
        subentry[j]['obj'].grid(row=i, column=j, ipady=6, padx=1, pady=1)
    entry.append(subentry)

for i in entry:
    for j in i:
        binder(j['obj'], entry)

solve = Button(text='Solve',
               cursor="hand2",
               width=14,
               command=lambda: solver(entry, solve))
solve.grid(column=3, row=10, columnspan=3, pady=6)

clear = Button(text='Clear',
               cursor="hand2",
               width=14,
               command=lambda: clearer(entry, solve))
clear.grid(column=0, row=10, columnspan=3, pady=6)

exitter = Button(text='Exit', width=14, command=root.quit, cursor="hand2")
exitter.grid(column=6, row=10, columnspan=3, pady=6)

author = Label(text='by Jinol Shah',
               fg='#696969',
               font='Helvetica 9 italic',
               cursor="hand2")
Пример #23
0
dt = tp[1] - tp[0]  # delta t
v = lambda t: 2 * t  # velocity function

# Displacement Function
from solver import *
m = 2  # mass of the system
b = 0.8  # friction parameter
k = 2  # spring parameter
V = 1.5
t = linspace(0, 25, 41)
s = lambda u: k * u  # restoring force of spring
F = lambda t: -m * ddh(v(t) * t)

# solver function --> you can change damping mode from 'linear'
# to 'quadratic' the result would be changed
u, t = solver(I=0, V=V, m=m, b=b, s=s, F=F, t=t, damping='linear')
'''
# if you want to see plot of solver function,turn me on
import matplotlib.pyplot as plt
plt.plot(t, u)
plt.show()
'''

#My figure
over = Rectangle(lower_left_corner=(-1.5 * R, 2 * H),
                 width=3 * R,
                 height=.75 * H)

tire = Composition({
    'wheel':
    Circle(center=(0, 0), radius=R),
Пример #24
0
    u_r = -q_step[1, -2] / q_step[0, -2]
    # u_r = 0
    t_r = qt_step[2, -2] / R / qt_step[0, -2]
    p_r = qt_step[2, -2]
    q1_r = p_r / 287 / t_r
    q2_r = q1_r * u_r
    q3_r = q1_r * (cv * t_r + u_r**2 / 2)

    q_r = [q1_r, q2_r, q3_r]
    q_l = [q1_l, q2_l, q3_l]
    return [q_l, q_r]


scheme = FTCS
shock_tube = solver(gridpts=500,
                    dtdx=0.05,
                    scheme=scheme,
                    ic=ic,
                    bc=bc,
                    spaceDomain=[-.5, .5],
                    tmax=5)
print(shock_tube.grid.dtdx)
dt = shock_tube.grid.t[1] - shock_tube.grid.t[0]

shock_tube.animate(int(shock_tube.grid.timesteps),
                   art_viscosity=[0.007, 0.0007],
                   save=True,
                   filename='q3_anim',
                   fps=60)
Пример #25
0
            counter = 1
            temp = line_req[i][0]
        line_req[i][1] = str(counter)

    for i in range(len(line_req)):
        if line_req[i][2].startswith("N$"):
            line_req[i][2] = line_req[i][2].replace("$", "et")


parser = argparse.ArgumentParser()
#parser.add_argument('-f', '--file', help='Input file', required=True)
parser.add_argument('ids', nargs='*', help='some ids')
args = parser.parse_args()
#inputFile= args.file
#fileName=os.path.splitext(inputFile)[0]
fileName = args.ids[1]
#Input=inputFile
InputFile = args.ids[0]
f = open(InputFile, 'r')
line = reading_file()
line_req = eleminate_unnecessary_data()

minor_editing()
assigning_nets()
changing_names()

#nets,file_type=parse_input(Input)
nets = creating_nets()
file_type = "kicad"
solver(nets, file_type, fileName)
Пример #26
0
import json
import numpy as np
from solver import *

with open("model.json") as jfile:
    data = json.load(jfile)

print("\n-----------------")
# Convert input
title = data["TITLE"]
print("\n", title)
dimensions = data["DIMENSIONS"]
coords = np.array(data["COORDS"])
connect = np.array(data["CONNECT"])
load = np.array(data["LOAD"])
restr = np.array(data["RESTR"])
prop = np.array(data["PROP"])
solver(coords, connect, load, restr, prop)
print("-----------------\n")
        eval_data_loader = get_loader(
            sentences=load_pickle(val_config.sentences_path),
            conversation_length=load_pickle(
                val_config.conversation_length_path),
            sentence_length=load_pickle(val_config.sentence_length_path),
            vocab=vocab,
            batch_size=val_config.eval_batch_size,
            shuffle=False)

    # for testing
    # train_data_loader = eval_data_loader
    if config.model in VariationalModels:

        if config.model == "ADEM":
            print("train line:69 config.model", config.model)
            solver = AdemSolver
        else:
            solver = VariationalSolver

    else:
        solver = Solver

    solver = solver(config,
                    train_data_loader,
                    eval_data_loader,
                    vocab=vocab,
                    is_train=True)

    solver.build(init_by_pretrained_model=True)
    solver.train()
Пример #28
0
def create_waves(bottom_shape):
    for frame in glob.glob("figures/2D_wave_*.png"):
        os.remove(frame)

    Lx = 1
    Ly = 1
    Nx = 120
    Ny = 120
    dt = -1  # Shortcut to maximum timestep
    T = 0.6
    b = 0.8

    def H(x, y, bottom_shape):
        if bottom_shape == 1:  # Gaussian
            Bmx = 0.5
            Bmy = 0.5
            B0 = 1
            Ba = -0.6
            Bs = np.sqrt(1. / 30)
            b = 0.8
            return B0 + Ba * np.exp(-((x - Bmx) / Bs)**2 - ((y - Bmy) /
                                                            (b * Bs))**2)

        elif bottom_shape == 2:  # Cosine hat
            Bmx = 0.5
            Bmy = 0.5
            B0 = 1
            Ba = -0.2
            Bs = 0.2
            condition = np.sqrt(x**2 + y**2)
            if condition <= Bs and condition >= 0:
                return B0 + Ba * np.cos(
                    (np.pi * (x - Bmx)) / (2 * Bs)) * np.cos(
                        (np.pi * (y - Bmy)) / (2 * Bs))
            else:
                return B0

        elif bottom_shape == 3:  # Box addition
            Bmx = 0.5
            Bmy = 0.5
            B0 = 1
            Ba = -0.6
            Bs = 0.2
            b = 0.8

            if (Bmx - Bs < x < Bmx + Bs) and (Bmy - b * Bs < y < Bmy + b * Bs):
                return B0 + Ba
            else:
                return B0

    def q(x, y):  # q = c**2
        g = 9.81  #[m/s^2] acceleration of gravity
        if len(x.shape) == 1:
            q = np.zeros((len(x), len(y)))
            for i, xx in enumerate(x):
                for j, yy in enumerate(y):
                    q[i, j] = g * H(xx, yy, bottom_shape)
        if len(x.shape) == 2:
            q = np.zeros((x.shape[0], y.shape[1]))
            for i, xx in enumerate(x[:, 0]):
                for j, yy in enumerate(y[0]):
                    q[i, j] = g * H(xx, yy, bottom_shape)
        return q

    sigma = 0.091
    I0 = 0
    Im = 0
    Ia = 0.3
    Is = np.sqrt(2) * sigma

    def I(x, y):
        return I0 + Ia * np.exp(-((x - Im) / Is)**2)

    f = lambda x, y, t: 0  # Source term
    V = lambda x, y: 0  # Initial du/dt

    solver(I,
           V,
           f,
           q,
           b,
           Lx,
           Ly,
           Nx,
           Ny,
           dt,
           T,
           user_action=plot_2D_wave,
           version='vectorized')
Пример #29
0
        'y_train': data['y_train'][:num_train],
        'X_val': data['X_val'],
        'y_val': data['y_val'],
    }

    solvers = {}

    for update_rule in ['sgd', 'rmsprop']:
        print('running with ', update_rule)
        model = fullyConnectedNet([100, 100, 100, 100, 100], input_dims = 32 * 32 * 3, \
                num_classes = 10, weight_scale=5e-2)

        Solver = solver(model,
                        small_data,
                        num_epochs=15,
                        batch_size=100,
                        update_rule=update_rule,
                        opt_config={'learning_rate': 1e-2},
                        verbose=True)
        Solver.train()
        solvers[update_rule] = Solver
        print('training finished.')

    # print-out results
    plt.subplot(3, 1, 1)
    plt.title('Training loss')
    plt.xlabel('Iteration')

    plt.subplot(3, 1, 2)
    plt.title('Training error')
    plt.xlabel('Epoch')
Пример #30
0
h = np.zeros(v)
node_num = np.zeros(v)
elements = np.zeros(v)

print('')
print(
    '   Total Nodes    Total Elements           h                L2_error                H1_error'
)
print('')

v = 0
for k in range(start, stop, step):
    i = 2**k
    print('i=', i)
    elements[v] = i * i
    u, h[v], node_num[v] = solver(element_linear_num=i)
    e2[v] = L2_error(element_linear_num=i, u=u)
    h1_error[v] = H1_error(element_linear_num=i, u=u)
    print('      %4d            %4d              %8f        %14g        %14g' %
          (node_num[v], elements[v], h[v], e2[v], h1_error[v]))
    v = v + 1

print('')

#
# plotting L2 error
#
plt.plot(node_num, e2, 'b')
plt.xlabel('Nodes')
plt.ylabel('$L_2 \,\,\, Error$')
plt.grid()
Пример #31
0
    def cell_is_valid(self, cell):
        if ((cell[0] < 0 or cell[0] >= self.nrows) \
                or (cell[1] < 0 or cell[1] >= self.ncols)):
            return False

        return True


if __name__ == "__main__":
    m = Maze()
    m.setup_maze()
    d = Displayer(m)

    print(">> Testing Q learning solver...")
    bfs_path = solver(m)
    try:
        validate_answer(m, bfs_path)  # m.goal in bfs_path:
        print(("solved maze. cost: ", len(bfs_path), "cells visited"))
        print("Display solution? [y/n]")
        display_command = input()
        if "y" in display_command:
            d.draw_path(bfs_path)
    except AssertionError as e:
        print(("answer is invalid: " + e.message))

    print(" 1) Save maze to file")
    print(" 2) exit")
    command = input()

    if "1" in command:
Пример #32
0
def main():
    param = def_param()
    accuracy_final = 0
    accuracy_initial = 0
    time_final = 0

    for method in param.method_list:
        param.method = method
        for name in param.list_data:
            param.name_data = name
            """
            create result file
            """
            direct = '/Users/messi/Documents/summer18/results/result_' + param.method + '_test111/'
            print(direct)
            file_name = direct + 'result_' + param.name_data + '.csv'
            if not os.path.exists(direct):
                os.makedirs(direct)
            with open(file_name, 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                #row_new = [['run', 'Accuracy_init', 'Accuracy_final', 'num. iters', 'soltime']]
                row_new = [[
                    'run', 'Accuracy_init', 'Accuracy_final', 'num. iters',
                    'soltime', 'moment_time'
                ]]
                a.writerows(row_new)
            m_accuracy_init = 0
            m_accuracy = 0
            m_num_iters = 0
            m_sol_time = 0
            m_moment = 0

            for run in range(16, 18):

                # run = 15
                data = dataReader(param, run + 1)

                print(run)
                print(param.method)
                print(param.name_data)

                print('Optimization process:')
                start_time = timeit.default_timer()
                w_final, num_iters = solver(param, data)
                end_time = timeit.default_timer()
                soltime_time = end_time - start_time

                accuracy_init = computeAccuracy(param, data, data.initw)
                print('Accuracy with initial w is: {}'.format(accuracy_init))

                accuracy = computeAccuracy(param, data, w_final)
                sol_time = soltime_time
                print(
                    'Accuracy after minimization is: {} with solution time :{}'
                    .format(accuracy, sol_time))
                #row_new = [[run, accuracy_init, accuracy, num_iters, sol_time]]
                row_new = [[
                    run, accuracy_init, accuracy, num_iters, sol_time,
                    data.soltime_time_mom
                ]]
                """
                write result file
                """
                m_accuracy_init += accuracy_init / param.num_run
                m_accuracy += accuracy / param.num_run
                m_num_iters += num_iters / param.num_run
                m_sol_time += sol_time / param.num_run
                m_moment += data.soltime_time_mom / param.num_run
                with open(file_name, 'a', newline="") as fp:
                    a = csv.writer(fp, delimiter=',')
                    a.writerows(row_new)
                if run == param.num_run - 1:
                    with open(file_name, 'a', newline="") as fp:
                        a = csv.writer(fp, delimiter=',')
                        row_new = [[
                            'average', m_accuracy_init, m_accuracy,
                            m_num_iters, m_sol_time, m_moment
                        ]]
                        a.writerows(row_new)
                accuracy_initial += accuracy_init
                accuracy_final += accuracy

                time_final += sol_time

            print('Total initial accuracy is: {}'.format(
                float(accuracy_initial) / param.num_run))
            print('FINAL accuracy is: {} with solution time: {}'.format(
                float(accuracy_final) / param.num_run,
                float(time_final) / param.num_run))
            print(w_final)
Пример #33
0
def test_plug_wave():
    def V(x, y): return 0
    def f(x, y, t): return 0
    def q(x,y): return 1
    def c(x,y): return np.sqrt(q(x,y))

    Lx = 1.1; Ly = 1.1
    Nx = 11;  Ny = 11
    dt = 0.1; T = 1.1
    b  = 0

    class Action:
        """Store last solution."""
        def __call__(self, u, x, xv, y, yv, t, n):
            if n == len(t)-1:
                self.u = u.copy(); self.x = x.copy()
                self.y = y.copy(); self.t = t[n]

    action = Action()

    def Ix_scalar(x,y): # Scalar initial condition
        if abs(x-Lx/2.0) > 0.1: return 0
        else: return 1


    def Ix_vec(x,y): # vectorized initial condition
        I = np.zeros(x.shape)
        for i in range(len(x[:,0])):
            if abs(x[i,0]-Lx/2.0) > 0.1:
                I[i,0] = 0
            else:
                I[i,0] = 1
        return I


    def Iy_scalar(x,y): # For scalar scheme
        if abs(y-Ly/2.0) > 0.1: return 0
        else: return 1


    def Iy_vec(x,y):
        I = np.zeros(y.shape)
        for j in range(len(y[0,:])):
            if abs(y[0,j]-Ly/2.0) > 0.1:
                I[0,j] = 0
            else:
                I[0,j] = 1
        return I


    solver(Ix_scalar, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
        user_action=action, version='scalar')
    u_s_x = action.u

    solver(Iy_scalar, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
        user_action=action, version='scalar')
    u_s_y = action.u

    solver(Ix_vec, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
        user_action=action, version='vectorized')
    u_v_x = action.u

    solver(Iy_vec, V, f, q, b, Lx, Ly, Nx, Ny, dt, T,
        user_action=action, version='vectorized')
    u_v_y = action.u

    diff1 = abs(u_s_x - u_v_x).max()
    diff2 = abs(u_s_y - u_v_y).max()

    tol = 1e-13
    assert diff1 < tol and diff1 < tol

    u_0_x = np.zeros((Nx+1,Ny+1))
    u_0_x[:,:] = Ix_vec(action.x[:,np.newaxis], action.y[np.newaxis,:])

    u_0_y = np.zeros((Nx+1,Ny+1))
    u_0_y[:,:] = Iy_vec(action.x[:,np.newaxis], action.y[np.newaxis,:])

    def check_wave():
        #Just to check that the wave splits for different timestep (in x-direction)
        #At which timestep to plot is modified in Action() by changing 'len(t)-1'
        import matplotlib.pyplot as plt
        x = np.linspace(0, Lx, Nx+1)
        y = np.linspace(0, Ly, Ny+1)
        plt.plot(x, u_v_x)
        plt.title("t=%.2f" % action.t)
        plt.xlabel('Lx')
        plt.ylabel('U')
        plt.show()
    #check_wave()

    diff3 = abs(u_s_x - u_0_x).max()
    diff4 = abs(u_s_y - u_0_y).max()
    diff5 = abs(u_v_x - u_0_x).max()
    diff6 = abs(u_v_y - u_0_y).max()
    assert diff3 < tol and diff4 < tol and diff5 < tol and diff6 < tol
Пример #34
0
    def __call__(self):

        tau = util.tau

        # Positions des billes après tau
        up = []
        for i in range(len(self.billes)):
            temp = self.billes[i].testUpdate(tau)
            up.append([i, temp[0], temp[1], temp[2], temp[3]])

        # On regarde s'il y a des conflits
        conflits = []

        # 1. Chocs entre billes
        tests = []
        for elem in up:
            for j in range(len(up)):
                if elem[0] != j and [elem[0], j] not in tests and [j, elem[0]] not in tests:
                    tests.append([elem[0], j])
                    if not self.billes[up[j][0]].rentre:
                        if util.choc([[up[elem[0]][1], up[elem[0]][2]], [up[j][1], up[j][2]]]):
                            conflits.append(["choc", elem[0], j])

        # 2. Bille qui s'arrête
        for elem in up:
            if not self.billes[elem[0]].rentre:
                if elem[3] <= 0 and self.billes[elem[0]].v[0] > 0:
                    conflits.append(["v0", elem[0]])
                elif elem[4] <= 0 and self.billes[elem[0]].v[1] > 0:
                    conflits.append(["v1", elem[0]])

        # 3. Bords du billard
        for elem in up:
            if not self.billes[elem[0]].rentre:
                if util.oob(elem[1:3]):
                    conflits.append(["oob", elem[0]])

        if len(conflits) > 0:
            # On résout le conflit et on récupère le tau correspondant
            solver(self.billes, conflits)
            tau = solver.solved[0]

        # MAJ des billes
        for b in self.billes:
            b.update(tau)

        if len(conflits) > 0:
            solution = solver.solved[1]

            # Problème résolu : annulation de la vitesse de glissement
            if solution[0] == self.V0:
                self.billes[solution[1]].v[0] = 0
                self.billes[solution[1]].glissement = False

            # Problème résolu : annulation de la vitesse de roulement
            elif solution[0] == self.V1:
                self.billes[solution[1]].v[1] = 0
                if self.billes[solution[1]].v[0] == 0:
                    self.billes[solution[1]].arret = True

            # Problème résolu : choc avec les bords
            elif solution[0] == self.OOB:
                pos = self.billes[solution[1]].pos

                # La bille ne tombe pas dans un trou
                pR = util.t_m * 0.85
                gR = util.t_b * 1.5
                if not (util.b_d / 2 - pR <= pos[0] <= util.b_d / 2 + pR) \
                        and not (pos[0] <= util.holes[0][0] + gR and pos[1] <= util.holes[0][1] + gR) \
                        and not (pos[0] >= util.holes[1][0] - gR and pos[1] <= util.holes[1][1] + gR) \
                        and not (pos[0] <= util.holes[2][0] + gR and pos[1] >= util.holes[2][1] - gR) \
                        and not (pos[0] >= util.holes[3][0] - gR and pos[1] >= util.holes[3][1] - gR):
                    dists = [[0, (pos[0] - util.b_g) ** 2], [1, (pos[1] - util.b_h) ** 2],
                             [2, (pos[0] - util.b_d) ** 2], [3, (pos[1] - util.b_b) ** 2]]
                    dists.sort(key=lambda x: x[1])
                    if dists[0][0] % 2 == 0:
                        self.billes[solution[1]].alpha = np.pi - \
                            self.billes[solution[1]].alpha
                    else:
                        self.billes[solution[1]].alpha = - \
                            self.billes[solution[1]].alpha
                    self.billes[solution[1]].v /= np.sqrt(2)

                # La bille tombe dans un trou
                else:
                    self.billes[solution[1]].arret = True
                    self.billes[solution[1]].rentre = True

                    # Problème résolu : choc entre bille
            elif solution[0] == self.CHOC:
                v1o, v2o = util.getOrth(
                    self.billes[solution[1]], self.billes[solution[2]])
                v1p, v2p = util.getPar(
                    self.billes[solution[1]], self.billes[solution[2]])

                # Choc
                v1of = v2o
                v2of = v1o
                v1pf = v1p
                v2pf = v2p

                alpha = util.getAlpha(
                    self.billes[solution[1]], self.billes[solution[2]])

                self.billes[solution[1]].alpha = np.pi - \
                    alpha - np.arctan2(v1pf, v1of)
                self.billes[solution[2]].alpha = alpha - \
                    np.pi / 2 + np.arctan2(v2of, v2pf)

                self.billes[solution[1]].v[0] = 0
                self.billes[solution[2]].v[0] = 0
                self.billes[solution[1]].glissement = False
                self.billes[solution[1]].glissement = False
                self.billes[solution[1]].v[1] = np.sqrt(v1of ** 2 + v1pf ** 2)
                self.billes[solution[2]].v[1] = np.sqrt(v2of ** 2 + v2pf ** 2)

                if self.billes[solution[1]].v[1] <= 0:
                    self.billes[solution[1]].arret = True
                else:
                    self.billes[solution[1]].arret = False
                if self.billes[solution[2]].v[1] <= 0:
                    self.billes[solution[2]].arret = True
                else:
                    self.billes[solution[2]].arret = False

        self.lastTau = tau