Exemplo n.º 1
0
    def listener_callback(self, msg):
        # create numpy array
        occdata = np.array(msg.data)
        # compute histogram to identify bins with -1, values between 0 and below 50, 
        # and values between 50 and 100. The binned_statistic function will also
        # return the bin numbers so we can use that easily to create the image 
        occ_counts, edges, binnum = scipy.stats.binned_statistic(occdata, np.nan, statistic='count', bins=occ_bins)
        # get width and height of map
        iwidth = msg.info.width
        iheight = msg.info.height
        # calculate total number of bins
        total_bins = iwidth * iheight
        # log the info
        # self.get_logger().info('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i' % (occ_counts[0], occ_counts[1], occ_counts[2], total_bins))

        # binnum go from 1 to 3 so we can use uint8
        # convert into 2D array using column order
        odata = np.uint8(binnum.reshape(msg.info.height,msg.info.width))
        # create image from 2D array using PIL
        img = Image.fromarray(odata)
        # show the image using grayscale map
        plt.imshow(img, cmap='gray', origin='lower')
        plt.draw_all()
        # pause to make sure the plot gets created
        plt.pause(0.00000000001)
    def animate_plot(self):
        '''Animation of the plots and shows'''
        #----------- Set figure -----------
        fig = plt.figure(figsize=(12, 4.5), dpi=80)
        ax1 = fig.add_subplot(1,2,1)
        ax2 = fig.add_subplot(1,2,2)


        for i in range(0, len(t), frame_step):

            self.x0 = A * np.cos(omega * t[i])
            ax1.plot([self.x0, self.x0 + self.x[i]], [0, self.y[i]])
            self.circle1 = Circle((self.x0, 0), r/2, fc='b', zorder=10)
            self.circle2 = Circle((self.x0 + self.x[i], self.y[i]), r, fc='orange', zorder=10)
            ax1.add_patch(self.circle1)
            ax1.add_patch(self.circle2)
            ax1.set_xlim(-np.max(L)-A, np.max(L)+A)
            ax1.set_ylim(-np.max(L)-A, np.max(L)+A)
            ax1.set_aspect('equal', adjustable='box')

            ax2.scatter(t[i], self.theta[i], lw=0.1, c='orange')
            ax2.set_xlabel(r'$t\;/\mathrm{s}$')
            ax2.set_ylabel(r'$\theta$')
            ax2.set_xlim(0, max(t))
            ax2.set_ylim(min(self.theta) - 0.1, max(self.theta) + 0.1)
            plt.pause(0.01)
            plt.draw_all()
            ax1.clear()  

        return self.x0, self.circle1, self.circle2
Exemplo n.º 3
0
def display_depth_plot():
    keep_running = True

    def handler(signum, frame):
        """Sets up the kill handler, catches SIGINT"""
        global keep_running
        print("SIGINT!!!")
        keep_running = False

    # Register signal interrupt handler
    signal.signal(signal.SIGINT, handler)

    pplot.ion()
    pplot.gray()
    pplot.figure(1)
    image_depth = pplot.imshow(kinect_proxy.get_depth(),
                               interpolation='nearest',
                               animated=True)
    print('Press Ctrl-C in terminal to stop')

    while keep_running:
        pplot.figure(1)
        image_depth.set_data(kinect_proxy.get_depth())
        pplot.draw_all()
        pplot.waitforbuttonpress(0.1)
    def generate_plot(self):
        '''Animation of the plots and shows'''
        #----------- Set figure -----------
        fig = plt.figure(figsize=(12, 4.5), dpi=80)
        ax1 = fig.add_subplot(1,2,1)
        ax2 = fig.add_subplot(1,2,2)


        for i in range(0, len(t), frame_step):

            ax1.plot([self.x1[i], self.x2[i]], [self.y1[i], self.y2[i]])
            self.circle1 = Circle((self.x1[i], self.y1[i]), r/2, fc='b', zorder=10)
            self.circle2 = Circle((self.x2[i], self.y2[i]), r, fc='orange', zorder=10)
            ax1.add_patch(self.circle1)
            ax1.add_patch(self.circle2)
            ax1.set_xlim(-2, 2)
            ax1.set_ylim(-2, 2)
            ax1.set_aspect('equal', adjustable='box')


            x1_ring = -R * np.sin(t)
            x2_ring = -R * np.cos(t)
            ax1.plot(x1_ring, x2_ring, color='black', linewidth=0.5)

            ax2.scatter(t[i], self.theta[i], lw=0.01, c='orange')
            ax2.set_xlabel(r'$t$')
            ax2.set_ylabel(r'$\theta$')
            ax2.set_xlim(0, max(t))
            ax2.set_ylim(min(self.theta) - 0.1, max(self.theta) + 0.1)
            plt.pause(0.01)
            plt.draw_all()
            ax1.clear()  

        return self.circle1, self.circle2
Exemplo n.º 5
0
def motion(event):
    buttonStart.set_active(False)  #禁用按钮,避免重复响应
    position = 0
    step = random() * 2
    ax1.lines.clear()
    ax1.plot([0, cos(position)], [0, sin(position)], lw=3, color='yellow')
    plt.draw_all(True)
    for i in range(150):
        if i % 15 == 0:
            step = max(0, step - 0.2)
        if step < 1e-2:
            break
        position = position + step

        plt.pause(0.05)
        ax1.lines.clear()

        ax1.plot([0, cos(position)], [0, sin(position)], lw=3, color='yellow')
        #强制更新图形
        plt.draw_all(True)
        #启动按钮
    buttonStart.set_active(True)
    position = position % (2 * pi)
    ratio = position / (2 * pi)
    if ratio > data['一等奖'] + data['二等奖']:
        showinfo('恭喜', '三等奖')
    elif ratio > data['一等奖']:
        showinfo('恭喜', '二等奖')
    else:
        showinfo('恭喜', '一等奖')
Exemplo n.º 6
0
    def refresh(self):
        # TODO Now real time plotting and FFT cannot be showed on the same time
        #  y_raw = App.get_running_app().data[-self.length:]
        y_raw = App.get_running_app().filteredData[-self.length:]

        y = [
            y_raw[i] for i in range(len(y_raw))
            if np.mod(i, self.plotScale) == 0
        ]
        # Frequency Domain filter
        #  b,a = signal.butter(4,[5 /(self.fs/2),45 /(self.fs/2)],'band')
        #  y = signal.filtfilt(b,a,y_raw)

        self.RealTimePlot.set_ydata(y)
        if self.scale == 'Auto':
            ymin, ymax = self.ax.get_ylim()
            if ymax - ymin != 0:
                padding = (np.max(y) - np.min(y)) * 0.1
                if np.min(y) < ymin or np.max(y) > ymax or padding < (
                        ymax - ymin) * 0.1 and (ymax - ymin) > 10:
                    padding = (np.max(y) - np.min(y)) * 0.1
                    # TODO To improve figure ylimits stability
                    self.ax.set_ylim(
                        [np.min(y) - padding,
                         np.max(y) + padding])

        plt.draw_all()
Exemplo n.º 7
0
    def replot(self):
        self._lastPlotRequest = time.time()
        x, y, yerr = self._getplotData()
        if self.drawn is None:
            self.plot()
            return
        errs = []
        if self.step:
            for tyerr,coll in zip(yerr,self.drawn['err']):
                color = coll.get_facecolor()
                coll.remove()
                errs.append(self.axes.fill_between(
                    x, tyerr[0], tyerr[1],
                    color=color, alpha=self.alpha, step='mid', lw=0))
        else:
            for tyerr,coll in zip(yerr,self.drawn['err']):
                color = coll.get_facecolor()
                coll.remove()
                errs.append(self.axes.fill_between(
                    x, tyerr[0], tyerr[1],
                    color=color, alpha=self.alpha, lw=0))


        self.drawn['err'] = errs
        self.drawn['line'].set_xdata(x)
        self.drawn['line'].set_ydata(y)
        if self.autoscale:
            self.axes.relim()
            self.axes.autoscale_view(True, True, True)
        plt.draw_all()
        self._lastPlottingTime = time.time()-self._lastPlotRequest
Exemplo n.º 8
0
 def plot(self):
     self._lastPlotRequest = time.time()
     x, y, yerr = self._getplotData()
     if len(x) == 0:
         self._lastPlottingTime = time.time()-self._lastPlotRequest
         return
     props = next(self.axes._get_lines.prop_cycler)
     errs = []
     if self.step:
         for n,eP in enumerate(self.errPercentiles):
             errs.append(self.axes.fill_between(x, yerr[n][0],
                                         yerr[n][1],
                                         color=props['color'],
                                         alpha=self.alpha,
                                         step='mid', lw=0))
         line = self.axes.step(x, y, where='mid', label=self.label, **props)[0]
     else:
         for n,eP in enumerate(self.errPercentiles):
             errs.append(self.axes.fill_between(x, yerr[n][0],
                                         yerr[n][1],
                                         color=props['color'],
                                         alpha=self.alpha,
                                         step='mid', lw=0))
         line = self.axes.plot(x, y,'.-', label=self.label, **props)[0]
     self.drawn = dict(err=errs, line=line)
     if self.autosetAxlabel:
         self.axes.set_xlabel(
             '%s / %s' % (
                 self.data.scan._parameters[self.scanVariable].name,
                 self.data.scan._parameters[self.scanVariable].unit))
         self.axes.set_ylabel('%s / %s' % (self.data.name, self.data.unit))
     plt.draw_all()
     self._lastPlottingTime = time.time()-self._lastPlotRequest
Exemplo n.º 9
0
def callback(msg):
    # create numpy array
    occdata = np.array([msg.data])
    # occdata is -1 (unexplored), 0 (occupied), or value between 0 and 100 (probability occupied)
    # compute histogram to identify percent of bins with -1
    occ_counts = np.histogram(occdata, occ_bins)
    # calculate total number of bins
    total_bins = msg.info.width * msg.info.height
    # log the info
    rospy.loginfo('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i',
                  occ_counts[0][0], occ_counts[0][1], occ_counts[0][2],
                  total_bins)

    # make occdata go from 0 to 2 so we can use uint8, which won't be possible if we have
    # negative values
    # first make negative values 0
    occ2 = occdata + 1
    # now change all the values above 1 to 2
    occ3 = (occ2 > 1).choose(occ2, 2)
    # convert into 2D array using column order
    odata = np.uint8(occ3.reshape(msg.info.width, msg.info.height, order='F'))
    # create image from 2D array using PIL
    img = Image.fromarray(odata)
    # show the image using grayscale map
    plt.imshow(img, cmap='gray')
    plt.draw_all()
    # pause to make sure the plot gets created
    plt.pause(0.001)
Exemplo n.º 10
0
def drawnow(draw_fig, show_once=False, confirm=False, *argv, **kwargs):
    """A function to refresh the current figure.
    Depends on matplotlib's interactive mode. Similar functionality to MATLAB's
    drawnow.
    Parameters
    ----------
    draw_fig : callable
               the function that draws the figure you want to update
    *argv    : any
               the list of parameters to pass ``draw_fig()``
    **kwargs : any
               the keywords to pass to ``draw_fig()``
    show_once, optional : bool, default == False.
               If True, will call show() instead of draw().
    confirm, optional : bool, default == False
               If True, wait for user input after each iteration and present
               option to drop to python debugger (pdb).
    Limitations
    -----------
    - Occaisonally ignores Ctrl-C especially while processing LaTeX.
    - Does not work in IPython's QtConsole. This depends on pylab's
      interactivity (implemented via ion()) working in QtConsole.
    - The initial processing of Latex labels (typically on the x/y axis and
      title) is slow. However, matplotlib caches the results so any subsequent
      animations are pretty fast.
    - If two figures open and focus moved between figures, then other figure
      gets cleared.
    Usage Example
    -------------
      >>> from pylab import * # import matplotlib before drawnow
      >>> from drawnow import drawnow, figure
      >>> def draw_fig_real():
      >>>     #figure() # don't call, otherwise opens new window
      >>>     imshow(z, interpolation='nearest')
      >>>     colorbar()
      >>>     #show()
      >>> N = 16
      >>> z = zeros((N,N))
      >>> figure()
      >>> for i in arange(N*N):
      >>>     z.flat[i] = 0
      >>>     drawnow(draw_fig_real)
    """
    # replace the current figure w/o opening new GUI
    plt.clf()
    draw_fig(*argv, **kwargs)

    if show_once: plt.show()
    else: plt.draw_all()

    plt.pause(1e-3) # allows time to draw

    if confirm:
        string = raw_input('Hit <Enter> to continue ("d" for debugger and "x" to exit): ')
        if string == 'x' or string=='exit':
            sys.exit()
        if string == 'd' or string=='debug':
            print('\nType "exit" to continue program execution\n')
            pdb.runeval('u')
    def show_plot(self):
        '''Animation of the plots and shows'''
        #----------- Set figure -----------
        #fig = plt.figure(figsize=(12, 4.5), dpi=80)
        #ax1 = fig.add_subplot(1,2,1)
        #ax2 = fig.add_subplot(1,2,2)
        gs = gridspec.GridSpec(2, 2)

        fig = plt.figure(figsize=(10, 10), dpi=80)
        ax1 = plt.subplot(gs[0, 0]) # row 0, col 0
        plt.plot([0,1])

        ax2 = plt.subplot(gs[0, 1]) # row 0, col 1
        plt.plot([0,1])

        ax3 = plt.subplot(gs[1, :]) # row 1, span all columns
        plt.plot([0,1])


        ax2.clear()
        ax3.clear()
        line1, = ax2.plot(self.x, self.y, '-', color='orange')
        line2, = ax3.plot(t, self.theta, '-', color='orange')
        

        for i in range(0, len(t), frame_step):

            self.x0 = A * np.cos(omega * t[i])
            ax1.plot([self.x0, self.x0 + self.x[i]], [0, self.y[i]])
            self.circle0 = Circle((self.x0, 0), r/2, fc='b', zorder=10)
            self.circle1 = Circle((self.x0 + self.x[i], self.y[i]), r/2, fc='orange', zorder=10)
            ax1.add_patch(self.circle0)
            ax1.add_patch(self.circle1)
            ax1.set_xlabel(r'$x$')
            ax1.set_ylabel(r'$y$')
            ax1.set_xlim(-L - 0.1, L + 0.1)
            ax1.set_ylim(-L - 0.1, L + 0.1)
            ax1.set_aspect('equal', adjustable='box')

            line1.set_xdata(A * np.cos(omega * t[:i]) + self.x[:i])
            line1.set_ydata(self.y[:i])
            ax2.set_xlabel(r'$x$')
            ax2.set_ylabel(r'$y$')
            ax2.set_xlim(-L - 0.1, L + 0.1)
            ax2.set_ylim(-L - 0.1, L + 0.1)
            
            line2.set_xdata(t[:i])
            line2.set_ydata(self.theta[:i])
            ax3.set_xlabel(r'$t$')
            ax3.set_ylabel(r'$\theta$')
            ax3.set_xlim(0, max(t))
            ax3.set_ylim(min(self.theta) - 0.3, max(self.theta) + 0.3)

            plt.pause(0.01)
            plt.draw_all()
            ax1.clear()  
        

        return self.x0, self.circle0, self.circle1
Exemplo n.º 12
0
def callback(msg, tfBuffer):
    global rotated

    # create numpy array
    occdata = np.array([msg.data])
    # compute histogram to identify percent of bins with -1
    occ_counts = np.histogram(occdata, occ_bins)
    # calculate total number of bins
    total_bins = msg.info.width * msg.info.height
    # log the info
    rospy.loginfo('Width: %i Height: %i', msg.info.width, msg.info.height)
    rospy.loginfo('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i',
                  occ_counts[0][0], occ_counts[0][1], occ_counts[0][2],
                  total_bins)

    # find transform to convert map coordinates to base_link coordinates
    # lookup_transform(target_frame, source_frame, time)
    trans = tfBuffer.lookup_transform('base_link', 'map', rospy.Time(0))
    rospy.loginfo(['Trans: ' + str(trans.transform.translation)])
    rospy.loginfo(['Rot: ' + str(trans.transform.rotation)])
    # convert quaternion to Euler angles
    orientation_list = [
        trans.transform.rotation.x, trans.transform.rotation.y,
        trans.transform.rotation.z, trans.transform.rotation.w
    ]
    (roll, pitch, yaw) = euler_from_quaternion(orientation_list)
    rospy.loginfo(['Yaw: R: ' + str(yaw) + ' D: ' + str(np.degrees(yaw))])

    # make occdata go from 0 instead of -1, reshape into 2D
    oc2 = occdata + 1
    # set all values above 1 (i.e. above 0 in the original map data, representing occupied locations)
    oc3 = (oc2 > 1).choose(oc2, 2)
    # reshape to 2D array using column order
    odata = np.uint8(oc3.reshape(msg.info.width, msg.info.height, order='F'))
    # create image from 2D array using PIL
    img = Image.fromarray(odata)
    ######  Translate the map centre to the robot
    trans2 = tfBuffer.lookup_transform('map', 'base_link', rospy.Time(0))
    robotX = (trans2.transform.translation.x -
              msg.info.origin.position.x) / msg.info.resolution
    robotY = (trans2.transform.translation.y -
              msg.info.origin.position.y) / msg.info.resolution
    diffX = robotX - 0.5 * img.size[0]
    diffY = robotY - 0.5 * img.size[1]
    img = img.transform(img.size,
                        Image.AFFINE, (1, 0, diffY, 0, 1, diffX),
                        fill=0)
    ######
    # rotate by 180 degrees to invert map so that the forward direction is at the top of the image
    rotated = img.rotate(np.degrees(yaw) + 180)
    # show image using grayscale map
    plt.imshow(rotated, cmap='gray')
    ######
    # plt.plot(img.size[0]/2, img.size[1]/2, 'y+')  # Optionally mark the centre
    ######
    plt.draw_all()
    # pause to make sure the plot gets created
    plt.pause(0.00000000001)
Exemplo n.º 13
0
def show_results_by_venue(venue, results):
    """Driver to plot the results for the venue.

    Make five plots that highlight the results of the run.

    - The number of wells used in each local model fit.
    - The local vertically-averaged head.
    - The local vertically-averaged flow direction.
    - The magnitude of the gradient of the local vertically-averaged head.
    - The laplacian zscore.

    Parameters
    ----------
    venue: type
        An instance of a political division, administrative region, or
        user-defined domain, as enumerated and detailed in `venues.py`.
        For example: a ``City``, ``Watershed``, or ``Neighborhood``.

    results : list[tuples] (xytarget, n, evp, varp)

        - xytarget : tuple(float, float)
            x- and y-coordinates of target location.
        - n : int
            number of neighborhood wells used in the local analysis.
        - evp : ndarray, shape=(6,1)
            expected value vector of the prarameters.
        - varp : ndarray, shape=(6,6)
            variance/covariance matrix of the parameters.

    Returns
    -------
    target_values : dictionary

    """
    xtarget, ytarget, xvec, yvec, p10 = local_flow_direction(venue, results)
    _, _, ntarget = local_number_of_wells(venue, results)
    _, _, head = local_head(venue, results)
    _, _, magnitude = local_gradient(venue, results)
    _, _, score = local_laplacian_zscore(venue, results)

    plt.draw_all()
    plt.show(block=False)

    target_values = {
        "xtarget": xtarget,
        "ytarget": ytarget,
        "xvec": xvec,
        "yvec": yvec,
        "p10": p10,
        "ntarget": ntarget,
        "head": head,
        "magnitude": magnitude,
        "score": score
    }

    return target_values
Exemplo n.º 14
0
def _profile_decoration(key):
    """
    """

    _plt.grid('on')
    _plt.gca().invert_yaxis()
    _plt.xlabel(MODEL_LABELS[key])
    _plt.ylabel(MODEL_LABELS['hl'])
    _plt.draw_all()
    _plt.show(block=False)
Exemplo n.º 15
0
 def plot(self):
     plt.figure(self.fig.number)
     plt.clf()
     plt.plot(np.array(self.loss_train))
     plt.title("Train loss / batch")
     plt.xlabel("Batch")
     plt.ylabel("Loss")
     plt.show()
     plt.draw_all()
     plt.pause(1e-3)
Exemplo n.º 16
0
	def show_map(self):
		img1 = Image.fromarray(self._occ_map)
		img2 = Image.fromarray(self._edge_map)

		plt.imshow(img1)
		# plt.imshow(img2)

		plt.draw_all()
		plt.pause(0.00000001)
		plt.show()
Exemplo n.º 17
0
def process_vertices(x, y):
    global vertices
    vertices.append([math.floor(x), math.floor(y)])
    [p.remove() for p in reversed(ax.patches)]
    poly = patches.Polygon(vertices, edgecolor='r', facecolor="none")
    ax.add_patch(poly)
    plt.draw_all()
    plt.pause(0.001)  # Extra pause to allow plt to draw box
    plt.draw_all()
    plt.pause(0.001)
Exemplo n.º 18
0
def real_time_anal_scan_delayline(npy_file,
                                  min_wl=500,
                                  max_wl=515,
                                  refresh_delay=1):
    min_idx = get_nearest_idx_from_list(min_wl, hero_pixel_wavelengths)
    max_idx = get_nearest_idx_from_list(max_wl, hero_pixel_wavelengths)
    _fig, fig, line, figall, fig2, line2 = anal_scan_delayline(npy_file,
                                                               min_wl=min_wl,
                                                               max_wl=max_wl)
    prev_data_len = 0
    num = 0
    global spec_sums
    while True:
        try:
            data = np.load(
                os.path.join(
                    r'D:/Nonlinear_setup/Experimental_data/scan_delayline',
                    npy_file + '.npy'))
        except:
            plt.pause(0.1)
            data = np.load(
                os.path.join(
                    r'D:/Nonlinear_setup/Experimental_data/scan_delayline',
                    npy_file + '.npy'))

        curr_data_len = len(data)
        if curr_data_len == prev_data_len:
            if num > 10:
                return
            plt.pause(refresh_delay)
            num += 1
            continue
        else:
            num = 0
        poss = list(map(lambda x: x[0][0], data))
        lockins = np.array(map(lambda x: x[0][1], data)) * 1e3
        specs = list(map(lambda x: x[1], data))
        spec_sums = list(map(lambda x: np.sum(x[min_idx:max_idx]), specs))

        line.set_xdata(poss)
        line.set_ydata(spec_sums)
        fig.relim(True)
        fig.autoscale_view(True, True, True)

        line2.set_xdata(poss)
        line2.set_ydata(lockins)
        fig2.relim(True)
        fig2.autoscale_view(True, True, True)

        while curr_data_len > len(figall.lines):
            figall.plot(hero_pixel_wavelengths, specs[len(figall.lines)])

        plt.draw_all()
        prev_data_len = curr_data_len
        plt.pause(refresh_delay)
Exemplo n.º 19
0
 def update(self, logs):
     if ('all_episode_rewards'
             in logs) and (len(logs['all_episode_rewards']['reward']) > 1):
         plt.figure(self.prefix + 'Cumulative Rewards')
         plt.clf()
         plt.plot(logs['all_episode_rewards']['episode'],
                  logs['all_episode_rewards']['reward'])
         plt.xlabel('Episode')
         plt.ylabel('Cumulative Reward')
         plt.draw_all()
         plt.pause(1e-3)
Exemplo n.º 20
0
    def draw(self, show=True, ax=None):
        if self.__draw_cfg['mode'] == '3d':
            ax = self.draw_3d()
        else:
            ax = self.draw_2d(ax)

        if show:
            plt.draw_all()
            plt.tight_layout()
            plt.show()
        return ax
Exemplo n.º 21
0
 def listener_callback(self, array):
     heat_array = np.reshape(array.data, (resolution, resolution))
     # print(heat_array)
     heat_img = Image.fromarray(np.uint8(heat_array), 'L')
     graph = plt.imshow(
         heat_img,
         cmap=plt.cm.hot)  # viridis, plasma, inferno, magma, cividis
     plt.clim(20, 60)
     plt.draw_all()
     self.get_logger().info('Receiving')
     plt.pause(0.00000000001)
Exemplo n.º 22
0
        def store(self, state):
            """
            Updates the plot using the given state.

            Args:
                state (dict): A model state dictionary.
            """
            self._fig.clear()
            self._plot_function(self._fig, state)
            plt.draw_all()
            plt.pause(
                1e-5)  # necessary to draw, pause can be arbitrarily small
Exemplo n.º 23
0
    def plotme():
        import matplotlib.pyplot as plt
        fig = plt.figure()
        first_axis = fig.add_subplot(2, 2, 1)
        second_axis = fig.add_subplot(2, 2, 2)
        third_axis = fig.add_subplot(2, 2, 3)
        fourth_axis = fig.add_subplot(2, 2, 4)
        '''
        The whole logic here is just to enable multiple
        points on the graph as users enter values separated
        by a comma
        '''

        E1_short = E1.get()
        num_x = []
        for i in (E1_short.split(",")):
            if i.isdigit():
                num_x.append(int(i))
        E2_short = E2.get()
        num_y = []
        for i in (E2_short.split(",")):
            if i.isdigit():
                num_y.append(int(i))

        first_axis = plt.plot(num_x, num_y, label='x-axis against y-axis')
        #first_axis.legend(loc='center')

        second_axis.scatter(num_x,
                            num_y,
                            label='Scatter - graph form of the axes')
        second_axis.legend(loc='center')

        third_axis.hist(num_x, num_y, label='Histogram of the axes')
        third_axis.legend(loc='center')

        #fourth_axis=sns.violinplot(num_x, num_y)
        '''first_axis.plot(randn(1000).cumsum(), 'k--', label='-- is for')
        first_axis.plot(randn(1000).cumsum(), 'k--', label='. is for')'''

        plotit = plt.xlabel('x axis', fontsize='small')
        plt.ylabel('y axis', fontsize='small')
        plt.title('Graph of x - axis against y - axis.', fontsize='small')
        #plt.scatter(num_x, num_y, edgecolors='black')
        #plt.plot(num_x, num_y)

        plt.yticks(color='blue')
        plt.xticks(color='darkred')
        #sns.regplot(num_x, num_y)
        plt.show()

        #        plotgraph= Label(root,text='$%.2f'% plotit).grid(x=605, y=500)
        plt.draw_all((num_x, num_y))
        return
Exemplo n.º 24
0
    def Passive_Display(self):
        """Opens all figures and listens for user commands.
        
        Adjusted for eclipse file processing mode:
        Does not block, permitting redraw and proceeding with the code.
        W {num} = Wait num secs until next waking.
        R {[figs] | all} = Redraw specific or all figs (space sep).
        S {[figs] | all} = Save figs as currently displayed.
        Q / C = Soft close (continue until reaching the proc's end, killing figs).
        Creep: Canvas draw seems to have no effect; pause redraws all rather than cur.
        Annoyingly, it also sets the focus on the entire series.
        As such, currently setting the duration higher.
        Creep: Reset the program entirely (rerun main), keeping the mplot refs.
        Currently, terminate + run doesn't seem a terrible inconvenience."""
        for fig in self.dplt.values():
            fig[0].show()  # Alt: plt.show.

        indstop = False
        cslp = USRWAIT
        while not indstop:
            plt.pause(max(cslp - NOWAIT,
                          NOWAIT))  # Only pause unlocks the gui.
            pwait = uti.List_Format(PUFIG, uti.LSTPH, NOWAIT)
            ursp = uti.Timed_Input(*pwait)

            if ursp:
                ursp2 = ursp.split(" ")
                comm = ursp2[0].lower()
                ursp2 = ursp2[1:]
                if comm.startswith("w"):  # Change the wait schedule.
                    try:
                        cslp = int(ursp2[0])
                    except (ValueError, IndexError):
                        print(
                            "Cannot update period, still at {}.".format(cslp))
                elif comm.startswith("r"):  # Redraw.
                    for fig in ursp2:
                        try:
                            fign = int(
                                fig)  # Numerical figs are stored as such.
                        except ValueError:
                            fign = fig
                        if fig.lower() == "all":
                            plt.draw_all(
                            )  # Faster than singles, still pointless.
                        elif fign in self.dplt:
                            self.dplt[fign][0].canvas.draw()
                        else:
                            print("Fig doesn't exist, cannot ref: {}.".format(
                                fign))
                elif (comm.startswith("q") or comm.startswith("c")):
                    indstop = True
Exemplo n.º 25
0
 def replot(self):
     self._lastPlotRequest = time.time()
     x, y = self._getplotData()
     if self.drawn is None:
         self.plot()
         return
     self.drawn["line"].set_xdata(x)
     self.drawn["line"].set_ydata(y)
     if self.autoscale:
         self.axes.relim()
         self.axes.autoscale_view(True, True, True)
     plt.draw_all()
     self._lastPlottingTime = time.time() - self._lastPlotRequest
Exemplo n.º 26
0
 def on_step_end(self, step, logs):
     if ('interval_metrics'
             in logs) and (len(logs['interval_metrics']['step']) > 1):
         for name, values in logs['interval_metrics'].items():
             if name == 'step': continue
             plt.figure(self.prefix + name)
             plt.clf()
             plt.plot(logs['interval_metrics']['step'], values)
             plt.title(self.prefix + name)
             plt.xlabel('Steps')
             plt.ylabel(name)
         plt.draw_all()
         plt.pause(1e-3)
Exemplo n.º 27
0
def callback(msg, tfBuffer):
    global rotated

    # create numpy array
    occdata = np.array([msg.data])
    # compute histogram to identify percent of bins with -1
    occ_counts = np.histogram(occdata, occ_bins)
    # calculate total number of bins
    total_bins = msg.info.width * msg.info.height
    # log the info
    rospy.loginfo('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i',
                  occ_counts[0][0], occ_counts[0][1], occ_counts[0][2],
                  total_bins)

    # try:
    # lookup_transform(target_frame, source_frame, time)
    trans = tfBuffer.lookup_transform('map', 'odom', rospy.Time(0))
    rospy.loginfo(['Trans: ' + str(trans.transform.translation)])
    rospy.loginfo(['Rot: ' + str(trans.transform.rotation)])
    orientation_list = [
        trans.transform.rotation.x, trans.transform.rotation.y,
        trans.transform.rotation.z, trans.transform.rotation.w
    ]
    (roll, pitch, yaw) = euler_from_quaternion(orientation_list)
    rospy.loginfo(['Yaw: R: ' + str(yaw) + ' D: ' + str(np.degrees(yaw))])

    # except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
    # pass

    # global counter)]
    # if counter % 10 == 0:
    # plt.cla()

    #    plt.imshow(occdata.reshape(msg.info.width,msg.info.height))
    # make occdata go from 0 to 255, reshape into 2D
    odata = np.uint8((occdata + occ_offset).reshape(msg.info.width,
                                                    msg.info.height))
    img = Image.fromarray(np.flipud(odata))
    # odata = uint8(occ2.reshape(msg.info.width,msg.info.height))
    # img = Image.fromarray(occdata.reshape(msg.info.width,msg.info.height),'RGB')
    # img.show()
    # close previous image
    # rotated.close()
    rotated = img.rotate(np.degrees(yaw))
    # plt.imshow(rotated)
    plt.imshow(img)
    # rotated.show()
    # plt.gca().invert_yaxis()
    plt.draw_all()
    rospy.sleep(1.0)
    plt.pause(0.00000000001)
Exemplo n.º 28
0
def find_center(img,
                psize=100e-6,
                dist=0.1,
                wavelength=0.8e-10,
                center=None,
                reference=None,
                **kwargs):
    """ center is the initial centr (can be None)
      reference is a reference position to be plot in 2D plots """
    plt.ion()
    kw = dict(pixel1=psize, pixel2=psize, dist=dist, wavelength=wavelength)
    kw.update(kwargs)
    ai = pyFAI.azimuthalIntegrator.AzimuthalIntegrator(**kw)
    fig_img, ax_img = plt.subplots(1, 1)
    fig_pyfai, ax_pyfai = plt.subplots(1, 1)
    fig_pyfai = plt.figure(2)
    temp = ax_img.imshow(img)
    plt.sca(ax_img)
    # set figure to use for mouse interaction
    temp.set_clim(*np.percentile(img, (2, 95)))
    ans = ""
    print("Enter 'end' when done")
    while ans != "end":
        if center is None:
            print("Click on beam center:")
            plt.sca(ax_img)
            # set figure to use for mouse interaction
            center = plt.ginput()[0]
        print("Selected center:", center)
        ai.set_poni1(center[1] * psize)
        ai.set_poni2(center[0] * psize)
        q, az, i = do2d(ai, img)
        mesh = ax_pyfai.pcolormesh(q, az, i)
        mesh.set_clim(*np.percentile(i, (2, 95)))
        ax_pyfai.set_title(str(center))
        if reference is not None: ax_pyfai.axvline(reference)
        plt.pause(0.01)
        plt.draw()
        plt.draw_all()
        ans = input("Enter to continue with clinking or enter xc,yc values ")
        if ans == '':
            center = None
        else:
            try:
                center = list(map(float, ans.split(",")))
            except Exception as e:
                center = None
        if center == []: center = None
    print("Final values: (in pixels) %.3f %.3f" % (center[0], center[1]))
    return ai
Exemplo n.º 29
0
def figs_equal(fig1, fig2, tol=None):
    """
    Test if two figures are identical
    
    Parameters
    ----------
    fig1 : matplotlib figure object
        Reference figure
    fig2 : matplotlib figure object
        Template figure
    tol : float
        Positive scalar (b/w 0 and 1) specifying tolerance level for considering 
        `fig1` and `fig2` identical. If `None`, two figures have to be exact 
        pixel-perfect copies to be qualified as identical. 
    
    Returns
    -------
    equal : bool
        `True` if `fig1` and `fig2` are identical, `False` otherwise
        
    Notes
    -----
    This is an auxiliary method that is intended purely for internal use. Thus, 
    no error checking is performed. 
    
    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> x = np.linspace(0, 2*np.pi, 100)
    >>> fig1 = plt.figure(); plt.plot(x, np.sin(x))
    >>> figs_equal(fig1, fig1)
    True
    >>> fig2 = plt.figure(); plt.plot(x, np.sin(x), color="red")
    >>> figs_equal(fig1, fig2)
    False
    >>> figs_equal(fig1, fig2, tol=0.9)
    True
    """
    plt.draw_all(force=True)
    with tempfile.NamedTemporaryFile(suffix='.png') as img1:
        with tempfile.NamedTemporaryFile(suffix='.png') as img2:
            fig1.savefig(img1.name)
            fig2.savefig(img2.name)
            if tol is None:
                return np.array_equal(plt.imread(img1.name),
                                      plt.imread(img2.name))
            return np.allclose(plt.imread(img1.name),
                               plt.imread(img2.name),
                               atol=tol)
Exemplo n.º 30
0
    def update_compound_widget(caller=None):
        """
        The update function checks the aggrupation characteristics, calculates the resulting df,
        and updates the table and graph.
        """

        information_widget.value = "Updating..."
        # find the aggregation level using the check boxes
        aggregation_level = []

        for level in check_boxes:
            check_box = check_boxes[level]

            if check_box.value:
                aggregation_level.append(level)

        table_df, graph_df = process_df_for_widget(
            df_traffic,
            aggregation_columns=aggregation_level,
            value_column=value_column,
            time_column=time_column,
            top_flows_to_show=top_flows_to_show,
        )
        ax_prefix_distribution.clear()
        aggregation_column_name = next(
            iter(set(graph_df.columns) - {time_column, value_column})
        )

        graph_df.plot.area(ax=ax_prefix_distribution)

        ax_prefix_distribution.legend_.remove()
        ax_prefix_distribution.legend(
            bbox_to_anchor=(0.1, 0.85, 0.9, 0.105),
            loc=3,
            ncol=2,
            mode=None,
            borderaxespad=0.1,
            fontsize=8,
        )
        ax_prefix_distribution.set_ylabel(value_column)
        table_widget.value = (
            table_df.style.set_table_attributes('class="table"')
            .set_table_styles([hover()])
            .render()
        )

        information_widget.value = "Redrawing..."
        plt.draw_all()
        information_widget.value = "Done"
Exemplo n.º 31
0
def draw(iteration, mesh, cost_to_go, policy):
    # Drawing is slow, don't draw every frame.
    if iteration % 20 != 0:
        return
    plt.title("iteration " + str(iteration))
    J = np.reshape(cost_to_go, Q.shape)
    surf = ax.plot_surface(Q, Qdot, J, rstride=1, cstride=1,
                           cmap=cm.jet)

    Pi = np.reshape(policy, Q.shape)
    surf2 = ax2.plot_surface(Q, Qdot, Pi, rstride=1, cstride=1, cmap=cm.jet)

    if plt.get_backend() != u'template':
        plt.draw_all()
        plt.pause(0.00001)

    surf.remove()
    surf2.remove()
Exemplo n.º 32
0
def test_text_stale():
    fig, (ax1, ax2) = plt.subplots(1, 2)
    plt.draw_all()
    assert not ax1.stale
    assert not ax2.stale
    assert not fig.stale

    txt1 = ax1.text(0.5, 0.5, "aardvark")
    assert ax1.stale
    assert txt1.stale
    assert fig.stale

    ann1 = ax2.annotate("aardvark", xy=[0.5, 0.5])
    assert ax2.stale
    assert ann1.stale
    assert fig.stale

    plt.draw_all()
    assert not ax1.stale
    assert not ax2.stale
    assert not fig.stale
Exemplo n.º 33
0
def test_text_stale():
    fig, (ax1, ax2) = plt.subplots(1, 2)
    plt.draw_all()
    assert not ax1.stale
    assert not ax2.stale
    assert not fig.stale

    txt1 = ax1.text(.5, .5, 'aardvark')
    assert ax1.stale
    assert txt1.stale
    assert fig.stale

    ann1 = ax2.annotate('aardvark', xy=[.5, .5])
    assert ax2.stale
    assert ann1.stale
    assert fig.stale

    plt.draw_all()
    assert not ax1.stale
    assert not ax2.stale
    assert not fig.stale
Exemplo n.º 34
0
def drawnow(draw_fig, show_once=False, confirm=False, *argv, **kwargs):
    """A function to refresh the current figure.

    Depends on matplotlib's interactive mode. Similar functionality to MATLAB's
    drawnow.

    Parameters
    ----------
    draw_fig : callable
               the function that draws the figure you want to update
    *argv    : any
               the list of parameters to pass ``draw_fig()``
    **kwargs : any
               the keywords to pass to ``draw_fig()``
    show_once, optional : bool, default == False.
               If True, will call show() instead of draw().
    confirm, optional : bool, default == False
               If True, wait for user input after each iteration and present
               option to drop to python debugger (pdb).

    Limitations
    -----------
    - Occaisonally ignores Ctrl-C especially while processing LaTeX.
    - Does not work in IPython's QtConsole. This depends on pylab's
      interactivity (implemented via ion()) working in QtConsole.
    - The initial processing of Latex labels (typically on the x/y axis and
      title) is slow. However, matplotlib caches the results so any subsequent
      animations are pretty fast.
    - If two figures open and focus moved between figures, then other figure
      gets cleared.

    Usage Example
    -------------
      >>> from pylab import * # import matplotlib before drawnow
      >>> from drawnow import drawnow, figure
      >>> def draw_fig_real():
      >>>     #figure() # don't call, otherwise opens new window
      >>>     imshow(z, interpolation='nearest')
      >>>     colorbar()
      >>>     #show()

      >>> N = 16
      >>> z = zeros((N,N))

      >>> figure()
      >>> for i in arange(N*N):
      >>>     z.flat[i] = 0
      >>>     drawnow(draw_fig_real)
    """
    # replace the current figure w/o opening new GUI
    plt.clf()
    draw_fig(*argv, **kwargs)

    if show_once: plt.show()
    else: plt.draw_all()

    plt.pause(1e-3) # allows time to draw

    if confirm:
        string = raw_input('Hit <Enter> to continue ("d" for debugger and "x" to exit): ')
        if string == 'x' or string=='exit':
            sys.exit()
        if string == 'd' or string=='debug':
            print('\nType "exit" to continue program execution\n')
            pdb.runeval('u')
Exemplo n.º 35
0
def qt_kicker():
    plt.draw_all()
    qApp.processEvents()
    loop.call_later(.1, qt_kicker)