def spatrect_plot(outpath, base_name, order_num, obj, flat): pl.figure('spatially rectified', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('spatially rectified, {}, order {}'.format( base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) try: obj_plot.imshow(exposure.equalize_hist(obj)) except BaseException: obj_plot.imshow(obj) obj_plot.set_title('object') # obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(2, 1, 2) try: flat_plot.imshow(exposure.equalize_hist(flat)) except BaseException: flat_plot.imshow(flat) flat_plot.set_title('flat') # flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'spatrect.png')) pl.close()
def traces_plot(outpath, base_name, order_num, obj, flat, top_trace, bot_trace): pl.figure('traces', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('order edge traces, {}, order {}'.format(base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') pl.rcParams['ytick.labelsize'] = 8 obj_plot = pl.subplot(1, 2, 1) obj_plot.imshow(exposure.equalize_hist(obj)) obj_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) obj_plot.set_title('object') obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(1, 2, 2) flat_plot.imshow(exposure.equalize_hist(flat)) flat_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) flat_plot.set_title('flat') flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'traces.png')) pl.close()
def cutouts_plot(outpath, obj_base_name, flat_base_name, order_num, obj_img, flat_img, top_trace, bot_trace, trace): pl.figure('traces', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('order cutouts, {}, order {}'.format(obj_base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) try: obj_plot.imshow(exposure.equalize_hist(obj_img)) except BaseException: obj_plot.imshow(obj_img) obj_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(1024), trace, 'y-', linewidth=1.5) obj_plot.set_title('object ' + obj_base_name) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(2, 1, 2) try: flat_plot.imshow(exposure.equalize_hist(flat_img)) except BaseException: flat_plot.imshow(flat_img) flat_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(1024), trace, 'y-', linewidth=1.5) flat_plot.set_title('flat ' + flat_base_name) flat_plot.set_xlim([0, 1023]) pl.tight_layout() pl.savefig( constructFileName(outpath, obj_base_name, order_num, 'cutouts.png')) pl.close()
def plot_features(im, features, num_to_plot=100, colors=["blue"]): plt.imshow(im) for i in range(min(features.shape[0], num_to_plot)): x = features[i,0] y = features[i,1] scale = features[i,2] rot = features[i,3] color = colors[i % len(colors)] box = patches.Rectangle((-scale/2,-scale/2), scale, scale, edgecolor=color, facecolor="none", lw=1) arrow = patches.Arrow(0, -scale/2, 0, scale, width=10, edgecolor=color, facecolor="none") t_start = plt.gca().transData transform = mpl.transforms.Affine2D().rotate(rot).translate(x,y) + t_start box.set_transform(transform) arrow.set_transform(transform) plt.gca().add_artist(box) plt.gca().add_artist(arrow) plt.axis('off') plt.set_cmap('gray') plt.show()
def plot_knn_boundary(): ## Training dataset preparation # use sklearn iris dataset iris_dataset = datasets.load_iris() # first two dimensions as the features # it's easy to plot boundary in 2D train_data = iris_dataset.data[:,:2] print "init:",train_data # get labels labels = iris_dataset.target # labels print "init2:",labels ## Test dataset preparation h = 0.1 x0_min = train_data[:,0].min() - 0.5 x0_max = train_data[:,0].max() + 0.5 x1_min = train_data[:,1].min() - 0.5 x1_max = train_data[:,1].max() + 0.5 x0_features, x1_features = np.meshgrid(np.arange(x0_min, x0_max, h), np.arange(x1_min, x1_max, h)) # test dataset are samples from the whole regions of feature domains test_data = np.c_[x0_features.ravel(), x1_features.ravel()] ## KNN classification p_labels = [] # prediction labels for test_sample in test_data: # knn prediction p_label = knn_predict(train_data, labels, test_sample, n_neighbors = 6) p_labels.append(p_label) # list to array p_labels = np.array(p_labels) p_labels = p_labels.reshape(x0_features.shape) ## Boundary plotting 边界策划 pl.figure(1) pl.set_cmap(pl.cm.Paired) pl.pcolormesh(x0_features, x1_features, p_labels) pl.scatter(train_data[:,0], train_data[:,1], c = labels) # x y轴的名称 pl.xlabel('feature 0') pl.ylabel('feature 1') # 设置x,y轴的上下限 pl.xlim(x0_features.min(), x0_features.max()) pl.ylim(x1_features.min(), x1_features.max()) # 设置x,y轴记号 pl.xticks(()) pl.yticks(()) pl.show()
def cutouts_plot(outpath, base_name, order_num, obj, flat, top_trace, bot_trace, trace): pl.figure('traces', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('order cutouts, {}, order {}'.format(base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) try: obj_plot.imshow(exposure.equalize_hist(obj)) except: obj_plot.imshow(obj) obj_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(1024), trace, 'y-', linewidth=1.5) obj_plot.set_title('object') # obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(2, 1, 2) try: flat_plot.imshow(exposure.equalize_hist(flat)) except: flat_plot.imshow(flat) flat_plot.plot(np.arange(1024), top_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(1024), bot_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(1024), trace, 'y-', linewidth=1.5) flat_plot.set_title('flat') # flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'cutouts.png')) pl.close()
def plot_figs(fig_num, elev, azim): fig = pl.figure(fig_num, figsize=(4, 3)) pl.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim) pl.set_cmap(pl.cm.hot_r) pts = ax.scatter(a[::10], b[::10], c[::10], c=density, marker='+', alpha=.4) Y = np.c_[a, b, c] U, pca_score, V = np.linalg.svd(Y, full_matrices=False) x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min() #ax.quiver(0.1*x_pca_axis, 0.1*y_pca_axis, 0.1*z_pca_axis, # x_pca_axis, y_pca_axis, z_pca_axis, # color=(0.6, 0, 0)) x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T x_pca_plane = np.r_[x_pca_axis[:2], -x_pca_axis[1::-1]] y_pca_plane = np.r_[y_pca_axis[:2], -y_pca_axis[1::-1]] z_pca_plane = np.r_[z_pca_axis[:2], -z_pca_axis[1::-1]] x_pca_plane.shape = (2, 2) y_pca_plane.shape = (2, 2) z_pca_plane.shape = (2, 2) ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([])
def analysis(): feature_importances_array = np.load("Default_AlexNet.npy") mean_feature_importances = np.mean(feature_importances_array, axis=0) for feature_importance, metric in zip(mean_feature_importances, METRIC_LIST): print("{}\t{}".format(metric, feature_importance)) time_indexes = np.arange(1, feature_importances_array.shape[0] + 1) feature_importances_cumsum = np.cumsum(feature_importances_array, axis=0) feature_importances_mean = feature_importances_cumsum for column_index in range(feature_importances_mean.shape[1]): feature_importances_mean[:, column_index] = feature_importances_cumsum[:, column_index] / time_indexes index_ranks = np.flipud(np.argsort(mean_feature_importances)) chosen_records = np.cumsum(mean_feature_importances[index_ranks]) <= 0.95 chosen_index_ranks = index_ranks[chosen_records] sorted_mean_feature_importances = mean_feature_importances[chosen_index_ranks] sorted_metric_list = np.array(METRIC_LIST)[chosen_index_ranks] remaining = np.sum(mean_feature_importances[index_ranks[~chosen_records]]) print("remaining is {:.4f}.".format(remaining)) sorted_mean_feature_importances = np.hstack((sorted_mean_feature_importances, remaining)) sorted_metric_list = np.hstack((sorted_metric_list, 'others')) pylab.pie(sorted_mean_feature_importances, labels=sorted_metric_list, autopct='%1.1f%%', startangle=0) pylab.axis('equal') pylab.set_cmap('plasma') pylab.show()
def plot_figs(fig_num, elev, azim): fig = pl.figure(fig_num, figsize=(4, 3)) pl.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim) pl.set_cmap(pl.cm.hot_r) pts = ax.scatter(a[::10], b[::10], c[::10], c=density, marker='+', alpha=.4) Y = np.c_[a, b, c] U, pca_score, V = np.linalg.svd(Y, full_matrices=False) x_pca_axis, y_pca_axis, z_pca_axis = V.T*pca_score/pca_score.min() #ax.quiver(0.1*x_pca_axis, 0.1*y_pca_axis, 0.1*z_pca_axis, # x_pca_axis, y_pca_axis, z_pca_axis, # color=(0.6, 0, 0)) x_pca_axis, y_pca_axis, z_pca_axis = 3*V.T x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]] y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]] z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]] x_pca_plane.shape = (2, 2) y_pca_plane.shape = (2, 2) z_pca_plane.shape = (2, 2) ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([])
def sparect_plot(outpath, base_name, order_num, obj, flat): pl.figure('spatially rectified', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('spatially rectified, {}, order {}'.format(base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) try: obj_plot.imshow(exposure.equalize_hist(obj)) except: obj_plot.imshow(obj) obj_plot.set_title('object') # obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(2, 1, 2) try: flat_plot.imshow(exposure.equalize_hist(flat)) except: flat_plot.imshow(flat) flat_plot.set_title('flat') # flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'sparect.png')) pl.close()
def twoDimOrderPlot(outpath, base_name, title, obj_name, base_filename, order_num, data, x): pl.figure('2d order image', facecolor='white', figsize=(8, 5)) pl.cla() pl.title(title + ', ' + base_name + ", order " + str(order_num), fontsize=14) pl.xlabel('wavelength($\AA$)', fontsize=12) pl.ylabel('row (pixel)', fontsize=12) #pl.imshow(img, aspect='auto') #pl.imshow(data, vmin=0, vmax=1024, aspect='auto') pl.imshow(exposure.equalize_hist(data), origin='lower', extent=[x[0], x[-1], 0, data.shape[0]], aspect='auto') # from matplotlib import colors # norm = colors.LogNorm(data.mean() + 0.5 * data.std(), data.max(), clip='True') # pl.imshow(data, norm=norm, origin='lower', # extent=[x[0], x[-1], 0, data.shape[0]], aspect='auto') pl.colorbar() pl.set_cmap('jet') # pl.set_cmap('Blues_r') fn = constructFileName(outpath, base_name, order_num, base_filename) pl.savefig(fn) log_fn(fn) pl.close() # np.save(fn[:fn.rfind('.')], data) return
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16): ''' :param data: :param outputname: :param cmap: ''' aspect_ratio = float(data.shape[1])/data.shape[0] fig = pylab.figure() Scale = 8 # add +1 to get axis text fig.set_size_inches(Scale*aspect_ratio+1,Scale*1) ax = pylab.gca() #ax.set_axis_off() #fig.add_axes(ax) if cmap != None: pylab.set_cmap(cmap) #ax.imshow(data, interpolation='nearest', aspect = 'normal') ax.imshow(data, interpolation='nearest') if rangeXpx == None: rangeXpx = (0, data.shape[1]) if rangeZpx == None: rangeZpx = (0, data.shape[0]) modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel) #plt.savefig(outputname, bbox_inches='tight', dpi = dpi) pylab.savefig(outputname, dpi = data.shape[0]/Scale) pylab.close() fig.clear()
def imshow_matches__(im, title): fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel('PW Level') ax.set_ylabel('S Level') ax.set_title(title) plt.set_cmap(plt.get_cmap('hot')) plt.imshow(im)
def display_FFT_magnitude(): global currnt_img f_img = np.fft.fft2(currnt_img) fshift = np.fft.fftshift(f_img)#shifting mag = 20*np.log(np.abs(fshift)) plt.imshow(mag) plt.set_cmap('gray') plt.show()
def part_b(): img_data = np.loadtxt('blur.txt') shape = img_data.shape blur = [[gaussian(x, y, shape[0], shape[1]) for x in range(shape[0])] for y in range(shape[1])] pylab.imshow(blur) pylab.set_cmap('Greys_r') pylab.show()
def display_FFT_phase(): global currnt_img f_img = np.fft.fft2(currnt_img) fshift = np.fft.fftshift(f_img) phase = np.arctan(fshift.imag/fshift.real)#phase calculation plt.imshow(phase) plt.set_cmap('gray') plt.show()
def draw_grids(self, rewards, trajectory=None, title=None): R = np.zeros([self.dim, self.dim]) for i in range(self.dim): for j in range(self.dim): R[i, j] = rewards[self.coord_to_index([i, j])] if title is None: pylab.title('Close window to continue') else: pylab.title(title) pylab.set_cmap('gray') pylab.axis([0, self.grids[0], self.grids[1], 0]) c = pylab.pcolor(R, edgecolors='w', linewidths=1) x = [] y = [] for i in range(0, self.dim / 2): j = i + self.dim / 2 - 2 if j < self.dim and j >= self.dim / 2: x.append(j) y.append(i) x.append(j + 1) y.append(i) elif j < self.dim - 2: x.append(self.dim / 2) y.append(i) for j in range(self.dim / 2 + self.dim / 2 - 2, self.dim + 1): x.append(j) y.append(self.dim / 2) pylab.plot(x, y, 'r') x = [] y = [] for i in range(0, self.dim / 2): j = i + self.dim / 2 - 2 if j < self.dim and j >= self.dim / 2: y.append(j) x.append(i) y.append(j + 1) x.append(i) elif j < self.dim - 1: y.append(self.dim / 2) x.append(i) for j in range(self.dim / 2 + self.dim / 2 - 2, self.dim + 1): y.append(j) x.append(self.dim / 2) pylab.plot(x, y, 'r') y = [] x = [] if trajectory != None: for trans in trajectory: coord = self.index_to_coord(trans[-1]) y.append(coord[0]) x.append(coord[1]) pylab.plot(x, y, 'bo', x, y, 'b-', [x[-1]], [y[-1]], 'ro') pylab.show()
def specrect_plot(outpath, base_name, order_num, before, after): if const.upgrade: endPix = 2048 else: endPix = 1024 pl.figure('before, after spectral rectify', facecolor='white', figsize=(10, 10)) pl.cla() pl.suptitle('before, after spectral rectify, {}, order {}'.format( base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') before_plot = pl.subplot(2, 1, 1) #before = imresize(before, (500, endPix), interp='bilinear') try: before[np.where(before < 0)] = np.median(before) norm = ImageNormalize(before, interval=ZScaleInterval(), stretch=SquaredStretch()) before_plot.imshow(before, origin='lower', aspect='auto', norm=norm) #before_plot.imshow(exposure.equalize_hist(before), aspect='auto', origin='lower') except: before_plot.imshow(before, aspect='auto', origin='lower') before_plot.set_title('before') # obj_plot.set_ylim([1023, 0]) before_plot.set_xlim([0, endPix - 1]) after_plot = pl.subplot(2, 1, 2) #after = imresize(after, (500, endPix), interp='bilinear') try: after[np.where(after < 0)] = np.median(after) norm = ImageNormalize(after, interval=ZScaleInterval(), stretch=SquaredStretch()) after_plot.imshow(after, origin='lower', aspect='auto', norm=norm) #after_plot.imshow(exposure.equalize_hist(after), aspect='auto', origin='lower') except: after_plot.imshow(after, aspect='auto', origin='lower') after_plot.set_title('after') # flat_plot.set_ylim([1023, 0]) after_plot.set_xlim([0, endPix - 1]) before_plot.minorticks_on() after_plot.minorticks_on() #pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'specrect.png'), bbox_inches='tight') pl.close()
def plot_sa_diff_figure(control_dataset, data, sa_mask): f = plt.figure('sa_diff') plt.set_cmap('RdGy_r') graph_settings = ( ((-4, 4), np.arange(-4, 4.1, 2)), ((-6, 6), np.arange(-6, 6.1, 3)), ((-0.7, 0.7), np.arange(-0.6, 0.61, 0.3)), ((-4, 4), np.arange(-4, 4.1, 2)), ((-0.2, 0.2), np.arange(-0.2, 0.21, 0.1))) variables = ['precip', 'surf_temp', 'q', 'field1389', 'field1385'] nice_names = {'precip': '$\Delta$Precip (mm/day)', 'surf_temp': '$\Delta$Surf temp (K)', 'q':'$\Delta$Humidity (g/kg)', 'field1389': '$\Delta$NPP (g/m$^2$/day)', 'field1385': '$\Delta$Soil moisture'} f.subplots_adjust(hspace=0.2, wspace=0.1) for i in range(len(variables)): variable = variables[i] ax = plt.subplot(2, 3, i + 1) ax.set_title(nice_names[variable]) variable_diff = data['data']['1pct'][variable] - data['data']['ctrl'][variable] if variable == 'field1389': variable_diff *= 24*60*60*1000 # per s to per day, kg to g. lons, lats = get_vars_from_control_dataset(control_dataset) vmin, vmax = graph_settings[i][0] #general_plot(control_dataset, variable_diff.mean(axis=0), vmin=graph_settings[i][0][0], vmax=graph_settings[i][0][1], loc='sa', sa_mask=sa_mask) plot_data = variable_diff.mean(axis=0) #plot_south_america(lons, lats, sa_mask, plot_data, vmin, vmax) if variable in ('surf_temp', 'precip', 'q'): # unmasked. data_masked = plot_data plot_lons, plot_data = extend_data(lons, lats, data_masked) else: data_masked = np.ma.array(plot_data, mask=sa_mask) plot_lons, plot_data = extend_data(lons, lats, data_masked) lons, lats = np.meshgrid(plot_lons, lats) m = Basemap(projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32) x, y = m(lons, lats) m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax) m.drawcoastlines() if i == 0 or i == 3: m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10) elif i == 2 or i == 4: m.drawparallels(np.arange(-60.,15.,10.), labels=[0, 1, 0, 0], fontsize=10) else: m.drawparallels(np.arange(-60.,15.,10.)) m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10) cbar = m.colorbar(location='bottom', pad='7%', ticks=graph_settings[i][1])
def imshow_matches(im, title): fig = plt.figure() ax = fig.add_subplot(111) # ax.set_xlabel('PW Level') # ax.set_ylabel('S Level') # ax.set_xticks(s_label) # ax.set_yticks(pw_label) ax.set_title(title) plt.set_cmap(plt.get_cmap('hot')) plt.imshow(im)
def plotting(): conf = [[0 for x in range(L)] for y in range(L)] for k in range(N): x, y = x_y(k, L) conf[x][y] = S[k] pylab.imshow(conf, extent=[0, L, 0, L], interpolation='nearest') pylab.set_cmap('hot') pylab.title('Local_' + str(T) + '_' + str(L)) pylab.savefig('plot_A2_local_' + str(T) + '_' + str(L) + '.png') pylab.show()
def plotting(): conf = [[0 for x in range(L)] for y in range(L)] for k in range(N): x, y = x_y(k, L) conf[x][y] = S[k] pylab.imshow(conf, extent=[0, L, 0, L], interpolation='nearest') pylab.set_cmap('hot') pylab.title('Local_'+ str(T) + '_' + str(L)) pylab.savefig('plot_A2_local_'+ str(T) + '_' + str(L)+ '.png') pylab.show()
def make_image(data, outputname, size=(20, 2), dpi=1000): fig = plt.figure() fig.set_size_inches(size) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.set_cmap('jet') ax.imshow(data, aspect='equal') plt.savefig(outputname, dpi=dpi) plt.close()
def cutouts_plot(outpath, obj_base_name, flat_base_name, order_num, obj_img, flat_img, top_trace, bot_trace, trace): if const.upgrade: endPix = 2048 else: endPix = 1024 pl.figure('traces', facecolor='white', figsize=(10, 10)) pl.cla() pl.suptitle('order cutouts, {}, order {}'.format(obj_base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) norm = ImageNormalize(obj_img, interval=ZScaleInterval(), stretch=SquaredStretch()) obj_plot.imshow(obj_img, origin='lower', aspect='auto', norm=norm) #try: # obj_plot.imshow(exposure.equalize_hist(obj_img), aspect='auto', origin='lower') #except: # obj_plot.imshow(obj_img, aspect='auto', origin='lower') obj_plot.plot(np.arange(endPix), top_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(endPix), bot_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(endPix), trace, 'y-', linewidth=1.5) obj_plot.set_title('object ' + obj_base_name) #obj_plot.set_xlim([0, endPix-1]) flat_plot = pl.subplot(2, 1, 2) norm = ImageNormalize(flat_img, interval=ZScaleInterval(), stretch=SquaredStretch()) flat_plot.imshow(flat_img, origin='lower', aspect='auto', norm=norm) #try: # flat_plot.imshow(exposure.equalize_hist(flat_img), aspect='auto', origin='lower') #except: # flat_plot.imshow(flat_img, aspect='auto', origin='lower') flat_plot.plot(np.arange(endPix), top_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(endPix), bot_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(endPix), trace, 'y-', linewidth=1.5) flat_plot.set_title('flat ' + flat_base_name) #flat_plot.set_xlim([0, endPix-1]) obj_plot.minorticks_on() flat_plot.minorticks_on() #pl.tight_layout() pl.savefig(constructFileName(outpath, obj_base_name, order_num, 'cutouts.png'), bbox_inches='tight') pl.close()
def draw(self): plt.imshow( self._original_values.T, interpolation='none', origin='lower', extent=[ self._origin[X], self._origin[X] + self._values.shape[0] * self._resolution, self._origin[Y], self._origin[Y] + self._values.shape[1] * self._resolution ]) plt.set_cmap('gray_r')
def plot_classification(X, y, y_pred, keys, title, clf): print 'plot_classification(X=%s, y=%s, y_pred=%s, keys=%s, title=%s)' % (X.shape, y.shape, y_pred.shape, keys, title) h = .02 # step size in the mesh n_plots = len(keys)*(len(keys)-1)//2 n_side = int(math.sqrt(float(n_plots))) cnt = 1 for i0 in range(len(keys)): for i1 in range(i0+1, len(keys)): # create a mesh to plot in x_min, x_max = X[:,i0].min()-1, X[:,i0].max()+1 y_min, y_max = X[:,i1].min()-1, X[:,i1].max()+1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) pl.set_cmap(pl.cm.Paired) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. print 'subplot(%d, %d, cnt=%d)' % (n_side, n_side, cnt) pl.subplot(n_side, n_side, cnt) print 'xx.size=%s, xx.shape=%s, X.shape=%s' % (xx.size, xx.shape, X.shape) points = np.zeros([xx.size, X.shape[1]]) points[:,i0] = xx.ravel() points[:,i1] = yy.ravel() Z = clf.predict(points) # Put the result into a color plot Z = Z.reshape(xx.shape) pl.set_cmap(pl.cm.Paired) pl.contourf(xx, yy, Z) pl.axis('tight') #pl.xlabel(keys[0]) #pl.ylabel(keys[1]) # Plot also the training points #pl.scatter(X[:,0], X[:,1], c=y) plot_2d_histo_raw(X[:,i0], X[:,i1], y, keys[i0], keys[i1], x_max-x_min, y_max-y_min) #pl.title('%s vs %s' % (keys[i1], keys[i0])) pl.axis('tight') cnt +=1 if cnt > n_side ** 2: break if cnt > n_side ** 2: break pl.savefig(os.path.join('results', '%s.png' % title)) pl.show()
def set_cmap(name='viridis'): try: import matplotlib.colormaps as cmaps plt.register_cmap(name='viridis', cmap=cmaps.viridis) except ImportError: # this is the local version from . import colormaps as cmaps plt.register_cmap(name='viridis', cmap=cmaps.viridis) finally: plt.set_cmap(name) # For some reason set_cmap creates a figure, so close it. plt.close(plt.gcf())
def cmap_smooth(I=None,axh=None,Nlevels=256,cmap_lin=None): if cmap_lin is None: cmap_lin = pl.cm.jet if I is None: if not axh: axh = pl.gca() ihandles = axh.findobj(matplotlib.image.AxesImage) ih = ihandles[-1] I = ih.get_array() levels = np.percentile(I.ravel(),list(np.linspace(0,100,Nlevels))) cmap_nonlin = nlcmap(cmap_lin,levels) pl.set_cmap(cmap_nonlin)
def saveBEVImageWithAxes(data, outputname, cmap=None, xlabel='x [m]', ylabel='z [m]', rangeX=[-10, 10], rangeXpx=None, numDeltaX=5, rangeZ=[7, 62], rangeZpx=None, numDeltaZ=5, fontSize=16): ''' :param data: :param outputname: :param cmap: ''' aspect_ratio = float(data.shape[1]) / data.shape[0] fig = pylab.figure() Scale = 8 # add +1 to get axis text fig.set_size_inches(Scale * aspect_ratio + 1, Scale * 1) ax = pylab.gca() #ax.set_axis_off() #fig.add_axes(ax) if cmap is not None: pylab.set_cmap(cmap) #ax.imshow(data, interpolation='nearest', aspect = 'normal') ax.imshow(data, interpolation='nearest') if rangeXpx is None: rangeXpx = (0, data.shape[1]) if rangeZpx is None: rangeZpx = (0, data.shape[0]) modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel=xlabel, ylabel=ylabel) #plt.savefig(outputname, bbox_inches='tight', dpi = dpi) pylab.savefig(outputname, dpi=data.shape[0] / Scale) pylab.close() fig.clear()
def plotConfiguration(self, S, L, saveFigure=False): """Plots configuration of given 2D Ising Lattice """ conf = [[0 for x in range(L)] for y in range(L)] for k in range(L * L): x, y = self.x_y(k, L) conf[x][y] = S[k] pylab.imshow(conf, extent=[0, L, 0, L], interpolation='nearest') pylab.set_cmap('hot') pylab.title('Local_'+ str(T) + '_' + str(L)) if (saveFigure): pylab.savefig('plot_A2_local_'+ str(T) + '_' + str(L)+ '.png') pylab.show()
def plot(polylines, img=None): import pylab as plt plt.figure(1) for n, c in enumerate(polylines): x = c[:, 0] y = c[:, 1] plt.plot(x, y, linewidth=3) plt.text(x[-1], y[-1], str(n + 1)) if img is not None: plt.imshow(img, interpolation='none') plt.set_cmap('gray') plt.show()
def _heatmap_engine(self, suptitle, numIter=None, filter_count=None, saveas=None, show=True, cmap="Blues"): ''' An alternative way to visualize the annotations per iterative via a heat-map like construct. The rows are the GO annotations and the columns are iterations. The color intensity indicates how much a given annotation was present in a given iteration ''' res = self.annotation_dat if numIter is None else self.annotation_dat[0:numIter] depth = self.depth pl.figure(num=1,figsize=(20,8)) #AS is complete Annotation Set, max_count is the maximum number # of genes that appears in any single annotation entry (AS, max_count) = self._common_Y() #map is a grid Y=annotation X=iteration M(X,Y) = scaled count (c/max c) M = sp.zeros( (len(AS), len(res) ) ) for (col, dat, _) in res: if len(dat) < 1: continue for (l,d,c,_) in dat: row = AS.index((d,l)) M[row,col] = c #(c*1.0)/max_count #filter rows / pathways which dont show up often if not filter_count is None: assert type(filter_count) == int vals = sp.sum(M, axis=1) M = M[ vals >= filter_count, :] #only pathways with at least filter count over all iterations AS = [ x for i,x in enumerate(AS) if vals[i] >= filter_count ] pl.imshow(M, interpolation='nearest', aspect=len(res)*1.0/len(AS), origin='lower') #for (l,d) in AS: # row = AS.index((d,l)) # pl.text(-0.5, row, d[0:40], color="white", verticalalignment='center', fontsize=9) (descs, _labels) = zip(*AS) descs = [ d[0:30] for d in descs] #truncate long descriptions ylocations = sp.array(range(len(descs))) pl.yticks(ylocations, descs, fontsize=9, verticalalignment='center') pl.set_cmap(cmap) pl.xticks(range(len(res)), range(1, len(res)+1)) pl.ylabel("GO Annotation at Depth %d"%depth, fontsize=16) pl.xlabel("Iteration", fontsize=16) pl.colorbar(ticks=range(1, max_count+1)) if not suptitle is None: pl.title("Ontology Annotations per Iteration: %s"%suptitle, fontsize=18) if not saveas is None: pl.savefig(saveas) if show: pl.show()
def main(): altitudes = pl.loadtxt('altitude.txt') # print(altitudes.shape) partial_x = np.zeros(altitudes.shape) partial_y = np.zeros(altitudes.shape) size_y, size_x = altitudes.shape for y in range(altitudes.shape[0] - 1): for x in range(altitudes.shape[1] - 1): partial_x[y][x] = (altitudes[y][x + 1] - altitudes[y][x]) / 30000 partial_y[y][x] = (altitudes[y + 1][x] - altitudes[y][x]) / 30000 for x in range(altitudes.shape[1] - 1): partial_x[size_y - 1][x] = (altitudes[size_y - 1][x - 1] - altitudes[size_y - 1][x]) / 30000 partial_y[size_y - 1][x] = (altitudes[size_y - 1][x] - altitudes[size_y - 2][x]) / 30000 for y in range(altitudes.shape[0] - 1): partial_x[y][size_x - 1] = (altitudes[y][size_x - 1] - altitudes[y][size_x - 2]) / 30000 partial_y[y][size_x - 1] = (altitudes[y + 1][size_x - 1] - altitudes[y][size_x - 1]) / 30000 intensity = np.zeros(altitudes.shape) for y in range(size_y): for x in range(size_x): intensity[y][x] = I(partial_x[y][x], partial_y[y][x], pi / 4) pl.set_cmap('Greys') pl.imshow(intensity) pl.show() altitudes = pl.loadtxt('stm.txt') partial_x = np.zeros(altitudes.shape) partial_y = np.zeros(altitudes.shape) size_y, size_x = altitudes.shape for y in range(altitudes.shape[0] - 1): for x in range(altitudes.shape[1] - 1): partial_x[y][x] = (altitudes[y][x + 1] - altitudes[y][x]) / 2.50 partial_y[y][x] = (altitudes[y + 1][x] - altitudes[y][x]) / 2.50 for x in range(altitudes.shape[1] - 1): partial_x[size_y - 1][x] = (altitudes[size_y - 1][x - 1] - altitudes[size_y - 1][x]) / 2.50 partial_y[size_y - 1][x] = (altitudes[size_y - 1][x] - altitudes[size_y - 2][x]) / 2.50 for y in range(altitudes.shape[0] - 1): partial_x[y][size_x - 1] = (altitudes[y][size_x - 1] - altitudes[y][size_x - 2]) / 2.50 partial_y[y][size_x - 1] = (altitudes[y + 1][size_x - 1] - altitudes[y][size_x - 1]) / 2.50 intensity = np.zeros(altitudes.shape) for y in range(size_y): for x in range(size_x): intensity[y][x] = I(partial_x[y][x], partial_y[y][x], pi / 4) pl.imshow(intensity) pl.show()
def spatrect_plot(outpath, base_name, order_num, obj, flat): if const.upgrade: endPix = 2048 else: endPix = 1024 pl.figure('spatially rectified', facecolor='white', figsize=(10, 10)) pl.cla() pl.suptitle('spatially rectified, {}, order {}'.format( base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') obj_plot = pl.subplot(2, 1, 1) norm = ImageNormalize(obj, interval=ZScaleInterval(), stretch=SquaredStretch()) obj_plot.imshow(obj, origin='lower', aspect='auto', norm=norm) #try: # obj_plot.imshow(exposure.equalize_hist(obj), aspect='auto', origin='lower') #except: # obj_plot.imshow(obj, aspect='auto', origin='lower') obj_plot.set_title('object') # obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, endPix - 1]) flat_plot = pl.subplot(2, 1, 2) norm = ImageNormalize(flat, interval=ZScaleInterval(), stretch=SquaredStretch()) flat_plot.imshow(flat, origin='lower', aspect='auto', norm=norm) #try: # flat_plot.imshow(exposure.equalize_hist(flat), aspect='auto', origin='lower') #except: # flat_plot.imshow(flat, aspect='auto', origin='lower') flat_plot.set_title('flat') # flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, endPix - 1]) obj_plot.minorticks_on() flat_plot.minorticks_on() #pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, order_num, 'spatrect.png'), bbox_inches='tight') pl.close()
def draw_grids(self, rewards=None, title=None): # Draw the reward mapping of the grid world with grey scale if rewards is None: rewards = self.M.R R = np.zeros([self.dim, self.dim]) for i in range(self.dim): for j in range(self.dim): R[i, j] = rewards[self.__coord_to_index__([i, j])] if title is None: title = 'Reward mapping' pylab.title(title) pylab.set_cmap('gray') pylab.axis([0, self.dim, self.dim, 0]) c = pylab.pcolor(R, edgecolors='w', linewidths=1) pylab.show()
def convertBinToLabelMap(segImage, saveIntermediate=False, figFilePath="./"): """ Convert the binary segmentation image to a label map. Each component of the label map will be labelled using a separate label (labels are numbers, shown as colors). The labels should be separate cells, or closely clumped groups of cells. Inputs: - segImage: the binary segmentation image (sitk Image) - saveIntermediate: flag to indicate whether to save intermediate images (boolean) - figFilePath: the path to the location where the figure will be saved (string) Returns: - labelImage: the label map image (sitk Image) """ # Set up label map filter convertToLabelMap = sitk.BinaryImageToLabelMapFilter() labelMap = convertToLabelMap.Execute(segImage) labelImageFilter = sitk.LabelMapToLabelImageFilter() labelImageFilter.SetNumberOfThreads(4) labelImage = labelImageFilter.Execute(labelMap) # Show the label map pylab.set_cmap('terrain') pylab.imshow(sitk.GetArrayFromImage(labelImage)) # Print information about the label image labelArray = sitk.GetArrayFromImage(labelImage) print("Number of labels in the label map (including background):", np.amax(labelArray) - np.amin(labelArray) + 1) # Need to change the pixel types castFilter = sitk.CastImageFilter() castFilter.SetOutputPixelType(sitk.sitkUInt8) labelImage = castFilter.Execute(labelImage) # The pixel type should be "8-bit unsigned integer" assert labelImage.GetPixelIDTypeAsString() == "8-bit unsigned integer" if saveIntermediate: outFn = figFilePath + "02-labelmap.png" segArray = sitk.GetArrayFromImage(segImage) plt.imsave(outFn, labelArray, cmap='nipy_spectral') return labelImage
def traces_plot(outpath, obj_base_name, flat_base_name, order_num, obj_img, flat_img, top_trace, bot_trace): if const.upgrade: endPix = 2048 else: endPix = 1024 pl.figure('traces', facecolor='white', figsize=(10, 6)) pl.cla() pl.suptitle('order edge traces, {}, order {}'.format( obj_base_name, order_num), fontsize=14) pl.set_cmap('Blues_r') pl.rcParams['xtick.labelsize'] = 8 pl.rcParams['ytick.labelsize'] = 8 obj_plot = pl.subplot(1, 2, 1) try: obj_plot.imshow(exposure.equalize_hist(obj_img), origin='lower') except: obj_plot.imshow(obj_img, origin='lower') obj_plot.plot(np.arange(endPix), top_trace, 'y-', linewidth=1.5) obj_plot.plot(np.arange(endPix), bot_trace, 'y-', linewidth=1.5) obj_plot.set_title('object ' + obj_base_name) #obj_plot.set_ylim([endPix-1, 0]) #obj_plot.set_xlim([0, endPix-1]) flat_plot = pl.subplot(1, 2, 2) try: flat_plot.imshow(exposure.equalize_hist(flat_img), origin='lower') except: flat_plot.imshow(flat_img, origin='lower') flat_plot.plot(np.arange(endPix), top_trace, 'y-', linewidth=1.5) flat_plot.plot(np.arange(endPix), bot_trace, 'y-', linewidth=1.5) flat_plot.set_title('flat ' + flat_base_name) #flat_plot.set_ylim([endPix-1, 0]) #flat_plot.set_xlim([0, endPix-1]) obj_plot.minorticks_on() flat_plot.minorticks_on() #pl.tight_layout() pl.savefig(constructFileName(outpath, obj_base_name, order_num, 'traces.png'), bbox_inches='tight') pl.close()
def part_c(): img_data = np.loadtxt('blur.txt') shape = img_data.shape blur = [[gaussian(x, y, shape[0], shape[1]) for x in range(shape[0])] for y in range(shape[1])] fft_img = np.fft.rfft2(img_data) fft_blur = np.fft.rfft2(blur) fft_unblured = fft_img for i, row in enumerate(fft_unblured): for j, elem in enumerate(row): if fft_blur[i][j] > 1e-3: fft_unblured[i][j] /= (fft_blur[i][j]) unblured = np.fft.irfft2(fft_unblured) pylab.imshow(unblured) pylab.set_cmap('Greys_r') pylab.show()
def showIMG(IMG, extent = None, ticks = False): pylab.imshow(IMG, origin = 'lower', extent = extent) pylab.set_cmap(pylab.cm.gray) if extent == None: pylab.ylim((0, IMG.shape[0] - 1)) pylab.xlim((0, IMG.shape[1] - 1)) else: pylab.ylim((extent[2], extent[3])) pylab.xlim((extent[0], extent[1])) if not ticks: pylab.gca().get_xaxis().set_ticks([]) pylab.gca().get_yaxis().set_ticks([]) pylab.gca().invert_yaxis()
def plot_sa_seasonal_figure(control_dataset, data, sa_mask): f = plt.figure('sa_seasonal') plt.set_cmap('RdGy_r') graph_settings = ( ((-4, 4), np.arange(-4, 4.1, 2)), ((-6, 6), np.arange(-6, 6.1, 3))) variables = ['precip', 'surf_temp'] nice_names = {'precip': '$\Delta$Precip (mm/day)', 'surf_temp': '$\Delta$Surf temp (K)'} f.subplots_adjust(hspace=0.2, wspace=0.1) for j in range(len(variables)): for i, roll in enumerate([1, 10, 7, 4]): titles = ('DJF', 'MAM', 'JJA', 'SON') variable = variables[j] ax = plt.subplot(2, 4, i + j * 4 + 1) ax.set_title(titles[i]) variable_diff = data['data']['1pct'][variable] - data['data']['ctrl'][variable] lons, lats = get_vars_from_control_dataset(control_dataset) vmin, vmax = graph_settings[j][0] plot_data = np.roll(variable_diff, roll, axis=0)[:3].mean(axis=0) # unmasked. data_masked = plot_data plot_lons, plot_data = extend_data(lons, lats, data_masked) lons, lats = np.meshgrid(plot_lons, lats) m = Basemap(projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32) x, y = m(lons, lats) m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax) m.drawcoastlines() if i == 0: m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10) ax.set_ylabel(nice_names[variable]) ax.get_yaxis().set_label_coords(-0.25, 0.5) elif i == 3: m.drawparallels(np.arange(-60.,15.,10.), labels=[0, 1, 0, 0], fontsize=10) else: m.drawparallels(np.arange(-60.,15.,10.)) m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10) cbar = m.colorbar(location='bottom', pad='7%', ticks=graph_settings[j][1])
def _show(S, L, T, nsteps, suffix, show): def x_y(k, L): y = k // L x = k - y * L return x, y conf = [[0 for x in range(L)] for y in range(L)] for k in range(N): x, y = x_y(k, L) conf[x][y] = S[k] pylab.imshow(conf, extent=[0, L, 0, L], interpolation='nearest') pylab.set_cmap('hot') pylab.title('Local_'+ str(T) + '_' + str(L)) pylab.savefig('plot_A2_local_'+ str(T) + '_' + str(L)+ suffix + '_' + str(nsteps) + '.png') if show: pylab.show()
def plot_classifier(X, Y, models, classMap=None): """ Plots classifier or classifiers on 2d plot """ #handle single model if not isinstance(models, types.ListType): models = [models] titles = ["classifier"] else: titles = [] for model in models: titles.append("Classifier...") #colors for different decisions colors = ["red", "green", "blue", "yellow", "black"] # create a mesh to plot in h = 500 # step size in mesh x_min, x_max = X[:, 0].min() - .002, X[:, 0].max() + .002 y_min, y_max = X[:, 1].min() - .002, X[:, 1].max() + .002 xx, yy = np.meshgrid(np.arange(x_min, x_max, (x_max-x_min)/h), np.arange(y_min, y_max, (y_max-y_min)/h)) #set cmap pl.set_cmap(pl.cm.Paired) for mi, clf in enumerate( models ): # Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. pl.subplot(1, len(models), mi + 1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) pl.set_cmap(pl.cm.Paired) pl.contourf(xx, yy, Z) #pl.axis('off') # Plot also the training points if classMap: for c,i in classMap.iteritems(): x = X[Y==i] pl.plot(x[:,0], x[:,1], "o", c=colors[i], label=c) #legend and title pl.legend() pl.title(titles[mi]) pl.show()
def plot_classifier(X, Y, models, classMap=None): """ Plots classifier or classifiers on 2d plot """ #handle single model if not isinstance(models, types.ListType): models = [models] titles = ["classifier"] else: titles = [] for model in models: titles.append("Classifier...") #colors for different decisions colors = ["red", "green", "blue", "yellow", "black"] # create a mesh to plot in h = 50 # step size in mesh x_min, x_max = X[:, 0].min() - .002, X[:, 0].max() + .002 y_min, y_max = X[:, 1].min() - .002, X[:, 1].max() + .002 xx, yy = np.meshgrid(np.arange(x_min, x_max, (x_max - x_min) / h), np.arange(y_min, y_max, (y_max - y_min) / h)) #set cmap pl.set_cmap(pl.cm.Paired) for mi, clf in enumerate(models): # Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. pl.subplot(1, len(models), mi + 1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) pl.set_cmap(pl.cm.Paired) pl.contourf(xx, yy, Z) #pl.axis('off') # Plot also the training points if classMap: for c, i in classMap.iteritems(): x = X[Y == i] pl.plot(x[:, 0], x[:, 1], "o", c=colors[i], label=c) #legend and title pl.legend() pl.title(titles[mi]) pl.show()
def show_spins(S0, S1, L, label): pylab.set_cmap('hot') conf0 = [[0 for x in range(L)] for y in range(L)] conf1 = [[0 for x in range(L)] for y in range(L)] for k in range(N): y = k // L x = k - y * L conf0[x][y] = S0[k] conf1[x][y] = S1[k] pylab.subplot(1, 2, 1) pylab.imshow(conf0, extent=[0, L, 0, L], interpolation='nearest') pylab.title('S0 ' + label) pylab.subplot(1, 2, 2) pylab.imshow(conf1, extent=[0, L, 0, L], interpolation='nearest') pylab.title('S1 ' + label) pylab.tight_layout() pylab.savefig('plot_' + label + '.png') pylab.close()
def twoDimNoiseOrderPlot(outpath, base_name, title, base_filename, order_num, data, x_scale, wave_note='unknown'): """ Produces a generic 2-d image plot. Arguments: output: Directory path of root products directory. base_name: Base name of object frame. title: Title of plot, e.g. rectified order image. base_filename: order_num: data: x_scale: """ pl.figure('2d order image', facecolor='white', figsize=(8, 5)) pl.cla() pl.title(title + ', ' + base_name + ", order " + str(order_num), fontsize=14) pl.xlabel('wavelength($\AA$) (' + wave_note + ')', fontsize=12) pl.ylabel('row (pixel)', fontsize=12) pl.imshow(exposure.equalize_hist(data), origin='lower', extent=[x_scale[0], x_scale[-1], 0, data.shape[0]], aspect='auto') # pl.colorbar() # pl.set_cmap('jet') pl.set_cmap('gray') # pl.set_cmap('Blues_r') pl.minorticks_on() fn = constructFileName(outpath, base_name, order_num, base_filename) savePreviewPlot(fn) log_fn(fn) pl.close() return
def saveCurvatureOverlay(origImage, curves, curvatures, figFilePath='./'): """ Show the curvatures of the cells on the original image. Inputs: - origImage: the original greyscale image (sitk Image) - curves: the locations of the cell curves (list of lists of ints) - curvatures: the curvatures of the curves (list of floats) - figFilePath: the path to the location where the figure will be saved (string) Effects: - Makes a composite image consisting of the original image overlaid with colored versions of the curvatures. Also includes a colorbar. """ # Make a new figure and show the original image pylab.figure(figsize=(35, 25)) pylab.set_cmap('gray') pylab.imshow(sitk.GetArrayFromImage(origImage)) # Set up the overlay image shape = origImage.GetSize() overlay = np.zeros((shape[1], shape[0])) # Make the value 0.0 appear transparent overlay[overlay == 0.0] = np.nan # Iterate through the curve points and curvatures for point, value in zip(curves, curvatures): # Since we're capping the curvature value at 1 (potential miscalculations), # make sure the curvature values being plotted are at most 1. if value < 1: overlay[point[0], point[1]] = value else: overlay[point[0], point[1]] = 1 # Combine the overlay image and the original image pylab.imshow(overlay, 'rainbow', alpha=1) # Add a colorbar pylab.colorbar() # Save the image with the curvatures outFn = figFilePath + 'curvatures.png' pylab.savefig(outFn, bbox_inches='tight')
def order_location_plot(outpath, obj_base_name, flat_base_name, flat_img, obj_img, orders): pl.figure('orders', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('order location and identification', fontsize=14) pl.set_cmap('Blues_r') pl.rcParams['ytick.labelsize'] = 8 obj_plot = pl.subplot(1, 2, 1) try: obj_plot.imshow(exposure.equalize_hist(obj_img)) except: obj_plot.imshow(obj_img) obj_plot.set_title('object ' + obj_base_name) obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(1, 2, 2) try: flat_plot.imshow(exposure.equalize_hist(flat_img)) except: flat_plot.imshow(flat_img) flat_plot.set_title('flat ' + flat_base_name) flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) for order in orders: obj_plot.plot(np.arange(1024), order.flatOrder.topEdgeTrace, 'k-', linewidth=1.0) obj_plot.plot(np.arange(1024), order.flatOrder.botEdgeTrace, 'k-', linewidth=1.0) obj_plot.plot(np.arange(1024), order.flatOrder.smoothedSpatialTrace, 'y-', linewidth=1.0) obj_plot.text(10, order.flatOrder.topEdgeTrace[0] - 10, str(order.flatOrder.orderNum), fontsize=10) flat_plot.plot(np.arange(1024), order.flatOrder.topEdgeTrace, 'k-', linewidth=1.0) flat_plot.plot(np.arange(1024), order.flatOrder.botEdgeTrace, 'k-', linewidth=1.0) flat_plot.plot(np.arange(1024), order.flatOrder.smoothedSpatialTrace, 'y-', linewidth=1.0) flat_plot.text(10, order.flatOrder.topEdgeTrace[0] - 10, str(order.flatOrder.orderNum), fontsize=10) pl.tight_layout() pl.savefig(constructFileName(outpath, obj_base_name, None, 'traces.png')) pl.close()
def plot2DHist(points, name, x_dimension, y_dimension, fig): #add points to data at each corner, truncate data past corners. x = points[x_dimension] y = points[y_dimension] #truncate any data outside off -2,-2 2,2 borders index = [] for i in range(0, len(x)): if x[i] > 2 or x[i] < -2: index = numpy.append(index, i) if y[i] > 2 or y[i] < -2: index = numpy.append(index, i) x = numpy.delete(x, index) y = numpy.delete(y, index) #fix borders of histogram with edge points x = numpy.append(x, -2) y = numpy.append(y, -2) x = numpy.append(x, -2) y = numpy.append(y, 2) x = numpy.append(x, 2) y = numpy.append(y, -2) x = numpy.append(x, 2) y = numpy.append(y, 2) #pylab.axis("off") #fig = pylab.figure() dpi = fig.get_dpi() inches = 512.0 / dpi fig.set_size_inches(inches,inches) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pylab.hist2d(x, y, bins=100) pylab.set_cmap('gray') pylab.savefig(name + '.png') pylab.clf()
def order_location_plot(outpath, base_name, flat, obj, orders): pl.figure('orders', facecolor='white', figsize=(8, 5)) pl.cla() pl.suptitle('order location and identification, {}'.format(base_name), fontsize=14) pl.set_cmap('Blues_r') pl.rcParams['ytick.labelsize'] = 8 obj_plot = pl.subplot(1, 2, 1) try: obj_plot.imshow(exposure.equalize_hist(obj)) except: obj_plot.imshow(obj) obj_plot.set_title('object') obj_plot.set_ylim([1023, 0]) obj_plot.set_xlim([0, 1023]) flat_plot = pl.subplot(1, 2, 2) try: flat_plot.imshow(exposure.equalize_hist(flat)) except: flat_plot.imshow(flat) flat_plot.set_title('flat') flat_plot.set_ylim([1023, 0]) flat_plot.set_xlim([0, 1023]) for order in orders: obj_plot.plot(np.arange(1024), order.topTrace, 'k-', linewidth=1.0) obj_plot.plot(np.arange(1024), order.botTrace, 'k-', linewidth=1.0) obj_plot.plot(np.arange(1024), order.smoothedTrace, 'y-', linewidth=1.0) obj_plot.text(10, order.topTrace[0] - 10, str(order.orderNum), fontsize=10) flat_plot.plot(np.arange(1024), order.topTrace, 'k-', linewidth=1.0) flat_plot.plot(np.arange(1024), order.botTrace, 'k-', linewidth=1.0) flat_plot.plot(np.arange(1024), order.smoothedTrace, 'y-', linewidth=1.0) flat_plot.text(10, order.topTrace[0] - 10, str(order.orderNum), fontsize=10) pl.tight_layout() pl.savefig(constructFileName(outpath, base_name, None, 'traces.png')) pl.close()
def plot2DHist(points, name, x_dimension, y_dimension, fig): #add points to data at each corner, truncate data past corners. x = points[x_dimension] y = points[y_dimension] #truncate any data outside off -2,-2 2,2 borders index = [] for i in range(0, len(x)): if x[i] > 2 or x[i] < -2: index = numpy.append(index, i) if y[i] > 2 or y[i] < -2: index = numpy.append(index, i) x = numpy.delete(x, index) y = numpy.delete(y, index) #fix borders of histogram with edge points x = numpy.append(x, -2) y = numpy.append(y, -2) x = numpy.append(x, -2) y = numpy.append(y, 2) x = numpy.append(x, 2) y = numpy.append(y, -2) x = numpy.append(x, 2) y = numpy.append(y, 2) #pylab.axis("off") #fig = pylab.figure() dpi = fig.get_dpi() inches = 512.0 / dpi fig.set_size_inches(inches, inches) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pylab.hist2d(x, y, bins=100) pylab.set_cmap('gray') pylab.savefig(name + '.png') pylab.clf()
def Hist_Equal(img): image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert image to grayscal # count values for each pixels(image histogram) x, y = image.shape # get image size x*y, for a image with x rows and y columns histo = [0.0] * 256 # Initializes a 256 array to hold the number of # occurrences of each gray level for i in range(0, x): # count each pixel value(gray level) from 0 to x for j in range(0, y): # count each pixel value(gray level) from 0 to y histo[image[ i, j]] += 1 # count the number of occurrences of each gray level # cdf and new pixels values cdf = np.cumsum(np.array(histo)) # cumulative distribution function trans_val = np.uint8( (cdf - cdf[0]) / ((x * y) - cdf[0]) * 255) # calculate transfer value # applying transfered values for each pixels new_img = np.zeros_like( image) # Return an empty array new_img with shape and type of input. for i in range(0, x): # count each pixel value(gray level) from 0 to x for j in range(0, y): # count each pixel value(gray level) from 0 to y new_img[i, j] = trans_val[image[ i, j]] #fill the equalization result in the array # show original and equalized image pl.subplot(121) # image position 1 row, 2 column, first position pl.imshow(image) # show image "grayimg" pl.title('original image') # graph title "original image" pl.set_cmap('gray') # show in gray scale pl.subplot(122) # image position 1 row, 2 column, second position pl.imshow(new_img) # show image "grayimg" pl.title('equalized image') # graph title "original image" pl.set_cmap('gray') # show in gray scale pl.show() # output image
# Gemerate grid along first two principal components multiples = np.arange(-2, 2, 0.1) # steps along first component first = multiples[:, np.newaxis] * pca.components_[0, :] # steps along second component second = multiples[:, np.newaxis] * pca.components_[1, :] # combine grid = first[np.newaxis, :, :] + second[:, np.newaxis, :] flat_grid = grid.reshape(-1, data.shape[1]) # title for the plots titles = ['SVC with rbf kernel', 'SVC (linear kernel) with rbf feature map\n n_components=100'] pl.figure(figsize=(12, 5)) pl.set_cmap(pl.cm.Paired) # predict and plot for i, clf in enumerate((kernel_svm, approx_kernel_svm)): # Plot the decision boundary. For that, we will asign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. pl.subplot(1, 2, i + 1) Z = clf.predict(flat_grid) # Put the result into a color plot Z = Z.reshape(grid.shape[:-1]) pl.set_cmap(pl.cm.Paired) pl.contourf(multiples, multiples, Z) pl.axis('off')
nbin = len(unI) h = histogram(im, unI) P = h[0].astype(float)/sum(h[0]) w = cumsum(P) nbin = len(P) mu = cumsum(arange(1, nbin+1) * P) sigma2B = (mu[-1] * w[1:-1] - mu[1:-1])** 2 / w[1:-1]/(1-w[1:-1]) idx = where(sigma2B == max(sigma2B))[0][0] return h[1][idx] # ------------------------------------------------------------------------------ im = array(Image.open('textures/structure/015.jpg').convert("L")) / 255. bg = ndimage.grey_opening(im, footprint = circle(5)) pb.set_cmap(pb.cm.gray) pb.figure() pb.title("Original") pb.imshow(im,vmin=0, vmax=1) pb.savefig('result/structure/001.png', dpi=150) imbgadj = imadjust(im) pb.figure() pb.title("Normalized") pb.imshow(imbgadj, vmin = 0, vmax=1) pb.savefig('result/structure/002.png', dpi=150) t = otsu(imbgadj) print t segm = imbgadj > t + 0.12
import sys import pylab as plt import cv2 s0, s1 = 100, 100 arr = np.zeros((s0, s1)) # draw shape: arr[10:70, 20] = 1 arr[30, 2:99] = 1 # ellipse cv2.ellipse(arr, (20, 20), (30, 30), 0, 10, 200, 1) # remove few points from ellipse: arr[30:50, 30:50] *= np.random.rand(20, 20) > 0.2 # add noise arr += np.random.rand(s0, s1) > 0.95 contours = polylinesFromBinImage(arr) if 'no_window' not in sys.argv: plt.figure(0) plt.imshow(arr, interpolation='none') plt.figure(1) for n, c in enumerate(contours): if len(c) > 1: x = c[:, 0] y = c[:, 1] plt.plot(x, y, linewidth=3) plt.text(x[-1], y[-1], str(n + 1)) plt.imshow(arr, interpolation='none') plt.set_cmap('gray') plt.show()
def plot_wfront(mwf, title_fig, isHlog, isVlog, i_x_min, i_y_min, orient, onePlot, bPlotPha=None): """ Plot 2D wavefront (a slice). :param mwf: 2D wavefront structure :param title_fig: Figure title :param isHlog: if True, plot the horizontal cut in logarithmic scale :param isVlog: if True, plot the vertical cut in logarithmic scale :param i_x_min: Intensity threshold for horizontral cut, i.e. x-axis limits are [min(where(i_x<i_x_min):max(where(i_x<i_x_min)] :param i_y_min: Intensity threshold for vertical cut, :param orient: 'x' for returning horizontal cut, 'y' for vertical cut :param onePlot: if True, put intensity map and plot of cuts on one plot, as subplots :param bPlotPha: if True, plot the cuts of WF phase :return: 2-column array containing horizontal or vertical cut data in dependence of 'orient' parameter """ if isHlog: print 'FWHMx[um]:', calculate_fwhm_x(mwf) * 1e6 else: print 'FWHMx [mm]:', calculate_fwhm_x(mwf) * 1e3 if isVlog: print 'FWHMy [um]:', calculate_fwhm_y(mwf) * 1e6 else: print 'FWHMy [mm]:', calculate_fwhm_y(mwf) * 1e3 [xc, yc] = calculate_peak_pos(mwf) print 'Coordinates of center, [mm]:', xc * 1e3, yc * 1e3 ii = mwf.get_intensity(slice_number=0, polarization='vertical') imax = numpy.max(ii) [nx, ny, xmin, xmax, ymin, ymax] = get_mesh(mwf) ph = mwf.get_phase(slice_number=0, polarization='vertical') print 'stepX, stepY [um]:', -(xmin - xmax) / (nx - 1) * 1e6, -(ymin - ymax) / (ny - 1) * 1e6, '\n' xa = numpy.linspace(xmin, xmax, nx) ya = numpy.linspace(ymin, ymax, ny) pylab.figure(figsize=(15,10)) if onePlot: pylab.subplot(221) [x1, x2, y1, y2] = mwf.get_limits() pylab.imshow(ii, extent=[x1 * 1e3, x2 * 1e3, y1 * 1e3, y2 * 1e3]) pylab.set_cmap('bone') pylab.set_cmap('hot') pylab.axis('auto') pylab.colorbar() pylab.xlabel('x (mm)') pylab.ylabel('y (mm)') pylab.title(title_fig) irr_y = ii[:, numpy.max(numpy.where(xa == xc))] irr_x = ii[numpy.max(numpy.where(ya == yc)), :] pha_y = ph[:, numpy.max(numpy.where(xa == xc))] pha_x = ph[numpy.max(numpy.where(ya == yc)), :] if onePlot: pylab.subplot(222) else: pylab.figure() if isVlog and max(irr_y) > 0: #ya = ya*1e6 pylab.semilogy(ya * 1e6, irr_y, '-vk') pylab.xlabel('(um)') pylab.xlim(min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e6, max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e6) else: #ya = ya*1e3 pylab.plot(ya * 1e3, irr_y) pylab.xlabel('y (mm)') pylab.xlim(min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3, max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3) pylab.title('Vertical cut, xc = ' + str(int(xc * 1e6)) + ' um') pylab.grid(True) if onePlot: pylab.subplot(223) else: pylab.figure() if isHlog and max(irr_x) > 0: #xa = xa*1e6 pylab.semilogy(xa * 1e6, irr_x, '-vr') pylab.xlabel('x, (um)') pylab.xlim(min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e6, max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e6) else: #xa = xa*1e3 pylab.plot(xa * 1e3, irr_x) pylab.xlabel('x (mm)') pylab.xlim(min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3, max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3) pylab.title('Horizontal cut, yc = ' + str(int(yc * 1e6)) + ' um') pylab.grid(True) if bPlotPha: pylab.figure() pylab.plot(ya * 1e3, pha_y, '-ok') pylab.xlim(min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3, max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3) pylab.ylim(-numpy.pi, numpy.pi) pylab.xlabel('y (mm)') pylab.title('phase, vertical cut, x=0') pylab.grid(True) pylab.figure() pylab.plot(xa * 1e3, pha_x, '-or') pylab.xlim(min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3, max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3) pylab.ylim(-numpy.pi, numpy.pi) pylab.xlabel('x (mm)') pylab.title('phase, horizontal cut, y=0') pylab.grid(True) if orient == 'x': dd = numpy.zeros(shape=(nx, 2), dtype=float) dd[:, 0] = xa #for idx in range(nx): dd[idx, 1] = sum(ii[:, idx]) dd[:, 1] = irr_x if orient == 'y': dd = numpy.zeros(shape=(ny, 2), dtype=float) dd[:, 0] = ya #for idx in range(ny): dd[idx, 1] = sum(ii[idx, :]) dd[:, 1] = irr_y return dd
def plot_wfront(mwf, title_fig, isHlog, isVlog, i_x_min, i_y_min, orient, onePlot, bPlotPha=None,saveDir=None): """ Plot 2D wavefront (a slice). :param mwf: 2D wavefront structure :param title_fig: Figure title :param isHlog: if True, plot the horizontal cut in logarithmic scale :param isVlog: if True, plot the vertical cut in logarithmic scale :param i_x_min: Intensity threshold for horizontral cut, i.e. x-axis limits are [min(where(i_x<i_x_min):max(where(i_x<i_x_min)] :param i_y_min: Intensity threshold for vertical cut, :param orient: 'x' for returning horizontal cut, 'y' for vertical cut :param onePlot: if True, put intensity map and plot of cuts on one plot, as subplots :param bPlotPha: if True, plot the cuts of WF phase :return: 2-column array containing horizontal or vertical cut data in dependence of 'orient' parameter """ if isHlog: print 'FWHMx[um]:', calculate_fwhm_x(mwf) * 1e6 else: print 'FWHMx [mm]:', calculate_fwhm_x(mwf) * 1e3 if isVlog: print 'FWHMy [um]:', calculate_fwhm_y(mwf) * 1e6 else: print 'FWHMy [mm]:', calculate_fwhm_y(mwf) * 1e3 [xc, yc] = calculate_peak_pos(mwf) print 'Coordinates of center, [mm]:', xc * 1e3, yc * 1e3 ii = mwf.get_intensity(slice_number=0, polarization='horizontal') # [LS14-06-02] # for 2D Gaussian the intrincic SRW GsnBeam wave field units Nph/mm^2/0.1%BW # to get fluence W/mm^2 # (Note: coherence time for Gaussian beam duration should be specified): ii = ii*mwf.params.photonEnergy/J2EV#*1e3 imax = numpy.max(ii) [nx, ny, xmin, xmax, ymin, ymax] = get_mesh(mwf) ph = mwf.get_phase(slice_number=0, polarization='horizontal') dx = (xmax-xmin)/(nx-1); dy = (ymax-ymin)/(ny-1) print 'stepX, stepY [um]:', dx * 1e6, dy * 1e6, '\n' xa = numpy.linspace(xmin, xmax, nx); ya = numpy.linspace(ymin, ymax, ny); if mwf.params.wEFieldUnit <> 'arbitrary': print 'Total power (integrated over full range): %g [GW]' %(ii.sum(axis=0).sum(axis=0)*dx*dy*1e6*1e-9) print 'Peak power calculated using FWHM: %g [GW]' %(imax*1e-9*1e6*2*numpy.pi*(calculate_fwhm_x(mwf)/2.35)*(calculate_fwhm_y(mwf)/2.35)) print 'Max irradiance: %g [GW/mm^2]' %(imax*1e-9) label4irradiance = 'Irradiance (W/$mm^2$)' else: ii = ii / imax label4irradiance = 'Irradiance (a.u.)' pylab.figure(figsize=(21,6)) if onePlot: pylab.subplot(131) [x1, x2, y1, y2] = mwf.get_limits() pylab.imshow(ii, extent=[x1 * 1e3, x2 * 1e3, y1 * 1e3, y2 * 1e3]) pylab.set_cmap('bone') #pylab.set_cmap('hot') pylab.axis('tight') #pylab.colorbar(orientation='horizontal') pylab.xlabel('x (mm)') pylab.ylabel('y (mm)') pylab.title(title_fig) irr_y = ii[:, numpy.max(numpy.where(xa == xc))] irr_x = ii[numpy.max(numpy.where(ya == yc)), :] pha_y = ph[:, numpy.max(numpy.where(xa == xc))] pha_x = ph[numpy.max(numpy.where(ya == yc)), :] if onePlot: pylab.subplot(132) else: pylab.figure() if isVlog and numpy.max(irr_y) > 0: #ya = ya*1e6 pylab.semilogy(ya * 1e6, irr_y, '-vk') pylab.xlabel('(um)') pylab.xlim(numpy.min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e6, numpy.max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e6) else: #ya = ya*1e3 pylab.plot(ya * 1e3, irr_y) pylab.xlabel('y (mm)') pylab.xlim(numpy.min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3, numpy.max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3) pylab.ylim(0,numpy.max(ii)*1.1) pylab.ylabel(label4irradiance) pylab.title('Vertical cut, xc = ' + str(int(xc * 1e6)) + ' um') pylab.grid(True) if onePlot: pylab.subplot(133) else: pylab.figure() if isHlog and numpy.max(irr_x) > 0: #xa = xa*1e6 pylab.semilogy(xa * 1e6, irr_x, '-vr') pylab.xlabel('x, (um)') pylab.xlim(numpy.min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e6, numpy.max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e6) else: #xa = xa*1e3 pylab.plot(xa * 1e3, irr_x) pylab.xlabel('x (mm)') pylab.xlim(numpy.min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3, numpy.max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3) pylab.ylim(0,numpy.max(ii)*1.1) pylab.ylabel(label4irradiance) pylab.title('Horizontal cut, yc = ' + str(int(yc * 1e6)) + ' um') pylab.grid(True) if saveDir is not None: epsname="%s/%s.eps" % (saveDir,title_fig.split("at ")[1].split(" m")[0]) pylab.savefig(epsname) #pylab.close(epsfig) if bPlotPha: pylab.figure() pylab.plot(ya * 1e3, pha_y, '-ok') pylab.xlim(numpy.min(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3, numpy.max(ya[numpy.where(irr_y >= imax * i_y_min)]) * 1e3) pylab.ylim(-numpy.pi, numpy.pi) pylab.xlabel('y (mm)') pylab.title('phase, vertical cut, x=0') pylab.grid(True) pylab.figure() pylab.plot(xa * 1e3, pha_x, '-or') pylab.xlim(numpy.min(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3, numpy.max(xa[numpy.where(irr_x >= imax * i_x_min)]) * 1e3) pylab.ylim(-numpy.pi, numpy.pi) pylab.xlabel('x (mm)') pylab.title('phase, horizontal cut, y=0') pylab.grid(True) if orient == 'x': dd = numpy.zeros(shape=(nx, 2), dtype=float) dd[:, 0] = xa #for idx in range(nx): dd[idx, 1] = sum(ii[:, idx]) dd[:, 1] = irr_x if orient == 'y': dd = numpy.zeros(shape=(ny, 2), dtype=float) dd[:, 0] = ya #for idx in range(ny): dd[idx, 1] = sum(ii[idx, :]) dd[:, 1] = irr_y return dd
delta_E = 2.0 * S[k] * sum(S[nn] for nn in nbr[k]) if random.uniform(0.0, 1.0) < math.exp(-beta * delta_E): S[k] *= -1 Energy += delta_E E.append(Energy) if step % math.floor(nsteps / 10) == 0: print 'step: ', step print 'mean energy per spin:', sum(E) / float(len(E) * N) f = open(filename, 'w') for a in S: f.write(str(a) + '\n') f.close() def x_y(k, L): y = k // L x = k - y * L return x, y conf = [[0 for x in range(L)] for y in range(L)] for k in range(N): x, y = x_y(k, L) conf[x][y] = S[k] pylab.imshow(conf, extent=[0, L, 0, L], interpolation='nearest') pylab.set_cmap('hot') pylab.title('Local_'+ str(T) + '_' + str(L)) pylab.savefig('plot_A2_local_'+ str(T) + '_' + str(L)+ '.png') pylab.show()
#run pyfusion/examples/small_65.py import numpy as np import pylab as pl size_scale=30 cind = 0 colorset=('b,g,r,c,m,y,k,orange,purple,lightgreen,gray'.split(',')) # to be rotated DA65MPH=DA('DA65MP2010HMPno612b5_M_N_fmax.npz',load=1) DA65MPH.extract(locals()) pyfusion.config.set('Plots',"FT_Axis","[0.5,4,0,80000]") """ run -i pyfusion/examples/plot_specgram.py shot_number=65139 channel_number=1 NFFT=1024 pl.set_cmap(cm.gray_r) pl.clim(-60,-0) """ sc_kw=dict(edgecolor='k',linewidth = 0.3) for n in (-1,0,1): for m in (-2, -1,1,2): w =np.where((N==n) & (M==m) & (_binary_svs < 99) & bw(freq,frlow,frhigh))[0] if len(w) != 0: col = colorset[cind] pl.scatter(t_mid[w], freq[w], size_scale*amp[w], color=col, label='m,n=~{m},{n}'.format(m=m, n=n),**sc_kw) cind += 1 w=where((_binary_svs < 99) & bw(freq,frlow,frhigh) & bw(MM, 0,130) & (NN== -4))[0] col = colorset[cind] ; cind+=1 m = 1; n=0 pl.scatter(t_mid[w], freq[w], size_scale*amp[w], color=col, label='m,n=~{m},{n}'.format(m=m, n=n),**sc_kw)
def rthetaz_pop(): # Creates a 1.e3 x 1.e3 x 1.e3 array of random numbers randa=scipy.random.random_sample(size=(10000,3)) # IAU Galactic constants R0 = 8500.0 V0 = 220.0 # R is the radius, phi is the azimuth # Populate the cylinder phi = -math.pi + 2*math.pi*randa[:,0] R = 25000.*randa[:,1] z = -100. + 200*randa[:,2] # Transform the the (R, phi, z) into cartesian. To be consistent with l,b standards: # coordinates (X,Y,Z), centred on the Galactic Centre. +Y should point towards the Sun # +X should point in the direction of rotation, and # +Z should point above the plane (positive b, North Galactic Pole). # Defined this way, phi is zero at the Sun-Centre line and increases in the direction of Galactic rotation. x = R * np.sin(phi) y = R * np.cos(phi) z = z print "Min x: %.2f Max x: %.2f" % (min(x),max(x)) print "Min y: %.2f Max y: %.2f" % (min(y),max(y)) print "Min z: %.2f Max z: %.2f" % (min(z),max(z)) # Make a spiral of the model used for velocity field X1 = np.arange(-10000, 10000, 100) Y1 = np.arange(-10000, 10000, 100) X1, Y1 = np.meshgrid(X1, Y1) R1 =np.sqrt(X1**2 + Y1**2) Z1 = 1/np.tan(math.pi/2) * R1 # To Transform to the Galactic positions Y is along the Sun-GC line increasing away from the GC yprime=R0-1.0*y # Shift to the position of the Sun d = np.sqrt(yprime**2 + x**2 + z**2) lat = np.degrees(np.arcsin(z/d)) lon = np.degrees(np.arctan2(x,yprime)) for i in range(len(R)): if R[i] >= R0 * abs(np.sin(np.radians(lon[i]))) -10. and R[i] <= R0 * abs(np.sin(np.radians(lon[i]))) +10.0: print " %.2f %.2f %.2f %.2f %.2f" % (R[i], lon[i], d[i], x[i],y[i]) print lon[i],np.degrees(phi[i]) # Get the LSR velocity # NOTE phi is in radians whereas lon, and lat are in degrees vel = vlsr(R,z,d,lon,lat,phi) # Standard Galactic rotation #vel = vnoncirc(R,z,d,lon,lat,phi) #vel = vel2(R,z,d,lon,lat,phi) # Burton & Liszt (1978) tilted disk # Plot the distribution of points on a 3d plot fig = pylab.figure(2) pylab.clf() ax = Axes3D(fig) ax.scatter(x,y,z,marker='o',s=40, c=vel) surf = ax.plot_surface(X1, Y1, Z1,linewidth=0, antialiased=False) ax.set_xlabel('X (pc)') ax.set_ylabel('Y (pc)') ax.set_zlabel('Z (pc)') # Plot the x, y disk pylab.figure(1) pylab.clf() CS=pylab.scatter(x,y,s=20,c=vel) pylab.clim(-250,250) pylab.set_cmap('jet') CB=pylab.colorbar(CS) pylab.xlim(-25000,25000) pylab.ylim(-25000,25000) #pylab.contour(x,y,xi) pylab.xlabel("X (pc)") pylab.minorticks_on() pylab.ylabel("Y (pc)") pylab.savefig("sim_xyv.pdf") # Plot the l,b,v clouds pylab.figure(2) pylab.clf() CS=pylab.scatter(lon,lat,s=40,c=vel) pylab.clim(-250,250) pylab.set_cmap('jet') CB=pylab.colorbar(CS) pylab.xlim(180,-180) pylab.ylim(-5,5) pylab.xlabel("GALACTIC Longitude (deg)") pylab.ylabel("GALACTIC Latitude (deg)") pylab.savefig("sim_lb.pdf") return lon,lat,vel