def test_cart2pol():
    v = np.array([0., 0., 1.])
    np.testing.assert_equal(cart2pol(v), np.array([0.,0.]))

    v = np.array([0., 0., -1.])
    np.testing.assert_equal(cart2pol(v), np.array([np.pi, 0.]))

    v = np.array([1., 0., 0.])
    np.testing.assert_equal(cart2pol(v), np.array([np.pi/2., 0.]))

    v = np.array([1., 1., 0.])
    v /= norm(v)[...,None]
    np.testing.assert_equal(cart2pol(v), np.array([np.pi/2., np.pi/4.]))
    
    v = np.array([0., 1., 0.])
    v /= norm(v)[...,None]
    np.testing.assert_equal(cart2pol(v), np.array([np.pi/2., np.pi/2.]))

    v = np.array([[0., 0., -1.],[1., 0., 0.]]) # shape 2,3
    exp = np.array([[np.pi, 0.], [np.pi/2., 0.]])
    np.testing.assert_equal(cart2pol(v), exp)

    v = np.array([[0., 0., -1.],[1., 0., 0.]]).T # shape 2,3
    exp = np.array([[np.pi, 0.], [np.pi/2., 0.]]).T
    np.testing.assert_equal(cart2pol(v, axis=0), exp)
 def Energy(X):
     t = X
     if t < 0 or t > 1:
         return 1e8
     rray = array(list(r_ray))
     rd = array(list(r_d))
     r = rray + t * rd
     rsphere = array(list(r_sphere))
     E = norm(r - rsphere)**2 - R**2
     return E
Example #3
0
 def control(self, player):
     for i in range(len(self.fighters)):
         fa = self.fighters[i]
         fa.receive_signal(["noslowdown"])
         for j in range(len(self.fighters)):
             if i != j:
                 fb = self.fighters[j]
                 if vectors.norm(vectors.sub_vec(fa.pos, fb.pos)) < 450:
                     d1 = vectors.norm(vectors.sub_vec(fa.v, player.pos))
                     d2 = vectors.norm(vectors.sub_vec(fb.v, player.pos))
                     if d1 < d2:
                         #fa is closen
                         # print("Slos")
                         fb.receive_signal(["slowdown"])
                     else:
                         fa.receive_signal(["slowdown"])
                 else:
                     fa.receive_signal(["noslowdown"])
                     fb.receive_signal(["noslowdown"])
Example #4
0
    def update(self, sprites, player):
        self.positions = []
        for sprite in sprites:
            k = vectors.sub_vec(sprite.pos, player.pos)
            k = [k[0] / 30, k[1] / 30]
            d = vectors.norm(k)

            if (d < 50):

                k = [k[0] + 63, k[1] + 63]
                self.positions.append(k)
        self.draw()
Example #5
0
def get_speed(pos, time, tax=0, spax=-1):
    '''Get speed

    Parameters
    ----------
    pos : array_like
      
    time : array_like
    
    tax : int, optional
      time axis, defaults to 0
    spax : int, optional
      space axis, defaults to -1, i.e. last axis
    '''    
    vel = get_vel(pos, time, tax=tax)
    return norm(vel, axis=spax)
Example #6
0
def CircleCircleIntersect(C1, r1, C2, r2, display_commands=False):
    """
    [1] http://mathworld.wolfram.com/Circle-CircleIntersection.html
    mentions a method of Circle Circle intersection. We extend
    the calculations.
    """
    if display_commands:
        s = "CircleCircleIntersect(%s,%s,%s,%s,display_commands=%s)" % \
            (str(C1),str(r1),str(C2),str(r2),str(display_commands))
        print s
    C1 = C1 + [0]
    C2 = C2 + [0]
    V1 = np.array(C2) - np.array(C1)
    V1 = list(V1 / v.norm(V1))
    theta = atan2(V1[1], V1[0]) * 180 / pi
    shape = [C1, C2]
    shape = Translate(shape, -C1[0], -C1[1], 0)
    shape = Rotate(shape, -theta, 0, 0, 1)
    d = shape[1][0]
    shape = Translate(shape, C1[0], C1[1], 0)
    R = r1
    r = r2
    epsilon = 1e-8
    if abs(d) < epsilon:
        pts = []
        return False, pts
    x = 1.0 * (d**2 - r**2 + R**2) / (2 * d)
    delta = R**2 - x**2
    if delta < 0:
        delta = 0
        return False, []
    y1 = 1.0 * sqrt(delta)
    y2 = -1.0 * sqrt(delta)
    pts = [[x, y1, 0], [x, y2, 0]]
    pts = Rotate(pts, theta, 0, 0, 1)
    pts = Translate(pts, C1[0], C1[1], 0)
    pts = map(lambda pt: pt[:2], pts)
    return True, pts
Example #7
0
def get_tgt_dir(pos, tgt):
    '''
    Calculate direction from current position to target.

    Parameters
    ----------
    pos : ndarray
      positional data,
      shape (ntask, nbin, ndim) or (ntask, nrep, nbin, ndim)
    tgt : ndarray
      target positions, shape (ntask, ndim)

    Notes
    -----
    Not yet made suitable for tax and spax variants.
    '''
    if np.rank(pos) == 3: # no repeats
        tgt = tgt[:,None]
    elif np.rank(pos) == 4: # with repeats
        tgt = tgt[:,None,None]
    drn = tgt - pos
    drn /= norm(drn, axis=-1)[...,None]
    return drn
def test_pol2cart_cart2pol():
    v = np.random.random(size=(2, 3))
    v /= norm(v, axis=1)[...,None]
    np.testing.assert_almost_equal(v, pol2cart(cart2pol(v)))
Example #9
0
    def detect_collisions(self):

        for missile in self.missiles.sprites():
            if (self.player.health <= 0):
                missile.killit = True
                continue
            if not missile.activated:
                continue
            col = py.sprite.collide_mask(missile, self.player)
            if col != None:
                missile.killit = True
                self.shake = True
                self.shakecount = 0
                self.missiles_exploded.append(
                    vectors.norm(vectors.sub_vec(missile.pos,
                                                 self.player.pos)))
                self.explosions.append(self.get_exp(missile.pos))
                self.player.health -= 30
                self.player.damaging = True
                self.turn_screen_red = True
                self.turn_screen_normal = False

                if self.player.health <= 0:
                    self.explosions.append(self.get_exp(self.player.pos))
                    self.player.live = False
                    self.bullets.bullets.empty()

            for fighter in self.fighters.sprites():
                if py.sprite.collide_mask(missile, fighter):
                    missile.killit = True
                    self.shake = True
                    self.shakecount = 14
                    self.missiles_exploded.append(
                        vectors.norm(
                            vectors.sub_vec(missile.pos, self.player.pos)))
                    self.explosions.append(self.get_exp(missile.pos))
                    fighter.health -= 10

        #enemy player collision
        if self.player.live:
            for ship in self.fighters.sprites():
                j = py.sprite.collide_mask(ship, self.player)
                if j != None:
                    ship.kill()
                    self.player.health = 0
                    self.shake = True
                    self.shakecount = 0
                    j = list(j)
                    self.missiles_exploded.append(0)
                    self.explosions.append(self.get_exp(self.player.pos))
                    self.explosions.append(self.get_exp(ship.pos))

        group = self.missiles.sprites()
        bulls = self.bullets.bullets.sprites()
        ebulls = self.enemiesbullets.bullets.sprites()
        hitted_bullets = []
        #missile missile collision
        for i in range(len(group)):
            missile = group[i]
            for j in range(i, len(group)):
                missileB = group[j]
                if missile != missileB:
                    if py.sprite.collide_mask(missile, missileB) != None:
                        missile.killit = True
                        missileB.killit = True
                        self.shake = True
                        self.shakecount = 14
                        self.missiles_exploded.append(
                            vectors.norm(
                                vectors.sub_vec(missile.pos, self.player.pos)))
                        self.explosions.append(self.get_exp(missile.pos))

            #bullet missile collision
            for j in range(i, len(bulls)):
                b = bulls[j]
                if py.sprite.collide_mask(b, missile):
                    missile.killit = True
                    self.shake = True
                    self.shakecount = 14
                    self.missiles_exploded.append(
                        vectors.norm(
                            vectors.sub_vec(missile.pos, self.player.pos)))
                    self.explosions.append(self.get_exp(missile.pos))
                    hitted_bullets.append(b)
                # bullet fighter collision

        for b in bulls:
            for fighter in self.fighters.sprites():
                if py.sprite.collide_mask(b, fighter) and not fighter.killit:
                    fighter.health -= 10
                    hitted_bullets.append(b)
                    self.fighterhit = True
                    self.sparkSystem.add_particles(b.pos, fighter.v, 25)
                    if fighter.health <= 0:
                        fighter.killit = True
                        self.shake = True
                        self.shakecount = 16

                        self.missiles_exploded.append(
                            vectors.norm(
                                vectors.sub_vec(fighter.pos, self.player.pos)))
                        self.explosions.append(self.get_exp(fighter.pos))

        if self.player.live:
            for b in ebulls:
                if py.sprite.collide_mask(b, self.player):
                    self.player.health -= 10
                    self.sparkSystem.add_particles(b.pos, b.dir, 20)
                    self.turn_screen_red = True
                    self.turn_screen_normal = False
                    hitted_bullets.append(b)
                    self.playerhit = True
                    if self.player.health <= 0:
                        self.player.health = 0
                        self.missiles_exploded.append(0)
                        self.explosions.append(self.get_exp(self.player.pos))

            for b in hitted_bullets:
                b.kill()

        for emp in self.emps.sprites():
            if py.sprite.collide_mask(emp, self.player):
                self.player.emp_affected = True
                emp.kill()
Example #10
0
def plot_gem(data, order='co', fig=None, ax=None,
             clim=None, **kwargs):
    '''
    Parameters
    ----------
    data : ndarray
      shape (26,)
    order : string, optional
      one of 'co' or 'oc', for center-out or out-center data order
      determines mapping of data to polygons
      defaults to center-out
    fig : matplotlib Figure instance
      an existing figure to use, optional
    ax : SplitLambertAxes instance
      an existing axis to use, optional
    clim : tuple or list of float, optional
      minimum and maximum values for color map
      if not supplied, min and max of data are used
    '''
    if not data.shape == (26,):
        raise ValueError('data has wrong shape; should be (26,),'
                         ' actually is %s' % (str(data.shape)))
    if order == 'co':
        mapping = get_targ_co_dir_mapping()
    elif order == 'oc':
        mapping = get_targ_oc_dir_mapping()
    else:
        raise ValueError('`order` not recognized')
    if (fig != None) & ~isinstance(fig, Figure):
        raise ValueError('`fig` must be an instance of Figure')
    if (ax != None) & \
            ~isinstance(ax, split_lambert_projection.SplitLambertAxes):
        raise ValueError('`ax` must be an instance of SplitLambertAxes')
    if (clim != None):
        if (type(clim) != tuple) and (type(clim) != list):
            raise ValueError('clim must be tuple or list')
        if len(clim) != 2:
            raise ValueError('clim must have 2 elements')
    else:
        clim = (np.min(data), np.max(data))
        
    if (fig == None):
        if (ax != None):
            fig = ax.figure
        else:
            fig = plt.figure()
    if (ax == None):
        ax = fig.add_subplot(111, projection='split_lambert')
    
    pts, spts, circs = make_26_targets()
    pts = pts.astype(float)
    pts /= norm(pts, axis=1)[:,None]
    tps = cart2pol(pts)

    q = 9
    cnrs = np.zeros((32, 5, 2)) # for non-polar polys
    ends = np.zeros((2, q, 2))  # for poles
    
    # for now use boundaries suggested by square ends
    squares = np.unique(tps[circs[0]][:,0])
    mids = np.mean(rolling_window(squares, 2), axis=1)
    eps = 1e-8
    tvs = np.hstack([mids[:2], np.pi / 2. - eps, np.pi / 2., mids[-2:]])
    pvs = np.linspace(0, 2 * np.pi, q, endpoint=True) % (2 * np.pi) \
        - np.pi / 8.

    k = 0
    rings = [0,1,3,4]
    for i in rings: # 3 rings of 4-cnr polys
        for j in xrange(8): # 8 polys per ring
            xs = np.array((tvs[i], tvs[i], tvs[i+1], tvs[i+1], tvs[i]))
            ys = np.array((pvs[j], pvs[j+1], pvs[j+1], pvs[j], pvs[j]))
            cnrs[k] = np.vstack((xs, ys)).T
            k += 1

    ends[0,:,0] = np.ones(q) * tvs[0]
    ends[1,:,0] = np.ones(q) * tvs[-1]
    ends[0,:,1] = pvs
    ends[1,:,1] = pvs

    kwargs.setdefault('edgecolors', 'none')
    kwargs.setdefault('linewidths', (0.25,))
    coll_cnrs = mcoll.PolyCollection(cnrs, **kwargs)
    coll_ends = mcoll.PolyCollection(ends, **kwargs)
    
    mapped_data = data[mapping]

    coll_cnrs.set_array(mapped_data[:-2])
    coll_ends.set_array(mapped_data[-2:])

    if clim == None:
        cmin, cmax = mapped_data.min(), mapped_data.max()
    else:
        cmin, cmax = clim
    coll_cnrs.set_clim(cmin, cmax)
    coll_ends.set_clim(cmin, cmax)
    
    ax.add_collection(coll_cnrs)
    ax.add_collection(coll_ends)
    return ax
Example #11
0
def SliceWithKnife(doc, Ax, Ay, Bx, By, alpha=0.15, beta=0.15):
    """
    New points added at lerp t = alpha and t = beta
    with default alpha = 0.25 and beta = 0.25 if knife
    AB slices an edge.

    For a graph document doc in a 2D embedding in the plane,
    with doc["V"],doc["E"],doc["pts"] defined, slice
    the edges of doc with knife. The knife is given
    by line segment AB with A = [Ax,Ay] and B = [Bx,By].

    doc1 = deepcopy(doc)

    For e in doc1["E"] and u,v = e, 

    Cx,Cy = doc1["pts"][u][:2]
    Dx,Dy = doc1["pts"][v][:2]

    flag,X,Y = line_intersection.SegmentIntersect(Ax,Ay,Bx,By,Cx,Cy,Dx,Dy)

    then if flag, then break line segments into separated
    two segments and

    orient CD such that C is on interior of plane n*(x-mid) < 0
    # add Utility package folder with sys.path.insert(0, <utility_path>)
    AB = list(array([Ax,Ay]) - array([Bx,By]))
    epsilon = generalized_cross_product.Epsilon(2) # do once to get Cross   
    normal = epsilon_levicivita_TMP.Cross([AB])
    n = normal/vectors.norm(normal)
    mid = vectors.lerp([Cx,Cy],[Dx,Dy],0.5)
    xm = list(array(x) - array(mid))
    interior = vectors.dotprod(n,xm)
    if not interior:
        #swap Cx,Cy with Dx,Dy if not interior
        tx = Cx
        ty = Cy
        Cx = Dx
        Cy = Dy
        Dx = tx
        Dy = ty

    pt_1 = vectors.lerp([Cx,Cy,0],[Dx,Dy,0], alpha=0.25)
    pt_2 = vectors.lerp([Cx,Cy,0],[Dx,Dy,0], beta=0.75)
    
    doc1,u2 = graph.SplitVertex(doc1,u)
    doc1["pts"].append(pt_1) # assign pt_1 to u2
    doc1,v2 = graph.SplitVertex(doc1,v)
    doc1["pts"].append(pt_2) # assign pt_2 to v2

    and returns:
    
    doc1 = SliceWithKnife(doc, Ax, Ay, Bx, By) 
    """
    doc1 = deepcopy(doc)
    ES = []
    VS = []
    for e in doc1["E"]:
        u, v = e
        Cx, Cy = doc1["pts"][u][:2]
        Dx, Dy = doc1["pts"][v][:2]
        flag, X, Y = line_intersection.SegmentIntersect(
            Ax, Ay, Bx, By, Cx, Cy, Dx, Dy)
        if flag:
            AB = list(array([Ax, Ay]) - array([Bx, By]))
            normal = generalized_cross_product.cross2(array(AB))
            n = normal / vectors.norm(normal) + [0]
            mid = vectors.lerp([Cx, Cy, 0], [Dx, Dy, 0], 0.5)
            # use x = [Cx,Cy] to check if on interior side
            xm = list(array([Cx, Cy, 0]) - array(mid))
            interior = vectors.dotprod(n, xm)
            if not interior:
                #swap Cx,Cy with Dx,Dy if not interior
                tx = Cx
                ty = Cy
                Cx = Dx
                Cy = Dy
                Dx = tx
                Dy = ty
            pt_1 = vectors.lerp([X, Y, 0], [Cx, Cy, 0], alpha)
            pt_2 = vectors.lerp([X, Y, 0], [Dx, Dy, 0], beta)
            doc1, u2 = graph.SplitVertex(doc1, u)
            doc1["pts"].append(pt_1)  # assign pt_1 to u2
            doc1, v2 = graph.SplitVertex(doc1, v)
            doc1["pts"].append(pt_2)  # assign pt_2 to v2
            ES.append([u, u2])
            ES.append([v2, v])
            VS.append(u2)
            VS.append(v2)
        else:
            ES.append(e)
    doc1["E"] = ES
    doc1["V"] = doc["V"] + VS

    for k in range(len(doc1["pts"])):
        doc1["pts"][k] = map(int, map(round, doc1["pts"][k]))
    return doc1