Пример #1
0
def plotter(data_size=100, wait=0.00001):
    start()

    time = np.arange(0, 1, 1/data_size)
    formatter = EngFormatter(unit='s', places=1)
    # interval
    frame_limits = [0, 1, -10, 10]

    while True:
        data = (yield)

        chart_n = len(data.keys())

        if not chart_n:
            continue

        plt.clf()

        i = 0
        for name in data:
            i += 1
            ax = plt.subplot(chart_n*100 + 10 + i)
            ax.grid()
            ax.set_xlabel(name)
            ax.xaxis.set_major_formatter(formatter)
            ax.axis(frame_limits)
            for ch in data[name]:
                ax.plot(time, data[name][ch])

        plt.draw()
        plt.pause(wait)
 def _plot_histogram(self, data, number_of_devices=1, 
         preamp_timeout=1253):
     if number_of_devices == 0:
         return
     data = np.array(data)
     plt.figure(3)
     plt.ioff()
     plt.get_current_fig_manager().window.wm_geometry("800x550+700+25")
     plt.clf()
     if number_of_devices == 1: 
         plt.hist(data[0,:], bins=preamp_timeout, range=(1, preamp_timeout-1),
             color='b')
     elif number_of_devices == 2:
         plt.hist(data[0,:], bins=preamp_timeout, range=(1, preamp_timeout-1),
             color='r', label='JPM A')
         plt.hist(data[1,:], bins=preamp_timeout, range=(1, preamp_timeout-1),
             color='b', label='JPM B')
         plt.legend()
     elif number_of_devices > 2:
         raise Exception('Histogram plotting for more than two ' +
         'devices is not implemented.')
     plt.xlabel('Timing Information [Preamp Time Counts]')
     plt.ylabel('Counts')
     plt.xlim(0, preamp_timeout)
     plt.draw()
     plt.pause(0.05)
Пример #3
0
def saveani(mesh, plc, data, label, out, cMin=None, cMax=None, logScale=False, cmap=None):
    """
    """
    dpi = 92
    scale = 1
    fig = plt.figure(facecolor="white", figsize=(scale * 800 / dpi, scale * 490 / dpi), dpi=dpi)
    ax = fig.add_subplot(1, 1, 1)

    gci = pg.mplviewer.drawModel(ax, mesh, data=data[0], cMin=cMin, cMax=cMax, cmap=cmap, logScale=logScale)

    cbar = pg.mplviewer.createColorbar(gci, label=label, pad=0.55)
    ax.set_ylabel("Depth [m]")
    ax.set_xlabel("$x$ [m]")

    ticks = ax.yaxis.get_majorticklocs()
    tickLabels = []
    for t in ticks:
        tickLabels.append(str(int(abs(t))))

    ax.set_yticklabels(tickLabels)

    pg.show(plc, axes=ax)

    plt.tight_layout()
    plt.pause(0.001)

    def animate(i):
        print(out + ": Frame:", i, "/", len(data))
        pg.mplviewer.setMappableData(gci, pg.abs(data[i]), cMin=cMin, cMax=cMax, logScale=logScale)
        # plt.pause(0.001)

    createAnimation(fig, animate, int(len(data)), dpi, out)
Пример #4
0
    def numpyImplicit(self, tmin, tmax,nPlotInc):
        g = self.grid
        k = self.k         #Diffusivity
        r = self.r         #Numerical Fourier number
        theta =self.theta  #Parameter for implicitness: theta=0.5 Crank-Nicholson, theta=1.0 fully implicit
        u, x, dx  = g.u, g.x, g.dx
        xmin, xmax = g.xmin, g.xmax
        
        dt=r*dx**2/k     #Compute timestep based on Fourier number, dx and diffusivity
        print 'timestep = ',dt

        m=round((tmax-tmin)/dt) # Number of temporal intervals
        print 'm = ',m
        print 'implicit solver with r=',r
        print 'and theta = ',theta
        time=np.linspace(tmin,tmax,m)

        #Create matrix for sparse solver. Solve for interior values only (nx-1)
        diagonals=np.zeros((3,g.nx-1))   
        diagonals[0,:] = -r*theta                       #all elts in first row is set to 1
        diagonals[1,:] = 1+2.0*r*theta  
        diagonals[2,:] = -r*theta 
        As = sc.sparse.spdiags(diagonals, [-1,0,1], g.nx-1, g.nx-1,format='csc') #sparse matrix instance

        #Crete rhs array
        d=np.zeros((g.nx-1,1),'d')
        
#        nPlotInc=5 #output every nPlotInc iteration
        i = 0        #iteration counter

                #Plot initial solution
        fig = plt.figure()
        ax=fig.add_subplot(111)
        Curve, = ax.plot( x, u[:], '-')
        ax.set_xlim([xmin,xmax])
#        ax.set_ylim([umin,umax])
        plt.xlabel('x')
        plt.ylabel('Velocity')

        plt.ion()
        plt.show()

        #Advance in time an solve tridiagonal system for each t in time
        for t in time:
            i+=1
            d[:] = u[1:-1]+r*(1-theta)*(u[0:-2]-2*u[1:-1]+u[2:])  
            d[0] += r*theta*u[0]
            w = sc.sparse.linalg.spsolve(As,d) #theta=sc.linalg.solve_triangular(A,d)
            u[1:-1] = w[:,None]
           
            if (np.mod(i,nPlotInc)==0): #output every nPlotInc iteration
                Curve.set_ydata(u)
                plt.pause(.005)
                plt.title( 'step = %3d; t = %f' % (i,t ) )
        
        g.u=u
        
        plt.pause(1)
        plt.ion()
        plt.close()
Пример #5
0
def plot_sample(m):
    for seq_to_plot in range(N_experiments):
        fig = plt.figure(seq_to_plot)
        fig.clf()
        if plot == 'states':
            axs = plot_latent_compartment_state(t,
                                                true_model.data_sequences[seq_to_plot].latent,
                                                true_model.data_sequences[seq_to_plot].states,
                                                true_model.population.neurons[0].compartments[0])
            plot_latent_compartment_state(t,
                                          m.data_sequences[seq_to_plot].latent,
                                          m.data_sequences[seq_to_plot].states,
                                          m.population.neurons[0].compartments[0],
                                          axs=axs, colors=['r'])
        elif plot == 'currents':
            axs = plot_latent_compartment_V_and_I(t,
                                                  true_model.data_sequences[seq_to_plot],
                                                  true_model.population.neurons[0].compartments[0],
                                                  true_model.observation.observations[0])
            plot_latent_compartment_V_and_I(t,
                                            m.data_sequences[seq_to_plot],
                                            m.population.neurons[0].compartments[0],
                                            m.observation.observations[0],
                                          axs=axs, colors=['r'])
        fig.suptitle('Iteration: %d' % i['i'])
    i['i'] += 1
    plt.pause(0.1)
Пример #6
0
def main():
    conn = krpc.connect()
    vessel = conn.space_center.active_vessel
    streams = init_streams(conn,vessel)
    print vessel.control.throttle
    plt.axis([0, 100, 0, .1])
    plt.ion()
    plt.show()

    t0 = time.time()
    timeSeries = []
    vessel.control.abort = False
    while not vessel.control.abort:

        t_now = time.time()-t0
        tel = Telemetry(streams,t_now)
        timeSeries.append(tel)
        timeSeriesRecent = timeSeries[-40:]

        plt.cla()
        plt.semilogy([tel.t for tel in timeSeriesRecent], [norm(tel.angular_velocity) for tel in timeSeriesRecent])
        #plt.semilogy([tel.t for tel in timeSeriesRecent[1:]], [quat_diff_test(t1,t2) for t1,t2 in zip(timeSeriesRecent,timeSeriesRecent[1:])])
        #plt.axis([t_now-6, t_now, 0, .1])
        plt.draw()
        plt.pause(0.0000001)
        #time.sleep(0.0001)

    with open('log.json','w') as f:
        f.write(json.dumps([tel.__dict__ for tel in timeSeries],indent=4))

    print 'The End'
def show_trajectory(target, xc, yc):  # pragma: no cover
    plt.clf()
    plot_arrow(target.x, target.y, target.yaw)
    plt.plot(xc, yc, "-r")
    plt.axis("equal")
    plt.grid(True)
    plt.pause(0.1)
def catchPotentiometry(ser, PGA_gain):
    i = 0
    voltage = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    t = ["0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0","0:0"]
    pH = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    
    while True:
        line = ser.readline()
        if line == b'@DONE\n':
            print('Experiment complete')
            break
        elif line == b'B\n':
            pass
        else:
            try:
                s, ms, v = struct.unpack('<HHix', line)
                v = ADCtomV(v, PGA_gain)
                voltage.append(v)
                pH.append(0.0169*v+6.9097)
                t.append("{}:{}".format(s,ms))
                plt.clf()
                plt.plot(pH[-50:-1])
                plt.draw()
                plt.pause(0.00000001)
            except:
                pass
Пример #9
0
def plot_data(x, t):
    plt.figure()
    plt.scatter(x, t, edgecolor='b', color='w', marker='o')
    plt.xlabel('x')
    plt.ylabel('t')
    plt.title('Data')
    plt.pause(.1)
def test_pf():

    #seed(1234)
    N = 10000
    R = .2
    landmarks = [[-1, 2], [20,4], [10,30], [18,25]]
    #landmarks = [[-1, 2], [2,4]]

    pf = RobotLocalizationParticleFilter(N, 20, 20, landmarks, R)

    plot_pf(pf, 20, 20, weights=False)

    dt = .01
    plt.pause(dt)

    for x in range(18):

        zs = []
        pos=(x+3, x+3)

        for landmark in landmarks:
            d = np.sqrt((landmark[0]-pos[0])**2 +  (landmark[1]-pos[1])**2)
            zs.append(d + randn()*R)

        pf.predict((0.01, 1.414), (.2, .05))
        pf.update(z=zs)
        pf.resample()
        #print(x, np.array(list(zip(pf.particles, pf.weights))))

        mu, var = pf.estimate()
        plot_pf(pf, 20, 20, weights=False)
        plt.plot(pos[0], pos[1], marker='*', color='r', ms=10)
        plt.scatter(mu[0], mu[1], color='g', s=100)
        plt.tight_layout()
        plt.pause(dt)
Пример #11
0
  def write(self, timestamps, actualValues, predictedValues,
            predictionStep=1):

    assert len(timestamps) == len(actualValues) == len(predictedValues)

    # We need the first timestamp to initialize the lines at the right X value,
    # so do that check first.
    if not self.linesInitialized:
      self.initializeLines(timestamps)

    for index in range(len(self.names)):
      self.dates[index].append(timestamps[index])
      self.convertedDates[index].append(date2num(timestamps[index]))
      self.actualValues[index].append(actualValues[index])
      self.predictedValues[index].append(predictedValues[index])

      # Update data
      self.actualLines[index].set_xdata(self.convertedDates[index])
      self.actualLines[index].set_ydata(self.actualValues[index])
      self.predictedLines[index].set_xdata(self.convertedDates[index])
      self.predictedLines[index].set_ydata(self.predictedValues[index])

      self.graphs[index].relim()
      self.graphs[index].autoscale_view(True, True, True)

    plt.draw()
    plt.legend(('actual','predicted'), loc=3)
    plt.pause(0.00000001)
def vis(i):
    s = 1.
    u = 0.
    zs = np.linspace(-1, 1, 500).astype('float32')[:, np.newaxis]
    xs = np.linspace(-5, 5, 500).astype('float32')[:, np.newaxis]
    ps = gaussian_likelihood(xs, 1.)

    gs = generator.predict(zs)
    preal = decoder.predict(xs)
    kde = gaussian_kde(gs.flatten())

    plt.clf()
    plt.plot(xs, ps, '--', lw=2)
    plt.plot(xs, kde(xs.T), lw=2)
    plt.plot(xs, preal, lw=2)
    plt.xlim([-5., 5.])
    plt.ylim([u, s])
    plt.ylabel('Prob')
    plt.xlabel('x')
    plt.legend(['P(data)', 'G(z)', 'D(x)'])
    plt.title('GAN learning gaussian')
    fig.canvas.draw()
    plt.show(block=False)
    if i % 100 == 0:
        plt.savefig('current.png')
    plt.pause(0.01)
Пример #13
0
def show_vector(dx, dy, arr = None, w=None, h=None, skip=6, holdon=False):
    if w is None or h is None:
        h = dx.shape[0]
        w = dx.shape[1]

    import matplotlib.pyplot as plt
    x, y = np.meshgrid(np.linspace(0, w, w), np.linspace(0, h, h))

    ax = plt.axes(xlim=(0, w), ylim=(0, h))
    line, = plt.plot(0,0,'ro')
    plt.ion()
    plt.ylim([0, h])
    if skip is None:
        ax.quiver(x, y, dx, dy)
    else:
        skip = (slice(None, None, skip), slice(None, None, skip))
        ax.quiver(x[skip], y[skip], dx[skip], dy[skip])
        if arr is not None:
            plt.imshow(arr, cmap=plt.cm.Greys_r)


    if holdon is True:
        plt.draw()
        plt.pause(0.0001)
        return line, plt
    else:
        plt.show()
Пример #14
0
    def display_data(self):
        try:
            while not self.end_sampling:
                mxyz=self.mxyz
                self.plt_xy.set_xdata(mxyz[:,0])
                self.plt_xy.set_ydata(mxyz[:,1])
                self.plt_zy.set_xdata(mxyz[:,2])
                self.plt_zy.set_ydata(mxyz[:,1])
                self.plt_xz.set_xdata(mxyz[:,0])
                self.plt_xz.set_ydata(mxyz[:,2])

                self.point_xy.set_xdata(mxyz[-1:,0])
                self.point_xy.set_ydata(mxyz[-1:,1])
                self.point_zy.set_xdata(mxyz[-1:,2])
                self.point_zy.set_ydata(mxyz[-1:,1])
                self.point_xz.set_xdata(mxyz[-1:,0])
                self.point_xz.set_ydata(mxyz[-1:,2])
                
                print len(mxyz)
                plt.pause(0.001)
        except KeyboardInterrupt:
            pass
        
        self.end_sampling=True
        self.sample_thread.join()
        return
Пример #15
0
def plot(model, div = 8):
    ecg, diff, filt = preprocess(div)

    # e = np.atleast_2d(eorig).T
    # sube = np.atleast_2d(eorig[0:3000]).T
    e = diff[:10000].reshape(-1,1)
    # e = np.column_stack((diff,filt))
    sube = e[:3000]

    plt.clf()
    plt.subplot(411)
    plt.imshow(model.transmat_,interpolation='nearest', shape=model.transmat_.shape)
    ax = plt.subplot(412)
    plt.plot(e[0:3000])
    plt.plot(ecg[:3000])
    # plt.imshow(model.emissions,interpolation='nearest', shape=model.emissions.shape)
    plt.subplot(413, sharex = ax)
    model.algorithm = 'viterbi'
    plt.plot(model.predict(sube))
    model.algorithm = 'map'
    plt.plot(model.predict(sube))
    plt.subplot(414, sharex = ax)
    samp = model.sample(3000)[0]
    plt.plot(samp)
    plt.plot(np.cumsum(samp[:,0]))
    plt.show()
    plt.pause(1)
Пример #16
0
    def view(key,reciprocals=None,show=True,suspend=False,save=True,name='KMap'):
        '''
        View the KMap.

        Parameters
        ----------
        key : 'L','S','H'
            The key of the database of KMap.
        reciprocals : iterable of 1d ndarray, optional
            The translation vectors of the reciprocal lattice.
        show : logical, optional
            True for showing the view. Otherwise not.
        suspend : logical, optional
            True for suspending the view. Otherwise not.
        save : logical, optional
            True for saving the view. Otherwise not.
        name : str, optional
            The title and filename of the view. Otherwise not.
        '''
        assert key in KMap.database
        if key=='L': reciprocals=np.asarray(reciprocals) or np.array([1.0])*2*np.pi
        elif key=='S': reciprocals=np.asarray(reciprocals) or np.array([[1.0,0.0],[0.0,1.0]])*2*np.pi
        elif key=='H': reciprocals=np.asarray(reciprocals) or np.array([[1.0,-1.0/np.sqrt(3.0)],[0,-2.0/np.sqrt(3.0)]])*2*np.pi
        plt.title(name)
        plt.axis('equal')
        for tag,position in KMap.database[key].items():
            if '1' not in tag:
                coords=reciprocals.T.dot(position)
                assert len(coords)==2
                plt.scatter(coords[0],coords[1])
                plt.text(coords[0],coords[1],'%s(%s1)'%(tag,tag) if len(tag)==1 else tag,ha='center',va='bottom',color='green',fontsize=14)
        if show and suspend: plt.show()
        if show and not suspend: plt.pause(1)
        if save: plt.savefig('%s.png'%name)
        plt.close()
Пример #17
0
    def pause(interval):
        """Pause for `interval` seconds, letting the GUI flush its event queue.

        @note This is a *necessary* function to be defined if these globals are
        not used!
        """
        plt.pause(interval)
Пример #18
0
def plot_func(play, stats):
    generation = stats["generation"]
    best = stats["generation_best"]
    every = play.config["live_plot"].get("every", 100)

    if generation == 0:
        plt.figure(figsize=(10, 8))

    if (generation % every) == 0:
        plt.clf()

        # create graph
        graph = nx.DiGraph()
        traverse_tree(best.root, graph)
        labels = dict((n, d["label"]) for n, d in graph.nodes(data=True))

        pos = nx.graphviz_layout(graph, prog='dot')
        nx.draw(
            graph,
            pos,
            with_labels=True,
            labels=labels,
            arrows=False,
            node_shape=None
        )

        # plot graph
        plt.draw()
        plt.pause(0.0001)  # very important else plot won't be displayed
 def run (self, gamma, ELA, dt, dx):
     for t in range(len(self.timestep)):
         self.dqdx=glacier_model.dqdx_func(dx)
         self.dhdt=glacier_model.b_func(gamma, ELA)-self.dqdx
         self.h+=self.dhdt*dt
         for i in range(0, len(self.h)): #make sure bottom limit of z does not go below zb
             if self.h[i]<0:
                 self.h[i]=0
         self.z=self.h+self.zb
         if self.timestep[t] % 10 ==0:
             self.figure.clear()
             plt.title('Glacier Accumulation & Ablation Over Time')
             plt.xlabel('Distance (m)')
             plt.ylabel('Elevation (m)')
             self.figure.set_ylim(2000, 4000) #make sure y axis doesn't change
             self.figure.set_xlim(0, 15000) #make sure x axis doesn't change
             plt.text(12000, 3500, 'Time [yrs]: %d\nELA=%d m' % (self.timestep[t], ELA))
             self.figure.plot(self.spacestep, self.z, label='Glacier Height', color='b')  
             self.figure.plot(self.spacestep, self.zb, label='Bedrock Height', color='k')
             self.figure.plot(self.spacestep, (np.zeros(len(self.spacestep))+ELA),  '--r', label='ELA')
             self.figure.fill_between(self.spacestep, self.zb, self.z, color ='b', interpolate=True)
             self.figure.fill_between(self.spacestep, 0, self.zb, color='k', interpolate=True)
             self.figure.legend()
             plt.pause(0.00001)
     plt.ioff()    
Пример #20
0
def streamVisionSensor(visionSensorName,clientID,pause=0.0001):
    #Get the handle of the vision sensor
    res1,visionSensorHandle=vrep.simxGetObjectHandle(clientID,visionSensorName,vrep.simx_opmode_oneshot_wait)
    #Get the image
    res2,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_streaming)
    #Allow the display to be refreshed
    plt.ion()
    #Initialiazation of the figure
    time.sleep(0.5)
    res,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_buffer)
    im = I.new("RGB", (resolution[0], resolution[1]), "white")
    #Give a title to the figure
    fig = plt.figure(1)    
    fig.canvas.set_window_title(visionSensorName)
    #inverse the picture
    plotimg = plt.imshow(im,origin='lower')
    #Let some time to Vrep in order to let him send the first image, otherwise the loop will start with an empty image and will crash
    time.sleep(1)
    while (vrep.simxGetConnectionId(clientID)!=-1): 
        #Get the image of the vision sensor
        res,resolution,image=vrep.simxGetVisionSensorImage(clientID,visionSensorHandle,0,vrep.simx_opmode_buffer)
        #Transform the image so it can be displayed using pyplot
        image_byte_array = array.array('b',image)
        im = I.frombuffer("RGB", (resolution[0],resolution[1]), image_byte_array, "raw", "RGB", 0, 1)
        #Update the image
        plotimg.set_data(im)
        #Refresh the display
        plt.draw()
        #The mandatory pause ! (or it'll not work)
        plt.pause(pause)
    print 'End of Simulation'
Пример #21
0
    def callback(params):
        print("Log likelihood {}".format(-objective(params)))
        plt.cla()
        print(params)
        # Show posterior marginals.
        plot_xs = np.reshape(np.linspace(-7, 7, 300), (300,1))
        pred_mean, pred_cov = predict(params, X, y, plot_xs)
        marg_std = np.sqrt(np.diag(pred_cov))
        ax.plot(plot_xs, pred_mean, 'b')
        ax.fill(np.concatenate([plot_xs, plot_xs[::-1]]),
                np.concatenate([pred_mean - 1.96 * marg_std,
                               (pred_mean + 1.96 * marg_std)[::-1]]),
                alpha=.15, fc='Blue', ec='None')

        # Show samples from posterior.
        rs = npr.RandomState(0)
        sampled_funcs = rs.multivariate_normal(pred_mean, pred_cov, size=10)
        ax.plot(plot_xs, sampled_funcs.T)

        ax.plot(X, y, 'kx')
        ax.set_ylim([-1.5, 1.5])
        ax.set_xticks([])
        ax.set_yticks([])
        plt.draw()
        plt.pause(1.0/60.0)
Пример #22
0
def main( steps=40 ):

  data = zeros((40,2))
  data[:,0] = 3
  data[4:9,1] = pi/4
  #data[:,1] = .3

  print (data)

  sim = RatSLAM(data=data,shape=POSE_SIZE) 

  fig = plt.figure()
  ax = fig.add_subplot(111, projection='3d')
  ax.set_xlim3d([0, POSE_SIZE[0]])
  ax.set_ylim3d([0, POSE_SIZE[1]])
  ax.set_zlim3d([0, POSE_SIZE[2]])
  ax.hold(False)
  plt.ion()
  plt.show()

  for s in xrange( steps ):
    #print ("Step: ",s)
    sim.step()

    pc = sim.pcn.posecells
    pc_index = nonzero(pc>.002)
    pc_value = pc[pc_index] * 100
    ax.scatter(pc_index[0],pc_index[1],pc_index[2],s=pc_value)
    ax.set_xlim3d([0, POSE_SIZE[0]])
    ax.set_ylim3d([0, POSE_SIZE[1]])
    ax.set_zlim3d([0, POSE_SIZE[2]])
    plt.pause(.01)
Пример #23
0
def view_patches(Yr, A, C, b, f, d1, d2):
    """
    view spatial and temporal components
    """

    nr, T = C.shape
    nA2 = np.sum(np.array(A.todense()) ** 2, axis=0)
    Y_r = np.array(spdiags(1 / nA2, 0, nr, nr) * (A.T * np.matrix(Yr - b[:, np.newaxis] * f[np.newaxis])) + C)
    fig = plt.figure()

    for i in range(nr + 1):
        if i < nr:
            ax1 = fig.add_subplot(2, 1, 1)
            plt.imshow(np.reshape(np.array(A.todense())[:, i], (d1, d2), order="F"), interpolation="None")
            ax1.set_title("Spatial component " + str(i + 1))
            ax2 = fig.add_subplot(2, 1, 2)
            plt.plot(np.arange(T), np.squeeze(np.array(Y_r[i, :])))
            plt.plot(np.arange(T), np.squeeze(np.array(C[i, :])))
            ax2.set_title("Temporal component " + str(i + 1))
            ax2.legend(labels=["Filtered raw data", "Inferred trace"])
            plt.pause(4)
            # plt.waitforbuttonpress()
            fig.delaxes(ax2)
        else:
            ax1 = fig.add_subplot(2, 1, 1)
            plt.imshow(np.reshape(b, (d1, d2), order="F"), interpolation="None")
            ax1.set_title("Spatial background background")
            ax2 = fig.add_subplot(2, 1, 2)
            plt.plot(np.arange(T), np.squeeze(np.array(f)))
            ax2.set_title("Temporal background")
def main():
    print("Start informed rrt star planning")

    # create obstacles
    obstacleList = [
        (5, 5, 0.5),
        (9, 6, 1),
        (7, 5, 1),
        (1, 5, 1),
        (3, 6, 1),
        (7, 9, 1)
    ]

    # Set params
    rrt = InformedRRTStar(start=[0, 0], goal=[5, 10],
                          randArea=[-2, 15], obstacleList=obstacleList)
    path = rrt.InformedRRTStarSearch(animation=show_animation)
    print("Done!!")

    # Plot path
    if show_animation:
        rrt.drawGraph()
        plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
        plt.grid(True)
        plt.pause(0.01)
        plt.show()
Пример #25
0
    def plotdata(self,new_values):
        # is  a valid message struct
        #print new_values

        self.x.append( float(new_values[0]))
        self.y.append( float(new_values[1]))
        self.z.append( float(new_values[2]))

        self.plotx.append( self.plcounter )

        self.line1.set_ydata(self.x)
        self.line2.set_ydata(self.y)
        self.line3.set_ydata(self.z)

        self.line1.set_xdata(self.plotx)
        self.line2.set_xdata(self.plotx)
        self.line3.set_xdata(self.plotx)

        self.fig.canvas.draw()
        plt.pause(0.0001)

        self.plcounter = self.plcounter+1

        if self.plcounter > self.rangeval:
          self.plcounter = 0
          self.plotx[:] = []
          self.x[:] = []
          self.y[:] = []
          self.z[:] = []
Пример #26
0
def test_mge_vcirc():
    """
    Usage example for mge_vcirc()
    It takes a fraction of a second on a 2GHz computer
    
    """    
    import matplotlib.pyplot as plt
    
    # Realistic MGE galaxy surface brightness
    # 
    surf = np.array([39483, 37158, 30646, 17759, 5955.1, 1203.5, 174.36, 21.105, 2.3599, 0.25493])
    sigma = np.array([0.153, 0.515, 1.58, 4.22, 10, 22.4, 48.8, 105, 227, 525])
    qObs = np.array([0.57, 0.57, 0.57, 0.57, 0.57, 0.57, 0.57, 0.57, 0.57, 0.57])
    
    inc = 60. # Inclination in degrees
    mbh = 1e6 # BH mass in solar masses
    distance = 10. # Mpc
    rad = np.logspace(-1,2,25) # Radii in arscec where Vcirc has to be computed
    ml = 5.0 # Adopted M/L ratio
    
    vcirc = mge_vcirc(surf*ml, sigma, qObs, inc, mbh, distance, rad)
    
    plt.clf()
    plt.plot(rad, vcirc, '-o')
    plt.xlabel('R (arcsec)')
    plt.ylabel(r'$V_{circ}$ (km/s)')
    plt.pause(0.01)
Пример #27
0
 def start_display(self):
     # improve spacing between graphs 
     self._fig.tight_layout()
     #  Do not forget this call, it displays graphs, plt.draw(),  
     #  self._fig.canvas.draw(), cannot replace it 
     plt.pause(0.001)   
     self.update_display()  
    def visCC(self):
        """fix me.... :/"""

        """to visualize the neighbours"""
        if isVisualize:
            fig888 = plt.figure()
            ax     = plt.subplot(1,1,1)

        """ visualization, see if connected components make sense"""
        s111,c111 = connected_components(sparsemtx) #s is the total CComponent, c is the label
        color     = np.array([np.random.randint(0,255) for _ in range(3*int(s111))]).reshape(s111,3)
        fig888    = plt.figure(888)
        ax        = plt.subplot(1,1,1)
        # im = plt.imshow(np.zeros([528,704,3]))
        for i in range(s111):
            ind = np.where(c111==i)[0]
            print ind
            for jj in range(len(ind)):
                startlimit = np.min(np.where(x[ind[jj],:]!=0))
                endlimit = np.max(np.where(x[ind[jj],:]!=0))
                # lines = ax.plot(x[ind[jj],startlimit:endlimit], y[ind[jj],startlimit:endlimit],color = (0,1,0),linewidth=2)
                lines = ax.plot(x[ind[jj],startlimit:endlimit], y[ind[jj],startlimit:endlimit],color = (color[i-1].T)/255.,linewidth=2)
                fig888.canvas.draw()
            plt.pause(0.0001) 
        plt.show()
def animatepoints(t, order, theta):
    fig, (ax, ax2) = plt.subplots(1, 2, subplot_kw=dict(polar=True))
    ax2 = plt.subplot(1, 2, 2, polar=False)
    ax.set_yticklabels([])
    ax.set_title('Individual Neuron Simulation')
    ax2.set_title('Order Parameter Trajectory')
    r = [0.98]*len(theta[0])
    pausetime = (t[1]-t[0])/1000
    for i in range(0, len(t)):
        if i == 0:
            points, = ax.plot(theta[i], r, color='r', marker='.', linestyle='None')
            ax.set_rmax(1.0)
            ax.grid = True
            unpackorder = [[order[0][0]], [order[0][1]]]
            orderpoints, = ax2.plot(unpackorder[0], unpackorder[1], color='b')
            ax2.set_ylim([-1, 1])
            ax2.set_xlim([-1, 1])
        else:
            points.set_data(theta[i], r)
            unpackorder[0].append(order[i][0])
            unpackorder[1].append(order[i][1])
            orderpoints.set_data(unpackorder[0], unpackorder[1])
#        print(unpackorder)
        plt.pause(pausetime)
    plt.show()
    print('Plotting Done.')
Пример #30
0
def rotate_window(maze, pt, yaw, window_size=(64, 64)):
    wall, route = np.max(maze), 0
    h_maze, w_maze = maze.shape
    #
    x, y = pt
    h_slide, w_slide = window_size
    # expected rect
    top, bottom, left, right = y - h_slide // 2, y + h_slide // 2, x - w_slide // 2, x + w_slide // 2
    # valid rect
    v_top, v_bottom, v_left, v_right = max(top, 0), min(bottom, h_maze), max(left, 0), min(right, w_maze)
    # generate slide window
    sw = np.ones([h_slide, w_slide], dtype=np.float32) * wall
    sw[v_top - top:h_slide - bottom + v_bottom, v_left - left:w_slide - right + v_right] = \
        maze[v_top:v_bottom,v_left:v_right]
    # rotation
    rr, cc = skimage.draw.circle(31, 31, 32)
    # circle = np.zeros_like(sw, dtype=np.bool)
    # circle[rr, cc] = True
    # circle = np.bitwise_not(circle)
    # sw = np.multiply(sw, circle)
    rw = np.ones_like(sw)
    rw[rr, cc] = sw[rr, cc]
    rw = skimage.transform.rotate(rw, yaw)
    #
    plt.ioff()
    plt.imshow(rw, cmap='Greys')
    plt.draw()
    plt.pause(0.1)
Пример #31
0
def main():
    print(__file__ + " start!!")

    time = 0.0
    # Q1_1, yaw_rate= 0.2
    # Define landmark positions [x, y]
    # N = 5  # number of landmarks
    # R1 = 3.5 # radius
    # R2 = 2
    # Landmarks = np.array([[0.0, 5.0]])
    # for i in range(N):
    #     Landmarks = np.append(Landmarks,
    #                           np.array([[0.0 + R1 * math.cos(2 * i * math.pi / N),
    #                                      5.0 + R1 * math.sin(2 * i * math.pi / N)]]),
    #                           axis=0)
    # for i in range(N):
    #     Landmarks = np.append(Landmarks,
    #                               np.array([[0.0 + R2 * math.cos((2 * i + 1) * math.pi / N ),
    #                                          5.0 + R2 * math.sin((2 * i + 1)  * math.pi / N + 0.1)]]),
    #                               axis=0)
    # Landmarks = Landmarks[1:,:]


    # # # Q1_2, yaw_rate= 0.1
    # # # Define landmark positions [x, y]
    # N = 9 # number of landmarks
    # R1 = 8 # radius
    # R2= 13
    # Landmarks = np.array([[0.0, 10.0]])
    # Landmarks = np.array([[0.0, 5.0]])
    # for i in range(N):
    #     Landmarks = np.append(Landmarks,
    #                           np.array([[0.0 + R1 * math.cos(2 * i * math.pi / N),
    #                                      10.0 + R1 * math.sin(2 * i * math.pi / N)]]),
    #                           axis=0)
    # for i in range(N):
    #     Landmarks = np.append(Landmarks,
    #                               np.array([[0.0 + R2 * math.cos((2 * i + 1) * math.pi / N ),
    #                                          10.0 + R2 * math.sin((2 * i + 1)  * math.pi / N + 0.1)]]),
    #                               axis=0)
    # Landmarks = Landmarks[1:,:]

    # Q1_3, yaw_rate= 0.1
    # Define landmark positions [x, y]
    N = 3 # number of landmarks
    R1 = 1 # radius
    R2= 13
    Landmarks = np.array([[0.0, 5.0]])
    # for i in range(N):
    #     Landmarks = np.append(Landmarks,
    #                           np.array([[0.0 + R1 * math.cos(2 * i * math.pi / N),
    #                                      0.0 + R1 * math.sin(2 * i * math.pi / N)]]),
    #                           axis=0)
    # Landmarks = Landmarks[1:,:]

    # Init state vector [x y yaw]' and covariance for Kalman
    xEst = np.zeros((STATE_SIZE, 1))
    PEst = initPEst

    # Init true state for simulator
    xTrue = np.zeros((STATE_SIZE, 1))

    # Init dead reckoning (sum of individual controls)
    xDR = np.zeros((STATE_SIZE, 1))

    # Init history
    hxEst = xEst
    hxTrue = xTrue
    hxDR = xTrue
    hxError = np.abs(xEst-xTrue)  # pose error
    hxVar = np.sqrt(np.diag(PEst[0:STATE_SIZE,0:STATE_SIZE]).reshape(3,1))  #state std dev


    # counter for plotting
    count = 0

    while  time <= SIM_TIME:
        count = count + 1
        time += DT

        # Simulate motion and generate u and y
        uTrue = calc_input()
        xTrue, y, xDR, u = observation(xTrue, xDR, uTrue, Landmarks)

        xEst, PEst = ekf_slam(xEst, PEst, u, y)
        # print(xEst.shape)

        # store data history
        hxEst = np.hstack((hxEst, xEst[0:STATE_SIZE]))
        hxDR = np.hstack((hxDR, xDR))
        hxTrue = np.hstack((hxTrue, xTrue))
        err = np.abs(xEst[0:STATE_SIZE]-xTrue)
        err[2] = pi_2_pi(err[2])
        hxError = np.hstack((hxError,err))
        hxVar = np.hstack((hxVar,np.sqrt(np.diag(PEst[0:STATE_SIZE,0:STATE_SIZE]).reshape(3,1))))


        if show_animation and count%15==0:
            # for stopping simulation with the esc key.
            plt.gcf().canvas.mpl_connect('key_release_event',
                    lambda event: [exit(0) if event.key == 'escape' else None])
            
            ax1.cla()
            
            # Plot true landmark and trajectory
            ax1.plot(Landmarks[:, 0], Landmarks[:, 1], "*k")
            ax1.plot(hxTrue[0, :], hxTrue[1, :], "-k", label="True")

            # Plot odometry trajectory
            ax1.plot(hxDR[0, :], hxDR[1, :], "-g", label="Odom")

            # Plot estimated trajectory, pose and landmarks
            ax1.plot(hxEst[0, :], hxEst[1, :], "-r", label="EST")
            ax1.plot(xEst[0], xEst[1], ".r")
            ax1.legend()
            plot_covariance_ellipse(xEst[0: STATE_SIZE],
                                    PEst[0: STATE_SIZE, 0: STATE_SIZE], ax1, "--r")

            for i in range(calc_n_lm(xEst)):
                id = STATE_SIZE + i * 2
                ax1.plot(xEst[id], xEst[id + 1], "xg")
                plot_covariance_ellipse(xEst[id:id + 2],
                                        PEst[id:id + 2, id:id + 2], ax1, "--g")



            ax1.axis([-12, 12, -2, 22])
            ax1.grid(True)
            
            # plot errors curves
            ax3.plot(hxError[0, :],'b')
            ax3.plot(3.0 * hxVar[0, :],'r')
            ax3.plot(-3.0 * hxVar[0, :],'r')
            ax3.set_ylabel('x')
            
            ax4.plot(hxError[1, :],'b')
            ax4.plot(3.0 * hxVar[1, :],'r')
            ax4.plot(-3.0 * hxVar[1, :],'r')
            ax4.set_ylabel('y')

            ax5.plot(hxError[2, :],'b')
            ax5.plot(3.0 * hxVar[2, :],'r')
            ax5.plot(-3.0 * hxVar[2, :],'r')
            ax5.set_ylabel(r"$\theta$")

            # plt.pause(0.001)
            plt.pause(2)


    plt.savefig('EKFSLAM.png')

    tErrors = np.sqrt(np.square(hxError[0, :]) + np.square(hxError[1, :]))
    oErrors = np.sqrt(np.square(hxError[2, :]))
    print("Mean (var) translation error : {:e} ({:e})".format(np.mean(tErrors), np.var(tErrors)))
    print("Mean (var) rotation error : {:e} ({:e})".format(np.mean(oErrors), np.var(oErrors)))    # keep window open
    print("Press Q in figure to finish...")
    plt.show()
        evaluation_data.to(device).float())

    for i in range(128):

        plt.ion()
        plt.subplot(211)
        plt.plot(validation_label[i].numpy())
        plt.title("the change of temperature in one hour")
        plt.ylabel("correlation coefficient")
        plt.xlabel("measurement")
        plt.subplot(212)
        plt.plot(decoded_data_eva.data.to('cpu').detach().numpy()[i])
        plt.title("the change of predicted temperature in one hour")
        plt.ylabel("correlation coefficient")
        plt.xlabel("measurement")
        plt.pause(2)
        # plt.savefig('D:/Research/DeepLearning/Results/autoencoder/predict_temperature' + str(i) +'.png')
        plt.close()

    plt.figure(2)
    plt.plot(loss_record)
    plt.title("the change of loss in each epoch")
    plt.xlabel("epoch")
    plt.ylabel("loss")
    plt.show()

    plt.figure(3)
    plt.plot(correlationCoefficientList_eva)
    plt.title("correlation coefficient between input and output in one bach")
    plt.xlabel("measurement")
    plt.ylabel("correlation coefficient")
Пример #33
0
        return xx

net = Net(n_feature=1, n_hidden=10, n_output=1)  # define network
print(net)  # net architecture

optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()  # this is for regression mean square error loss

plt.ion()
plt.show()

for t in range(100):
    prediction = net(x)     # input x and predict based on x

    loss = loss_func(prediction, y)     # must be (1. nn output, 2. target)

    optimizer.zero_grad()  # clear gradients for next train
    loss.backward()        # back propagation, compute gradients
    optimizer.step()       # apply gradients

    if t % 5 == 0:
        # plot and show learning process
        plt.cla()
        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
        plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()
Пример #34
0
            fontsize=15,
            transform=plt.gca().transAxes,
        )

        plt.plot(fitx, p(fitx))

    plt.errorbar(iters, energy, yerr=sigma, color="red")
    plt.axhline(y=exact,
                xmin=0,
                xmax=iters[-1],
                linewidth=2,
                color="k",
                label="Exact")

    plt.legend(frameon=False)
    plt.pause(1)
    plt.savefig('bh.png')
    plt.draw()

# plt.savefig('acc_plot_optimizers.png')
# plt.show()

# iters = []
# energy = []
# sigma = []
# evar = []
#
# data = json.load(open("test.log"))
# for iteration in data["Output"]:
#     iters.append(iteration["Iteration"])
#     energy.append(iteration["Energy"]["Mean"])
                           vdx[a],
                           vdy[a],
                           head_width=arrow_head_width,
                           head_length=arrow_head_length,
                           length_includes_head=True,
                           color=arrow_colors[a])))
        gc.append(
            ax.add_patch(
                Circle((x_r[a, 0], x_r[a, 1]),
                       facecolor='none',
                       edgecolor=arrow_colors[a],
                       radius=0.3)))
        for b in range(a):
            if nbr[a, b] == 1.:
                gc.append(
                    ax.add_line(
                        plt.Line2D((x[a, 0], x[b, 0]), (x[a, 1], x[b, 1]),
                                   lw=0.5,
                                   color='r')))

    plt.pause(0.01)

    for g in gc:
        g.remove()

    # termination condition
    if cumu_covg == 100:
        break
    else:
        counter += 1
Пример #36
0
 def test_viz(self):
   plt.figure(1, figsize=(20,12))
   self.car_1.viz()
   plt.pause(1)
Пример #37
0
def main(arg,initialized_curves=False,fig=None,axarr=None,found_curves=None,block=True,first=True):
    try:
        if arg.plot=="all":
            what_to_plot = [c for c in GrebberDict.keys() if c !='iter']
        else:
            what_to_plot = arg.plot.split(',')


        for log_file in arg.train_log_file:
            with open(log_file,'r') as f:
                log_lines = f.readlines()

            curves = [[] for c in xrange(len(what_to_plot)+1)]

            for line in log_lines:
                matchObj = re.match( GrebberDict['iter'][0] , line, re.M | re.I)
                if matchObj:
                    curves[0].append(int(matchObj.group(1)))


            for c in xrange(len(what_to_plot)):
                for line in log_lines:
                    matchObj = re.match( GrebberDict[what_to_plot[c]][0] , line, re.M | re.I)
                    if matchObj:
                        curves[c+1].append(GrebberDict[what_to_plot[c]][1](float(matchObj.group(1))))

            if not initialized_curves:
                found_curves = [len(c) > 0 for c in curves]

            if len(curves[0])==0:
                print "unable to find measurments for \"iter\" with {}".format(GrebberDict[what_to_plot[0]][0])
                return


            for c in xrange(len(what_to_plot)):
                if not found_curves[c+1]:
                    continue

                if GrebberDict[what_to_plot[c]][2]:
                   curves[c+1] = np.convolve(np.array(curves[c+1]), np.ones((arg.avg_size,), dtype=np.float32)/arg.avg_size, mode='valid')
                else:
                   curves[c+1] = np.array(curves[c+1])


            if not initialized_curves:
                fig , axarr = plt.subplots(int(reduce(lambda x,y : int(x) + int(y),found_curves[1::])),sharex=True,figsize=(12,8),frameon=False)
                if len(what_to_plot)==1:
                    axarr = [axarr]

            ax_counter = 0
            for c in xrange(len(what_to_plot)):
                if not found_curves[c+1]:
                    continue

                marker = GrebberDict[what_to_plot[c]][3]
                curv_min = np.min(curves[c+1])
                curv_max = np.max(curves[c+1])

                current_y_middle = (curv_min + curv_max)/2
                delta = 0 if curv_max > curv_min else abs(curv_max)
                current_y_bottom = curv_min - (delta + current_y_middle - curv_min)*0.15
                current_y_top    = curv_max + (delta + curv_max -  current_y_middle)*0.15
                if initialized_curves:
                    yrange = (np.min([current_y_bottom,axarr[ax_counter].get_ylim()[0]]) ,  np.max([current_y_top,axarr[ax_counter].get_ylim()[1]]) )
                else:
                    yrange = ( current_y_bottom,  current_y_top )

                axarr[ax_counter].semilogy(np.linspace(curves[0][0],curves[0][-1],curves[c+1].shape[0]), curves[c+1], marker ,linewidth=1.0, label=log_file )
                axarr[ax_counter].set_xlabel('iters')
                axarr[ax_counter].set_ylabel(what_to_plot[c])
                axarr[ax_counter].set_yscale('log', basey=1.05)
                if first:
                    axarr[ax_counter].set_ylim(yrange)
                axarr[ax_counter].grid(True,which='both')
                axarr[ax_counter].legend(loc="upper right",  ncol=2, shadow=True, title="Legend", fancybox=True, prop={'size':6})
                ax_counter+=1

            initialized_curves = True

        plt.legend(loc="upper right",  ncol=2, shadow=True, title="Legend", fancybox=True, prop={'size':6})

        plt.grid(True)
        if block:
            plt.show()
        else:
            plt.pause(4)
            for ax in axarr:
                ylim = ax.get_ylim()
                xlim = ax.get_xlim()
                ax.clear()
                ax.set_ylim(ylim)
                ax.set_xlim(xlim)

        return fig, axarr , found_curves

    except Exception as E:
        print "ERROR {}".format(E)
Пример #38
0
    stdscr.timeout(10)
    stdscr.clear()

    f=name+'_j.png'
    im=img.imread(f)
    plt.clf()
    plt.imshow(im)
    plt.axis('off')
    plt.tight_layout()
    plt.ion()
    plt.show()
    
    cur.execute('select count(object) from %s where classification is NULL' % table)
    res=cur.fetchall()
    remaining=res[0]['count(object)']
    plt.pause(0.1)

    #sleep(1.5)
    #os.system('wmctrl -a "Classify"')

    if classification is None:
        desc='Unclassified'
    else:
        desc=options[classification-1]
    instructions=[str(name),'LR '+str(r['LR']),'(%i done, %i to do)' % (i, remaining),desc,'']
    instructions+=['(%i) %s' % (j+1,s) for j,s in enumerate(options)]
    instructions+=['','LEFT: back one','RIGHT: forward one', 'Q: quit','',"Your choice:"]
    attrs=[curses.color_pair(1)]*4+[None,]*(len(instructions)-4)
    lrvalid=True
    if np.isnan(r['LR']) or r['LR']==0.0:
        attrs[6]=curses.A_REVERSE
Пример #39
0
        beaconDic['table'] = beaconList
        if beaconList:
            beaconLog.append(beaconDic)

    return beaconLog


if __name__ == '__main__':
    import matplotlib.pyplot as plt
    beaconLog = logToList("ibeaconScanner.dat")
    for beacon in beaconLog:
        print(beacon)
    beaconInfos = beaconTable.getBeaconInfo()
    ts_pre = 0
    for rssiTable in beaconLog:
        ts, locx, locy = beacon_locs(beaconInfos, rssiTable)
        if locx != -10000:
            print(ts, locx, locy)
            plt.xlim(600, 1100)
            #把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白
            plt.ylim(-2332, -1835)
            plt.scatter(locx, -locy)

        else:
            print(ts, {})
            continue
        if ts_pre != 0:
            plt.pause((ts - ts_pre) / 1000)
            #plt.clf()
        ts_pre = ts
Пример #40
0
def main():
    #  target course
    cx = np.arange(0, 50, 0.1)
    cy = [math.sin(ix / 5.0) * ix / 2.0 for ix in cx]

    target_speed = 10.0 / 3.6  # [m/s]

    T = 100.0  # max simulation time

    # initial state
    state = State(x=-0.0, y=-3.0, yaw=0.0, v=0.0)

    lastIndex = len(cx) - 1
    time = 0.0
    x = [state.x]
    y = [state.y]
    yaw = [state.yaw]
    v = [state.v]
    t = [0.0]
    target_ind = calc_target_index(state, cx, cy)

    while T >= time and lastIndex > target_ind:
        ai = PIDControl(target_speed, state.v)
        di, target_ind = pure_pursuit_control(state, cx, cy, target_ind)
        state = update(state, ai, di)

        time = time + dt

        x.append(state.x)
        y.append(state.y)
        yaw.append(state.yaw)
        v.append(state.v)
        t.append(time)

        if show_animation:  # pragma: no cover
            plt.cla()
            # for stopping simulation with the esc key.
            plt.gcf().canvas.mpl_connect(
                'key_release_event',
                lambda event: [exit(0) if event.key == 'escape' else None])
            plot_arrow(state.x, state.y, state.yaw)
            plt.plot(cx, cy, "-r", label="course")
            plt.plot(x, y, "-b", label="trajectory")
            plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
            plt.axis("equal")
            plt.grid(True)
            plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4])
            plt.pause(0.001)

    # Test
    assert lastIndex >= target_ind, "Cannot goal"

    if show_animation:  # pragma: no cover
        plt.cla()
        plt.plot(cx, cy, ".r", label="course")
        plt.plot(x, y, "-b", label="trajectory")
        plt.legend()
        plt.xlabel("x[m]")
        plt.ylabel("y[m]")
        plt.axis("equal")
        plt.grid(True)

        plt.subplots(1)
        plt.plot(t, [iv * 3.6 for iv in v], "-r")
        plt.xlabel("Time[s]")
        plt.ylabel("Speed[km/h]")
        plt.grid(True)
        plt.show()
Пример #41
0
    """
    R = 1 - np.sqrt(X**2 + Y**2)
    return np.cos(2 * np.pi * X + phi) * R


fig = plt.figure()
ax = fig.add_subplot(projection='3d')

# Make the X, Y meshgrid.
xs = np.linspace(-1, 1, 50)
ys = np.linspace(-1, 1, 50)
X, Y = np.meshgrid(xs, ys)

# Set the z axis limits so they aren't recalculated each frame.
ax.set_zlim(-1, 1)

# Begin plotting.
wframe = None
tstart = time.time()
for phi in np.linspace(0, 180. / np.pi, 100):
    # If a line collection is already remove it before drawing.
    if wframe:
        wframe.remove()

    # Plot the new wireframe and pause briefly before continuing.
    Z = generate(X, Y, phi)
    wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
    plt.pause(.001)

print('Average FPS: %f' % (100 / (time.time() - tstart)))
        rect = [
            rect_init[0] + result_star[0], rect_init[1] + result_star[1],
            rect_init[2] + result_star[0], rect_init[3] + result_star[1]
        ]

    # print(np.linalg.norm(result_star - result_n))
    # print(com)
    # print(rect)
    # print(result_pre)

    # LucasKanade(It, It1, rect, threshold, num_iters, p0=np.zeros(2)):
    plt.imshow(frame_now, cmap='gray')
    plt.axis('off')
    plt.axis('tight')
    patch = patches.Rectangle((rect[0], rect[1]),
                              rect[2] - rect[0],
                              rect[3] - rect[1],
                              linewidth=1,
                              edgecolor='r',
                              facecolor='none')
    ax = plt.gca()
    ax.add_patch(patch)
    #visualizing the result
    plt.show(block=False)
    plt.pause(0.2)
    # if i == 1 or i==100 or i==200 or i ==300 or i ==400:
    #     fig.savefig('../result/carseq-wcrt_frame' + str(i) + '.png',bbox_inches = 'tight')
    carseqrects_wcrt[i, :] = np.array([rect[0], rect[1], rect[2], rect[3]])
    ax.clear()
np.save('../result/carseqrects-wcrt.npy', carseqrects_wcrt)
def update_score(plot, updateScore, scoreArray):
    scoreArray = scoreArray[1:]
    plot.set_ydata(np.append(scoreArray,updateScore))
    plt.ylim(ymin=0,ymax=max(scoreArray))
    plt.show(block=False)
    plt.pause(0.001)
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.Raw(raw_fname, preload=True)

# select gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,
                       stim=True, exclude=raw.info['bads'])

# select the left-auditory condition
event_id, tmin, tmax = 1, -0.2, 0.5

# create the mock-client object
rt_client = MockRtClient(raw)

# create the real-time epochs object
rt_epochs = RtEpochs(rt_client, event_id, tmin, tmax, picks=picks,
                     decim=1, reject=dict(grad=4000e-13, eog=150e-6))

# start the acquisition
rt_epochs.start()

# send raw buffers
rt_client.send_data(rt_epochs, picks, tmin=0, tmax=150, buffer_size=1000)
for ii, ev in enumerate(rt_epochs.iter_evoked()):
    print("Just got epoch %d" % (ii + 1))
    if ii > 0:
        ev += evoked
    evoked = ev
    plt.clf() # clear canvas
    evoked.plot(axes=plt.gca())  # plot on current figure
    plt.pause(0.05)
Пример #45
0
def run_experiment(args):

    # Make a folder to save everything
    extra = args.elbo + "_" + str(args.beta0)

    if args.modellt < 0.01:
        extra += "_lt0_"

    chkpnt_dir = make_checkpoint_folder(args.base_dir, args.expid, extra)
    # chkpnt_dir = "/home/michael/GPVAE_checkpoints/84:__on__9_10_2019__at__19:15:31/"
    pic_folder = chkpnt_dir + "pics/"
    res_file = chkpnt_dir + "res/ELBO_pandas"
    print("\nCheckpoint Directory:\n" + str(chkpnt_dir) + "\n")

    # Data synthesis settings
    batch = 35
    tmax = 30
    px = 32
    py = 32
    r = 3
    vid_lt = 5
    model_lt = args.modellt

    # Load/ceate batches of reproducible videos
    if os.path.isfile(args.base_dir + "/Test_Batches.pkl"):
        with open(args.base_dir + "/Test_Batches.pkl", "rb") as f:
            Test_Batches = pickle.load(f)
    else:
        make_batch = lambda s: Make_Video_batch(
            tmax=tmax, px=px, py=py, lt=vid_lt, batch=batch, seed=s, r=r)
        Test_Batches = [make_batch(s) for s in range(10)]
        with open(args.base_dir + "/Test_Batches.pkl", "wb") as f:
            pickle.dump(Test_Batches, f)

    # Initialise a plots
    # this plot displays a  batch of videos + latents + reconstructions
    fig, ax = plt.subplots(4, 4, figsize=(8, 8), constrained_layout=True)
    plt.ion()

    truth_c, V_c = Make_circles()
    batch_V_c = np.tile(V_c, (batch, 1, 1, 1))
    truth_sq, V_sq = Make_squares()
    batch_V_sq = np.tile(V_sq, (batch, 1, 1, 1))

    # make sure everything is created in the same graph!
    graph = tf.Graph()
    with graph.as_default():

        # Make all the graphs
        beta = tf.compat.v1.placeholder(dtype=tf.float32, shape=())
        vid_batch = build_video_batch_graph(batch=batch,
                                            tmax=tmax,
                                            px=px,
                                            py=py,
                                            r=r,
                                            lt=vid_lt)
        s_elbo, s_rec, s_pkl, np_elbo, np_rec, np_pkl, \
            p_m,p_v,q_m,q_v,pred_vid, _ = build_sin_and_np_elbo_graphs(vid_batch, beta, lt=model_lt)

        # The actual loss functions
        if args.elbo == "SIN":
            loss = -tf.reduce_mean(s_elbo)
            e_elb = tf.reduce_mean(s_elbo)
            e_pkl = tf.reduce_mean(s_pkl)
            e_rec = tf.reduce_mean(s_rec)
        elif args.elbo == "NP":
            loss = -tf.reduce_mean(np_elbo)
            e_elb = tf.reduce_mean(np_elbo)
            e_pkl = tf.reduce_mean(np_pkl)
            e_rec = tf.reduce_mean(np_rec)

        av_s_elbo = tf.reduce_mean(s_elbo)
        av_s_rec = tf.reduce_mean(s_rec)
        av_s_pkl = tf.reduce_mean(s_pkl)

        # Add optimizer ops to graph (minimizing neg elbo!), print out trainable vars
        global_step = tf.Variable(0, name='global_step', trainable=False)
        optimizer = tf.compat.v1.train.AdamOptimizer()
        train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
        optim_step = optimizer.minimize(loss=loss,
                                        var_list=train_vars,
                                        global_step=global_step)
        print("\n\nTrainable variables:")
        for v in train_vars:
            print(v)

        # Initializer ops for the graph and saver
        init_op = tf.global_variables_initializer()
        saver = tf.compat.v1.train.Saver()

        # Results to be tracked and Pandas saver
        res_vars = [
            global_step, loss, av_s_elbo, av_s_rec, av_s_pkl, e_elb, e_rec,
            e_pkl,
            tf.math.reduce_min(q_v),
            tf.math.reduce_max(q_v),
            tf.math.reduce_min(p_v),
            tf.math.reduce_max(p_v)
        ]
        res_names = [
            "Step", "Loss", "Test ELBO", "Test Reconstruction",
            "Test Prior KL", "Train ELBO", "Train Reconstruction",
            "Train Prior KL", "min qs_var", "max qs_var", "min q_var",
            "max q_var", "MSE", "Beta", "Time"
        ]
        res_saver = pandas_res_saver(res_file, res_names)

        # Now let's start doing some computation!
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.ram)
        with tf.Session(config=tf.ConfigProto(
                gpu_options=gpu_options)) as sess:

            # Attempt to restore weights
            try:
                saver.restore(sess, tf.train.latest_checkpoint(chkpnt_dir))
                print("\n\nRestored Model Weights")
            except:
                sess.run(init_op)
                print("\n\nInitialised Model Weights")

            # Start training that elbo!
            for t in range(args.steps):

                # Annealing factor for prior KL
                beta_t = 1 + (args.beta0 - 1) * np.exp(t / 2000)

                # Train: do an optim step
                _, g_s = sess.run([optim_step, global_step], {beta: beta_t})

                # Print out diagnostics/tracking
                if g_s % 10 == 0:
                    TD = Test_Batches[0][1]
                    test_elbo, e_rec_i, e_pkl_i = sess.run(
                        [e_elb, e_rec, e_pkl], {
                            vid_batch: TD,
                            beta: 1.0
                        })
                    test_qv, test_pv, test_pm, test_qm = sess.run(
                        [q_v, p_v, p_m, q_m], {
                            vid_batch: TD,
                            beta: 1.0
                        })

                    print(str(g_s) + ": elbo " + str(test_elbo)
                          )  #+"\t "+"\t "+str(e_rec_i)+"  "+str(e_pkl_i)+\
                    # ",\t\t qvar range:\t",str(test_pv.max()),"\t",str(test_qv.min()) ,\
                    # ",\t\t qmean range:\t",str(np.abs(test_pm).max()),"\t",str(np.abs(test_qm).max())  )

                # Save elbo, recon, priorKL....
                if g_s % 100 == 0:
                    TT, TD = Test_Batches[0]
                    p_m_i, p_v_i = sess.run([p_m, p_v], {
                        vid_batch: TD,
                        beta: 1
                    })
                    _, _, MSE, _ = MSE_rotation(p_m_i, TT, p_v_i)
                    new_res = sess.run(res_vars, {vid_batch: TD, beta: 1})
                    new_res += [MSE, beta_t, time.time()]
                    res_saver(new_res)

                # show plot and occasionally save
                if g_s % 20 == 0:
                    # [[ax_ij.clear() for ax_ij in ax_i] for ax_i in ax]
                    TT, TD = Test_Batches[0]
                    reconpath, reconvar, reconvid = sess.run(
                        [p_m, p_v, pred_vid], {
                            vid_batch: TD,
                            beta: 1
                        })
                    rp, W, MSE, rv = MSE_rotation(reconpath, TT, reconvar)
                    _ = plot_latents(TD, TT, reconvid, rp, rv, ax=ax, nplots=4)
                    # plt.tight_layout()
                    plt.draw()
                    fig.suptitle(str(g_s) + ' ELBO: ' + str(test_elbo))

                    q_m_c = sess.run(q_m, {vid_batch: batch_V_c})
                    q_m_sq = sess.run(q_m, {vid_batch: batch_V_sq})

                    # import pdb; pdb.set_trace()

                    q_m_c = np.hstack([q_m_c[0, :, :], np.ones((30, 1))])
                    rot_qnet_c = np.matmul(q_m_c, W)
                    plot_circle(ax[3][0], ax[3][1], rot_qnet_c)

                    q_m_sq = np.hstack([q_m_sq[0, :, :], np.ones((30, 1))])
                    rot_qnet_sq = np.matmul(q_m_sq, W)
                    plot_square(ax[3][2], ax[3][3], rot_qnet_sq)

                    plt.show()
                    plt.pause(0.01)
                    if True:  #g_s%500==0:
                        plt.savefig(pic_folder + str(g_s).zfill(6) + ".png")

                # Save NN weights
                if g_s % 1000 == 0:
                    saver.save(sess, chkpnt_dir + "model", global_step=g_s)
                    print("\n\nModel Saved: " + chkpnt_dir + "\n\n")
def update_testing_plot(plot,updateGrid):
    plot.set_data(updateGrid)
    plt.show(block=False)
    plt.pause(0.001)
def main():
    print("Please select question to display output for:\n" +
          "\t1 2 3 4 5 6 7 8")
    question = raw_input()

    if question == '1':
        print('The downloading and cropping of images is done by the '
              'get_data function in the get_data.py file.')
        get_data.get_data()
        # For some strange reason, when performing downloading all the images
        # the program hangs after completion, never exiting. 'Done' is printed
        # however. The program does not close even if I forcibly throw an error.
        # On small subsets however, it does close. I suspect it has something to
        # with the automatic garbage collection running into some issue, but I
        # do not have any clue as to what. If you know what could be the cause,
        # please let me know! Otherwise, take this as a notice that when 'Done'
        # is printed the program has finished.
        print('Done')

    elif question == '2':
        print('The loading of images is done by the load_data function in the '
              'get_data.py file. Seperating the images into three sets is done '
              'as part of the classify function in the classifier.py file.')
        images = get_data.load_data('baldwin') # for example
        # Note that by default, the seed is fixed so that repeated identical
        # calls will produce an identical selection of images. This is how we
        # ensure reproducibility. For true randomness, just set the parameter:
        rand_imgs = get_data.load_data('baldwin', is_random=True)

    elif question == '3':
        p, cost, accuracy = classifier.classify(['baldwin', 'carell'])
        print("Training Error:", cost[0])
        print("Validation Error:", cost[1])
        print("Validation Accuracy:", accuracy[1])
        print("Testing Accuracy:", accuracy[2])

    elif question == '4':
        def visualize(p, name):
            vis = p[1:].reshape((32, 32))
            io.imshow(vis)
            plt.savefig(name)
            plt.show()

        print('Full training set')
        p, _, _ = classifier.classify(['baldwin', 'carell'])
        visualize(p, '4a-1.png')
        print('Two image training set')
        p, _, _ = classifier.classify(['baldwin', 'carell'],
                                      set_sizes=(2, 10, 10))
        visualize(p, '4a-2.png')
        print('Stop too early vs stop too late')
        p, _, _ = classifier.classify(['baldwin', 'carell'], max_iter=100)
        visualize(p, '4b-1.png')
        p, _, _ = classifier.classify(['baldwin', 'carell'], epsilon=1e-7)
        visualize(p, '4b-2.png')

    elif question == '5':
        train_act = [['bracco', 'gilpin', 'harmon'],
                     ['baldwin', 'carell', 'hader']]
        other_act = [['chenoweth', 'ferrera', 'drescher'],
                     ['butler', 'vartan', 'radcliffe']]

        # Compare performance against other actors
        def check_performance(name, labels, parameters):
            images = get_data.load_data(name, sizes=[50])
            a = classifier.labelling_accuracy(images, labels, parameters)
            print('\t', name, 'classified with', a, 'accuracy')

        p, _, _ = classifier.classify([train_act[0], train_act[1]],
                                      set_sizes=(66, 10, 10))
        print('Training Actors')
        for act in train_act[0]:
            check_performance(act, np.ones(50), p)
        for act in train_act[1]:
            check_performance(act, np.zeros(50), p)
        print('Other Actors')
        for act in other_act[0]:
            check_performance(act, np.ones(50), p)
        for act in other_act[1]:
            check_performance(act, np.zeros(50), p)

        # Visualize performance vs set size
        plt.axis((0, 70, 0.5, 1))
        plt.xlabel('Size of Training Set')
        plt.ylabel('Classification Accuracy')
        vald = mpatches.Patch(color='blue', label='Validation Set')
        test = mpatches.Patch(color='green', label='Testing Set')
        plt.legend(handles=[vald, test], loc=4)
        plt.ion()
        for i in range(1, 67):
            p, e, a = classifier.classify([train_act[0], train_act[1]],
                                          set_sizes=(i, 10, 10), is_random=True)
            plt.scatter(i, a[1], c='b')
            plt.scatter(i, a[2], c='g')
            plt.pause(0.01)
        plt.savefig('5.png')

    elif question == '6':
        # initialize some data to be used and find gradient
        images = get_data.load_data('bracco', [40])
        param = np.random.random((1025, 6)) * 1e-2
        labels = np.array([[1, 0, 0, 0, 0, 0]] * 40)
        grad = classifier.cost_gradient(images, labels, param)
        h = 1e-6
        # compare against finite differences
        np.random.seed(17)
        for _ in range(5):
            x = np.random.randint(0, 1025)
            y = np.random.randint(0, 6)
            param_mod = param.copy()
            param_mod[x, y] += h
            estimate = (classifier.cost_function(images, labels, param_mod) -
                        classifier.cost_function(images, labels, param)) / h
            print('(p,q) =', (x, y), '-> function:', '{:f}'.format(grad[x, y]),
                  '\t', 'estimate:', '{:f}'.format(estimate))


    elif question == '7':
        act = ['bracco', 'gilpin', 'harmon', 'baldwin', 'carell', 'hader']
        p, cost, accuracy = classifier.classify(act, set_sizes=(66, 10, 10))
        print("Validation Accuracy:", accuracy[1])
        print("Testing Accuracy:", accuracy[2])

    elif question == '8':
        act = ['bracco', 'gilpin', 'harmon', 'baldwin', 'carell', 'hader']
        p, e, a = classifier.classify(act, set_sizes=(66, 10, 10))
        for i, vis in enumerate(p[1:].T):
            vis = vis.reshape((32, 32))
            io.imshow(vis)
            plt.savefig('8-' + str(i) + '.png')
            plt.show()
Пример #48
0
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 3, 100)
k = 2 * np.pi
w = 2 * np.pi
dt = 0.01

t = 0
for i in range(50):
    y = np.cos(k * x - w * t)
    if i == 0:
        line, = plt.plot(x, y)
    else:
        line.set_ydata(y)
    plt.pause(0.01)  # pause avec duree en secondes
    t = t + dt

plt.show()
 def refresh(self):
     plt.pause(self._refresh_timer)    
controller = satelliteController()
reference = signalGenerator(amplitude=15.0*np.pi/180.0, frequency=0.03)
disturbance = signalGenerator(amplitude=1.0)

# instantiate the simulation plots and animation
dataPlot = dataPlotter()
animation = satelliteAnimation()

t = P.t_start  # time starts at t_start
y = satellite.h()  # output of system at start of simulation
while t < P.t_end:  # main simulation loop
    # Propagate dynamics in between plot samples
    t_next_plot = t + P.t_plot
    while t < t_next_plot:  # updates control and dynamics at faster simulation rate
        r = reference.square(t)  # reference input
        d = disturbance.step(t)  # input disturbance
        n = 0.0  #noise.random(t)  # simulate sensor noise
        x = satellite.state
        u = controller.update(r, x)  # update controller
        y = satellite.update(u + d)  # propagate system
        t = t + P.Ts  # advance time by Ts
    # update animation and data plots
    animation.update(satellite.state)
    dataPlot.update(t, r, satellite.state, u)
    plt.pause(0.0001)  # the pause causes the figure to be displayed during the simulation

# Keeps the program from closing until the user presses a button.
print('Press key to close')
plt.waitforbuttonpress()
plt.close()
Пример #51
0
def run(infile, ddc_file, time_lim, live, verbose):
    """Main function to run FPGA and DDC2 chain and collect the data"""
    print '=========='
    print 'Running for {0}s'.format(time_lim)

    process = run_setup(COMMAND.format(ddc_file, infile))

    def signal_handler(sig, frame):
        print 'Caught signal, cleaning up\n'
        os.killpg(os.getpgid(process.pid), signal.SIGTERM)
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    str_data = []
    skip_intro = True
    skip_initial_wv = True
    idx = 0
    try:
        if live:
            from matplotlib import pyplot as plt
            from matplotlib.offsetbox import AnchoredText
            plt.ion()
            fig = plt.figure(figsize=(12, 8))
            ax = fig.add_subplot(111)
            ax.set_xlabel('Time (4ns)')
            ax.set_ylabel('Voltage (A.U.)')
            xmax = 1
            ymin, ymax = (999999, 1)
            live_data = []

        for line in iter(process.stdout.readline, b''):
            if skip_intro:
                try:
                    int(line.split(',')[0])
                except:
                    print line,
                    if 'INVALID' in line:
                        raise AssertionError('Reset the DDC2 and run again')
                    idx += 1
                    continue
                else:
                    if idx < 10:
                        raise AssertionError('Reset the DDC2 and run again')
                    start_t = timer()
                    skip_intro = False
                    continue
            if skip_initial_wv:
                time = timer()
                # Wait before recording any data to flush previous buffer
                if time - start_t < 2 or '---------------------------' in line:
                    continue
                else:
                    start_t = timer()
                    skip_initial_wv = False
            time = timer()
            if verbose:
                print line,
            if time - start_t > time_lim:
                break
            str_data.append(line)

            if live:
                try:
                    d = map(int, parse(line))
                except:
                    continue
                if len(d) == 0: continue
                if d[0] == 0:
                    if live_data == []: continue
                    ax.set_xlim(0, xmax)
                    ax.set_ylim(ymin, ymax)
                    # ax.set_ylim(9070-50, 9070+10)
                    ax.xaxis.grid(True, which='major')
                    ax.yaxis.grid(True, which='major')
                    ld = np.vstack(live_data)
                    ax.scatter(ld[:, 0], ld[:, 1], marker='o', c='crimson')
                    ax.plot(ld[:, 0],
                            ld[:, 1],
                            linestyle='--',
                            linewidth=1,
                            c='crimson')
                    diff = np.max(ld[:, 1]) - np.min(ld[:, 1])
                    at = AnchoredText('min = {0}\nmax = {1}\ndiff = '
                                      '{2}'.format(ymin, ymax, diff),
                                      prop=dict(size=14),
                                      frameon=True,
                                      loc=1)
                    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.5")
                    ax.add_artist(at)
                    plt.pause(0.001)
                    ax.cla()
                    live_data = []
                if d[0] > xmax: xmax = d[0]
                if d[1] < ymin: ymin = d[1]
                if d[1] > ymax: ymax = d[1]
                live_data.append([d[0], d[1]])
    except:
        os.killpg(os.getpgid(process.pid), signal.SIGTERM)
        raise
    os.killpg(os.getpgid(process.pid), signal.SIGTERM)

    n_count = 0
    nsamples = 0
    timestamp = 0
    local_time = 0
    raw_data = []
    for idx in range(len(str_data)):
        if 'Nsamples' in str_data[idx] and nsamples == 0:
            nsamples = int(str_data[idx].split()[2])
            continue
        if 'timestamp' in str_data[idx]:
            timestamp = int(str_data[idx].split()[3][:-1])
            continue
        if 'local time' in str_data[idx]:
            local_time = int(str_data[idx].split()[4][:-1])
            continue
        if nsamples == 0: continue
        if ',' not in str_data[idx]: continue
        if len(str_data[idx].split()) != 5: continue
        try:
            timing = int(str_data[idx].split()[0][:-1])
        except:
            continue
        if verbose:
            print timing, n_count
        if timing == 0 and n_count != 0:
            # remove incomplete waveforms
            raw_data = raw_data[:-n_count]
            n_count = 0
        if n_count == 0 and timing != 0:
            n_count = timing
        if timing != n_count:
            raise AssertionError(
                'Something went wrong! timing != n_count! {0} != '
                '{1}\n{2}'.format(timing, n_count, str_data[idx]))
        raw_data.append(
            map(int, parse(str_data[idx])) + [timestamp, local_time])
        if n_count >= nsamples: n_count += 1
        elif n_count == nsamples - 1: n_count = 0
        else: n_count += 1
    raw_data = np.array(raw_data)
    try:
        data = check_data(raw_data, nsamples, verbose)
    except:
        print 'Error occured, dumping data to dump.npy'
        np.save('dump', raw_data)
        raise

    timings, run_counts = np.unique(data[:, 0], return_counts=True)

    if len(set(run_counts)) != 1:
        print 'Error occured, dumping data to dump.npy'
        np.save('dump', data)
        raise AssertionError(
            'Something bad happened!\nrun_counts = {0}\nlen(set(run_counts)) '
            '= {1}'.format(run_counts, len(set(run_counts))))
    run_counts = run_counts[0]

    try:
        trns_data = data.reshape(run_counts, len(timings), data.shape[1])
    except:
        print 'Error occured, dumping data to dump.npy'
        np.save('dump', data)
        raise
    if verbose:
        print 'trns_data', trns_data
        print 'trns_data.shape', trns_data.shape

    return trns_data
Пример #52
0
def plot_with_labels(lowDWeights, labels):
    plt.cla(); X, Y = lowDWeights[:, 0], lowDWeights[:, 1]
    for x, y, s in zip(X, Y, labels):
        c = cm.rainbow(int(255 * s / 9)); plt.text(x, y, s, backgroundcolor=c, fontsize=9)
    plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01)
Пример #53
0
def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data/cifar10/', plotable=False, second=3):
    """The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with
    6000 images per class. There are 50000 training images and 10000 test images.

    The dataset is divided into five training batches and one test batch, each with
    10000 images. The test batch contains exactly 1000 randomly-selected images from
    each class. The training batches contain the remaining images in random order,
    but some training batches may contain more images from one class than another.
    Between them, the training batches contain exactly 5000 images from each class.

    Parameters
    ----------
    shape : tupe
        The shape of digit images: e.g. (-1, 3, 32, 32) , (-1, 32, 32, 3) , (-1, 32*32*3)
    plotable : True, False
        Whether to plot some image examples.
    second : int
        If ``plotable`` is True, ``second`` is the display time.
    path : string
        Path to download data to, defaults to data/cifar10/

    Examples
    --------
    >>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3), plotable=True)

    Notes
    ------
    CIFAR-10 images can only be display without color change under uint8.
    >>> X_train = np.asarray(X_train, dtype=np.uint8)
    >>> plt.ion()
    >>> fig = plt.figure(1232)
    >>> count = 1
    >>> for row in range(10):
    >>>     for col in range(10):
    >>>         a = fig.add_subplot(10, 10, count)
    >>>         plt.imshow(X_train[count-1], interpolation='nearest')
    >>>         plt.gca().xaxis.set_major_locator(plt.NullLocator())    # 不显示刻度(tick)
    >>>         plt.gca().yaxis.set_major_locator(plt.NullLocator())
    >>>         count = count + 1
    >>> plt.draw()
    >>> plt.pause(3)

    References
    ----------
    - `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`_
    - `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`_
    - `Code references <https://teratail.com/questions/28932>`_
    """

    print("Load or Download cifar10 > {}".format(path))

    #Helper function to unpickle the data
    def unpickle(file):
        fp = open(file, 'rb')
        if sys.version_info.major == 2:
            data = pickle.load(fp)
        elif sys.version_info.major == 3:
            data = pickle.load(fp, encoding='latin-1')
        fp.close()
        return data

    filename = 'cifar-10-python.tar.gz'
    url = 'https://www.cs.toronto.edu/~kriz/'
    #Download and uncompress file
    maybe_download_and_extract(filename, path, url, extract=True)

    #Unpickle file and fill in data
    X_train = None
    y_train = []
    for i in range(1,6):
        data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "data_batch_{}".format(i)))
        if i == 1:
            X_train = data_dic['data']
        else:
            X_train = np.vstack((X_train, data_dic['data']))
        y_train += data_dic['labels']

    test_data_dic = unpickle(os.path.join(path,  'cifar-10-batches-py/', "test_batch"))
    X_test = test_data_dic['data']
    y_test = np.array(test_data_dic['labels'])

    if shape == (-1, 3, 32, 32):
        X_test = X_test.reshape(shape)
        X_train = X_train.reshape(shape)
    elif shape == (-1, 32, 32, 3):
        X_test = X_test.reshape(shape, order='F')
        X_train = X_train.reshape(shape, order='F')
        X_test = np.transpose(X_test, (0, 2, 1, 3))
        X_train = np.transpose(X_train, (0, 2, 1, 3))
    else:
        X_test = X_test.reshape(shape)
        X_train = X_train.reshape(shape)

    y_train = np.array(y_train)

    if plotable == True:
        print('\nCIFAR-10')
        import matplotlib.pyplot as plt
        fig = plt.figure(1)

        print('Shape of a training image: X_train[0]',X_train[0].shape)

        plt.ion()       # interactive mode
        count = 1
        for row in range(10):
            for col in range(10):
                a = fig.add_subplot(10, 10, count)
                if shape == (-1, 3, 32, 32):
                    # plt.imshow(X_train[count-1], interpolation='nearest')
                    plt.imshow(np.transpose(X_train[count-1], (1, 2, 0)), interpolation='nearest')
                    # plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')
                elif shape == (-1, 32, 32, 3):
                    plt.imshow(X_train[count-1], interpolation='nearest')
                    # plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')
                else:
                    raise Exception("Do not support the given 'shape' to plot the image examples")
                plt.gca().xaxis.set_major_locator(plt.NullLocator())    # 不显示刻度(tick)
                plt.gca().yaxis.set_major_locator(plt.NullLocator())
                count = count + 1
        plt.draw()      # interactive mode
        plt.pause(3)   # interactive mode

        print("X_train:",X_train.shape)
        print("y_train:",y_train.shape)
        print("X_test:",X_test.shape)
        print("y_test:",y_test.shape)

    X_train = np.asarray(X_train, dtype=np.float32)
    X_test = np.asarray(X_test, dtype=np.float32)
    y_train = np.asarray(y_train, dtype=np.int32)
    y_test = np.asarray(y_test, dtype=np.int32)

    return X_train, y_train, X_test, y_test
Пример #54
0
def test(data_path, label_path, vid=None, graph=None, is_3d=False):
    '''
    vis the samples using matplotlib
    :param data_path:
    :param label_path:
    :param vid: the id of sample
    :param graph:
    :param is_3d: when vis NTU, set it True
    :return:
    '''
    import matplotlib.pyplot as plt
    loader = torch.utils.data.DataLoader(dataset=Feeder(data_path, label_path),
                                         batch_size=64,
                                         shuffle=False,
                                         num_workers=2)

    if vid is not None:
        sample_name = loader.dataset.sample_name
        sample_id = [name.split('.')[0] for name in sample_name]
        index = sample_id.index(vid)
        data, label, index = loader.dataset[index]
        data = data.reshape((1, ) + data.shape)

        # for batch_idx, (data, label) in enumerate(loader):
        N, C, T, V, M = data.shape

        plt.ion()
        fig = plt.figure()
        if is_3d:
            from mpl_toolkits.mplot3d import Axes3D
            ax = fig.add_subplot(111, projection='3d')
        else:
            ax = fig.add_subplot(111)

        if graph is None:
            p_type = [
                'b.', 'g.', 'r.', 'c.', 'm.', 'y.', 'k.', 'k.', 'k.', 'k.'
            ]
            pose = [
                ax.plot(np.zeros(V), np.zeros(V), p_type[m])[0]
                for m in range(M)
            ]
            ax.axis([-1, 1, -1, 1])
            for t in range(T):
                for m in range(M):
                    pose[m].set_xdata(data[0, 0, t, :, m])
                    pose[m].set_ydata(data[0, 1, t, :, m])
                fig.canvas.draw()
                plt.pause(0.001)
        else:
            p_type = [
                'b-', 'g-', 'r-', 'c-', 'm-', 'y-', 'k-', 'k-', 'k-', 'k-'
            ]
            import sys
            from os import path
            sys.path.append(
                path.dirname(path.dirname(path.dirname(
                    path.abspath(__file__)))))
            G = import_class(graph)()
            edge = G.inward
            pose = []
            for m in range(M):
                a = []
                for i in range(len(edge)):
                    if is_3d:
                        a.append(
                            ax.plot(np.zeros(3), np.zeros(3), p_type[m])[0])
                    else:
                        a.append(
                            ax.plot(np.zeros(2), np.zeros(2), p_type[m])[0])
                pose.append(a)
            ax.axis([-1, 1, -1, 1])
            if is_3d:
                ax.set_zlim3d(-1, 1)
            for t in range(T):
                for m in range(M):
                    for i, (v1, v2) in enumerate(edge):
                        x1 = data[0, :2, t, v1, m]
                        x2 = data[0, :2, t, v2, m]
                        if (x1.sum() != 0
                                and x2.sum() != 0) or v1 == 1 or v2 == 1:
                            pose[m][i].set_xdata(data[0, 0, t, [v1, v2], m])
                            pose[m][i].set_ydata(data[0, 1, t, [v1, v2], m])
                            if is_3d:
                                pose[m][i].set_3d_properties(data[0, 2, t,
                                                                  [v1, v2], m])
                fig.canvas.draw()
                # plt.savefig('/home/lshi/Desktop/skeleton_sequence/' + str(t) + '.jpg')
                plt.pause(0.01)
Пример #55
0
    def __init__(self,
                 f,
                 t,
                 x,
                 y,
                 thr,
                 maxit,
                 leg=[],
                 col=tudcols[0],
                 save=False,
                 dpi=100,
                 fmt='png',
                 plotstates=True,
                 n=1,
                 styles=['-', '--', '-.', ':']):

        nth = len(thr)
        nx = len(x[:, 0])
        ny = len(y[:, 0])
        self.nth = nth
        self.nx = nx
        self.ny = ny
        self.t = t
        self.fmt = fmt
        self.dpi = dpi
        self.n = n
        self.pls = plotstates

        th = zeros((nth, 2))
        th[:, 0] = thr
        th[:, 1] = thr

        xbet = [0.02, 0.01]
        ybet = [0.05, 0.005]
        lef = 0.02
        bot = 0.06
        top = 0.05

        self.it = linspace(1, maxit, maxit)

        xtcks = [0.1 * maxit, 0.9 * maxit]
        xtcklabs = ['%d' % xtcks[0], '%d' % xtcks[1]]
        rat = 3 / 7
        if plotstates:
            hp = rat - top - ybet[0]
            hs = (1 - rat - bot - (nx + ny) * ybet[1]) / (nx + ny)
            ws = 1 - lef - xbet[1]
            yp = 1 - rat + ybet[0]
        else:
            hp = 1 - top - bot
            yp = bot
        wp = (1 - lef - (nth - 1) * xbet[0] - xbet[1]) / nth

        self.axth = []
        for i in range(0, nth):
            ax = plt.axes([lef + i * (wp + xbet[0]), yp, wp, hp])
            xlimit = [1, maxit]
            ymin = 0
            h = max(th[i, :])
            ylimit = [ymin - 0.1 * h, ymin + 1.6 * h]
            ytcks = [0, th[i, 0]]
            ytcklabs = ['%d ' % 0, '%d' % th[i, 0]]
            if nth == 1:
                title = 'Parameter: \u03b8'
            else:
                title = 'Parameter ' + str(i +
                                           1) + ': \u03b8$_{' + str(i +
                                                                    1) + '}$'
            self.axth.append(animaxis(f, ax, tit=title,\
                                xlim=xlimit,\
                                ylim=ylimit,\
                                xcoords=(0.5, -0.03),\
                                xtx=xtcks,\
                                xtlbs=xtcklabs,\
                                ytx=ytcks,\
                                ytlbs=ytcklabs,\
                                xlab='iter.'))
            self.axth[i].add_line(self.it[[0, -1]],
                                  th[i, :],
                                  col='black',
                                  wdth=1)
            for j in range(0, self.n):
                self.axth[i].add_line([], [],
                                      col=tudcols[0],
                                      wdth=1,
                                      style=styles[j])

        plt.legend(leg, loc=4)
        if plotstates:
            self.axx = []
            for i in range(0, nx):
                ax = plt.axes(
                    [lef, bot + (nx - 1 - i) * (hs + ybet[1]), ws, hs])
                xlimit = t[[0, -1]]
                ymin = min(x[i, :])
                h = max(x[i, :]) - ymin
                ylimit = [ymin - 0.1 * h, ymin + 1.6 * h]
                if nx == 1:
                    title = 'Hidden state: x'
                else:
                    title = 'Hidden state ' + str(i +
                                                  1) + ': x$_{' + str(i +
                                                                      1) + '}$'
                if i == nx - 1:
                    xlbl = 't (s)'
                    xtcks = 'def'
                    xtcklabs = 'def'
                else:
                    xlbl = ''
                    xtcks = []
                    xtcklabs = ''

                yrng = max(abs(min(x[i, :])), abs(min(x[i, :])))
                ytcks = [2 * int(-0.5 * yrng), 0, 2 * int(0.5 * yrng)]
                ytcklabs = ['%d ' % ytcks[0], '0',
                            '%d' % ytcks[2]]

                self.axx.append(animaxis(f, ax, tit=title,\
                                    xlim=xlimit,\
                                    ylim=ylimit,\
                                    xcoords=(0.5, -0.03),\
                                    xlab = xlbl,\
                                    xtx = xtcks,\
                                    xtlbs = xtcklabs,\
                                    ytx = ytcks,\
                                    ytlbs = ytcklabs))
                self.axx[i].add_line(t, x[i, :], col='black', wdth=1)
                for j in range(0, self.n):
                    self.axx[i].add_line([], [],
                                         col=tudcols[0],
                                         wdth=1,
                                         style=styles[j])

            self.axy = []
            for i in range(0, ny):
                ax = plt.axes(
                    [lef, bot + (nx + ny - 1 - i) * (hs + ybet[1]), ws, hs])
                xlimit = t[[0, -1]]
                ymin = min(y[i, :])
                h = max(y[i, :]) - ymin
                ylimit = [ymin - 0.1 * h, ymin + 1.6 * h]
                if ny == 1:
                    title = 'Output: y'
                else:
                    title = 'Output ' + str(i + 1) + ': y$_{' + str(i +
                                                                    1) + '}$'

                ytcks = [
                    2 * int(0.5 * min(y[i, :])), 0, 2 * int(0.5 * max(y[i, :]))
                ]
                ytcklabs = ['%d ' % ytcks[0], '0',
                            '%d' % ytcks[2]]

                self.axy.append(animaxis(f, ax, tit=title,\
                                    xlim=xlimit,\
                                    ylim=ylimit,\
                                    xcoords=(0.5, -0.03),\
                                    xtx = [],\
                                    xtlbs = '',\
                                    ytx = ytcks,\
                                    ytlbs = ytcklabs))
                self.axy[i].add_line(t, y[i, :], col='black', wdth=1)
                for j in range(0, self.n):
                    self.axy[i].add_line([], [],
                                         col=tudcols[0],
                                         wdth=1,
                                         style=styles[j])

        plt.show(False)
        plt.draw()
        plt.pause(5e-1)
        plt.savefig('frames/frame%d.' % 0, dpi=self.dpi)
Пример #56
0
            y_ = w_samples[:, 1]

            # Peform the kernel density estimate
            xmin, xmax = -6, 6
            ymin, ymax = -6, 6

            xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
            positions = np.vstack([xx.ravel(), yy.ravel()])
            values = np.vstack([x_, y_])
            kernel = st.gaussian_kde(values)
            f = np.reshape(kernel(positions).T, xx.shape)

            cfset = ax.contourf(xx, yy, f, cmap='Blues')
            plt.show()

            target_distribution = lambda x: np.exp(G_SVI.log_density(x))
            plot_isocontours(ax, target_distribution, cmap='Blues')
            var_distribution = lambda x: np.exp(
                log_variational(x, mean, logvar))
            plot_isocontours(ax, var_distribution, cmap='Reds')

            ax.set_autoscale_on(False)
            plt.draw()
            plt.pause(1.0 / 30.0)

    target_distribution = lambda x: np.exp(G_SVI.log_density(x))
    plot_isocontours(ax, target_distribution, cmap='Blues')
    var_distribution = lambda x: np.exp(log_variational(x, mean, logvar))
    plot_isocontours(ax, var_distribution, cmap='Reds')
    plt.show()
Пример #57
0
    def __init__(self,
                 f,
                 t,
                 w,
                 tit='def',
                 col=tudcols[0],
                 save=False,
                 Tvid='def',
                 fps=25,
                 dpi=100,
                 fmt='png'):

        nw = len(w[:, 0])
        Nw = len(w[0, :])
        if Tvid == 'def':
            Tvid = t[-1]
        else:
            Tvid = Tvid
        Nf = int(Tvid * fps)

        ybet = 0.02
        rght = 0.06
        lef = 0.02
        bot = 0.06

        hn = (1 - bot) / nw - ybet
        wn = 1 - lef - rght

        self.t = t

        self.axw = []
        for i in range(0, nw):
            ax = plt.axes([lef, 1 - (i + 1) * (hn + ybet), wn, hn])
            ymin = min(w[i, :])
            ymax = max(w[i, :])
            h = ymax - ymin
            ylimit = [ymin - 0.1 * h, ymax + 0.3 * h]
            ytcks = []
            ytcklabs = []

            if tit == 'def':
                title = 'Noise %d' % (i + 1)
            else:
                title = tit[i]
            if i == nw - 1:
                xlbl = 't (s)'
                xtcks = 'def'
                xtcklabs = 'def'
            else:
                xlbl = ''
                xtcks = []
                xtcklabs = ''

            self.axw.append(animaxis(f, ax, tit=title,\
                                xlim=t[[0,-1]],\
                                ylim=ylimit,\
                                xcoords=(0.6, -0.03),\
                                xtx = xtcks,\
                                xtlbs = xtcklabs,\
                                xlab = xlbl,\
                                ytx=ytcks,\
                                ytlbs=ytcklabs))

            self.axw[i].add_line(self.t[[0, -1]], [0, 0], col='black', wdth=2)
            self.axw[i].add_line([], [], col=tudcols[0], wdth=1)

        plt.show(False)
        plt.draw()
        plt.pause(1e-1)
        plt.savefig('frames/frame0.png', dpi=300)

        for fr in range(0, Nf):
            k = int(Nw * fr / Nf)
            for i in range(0, nw):
                self.axw[i].update_lines(t[:k], w[i, :k], 1)

            plt.pause(1e-2)
            if save:
                plt.savefig('frames/frame%d.' % fr + fmt, dpi=dpi)
Пример #58
0
 def update(self):
     plt.draw()
     plt.pause(0.001)
     input("Press [enter] to continue.")
Пример #59
0
    def __init__(self,
                 f,
                 t,
                 x,
                 y,
                 leg=[],
                 col=tudcols[0],
                 save=False,
                 win='def',
                 dpi=100,
                 fmt='png',
                 n=1,
                 styles=['-', '--', '-.', ':']):

        nx = len(x[:, 0])
        ny = len(y[:, 0])
        self.nx = nx
        self.ny = ny
        self.t = t
        self.win = win
        self.dpi = dpi
        self.fmt = fmt
        self.n = n
        self.styles = styles

        xbet = [0.02, 0.01]
        ybet = [0.06, 0.005]
        lef = 0.02
        bot = 0.06

        hs = (1 - bot - (nx + ny - 1) * ybet[1] - ybet[0]) / (nx + ny)
        ws = 1 - lef - xbet[1]

        self.axy = []
        for i in range(0, ny):
            ax = plt.axes([
                lef, 1 - (i + 1) * (hs + ybet[1]) - ybet[0] + ybet[1], ws, hs
            ])
            ymin = min(y[i, :])
            h = max(y[i, :]) - ymin
            ylimit = [ymin - 0.1 * h, ymin + 1.6 * h]
            if ny == 1:
                title = 'Output: y'
            else:
                title = 'Output ' + str(i + 1) + ': y$_{' + str(i + 1) + '}$'

            ytcks = [
                2 * int(0.5 * min(y[i, :])), 0, 2 * int(0.5 * max(y[i, :]))
            ]
            ytcklabs = ['%d ' % ytcks[0], '0',
                        '%d' % ytcks[2]]

            if self.win != 'def':
                xlimit = t[[0, win]]
            else:
                xlimit = t[[0, -1]]

            self.axy.append(animaxis(f, ax, tit=title,\
                                xlim=xlimit,\
                                ylim=ylimit,\
                                xcoords=(0.5, -0.03),\
                                xtx = [],\
                                xtlbs = '',\
                                ytx = ytcks,\
                                ytlbs = ytcklabs))
            self.axy[i].add_line(t, y[i, :], col='black', wdth=1)
            for j in range(0, n):
                self.axy[i].add_line([], [],
                                     col=tudcols[0],
                                     wdth=1,
                                     style=styles[j])

        self.axx = []
        for i in range(0, nx):
            ax = plt.axes([
                lef, 1 - (i + ny + 1) * (hs + ybet[1]) - ybet[0] + ybet[1], ws,
                hs
            ])
            ymin = min(x[i, :])
            h = max(x[i, :]) - ymin
            ylimit = [ymin - 0.1 * h, ymin + 1.6 * h]
            if nx == 1:
                title = 'Hidden state: x'
            else:
                title = 'Hidden state ' + str(i + 1) + ': x$_{' + str(i +
                                                                      1) + '}$'
            if i == nx - 1:
                xlbl = 't (s)'
                xtcks = 'def'
                xtcklabs = 'def'
            else:
                xlbl = ''
                xtcks = []
                xtcklabs = ''

            if self.win != 'def':
                xlimit = t[[0, win]]
            else:
                xlimit = t[[0, -1]]

            yrng = max(abs(min(x[i, :])), abs(min(x[i, :])))
            ytcks = [2 * int(-0.5 * yrng), 0, 2 * int(0.5 * yrng)]
            ytcklabs = ['%d ' % ytcks[0], '0',
                        '%d' % ytcks[2]]

            self.axx.append(animaxis(f, ax, tit=title,\
                                xlim=xlimit,\
                                ylim=ylimit,\
                                xcoords=(0.5, -0.03),\
                                xlab = xlbl,\
                                xtx = xtcks,\
                                xtlbs = xtcklabs,\
                                ytx = ytcks,\
                                ytlbs = ytcklabs))
            self.axx[i].add_line(t, x[i, :], col='black', wdth=1)
            for j in range(0, n):
                self.axx[i].add_line([], [],
                                     col=tudcols[0],
                                     wdth=1,
                                     style=styles[j])
            if i == 0:
                plt.legend(leg, loc=4)

        plt.show(False)
        plt.draw()
        plt.pause(1e-1)
        plt.savefig('frames/frame%d.' % 0 + self.fmt, dpi=self.dpi)
Пример #60
0
    def __init__(self,f,t,truth,data,col=tudcols[0],leg='def',\
                 save=False,Tvid='def',fps = 25,dpi=100,fmt='png',styles=['-','--','-.',':']):

        ybet = 0.01
        lef = 0.01
        rght = 0.01
        bot = 0.05

        p = len(truth[:, 0])
        N = len(truth[0, :])
        n = len(data)
        hf = (1 - p * ybet - bot) / p
        wf = 1 - lef - rght

        # Set titles
        tit = ['Signal layer ' + str(1) + ': ' + r'$\phi(t)$']
        for i in range(0, p):
            if i == 1:
                tit.append('Signal layer 2: ' + r'$\dot{\phi}(t)$')
            elif i == 2:
                tit.append('Signal layer 3: ' + r'$\ddot{\phi}(t)$')
            elif i > 2:
                tit.append('Signal layer ' + str(i+1) + ': ' + \
                           r'$\phi^{(' + str(i) + ')}(t)$')

        if Tvid == 'def':
            Tvid = t[-1]
        else:
            Tvid = Tvid
        Nf = int(Tvid * fps)

        self.t = t

        self.ax = []
        for i in range(0, p):
            ax = plt.axes([lef, 1 - (i + 1) * (hf + ybet), wf, hf])
            ymin = min(truth[i, :])
            ymax = max(truth[i, :])
            h = ymax - ymin
            ylimit = [ymin - 0.1 * h, ymax + 0.3 * h]
            ytcks = []
            ytcklabs = []
            if i == p - 1:
                xlbl = 't (s)'
                xtcks = 'def'
                xtcklabs = 'def'
            else:
                xlbl = ''
                xtcks = []
                xtcklabs = ''

            self.ax.append(animaxis(f, ax, tit=tit[i],\
                                xlim=t[[0,-1]],\
                                ylim=ylimit,\
                                xcoords=(0.5, -0.03),\
                                xtx = xtcks,\
                                xtlbs = xtcklabs,\
                                xlab = xlbl,\
                                ytx=ytcks,\
                                ytlbs=ytcklabs,\
                                pad = -20))

            self.ax[i].add_line(self.t, truth[i, :], col='black', wdth=2)
            for j in range(0, n):
                self.ax[i].add_line([], [],
                                    col=tudcols[0],
                                    wdth=1,
                                    style=styles[j])

        if leg != 'def':
            plt.legend(leg, loc=2)

        plt.show(False)
        plt.draw()
        plt.pause(1e-1)
        plt.savefig('frames/frame0.png', dpi=300)

        for fr in range(0, Nf):
            k = int(N * fr / Nf)
            for i in range(0, p):
                for j in range(0, n):
                    self.ax[i].update_lines(t[:k], data[j][i, :k], 1 + j)

            plt.pause(1e-2)
            if save:
                plt.savefig('frames/frame%d.' % fr + fmt, dpi=dpi)