def display(self, X, y, w): # create a mesh to plot in h = .02 x_min, x_max = X[:, 1].min() - 1, X[:, 1].max() + 1 y_min, y_max = X[:, 2].min() - 1, X[:, 2].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = np.inner(w, np.c_[np.ones(xx.ravel().shape), xx.ravel(), yy.ravel()]) Z[Z >= 0] = 1 Z[Z < 0] = -1 Z = Z.reshape(xx.shape) # print 'Z', Z plt.figure() plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # Plot also the training points plt.scatter(X[:, 1], X[:, 2], c=y, cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
def do_plot(mode, content, wide): global style style.apply(mode, content, wide) data = np.load("data/prr_AsAu_%s%s.npz"%(content, wide)) AU, TAU = np.meshgrid(-data["Au_range_dB"], data["tau_range"]) Zu = data["PRR_U"] Zs = data["PRR_S"] assert TAU.shape == AU.shape == Zu.shape, "The inputs TAU, AU, PRR_U must have the same shape for plotting!" plt.clf() if mode in ("sync",): # Plot the inverse power ratio, sync signal is stronger for positive ratios CSf = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower") CS2 = plt.contour(CSf, colors = ("r",)*5+("w",), linewidths=(0.75,)*5+(1.0,), origin="lower", hold="on") else: CSf = plt.contourf(TAU, AU, Zs, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0), colors=("1.0", "0.75", "0.5", "0.25", "0.15", "0.0"), origin="lower") CS2f = plt.contour(CSf, levels=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0), colors=4*("r",)+("w",), linewidths=(0.75,)*4+(1.0,), origin="lower", hold="on") #CS2f = plt.contour(TAU, -AU, Zu, levels=(0.9, 1.0), colors=("0.0",), linewidths=(1.0,), origin="lower", hold="on") if content in ("unif",): CSu = plt.contourf(TAU, AU, Zu, levels=(0.2, 1.0), hatches=("////",), colors=("0.75",), origin="lower") CS2 = plt.contour(CSu, levels=(0.2,), colors = ("r",), linewidths=(1.0,), origin="lower", hold="on") style.annotate(mode, content, wide) plt.axis([data["tau_range"][0], data["tau_range"][-1], -data["Au_range_dB"][-1], -data["Au_range_dB"][0]]) plt.ylabel(r"Signal power ratio ($\mathrm{SIR}$)", labelpad=2) plt.xlabel(r"Time offset $\tau$ ($/T$)", labelpad=2) plt.savefig("pdf/prrc2_%s_%s%s_z.pdf"%(mode, content, wide))
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # plot class samples for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) # Highlight test samples if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, linewidths=1, marker='o', s=55, label='test set')
def plot_landscape_2d(landscape, ds): """ Plot the height of the landscape in 2 dimensions given a landscape object :param landscape: Landscape object with all data :param ds: Downsampling factor for only plotting every ds point :return: Plot the landscape in the x-y-coordinate system """ # Construct the (x, y)-coordinate system x_grid = np.linspace(landscape.x_min, landscape.x_max, landscape.num_of_nodes_x) y_grid = np.linspace(landscape.y_max, landscape.y_min, landscape.num_of_nodes_y) x, y = np.meshgrid(x_grid[0::ds], y_grid[0::ds]) z = landscape.arr[0::ds, 0::ds] # Decide color map and number of contour levels cmap = plt.get_cmap('terrain') v = np.linspace(min(landscape.coordinates[:, 2]), max(landscape.coordinates[:, 2]), 100, endpoint=True) plt.contourf(x, y, z, v, cmap=cmap) plt.colorbar(label='Height', spacing='uniform') # Title and labels plt.rcParams.update({'font.size': 14}) plt.title('The landscape') plt.xlabel('x') plt.ylabel('y') plt.show()
def draw(data, classes, model, resolution=100): mycm = mpl.cm.get_cmap('Paired') one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1 two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1 xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution), np.arange(two_min, two_max, (two_max-two_min)/resolution)) inputs = np.c_[xx1.ravel(), xx2.ravel()] z = [] for i in range(len(inputs)): z.append(predict(model, inputs[i])[0]) result = np.array(z).reshape(xx1.shape) plt.contourf(xx1, xx2, result, cmap=mycm) plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm) t = np.zeros(15) for i in range(15): if i < 5: t[i] = 0 elif i < 10: t[i] = 1 else: t[i] = 2 plt.scatter(model[:, 0], model[:, 1], s=150, c=t, cmap=mycm) plt.xlim([0, 10]) plt.ylim([0, 10]) plt.show()
def plot_fgmax_grid(): fg = fgmax_tools.FGmaxGrid() fg.read_input_data('fgmax_grid1.txt') fg.read_output() #clines_zeta = [0.01] + list(numpy.linspace(0.05,0.3,6)) + [0.5,1.0,10.0] clines_zeta = [0.001] + list(numpy.linspace(0.05,0.25,10)) colors = geoplot.discrete_cmap_1(clines_zeta) plt.figure(1) plt.clf() zeta = numpy.where(fg.B>0, fg.h, fg.h+fg.B) # surface elevation in ocean plt.contourf(fg.X,fg.Y,zeta,clines_zeta,colors=colors) plt.colorbar() plt.contour(fg.X,fg.Y,fg.B,[0.],colors='k') # coastline # plot arrival time contours and label: arrival_t = fg.arrival_time/3600. # arrival time in hours #clines_t = numpy.linspace(0,8,17) # hours clines_t = numpy.linspace(0,2,5) # hours #clines_t_label = clines_t[::2] # which ones to label clines_t_label = clines_t[::1] # which ones to label clines_t_colors = ([.5,.5,.5],) con_t = plt.contour(fg.X,fg.Y,arrival_t, clines_t,colors=clines_t_colors) plt.clabel(con_t, clines_t_label) # fix axes: plt.ticklabel_format(format='plain',useOffset=False) plt.xticks(rotation=20) plt.gca().set_aspect(1./numpy.cos(fg.Y.mean()*numpy.pi/180.)) plt.title("Maximum amplitude / arrival times (hrs)")
def contourf(self,vv=range(-10,0),**kwargs): fig= plt.figure(figsize=(9,8)) #h.imshow(np.flipud(self.Z),extent=[bbox[0],bbox[1],bbox[3],bbox[2]]) plt.contourf(self.grd.X,self.grd.Y,self.Z,vv,**kwargs) plt.colorbar() plt.axis('equal') return fig
def plot_decision_regions(X, y, classifier, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # plot class samples for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx], marker=markers[idx], label=cl, edgecolor='black')
def test_complete(): fig = plt.figure('Figure with a label?', figsize=(10, 6)) plt.suptitle('Can you fit any more in a figure?') # make some arbitrary data x, y = np.arange(8), np.arange(10) data = u = v = np.linspace(0, 10, 80).reshape(10, 8) v = np.sin(v * -0.6) plt.subplot(3, 3, 1) plt.plot(list(xrange(10))) plt.subplot(3, 3, 2) plt.contourf(data, hatches=['//', 'ooo']) plt.colorbar() plt.subplot(3, 3, 3) plt.pcolormesh(data) plt.subplot(3, 3, 4) plt.imshow(data) plt.subplot(3, 3, 5) plt.pcolor(data) plt.subplot(3, 3, 6) plt.streamplot(x, y, u, v) plt.subplot(3, 3, 7) plt.quiver(x, y, u, v) plt.subplot(3, 3, 8) plt.scatter(x, x**2, label='$x^2$') plt.legend(loc='upper left') plt.subplot(3, 3, 9) plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4) ###### plotting is done, now test its pickle-ability ######### # Uncomment to debug any unpicklable objects. This is slow (~200 seconds). # recursive_pickle(fig) result_fh = BytesIO() pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL) plt.close('all') # make doubly sure that there are no figures left assert_equal(plt._pylab_helpers.Gcf.figs, {}) # wind back the fh and load in the figure result_fh.seek(0) fig = pickle.load(result_fh) # make sure there is now a figure manager assert_not_equal(plt._pylab_helpers.Gcf.figs, {}) assert_equal(fig.get_label(), 'Figure with a label?')
def animate(i): ax.cla() active_list = np.where(active[:, i] == 1)[0] if len(active_list) < 1: active_list = 0 #active_list = range(len(lon[:,i]))#indices # if len(np.where(active_list)) > 1: if drawland: m.drawcoastlines() m.fillcontinents(color='forestgreen', lake_color='aqua') if recordedvar is not 'none': scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c=record[active_list, i], cmap=rcmap, vmin=0, vmax=1) elif plot_mfregion: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, color=mf_cols, cmap='summer', vmin=0, vmax=1) else: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c='blue', edgecolors='black') ax.set_xlim([limits[0], limits[1]]) ax.set_ylim([limits[2], limits[3]]) if backgroundfield is not 'none': field_time = np.argmax(bT > time[0, i]) - 1 plt.contourf(bY[:], bX[:], bVar[field_time, :, :], vmin=0, vmax=np.max(bVar[field_time, :, :]), levels=np.linspace(0, np.max(bVar[field_time, :, :]), 100), xlim=[limits[0], limits[1]], zorder=-1,ylim=[limits[2], limits[3]], cmap=cmap) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) if display is not 'none': if display == 'time': plt.suptitle(datetime.fromtimestamp(title[0,i])) else: plt.suptitle("Cohort age %s months" % display)#"Cohort age = %s months" % title[0,i]) plt.title("Region %s" % mf_focus) return scat,
def plot_qdens_log(r,z,dens, dens0): CS0 = plt.contourf(z,r,dens0, colors='k') #mark areas with data but zero density if dens.max() > 0.0: CS1 = plt.contourf(z, r, dens,norm=LogNorm(vmin=1e10, vmax=1e20)) if drawCB: CB1 = plt.colorbar(CS1) else: CS1 = None if drawCB: CB1 = plt.colorbar(CS0, ticks=[]) if dens.min() < 0.0: CS2 = plt.contourf(z, r, -dens,norm=LogNorm(vmin=1e10, vmax=1e20), hatches='x') if drawCB: CB2 = plt.colorbar(CS2) else: CS2 = None if drawCB: CB2 = plt.colorbar(CS0, ticks=[]) if drawCB: CB1.set_label("Positive charge density [cm$^{-3}$]") CB2.set_label("Negative charge density [cm$^{-3}$]") plt.xlabel("z [um]") plt.ylabel("r [um]") if axisShape == "image": plt.axis('image') if cutR != None: plt.ylim(0,cutR) return (CS0, CS1, CS2)
def gridplot(z, npoints=1024, phi=None, theta=None, cbar=True, earthpt=None, vmin=None, vmax=None, aspect='auto', rasterized=False): importmpl() if phi == None: import gbm (phi, theta) = gbm.respgrid() p = np.linspace(0, 2*np.pi, npoints) t = np.linspace(0, np.pi, int(npoints/2)) idx = np.nonzero(phi == 0) pwrap = phi[idx] + 2 * np.pi twrap = theta[idx] zwrap = z[idx] (pp, tt) = np.meshgrid(p, t) zgrid = mlab.griddata(np.hstack((phi, pwrap)), np.hstack((theta, twrap)), np.hstack((z, zwrap)), pp, tt, interp='linear') if earthpt != None: occlimit = np.cos(67 * np.pi/180.) eagrid = np.sum(pt2xyz((pp.ravel(), tt.ravel())).T * pt2xyz(earthpt), axis=1).reshape(pp.shape) zgrid[eagrid > occlimit] = 0 h = plt.imshow(zgrid, extent=(0, 2*np.pi, np.pi, 0), vmin=vmin, vmax=vmax, aspect=aspect, rasterized=rasterized) if cbar: plt.colorbar(orientation='horizontal', aspect=30, shrink=1.0) if earthpt != None: plt.contourf(pp, tt, eagrid, [occlimit, 1.0], colors='0.75', label='Earth extent') plt.plot(earthpt[0], earthpt[1], marker=r'$\oplus$', ls='none', label='Earth') # plt.subplots_adjust(top=0.875) return (h, plt.gca())
def plot_3d(M, epoints, eloss, limits = [], xlim = [], ylim = [], title = '', save_fig = False, outname = '3dmap.png'): """ Plots 3d incident energy x energy loss graph. M is a matrix with the data as M[incident energy, energy loss]. epoints is the incident energies, and eloss the energy loss. """ plt.figure() if len(limits[:]) == 0: fig = plt.contourf(epoints, eloss, M, 100) plt.colorbar() else: tks = [] for i in range (6): tks.append(limits[0] + i*(limits[1]-limits[0])/5) z = np.linspace(limits[0],limits[1], 100, endpoint=True) fig = plt.contourf(epoints, eloss, M, z) plt.colorbar(ticks=tks) plt.xlabel('Incident Energy (eV)', fontsize=15) plt.ylabel('Energy Loss (eV)', fontsize=15) if len(xlim) != 0: plt.xlim(xlim[0],xlim[1]) if len(ylim) != 0: plt.ylim(ylim[0], ylim[1]) plt.title(title) if save_fig is True: plt.savefig(outname, format='png', dpi=1000)
def graph(self, x_axis, y_axis, image, params, result = None): #plot the sample data from matplotlib import pyplot pyplot.figure() pyplot.subplot(2,1,1) pyplot.contourf(x_axis, y_axis, image, alpha = 0.5) #plot the fit #sample the fit with more precision x_axis_fit = np.linspace(x_axis.min(), x_axis.max(), x_axis.size * 5) y_axis_fit = np.linspace(y_axis.min(), y_axis.max(), y_axis.size * 5) xx, yy = np.meshgrid(x_axis_fit, y_axis_fit) params['background_level'].value = 0 fit_1d = self.ion_model(params, xx, yy, use_1d=True) xx, yy = np.meshgrid(x_axis, y_axis) pyplot.subplot(2,1,2) ximage = image.sum(axis=0) ximage = ximage - ximage[0] a1d = np.ones_like(self.allions_1d) #low_values_indices = self.allions_1d - bg < (0.5)*params['amplitude'].value # Where values are low low_values_indices = self.allions_1d < self.model_threshold # Where values are low a1d[low_values_indices] = 0 # All low values set to 0 pyplot.plot(x_axis, a1d * ximage.max()) #pyplot.plot(x_axis, ximage * a1d, 'o', markersize=10) pyplot.plot(x_axis, ximage) pyplot.plot(x_axis_fit, fit_1d) pyplot.tight_layout() pyplot.show()
def plot_pot(): x, y = np.meshgrid(np.arange(-2, 2, .1), np.arange(-2, 2, .1)) pot = SimpleTSPot() energies = [pot.getEnergy(np.array([xi, yi])) for xi, yi in izip(x.reshape(-1), y.reshape(-1))] energies = np.array(energies).reshape(x.shape) plt.contourf(x, y, energies) plt.show()
def main(argv): # Load Station Data conn = sqlite3.connect(_BABS_DATABASE_PATH) station_data = pd.read_sql(_BABS_QUERY, conn) station_data['Usage'] = 0.5*(station_data['Start Count'] + station_data['End Count']) print("\n\nLoading model to file ... ") with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir, 'models', 'babs_usage_model.dill'), 'r') as f: babs_usage_model = dill.load(f) # Interpolate all features from feature models lats, longs = np.meshgrid(np.linspace(37.7,37.82,30), np.linspace(-122.55,-122.35,30)) transformed_features = babs_usage_model.named_steps['features_from_lat_long'].transform(pd.DataFrame({'Latitude': lats.reshape(1,-1).squeeze(), 'Longitude': longs.reshape(1,-1).squeeze()})) prediction_features = pd.DataFrame({'Latitude': lats.reshape(1,-1).squeeze(), 'Longitude': longs.reshape(1,-1).squeeze()}) usage_predictions = babs_usage_model.predict(prediction_features) usage_predictions[np.array(transformed_features['Elevation']<0)] = np.nan usage_predictions = np.lib.scimath.logn(100, usage_predictions - np.nanmin(usage_predictions) + 1) usage_predictions[np.where(np.isnan(usage_predictions))] = 0 plt.contourf(longs, lats, usage_predictions.reshape(30,-1), norm=colors.Normalize(np.mean(usage_predictions)-(1*np.std(usage_predictions)), np.mean(usage_predictions)+(1*np.std(usage_predictions)), clip=True), levels=np.linspace(0.01,max(usage_predictions),300)) plt.contour(longs, lats, (transformed_features['Elevation']).reshape(30,-1), linewidth=0.2, colors='white') plt.scatter(station_data[station_data['Landmark']=='San Francisco']['Longitude'], station_data[station_data['Landmark']=='San Francisco']['Latitude'], s=2, ) # plt.scatter(longs, # lats, # #s=(usage_predictions<0)*10, # s=(transformed_features['Elevation']>0)*10, # cmap=matplotlib.cm.Reds) plt.show()
def example2(): """散点栅格情况下的画法 x, y = (1,7), (4,9), (11,2),... 这种没有规律的散点x,y坐标,我们称其为散点栅格 """ dx, dy = 0.05, 0.05 x = np.array([[1, 2], [1, 3]]) y = np.array([[3, 3], [1, 1]]) z = np.array([[5, 10],[15, 20]]) levels = MaxNLocator(nbins=4).tick_values(z.min(), z.max()) cmap = plt.get_cmap('PiYG') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) plt.subplot(2, 1, 1) im = plt.pcolormesh(x, y, z, cmap=cmap, norm=norm) plt.colorbar() plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.title('pcolormesh with levels') plt.subplot(2, 1, 2) plt.contourf(x + dx / 2., y + dy / 2., z, levels=levels, cmap=cmap) plt.colorbar() plt.title('contourf with levels') plt.show()
def draw_graph(X, y, svc_linear, svc_poly2, svc_poly3, svc_rbf, h = 0.2): draw_init() x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) titles = ['SVC with linear kernel', 'SVC with polynomial degree 2 kernel', 'SVC with polynomial degree 3 kernel', 'SVC with RBF kernel'] colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk']) colors = np.hstack([colors] * 20) for i, clf in enumerate((svc_linear, svc_poly2, svc_poly3, svc_rbf)): plt.subplot(2, 2, i + 1) plt.subplots_adjust(wspace=0.4, hspace=0.4) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], color=colors[y.tolist()].tolist()) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title(titles[i]) print(show_graph())
def contour_plot(X,Y,model): h = 1 # step size in the mesh # create a mesh to plot in gr = [] fl_gr = [] for i in range(0, model.steps[1][1].n_components): gr.append( (X[:, i].min() - 1, X[:, i].max() + 1) ) fl_gr.append(np.arange(X[:, i].min() - 1, X[:, i].max() + 1, h)) #x_min, x_max = X_scaled[:, 0].min() - 1, X_scaled[:, 0].max() + 1 #y_min, y_max = X_scaled[:, 1].min() - 1, X_scaled[:, 1].max() + 1 #print y_min, y_max ms = np.meshgrid(fl_gr[0],fl_gr[1],fl_gr[2],fl_gr[3],fl_gr[4]) rr =[r.ravel() for r in ms] #print len(rr) r =np.transpose(rr) #print r.shape #print xx.shape, '\n',np.c_[xx.ravel(), yy.ravel()] Z =model.steps[2][1].predict(r) #ms = np.meshgrid(fl_gr[0],fl_gr[1]) xx = ms[0] yy = ms[1] print xx.shape print X.shape # Put the result into a color plot Z = Z.reshape(xx.shape) print xx.shape print X.shape pl.contourf(xx[:,:,0,0,0], yy[:,:,0,0,0], Z[:,:,0,0,0], cmap=pl.cm.hsv) #pl.contourf(xx, yy, Z, cmap=pl.cm.hsv) pl.axis('off') # Plot also the training points pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.hsv,s = 100) pl.show()
def example1(): """标准栅格情况下的画法 当 x = [1,2,3,4], y = [1,2,3,4], 也就是一共是16个点,x和y相互对应的时候。这就叫标准栅格。 """ dx, dy = 0.01, 0.01 x = np.arange(0.0, 10.0, 0.05) y = np.arange(0.0, 5.0, 0.05) x, y = np.meshgrid(x, y) z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x) levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) cmap = plt.get_cmap('PiYG') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) plt.subplot(2, 1, 1) im = plt.pcolormesh(x, y, z, cmap=cmap, norm=norm) plt.colorbar() plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.title('pcolormesh with levels') plt.subplot(2, 1, 2) plt.contourf(x + dx / 2., y + dy / 2., z, levels=levels, cmap=cmap) plt.colorbar() plt.title('contourf with levels') plt.show()
def plot2DInRealCrd( u, transverseProfile, stat ): R = stat["outerRadius"] v = np.linspace(0.0, 5E5, 1001) U, V = np.meshgrid(u,v) A = damping(U, V, stat["wavenumber"], stat["width"], stat["solver"]["eigenvalue"], R) energy = np.zeros(U.shape) for i in range(0, U.shape[1]): if (( U[0,i] > 0.0 ) or ( U[0,i] < -stat["width"])): energy[:,i] = transverseProfile[i]*A[:,i] else: energy[:,i] = transverseProfile[i] plt.contourf(U,V/1000.0, energy, 100, cmap="gist_heat", norm=mpl.colors.LogNorm()) plt.xlabel("$u$ (nm)") plt.ylabel("$v \; (\mathrm{\mu m})$") fname = "Figures/profile2D_uvplane.jpeg" plt.savefig(fname, bbox_inches="tight", dpi=800) print ("Figure written to %s"%(fname)) plt.clf() XYcompl = R*np.exp((U+1j*V)/R) transverse = XYcompl.real longitudinal = XYcompl.imag plt.contourf(longitudinal/1000.0,transverse,energy, 100, cmap="gist_heat", norm=mpl.colors.LogNorm()) plt.gca().set_axis_bgcolor("#3E0000") plt.xlabel("$z \; (\mathrm{\mu m}$)") plt.ylabel("$x$ (nm)") fname = "Figures/profile2D_xyplane.jpeg" plt.savefig(fname, bbox_inches="tight", dpi=800) print ("Figure written to %s"%(fname)) return longitudinal, transverse, energy
def plot_decision_regions( X, y, classifier, xlab="X", ylab="y", legend_loc="upper left", test_idx=None, resolution=0.02 ): # setup marker generator and color map markers = ("s", "x", "o", "^", "v") colors = ("red", "blue", "lightgreen", "gray", "cyan") cmap = ListedColormap(colors[: len(np.unique(y))]) x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) X_test, y_test = X[test_idx, :], y[test_idx] # plot class samples for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c="", alpha=1.0, linewidth=1, marker="o", s=55, label="test set") plt.xlabel(xlab) plt.ylabel(ylab) plt.legend(loc=legend_loc)
def plot_vert_vgradrho_rho_diff(show=True, save=False): plt.close('all') plt.figure() rho1 = np.array(g1a['Rho']) vgradrho1 = \ g1a['V!Dn!N (up)']\ *cr.calc_rusanov_alts_ausm(g1a['Altitude'],rho1)/g1a['Rho'] rho2 = np.array(g2a['Rho']) vgradrho2 = \ g2a['V!Dn!N (up)']\ *cr.calc_rusanov_alts_ausm(g2a['Altitude'],rho2)/g2a['Rho'] ilt = np.argmin(np.abs(g1a['LT'][2:-2, 0, 0]-whichlt))+2 vgradrho1 = vgradrho1[ilt,2:-2,2:-2] vgradrho2 = vgradrho2[ilt,2:-2,2:-2] dvgradrho = np.array(vgradrho1-vgradrho2).T lat = np.array(g1a['dLat'][ilt, 2:-2, 2:-2]).T alt = np.array(g1a['Altitude'][ilt, 2:-2, 2:-2]/1000).T plt.contourf(lat, alt, dvgradrho, levels=np.linspace(-1, 1, 21)*1e-4, cmap='seismic', extend='both') plt.xlim(-90, -40) plt.xlabel('Latitude') plt.ylabel('Altitude') plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15, horizontalalignment='center', transform=plt.gcf().transFigure) if show: plt.show() if save: plt.savefig(spath+'06_vert_vgradrho_rho_diff_%s.pdf' % tstring) return
def plot_ICON_clt(ICON_data_dict): "This function gets ICON data and plots corresponding satellite pictures." # Import and create basemap for plotting countries and coastlines from mpl_toolkits.basemap import Basemap # Create well formatted time_string time_string = datetime.fromtimestamp(int(unix_time_in)).strftime('%Y-%m-%d-%H-%M') # Plotting temperature data plt.figure() # Plot contourf plot with lat/lon regridded ICON data cmap_cloud = plt.cm.gray levels_cloud = np.arange(0,101,10) plt.contourf(ICON_data_dict["ICON_X_mesh"], ICON_data_dict["ICON_Y_mesh"], ICON_data_dict["ICON_clt"], levels=levels_cloud, cmap=cmap_cloud) plt.colorbar() # Plot map data map = Basemap(llcrnrlon=4.0,llcrnrlat=47.0,urcrnrlon=15.0,urcrnrlat=55.0, resolution='i') map.drawcoastlines() map.drawcountries() lat_ticks = [55.0,53.0,51.0,49.0,47.0] map.drawparallels(lat_ticks, labels=[1,0,0,0], linewidth=0.0) lon_ticks = [4.0,6.0,8.0,10.0,12.0,14.0] map.drawmeridians(lon_ticks, labels=[0,0,0,1], linewidth=0.0) # Save plot and show it plt.savefig(output_path + 'TotalCloudCover_' + time_string + '.png')
def plot_vert_divv_diff(show=True, save=False): plt.close('all') plt.figure() velr = np.array(g1a['V!Dn!N (up)']) divv1 = cr.calc_div_vert(g1a['Altitude'], velr) velr = np.array(g2a['V!Dn!N (up)']) divv2 = cr.calc_div_vert(g2a['Altitude'], velr) ilt = np.argmin(np.abs(g1a['LT'][2:-2, 0, 0]-whichlt))+2 divv1 = divv1[ilt,2:-2,2:-2] divv2 = divv2[ilt,2:-2,2:-2] ddivv = np.array(divv1-divv2).T lat = np.array(g1a['dLat'][ilt, 2:-2, 2:-2]).T alt = np.array(g1a['Altitude'][ilt, 2:-2, 2:-2]/1000).T plt.contourf(lat, alt, ddivv, levels=np.linspace(-1, 1, 21)*1e-4, cmap='seismic', extend='both') plt.xlim(-90, -40) plt.xlabel('Latitude') plt.ylabel('Altitude') plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15, horizontalalignment='center', transform=plt.gcf().transFigure) if show: plt.show() if save: plt.savefig(spath+'04_vert_divv_diff%s.pdf' % tstring) return
def plot(self): bounds = self.bounds x1 = np.linspace(bounds[0][0], bounds[0][1], 100) x2 = np.linspace(bounds[1][0], bounds[1][1], 100) X1, X2 = np.meshgrid(x1, x2) X = np.hstack((X1.reshape(100*100,1),X2.reshape(100*100,1))) Y = self.f(X) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(X1, X2, Y.reshape((100,100)), rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) ax.set_title(self.name) plt.figure() size_color = np.linspace(-1.5, 6.0, 100, endpoint=True) plt.contourf(X1, X2, Y.reshape((100,100)),size_color) if (len(self.min)>1): plt.plot(np.array(self.min)[:,0], np.array(self.min)[:,1], 'w.', markersize=20, label=u'Observations') else: plt.plot(self.min[0][0], self.min[0][1], 'w.', markersize=20, label=u'Observations') plt.colorbar() plt.xlabel('X1') plt.ylabel('X2') plt.title(self.name) # plt.show() savefig("object_true_2d.pdf")
def plot_kde(opts, kde_data, centre = None): plt.figure() plt.contourf(kde_data[0], kde_data[1], kde_data[2], 30) if centre: plt.plot(np.ones(2) * centre[0], (plt.ylim()), 'w:', label = 'KDE Centre') plt.plot((plt.xlim()), np.ones(2) * centre[1], 'w:') if opts.H0 == 100.0: plt.xlabel(r'X [Mpc h$^{-1}$]') plt.ylabel(r'Y [Mpc h$^{-1}$]') else: plt.xlabel('X [Mpc]') plt.ylabel('Y [Mpc]') plt.legend() plt.colorbar() output_file = opts.input_file + '.kde.pdf' plt.savefig(output_file) print ' KDE plot saved to:', output_file plt.close()
def plot2D_decision_boundary(self, h=.1, markers=['*', 'v', 'o', '+', '-', '.', ',']): X, y = self.__check_data_available() _, n_col = X.shape if n_col > 2: raise Exception("Not implemented for n-dimension yet.") import matplotlib.pyplot as plt x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = np.array([]) clazz_by_index = dict((clazz, idx) for idx, clazz in enumerate(self._clazz, 1)) NO_CLASS_COMPARABLE = -1 for query in np.c_[xx.ravel(), yy.ravel()]: answer, _ = self.evaluate(query) if len(answer) > 1 or len(answer) == 0: z = np.append(z, NO_CLASS_COMPARABLE) else: z = np.append(z, clazz_by_index[answer[0]]) y_colors = [clazz_by_index[clazz] for clazz in y] markers = dict((self._clazz[idx], markers[idx]) for idx in range(0, self._nb_clazz)) z = z.reshape(xx.shape) plt.contourf(xx, yy, z, alpha=0.4) for row in range(0, len(y)): plt.scatter(X[row, 0], X[row, 1], c=y_colors[row], s=40, marker= markers[y[row]], edgecolor='k') plt.show()
def plot_decision_regions(X, y, classifier, resolution=0.02): # マーカーとカラーマップの準備 markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # 決定領域のプロット x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # グリッドポイントの生成 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) # 各特徴量を1次元配列に変換して予測を実行 Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) # 予測結果を元のグリッドポイントのデータサイズに変換 Z = Z.reshape(xx1.shape) # グリッドポイントの等高線プロット plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) # 軸の範囲設定 plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # クラスごとにサンプルをプロット for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)
def three_d_contour(file,show): xloc = raw_input("xlocation(two_d_initial_x_value.txt):") or "two_d_initial_x_value.txt" yloc = raw_input("ylocation(two_d_initial_y_value.txt):") or "two_d_initial_y_value.txt" uloc = raw_input("ulocation(two_d_cavity_u_results.txt):") or "two_d_cavity_u_results.txt" vloc = raw_input("vlocation(two_d_cavity_v_results.txt):") or "two_d_cavity_v_results.txt" ploc = raw_input("plocation(two_d_cavity_p_results.txt):") or "two_d_cavity_p_results.txt" u=np.loadtxt(uloc) v=np.loadtxt(vloc) p=np.loadtxt(ploc) X=np.loadtxt(xloc) Y=np.loadtxt(yloc) X,Y=np.meshgrid(X,Y) # print X,Y fig = plt.figure() plt.contourf(X,Y,p,alpha=0.5) ###plnttong the pressure field as a contour plt.colorbar() plt.contour(X,Y,p) ###plotting the pressure field outlines plt.quiver(X[::3,::3],Y[::3,::3],u[::3,::3],v[::3,::3]) ##plotting velocity plt.xlabel('X') plt.ylabel('Y') plt.title(file) sep = '.' filename = file.split(sep, 1)[0] plt.savefig(filename+'.png') # save figure as .png file if show: # print('test') plt.show() plt.close(fig)
#surface_geopotential swe1=Netcdf(file1).slice("liquid_water_content_of_surface_snow",members=[0],times=[3]) swe1=np.reshape(swe1,(swe1.shape[0],swe1.shape[1])) swe2=Netcdf(file2).slice("liquid_water_content_of_surface_snow",members=[0],times=[0]) swe2=np.reshape(swe2,(swe2.shape[0],swe2.shape[1])) swe=np.subtract(swe2,swe1) lons=np.reshape(Netcdf(file1).slice("longitude"),(swe.shape[0],swe.shape[1])) lats=np.reshape(Netcdf(file1).slice("latitude"),(swe.shape[0],swe.shape[1])) #proj = ccrs.LambertConformal(central_longitude=15., central_latitude=63., standard_parallels=[63.]) proj=ccrs.Miller() ax = plt.axes(projection=proj) ax.set_global() ax.coastlines(resolution="10m") ax.set_extent([lons.min(),lons.max(),lats.min(),lats.max()],ccrs.PlateCarree()) print(lons.shape) print(lats.shape) print(swe.shape) print(swe) #plt.imshow(swe, origin="lower",transform=proj, interpolation="bilinear", cmap="Accent") plt.contourf(lons,lats,swe,transform=ccrs.PlateCarree(), levels=[-500,-50,-20,-10,-5,0,5,10,20,50,500],cmap="Accent") #,extent=(lons.min(),lons.max(),lats.min(),lats.max())) plt.colorbar() plt.show()
psidp = file_rad.variables['Psidp'][:] rhohv = file_rad.variables['Rhohv'][:] # You should replace your masking values with nans in order for the code to work psidp[psidp == -99900.0] = np.nan rhohv[rhohv == -99900.0] = np.nan dr = (ranges[1] - ranges[0]) / 1000. # convert to km # Filter psidp before running the Kdp estimation methods psidp_filt = filter_psidp(psidp, rhohv) # Vulpiani method kdp_vulp, phidp_rec_vulp = estimate_kdp_vulpiani(psidp_filt, dr) kdp_levs = np.arange(-1, 15, 0.2) plt.figure() plt.contourf(angles, ranges, kdp_vulp, levels=kdp_levs) plt.title('Vulpiani method') plt.xlabel(r'Angle $^{\circ}$') plt.ylabel('Range [m]') # Kalman method kdp_kalm, kdp_std_kalm, phidp_rec_kalm = estimate_kdp_kalman(psidp_filt, dr) plt.figure() plt.contourf(angles, ranges, kdp_kalm, levels=kdp_levs) plt.title('Kalman method') plt.xlabel(r'Angle $^{\circ}$') plt.ylabel('Range [m]')
y_min, y_max = x_vals[:, 1].min() - 1, x_vals[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) # Translates slice objects to concatenation along the second axis. # 将所有数据都转换到矩阵的第二维中。数值默认为一个2维的矩阵数据 # np.c_[np.array([[[1,2,3]]]), 0, 0, np.array([[4,5,6]])] --> [[1,2,3,0,0,4,5,6] # 将所有同维的矩阵合并到同维的一个矩阵中。 # np.c_[np.array([[[1,2,3]]]), np.array([[[4,5,6]]])] --> [[[1,2,3,4,5,6]]] grid_points = np.c_[xx.ravel(), yy.ravel()] grid_predictions = sess.run( prediction, feed_dict = { x_data: rand_x, y_target: rand_y, prediction_grid: grid_points }).reshape(xx.shape) # Plot points and grid plt.figure() plt.contourf(xx, yy, grid_predictions, cmap = plt.cm.Paired, alpha = 0.8) plt.plot(class1_x, class1_y, 'ro', label = "Class 1") plt.plot(class2_x, class2_y, 'bx', label = "Class -1") plt.title("图4-8:使用非线性的高斯核函数 SVM 在非线性可分的数据集上进行分割") plt.xlabel('x') plt.ylabel('y') plt.legend(loc = "lower right") plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) # Plot batch accuracy plt.figure() plt.plot(batch_accuracy, 'b-', label = 'Accuracy') plt.title("批处理的精确度") plt.xlabel("迭代次数") plt.ylabel("精确度")
# we are using everything we have done before ### Asymptotic behavior #Qsource = np.zeros((n_y, n_x)) #A, b = build_2D_matrix(bc_dict, the_prob, D_matrix, Qsource,K,y_p) #head_array = np.linalg.solve(A, b) #n = n_x * n_y #print(head_array) # array v contains the solution # we convert it in a matrix: #c = vec2mat(head_array, n_y, n_x) # and we plot the matrix plt.contourf(x1, y1, head_2D, 20, cmap=cm) plt.colorbar() # %% print(y1) # %% # %% [markdown] # This solves the problem using the fast sparse solver spsolve (use this one!) # %% {"scrolled": true} # Here we give you the asymptotic solution to the problem # we are using everything we have done before ### Asymptotic behavior
#cound speed cs=np.sqrt(data['prs']/data['rho']) # Mach Number M=vp/cs # Alfvenic Mach Number Ma=vp/va # Plasma beta betap=2*data['prs']/(data['Bx1']**2+data['Bx2']**2) V=1.5 plt.figure(figsize=(10,12)) plt.contourf(x,y,np.log10(M.T),64,cmap='RdBu_r',vmin=-V,vmax=V) plt.colorbar() plt.streamplot(x,y,data['vR'].T,data['vZ'].T,color='k',density=3) plt.xlabel('R') plt.ylabel('Z') plt.title('V (color in Mach)') plt.axis([x[0], x[-1],y[0],y[-1]]) plt.figure(figsize=(10,12)) plt.contourf(x,y,np.log10(data['rho']).T,64,cmap='gnuplot') plt.colorbar() plt.streamplot(x,y,data['BR'].T,data['BZ'].T,color='w',density=2) plt.xlabel('R') plt.ylabel('Z') plt.title(r'B (color in $\log(\rho)$)')
# Calculating Prediction y_pred = MLPClassifierModel.predict(X_test) y_pred_prob = MLPClassifierModel.predict_proba(X_test) print('Prediction Probabilities Value for MLPClassifierModel is : ', y_pred_prob[:5]) print('Pred Value for MLPClassifierModel is : ', y_pred[:5]) print('True Value for MLPClassifierModel is : ', y_test[:5]) print("=" * 10) # --------------------- from sklearn.metrics import confusion_matrix, classification_report CM = confusion_matrix(y_test, y_pred) ClassificationReport = classification_report(y_test, y_pred) print(ClassificationReport) plt.figure() sns.heatmap(CM, center=True, annot=True, fmt="d") plt.show(block=False) print("=" * 25) # ---------------------------------------------------- x_axis = np.arange(0 - 0.1, 1 + 0.1, 0.001) xx0, xx1 = np.meshgrid(x_axis, x_axis) Z = MLPClassifierModel.predict(np.c_[xx0.ravel(), xx1.ravel()]).reshape(xx0.shape) plt.figure() sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, alpha=1) plt.contourf(xx0, xx1, Z, alpha=0.2, cmap=plt.cm.Paired) plt.show(block=True)
def variable_sweep(problem): from matplotlib import rcParams rcParams['font.family'] = 'times new roman' # rcParams['font.times-new-roman'] = ['times new roman'] number_of_points = 5 outputs = carpet_plot(problem, number_of_points, 0, 0) #run carpet plot, suppressing default plots inputs = outputs.inputs objective = outputs.objective constraints = outputs.constraint_val plt.figure(0) CS = plt.contourf(inputs[0,:],inputs[1,:], objective, 20, linewidths=2) cbar = plt.colorbar(CS) cbar.ax.set_ylabel('Fuel Burn (kg)') CS_const = plt.contour(inputs[0,:],inputs[1,:], constraints[-1,:,:],cmap=plt.get_cmap('hot')) plt.clabel(CS_const, inline=1, fontsize=12, family='times new roman') cbar = plt.colorbar(CS_const) # plt.FontProperties(family='times new roman', style='italic', size=12) cbar.ax.set_ylabel('BOW (kg)') # font = matplotlib.font_manager.FontProperties(family='times new roman', style='italic', size=12) # CS_const.font_manager.FontProperties.set_family(family='times new roman') plt.xlabel('Wing Area (m^2)') plt.ylabel('Aspect Ratio (-)') plt.legend(loc='upper left') # plt.show(block=True) plt.show() number_of_points = 5 outputs = carpet_plot(problem, number_of_points, 0, 0, sweep_index_0=1, sweep_index_1=3) # run carpet plot, suppressing default plots inputs = outputs.inputs objective = outputs.objective constraints = outputs.constraint_val plt.figure(0) CS = plt.contourf(inputs[0, :], inputs[1, :], objective, 20, linewidths=2) cbar = plt.colorbar(CS) cbar.ax.set_ylabel('Fuel Burn (kg)') CS_const = plt.contour(inputs[0, :], inputs[1, :], constraints[-1, :, :], cmap=plt.get_cmap('hot')) plt.clabel(CS_const, inline=1, fontsize=10) cbar = plt.colorbar(CS_const) cbar.ax.set_ylabel('BOW (kg)') plt.xlabel('AR (-)') plt.ylabel('Sweep Angle (Deg)') plt.legend(loc='upper left') plt.show() number_of_points = 5 outputs = carpet_plot(problem, number_of_points, 0, 0, sweep_index_0=2, sweep_index_1=3) # run carpet plot, suppressing default plots inputs = outputs.inputs objective = outputs.objective constraints = outputs.constraint_val plt.figure(0) CS = plt.contourf(inputs[0, :], inputs[1, :], objective, 20, linewidths=2) cbar = plt.colorbar(CS) cbar.ax.set_ylabel('Fuel Burn (kg)') CS_const = plt.contour(inputs[0, :], inputs[1, :], constraints[-1, :, :], cmap=plt.get_cmap('hot')) plt.clabel(CS_const, inline=1, fontsize=10) cbar = plt.colorbar(CS_const) cbar.ax.set_ylabel('BOW (kg)') plt.xlabel('t/c (-)') plt.ylabel('Sweep Angle (Deg)') plt.legend(loc='upper left') plt.show(block=True) return
p.sort() p.reverse() for p2 in p: if float(p2[0]) <= 1.: xs += [float(x)] zs += [float(z)] ts += [float(p2[1]["load"])] break xi = np.linspace(xmin - offset, xmax + offset, 2000) zi = np.linspace(zmin - offset, zmax + offset, 2000) ti = griddata(xs, zs, ts, xi, zi, interp='linear') ti.set_fill_value(0.0) CS = plt.contour(xi, zi, ti, [0, 3, 5, 10], linewidths=1, colors='k') CS = plt.contourf(xi, zi, ti, [0, 3, 5, 10], cmap=plt.cm.rainbow, vmax=abs(ti).max(), vmin=-abs(ti).max()) plt.colorbar() # draw colorbar plt.scatter(xs, zs, marker='o', c='b', s=5, zorder=10) plt.xlim(xmin, xmax) plt.ylim(zmin, zmax) npts = 3 plt.title('load curve (%d points)' % len(xs)) plt.show() # meh
plt.contour(E.R, E.Z, E.psiN[:], 300, colors='c', linewidths=0.5, alpha=0.5) plt.contour(E.R, E.Z, E.psiN[:], [1.0], colors='c', linewidths=2.0, alpha=0.75) plt.contourf(r_in.reshape(npsi_in, npol_in), z_in.reshape(npsi_in, npol_in), inv_in.reshape(npsi_in, npol_in), np.linspace(0, 2000, 400), cmap='afmhot') #plt.contour(E.R,E.Z,E.psiN[:],100,colors='w',linewidths=0.3,alpha=0.5) plt.xlim(r_in.min(), r_in.max()) plt.ylim(z_in.min(), z_in.max()) plt.gca().set_aspect('equal') plt.subplot(133) plt.imshow(gmat_in.dot(inv_in).reshape(nx, ny), cmap='gray') plt.savefig('images/29724_inner_' + str(i) + '.png', bbox_inches='tight') plt.clf() #plt.show()
# 学習結果のプロット plt.plot(np.arange(len(loss_list)), loss_list, label='train') plt.xlabel('epochs') plt.ylabel('loss') plt.show() # 境界領域のプロット h = 0.001 x_min, x_max = x[:, 0].min() - .1, x[:, 0].max() + .1 y_min, y_max = x[:, 1].min() - .1, x[:, 1].max() + .1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) X = np.c_[xx.ravel(), yy.ravel()] score = model.predict(X) predict_cls = np.argmax(score, axis=1) Z = predict_cls.reshape(xx.shape) plt.contourf(xx, yy, Z) plt.axis('off') # データ点のプロット x, t = spiral.load_data() N = 100 CLS_NUM = 3 markers = ['o', 'x', '^'] for i in range(CLS_NUM): plt.scatter(x[i * N:(i + 1) * N, 0], x[i * N:(i + 1) * N, 1], s=40, marker=markers[i]) plt.show()
def main(): # Problem 2 print("Problem 2") print("See figure 1,2,3") print() time_ss = [] time_ps = [] for iter in range(10): x = np.random.rand(100 + 100 * iter) y = np.random.rand(100 + 100 * iter) start_s = time() for i in range(10): f_s = fArray(x, y) end_s = time() time_s = end_s - start_s time_ss.append(time_s) start_p = time() for i in range(100): f_p = fArray2D(x, y) end_p = time() time_p = end_p - start_p time_ps.append(time_p) # print("serial", time_s) # print(f_s) # print("parallel", time_p) # print(f_p) acc = [] for i in range(10): acc.append(time_ss[i] / time_ps[i] * 10) array_sizes = [(100 + 100 * i) for i in range(10)] plt.figure(1) plt.plot(array_sizes, acc) plt.xlabel("Array size") plt.ylabel("Acceleration") plt.savefig("figure1") plt.figure(2) plt.plot(array_sizes, np.array(time_ss) * 10) plt.xlabel("Array size") plt.ylabel("Time(ms)") plt.title("Serial time") plt.savefig("figure2") plt.figure(3) plt.plot(array_sizes, np.array(time_ps)) plt.xlabel("Array size") plt.ylabel("Time(ms)") plt.title("Parallel time") plt.savefig("figure3") print() # Problem 3 print("Problem 3") print( "The largest square size is 32*32. In cuda, the largest number of threads in a block is 1024 (32*32=1024)." ) print( "The error message is: numba.cuda.cudadrv.driver.CudaAPIError: [1] Call to cuLaunchKernel results in CUDA_ERROR_INVALID_VALUE" ) print() # Problem 4 print("problem 4") print("a") # change these sizes to see difference TPBX = [4, 8, 16, 32, 4, 8] TPBY = [4, 8, 16, 32, 32, 16] time_4 = [] for i in range(6): x = np.random.rand(100) y = np.random.rand(100) start_p_4 = time() for i in range(100): fArray2D(x, y) end_p_4 = time() time_4.append(end_p_4 - start_p_4) print(time_4) print( "With a size 100 random initialized array, I tested block ratio of 4*4, 8*8, 32*32, 4*32, 8*16. The results are shown above: the execution times are similar. The aspect ratio won't affect much." ) print() print("b") TPBX = 16 TPBY = 16 x = np.random.rand(1000) y = np.random.rand(1000) time_4b_start = time() f, ker_time = fArray2D(x, y) time_4b_end = time() print("Outside time :", time_4b_end - time_4b_start) print("Kernel time: ", ker_time * 32) print( "With a size 100 random initialized array, I tested the exection time of wrapping around fArray2D() and around the kernel function." ) print( "They are very similar. Wrapping around the kernel is a little faster, due to data transfer operation." ) print() # Problem 5 print("Problem 5") print("Input plot see figure5") for k in range(1): N = 256 x = np.linspace(0, 1, 256) y = np.linspace(0, 1, 256) f = np.empty(256 * 256).reshape((256, 256)) for i in range(256): for j in range(256): f[i][j] = math.sin(2 * np.pi * x[i]) * math.sin( 2 * np.pi * y[j]) plt.figure() plt.contourf(x, y, f) plt.savefig("figure5") p = [2, 4, 6] for i in range(3): print("L", p[i], " norm = ", lp_norm(p[i])) print("Inf norm = ", inf_norm()) print("Yes, the norm are approching L inf norm when p increases.") print() # Problem 6 print("Problem 6") print("a") print( "It's impossible to parallel the computation over a grid of time intervals, due to the current step is depends on the previous one, the data in different grids couldn't communicate. " ) print() print("b") print( "Yes, there is a way to direct parallel over a grid of initial conditions. Send one pair of initial condition (x and v) to a thread. In the kernel function, do iteration with the given relation between x and v. Since the computation only depends on its own previous state, we can parallel over different ICs. " ) print() print("c") print("See figure6_c") print("Distance to the origin: ") state_c = ode_solver(ode_kernel_c) for item in state_c: print(pow(item[0]**2 + item[1]**2, 1 / 2)) plt.figure(figsize=(8, 8)) plt.plot(state_c[:, 0], state_c[:, 1]) plt.savefig("figure6_c") print() print("d") print("See figure6_d") print("Distance to the origin: ") state_d = ode_solver(ode_kernel_d) for item in state_d: print(pow(item[0]**2 + item[1]**2, 1 / 2)) plt.figure(figsize=(8, 8)) plt.plot(state_d[:, 0], state_d[:, 1]) plt.savefig("figure6_d") print() print("e") print("See figure6_e") print("Distance to the origin: ") state_e = ode_solver(ode_kernel_e) for item in state_e: print(pow(item[0]**2 + item[1]**2, 1 / 2)) plt.figure(figsize=(8, 8)) plt.plot(state_e[:, 0], state_e[:, 1]) plt.savefig("figure6_e") print() print("Disscussion:") print( "I select 20 points on the circle (r=3) in the phase diagram as ICs. Step size 0.001, totally 10000 steps. The distance between the final state and the origin" ) print( "The distance between the final state and the origin: c) a sightly larger than 3. This value should keep unchaged in this case; d), e) due to damping, the distance decrease. If it runs for more steps, it would go to 0." ) print( "Only in figure_6e, points from different ICs have different distance from the origin point. Because it follows a nonliner ODE." )
tstep = 3 # 4-th time frame # ------------------- # Extract the data # ------------------- fid = Dataset(romsfile) sst = fid.variables['temp'][tstep, -1, :, :] M = fid.variables['mask_rho'][:, :] fid.close() # -------------- # Data handling # -------------- # Mask out the SST data with NaN on land # to improve the contour plot sst[M < 1] = np.NaN # ------------- # Plot # ------------- # Contour plot with colorbar plt.contourf(sst) plt.colorbar() # Plot with correct aspect ratio plt.axis('image') plt.show()
kernel2 = best_fit_parameters_sig[ 2] * george.kernels.LocalGaussianKernel( location=best_fit_parameters_sig[4], log_width=best_fit_parameters_sig[3]) kernel = kernel1 + kernel2 gp = george.GP(kernel=kernel, solver=george.HODLRSolver, mean=np.median(toy)) gp.compute(mass, yerr=np.sqrt(toy)) Sigamp = np.sqrt(best_fit_parameters_sig[2]) Sigamperror = best_fit_parameters_sig_errors[2] print(Sigamp, '+/-', Sigamperror / (2 * Sigamp)) y_pred_sig, y_covar_sig = gp.predict(toy, mass, return_var=False) plt.contourf(mass, mass, y_covar) plt.colorbar() plt.show() #foobar #h_best_Amplitude[t] = best_fit_params[0] #h_best_lengthscale[t] = best_fit_params[1] #y_pred, y_var = gp.predict(toy,mass,return_var = True) chi2_ge[t] = np.sum((toy - y_pred)**2 / y_pred) h_chi2_ge[t] = chi2_ge[t] / (len(toy) - len(ge.get_parameter_vector())) print("George Chi2/ndf", h_chi2_ge[t]) #,"Ad-hoc Chi2/ndf",h_chi2_par) if t % 1000 == 0: print(t / 1000.)
def demo(self): import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier X = [[0, 0], [1, 1]] y = [0, 1] clf = DecisionTreeClassifier() clf.fit(X, y) print(clf.predict([[2, 2], [-1, -1], [0, 1]])) # Parameters n_classes = 3 plot_colors = 'ryb' plot_step = 0.02 # Load data iris = load_iris() for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]): # We only take the two corresponding features X = iris.data[:, pair] y = iris.target # Train clf = DecisionTreeClassifier() clf.fit(X, y) # Plot the decision boundary plt.subplot(2, 3, pairidx + 1) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)) plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu) plt.xlabel(iris.feature_names[pair[0]]) plt.ylabel(iris.feature_names[pair[1]]) # Plot the training points for i, color in zip(range(n_classes), plot_colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], cmap=plt.cm.RdYlBu, edgecolors='black', s=15) plt.suptitle( "Decision surface of a decision tree using paired features") plt.legend(loc='lower right', borderpad=0, handletextpad=0) plt.show() import graphviz from sklearn import tree iris = load_iris() clf = DecisionTreeClassifier() clf.fit(iris.data, iris.target) dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) from sklearn.tree import DecisionTreeRegressor # Create a random dataset X = np.sort(5 * np.random.rand(80, 1), axis=0) y = np.sin(X).ravel() # Add noise y[::5] += 3 * (0.5 - np.random.rand(16)) # Fit regression model regr_1 = DecisionTreeRegressor(max_depth=2) regr_2 = DecisionTreeRegressor(max_depth=5) regr_1.fit(X, y) regr_2.fit(X, y) # Predict X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis] y_1 = regr_1.predict(X_test) y_2 = regr_2.predict(X_test) # Plot the results plt.figure() plt.scatter(X, y, s=20, edgecolor='black', c='darkorange', label='data') plt.plot(X_test, y_1, color='cornflowerblue', label='max_depth=2', linewidth=2) plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2) plt.xlabel("data") plt.ylabel("target") plt.title("Decision Tree Regression") plt.legend() plt.show() import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor # Create a random dataset rng = np.random.RandomState(1) X = np.sort(200 * rng.rand(100, 1) - 100, axis=0) y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T y[::5, :] += (0.5 - rng.rand(20, 2)) # Fit regression model regr_1 = DecisionTreeRegressor(max_depth=2) regr_2 = DecisionTreeRegressor(max_depth=5) regr_3 = DecisionTreeRegressor(max_depth=8) regr_1.fit(X, y) regr_2.fit(X, y) regr_3.fit(X, y) # Predict X_test = np.arange(-100.0, 100.0, 0.01)[:, np.newaxis] y_1 = regr_1.predict(X_test) y_2 = regr_2.predict(X_test) y_3 = regr_3.predict(X_test) # Plot the results plt.figure() s = 25 plt.scatter(y[:, 0], y[:, 1], c="navy", s=s, edgecolor="black", label="data") plt.scatter(y_1[:, 0], y_1[:, 1], c="cornflowerblue", s=s, edgecolor="black", label="max_depth=2") plt.scatter(y_2[:, 0], y_2[:, 1], c="red", s=s, edgecolor="black", label="max_depth=5") plt.scatter(y_3[:, 0], y_3[:, 1], c="orange", s=s, edgecolor="black", label="max_depth=8") plt.xlim([-6, 6]) plt.ylim([-6, 6]) plt.xlabel("target 1") plt.ylabel("target 2") plt.title("Multi-output Decision Tree Regression") plt.legend(loc="best") plt.show()
np.arange(0.1,1+0.05,0.1))) plt.figure(figsize=(11,11)) plt.clf() ax1 = plt.subplot(2,2,1) proj = bm.Basemap(projection='merc', llcrnrlat=domain[0], llcrnrlon=domain[1], \ urcrnrlat=domain[2], urcrnrlon=domain[3], resolution='i') proj.fillcontinents(color=(0,0,0), lake_color=(0,0,0), ax=None, \ zorder=None, alpha=None) proj.drawparallels(range(domain_draw[0],domain_draw[2]+1,dlat), \ labels=[True,False,False,False], fontsize=14) proj.drawmeridians(range(domain_draw[1],domain_draw[3]+1,dlon), \ labels=[False,False,False,True], fontsize=14) lonproj, latproj = proj(llon_mdl, llat_mdl) plt.contourf(lonproj, latproj, corr_map_mode1, \ levels= lev, \ cmap=plt.cm.seismic) cb=plt.colorbar(ticks=lev,shrink=0.9) plt.title('Pearson Correlation map for EOF1', \ fontsize=16, y=1.04) ax2 = plt.subplot(2,2,2) proj = bm.Basemap(projection='merc', llcrnrlat=domain[0], llcrnrlon=domain[1], \ urcrnrlat=domain[2], urcrnrlon=domain[3], resolution='i') proj.fillcontinents(color=(0,0,0), lake_color=(0,0,0), ax=None, \ zorder=None, alpha=None) proj.drawparallels(range(domain_draw[0],domain_draw[2]+1,dlat), \ labels=[True,False,False,False], fontsize=14) proj.drawmeridians(range(domain_draw[1],domain_draw[3]+1,dlon), \ labels=[False,False,False,True], fontsize=14) lonproj, latproj = proj(llon_mdl, llat_mdl) plt.contourf(lonproj, latproj, corr_map_mode2, levels=lev, cmap=plt.cm.seismic)