Python matplotlib.pyplot.quiver() Examples

The following are 30 code examples of matplotlib.pyplot.quiver(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: fitzhugh_nagumo.py    From neuronaldynamics-exercises with GNU General Public License v2.0 6 votes vote down vote up
def plot_flow(I=0., eps=0.1, a=2.0):
    """Plots the phase plane of the Fitzhugh-Nagumo model
    for given model parameters.

    Args:
        I: Constant input [mV]
        eps: Inverse time constant of the recovery variable w [1/ms]
        a: Offset of the w-nullcline [mV]
    """

    # define the interval spanned by voltage v and recovery variable w
    # to produce the phase plane
    vv = np.arange(-2.5, 2.5, 0.2)
    ww = np.arange(-2.5, 5.5, 0.2)
    (VV, WW) = np.meshgrid(vv, ww)

    # Compute derivative of v and w according to FHN equations
    # and velocity as vector norm
    dV = VV * (1. - (VV**2)) - WW + I
    dW = eps * (VV + 0.5 * (a - WW))
    vel = np.sqrt(dV**2 + dW**2)

    # Use quiver function to plot the phase plane
    plt.quiver(VV, WW, dV, dW, vel) 
Example #2
Source File: plot.py    From neuron with GNU General Public License v3.0 6 votes vote down vote up
def flow_legend():
    """
    show quiver plot to indicate how arrows are colored in the flow() method.
    https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot
    """
    ph = np.linspace(0, 2*np.pi, 13)
    x = np.cos(ph)
    y = np.sin(ph)
    u = np.cos(ph)
    v = np.sin(ph)
    colors = np.arctan2(u, v)

    norm = Normalize()
    norm.autoscale(colors)
    # we need to normalize our colors array to match it colormap domain
    # which is [0, 1]

    colormap = cm.winter

    plt.figure(figsize=(6, 6))
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.quiver(x, y, u, v, color=colormap(norm(colors)),  angles='xy', scale_units='xy', scale=1)
    plt.show() 
Example #3
Source File: base_backend.py    From delira with GNU Affero General Public License v3.0 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 #4
Source File: plotting_utils.py    From differentiable-particle-filters with 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 #5
Source File: dpf.py    From differentiable-particle-filters with 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 #6
Source File: dpf.py    From differentiable-particle-filters with 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 #7
Source File: plot.py    From voxelmorph with GNU General Public License v3.0 6 votes vote down vote up
def flow_legend():
    """
    show quiver plot to indicate how arrows are colored in the flow() method.
    https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot
    """
    ph = np.linspace(0, 2*np.pi, 13)
    x = np.cos(ph)
    y = np.sin(ph)
    u = np.cos(ph)
    v = np.sin(ph)
    colors = np.arctan2(u, v)

    norm = Normalize()
    norm.autoscale(colors)
    # we need to normalize our colors array to match it colormap domain
    # which is [0, 1]

    colormap = cm.winter

    plt.figure(figsize=(6, 6))
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.quiver(x, y, u, v, color=colormap(norm(colors)),  angles='xy', scale_units='xy', scale=1)
    plt.show() 
Example #8
Source File: test_alpha_shape.py    From spimagine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_2d():
    import matplotlib.pyplot as plt

    plt.ion()
    np.random.seed(0)

    N = 500
    phi = np.random.uniform(0, 2*np.pi, N)

    points = np.stack([np.cos(phi), np.sin(phi)*np.cos(phi)]).T
    #points += .1*np.random.uniform(-1, 1, (N, 2))
    #points = np.concatenate([points,.9*points])

    points, normals, indices = alpha_shape(points, .1)


    plt.clf()



    _x = points[indices].reshape(len(indices)*2,2)
    _n = normals[indices].reshape(len(indices)*2,2)


    plt.quiver(_x[:,0],_x[:,1],_n[:,0],_n[:,1], color = (.5,)*3)
    plt.plot(points[:,0],points[:,1],".")
    for edge in indices:
        plt.plot(points[edge, 0], points[edge, 1], "k", lw=2)

    plt.axis("equal")
    plt.pause(0.1)
    plt.close()

    return points, normals, indices 
Example #9
Source File: tests.py    From sea_ice_drift with 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 #10
Source File: test_basis.py    From OpenModes with GNU General Public License v3.0 5 votes vote down vote up
def test_interpolate_rwg(plot=False, write_reference=False, skip_asserts=False):
    "Interpolate an RWG basis function over a triangle"

    sim = Simulation()
    srr = sim.load_mesh(osp.join(mesh_dir, 'SRR.msh'))

    basis = DivRwgBasis(srr)

    rwg_function = np.zeros(len(basis), np.float64)
    rwg_function[20] = 1

    rule = DunavantRule(10)

    r, basis_func = basis.interpolate_function(rwg_function, rule)

    if write_reference:
        # save reference data
        write_2d_real(osp.join(reference_dir, 'rwg_r.txt'), r)
        write_2d_real(osp.join(reference_dir, 'rwg_basis_func.txt'),
                      basis_func)

    r_ref = read_2d_real(osp.join(reference_dir, 'rwg_r.txt'))
    basis_func_ref = read_2d_real(osp.join(reference_dir,
                                           'rwg_basis_func.txt'))

    if not skip_asserts:
        assert_allclose(r, r_ref, rtol=1e-6)
        assert_allclose(basis_func, basis_func_ref, rtol=1e-6)

    if plot:
        plt.figure(figsize=(6, 6))
        plt.quiver(r[:, 0], r[:, 1], basis_func[:, 0], basis_func[:, 1],
                   scale=5e4)
        plt.show() 
Example #11
Source File: test_collections.py    From ImageFusion with 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 #12
Source File: vectorfields.py    From VectorFields with 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 #13
Source File: plot_models.py    From differentiable-particle-filters with 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 #14
Source File: plot_models.py    From differentiable-particle-filters with 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 #15
Source File: plotting_utils.py    From differentiable-particle-filters with 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 #16
Source File: gd_algorithms_visualization.py    From neupy with MIT License 5 votes vote down vote up
def weight_quiver(weights, color='c'):
    plt.quiver(weights[0, :-1],
               weights[1, :-1],
               weights[0, 1:] - weights[0, :-1],
               weights[1, 1:] - weights[1, :-1],
               scale_units='xy', angles='xy', scale=1,
               color=color) 
Example #17
Source File: gd_algorithms_visualization.py    From neupy with MIT License 5 votes vote down vote up
def draw_quiver(network_class, name, color='r'):
    """
    Train algorithm and draw quiver for every epoch update
    for this algorithm.
    """
    global weights
    global current_epoch

    bpn = network_class(create_network(), signals=save_epoch_weight)

    # We don't know in advance number of epochs that network
    # need to reach the goal. For this reason we use 1000 as
    # an upper limit for all network epochs, later we
    # need to fix
    weights = np.zeros((2, 1000))
    weights[:, 0:1] = default_weight.copy()

    current_epoch = 0
    while bpn.score(X_train, y_train) > 0.125:
        bpn.train(X_train, y_train, epochs=1)
        current_epoch += 1

    weights = weights[:, :current_epoch + 1]
    weight_quiver(weights, color=color)

    label = "{name} ({n} steps)".format(name=name, n=current_epoch)
    return mpatches.Patch(color=color, label=label) 
Example #18
Source File: test_collections.py    From coffeegrindsize with 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 #19
Source File: _visualization_2d.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _plot_orientations(self, x, y, Gx, Gy, series_to_plot_f, min_axis, extent, p, aspect=None, ax=None):
        if series_to_plot_f.shape[0] != 0:
            # print('hello')
            if p is False:
                # size = fig.get_size_inches() * fig.dpi
                # print('before plot orient', size)
                surflist = list(series_to_plot_f['surface'].unique())
                for surface in surflist:
                    to_plot = series_to_plot_f[series_to_plot_f['surface'] == surface]
                    plt.quiver(to_plot[x], to_plot[y],
                               to_plot[Gx], to_plot[Gy],
                               pivot="tail", scale_units=min_axis, scale=30, color=self._color_lot[surface],
                               edgecolor='k', headwidth=8, linewidths=1)
                    # ax.Axes.set_ylim([extent[2], extent[3]])
                    # ax.Axes.set_xlim([extent[0], extent[1]])
                # fig = plt.gcf()
                # fig.set_size_inches(20,10)
                # if aspect is not None:
                # ax = plt.gca()
                # ax.set_aspect(aspect)

            else:
                p = sns.FacetGrid(series_to_plot_f, hue="surface",
                                  palette=self._color_lot,
                                  ylim=[extent[2], extent[3]],
                                  xlim=[extent[0], extent[1]],
                                  legend_out=False,
                                  aspect=aspect,
                                  height=6)
                p.map(plt.quiver, x, y, Gx, Gy, pivot="tail", scale_units=min_axis, scale=10, edgecolor='k',
                      headwidth=4, linewidths=1)
        else:
            # print('no orient')
            pass

        # size = fig.get_size_inches() * fig.dpi
        # print('after plot_orientations', size) 
Example #20
Source File: test_collections.py    From twitter-stock-recommendation with 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 #21
Source File: plt_results2D.py    From snn4hrl with MIT License 5 votes vote down vote up
def plot_policy_learned(data_unpickle, color, fig_dir=None):
    # recover the policy
    poli = data_unpickle['policy']
    # range to plot it
    X = np.arange(-2, 2, 0.5)
    Y = np.arange(-2, 2, 0.5)
    X, Y = np.meshgrid(X, Y)
    X_flat = X.reshape((-1, 1))
    Y_flat = Y.reshape((-1, 1))
    XY = np.concatenate((X_flat, Y_flat), axis=1)
    means_1 = np.zeros((np.size(X_flat), 1))
    means_2 = np.zeros((np.size(Y_flat), 1))
    logstd = np.zeros((np.size(X_flat), 2))
    for i, xy in enumerate(XY):
        means_1[i], means_2[i] = poli.get_action(xy)[1]['mean']
        logstd[i] = poli.get_action(xy)[1]['log_std']
    means_1 = means_1.reshape(np.shape(X))
    means_2 = means_2.reshape(np.shape(Y))
    means_norm = np.sqrt(means_1 ** 2 + means_2 ** 2)
    plt.quiver(X, Y, means_1, means_2, scale=1, scale_units='x')

    plt.title('Final policy')
    # plt.show()
    if fig_dir:
        plt.savefig(os.path.join(fig_dir, 'policy_learned'))
    else:
        print("No directory for saving plots")


## estimate by MC the policy at 0! 
Example #22
Source File: deformer.py    From theanet with Apache License 2.0 5 votes vote down vote up
def test_one(img_name, img, scale, sigma, cval=255):
        img2, trans = transform(img, scale, sigma, ret_trans=True, cval=cval)
        tx, ty = trans

        print 'image : ', img_name, ' scale: ', scale, ' sigma: ', sigma
        print 'Scale', scale, 'sigma', sigma
        print "({:.2f}, {:.2f}) ({:.2f}, {:.2f}) ".format(
            tx.min(), tx.max(), ty.min(), ty.max())
        im.fromarray(np.vstack((img, img2))).save(img_name)

        plt.quiver(tx, ty)
        plt.imshow(np.hstack((img, img2))) 
Example #23
Source File: gd_poisoners.py    From manip-ml with MIT License 5 votes vote down vote up
def plot_grad(self,clf,lam,eq7lhs,mu,min_x=0,max_x=1,resolution=0.1):
        """
        plot_grad plots vector field for gradients of the objective function

        clf, lam, eq7lhs, mu: values needed for gradient computation
        min_x: smallest value of x desired in the vector field
        max_x: largest value of x desired in the vector field
        resolution: spacing between arrows
        """

        xx1,xx2 = np.meshgrid(
                        np.arange(min_x, max_x + resolution, resolution),
                        np.arange(min_x, max_x + resolution, resolution))

        grid_x = np.array([xx1.ravel(), xx2.ravel()]).T
        z = np.zeros(shape=(grid_x.shape[0],2))

        for i in range(grid_x.shape[0]):
            clf,lam = self.learn_model(
                            np.concatenate((self.trnx, 
                                            grid_x[i,0].reshape((1,1))),
                                            axis=0),
                            self.trny+[x[i,1]], None)
            z[i,0], z[i,1] = self.comp_grad_dummy(eq7lhs, mu, clf, lam, \
                                                  x[i,0].reshape((1,1)), x[i,1])

        U = z[:,0]
        V = z[:,1]
        plt.quiver(xx1, xx2, U, V) 
Example #24
Source File: tests.py    From sea_ice_drift with 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 #25
Source File: tests.py    From sea_ice_drift with 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 #26
Source File: starwarps.py    From eht-imaging with GNU General Public License v3.0 5 votes vote down vote up
def plot_Flow(Im, theta, init_x, init_y, flowbasis_x, flowbasis_y, initTheta, step=4, ipynb=False):
    
    # Get vectors and ratio from current image
    x = np.array([[i for i in range(Im.xdim)] for j in range(Im.ydim)])
    y = np.array([[j for i in range(Im.xdim)] for j in range(Im.ydim)])
    
    flow_x_new, flow_y_new = applyMotionBasis(init_x, init_y, flowbasis_x, flowbasis_y, theta)
    flow_x_orig, flow_y_orig = applyMotionBasis(init_x, init_y, flowbasis_x, flowbasis_y, initTheta)
    
    vx = -(flow_x_new - flow_x_orig)
    vy = -(flow_y_new - flow_y_orig)

    # Create figure and title
    plt.ion()
    plt.clf()

    # Stokes I plot
    plt.subplot(111)
    plt.imshow(Im.imvec.reshape(Im.ydim, Im.xdim), cmap=plt.get_cmap('afmhot'), interpolation='gaussian')
    plt.quiver(x[::step,::step], y[::step,::step], vx[::step,::step], vy[::step,::step],
               headaxislength=3, headwidth=7, headlength=5, minlength=0, minshaft=1,
               width=.005*Im.xdim/30., pivot='mid', color='w', angles='xy')

    xticks = ticks(Im.xdim, Im.psize/ehtim.RADPERAS/1e-6)
    yticks = ticks(Im.ydim, Im.psize/ehtim.RADPERAS/1e-6)
    plt.xticks(xticks[0], xticks[1])
    plt.yticks(yticks[0], yticks[1])
    plt.xlabel('Relative RA ($\mu$as)')
    plt.ylabel('Relative Dec ($\mu$as)')
    plt.title('Flow Map')
    #plt.ylim(plt.ylim()[::-1])
    # Display
    plt.draw() 
Example #27
Source File: v_tgt_field.py    From osim-rl with 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 #28
Source File: visualization.py    From vivarium with GNU General Public License v3.0 5 votes vote down vote up
def plot_birds(simulation, plot_velocity=False):
    width = simulation.configuration.location.width
    height = simulation.configuration.location.height
    pop = simulation.get_population()

    plt.figure(figsize=[12, 12])
    plt.scatter(pop.x, pop.y, color=pop.color)
    if plot_velocity:
        plt.quiver(pop.x, pop.y, pop.vx, pop.vy, color=pop.color, width=0.002)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.axis([0, width, 0, height])
    plt.show() 
Example #29
Source File: parametric.py    From AeroPy with MIT License 5 votes vote down vote up
def plot(self, basis=False, r = None, label=None, linestyle = '-', color = None, scatter = False):
        if r is None:
            r = self.r(self.x1_grid)

        if color is None:
            color = self.color

        if scatter:
            if label is None:
                plt.scatter(r[:,0], r[:,2], c = color)
            else:
                plt.scatter(r[:,0], r[:,2], c = color, label=label, zorder = 2, edgecolors='k')
        else:
            if label is None:
                plt.plot(r[:,0], r[:,2], color, linestyle = linestyle, lw = 4)
            else:
                plt.plot(r[:,0], r[:,2], color, linestyle = linestyle, lw = 4,
                         label=label, zorder = 1)
        if basis:
            plt.quiver(r[:,0], r[:,2],
                       self.a[0,:,0], self.a[0,:,2],
                       angles='xy', color = color, scale_units='xy')
            plt.quiver(r[:,0], r[:,2],
                       self.a[2,:,0], self.a[2,:,2],
                       angles='xy', color = color, scale_units='xy')
        plt.xlabel('x (m)')
        plt.ylabel('y (m)') 
Example #30
Source File: test_collections.py    From neural-network-animation with 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))