예제 #1
0
def plotting(xgrid, vgrid, x, v, f, scalar_field, f0, timestep, plot_save,
             plot_show):
    if (plot_show == 1):
        plt.clf()
        plt.ion()
    # plt.subplot(2,1,1)
    plt.pcolormesh(xgrid, vgrid, f)
    plt.axis([x[0], x[-1], v[0], v[-1]])
    plt.xlabel('X', fontsize=20)
    plt.ylabel('V', fontsize=20)
    plt.title('Phase Space')

    # Electric Field Comparison
    # time = 0.02*timestep
    # Et = 4.0*0.01 * 0.3677 * np.exp(-0.1533*time)*np.sin(0.5*x)*np.cos(1.4156*time - 0.5326245)
    # plot_title = 't = '+str(timestep*0.02)
    # plt.plot(x,scalar_field)
    # plt.plot(x,Et)
    # plt.title(plot_title)

    # plt.subplot(2,1,2)
    # plt.plot(x,potential)
    # plt.xlabel('X')
    # plt.ylabel('$\phi$')
    if (plot_show == 1):
        plt.draw()
        plt.pause(.05)

    if (plot_save == 1):
        FIG_NAME = 'OUT/f_nonlinear_' + str(timestep) + '.png'
        plt.savefig(FIG_NAME)
예제 #2
0
    def plot(self):
        self._fig.clf()
        self._ax.cla()

        self._fig = plt.figure('taylor')
        self._ax = self._fig.add_subplot(1, 1, 1)

        self._ax.plot(self._x_list,
                      self._y_list,
                      linestyle='solid',
                      label='origin')
        for order in range(len(self._taylor_y_array)):
            label = '{} order approximation'.format(order + 1)
            self._ax.plot(self._x_list,
                          self._taylor_y_array[order],
                          linestyle='dashed',
                          label=label)
        self._ax.plot([self.base_x],
                      self._model.fx([self.base_x]),
                      marker='.',
                      label='approximation base point')

        self._ax.set_title('Taylor expansion')
        self._ax.legend(loc='lower right')
        self._ax.set_ylim(min(self._y_list), max(self._y_list))

        plt.pause(0.01)
예제 #3
0
    def on_epoch_end(self, epoch, logs={}):
        self.val_mse_acc.append(logs.get('val_mean_squared_error'))
        self.val_mae_acc.append(logs.get('val_mean_absolute_error'))
        self.mse_acc.append(logs.get('mean_squared_error'))
        self.mae_acc.append(logs.get('mean_absolute_error'))
        self.losses.append(logs.get('loss'))
        self.val_losses.append(logs.get('val_loss'))
        self.x.append(self.i)
        self.i += 1

        self.ax1.cla()
        self.ax2.cla()
        self.ax3.cla()
        self.ax1.set_title('Losses')
        self.ax1.set(ylabel='Logarithmic MSE')

        self.ax2.set_title('Accuracy (MSE)')
        self.ax2.set(ylabel='Mean Squared Error')

        self.ax3.set_title('Accuracy (MAE)')
        self.ax3.set(ylabel='Mean Absolute Error')

        self.ax1.plot(self.x, self.losses, label="loss")
        self.ax1.plot(self.x, self.val_losses, label="val_loss")
        self.ax1.legend(loc="upper right")
        self.ax2.plot(self.x, self.mse_acc, label="training")
        self.ax2.plot(self.x, self.val_mse_acc, label="validation")
        self.ax2.legend(loc="upper right")
        self.ax3.plot(self.x, self.mae_acc, label="training")
        self.ax3.plot(self.x, self.val_mae_acc, label="validation")
        self.ax3.legend(loc="upper right")

        plt.pause(.01)
        plt.draw()
        plt.savefig("lossaccplot.png", dpi='figure')
예제 #4
0
    def movieshow(self):
        self.var = self.dlg.comboBoxSpatialVariables.currentText()

        if self.var == 'Not Specified':
            QMessageBox.critical(self.dlg, "Error", "No variable is selected")
            return

        cmin = self.dlg.spinBoxMovieMin.value()
        cmax = self.dlg.spinBoxMovieMax.value()

        plt.figure(1, figsize=(9, 9), facecolor='white')
        plt.ion()
        index = 0
        for file in self.l:
            if file.startswith(self.var + '_') and file.endswith('.tif'):
                self.posAll.append(index)
            index += 1

        index = 0
        for i in self.posAll:
            gdal_dsm = gdal.Open(self.folderPath[0] + '/' + self.l[i])
            grid = gdal_dsm.ReadAsArray().astype(np.float)
            plt.imshow(grid, clim=(cmin, cmax))
            plt.title(self.l[i])
            if index == 0:
                plt.colorbar(orientation='horizontal')
            plt.show()
            plt.pause(0.5)
            index += 1

        del self.posAll[:]
예제 #5
0
파일: cosa6.py 프로젝트: Wenarepo/HOLArepo
def histogramac(histc):
    
    histc=histc.histogram(255)
    B.show()
    pylab.plot(histc)
    pylab.draw()
    pylab.pause(0.0001)
예제 #6
0
def wait(seconds):
    """Wait for specified seconds.

    Args:
        seconds: Time to wait. (waiting only the half to simulate faster)
    """
    plt.pause(seconds / 2)
def draw_graph(theta):

	#theta = math.pi/2 - theta

	t = np.linspace(0, 2, num=500) # Set time as 'continous' parameter.
	
	#for i in theta: # Calculate trajectory for every angle
	x1 = []
	y1 = []
	for k in t:
		x = ((v*k)*math.cos(theta)) 
		y = ((v*k)*math.sin(theta))-((0.5*9.81)*(k*k))
		x1.append(x)
		y1.append(y)
	p = [i for i, j in enumerate(y1) if j < 0] 

	for i in sorted(p, reverse = True):
		del x1[i]
		del y1[i]

	plot.axis([0.0,2.5, 0.0,2.0])
	ax = plot.gca()
	ax.set_autoscale_on(False)

	theta_deg = math.degrees(theta)	
	plot.plot(x1, y1, label='yServoAngle = %f' % theta_deg) # Plot for every angle
	plot.legend(loc='upper right')
	plot.ion()
	plot.pause(0.000000001)
	plot.draw() # And show on one graphic
	graph1.clear()
예제 #8
0
def sch_distPdist_linkage_fcluster(points, t, method='complete', metric='euclidean'):
    # 1. 层次聚类
    # 生成点与点之间的距离矩阵,这里用的欧氏距离:
    disMat = sch.distance.pdist(points, metric)
    #print(disMat)
    # 进行层次聚类:
    Z = sch.linkage(disMat, method, metric)
    # # 将层级聚类结果以树状图表示出来并保存为plot_dendrogram.png
    # P = sch.dendrogram(Z)
    # plt.savefig('plot_dendrogram.png')
    # # 根据linkage matrix Z得到聚类结果:
    cluster = sch.fcluster(Z, t, criterion='maxclust')
    #print("Original cluster by hierarchy clustering:\n", cluster)

    # PCA 主成份分析 用于结果的散点图显示
    pca = PCA(2)  # 选取2个主成份
    pca.fit(points)
    low_d = pca.transform(points)  # 降低维度

    plt.figure()
    mark = ['pb', 'or', 'ob', 'og', 'ok', 'oy', 'om', 'oc',
                  'sr', 'sb', 'sg', 'sk', 'sy', 'sm', 'sc',
                  'pr', 'pb', 'pg', 'pk', 'py', 'pm', 'pc',
                  'Dr', 'Db', 'Dg', 'Dk', 'Dy', 'Dm', 'Dc']
    for i in range(len(points)):
        markIndex = int(cluster[i])%28+1  # 为样本指定颜色
        plt.plot(low_d[i, 0], low_d[i, 1], mark[markIndex], markersize=6)
        #plt.text(points[i, 0], points[i, 1], i)
    plt.grid()
    plt.show()
    plt.pause(3)
    return cluster
예제 #9
0
def draw_epsilon(criteria,
                 initial_sample_size,
                 batch_size,
                 color,
                 fontsize=24,
                 isLegend=True):
    plt.figure(3, [8, 5])
    plt.clf()
    plt.ylim(-0.1, 1.1)
    for criterion in criteria:
        sample_size_list = np.arange(
            batch_size + initial_sample_size,
            batch_size * (criterion.error_ratio.shape[0] + 1) +
            initial_sample_size, batch_size)
        stopping_data_size = batch_size + initial_sample_size + criterion.stop_timings * batch_size
        plt.plot(sample_size_list, criterion.error_ratio, c="k")
        plt.plot([
            batch_size + initial_sample_size,
            batch_size * criterion.error_ratio.shape[0] + initial_sample_size
        ], [criterion.threshold, criterion.threshold],
                 c=color[criterion.criterion_name],
                 label=r"$\lambda={0}$".format(criterion.threshold))
        plt.plot([stopping_data_size, stopping_data_size],
                 [0, criterion.error_ratio.max()],
                 c=color[criterion.criterion_name],
                 linestyle="dashed")
    if isLegend:
        plt.legend(fontsize=fontsize)
    plt.xlabel("Sample size", fontsize=fontsize)
    plt.ylabel("Error ratio", fontsize=fontsize)
    plt.tick_params(labelsize=fontsize)
    plt.pause(0.01)
예제 #10
0
def draw_gene_error(test_error,
                    criteria,
                    initial_sample_size,
                    batch_size,
                    color,
                    fontsize=24,
                    isLegend=True):
    plt.figure(1, [8, 5])
    plt.clf()
    sample_size_list = np.arange(
        batch_size + initial_sample_size,
        batch_size * (test_error.shape[0] + 1) + initial_sample_size,
        batch_size)
    plt.plot(sample_size_list, test_error, c='k', label="Generalization error")
    for criterion in criteria:
        stopping_data_size = batch_size + initial_sample_size + criterion.stop_timings * batch_size
        plt.plot([stopping_data_size, stopping_data_size],
                 [test_error.min(), test_error.max()],
                 c=color[criterion.criterion_name],
                 linestyle="dashed",
                 label=r"$\lambda={0}$".format(criterion.threshold))
    if isLegend:
        plt.legend(fontsize=fontsize)
    plt.xlabel("Sample size", fontsize=fontsize)
    plt.ylabel("Generalization error", fontsize=fontsize)
    plt.tick_params(labelsize=fontsize)
    plt.pause(0.01)
예제 #11
0
def draw_correlations(result,
                      y_label,
                      data_names,
                      color,
                      label,
                      fontsize=24,
                      ylim=1):
    fig = plt.figure(4, [25, 10])
    plt.clf()
    plt.ylim(0, ylim)
    y_ticks = np.linspace(0, ylim, 11)
    sum_left = 0
    lefts = []
    for i, data_name_list in enumerate(data_names):
        left = np.arange(len(data_name_list)) + sum_left
        plt.bar(left,
                result[i],
                color=color[i],
                label=label[i],
                align="center",
                ecolor="k")
        sum_left += len(data_name_list)
        lefts.append(left)
    left = np.concatenate(lefts)
    data_names = list(itertools.chain.from_iterable(data_names))
    plt.xticks(left, data_names)
    fig.autofmt_xdate(rotation=20)
    plt.yticks(y_ticks)
    plt.ylabel(y_label, fontsize=fontsize)
    plt.tick_params(labelsize=fontsize)
    plt.legend(fontsize=fontsize, loc='lower left')
    plt.tight_layout()
    plt.grid(axis='y', linestyle='dotted', color='k')
    plt.pause(0.01)
예제 #12
0
    def plot(self, cmap='Greys', pause=1):

        if self.fig is None:
            self.fig = plt.figure(1, figsize=(24, 5))
            self.ax1 = self.fig.add_subplot(211)
            self.ax2 = self.fig.add_subplot(212)
            plt.tight_layout()
            #plt.show()
        else:
            plt.figure(1)

        #... build numpy array... FOR EXAMPLE :
        aview = np.random.randint(0, 2, (5, 300))
        pview = np.random.randint(0, 2, (5, 300))

        self.ax1.imshow(aview,
                        cmap=cmap,
                        interpolation='nearest',
                        aspect='auto')
        self.ax2.imshow(pview,
                        cmap=cmap,
                        interpolation='nearest',
                        aspect='auto')
        plt.pause(pause)
        self.fig.canvas.draw()
예제 #13
0
def plot_generated_batch(i, model,data1,data2):
    x_test, y_test = data1
    y_pred, x_recon = model.predict([x_test, y_test], batch_size=32)
    X_gen = x_recon
    X_raw = x_test   
    
    Xs1 = to3d(X_raw[:10])
    Xg1 = to3d(X_gen[:10])
    Xs1 = np.concatenate(Xs1, axis=1)
    Xg1 = np.concatenate(Xg1, axis=1)
    Xs2 = to3d(X_raw[10:20])
    Xg2 = to3d(X_gen[10:20])
    Xs2 = np.concatenate(Xs2, axis=1)
    Xg2 = np.concatenate(Xg2, axis=1)
    
    x_train, y_train = data2
    y_pred, x_recon = model.predict([x_train, y_train], batch_size=32)
    X_gen = x_recon
    X_raw = x_train   
    
    Xs3 = to3d(X_raw[:10])
    Xg3 = to3d(X_gen[:10])
    Xs3 = np.concatenate(Xs3, axis=1)
    Xg3 = np.concatenate(Xg3, axis=1)
    Xs4 = to3d(X_raw[10:20])
    Xg4 = to3d(X_gen[10:20])
    Xs4 = np.concatenate(Xs4, axis=1)
    Xg4 = np.concatenate(Xg4, axis=1)

    XX = np.concatenate((Xs1,Xg1,Xs2,Xg2,Xs3,Xg3,Xs4,Xg4), axis=0)
    plt.imshow(XX)
    plt.axis('off')
    plt.savefig("./caps_figures/CapsAutoencoder{0:03d}.png".format(i))
    plt.pause(3)
    plt.close()
예제 #14
0
    def rysuj(self):
        try:
            parA = float(self.parAedit.text())
            parB = float(self.parBedit.text())
            parC = float(self.parCedit.text())
            if parA == 0 and parB == 0 and parC == 0:
                QMessageBox.warning(self, '', "Funkjca tożsamościowa")
                return
            xlist = []
            y = []
            import numpy as np
            x = np.linspace(-20, 10)
            fig, ax = plt.subplots()
            ax.axhline(y=0, color='k')
            ax.axvline(x=0, color='k')
            ax.grid(True, which='both')
            #plt.grid(b=None, which='major', axis='both', color='b', linestyle='-', linewidth=2)
            for x in self.drange(-10, 10, 0.5):
                y.append(parA * x**2 + parB * x + parC)
                xlist.append(x)
                plt.plot(xlist, y)
                plt.pause(0.001)

            plt.show()
        except ValueError:
            QMessageBox.critical(self, "Błąd", "Zły parametr")
            return
def main(a):
    K = 0  #循环次数控制
    algo_choose(a)
    init()
    fit_list = []
    temp = 0
    while (True):
        for i in range(n):
            swarm[i].refresh_memory()
        for i in range(n):
            swarm[i].refresh_pos()
        cal_FitXm()
        cal_standard_deviation()
        for i in range(n):
            group = int(i / (n / M))
            #print(group)
            swarm[i].escape(group)
        update_Td()
        print(swarm_best_fitness, swarm_best_pos)
        #if (#精度控制条件#):
        #	break			#到达一定精度退出程序
        fit_list.append(swarm_best_fitness)
        plt.plot(fit_list)
        plt.draw()
        plt.pause(0.01)
        plt.clf()
        K = K + 1
        temp = swarm_best_fitness
        if K == 100:  #到达一定次数退出程序
            break
def main():
    global df
    poss_reproduct = 0.1  #繁殖的概率
    poss_hybridize = 0.3  #杂交的概率
    poss_mutate = 0.6  #变异的概率
    for i in range(100000):
        te = poss_for_reproduct(df)
        r = np.random.random(1)[0]
        if (r < poss_reproduct):
            df = reproduct(te)
            print(1)
        if (poss_reproduct < r < poss_reproduct + poss_hybridize):
            df = hybridize(te)
            print('2')
        if (poss_reproduct + poss_hybridize < r):
            #pass
            df = mutate(te)
            print('3')
        if (i % 10 == 0):
            test = list(df.loc[te.loc[0]['ind']])
            plot(test)
            plt.draw()
            plt.pause(0.01)
            plt.clf()
        print(te.loc[0][0])
        #print(df)
        #print(df.loc[te.loc[0]['ind']])
        test = list(df.loc[te.loc[0]['ind']])
예제 #17
0
def histograma(hist):
    
    hist=hist.histogram(255)
##    hist.save("hola4Hist.txt")
    pylab.plot(hist)
    pylab.draw()
    pylab.pause(0.0001)
예제 #18
0
def B_method(p, len):
    d = get_distance2(p[0], p[1])
    a = 0
    b = 1
    plt.plot([p[a].x, p[b].x], [p[a].y, p[b].y], color='r')
    plt.pause(1)
    for i in range(len - 1):
        for j in range(i + 1, len):
            if i == 0 and j == 1:
                continue
            distance2 = get_distance2(p[i], p[j])
            plt.plot([p[i].x, p[j].x], [p[i].y, p[j].y], color='B', ls='--')
            plt.pause(1)
            plt.plot([p[i].x, p[j].x], [p[i].y, p[j].y], color='W', alpha=0.99)
            plt.pause(1)
            if distance2 < d:
                plt.plot([p[a].x, p[b].x], [p[a].y, p[b].y],
                         color='W',
                         alpha=0.99)
                plt.pause(1)
                a = i
                b = j
                d = distance2
                plt.plot([p[i].x, p[j].x], [p[i].y, p[j].y], color='r')
                plt.pause(1)

    print("最近点对为:(%.2f,%.2f) 和 (%.2f,%.2f),距离为: %.2f" %
          (p[a].x, p[a].y, p[b].x, p[b].y, math.sqrt(d)))
    def plot(self, bit_stream):
        if self.previous_bit_stream != bit_stream.to_list():
            self.previous_bit_stream = bit_stream

            x = []
            y = []
            bit = None

            for bit_time in bit_stream.to_list():
                if bit is None:
                    x.append(bit_time)
                    y.append(0)
                    bit = 0
                elif bit == 0:
                    x.extend([bit_time, bit_time])
                    y.extend([0, 1])
                    bit = 1
                elif bit == 1:
                    x.extend([bit_time, bit_time])
                    y.extend([1, 0])
                    bit = 0

            plt.clf()
            plt.plot(x, y)
            plt.xlim([0, 10000])
            plt.ylim([-0.1, 1.1])
            plt.show()
            plt.pause(0.005)
예제 #20
0
 def do_next(self, args):
     """next: Shows the next epoch in the animation"""
     obs = self.obs
     obs.next_epoch()
     obs.get_predictions()
     obs.show_predictions()
     plt.pause(0.000001)
예제 #21
0
def animate(y, ndim, cmap) :
    plt.ion()

    if ndim == 5:
        plt.figure()
        plt.show()
        for i in range(y.shape[1]) :
            print "Showing batch", i
            plt.close('all')
            for j in range(y.shape[0]) :
                plt.imshow(y[j,i], interpolation='none', cmap=cmap)
                plt.pause(0.1)

            time.sleep(1)
    else:
        for i in range(y.shape[1]) :
            print "Showing batch", i
            plt.close('all')
            for j in range(y.shape[0]) :
                plt.figure(0)
                plt.imshow(y[j,i], interpolation='none', cmap=cmap)
                plt.figure(1)
                plt.imshow(x[j,i], interpolation='none', cmap=cmap)
                plt.pause(0.2)

            time.sleep(1)
예제 #22
0
def return_param_BPM(even_odd, hist_val, num):
    if even_odd == "odd":
        eo = 1
    else:
        eo = 0
    # print(even_odd,hist_val)
    histValues = plt.hist(df[(df['y_vals'] % 2 == eo)
                             & (df['heights'] < 100)][hist_val],
                          bins=45)
    mphist = midpoints(histValues[1])
    meanh = df[(df['y_vals'] % 2 == eo) & (df['heights'] < 100) &
               (df['means'] > 0)][hist_val].mean()
    stdh = df[(df['y_vals'] % 2 == eo) & (df['heights'] < 100) &
              (df['means'] > 0)][hist_val].std()
    print(meanh, stdh)

    popt, pcov = curve_fit(gaus,
                           mphist[2:],
                           histValues[0][2:],
                           p0=[100, meanh, stdh])
    plt.plot(mphist, gaus(mphist, *popt), 'ro:', label='fit')
    plt.pause(0.01)
    input("wait")
    #     plt.show()
    plt.clf()
    return popt[1], popt[2]
def show():
    args = get_args()

    # Load model
    nn.load_parameters(args.model_load_path)
    params = nn.get_parameters()

    # Show heatmap
    for name, param in params.items():
        # SSL only on convolution weights
        if "conv/W" not in name:
            continue
        print(name)
        n, m, k0, k1 = param.d.shape
        w_matrix = param.d.reshape((n, m * k0 * k1))
        # Filter x Channel heatmap

        fig, ax = plt.subplots()
        ax.set_title(
            "{} with shape {} \n Filter x (Channel x Heigh x Width)".format(
                name, (n, m, k0, k1)))
        heatmap = ax.pcolor(w_matrix)
        fig.colorbar(heatmap)

        plt.pause(0.5)
        raw_input("Press Key")
        plt.close()
예제 #24
0
 def ani(t):
     train_op(t, x, y)
     fig.clf()
     ax = fig.add_subplot(111)
     pts = 300
     pylab.plot(x.data.numpy().ravel(), y.data.numpy().ravel(), 'r.')
     x_plot = Variable(
         torch.linspace(
             torch.min(x.data) - 1.,
             torch.max(x.data) + 1., pts)[:, None])
     y_plot = torch.Tensor(0, 1)
     for _ in range(100):
         y_plot = torch.cat([y_plot, model(x_plot).data], 1)
     y_mu = torch.mean(y_pred, 1).numpy()
     y_std = torch.std(y_pred, 1).numpy()
     errors = [0.25, 0.39, 0.52, 0.67, 0.84, 1.04, 1.28, 1.64, 2.2]
     for e in errors:
         ax.fill_between(x_plot.data.numpy().ravel(),
                         y_mu - e * y_std,
                         y_mu + e * y_std,
                         alpha=((3 - e) / 5.5)**1.7,
                         facecolor='b',
                         linewidth=1e-3)
     pylab.plot(x_plot.data.numpy().ravel(), y_mu, 'k')
     ax.set_ylim([torch.min(y.data) - 1, torch.max(y.data) + 1])
     ax.set_xlim([torch.min(x.data) - 1, torch.max(x.data) + 1])
     pylab.pause(.1)
     return ax
예제 #25
0
    def plot(self):
        if not self.__first:
            self.__fig.clf()
            self.__ax.cla()
        self.__first = False

        self.__fig = plt.figure('residual')
        self.__ax = self.__fig.add_subplot(1, 1, 1)

        # 現在のパラメータを中心にプロットするためのrangeを計算
        self._reset_range()

        # 現在のパラメータを履歴に追加
        current_param = self.__model.get_param()
        self._param_history[0].append(current_param[0])
        self._param_history[1].append(current_param[1])

        # パラメータを書き換えるのでコピーして参照している他のモジュールへの影響を防ぐ
        model = deepcopy(self.__model)
        Z = self._compute_residual_distribution(model)

        im = self.__ax.pcolormesh(self.__X, self.__Y, Z, cmap='hsv')
        self.__ax.plot(self._param_history[0],
                       self._param_history[1],
                       marker='.')
        self.__fig.colorbar(im)

        plt.pause(0.01)
def plot_weight_matrix(rbm_struct, weight_matrix, input_nodes, hidden_nodes):

    #mat_to_plot = np.zeros([n_hidden_nodes, n_visible_nodes-1])
    sub_mat_val = int(m.sqrt(input_nodes))
    total_mat_val = int(m.sqrt(hidden_nodes))

    reshaped_mat = np.zeros([hidden_nodes, sub_mat_val, sub_mat_val])
    plot_mat = np.zeros(
        [total_mat_val, total_mat_val, sub_mat_val, sub_mat_val])

    for i in range(0, input_nodes):
        a = np.reshape(rbm_struct.weights[i][1][:], (529, 1))
        b = np.reshape(a, (23, 23))
        mplt.imshow(b, cmap='gray')
        mplt.draw()
        mplt.pause(0.001)
        a = 'weight_matrix' + str(i) + '.png'
        mplt.savefig(a)
    #for i in range(0, hidden_nodes):
    #    mat_to_plot = weight_matrix[i][1][:input_nodes]
    #    mat_to_plot = np.reshape(mat_to_plot, (rbm_struct.h_val, 1))
    #    reshaped_mat[i][:][:] = np.reshape(mat_to_plot, (sub_mat_val, sub_mat_val))

    plot_mat = np.reshape(
        reshaped_mat, (total_mat_val, total_mat_val, sub_mat_val, sub_mat_val))
    for i in range(0, total_mat_val):
        for j in range(0, total_mat_val):
            mplt.imshow(plot_mat[i][j], cmap='gray')
            mplt.show()
예제 #27
0
def plotCurrentW(ww, currentData, flush=True):
    # Plot the randomly generated data
    plt.scatter(currentData[currentData["yp"] == 1]["x1"],
                currentData[currentData["yp"] == 1]["x2"],
                marker="o")
    plt.scatter(currentData[currentData["yp"] == -1]["x1"],
                currentData[currentData["yp"] == -1]["x2"],
                marker="x")
    plt.xlim(-1, 1)
    plt.ylim(-1, 1)
    plt.xlabel("x1")
    plt.ylabel("x2")

    # Create data points corresponding the the weights so that they can be plotted on the graph
    wDict = {'x1': [], 'x2': []}
    leftx2 = (ww[1] - ww[0]) / ww[2]
    rightx2 = (-ww[1] - ww[0]) / ww[2]

    wDict["x1"].append(-1.0)
    wDict["x2"].append(leftx2)
    wDict["x1"].append(1.0)
    wDict["x2"].append(rightx2)

    resultW = pd.DataFrame(wDict)

    # Plot the corresponding classification separating line
    plt.plot(resultW.x1, resultW.x2)

    if flush:
        plt.draw()
        plt.pause(0.1)
        plt.clf()
    else:
        plt.show()
예제 #28
0
파일: rrt.py 프로젝트: elishafer/rrt2
    def draw_graph(self, rnd=None):  # pragma: no cover
        """
        Draw Graph
        """
        plt.clf()
        if rnd is not None:
            plt.plot(rnd[0], rnd[1], "^k")
        for node in self.nodes:
            if node.parent is not None:
                plt.plot([node.x[0], self.nodes[node.parent].x[0]],
                         [node.x[1], self.nodes[node.parent].x[1]], "-g")

        circles = []
        fig = plt.gcf()
        ax = fig.gca()
        for (ox, oy, size) in self.obstacle_list:
            # plt.plot(ox, oy, "ok", ms=30 * size)
            circle = plt.Circle((ox, oy), size, fill=False)
            circles.append(circle)
        p = PatchCollection(circles)
        ax.add_collection(p)
        ax.set_aspect('equal')

        plt.plot(self.start[0], self.start[1], "xr")
        plt.plot(self.goal[0], self.goal[1], "xr")
        plt.axis([
            self.c_space_bounds[0][0], self.c_space_bounds[0][1],
            self.c_space_bounds[1][0], self.c_space_bounds[1][1]
        ])
        plt.grid(True)
        plt.pause(0.01)
예제 #29
0
 def drawing(x):
     plt.figure(num=1)
     plt.plot(x, color='g', linewidth=0.8)
     plt.title('prob')
     plt.grid()
     plt.legend(['loss'])
     plt.pause(0.0001)
예제 #30
0
def imshow(inp, title=None):
    """Imshow for Tensor."""
    inp = inp.numpy().transpose((1, 2, 0))
    plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)  # pause a bit so that plots are updated
예제 #31
0
 def ani(t):
     train_op(t, x, y)
     fig.clf()
     ax = fig.add_subplot(111)
     pts = 300
     pylab.plot(x.data.numpy().ravel(), y.data.numpy().ravel(), 'r.')
     x_plot = Variable(
         torch.linspace(
             torch.min(x.data) - 1.,
             torch.max(x.data) + 1., pts)[:, None])
     y_plot = np.linspace(
         torch.min(y.data) - 1.,
         torch.max(y.data) + 1., pts)[:, None]
     y_pred = torch.Tensor(0, 1)
     for _ in range(100):
         y_pred = torch.cat([y_pred, model(x_plot).data], 1)
     y_mu = torch.mean(y_pred, 1).numpy()
     y_std = torch.std(y_pred, 1).numpy()
     kde_skl = KernelDensity(bandwidth=0.5)
     grid = []
     for i in range(pts):
         kde_skl.fit(y_pred.numpy()[i][:, None])
         log_pdf = kde_skl.score_samples(y_plot)
         grid.append(np.exp(log_pdf)[:, None])
     grid = np.asarray(grid).reshape((pts, pts)).T
     ax.imshow(grid,
               extent=(x_plot.data.numpy().min(),
                       x_plot.data.numpy().max(), y_plot.max(),
                       y_plot.min()),
               interpolation='bicubic',
               cmap=cm.Blues)
     ax.set_ylim([torch.min(y.data) - 1, torch.max(y.data) + 1])
     ax.set_xlim([torch.min(x.data) - 1, torch.max(x.data) + 1])
     pylab.pause(.5)
     return ax
예제 #32
0
def imshow(inp, title=None):
    """Imshow for Tensor."""
    import matplotlib.pylab as plt
    inp = inp.numpy().transpose((1, 2, 0))
    plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)  # 갱신이 될 때까지 잠시 기다립니다.
예제 #33
0
    def DisplayData(self,
                    data,
                    rec=None,
                    fut=None,
                    fig=1,
                    case_id=0,
                    output_file=None):
        output_file1 = output_file2 = None
        if output_file is not None:
            name, ext = os.path.splitext(output_file)
            output_file1 = '%s_original%s' % (name, ext)
            output_file2 = '%s_recon%s' % (name, ext)
        data = data[case_id, :].reshape(-1, self.image_size_, self.image_size_)
        if rec is not None:
            rec = rec[case_id, :].reshape(-1, self.image_size_,
                                          self.image_size_)
            enc_seq_length = rec.shape[0]
        if fut is not None:
            fut = fut[case_id, :].reshape(-1, self.image_size_,
                                          self.image_size_)
            if rec is None:
                enc_seq_length = self.seq_length_ - fut.shape[0]
            else:
                assert enc_seq_length == self.seq_length_ - fut.shape[0]
        num_rows = 1
        plt.figure(2 * fig - 1, figsize=(20, 1))
        plt.clf()
        for i in xrange(self.seq_length_):
            plt.subplot(num_rows, self.seq_length_, i + 1)
            plt.imshow(data[i, :, :],
                       cmap=plt.cm.gray,
                       interpolation="nearest")
            plt.axis('off')
        plt.draw()
        if output_file1 is not None:
            print output_file1
            plt.savefig(output_file1, bbox_inches='tight')

        plt.figure(2 * fig, figsize=(20, 1))
        plt.clf()
        for i in xrange(self.seq_length_):
            if rec is not None and i < enc_seq_length:
                plt.subplot(num_rows, self.seq_length_, i + 1)
                plt.imshow(rec[rec.shape[0] - i - 1, :, :],
                           cmap=plt.cm.gray,
                           interpolation="nearest")
            if fut is not None and i >= enc_seq_length:
                plt.subplot(num_rows, self.seq_length_, i + 1)
                plt.imshow(fut[i - enc_seq_length, :, :],
                           cmap=plt.cm.gray,
                           interpolation="nearest")
            plt.axis('off')
        plt.draw()
        if output_file2 is not None:
            print output_file2
            plt.savefig(output_file2, bbox_inches='tight')
        else:
            plt.pause(0.1)
def plot_data():
    datalist = [ ( plt.loadtxt("myfile.txt"), "label")]

    for data, label in datalist:
        plt.plot( data[:,0], data[:,1], label=label )

    plt.legend()
    plt.title("Plot of coupled oscillator")
    plt.xlabel("Time")
    plt.ylabel("Position")
    plt.show()
    plt.pause(0.000005)
예제 #35
0
def sample02(fnum):
    # インタラクティブモード
    x = np.mat(np.r_[0:1:0.01])
    y2 = np.power(x,2)
    pl.ion() #非インタラクティブにする
    pl.figure(fnum)
    pl.plot(x.A1, y2.A1) #これは成功 
    pl.grid(True)
#    pl.show() #インタラクティブモードだと、showは使わない
    pl.draw() #drawを使う
    print "end2"
#     time.sleep(1)
    pl.pause(1)
예제 #36
0
    def plot(self, title='', confidence_interval=DEFAULT_CONFIDENCE_INTERVAL, block=False, pause=0, figsize=None):

        self.init_dataframe_errors(confidence_interval)

        assert isinstance(self, Results)

        if not self.periods:
            raise ValueError("Results have no periods to plot")

        fig, axes = plt.subplots(nrows=3, ncols=1, figsize=figsize)

        if title:
            fig.canvas.set_window_title(title)

        if isinstance(self.observation_date, datetime.datetime):
            observation_date = self.observation_date.date()
        else:
            observation_date = self.observation_date

        fig.suptitle('Obs {}, rate {}%, path {}, pert {}, conf {}%'.format(
            observation_date, self.interest_rate, self.path_count,
            self.perturbation_factor,
            confidence_interval))

        with pandas.plotting.plot_params.use('x_compat', False):

            # Todo: Try to get the box plots working:
            # https://stackoverflow.com/questions/38120688/pandas-box-plot-for-multiple-column

            # if len(results.prices_raw) == 1:
            #     prices = results.prices_raw[0]
            #     seaborn.boxplot(prices, prices.to_series().apply(lambda x: x.strftime('%Y%m%d')), ax=axes[0])

            self.prices_mean.plot(ax=axes[0], kind='bar', yerr=self.prices_errors)
            axes[0].set_title('Market prices')
            axes[0].get_xaxis().set_visible(False)

            self.hedges_mean.plot(ax=axes[1], kind='bar', yerr=self.hedges_errors).axhline(0, color='0.5')
            axes[1].set_title('Delta hedges')
            axes[1].get_xaxis().set_visible(False)

            self.cash_mean.plot(ax=axes[2], kind='bar', yerr=self.cash_errors, color='g').axhline(0, color='0.5')
            axes[2].set_title('Cash account')
            axes[2].get_xaxis().set_visible(True)

        fig.autofmt_xdate(rotation=30)

        if pause and not block:
            plt.pause(pause)
        else:
            plt.show(block=block)
예제 #37
0
def animate_signals(nb_signals, incre, fs=256, refresh_rate=30., anim_dur=10., figsize=(12,8)):
    """
    Draw and update a figure in real-time representing the summation of many 
    sine waves, to explain the concept of Fourier decomposition.
    
    INPUTS
     nb_signals   : number of signals to sum together
     incre        : increment, in Hz, between each of the signals
     fs           : sampling frequency
     refresh_rate : refresh rate of the animation
     anim_dur     : approximate duration of the animation, in seconds
    """
    
    # Initialize values that remain constant throughout the animation
    A = 1
    t = np.linspace(0, 2, fs)
    offsets = np.arange(nb_signals+1).reshape((nb_signals+1,1))*(A*(nb_signals+1))
    freqs = np.arange(nb_signals)*incre
        
    # Initialize the figure
    fig, ax = plt.subplots(figsize=figsize)
    ax.hold(True)
    plt.xlabel('Time')
    ax.yaxis.set_ticks(offsets)
    ax.set_yticklabels([str(f)+' Hz' for f in freqs] + ['Sum'])
    ax.xaxis.set_ticks([]) 
    
    # Initialize the Line2D elements for each signal
    sines = np.array([sinewave(A, f, 0, t) for f in freqs])
    sines = np.vstack((sines, np.sum(sines, axis=0))) + offsets
    points = [ax.plot(t, x)[0] for x in sines]

    # Animation refresh loop
    for i in np.arange(anim_dur*refresh_rate):     
        
        # Update time
        t = np.linspace(0, 2, fs) + i*fs/refresh_rate
        
        # Update signals
        sines = np.array([sinewave(A, f, 0, t) for f in freqs])
        sines = np.vstack((sines, np.sum(sines, axis=0))) + offsets
    
        # Update figure
        for p, x in zip(points, sines):
            p.set_ydata(x)
        
        # Wait before starting another cycle
        plt.pause(1./refresh_rate)
def cruiseControllerNoPID(n, req_speed, initial_speed = 0, accelerate_step = 1):
    speeds = []
    current_speed = initial_speed
    ns = []
    x = 0
    acc = []
    
    while x < n + 1:
        x += 1

        #print current_speed
        
        #plt.axis([-10, n + 10 , -10, req_speed + 10])
        plt.axis([-10, n + 10 , -1.5, 0.75])
        speeds.append(current_speed)
        
        
        acc.append(speeds[x - 1] - speeds[x - 2])
        ns.append(x)
        #plt.plot(ns, speeds, 'g-',label = "speed")
        plt.plot(ns, acc, 'r-', label = "input (force applied to pedal)")
        
        if (x == 1):
            plt.legend()

        plt.xlabel("time")
        plt.ylabel("Input (Force applied to pedal)")
        
        
        plt.pause(0.000001)


        if (current_speed < req_speed):
            #accelerate
            current_speed += accelerate_step
            
        elif (current_speed > req_speed):
            #apply brakes
            current_speed -= accelerate_step

        else:
            #speed reduction when pedal isn't pressed
            current_speed -= 1

        if (current_speed < 0):
            current_speed = 0
def PIDController(n, req_speed, initial_speed = 0, accelerate_step = 1):
    speeds = []
    current_speed = initial_speed
    ns = []
    x = 0
    acc = []
    req_speeds = []
    accumulated_e = 0
    
    while x < n + 1:
        x += 1
        #print current_speed
        
        plt.axis([-10, n + 10 , -10, req_speed + 10])
        #plt.axis([-10, n + 10 , -1.5, 0.75])
        speeds.append(current_speed)
        req_speeds.append(req_speed)
        acc.append(speeds[x - 1] - speeds[x - 2])
        ns.append(x)
        plt.plot(ns, speeds, 'g-',label = "speed")
        plt.plot(ns, req_speeds, 'r--', label = "required speed")
        #plt.plot(ns, acc, 'r-', label = "input (force applied to pedal)")
        
        if (x == 1):
            plt.legend()

        plt.xlabel("time")
        plt.ylabel("Car's speed")
        
        
        plt.pause(0.000001)

        drag = 0.03 
        e = req_speed - current_speed
       
        KI = 0.07
        Kd = 0.1
        Kp = 0.1

        accumulated_e += e
        diff_e = speeds[x - 1] - speeds[x - 2]

        current_speed += (e * Kp - drag * current_speed) + (Kp * accumulated_e) + (Kd * diff_e) 

        print current_speed
예제 #40
0
  def DisplayData(self, data, rec=None, fut=None, fig=1, case_id=0, output_file=None):
    output_file1 = output_file2 = None
    if output_file is not None:
      name, ext = os.path.splitext(output_file)
      output_file1 = '%s_original%s' % (name, ext)
      output_file2 = '%s_recon%s' % (name, ext)
    data = data[case_id, :].reshape(-1, self.image_size_, self.image_size_)
    if rec is not None:
      rec = rec[case_id, :].reshape(-1, self.image_size_, self.image_size_)
      enc_seq_length = rec.shape[0]
    if fut is not None:
      fut = fut[case_id, :].reshape(-1, self.image_size_, self.image_size_)
      if rec is None:
        enc_seq_length = self.seq_length_ - fut.shape[0]
      else:
        assert enc_seq_length == self.seq_length_ - fut.shape[0]
    num_rows = 1
    plt.figure(2*fig-1, figsize=(20, 1))
    plt.clf()
    for i in xrange(self.seq_length_):
      plt.subplot(num_rows, self.seq_length_, i+1)
      plt.imshow(data[i, :, :], cmap=plt.cm.gray, interpolation="nearest")
      plt.axis('off')
    plt.draw()
    if output_file1 is not None:
      print output_file1
      plt.savefig(output_file1, bbox_inches='tight')

    plt.figure(2*fig, figsize=(20, 1))
    plt.clf()
    for i in xrange(self.seq_length_):
      if rec is not None and i < enc_seq_length:
        plt.subplot(num_rows, self.seq_length_, i + 1)
        plt.imshow(rec[rec.shape[0] - i - 1, :, :], cmap=plt.cm.gray, interpolation="nearest")
      if fut is not None and i >= enc_seq_length:
        plt.subplot(num_rows, self.seq_length_, i + 1)
        plt.imshow(fut[i - enc_seq_length, :, :], cmap=plt.cm.gray, interpolation="nearest")
      plt.axis('off')
    plt.draw()
    if output_file2 is not None:
      print output_file2
      plt.savefig(output_file2, bbox_inches='tight')
    else:
      plt.pause(0.1)
예제 #41
0
파일: anim_test.py 프로젝트: vsraptor/bbhtm
	def plot(self, cmap='Greys',pause=1):

		if self.fig is None :
			self.fig = plt.figure(1,figsize=(24,5))
			self.ax1 = self.fig.add_subplot(211)
			self.ax2 = self.fig.add_subplot(212)
			plt.tight_layout()
			#plt.show()
		else :
			plt.figure(1)

		#... build numpy array... FOR EXAMPLE :
		aview = np.random.randint(0,2,(5,300))
		pview = np.random.randint(0,2,(5,300))

		self.ax1.imshow(aview, cmap=cmap, interpolation='nearest', aspect='auto')
		self.ax2.imshow(pview, cmap=cmap, interpolation='nearest', aspect='auto')
		plt.pause(pause)
		self.fig.canvas.draw()
예제 #42
0
	def showImg (self):
		if self._pltmoon == 1:
			# Convert UTC unix time to datetime
			self._obssite.date = datetime.datetime.fromtimestamp(self._im._tobs); 

			# Compute azi/alt
			self._moon.compute(self._obssite);
			self._casa.compute(self._obssite);


			if self._moon.alt < 0:
				print 'Moon below horizon at time ', _obssite.date;
			else:
				# Compute l,m of moon's position, in units of array indices

				moon_l = -(numpy.cos(self._moon.alt) * numpy.sin(self._moon.az));
				moon_m =  (numpy.cos(self._moon.alt) * numpy.cos(self._moon.az)); 
				# print 'l/m: %f, %f' % (moon_l, moon_m);
				moon_l = moon_l/self._im._dl + self._im._npix/2;
				moon_m = moon_m/self._im._dl + self._im._npix/2;
				# print 'Moon: RA/dec = %f/%f, alt/az = %f/%f, lind/mind = %f/%f, dl=%f'% (self._moon.ra, self._moon.dec, self._moon.alt, self._moon.az, moon_l, moon_m, self._im._dl);

				casa_l = -(numpy.cos(self._casa.alt) * numpy.sin(self._casa.az));
				casa_m =  (numpy.cos(self._casa.alt) * numpy.cos(self._casa.az)); 
				# print 'l/m: %f, %f' % (casa_l, casa_m);
				casa_l = casa_l/self._im._dl + self._im._npix/2;
				casa_m = casa_m/self._im._dl + self._im._npix/2;
				# print 'CasA: RA/dec = %f/%f, alt/az = %f/%f, lind/mind = %f/%f, dl=%f'% (self._casa.ra, self._casa.dec, self._casa.alt, self._casa.az, casa_l, casa_m, self._im._dl);


			# Create a circle in the skymap centered at the location of the moon.
			# blacking out a couple of pixels for now. 
			self._im._skymap[moon_m-1:moon_m+1, moon_l-1:moon_l+1] = 5e10;	
			self._im._skymap[casa_m-1:casa_m+1, casa_l-1:casa_l+1] = 5e10;	
			

		self._imgplt.set_data (abs(self._im._skymap[:,:]));

		plt.title ('XX - %f' % self._im._tobs);
		plt.draw();
		plt.pause(0.001);
		if self._wrpng == 1:
			plt.savefig ('%s/%.0f_XX.png' % (self._fprefix,self._im._tobs));
예제 #43
0
def classify(im, K, show=False):
    """ classify    - classify an image using k-means algorithm.

    Arguments:
        * im            - an image (ndarray) or a filename.
        * K             - number of classes.
        * show  = False - if True, display the image and the classes.

    Return:
        * imClasses     - the classes of the image (ndarray, 2D).

    See also:
        * kMeans        - K-means algorithm.
    """
    a = Image(im)
    a = a.histogram(255)
    
    # Load image
    if type(im) is str:
        im = plt.imread(im)

    # Reshape and apply k-mean
    values = im.reshape((im.shape[0] * im.shape[1], -1))
    centers, classes = kMeans(values, K)
    imClasses = classes.reshape((im.shape[0], im.shape[1]))
##    imClasses.save("imClassesH.png")
##    imClassesHl=image("imClassesH.png")
##    imClassHisto=imClassesH1.histogram(255)
    
    
    # Display
    if show:
                
        cmap = 'gray' if im.ndim < 3 else None
        plt.subplot(221), plt.imshow(im, cmap=cmap), plt.title('Imagen Gray')
        plt.subplot(222), plt.imshow(imClasses), plt.title('Segmentacion por Clases')
        pylab.subplot(223), pylab.plot(a), pylab.draw(), pylab.pause(0.0001), pylab.title('Histograma Img Gray')
        pylab.subplot(224), pylab.plot(a), pylab.draw(), pylab.pause(0.0001), pylab.title('Histograma Img Segmentada')
        plt.show()

    # The end
    return imClasses
예제 #44
0
    def showImg(self):
        if self._pltmoon == 1:
            # Convert UTC unix time to datetime
            self._obssite.date = datetime.datetime.fromtimestamp(self._im[0]._tobs)

            # Compute azi/alt
            self._moon.compute(self._obssite)
            self._casa.compute(self._obssite)

            if self._moon.alt < 0:
                print "Moon below horizon at time ", self._obssite.date
            else:
                # Compute l,m of moon's position, in units of array indices

                moon_l = -(numpy.cos(self._moon.alt) * numpy.sin(self._moon.az))
                moon_m = numpy.cos(self._moon.alt) * numpy.cos(self._moon.az)
                print "moon l/m: %f, %f" % (moon_l, moon_m)
                # moon_l = moon_l/self._im[0]._dl + self._im[0]._npix/2;
                # moon_m = moon_m/self._im[0]._dl + self._im[0]._npix/2;
                # print 'Moon: RA/dec = %f/%f, alt/az = %f/%f, lind/mind = %f/%f, dl=%f'% (self._moon.ra, self._moon.dec, self._moon.alt, self._moon.az, moon_l, moon_m, self._im._dl);

            if self._casa.alt < 0:
                print "CasA below horizon at time ", self._obssite.date
            else:
                casa_l = -(numpy.cos(self._casa.alt) * numpy.sin(self._casa.az))
                casa_m = numpy.cos(self._casa.alt) * numpy.cos(self._casa.az)
                print "CasA l/m: %f, %f" % (casa_l, casa_m)
                # casa_l = casa_l/self._im[0]._dl + self._im[0]._npix/2;
                # casa_m = casa_m/self._im[0]._dl + self._im[0]._npix/2;
                # print 'CasA: RA/dec = %f/%f, alt/az = %f/%f, lind/mind = %f/%f, dl=%f'% (self._casa.ra, self._casa.dec, self._casa.alt, self._casa.az, casa_l, casa_m, self._im._dl);

        self._imgplt.set_data(abs(self._im[0]._skymap[:, :]))

        plt.title("%s - %f" % (self._im[0]._pol, self._im[0]._tobs))
        # if self._moon.alt > 0:
        # self._im[0]._skymap[moon_m-1:moon_m+1, moon_l-1:moon_l+1] = 5e10;
        # plt.annotate ('*',xy=(-moon_l,-moon_m),color='yellow');
        # plt.annotate ('*',xy=(-casa_m,casa_l),color='white');
        plt.draw()
        plt.pause(0.001)
        if self._wrpng == 1:
            plt.savefig("%s/%.0f_XX.png" % (self._fprefix, self._im[0]._tobs))
    def run(self):
        fig = plt.figure()
        fig.subplots_adjust(top=0.8)
        ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
        ax2.set_xlabel('Simulation of boat')
        (ax_min_x, ax_min_y, axis_len) = (-20, -20, 40)
        while(self.run_th):

            self.lock.acquire()
            th_data = copy.deepcopy(temp_data)
            self.lock.release()
            self.run_th = th_data.run

            plt.cla()   # Clear axis
            plt.clf()   # Clear figure
            fig.subplots_adjust(top=0.8)
            ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
            ax2.set_xlabel('Simulation of boat %0.1f %0.1f speed:%0.1f m/s rudder:%0.3f\
lat %.5f long %.5f ' %
                           (wrapTo2Pi(-th_data.theta+np.pi/2)*180/np.pi,
                            wrapTo2Pi(-th_data.phi+np.pi/2)*180/np.pi,
                            th_data.speed,
                            th_data.delta_r,
                            th_data.latitude, th_data.longitude))
            cds.draw_boat(ax2, 1, th_data.x, th_data.y,
                          th_data.theta, th_data.delta_r, th_data.delta_s)
            ax_min_x = x-axis_len/2.0
            ax_min_y = y-axis_len/2.0
            cds.draw_wind_direction(ax2, (ax_min_x+1, ax_min_y+1), axis_len, 1, th_data.phi)
            plt.axis([ax_min_x, ax_min_x+axis_len,
                      ax_min_y, ax_min_y+axis_len])
            plt.draw()
            plt.pause(0.001)

        print("Stopping Draw Thread")
        plt.close()
예제 #46
0
fig0, ax0 = plt.subplots(num=0)
plt.title("COOLFluiD Convergence Monitoring")
if res=="T":
    lh0, = ax0.plot(iterations,T_res,"+",color="#1f77b4")
    ax0.set_ylabel(r"$\log\, T$ Residual",color="#1f77b4")
elif res=="rho":
    lh0, = ax0.plot(iterations,rho_res,"+",color="#1f77b4")
    ax0.set_ylabel(r"$\log\, \varrho$ Residual",color="#1f77b4")    
ax0.set_xlabel(r"Number of iterations")
ax0.tick_params("y",colors="#1f77b4")
ax0.grid(True)
ax1 = ax0.twinx()
lh1, = ax1.plot(iterations,CFL,".",color="#d62728")
ax1.set_ylabel(r"CFL",color="#d62728")
ax1.tick_params("y",colors="#d62728")
plt.pause(1)   # flush the figure

plt.close(1)
fig1, ax2 = plt.subplots(num=1)
plt.title("COOLFluiD Convergence Monitoring")
lh2, = ax2.plot(iterations,Bx_res,"+",color="#ff7f0e",label=r"$\log\,B$ residual")
lh3, = ax2.plot(iterations,Ex_res,"+",color="#2ca02c",label=r"$\log\,E$ residual")
lh4, = ax2.plot(iterations,vx_res,"+",color="#7f7f7f",label=r"$\log\,U$ residual")
if res=="T":
    # Plot the residual that is not already monitored in Fig. 1
    lh5, = ax2.plot(iterations,rho_res,"+",color="#9467bd",label=r"$\log\,\varrho$ residual")
elif res=="rho":
    lh5, = ax2.plot(iterations,T_res,"+",color="#9467bd",label=r"$\log\,T$ residual")
plt.legend(loc=1)
ax2.set_xlabel(r"Number of iterations")
ax2.tick_params("y",colors="k")
예제 #47
0
def main( conf_file='config.cfg', logfile=None ):
    #%% parameters
    print "reading config parameters..."
    config, pars = front_end.parser( conf_file )

    if pars.has_key('logging') and pars['logging']:
        print "recording configuration file..."
        front_end.record_config_file( pars )

        logfile = front_end.make_logfile_name( pars )

    #%% create and initialize the network
    if pars['train_load_net'] and os.path.exists(pars['train_load_net']):
        print "loading network..."
        net = netio.load_network( pars )
        # load existing learning curve
        lc = zstatistics.CLearnCurve( pars['train_load_net'] )
    else:
        if pars['train_seed_net'] and os.path.exists(pars['train_seed_net']):
            print "seeding network..."
            net = netio.load_network( pars, is_seed=True )
        else:
            print "initializing network..."
            net = netio.init_network( pars )
        # initalize a learning curve
        lc = zstatistics.CLearnCurve()

    # show field of view
    print "field of view: ", net.get_fov()
    print "output volume info: ", net.get_outputs_setsz()

    # set some parameters
    print 'setting up the network...'
    vn = utils.get_total_num(net.get_outputs_setsz())
    eta = pars['eta'] #/ vn
    net.set_eta( eta )
    net.set_momentum( pars['momentum'] )
    net.set_weight_decay( pars['weight_decay'] )

    # initialize samples
    outsz = pars['train_outsz']
    print "\n\ncreate train samples..."
    smp_trn = front_end.CSamples(config, pars, pars['train_range'], net, outsz, logfile)
    print "\n\ncreate test samples..."
    smp_tst = front_end.CSamples(config, pars, pars['test_range'],  net, outsz, logfile)

    # initialization
    elapsed = 0
    err = 0
    cls = 0

    # interactive visualization
    plt.ion()
    plt.show()

    # the last iteration we want to continue training
    iter_last = lc.get_last_it()


    print "start training..."
    start = time.time()
    print "start from ", iter_last+1
    for i in xrange(iter_last+1, pars['Max_iter']+1):
        vol_ins, lbl_outs, msks = smp_trn.get_random_sample()

        # forward pass
        vol_ins = utils.make_continuous(vol_ins, dtype=pars['dtype'])

        props = net.forward( vol_ins )

        # cost function and accumulate errors
        props, cerr, grdts = pars['cost_fn']( props, lbl_outs )
        err = err + cerr
        cls = cls + cost_fn.get_cls(props, lbl_outs)

        # mask process the gradient
        grdts = utils.dict_mul(grdts, msks)

        # run backward pass
        grdts = utils.make_continuous(grdts, dtype=pars['dtype'])
        net.backward( grdts )

        if pars['is_malis'] :
            malis_weights = cost_fn.malis_weight(props, lbl_outs)
            grdts = utils.dict_mul(grdts, malis_weights)

        if i%pars['Num_iter_per_test']==0:
            # test the net
            lc = test.znn_test(net, pars, smp_tst, vn, i, lc)

        if i%pars['Num_iter_per_show']==0:
            # anneal factor
            eta = eta * pars['anneal_factor']
            net.set_eta(eta)
            # normalize
            err = err / vn / pars['Num_iter_per_show']
            cls = cls / vn / pars['Num_iter_per_show']
            lc.append_train(i, err, cls)

            # time
            elapsed = time.time() - start
            elapsed = elapsed / pars['Num_iter_per_show']

            show_string = "iteration %d,    err: %.3f,    cls: %.3f,   elapsed: %.1f s/iter, learning rate: %.6f"\
                    %(i, err, cls, elapsed, eta )

            if pars.has_key('logging') and pars['logging']:
                utils.write_to_log(logfile, show_string)
            print show_string

            if pars['is_visual']:
                # show results To-do: run in a separate thread
                front_end.inter_show(start, lc, eta, vol_ins, props, lbl_outs, grdts, pars)
                if pars['is_rebalance'] and 'aff' not in pars['out_type']:
                    plt.subplot(247)
                    plt.imshow(msks.values()[0][0,0,:,:], interpolation='nearest', cmap='gray')
                    plt.xlabel('rebalance weight')
                if pars['is_malis']:
                    plt.subplot(248)
                    plt.imshow(malis_weights.values()[0][0,0,:,:], interpolation='nearest', cmap='gray')
                    plt.xlabel('malis weight (log)')
                plt.pause(2)
                plt.show()
            # reset err and cls
            err = 0
            cls = 0
            # reset time
            start = time.time()

        if i%pars['Num_iter_per_save']==0:
            # save network
            netio.save_network(net, pars['train_save_net'], num_iters=i)
            lc.save( pars, elapsed )
예제 #48
0
파일: Person.py 프로젝트: niamiot/pylayers
    def move(self):
        """ Move the Person

        """
        if self.pdshow:
            fig =plt.gcf()
            fig,ax=self.L.showG('w',labels=False,alphacy=0.,edges=False,fig=fig)
            plt.draw()
            plt.ion()
        while True:
            if self.moving:
                if self.sim.verbose:
                    print 'meca: updt ag ' + self.ID + ' @ ',self.sim.now()
                
                # if np.allclose(conv_vecarr(self.destination)[:2],self.L.Gw.pos[47]):
                #     import ipdb
                #     ipdb.set_trace()


                while self.cancelled:
                    yield passivate, self
                    print "Person.move: activated after being cancelled" 
                checked = []
                for zone in self.world.zones(self):
                    if zone not in checked:
                        checked.append(zone)
                        zone(self)

                # updating acceleration
                acceleration = self.steering_mind(self)
                acceleration = acceleration.truncate(self.max_acceleration)
                self.acceleration = acceleration

                # updating velocity
                velocity = self.velocity + acceleration * self.interval
                self.velocity = velocity.truncate(self.max_speed)


                if velocity.length() > 0.2:
                    # record direction only when we've really had some
                    self.localy = velocity.normalize()
                    self.localx = vec3(self.localy.y, -self.localy.x)

                # updating position
                self.position = self.position + self.velocity * self.interval
#                self.update()
                self.position.z=0
                self.world.update_boid(self)

                self.net.update_pos(self.ID,conv_vecarr(self.position),self.sim.now())
                p=conv_vecarr(self.position).reshape(3,1)
                v=conv_vecarr(self.velocity).reshape(3,1)
                a=conv_vecarr(self.acceleration).reshape(3,1)

                # fill panda dataframe 2D trajectory
                self.df = self.df.append(pd.DataFrame({'t':pd.Timestamp(self.sim.now(),unit='s'),
                'x':p[0],
                'y':p[1],
                'vx':v[0],
                'vy':v[1],
                'ax':a[0],
                'ay':a[1]},
                columns=['t','x','y','vx','vy','ax','ay']))

                if self.pdshow:
                    ptmp =np.array([p[:2,0],p[:2,0]+v[:2,0]])

                    if hasattr(self, 'pl'):
                        self.pl[0].set_data(self.df['x'].tail(1),self.df['y'].tail(1))
                        self.pla[0].set_data(ptmp[:,0],ptmp[:,1])
                    else :
                        self.pl = ax.plot(self.df['x'].tail(1),self.df['y'].tail(1),'o',color=self.color,ms=self.radius*10)
                        self.pla = ax.plot(ptmp[:,0],ptmp[:,1],'r')

                    # try:
                    #     fig,ax=plu.displot(p[:2],p[:2]+v[:2],'r')
                    # except:
                    #     pass
                    # import ipdb
                    # ipdb.set_trace()
                    plt.draw()
                    plt.pause(0.0001) 
                if 'mysql' in self.save:
                    self.db.writemeca(self.ID,self.sim.now(),p,v,a)

                if 'txt' in self.save:
                    pyu.writemeca(self.ID,self.sim.now(),p,v,a)

                # new target when arrived in poi

                if self.arrived and\
                    (self.L.pt2ro(self.position) ==\
                        self.L.Gw.node[self.rooms[1]]['room']):

                    self.arrived = False
                    if self.endpoint:
                        self.endpoint=False
                        self.roomId = self.nextroomId
                        # remove the remaining waypoint which correspond 
                        # to current room position
                        del self.waypoints[0]
                        del self.rooms[0]
                        # del self.dlist[0]
                    #
                    # If door lets continue 
                    #
                    #
                    # ig destination --> next room
                    #
                    #adjroom  = self.L.Gr.neighbors(self.roomId)
                    #Nadjroom = len(adjroom)
                        if self.cdest == 'random':
                            # self.nextroomId   = int(np.floor(random.uniform(0,self.L.Gr.size())))
                            self.nextroomId   = random.sample(self.L.Gr.nodes(),1)[0]
                            # test 1 ) next != actualroom
                            #      2 ) nextroom != fordiden room
                            #      3 ) room not share without another agent
                            while self.nextroomId == self.roomId or (self.nextroomId in self.forbidroomId):# or (self.nextroomId in self.sim.roomlist):
                                # self.nextroomId   = int(np.floor(random.uniform(0,self.L.Gr.size())))
                                self.nextroomId   = random.sample(self.L.Gr.nodes(),1)[0]
                        elif self.cdest == 'file':
                           self.room_counter=self.room_counter+1
                           if self.room_counter >= self.nb_room:
                                self.room_counter=0
                           self.nextroomId=self.room_seq[self.room_counter]
                           self.wait=self.room_wait[self.room_counter]
                        #self.sim.roomlist.append(self.nextroomId) # list of all destiantion of all nodes in object sim
                        self.rooms, wp =  self.L.waypointGw(self.roomId,self.nextroomId)
                        # self.dlist =  [i in self.L.Gw.ldo for i in self.rooms]
                        for tup in wp[1:]:
                            self.waypoints.append(vec3(tup)) 
                    #nextroom = adjroom[k]
                    #    print "room : ",self.roomId
                    #    print "nextroom : ",self.nextroomId
                    #p_nextroom = self.L.Gr.pos[self.nextroomId]
                    #setdoors1  = self.L.Gr.node[self.roomId]['doors']
                    #setdoors2  = self.L.Gr.node[nextroom]['doors']
                    #doorId     = np.intersect1d(setdoors1,setdoors2)[0]
                    #
                    # coord door
                    #
                    #unode = self.L.Gs.neighbors(doorId)    
                    #p1    = self.L.Gs.pos[unode[0]]
                    #p2    = self.L.Gs.pos[unode[1]]
                    #print p1
                    #print p2
                    #pdoor = (np.array(p1)+np.array(p2))/2
                        self.destination = self.waypoints[0]
                    
                        if self.sim.verbose:
                            print 'meca: ag ' + self.ID + ' wait ' + str(self.wait)#*self.interval) 
                        yield hold, self, self.wait

                    else:
                        del self.waypoints[0]
                        del self.rooms[0]
                        # del self.dlist[0]
                    #print "wp : ", self.waypoints
                        if len(self.waypoints)==1:
                            self.endpoint=True
                        self.destination = self.waypoints[0]
                    #print "dest : ", self.destination
                else:
                    yield hold, self, self.interval
            else:
#                self.update()
                self.world.update_boid(self)
                self.net.update_pos(self.ID,conv_vecarr(self.position),self.sim.now())

                yield hold, self, self.interval
예제 #49
0
파일: scurve.py 프로젝트: leeshunn/norbert
  f.build_operators()
  f.regrid() ; f.solve_steady()
  tt = interp1d(f.z,f.T,kind="cubic")
  Tst = np.append(Tst,tt(f.z_ref))
  Xst = np.append(Xst,f.chi_ref)
  G   = np.append(G,np.trapz(f.d*f.G,f.z))
  S   = np.append(S,np.trapz(f.d*f.S,f.z))
  if len(Tst)>1:
    dT = abs(Tst[-1]-Tst[-2])
  y2 = y1 ; y1 = y0 ; y0 = f.Y
  z2 = z1 ; z1 = z0 ; z0 = f.z

  pl.subplot(3,1,1) ; pl.plot(f.z,f.T)
  pl.subplot(3,1,2) ; pl.plot(f.z,f.Y)
  pl.subplot(3,1,3) ; pl.plot(f.z,f.s)
  pl.pause(.1) ; pl.clf()

while Tst[-1] > Tmix+deltaT:
  w0,w1,w2 = quadwts(Tst[-1]-deltaT,Tst[-1],Tst[-2],Tst[-3])
  f.chi_ref = np.exp(w0*np.log(Xst[-1])+w1*np.log(Xst[-2])+w2*np.log(Xst[-3]))
  f.build_operators()

  #yy1 = interp1d(z1,y1,axis=0)
  #yy2 = interp1d(z2,y2,axis=0)
  #f.Y = w0*y0+w1*yy1(z0)+w2*yy2(z0)
  f.regrid() ; f.solve_steady()

  tt = interp1d(f.z,f.T,kind="cubic")
  Tst = np.append(Tst,tt(f.z_ref))
  Xst = np.append(Xst,f.chi_ref)
  G   = np.append(G,np.trapz(f.d*f.G,f.z))
예제 #50
0
for i in range(0,999):
  gc=0
  for j in range(0,len(dnalist)):
    dnalist[j]=(dnalist[j][0]+'{:02d}'.format(j),mutated_string(dnalist[j][1][:]))
    gc+=gc_content(dnalist[j][1])
  gccont=gc/len(dnalist)
  numseqs,dnalist = sample_seqs(dnalist)
  x.append(i)
  y.append(gccont)
  y2.append(numseqs)
  print(numseqs,gccont, sep='\t')
  line.set_xdata(np.array(x))
  line.set_ydata(np.array(y))
  line2.set_xdata(np.array(x))
  line2.set_ydata(np.array(y2))
  if (i>500):
    plt.subplot(211)
    plt.xlim(i-500,i+10)
  if (i>100):
    plt.subplot(212)
    plt.xlim(i-100,i+10)
  plt.draw()
  plt.pause(0.005)


for i in dnalist:
  #print('>'+i[0],''.join(i[1]),sep='\n')
  pass

  # of  Life
if __name__ == '__main__':
  
  N = 100.0

  domain = np.zeros((N,N), dtype=np.int)
  
  domain = add_glider(domain,(10,50))
  domain = add_smallgrower(domain,(70,70))

  domain = add_gospergun(domain,(20,20))

  # note infinate loop
  # exits with ctrl-c
  while True:
    plt.imshow(domain)
    #plt.show()
    plt.pause(.1)
    plt.draw()    
    
    plt.clf()

    domain = update_array(domain)





 

예제 #52
0
    def plot_rssi(self, port):
        self.count = 0
        self.dt = 0.5
        self.tlen = 120
        # Generate mesh for plotting
        Y, X = np.mgrid[slice(0 - .5, 26 + 1.5, 1), slice(0 - self.dt / 2, self.tlen + 1 - self.dt / 2, self.dt)]
        Z = np.zeros_like(X)
        # X and Y are bounds, so Z should be the value *inside* those bounds.
        # Therefore, remove the last value from the Z array.
        Z = Z[:, :-1]
        logging.debug("Creating figure")
        plt.figure()
        pcm = plt.pcolormesh(X, Y, Z, vmin=-128, vmax=0, cmap=plt.cm.get_cmap('jet'))
        plt.xlim([0, self.tlen])
        plt.ylim([0, 26])
        plt.colorbar(label="Measured signal level [dB]")
        plt.ylabel("Channel number")
        plt.xlabel("Time [s]")
        plt.ion()
        logging.debug("Show plot window")
        plt.show()
        ch_min = 26
        ch_max = 0
        last_update = time.time()

        logging.info("Begin collecting data from serial port")
        while True:
            line = port.readline().rstrip()

            pkt_data = re.match(r"\[([-+]?\d+),\s*([-+]?\d+),\s*([-+]?\d+)\]\s*(.*)", line.decode(errors='replace'))
            if pkt_data:
                now = time.time()
                try:
                    iface_id = int(pkt_data.group(1))
                    timestamp = int(pkt_data.group(2))
                    count = int(pkt_data.group(3))
                    tidx = int(timestamp / (self.dt * 1000000)) % (Z.shape[1])
                except ValueError:
                    continue
                logging.debug("data: tidx=%d if=%d cnt=%d t=%d", tidx, iface_id, count, timestamp)
                raw = pkt_data.group(4)
                resize = False
                for ch_ed in raw.split(","):
                    try:
                        pair = ch_ed.split(":")
                        ch = int(pair[0])
                        ed = float(pair[1])
                        if ch < ch_min:
                            ch_min = ch
                            resize = True
                        if ch > ch_max:
                            ch_max = ch
                            resize = True
                        Z[ch, tidx] = ed
                    except (ValueError, IndexError):
                        continue
                if resize:
                    logging.debug("resize: %d %d" % (ch_min, ch_max))
                    plt.ylim([ch_min - .5, ch_max + .5])
                if now > last_update + 1:
                    last_update = now
                    pcm.set_array(Z.ravel())
                    pcm.autoscale()
                    pcm.changed()
            plt.pause(0.01)
예제 #53
0
import signal;
import vismon;

def sighdlr (signal, frame):
	print 'Keyboard interrupt! aborting...'
	sys.exit(0);

if __name__ == "__main__":
	rec = 0;
	fid = open (sys.argv[1], 'r');
	im = vismon.imager ();
	im.readMetaFromFile (fid);
	tobs, fobs, img = im.readImgFromFile (fid);		
	print 'Rec: %04d, Time: %.0f, Freq: %.0f' % (rec, tobs, fobs);
	img.shape  = (im._npix, im._npix);
	imgplt = plt.imshow (abs(img));
	plt.colorbar();
	
	signal.signal(signal.SIGINT, sighdlr);

	while True:
		tobs, fobs, img = im.readImgFromFile (fid);		
		print 'Rec: %d, Time: %.0f, Freq: %.0f' % (rec, tobs, fobs);
		img.shape = (im._npix, im._npix);
		imgplt.set_data (abs(img));
		plt.draw();
		plt.title ('XX - %f' % tobs);
		plt.pause(0.01);
		# plt.clf();
		rec = rec + 1;
예제 #54
0

if __name__ == '__main__':
    
    # Plotting distance modulus as a function of redshift for all C11 parameters
    types   = ["C11_Combined", "C11_SALT2_stat_sys", "C11_SiFTO_stat_sys", "C11_SALT2_stat", "C11_SiFTO_stat", "C11_reanalized", "C11_recalibrated", "JLA"]
    dirname = "/Users/anita/Documents/Grad_First_Year/Summer_2016_research/Codes/"
    cvals   = ["black","blue","red","green","yellow","orange","magenta","teal"]

    plt.ion()
    
    for i in range(len(types)):
        zcmb, mu= dist_modul(dirname,"table3_new.txt",ptype=types[i])
        plt.plot(zcmb, mu,"o", ms=4, color=cvals[i], label=str(types[i]))
        plt.title(types[i])
        plt.pause(1.5)
        plt.draw()

    plt.xlabel("$z_{cmb}$", fontsize=25)
    plt.ylabel(r"$\mu = m_B - (M_B - \alpha X_1 + \beta C)$", fontsize=20)
    plt.legend(loc='best')









예제 #55
0
    plt.figure(figsize=(9.5, 8.5))

    # load up a single event, so we can get the subarray info:
    source = event_source(
        datasets.get_dataset_path("gamma_test_large.simtel.gz"),
        max_events=1,
    )

    event = next(iter(source))

    # display the array
    subarray = event.inst.subarray
    ad = ArrayDisplay(subarray, tel_scale=3.0)

    print("Now setting vectors")
    plt.pause(1.0)
    plt.tight_layout()

    for phi in np.linspace(0, 360, 30) * u.deg:
        r = np.cos(phi / 2)
        ad.set_vector_rho_phi(r, phi)
        plt.pause(0.01)

    ad.set_vector_rho_phi(0, 0 * u.deg)
    plt.pause(1.0)

    print("Now setting values")
    ad.telescopes.set_linewidth(0)
    for ii in range(50):
        vals = np.random.uniform(100.0, size=subarray.num_tels)
        ad.values = vals
예제 #56
0
파일: dgp3.py 프로젝트: blutooth/gp
    if step % 500 == 0:

        print(step)
        print(s.run(lrate))
        print('sig,noise,len',s.run(sigma_2),s.run(noise_2),s.run(len_sc_2))
        plt.clf()
        plt.scatter(X,s.run(mean),color='blue')
        #plt.scatter(s.run(tf.reshape(X_m_1,[M])),s.run(tf.reshape(opti_mu2,[M])),color='orange')
        #plt.scatter(X_m_1,np.zeros((1,M)),color='purple')
        plt.scatter(s.run(Xtr),s.run(X_mean2))
        #plt.scatter(s.run(X_m),np.zeros(M),color='red')
        plt.plot(X,s.run(mean),color='blue')
        plt.scatter(X,Y,color='red')
        #plt.plot(X,s.run(tf.add(var_terms,mean)),color='black')
        #plt.plot(X,s.run(tf.sub(mean,var_terms)),color='black')

       # plt.plot(s.run(Xtr),s.run(X_mean2+2*tf.sqrt(X_cov2+X_cov1)),color='green')
        #plt.plot(s.run(Xtr),s.run(X_mean2-2*tf.sqrt(X_cov2+X_cov1)),color='green')
        print('F2',s.run(F_v_2))
        #plt.scatter(X,Y,color='green')

        h.set_sess(s);GPLVM.printer()
        plt.scatter(s.run(tf.reshape(X_m_2/10,[-1])),np.zeros(M),color='purple')
        #plt.scatter(X_odd,Y_odd,color='black')
        #plt.scatter(s.run(tf.reshape(X_m_1,[-1])),np.zeros(M),color='black')
        plt.plot(s.run(Xtr),s.run(sample_all()),color='black')

        plt.pause(2)
        #print(s.run(tf.reduce_min(h.abs_diff(Z,Z)+np.eye(M,M))))
s.close()
    plt.legend(loc='best')

    # Calculate MTF.
    # According to http://www.imatest.com/docs/validating_slanted_edge/, the MTF is
    # the Fourier transform of the line spread function, which is the derivative of
    # the averaged edge.
    # We thus calculate the average edge ($source$Response) and take the derivative
    # of this (with the `LSF` function, which uses `numpy.diff`).
    # To the derivative we fit a gaussian function with the `gaussianfit` function
    # which then acts as an input for the `MTF` function above.
    plt.subplot(154)
    plt.title('Line spread function')
    plt.plot(LSF(ResponseERI), c=Colors[2], linestyle='dashed', label='ERI Data')
    plt.plot(LSF(ResponseHamamatsu), c=Colors[3], linestyle='dashed', label='Hamamatsu Data')
    plt.plot(gaussianfit(LSF(ResponseERI)), c=Colors[0], label='ERI fit')
    plt.plot(gaussianfit(LSF(ResponseHamamatsu)), c=Colors[1], label='Hamamatsu fit')
    plt.legend(loc='best')
    plt.subplot(155)
    plt.title('MTF')
    plt.plot(normalize(MTF(gaussianfit(LSF(ResponseERI)))), c=Colors[0],
             label='MTF ERI')
    plt.plot(normalize(MTF(gaussianfit(LSF(ResponseHamamatsu)))), c=Colors[1],
             label='MTF Hamamatsu')
    plt.legend(loc='best')
    # Save figure and concatenated results
    plt.savefig(os.path.join(OutputPath, 'MTF%03dkV%03duA.png' % (VoltageERI[c], CurrentERI[c])))
    plt.draw()
    plt.pause(0.01)
plt.ioff()
plt.show()
import siena_cms_tools as cms
import matplotlib.pylab as plt

import sys

import time

start = time.time()
collisions = cms.get_collisions(sys.argv[1])
print "Time to read in %d collisions: %f seconds" % (len(collisions),time.time()-start)

print len(collisions)

#fig = plt.figure(figsize=(7,5),dpi=100)
#ax = fig.add_subplot(1,1,1)
#ax = fig.gca(projection='3d')
#plt.subplots_adjust(top=0.98,bottom=0.02,right=0.98,left=0.02)

fig = plt.figure()
#ax = fig.add_subplot(1,1,1)
ax = fig.gca(projection='3d')
for i in xrange(1000):
    lines,fig,ax = cms.display_collision3D(collisions[i],fig=fig,ax=ax)
    plt.pause(0.0001)

#plt.show(block=False)

    image_extent = [0,num_cols*dx,0,num_rows*dx]
    im = plt.imshow(zwR,cmap=plt.cm.RdBu,extent=image_extent)
    plt.xlabel('Distance (m)', fontsize=12)
    plt.ylabel('Distance (m)', fontsize=12)
    # create contours
    cset = plt.contour(zwR,extent=image_extent)
    plt.clabel(cset,inline=True, fmt='%1.1f', fontsize=10)
    # color bar on side
    cb = plt.colorbar(im)
    cb.set_label('Water Elevation (m)', fontsize=12)
    # add title
    plt.title('Water Elevation')
    # Save plot
    #plt.savefig('Water_Elevation')
    # Display plot
    plt.pause(0.1)
    #else:
        #pass




 # FINALIZE 
# get 2D array for contours
Hr = mg.node_vector_to_raster(H)

# Water height plot
image_extent = [0,num_cols*dx,0,num_rows*dx]
im = plt.imshow(Hr,cmap=plt.cm.RdBu,extent=image_extent)
plt.xlabel('Distance (m)', fontsize=12)
plt.ylabel('Distance (m)', fontsize=12)