Example #1
0
def test_solver():
    """Verify linear/quadratic solution."""
    # Set input data for the test
    I = 1.2; V = 3; m = 2; b = 0.9; k = 4
    s = lambda u: k*u
    T = 2
    dt = 0.2
    N = int(round(T/dt))
    time_points = np.linspace(0, T, N+1)

    # Test linear damping
    t = sp.Symbol('t')
    q = 2  # arbitrary constant
    u_exact = I + V*t + q*t**2   # sympy expression
    F_term = lhs_eq(t, m, b, s, u_exact, 'linear')
    print 'Fitted source term, linear case:', F_term
    F = sp.lambdify([t], F_term)
    u, t_ = solver(I, V, m, b, s, F, time_points, 'linear')
    u_e = sp.lambdify([t], u_exact, modules='numpy')
    error = abs(u_e(t_) - u).max()
    tol = 1E-13
    assert error < tol

    # Test quadratic damping: u_exact must be linear
    u_exact = I + V*t
    F_term = lhs_eq(t, m, b, s, u_exact, 'quadratic')
    print 'Fitted source term, quadratic case:', F_term
    F = sp.lambdify([t], F_term)
    u, t_ = solver(I, V, m, b, s, F, time_points, 'quadratic')
    u_e = sp.lambdify([t], u_exact, modules='numpy')
    error = abs(u_e(t_) - u).max()
    assert error < tol
 def setUp(self):
     self.testcube = solver()
     self.solved = cube()
     self.strings = ["FRLUULRFFBLF","FBFRRBLF","UULLFBLUURRDDBDRDLLFBBB",
                     "DBLURFBLURUDDDBFRLLRUFFB","BRBULFFUDDUBRBURLDUBLDRU",
                     "BFRDUFRLURFBDURBFLRUULRDBFLRUFBRLDUFRDDRFBLDUFBDRLUBF",
                     "UBRDULRUDRURBFURDBFRDLUBFRLUDBFRDUBFRLUDBFRURDFBURLBF"]
Example #3
0
def test_all_functions():
    """Verify a linear/quadratic solution."""
    I = 1.2; V = 3; m = 2; b = 0.9
    s = lambda u: 4*u
    t = sp.Symbol('t')
    T = 2
    dt = 0.2
    N = int(round(T/dt))
    time_points = np.linspace(0, T, N+1)

    def solver_linear_damping_wrapper(
        I, V, m, b, s, F, t, damping='linear'):
        """Wrapper such that solver_linear_damping can be called as solver."""
        if callable(F):
            F = F(t)
        return solver_linear_damping(I, V, m, b, s, F, t), t

    functions = [solver, solver_linear_damping_wrapper]
    try:
        from solver_cy import solver as solver_cy
        functions.append(solver_cy)
    except ImportError:
        print 'Cython module is not compiled'
        pass

    for function in functions:
        print 'testing', function.__name__
        # Test linear damping
        q = 2  # arbitrary constant
        u_exact = I + V*t + q*t**2
        u_e = sp.lambdify(t, u_exact, modules='numpy')
        F = sp.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'linear'))
        u, t_ = solver(I, V, m, b, s, F, time_points, 'linear')
        error = abs(u_e(t_) - u).max()
        nt.assert_almost_equal(error, 0, places=13)

        # Test quadratic damping
        if function != solver_linear_damping_wrapper:

            # In the quadratic damping case, u_exact must be linear
            # in order exactly recover this solution
            u_exact = I + V*t
            u_e = sp.lambdify(t, u_exact, modules='numpy')
            F = sp.lambdify(t, lhs_eq(t, m, b, s, u_exact, 'quadratic'))
            u, t_ = solver(I, V, m, b, s, F, time_points, 'quadratic')
            error = abs(u_e(t_) - u).max()
            nt.assert_almost_equal(error, 0, places=13)
Example #4
0
def test(size):
  a = generate_a(size)
  x = generate_x(size)
  b = a.dot(x)
  xx = solver.solver(a,b)
  print(x)
  print("result:",xx)
  print(linalg.norm(x-xx))
Example #5
0
def box_actions(results, times, N_matrix, ifprint):
    """
        Finds actions, angles and frequencies for box orbit.
        Takes a series of phase-space points from an orbit integration at times t and returns
        L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
    """
    if ifprint:
        print ("\n=====\nUsing triaxial harmonic toy potential")

    t = time.time()
    # Find best toy parameters
    omega = toy.findbestparams_ho(results)
    if ifprint:
        print ("Best omega " + str(omega) + " found in " + str(time.time() - t) + " seconds")

    # Now find toy actions and angles
    AA = np.array([toy.angact_ho(i, omega) for i in results])
    AA = AA[~np.isnan(AA).any(1)]
    if len(AA) == 0:
        return

    t = time.time()
    act = solver.solver(AA, N_matrix)
    if act == None:
        return

    if ifprint:
        print (
            "Action solution found for N_max = "
            + str(N_matrix)
            + ", size "
            + str(len(act[0]))
            + " symmetric matrix in "
            + str(time.time() - t)
            + " seconds"
        )

    np.savetxt("GF.Sn_box", np.vstack((act[1].T, act[0][3:])).T)

    ang = solver.angle_solver(AA, times, N_matrix, np.ones(3))
    if ifprint:
        print (
            "Angle solution found for N_max = "
            + str(N_matrix)
            + ", size "
            + str(len(ang))
            + " symmetric matrix in "
            + str(time.time() - t)
            + " seconds"
        )

    # Just some checks
    if len(ang) > len(AA):
        print ("More unknowns than equations")

    return act[0], ang, act[1], AA, omega
    def test_solving_steps(self):
       cubes = []
       for s in self.strings:
            c = solver()
            c.do_string(s)
            cubes.append(c)
       for c in cubes:
            c.solmoves = []
            c._upper_edges_FRBL()
            c._upper_edges_D()
            self.check_top_edges(c)

            c._upper_corners()
            self.check_top_corners(c)

            c.solve_middle()
            self.check_middle(c)

            c.solve_down()
            temp = solver()
            self.assertTrue(c == temp)
Example #7
0
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.rcube = solver()
        self.scramble_moves = []

        bframe = Frame(frame) #frame for cube manipulation

        #rotation buttons
        self.r = Button(bframe, text="Right", command=lambda: self.do_rotation('R'))
        self.r.grid(row=1)
        self.l = Button(bframe, text="Left", command=lambda: self.do_rotation('L'))
        self.l.grid(row=1,column=1)
        self.f = Button(bframe, text="Front", command=lambda: self.do_rotation('F'))
        self.f.grid(row=2)
        self.b = Button(bframe, text="Back", command=lambda: self.do_rotation('B'))
        self.b.grid(row=2,column=1)
        self.u = Button(bframe, text="Upper", command=lambda: self.do_rotation('U'))
        self.u.grid(row=3)
        self.d = Button(bframe, text="Down", command=lambda: self.do_rotation('D'))
        self.d.grid(row=3,column=1)

        self.newcube = Button(bframe, text="Create New Cube", command=self.create_cube)
        self.newcube.grid(row=0,column=0)

        self.scramble = Button(bframe, text="Scramble Cube",command=self.scramble_cube)
        self.scramble.grid(row=0,column=1)

        bframe.pack(side=RIGHT)

        downframe = Frame(frame)

        self.quit = Button(downframe, text="QUIT", fg="red", command=frame.quit)
        self.quit.pack(side=RIGHT)

        solveframe = Frame(downframe)

        self.solve = Button(solveframe, text="Solve Cube",command=self.solve_cube)
        self.solve.pack(side=LEFT)

        self.solinfo = Button(solveframe, text="Solution Info",command=self.sol_info)
        self.solinfo.pack(side=RIGHT)

        solveframe.pack(side=LEFT)
        downframe.pack(side=BOTTOM,pady=15,padx=15)

        self.cube_disp(frame)
Example #8
0
def loop_actions(results, times, N_matrix, ifprint):
    """
        Finds actions, angles and frequencies for loop orbit.
        Takes a series of phase-space points from an orbit integration at times t and returns
        L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
        results must be oriented such that circulation is about the z-axis
    """
    if(ifprint):
        print("\n=====\nUsing isochrone toy potential")
    
    t = time.time()
    # First find the best set of toy parameters
    params = toy.findbestparams_iso(results)
    if(params[0]!=params[0]):
        params = np.array([10.,10.])
    if(ifprint):
        print("Best params "+str(params)+" found in "+str(time.time()-t)+" seconds")

    # Now find the toy angles and actions in this potential
    AA = np.array([toy.angact_iso(i,params) for i in results])
    AA = AA[~np.isnan(AA).any(1)]
    if(len(AA)==0):
        return 

    t = time.time()
    act = solver.solver(AA, N_matrix,symNx = 1)
    if act==None:
        return

    if(ifprint):
        print("Action solution found for N_max = "+str(N_matrix)+", size "+str(len(act[0]))+" symmetric matrix in "+str(time.time()-t)+" seconds")

    # Store Sn
    np.savetxt("GF.Sn_loop",np.vstack((act[1].T,act[0][3:])).T)

    # Find angles
    sign = np.array([1.,np.sign(results[0][0]*results[0][4]-results[0][1]*results[0][3]),1.])
    ang = solver.angle_solver(AA,times,N_matrix,sign,symNx = 1)
    if(ifprint):
        print("Angle solution found for N_max = "+str(N_matrix)+", size "+str(len(ang))+" symmetric matrix in "+str(time.time()-t)+" seconds")
    
    # Just some checks
    if(len(ang)>len(AA)):
        print("More unknowns than equations")

    return act[0], ang, act[1], AA, params
Example #9
0
def generate_bumpy_road(nbumps=12, L=200, resolution=500):
    """Generate one road profile by using a vibration ODE."""
    n = nbumps*resolution      # no of compute intervals along the road
    x = np.linspace(0, L, n+1) # points along the road
    dx = x[1] - x[0]           # step along the road
    white_noise = np.random.randn(n+1)/np.sqrt(dx)
    # Compute h(x)
    k = 1.
    m = 4.
    if dx > 2/np.sqrt(k/m):
        print 'Unstable scheme'
    def s(u):
        return k*u

    h, x = solver(I=0, V=0, m=m, b=3, s=s, F=white_noise,
                  t=x, damping='linear')
    h = h/h.max()*0.2
    return h, x
Example #10
0
def test_compare_action_prepare():

    from ..actionangle import _action_prepare, _angle_prepare
    import solver
    logger.setLevel(logging.ERROR)
    AA = np.random.uniform(0., 100., size=(1000,6))
    t = np.linspace(0., 100., 1000)

    act_san,n_vectors = solver.solver(AA, N_max=6, symNx=2)
    A2,b2,n = _action_prepare(AA, N_max=6, dx=2, dy=2, dz=2)
    act_apw = np.array(solve(A2,b2))

    ang_san = solver.angle_solver(AA, t, N_max=6, symNx=2, sign=1)
    A2,b2,n = _angle_prepare(AA, t, N_max=6, dx=2, dy=2, dz=2)
    ang_apw = np.array(solve(A2,b2))

    assert np.allclose(act_apw, act_san)
    assert np.allclose(ang_apw, ang_san)
Example #11
0
def getpost():
    """
    Stdin comes from the web page and is a set of letters.

    Call solver and send the solution (an html table) to stdout.
    """
    logging.basicConfig(filename='results.log',level=logging.DEBUG)
    cgitb.enable()
    form = cgi.FieldStorage()
    instr = form["data"].value.replace(' ','0')
    pieces = list(instr)
    logging.info(pieces)
    answer = solver(pieces)
    print "Content-type: text/html"
    print
    logging.info('response: ')
    logging.info(answer)
    print answer
Example #12
0
 def main(self):
     solver= sol.solver();
     i=0;
     answer=""
     while i!=-1:
         print("Please chose one of the modes");
         print("1.SA-KQ");
         print("2.SA-GC");
         print("3.MC-KQ");
         print("4.MC-GC");
         print("5.Exit");
         answer=input(">>");
         try:
             index=int(answer);
         except ValueError:
             continue;
         if(index==1):
             print("1")
             print("Puzzle size ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             puzzle=K.K_Puzzle(nr)
             print("How many neighbours? ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             solver.algorithm_SA(puzzle,nr)
         elif(index==2):
             print("2")
         elif(index==3):
             print("3")
             print("Puzzle size ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             puzzle=K.K_Puzzle(nr)
             print("How many neighbours? ");
             answer=input(">>");
             nr=gr.conv_str2int(answer)
             solver.algorithm_MC(puzzle,nr)
         elif(index==4):
             print("4")
         elif(index==5):
             print("5")
             i=-1
Example #13
0
def doit(name, n,r, g,W, x,z):
    print
    print
    print "// ------- Generated from kkt_test.py ---"
    print "template <typename Scalar> int kkt_test_%s() {" % name
    print
    print "typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;"
    print "typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;"
    print
    print "// Problem"
    print "int n = %d;" % n
    print "int r = %d;" % r
    print "Matrix g(n,n);"

    print "cvxopt::ScalingMatrix<Scalar> w;"
    print "w.d.resize(2*r*n);"
    print "Vector x(n*(r+1)), y, z(2*n*r);"

    print_cxx("x", x)
    print_cxx("z", z)

    print_cxx("g", g)
    print_cxx("w.d", W['d'])

    print
    print "// Solve"
    print "KQP_KKTPreSolver<Scalar> kkt_presolver(g, Vector::Ones(r));"
    print "boost::shared_ptr<cvxopt::KKTSolver<Scalar> > kktSolver(kkt_presolver.get(w));"
    print "kktSolver->solve(x,y,z);"
    print
    
    F = solver(n,r,g)
    sF = F(W)
    sF(x, None, z)

    print
    print "// Solution"
    
    print "Eigen::VectorXd s_x(n*(r+1)), s_z(2*n*r);"
    print_cxx("s_x", x)
    print_cxx("s_z", z)

    print """
Example #14
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 = a.solver(ai,af,0)
    t1 = time.clock()
    print t1-t0
    print mv.shape
Example #15
0
def getpost():
    """
    Stdin comes from the web page and is a set of sudoku numbers.

    Call solver and send the solution as a set of cell values to stdout.
    """
    logging.basicConfig(filename='results.log',level=logging.DEBUG)
    cgitb.enable()
    form = cgi.FieldStorage()
    instr = form["data"].value.replace(' ','0')
    pieces = list(instr);
    tplate = []
    indx = 0
    logging.info('input: ')
    logging.info(instr)
    for i in range(0,9):
        tplate.append([])
        for j in range(0,9):
           tplate[i].append(pieces[indx])
           indx += 1
    info_res, result = solver(tplate)
    logging.info('info_res:')
    logging.info(info_res)
    if info_res == 'failure':
        logging.info('failure')
        print "Content-type: text/html"
        print
        print instr.replace('0', ' ')
        return
    outstr = []
    for i in range(0,9):
        for j in range(0,9):
            outstr.append(result[i][j])
    print "Content-type: text/html"
    print
    response = ''.join(outstr).replace('0', ' ')
    logging.info('response: ')
    logging.info(response)
    print response
Example #16
0
tests = 0

all_lines = []
full_dict = []
cases = []

with open(in_file) as f:
	all_lines = f.readlines()

params = all_lines[0]
params = params.split(" ");
wordsize = int(params[0])
dictSize = int(params[1])
tests = int(params[2])

full_dict = all_lines[1:1+dictSize]
cases = all_lines[1+dictSize:]
	
word_graph = alien_dict(full_dict, wordsize)

for i in range(len(cases)):
	cases[i] = ip.parse_raw(cases[i])

result = dict()

for i in range(len(cases)):
	result[i+1] = sv.solver(word_graph, cases[i]).solve()

for key, val in result.items():
	print('Case {}: {}'.format(key, val))
Example #17
0
v = 2.0                         # velocity (constant)

# Vertical displacement calculation
m = 2                           # mass of the system
b = 0.2                         # friction parameter
k = 1.5                         # spring parameter
T = road_xmax/v                 # end time
t = np.linspace(0, T, n+1)      # numerical time mesh
s = lambda u: k*u               # restoring force of spring
F = lambda t: -m*d2h(v*t)       # excitation force

import sys, os
sys.path.insert(0, os.path.join(os.pardir, 'src-bumpy'))
import solver

u, t = solver.solver(I=0, V=0, m=m, b=b, s=s, F=F, t=t,
                     damping='linear')

u_amplitude = (u.max() - u.min())/2
u_scaled = R*u/u_amplitude
u_solution = Curve(v*t, 5*H + u_scaled).set_linecolor('blue').set_linewidth(1)

arc_length = 0  # arc_length along road

def draw_vehicle(x, y, x0, y0, u):
    mass_width = 3*R
    mass_height = 1.5*R
    spring_length = 3*R
    spring_start = (x, y+2*R)

    tire_center = point(x, y+R)
    tire = Composition({
Example #18
0
def main():
    input = input_pipeline()
    print("ready input pipeline")
    net = softmax_regression()
    _solver = solver(net, input, './log')
    _solver.train_and_test()
Example #19
0
 def test_solver_on_small_data(self):
     data = '../data/words_small.txt'
     [largest_word, second_largest_word, count] = solver(data)
     self.assertEquals(largest_word, (11, ['catsdogcats']))
     self.assertEquals(second_largest_word, (10, ['dogcatsdog']))
     self.assertEquals(count, 3)
Example #20
0
	if args.none is True:
		args.debug = False
		args.correction = False
	commands = commands_gen([x.upper() for x in args.Moves])
	verbose = ""
	if len(commands) != 0:
		if args.ultraverbose is True:
			verbose += f"{'Original Cube':^22}\n\n{ft_print(cube)}\n\n"
		if args.debug is False and args.correction is False and args.none is False:
			print(f"{'Scramble Moves'} ({len(commands)}):\n{' '.join(args.Moves)}\n")
		mv.use_move(commands, cube)
		if args.ultraverbose is True:
			verbose += f"{'Scrambled Cube':^22}\n\n{ft_print(cube)}\n"
		if cube == full_cube:
			sys.exit("Cube was already solved")
		solved, solved_len, tmp_vb = solver.solver(cube, args.ultraverbose, args.verbose, args.time)
		verbose += tmp_vb
		if args.time is True and solved_len != 0:
			if args.verbose is True:
				verbose += f"\nTotal time : {timer() - start:.5f} seconds\n"
			else:
				print(f"Total time : {timer() - start:.5f} seconds\n")
		print_verbose(args.verbose, verbose)
		if args.none is True:
			print(solved)
		if solved_len != 0 and args.debug is False and args.correction is False and args.none is False:
			print(f"Total moves to solve ({solved_len}):\n{solved}")
		if args.debug is True and args.correction is False:
			print(f"nb_s: {len(commands):>3} | nb_m: {solved_len:>3} | time: {timer() - start:>6.5f} ")
		if args.correction is True:
			print(f"{' '.join(args.Moves)} {solved}")
Example #21
0
def has_WIN():
	for num in winning_numbers:
		assert solver.solver(num, fourtozero.primitive, fourtozero.gen_moves, fourtozero.do_moves) == fourtozero.WIN
Example #22
0
def box_line(board, cands, square_pos):
    ischanged = 0

    #check row by row
    for rows in range(9):
        use = cands.loc[rows].dropna()
        for val in range(1, 10):
            inxs = use.apply(lambda x: val in x)
            # if len(inxs) == 0:
            if len(inxs) < 2:
                break
            inxs = list(inxs.index[inxs])

            #find locations of the box/line reduction candidates
            if len(inxs) == 2 or len(inxs) == 3:
                board_pos = square_pos.loc[rows][inxs]
                if np.diff(board_pos).sum() == 0:
                    square = board_pos.iloc[0]
                    inx = pd.Series(square_pos[square_pos ==
                                               square].stack().index.tolist())

                    #go through the square cells except the box/line
                    for ix in inx:
                        if ix[0] != rows:
                            # if ix != (rows,board_pos.index[0]) and ix != (rows,board_pos.index[1]) and ix != (rows,board_pos.index[2]):
                            try:
                                temp = cands.iloc[ix].tolist()
                                temp.remove(val)
                                # cands.iloc[ix] = np.array(temp)
                                cands.set_value(ix[0], ix[1], np.array(temp))
                                ischanged = 1
                                print(
                                    f"R{ix[0]}C{ix[1]}     Box/Line (row) reduction value {val} removed"
                                )
                                # solver.solver(board,cands,square_pos)
                            except:
                                pass

        #columns
        for cols in range(9):
            use = cands[cols].dropna()
            for val in range(1, 10):
                inxs = use.apply(lambda x: val in x)
                # if len(inxs) == 0:
                if len(inxs) < 2:
                    break
                inxs = list(inxs.index[inxs])

                #find locations of the box/line reduction candidates
                if len(inxs) == 2 or len(inxs) == 3:
                    board_pos = square_pos[cols][inxs]
                    if np.diff(board_pos).sum() == 0:
                        square = board_pos.iloc[0]
                        inx = pd.Series(square_pos[
                            square_pos == square].stack().index.tolist())

                        #go through the square cells except the box/line
                        for ix in inx:
                            if ix[1] != cols:
                                # if ix != (board_pos.index[0],cols) and ix != (board_pos.index[1],cols):
                                try:
                                    temp = cands.iloc[ix].tolist()
                                    temp.remove(val)
                                    # cands.iloc[ix] = np.array(temp)
                                    cands.set_value(ix[0], ix[1],
                                                    np.array(temp))
                                    ischanged = 1
                                    print(
                                        f"R{ix[0]}C{ix[1]}     Box/Line (col) reduction value {val} removed"
                                    )
                                    # solver.solver(board,cands,square_pos)
                                except:
                                    pass

    if ischanged:
        solver.solver(board, cands, square_pos)
                                               pin_memory=False,
                                               shuffle=True)

    # model
    model = Encoder_Decoder(args.hidden_size)
    if args.load:
        continue_epochs, continue_iters = load_checkpoint(model, load_pth)

    if use_cuda:
        model = model.cuda()

    if not args.load:
        solver(model,
               train_loader,
               args.num_epochs,
               print_every=20,
               save_every=10000,
               output_dir=output_dir,
               learning_rate=args.learning_rate,
               step=args.step)
    else:
        solver(model,
               train_loader,
               args.num_epochs,
               print_every=20,
               save_every=10000,
               output_dir=output_dir,
               learning_rate=args.learning_rate,
               step=args.step,
               continue_epochs=continue_epochs,
               continue_iters=continue_iters)
Example #24
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()
block_length = 280/9 # 棋盤格子長度
block_width = 262/9

# 以下 板子正中央為 90 deg
waiting_action = [30, 0, 64, 178, 179, 0, 38] # 落子後的待機位置

ang_90 = 85 # 用90為基準修正,想要轉90度時的實際角度
y_center = 95 # 轉軸正中央相對於基準面的高度
y_150 = 108 # 用0為基準修正,150.0時相對於基準面的高度
y_400 = 118 # 用0為基準修正,400.0時相對於基準面的高度
y_board = -95 + 50 # 落子的高度
y_board_chess = -95 + 26 # 夾棋子的高度

# -----------------------------------------------------------------

s = solver()
u = usb()

#! port here
class Global():
    @staticmethod
    def port():
        return 'COM4'

def init(testMode):
    global u
    u.AddClient(Global.port(), 9600, show = False, testMode = testMode)
    u.Run()
    u.UserSend(data = waiting_action, port = Global.port())
    u.Wait(port=Global.port())
from cube import cube
from solver import solver

cb = solver()
done = False
while not done:
    ms = raw_input("Scramble String: ")
    ms = ms.upper()
    done = True
    for c in ms:
        done = done and ((c in cb.sides) or (c in ["2", "3"]) or (c == "'"))
    if not done:
        print "You used an invalid character"

cb.do_string(ms)
cb.solve()
disp = cube()
disp.do_string(ms)

print "Initial cube state:"
disp.print_cube()
for step in cb.solmoves:
    raw_input("next move is: " + step)
    disp.do_string(step)
    disp.print_cube()
Example #27
0
for y in range(3):
    for x in range(3):
        coords.append((dx * x, dy * y))

s = ''
while True:
    #s = input()
    if s == 'exit':
        break
    sleep(3)
    pyautogui.press('space')
    sleep(1)
    print('start inspection')
    stickers = []
    for face in range(6):
        img = np.array(
            ImageGrab.grab(bbox=(strt_x, strt_y, end_x + 1, end_y + 1)))
        pyautogui.press(inspection_commands[face])
        for x, y in coords:
            stickers.append(color(x, y))
        sleep(0.1)
    strt = time()
    solution = solver(stickers)
    print('solution found in ', time() - strt, 'sec')
    print('len is', len(solution))
    solution_str = ''.join(''.join(j for j in twists_key[i]) for i in solution)
    print('len of type is', len(solution_str))
    pyautogui.typewrite(solution_str)
    print('done')
    print('')
Example #28
0
from matplotlib.pyplot import *
plot(t, u)
savefig('tmp.pdf')   # save plot to PDF file
savefig('tmp.png')   # save plot to PNG file
show()
# End solver_linear_damping

import numpy as np
from numpy import sin, pi  # for nice math
from solver import solver

def F(t):
    # Sinusoidal bumpy road
    return A*sin(pi*t)

def s(u):
    return k*(0.2*u + 1.5*u**3)

A = 0.25
k = 2
t = np.linspace(0, 100, 10001)
u, t = solver(I=0.1, V=0, m=2, b=0.5, s=s, F=F, t=t,
              damping='quadratic')

# Show u(t) as a curve plot
import matplotlib.pyplot as plt
plt.plot(t, u)
plt.savefig('tmp.png')
plt.savefig('tmp.pdf')
plt.show()
Example #29
0
 def get_x_t(self):
     """Dummy solver call just to get the x & t"""
     _, _, x, t, _ = solver(I=0, V=0, f=0, q=0, c=1, L=self.L, dt=self.dt, C=self.C, T=self.T)
     return x, t
Example #30
0
def entradaTexto(ecuaciones,
                 pyENL_timeout,
                 varsObj=None,
                 tol=None,
                 method='hybr'):
    '''
    ecuaciones es una lista de cadenas de texto con ecuaciones de entrada.
    varsObj define si llegan objetos variable como entrada.
    La salida de esta función está dada por
    '''
    lista = []
    dicc_condiciones = {}
    # Si el método no está listado entonces no se procede
    # method = method.strip(' ')
    methods = [
        'hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing',
        'diagbroyden', 'excitingmixing', 'krylov', 'df-sane'
    ]
    if method not in methods:
        raise Exception('El método de resolución no está listado, ver ayuda.')
    for ie, eqn in enumerate(ecuaciones):
        if ((eqn.replace(' ', '').replace('\t', '') != '') and
            ('{' not in eqn)) and ('<<' not in eqn):
            expresion = eqn.replace(" ", "")
            expresion = expresion.replace('\t', '')
            # Capacidad de interpretar pow
            expresion = expresion.replace("^", "**")
            izq_der = expresion.split('=')
            operandos = ["+", "-", "*", "/", "("]
            # Revisar que no haya operadores incompletos
            if (izq_der[0][-1] in operandos) or (izq_der[1][-1] in operandos):
                raise Exception('Ecuación mal escrita: ' + str(ie + 1))
            # Revisar que no hayan paréntesis sin cerrar
            par_err1 = izq_der[0].count("(") != izq_der[0].count(")")
            par_err2 = izq_der[1].count("(") != izq_der[1].count(")")
            if par_err1 or par_err2:
                raise Exception("No cierran los paréntesis en " + str(ie + 1))
            paraRaiz = izq_der[0] + \
                '-(' + izq_der[1] + ')'  # Igualación de cero
            lista.append(paraRaiz)
        if '{' in eqn:
            # Entonces acá vienen condiciones, que son de la forma:
            #   {x,first_guess,-lim,+lim}
            if '}' not in eqn:
                raise Exception("Falt cerrar corchete")
            condicion = find_between(eqn, '{', '}')
            condicion = condicion.replace(' ', '')
            condiciones = condicion.split(',')
            dicc_condiciones.update({condiciones[0]: condiciones[1:4]})

    # Lista contiene las ecuaciones
    lista_vars = []
    for ecuacion in lista:
        lista_vars = lista_vars + variables(ecuacion)
    lista_vars = list(set(lista_vars))
    variables_salida = []
    for miembro in lista_vars:
        # Crear los objetos pyENL_variable a partir de los strings de nombres
        # de vars
        objeto = pyENL_variable(miembro)
        # Ahora verificar que se encuentre listada en las condidiones
        # Si se puede definir directamente entonces dejar ese valor inicial
        # Es decir, tomar el valor del guess como el sugerido en una ecuación
        # Tipo:
        # x = ln(y)
        # y = 5
        # Entonces el valor inicial de y será 5, aún si el usuario no lo deja
        # especificado por los corchetes {}
        for cadaEqn in lista:
            varAux = cadaEqn
            varAux = varAux.replace(objeto.name + '-', '')
            try:
                objeto.guess = eval(varAux)
            except:
                pass
            # Si no, entonces buscar si ya hay una definición:
        try:
            objeto.guess = float(dicc_condiciones[miembro][0])
        except:
            pass
        try:
            objeto.lowerlim = float(dicc_condiciones[miembro][1])
        except:
            pass
        try:
            objeto.upperlim = float(dicc_condiciones[miembro][2])
        except:
            pass
        # Se van añadiendo los objetos de salida de las variables:
        variables_salida.append(objeto)
    pyENL_inicio = time()  # Tiempo de inicio de llamada al solver
    # Llamada al solver
    # Si los objetos variables ya vienen entonces:
    if varsObj:
        variables_salida = varsObj
    pyENL_solved = False
    try:
        pyENL_solucion = solver(lista,
                                variables_salida,
                                tol=tol,
                                method=method)
        pyENL_solved = True
        pyENL_final = time()
        pyENL_transcurrido = pyENL_final - pyENL_inicio
    except Exception as e:
        # exit(0)
        # Intento aleatorio
        # Si el error es de sintaxis hay que detectarlo sin que intente
        # nuevamente buscar soluciones infructuosamente:
        er = str(e)
        if 'de tipeo' in er:
            raise Exception(er)
        if 'Cannot convert' in er or 'is not defined in the unit registry' in er:
            raise Exception(er)
        if 'Improper input parameters were entered.' in er:
            raise Exception('Parámetros inválidos suministrados')
        if 'de sintaxis' in er:
            raise Exception(er)
        if 'No se ha definido' in er:
            # Una función no está definida
            raise Exception(er)
        if 'como variable en' in er:
            raise Exception(er)
        if 'Faltan argumentos' in er:
            raise Exception(er)
        if 'inadecuado en función' in er:
            raise Exception(er)
        if 'Mala entrada' in er:
            raise Exception(er)
        if 'No se tienen los valores' in er:
            raise Exception(er)
        if 'debe tener unidades' in er:
            raise Exception(er)
        pyENL_final = time()
        pyENL_transcurrido = pyENL_final - pyENL_inicio
        while pyENL_transcurrido < pyENL_timeout:
            # Encontrar nuevos valores de guesses:
            for cont, objetoVar in enumerate(variables_salida):
                obtemp = objetoVar  # Objeto variable temporal
                obtemp.guess = random_lim(objeto.lowerlim, objeto.upperlim)
                variables_salida[cont] = obtemp
            # Termina de actualizar, ahora:
            try:
                pyENL_solucion = solver(lista,
                                        variables_salida,
                                        tol=1.49012e-08)
                pyENL_solved = True
                break
            except Exception as e:
                er = str(e)
                if 'de tipeo' in er:
                    raise Exception(er)
                if 'Cannot convert' in er or 'is not defined in the unit registry' in er:
                    raise Exception(er)
                if 'Improper input parameters were entered.' in er:
                    raise Exception('Parámetros inválidos suministrados')
                if 'de sintaxis' in er:
                    raise Exception(er)
                if 'No se ha definido' in er:
                    # Una función no está definida
                    raise Exception(er)
                if 'como variable en' in er:
                    raise Exception(er)
                if 'Faltan argumentos' in er:
                    raise Exception(er)
                if 'inadecuado en función' in er:
                    raise Exception(er)
                if 'Mala entrada' in er:
                    raise Exception(er)
                if 'No se tienen los valores' in er:
                    raise Exception(er)
                if 'debe tener unidades' in er:
                    raise Exception(er)
                if 'Error de unidades' in er:
                    raise Exception(er)
            # Actualiza el tiempo que ha transcurido:
            pyENL_final = time()
            pyENL_transcurrido = pyENL_final - pyENL_inicio
    if pyENL_solved == False:
        raise Exception(
            'El tiempo de espera ha sido superado, verifique las ecuaciones')
    if pyENL_solucion == 'Error ecuaciones/variables':
        raise ValueError("Hay " + str(len(lista)) + ' ecuación(es) y ' +
                         str(len(variables_salida)) + ' variable(s)')
    return [pyENL_solucion, pyENL_transcurrido]
Example #31
0
def pretty_print(board):
    for i in range(len(board)):
        print board[i]


edge = 4

lst_board = 'D C L P  E I A E  R N T R  S E G S'.lower().split()


board = []
for i in range(0,16,4):
    board.append(lst_board[i:i+4])
pretty_print(board)
s = solver.solver(edge)
words =  sorted(s.solve(board))
print words

score = 0
for word in words:
    if len(word) == 3 or len(word) == 4:
        score += 1
    if len(word) == 5:
        score += 2
    if len(word) == 6:
        score += 3
    if len(word) > 6:
        score += 5
print score
    
Example #32
0
def naked_triples(board, cands, square_pos):
    ischanged = 0

    #rows
    for row in range(9):
        use = cands.loc[row].dropna()

        #go through combinations (3 elements at a time)
        for comb in itertools.combinations(use, 3):
            comb = [i.tolist() for i in comb]
            temp = []
            for i in comb:
                temp.extend(i)
            naked_triple = pd.Series(temp).unique()
            if len(naked_triple) == 3:

                #remove naked triple elements from the rest of the row
                for j in use.index:
                    try:
                        used = use[j].tolist()
                        if not used in comb:
                            temp1 = used
                            for nt in naked_triple:
                                try:
                                    temp1.remove(nt)
                                    use[j] = np.array(temp1)
                                    print(
                                        f"R{row}C{j}     Naked Triple (rows), {nt} removed, Triple: {naked_triple}"
                                    )
                                    ischanged = 1
                                except:
                                    pass
                    except:
                        pass

                cands.loc[row] = use

    #cols
    for col in range(9):
        use = cands[col].dropna()

        #go through combinations (3 elements at a time)
        for comb in itertools.combinations(use, 3):
            comb = [i.tolist() for i in comb]
            temp = []
            for i in comb:
                temp.extend(i)
            naked_triple = pd.Series(temp).unique()
            if len(naked_triple) == 3:

                #remove naked triple elements from the rest of the column
                for j in use.index:
                    try:
                        used = use[j].tolist()
                        if not used in comb:
                            temp1 = used
                            for nt in naked_triple:
                                try:
                                    temp1.remove(nt)
                                    use[j] = np.array(temp1)
                                    print(
                                        f"R{j}C{col}     Naked Triple (columns), {nt} removed, Triple: {naked_triple}"
                                    )
                                    # print(f"Column{col} Naked triples removed {nt}, {comb}")
                                    ischanged = 1
                                except:
                                    pass
                    except:
                        pass

                cands[col] = use

    if ischanged:
        solver.solver(board, cands, square_pos)
Example #33
0
File: test.py Project: bpiwowar/kqp
    print
    print "=== G"
    print G
    print
    print "=== h"
    print h.T
    print

    
print "=== Problem size: n=%d and r=%d ===\n\n" % (n, r)
print "* np = %d" % np
print "* lambda = %g" % Lambda

print "\n\n   [[[Solving with optimised]]]"
T1 = time()
sol = solvers.coneqp(P, q, G, h, kktsolver=solver(n,r,g))
print "Time taken = %s" % (time() - T1)
print sol['status']
if (n * r < 10): print "Solution = %s" % sol['x'].T

printing.options['width'] = n

nzeros=0
xi = sol['x'][n*r:n*(r+1)]
maxxi=max(xi)
print sum(xi[0:n])
for i in xrange(n):
    if xi[i]/maxxi < 1e-4: nzeros += 1

print "xi = %s" % sorted(xi.T/maxxi)
print "Sparsity = %d on %d" % (nzeros, n)
def main():
  # sentences = ['distance is speed times time', 'energy is force times distance',
  #              'energy is power times time', 'power is speed times force']
  sentences = ['distance is speed times time', 'speed times time is distance',
               'force is mass times acceleration',
               'speed is acceleration times time', 'power is speed times force',
               'energy is force times distance', 'energy is power times time',
               'speed is distance divided by time',
               'acceleration is speed divided by time',
               'speed times force is power',
               'speed is power divided by force']
  # sentences = [
  #   'distance is speed times time',
  #   'speed times time is distance',
  #   'speed is distance divided time',
  #   'distance is speed2 times time',
  #              'speed2 times time is distance',
  #              'speed2 is distance divided time',
  #              ]
  tuples = generateTuples(sentences)
  # [
  # [
  #     ('f', frozenset(['m', 'a']))
  #   ],
  #   [
  #     ('p', frozenset(['s', 'f']))
  #   ]
  # ]
  (solutions, globalStats) = solver.solver(tuples, [solver.featureConsistentTemplates, solver.validModels, solver.featurePercentagesTemplates, solver.featureMajorityTemplates])

  # solMap = {}
  # for s in solutions.keys():
  #   varSet = set({s[0][0]}).union(s[0][1])
  #   k = (varSet,s[1][0].word,s[1][1].word)
  #   if not solMap.has_key(k):
  #     solMap[k] = solutions[s]
  #   elif solutions[s]>solMap[k]:
  #     solMap[k] = solutions[s]

  pprint.pprint(solutions)
  pprint.pprint(globalStats)

  f1TimesCount = 0
  f1DividedCount = 0
  f2TimesCount = 0
  f2DividedCount = 0
  f3TimesCount = 0
  f3DividedCount = 0

  for (k, c) in solutions.iteritems():
    if k[1][1].word == "times" and k[1][0].templateNumber == 0: f1TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 0: f1DividedCount += c
    if k[1][1].word == "times" and k[1][0].templateNumber == 1: f2TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 1: f2DividedCount += c
    if k[1][1].word == "times" and k[1][0].templateNumber == 2: f3TimesCount += c
    if k[1][1].word == "divided" and k[1][0].templateNumber == 2: f3DividedCount += c

  print f1TimesCount
  print f1DividedCount
  print f2TimesCount
  print f2DividedCount
  print f3TimesCount
  print f3DividedCount
Example #35
0
b = 0.8  # friction parameter
k = 2  # spring parameter
V = 1.5
T = road_xmax / v  # end time
t = np.linspace(0, T, 101)  # numerical time mesh
s = lambda u: k * u  # restoring force of spring
F = lambda t: -m * d2h(v * t)  # excitation force

import sys, os

sys.path.insert(0, os.path.join(os.pardir, "src-bumpy"))
import solver

print road_xmax, T, v, v * T

u, t = solver.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()
"""
u_solution = Curve(v * t, 5 * H + 0.5 * H * u)

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))}),
Example #36
0
def fem(le, beta_values, num_elements_in_region, total_num_elements, EpsilonR,
        MuR):
    A, B = assembly(num_elements_in_region, total_num_elements, le,
                    beta_values, EpsilonR, MuR)
    eig_values, eig_vectors = solver(A, B)
    return eig_values, eig_vectors
Example #37
0
m = 2  # mass of the system
b = 0.8  # friction parameter
k = 2  # spring parameter
V = 1.5
T = road_xmax / v  # end time
t = np.linspace(0, T, 101)  # numerical time mesh
s = lambda u: k * u  # restoring force of spring
F = lambda t: -m * d2h(v * t)  # excitation force

import sys, os
sys.path.insert(0, os.path.join(os.pardir, 'src-bumpy'))
import solver

print road_xmax, T, v, v * T

u, t = solver.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()
'''
u_solution = Curve(v * t, 5 * H + 0.5 * H * u)

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),
Example #38
0
 def create_cube(self):
     del self.rcube
     self.rcube = solver()
     self.output_cube()
     self.scramble_moves = []
Example #39
0
def has_LOSE()):
	for num in losing_numbers:
		assert solver.solver(num, fourtozero.primitive, fourtozero.gen_moves, fourtozero.do_moves) == fourtozero.LOSE