def plot_cam_location(camera_list, n, fig=None, ax=None): FigSz = (8, 8) L = np.array([list(c.location[n]) for c in camera_list]) x = L[:, 0] y = L[:, 1] z = L[:, 2] if not fig: fig = plt.figure(figsize=FigSz) #view1 = np.array([-85., 60.]) if not ax: ax = Axes3D(fig) #, azim=view1[0], elev=view1[1]) Axes3D.scatter(ax, x, y, zs=z, color='k') zer = np.array Axes3D.scatter(ax, zer([0]), zer([0]), zs=zer([5]), color='r') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_ylim3d(-50, 50) ax.set_xlim3d(-50, 50) ax.set_zlim3d(0, 50) #if Flag['ShowPositions']: fig.show() #else: # fig.savefig(fName) return ax, fig
def onpick(event): # get event indices and x y z coord for click ind = event.ind[0]; x_e, y_e, z_e = event.artist._offsets3d; print x_e[ind], y_e[ind], z_e[ind]; seg_coord = [x_e[ind], y_e[ind], z_e[ind]]; seg_elecs.append(seg_coord); # refresh plot with red dots picked and blue dots clean #fig.clf(); seg_arr = np.array(seg_elecs); x_f = seg_arr[:,0]; y_f = seg_arr[:,1]; z_f = seg_arr[:,2]; plt.cla(); Axes3D.scatter3D(ax,x_f,y_f,z_f,s=150,c='r', picker=5); # get array of only clean elecs to re-plot as blue dots clean_list = list(coords); clean_list = [list(i) for i in clean_list]; for coordin in clean_list: if list(coordin) in seg_elecs: clean_list.pop(clean_list.index(coordin)); clean_coordis = np.array(clean_list); x_c = clean_coordis[:,0]; y_c = clean_coordis[:,1]; z_c = clean_coordis[:,2]; Axes3D.scatter3D(ax,x_c, y_c, z_c, s=150,c='b', picker=5); time.sleep(0.5); plt.draw();
def plotFiguresTemp(xSolid, ySolid, zSolid, xFFDDeform, yFFDDeform, zFFDDeform): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #fig = plt.figure() #ax = fig.gca(projection='3d') # Axes3D.plot_wireframe(ax, z, x, y) ax.set_xlabel('Z axis') ax.set_ylabel('X axis') ax.set_zlabel('Y axis') #ax.plot_trisurf(zSolid, xSolid, ySolid, cmap=cm.jet, linewidth=0.2) ax.plot_wireframe(zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="y") #Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b') Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r') # Axes3D.set_ylim(ax, [-0.5,4.5]) # Axes3D.set_xlim(ax, [-0.5,4.5]) Axes3D.set_zlim(ax, [-0.7, 0.7]) plt.show(block=True)
def plotData(tuplesArray): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = [] y = [] z = [] for point in tuplesArray: x.append(point[0]) y.append(point[1]) z.append(point[2]) if (FILEInQuestion == "newsbp.fuselageZ.dat"): Axes3D.scatter(ax, x,y,z, s=30, c ='b') Axes3D.set_zlim(ax, [0, 1000]) Axes3D.set_ylim(ax, [0, 3000]) Axes3D.set_xlim(ax, [0, 3000]) ax.set_xlabel('Z axis') ax.set_ylabel('X axis') ax.set_zlabel('Y axis') else: Axes3D.scatter(ax, z,x,y, s=30, c ='b') ax.set_xlabel('Z axis') ax.set_ylabel('X axis') ax.set_zlabel('Y axis') plt.show(block=True)
def plotData2files(tuplesArray1, tuplesArray2): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x1 = [] y1 = [] z1 = [] for point in tuplesArray1: x1.append(point[0]) y1.append(point[1]) z1.append(point[2]) x2 = [] y2 = [] z2 = [] for point in tuplesArray2: x2.append(point[0]) y2.append(point[1]) z2.append(point[2]) Axes3D.scatter(ax, x1,y1,z1, s=30, c ='b') Axes3D.scatter(ax, x2,y2,z2, s=30, c ='r') Axes3D.set_xlim(ax, [0, 2000]) Axes3D.set_ylim(ax, [0, 3000]) Axes3D.set_zlim(ax, [0, 1000]) plt.show(block=True)
def updatePlot(self, X, Y, Z, population=None): self.activePlot = (X,Y,Z) x, y = np.meshgrid(X,Y) if self.surface is not None: self.surface.remove() if self.scatter is not None: self.scatter.remove() # surface self.surface = Axes3D.plot_surface( self.axes, x, y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False, shade=False, alpha=0.5 ) # population if population is not None: self.activePopulation = population x, y, z = self.preparePopulationData(population) self.scatter = Axes3D.scatter(self.axes, x, y, z, c="r", marker="o") self.scatter.set_alpha(1.0) # Draw all self.canvas.draw() self.canvas.flush_events()
def volume_display(self, zstep = 3.00): """ This is a daring attempt for 3-D plots of all the blobs in the brain. Prerequisites: self.blobs_archive are established. The magnification of the microscope must be known. """ fig3 = plt.figure(figsize = (10,6)) ax_3d = fig3.add_subplot(111, projection = '3d') for n_frame in self.valid_frames: # below the coordinates of the cells are computed. blobs_list = self.c_list[n_frame] ys = blobs_list[:,0]*magni_lateral xs = blobs_list[:,1]*magni_lateral zs = np.ones(len(blobs_list))*n_frame*zstep ss = (np.sqrt(2)*blobs_list[:,2]*magni_lateral)**2*np.pi Axes3D.scatter(xs,ys, zs, zdir = 'z', s=ss, c='g') ax_3d.set_xlabel('x (micron)', fontsize = 12) ax_3d.set_xlabel('y (micron)', fontsize = 12) return fig3
def clust(elect_coords, n_clusts, iters, init_clusts): # Load resultant coordinates from Hough circles transform #coords = scipy.io.loadmat(elect_coords); #dat = coords.get('elect_coords'); dat = elect_coords; # Configure Kmeans cluster = sklearn.cluster.KMeans(); cluster.n_clusters= n_clusts; cluster.init = 'k-means++'; cluster.max_iter = iters; cluster.verbose = 0; cluster.n_init = init_clusts; cluster.fit(dat); # Grab vector for plotting each dimension x = list(cluster.cluster_centers_[:,0]); y = list(cluster.cluster_centers_[:,1]); z = list(cluster.cluster_centers_[:,2]); c = list(cluster.labels_); scipy.io.savemat('k_labels.mat', {'labels':cluster.labels_}) scipy.io.savemat('k_coords.mat', {'coords':cluster.cluster_centers_}) # plot the results of kmeans cmap = colors.Colormap('hot'); norm = colors.Normalize(vmin=1, vmax=10); s = 64; fig = plt.figure(); ax = fig.add_subplot(111,projection='3d'); Axes3D.scatter3D(ax,x,y,z,s=s); plt.show(fig); return cluster.cluster_centers_,cluster.labels_;
def plotFigures(xSolid,ySolid,zSolid,xFFDDeform,yFFDDeform,zFFDDeform, xsolidInitial, ysolidInitial, zsolidInitial, xFFDInitial, yFFDInitial, zFFDInitial): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Axes3D.plot_wireframe(ax, z, x, y) ax.set_xlabel('Z axis') ax.set_ylabel('X axis') ax.set_zlabel('Y axis') #Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b') Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b") Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r') #Axes3D.scatter(ax, zsolidInitial, xsolidInitial, ysolidInitial, s=10, c='y') Axes3D.plot_wireframe(ax, zsolidInitial, xsolidInitial, ysolidInitial,rstride = 1, cstride = 1, color="y") Axes3D.scatter(ax, zFFDInitial, xFFDInitial, yFFDInitial, s=30, c='g') xZCross = [] yZCross = [] zZCross = [] #plot the points for the limits of each cross section for zCrossSect in GLOBAL_zCrossSectionObjects: zCrossSectionObject = GLOBAL_zCrossSectionObjects[zCrossSect] #add to the arrays, for a fixed z, the following combinations # (xmax, ymax) (xmax, ymin) (xmin, ymin) (xmin, ymax) # (xmax, ymax) xZCross.append(zCrossSectionObject.getXMax()) yZCross.append(zCrossSectionObject.getYMax()) zZCross.append(zCrossSect) #(xmax, ymin) xZCross.append(zCrossSectionObject.getXMax()) yZCross.append(zCrossSectionObject.getYMin()) zZCross.append(zCrossSect) #(xmin, ymin) xZCross.append(zCrossSectionObject.getXMin()) yZCross.append(zCrossSectionObject.getYMin()) zZCross.append(zCrossSect) #(xmin, ymax) xZCross.append(zCrossSectionObject.getXMin()) yZCross.append(zCrossSectionObject.getYMax()) zZCross.append(zCrossSect) #Axes3D.plot_wireframe(ax, zZCross, xZCross, yZCross) #Axes3D.set_ylim(ax, [-0.5,4.5]) #Axes3D.set_xlim(ax, [-0.5,4.5]) Axes3D.set_zlim(ax, [-0.7, 0.7]) plt.show(block=True)
def elecDetect(CT_dir, T1_dir, img, thresh, frac, num_gridStrips, n_elects): # navigate to dir with CT img os.chdir(T1_dir) # Extract and apply CT brain mask mask_CTBrain(CT_dir, T1_dir, frac) masked_img = "masked_" + img # run CT_electhresh print "::: Thresholding CT at %f stdv :::" % (thresh) electhresh(masked_img, thresh) # run im_filt to gaussian smooth thresholded image fname = "thresh_" + masked_img print "::: Applying guassian smooth of 2.5mm to thresh-CT :::" img_filt(fname) # run hough transform to detect electrodes new_fname = "smoothed_" + fname print "::: Applying 2d Hough Transform to localize electrode clusts :::" elect_coords = CT_hough(CT_dir, new_fname) # set up x,y,z coords to view hough results x = elect_coords[:, 0] x = x.tolist() y = elect_coords[:, 1] y = y.tolist() z = elect_coords[:, 2] z = z.tolist() # plot the hough results s = 64 fig = plt.figure() ax = fig.add_subplot(111, projection="3d") Axes3D.scatter3D(ax, x, y, z, s=s) plt.show(fig) # run K means to find grid and strip clusters n_clusts = num_gridStrips # number of cluster to find = number of electrodes iters = 1000 init_clusts = n_clusts print "::: Performing K-means cluster to find %d grid-strip and noise clusters :::" % (n_clusts) [clust_coords, clust_labels] = clust(elect_coords, n_clusts, iters, init_clusts) # run K means to find electrode center coordinates n_clusts = n_elects # number of cluster to find = number of electrodes iters = 1000 init_clusts = n_clusts print "::: Performing K-means cluster to find %d electrode centers :::" % (n_clusts) [center_coords, labels] = clust(elect_coords, n_clusts, iters, init_clusts) print "::: Finished :::" return elect_coords, clust_coords, clust_labels
def draw(self, axes: Axes3D): R = (self.orientation * (self.orientation_origin.get_inverse())).to_rot_matrix() xx = R[0, 0] * self.x + R[0, 1] * self.y + R[0, 2] * self.z yy = R[1, 0] * self.x + R[1, 1] * self.y + R[1, 2] * self.z zz = R[2, 0] * self.x + R[2, 1] * self.y + R[2, 2] * self.z axes.plot_surface(xx, yy, zz, rstride=4, cstride=4, color='b') return axes,
def water(self, *argv): # Dimension is unit type as V(olt) W(att), etc # http://matplotlib.org/examples/mplot3d/polys3d_demo.html Axes3D.plot_surface(self.signalx, self.signaly, self.signalz) # till better funcion plt.xlabel('time [s]') # Or Sample number plt.ylabel('Frequency [Hz]') # Or Freq Bins number plt.zlabel('voltage [mV]') # auto add unit here plt.title(' ') # set title plt.grid(True) plt.show()
def __init__(self,*args,**kwargs): if (len(args) > 1) | kwargs.has_key('rect'): _Axes3D.__init__(self,*args,**kwargs) else: rect = (0.1,0.1,0.8,0.8) _Axes3D.__init__(self,*args,rect=rect,**kwargs) self.cross_section_clim_set = False self.pbaspect = np.array([1.0,1.0,1.0])
def addmpl(self, fig): self.fig = fig self.canvas = FigureCanvas(fig) self.mplvl.addWidget(self.canvas) self.canvas.draw() self.toolbar = NavigationToolbar(self.canvas, self.mplwindow, coordinates=True) self.mplvl.addWidget(self.toolbar) ax = fig.get_axes()[0] Axes3D.mouse_init(ax)
def addcurve( ax, path, endpoints, color ) : px = path[ :,0 ] py = path[ :,1 ] pz = path[ :,2 ] n = len(px) - 1 q = Axes3D.plot(ax, px, py, zs=pz, c=color, linewidth=2 ) px = endpoints[ :,0 ] py = endpoints[ :,1 ] pz = endpoints[ :,2 ] print px, py, pz q = Axes3D.scatter(ax, px,py, zs=pz, c=color, marker='o', s=60)
def main(): # initialize ros node rospy.init_node('compute_calibration') # get path to folder containing recorded data filesPath = rospy.get_param('~files_path') # load trajectories kinectTraj = np.loadtxt('%skinect_trajectory' % (filesPath), delimiter=',') baxterTraj = np.loadtxt('%sbaxter_trajectory' % (filesPath), delimiter=',') # compute absolute orientation kinectOut, rot, trans = absOrientation(kinectTraj,baxterTraj) # plot both point sets together fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # plot the data Axes3D.scatter(ax, kinectOut[:,0], kinectOut[:,1], kinectOut[:,2], s=20, c='r') Axes3D.scatter(ax, baxterTraj[:,0],baxterTraj[:,1], baxterTraj[:,2], s=20, c='b') # add labels and title ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') plt.title('Kinect-Baxter Calibration') plt.legend(['Kinect','Baxter']) plt.show() # get rotation matrix as quaternion and euler angles euler = tf.transformations.euler_from_matrix(rot) quat = tf.transformations.quaternion_from_euler(*euler) # save results to yaml file f = open('%skinect_calibration.yaml' % (filesPath), 'w') lines = ['trans: [', 'rot: [', 'rot_euler: ['] for elem in trans: lines[0] += str(elem) + ', ' lines[0] += ']\n' for elem in quat: lines[1] += str(elem) + ', ' lines[1] += ']\n' for elem in euler: lines[2] += str(elem) + ', ' lines[2] += ']\n' lines.append('parent: /base\n') lines.append('child: /kinect2_link\n') f.writelines(lines) f.close()
def Spect(self): #, dimension): # Dimension is unit type as V(olt) W(att), etc Axes3D.plot_surface(self.signalx, self.signaly, self.signalz) if self.signalx.shape == self.signaly.shape == self.signalz.shape: pass elif self.signalx.shape == (len(self.signalx), ) or self.signaly.shape == (len(self.signaly), ): # Check for 1D array both if self.signalx.shape == (len(self.signalx), ) and self.signaly.shape == (len(self.signaly), ): self.signalx, self.signaly = np.meshgrid(self.signalx, self.signaly) nx, mx = np.shape(self.signalx) nz, mz = np.shape(self.signalz) if nx == nz and mx == mz: pass elif nx == mz and mx == nz: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 elif self.signalx.shape == (len(self.signalx), ): pass elif self.signaly.shape == (len(self.signaly), ): pass if self.signalx.shape == self.signaly.shape != self.signalz.shape: nx, mx = np.shape(self.signalx) nz, mz = np.shape(self.signalz) if nx == nz and mx == mz: pass elif nx == mz and mx == nz: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 elif self.signalx.shape == self.signalz.shape != self.signaly.shape: nx, mx = np.shape(self.signalx) ny, my = np.shape(self.signalz) if nx == ny and mx == my: pass elif nx == my and mx == ny: self.signaly = np.rot90(self.signaly, 1) # find out if it has to be 1 or 3 elif self.signaly.shape == self.signalz.shape != self.signalx.shape: ny, my = np.shape(self.signaly) nx, mx = np.shape(self.signalx) if ny == nx and my == mx: pass elif ny == mx and my == nx: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 else: raise MeasError.DataError("No Valid data found in at least one of the axis") plt.xlabel('time [s]') # Or Sample number plt.ylabel('Frequency [Hz]') # Or Freq Bins number plt.zlabel('voltage [mV]') # auto add unit here plt.title(' ') # set title plt.grid(True) plt.show()
def plotPCA(proj3D, X_r, PCs, ligs, colors, csvPath, save_flag): """ Plot the PCA data on 2D plot """ # Main figure fig = plt.figure(figsize=(13, 12), dpi=100) if proj3D: ax = fig.add_subplot(111, projection="3d") for label, col, x, y, z in zip(ligs, colors, X_r[:, 0], X_r[:, 1], X_r[:, 2]): newCol = makeColor(col) Axes3D.scatter(ax, x, y, z, label=label, color=newCol, marker="o", lw=1, s=800) ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30) ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30) ax.set_zlabel("PC3 (" + '{0:g}'.format(PCs[2]) + " %)", fontsize=30) ax.tick_params(axis="both", which="major", labelsize=20) pngPath = csvPath.replace(".csv", "_3D.png") else: ax = fig.add_subplot(111) for label, col, x, y in zip(ligs, colors, X_r[:, 0], X_r[:, 1]): newCol = makeColor(col) ax.scatter(x, y, label=label, color=newCol, marker="o", lw=1, s=800) # ax.annotate(label, xy=(x, y - 0.05), fontsize=10, # ha='center', va='top') ax.set_xlabel("PC1 (" + '{0:g}'.format(PCs[0]) + " %)", fontsize=30) ax.set_ylabel("PC2 (" + '{0:g}'.format(PCs[1]) + " %)", fontsize=30) ax.tick_params(axis="both", which="major", labelsize=30) pngPath = csvPath.replace(".csv", "_2D.png") # figTitle = "PCA on " + csvPath + " (PC1=" + pcVals[0] + ", PC2=" + # pcVals[1] + ")" # ax.text(0.5, 1.04, figTitle, horizontalalignment="center", fontsize=30, # transform=ax.transAxes) # Legend figure fig_legend = plt.figure(figsize=(13, 12), dpi=100) plt.figlegend(*ax.get_legend_handles_labels(), scatterpoints=1, loc="center", fancybox=True, shadow=True, prop={"size": 30}) # Save figures if save flag was used if save_flag: print("\nSAVING figures\n") fig.savefig(pngPath, bbox_inches="tight") fig_legend.savefig(pngPath.replace(".png", "_legend.png")) # Otherwise show the plots else: print("\nSHOWING figures\n") plt.show()
def makeequator( ax ) : npts = 256 x = numpy.zeros( npts ) y = numpy.zeros( npts ) z = numpy.zeros( npts ) n = 0 for phi in numpy.arange( 0., 2*math.pi, 2*math.pi/npts ) : x[n] = math.cos(phi) y[n] = math.sin(phi) n = n+1 q = Axes3D.plot(ax, x, y, zs=z, c='gray' ) q = Axes3D.plot(ax, x, z, zs=y, c='gray' ) q = Axes3D.plot(ax, z, y, zs=x, c='gray' )
def __init__(self, parent): self.figure = Figure(tight_layout=True) self.canvas = FigureCanvas(self.figure) self.canvas.setContentsMargins(0,0,0,0) self.axes = self.figure.add_subplot(111, projection='3d') Axes3D.set_autoscale_on(self.axes, True) Axes3D.autoscale_view(self.axes) self.canvas.setParent(parent) self.activePlot = None self.activePopulation = None self.surface = None self.scatter = None
def custom_plot(self, additional): for k in additional: if(k == Simulation.DISCRETIZE): for i in range(self.examples.noutputs): for j in range(self.nbr_epoch): if(self.plots['discretize_div'][i][j] != 0): self.plots['discretize'][i][j] /= (self.plots['discretize_div'][i][j] * (self.nbDiscre ** self.nbDiscre)) colors = [(0.2, 0.8, 0.88), 'b', 'g', 'r', 'c', 'm', 'y', 'k', (0.8, 0.1, 0.8), (0., 0.2, 0.5)] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for j in range(self.examples.noutputs): ax.scatter([self.plots['discretize'][j][k] for k in self.plots['discretize_valid'][j]], [j] * len(self.plots['discretize_valid'][j]), self.plots['discretize_valid'][j], color=colors[j], marker='x') ax.set_xlabel('DISCRETIZED VALUE') ax.set_ylabel('SHAPE') ax.set_zlabel('EPOCH') path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime())) plt.savefig(path) plt.show() plt.title('Discretize hidden layer') plt.ylabel('DISCRETIZED VALUE') plt.xlabel("EPOCHS") for j in range(self.examples.noutputs): plt.plot(self.plots['discretize_valid'][j], [self.plots['discretize'][j][k] for k in self.plots['discretize_valid'][j]], '.', color=colors[j]) path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime())) try: plt.savefig(path) except ValueError: print('Cannot save discretize_cloud') try: plt.show() except ValueError: print('Cannot display discretize_cloud') elif(k == Simulation.PROTOTYPE): lplot = [[0. for _ in range(self.examples.ninputs)] for _ in range(self.examples.noutputs)] for network in self.networks: for i in range(len(self.examples.inputs)): network['FoN'].calc_output(self.examples.inputs[i]) network['SoN'].calc_output(network['FoN'].stateHiddenNeurons) im = index_max(self.examples.outputs[i]) for j in range(self.examples.ninputs): lplot[im][j] += network['SoN'].stateOutputNeurons[j] fig = plt.figure() plt.clf() for i in range(self.examples.noutputs): rpr.show_repr(lplot[i], self.width, fig, 250 + i, i) path = "/tmp/pyplot.%s.%s.png" % (sys.argv[0], time.strftime("%m-%d-%H-%M-%S", time.localtime())) plt.savefig(path) plt.show()
def main(): global rR global v #v = polynomial_surface2(rR) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') v=[ 345.01147843, -731.53883648, 701.43498064, -333.41157482, 61.69405675, 434.95848754, -734.92037163, 468.45066799, -108.66899203, 197.05683428, -229.38490931, 73.72852732, 38.62490216, -23.11704968, 2.79760705, 1112.02959271, -1850.90352232, 1243.44148281, -301.1366546, 1096.50133704, -1278.21349214, 419.17838208, 338.80540403, -201.95899053, 33.68403733, 1333.97626976, -1566.15905716, 552.3302448, 922.09578713, -558.92492054, 145.7445413, 705.90344671, -442.88105472, 259.89354682, 138.22604583] #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='b', ax=ax) v=[ 2.18930311, 0.24260729, 57.46589779, 3.38543536, -9.56889825, 34.36258001, -36.2221404, 4.86597348, 12.89329227, 21.10709896, -4.36372996, -5.89323474, 3.98227029, 0.9848254, 0.23593784, -36.46890674, -25.34400559, 81.86028261, 14.43120124, 44.89510312, -52.04801532, -9.90597384, 16.49023335, 2.29875215, 0.40597427, -55.46318028, -39.9563639, 26.95078929, 35.15384941, -18.2399162, 5.13417155, -31.78519693, -14.89522473, 10.38829065, -6.66988281] #ax=implicit.plot_implicit(fn4,bbox=(-1.5,0,-3.5,-1.5,-2,1),rc=200,ns=30,colors='r', ax=ax) #rR = tree_time.tree_time(rR,0.05) rR=array(rR) Axes3D.scatter(ax,rR[:,0],rR[:,1],rR[:,2]) Axes3D.scatter(ax,-0.87676517,-2.5211104,-0.76908632,color='green') plt.show()
def visualize( Z, solution=[]): Y = np.arange(0,YSIZE,1) X = np.arange(0,XSIZE,1) fig = plt.figure() ax = fig.gca(projection='3d') X, Y = np.meshgrid(X, Y) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) if 0 < len( solution) : # TODO plot line not implemented - which function again? Axes3D.plot(X, Y, solution) ax.set_zlim(0.0, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
def plot_3d(self, z_data, x_coverage, y_coverage, title=None, x_axis_label="X", y_axis_label="Y", z_axis_label="Z"): # 3D plotting is sort of a pain in the neck, and heavily dependent on data formatting. This routine assumes that you are # providing the z height data as a two dimensional array array, and that the overall X and Y spans are # given, so the routine can automatically compute arrays comprising the X and Y positions. If your data files contain the X and Y # positions explicitly, this routine AND the data file reader will require heavy modification to ensure that the data gets # passed and plotted correctly. # takes Z data as an X by Y array of z values, and computes the X and Y arrays based on the "coverage" provided and the size # of the Z array # \todo design a better way of handling x and y coordinates # these might be passed as strings by the config parser, so ensure that they are recast as integers # \todo use configobj validators to handle this casting x_coverage = int(x_coverage) y_coverage = int(y_coverage) z_data = npy.array(z_data) self.clear_figure() # set up some borders # these borders never go away, and screw up the other plots - leave them out until a better way is found to elegently fix them # self.fig.subplots_adjust(left=0.05) # self.fig.subplots_adjust(right=0.95) # self.fig.subplots_adjust(top=0.97) # self.fig.subplots_adjust(bottom = 0.03) axes = self.fig.add_subplot(111, projection="3d") # allow us to use the mouse to spin the 3d plot around Axes3D.mouse_init(axes) (x_data, y_data) = compute_3d_coordinates(z_data, x_coverage, y_coverage) axes.plot_wireframe(x_data, y_data, z_data) if title: axes.set_title(title) axes.set_xlabel(x_axis_label) axes.set_ylabel(y_axis_label) axes.set_zlabel(z_axis_label) axes.view_init(self.elev_3d, self.azim_3d) self.canvas.draw() self.current_plot_type = "3D"
def drawcylinder( ax ) : npts = 2048 xa = numpy.array( [-1, 1] ) ya = numpy.array( [0.,0.] ) za = numpy.array( [40.,40.] ) q = Axes3D.plot(ax, xa, za, zs=ya, c='gray' ) q = Axes3D.plot(ax, ya, za, zs=xa, c='gray' ) za = numpy.array( [-40.,-40.] ) q = Axes3D.plot(ax, xa, za, zs=ya, c='gray' ) q = Axes3D.plot(ax, ya, za, zs=xa, c='gray' ) xa = numpy.array( [0.,0.] ) za = numpy.array( [0.,0.] ) ya = numpy.array( [-40.,40.] ) q = Axes3D.plot(ax, xa, ya, zs=za, c='gray', linestyle='--' ) x = numpy.zeros( npts ) y = -30.*numpy.ones( npts ) z = numpy.zeros( npts ) xx = numpy.zeros( npts ) yy = numpy.zeros( npts ) zz = numpy.zeros( npts ) n = 0 for phi in numpy.arange( 0., 2*math.pi, 2*math.pi/npts ) : x[n] = math.cos(phi) z[n] = math.sin(phi) n = n+1 #q = Axes3D.plot(ax, x, y, zs=z, c='gray' ) y = 30.* numpy.ones( npts ) #q = Axes3D.plot(ax, x, y, zs=z, c='gray' ) n = 0 for phi in numpy.arange( -30., 30.0, (60./npts) ) : yy[n] = phi amp = math.cos(phi) zz[n] = amp * math.cos( .007 * (30.-phi) ) xx[n] = -1.* amp * math.sin( .007 * (30.-phi) ) #zz[n] = math.cos(phi) n = n+1 q = Axes3D.plot(ax, xx, yy, zs=zz, c='black' ) xxx = numpy.zeros( 2 ) yyy = 40.*numpy.ones( 2 ) zzz = numpy.zeros( 2 ) zzz[0] = -1. zzz[1] = 1. q = Axes3D.plot(ax, xxx, yyy, zs=zzz, c='black' ) xxxx = numpy.zeros( 2 ) yyyy = -40.*numpy.ones( 2 ) zzzz = numpy.zeros( 2 ) xxxx[0] = -1.* math.sin( .007 * (60.) ) zzzz[0] = math.cos( .007 * (60.) ) xxxx[1] = 1.* math.sin( .007 * (60.) ) zzzz[1] = -1.* math.cos( .007 * (60.) ) q = Axes3D.plot(ax, xxxx, yyyy, zs=zzzz, c='black' )
def vectorplot(Points_From,Points_To): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in range(len(Points_From)): # ax.plot([Points_From[i][0], Points_To[i][0]], [Points_From[i][1], Points_To[i][1]],zs=[Points_From[i][2], Points_To[i][2]]) a=Arrow3D([Points_From[i][0], Points_To[i][0]], [Points_From[i][1], Points_To[i][1]],[Points_From[i][2], Points_To[i][2]],mutation_scale=2000, lw=3, arrowstyle="-|>", color="r") ax.add_artist(a) plt.show() Axes3D.plot()
def updatePopulation(self, population): self.activePopulation = population x, y, z = self.preparePopulationData(population) if self.scatter is not None: self.scatter.remove() self.scatter = Axes3D.scatter(self.axes, x, y, z, c="r", marker="o") # self.surface.set_zorder(2) # self.scatter.set_zorder(100) self.scatter.set_alpha(1.0) self.canvas.draw() self.canvas.flush_events()
def plotElements(PhysicalElementMatrix): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Axes3D.plot_wireframe(ax, z, x, y) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') xVector = [] yVector = [] zVector = [] for i in range(CONST_DIMENSION_X): for j in range(CONST_DIMENSION_Y): for k in range(CONST_DIMENSION_Z): elementObject = PhysicalElementMatrix[i][j][k] for gridPointObject in elementObject.gridPointList: xVector.append(gridPointObject.getX()) yVector.append(gridPointObject.getY()) zVector.append(gridPointObject.getZ()) Axes3D.scatter(ax, xVector, yVector, zVector, s=30, c='r') #Axes3D.plot_wireframe(ax, zSolid, xSolid, ySolid, rstride = 1, cstride = 1, color="b") # create the lines around all the elements for i in range(CONST_DIMENSION_X): for j in range(CONST_DIMENSION_Y): for k in range(CONST_DIMENSION_Z): elementObject = PhysicalElementMatrix[i][j][k] ListXVectors,ListYVectors,ListZVectors = elementObject.getOuterLineVectors() for l in range(len(ListXVectors)): plt.plot(ListXVectors[l],ListYVectors[l], ListZVectors[l], c = 'b') Axes3D.set_ylim(ax, [-10,10]) Axes3D.set_xlim(ax, [-10,10]) Axes3D.set_zlim(ax, [-10, 10]) plt.show(block=True)
def plotElements(fig, ax, ElementsSbpData, ElementsFFDData, NumElements,c1,c2,\ c3,c4): for i in range(NumElements): xSolid = [] ySolid = [] zSolid = [] xFFD = [] yFFD = [] zFFD = [] #fill the Solid body points for SBPTuple in ElementsSbpData[i]: xSolid.append(SBPTuple[0][0]) ySolid.append(SBPTuple[0][1]) zSolid.append(SBPTuple[0][2]) for FFDTuple in ElementsFFDData[i]: xFFD.append(FFDTuple[1][0]) yFFD.append(FFDTuple[1][1]) zFFD.append(FFDTuple[1][2]) # element 1 is the fuselage whose x and z values were switched # to make z cross sections. So switch these back when plotting if(i == 0): #ax.plot_trisurf(zSolid, xSolid, ySolid, cmap=cm.jet, linewidth=0.2) Axes3D.scatter(ax, zSolid,xSolid, ySolid, s=20, c=c1) Axes3D.scatter(ax, zFFD, xFFD, yFFD, s=30, c= c2) #Axes3D.plot_wireframe(ax, zFFD, xFFD, yFFD) if(i == 1): #ax.plot_trisurf(xSolid, zSolid, ySolid, cmap=cm.jet, linewidth=0.2) Axes3D.scatter(ax, zSolid,xSolid, ySolid, s=20, c=c3) Axes3D.scatter(ax, zFFD, xFFD, yFFD, s=30, c= c4)
def plotFiguresTemp(xSolid, ySolid, zSolid, xFFDDeform, yFFDDeform, zFFDDeform): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Axes3D.plot_wireframe(ax, z, x, y) ax.set_xlabel('Z axis') ax.set_ylabel('X axis') ax.set_zlabel('Y axis') Axes3D.scatter(ax, zSolid, xSolid, ySolid, s=10, c='b') Axes3D.scatter(ax, zFFDDeform, xFFDDeform, yFFDDeform, s=30, c='r') # Axes3D.set_ylim(ax, [-0.5,4.5]) # Axes3D.set_xlim(ax, [-0.5,4.5]) Axes3D.set_zlim(ax, [-0.7, 0.7]) plt.show(block=True)
def train(net, x_train, x_test, y_train, y_test, lr, epoches): train_losses = [] test_losses = [] plt.ion() print_interval = int(epoches*0.2) for i in range(epoches): print('i=', i) # 为了得到更好的效果,适当改变学习率 if i%print_interval==0 and i!=0: lr=lr*0.8 print('-----------learning rate=',lr,'------------') for j in range(len(x_train)): net.back_propagation(x_train[j], y_train[j], lr) if i%print_interval==0: # 均方差 train_loss = np.mean(np.square(y_train - net.forward_propagation(x_train))) test_loss = np.mean(np.square(y_test - net.forward_propagation(x_test))) train_losses.append(train_loss) test_losses.append(test_loss) print('Epoch=', i, ', train_loss=', train_loss, ', test_loss=', test_loss) # 回想泛化实况 plt.figure(1) plt.cla() xx = np.linspace(1, len(test_losses), len(test_losses)) plt.title("generalization") plt.xlabel('epoches') plt.ylabel('test_loss') plt.plot(xx, test_losses) # plt.show() plt.figure(2) plt.cla() xx = np.linspace(1, len(train_losses), len(train_losses)) plt.title("recall") plt.xlabel('epoches') plt.ylabel('train_loss') plt.plot(xx, train_losses) # 二维空间函数拟合 if len(x_train[0])==1: plt.figure(3) plt.cla() plt.scatter(x_train, y_train, s=5) plt.scatter(x_train,net.forward_propagation(x_train),s=4 , color='red') plt.text(1.5,0.2,'train loss=%.6lf'%train_loss,fontdict={'size':15,'color':'red','style':'italic'}) plt.figure(4) plt.cla() plt.scatter(x_test, y_test, s=5) plt.scatter(x_test, net.forward_propagation(x_test), s=4, color='black') plt.text(plt.axis()[0]+0.1,plt.axis()[2]+0.1,'test loss=%.6lf'%test_loss,fontdict={'size':15,'color':'blue','style':'italic'}) plt.pause(0.01) # 三维空间函数拟合 elif len(x_train[0])==2: x1_train = x_train[:, 0] x2_train = x_train[:, 1] x1_train, x2_train = np.meshgrid(x1_train, x2_train) trainY = np.add(x1_train, x2_train) x1_test = x_test[:, 0] x2_test = x_test[:, 1] x1_test, x2_test = np.meshgrid(x1_test, x2_test) testY = np.add(x1_test, x2_test) a = [] b = [] for k in x1_train: for p in x2_train: m = np.vstack((k, p)).T a.append(m) a = np.array(a) a.resize((x1_train.shape[0]*x2_train.shape[0], 2)) for k in x1_test: for p in x2_test: m = np.vstack((k, p)).T b.append(m) b = np.array(b) b.resize((x1_test.shape[0]*x2_test.shape[0], 2)) trainy = net.forward_propagation(a).reshape((x1_train.shape[0], x2_train.shape[0])) testy = net.forward_propagation(b).reshape((x1_test.shape[0], x2_test.shape[0])) # print(trainy.shape, testy.shape) #(280, 280), (120, 120) fig1 = plt.figure(3, figsize=(6, 4)) plt.cla() ax1=Axes3D(fig1) ax1.scatter(x1_train, x2_train, trainY, ) # 预期输出 ax1.scatter(x1_train, x2_train, trainy, ) # 实际输出 ax1.text(plt.axis()[1]-0.1, plt.axis()[2]+0.1, 0, 'train loss=%.6lf'%train_loss, fontdict={'size':15,'color':'blue','style':'italic'}) ax1.set_xlabel('x1') ax1.set_ylabel('x2') ax1.set_zlabel('y') fig2 = plt.figure(4, figsize=(6, 4)) plt.cla() ax2=Axes3D(fig2) ax2.scatter(x1_test, x2_test, testY, ) ax2.scatter(x1_test, x2_test, testy, ) ax2.text(plt.axis()[1]-0.1, plt.axis()[2]+0.1, 0, 'test loss=%.6lf'%test_loss, fontdict={'size':15,'color':'blue','style':'italic'}) ax2.set_xlabel('x1') ax2.set_ylabel('x2') ax2.set_zlabel('y') plt.pause(0.01) plt.show() plt.ioff() return train_losses, test_losses
def plot_surf(surf_mesh, surf_map=None, bg_map=None, hemi='left', view='lateral', cmap=None, colorbar=False, avg_method='mean', threshold=None, alpha='auto', bg_on_data=False, darkness=1, vmin=None, vmax=None, cbar_vmin=None, cbar_vmax=None, title=None, output_file=None, axes=None, figure=None, **kwargs): """ Plotting of surfaces with optional background and data .. versionadded:: 0.3 Parameters ---------- surf_mesh: str or list of two numpy.ndarray Surface mesh geometry, can be a file (valid formats are .gii or Freesurfer specific files such as .orig, .pial, .sphere, .white, .inflated) or a list of two Numpy arrays, the first containing the x-y-z coordinates of the mesh vertices, the second containing the indices (into coords) of the mesh faces. surf_map: str or numpy.ndarray, optional. Data to be displayed on the surface mesh. Can be a file (valid formats are .gii, .mgz, .nii, .nii.gz, or Freesurfer specific files such as .thickness, .curv, .sulc, .annot, .label) or a Numpy array with a value for each vertex of the surf_mesh. bg_map: Surface data object (to be defined), optional, Background image to be plotted on the mesh underneath the surf_data in greyscale, most likely a sulcal depth map for realistic shading. hemi : {'left', 'right'}, default is 'left' Hemisphere to display. view: {'lateral', 'medial', 'dorsal', 'ventral', 'anterior', 'posterior'}, default is 'lateral' View of the surface that is rendered. cmap: matplotlib colormap, str or colormap object, default is None To use for plotting of the stat_map. Either a string which is a name of a matplotlib colormap, or a matplotlib colormap object. If None, matplotlib default will be chosen colorbar : bool, optional, default is False If True, a colorbar of surf_map is displayed. avg_method: {'mean', 'median'}, default is 'mean' How to average vertex values to derive the face value, mean results in smooth, median in sharp boundaries. threshold : a number or None, default is None. If None is given, the image is not thresholded. If a number is given, it is used to threshold the image, values below the threshold (in absolute value) are plotted as transparent. alpha: float, alpha level of the mesh (not surf_data), default 'auto' If 'auto' is chosen, alpha will default to .5 when no bg_map is passed and to 1 if a bg_map is passed. bg_on_data: bool, default is False If True, and a bg_map is specified, the surf_data data is multiplied by the background image, so that e.g. sulcal depth is visible beneath the surf_data. NOTE: that this non-uniformly changes the surf_data values according to e.g the sulcal depth. darkness: float, between 0 and 1, default is 1 Specifying the darkness of the background image. 1 indicates that the original values of the background are used. .5 indicates the background values are reduced by half before being applied. vmin, vmax: lower / upper bound to plot surf_data values If None , the values will be set to min/max of the data title : str, optional Figure title. output_file: str, or None, optional The name of an image file to export plot to. Valid extensions are .png, .pdf, .svg. If output_file is not None, the plot is saved to a file, and the display is closed. axes: instance of matplotlib axes, None, optional The axes instance to plot to. The projection must be '3d' (e.g., `figure, axes = plt.subplots(subplot_kw={'projection': '3d'})`, where axes should be passed.). If None, a new axes is created. figure: instance of matplotlib figure, None, optional The figure instance to plot to. If None, a new figure is created. See Also -------- nilearn.datasets.fetch_surf_fsaverage : For surface data object to be used as background map for this plotting function. nilearn.plotting.plot_surf_roi : For plotting statistical maps on brain surfaces. nilearn.plotting.plot_surf_stat_map : for plotting statistical maps on brain surfaces. """ # load mesh and derive axes limits mesh = load_surf_mesh(surf_mesh) coords, faces = mesh[0], mesh[1] limits = [coords.min(), coords.max()] # set view if hemi == 'right': if view == 'lateral': elev, azim = 0, 0 elif view == 'medial': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') elif hemi == 'left': if view == 'medial': elev, azim = 0, 0 elif view == 'lateral': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') else: raise ValueError('hemi must be one of right or left') # set alpha if in auto mode if alpha == 'auto': if bg_map is None: alpha = .5 else: alpha = 1 # if no cmap is given, set to matplotlib default if cmap is None: cmap = plt.cm.get_cmap(plt.rcParamsDefault['image.cmap']) else: # if cmap is given as string, translate to matplotlib cmap if isinstance(cmap, str): cmap = plt.cm.get_cmap(cmap) # initiate figure and 3d axes if axes is None: if figure is None: figure = plt.figure() axes = Axes3D(figure, rect=[0, 0, 1, 1], xlim=limits, ylim=limits) else: if figure is None: figure = axes.get_figure() axes.set_xlim(*limits) axes.set_ylim(*limits) axes.view_init(elev=elev, azim=azim) axes.set_axis_off() # plot mesh without data p3dcollec = axes.plot_trisurf(coords[:, 0], coords[:, 1], coords[:, 2], triangles=faces, linewidth=0., antialiased=False, color='white') # reduce viewing distance to remove space around mesh axes.dist = 8 # set_facecolors function of Poly3DCollection is used as passing the # facecolors argument to plot_trisurf does not seem to work face_colors = np.ones((faces.shape[0], 4)) if bg_map is None: bg_data = np.ones(coords.shape[0]) * 0.5 else: bg_data = load_surf_data(bg_map) if bg_data.shape[0] != coords.shape[0]: raise ValueError('The bg_map does not have the same number ' 'of vertices as the mesh.') bg_faces = np.mean(bg_data[faces], axis=1) if bg_faces.min() != bg_faces.max(): bg_faces = bg_faces - bg_faces.min() bg_faces = bg_faces / bg_faces.max() # control background darkness bg_faces *= darkness face_colors = plt.cm.gray_r(bg_faces) # modify alpha values of background face_colors[:, 3] = alpha * face_colors[:, 3] # should it be possible to modify alpha of surf data as well? if surf_map is not None: surf_map_data = load_surf_data(surf_map) if surf_map_data.ndim != 1: raise ValueError('surf_map can only have one dimension but has' '%i dimensions' % surf_map_data.ndim) if surf_map_data.shape[0] != coords.shape[0]: raise ValueError('The surf_map does not have the same number ' 'of vertices as the mesh.') # create face values from vertex values by selected avg methods if avg_method == 'mean': surf_map_faces = np.mean(surf_map_data[faces], axis=1) elif avg_method == 'median': surf_map_faces = np.median(surf_map_data[faces], axis=1) # if no vmin/vmax are passed figure them out from data if vmin is None: vmin = np.nanmin(surf_map_faces) if vmax is None: vmax = np.nanmax(surf_map_faces) # treshold if inidcated if threshold is None: kept_indices = np.arange(surf_map_faces.shape[0]) else: kept_indices = np.where(np.abs(surf_map_faces) >= threshold)[0] surf_map_faces = surf_map_faces - vmin surf_map_faces = surf_map_faces / (vmax - vmin) # multiply data with background if indicated if bg_on_data: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices])\ * face_colors[kept_indices] else: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices]) if colorbar: our_cmap = get_cmap(cmap) norm = Normalize(vmin=vmin, vmax=vmax) nb_ticks = 5 ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, our_cmap.N) if threshold is not None: cmaplist = [our_cmap(i) for i in range(our_cmap.N)] # set colors to grey for absolute values < threshold istart = int(norm(-threshold, clip=True) * (our_cmap.N - 1)) istop = int(norm(threshold, clip=True) * (our_cmap.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.) our_cmap = LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, our_cmap.N) # we need to create a proxy mappable proxy_mappable = ScalarMappable(cmap=our_cmap, norm=norm) proxy_mappable.set_array(surf_map_faces) cax, kw = make_axes(axes, location='right', fraction=.1, shrink=.6, pad=.0) cbar = figure.colorbar(proxy_mappable, cax=cax, ticks=ticks, boundaries=bounds, spacing='proportional', format='%.2g', orientation='vertical') _crop_colorbar(cbar, cbar_vmin, cbar_vmax) p3dcollec.set_facecolors(face_colors) if title is not None: axes.set_title(title, position=(.5, .95)) # save figure if output file is given if output_file is not None: figure.savefig(output_file) plt.close(figure) else: return figure
def hist3d(y_label, x_label, z_value, \ y_label_name = "y", x_label_name = "x", z_label_name = "z", output_filepath = "..\\result\\lsfs_featue_namuda.png"): """ y -> row -> data.shape[0] x -> column -> data->shape[1] """ column_names = x_label.copy() row_names = y_label.copy() data = z_value.copy() fig = plt.figure(figsize=(8, 5)) ax = Axes3D(fig) lx= len(data[0]) # Work out matrix dimensions ly= len(data[:,0]) xpos = np.arange(0,lx,1) # Set up a mesh of positions ypos = np.arange(0,ly,1) xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) xpos = xpos.flatten() # Convert positions to 1D array ypos = ypos.flatten() zpos = np.zeros(lx*ly) dx = 0.5 * np.ones_like(zpos) dy = dx.copy() dz = data.flatten() bar_colors = ['red', 'green', 'blue', 'aqua', 'burlywood', 'cadetblue', 'chocolate', 'cornflowerblue', 'crimson', 'darkcyan', 'darkgoldenrod', 'darkgreen', 'purple', 'darkred', 'darkslateblue', 'darkviolet'] colors = [] for i in range(len(y_label)): for j in range(len(x_label)): colors.append(bar_colors[i]) ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color=colors, alpha = 0.6) #sh() ax.w_xaxis.set_ticklabels(x_label) ax.w_yaxis.set_ticklabels(y_label) ax.set_xlabel(x_label_name) ax.set_ylabel(y_label_name) ax.set_zlabel(z_label_name) #ax.w_xaxis.set_ticklabels(column_names) #ax.w_yaxis.set_ticklabels(row_names) # start, stop, step ticksx = np.arange(0.5, lx, 1) plt.xticks(ticksx, x_label) ticksy = np.arange(0.6, ly, 1) plt.yticks(ticksy, y_label) plt.savefig(output_filepath) print("save to ", output_filepath) plt.close()
import os import pylab as pl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np os.system("clear") fig = pl.figure() axx = Axes3D(fig) raiz=np.sqrt ln=np.log X = np.arange(-2, 12, 0.1) Y = np.arange(-2, 12, 0.1) X[25]=0.49 X[65]=4.49 X[105]=8.49 Y[25]=0.49 Y[65]=4.49 Y[105]=8.49 X, Y = np.meshgrid(X, Y) ax, ay = 0, 0 bx, by = 4, 0
vind = [[node1[i], node2[i], node3[i]] for i in range(ntria)] # vind = np.matrix([[node1[i], node2[i], node3[i]] # for i in range(ntria)]) print(vind) x = xpts y = ypts z = zpts r = [[x[i], y[i], z[i]] for i in range(nverts)] # r = np.matrix([[x[i], y[i], z[i]] # for i in range(nverts)]) print(r) # inicio plot fig1 = plt.figure() ax = Axes3D(fig1) # print(x[int(vind[0][0])]) # print(vind[0][0]) # int(vind[0][0]) # print(isinstance(int(vind[0][0]), float)) print(x) for i in range(ntria): # print(int(vind[i][0])) # Xa = [x[int(vind[0][0])]]# , x[int(vind[i][1])], x[int(vind[i][2])], x[int(vind[i][0])]] Xa = [int(r[int(vind[i][0])-1][0]), int(r[int(vind[i][1])-1][0]), int(r[int(vind[i][2])-1][0]), int(r[int(vind[i][0])-1][0])] print(Xa) Ya = [int(r[int(vind[i][0])-1][1]), int(r[int(vind[i][1])-1][1]), int(r[int(vind[i][2])-1][1]), int(r[int(vind[i][0])-1][1])] # print(Ya) Za = [int(r[int(vind[i][0])-1][2]), int(r[int(vind[i][1])-1][2]), int(r[int(vind[i][2])-1][2]), int(r[int(vind[i][0])-1][2])] # print(Za) # ax.plot3D(Xa, Ya, Za)
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D X = [1, 1, 2, 2] Y = [3, 4, 4, 3] Z = [1, 100, 1, 1] figure = plt.figure() ax = Axes3D(figure) ax.plot_trisurf(X, Y, Z) plt.show()
import math def fonction(X, Y): return X * np.exp(-X**2 - Y**2) + (X**2 + Y**2) / 20 def gradient_fonction(X, Y): g_x = np.exp(-X**2 - Y**2) + X * -2 * X * np.exp(-X**2 - Y**2) + X / 10 g_y = -2 * Y * X * np.exp(-X**2 - Y**2) + Y / 10 return g_x, g_y fig = plt.figure() fig.set_size_inches(9, 7, forward=True) ax = Axes3D(fig, azim=-29, elev=49) X = np.arange(-3, 3, 0.2) Y = np.arange(-3, 3, 0.2) X, Y = np.meshgrid(X, Y) Z = fonction(X, Y) ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1) #ax.contour(X, Y, Z, 70, rstride=1, cstride=1, cmap='plasma') plt.xlabel("Paramètre 1 (x)") plt.ylabel("Paramètre 2 (y)") x = np.random.random_integers(-2, 2) + np.random.rand(1)[0] y = np.random.random_integers(-2, 2) + np.random.rand(1)[0] lr = 0.2 lr2 = 0.9
def sphereplot(theta, phi, values, fig=None, ax=None, save=False): """Plots a matrix of values on a sphere Parameters ---------- theta : float Angle with respect to z-axis phi : float Angle in x-y plane values : array Data set to be plotted fig : a matplotlib Figure instance The Figure canvas in which the plot will be drawn. ax : a matplotlib axes instance The axes context in which the plot will be drawn. save : bool {False , True} Whether to save the figure or not Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. """ if fig is None or ax is None: fig = plt.figure() ax = Axes3D(fig) thetam, phim = np.meshgrid(theta, phi) xx = sin(thetam) * cos(phim) yy = sin(thetam) * sin(phim) zz = cos(thetam) r = array(abs(values)) ph = angle(values) # normalize color range based on phase angles in list ph nrm = mpl.colors.Normalize(ph.min(), ph.max()) # plot with facecolors set to cm.jet colormap normalized to nrm surf = ax.plot_surface(r * xx, r * yy, r * zz, rstride=1, cstride=1, facecolors=cm.jet(nrm(ph)), linewidth=0) # create new axes on plot for colorbar and shrink it a bit. # pad shifts location of bar with repsect to the main plot cax, kw = mpl.colorbar.make_axes(ax, shrink=.66, pad=.02) # create new colorbar in axes cax with cm jet and normalized to nrm like # our facecolors cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cm.jet, norm=nrm) # add our colorbar label cb1.set_label('Angle') if save: plt.savefig("sphereplot.png") return fig, ax
def plot_spin_distribution_3d(P, THETA, PHI, fig=None, ax=None, figsize=(8, 6)): """Plots a matrix of values on a sphere Parameters ---------- P : matrix Distribution values as a meshgrid matrix. THETA : matrix Meshgrid matrix for the theta coordinate. PHI : matrix Meshgrid matrix for the phi coordinate. fig : a matplotlib figure instance The figure canvas on which the plot will be drawn. ax : a matplotlib axis instance The axis context in which the plot will be drawn. figsize : (width, height) The size of the matplotlib figure (in inches) if it is to be created (that is, if no 'fig' and 'ax' arguments are passed). Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. """ if fig is None or ax is None: fig = plt.figure(figsize=figsize) ax = Axes3D(fig, azim=-35, elev=35) xx = sin(THETA) * cos(PHI) yy = sin(THETA) * sin(PHI) zz = cos(THETA) if P.min() < -1e12: cmap = cm.RdBu norm = mpl.colors.Normalize(-P.max(), P.max()) else: cmap = cm.RdYlBu norm = mpl.colors.Normalize(P.min(), P.max()) surf = ax.plot_surface(xx, yy, zz, rstride=1, cstride=1, facecolors=cmap(norm(P)), linewidth=0) cax, kw = mpl.colorbar.make_axes(ax, shrink=.66, pad=.02) cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) cb1.set_label('magnitude') return fig, ax
def matrix_histogram(M, xlabels=None, ylabels=None, title=None, limits=None, colorbar=True, fig=None, ax=None): """ Draw a histogram for the matrix M, with the given x and y labels and title. Parameters ---------- M : Matrix of Qobj The matrix to visualize xlabels : list of strings list of x labels ylabels : list of strings list of y labels title : string title of the plot (optional) limits : list/array with two float numbers The z-axis limits [min, max] (optional) ax : a matplotlib axes instance The axes context in which the plot will be drawn. Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. Raises ------ ValueError Input argument is not valid. """ if isinstance(M, Qobj): # extract matrix data from Qobj M = M.full() n = np.size(M) xpos, ypos = np.meshgrid(range(M.shape[0]), range(M.shape[1])) xpos = xpos.T.flatten() - 0.5 ypos = ypos.T.flatten() - 0.5 zpos = np.zeros(n) dx = dy = 0.8 * np.ones(n) dz = np.real(M.flatten()) if limits and type(limits) is list and len(limits) == 2: z_min = limits[0] z_max = limits[1] else: z_min = min(dz) z_max = max(dz) if z_min == z_max: z_min -= 0.1 z_max += 0.1 norm = mpl.colors.Normalize(z_min, z_max) cmap = cm.get_cmap('jet') # Spectral colors = cmap(norm(dz)) if ax is None: fig = plt.figure() ax = Axes3D(fig, azim=-35, elev=35) ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors) if title and fig: ax.set_title(title) # x axis ax.axes.w_xaxis.set_major_locator(plt.IndexLocator(1, -0.5)) if xlabels: ax.set_xticklabels(xlabels) ax.tick_params(axis='x', labelsize=14) # y axis ax.axes.w_yaxis.set_major_locator(plt.IndexLocator(1, -0.5)) if ylabels: ax.set_yticklabels(ylabels) ax.tick_params(axis='y', labelsize=14) # z axis ax.axes.w_zaxis.set_major_locator(plt.IndexLocator(1, 0.5)) ax.set_zlim3d([min(z_min, 0), z_max]) # color axis if colorbar: cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.0) cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) return fig, ax
np.random.seed(5) iris = datasets.load_iris() X = iris.data y = iris.target estimators = [('k_means_iris_8', KMeans(n_clusters=8)), ('k_means_iris_3', KMeans(n_clusters=3)), ('k_means_iris_bad_init', KMeans(n_clusters=3, n_init=1, init='random'))] fignum = 1 titles = ['8 clusters', '3 clusters', '3 clusters, bad initialization'] for name, est in estimators: fig = plt.figure(fignum, figsize=(4, 3)) ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float), edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length')
def contour_plot(self, data=None, labels=None, interval=0.2, title="adaboost", name=None, make_gif=False, mode="3d"): if data is None: data = self.X labels = self.y if labels is None: labels = np.ones([len(data)]) x_min, x_max = data[:, 0].min() - .5, data[:, 0].max() + .5 y_min, y_max = data[:, 1].min() - .5, data[:, 1].max() + .5 #xx, yy, Z_grid are used for plotting surface xx, yy = np.meshgrid(np.arange(x_min, x_max, interval), np.arange(y_min, y_max, interval)) X_grid = np.concatenate([ np.expand_dims(np.ravel(xx), axis=-1), np.expand_dims(np.ravel(yy), axis=-1) ], axis=-1) Z_grid = self.predict(data=X_grid, reduction="mean") Z_grid = Z_grid.reshape(xx.shape) if mode == "3d": fig = plt.figure() ax = Axes3D(fig) ax.set_zlim(Z_grid.min() * 1.1, Z_grid.max() * 1.1) ax.view_init(azim=120) plt.title(title) ax.plot_surface(xx, yy, Z_grid, cmap=plt.cm.summer, alpha=0.6) ax.scatter(xs=data[labels == 1][:, 0], ys=data[labels == 1][:, 1], zs=self.predict(data=data, reduction="mean")[labels == 1], c='#00CED1') ax.scatter(xs=data[labels == -1][:, 0], ys=data[labels == -1][:, 1], zs=self.predict(data=data, reduction="mean")[labels == -1], c='#DC143C') if not os.path.exists('temp'): os.mkdir('temp') if name is None: plt.savefig(title + '.png') plt.close() else: plt.savefig('temp/' + name + '.png') plt.close() if mode == "2d": plt.contourf(xx, yy, Z_grid, cmap=plt.cm.RdBu, alpha=.8) plt.scatter(data[:, 0], data[:, 1], c=labels, cmap=ListedColormap(['#FF0000', '#0000FF']), edgecolors='k') plt.title(title) if name is None: plt.savefig(title + '.png') plt.close() else: plt.savefig('temp/' + name + '.png') plt.close() if make_gif == True: imgs = [] for i in range(len(os.listdir('temp'))): imgs.append(imageio.imread('temp/' + str(i + 1) + '.png')) imageio.mimsave('AdaBoost.gif', imgs, 'GIF', duration=0.1)
def matrix_histogram_complex(M, xlabels=None, ylabels=None, title=None, limits=None, phase_limits=None, colorbar=True, fig=None, ax=None, threshold=None): """ Draw a histogram for the amplitudes of matrix M, using the argument of each element for coloring the bars, with the given x and y labels and title. Parameters ---------- M : Matrix of Qobj The matrix to visualize xlabels : list of strings list of x labels ylabels : list of strings list of y labels title : string title of the plot (optional) limits : list/array with two float numbers The z-axis limits [min, max] (optional) phase_limits : list/array with two float numbers The phase-axis (colorbar) limits [min, max] (optional) ax : a matplotlib axes instance The axes context in which the plot will be drawn. threshold: float (None) Threshold for when bars of smaller height should be transparent. If not set, all bars are colored according to the color map. Returns ------- fig, ax : tuple A tuple of the matplotlib figure and axes instances used to produce the figure. Raises ------ ValueError Input argument is not valid. """ if isinstance(M, Qobj): # extract matrix data from Qobj M = M.full() n = np.size(M) xpos, ypos = np.meshgrid(range(M.shape[0]), range(M.shape[1])) xpos = xpos.T.flatten() - 0.5 ypos = ypos.T.flatten() - 0.5 zpos = np.zeros(n) dx = dy = 0.8 * np.ones(n) Mvec = M.flatten() dz = abs(Mvec) # make small numbers real, to avoid random colors idx, = np.where(abs(Mvec) < 0.001) Mvec[idx] = abs(Mvec[idx]) if phase_limits: # check that limits is a list type phase_min = phase_limits[0] phase_max = phase_limits[1] else: phase_min = -pi phase_max = pi norm = mpl.colors.Normalize(phase_min, phase_max) cmap = complex_phase_cmap() colors = cmap(norm(angle(Mvec))) if threshold is not None: colors[:, 3] = 1 * (dz > threshold) if ax is None: fig = plt.figure() ax = Axes3D(fig, azim=-35, elev=35) ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors) if title and fig: ax.set_title(title) # x axis ax.axes.w_xaxis.set_major_locator(plt.IndexLocator(1, -0.5)) if xlabels: ax.set_xticklabels(xlabels) ax.tick_params(axis='x', labelsize=12) # y axis ax.axes.w_yaxis.set_major_locator(plt.IndexLocator(1, -0.5)) if ylabels: ax.set_yticklabels(ylabels) ax.tick_params(axis='y', labelsize=12) # z axis if limits and isinstance(limits, list): ax.set_zlim3d(limits) else: ax.set_zlim3d([0, 1]) # use min/max # ax.set_zlabel('abs') # color axis if colorbar: cax, kw = mpl.colorbar.make_axes(ax, shrink=.75, pad=.0) cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) cb.set_ticks([-pi, -pi / 2, 0, pi / 2, pi]) cb.set_ticklabels( (r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$')) cb.set_label('arg') return fig, ax
def plot_3D(data): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Axes3D.scatter(ax,data[:,0],data[:,1],data[:,2]) ax.view_init(azim=160) plt.show()
self.b_2 += -0.5*b2 # --- Dane --- X = [] X.append(rand(100)*6 - 3) X.append(rand(100)*4 - 1) X = np.matrix(X) Y = np.sin(2 * X[0] + X[1]) # --- Uczenie sieci na 100000 iteracji --- N= Neuron() blad= [] for i in range(10000): blad.append(np.sum(((N.impuls(X)-Y)@(N.impuls(X)-Y).T))) N.aktualizacja_wag(X,Y) plt.plot(blad) x1 = np.linspace(-3 ,3, 50) y1 = np.linspace(-1 ,3, 50) x1, y1 = np.meshgrid(x1,y1) z = np.sin(2*x1 + y1)to H = Axes3D(plt.figure(1)) H.plot_surface(x1 , y1, z , cmap = 'Greens' ,alpha=0.8) H.scatter(X[0],X[1],N.impuls(X),c='red',marker='^') plt.show()
gamma2 = 0.2 # qubit dephasing rate # initial state a = 1.0 psi0 = (a * basis(2, 0) + (1 - a) * basis(2, 1)) / (sqrt(a**2 + (1 - a)**2)) tlist = linspace(0, 4, 250) sx, sy, sz = qubit_integrate(w, theta, gamma1, gamma2, psi0, tlist) ## animate the dynamics on the Bloch sphere from pylab import * import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D fig = figure() ax = Axes3D(fig, azim=-40, elev=30) sphere = Bloch(axes=ax) def animate(i): sphere.clear() sphere.add_vectors([sin(theta), 0, cos(theta)]) sphere.add_points([sx[:i + 1], sy[:i + 1], sz[:i + 1]]) sphere.make_sphere() return ax def init(): sphere.vector_color = ['r'] return ax
def plot_attractor(steps=15000, dt=0.001, attractor='lorenz', random=True, color='b'): """ Plots a the chosen attractor :param steps: timesteps to integrate :param dt: delta t :param attractor: type of attractor :return: """ # Need one more for the initial values xo_vals = np.empty(steps) yo_vals = np.empty(steps) zo_vals = np.empty(steps) xo_dot = 0 yo_dot = 0 zo_dot = 0 if random: if attractor == 'lorenz': xo_vals[0], yo_vals[0], zo_vals[0] = init_random(x_variance=20.0, y_variance=20.0, z_variance=20.0) elif attractor == 'rossler': xo_vals[0], yo_vals[0], zo_vals[0] = init_random(x_variance=10.0, y_variance=10.0, z_variance=10.0) elif attractor == 'chua': xo_vals[0], yo_vals[0], zo_vals[0] = init_random(x_variance=2.0, y_variance=0.5, z_variance=2.0) else: log.out.error("Attractor: " + attractor + " not defined.") sys.exit(-1) else: if attractor == 'lorenz': xo_vals[0] = 1.0 yo_vals[0] = 1.0 zo_vals[0] = 1.0 elif attractor == 'rossler': xo_vals[0] = 1.0 yo_vals[0] = 1.0 zo_vals[0] = 1.0 elif attractor == 'chua': xo_vals[0] = 0.777 yo_vals[0] = -0.222 zo_vals[0] = -1.222 else: log.out.error("Attractor: " + attractor + " not defined.") sys.exit(-1) # Stepping through time for i in range(0, steps - 1): # Calculate the derivatives of the X, Y, Z state if attractor == 'lorenz': xo_dot, yo_dot, zo_dot = lorenz(xo_vals[i], yo_vals[i], zo_vals[i]) elif attractor == 'rossler': xo_dot, yo_dot, zo_dot = rossler(xo_vals[i], yo_vals[i], zo_vals[i]) elif attractor == 'chua': xo_dot, yo_dot, zo_dot = chua(xo_vals[i], yo_vals[i], zo_vals[i]) # Propagate the system xo_vals[i + 1] = xo_vals[i] + (xo_dot * dt) yo_vals[i + 1] = yo_vals[i] + (yo_dot * dt) zo_vals[i + 1] = zo_vals[i] + (zo_dot * dt) fig3d = plt.figure() fig3d.canvas.set_window_title('3D View (model)') ax3d = Axes3D(fig3d) ax3d.plot(xo_vals, yo_vals, zo_vals, color=color, linewidth=0.5) ax3d.set_xlabel("X Axis") ax3d.set_ylabel("Y Axis") ax3d.set_zlabel("Z Axis") if attractor == 'lorenz': ax3d.set_title("Lorenz Attractor") elif attractor == 'rossler': ax3d.set_title("Rössler Attractor") elif attractor == 'chua': ax3d.set_title("Chua's Circuit Attractor") plt.show()
return k*cm.exp(1j*b*t*t) def signal_u2(t): return k*cm.exp(-1j*b*t*t) def signal_u(t): if -T<t<T: return signal_u1(t)+signal_u2(t) else: return 0 def X11(t,f): k1 = 0.5*(1-abs(t)/T)*il.m.sin(il.m.pi*(f-b*t/il.m.pi)*(T - abs(t))) k2 = cm.exp(1j*(il.m.pi*f*(T+t)-b*t*T)) if (il.m.pi*(f-b*t/il.m.pi)*(T - abs(t)))==0: return 1 else: return k1*k2/(il.m.pi*(f-b*t/il.m.pi)*(T - abs(t))) def X22(t,f): return X11(t,-f)*cm.exp(1j*2*il.m.pi*f*t) def Lchm_V(t,f): return X11(t,f) + X22(t,f) if __name__ == "__main__": time = [t for t in il.np.arange(-6,6,100*T)] freq = [f for f in il.np.arange(-2e3,2e3,1/T)] xgrid, ygrid = il.np.meshgrid(time, freq) Z = [[abs(Lchm_V(t,f)) for t in time ] for f in freq] import pylab from mpl_toolkits.mplot3d import Axes3D fig = pylab.figure() axes = Axes3D(fig) axes.plot_surface(xgrid, ygrid,Z, rstride=1, cstride=1) pylab.show()
model.score(X, y) # is the R2 score for full model ## Creating testing and training data from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, stratify = y) # The stratify means that the testing data and training #data will contain the same ratio. For instance, if the training data is 60% female, the testing data will also be 60% female. ## Multiple Linear Regression from sklearn.datasets import make_regression X, y = make_regression(n_samples=30, n_features=3, n_informative=3, random_state=42, noise = 0.5, bias = 100) # To visualize on a 3 D plot from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(1, figsize=(5,5)) axes = Axes3D(fig, elev=20, azim=45) axes.scatter(X[:,0], X[:,1], X[:,2], c=y, cmap=plt.cm.get_cmap("Spectra")) plt.show # Can still fit model as normal (The Linear Regression model in sklearn uses the Ordinary Least Squares method) model = LinearRegression() model.fit(X, y) # to fit against the 3D dataset. ##To plot residuals predictions = model.predict(X) plt.scatter(predictions, predictions - y) plt.hlines(y=0, xmin=predictions.min(), xmax=predictions.max()) plt.show() ## Data where the residuals looks random is good. Data where the residuals follow a patter, such as a curve, suggest we're missing something in our training ##Example code (from class) on charting the residuals for training and testing data on the same plot. plt.scatter(model.predict(X_train), model.predict(X_train - y_train), c="blue")
def plot_mag_3d(measured, calibrated, p): # set up points for sphere and ellipsoid wireframes u = r_[0:2 * pi:20j] v = r_[0:pi:20j] wx = outer(cos(u), sin(v)) wy = outer(sin(u), sin(v)) wz = outer(ones(size(u)), cos(v)) ex = p[0] * ones(size(u)) + outer(cos(u), sin(v)) / p[3] ey = p[1] * ones(size(u)) + outer(sin(u), sin(v)) / p[4] ez = p[2] * ones(size(u)) + outer(ones(size(u)), cos(v)) / p[5] # measurements mx = measured[:, 0] my = measured[:, 1] mz = measured[:, 2] m_max = amax(abs(measured)) # calibrated values cx = calibrated[:, 0] cy = calibrated[:, 1] cz = calibrated[:, 2] # axes size left = 0.02 bottom = 0.05 width = 0.46 height = 0.9 rect_l = [left, bottom, width, height] rect_r = [left / 2 + 0.5, bottom, width, height] fig = figure(figsize=figaspect(0.5)) if matplotlib.__version__.startswith('0'): ax = Axes3D(fig, rect=rect_l) else: ax = fig.add_subplot(1, 2, 1, position=rect_l, projection='3d') # plot measurements ax.scatter(mx, my, mz) hold(True) # plot line from center to ellipsoid center ax.plot([0.0, p[0]], [0.0, p[1]], [0.0, p[2]], color='black', marker='+') # plot ellipsoid ax.plot_wireframe(ex, ey, ez, color='grey', alpha=0.5) ax.set_title('MAG raw with fitted ellipsoid and center offset') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_xlim3d(-m_max, m_max) ax.set_ylim3d(-m_max, m_max) ax.set_zlim3d(-m_max, m_max) if matplotlib.__version__.startswith('0'): ax = Axes3D(fig, rect=rect_r) else: ax = fig.add_subplot(1, 2, 2, position=rect_r, projection='3d') ax.plot_wireframe(wx, wy, wz, color='grey', alpha=0.5) hold(True) ax.scatter(cx, cy, cz) ax.set_title('MAG calibrated on unit sphere') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) show()
def __init__(self): super(MainWindow, self).__init__() self.expression_index = 0 self.point_index = 0 self.size = 0 self.current_full_filename = '' self.current_filename = '' self.limits = 96 self.x_ = [] self.y_ = [] self.z_ = [] self.head_data = () self.head_data_copy = () self.setFixedSize(800, 600) self.setWindowTitle('HeadEditor') self.center() main_layout = QtGui.QHBoxLayout() layout_left = QtGui.QVBoxLayout() self.figure = matplotlib.figure.Figure() # Plot self.canvas = FigureCanvas(self.figure) self.axes = Axes3D(self.figure) group_box = QGroupBox("Editing:") self.cb = QComboBox() self.cb.currentIndexChanged.connect(self.select_change) slider_lim = 128 slider_interval = 32 self.x_slider = QSlider(Qt.Horizontal) self.x_slider.valueChanged.connect(self.x_slider_change) self.x_slider.setMinimum(-slider_lim) self.x_slider.setMaximum(slider_lim) self.x_slider.setTickPosition(QSlider.TicksBelow) self.x_slider.setTickInterval(slider_interval) self.x_slider.setEnabled(False) self.y_slider = QSlider(Qt.Horizontal) self.y_slider.valueChanged.connect(self.y_slider_change) self.y_slider.setMinimum(-slider_lim) self.y_slider.setMaximum(slider_lim) self.y_slider.setTickPosition(QSlider.TicksBelow) self.y_slider.setTickInterval(slider_interval) self.y_slider.setEnabled(False) self.z_slider = QSlider(Qt.Horizontal) self.z_slider.valueChanged.connect(self.z_slider_change) self.z_slider.setMinimum(-slider_lim) self.z_slider.setMaximum(slider_lim) self.z_slider.setTickPosition(QSlider.TicksBelow) self.z_slider.setTickInterval(slider_interval) self.z_slider.setEnabled(False) self.expression_slider = QSlider(Qt.Horizontal) self.expression_slider.valueChanged.connect( self.expression_slider_change) self.expression_slider.setMinimum(0) self.expression_slider.setMaximum(4) self.expression_slider.setValue(0) self.expression_slider.setTickPosition(QSlider.TicksBelow) self.expression_slider.setTickInterval(1) self.expression_slider.setEnabled(False) self.load_button = QtGui.QPushButton('Load', self) self.load_button.clicked.connect(self.load_data) self.save_button = QtGui.QPushButton('Save', self) self.save_button.clicked.connect(self.save_data) self.x_slider_label = QLabel("x : 0") self.y_slider_label = QLabel("y : 0") self.z_slider_label = QLabel("z : 0") self.exp_slider_label = QLabel("Expression : 1") hbox = QVBoxLayout() hbox.addWidget(self.x_slider_label) hbox.addWidget(self.x_slider) hbox.addWidget(self.y_slider_label) hbox.addWidget(self.y_slider) hbox.addWidget(self.z_slider_label) hbox.addWidget(self.z_slider) hbox.addWidget(self.exp_slider_label) hbox.addWidget(self.expression_slider) hbox.addWidget(self.load_button) hbox.addWidget(self.save_button) hbox.addStretch(1) allitems = QVBoxLayout() allitems.addWidget(self.cb) allitems.addLayout(hbox) group_box.setLayout(allitems) layout_left.addWidget(self.canvas) main_layout.addLayout(layout_left) main_layout.addWidget(group_box) self.setLayout(main_layout) self.axes.view_init(20, 60) self.plot_3d()
%matplotlib notebook from sklearn import linear_model import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D X = np.array([[0, 0], [1,2], [2,4], [3,0], [4,1]]) y = np.array([0, 0.3, 0.75, 1, 2]) lin_regr = linear_model.LinearRegression() lin_regr.fit(X, y) fig = plt.figure(figsize=(6, 5)) ax = Axes3D(fig, elev=45, azim=-120) ax.scatter(X[:, 0], X[:, 1], y, c='r', marker='o', label='training set') ax.plot_surface(np.array([[-1, -1], [5, 5]]), np.array([[-1, 5], [-1, 5]]), lin_regr.predict(np.array([[-1, -1, 5, 5], [-1, 5, -1, 5]]).T).reshape((2, 2)), alpha=.5, label='linear regression predictor') ax.set_xlabel('input X_1') ax.set_ylabel('input X_2') ax.set_zlabel('output Y') plt.title("Simplistic test of linear regression on 2d input") plt.show()
y_train = np.loadtxt(y_train_file_file) y_final_test = np.loadtxt(y_final_test_file) activity_labels = np.loadtxt(activity_labels_file, dtype=str) X_train_file.close() X_final_test_file.close() y_train_file_file.close() y_final_test_file.close() activity_labels_file.close() k_means = cluster.KMeans(n_clusters=6) km = k_means.fit(X_train) labels = km.predict(X_final_test) fig1 = plt.figure(1, figsize=(10, 8)) ax = Axes3D(fig1, rect=[0, 0, .95, 1], elev=48, azim=134) ax.scatter(X_final_test[:, 0], X_final_test[:, 40], X_final_test[:, 80], c=labels.astype(np.float), edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('tBodyAcc-XYZ') ax.set_ylabel('tGravityAcc-XYZ') ax.set_zlabel('tBodyAccJerk-XYZ') ax.set_title("6 Clusters") ax.dist = 10
def graph(): # 连接数据库 conn = mdb.connect(host='127.0.0.1', port=3306, user='******', passwd='root', db='alibaba_trace', charset='utf8') # 如果使用事务引擎,可以设置自动提交事务,或者在每次操作完成后手动提交事务conn.commit() conn.autocommit(1) # conn.autocommit(True) # 使用cursor()方法获取操作游标 cursor = conn.cursor() # 因该模块底层其实是调用CAPI的,所以,需要先得到当前指向数据库的指针。 try: # 查询数据条目 job_duration = cursor.execute( "SELECT max(end_timestamp) - min(start_timestamp) FROM batch_instance WHERE status = 'Terminated' and real_mem_avg != 0 group by job_id ASC " ) job_duration = cursor.fetchall() list_job_duration = list(job_duration) arr_job_duration = [x[0] for x in list_job_duration] print(arr_job_duration) arr_job_duration_norm = MaxMinNormalization(arr_job_duration, max(arr_job_duration), min(arr_job_duration)) cursor.execute( "select t.job_id, avg(t.avg_cpu), avg(t.avg_mem) from (select job_id, task_id, avg(real_cpu_avg) as avg_cpu, avg(real_mem_avg) as avg_mem from batch_instance where status='Terminated' and real_mem_avg != 0 group by task_id )t group by job_id ASC" ) # cursor.execute("select t.job_id, avg(t.avg_cpu), avg(t.avg_mem) from (select job_id, task_id, avg(cpu) as avg_cpu, avg(mem) as avg_mem from test group by task_id )t group by job_id ") records = cursor.fetchall() list_records = list(records) res = [] res[:] = map(list, list_records) job_arr = [x[0] for x in res] cpu_arr = [x[1] for x in res] print(cpu_arr) cpu_arr_norm = MaxMinNormalization(cpu_arr, max(cpu_arr), min(cpu_arr)) mem_arr = [x[2] for x in res] print(mem_arr) mem_arr_norm = MaxMinNormalization(mem_arr, max(mem_arr), min(cpu_arr)) # 如果没有设置自动提交事务,则这里需要手动提交一次 conn.commit() # k-means聚类 # 设置类别为3 clf = KMeans(n_clusters=3) # 将数据带入到聚类模型中 loan = [] loan.append(arr_job_duration_norm) loan.append(cpu_arr_norm) loan.append(mem_arr_norm) loan = np.asarray(loan) loan = loan.transpose() clf = clf.fit(loan) loan = np.insert(loan, 3, values=clf.labels_, axis=1) fig = plt.figure() ax = Axes3D(fig) loan_df = pd.DataFrame(loan) class_1 = loan_df[loan_df.iloc[:, 3] == 0] print('class_1:') print(class_1) x1 = class_1.iloc[:, 0].values y1 = class_1.iloc[:, 1].values z1 = class_1.iloc[:, 2].values class_2 = loan_df[loan_df.iloc[:, 3] == 1] x2 = class_2.iloc[:, 0].values y2 = class_2.iloc[:, 1].values z2 = class_2.iloc[:, 2].values print("class_2:") print(class_2) class_3 = loan_df[loan_df.iloc[:, 3] == 2] x3 = class_3.iloc[:, 0].values y3 = class_3.iloc[:, 1].values z3 = class_3.iloc[:, 2].values print("class_3") print(class_3) ax.scatter(x1, y1, z1, color='red', s=1) ax.scatter(x2, y2, z2, color='blue', s=1) ax.scatter(x3, y3, z3, color='yellow', s=1) ax.set_xlabel('job duration') ax.set_ylabel('average cpu(per job)') ax.set_zlabel('average memory(per job)') ax.set_xlim(0, 1) ax.view_init(elev=20., azim=-35) ax.grid(False) plt.savefig('../imgs_mysql/knn_job.png') plt.show() except: import traceback traceback.print_exc() # 发生错误时回滚 conn.rollback() finally: # 关闭游标连接 cursor.close() # 关闭数据库连接 conn.close()
#call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, frames=time, interval=10, blit=False) anim.save('dynamic_images3.gif', fps=60) plt.show() T_list = np.array(T_list) from mpl_toolkits.mplot3d import Axes3D fig2 = plt.figure(figsize=(10, 10)) ax2 = Axes3D(fig2) ax2.set_title('Heat Simulation 0.0s', fontsize=30) ax2.plot_surface(X, Y, T_list[0], rstride=1, cstride=1, vmin=min(U), vmax=max(U), cmap='hot') ax2.contourf(X, Y, T_list[0], zdir='z', offset=min(U),
ols_trainX1 = trainX1.copy() ols_trainX1 = sm.add_constant(ols_trainX1) est = sm.OLS(trainY, ols_trainX1).fit() est.summary() # %% 3D Plot x0 = ols_trainX1.T[0] x1 = ols_trainX1.T[1] Z = est.params[0] + est.params[1] * x0 + est.params[2] * x1 fig = plt.figure(figsize=(12, 8)) ax = Axes3D(fig, azim=-115, elev=15) #ax = fig.add_subplot(111, projection='3d') x0 = ols_trainX1.T[0] x1 = ols_trainX1.T[1] xx0, xx1 = np.meshgrid(np.linspace(x0.min(), x0.max(), len(x0)), np.linspace(x1.min(), x1.max(), len(x1))) Z0 = est.params[0] + est.params[1] * xx0 + est.params[2] * xx1 Z1 = est.params[0] + est.params[1] * x0 + est.params[2] * x1 surf = ax.plot_surface(xx0, xx1, Z1, cmap=plt.cm.RdBu_r, alpha=.1, linewidth=0) resid = trainY.T[0] - est.predict(ols_trainX1) ax.scatter(x0[resid >= 0], x1[resid >= 0], trainY[resid >= 0],
def run(): # Configure parameters N = 10 # number of cavity fock states wc = 2 * pi * 1.0 # cavity frequency wa = 2 * pi * 1.0 # atom frequency g = 2 * pi * 0.1 # coupling strength kappa = 0.05 # cavity dissipation rate gamma = 0.15 # atom dissipation rate use_rwa = True # a coherent initial state the in cavity psi0 = tensor(coherent(N, 1.5), basis(2, 0)) # Hamiltonian a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) if use_rwa: # use the rotating wave approxiation H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag()) else: H = wc * a.dag() * a + wa * sm.dag() * sm + g * (a.dag() + a) * (sm + sm.dag()) # collapse operators c_op_list = [] n_th_a = 0.0 # zero temperature rate = kappa * (1 + n_th_a) if rate > 0.0: c_op_list.append(sqrt(rate) * a) rate = kappa * n_th_a if rate > 0.0: c_op_list.append(sqrt(rate) * a.dag()) rate = gamma if rate > 0.0: c_op_list.append(sqrt(rate) * sm) # evolve the system tlist = linspace(0, 10, 100) output = mesolve(H, psi0, tlist, c_op_list, []) # calculate the wigner function xvec = linspace(-5., 5., 100) X, Y = meshgrid(xvec, xvec) #for idx, rho in enumerate(output.states): # suggestion: try to loop over all rho for idx, rho in enumerate([output.states[44] ]): # for a selected time t=4.4 rho_cavity = ptrace(rho, 0) W = wigner(rho_cavity, xvec, xvec) # plot the wigner function fig = figure(figsize=(9, 6)) ax = Axes3D(fig, azim=-107, elev=49) ax.set_xlim3d(-5, 5) ax.set_ylim3d(-5, 5) ax.set_zlim3d(-0.30, 0.30) surf = ax.plot_surface(X, Y, W, rstride=1, cstride=1, cmap=cm.jet, alpha=1.0, linewidth=0.05, vmax=0.4, vmin=-0.4) fig.colorbar(surf, shrink=0.65, aspect=20) #savefig("jc_model_wigner_"+str(idx)+".png") show()
def dbscan(): data = a sse = [] ch = [] sc = [] purity = [] nmi = [] ari = [] xs = [] ys = [] zs = [] labels_true = [1, 1, 1, 0, 0, 0, 1, 1] # 实际分类 epsmax = 13 minspmax = 4 for ms in range(1, minspmax): for e in range(2, epsmax): xs.append(ms) #建立x数列 ys.append(e) #建立y数列 #开始分类 db = DBSCAN(eps=e, min_samples=ms, metric='euclidean') #esp聚类半径,min半径内最少点数,metric距离 predict = db.fit_predict(data) print(predict) #打印分类结果 labels = db.labels_ print('labels=', labels) #可视化结果 purity.append(ACC(labels_true, predict)) # 设计算NMI nmi.append( metrics.normalized_mutual_info_score(labels_true, predict)) # 计算ARI ari.append(metrics.adjusted_rand_score(labels_true, predict)) # 计算CH系数 轮廓系数 ch.append(metrics.calinski_harabasz_score(data, labels)) sc.append( metrics.silhouette_score( data, labels, metric='euclidean')) # 此处算法一定要与上面ag中的算法一致 print('min_samples:', xs) print('eps:', ys) print('SC:', sc) print('CH:', ch) print('purity:', purity) print('NMI:', nmi) print('ARI:', ari) #开始绘图 #绘制min_samples-esp-SC图 fig = plt.figure() # 创建一个画布figure,然后在这个画布上加各种元素。 ax = Axes3D(fig) # 将画布作用于 Axes3D 对象上。 # 基于ax变量绘制三维图 # xs表示x方向的变量 # ys表示y方向的变量 # zs表示z方向的变量,这三个方向上的变量都可以用list的形式表示 # m表示点的形式,o是圆形的点,^是三角形(marker) # c表示颜色(color for short) ax.plot(xs, ys, sc, c='r', marker='X', label='Silhouette Score') # 点为红色三角形 # 显示图例 ax.legend() # 设置坐标轴 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 ax.set_xlabel('min samples') ax.set_ylabel('eps') ax.set_zlabel('Silhouette Score') ax.set_title('min_samples-eps-SC for JDD') for x, y, z in zip(xs, ys, sc): ax.text(x, y, z, str(np.around(z, 2)), ha='center', va='bottom', fontsize=8.5) # 显示图形 plt.show() # 绘制min_samples-esp-ch图 fig = plt.figure() # 创建一个画布figure,然后在这个画布上加各种元素。 ax = Axes3D(fig) # 将画布作用于 Axes3D 对象上。 ax.plot(xs, ys, ch, c='r', marker='o', label='Calinski-Harabasz') # 显示图例 ax.legend() # 设置坐标轴 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 ax.set_xlabel('min samples') ax.set_ylabel('eps') ax.set_zlabel('Calinski-Harabasz') ax.set_title('min_samples-eps-ch for JDD') for x, y, z in zip(xs, ys, ch): ax.text(x, y, z, str(np.around(z, 2)), ha='center', va='bottom', fontsize=8.5) # 显示图形 plt.show() # 绘制min_samples-eps-purity图 fig = plt.figure() # 创建一个画布figure,然后在这个画布上加各种元素。 ax = Axes3D(fig) # 将画布作用于 Axes3D 对象上。 ax.plot(xs, ys, purity, c='r', marker='o', label='purity') # 点为红色圆形 # 显示图例 ax.legend() # 设置坐标轴 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 ax.set_xlabel('min samples') ax.set_ylabel('eps') ax.set_zlabel('purity') ax.set_title('min_samples-eps-purity for JDD') for x, y, z in zip(xs, ys, purity): ax.text(x, y, z, str(np.around(z, 2)), ha='center', va='bottom', fontsize=8.5) # 显示图形 plt.show() # 绘制min_samples-eps-NMI图 fig = plt.figure() # 创建一个画布figure,然后在这个画布上加各种元素。 ax = Axes3D(fig) # 将画布作用于 Axes3D 对象上。 ax.plot(xs, ys, nmi, c='r', marker='*', label='NMI') # 点为红色*形 # 显示图例 ax.legend() # 设置坐标轴 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 ax.set_xlabel('min samples') ax.set_ylabel('eps') ax.set_zlabel('NMI') ax.set_title('min_samples-eps-NMI for JDD') for x, y, z in zip(xs, ys, nmi): ax.text(x, y, z, str(np.around(z, 2)), ha='center', va='bottom', fontsize=8.5) # 显示图形 plt.show() # 绘制min_samples-eps-ARI图 fig = plt.figure() # 创建一个画布figure,然后在这个画布上加各种元素。 ax = Axes3D(fig) # 将画布作用于 Axes3D 对象上。 ax.plot(xs, ys, ari, c='r', marker='X', label='ARI') # 点为红色X形 # 显示图例 ax.legend() # 设置坐标轴 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 ax.set_xlabel('min samples') ax.set_ylabel('eps') ax.set_zlabel('ARI') ax.set_title('min_samples-eps-ARI for JDD') for x, y, z in zip(xs, ys, ari): ax.text(x, y, z, str(np.around(z, 2)), ha='center', va='bottom', fontsize=8.5) # 显示图形 plt.show()
from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import FastICA from sklearn.random_projection import GaussianRandomProjection from sklearn.feature_selection import VarianceThreshold fn = "phishing_dataset.csv" writeFn = fn[:-4] + "_vtresh_kmeans_output.csv" print(writeFn) norms = [True, False] #whitens = [False,False] #algs = ['parallel','deflation'] treshs = [0,.035,.04,.045] fig = plot.figure(1) ax = Axes3D(fig) def runEverything(): data,x,y,normx,normy = preProcessData(fn) results = [] for tresh in treshs: for norm in norms: err = classify(x,y,normx,normy,tresh,norm) print(tresh,norm,":",err) results.append([tresh,norm,err]) file = open(writeFn,"w",newline="") csvW = csv.writer(file) csvW.writerow(["tresh","norm","error"]) csvW.writerows(results) print("Open your file")
def get_TPI(params, bvec1, graphs): start_time = time.clock() (S, T, beta, sigma, chi_n_vec, b_ellip, mu, l_tilde, A, alpha, delta, b_ss, n_ss, K_ss, C_ss, L_ss, maxiter_TPI, mindist_TPI, xi, TPI_tol, EulDiff) = params K1, K1_cnstr = fun3.get_K(bvec1) # Create time paths for K and L Kpath_init = np.zeros(T + S - 2) Kpath_init[:T] = get_path(K1, K_ss, T, "linear") Kpath_init[T:] = K_ss Lpath_init = L_ss * np.ones(T + S - 2) iter_TPI = int(0) dist_TPI = 10. Kpath_new = Kpath_init.copy() Lpath_new = Lpath_init.copy() r_params = (A, alpha, delta) w_params = (A, alpha) cbne_params = (S, T, beta, sigma, chi_n_vec, b_ellip, mu, l_tilde, bvec1, b_ss, n_ss, TPI_tol, EulDiff) while (iter_TPI < maxiter_TPI) and (dist_TPI >= mindist_TPI): iter_TPI += 1 Kpath_init = xi * Kpath_new + (1 - xi) * Kpath_init Lpath_init = xi * Lpath_new + (1 - xi) * Lpath_init rpath = fun3.get_r(r_params, Kpath_init, Lpath_init) wpath = fun3.get_w(w_params, Kpath_init, Lpath_init) cpath, bpath, npath, EulErrPath_inter, EulErrPath_intra = get_cbnepath( cbne_params, rpath, wpath) Kpath_new = np.zeros(T + S - 2) Kpath_new[:T], Kpath_cnstr = fun3.get_K(bpath[:, :T]) Kpath_new[T:] = K_ss * np.ones(S - 2) Lpath_new[:T - 1] = fun3.get_L(npath[:, :T - 1]) Lpath_new[T - 1:] = L_ss * np.ones(S - 1) Kpath_cnstr = np.append(Kpath_cnstr, np.zeros(S - 2, dtype=bool)) Kpath_new[Kpath_cnstr] = 0.1 dist_TPI = ((Kpath_new[1:T] - Kpath_init[1:T]) ** 2).sum() + \ ((Lpath_new[:T] - Lpath_init[:T]) ** 2).sum() if iter_TPI == maxiter_TPI and dist_TPI > mindist_TPI: print('TPI reached maximum interation but did not converge.') Kpath = Kpath_new Lpath = Lpath_new Y_params = (A, alpha) Ypath = fun3.get_Y(Y_params, Kpath, Lpath) Cpath = np.zeros(T + S - 2) Cpath[:T - 1] = fun3.get_C(cpath[:, :T - 1]) Cpath[T - 1:] = C_ss * np.ones(S - 1) RCerrPath = (Ypath[:-1] - Cpath[:-1] - Kpath[1:] + (1 - delta) * Kpath[:-1]) tpi_time = time.clock() - start_time tpi_output = { 'bpath': bpath, 'cpath': cpath, 'npath': npath, 'wpath': wpath, 'rpath': rpath, 'Kpath': Kpath, 'Lpath': Lpath, 'Ypath': Ypath, 'Cpath': Cpath, 'EulErrPath IntraTemporal': EulErrPath_intra, 'EulErrPath InterTemporal': EulErrPath_inter, 'RCerrPath': RCerrPath, 'tpi_time': tpi_time } # Print TPI computation time fun3.print_time(tpi_time, 'TPI') if graphs: # Create directory if images directory does not already exist cur_path = os.path.split(os.path.abspath(__file__))[0] output_fldr = "images" output_dir = os.path.join(cur_path, output_fldr) if not os.access(output_dir, os.F_OK): os.makedirs(output_dir) # Plot time path of aggregate capital stock tvec = np.linspace(1, T + S - 2, T + S - 2) minorLocator = MultipleLocator(1) fig, ax = plt.subplots() plt.plot(tvec, Kpath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for aggregate capital stock K') plt.xlabel(r'Period $t$') plt.ylabel(r'Aggregate capital $K_{t}$') output_path = os.path.join(output_dir, "Kpath") plt.savefig(output_path) plt.show() plt.plot(tvec, Lpath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for aggregate labor supply L') plt.xlabel(r'Period $t$') plt.ylabel(r'Aggregate labor supply $L_{t}$') output_path = os.path.join(output_dir, "Lpath") plt.savefig(output_path) plt.show() # Plot time path of aggregate output (GDP) fig, ax = plt.subplots() plt.plot(tvec, Ypath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for aggregate output (GDP) Y') plt.xlabel(r'Period $t$') plt.ylabel(r'Aggregate output $Y_{t}$') output_path = os.path.join(output_dir, "Ypath") plt.savefig(output_path) # plt.show() # Plot time path of aggregate consumption fig, ax = plt.subplots() plt.plot(tvec, Cpath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for aggregate consumption C') plt.xlabel(r'Period $t$') plt.ylabel(r'Aggregate consumption $C_{t}$') output_path = os.path.join(output_dir, "C_aggr_path") plt.savefig(output_path) # plt.show() # Plot time path of real wage fig, ax = plt.subplots() plt.plot(tvec, wpath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for real wage w') plt.xlabel(r'Period $t$') plt.ylabel(r'Real wage $w_{t}$') output_path = os.path.join(output_dir, "wpath") plt.savefig(output_path) # plt.show() # Plot time path of real interest rate fig, ax = plt.subplots() plt.plot(tvec, rpath, marker='D') # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Time path for real interest rate r') plt.xlabel(r'Period $t$') plt.ylabel(r'Real interest rate $r_{t}$') output_path = os.path.join(output_dir, "rpath") plt.savefig(output_path) # plt.show() # Plot time path of individual savings distribution tgridT = np.linspace(1, T, T) sgrid2 = np.linspace(2, S, S - 1) tmatb, smatb = np.meshgrid(tgridT, sgrid2) cmap_bp = matplotlib.cm.get_cmap('summer') fig = plt.figure() ax = Axes3D(fig) # ax = fig.gca(projection='3d') ax.set_xlabel(r'period-$t$') ax.set_ylabel(r'age-$s$') ax.set_zlabel(r'individual savings $b_{s,t}$') strideval = max(int(1), int(round(S / 10))) ax.plot_surface(tmatb, smatb, bpath[:, :T], rstride=strideval, cstride=strideval, cmap=cmap_bp) output_path = os.path.join(output_dir, "bpath") plt.savefig(output_path) # plt.show() # Plot time path of individual consumption distribution tgridTm1 = np.linspace(1, T - 1, T - 1) sgrid = np.linspace(1, S, S) tmatc, smatc = np.meshgrid(tgridTm1, sgrid) cmap_cp = matplotlib.cm.get_cmap('summer') fig = plt.figure() ax = Axes3D(fig) # ax = fig.gca(projection='3d') ax.set_xlabel(r'period-$t$') ax.set_ylabel(r'age-$s$') ax.set_zlabel(r'individual consumption $c_{s,t}$') strideval = max(int(1), int(round(S / 10))) ax.plot_surface(tmatc, smatc, cpath[:, :T - 1], rstride=strideval, cstride=strideval, cmap=cmap_cp) output_path = os.path.join(output_dir, "cpath") plt.savefig(output_path) # plt.show() return tpi_output