Python matplotlib.pyplot.quiver() Examples

The following are code examples for showing how to use matplotlib.pyplot.quiver(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: vmap   Author: dshean   File: disp2v.py    MIT License 7 votes vote down vote up
def plotvec(h, v):
    #Probably want to smooth h and v here, or at least filter outliers
    #Interpolation or hole filling would also help with lots of nodata holes 
    #Compute stats within window centered on X and Y
    nvec = np.array([40,40], dtype=np.float)
    stride = np.round(min(h.shape/nvec)).astype('int')
    X,Y = np.meshgrid(np.arange(0,h.shape[1],stride),np.arange(0,h.shape[0],stride))
    h_sub = h[::stride,::stride]
    v_sub = v[::stride,::stride]
    norm = False
    if norm:
        m_sub = np.ma.sqrt(h_sub**2+v_sub**2)
        h_sub /= m_sub
        v_sub /= m_sub
    Q = plt.quiver(X,Y,h_sub,v_sub,pivot='middle',color='white')
    #Add quiver key
    #scale = float(Q.scale)
    #lbl = str(np.round(Q.scale).astype(int)) + r'$\frac{m}{s}$'
    #lbl = '%i m/s' % np.around(scale, decimals=0).astype(int) 
    #qk = plt.quiverkey(Q, 0.05, 0.05, 1, lbl, labelpos='N', fontproperties={'weight':'bold'}) 
Example 2
Project: Explore-Coarse-3D-Reconstruction-Path-Planning-ATRC-Summer-2017   Author: AFRL-RY   File: plotting.py    MIT License 6 votes vote down vote up
def plotSection(cn,ce,cd,cor_n,cor_e,cor_d,cup_n,cup_e,cup_d,crange):
    '''
    Plots a portion of the camera positions
    '''
    
    # Initialize plot
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    ax.set_aspect('equal')
    plt.quiver(cn[crange],ce[crange],cd[crange],cor_n[crange],cor_e[crange],cor_d[crange],color='b',pivot='tail',normalize='True')
    plt.quiver(cn[crange],ce[crange],cd[crange],cup_n[crange],cup_e[crange],cup_d[crange],color='g',pivot='tail',normalize='True')
    
    ax = plt.gca()
    set_axes_equal(ax)
    
    ax.set_xlim(cn[crange].min()-2,cn[crange].max()+2)
    ax.set_ylim(ce[crange].min()-2,ce[crange].max()+2)
    ax.set_zlim(cd[crange].min()-2,cd[crange].max()+2) 
Example 3
Project: Explore-Coarse-3D-Reconstruction-Path-Planning-ATRC-Summer-2017   Author: AFRL-RY   File: plotting.py    MIT License 6 votes vote down vote up
def plotSection(cn,ce,cd,cor_n,cor_e,cor_d,cup_n,cup_e,cup_d,crange):
    '''
    Plots a portion of the camera positions
    '''
    
    # Initialize plot
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    ax.set_aspect('equal')
    plt.quiver(cn[crange],ce[crange],cd[crange],cor_n[crange],cor_e[crange],cor_d[crange],color='b',pivot='tail',normalize='True')
    plt.quiver(cn[crange],ce[crange],cd[crange],cup_n[crange],cup_e[crange],cup_d[crange],color='g',pivot='tail',normalize='True')
    
    ax = plt.gca()
    set_axes_equal(ax)
    
    ax.set_xlim(cn[crange].min()-2,cn[crange].max()+2)
    ax.set_ylim(ce[crange].min()-2,ce[crange].max()+2)
    ax.set_zlim(cd[crange].min()-2,cd[crange].max()+2) 
Example 4
Project: Explore-Coarse-3D-Reconstruction-Path-Planning-ATRC-Summer-2017   Author: AFRL-RY   File: plotting.py    MIT License 6 votes vote down vote up
def plotSection(cn,ce,cd,cor_n,cor_e,cor_d,cup_n,cup_e,cup_d,crange):
    '''
    Plots a portion of the camera positions
    '''
    
    # Initialize plot
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    ax.set_aspect('equal')
    plt.quiver(cn[crange],ce[crange],cd[crange],cor_n[crange],cor_e[crange],cor_d[crange],color='b',pivot='tail',normalize='True')
    plt.quiver(cn[crange],ce[crange],cd[crange],cup_n[crange],cup_e[crange],cup_d[crange],color='g',pivot='tail',normalize='True')
    
    ax = plt.gca()
    set_axes_equal(ax)
    
    ax.set_xlim(cn[crange].min()-2,cn[crange].max()+2)
    ax.set_ylim(ce[crange].min()-2,ce[crange].max()+2)
    ax.set_zlim(cd[crange].min()-2,cd[crange].max()+2) 
Example 5
Project: cavelab   Author: Loqsh   File: visual.py    MIT License 6 votes vote down vote up
def draw_vector_field(ang, hsv, my_dpi=160, width=312):
    if hsv.shape[1]<32:
        rate = 1
    else:
        rate = int(10*hsv.shape[1]/256)

    plt.figure(figsize=(width/my_dpi, width/my_dpi), dpi=my_dpi, frameon=False)
    X, Y = np.meshgrid(np.arange(hsv.shape[0])[::rate],
                       np.arange(hsv.shape[1])[::rate])

    U = np.cos(ang[::rate,::rate]) * hsv[...,2][::rate,::rate]
    V = np.sin(ang[::-rate,::-rate]) * hsv[...,2][::-rate,::-rate]

    Q = plt.quiver(X, Y, U, V)

    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    crop = int(0.1*width)
    fig = np.array(Image.open(buf))[crop+8:width-crop,crop+8:width-crop,0:3]
    plt.close('all')

    return fig 
Example 6
Project: Gravity_Simulator   Author: albinjal   File: newton.py    MIT License 6 votes vote down vote up
def save(self, file_name, axis, second):
        plt.axis(axis)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.title('Day: %d, Hour: %d' % (
        math.floor(second / 60 / 60 / 24), second / 60 / 60 - math.floor(second / 60 / 60 / 24) * 24))
        plt.xlabel('Meters')
        plt.ylabel('Meters')
        plt.axvline(color='black')
        plt.axhline(color='black')
        for body in self.bodies:
            print(body.disp())
            plt.scatter(body.position[0], body.position[1], body.diameter/10**5, edgecolors='none')
            if vector_length(body.applied_force) and vector_length(body.velocity):
                plt.quiver(body.position[0], body.position[1], body.applied_force[0], body.applied_force[1],
                           color=['r'], scale=3 * 10 ** 21)
                plt.quiver(body.position[0], body.position[1], body.velocity[0], body.velocity[1], color=['b'],
                           scale=10000)
        plt.savefig(file_name, bbox_inches='tight')
        plt.clf()
        return file_name 
Example 7
Project: gimic   Author: qmcurrents   File: plot.py    GNU General Public License v2.0 6 votes vote down vote up
def vector_plot(self, fname=None, k=0):
        if not isinstance(self.field, VectorField):
            raise TypeError('Not a vector field')
        fig = plt.figure()
        x = self.grid.get_axis(0).get_points()
        y = self.grid.get_axis(1).get_points()
        x, y = np.meshgrid(x, y)
        u, v, w = self.field.get_field(k)
        q = plt.quiver(v, u)
#        qk = plt.quiverkey(q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W',
#                               fontproperties={'weight': 'bold'})
        l,r,b,t = plt.axis()
        dx, dy = r-l, t-b
        plt.axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy])

        plt.title('Minimal vector plot')

        if fname is not None:
            plt.savefig(fname)
        else:
            plt.show() 
Example 8
Project: monsoon-onset   Author: jenfly   File: scratchpad.py    MIT License 6 votes vote down vote up
def animate(data, day, axlims=(-30, 45, 40, 120), dx=5, dy=5, climits=(-5, 15),
            cmap='BuPu', d0=138, clev=np.arange(5, 15.5, 1),
            cticks=np.arange(5, 16, 2.5)):
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v)
    plt.title(title)
    plt.draw()

# Need to scale arrows in quiver plot so that they are consistent across
# different days 
Example 9
Project: modelling-course   Author: robjstan   File: f03.py    MIT License 6 votes vote down vote up
def plot_lv_pp(r=fixed(1.5), x0:(0.4,4,0.1)=2, y0=fixed(1)):
    t = np.linspace(0.0, 5.0, 30)
    x,y = list(zip( *integrate.odeint(lv, [x0,y0], t, (r,)) ))
    x = np.array(x); y = np.array(y)

    plt.figure(figsize=[9,6])

    plt.quiver(x[:-1], y[:-1], \
               (x[1:]-x[:-1])*0.98, (y[1:]-y[:-1])*0.98, \
               scale_units='xy', angles='xy', scale=1, \
               width=0.005, headwidth=3, headlength=3, \
               headaxislength=3, color=col[0])

    plt.scatter([r, x0], [1, y0], s=60, marker='o', c='k')
    plt.xlabel('prey population')
    plt.ylabel('predator population')
    plt.xlim(0, 4.2)
    plt.ylim(0,3.4)
    plt.show() 
Example 10
Project: qqmbr   Author: ischurov   File: odebook.py    MIT License 6 votes vote down vote up
def normvectorfield(xs,ys,fs,**kw):
    """
    plot normalized vector field
    
    kwargs
    ======
    
    - length is a desired length of the lines (default: 1)
    - the rest of kwards are passed to plot
    """
    length = kw.pop('length') if 'length' in kw else 1
    x, y = np.meshgrid(xs, ys)
    # calculate vector field
    vx,vy = fs(x,y)
    # plot vecor field
    norm = length /np.sqrt(vx**2+vy**2)
    plt.quiver(x, y, vx * norm, vy * norm, angles='xy',**kw) 
Example 11
Project: qqmbr   Author: ischurov   File: odebook.py    MIT License 6 votes vote down vote up
def vectorfield(xs,ys,fs,**kw):
    """
    plot vector field (no normalization!)

    args
    ====
    fs is a function that returns tuple (vx,vy)
    
    kwargs
    ======
    
    - length is a desired length of the lines (default: 1)
    - the rest of kwards are passed to plot
    """
    length= kw.pop('length') if 'length' in kw else 1
    x, y=np.meshgrid(xs, ys)
    # calculate vector field
    vx,vy=fs(x,y)
    # plot vecor field
    norm = length 
    plt.quiver(x, y, vx * norm, vy * norm, angles='xy',**kw) 
Example 12
Project: delira   Author: delira-dev   File: base_backend.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _quiver(self, plot_kwargs=None, figure_kwargs=None, **kwargs):
        """
        Function to create a quiver plot and push it

        Parameters
        ----------
        plot_kwargs : dict
            the arguments for plotting
        figure_kwargs : dict
            the arguments to actually create the figure
        **kwargs :
            additional keyword arguments for pushing the created figure to the
            logging writer

        """
        if plot_kwargs is None:
            plot_kwargs = {}
        if figure_kwargs is None:
            figure_kwargs = {}
        with self.FigureManager(self._figure, figure_kwargs, kwargs):
            from matplotlib.pyplot import quiver
            quiver(**plot_kwargs) 
Example 13
Project: differentiable-particle-filters   Author: tu-rbo   File: dpf.py    MIT License 6 votes vote down vote up
def plot_motion_model(self, sess, batch, motion_samples, task):

        # define the inputs and train/run the model
        input_dict = {**{self.placeholders[key]: batch[key] for key in 'osa'},
                      **{self.placeholders['num_particles']: 100},
                      }

        s_motion_samples = sess.run(motion_samples, input_dict)

        plt.figure('Motion Model')
        plt.gca().clear()
        plot_maze(task)
        for i in range(min(len(s_motion_samples), 10)):
            plt.quiver(s_motion_samples[i, :, 0], s_motion_samples[i, :, 1], np.cos(s_motion_samples[i, :, 2]), np.sin(s_motion_samples[i, :, 2]), color='blue', width=0.001, scale=100)
            plt.quiver(batch['s'][i, 0, 0], batch['s'][i, 0, 1], np.cos(batch['s'][i, 0, 2]), np.sin(batch['s'][i, 0, 2]), color='black', scale=50, width=0.003)
            plt.quiver(batch['s'][i, 1, 0], batch['s'][i, 1, 1], np.cos(batch['s'][i, 1, 2]), np.sin(batch['s'][i, 1, 2]), color='red', scale=50, width=0.003)

        plt.gca().set_aspect('equal')
        plt.pause(0.01) 
Example 14
Project: differentiable-particle-filters   Author: tu-rbo   File: dpf.py    MIT License 6 votes vote down vote up
def plot_particle_proposer(self, sess, batch, proposed_particles, task):

        # define the inputs and train/run the model
        input_dict = {**{self.placeholders[key]: batch[key] for key in 'osa'},
                      **{self.placeholders['num_particles']: 100},
                      }

        s_samples = sess.run(proposed_particles, input_dict)

        plt.figure('Particle Proposer')
        plt.gca().clear()
        plot_maze(task)

        for i in range(min(len(s_samples), 10)):
            color = np.random.uniform(0.0, 1.0, 3)
            plt.quiver(s_samples[i, :, 0], s_samples[i, :, 1], np.cos(s_samples[i, :, 2]), np.sin(s_samples[i, :, 2]), color=color, width=0.001, scale=100)
            plt.quiver(batch['s'][i, 0, 0], batch['s'][i, 0, 1], np.cos(batch['s'][i, 0, 2]), np.sin(batch['s'][i, 0, 2]), color=color, scale=50, width=0.003)

        plt.pause(0.01) 
Example 15
Project: differentiable-particle-filters   Author: tu-rbo   File: plotting_utils.py    MIT License 6 votes vote down vote up
def plot_trajectory(data, figure_name=None, show=False, pause=False, emphasize=None, odom=False, mincolor=0.0, linewidth=0.3):
    from methods.odom import OdometryBaseline
    if figure_name is not None:
        plt.figure(figure_name)
    for i, trajectories in enumerate(data['s']):
        plt.plot(trajectories[:, 0], trajectories[:, 1], '-', color='red', linewidth=linewidth, zorder=0, markersize=4)
        plt.plot(trajectories[:5, 0], trajectories[:5, 1], '.', color='blue', linewidth=linewidth, zorder=0, markersize=8)
        plt.plot(trajectories[0, 0], trajectories[0, 1], '.', color='blue', linewidth=linewidth, zorder=0, markersize=16)

        # plt.quiver(trajectories[:5, 0], trajectories[:5, 1],
        #        np.cos(trajectories[:5, 2]), np.sin(trajectories[:5, 2]),
        #            # np.arange(len(trajectories)), cmap='viridis', alpha=1.0,
        #            color='red', alpha=1.0,
        #        **quiv_kwargs
        #        )

    plt.gca().set_aspect('equal')
    show_pause(show, pause) 
Example 16
Project: shenfun   Author: spectralDNS   File: RayleighBenardRK3.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_plots(self):
        ub = self.u_.backward(self.ub)
        T_b = self.T_.backward(self.T_b)
        if comm.Get_rank() == 0:
            plt.figure(1, figsize=(6, 3))
            self.im1 = plt.quiver(self.X[1], self.X[0], ub[1], ub[0], pivot='mid', scale=0.01)
            plt.draw()
            plt.figure(2, figsize=(6, 3))
            self.im2 = plt.contourf(self.X[1], self.X[0], T_b, 100)
            plt.draw()
            plt.pause(1e-6) 
Example 17
Project: tectosaur   Author: tbenthompson   File: inverse_tools.py    MIT License 5 votes vote down vote up
def plot_situation(m, data, proj = None, modeled = None, view_R = 2.0, filename = None, min_elevation = None, max_elevation = None, latlon_step = 0.5, figsize = (13,13)):
    fault_pts = m.get_tri_pts('fault').reshape((-1,3))
    fC = np.mean(fault_pts, axis = 0)
    R = np.sqrt(np.max(np.sum((fault_pts - fC) ** 2, axis = 1)))

    surf_pts = m.get_tri_pts('surf')
    if min_elevation is None:
        min_elevation = int(np.floor(np.min(surf_pts[:,:,2]) / 1000.0))
    if max_elevation is None:
        max_elevation = int(np.ceil(np.max(surf_pts[:,:,2]) / 1000.0))
    n_steps = (max_elevation - min_elevation) * 2 + 1
    levels = np.linspace(min_elevation, max_elevation, n_steps)

    plt.figure(figsize = figsize)
    cntf = plt.tricontourf(
        m.pts[:,0], m.pts[:,1], m.get_tris('surf'), m.pts[:,2] / 1000.0,
        levels = levels, extend = 'both'
    )
    plot_fault_trace(m)
    plt.triplot(m.pts[:,0], m.pts[:,1], m.get_tris('fault'), 'w-', linewidth = 0.4)
    plt.quiver(data['X'], data['Y'], data['EW'], data['SN'], color = 'r')
    if modeled is not None:
        plt.quiver(data['X'], data['Y'], modeled[:,0], modeled[:,1], color = 'w')
    cbar = plt.colorbar(cntf)
    cbar.set_label('elevation (km)')

    map_axis(fC, R, view_R, proj, latlon_step)

    if filename is not None:
        plt.savefig(filename)
    plt.show() 
Example 18
Project: frame-block-matching   Author: javiribera   File: utils.py    The Unlicense 5 votes vote down vote up
def show_quiver(x_component_arrows, y_components_arrows):
    plt.quiver(x_component_arrows, y_components_arrows)
    plt.show() 
Example 19
Project: kappa   Author: ajkerr0   File: plot.py    MIT License 5 votes vote down vote up
def normal_modes(mol,evec, track=None):
    """Draw a visualization of a normal mode of a molecule.
    
    Keywords:
        track (array-like): An array of indices to highlight in the plots.
            Indices should be in '3*index' format to reflect direction."""
    
    fig = plt.figure()
    ax=Axes3D(fig)
    
    length = len(mol)
    ar = np.arange(length, dtype=int)

    ax.scatter(mol.posList[:,0],mol.posList[:,1],mol.posList[:,2])
    ax.quiver( mol.posList[:,0],mol.posList[:,1],mol.posList[:,2],
               evec[3*ar].real, evec[3*ar + 1].real, evec[3*ar + 2].real, pivot='tail')
               
    if track is not None:
        for index in track:
            atom = int(index/3.)
            ax.scatter(mol.posList[atom,0], mol.posList[atom,1], mol.posList[atom,2], 
                       s=100., c='red', zorder=-3)
            point_index = index%3
            point = np.array([0.,0.,0.])
            point[point_index] = 1.
            ax.quiver(mol.posList[atom,0], mol.posList[atom,1], mol.posList[atom,2], 
                      point[0], point[1], point[2], pivot='tail', cmap='Reds', zorder=-2, lw=5.)
    
    size = 12
    ax.set_xlim3d(-size,size)
    ax.set_ylim3d(-size,size)
    ax.set_zlim3d(-size,size)    
    
    ax._axis3don = False
    
    plt.show() 
Example 20
Project: ble5-nrf52-mac   Author: tomasero   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) 
Example 21
Project: sea_ice_drift   Author: nansencenter   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_displacement_km(self):
        ''' Shall find matching coordinates and plot quiver in lon/lat'''
        keyPoints1, descr1 = find_key_points(self.img1, nFeatures=self.nFeatures)
        keyPoints2, descr2 = find_key_points(self.img2, nFeatures=self.nFeatures)
        x1, y1, x2, y2 = get_match_coords(keyPoints1, descr1,
                                          keyPoints2, descr2)
        h = get_displacement_km(self.n1, x1, y1, self.n2, x2, y2)

        plt.scatter(x1, y1, 30, h)
        plt.colorbar()
        plt.savefig('sea_ice_drift_tests_%s.png' % inspect.currentframe().f_code.co_name)
        plt.close('all')
        self.assertTrue(len(h) == len(x1)) 
Example 22
Project: sea_ice_drift   Author: nansencenter   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_displacement_pix(self):
        ''' Shall find matching coordinates and plot quiver in pixel/line'''
        keyPoints1, descr1 = find_key_points(self.img1, nFeatures=self.nFeatures)
        keyPoints2, descr2 = find_key_points(self.img2, nFeatures=self.nFeatures)
        x1, y1, x2, y2 = get_match_coords(keyPoints1, descr1,
                                          keyPoints2, descr2)
        u, v = get_displacement_pix(self.n1, x1, y1, self.n2, x2, y2)

        plt.quiver(x1, y1, u, v)
        plt.savefig('sea_ice_drift_tests_%s.png' % inspect.currentframe().f_code.co_name)
        plt.close('all')
        self.assertEqual(len(u), len(x1)) 
Example 23
Project: sea_ice_drift   Author: nansencenter   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_drift_vectors(self):
        keyPoints1, descr1 = find_key_points(self.img1, nFeatures=self.nFeatures)
        keyPoints2, descr2 = find_key_points(self.img2, nFeatures=self.nFeatures)
        x1, y1, x2, y2 = get_match_coords(keyPoints1, descr1,
                                          keyPoints2, descr2)
        u, v, lon1, lat1, lon2, lat2 = get_drift_vectors(self.n1, x1, y1,
                                                   self.n2, x2, y2)

        plt.plot(lon1, lat1, '.')
        plt.plot(lon2, lat2, '.')
        plt.quiver(lon1, lat1, u, v, angles='xy', scale_units='xy', scale=0.25)
        plt.savefig('sea_ice_drift_tests_%s.png' % inspect.currentframe().f_code.co_name)
        plt.close('all')
        self.assertEqual(len(u), len(x1))
        self.assertEqual(len(v), len(x1)) 
Example 24
Project: sea_ice_drift   Author: nansencenter   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_integrated(self):
        ''' Shall use all developed functions for feature tracking'''
        lon1pm, lat1pm = np.meshgrid(np.linspace(-3, 2, 50),
                             np.linspace(86.4, 86.8, 50))

        sid = SeaIceDrift(self.testFiles[0], self.testFiles[1])
        uft, vft, lon1ft, lat1ft, lon2ft, lat2ft = sid.get_drift_FT()
        upm, vpm, apm, rpm, hpm, lon2pm, lat2pm = sid.get_drift_PM(
                                            lon1pm, lat1pm,
                                            lon1ft, lat1ft,
                                            lon2ft, lat2ft)

        lon1, lat1 = sid.n1.get_border()
        lon2, lat2 = sid.n2.get_border()
        sid.n1.reproject(Domain(NSR().wkt, '-te -3 86.4 2 86.8 -ts 500 500'))
        s01 = sid.n1['sigma0_HV']
        sid.n2.reproject(Domain(NSR().wkt, '-te -3 86.4 2 86.8 -ts 500 500'))
        s02 = sid.n2['sigma0_HV']

        plt.imshow(s01, extent=[-3, 2, 86.4, 86.8], cmap='gray', aspect=12)
        plt.quiver(lon1ft, lat1ft, uft, vft, color='r',
                   angles='xy', scale_units='xy', scale=0.5)
        plt.plot(lon2, lat2, '.-r')
        plt.xlim([-3, 2])
        plt.ylim([86.4, 86.8])
        plt.savefig('sea_ice_drift_tests_%s_img1_ft.png' % inspect.currentframe().f_code.co_name,
                    dpi=150, bbox_inches='tight', pad_inches=0)
        plt.close('all')

        plt.imshow(s02, extent=[-3, 2, 86.4, 86.8], cmap='gray', aspect=12)
        gpi = rpm > 0.4
        plt.quiver(lon1pm[gpi], lat1pm[gpi], upm[gpi], vpm[gpi], rpm[gpi]*hpm[gpi],
                   angles='xy', scale_units='xy', scale=0.5)
        plt.plot(lon1, lat1, '.-r')
        plt.xlim([-3, 2])
        plt.ylim([86.4, 86.8])
        plt.savefig('sea_ice_drift_tests_%s_img2_pm.png' % inspect.currentframe().f_code.co_name,
                    dpi=150, bbox_inches='tight', pad_inches=0)
        plt.close('all') 
Example 25
Project: osim-rl   Author: stanfordnmbl   File: v_tgt_field.py    MIT License 5 votes vote down vote up
def get_vtgt_field_local(self, pose):
        xy = pose[0:2]
        th = pose[2]

        # create query map
        get_map0 = self._generate_grid(self.rng_get, self.res_get)
        get_map_x = np.cos(th)*get_map0[0,:,:] - np.sin(th)*get_map0[1,:,:] + xy[0]
        get_map_y = np.sin(th)*get_map0[0,:,:] + np.cos(th)*get_map0[1,:,:] + xy[1]

        # get vtgt
        vtgt_x0 = np.reshape(np.array([self.vtgt_interp_x(x, y) \
                            for x, y in zip(get_map_x.flatten(), get_map_y.flatten())]),
                            get_map_x.shape)
        vtgt_y0 = np.reshape(np.array([self.vtgt_interp_y(x, y) \
                            for x, y in zip(get_map_x.flatten(), get_map_y.flatten())]),
                            get_map_y.shape)

        vtgt_x = np.cos(-th)*vtgt_x0 - np.sin(-th)*vtgt_y0
        vtgt_y = np.sin(-th)*vtgt_x0 + np.cos(-th)*vtgt_y0

        # debug
        """
        if xy[0] > 10:
            import matplotlib.pyplot as plt
            plt.figure(100)
            plt.axes([.025, .025, .95, .95])
            plt.plot(get_map_x, get_map_y, '.')
            plt.axis('equal')

            plt.figure(101)
            plt.axes([.025, .025, .95, .95])
            R = np.sqrt(vtgt_x0**2 + vtgt_y0**2)
            plt.quiver(get_map_x, get_map_y, vtgt_x0, vtgt_y0, R)
            plt.axis('equal')

            plt.show()
        """

        return np.stack((vtgt_x, vtgt_y)) 
Example 26
Project: neural-network-animation   Author: miloharper   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.))

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) 
Example 27
Project: mvsec   Author: daniilidis-group   File: compute_flow.py    MIT License 5 votes vote down vote up
def compute_flow_single_frame(self, V, Omega, depth_image, dt):
        """
        params:
            V : [3,1]
            Omega : [3,1]
            depth_image : [m,n]
        """
        flat_depth = depth_image.ravel()
        # flat_depth[np.logical_or(np.isclose(flat_depth,0.0), flat_depth<0.)]
        mask = np.isfinite(flat_depth)

        fdm = 1./flat_depth[mask]
        fxm = self.flat_x_map[mask]
        fym = self.flat_y_map[mask]
        omm = self.omega_mat[mask,:,:]

        x_flow_out = np.zeros((depth_image.shape[0], depth_image.shape[1]))
        flat_x_flow_out = x_flow_out.reshape((-1))
        flat_x_flow_out[mask] = fdm * (fxm*V[2]-V[0])
        flat_x_flow_out[mask] +=  np.squeeze(np.dot(omm[:,0,:], Omega))

        y_flow_out = np.zeros((depth_image.shape[0], depth_image.shape[1]))
        flat_y_flow_out = y_flow_out.reshape((-1))
        flat_y_flow_out[mask] = fdm * (fym*V[2]-V[1])
        flat_y_flow_out[mask] +=  np.squeeze(np.dot(omm[:,1,:], Omega))

        flat_x_flow_out *= dt * self.P[0,0]
        flat_y_flow_out *= dt * self.P[1,1]

        """
        plt.quiver(flat_distorted_x[::100],
                   flat_distorted_y[::100],
                   flat_distorted_x_flow_out[::100],
                   flat_distorted_y_flow_out[::100])

        plt.show()
        """

        return x_flow_out, y_flow_out 
Example 28
Project: python3_ios   Author: holzschu   File: test_collections.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) 
Example 29
Project: monsoon-onset   Author: jenfly   File: scratchpad.py    MIT License 5 votes vote down vote up
def animate(data, day, axlims=(-30, 45, 40, 120), dx=5, dy=5, climits=(-5, 15),
            cmap='BuPu', d0=138, clev=np.arange(5, 15.5, 1),
            cticks=np.arange(5, 16, 2.5)):
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v)
    plt.title(title)
    plt.draw()

# Need to scale arrows in quiver plot so that they are consistent across
# different days 
Example 30
Project: monsoon-onset   Author: jenfly   File: thesis-figs.py    MIT License 5 votes vote down vote up
def animate(i):
    days = range(-136, 227, 1)
    day = days[i]
    axlims=(-30, 45, 40, 120)
    dx, dy = 5, 5
    climits=(0, 20)
    cmap = 'hot_r'
    d0 = 138
    cticks=np.arange(4, 21, 2)
    scale = 250
    clev=np.arange(4, 20.5, 1)
    lat1, lat2, lon1, lon2 = axlims
    subset_dict = {'lat' : (lat1, lat2), 'lon' : (lon1, lon2)}
    xticks = range(40, 121, 20)
    yticks = range(-20, 41, 10)
    mm, dd = atm.jday_to_mmdd(day + d0)
    title = (atm.month_str(mm)).capitalize() + ' %d' % dd

    u = atm.subset(data['U'].sel(dayrel=day), subset_dict)
    v = atm.subset(data['V'].sel(dayrel=day), subset_dict)
    u = u[::dy, ::dx]
    v = v[::dy, ::dx]
    #spd = np.sqrt(u**2 + v**2)
    pcp = data['PREC'].sel(dayrel=day)
    lat = atm.get_coord(u, 'lat')
    lon = atm.get_coord(u, 'lon')

    plt.clf()
    m = atm.init_latlon(lat1, lat2, lon1, lon2, coastlines=False)
    m.drawcoastlines(color='k', linewidth=0.5)
    m.shadedrelief(scale=0.3)
    atm.contourf_latlon(pcp, clev=clev, axlims=axlims, m=m, cmap=cmap,
                        extend='max', cb_kwargs={'ticks' : cticks})
    #atm.pcolor_latlon(pcp, axlims=axlims, cmap=cmap, cb_kwargs={'extend' : 'max'})
    plt.xticks(xticks, atm.latlon_labels(xticks, 'lon'))
    plt.yticks(yticks, atm.latlon_labels(yticks, 'lat'))
    plt.clim(climits)
    #plt.quiver(lon, lat, u, v, linewidths=spd.values.ravel())
    plt.quiver(lon, lat, u, v, scale=scale, pivot='middle')
    plt.title(title)
    plt.draw() 
Example 31
Project: amfm   Author: alvarouc   File: amfm2d.py    GNU General Public License v3.0 5 votes vote down vote up
def plotAMFM(im, ifRow,ifCol):

    plt.imshow(im,interpolation="nearest",
               cmap = "Greys_r")
    Row,Col = np.meshgrid(range(0,im.shape[0]),
                          range(0,im.shape[1]))
    sp= np.round(max(im.shape)/30)
    plt.quiver(Col[::sp,::sp],Row[::sp,::sp],
               ifCol[::sp,::sp],ifRow[::sp,::sp],
               scale = 10, color = "r",
               pivot = "mid", width = 0.004)
    plt.title("Instantaneous frequency") 
Example 32
Project: linear_neuron   Author: uglyboxer   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.))

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) 
Example 33
Project: qqmbr   Author: ischurov   File: odebook.py    MIT License 5 votes vote down vote up
def mquiver(xs, ys, v, **kw):
    """wrapper function for quiver
    xs and ys are arrays of x's and y's
    v is a function R^2 -> R^2, representing vector field
    kw are passed to quiver verbatim"""
    X,Y = np.meshgrid(xs, ys)
    V = [[v(x,y) for x in xs] for y in ys]
    VX = [[w[0] for w in q] for q in V]
    VY = [[w[1] for w in q] for q in V]
    plt.quiver(X, Y, VX, VY, **kw) 
Example 34
Project: qqmbr   Author: ischurov   File: odebook.py    MIT License 5 votes vote down vote up
def dirfield(xs, ys, f, **kw):
    """
    wrapper function of mquiver that plots the direction field
    xs and ys are arrays of x's and y's
    f is a function R^2->R
    kw are passed to quiver verbatim
    """
    xs, ys = list(xs), list(ys) #in case something wrong was given
    mquiver(xs, ys, lambda x,y: (1,f(x,y)), scale=90, headwidth=0.0,
                    headlength=0.0,
                    headaxislength=0.0,pivot='middle',angles='xy',**kw) 
Example 35
Project: mpb-plotting   Author: FilipDominec   File: plot_dispersion_and_modes.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_mode(file1, file2, file3, title='', plot_vectors=True):#{{{
    #print "---------"
    #print h5py.File('epsilon.h5', "r").keys()
    #print h5py.File(file2, "r").keys()
    eps = np.array(h5py.File('%sepsilon.h5' % ctlscript, "r")['data-new'])
    Ez_data = np.array(h5py.File(file1, "r")['z.i-new'])
    Hx_data = np.array(h5py.File(file2, "r")['x.r-new'])
    Hy_data = np.array(h5py.File(file3, "r")['y.r-new'])

    ## Location of data points
    xpoints = np.linspace(0, 1, len(Ez_data))
    ypoints = np.linspace(0, 1, len(Ez_data[0]))

    ## Plot the scalar values, normalize the field amplitude scale
    lvlextent = max(np.abs(np.min(Ez_data)), np.abs(np.max(Ez_data)))
    contours = plt.contourf(xpoints, ypoints, Ez_data, cmap=matplotlib.cm.RdBu, levels=np.linspace(-lvlextent, lvlextent, contourcount), label='')
    for contour in contours.collections: contour.set_antialiased(False) ## fix aliasing for old Matplotlib
    plt.contour(xpoints, ypoints, Ez_data, levels=[0], label='', colors='#00ff00', lw=2, alpha=.5)

    ## Plot permittivity
    plt.contour(xpoints, ypoints, eps, colors='k',alpha=1, label='', lw=4, levels=[1.5])

    ## Plot the vector field
    if plot_vectors:
        xgrid, ygrid    = np.meshgrid(xpoints, ypoints)                 ## the vector locations
        plt.quiver(xgrid, ygrid, Hy_data, Hx_data, pivot='middle', headwidth=3, headlength=6, label='')
    if title: plt.title(title)

    ## Finish the graph + save 
    #plt.xlabel(u"$y/(2a)$"); plt.ylabel(u"$x/(2a)$"); 
#}}}


#columncount = 3     # Gamma-modes, bandstructure, X-modes 
Example 36
Project: edask   Author: nasa-nccs-cds   File: modelInterpretation.py    GNU General Public License v3.0 5 votes vote down vote up
def feature_optimization( conv_model, in_vars, scaling_values ):
    out_diff = K.mean((conv_model.layers[-1].output - 1) ** 2)
    grad = K.gradients(out_diff, [conv_model.input])[0]
    grad /= K.maximum(K.sqrt(K.mean(grad ** 2)), K.epsilon())
    iterate = K.function([conv_model.input, K.learning_phase()],
                         [out_diff, grad])
    # input_img_data = np.random.normal(scale=0.1, size=(1, 32, 32, len(in_vars)))
    input_img_data = np.zeros(shape=(1, 32, 32, len(in_vars)))

    out_losses = []
    for i in range(20):
        out_loss, out_grad = iterate([input_img_data, 0])
        input_img_data -= out_grad * 0.1
        out_losses.append(out_loss)

    plt.figure(figsize=(8, 8))
    plt.pcolormesh(input_img_data[0, :, :, 0] * scaling_values.loc[0, "std"] + scaling_values.loc[0, "mean"],
                   vmin=-10, vmax=80, cmap="gist_ncar")
    plt.colorbar()
    plt.quiver(input_img_data[0, :, :, -2] * scaling_values.loc[1, "std"] + scaling_values.loc[1, "mean"],
               input_img_data[0, :, :, -1] * scaling_values.loc[2, "std"] + scaling_values.loc[2, "mean"],
               scale=500)
    plt.title("Mesocyclone Conv Net Output Layer Feature Optimization")
    plt.savefig("conv_model_output_feature.png", dpi=200, bbox_inches="tight")

    plt.figure(figsize=(8, 8))
    plt.pcolormesh(input_img_data[0, :, :, 0], vmin=-5, vmax=5, cmap="RdBu_r")
    plt.quiver(input_img_data[0, :, :, 1], input_img_data[0, :, :, 2], scale=100)

    return out_losses 
Example 37
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) 
Example 38
Project: fastGPOM   Author: STAR-Center   File: fast_gpom_online.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_current_map():
    font = {'weight': 'normal',
            'size': 20}

    matplotlib.rc('font', **font)

    plt.figure("GP Occupancy Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.map, vmin=0, vmax=1)
    plt.colorbar()
    '''
    if not gp_map.current_pose is None:
        plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
                   1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
                   edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    plt.axis('equal')
    '''
    '''
    plt.figure("GP Frontier Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.frontier_map, vmin=0, vmax=1)
    plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
               1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
               edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    if not gp_map.expl_goal is None:
        plt.plot(gp_map.expl_goal[:, 0], gp_map.expl_goal[:, 1], linestyle='-.', c='m', marker='+', markersize=14)
    plt.axis('equal')
    '''
    plt.draw()
    plt.pause(.1) 
Example 39
Project: fastGPOM   Author: STAR-Center   File: gpom_online.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_current_map():
    font = {'weight': 'normal',
            'size': 20}

    matplotlib.rc('font', **font)

    plt.figure("GP Occupancy Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.map, vmin=0, vmax=1)
    plt.colorbar()
    '''
    if not gp_map.current_pose is None:
        plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
                   1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
                   edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    plt.axis('equal')
    '''
    '''
    plt.figure("GP Frontier Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.frontier_map, vmin=0, vmax=1)
    plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
               1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
               edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    if not gp_map.expl_goal is None:
        plt.plot(gp_map.expl_goal[:, 0], gp_map.expl_goal[:, 1], linestyle='-.', c='m', marker='+', markersize=14)
    plt.axis('equal')
    '''
    plt.draw()
    plt.pause(.1) 
Example 40
Project: fastGPOM   Author: STAR-Center   File: gp_occ_map.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_current_map():
    font = {'weight': 'normal',
            'size': 20}

    matplotlib.rc('font', **font)

    plt.figure("GP Occupancy Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.map, vmin=0, vmax=1)
    plt.colorbar()
    if not gp_map.current_pose is None:
        plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
                   1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
                   edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    plt.axis('equal')

    plt.figure("GP Frontier Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.frontier_map, vmin=0, vmax=1)
    plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
               1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
               edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    if not gp_map.expl_goal is None:
        plt.plot(gp_map.expl_goal[:, 0], gp_map.expl_goal[:, 1], linestyle='-.', c='m', marker='+', markersize=14)
    plt.axis('equal')
    plt.draw()
    plt.pause(.1) 
Example 41
Project: fastGPOM   Author: STAR-Center   File: gp_occ_map_offline.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_current_map():
    font = {'weight': 'normal',
            'size': 20}

    matplotlib.rc('font', **font)

    plt.figure("GP Occupancy Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.map, vmin=0, vmax=1)
    plt.colorbar()
    if not gp_map.current_pose is None:
        plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
                   1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
                   edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    plt.axis('equal')

    plt.figure("GP Frontier Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.frontier_map, vmin=0, vmax=1)
    plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
               1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
               edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    if not gp_map.expl_goal is None:
        plt.plot(gp_map.expl_goal[:, 0], gp_map.expl_goal[:, 1], linestyle='-.', c='m', marker='+', markersize=14)
    plt.axis('equal')
    plt.draw()
    plt.pause(.1) 
Example 42
Project: fastGPOM   Author: STAR-Center   File: gpom_offline.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_current_map():
    font = {'weight': 'normal',
            'size': 20}

    matplotlib.rc('font', **font)

    plt.figure("GP Occupancy Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.map, vmin=0, vmax=1)
    plt.colorbar()
    '''
    if not gp_map.current_pose is None:
        plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
                   1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
                   edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    plt.axis('equal')
    '''
    '''
    plt.figure("GP Frontier Map")
    plt.clf()
    plt.pcolor(gp_map.X, gp_map.Y, gp_map.frontier_map, vmin=0, vmax=1)
    plt.quiver(gp_map.current_pose[0], gp_map.current_pose[1], 1. * np.cos(gp_map.current_pose[2]),
               1. * np.sin(gp_map.current_pose[2]), angles='xy', scale_units='xy', scale=1,
               edgecolors='m', pivot='mid', facecolor='none', linewidth=1, width=0.001, headwidth=400, headlength=800)
    if not gp_map.expl_goal is None:
        plt.plot(gp_map.expl_goal[:, 0], gp_map.expl_goal[:, 1], linestyle='-.', c='m', marker='+', markersize=14)
    plt.axis('equal')
    '''
    plt.draw()
    plt.pause(.1) 
Example 43
Project: Symmetrical-Components-Visualization   Author: BJohnson98   File: general_symmetrical_components.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self, start_x, start_y, c):
		plt.quiver(start_x, start_y, self.get_cart().real, self.get_cart().imag, angles='xy', scale_units='xy', scale=1, color=c) 
Example 44
Project: Symmetrical-Components-Visualization   Author: BJohnson98   File: Symmetrical_Components.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_vector(start_x, start_y, radius, angle, c):
	x,y = pol2cart(radius,angle)
	plt.quiver(start_x, start_y, x, y, angles='xy', scale_units='xy', scale=1, color=c) 
Example 45
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) 
Example 46
Project: ImageFusion   Author: pfchai   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.))

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) 
Example 47
Project: Blackjack-Tracker   Author: martinabeleda   File: test_collections.py    MIT License 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.))

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) 
Example 48
Project: shesha   Author: ANR-COMPASS   File: tools.py    GNU General Public License v3.0 5 votes vote down vote up
def plpyr(slopesvector, validArray):
    """
    wao.config.p_wfs0._isvalid
    """
    nslopes = slopesvector.shape[0] / 2
    x, y = np.where(validArray.T)
    plt.quiver(x, y, slopesvector[0:nslopes], slopesvector[nslopes:]) 
Example 49
Project: VectorFields   Author: OlafHaag   File: vectorfields.py    MIT License 5 votes vote down vote up
def plot(self, filename=None):
        """ Plot a top-down view on the XY plane of the vector field. """
        plt.figure(figsize=(6, 6))
        plt.quiver(np.squeeze(self.grid_x, axis=2),
                   np.squeeze(self.grid_y, axis=2),
                   np.squeeze(self.u, axis=2),
                   np.squeeze(self.v, axis=2),
                   pivot='middle', headwidth=4, headlength=6)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.axis('image')
        self._plot_save_or_show(filename) 
Example 50
Project: iris-extensions   Author: LSaffin   File: __init__.py    MIT License 5 votes vote down vote up
def overlay_winds(u, v, nx, ny, **kwargs):
    """Overlay a quiver plot on an existing iris plot

    Args:
        u (iris.cube.Cube): The x-component of the vector to be plotted

        v (iris.cube.Cube): The y-component of the vector to be plotted

        nx (int): The coarse grained resolution on the x-axis

        ny (int): The coarse grained resolution on the y-axis

    """
    # Extract a coarse representation of the x and y coordinates
    xcoord = grid.extract_dim_coord(u, 'x')
    x_fac = int(len(xcoord.points) / nx)
    ycoord = grid.extract_dim_coord(u, 'y')
    y_fac = int(len(ycoord.points) / ny)
    x_coarse = xcoord.points[::x_fac]
    y_coarse = ycoord.points[::y_fac]

    # Interpolate the vector field to the coarse resolution
    interp_kwargs = {xcoord.name(): x_coarse, ycoord.name(): y_coarse}
    u_coarse = interpolate.interpolate(u, **interp_kwargs)
    v_coarse = interpolate.interpolate(v, **interp_kwargs)

    # Plot the coarse data
    return plt.quiver(
        x_coarse, y_coarse, u_coarse.data, v_coarse.data,**kwargs) 
Example 51
Project: dynamo-release   Author: aristoteleo   File: utilities.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def quiver_autoscaler(X_emb, V_emb):
    """Function to automatically calculate the value for the scale parameter of quiver plot, adapted from scVelo

    Parameters
    ----------
        X_emb: `np.ndarray`
            X, Y-axis coordinates
        V_emb:  `np.ndarray`
            Velocity (U, V) values on the X, Y-axis

    Returns
    -------
        The scale for quiver plot
    """

    import matplotlib.pyplot as plt
    scale_factor = np.ptp(X_emb, 0).mean()
    X_emb = X_emb - X_emb.min(0)

    if len(V_emb.shape) == 3:
        Q = plt.quiver(X_emb[0] / scale_factor, X_emb[1] / scale_factor,
                   V_emb[0], V_emb[1], angles='xy', scale_units='xy', scale=None)
    else:
        Q = plt.quiver(X_emb[:, 0] / scale_factor, X_emb[:, 1] / scale_factor,
                      V_emb[:, 0], V_emb[:, 1], angles='xy', scale_units='xy', scale=None)

    Q._init()
    plt.clf()

    return Q.scale / scale_factor 
Example 52
Project: quasi-unsupervised-cc   Author: claudio-unipv   File: evalmodel.py    MIT License 5 votes vote down vote up
def plot_estimates(estimates, illuminants):
    import matplotlib.pyplot as plt
    diff = estimates - illuminants
    for i in range(3):
        j = (i + 1) % 3
        plt.subplot(2, 2, i + 1)
        plt.grid()
        plt.quiver(illuminants[:, i], illuminants[:, j], diff[:, i], diff[:, j], color=estimates)
        plt.xlabel("RGB"[i]);
        plt.ylabel("RGB"[j]);
    plt.show() 
Example 53
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_collections.py    GNU General Public License v3.0 5 votes vote down vote up
def test_quiver_limits():
    ax = plt.axes()
    x, y = np.arange(8), np.arange(10)
    u = v = np.linspace(0, 10, 80).reshape(10, 8)
    q = plt.quiver(x, y, u, v)
    assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)

    plt.figure()
    ax = plt.axes()
    x = np.linspace(-5, 10, 20)
    y = np.linspace(-2, 4, 10)
    y, x = np.meshgrid(y, x)
    trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
    plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
    assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) 
Example 54
Project: differentiable-particle-filters   Author: tu-rbo   File: plot_models.py    MIT License 5 votes vote down vote up
def plot_proposer(session, method, statistics, batch, task, num_examples, variant):

    num_particles = 1000
    proposer_out = method.propose_particles(method.encodings[0, :], num_particles, statistics['state_mins'], statistics['state_maxs'])

    # define the inputs and train/run the model
    input_dict = {**{method.placeholders[key]: batch[key] for key in 'osa'},
                  }
    particles = session.run(proposer_out, input_dict)

    for i in range(num_examples):
        fig = plt.figure(figsize=(2.4, 1.29/0.9), num="%s %s proposer" % (variant, i))
        # plt.gca().clear()
        plot_maze(task, margin=5, linewidth=0.5)

        quiv = plt.quiver(particles[i, :, 0], particles[i, :, 1], np.cos(particles[i, :, 2]),
                         np.sin(particles[i, :, 2]), np.ones([num_particles]), cmap='viridis_r', clim=[0, 2], alpha=1.0,
                          **quiv_kwargs
                          )

        plt.quiver([batch['s'][0, i, 0]], [batch['s'][0, i, 1]], np.cos([batch['s'][0,i, 2]]),
                  np.sin([batch['s'][0, i, 2]]), color='red',
                **quiv_kwargs)  # width=0.01, scale=100
        plt.plot([batch['s'][0, i, 0]], [batch['s'][0, i, 1]], 'or', **marker_kwargs)


        plt.gca().axis('off')
        plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95, wspace=0.0, hspace=0.00)

        # plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.001, hspace=0.1)
        plt.savefig('../plots/models/prop{}.pdf'.format(i), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01) 
Example 55
Project: differentiable-particle-filters   Author: tu-rbo   File: plot_models.py    MIT License 5 votes vote down vote up
def plot_motion_model(session, method, statistics, batch, task, num_examples, num_particles, variant):

    motion_samples = method.motion_update(method.placeholders['a'][:, 1],
                                        tf.tile(method.placeholders['s'][:, :1], [1, num_particles, 1]),
                                        statistics['means'], statistics['stds'], statistics['state_step_sizes'])

    # define the inputs and train/run the model
    input_dict = {**{method.placeholders[key]: batch[key] for key in 'osa'},
                  }
    particles = session.run(motion_samples, input_dict)

    fig = plt.figure(figsize=(2.4, 1.29), num="%s motion model" % (variant))
    # plt.gca().clear()
    plot_maze(task, margin=5, linewidth=0.5)

    for i in range(num_examples):

        plt.quiver(particles[i, :, 0], particles[i, :, 1], np.cos(particles[i, :, 2]),
                          np.sin(particles[i, :, 2]), np.ones([num_particles]), cmap='viridis_r',
                   **quiv_kwargs,
                   alpha=1.0, clim=[0, 2])  # width=0.01, scale=100

        plt.quiver([batch['s'][i, 0, 0]], [batch['s'][i, 0, 1]], np.cos([batch['s'][i, 0, 2]]),
                   np.sin([batch['s'][i, 0, 2]]), color='black',
                   **quiv_kwargs,
                   )  # width=0.01, scale=100

        plt.plot(batch['s'][i, :2, 0], batch['s'][i, :2, 1], '--', color='black', linewidth=0.3)
        plt.plot(batch['s'][i, :1, 0], batch['s'][i, :1, 1], 'o', color='black', linewidth=0.3, **marker_kwargs)
        plt.plot(batch['s'][i, 1:2, 0], batch['s'][i, 1:2, 1], 'o', color='red', linewidth=0.3, **marker_kwargs)

        plt.quiver([batch['s'][i, 1, 0]], [batch['s'][i, 1, 1]], np.cos([batch['s'][i, 1, 2]]),
                   np.sin([batch['s'][i, 1, 2]]), color='red',
                   **quiv_kwargs)  # width=0.01, scale=100

    plt.gca().axis('off')

    plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.001, hspace=0.1)
    plt.savefig('../plots/models/motion_model{}.pdf'.format(i), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01) 
Example 56
Project: differentiable-particle-filters   Author: tu-rbo   File: plotting_utils.py    MIT License 5 votes vote down vote up
def plot_trajectories(data, figure_name=None, show=False, pause=False, emphasize=None, odom=False, mincolor=0.0, linewidth=0.3):
    from methods.odom import OdometryBaseline
    if figure_name is not None:
        plt.figure(figure_name)
    for i, trajectories in enumerate(data['s']):
        color = np.random.uniform(low=mincolor, high=1.0, size=3)
        plt.plot(trajectories[:, 0], trajectories[:, 1], color=color, linewidth=linewidth, zorder=0)
    if emphasize is not None:
        true_traj = data['s'][emphasize, :20, :]
        odom = OdometryBaseline()
        odom_traj = odom.predict(None, {k:data[k][emphasize:emphasize+1, :20] for k in data.keys()})[0]
        print(true_traj)
        print(odom_traj)

        traj = odom_traj
        plt.plot(traj[:, 0], traj[:, 1], '--', color=[0.0, 0.0, 1.0], linewidth=0.8, zorder=0)
        # plt.plot(traj[:, 0], traj[:, 1], 'o', markerfacecolor='None',
        #     markeredgecolor=[0.0, 0.0, 0.0],
        #     markersize=5)
        # plt.quiver(traj[:, 0], traj[:, 1], np.cos(traj[:, 2]), np.sin(traj[:, 2]),
        #            color=[0.0, 0.0, 0.0], zorder=1, headlength=0, headaxislength=0, scale=10, width=0.02, units='inches', scale_units='inches')

        traj = true_traj
        plt.plot(traj[:, 0], traj[:, 1], '-', color=[0.0, 0.0, 1.0], linewidth=0.8, zorder=0)
        plt.plot(traj[:, 0], traj[:, 1], 'o', markerfacecolor='None',
            markeredgecolor=[0.0, 0.0, 0.0],
            markersize=5)
        plt.quiver(traj[:, 0], traj[:, 1], np.cos(traj[:, 2]), np.sin(traj[:, 2]),
                   color=[0.0, 0.0, 0.0], zorder=1, headlength=0, headaxislength=0, scale=10, width=0.02, units='inches', scale_units='inches')

    plt.gca().set_aspect('equal')
    show_pause(show, pause) 
Example 57
Project: kappa   Author: ajkerr0   File: plot.py    MIT License 4 votes vote down vote up
def bonds(molecule, sites=False, indices=False, faces=False, order=False, 
          atomtypes=False, linewidth=4.):
    """Draw a 2d 'overhead' view of a molecule."""
    
    fig = plt.figure()
    figTitle = molecule.name
    
    posList = molecule.posList
    length = len(molecule)
    
    for bond in molecule.bondList:
        i,j = bond
        plt.plot([posList[i][0],posList[j][0]],
                 [posList[i][1],posList[j][1]],
                 color='k', zorder=-1, linewidth=linewidth)
        
    cList = np.zeros([length,3])
    
    if sites:
        for count in range(len(molecule)):
            cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]])
        plt.scatter(posList[:,0],posList[:,1],s=1.5*radList[molecule.zList],c=cList,
                    edgecolors='k')
        
    if indices:
        for index, pos in enumerate(molecule.posList):
            plt.annotate(index, (pos[0]+.1, pos[1]+.1), color='b', fontsize=10)
            
    if atomtypes:
        for atomtype, pos in zip(molecule.atomtypes, molecule.posList):
            plt.annotate(atomtype, (pos[0]-.5, pos[1]-.5), color='b', fontsize=10)
        
    if faces:
        for i,face in enumerate(molecule.faces):
            openAtoms = [x for x in face.atoms if x not in face.closed]
            plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2)
            plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red')
            plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s=40, c='purple')
            plt.annotate(i, (face.pos[0]-.35*face.norm[0], face.pos[1]-.35*face.norm[1]), 
                         color='r', fontsize=20)
            if np.linalg.norm(face.norm[:2]) > 0.0001:
                plt.quiver(face.pos[0]+.5*face.norm[0], face.pos[1]+.5*face.norm[1], 5.*face.norm[0], 5.*face.norm[1],
                color='r', headwidth=1, units='width', width=5e-3, headlength=2.5)
                
    if order:
        for index, bo in enumerate(molecule.bondorder):
            i,j = molecule.bondList[index]
            midpoint = (molecule.posList[i]+molecule.posList[j])/2.
            plt.annotate(bo, (midpoint[0], midpoint[1]), color='k', fontsize=20)
    
    fig.suptitle(figTitle, fontsize=18)
    plt.axis('equal')
    plt.xlabel('x-position', fontsize=13)
    plt.ylabel('y-position', fontsize=13)
    
    plt.show() 
Example 58
Project: kappa   Author: ajkerr0   File: plot.py    MIT License 4 votes vote down vote up
def bondsax(molecule, ax, sites=False, indices=False, faces=False, order=False, 
          atomtypes=False, linewidth=4., size_scale=1.):
    """Draw a 2d 'overhead' view of a molecule."""
    
    plt.sca(ax)
    
    posList = molecule.posList
    length = len(molecule)
    
    for bond in molecule.bondList:
        i,j = bond
        plt.plot([posList[i][0],posList[j][0]],
                 [posList[i][1],posList[j][1]],
                 color='k', zorder=-1, linewidth=linewidth)
        
    cList = np.zeros([length,3])
    
    if sites:
        for count in range(len(molecule)):
            cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]])
        plt.scatter(posList[:,0],posList[:,1],s=1.5*radList[molecule.zList]*size_scale,c=cList,
                    edgecolors='k')
        
    if indices:
        for index, pos in enumerate(molecule.posList):
            plt.annotate(index, (pos[0]+.1, pos[1]+.1), color='b', fontsize=10)
            
    if atomtypes:
        for atomtype, pos in zip(molecule.atomtypes, molecule.posList):
            plt.annotate(atomtype, (pos[0]-.5, pos[1]-.5), color='b', fontsize=10)
        
    if faces:
        for i,face in enumerate(molecule.faces):
            openAtoms = [x for x in face.atoms if x not in face.closed]
            plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2)
            plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red')
            plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s=40, c='purple')
            plt.annotate(i, (face.pos[0]-.35*face.norm[0], face.pos[1]-.35*face.norm[1]), 
                         color='r', fontsize=20)
            if np.linalg.norm(face.norm[:2]) > 0.0001:
                plt.quiver(face.pos[0]+.5*face.norm[0], face.pos[1]+.5*face.norm[1], 5.*face.norm[0], 5.*face.norm[1],
                color='r', headwidth=1, units='width', width=5e-3, headlength=2.5)
                
    if order:
        for index, bo in enumerate(molecule.bondorder):
            i,j = molecule.bondList[index]
            midpoint = (molecule.posList[i]+molecule.posList[j])/2.
            plt.annotate(bo, (midpoint[0], midpoint[1]), color='k', fontsize=20)
    
    plt.axis('equal')
    
    plt.show() 
Example 59
Project: ble5-nrf52-mac   Author: tomasero   File: test_triangulation.py    MIT License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex**2 + Ey**2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 60
Project: osim-rl   Author: stanfordnmbl   File: v_tgt_field.py    MIT License 4 votes vote down vote up
def update(self, pose):
        self.t += self.dt
        self.i += 1

        self.pose_agent = pose

        if not hasattr(self, 'p_sink'):
            flag_target_achieved = 0
        else:
            if np.linalg.norm(self.p_sink - self.pose_agent[0:2]) < self.r_target:
                self.t_target += self.dt
            else: # reset t_target if agent goes out of 
                self.t_target = 0

            flag_target_achieved = 0
            if (self.t_target > self.t0_target # stayed at the target
                and self.i_target <= self.n_new_target): # on a new target
                if self.i_target < self.n_new_target: # if ... create new target
                    del_p_sink_r = np.random.uniform(self.rng_p_sink_r_th[0,0], self.rng_p_sink_r_th[0,1])
                    del_p_sink_th = np.random.uniform(self.rng_p_sink_r_th[1,0], self.rng_p_sink_r_th[1,1])
                    self.path_th += del_p_sink_th
                    del_p_sink_x = np.cos(self.path_th)*del_p_sink_r
                    del_p_sink_y = np.sin(self.path_th)*del_p_sink_r
                    self.p_sink += np.array([del_p_sink_x, del_p_sink_y])
                    self.rng_xy = (self.pose_agent[0:2] + self.rng_xy0.T).T
                    self.vtgt_obj.create_map(self.rng_xy)
                    self.create_vtgt_sink(self.v_amp_rng)
                self.i_target += 1
                self.t_target = 0
                flag_target_achieved = 1

        v_tgt_field = self.vtgt_obj.get_vtgt_field_local(pose)
        if self.visualize:
            if flag_target_achieved:
                self.vis['q0'].remove()
                X = self.vtgt_obj.map[0]
                Y = self.vtgt_obj.map[1]
                U = self.vtgt_obj.vtgt[0]
                V = self.vtgt_obj.vtgt[1]
                R = np.sqrt(U**2 + V**2)
                self.vis['q0'] = self.vis['axes'][0].quiver(X, Y, U, V, R)
                self.vis['axes'][0].axis('equal')

            if self.di_visualize == 1 or self.i%self.di_visualize==1 or self.t == self.dt:
                self.vis['axes'][0].plot(pose[0], pose[1], 'k.')
                
                X, Y = self.vtgt_obj._generate_grid(self.vtgt_obj.rng_get, self.vtgt_obj.res_get)
                U = v_tgt_field[0]
                V = v_tgt_field[1]
                R = np.sqrt(U**2 + V**2)
                self.vis['q1'].remove()
                self.vis['q1'] = self.vis['axes'][1].quiver(X, Y, U, V, R)
                self.vis['axes'][1].plot(0, 0, 'k.')
                self.vis['axes'][1].axis('equal')

                self.vis['plt'].pause(0.0001)


        return v_tgt_field, flag_target_achieved

# ----------------------------------------------------------------------------------------------------------------- 
Example 61
Project: neural-network-animation   Author: miloharper   File: test_triangulation.py    MIT License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
    triang.set_mask(mask)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex**2 + Ey**2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.) 
Example 62
Project: python3_ios   Author: holzschu   File: test_triangulation.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex**2 + Ey**2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 63
Project: pompy   Author: InsectRobotics   File: demos.py    MIT License 4 votes vote down vote up
def wind_model_demo(dt=0.01, t_max=100, steps_per_frame=20, seed=DEFAULT_SEED):
    """Set up wind model and animate velocity field with quiver plot.

    Parameters
    ----------
    dt : float
        Simulation timestep.
    t_max : float
        End time to simulate to.
    steps_per_frame: integer
        Number of simulation time steps to perform between animation frames.
    seed : integer
        Seed for random number generator.

    Returns
    -------
    fig : Figure
        Matplotlib figure object.
    ax : AxesSubplot
        Matplotlib axis object.
    anim : FuncAnimation
        Matplotlib animation object.
    """
    rng = np.random.RandomState(seed)
    # define simulation region
    wind_region = models.Rectangle(x_min=0., x_max=100., y_min=-25., y_max=25.)
    # set up wind model
    wind_model = models.WindModel(wind_region, 21, 11, rng=rng)
    # let simulation run for 10s to equilibrate wind model
    for t in np.arange(0, 10, dt):
        wind_model.update(dt)
    # generate figure and attach close event
    fig, ax, title = set_up_figure()
    # create quiver plot of initial velocity field
    vf_plot = ax.quiver(wind_model.x_points, wind_model.y_points,
                        wind_model.velocity_field.T[0],
                        wind_model.velocity_field.T[1], width=0.003)
    # expand axis limits to make vectors at boundary of field visible
    ax.axis(ax.axis() + np.array([-0.25, 0.25, -0.25, 0.25]))
    ax.set_xlabel('x-coordinate / m')
    ax.set_ylabel('y-coordinate / m')
    ax.set_aspect(1)
    fig.tight_layout()

    # define update function
    @update_decorator(dt, title, steps_per_frame, [wind_model])
    def update(i):
        vf_plot.set_UVC(
            wind_model.velocity_field.T[0], wind_model.velocity_field.T[1])
        return [vf_plot]

    # create animation object
    n_frame = int(t_max / (dt * steps_per_frame) + 0.5)
    anim = FuncAnimation(fig, update, n_frame, blit=True)
    return fig, ax, anim 
Example 64
Project: global-divergences   Author: jeanfeydy   File: demo_2D.py    MIT License 4 votes vote down vote up
def test(name, params, verbose=True) :
    params["kernel_heatmap_range"] = (0,1,100)

    # Compute the cost and gradient (+ fancy heatmaps in the background) ========================
    t_0 = time()
    cost, grad_src, heatmaps = sparse_distance_bmp(params, source, target, 
                                                           affine, affine, 
                                                           normalize=True, info=display )
    t_1 = time()
    if verbose : print("{} : {:.2f}s, cost = {:.6f}".format( name, t_1-t_0, cost.item()) )

    # Display ==================================================================================
    grad_src = - grad_src # N.B.: We want to visualize a descent direction, not the opposite!
    if display :
        plt.clf()

        # Source + Target : fancy  red+blue overlay
        source_plot = .3*source.cpu().numpy()
        target_plot = .3*target.cpu().numpy()
        img_plot    = np.dstack( ( np.ones(source_plot.shape) - target_plot, 
                                   np.ones(source_plot.shape) - source_plot - target_plot, 
                                   np.ones(source_plot.shape) - source_plot ) )
        
        plt.imshow( np.swapaxes(img_plot,0,1), origin="lower", extent=(0,1,0,1))

        if name != "dataset" :
            # Subsample the gradient field :
            grad_plot = grad_src.cpu().numpy()
            grad_plot = grad_plot[::sample, ::sample, :]
            if smooth :
                grad_plot = gaussian_filter(grad_plot, [2,2,0], mode='nearest')

            # Display the gradient field :
            X,Y   = np.meshgrid( np.linspace(0, 1, grad_plot.shape[0]+1)[:-1] + .5/(sample*grad_plot.shape[0]), 
                                np.linspace(0, 1, grad_plot.shape[1]+1)[:-1] + .5/(sample*grad_plot.shape[1]) )
            U, V  = grad_plot[:,:,0], grad_plot[:,:,1]
            norms = np.sqrt( (grad_plot[:,:,1]**2 + grad_plot[:,:,0]**2) )
            mask  = (norms>0)
            scale = np.mean( norms[mask] )
            if smooth : mask  = (source_plot[::sample, ::sample]>0)

            Y, X, U, V = Y[mask], X[mask], U[mask], V[mask]
            plt.quiver( Y, X, U, V, 
                        scale = scale_grad*scale, scale_units="dots", color="#5CBF3A", zorder=3, width=0.0025)

            # "Distance", influence fields in the background :
            if heatmaps is not None :
                heatmaps.plot(plt.gca())
            
        # Save result in the "output/" folder :
        plt.savefig("output/2D/" + dataset + "_" + name +".png") 
        plt.pause(.01) 
Example 65
Project: global-divergences   Author: jeanfeydy   File: demo_sinkhorn.py    MIT License 4 votes vote down vote up
def test(name, params, verbose=True) :
    params["kernel_heatmap_range"] = (0,1,100)
    # Compute the cost and gradient (+ fancy heatmaps in the background) ========================
    t_0 = time()
    cost, grad_src, heatmaps = sparse_distance_bmp(params, source, target, 
                                                           affine, affine, 
                                                           normalize=True, info=display )
    t_1 = time()
    if verbose : print("{} : {:.2f}s, cost = {:.6f}".format( name, t_1-t_0, cost.item()) )

    # Display ==================================================================================
    grad_src = - grad_src # N.B.: We want to visualize a descent direction, not the opposite!
    if display :
        plt.clf()

        # Source + Target : fancy  red+blue overlay
        source_plot = .3*source.cpu().numpy()
        target_plot = .3*target.cpu().numpy()
        img_plot    = np.dstack( ( np.ones(source_plot.shape) - target_plot, 
                                   np.ones(source_plot.shape) - source_plot - target_plot, 
                                   np.ones(source_plot.shape) - source_plot ) )
        
        plt.imshow( np.swapaxes(img_plot,0,1), origin="lower", extent=(0,1,0,1))

        if name != "dataset" :
            # Subsample the gradient field :
            grad_plot = grad_src.cpu().numpy()
            grad_plot = grad_plot[::sample, ::sample, :]
            if smooth :
                grad_plot = gaussian_filter(grad_plot, [2,2,0], mode='nearest')

            # Display the gradient field :
            X,Y   = np.meshgrid( np.linspace(0, 1, grad_plot.shape[0]+1)[:-1] + .5/(sample*grad_plot.shape[0]), 
                                np.linspace(0, 1, grad_plot.shape[1]+1)[:-1] + .5/(sample*grad_plot.shape[1]) )
            U, V  = grad_plot[:,:,0], grad_plot[:,:,1]
            norms = np.sqrt( (grad_plot[:,:,1]**2 + grad_plot[:,:,0]**2) )
            mask  = (norms>0)
            scale = np.mean( norms[mask] )
            if smooth : mask  = (source_plot[::sample, ::sample]>0)

            Y, X, U, V = Y[mask], X[mask], U[mask], V[mask]
            plt.quiver( Y, X, U, V, 
                        scale = scale_grad*scale, scale_units="dots", color="#5CBF3A", zorder=3, width=0.0025)

            # "Distance", influence fields in the background :
            if heatmaps is not None :
                heatmaps.plot(plt.gca())
            
        # Save result in the "output/" folder :
        plt.savefig("output/sinkhorn/" + dataset + "_" + name +".png") 
        plt.pause(.01) 
Example 66
Project: global-divergences   Author: jeanfeydy   File: demo_2D.py    MIT License 4 votes vote down vote up
def test(name, params, verbose=True) :
    params["kernel_heatmap_range"] = (0,1,100)

    # Compute the cost and gradient (+ fancy heatmaps in the background) ========================
    t_0 = time()
    cost, grad_src, heatmaps = sparse_distance_bmp(params, source, target, 
                                                           affine, affine, 
                                                           normalize=True, info=display )
    t_1 = time()
    if verbose : print("{} : {:.2f}s, cost = {:.6f}".format( name, t_1-t_0, cost.item()) )

    # Display ==================================================================================
    grad_src = - grad_src # N.B.: We want to visualize a descent direction, not the opposite!
    if display :
        plt.clf()

        # Source + Target : fancy  red+blue overlay
        source_plot = .3*source.cpu().numpy()
        target_plot = .3*target.cpu().numpy()
        img_plot    = np.dstack( ( np.ones(source_plot.shape) - target_plot, 
                                   np.ones(source_plot.shape) - source_plot - target_plot, 
                                   np.ones(source_plot.shape) - source_plot ) )
        
        plt.imshow( np.swapaxes(img_plot,0,1), origin="lower", extent=(0,1,0,1))

        if name != "dataset" :
            # Subsample the gradient field :
            grad_plot = grad_src.cpu().numpy()
            grad_plot = grad_plot[::sample, ::sample, :]
            if smooth :
                grad_plot = gaussian_filter(grad_plot, [2,2,0], mode='nearest')

            # Display the gradient field :
            X,Y   = np.meshgrid( np.linspace(0, 1, grad_plot.shape[0]+1)[:-1] + .5/(sample*grad_plot.shape[0]), 
                                np.linspace(0, 1, grad_plot.shape[1]+1)[:-1] + .5/(sample*grad_plot.shape[1]) )
            U, V  = grad_plot[:,:,0], grad_plot[:,:,1]
            norms = np.sqrt( (grad_plot[:,:,1]**2 + grad_plot[:,:,0]**2) )
            mask  = (norms>0)
            scale = np.mean( norms[mask] )
            if smooth : mask  = (source_plot[::sample, ::sample]>0)

            Y, X, U, V = Y[mask], X[mask], U[mask], V[mask]
            plt.quiver( Y, X, U, V, 
                        scale = scale_grad*scale, scale_units="dots", color="#5CBF3A", zorder=3, width=0.0025)

            # "Distance", influence fields in the background :
            if heatmaps is not None :
                heatmaps.plot(plt.gca())
            
        # Save result in the "output/" folder :
        plt.savefig("output/2D/" + dataset + "_" + name +".png") 
        plt.pause(.01) 
Example 67
Project: MuMoT   Author: DiODeProject   File: views.py    GNU General Public License v3.0 4 votes vote down vote up
def _plot_field(self, _=None):

        super()._plot_field()

        if self._stateVariable3 is None:
            self._get_field2d("2d vector plot", 10)  # @todo: allow user to set mesh points with keyword
            fig_vector = plt.quiver(self._X, self._Y, self._Xdot, self._Ydot, units='width', color='black')  # @todo: define colormap by user keyword

            if self._mumotModel._constantSystemSize:
                plt.fill_between([0, 1], [1, 0], [1, 1], color='grey', alpha='0.25')
                if self._chooseXrange:
                    choose_xrange = self._chooseXrange
                else:
                    choose_xrange = [0, 1]
                if self._chooseYrange:
                    choose_yrange = self._chooseYrange
                else:
                    choose_yrange = [0, 1]
            else:
                if self._chooseXrange:
                    choose_xrange = self._chooseXrange
                else:
                    choose_xrange = [0, self._X.max()]
                if self._chooseYrange:
                    choose_yrange = self._chooseYrange
                else:
                    choose_yrange = [0, self._Y.max()]
                # plt.xlim(0,self._X.max())
                # plt.ylim(0,self._Y.max())

            _fig_formatting_2D(figure=fig_vector, xlab=self._xlab,
                               specialPoints=self._FixedPoints,
                               showFixedPoints=self._showFixedPoints,
                               ax_reformat=False, curve_replot=False,
                               ylab=self._ylab, fontsize=self._chooseFontSize,
                               aspectRatioEqual=True,
                               choose_xrange=choose_xrange,
                               choose_yrange=choose_yrange)
        else:
            self._get_field3d("3d vector plot", 10)
            ax = self._figure.gca(projection='3d')
            # @todo: define colormap by user keyword; normalise off maximum value
            # in self._speed, and meshpoints?
            fig_vec3d = ax.quiver(self._X, self._Y, self._Z, self._Xdot,
                                  self._Ydot, self._Zdot, length=0.01, color='black')

            _fig_formatting_3D(figure=fig_vec3d, xlab=self._xlab,
                               ylab=self._ylab, zlab=self._zlab,
                               specialPoints=self._FixedPoints,
                               showFixedPoints=self._showFixedPoints,
                               ax_reformat=True,
                               showPlane=self._mumotModel._constantSystemSize,
                               fontsize=self._chooseFontSize)

        with io.capture_output() as log:
            self._appendFixedPointsToLogs(self._realEQsol, self._EV, self._Evects)
        self._logs.append(log) 
Example 68
Project: edask   Author: nasa-nccs-cds   File: modelInterpretation.py    GNU General Public License v3.0 4 votes vote down vote up
def plot_max_activation_pattern(conv_model, norm_in_data,all_in_data,all_valid_times):
    weights = conv_model.layers[-2].get_weights()[0].ravel()
    num_top = 16
    num_ex = 9
    batch_size = 2048
    top_neurons = weights.argsort()[::-1][0:num_top]
    top_examples = np.zeros((num_top, num_ex), dtype=int)
    top_gradients = np.zeros((num_top, num_ex, 32, 32, 3))
    batch_i = list(range(0, norm_in_data.shape[0], batch_size)) + [norm_in_data.shape[0]]
    for n, neuron in enumerate(top_neurons):
        print(n, neuron, weights[neuron])
        act_func = K.function([conv_model.input, K.learning_phase()], [conv_model.layers[-3].output[:, neuron]])
        loss = 0.5 * (conv_model.layers[-3].output[:, neuron] - 4) ** 2
        grads = K.gradients(loss, conv_model.input)[0]
        grads /= K.maximum(K.std(grads), K.epsilon())
        grad_func = K.function([conv_model.input, K.learning_phase()], [grads])
        act_values = np.zeros(norm_in_data.shape[0])
        for b in range(len(batch_i) - 1):
            act_values[batch_i[b]:batch_i[b + 1]] = act_func([norm_in_data[batch_i[b]:batch_i[b + 1]], 0])[0]
        top_examples[n] = act_values.argsort()[::-1][0:num_ex]
        top_gradients[n] = -grad_func([norm_in_data[top_examples[n]], 0])[0]

    fig, axes = plt.subplots(4, 4, figsize=(16, 16), sharex=True, sharey=True)
    plt.subplots_adjust(0.01, 0.01, 0.95, 0.94, hspace=0, wspace=0)
    for a, ax in enumerate(axes.ravel()):
        ax.pcolormesh(all_in_data[top_examples[a, 0], :, :, 0], vmin=-10, vmax=80, cmap="gist_ncar")
        ax.contour(top_gradients[a, 0, :, :, 0], np.arange(1, 8, 2), cmap="Blues", linewidths=3)

        ax.quiver(all_in_data[top_examples[a, 0], :, :, 1], all_in_data[top_examples[a, 0], :, :, 2])
        ax.text(2, 2, "W: {0:0.2f} N: {1:02d} ".format(weights[top_neurons[a]], top_neurons[a]) + pd.Timestamp(
            all_valid_times[top_examples[a, 0]]).strftime("%Y-%m-%d H%H"), fontsize=14, color="k",
                bbox=dict(boxstyle="square", ec="k", fc="0.8"))
        ax.set_xticks(np.arange(8, 32, 8))
        ax.set_xticklabels(np.arange(8, 32, 8) * 3, fontsize=14)
        ax.set_yticks(np.arange(8, 32, 8))
        ax.set_yticklabels(np.arange(8, 32, 8) * 3, fontsize=14)
    plt.suptitle("Top Neuron Activations", fontsize=16)
    plt.savefig("top_neuron_acts.png", dpi=200, bbox_inches="tight")

    fig, axes = plt.subplots(3, 3, figsize=(16, 16), sharex=True, sharey=True)
    plt.subplots_adjust(0.01, 0.01, 0.95, 0.95, hspace=0, wspace=0)
    pn = 6
    for a, ax in enumerate(axes.ravel()):
        ax.pcolormesh(all_in_data[top_examples[pn, a], :, :, 0], vmin=-10, vmax=80, cmap="gist_ncar")
        ax.contour(top_gradients[pn, a, :, :, 0], np.arange(1, 8, 2), cmap="Blues", linewidths=3)
        ax.quiver(all_in_data[top_examples[pn, a], :, :, 1], all_in_data[top_examples[pn, a], :, :, 2])
        ax.text(2, 2, pd.Timestamp(all_valid_times[top_examples[pn, a]]).strftime("%Y-%m-%d H%H"), fontsize=16,
                bbox=dict(boxstyle="square", ec="k", fc="0.8"))
        ax.set_xticks(np.arange(8, 32, 8))
        ax.set_xticklabels(np.arange(8, 32, 8) * 3, fontsize=14)
        ax.set_yticks(np.arange(8, 32, 8))
        ax.set_yticklabels(np.arange(8, 32, 8) * 3, fontsize=14)
    plt.suptitle("Neuron {0:02d} Top Examples".format(top_neurons[pn]), fontsize=16)
    plt.savefig("neuron_{0:02d}_top_examples.png".format(top_neurons[pn]), dpi=200, bbox_inches="tight") 
Example 69
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_triangulation.py    MIT License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """An electric dipole potential V."""
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    Ex, Ey = tci.gradient(triang.x, triang.y)
    E_norm = np.hypot(Ex, Ey)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 70
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_triangulation.py    MIT License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """An electric dipole potential V."""
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    Ex, Ey = tci.gradient(triang.x, triang.y)
    E_norm = np.hypot(Ex, Ey)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 71
Project: Blackjack-Tracker   Author: martinabeleda   File: test_triangulation.py    MIT License 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex**2 + Ey**2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 72
Project: shesha   Author: ANR-COMPASS   File: tools.py    GNU General Public License v3.0 4 votes vote down vote up
def plsh(slopesvector, nssp, validint, sparta=False, invertxy=False, returnquiver=False):
    """
    <slopesvector> is the input vector of slopes
    <nssp> is the number of subapertures in the diameter of the pupil
    <validint> is the normalized diameter of central obscuration (between 0 and 1.00)
    <sparta> when==1, slopes are ordered xyxyxyxy...
             when==0, slopes are xxxxxxyyyyyyy
    <xy> when==1, swap x and y. Does nothing special when xy==0.

    The routine plots a field vector of subaperture gradients defined in
    vector <slopesvector>.
    The routine automatically adjusts/finds what are the valid subapertures
    for plotting, depending on the number of elements in <slopesvector>. Only the
    devalidated subapertures inside the central obscuration cannot be
    known, that’s why <validint> has to be passed in the argument list.

    """
    nsub = slopesvector.shape[0] // 2
    x = np.linspace(-1, 1, nssp)
    x, y = np.meshgrid(x, x)
    r = np.sqrt(x * x + y * y)
    # defines outer and inner radiuses that will decide of validity of subapertures
    # inner radius <validint> is passed as an argument.
    # outer one will be computed so that it will match the number of
    # subapertures in slopesvector
    rorder = np.sort(r.reshape(nssp * nssp))
    # number of subapertures not valid due to central obscuration
    ncentral = nssp * nssp - np.sum(r >= validint, dtype=np.int32)
    # determine value of external radius so that the test (validint < r < validext)
    # leads to the correct number of subapertures
    validext = rorder[ncentral + nsub]
    # get the indexes of valid subapertures in the nsspxnssp map
    valid = (r < validext) & (r >= validint)
    ivalid = np.where(valid)
    # feeding data <slopesvector> into <vv>
    vx = np.zeros([nssp, nssp])
    vy = np.zeros([nssp, nssp])
    if (sparta is False):
        # Canary, compass, etc..  slopes ordered xxxxxxxyyyyyyy
        vy[ivalid] = slopesvector[0:nsub]
        vx[ivalid] = slopesvector[nsub:]
    else:
        # SPARTA case, slopes ordered xyxyxyxyxyxy...
        vx[ivalid] = slopesvector[0::2]
        vy[ivalid] = slopesvector[1::2]
    if (invertxy is True):
        # swaps X and Y
        tmp = vx
        vx = vy
        vy = tmp
    if (returnquiver):
        return x, y, vx, vy
    else:
        plt.quiver(x, y, vx, vy, pivot='mid') 
Example 73
Project: PYPIC   Author: max614   File: plotting.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def plot_particle_positions_h5(t):

    fig = plt.figure()
    #ax = Axes3D(fig)
    #ax.set_xlim3d(0, 128)
    #ax.set_ylim3d(0, 196)
    #ax.set_zlim3d(0, 196)
    #ax.set_xlabel('X axis')
    #ax.set_ylabel('Y axis')
    #ax.set_zlabel('Z axis')
    colors = itertools.cycle(["r", "b", "g"])

    for rank in range(16):
        #try:
        filename = "TrackedParticles/rank" + str(rank) + ".h5"
        hf = h5py.File(filename, 'r')
        #print(hf.keys())
        #return
        collection = hf.get(str(t))
        data = np.array(collection)

        #print(data)
        id_list = data[:,0]

        x = data[:, 2]
        y = data[:, 3]
        z = data[:, 4]

        xf = np.floor(x)
        yf = np.floor(y)
        zf = np.floor(z)



        vx = data[:, 5]
        vy = data[:, 6]
        vz = data[:, 7]
        col = next(colors)
        plt.quiver(xf, yf, vx, vy, units='width')
        #ax.plot(x, y, z, '.', color=col)

        #ax.view_init(30, t)
        plt.savefig("TrackedParticles/hdf5_ " + str(t) + ".png")
    plt.close() 
Example 74
Project: PyStrain   Author: mompiou   File: pyStrain.py    GNU General Public License v2.0 4 votes vote down vote up
def piv():
    global a,b,D,g,arrows
    a=np.rot90(a,k=1)
    b=np.rot90(b,k=1)
    #print(a.shape,b.shape)
    ov=np.int(a.shape[0]-2)
    ws=np.int(a.shape[0]-1) #taille de la zone de recherche dans la premiere image
    sas=np.int(b.shape[0]-1) #taille de la zone de recherche dans la seconde image
    #img=mpimg.imread('Be1-7b (Channel 1) 010 - 00006.tif')
    
    u, v, sig2noise = openpiv.process.extended_search_area_piv( a.astype(np.int32), b.astype(np.int32), window_size=ws, overlap=ov, dt=1, search_area_size=sas, sig2noise_method='peak2peak' )
    
    
    x, y = openpiv.process.get_coordinates( image_size=a.shape, window_size=ws, overlap=ov )
    
    u, v, mask = openpiv.validation.sig2noise_val( u, v, sig2noise, threshold =0 )
    
    #u, v = openpiv.filters.replace_outliers( u, v, method='localmean', max_iter=10, kernel_size=2)
    #print(u,v)
    #plt.quiver( x, y, u, v, color='blue' )
    #plt.quiver( x, y, u, v )
    #plt.show()   
     
    D=np.vstack((D,np.array([u[0,0],v[0,0],g[0],g[1]])))
    print(D)
    text2.setText('u,v (px):'+str(np.around((u[0,0]), decimals=2))+','+str(np.around(v[0,0],decimals=2)))
    umean=u[0,0]
    vmean=v[0,0]
    print(umean,vmean)
    arrow=pg.ArrowItem(headlen=5, tailLen=umean, angle=180+np.arctan(-vmean/umean)*180/np.pi)
    
    arrow.setPos(g[0]+a.shape[0]/2, g[1]+a.shape[1]/2)
    arrows.append(arrow)
    v1.addItem(arrow)
    epsx()
#    Dx=x[0,1]-x[0,0]
#    Dy=y[0,0]-y[1,0]
#    print(Dx,Dy)
#    X=x[0,:]
#    Y=y[:,0]
#    U=u[0,:]
    
    #dU=np.diff(u)/(a.shape[1])
    #dV=np.diff(v, axis=0)/(frame_a.shape[1])
    
    #eps=np.sum(dU)/dU.shape[0]
    #print(eps,dU.shape[0])    
    return u,v 
Example 75
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_triangulation.py    GNU General Public License v3.0 4 votes vote down vote up
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """An electric dipole potential V."""
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta)/r_sq
        return (np.max(z)-z) / (np.max(z)-np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi/n_angles
    x = (radii*np.cos(angles)).flatten()
    y = (radii*np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                             y[triang.triangles].mean(axis=1))
                    < min_radius)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    Ex, Ey = tci.gradient(triang.x, triang.y)
    E_norm = np.hypot(Ex, Ey)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
               units='xy', scale=10., zorder=3, color='blue',
               width=0.007, headwidth=3., headlength=4.)
    # We are leaving ax.use_sticky_margins as True, so the
    # view limits are the contour data limits. 
Example 76
Project: differentiable-particle-filters   Author: tu-rbo   File: plot_models.py    MIT License 4 votes vote down vote up
def plot_measurement_model(session, method, statistics, batch, task, num_examples, variant):

    batch_size = len(batch['o'])

    x = np.linspace(100.0 / 4, 1000.0 - 100.0 / 4, 20)
    y = np.linspace(100.0 / 4, 500.0 - 100.0 / 4, 10)
    theta = np.linspace(-np.pi, np.pi, 12 + 1)[1:]
    g = np.meshgrid(x, y, theta)

    poses = np.vstack([np.ravel(x) for x in g]).transpose([1, 0])
    test_poses = tf.tile(tf.constant(poses, dtype='float32')[None, :, :], [batch_size, 1, 1])
    measurement_model_out = method.measurement_update(method.encodings[0, :], test_poses, statistics['means'],
                                                      statistics['stds'])

    # define the inputs and train/run the model
    input_dict = {**{method.placeholders[key]: batch[key] for key in 'osa'},
                  }

    obs_likelihood = session.run(measurement_model_out, input_dict)
    print(obs_likelihood.shape)

    for i in range(num_examples):
        # plt.figure("%s likelihood" % i)
        fig, (ax, cax) = plt.subplots(1, 2, figsize=(2.4 / 0.83 / 0.95 / 0.97, 1.29 / 0.9),
                                      gridspec_kw={"width_ratios": [0.97, 0.03]}, num="%s %s likelihood" % (variant, i))
        # plt.gca().clear()
        plot_maze(task, margin=5, linewidth=0.5, ax=ax)

        idx = obs_likelihood[i,:] > 1*np.mean(obs_likelihood[i,:])
        # idx = obs_likelihood[i, :] > 0 * np.mean(obs_likelihood[i, :])
        max = np.max(obs_likelihood[i, :])

        # ax.scatter([poses[:, 0]], [poses[:, 1]], s=[0.001], c=[(0.8, 0.8, 0.8)], marker='.')

        quiv = ax.quiver(poses[idx, 0] + 0 * np.cos(poses[idx, 2]), poses[idx, 1] + 0* np.sin(poses[idx, 2]), np.cos(poses[idx, 2]),
                         np.sin(poses[idx, 2]), obs_likelihood[i, idx],
                         cmap='viridis_r',
                         clim=[0.0, max],
                         **quiv_kwargs
                         )

        ax.plot([batch['s'][0, i, 0]], [batch['s'][0, i, 1]], 'or', **marker_kwargs)

        ax.quiver([batch['s'][0, i, 0]], [batch['s'][0, i, 1]], np.cos([batch['s'][0, i, 2]]),
                  np.sin([batch['s'][0, i, 2]]), color='red',
                  **quiv_kwargs
                  )
        ax.axis('off')
        fig.colorbar(quiv, cax=cax, orientation="vertical", label='Obs. likelihood', ticks=[0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
        plt.subplots_adjust(left=0.0, bottom=0.05, right=0.83, top=0.95, wspace=0.05, hspace=0.00)
        plt.savefig('../plots/models/measurement_model{}.pdf'.format(i), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01) 
Example 77
Project: differentiable-particle-filters   Author: tu-rbo   File: plot_models.py    MIT License 4 votes vote down vote up
def plot_particle_filter(session, method, statistics, batch, task, num_examples, num_particles, variant):
    color_list = plt.cm.tab10(np.linspace(0, 1, 10))
    colors = {'lstm': color_list[0], 'pf_e2e': color_list[1], 'pf_ind_e2e': color_list[2], 'pf_ind': color_list[3],
              'ff': color_list[4], 'odom': color_list[4]}

    pred, s_particle_list, s_particle_probs_list = method.predict(session, batch, num_particles, return_particles=True)

    num_steps = 20 # s_particle_list.shape[1]

    for s in range(num_examples):

        plt.figure("example {}, vartiant: {}".format(s, variant), figsize=[12, 5.15])
        plt.gca().clear()

        for i in range(num_steps):
            ax = plt.subplot(4, 5, i + 1, frameon=False)
            plt.gca().clear()

            plot_maze(task, margin=5, linewidth=0.5)

            if i < num_steps - 1:
                ax.quiver(s_particle_list[s, i, :, 0], s_particle_list[s, i, :, 1],
                           np.cos(s_particle_list[s, i, :, 2]), np.sin(s_particle_list[s, i, :, 2]),
                           s_particle_probs_list[s, i, :], cmap='viridis_r', clim=[.0, 2.0/num_particles], alpha=1.0,
                          **quiv_kwargs
                          )

                current_state = batch['s'][s, i, :]
                plt.quiver(current_state[0], current_state[1], np.cos(current_state[2]),
                           np.sin(current_state[2]), color="red", **quiv_kwargs)

                plt.plot(current_state[0], current_state[1], 'or', **marker_kwargs)
            else:

                ax.plot(batch['s'][s, :num_steps, 0], batch['s'][s, :num_steps, 1], '-', linewidth=0.6, color='red')
                ax.plot(pred[s, :num_steps, 0], pred[s, :num_steps, 1], '-', linewidth=0.6,
                        color=colors['pf_ind_e2e'])

                ax.plot(batch['s'][s, :1, 0], batch['s'][s, :1, 1], '.', linewidth=0.6, color='red', markersize=3)
                ax.plot(pred[s, :1, 0], pred[s, :1, 1], '.', linewidth=0.6, markersize=3,
                        color=colors['pf_ind_e2e'])


            plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.001, hspace=0.1)
            plt.gca().set_aspect('equal')
            plt.xticks([])
            plt.yticks([])

        plt.savefig('../plots/models/pf{}.pdf'.format(s), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01)

        plt.figure('colorbar', (12, 0.6))
        a = np.array([[0, 2.0/num_particles]])
        img = plt.imshow(a, cmap="viridis_r")
        plt.gca().set_visible(False)
        cax = plt.axes([0.25, 0.75, 0.50, 0.2])
        plt.colorbar(orientation="horizontal", cax=cax, label='Particle weight', ticks=[0, 0.001, 0.002])

        plt.savefig('../plots/models/colorbar.pdf'.format(s), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01) 
Example 78
Project: differentiable-particle-filters   Author: tu-rbo   File: plot_models.py    MIT License 4 votes vote down vote up
def plot_prediction(pred1, pred2, statistics, batch, task, num_examples, variant):
    color_list = plt.cm.tab10(np.linspace(0, 1, 10))
    colors = {'lstm': color_list[0], 'pf_e2e': color_list[1], 'pf_ind_e2e': color_list[2], 'pf_ind': color_list[3],
                'ff': color_list[4], 'odom': color_list[4]}

    num_steps = 50
    init_steps = 20

    for s in range(num_examples):

        fig = plt.figure(figsize=(2.4, 1.29), num="%s prediction %s" % (variant, s))

        # plt.figure("example {}, vartiant: {}".format(s, variant), figsize=[12, 5.15])
        plt.gca().clear()
        plot_maze(task, margin=5, linewidth=0.5)

        plt.plot(batch['s'][s, :num_steps, 0], batch['s'][s, :num_steps, 1], '-', linewidth=0.3, color='gray')
        plt.plot(pred1[s, :init_steps, 0], pred1[s, :init_steps, 1], '--', linewidth=0.3, color=colors['pf_ind_e2e'])
        plt.plot(pred1[s, init_steps-1:num_steps, 0], pred1[s, init_steps-1:num_steps, 1], '-', linewidth=0.3, color=colors['pf_ind_e2e'])
        plt.plot(pred2[s, :init_steps, 0], pred2[s, :init_steps, 1], '--', linewidth=0.3, color=colors['lstm'])
        plt.plot(pred2[s, init_steps-1:num_steps, 0], pred2[s, init_steps-1:num_steps, 1], '-', color=colors['lstm'], linewidth=0.3)

        # for i in range(init_steps, num_steps):
        #
        #     p = pred1[s, i, :]
        #     plt.quiver(p[0], p[1], np.cos(p[2]),
        #                np.sin(p[2]), color=colors['pf_ind_e2e'], **quiv_kwargs)
        #     p = pred2[s, i, :]
        #     plt.quiver(p[0], p[1], np.cos(p[2]),
        #                np.sin(p[2]), color=colors['lstm'], **quiv_kwargs)
        #     # plt.plot(p[0], p[1], 'og', **marker_kwargs)
        #
        #     current_state = batch['s'][s, i, :]
        #     plt.quiver(current_state[0], current_state[1], np.cos(current_state[2]),
        #                np.sin(current_state[2]), color="black", **quiv_kwargs)
        #     # plt.plot(current_state[0], current_state[1], 'or', **marker_kwargs)

        plt.gca().set_aspect('equal')
        plt.xticks([])
        plt.yticks([])
        plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.001, hspace=0.1)
        plt.savefig('../plots/models/pred{}.pdf'.format(s), transparent=True, dpi=600, frameon=False, facecolor='w', pad_inches=0.01) 
Example 79
Project: differentiable-particle-filters   Author: tu-rbo   File: dpf.py    MIT License 4 votes vote down vote up
def plot_particle_filter(self, sess, batch, particle_list,
                        particle_probs_list, num_particles, state_step_sizes, task):

        num_particles = 1000
        head_scale = 1.5
        quiv_kwargs = {'scale_units': 'xy', 'scale': 1. / 40., 'width': 0.003, 'headlength': 5 * head_scale,
                       'headwidth': 3 * head_scale, 'headaxislength': 4.5 * head_scale}
        marker_kwargs = {'markersize': 4.5, 'markerfacecolor': 'None', 'markeredgewidth': 0.5}

        color_list = plt.cm.tab10(np.linspace(0, 1, 10))
        colors = {'lstm': color_list[0], 'pf_e2e': color_list[1], 'pf_ind_e2e': color_list[2], 'pf_ind': color_list[3],
                  'ff': color_list[4], 'odom': color_list[4]}

        pred, s_particle_list, s_particle_probs_list = self.predict(sess, batch, num_particles,
                                                                      return_particles=True)

        num_steps = 20  # s_particle_list.shape[1]

        for s in range(1):

            plt.figure("example {}".format(s), figsize=[12, 5.15])
            plt.gca().clear()

            for i in range(num_steps):
                ax = plt.subplot(4, 5, i + 1, frameon=False)
                plt.gca().clear()

                plot_maze(task, margin=5, linewidth=0.5)

                if i < num_steps - 1:
                    ax.quiver(s_particle_list[s, i, :, 0], s_particle_list[s, i, :, 1],
                              np.cos(s_particle_list[s, i, :, 2]), np.sin(s_particle_list[s, i, :, 2]),
                              s_particle_probs_list[s, i, :], cmap='viridis_r', clim=[.0, 2.0 / num_particles],
                              alpha=1.0,
                              **quiv_kwargs
                              )

                    current_state = batch['s'][s, i, :]
                    plt.quiver(current_state[0], current_state[1], np.cos(current_state[2]),
                               np.sin(current_state[2]), color="red", **quiv_kwargs)

                    plt.plot(current_state[0], current_state[1], 'or', **marker_kwargs)
                else:

                    ax.plot(batch['s'][s, :num_steps, 0], batch['s'][s, :num_steps, 1], '-', linewidth=0.6, color='red')
                    ax.plot(pred[s, :num_steps, 0], pred[s, :num_steps, 1], '-', linewidth=0.6,
                            color=colors['pf_ind_e2e'])

                    ax.plot(batch['s'][s, :1, 0], batch['s'][s, :1, 1], '.', linewidth=0.6, color='red', markersize=3)
                    ax.plot(pred[s, :1, 0], pred[s, :1, 1], '.', linewidth=0.6, markersize=3,
                            color=colors['pf_ind_e2e'])

                plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.001, hspace=0.1)
                plt.gca().set_aspect('equal')
                plt.xticks([])
                plt.yticks([])

        show_pause(pause=0.01)