Example #1
0
def algRaySphereIntersection(sphere, ray):
    b = 2 * (ray.direction.x *
             (ray.origin.x - sphere.center.x) + ray.direction.y *
             (ray.origin.y - sphere.center.y) + ray.direction.z *
             (ray.origin.z - sphere.center.z))
    c = square(ray.origin.x - sphere.center.x) + square(
        ray.origin.y -
        sphere.center.y) + square(ray.origin.z -
                                  sphere.center.z) - sphere.square_radius
    discriminant = square(b) - 4 * c
    # The ray misses the sphere
    if discriminant < 0:
        return None
    # The square root of the discriminant is precomputed since
    # taking the square root is often an expensive operation.
    sqrt_discriminant = sqrt(discriminant)
    t0 = (-b - sqrt_discriminant) / 2
    # Intersection is not behind the origin of the ray
    if t0 >= 0:
        return Vector(
            array([
                ray.origin.x + ray.direction.x * t0,
                ray.origin.y + ray.direction.y * t0,
                ray.origin.z + ray.direction.z * t0
            ]))
    else:
        t1 = (-b + sqrt_discriminant) / 2
        return Vector(
            array([
                ray.origin.x + ray.direction.x * t1,
                ray.origin.y + ray.direction.y * t1,
                ray.origin.z + ray.direction.z * t1
            ]))
Example #2
0
    def adadelta(allparams,
                 nat_stepsize,
                 num_epochs,
                 seq_len,
                 num_seqs=None,
                 rho=0.95,
                 epsilon=1e-6,
                 num_samples=1,
                 permute=True):
        natparams, params = allparams[:1], allparams[1:]
        sum_gsq = zeros_like(params)  # accumulated sq. grads
        sum_usq = zeros_like(params)  # accumulated sq. updates
        accumulate = lambda a, b: add(scale(rho, a), scale(1 - rho, b))

        for epoch in xrange(num_epochs):
            vals = []
            batches, num_batches = split_into_batches(data, seq_len, num_seqs)
            for y in batches:
                val, grad = scale(
                    1. / num_datapoints,
                    val_and_grad(y, num_batches, num_samples, *allparams))
                natgrad, grad = grad[:1], grad[1:]
                sum_gsq = accumulate(sum_gsq, square(grad))
                diag_scaling = div(sqrt(add_scalar(epsilon, sum_usq)),
                                   sqrt(add_scalar(epsilon, sum_gsq)))
                update = mul(diag_scaling, grad)
                sum_usq = accumulate(sum_usq, square(update))

                natparams = add(natparams, scale(nat_stepsize, natgrad))
                params = add(params, update)
                allparams = concat(natparams, params)
                vals.append(val)

                if callback: callback(epoch, vals, natgrad, allparams)
        return allparams
Example #3
0
def raySphereIntersection(sphere, ray):
    # Origin of ray to center of sphere vector (Origin to Center)
    oc = sphere.center - ray.origin
    # Length squared of oc
    l2oc = oc.dot(oc)
    outside = l2oc > sphere.square_radius
    # t-value of point on the ray that is closest to the center of the sphere
    # (t Closest Approach)
    tca = oc.dot(ray.direction)
    # Ray originates outside the sphere and is pointing away from it,
    # therefore it cannot intersect it
    if tca < 0 and outside:
        return None
    t2ca = square(tca)
    # Check if the closest point is within the sphere, otherwise the ray misses
    d2 = square(l2oc - t2ca)
    t2hc = sphere.square_radius - d2
    if t2hc < 0:
        return None
    t = tca + sqrt(t2hc)
    if outside:
        t = tca - sqrt(t2hc)
    return Vector(
        array([
            ray.origin.x + ray.direction.x * t,
            ray.origin.y + ray.direction.y * t,
            ray.origin.z + ray.direction.z * t
        ]))
Example #4
0
def move():
    global T
    global cnt
    head = snake[-1].copy()
    head.move(aim)
    if head in walls:
        rectangle(-200, -195, 60, 20, 'white') f
        timer()
        ontimer(move, 100)
        return
    if head in pwalls:
        if pwalls.get(head) != None:
            pwalls[head] -= 1
            if pwalls[head] == 0:
                pwalls.pop(head)
                walls.add(head)
    if head in thorns:
        again()
        return
    for body in snake:
            for i in range(len(lasers)):
                if cnt > 0 and lasers[i][0].x <= body.x <= lasers[i][1].x and lasers[i][0].y <= body.y <= lasers[i][1].y:
                    again()
                    return
    if len(foods) == 0:
        nextstage()
        return
    if head in teledict:
        head = teledict[head]
    if head in foods:
        foods.remove(head)
    else:
        snake.pop(0)

    snake.append(head)
    clear()

    for body in snake:
        square(body.x, body.y, 9, 'black')
    for telep in teledict:
        square(telep.x, telep.y, 9, 'magenta')
        square(teledict[telep].x, teledict[telep].y, 9, 'purple')
    for food in foods:
        square(food.x, food.y, 9, 'green')
    for i in range(len(lasers)):
        if cnt > 0 : line(lasers[i][0].x, lasers[i][0].y+4.5, lasers[i][1].x, lasers[i][1].y+4.5)
        cnt += 1
        if cnt == 10: cnt = -5

    for wall in walls:
        square(wall.x, wall.y, 9, 'gray')
    for pwall in pwalls:
        squarenum(pwall.x, pwall.y, 9, 'blue', pwalls[pwall])
    for thorn in thorns:
        triangle(thorn.x, thorn.y, 9, 'red')
    timer()
    update()
    ontimer(move, 100)
Example #5
0
def fib_iter(a, b, p, q, count):
    logl("(" + str(a) + ", " + str(b) + ", " + str(p) + ", " + str(q) + ", " +
         str(count) + ")")

    if count == 0:
        return b
    elif even(count):
        return fib_iter(a, b,
                        square(p) + square(q), 2 * p * q + square(q),
                        count / 2)
    else:
        return fib_iter((b * q) + (a * q) + (a * p), (b * p) + (a * q), p, q,
                        (count - 1))
Example #6
0
 def fast_expt(b, n):
     if n == 0:
         return 1
     elif even(n):
         return square(fast_expt(b, n / 2))
     else:
         return b * fast_expt(b, n - 1)
Example #7
0
 def expmod(base, exp, m):
     if exp == 0:
         return 1
     elif even(exp):
         return square(expmod(base, exp / 2, m)) % m
     else:
         return base * expmod(base, exp - 1, m) % m
Example #8
0
def sarsa(amap, gamma, alpha, epsilon, num_episodes, seed):
    '''SARSA algorithm'''
    env = gym.make('FrozenLake-v0', desc=util.square(amap)).unwrapped

    env.seed(seed)
    np.random.seed(seed)

    Q = np.zeros([env.observation_space.n, env.action_space.n])

    for _ in range(num_episodes):
        state = env.reset()
        action = util.select_action(state, Q, epsilon, env)

        done = False
        while not done:
            next_state, reward, done, _ = env.step(action)
            next_action = util.select_action(next_state, Q, epsilon, env)
            update = reward + gamma * Q[next_state, next_action] - Q[state,
                                                                     action]
            Q[state, action] = Q[state, action] + alpha * update
            state = next_state
            action = next_action

    env.close()
    Q_star = np.argmax(Q, axis=1)
    mapping = ['<', 'v', '>', '^']
    return ''.join([mapping[action] for action in Q_star])
Example #9
0
        def sqrmod(x):
            def check_sqrt(x, square):
                if square == 1 and x != 1 and x != m - 1:
                    return 0

                return square

            return check_sqrt(x, square(x)) % m
Example #10
0
def fast_expt(b, n):
    logl("(" + str(b) + ", " + str(n) + ")")

    if n == 0:
        return 1
    elif even(n):
        return square(fast_expt(b, n / 2))
    else:
        return b * fast_expt(b, n - 1)
Example #11
0
def find_divisor(n, test_divisor):
    logl("(" + str(n) + ", " + str(test_divisor) + ")")

    if square(test_divisor) > n:
        return n
    elif divides(test_divisor, n):
        return test_divisor
    else:
        return find_divisor(n, test_divisor + 1)
Example #12
0
    def expt_iter(a, b, n):
        logl("(" + str(a) + ", " + str(b) + ", " + str(n) + ")")

        if n == 0:
            return a
        elif even(n):
            return expt_iter(a, square(b), n / 2)
        else:
            return expt_iter(a * b, b, n - 1)
Example #13
0
def expmod(base, exp, m):
    logl("(" + str(base) + ", " + str(exp) + ", " + str(m) + ")")

    if exp == 0:
        return 1
    elif even(exp):
        return square(expmod(base, exp / 2, m)) % m
    else:
        return base * expmod(base, exp - 1, m) % m
Example #14
0
def gardenWindows():
    dest=x(width-2850-wallThick)
    return map(lambda x: window.Window(x)\
            .withFrameThickness(150) \
            .withBoxDepth(150),
    [
        util.square(x(2850),z(wallMinHeight)).transO(dest),
        util.faceFromVectors([O,x(2850),xz(2850,heightAt(wallThick)), z(heightAt(2850+wallThick))])
            .transO(dest+z(wallMinHeight)) \
    ])
Example #15
0
    def draw_stone_masks(self, im):
        for i,j in util.square(self.board_size):
            #print('roi_middle', self.roi_middle)
            #print('stone roi', self.stone_roi[i,j].shape)
            roi = im[self.cur_grid[i,j,0]-self.roi_middle:
                     self.cur_grid[i,j,0]+self.roi_middle+1,
                     self.cur_grid[i,j,1]-self.roi_middle:
                     self.cur_grid[i,j,1]+self.roi_middle+1]
            #print('roi', roi.shape)
            roi[self.stone_roi[i,j] > 0, :] = 255

        return im
Example #16
0
def f(x, y):
    # def f_helper(a, b):
    #     return x * square(a) + y * b + a * b

    # return f_helper(1 + (x * y), 1 - y)

    # l = lambda a, b: x * square(a) + y * b + a * b

    # return l(1 + x * y, 1 - y)
    a = 1 + (x * y)
    b = 1 - y

    return x * square(a) + y * b + a * b
Example #17
0
def get_starting_world():
    world = []

    p = player.get_player()
    ability = player.get_ability(p)

    difficulty = util.get_config_var("difficulty")

    for i in range(util.square(ability) * difficulty):
        monster = f"Monster {i}"
        world.append(monster)

    return world
Example #18
0
    def initialize(self):
        cap = cv2.VideoCapture(self.source)
        if not cap.isOpened():
            cap.open()

        # read a few frames to make sure the camera is self-calibrated
        for i in range(10):
            cap.read()

        # let user position camera
        print("Position the camera, then hit space.")
        while cv2.waitKey(20) != ord(' '):
            ret, img = cap.read()
            cv2.imshow(self.window_name, img)

        # find the board grid
        ret, img = cap.read()
        self.lines = find_grid.find_grid(img, self.board_size)
        self.grid = find_grid.get_grid_intersections(self.lines,
                                                     self.board_size)
        self.corners = util.get_board_corners(self.grid)
        rvec, tvec, inliners, t = pose.get_pose(self.corners, self.board_size,
                                                self.cam_mtx, self.distortion)
        self.offsets = pose.compute_offsets(self.grid, self.board_size, t,
                                            rvec, tvec, self.cam_mtx,
                                            self.distortion)

        self.corners = np.int32(self.corners)
        self.offsets = np.int32(self.offsets)
        board_mask = util.get_board_mask(img.shape[:2], self.corners)
        self.cap = select_frames.FrameSelector(cap)
        self.cap.set_roi(None, board_mask)
        self.cap.initialize()

        self.finder = find_stones.StoneFinder(self.board_size, self.lines,
                                              self.grid, self.black,
                                              self.white, self.offsets)
        self.finder.set_last_gray_image(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))

        if self.debug:
            self.finder.draw_stone_masks(img)

            for i, j in util.square(self.board_size):
                pt1, pt2 = tuple(self.grid[i,j,::-1].ravel()), \
                           tuple(self.offsets[i,j,::-1].ravel())
                cv2.line(img, pt1, pt2, (0, 255, 0), 2)
            cv2.imshow('pose', img)
            cv2.waitKey(0)
            cv2.destroyWindow('pose')

        return True
Example #19
0
 def test_practice_input_1(self):
     '''test_practice_input_1'''
     result = sarsa(
         'SFFG',
         1.0,
         0.24,
         0.09,
         49553,
         202404,
     )
     answer = '<<v<'
     mapped_answer = util.square(answer)
     util.logger('Answer policy:', level='high')
     util.logger(np.array([mapped_answer]).T, level='high')
     self.assertEqual(result, answer)
Example #20
0
 def test_practice_input_2(self):
     '''test_practice_input_2'''
     result = sarsa(
         'SFFFHFFFFFFFFFFG',
         1.0,
         0.25,
         0.29,
         14697,
         741684,
     )
     answer = '^vv><>>vvv>v>>><'
     mapped_answer = util.square(answer)
     util.logger('Answer policy:', level='high')
     util.logger(np.array([mapped_answer]).T, level='high')
     self.assertEqual(result, answer)
Example #21
0
 def test_practice_input_3(self):
     '''test_practice_input_3'''
     result = sarsa(
         'SFFFFHFFFFFFFFFFFFFFFFFFG',
         0.91,
         0.12,
         0.13,
         42271,
         983459,
     )
     answer = '^>>>><>>>vvv>>vv>>>>v>>^<'
     mapped_answer = util.square(answer)
     util.logger('Answer policy:', level='high')
     util.logger(np.array([mapped_answer]).T, level='high')
     self.assertEqual(result, answer)
Example #22
0
    def adam(allparams,
             nat_stepsize,
             stepsize,
             num_epochs,
             seq_len,
             num_seqs=None,
             b1=0.9,
             b2=0.999,
             eps=1e-8,
             num_samples=1):
        natparams, params = allparams[:1], allparams[1:]
        m = zeros_like(params)
        v = zeros_like(params)
        i = 0
        accumulate = lambda rho, a, b: add(scale(1 - rho, a), scale(rho, b))

        for epoch in xrange(num_epochs):
            vals = []
            batches, num_batches = split_into_batches(data, seq_len, num_seqs)
            for y in batches:
                val, grad = scale(
                    1. / num_datapoints,
                    val_and_grad(y, num_batches, num_samples, *allparams))
                natgrad, grad = grad[:1], grad[1:]

                m = accumulate(b1, grad, m)  # first moment estimate
                v = accumulate(b2, square(grad), v)  # second moment estimate
                mhat = scale(1. / (1 - b1**(i + 1)), m)  # bias correction
                vhat = scale(1. / (1 - b2**(i + 1)), v)
                update = scale(stepsize, div(mhat, add_scalar(eps,
                                                              sqrt(vhat))))

                natparams = add(natparams, scale(nat_stepsize, natgrad))
                params = add(params, update)
                allparams = concat(natparams, params)
                vals.append(val)
                i += 1

                if callback: callback(epoch, vals, natgrad, allparams)

        return allparams
Example #23
0
def adam(gradfun, allparams, num_iters, step_size, b1=0.9, b2=0.999, eps=1e-8):
    natparams, params = allparams[:1], allparams[1:]
    m = zeros_like(params)
    v = zeros_like(params)
    i = 0
    accumulate = lambda rho, a, b: add(scale(1-rho, a), scale(rho, b))
 
    for i in xrange(num_iters):
        grad = gradfun(allparams, i)
        natgrad, grad = grad[:1], grad[1:]
 
        m = accumulate(b1, grad, m)          # first moment estimate
        v = accumulate(b2, square(grad), v)  # second moment estimate
        mhat = scale(1./(1 - b1**(i+1)), m)  # bias correction
        vhat = scale(1./(1 - b2**(i+1)), v)
        update = scale(step_size, div(mhat, add_scalar(eps, sqrt(vhat))))
 
        natparams = sub(natparams, scale(step_size, natgrad))
        params = sub(params, update)
        allparams = concat(natparams, params)
 
    return allparams
Example #24
0
def sqrt3(x):
    return fixed_point_of_transform(lambda y: square(y) - x, newton_transform,
                                    1.0)
Example #25
0
def sqrt(x):
    return newtons_method(lambda y: square(y) - x, 1.0)
Example #26
0
img = cv2.imread('tests/photos/1.jpg')
corners = np.array([[75, 251], [164, 542], [445, 383], [275, 51]],
                   dtype=np.int32)
board_size = 9

data = np.load('camera_params.npz')
mtx = data['mtx']
#dist = data['dist']
dist = None

rvec, tvec, inliers, t = pose.get_pose(corners, board_size, mtx, dist, True)
img = pose.draw_pose(img, board_size, corners, t, rvec, tvec, mtx, dist)

lines = find_grid.find_grid(img, board_size, corners)
grid = find_grid.get_grid_intersections(lines, board_size)
offsets = pose.compute_offsets(grid, board_size, t, rvec, tvec, mtx, dist)

finder = find_stones.StoneFinder(board_size, lines, grid,
                                 np.zeros((0, 2), dtype=np.int32),
                                 np.zeros((0, 2), dtype=np.int32), offsets)
finder.draw_stone_masks(img)

for i, j in util.square(board_size):
    pt1, pt2 = tuple(grid[i, j, ::-1].ravel()), tuple(offsets[i,
                                                              j, ::-1].ravel())
    cv2.line(img, pt1, pt2, (0, 255, 0), 2)

cv2.imshow('pose', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Example #27
0
def problem_6(max):
	natural_numbers = range(1, max+1)
	return square(sum(natural_numbers)) - sum(map(square, natural_numbers))
Example #28
0
 def n(i):
     if i == 1:
         return x
     else:
         return -square(x)
Example #29
0
setup(600, 600, 370, 0)
hideturtle()
tracer(False)
listen()

#stage setting
snake = [vector(20, 20)]
walls = {vector(100, 0), vector(-100, 0)}
pwalls = {vector(150, 0): 5}
thorns = {vector(10, 10)}
lasers = [[vector(-100, 0), vector(100, 0)]]
teledict = {vector(0, 100): vector(0, -100)}
foods = {vector(0, 0), vector(50, 50)}

for body in snake:
    square(body.x, body.y, 9, 'black')
for telep in teledict:
    square(telep.x, telep.y, 9, 'magenta')
    square(teledict[telep].x, teledict[telep].y, 9, 'purple')
for food in foods:
    square(food.x, food.y, 9, 'green')
for i in range(len(lasers)):
    line(lasers[i][0].x, lasers[i][0].y + 4.5, lasers[i][1].x,
         lasers[i][1].y + 4.5)
for wall in walls:
    square(wall.x, wall.y, 9, 'gray')
for pwall in pwalls:
    squarenum(pwall.x, pwall.y, 9, 'blue', pwalls[pwall])
for thorn in thorns:
    triangle(thorn.x, thorn.y, 9, 'red')
done()
Example #30
0
def cubic(a, b, c):
    return lambda x: cube(x) + a * square(x) + b * x + c
Example #31
0
from math import pi, sin

import util

if __name__ == '__main__':
    print('8 squared = {}'.format(util.square(8)))

    val = util.quad(pi)
    print('pi quad = {:0.6f}'.format(val))

    print('sin(pi) = {:0.2f}'.format(sin(pi)))

    xs = [1, 2, 3, 4]
    x = 6
    if x in xs:
        print('{} is in {}'.format(x, xs))
    else:
        print('{} is not in  {}'.format(x, xs))
Example #32
0
 def good_enough(guess):
     return abs(square(guess) - x) < 0.001