def __init__(self,
                 fig,
                 func,
                 frames=None,
                 init_func=None,
                 fargs=None,
                 save_count=None,
                 save_pth=None,
                 pos=(0.125, 0.92),
                 **kwargs):
        self.save_pth = save_pth
        self.i = 0
        self.min = frames[0]
        self.max = frames[-1]
        self.runs = True
        self.forwards = True
        self.fig = fig
        self.func = func
        self.frames = frames
        self.setup(pos)
        self.added_speed = 0
        FuncAnimation.__init__(self,
                               self.fig,
                               self.update,
                               frames=self.play(),
                               init_func=init_func,
                               fargs=fargs,
                               save_count=save_count,
                               **kwargs)

        self._observers = []

        get_current_fig_manager().toolbar.save_figure = self.save_event
        self.fig.canvas.mpl_connect('close_event', self.close_event)
Пример #2
0
 def __init__(self,
              fig,
              func,
              frames=None,
              init_func=None,
              fargs=None,
              save_count=None,
              mini=0,
              maxi=100,
              pos=(0.15, 0.96),
              **kwargs):
     self.i = 0
     self.min = mini
     self.max = maxi
     self.runs = True
     self.forwards = True
     self.fig = fig
     self.func = func
     self.setup(pos)
     FuncAnimation.__init__(self,
                            self.fig,
                            self.func,
                            frames=self.play(),
                            init_func=init_func,
                            fargs=fargs,
                            save_count=save_count,
                            **kwargs)
Пример #3
0
    def __init__(self, fig, startFrame, endFrame, tail, fade=False, **kwargs) :
        """
        Create an animation of track segments.

        *fig*               matplotlib Figure object
        *startFrame*        The frame number to start animation loop at
        *endFrame*          The frame number to end the loop at
        *tail*              How many frames to keep older segments in view
        *fade*              Whether or not to fade track tails for
                            non-active tracks (default: False).

        All other :class:`FuncAnimation` constructor  kwargs are available
        except *frames* and *fargs*.

        TODO: Add usage info.
        """
        self._lineData = []
        self._lines = []
        if 'frames' in kwargs :
            raise KeyError("Do not specify 'frames' for the constructor"
                           " of SegAnimator")

        self.fade = fade

        FuncAnimation.__init__(self, fig, self.update_lines,
                                     endFrame - startFrame + 1,
                                     fargs=(self._lineData, self._lines,
                                            startFrame, endFrame, tail),
                                     **kwargs)
Пример #4
0
    def __init__(self, fig, domain, function, cache=False, **kwargs):

        plotting_function = self.mesh_plot
        if domain.is_regular:
            plotting_function = self.image_plot

        FuncAnimation.__init__(self, fig, plotting_function, frames=function)
Пример #5
0
    def __init__(self, fig, startFrame, endFrame, tail, fade=False, **kwargs):
        """
        Create an animation of track segments.

        *fig*               matplotlib Figure object
        *startFrame*        The frame number to start animation loop at
        *endFrame*          The frame number to end the loop at
        *tail*              How many frames to keep older segments in view
        *fade*              Whether or not to fade track tails for
                            non-active tracks (default: False).

        All other :class:`FuncAnimation` constructor  kwargs are available
        except *frames* and *fargs*.

        TODO: Add usage info.
        """
        self._lineData = []
        self._lines = []
        if 'frames' in kwargs:
            raise KeyError("Do not specify 'frames' for the constructor"
                           " of SegAnimator")

        self.fade = fade

        FuncAnimation.__init__(self,
                               fig,
                               self.update_lines,
                               endFrame - startFrame + 1,
                               fargs=(self._lineData, self._lines, startFrame,
                                      endFrame, tail),
                               **kwargs)
    def __init__(self, parent=None):
        self._fig = Figure()
        self.idx = 0
        self.ax1 = self._fig.add_subplot(211)
        self.procs = []
        self.ax2 = self._fig.add_subplot(212)
        FigureCanvas.__init__(self, self._fig)
        FuncAnimation.__init__(
            self, self._fig, self.animate, interval=100, blit=False)
        self.setParent(parent)
        # Needed to initialize the capture
        psutil.cpu_times_percent(interval=None)
        self.x_data = np.arange(0, 100)
        self.cpu_data = np.zeros((0, 100))
        self.ram_data = np.zeros((0, 100))
        self.cpu_dict = defaultdict(list)
        self.ram_dict = defaultdict(list)
        self.colors = {}
        self.colors.update(mcolors.TABLEAU_COLORS)
        self.colors.update(mcolors.BASE_COLORS)
        self.colors.update(mcolors.CSS4_COLORS)
        self.colors = list(self.colors.values())
        for ax in [self.ax1, self.ax2]:
            #ax.set_xlim(0, 100)
            ax.set_xlabel("Time")
            #ax.set_ylim(0, 100)
            ax.get_xaxis().set_ticks([])
            ax.spines['right'].set_color(None)
            ax.spines['top'].set_color(None)
        self.ax1.set_ylabel("Usage (%)")
        self.ax2.set_ylabel("Usage (MB)")

        self.ax1.set_title("CPU Usage")
        self.ax2.set_title("Memory (RAM) Usage")
Пример #7
0
    def __init__(self,
                 parent,
                 figure,
                 func=None,
                 frames=None,
                 init_func=None,
                 fargs=None,
                 save_count=None,
                 **kwargs):
        self.fig = figure
        self.func = func
        self.frames = frames

        if self.func is not None:
            FuncAnimation.__init__(self,
                                   self.fig,
                                   self.func,
                                   frames=self.play(),
                                   init_func=init_func,
                                   fargs=fargs,
                                   save_count=save_count,
                                   **kwargs)

        canvas = FigureCanvasTkAgg(figure, parent)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        toolbar = NavigationToolbar2Tk(canvas, parent)
        toolbar.update()

        self.scale = ttk.Scale(parent, orient=tk.HORIZONTAL)
        self.scale.pack(fill=tk.BOTH)
        self.button_play = ttk.Button(parent,
                                      text="Play",
                                      command=self.on_button_play)
        self.button_play.pack(side=tk.LEFT)
        self.button_stop = ttk.Button(parent, text="Stop")
        self.button_stop.pack(side=tk.LEFT)
        self.button_back = ttk.Button(parent, text="< Back")
        self.button_back.pack(side=tk.LEFT)
        self.button_forward = ttk.Button(parent, text="Forward >")
        self.button_forward.pack(side=tk.LEFT)
        self.label_step = ttk.Label(parent, text='0.000/0.000 sec, 0/0 frames')
        self.label_step.pack(side=tk.LEFT, padx=5)
        self.label_stepsize = ttk.Label(parent, text="Step size: Frames: ")
        self.label_stepsize.pack(side=tk.LEFT)
        self.entryvar_steps_frames = tk.StringVar()
        self.entryvar_steps_frames.set("0")
        self.entry_stepsize_frame = ttk.Entry(
            parent, width=6, textvariable=self.entryvar_steps_frames)
        self.entry_stepsize_frame.pack(side=tk.LEFT)
        self.label_stepsize_sec = ttk.Label(parent, text=" Sec: ")
        self.label_stepsize_sec.pack(side=tk.LEFT)
        self.entryvar_steps_sec = tk.StringVar()
        self.entryvar_steps_sec.set("0.000")
        self.entry_stepsize_sec = ttk.Entry(
            parent, width=6, textvariable=self.entryvar_steps_sec)
        self.entry_stepsize_sec.pack(side=tk.LEFT)
Пример #8
0
    def __init__(self):
        self.fig, self.axs = plt.subplots()
        self.axs.grid()
        self.axs.set_ylim(-1.1, 1.1)
        self.axs.set_xlim(0, 10)

        self.init()
        FuncAnimation.__init__(self, self.fig, self.run, frames=self.data_gen,
                               blit=False, interval=0.1, repeat=False, init_func=self.init)
Пример #9
0
    def play(self):
        pp.tight_layout()

        frames = np.arange(self.frames_start, self.frames_end, self.fps)

        FuncAnimation.__init__(self,
                               self.figure,
                               self.animate,
                               frames=frames,
                               interval=100)
    def __init__(self, parent=None):
        self._fig = Figure()
        ax = self._fig.add_subplot(111)
        FigureCanvas.__init__(self, self._fig)
        FuncAnimation.__init__(self,
                               self._fig,
                               self.animate,
                               interval=100,
                               blit=False)
        self.setParent(parent)

        # Needed to initialize the capture
        psutil.cpu_times_percent(interval=None)
        self.ax = ax
        self.x_data = np.arange(0, 100)
        self.user_data = np.zeros(100)
        self.system_data = np.zeros(100)
        self.ram_data = np.zeros(100)

        self.ax.set_xlim(0, 100)
        self.ax.set_ylabel("Usage (%)")
        self.ax.set_xlabel("Time")

        self.ax.set_ylim(0, 100)
        self.ax.get_xaxis().set_ticks([])
        self.ax.spines['right'].set_color(None)
        self.ax.spines['top'].set_color(None)

        self.cpu_percent = psutil.cpu_times_percent(interval=None)
        self.ram_percent = psutil.virtual_memory().percent

        self.user_data[0] = self.cpu_percent.user
        self.system_data[0] = self.cpu_percent.system
        self.ram_data[0] = self.ram_percent

        self.system_line, = self.ax.plot([], [],
                                         lw=2,
                                         label="System-CPU Usage",
                                         color='orange')
        self.system_line.set_data(self.x_data, self.system_data)

        self.user_line, = self.ax.plot([], [],
                                       label="User-CPU Usage",
                                       color=(17 / 256, 125 / 256, 187 / 256))
        self.user_line.set_data(self.x_data, self.user_data)

        self.ram_line, = self.ax.plot([], [],
                                      lw=2,
                                      label="Memory (RAM) Usage",
                                      color='purple')
        self.ram_line.set_data(self.x_data, self.ram_data)

        self.ax.legend(loc='upper left')
 def __init__(self, parent, fig, animate=False, animation=None):
     self.fig = fig
     FigureCanvasQTAgg.__init__(self, self.fig)
     if animate:
         FuncAnimation.__init__(self,
                                self.fig,
                                animation[0],
                                frames=animation[1],
                                repeat_delay=animation[2])
     self.setParent(parent)
     FigureCanvasQTAgg.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding,
                                     QtWidgets.QSizePolicy.Expanding)
     self.draw()
Пример #12
0
    def __init__(self, fig, files, load_func=None, robust=False, **kwargs):
        """
        Create an animation object for viewing radar reflectivities.

        *fig*           matplotlib Figure object

        *files*         list of filenames containing the radar data

        *load_func*     The function to use to load the data from a file.
                        Must return a dictionary of 'vals' which contains
                        the 3D numpy array (T by Y by X), 'lats' and 'lons'.

                        It is also optional that the loading function also
                        provides a 'scan_time', either as a
                        :class:`datetime.datetime` object or as an integer
                        or a float representing the number of seconds since
                        UNIX Epoch.

        *frames*        The number of frames to display. If not given, then
                        assume it is the same number as 'len(files)'.

        *robust*        Boolean (default: False) indicating whether or not
                        we can assume all the data will be for the same domain.
                        If you can't assume a consistant domain, then set
                        *robust* to True.  This often happens for PAR data.
                        Note that a robust rendering is slower.

        All other kwargs for :class:`FuncAnimation` are also allowed.

        To use, specify the axes to display the image on using :meth:`add_axes`.
        """
        self._rd = files
        self._loadfunc = load_func if load_func is not None else LoadRastRadar

        self._ims = []
        self._im_kwargs = []
        self._new_axes = []
        self._curr_time = None
        self._robust = robust
        frames = kwargs.pop("frames", None)
        # if len(files) < frames :
        #    raise ValueError("Not enough data files for the number of frames")
        FuncAnimation.__init__(
            self,
            fig,
            self.nextframe,
            frames=len(self._rd),
            #                                     init_func=self.firstframe,
            **kwargs
        )
Пример #13
0
    def __init__(self, fig, files, load_func=None, robust=False, **kwargs):
        """
        Create an animation object for viewing radar reflectivities.

        *fig*           matplotlib Figure object

        *files*         list of filenames containing the radar data

        *load_func*     The function to use to load the data from a file.
                        Must return a dictionary of 'vals' which contains
                        the 3D numpy array (T by Y by X), 'lats' and 'lons'.

                        It is also optional that the loading function also
                        provides a 'scan_time', either as a
                        :class:`datetime.datetime` object or as an integer
                        or a float representing the number of seconds since
                        UNIX Epoch.

        *frames*        The number of frames to display. If not given, then
                        assume it is the same number as 'len(files)'.

        *robust*        Boolean (default: False) indicating whether or not
                        we can assume all the data will be for the same domain.
                        If you can't assume a consistant domain, then set
                        *robust* to True.  This often happens for PAR data.
                        Note that a robust rendering is slower.

        All other kwargs for :class:`FuncAnimation` are also allowed.

        To use, specify the axes to display the image on using :meth:`add_axes`.
        """
        self._rd = files
        self._loadfunc = load_func if load_func is not None else LoadRastRadar

        self._ims = []
        self._im_kwargs = []
        self._new_axes = []
        self._curr_time = None
        self._robust = robust
        frames = kwargs.pop('frames', None)
        #if len(files) < frames :
        #    raise ValueError("Not enough data files for the number of frames")
        FuncAnimation.__init__(
            self,
            fig,
            self.nextframe,
            frames=len(self._rd),
            #                                     init_func=self.firstframe,
            **kwargs)
Пример #14
0
    def __init__(self,
                 fig,
                 func,
                 init_func=None,
                 fargs=None,
                 save_count=None,
                 button_color='yellow',
                 bg_color='red',
                 dis_start=0,
                 dis_stop=100,
                 pos=(0.125, 0.05),
                 **kwargs):
        """
        initialization
        :param fig: matplotlib fifure object
        :param func: user-defined function which takes a integer (frame number) as an input
        :param init_func: user-defined initial function used by the FuncAnimation class
        :param fargs: arguments of func, used by FuncAnimation class
        :param save_count: save count arg used by FuncAnimation class
        :param button_color: string, color of the buttons of the player
        :param bg_color: string, hovercolor of the buttons and slider
        :param dis_start: int, start frame number
        :param dis_stop: int, stop frame number
        :param pos: length 2 tuple, position of the buttons
        :param kwargs: kwargs for FuncAnimation class
        """
        # setting up the index
        self.start_ind = dis_start
        self.stop_ind = dis_stop
        self.dis_length = self.stop_ind - self.start_ind
        self.ind = self.start_ind

        self.runs = True
        self.forwards = True
        self.fig = fig
        self.fig.set_facecolor('k')
        self.button_color = button_color
        self.bg_color = bg_color

        self.func = func
        self.setup(pos)
        FuncAnimation.__init__(self,
                               self.fig,
                               self.func,
                               frames=self.play(),
                               init_func=init_func,
                               fargs=fargs,
                               save_count=save_count,
                               **kwargs)
Пример #15
0
    def __init__(self, fig, grid, filelists,
                       load_funcs=None, robusts=False, **kwargs) :

        self._filelists = [cycle(files) for files in filelists]
        self._loadfunc = load_func if load_func is not None else LoadRastRadar
        self._curr_times = [None] * len(filelists)
        self._ims = [None] * len(filelists)
        self._datas = [None] * len(filelists)
        #self.im_kwargs = [None] * len(filelists)
        self._has_looped = [False] * len(filelists)
        self._grid = grid
        self.robust = robust

        FuncAnimation.__init__(self, fig, self.nexttick, blit=False,
                                          init_func=self.firsttick, **kwargs)
Пример #16
0
 def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
              save_count=None, mini=0, maxi=100, pos=(0.2, 0.98), **kwargs):
     self.i = 0
     self.min = mini
     self.max = maxi
     self.runs = True
     self.forwards = True
     self.fig = fig
     self.func = func
     self.setup(pos)
     FuncAnimation.__init__(
         self, self.fig, self.update, frames=self.play(),
         init_func=init_func, fargs=fargs,
         save_count=save_count, **kwargs
     )
Пример #17
0
 def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
              save_count=None, mini=0, maxi=100, pos=(0.125, 0.92), **kwargs):
     self.i = 0
     self.min=mini
     self.max=maxi
     self.fastest_speed = 100
     self.slowest_speed = 1500
     self.runs = True
     self.forwards = True
     self.fig = fig
     self.func = func
     self.setup(pos)
     FuncAnimation.__init__(self,self.fig, self.update, frames=self.play(), 
                                        init_func=init_func, fargs=fargs,
                                        save_count=save_count, **kwargs )    
     self.set_speed(50)
Пример #18
0
    def __init__(self):
        self.rotateMat = dict(zip(imu.IMU_List, [np.array([])] * quanIMU))
        self.calMat = dict(zip(imu.IMU_List, [np.identity(3)] * quanIMU))
        self.posAngles = [0] * quanAngles
        self.angleSignal = Communicate()

        # Plot parameters
        bodyLen = 2

        self.X_Body = [0, 0]
        self.Y_Body = [bodyLen / 2, -bodyLen / 2]
        self.Z_Body = [0, 0]

        # Figure setting
        self.labelX = [0] * 2
        self.labelY = [0] * 2
        self.lines = []
        self.angLabel = []
        self.fig = Figure(figsize=(10, 10), dpi=100, tight_layout=True)

        FigureCanvas.__init__(self, self.fig)

        self.axes = self.fig.add_subplot(111, projection='3d')
        self.lines.append(
            self.axes.plot(self.X_Body,
                           self.Y_Body,
                           self.Z_Body,
                           color='seagreen',
                           linewidth=4))

        self.angLabel.append(self.axes.text2D(0, 0, 'L'))
        self.angLabel.append(self.axes.text2D(0, 0, 'R'))

        self.axes.set_xlim3d([-3.0, 3.0])
        self.axes.set_xlabel('X')
        self.axes.set_ylim3d([-3.0, 3.0])
        self.axes.set_ylabel('Y')
        self.axes.set_zlim3d([-3.0, 3.0])
        self.axes.set_zlabel('Z')
        self.axes.view_init(elev=20, azim=-40)

        FuncAnimation.__init__(self,
                               fig=self.fig,
                               func=self.plot_update,
                               fargs=(),
                               interval=1000 / plotFPS)
Пример #19
0
 def __init__(self, fig: plt.Figure,
              func: Callable,
              max_index: int,
              min_index: int = 0,
              repeat: bool = True,
              pos=(0.125, 0.92),
              init_func=None,
              fargs=None,
              save_count=None,
              **kwargs):
     """
     :param fig:
     :param func:
     :param max_index: exclusive
     :param min_index: inclusive
     :param repeat:
     :param pos:
     :param init_func:
     :param fargs:
     :param save_count:
     :param kwargs:
     """
     self.i = 0
     self.min = min_index
     self.max = max_index
     self.runs = True
     self.forwards = True
     self.fig = fig
     self.repeat = repeat
     self.func = func
     self.button_oneback = None
     self.button_back = None
     self.button_stop = None
     self.button_forward = None
     self.button_oneforward = None
     self.setup(pos)
     FuncAnimation.__init__(self,
                            self.fig,
                            self.func,
                            frames=self.play(),
                            init_func=init_func,
                            fargs=fargs,
                            save_count=save_count,
                            **kwargs)
Пример #20
0
    def __init__(self, figure, frameCnt, tail=0, fade=False, **kwargs):
        """
        Create an animation of the 'corners' (the centroids of detections).

        *figure*            The matplotlib Figure object
        *frameCnt*          The number of frames for the animation loop
        *tail*              The number of frames to hold older corners
        *fade*              Whether to fade older features (default: False).

        All other :class:`FuncAnimation` kwargs are available.

        TODO: Add usage information.
        """
        self._allcorners = []
        self._flatcorners = []
        self._myframeCnt = frameCnt
        self.fade = fade

        FuncAnimation.__init__(self, figure, self.update_corners, frameCnt, fargs=(self._allcorners, tail), **kwargs)
    def __init__(self,
                 stream,
                 parent=None,
                 width=5,
                 height=4,
                 dpi=100,
                 channels=1,
                 device=1,
                 window=750,
                 interval=25,
                 blocksize=1024,
                 samplerate=48000,
                 downsample=10,
                 subtype='FLOAT'):

        self.stream = stream
        self.length = int(window * samplerate / (1000 * downsample))

        self.plotData = np.zeros((self.length, channels))
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        FigureCanvasQTAgg.__init__(self, fig)
        self.setParent(parent)
        FigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        FigureCanvasQTAgg.updateGeometry(self)
        self.lines = self.axes.plot(self.plotData)
        self.axes.axis((0, len(self.plotData), -1, 1))
        self.axes.set_yticks([0])
        self.axes.yaxis.grid(True)
        self.axes.tick_params(bottom='off',
                              top='off',
                              labelbottom='off',
                              right='off',
                              left='off',
                              labelleft='off')
        fig.tight_layout(pad=0)

        FuncAnimation.__init__(self,
                               fig,
                               self.update_plot,
                               interval=interval,
                               blit=True)
Пример #22
0
    def play(self):
        """
        This function starts the animation.
        """
        # We initiate lines and continuous line here, to avoid the default
        # attribute punctual = True.
        self.lines, self.continuous_lines = self.create_lines_for_particles()

        maximize = False
        if maximize:
            manager = pp.get_current_fig_manager()
            manager.window.showMaximized()

        frames = np.arange(self.frames_start, self.frames_end, self.fps)

        FuncAnimation.__init__(self,
                               self.figure,
                               self.animate,
                               frames=frames,
                               interval=100)
Пример #23
0
    def __init__(self, figure, frameCnt, tail=0, fade=False, **kwargs):
        """
        Create an animation of the 'corners' (the centroids of detections).

        *figure*            The matplotlib Figure object
        *frameCnt*          The number of frames for the animation loop
        *tail*              The number of frames to hold older corners
        *fade*              Whether to fade older features (default: False).

        All other :class:`FuncAnimation` kwargs are available.

        TODO: Add usage information.
        """
        self._allcorners = []
        self._flatcorners = []
        self._myframeCnt = frameCnt
        self.fade = fade

        FuncAnimation.__init__(self,
                               figure,
                               self.update_corners,
                               frameCnt,
                               fargs=(self._allcorners, tail),
                               **kwargs)
Пример #24
0
    def __init__(self):
        self.rotateMat = dict(zip(imu.IMU_List, [np.array([])] * quanIMU))
        self.calMat = dict(zip(imu.IMU_List, [np.identity(3)] * quanIMU))
        self.posAngles = [0] * quanAngles
        self.angleSignal = Communicate()

        # Plot parameters
        bodyLen = 2
        shoulderLen = 1.2
        pelvisLen = 1
        armsLen = 1
        legLen = 1
        textInitPos = [0, 0]

        self.X_Body = [0, 0]
        self.Y_Body = [bodyLen / 2, -bodyLen / 2]
        self.Z_Body = [0, 0]

        self.seg_Shoulder = np.array(
            [[-shoulderLen / 2, self.Y_Body[0], self.Z_Body[0]],
             [shoulderLen / 2, self.Y_Body[0], self.Z_Body[0]]])
        self.seg_Pelvis = np.array(
            [[-pelvisLen / 2, self.Y_Body[1], self.Z_Body[1]],
             [pelvisLen / 2, self.Y_Body[1], self.Z_Body[1]]])

        self.seg_UpperArm_R = np.array([
            self.seg_Shoulder[1, 0], self.seg_Shoulder[1, 1] - armsLen,
            self.seg_Shoulder[1, 2]
        ])
        self.seg_LowerArm_R = np.array([
            self.seg_UpperArm_R[0], self.seg_UpperArm_R[1] - armsLen,
            self.seg_UpperArm_R[2]
        ])
        self.seg_UpperArm_L = np.array([
            self.seg_Shoulder[0, 0], self.seg_Shoulder[0, 1] - armsLen,
            self.seg_Shoulder[0, 2]
        ])
        self.seg_LowerArm_L = np.array([
            self.seg_UpperArm_L[0], self.seg_UpperArm_L[1] - armsLen,
            self.seg_UpperArm_L[2]
        ])

        if (halfBody == 0):
            self.seg_Thigh_R = np.array([
                self.seg_Pelvis[1, 0], self.seg_Pelvis[1, 1] - legLen,
                self.seg_Pelvis[1, 2]
            ])
            self.seg_Calf_R = np.array([
                self.seg_Thigh_R[0], self.seg_Thigh_R[1] - legLen,
                self.seg_Thigh_R[2]
            ])
            self.seg_Thigh_L = np.array([
                self.seg_Pelvis[0, 0], self.seg_Pelvis[0, 1] - legLen,
                self.seg_Pelvis[0, 2]
            ])
            self.seg_Calf_L = np.array([
                self.seg_Thigh_L[0], self.seg_Thigh_L[1] - legLen,
                self.seg_Thigh_L[2]
            ])

        # Figure setting
        self.labelX = [0] * (quanAngles + 2)
        self.labelY = [0] * (quanAngles + 2)
        self.angLabel = []
        self.lines = []
        self.fig = Figure(figsize=(10, 10), dpi=100, tight_layout=True)

        FigureCanvas.__init__(self, self.fig)

        self.axes = self.fig.add_subplot(111, projection='3d')
        self.lines.append(
            self.axes.plot(self.X_Body,
                           self.Y_Body,
                           self.Z_Body,
                           color='seagreen',
                           linewidth=4))
        self.lines.append(
            self.axes.plot(self.X_Body,
                           self.Y_Body,
                           self.Z_Body,
                           'o-',
                           color='red',
                           linewidth=2))

        if (halfBody == 0):
            self.lines.append(
                self.axes.plot(self.X_Body,
                               self.Y_Body,
                               self.Z_Body,
                               'o-',
                               color='blueviolet',
                               linewidth=2))

        for i in range(quanAngles):
            self.angLabel.append(
                self.axes.text2D(textInitPos[0], textInitPos[1], ''))
        self.angLabel.append(
            self.axes.text2D(textInitPos[0], textInitPos[1], 'L'))
        self.angLabel.append(
            self.axes.text2D(textInitPos[0], textInitPos[1], 'R'))

        self.axes.set_xlim3d([-3.0, 3.0])
        self.axes.set_xlabel('X')
        self.axes.set_ylim3d([-3.0, 3.0])
        self.axes.set_ylabel('Y')
        self.axes.set_zlim3d([-3.0, 3.0])
        self.axes.set_zlabel('Z')
        self.axes.view_init(elev=20, azim=-40)

        FuncAnimation.__init__(self,
                               fig=self.fig,
                               func=self.plot_update,
                               fargs=(),
                               interval=1000 / plotFPS)
Пример #25
0
    def __init__(self, fig, files, load_func=None, robust=False,
                       sps=None, time_markers=None,
                       **kwargs) :
        """
        Create an animation object for viewing radar reflectivities.

        *fig*           matplotlib Figure object

        *files*         list of filenames containing the radar data

        *load_func*     The function to use to load the data from a file.
                        Must return a dictionary of 'vals' which contains
                        the 3D numpy array (T by Y by X), 'lats' and 'lons'.

                        It is also optional that the loading function also
                        provides a 'scan_time', either as a
                        :class:`datetime.datetime` object or as an integer
                        or a float representing the number of seconds since
                        UNIX Epoch.

        *robust*        Boolean (default: False) indicating whether or not
                        we can assume all the data will be for the same domain.
                        If you can't assume a consistant domain, then set
                        *robust* to True.  This often happens for PAR data.
                        Note that a robust rendering is slower.

        *sps*           The rate of data time for each second displayed.
                        Default: None (a data frame per display frame).

        *time_markers*  A list of time offsets (in seconds) for each frame.
                        If None, then autogenerate from the event_source
                        and data (unless *sps* is None).

        All other kwargs for :class:`FuncAnimation` are also allowed.

        To use, specify the axes to display the image on using
        :meth:`add_axes`. If no axes are added by draw time, then this class
        will use the current axes by default with no extra keywords.
        """
        #self._rd = files
        #self._loadfunc = load_func if load_func is not None else LoadRastRadar
        self._rd = RadarCache(files, cachewidth=3, load_func=load_func,
                              cyclable=True)

        self.startTime = self.curr_time
        self.endTime = self.prev_time

        self._ims = []
        self._im_kwargs = []
        self._new_axes = []
        #self._curr_time = None
        self._robust = robust
        frames = kwargs.pop('frames', None)
        #if len(files) < frames :
        #    raise ValueError("Not enough data files for the number of frames")
        self.time_markers = None
        FuncAnimation.__init__(self, fig, self.nextframe, #frames=len(self._rd),
                                     init_func=self.firstframe,
                                     **kwargs)

        self._sps = sps

        if time_markers is None :
            # Convert milliseconds per frame to frames per second
            self._fps = 1000.0 / self.event_source.interval
            if self._sps is not None :
                #timelen = (self.endTime - self.startTime)
                timestep = timedelta(0, self._sps / self._fps)

                currTime = self.startTime
                self.time_markers = [currTime]
                while currTime < self.endTime :
                    currTime += timestep
                    self.time_markers.append(currTime)
            else :
                # Don't even bother trying to make playback uniform.
                self.time_markers = None

        else :
            self.time_markers = time_markers
            self._fps = ((len(time_markers) - 1) /
                         ((self.time_markers[-1] -
                           self.time_markers[0]).total_seconds() / self._sps))
            self.event_source.interval = 1000.0 / self._fps
        self.save_count = (len(self.time_markers) if 
                           self.time_markers is not None else
                           len(self._rd))
Пример #26
0
    def __init__(self, anim, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        FuncAnimation.__init__(self,
                               anim.fig,
                               anim,
                               frames=anim.frames,
                               init_func=anim.init,
                               fargs=anim.fargs,
                               save_count=anim.save_count,
                               interval=anim.interval,
                               repeat=anim.repeat,
                               repeat_delay=anim.repeat_delay,
                               blit=False)

        # container = tk.Frame(self)
        # container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # container.grid_rowconfigure(0, weight=1)
        # container.grid_columnconfigure(0, weight=1)

        # self.fig = Figure(figsize=(12, 6), dpi=72)
        # figsize: with, height in inches (25.4mm)
        # dpi: number of pixels per inch

        # self.frames = {}

        # menu = MenuFrame(container, self)
        # self.frames[MenuFrame] = menu
        # menu.grid(row=0, column=0, sticky="nsew")

        # frame = AnimationFrame(container, self, fig)
        # self.frames[AnimationFrame] = frame
        # frame.grid(row=0, column=0, sticky="nsew")

        frame_anim = tk.Frame(self)

        # player = FuncAnimationPlayer(frame_anim, self.fig, None)
        # self.frames[FuncAnimationPlayer] = frame_anim

        frame_anim.grid(row=0, column=0, sticky="nsew")

        # self.show_frame(MenuFrame)
        # self.show_frame(AnimationFrame)
        # self.show_frame(FuncAnimationPlayer)

        canvas = FigureCanvasTkAgg(anim.fig, frame_anim)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        toolbar = NavigationToolbar2Tk(canvas, frame_anim)
        toolbar.update()

        self.scale = ttk.Scale(frame_anim, orient=tk.HORIZONTAL)
        self.scale.pack(fill=tk.BOTH)
        self.button_play = ttk.Button(frame_anim,
                                      text="Play",
                                      command=self.on_button_play)
        self.button_play.pack(side=tk.LEFT)
        self.button_stop = ttk.Button(frame_anim, text="Stop")
        self.button_stop.pack(side=tk.LEFT)
        self.button_back = ttk.Button(frame_anim, text="< Back")
        self.button_back.pack(side=tk.LEFT)
        self.button_forward = ttk.Button(frame_anim, text="Forward >")
        self.button_forward.pack(side=tk.LEFT)
        self.label_step = ttk.Label(frame_anim,
                                    text='0.000/0.000 sec, 0/0 frames')
        self.label_step.pack(side=tk.LEFT, padx=5)
        self.label_stepsize = ttk.Label(frame_anim, text="Step size: Frames: ")
        self.label_stepsize.pack(side=tk.LEFT)
        self.entryvar_steps_frames = tk.StringVar()
        self.entryvar_steps_frames.set("0")
        self.entry_stepsize_frame = ttk.Entry(
            frame_anim, width=6, textvariable=self.entryvar_steps_frames)
        self.entry_stepsize_frame.pack(side=tk.LEFT)
        self.label_stepsize_sec = ttk.Label(frame_anim, text=" Sec: ")
        self.label_stepsize_sec.pack(side=tk.LEFT)
        self.entryvar_steps_sec = tk.StringVar()
        self.entryvar_steps_sec.set("0.000")
        self.entry_stepsize_sec = ttk.Entry(
            frame_anim, width=6, textvariable=self.entryvar_steps_sec)
        self.entry_stepsize_sec.pack(side=tk.LEFT)
Пример #27
0
    def __init__(self, radanim, ax, **kwargs) :
        self._radanim = radanim
        self._ax = ax

        FuncAnimation.__init__(self, radanim._fig, self.update_title,
                                    blit=False, **kwargs)