def plot(shiftRelabel): xs, srBias, srError = np.array(shiftRelabel).T #xs2, trError, trBias = np.array(thresholdRelabel).T #f, (ax1, ax2) = plt.subplots(2,1) width = 3 #plt.plot(figsize=(plt.figaspect(2.0))) plt.plot(xs, srError, label='Label error', linewidth=width) plt.plot(xs, srBias, label='Bias', linewidth=width) plt.title("Shifted Decision Boundary Bias vs Error") plt.gca().invert_xaxis() plt.axhline(0, color='black') plt.figaspect(10.0) #handles, labels = plt.get_legend_handles_labels() # ax2.plot(xs2, trError, label='Label error', linewidth=width) # ax2.plot(xs2, trBias, label='Bias', linewidth=width) # ax2.set_title("Margin Threshold Relabeling Bias vs Error") # ax2.axhline(0, color='black') #plt.subplots_adjust(hspace=.75) #plt.figlegend(handles, labels, 'center right') plt.legend(loc='center right') #plt.savefig("relabeling-msr-tradeoffs.pdf",bbox_inches='tight') plt.show()
def test_figaspect(): w, h = plt.figaspect(np.float64(2) / np.float64(1)) assert h / w == 2 w, h = plt.figaspect(2) assert h / w == 2 w, h = plt.figaspect(np.zeros((1, 2))) assert h / w == 0.5 w, h = plt.figaspect(np.zeros((2, 2))) assert h / w == 1
def main(argv): plt.figure(figsize=plt.figaspect(0.55)) xd=np.linspace(0,4000,100) td = getTC(xd) plt1, = plt.plot(td,xd,'b--',lw=3) plt.grid() plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20) plt.ylabel(r'$x_d \rm[m]$',fontsize=20) plt.text(91.55, 1200, 'Zona permitida', bbox={'facecolor':'white', 'alpha':0.5, 'pad':10}) plt.legend([plt1],["$x_d^{CUT}$"],loc=2) plt.savefig("thetaDCut.pdf",format="pdf") thD = np.arange(90.1,95,0.00001) cThD = np.cos(thD*kdeg2rad) #Xd = np.arange(100,1700,200) Xd = np.arange(100,3700,400) plt.figure(figsize=plt.figaspect(0.55)) plots = [] xds = [] for x in Xd: cThE = np.sqrt((R**2 - ((R+x)**2) * (1-cThD**2))/R**2) auxP, = plt.plot(thD,(x*(R*cThE-(R+x)*cThD))/((R**2 - (R+x)**2)*cThD),c=cm.gist_rainbow(float(x-5)/Xd[-1],1),lw=2.5) plots.append(auxP) xds.append(str(x)) plt.grid() plt.legend(plots,xds,loc=4,title=r'$\bf{x_d \rm [m]}$') plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20) plt.ylabel(r'$\frac{l_{plano}}{l_{curvo}}$',fontsize=20) plt.savefig("lPlane_lCurve.pdf",format="pdf") plt.figure(figsize=plt.figaspect(0.55)) plots = [] xds = [] for x in Xd: cThE = -np.sqrt((R**2 - ((R+x)**2) * (1-cThD**2))/R**2) thE = np.arccos(cThE)*krad2deg auxP, = plt.plot(thD,thE,lw=2.5,c=cm.gist_rainbow(float(x-5)/Xd[-1],1)) plots.append(auxP) xds.append(str(x)) plt.grid() plt.legend(plots,xds,loc=4,title=r'$\bf{x_d \rm [m]}$') plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20) plt.ylabel(r'$\theta_E \rm[deg]$',fontsize=20) plt.savefig("thE_thD.pdf",format="pdf")
def _plot_orbits(x, y, z): from matplotlib import pyplot, rc fig = pyplot.figure(figsize=(14,14)) font = {'size' : 30} rc('font', **font) pyplot.figaspect(1.0) pyplot.scatter(x[0].value_in(units.AU), y[0].value_in(units.AU), 200, lw=0) pyplot.plot(x.value_in(units.AU), y.value_in(units.AU), lw=2) pyplot.xlabel("$X [AU]$") pyplot.ylabel("$Y [AU]$") pyplot.xlim(-15000, 15000) pyplot.ylim(-30000, 10000) # pyplot.show() pyplot.savefig("SStars_1Jan2001_orbits")
def main(): import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs n_centers = 3 X, y = make_blobs(n_samples=1000, centers=n_centers, n_features=2, cluster_std=0.7, random_state=0) # Run this K-Means import kmeans t0 = time.time() y_pred, centers, obj_val_seq = kmeans.kmeans(X, n_centers) t1 = time.time() print("Final obj val: {}".format(obj_val_seq[-1])) print("Time taken (this implementation): {}".format(t1 - t0)) # Run scikit-learn's K-Means from sklearn.cluster import k_means t0 = time.time() centers, y_pred, obj_val = k_means(X, n_centers, random_state=0) t1 = time.time() print("Final obj val: {}".format(obj_val)) print("Time taken (Scikit, 1 job): {}".format(t1 - t0)) # Plot change in objective value over iteration fig = plt.figure() ax = fig.add_subplot(111) ax.plot(obj_val_seq, 'b-', marker='*') fig.suptitle("Change in K-means objective value across iterations") ax.set_xlabel("Iteration") ax.set_ylabel("Objective value") fig.show() # Plot data from itertools import cycle colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') fig = plt.figure(figsize=plt.figaspect(0.5)) # Make twice as wide to accomodate both plots ax = fig.add_subplot(121) ax.set_title("Data with true labels and final centers") for k, color in zip(range(n_centers), colors): ax.plot(X[y==k, 0], X[y==k, 1], color + '.') initial_centers = kmeans.init_centers(X, n_centers, 2) # This is valid because we always use the same random seed. # Plot initial centers for x in initial_centers: ax.plot(x[0], x[1], "mo", markeredgecolor="k", markersize=8) # Plot final centers for x in centers: ax.plot(x[0], x[1], "co", markeredgecolor="k", markersize=8) # Plot assignments colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') ax = fig.add_subplot(122) ax.set_title("Data with final assignments") for k, color in zip(range(n_centers), colors): ax.plot(X[y_pred==k, 0], X[y_pred==k, 1], color + '.') fig.tight_layout() fig.gca() fig.show()
def draw_trajectories_eps(paths_list): """ Same as draw_trajectories with additional labels Plots trajectories listed in the paths_list tuple. Paths tuple contains other tuples of the form (x0,x1,...) where xi is the i^th coordinate of the diffusion. """ # set up figures fig = plt.figure(figsize=plt.figaspect(2.)) fig.suptitle('Paths simulated using Euler-Maruyama scheme.') for (i,paths) in enumerate(paths_list): ax = fig.add_subplot(1, len(paths_list), i+1, projection='3d') # plot the path of a realisation of a diffusion for path in paths: ax.plot(path[0], path[1], path[2]) # add labels ax.grid(True) text = "time step: " + str(np.power(10.0, (-i-1))) ax.set_title(text) plt.show()
def plot_3d(X,Y,Z,plot_type = "surface",ax = None,color = "blue"): from scipy.interpolate import griddata if ax == None: fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(1, 1, 1, projection='3d') if plot_type == "scatter": ax.scatter(X,Y,Z) return x = np.array(X) y = np.array(Y) z = np.array(Z) xi = np.linspace(x.min(),x.max(),100) yi = np.linspace(y.min(),y.max(),100) # VERY IMPORTANT, to tell matplotlib how is your data organized zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear') xig, yig = np.meshgrid(xi, yi) if plot_type == "contour": CS = plt.contour(xi,yi,zi,15,linewidths=0.5,color='k') else: surf = ax.plot_surface(xig, yig, zi,linewidth=0,color=color)#,cmap=cm.coolwarm) return ax
def componentes(self): fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(2, 3, 1, projection='3d') surf = ax.plot_surface(self.X, self.Y,self.SOL[:,:,0],cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("ciclohexanol (kmol/h)") ax = fig.add_subplot(2, 3, 2, projection='3d') surf = ax.plot_surface(self.X, self.Y, self.SOL[:,:,1],cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("ciclohexanona (kmol/h)") ax = fig.add_subplot(2, 3, 3, projection='3d') surf = ax.plot_surface(self.X, self.Y, self.SOL[:,:,2],cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("fenol (kmol/h)") ax = fig.add_subplot(2, 3, 4, projection='3d') surf = ax.plot_surface(self.X, self.Y, self.SOL[:,:,3]*1000,cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("ciclohexenona (mol/h)") ax = fig.add_subplot(2, 3, 6, projection='3d') surf = ax.plot_surface(self.X, self.Y, self.SOL[:,:,4],cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("H2 (kmol/h)") plt.show()
def moduloThiele(self): mL = np.zeros((self.nt,self.nl)) rr = kn.CuZn() for i in range(self.nt): for j in range(self.nl): n = self.SOL[i,j,0:5] #kmol/h T = self.SOL[i,j,5]+273.15# K P = self.SOL[i,j,7] #atm a = self.SOL[i,j,8] L = datos.Dint/2/2 #m r = -rr.dnjdW(n,T,P,a)[0]/3600/1000 #kmol/(kgs), (tiene que ser positiva) if (r<0): r = 0 C_ol = n[0]/((sum(n))*datos.R*T/P) #kmol/m3 k = r*datos.ro_l/C_ol # s(-1) D_OL = datos.D0_OL*np.exp(-datos.Ed_OL/((datos.R*101325)*T)) #cambiar la R a kJ/molK De = D_OL*datos.e_cat**2 #m2/s X = 0.712505333333 #grado de conversion de ciclohexanol en equilibrio mL[i,j] = L*(k/De/X)**0.5 #adimensional fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(1, 1, 1, projection='3d') surf = ax.plot_surface(self.X, self.Y, mL, cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("modulo de Thiele") plt.show()
def run(self): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as ani self.fig = plt.figure(figsize=plt.figaspect(0.5)) # setup 3d axis self.ax3d = self.fig.add_subplot(1, 2, 1, projection="3d") self.ax3d.set_xlabel("X") self.ax3d.set_ylabel("Y") self.ax3d.set_zlabel("Z") self.ax3d_lines = [self.ax3d.plot([1, 1], [2, 2], [3, 3], c="b")[0] for i in range(17 * 12)] self.ax3d_scatters = [self.ax3d.scatter(0, 0) for i in range(17)] # setup 2d axis self.ax_flat = self.fig.add_subplot(1, 2, 2) self.ax_flat.set_xlim([-17, 17]) self.ax_flat.set_ylim([-17, 17]) self.ax_flat.set_xlabel("X") self.ax_flat.set_ylabel("Y") self.ax_flat.grid() self.ax_flat_scatters = [self.ax_flat.scatter(0, 0) for i in range(2)] self.ax_flat_lines = [self.ax_flat.plot([], [], c="b")[0] for i in range(5)] self.BASE_CUBE_POINTS = np.array( [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]] ) self.BASE_CUBE_POINTS = np.transpose(np.insert(self.BASE_CUBE_POINTS, 3, 1, axis=1)) a = ani.FuncAnimation(self.fig, self.runani, self.data_gen, blit=False, interval=300) plt.show()
def esfera(meia): fig = plt.figure(figsize=plt.figaspect(1)) ax = fig.add_subplot(111, projection='3d') vx= eval(input("Raio da esfera(r): ")) coefs = (vx, vx, vx) rx, ry, rz = [1/np.sqrt(coef) for coef in coefs] if meia == 1: u = np.linspace(0,1 * np.pi, 100) else: u = np.linspace(0,2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = rx * np.outer(np.cos(u), np.sin(v)) y = ry * np.outer(np.sin(u), np.sin(v)) z = rz * np.outer(np.ones_like(u), np.cos(v)) ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') max_radius = max(rx, ry, rz) for axis in 'xyz': getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius)) plt.show()
def plotMe(self): fig = plt.figure(figsize=plt.figaspect(1)) # Square figure ax = fig.add_subplot(111, projection='3d') getattr(ax, 'set_{}lim'.format('x'))((-np.pi / 4, np.pi / 4)) getattr(ax, 'set_{}lim'.format('y'))((-np.pi / 4, np.pi / 4)) getattr(ax, 'set_{}lim'.format('z'))((-np.pi / 4, 2.25 * np.pi))
def test(): # Twice as wide as it is tall. fig = plt.figure(figsize=plt.figaspect(0.5)) #---- First subplot ax = fig.add_subplot(1, 2, 1, projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) print type(X) print X.shape print Y.shape print Z.shape surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim3d(-1.01, 1.01) fig.colorbar(surf, shrink=0.5, aspect=10) #---- Second subplot ax = fig.add_subplot(1, 2, 2, projection='3d') X, Y, Z = get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show()
def plot_ellipse_mpl(Dxx, Dyy, Dzz, rstride=4, cstride=4, color='b'): """ Plot an ellipse shape (in contrast to a tensor ellipsoid, see plot_ellipsoid_mpl for that) in 3d using matplotlib """ fig = plt.figure(figsize=plt.figaspect(1)) # Square figure ax = fig.add_subplot(111, projection='3d') coefs = Dxx, Dyy, Dzz # Coefficients in a0/c x**2 + a1/c y**2 + a2/c z**2 = # 1 Radii corresponding to the coefficients: rx, ry, rz = Dxx, Dyy, Dzz#[1/np.sqrt(coef) for coef in coefs] # Set of all spherical angles: u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) # Cartesian coordinates that correspond to the spherical angles: # (this is the equation of an ellipsoid): x = rx * np.outer(np.cos(u), np.sin(v)) y = ry * np.outer(np.sin(u), np.sin(v)) z = rz * np.outer(np.ones_like(u), np.cos(v)) # Plot: ax.plot_surface(x, y, z, rstride=rstride, cstride=cstride, color=color) # Adjustment of the axes, so that they all have the same span: max_radius = max(rx, ry, rz) for axis in 'xyz': getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius)) return fig
def plotFile(file): data = [] for row in file: data.append(map(float,row.strip().split())) adata = np.array(data) adata = adata[np.argsort(adata[:,1])] norm = max(adata[:,2]) adata[:,2] = np.multiply(adata[:,2],1./norm) #~ p0 = [1,-1,-80,-0.5,0.1] p0 = [1,-40,3660,1./375,13./30,0] #~ p0 = [1,-0.5,1,100,1,0] pOut = leastsq(regF,p0, args=(adata[:,2],(adata[:,0],adata[:,1])),full_output=1) print pOut[0] xs = adata[:,0] ys = adata[:,1] zs = adata[:,2] nPoints = 31 xd = np.linspace(0, 300, nPoints) th = np.linspace(87, 90, nPoints) X,Y = np.meshgrid(xd, th) Z = fitF((X, Y),pOut[0]) #~ aspect = 1./(1+np.sqrt(5)/2.) fig = plt.figure(figsize=plt.figaspect(0.55)) ax = Axes3D(fig) ax.scatter(xs,ys,zs,c='y',marker='o',s=2000) ax.plot_wireframe(X, Y, Z,cmap='hot')
def plot(filename): states=[ 2, 10, 18, 26, 42, 50, 58, 74, 90, 98, 114, 122, 138, 162, 178, 194, 202, 218, 226, 242, 258, 274, 290, 298, 322, 338, 354, 370, 386, 394, 426, 442, 450, 466, 482, 498, 506, 522, 554, 570, 586, 602, 610, 634, 650, 666, 682, 698, 714, 730, 746, 754, 770, 802, 810, 842, 858, 874, 882, 914, 930, 946, 962, 978, 994, 1010, 1018, 1034, 1058, 1090, 1106, 1122, 1138, 1154, 1186, 1202, 1218, 1226, 1242, 1266, 1282, 1314, 1330, 1346, 1362, 1394, 1418, 1434, 1450, 1466, 1482, 1498, 1514, 1522, 1538, 1554, 1586, 1594, 1610, 1642, 1658, 1690, 1706, 1722, 1738, 1754, 1770, 1778, 1802, 1834, 1850, 1866, 1882, 1898, 1930, 1946, 1962, 1978, 1994, 2010, 2018, 2066, 2082, 2098, 2114, 2138, 2170, 2186, 2202, 2218, 2234, 2250, 2258, 2274, 2306, 2322, 2354, 2370, 2402, 2418, 2434, 2450, 2458, 2474, 2490, 2514, 2530, 2546, 2562, 2578, 2610, 2626, 2642, 2658, 2706, 2722, 2738, 2746, 2778, 2810, 2826, 2850, 2866, 2882, 2898, 2914, 2930, 2946, 2962, 2978, 3010, 3026, 3034, 3066, 3082, 3098, 3130, 3162, 3194, 3210, 3218, 3234, 3266, 3282, 3298, 3306, 3338, 3370, 3386, 3402, 3418, 3450, 3466, 3482, 3498, 3514, 3530, 3562, 3578, 3586, 3602, 3626, 3658, 3674, 3706, 3722, 3738, 3754, 3770, 3786, 3802, 3834, 3850, 3866, 3882, 3922, 3938, 3954, 3986, 4002, 4018, 4034] data = loadtxt(filename) l = len(data) dataStates = ones(l) for i in range(l): dataStates[i] = states[(int)(data[i,0]-1+0.1)] fig = plt.figure(figsize=plt.figaspect(1.)) ax = fig.gca() ax.set_xlabel(r'Basis size',fontsize=16) ax.set_ylabel(r'Corr. energy',fontsize=16) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(14) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14) plt.plot(dataStates[:], data[:,2],'b') #ax.set_xticks(dataStates, minor=False) #savefig('test.pdf', format='pdf') plt.show()
def show3D(): # imports specific to the plots in this example import numpy as np from matplotlib import cm from mpl_toolkits.mplot3d.axes3d import get_test_data # Twice as wide as it is tall. fig = plt.figure(figsize=plt.figaspect(0.5)) #---- First subplot ax = fig.add_subplot(1, 2, 1, projection='3d') X = np.arange(-5, 5, 0.1) Y = np.arange(-5, 5, 0.1) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False) ax.set_zlim3d(-1.01, 1.01) fig.colorbar(surf, shrink=0.5, aspect=10) #---- Second subplot ax = fig.add_subplot(1, 2, 2, projection='3d') X, Y, Z = get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) mystyle.printout_plain('3dGraph.png')
def Main(): myPoints = importPoints('points.csv', 3) # Import the Given Point Cloud C = np.array([[0,0,100]]) # View Point, which is well above the point cloud in z direction flippedPoints = sphericalFlip(myPoints, C, math.pi) # Reflect the point cloud about a sphere centered at C myHull = convexHull(flippedPoints) # Take the convex hull of the center of the sphere and the deformed point cloud # Plot fig = plt.figure(figsize = plt.figaspect(0.5)) plt.title('Cloud Points With All Points (Left) vs. Visible Points Viewed from Well Above (Right)') # First subplot ax = fig.add_subplot(1,2,1, projection = '3d') ax.scatter(myPoints[:, 0], myPoints[:, 1], myPoints[:, 2], c='r', marker='^') # Plot all points ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') # Second subplot ax = fig.add_subplot(1,2,2, projection = '3d') for vertex in myHull.vertices[:-1]: # Exclude Origin, which is the last element ax.scatter(myPoints[vertex, 0], myPoints[vertex, 1], myPoints[vertex, 2], c='b', marker='o') # Plot visible points ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') plt.show() return
def Test(): myPoints = importPoints('sphere.csv', 3) # Import the Test Point Cloud C = np.array([[0,0,10]]) # 10 is well above the peak of circle which is 1 flippedPoints = sphericalFlip(myPoints, C, math.pi) myHull = convexHull(flippedPoints) # Plot fig = plt.figure(figsize = plt.figaspect(0.5)) plt.title('Test Case With A Sphere (Left) and Visible Sphere Viewed From Well Above (Right)') # First subplot ax = fig.add_subplot(1,2,1, projection = '3d') ax.scatter(myPoints[:, 0], myPoints[:, 1], myPoints[:, 2], c='r', marker='^') # Plot all points ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') # Second subplot ax = fig.add_subplot(1,2,2, projection = '3d') for vertex in myHull.vertices[:-1]: ax.scatter(myPoints[vertex, 0], myPoints[vertex, 1], myPoints[vertex, 2], c='b', marker='o') # Plot visible points ax.set_zlim3d(-1.5, 1.5) ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') plt.show() return
def plot_surface_wire(X, Y, Z, filename='resultFigure.png', stride=1): from mpl_toolkits.mplot3d import axes3d from matplotlib import cm import matplotlib.pyplot as plt fig = plt.figure(filename.replace('.png', ''), figsize=plt.figaspect(0.5)) # surface ax = fig.add_subplot(1, 3, 1, projection='3d', title='Grey') surf = ax.plot_surface(X, Y, Z, rstride=stride, cstride=stride, cmap=cm.Greys, linewidth=0, antialiased=True) ax.view_init(elev=8., azim=-49.) fig.colorbar(surf, shrink=0.5, aspect=15) ax = fig.add_subplot(1, 3, 2, projection='3d', title='Bone') surf = ax.plot_surface(X, Y, Z, rstride=stride, cstride=stride, cmap=cm.bone, linewidth=0, antialiased=True) ax.view_init(elev=8., azim=-49.) fig.colorbar(surf, shrink=0.5, aspect=15) # wire ax = fig.add_subplot(1, 3, 3, projection='3d', title='Wireframe') wire = ax.plot_wireframe(X, Y, Z, rstride=stride, cstride=stride) ax.view_init(elev=8., azim=-49.) ## mesh #ax = fig.add_subplot(1, 4, 3, projection='3d', title='Wireframe') #wire = ax.mesh(X, Y, Z, rstride=stride, cstride=stride) # save and display plt.savefig(filename) plt.show()
def showslice2(thedata, thelabel, minval, maxval, colormap): # initialize and show a 2D slice from a dataset in greyscale plt.figure(figsize=plt.figaspect(1.0)) theshape = thedata.shape numslices = theshape[0] ysize = theshape[1] xsize = theshape[2] slicesqrt = int(np.ceil(np.sqrt(numslices))) theslice = np.zeros((ysize * slicesqrt, xsize * slicesqrt)) for i in range(numslices): ypos = int(i / slicesqrt) * ysize xpos = int(i % slicesqrt) * xsize theslice[ypos:ypos + ysize, xpos:xpos + xsize] = thedata[i, :, :] if plt.isinteractive(): plt.ioff() plt.axis('off') plt.axis('equal') plt.subplots_adjust(hspace=0.0) plt.axes([0, 0, 1, 1], frameon=False) if colormap == 0: thecmap = cm.gray else: mycmdata1 = { 'red': ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 1., 1.)), 'green': ((0., 0., 0.), (0.5, 1.0, 1.0), (1., 0., 0.)), 'blue': ((0., 0., 0.), (0.5, 1.0, 0.0), (1., 0., 0.)) } thecmap = colors.LinearSegmentedColormap('mycm', mycmdata1) plt.imshow(theslice, vmin=minval, vmax=maxval, interpolation='nearest', label=thelabel, aspect='equal', cmap=thecmap)
def draw(self): dx = rx1.max() - rx1.min() dy = ry1.max() - ry1.min() w,h = plt.figaspect(float(dy/dx)) fig = plt.figure(figsize=(w,h),frameon=False,dpi=80,facecolor='w') ax = fig.add_axes([0,0,1,1],frameon=False,axisbg='w') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) step = (struct1.max() - struct1.min()) / 256 levels = np.arange(struct1.min(),struct1.max()+step,step) clr = np.zeros((256,3)) for i in np.arange(256): clr[i,0] = i / 255.0 cmap = colors.ListedColormap(clr) #ax.contourf(rx1,ry1,struct1,levels=levels,cmap=cmap,antialiased=False) #plt.show() fig1 = plt.figure(figsize=(w,h),frameon=False,dpi=80,facecolor='w') ax = fig1.add_axes([0,0,1,1],frameon=False,axisbg='w') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.imshow(struct2) plt.show()
def plotAllTheThings(pl1,pl2,thete,lines, contourCount = 20,simbol="x",figname=""): # Twice as wide as it is tall. fig = plt.figure(figsize=plt.figaspect(0.4)) #---- First subplot ax = fig.add_subplot(1, 2, 1) X,Y,Z = pl1 for t in thete: ax.plot(t[0],t[1],simbol,color="blue") levels = np.arange(Z.min(), Z.max(), (Z.max()-Z.min())/contourCount) ax.contour(X, Y, Z,levels) ax.set_title("Konvergenca theta_0 in theta_1") #---- Second subplot a,b = pl2 a = a[1] ax = fig.add_subplot(1,2,2) ax.plot(a, b, 'o') lsp = np.linspace(a.min(),a.max(),1+a.max()-a.min()) print lsp for ll in lines: l = ll[0]+ll[1]*lsp ax.plot(lsp,l) ax.set_title("Prikaz tock z prilegajoco premico") if figname == "": plt.show() else: plt.savefig(figname)
def class_wise_roc_fnr_fpr(y_true_cw, y_score_cw): """ y_true_cw: DataFrame, [samples x classes] y_score_cw: DataFrame, [samples x classes] """ # calculate fpr/tpr per class fprs, fnrs, thresholds, eer_vals = [], [], [], [] for cname in y_true_cw: y_true = y_true_cw[cname].values y_score = y_score_cw[cname].values fpr, tpr, thresh = sk_metrics.roc_curve(y_true, y_score, drop_intermediate=True) # TODO: fix plot values # thresh = np.insert(thresh, 0, 1.) # fpr = np.insert(fpr, 0, 0.) # tpr = np.insert(tpr, 0, 0.) fnr = 1. - tpr # append for each class fprs.append(fpr) fnrs.append(fnr) thresholds.append(thresh) eer_vals.append(eer(y_true, y_score)) # plot FNR/FPR distributions fig = plt.figure(figsize=plt.figaspect(0.5)) n_row = 2 n_col = np.round(len(y_true_cw.columns) / float(n_row)) i = 1 for fnr, fpr, th, er in zip(fnrs, fprs, thresholds, eer_vals): ax = fig.add_subplot(n_row, n_col, i, frameon=True) mfom_plt.view_fnr_fpr_dist(ax, fnr, fpr, th, er) i += 1 fig.tight_layout() plt.show()
def class_wise_rocch_fnr_fpr(y_true_df, y_score_df): """ y_true_df: DataFrame, [samples x classes] y_score_df: DataFrame, [samples x classes] """ # calculate fpr/tpr per class fprs, fnrs, thresholds, eer_vals = [], [], [], [] for cname in y_true_df: y_true = y_true_df[cname].values y_score = y_score_df[cname].values fpr, tpr, thresh, y_calibr, p_calibr = sklearn_rocch(y_true, y_score) # TODO: fix plot values fnr = 1. - tpr # append for each class fprs.append(fpr) fnrs.append(fnr) thresholds.append(thresh) eer_vals.append(eer(y_true=y_calibr, y_score=p_calibr)) # plot FNR/FPR distributions fig = plt.figure(figsize=plt.figaspect(0.5)) n_row = 2 n_col = np.round(len(y_true_df.columns) / float(n_row)) i = 1 for fnr, fpr, th, er in zip(fnrs, fprs, thresholds, eer_vals): ax = fig.add_subplot(n_row, n_col, i, frameon=True) mfom_plt.view_fnr_fpr_dist(ax, fnr, fpr, th, er) i += 1 fig.tight_layout() plt.show()
def toy_score_table(p_df, y_df): fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(2, 1, 1, xticks=[], yticks=[], frameon=False) mfom_plt.colored_table(ax, vals=p_df.values, col_lab=p_df.columns, row_lab=p_df.index) ax = fig.add_subplot(2, 1, 2, xticks=[], yticks=[], frameon=False) mfom_plt.colored_table(ax, vals=y_df.values, col_lab=y_df.columns, row_lab=y_df.index) plt.show()
def plot_orbits(x, y, z): from matplotlib import pyplot, rc fig = pyplot.figure(figsize=(14,14)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) font = {'size' : 30} rc('font', **font) pyplot.figaspect(1.0) pyplot.scatter(x[0].value_in(units.AU), y[0].value_in(units.AU), 200, lw=0) pyplot.plot(x.value_in(units.AU), y.value_in(units.AU), lw=2) pyplot.xlabel("$X [AU]$") pyplot.ylabel("$Y [AU]$") pyplot.xlim(-10000, 10000) pyplot.ylim(-10000, 10000) # pyplot.show() pyplot.savefig("SStars_1Jan2001_orbits")
def plotAll(self): """ Make a plot overlaying L1, L2, EF PS, and the total PS. """ #total = [max([x*y*z,-1]) for x,y,z in zip(self.L1PS, self.L2PS, self.EFPS)] total = self.TotalPS #Make a new canvas, twice as long as it is wide w,h = plt.figaspect(0.4) fig = plt.figure(figsize=(w*1.,h*1.)) #Set the plotting area ax = fig.add_axes([0.1, 0.47, 0.85, 0.42]) ax.plot(self.Lumi , self.L1PS , self.styles[0] , color=self.colors[0] , linewidth=self.widths[0] , label=self.L1Name) ax.plot(self.Lumi , self.L2PS , self.styles[1] , color=self.colors[1] , linewidth=self.widths[1] , label=self.L2Name) ax.plot(self.Lumi , self.EFPS , self.styles[2] , color=self.colors[2] , linewidth=self.widths[2] , label=self.EFName) ax.plot(self.Lumi , total , self.styles[3] , color=self.colors[3] , linewidth=self.widths[3] , label='Total' ) #Set the label text plt.ylabel(self.ytitle) maxL1 = max(self.L1PS) maxL2 = max(self.L2PS) maxEF = max(self.EFPS) maxT = max(total) #Set the x axis range, and tick points axis = [0, max(self.Lumi) + 1000, -10, max(maxL1, maxL2, maxEF, maxT)*1.1] plt.axis(axis) plt.xticks(self.Lumi) #Turn on the grid marks plt.grid(True) #Put the legend above the plot plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, mode="expand", borderaxespad=0.) ax_log = fig.add_axes([0.1, 0.05, 0.85, 0.42]) ax_log.plot(self.Lumi , self.L1PS , self.styles[0] , color=self.colors[0] , linewidth=self.widths[0] , label=self.L1Name) ax_log.plot(self.Lumi , self.L2PS , self.styles[1] , color=self.colors[1] , linewidth=self.widths[1] , label=self.L2Name) ax_log.plot(self.Lumi , self.EFPS , self.styles[2] , color=self.colors[2] , linewidth=self.widths[2] , label=self.EFName) ax_log.plot(self.Lumi , total , self.styles[3] , color=self.colors[3] , linewidth=self.widths[3] , label='Total' ) #Set the label text plt.xlabel(self.xtitle) plt.ylabel(self.ytitle) plt.yscale('log') #Set the x axis range, and tick points axis = [0, max(self.Lumi) + 1000, 0.5, max(total)*2] plt.axis(axis) plt.xticks(self.Lumi) #Turn on the grid marks plt.grid(True) #Print the plot to screen plt.show()
def actividad(self): fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(1, 1, 1, projection='3d') surf = ax.plot_surface(self.X, self.Y,self.SOL[:,:,8],cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title("actividad") plt.show()
def general_plot(self, y, x, t, title=" "): X, Y = np.meshgrid(x, t) fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.add_subplot(1, 1, 1, projection='3d') surf = ax.plot_surface(X, Y, y,cmap=cm.coolwarm) plt.xlabel("longitud (m)") plt.ylabel("tiempo (horas)") plt.title(title) plt.show()
def interpimshow(lines=[],savename='temp', loaddata=0, limits=[],datafolder='figs'): ''' Plot conditioning surfaces and save data Input: lines : (N*4,1) vector of conditioning suface points savename : name for saving .png and .npy files Output: Multiple figures, and npy data, into './figs' ''' if(loaddata==0): ## IF FIRST RUN ## CONVERT LINES LIST TO 2D ARRAY l = np.size(np.asarray(lines))/4 lines = np.reshape(np.asarray(lines).T,(-1,4),order='F') print('num lines : %d'%l) ## CONVERT OUTPUT DATA TO N-BY-4 ARRAY, GET LIMITS nfas = np.zeros((len(lines),)) lengths,angles,widths = np.copy(nfas),np.copy(nfas),np.copy(nfas); for k in range(0,len(lines)): lengths[k] = lines[k,0] angles[k] = lines[k,1] widths[k] = lines[k,2] nfas[k] = lines[k,3] lims = np.array([[np.min(lengths),np.max(lengths)],[np.min(angles),np.max(angles)],[np.min(widths),np.max(widths)]]) else: ## IF RELOADING ## LOAD DATA loaddata = np.load("%s/data_%s.npy"%(datafolder,savename)) lengths,angles,widths,nfas = loaddata[0],loaddata[1],loaddata[2],loaddata[3] lims = limits ## PLOT 3D SCATTER (COLOR AS 4TH DIMENSION FOR NFA VALUE) title='Test: %s'%savename fig=plt.figure() ax=fig.gca(projection='3d') p=ax.scatter3D(lengths,angles,widths,c=nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('length'); ax.set_ylabel('angle'); ax.set_zlabel('width'); cbar = fig.colorbar(p) cbar.ax.set_ylabel('conditional probability') plt.savefig('figs/3D_%s.png'%savename) ## PLOT 2D SCATTER PROJECTIONS (COLOR AS NFA VALUE) fig=plt.figure(figsize=plt.figaspect(1./3.)) ax = fig.add_subplot(1,3,1) ax.set_xlim(lims[0,0],lims[0,1]); ax.set_ylim(lims[1,0],lims[1,1]); ax.scatter(lengths,angles,c=nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('lenth'); ax.set_ylabel('angle') ax = fig.add_subplot(1,3,2) ax.set_xlim(lims[0,0],lims[0,1]); ax.set_ylim(lims[2,0],lims[2,1]); ax.scatter(lengths,widths,c=nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('lenth'); ax.set_ylabel('width') ax = fig.add_subplot(1,3,3) ax.set_xlim(lims[1,0],lims[1,1]); ax.set_ylim(lims[2,0],lims[2,1]); p=ax.scatter(angles,widths,c=nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('angle'); ax.set_ylabel('width') cbar=fig.colorbar(p) cbar.ax.set_ylabel('conditional probability') plt.savefig('figs/2D_%s.png'%savename) ## PLOT 2D PROJECTIONS AS 3D TRIANGULAR MESH SURFACES fig=plt.figure(figsize=plt.figaspect(1./3.)) ax = fig.add_subplot(1,3,1,projection='3d') ax.set_xlim(lims[0,0],lims[0,1]); ax.set_ylim(lims[1,0],lims[1,1]);ax.set_zlim(0,1); ax.plot_trisurf(lengths,angles,nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('lenth'); ax.set_ylabel('angle') ax = fig.add_subplot(1,3,2,projection='3d') ax.set_xlim(lims[0,0],lims[0,1]); ax.set_ylim(lims[2,0],lims[2,1]);ax.set_zlim(0,1); ax.plot_trisurf(lengths,widths,nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('lenth'); ax.set_ylabel('width') ax = fig.add_subplot(1,3,3,projection='3d') ax.set_xlim(lims[1,0],lims[1,1]); ax.set_ylim(lims[2,0],lims[2,1]);ax.set_zlim(0,1); p=ax.plot_trisurf(angles,widths,nfas,cmap='viridis') ax.set_title(title); ax.set_xlabel('angle'); ax.set_ylabel('width') cbar=fig.colorbar(p) cbar.ax.set_ylabel('conditional probability') plt.savefig('figs/surf_%s.png'%savename) ## SAVE DATA TABLES if(loaddata==0): savedata = np.array([lengths,angles,widths,nfas]) np.save('figs/data_%s'%savename,savedata)
def plot_positions(particles, timestep): fig = plt.figure(figsize=plt.figaspect(0.5)) # Front view ax = fig.add_subplot(1, 2, 1, projection='3d') ax.set_title("Front View") ax.set_xlabel("X - Longitude") ax.set_ylabel("Y - Depth") ax.set_zlabel("Z - Latitude") ax.set_yticks([]) ax.set_xlim(0, 13.6) ax.set_ylim(0, 2.8) ax.set_zlim(0, 13.6) ax.view_init(elev=5, azim=275) # Plot 3D H outline alpha = 0.2 p1 = Rectangle([0, 0], 2.8, 13.6, alpha=alpha) p2 = Rectangle([2.8, 4.8], 8, 4, alpha=alpha) p3 = Rectangle([10.8, 0], 2.6, 13.6, alpha=alpha) p1_z = Rectangle([0, 0], 2.8, 13.6, alpha=alpha) p2_z = Rectangle([2.8, 4.8], 8, 4, alpha=alpha) p3_z = Rectangle([10.8, 0], 2.6, 13.6, alpha=alpha) p_top = Rectangle([2.8, 0], 8, 2.8, alpha=alpha) p_bottom = Rectangle([2.8, 0], 8, 2.8, alpha=alpha) ax.add_patch(p1) ax.add_patch(p2) ax.add_patch(p3) ax.add_patch(p1_z) ax.add_patch(p2_z) ax.add_patch(p3_z) ax.add_patch(p_top) ax.add_patch(p_bottom) art3d.pathpatch_2d_to_3d(p1, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p2, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p3, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p1_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p2_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p3_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p_top, z=4.8, zdir="z") art3d.pathpatch_2d_to_3d(p_bottom, z=8.8, zdir="z") # Plot particles for particle in particles: if not np.ma.is_masked(nc.variables["lon"][particle]): x = nc.variables["lon"][particle][timestep] y = nc.variables["z"][particle][timestep] z = nc.variables["lat"][particle][timestep] plot = ax.scatter(x, y, z, 'o-', c='r', s=0.3, alpha=0.1) # Side view ax = fig.add_subplot(1, 2, 2, projection='3d') ax.set_title("Side View") ax.set_xlabel("X - Longitude") ax.set_ylabel("Y - Depth") ax.set_zlabel("Z - Latitude") ax.set_xticks([]) ax.set_xlim(0, 13.6) ax.set_ylim(0, 2.8) ax.set_zlim(0, 13.6) ax.view_init(elev=5, azim=5) # Plot 3D H outline alpha = 0.2 p1 = Rectangle([0, 0], 2.8, 13.6, alpha=alpha) p2 = Rectangle([2.8, 4.8], 8, 4, alpha=alpha) p3 = Rectangle([10.8, 0], 2.6, 13.6, alpha=alpha) p1_z = Rectangle([0, 0], 2.8, 13.6, alpha=alpha) p2_z = Rectangle([2.8, 4.8], 8, 4, alpha=alpha) p3_z = Rectangle([10.8, 0], 2.6, 13.6, alpha=alpha) p_top = Rectangle([2.8, 0], 8, 2.8, alpha=alpha) p_bottom = Rectangle([2.8, 0], 8, 2.8, alpha=alpha) ax.add_patch(p1) ax.add_patch(p2) ax.add_patch(p3) ax.add_patch(p1_z) ax.add_patch(p2_z) ax.add_patch(p3_z) ax.add_patch(p_top) ax.add_patch(p_bottom) art3d.pathpatch_2d_to_3d(p1, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p2, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p3, z=0, zdir="y") art3d.pathpatch_2d_to_3d(p1_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p2_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p3_z, z=2.8, zdir="y") art3d.pathpatch_2d_to_3d(p_top, z=4.8, zdir="z") art3d.pathpatch_2d_to_3d(p_bottom, z=8.8, zdir="z") # Plot particles for particle in particles: if not np.ma.is_masked(nc.variables["lon"][particle]): x = nc.variables["lon"][particle][timestep] y = nc.variables["z"][particle][timestep] z = nc.variables["lat"][particle][timestep] plot = ax.scatter(x, y, z, 'o-', c='r', s=0.3, alpha=0.1) plt.savefig( "/media/alexander/DATA/Ubuntu/Miniproject/ParcelsDrake/outputs/H_3D/Hhigh/particlespot/offline/0Ti_960Tf_0.5dt_0.01mu_70000particles/durham_sim/img/" + "%05.0f" % timestep + ".png") plt.close()
return (g, nodes_dict) s = Snooki() g = create_graph(s.m_chain) nodes_dict = g[1] g = g[0] root = Tk.Tk() root.wm_title("Markov Chain") root.wm_protocol('WM_DELETE_WINDOW', root.quit()) pos = nx.circular_layout(g) w, h = plt.figaspect(1) f = plt.figure(figsize=(w, h)) a = f.add_subplot(111) plt.axis('off') nx.draw_networkx(g, pos=pos, ax=a) xlim = a.get_xlim() ylim = a.get_ylim() canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def next(node): a.cla()
prob = np.zeros(len(pairs)) for i in range(len(pairs)): prob[i] = sum(pair_found <= i) prob1 = prob * 1.0 / total_run num_pairs1 = range(1,len(pairs)+1) with open('RB500Struct.pickle', 'rb') as handle: [pairs, pair_found, total_key_find_good] = pickle.load(handle) prob = np.zeros(len(pairs)) for i in range(len(pairs)): prob[i] = sum(pair_found <= i) prob2 = prob * 1.0 / total_run num_pairs2 = range(1,len(pairs)+1) w, h = plt.figaspect(0.5) plt.figure(figsize=(w, h)) plt.plot(num_pairs1, prob1, 'b-', label='i.i.d pairs') plt.plot(num_pairs2, prob2, 'r--', label='structured pairs') plt.legend(loc='upper left') plt.ylabel('Attack Success Probability') plt.xlabel('Number of Plaintext Pairs') plt.savefig('RB.png', dpi=600, format='png') plt.show()
import matplotlib.pyplot as plt import matplotlib.lines as mlines import numpy as np # Data for plotting t = np.arange(0.0, 1.01, 0.01) x = t * 2 - 1 c = np.abs(x) fig, ax = plt.subplots(figsize=plt.figaspect(.5)) plt.autoscale(tight=True) ax.plot(x, c) lines = [ mlines.Line2D([-1,0],[1,0], color='r', linestyle='-', marker='x'),\ mlines.Line2D([0,1],[0,1], color='r', linestyle='-', marker='x')] for l in lines: ax.add_line(l) ax.set(xlabel='x', ylabel='y') ax.grid() plt.axis('scaled') fig.savefig("figures/plot_abs_function_n3.svg") plt.show()
def inference( output_dir: str, batch_size: int, dtype: str, ngpu: int, seed: int, num_workers: int, log_level: Union[int, str], data_path_and_name_and_type: Sequence[Tuple[str, str, str]], key_file: Optional[str], train_config: Optional[str], model_file: Optional[str], threshold: float, minlenratio: float, maxlenratio: float, use_teacher_forcing: bool, use_att_constraint: bool, backward_window: int, forward_window: int, speed_control_alpha: float, allow_variable_data_keys: bool, vocoder_conf: dict, ): """Perform TTS model decoding.""" assert check_argument_types() if batch_size > 1: raise NotImplementedError("batch decoding is not implemented") if ngpu > 1: raise NotImplementedError("only single GPU decoding is supported") logging.basicConfig( level=log_level, format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s", ) if ngpu >= 1: device = "cuda" else: device = "cpu" # 1. Set random-seed set_all_random_seed(seed) # 2. Build model text2speech = Text2Speech( train_config=train_config, model_file=model_file, threshold=threshold, maxlenratio=maxlenratio, minlenratio=minlenratio, use_teacher_forcing=use_teacher_forcing, use_att_constraint=use_att_constraint, backward_window=backward_window, forward_window=forward_window, speed_control_alpha=speed_control_alpha, vocoder_conf=vocoder_conf, dtype=dtype, device=device, ) # 3. Build data-iterator if not text2speech.use_speech: data_path_and_name_and_type = list( filter(lambda x: x[1] != "speech", data_path_and_name_and_type) ) loader = TTSTask.build_streaming_iterator( data_path_and_name_and_type, dtype=dtype, batch_size=batch_size, key_file=key_file, num_workers=num_workers, preprocess_fn=TTSTask.build_preprocess_fn(text2speech.train_args, False), collate_fn=TTSTask.build_collate_fn(text2speech.train_args, False), allow_variable_data_keys=allow_variable_data_keys, inference=True, ) # 6. Start for-loop output_dir = Path(output_dir) (output_dir / "norm").mkdir(parents=True, exist_ok=True) (output_dir / "denorm").mkdir(parents=True, exist_ok=True) (output_dir / "speech_shape").mkdir(parents=True, exist_ok=True) (output_dir / "wav").mkdir(parents=True, exist_ok=True) (output_dir / "att_ws").mkdir(parents=True, exist_ok=True) (output_dir / "probs").mkdir(parents=True, exist_ok=True) (output_dir / "durations").mkdir(parents=True, exist_ok=True) (output_dir / "focus_rates").mkdir(parents=True, exist_ok=True) # Lazy load to avoid the backend error matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator with NpyScpWriter( output_dir / "norm", output_dir / "norm/feats.scp", ) as norm_writer, NpyScpWriter( output_dir / "denorm", output_dir / "denorm/feats.scp" ) as denorm_writer, open( output_dir / "speech_shape/speech_shape", "w" ) as shape_writer, open( output_dir / "durations/durations", "w" ) as duration_writer, open( output_dir / "focus_rates/focus_rates", "w" ) as focus_rate_writer: for idx, (keys, batch) in enumerate(loader, 1): assert isinstance(batch, dict), type(batch) assert all(isinstance(s, str) for s in keys), keys _bs = len(next(iter(batch.values()))) assert _bs == 1, _bs # Change to single sequence and remove *_length # because inference() requires 1-seq, not mini-batch. batch = {k: v[0] for k, v in batch.items() if not k.endswith("_lengths")} start_time = time.perf_counter() wav, outs, outs_denorm, probs, att_ws, duration, focus_rate = text2speech( **batch ) key = keys[0] insize = next(iter(batch.values())).size(0) + 1 logging.info( "inference speed = {:.1f} frames / sec.".format( int(outs.size(0)) / (time.perf_counter() - start_time) ) ) logging.info(f"{key} (size:{insize}->{outs.size(0)})") if outs.size(0) == insize * maxlenratio: logging.warning(f"output length reaches maximum length ({key}).") norm_writer[key] = outs.cpu().numpy() shape_writer.write(f"{key} " + ",".join(map(str, outs.shape)) + "\n") denorm_writer[key] = outs_denorm.cpu().numpy() if duration is not None: # Save duration and fucus rates duration_writer.write( f"{key} " + " ".join(map(str, duration.cpu().numpy())) + "\n" ) focus_rate_writer.write(f"{key} {float(focus_rate):.5f}\n") # Plot attention weight att_ws = att_ws.cpu().numpy() if att_ws.ndim == 2: att_ws = att_ws[None][None] elif att_ws.ndim != 4: raise RuntimeError(f"Must be 2 or 4 dimension: {att_ws.ndim}") w, h = plt.figaspect(att_ws.shape[0] / att_ws.shape[1]) fig = plt.Figure( figsize=( w * 1.3 * min(att_ws.shape[0], 2.5), h * 1.3 * min(att_ws.shape[1], 2.5), ) ) fig.suptitle(f"{key}") axes = fig.subplots(att_ws.shape[0], att_ws.shape[1]) if len(att_ws) == 1: axes = [[axes]] for ax, att_w in zip(axes, att_ws): for ax_, att_w_ in zip(ax, att_w): ax_.imshow(att_w_.astype(np.float32), aspect="auto") ax_.set_xlabel("Input") ax_.set_ylabel("Output") ax_.xaxis.set_major_locator(MaxNLocator(integer=True)) ax_.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.set_tight_layout({"rect": [0, 0.03, 1, 0.95]}) fig.savefig(output_dir / f"att_ws/{key}.png") fig.clf() if probs is not None: # Plot stop token prediction probs = probs.cpu().numpy() fig = plt.Figure() ax = fig.add_subplot(1, 1, 1) ax.plot(probs) ax.set_title(f"{key}") ax.set_xlabel("Output") ax.set_ylabel("Stop probability") ax.set_ylim(0, 1) ax.grid(which="both") fig.set_tight_layout(True) fig.savefig(output_dir / f"probs/{key}.png") fig.clf() # TODO(kamo): Write scp if wav is not None: sf.write( f"{output_dir}/wav/{key}.wav", wav.numpy(), text2speech.fs, "PCM_16" ) # remove duration related files if attention is not provided if att_ws is None: shutil.rmtree(output_dir / "att_ws") shutil.rmtree(output_dir / "durations") shutil.rmtree(output_dir / "focus_rates") if probs is None: shutil.rmtree(output_dir / "probs")
run = True done = 0 all_nodes = NodeSet() nodes_ip4s = {} nodes_ip6s = {} lats = [] lons = [] cities = [] xys = [] colors = [] all_lines = [] points = [] not_found = [] plt.ion() plt.figaspect(2.) fig, axes = plt.subplots(2, 1) #fig.set_size_inches(8,16,forward=True) fig.tight_layout() fig.canvas.set_window_title('OpenDHT scanner') mpx = axes[0] mpx.set_title("Node GeoIP") m = Basemap(projection='robin', resolution='l', area_thresh=1000.0, lat_0=0, lon_0=0, ax=mpx)
def plot_ramachandran(rama_analysis, label: str, output_file: str): fig, ax = plt.subplots(figsize=plt.figaspect(1)) rama_analysis.plot(ax=ax, color='k', marker='o', s=5, ref=True) #fig.title(label) fig.tight_layout() fig.savefig(output_file)
def plotSwarm(x, net, prob, nt, sPath, sTitle="", approach='ocflow'): """plot images of swarm problem""" nex = x.shape[0] d = x.shape[1] xtarget = prob.xtarget.detach().cpu().numpy() msz = 3 # markersize if approach == 'ocflow': traj, trajCtrl = OCflow(x, net, prob, tspan=[0.0, 1.0], nt=nt, stepper="rk4", alph=net.alph, intermediates=True) # 3-d plot bounds xbounds = [ min(x[:, 0::3].min().item(), xtarget[0::3].min().item()) - 1, max(x[:, 0::3].max().item(), xtarget[0::3].max().item()) + 1 ] ybounds = [ min(x[:, 1::3].min().item(), xtarget[1::3].min().item()) - 1, max(x[:, 1::3].max().item(), xtarget[1::3].max().item()) + 1 ] zbounds = [ min(x[:, 2::3].min().item(), xtarget[2::3].min().item()) - 1, max(x[:, 2::3].max().item(), xtarget[2::3].max().item()) + 1 ] xls = torch.linspace(*xbounds, 50) yls = torch.linspace(*ybounds, 50) gridPts = torch.stack(torch.meshgrid(xls, yls)).to(x.dtype).to(x.device) gridShape = gridPts.shape[1:] gridPts = gridPts.reshape(2, -1).t() # setup example initial z z0 = pad(gridPts, [0, 1, 0, 0], value=-1.5) z0 = pad(z0, [0, 1, 0, 0], value=0.0) # make grid of subplots nCol = 3 nRow = 2 fig = plt.figure(figsize=plt.figaspect(1.0)) fig.set_size_inches(17, 10) # (14,10) fig.suptitle(sTitle) # positional movement/trajectory for place in [1, 4, 5]: # plot multiple angles of it ax = fig.add_subplot(nRow, nCol, place, projection='3d') ax.set_title('Flight Path') if prob.obstacle == 'blocks': shade = 0.4 # block 1 X, Y = np.meshgrid([-2, 2], [-0.5, 0.5]) ax.plot_surface(X, Y, 7 * np.ones((2, 2)), alpha=shade, color='gray') ax.plot_surface(X, Y, 0 * np.ones((2, 2)), alpha=shade, color='gray') X, Z = np.meshgrid([-2, 2], [0, 7]) ax.plot_surface(X, -0.5 * np.ones((2, 2)), Z, alpha=shade, color='gray') ax.plot_surface(X, 0.5 * np.ones((2, 2)), Z, alpha=shade, color='gray') Y, Z = np.meshgrid([-0.5, 0.5], [0, 7]) ax.plot_surface(-2 * np.ones((2, 2)), Y, Z, alpha=shade, color='gray') ax.plot_surface(2 * np.ones((2, 2)), Y, Z, alpha=shade, color='gray') # block 2 X, Y = np.meshgrid([2, 4], [-1, 1]) ax.plot_surface(X, Y, 4 * np.ones((2, 2)), alpha=shade, color='gray') ax.plot_surface(X, Y, 0 * np.ones((2, 2)), alpha=shade, color='gray') X, Z = np.meshgrid([2, 4], [0, 4]) ax.plot_surface(X, -1 * np.ones((2, 2)), Z, alpha=shade, color='gray') ax.plot_surface(X, 1 * np.ones((2, 2)), Z, alpha=shade, color='gray') Y, Z = np.meshgrid([-1, 1], [0, 4]) ax.plot_surface(2 * np.ones((2, 2)), Y, Z, alpha=shade, color='gray') ax.plot_surface(4 * np.ones((2, 2)), Y, Z, alpha=shade, color='gray') for j in range(prob.nAgents): # ax.plot(traj[0, 3*j , :].view(-1).cpu().numpy(), # traj[0, 3*j+1, :].view(-1).cpu().numpy(), # traj[0, 3*j+2, :].view(-1).cpu().numpy(), 'o-', linewidth=2, markersize=msz) # ax.scatter(xtarget[3*j ], # xtarget[3*j+1], # xtarget[3*j+2], s=140, marker='x', c='r', label="target") ax.plot(traj[0, 3 * j, :].view(-1).cpu().numpy(), traj[0, 3 * j + 1, :].view(-1).cpu().numpy(), traj[0, 3 * j + 2, :].view(-1).cpu().numpy(), linewidth=2) ax.scatter(xtarget[3 * j], xtarget[3 * j + 1], xtarget[3 * j + 2], s=20, marker='x', c='r', label="target") if place == 1: ax.view_init(60, -30) # ax.view_init(10, -30) elif place == 4: ax.view_init(20, -5) # ax.view_init(-10, 270) else: ax.view_init(25, 190) # ax.legend() ax.set_xlim(*xbounds) ax.set_ylim(*ybounds) ax.set_zlim(*zbounds) # make the panes transparent ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # make the grid lines transparent ax.xaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) ax.yaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) ax.zaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) # plotting path from eagle view ax = fig.add_subplot(nRow, nCol, 2) # traj is nex by d+1 by nt+1 for j in range(prob.nAgents): ax.plot(traj[0, 3 * j, :].cpu().numpy(), traj[0, 3 * j + 1, :].cpu().numpy(), linewidth=2) circ = matplotlib.patches.Circle( (traj[0, 3 * j, -1], traj[0, 3 * j + 1, -1]), radius=prob.r, fill=False, color='m') ax.add_patch(circ) ax.scatter(xtarget[3 * j], xtarget[3 * j + 1], marker='x', color='red') if prob.obstacle == 'hardcorridor' or 'blocks' or 'cylinders': tmp = z0[:, 0:3] tmp[:, 2] = 1.0 # where altitude z = 1.0 Qgrid = prob.calcObstacle(tmp) im = ax.imshow(Qgrid.reshape(gridShape).t().detach().cpu().numpy(), extent=[*xbounds, *ybounds], origin='lower') # fig.colorbar(im, ax=ax) ax.set_xlim(*xbounds) ax.set_ylim(*ybounds) ax.set_aspect('equal') ax.set_title('Path From Bird View') # plotting path from eagle view ax = fig.add_subplot(nRow, nCol, 3) # traj is nex by d+1 by nt+1 for j in range(prob.nAgents): ax.plot(traj[0, 3 * j, :].cpu().numpy(), traj[0, 3 * j + 2, :].cpu().numpy(), linewidth=2) circ = matplotlib.patches.Circle( (traj[0, 3 * j, -1], traj[0, 3 * j + 2, -1]), radius=prob.r, fill=False, color='m') ax.add_patch(circ) ax.scatter(xtarget[3 * j], xtarget[3 * j + 2], marker='x', color='red') if prob.obstacle == 'hardcorridor' or 'blocks' or 'cylinders': xls = torch.linspace(*xbounds, 50) zls = torch.linspace(*zbounds, 50) gridPts = torch.stack(torch.meshgrid(xls, zls)).to(x.dtype).to(x.device) gridShape = gridPts.shape[1:] gridPts = gridPts.reshape(2, -1).t() # setup example initial z z0 = pad(gridPts, [0, 1, 0, 0], value=-1.5) z0 = pad(z0, [0, 1, 0, 0], value=0.0) tmp = torch.zeros(gridPts.shape[0], gridPts.shape[1] + 1, device=x.device, dtype=x.dtype) tmp[:, 0] = gridPts[:, 0] tmp[:, 1] = 0.0 * gridPts[:, 0] # fix y=0.0 tmp[:, 2] = gridPts[:, 1] Qgrid = prob.calcObstacle(tmp) im = ax.imshow(Qgrid.reshape(gridShape).t().detach().cpu().numpy(), extent=[*xbounds, *zbounds], origin='lower') # fig.colorbar(im, ax=ax) ax.set_xlim(*xbounds) ax.set_ylim(*zbounds) ax.set_aspect('equal') ax.set_title('Path From Side View') if not os.path.exists(os.path.dirname(sPath)): os.makedirs(os.path.dirname(sPath)) plt.savefig(sPath, dpi=300) plt.close()
def solution(self): # input variables rho = self.rho bc_input = self.bc_input # Other variables/constants mu = self.mu lambda_ = self.lambda_ g = 9.81 # Create mesh and define function space mesh = self.mainMesh V = VectorFunctionSpace(mesh, 'P', 1) # Define boundary conditions tol = 1E-14 def clamped_left(x, on_boundary): return on_boundary and x[0] < tol def clamped_right(x, on_boundary): return on_boundary and near(x[0], self.length, tol) #defining rotating boundary functions def all_boundary(x, on_boundary): return on_boundary def yaxis(x, on_boundary): return on_boundary and near(x[1], 0, tol) def pinned_right(x, on_boundary): return on_boundary and near(x[2], 0, tol) and near( x[0], self.length, tol) def pinned_left(x, on_boundary): return on_boundary and near(x[2], 0, tol) and near(x[0], 0, tol) if bc_input == "clamped free": bc = DirichletBC(V, Constant((0, 0, 0)), clamped_left) elif bc_input == "clamped clamped": bc1 = DirichletBC(V, Constant((0, 0, 0)), clamped_left) bc2 = DirichletBC(V, Constant((0, 0, 0)), clamped_right) bc = [bc1, bc2] elif bc_input == "clamped pinned": bc1 = DirichletBC(V, Constant((0, 0, 0)), clamped_left) bc2 = DirichletBC(V, Constant((0, 0, 0)), pinned_right) bc = [bc1, bc2] elif bc_input == "pinned pinned": bc1 = DirichletBC(V, Constant((0, 0, 0)), pinned_left) bc2 = DirichletBC(V, Constant((0, 0, 0)), pinned_right) bc = [bc1, bc2] # Define strain and stress def epsilon(u): return 0.5 * (nabla_grad(u) + nabla_grad(u).T) #return sym(nabla_grad(u)) def sigma(u): return lambda_ * nabla_div(u) * Identity(d) + 2 * mu * epsilon(u) # Define variational problem u = TrialFunction(V) d = u.geometric_dimension() # space dimension v = TestFunction(V) T = Constant((0, 0, 0)) a = inner(sigma(u), epsilon(v)) * dx # Apply uniform load if called for if bool(self.load_input) and self.load_input.type == 'uniform': u_l = self.load_input.body_force f = Constant((0 + u_l[0], 0 + u_l[1], -rho * g + u_l[2])) else: f = Constant((0, 0, -rho * g)) # Apply point load if called for if bool(self.load_input) and self.load_input.type == 'point': p_l = self.load_input delta = Delta(eps=scale(p_l.direction), x0=p_l.location, degree=5) L = dot(f, v) * dx + dot(T, v) * ds + inner( Constant(p_l.magnitude) * delta, v) * dx else: L = dot(f, v) * dx + dot(T, v) * ds # Compute solution u = Function(V) solve(a == L, u, bc) s = sigma(u) - (1. / 3) * tr(sigma(u)) * Identity( d) # deviatoric stress von_Mises = sqrt(3. / 2 * inner(s, s)) V = FunctionSpace(mesh, 'P', 1) von_Mises = project(von_Mises, V) # Compute magnitude of displacement u_magnitude = sqrt(dot(u, u)) u_magnitude = project(u_magnitude, V) # Important data outputs coordinates = V.tabulate_dof_coordinates().reshape( (-1, mesh.geometry().dim())) # Displacement magnitudes um_plot = u_magnitude.vector()[:] # Displacement vectors uv_plot = np.reshape(u.vector()[:], (np.shape(coordinates))) # Stress magnitudes vm_plot = von_Mises.vector()[:] #Plotting: #xyz coordinates x_plot3d = coordinates[:, 0] y_plot3d = coordinates[:, 1] z_plot3d = coordinates[:, 2] #Change in xyz coordinates u_vec_i = uv_plot[:, 0] u_vec_j = uv_plot[:, 1] u_vec_k = uv_plot[:, 2] #Scale factor for displaying change in coordinates scaling = (z_plot3d.max() - z_plot3d.min()) / abs(um_plot).max() #Deformed xyz coordinates x_plot_def = x_plot3d + scaling * u_vec_i y_plot_def = y_plot3d + scaling * u_vec_j z_plot_def = z_plot3d + scaling * u_vec_k #Finding where deformation and stress are each at a maximum loc_u_max = [] um_plot_max = [] loc_vm_max = [] vm_plot_max = [] for i in range(um_plot.size): if um_plot[i] == um_plot.max(): um_plot_max.append(um_plot.max()) loc_u_max = list(coordinates[i]) if vm_plot[i] == vm_plot.max(): vm_plot_max.append(vm_plot.max()) loc_vm_max = list(coordinates[i]) #Convert to numpy arrays for plotting um_plot_max = np.array(um_plot_max) vm_plot_max = np.array(vm_plot_max) #Plot Results #%matplotlib auto #Uncomment to set backend if ipy file fig = plt.figure(figsize=plt.figaspect(1.8)) fig.tight_layout() cmap = plt.get_cmap('jet') #Plotting displacement ax_uv = fig.add_subplot(2, 1, 1, projection='3d') im_um = ax_uv.scatter(x_plot_def, y_plot_def, z_plot_def, c=um_plot.ravel(), cmap=cmap) fig.colorbar(im_um, ax=ax_uv, format='%.0E') ax_uv.auto_scale_xyz([0, self.length], [-self.length / 2, self.length / 2], [-self.length / 2, self.length / 2]) ax_uv.set_title( 'Displacement (m)\nVisual Deflection = {:.3E}:1'.format(scaling)) ax_uv.set_xlabel('x (m)') ax_uv.set_ylabel('y (m)') ax_uv.set_zlabel('z (m)') label_uv = 'u = {:.3E}m at ({:.1f}, {:.1f}, {:.1f})m'.format( um_plot.max(), loc_u_max[0], loc_u_max[1], loc_u_max[2]) ax_uv.text(-self.length / 2, -self.length, -self.length / 4, label_uv) #Plotting von Mises stress ax_vm = fig.add_subplot(2, 1, 2, projection='3d') im_vm = ax_vm.scatter(x_plot_def, y_plot_def, z_plot_def, c=vm_plot.ravel(), cmap=cmap) ax_vm.auto_scale_xyz([0, self.length], [-self.length / 2, self.length / 2], [-self.length / 2, self.length / 2]) fig.colorbar(im_vm, ax=ax_vm, format='%.0E') ax_vm.set_title( 'von Mises Stress (Pa)\nVisual Deflection = {:.3E}:1'.format( scaling)) ax_vm.set_xlabel('x (m)') ax_vm.set_ylabel('y (m)') ax_vm.set_zlabel('z (m)') label_vm = 'sigma = {:.3E}Pa at ({:.1f}, {:.1f}, {:.1f})m'.format( vm_plot.max(), loc_vm_max[0], loc_vm_max[1], loc_vm_max[2]) ax_vm.text(-self.length / 2, -self.length, -self.length / 4, label_vm) label_sf = 'SF = {:.1f} at ({:.1f}, {:.1f}, {:.1f})m'.format( self.E / vm_plot.max(), loc_vm_max[0], loc_vm_max[1], loc_vm_max[2]) ax_vm.text(-self.length / 2, -self.length, -self.length / 2, label_sf) plt.show() return { 'Coordinates': coordinates, 'Displacement Magnitudes': um_plot, 'Displacement Vectors': uv_plot, 'Stress Magnitudes': vm_plot }
l = 3 nplots = 2 * l + 2 nrows = int(np.sqrt(nplots)) ncolumns = int(nplots / nrows) if (ncolumns * nrows < nplots): nrows = nrows + 1 if (ncolumns - nrows > 1): nrows = nrows + 1 ncolumns = ncolumns - 1 print(nplots, nrows, ncolumns) # Set the aspect ratio to 1 so our sphere looks spherical fig = plt.figure(figsize=plt.figaspect(1.)) for m in range(-l, l + 1): fcolors = sph_harm(m, l, phi, theta).real * sph_harm( m, l, phi, theta).real + sph_harm(m, l, phi, theta).imag * sph_harm( m, l, phi, theta).imag fmax, fmin = fcolors.max(), fcolors.min() fcolors = (fcolors - fmin) / (fmax - fmin) ax = plt.subplot(nrows, ncolumns, m + l + 1, projection='3d') ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(fcolors))
mp.clf() #figure 5 covar = cv.SE #Covariance matrix to be used x_training = np.array([0.1, 0.31, 0.35, 0.5, 0.9, 1.1]) x_grid = np.arange(-10,10.05,0.05) x_test = 1.4 sigma = 0.1 y = func(x_training,sigma,seed=23) f = func(x_grid,0) hypdict = {'hyp':[0,0],'mean':0,'sigma':sigma} f_test,f_test_sigma,fcovar,alpha,nlml = gp.gp(hypdict,cv.SE,x_training,y,x_test) f_grid,f_grid_sigma,fcovar,alpha,nlml = gp.gp(hypdict,cv.SE,x_training,y,x_grid) w, h = mp.figaspect(0.5) fig = mp.figure(figsize=(w,h),facecolor='w') mp.fill_between(x_grid,f_grid+2*f_grid_sigma,y2=f_grid-2*f_grid_sigma,color='0.75') mp.errorbar(x_training,y,fmt='.',yerr=sigma) mp.errorbar(x_test,f_test,fmt='.',yerr=f_test_sigma) #mp.plot(x_grid,f_grid,'--k') mp.plot(x_grid,func(x_grid,0),'--k') mp.axis([-5, 5, -2.1, 2.1]) mp.xlabel('x') mp.ylabel('y') mp.savefig('fig5.eps') mp.clf() #figure 6 covar = cv.SE #Covariance matrix to be used
def plot(f, xs, ys, optimizers, frames=50, levels=50, steps_per_frame=1): X, Y = np.meshgrid(xs, ys) Z = np.array( [f(np.array(v), False) for v in zip(X.flatten(), Y.flatten())] ).reshape(X.shape) fig = plt.figure(figsize=plt.figaspect(0.5)) ax1 = fig.add_subplot(1, 2, 1, projection='3d') ax2 = fig.add_subplot(1, 2, 2) ax1.plot_surface( X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=True ) ax1.set_xlim3d((xs.min(), xs.max())) ax1.set_ylim3d((ys.min(), ys.max())) # ax1.set_zlim3d((0, 100.0)) ax2.contour(X, Y, Z, levels, cmap=cm.coolwarm) ax2.set_xlim((xs.min(), xs.max())) ax2.set_ylim((ys.min(), ys.max())) data_points = np.zeros((frames * steps_per_frame, len(optimizers), 3)) for i in range(frames * steps_per_frame): for (j, opti) in enumerate(optimizers): data_points[i, j, :] = ( opti.state[0], opti.state[1], f(opti.state, False) ) opti.step() cmap = cm.Accent opti_paths1 = [ ax1.plot([], [], [], '-o', zorder=5, label=opti.name, color=cmap(c), markevery=[0, -1])[0] for (c, opti) in zip(np.linspace(0, 1, len(optimizers)), optimizers) ] opti_paths2 = [ ax2.plot([], [], '-o', zorder=5, label=opti.name, color=cmap(c), markevery=[0, -1])[0] for (c, opti) in zip(np.linspace(0, 1, len(optimizers)), optimizers) ] ax1.legend() def update(frame, data_points, opti_paths1, opti_paths2): n = frame * steps_per_frame for i in range(len(opti_paths1)): opti_paths1[i].set_data( data_points[:n, i, 0].flatten(), data_points[:n, i, 1].flatten(), ) opti_paths1[i].set_3d_properties( data_points[:n, i, 2].flatten() ) opti_paths2[i].set_data( data_points[:n, i, 0].flatten(), data_points[:n, i, 1].flatten(), ) return opti_paths1 + opti_paths2 ani = FuncAnimation( fig, update, frames=frames, fargs=(data_points, opti_paths1, opti_paths2), blit=False ) return ani
# your ellispsoid and center in matrix form A = samples#np.array([[80,0.1,0],[0,1,0],[0,0,1]]) center = [mean_x,mean_y,mean_z] x,y,z,s,rotation = ellipsoid(A,center) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(x, y, z, rstride=4, cstride=4, color='b', alpha=0.2) # <codecell> from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=plt.figaspect(1)) # Square figure ax = fig.add_subplot(111, projection='3d') coefs = (10, 5, 2) # Coefficients in a0/c x**2 + a1/c y**2 + a2/c z**2 = 1 # Radii corresponding to the coefficients: rx, ry, rz = 1/np.sqrt(coefs) # Set of all spherical angles: u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) # Cartesian coordinates that correspond to the spherical angles: # (this is the equation of an ellipsoid): x = rx * np.outer(np.cos(u), np.sin(v)) y = ry * np.outer(np.sin(u), np.sin(v)) z = rz * np.outer(np.ones_like(u), np.cos(v))
plot_boxplot = True l = [approaches]*nruns labels = [list(i) for i in zip(*l)] labels = [y for x in labels for y in x] p_vals_all = None index_all = None for samp in sampling: for prob in problems: for obj in objectives: for n_vars in dims: fig = plt.figure(figsize=plt.figaspect(0.25)) fig.set_size_inches(30, 5) #plt.xlim(0, 1) #plt.ylim(0, 1) #ax = fig.add_subplot(111, projection='3d') if problem_testbench is 'DTLZ': pareto_front = np.genfromtxt(pareto_front_directory + '/True_5000_' + prob + '_' + str(obj) + '.txt' , delimiter=',') for algo in emo_algorithm: #igd_all = np.zeros([nruns, np.shape(modes)[0]]) igd_all = None solution_ratio_all = None for mode, mode_count in zip(modes,range(np.shape(modes)[0])):
import face_alignment import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from skimage import io # Run the 3D face alignment on a test image, without CUDA. fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, enable_cuda=False, flip_input=False) input = io.imread('../test/assets/aflw-test.jpg') preds = fa.get_landmarks(input)[-1] #TODO: Make this nice fig = plt.figure(figsize=plt.figaspect(.5)) ax = fig.add_subplot(1, 2, 1) ax.imshow(input) ax.plot(preds[0:17, 0], preds[0:17, 1], marker='o', markersize=6, linestyle='-', color='w', lw=2) ax.plot(preds[17:22, 0], preds[17:22, 1], marker='o', markersize=6, linestyle='-', color='w',
def plot_attention( cls, model: torch.nn.Module, output_dir: Optional[Path], summary_writer, iterator: Iterable[Tuple[List[str], Dict[str, torch.Tensor]]], reporter: SubReporter, options: TrainerOptions, ) -> None: assert check_argument_types() import matplotlib ngpu = options.ngpu no_forward_run = options.no_forward_run matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator model.eval() for ids, batch in iterator: assert isinstance(batch, dict), type(batch) assert len(next(iter(batch.values()))) == len(ids), ( len(next(iter(batch.values()))), len(ids), ) batch = to_device(batch, "cuda" if ngpu > 0 else "cpu") if no_forward_run: continue # 1. Forwarding model and gathering all attentions # calculate_all_attentions() uses single gpu only. att_dict = calculate_all_attentions(model, batch) # 2. Plot attentions: This part is slow due to matplotlib for k, att_list in att_dict.items(): assert len(att_list) == len(ids), (len(att_list), len(ids)) for id_, att_w in zip(ids, att_list): if isinstance(att_w, torch.Tensor): att_w = att_w.detach().cpu().numpy() if att_w.ndim == 2: att_w = att_w[None] elif att_w.ndim > 3 or att_w.ndim == 1: raise RuntimeError( f"Must be 2 or 3 dimension: {att_w.ndim}") w, h = plt.figaspect(1.0 / len(att_w)) fig = plt.Figure(figsize=(w * 1.3, h * 1.3)) axes = fig.subplots(1, len(att_w)) if len(att_w) == 1: axes = [axes] for ax, aw in zip(axes, att_w): ax.imshow(aw.astype(np.float32), aspect="auto") ax.set_title(f"{k}_{id_}") ax.set_xlabel("Input") ax.set_ylabel("Output") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) if output_dir is not None: p = output_dir / id_ / f"{k}.{reporter.get_epoch()}ep.png" p.parent.mkdir(parents=True, exist_ok=True) fig.savefig(p) if summary_writer is not None: summary_writer.add_figure(f"{k}_{id_}", fig, reporter.get_epoch()) if options.use_wandb: import wandb wandb.log( {f"attention plot/{k}_{id_}": wandb.Image(fig)}) reporter.next()
countriesList = ["US", "Italy", "Spain"] #Numbers we may consider HospitalBeds = 924107 #https://www.washingtonpost.com/business/2020/03/14/hospital-doctors-patients-coronavirus/ Ventilators = 160000 #http://www.centerforhealthsecurity.org/resources/COVID-19/200214-VentilatorAvailability-factsheet.pdf #reference of these numbers: # plt.rcParams["font.size"] = 13 #some of the early dates have different file structure and you may see an error f_date = date(2020, 2, 25) l_date = date.today() delta = l_date - f_date daycount = delta.days + 1 totEachDay = [0] * daycount fig1 = plt.figure(figsize=plt.figaspect(1. / 3.)) fig1.suptitle('COVID-19 - ' + ' ( date (0): ' + str(l_date) + ')') ax1 = fig1.add_subplot(231) #ax1.set_xlabel('days ago') ax1.set_ylabel('Log(N)') ax1.set_xlim(daycount - 1, -3) ax1.title.set_text('Confirmed') ax1.grid(True) ax2 = fig1.add_subplot(232) #ax2.set_xlabel('days ago') ax2.set_ylabel('Log(N)') ax2.set_xlim(daycount - 1, -3) ax2.title.set_text('Recovered') ax2.grid(True) ax3 = fig1.add_subplot(233) #ax3.set_xlabel('days ago')
def videoQuadcopter(x, net, prob, nt, sPath, sTitle="", approach='ocflow'): """ make video for the 12-d quadcopter """ if approach != 'ocflow': print('approach ' + approach + ' is not supported') return 1 nex, d = x.shape LOWX, HIGHX, LOWY, HIGHY, msz = getMidcrossBounds(x, d) extent = [LOWX, HIGHX, LOWY, HIGHY] xtarget = prob.xtarget.view(-1).detach().cpu().numpy() # 3-d plot bounds xbounds = [-3.0, 3.0] ybounds = [-3.0, 3.0] zbounds = [-3.0, 3.0] traj, trajCtrl = OCflow(x, net, prob, tspan=[0.0, 1.0], nt=nt, stepper="rk4", alph=net.alph, intermediates=True) ims = [] if nex > 1: examples = [0, 1, 2] else: examples = [0] for ex in examples: tracePhiFlow = traj[ex, 0:d, :] tracePhiFlow = tracePhiFlow.detach().cpu().numpy() ctrls = trajCtrl[ex, :, :].detach().cpu().numpy() timet = range(1, nt + 1) for n in range(1, nt - 1): # make grid of plots nCol = 1 nRow = 2 fig = plt.figure(figsize=plt.figaspect(1.0)) fig.set_size_inches(14, 10) # postional movement training ax = fig.add_subplot(nRow, nCol, 1, projection='3d') ax.set_title('Flight Path') for j in range(prob.nAgents): for i in range(ex): ax.plot(traj[i, 12 * j, :nt - 1], traj[i, 12 * j + 1, :nt - 1], traj[i, 12 * j + 2, :nt - 1], '-', linewidth=1, color='gray') ax.plot(tracePhiFlow[12 * j, :n], tracePhiFlow[12 * j + 1, :n], tracePhiFlow[12 * j + 2, :n], 'o-', linewidth=2, markersize=msz) ax.scatter(xtarget[12 * j], xtarget[12 * j + 1], xtarget[12 * j + 2], s=140, marker='x', color='red') ax.view_init(10, -30) ax.set_xlim(*xbounds) ax.set_ylim(*ybounds) ax.set_zlim(*zbounds) # plot controls ax = fig.add_subplot(nRow, nCol, 2) # not using the t=0 values ax.plot(timet[:n], trajCtrl[ex, 0, 1:n + 1].cpu().numpy(), 'o-', label='u') ax.plot(timet[:n], trajCtrl[ex, 1, 1:n + 1].cpu().numpy(), 'o-', label=r'$\tau_\psi$') ax.plot(timet[:n], trajCtrl[ex, 2, 1:n + 1].cpu().numpy(), 'o-', label=r'$\tau_\theta$') ax.plot(timet[:n], trajCtrl[ex, 3, 1:n + 1].cpu().numpy(), 'o-', label=r'$\tau_\phi$') ax.legend(loc='upper center') ax.set_xticks([0, nt / 2, nt]) ax.set_xlabel('nt') ax.set_ylabel('control') ax.set_ylim(-80, 80) ax.set_xlim(0, nt) ax.set_title('Controls') im = fig2img(fig) ims.append(im) plt.close(fig) sPath = sPath[:-4] + '.gif' ims[0].save(sPath, save_all=True, append_images=ims[1:], duration=100, loop=0) print('saved video to', sPath)
def plotQuadcopter(x, net, prob, nt, sPath, sTitle="", approach='ocflow'): """ plot images of the 12-d quadcopter :param x: tensor, initial spatial point(s) at initial time :param net: Module, the network Phi (or in some cases the baseline) :param prob: problem object, which is needed for targets and obstacles :param nt: int, number of time steps :param sPath: string, path where you want the files saved :param sTitle: string, the title wanted to be applied to the figure :param approach: string, used to distinguish how the plot function behaves with inputs 'ocflow' or 'baseline' """ xtarget = prob.xtarget if approach == 'ocflow': traj, trajCtrl = OCflow(x, net, prob, tspan=[0.0, 1.0], nt=nt, stepper="rk4", alph=net.alph, intermediates=True) trajCtrl = trajCtrl[:, :, 1:] # want last dimension to be nt elif approach == 'baseline': # overload inputs to treat x and net differently for baseline traj = x # expects a tensor of size (nex, d, nt+1) trajCtrl = net # expects a tensor (nex, a, nt) where a is the dimension of the controls else: print("approach=", approach, " is not an acceptable parameter value for plotQuadcopter") # 3-d plot bounds xbounds = [-3.0, 3.0] ybounds = [-3.0, 3.0] zbounds = [-3.0, 3.0] # make grid of plots nCol = 3 nRow = 2 fig = plt.figure(figsize=plt.figaspect(1.0)) fig.set_size_inches(16, 8) fig.suptitle(sTitle) # positional movement training ax = fig.add_subplot(nRow, nCol, 1, projection='3d') ax.set_title('Flight Path') ax.scatter(xtarget[0].cpu().numpy(), xtarget[1].cpu().numpy(), xtarget[2].cpu().numpy(), s=140, marker='x', c='r', label="target") for i in range(traj.shape[0]): ax.plot(traj[i, 0, :].view(-1).cpu().numpy(), traj[i, 1, :].view(-1).cpu().numpy(), traj[i, 2, :].view(-1).cpu().numpy(), 'o-') # ax.legend() ax.view_init(10, -30) ax.set_xlim(*xbounds) ax.set_ylim(*ybounds) ax.set_zlim(*zbounds) # plotting path from eagle view ax = fig.add_subplot(nRow, nCol, 2) # traj is nex by d+1 by nt+1 ax.plot(traj[0, 0, :].cpu().numpy(), traj[0, 1, :].cpu().numpy(), 'o-') xtarget = xtarget.detach().cpu().numpy() ax.scatter(xtarget[0], xtarget[1], marker='x', color='red') ax.set_xlim(*xbounds) ax.set_ylim(*ybounds) ax.set_aspect('equal') ax.set_title('Path From Bird View') # plot controls ax = fig.add_subplot(nRow, nCol, 3) timet = range(nt) # not using the t=0 values ax.plot(timet, trajCtrl[0, 0, :].cpu().numpy(), 'o-', label='u') ax.plot(timet, trajCtrl[0, 1, :].cpu().numpy(), 'o-', label=r'$\tau_\psi$') ax.plot(timet, trajCtrl[0, 2, :].cpu().numpy(), 'o-', label=r'$\tau_\theta$') ax.plot(timet, trajCtrl[0, 3, :].cpu().numpy(), 'o-', label=r'$\tau_\phi$') ax.legend() ax.set_xticks([0, nt / 2, nt]) ax.set_xlabel('nt') ax.set_ylabel('control') # plot L at each time step ax = fig.add_subplot(nRow, nCol, 4) timet = range(nt) # not using the t=0 values trajL = torch.sum(trajCtrl[0, :, :]**2, dim=0, keepdims=True) totL = torch.sum(trajL[0, :]) / nt ax.plot(timet, trajL[0, :].cpu().numpy(), 'o-', label='L') ax.legend() ax.set_xticks([0, nt / 2, nt]) ax.set_xlabel('nt') ax.set_ylabel('L') ax.set_title('L(x,T)=' + str(totL.item())) # plot velocities ax = fig.add_subplot(nRow, nCol, 5) timet = range(nt + 1) ax.plot(timet, traj[0, 6, :].cpu().numpy(), 'o-', label=r'$v_x$') ax.plot(timet, traj[0, 7, :].cpu().numpy(), 'o-', label=r'$v_y$') ax.plot(timet, traj[0, 8, :].cpu().numpy(), 'o-', label=r'$v_z$') ax.plot(timet, traj[0, 9, :].cpu().numpy(), 'o-', label=r'$v_\psi$') ax.plot(timet, traj[0, 10, :].cpu().numpy(), 'o-', label=r'$v_\theta$') ax.plot(timet, traj[0, 11, :].cpu().numpy(), 'o-', label=r'$v_\phi$') ax.legend(ncol=2) ax.set_xticks([0, nt / 2, nt]) ax.set_xlabel('nt') ax.set_ylabel('value') # plot angles ax = fig.add_subplot(nRow, nCol, 6) timet = range(nt + 1) ax.plot(timet, traj[0, 3, :].cpu().numpy(), 'o-', label=r'$\psi$') ax.plot(timet, traj[0, 4, :].cpu().numpy(), 'o-', label=r'$\theta$') ax.plot(timet, traj[0, 5, :].cpu().numpy(), 'o-', label=r'$\phi$') ax.legend() ax.set_xticks([0, nt / 2, nt]) ax.set_xlabel('nt') ax.set_ylabel('value') if not os.path.exists(os.path.dirname(sPath)): os.makedirs(os.path.dirname(sPath)) plt.savefig(sPath, dpi=300) plt.close()
# ### Plot figures of neural network raster inputs in 2D and 3D # %% fig, axarr = plt.subplots(nrows=1, ncols=4, squeeze=False, figsize=(16, 12)) axarr[0, 0].imshow(X_tile[0, 0, :, :], cmap="BrBG") axarr[0, 0].set_title("BEDMAP2\n(1000m resolution)") axarr[0, 1].imshow(W1_tile[0, 0, :, :], cmap="BrBG") axarr[0, 1].set_title("Reference Elevation Model of Antarctica\n(100m resolution)") axarr[0, 2].imshow(np.linalg.norm(W2_tile, axis=(0, 1)), cmap="BrBG") axarr[0, 2].set_title("MEaSUREs Ice Speed\n(450m resolution)") axarr[0, 3].imshow(W3_tile[0, 0, :, :], cmap="BrBG") axarr[0, 3].set_title("Antarctic Snow Accumulation\n(1000m resolution)") plt.show() # %% fig = plt.figure(figsize=plt.figaspect(1 / 4) * 2.5) axarr = [fig.add_subplot(1, 4, i + 1, projection="3d") for i in range(4)] plot_3d_view( img=X_tile, ax=axarr[0], title="BEDMAP2\n(1000m resolution)", zlabel="Elevation (metres)", ) plot_3d_view( img=W1_tile, ax=axarr[1], title="Reference Elevation Model of Antarctica\n(100m resolution)", zlabel="Elevation (metres)", ) plot_3d_view(
def _plot_modes_single_model(star: Star, puls_data: GyreData, model: Series, col: str, output: Path, x_lim: tuple, star_name: str, plot_legend: bool = False, legend_loc: str = None, save_pdf: bool = True, save_eps: bool = False) -> None: periods = star.periods_explicit()[0] degrees = np.sort(np.unique([p['l'] for p in periods.values()])) colors = ['red', 'green', 'blue', 'magenta'] w, h = plt.figaspect(0.3 * len(degrees)) fig = plt.figure(figsize=(w, h)) gs = fig.add_gridspec(len(degrees), hspace=0) axs = gs.subplots(sharex=True, squeeze=False) for i, deg in enumerate(degrees): periods_deg = [p['P'] for p in periods.values() if p['l'] == deg] if deg == degrees[-1]: axs[i, 0].set_xlabel(r'$P\/\mathrm{{[s]}}$') axs[i, 0].set_ylabel(fr'$\ell={int(deg)}$') axs[i, 0].set_ylim(0.0, 1.0) axs[i, 0].tick_params(axis='y', which='both', left=False, right=False, labelleft=False, labelright=False) axs[i, 0].vlines(x=puls_data.periods(deg=deg, g_modes_only=True), ymin=0, ymax=1, colors='black', linewidth=1) axs[i, 0].vlines(x=periods_deg, ymin=0, ymax=1, colors=colors[i], linestyles='dotted', linewidth=4) if i == 0: axs[i, 0].text( x_lim[0] + int(0.02 * (x_lim[1] - x_lim[0])), 1.1, f'{star_name}' fr'$,\/\chi^2={model[f"{col}"]:.2f},\/$' fr'$\mathrm{{id}}={model.id},\/Z_\mathrm{{i}}={model.z_i:.3f},\/$' fr'$Y_\mathrm{{i}}={model.y_i:.4f},\/M_\mathrm{{i}}={model.m_i:.2f}\,M_\odot,\/$' '\n' fr'$M_\mathrm{{env}}={model.m_env:.4f}\,M_\odot,\/Y_\mathrm{{c}}={model.he4:.2f},\/$' fr'$T_\mathrm{{eff}}={10 ** model.log_Teff:.0f}\,\mathrm{{K}},\/\log\,g={model.log_g:.3f}$' ) plt.xlim(x_lim) if plot_legend and legend_loc: plt.legend(loc=legend_loc) if save_pdf: plt.savefig(output.with_suffix(output.suffix + '.pdf'), format='pdf', bbox_inches='tight') if save_eps: plt.savefig(output.with_suffix(output.suffix + '.eps'), format='eps', bbox_inches='tight') plt.close()
def test(): DO_PLOTS = False PLOT_3D = False mass = 75 # mass of the robot mu = 0.5 # friction coefficient lx = 0.1 # half foot size in x direction ly = 0.07 # half foot size in y direction USE_DIAGONAL_GENERATORS = True GENERATE_QUASI_FLAT_CONTACTS = True #First, generate a contact configuration CONTACT_POINT_UPPER_BOUNDS = [0.5, 0.5, 0.0] CONTACT_POINT_LOWER_BOUNDS = [-0.5, -0.5, 0.0] gamma = atan(mu) # half friction cone angle RPY_LOWER_BOUNDS = [-0 * gamma, -0 * gamma, -pi] RPY_UPPER_BOUNDS = [+0 * gamma, +0 * gamma, +pi] MIN_CONTACT_DISTANCE = 0.3 N_CONTACTS = 2 READ_CONTACTS_FROM_FILE = True X_MARG = 0.07 Y_MARG = 0.07 if (READ_CONTACTS_FROM_FILE): import pickle f = open("./data.pkl", 'rb') res = pickle.load(f) f.close() # (p, N) = generate_contacts(N_CONTACTS, lx, ly, mu, CONTACT_POINT_LOWER_BOUNDS, CONTACT_POINT_UPPER_BOUNDS, RPY_LOWER_BOUNDS, RPY_UPPER_BOUNDS, MIN_CONTACT_DISTANCE, GENERATE_QUASI_FLAT_CONTACTS); p = res['contact_points'].T N = res['contact_normals'].T print "Contact points\n", p print "Contact normals\n", 1e3 * N X_LB = np.min(p[:, 0] - X_MARG) X_UB = np.max(p[:, 0] + X_MARG) Y_LB = np.min(p[:, 1] - Y_MARG) Y_UB = np.max(p[:, 1] + Y_MARG) Z_LB = np.min(p[:, 2] - 0.05) Z_UB = np.max(p[:, 2] + 1.5) (H, h) = compute_GIWC(p, N, mu, False, USE_DIAGONAL_GENERATORS) (succeeded, c0) = find_static_equilibrium_com(mass, [X_LB, Y_LB, Z_LB], [X_UB, Y_UB, Z_UB], H, h) if (not succeeded): print "Impossible to find a static equilibrium CoM position with the contacts read from file" return else: succeeded = False while (succeeded == False): (p, N) = generate_contacts(N_CONTACTS, lx, ly, mu, CONTACT_POINT_LOWER_BOUNDS, CONTACT_POINT_UPPER_BOUNDS, RPY_LOWER_BOUNDS, RPY_UPPER_BOUNDS, MIN_CONTACT_DISTANCE, GENERATE_QUASI_FLAT_CONTACTS) X_LB = np.min(p[:, 0] - X_MARG) X_UB = np.max(p[:, 0] + X_MARG) Y_LB = np.min(p[:, 1] - Y_MARG) Y_UB = np.max(p[:, 1] + Y_MARG) Z_LB = np.min(p[:, 2] - 0.05) Z_UB = np.max(p[:, 2] + 1.5) (H, h) = compute_GIWC(p, N, mu, False, USE_DIAGONAL_GENERATORS) (succeeded, c0) = find_static_equilibrium_com(mass, [X_LB, Y_LB, Z_LB], [X_UB, Y_UB, Z_UB], H, h) dc0 = np.random.uniform(-1, 1, size=3) dc0[2] = 0 if (DO_PLOTS): f, ax = plut.create_empty_figure() for j in range(p.shape[0]): ax.scatter(p[j, 0], p[j, 1], c='k', s=100) ax.scatter(c0[0], c0[1], c='r', s=100) com_x = np.zeros(2) com_y = np.zeros(2) com_x[0] = c0[0] com_y[0] = c0[1] com_x[1] = c0[0] + dc0[0] com_y[1] = c0[1] + dc0[1] ax.plot(com_x, com_y, color='b') plt.axis([X_LB, X_UB, Y_LB, Y_UB]) plt.title('Contact Points and CoM position') if (PLOT_3D): fig = plt.figure(figsize=plt.figaspect(0.5) * 1.5) ax = fig.gca(projection='3d') line_styles = ["b", "r", "c", "g"] ss = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ax.scatter(c0[0], c0[1], c0[2], c='k', marker='o') for i in range(p.shape[0]): ax.scatter(p[i, 0], p[i, 1], p[i, 2], c=line_styles[i % len(line_styles)], marker='o') for s in ss: ax.scatter(p[i, 0] + s * N[i, 0], p[i, 1] + s * N[i, 1], p[i, 2] + s * N[i, 2], c=line_styles[i % len(line_styles)], marker='x') for s in ss: ax.scatter(c0[0] + s * dc0[0], c0[1] + s * dc0[1], c0[2] + s * dc0[2], c='k', marker='x') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # return can_I_stop(c0, dc0, p, N, mu, mass, 1.0, 100, DO_PLOTS=DO_PLOTS); (has_stopped, c_final, dc_final) = can_I_stop(c0, dc0, p, N, mu, mass, 1.0, 100, DO_PLOTS=DO_PLOTS) print "Contact points\n", p print "Contact normals\n", N print "Initial com position", c0 print "Initial com velocity", dc0, "norm %.3f" % norm(dc0) print "Final com position", c_final print "Final com velocity", dc_final, "norm %.3f" % norm(dc_final) if (has_stopped): print "The system is stable" else: print "The system is unstable" return True
def setup_plot(self, filename): self.fig = plt.figure(figsize=plt.figaspect(0.4)) self.ax = self.fig.add_subplot(111) self.plot_name = "mpl_" + filename
# ax = fig.add_subplot(1, 2, jj+1, projection='3d') # surf = ax.plot_surface(T, X, pca_modes[jj], cmap='summer',linewidth=0, antialiased=True, rstride=1, cstride=1, alpha=None) # surf.set_clim(vmin,vmax) # ax.set_ylabel(r'$X$') # ax.set_xlabel(r'$T$') # ax.set_title('Var explained: {:.2f}%'.format(eigen_values[jj]/np.sum(eigen_values)*100)) # plt.colorbar(surf) # plt.subplots_adjust(hspace=0.5,wspace=0.05) # plt.tight_layout() # plt.savefig('PCA_space_time_func_modes.png',dpi=300,bbox_inches='tight') # plt.close('all') ## Spatial and temporal behaviour fig, ax = plt.subplots(2,1,figsize=plt.figaspect(0.5)) ax[0].plot(x,v[0,:],'k-',label='mode 1') ax[0].plot(x,v[1,:],'k--',label='mode 2') ax[0].set_xlabel('x') ax[0].set_ylabel('PCA modes') ax[0].legend() ax[1].plot(t,u[:,0],'k-',label='mode 1') ax[1].plot(t,u[:,1],'k--',label='mode 2') ax[1].set_xlabel('x') ax[1].set_ylabel('PCA modes') ax[1].legend() plt.subplots_adjust(hspace=0.5,wspace=0.05) plt.tight_layout()
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # konfiguracja wielkości wykresu, figsize określa wielkość wykresu w calach fig = plt.figure(figsize=(plt.figaspect(0.15))) ax1 = fig.add_subplot(151, projection='3d') ax2 = fig.add_subplot(152, projection='3d') ax3 = fig.add_subplot(153, projection='3d') ax4 = fig.add_subplot(154, projection='3d') ax5 = fig.add_subplot(155, projection='3d') # fikcyjne dane _x = np.arange(4) _y = np.arange(5) _xx, _yy = np.meshgrid(_x, _y) x, y = _xx.ravel(), _yy.ravel() top = x + y bottom = np.zeros_like(top) width = depth = 1 ax1.bar3d(x, y, bottom, width, depth, top, shade=True) ax1.set_title('Wykres 1') ax2.bar3d(x, y, top, width, depth, bottom, color='r', shade=True) ax2.set_title('Wykres 2') ax3.bar3d(x, y, bottom, width, depth, top, color='g') ax3.set_title('Wykres 3') ax4.bar3d(2 * x, 3 * y, bottom, width, depth, top, shade=False) ax4.set_title('Wykres 4') ax5.bar3d(2 * x, 1.5 * y, bottom, width, depth, top, color='b', shade=True) ax5.set_title('Wykres 5') plt.show()
x = np.arange(0, 1.05, 0.05) # Radius of one cicle is 0.1, the other circle 0.3 x_1 = [] x_2 = [] y_1 = [] y_2 = [] for i in range(0, 1000): angle = random.uniform(0, 1) * (math.pi * 2) x_1.append(math.cos(angle) / 3 + 0.5 + random.gauss(0, 0.025)) x_2.append(math.cos(angle) / 10 + 0.5 + random.gauss(0, 0.025)) y_1.append(math.sin(angle) / 3 + 0.5 + random.gauss(0, 0.025)) y_2.append(math.sin(angle) / 10 + 0.5 + random.gauss(0, 0.025)) fig = plot.figure(figsize=plot.figaspect(2.)) ax = fig.add_subplot(1, 2, 1) plot.hold(True) ax.plot(x_1, y_1, 'ro') ax.plot(x_2, y_2, 'bo') ax.legend(['$class$ $1$ $(other$ $activity)$', '$class$ $2$ $(walking)$'], loc=2, fontsize='small', numpoints=1) ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) ax.set_xlabel('$X_{1}$') ax.set_ylabel('$X_{2}$') df1 = pd.DataFrame(columns=list('XY'))
help="output file [%(default)s]") parser.add_argument("tsv", help="D_stats.tsv") parser.add_argument("outgroup", help="Outgroup, to show in the title") return parser.parse_args() if __name__ == "__main__": args = parse_args() dstats = parse_dstats_tsv(args.tsv) tt = "$" + args.outgroup.replace(" ", "$ $") + "$" pdf = PdfPages(args.outpdf) #fig_w, fig_h = plt.figaspect(9.0/16.0) fig_w, fig_h = plt.figaspect(3.0 / 4.0) fig1 = plt.figure(figsize=(args.figscale * fig_w, args.figscale * fig_h)) ax1 = fig1.add_subplot(111) y_pos = np.arange(len(dstats)) p4_labels = [ "(({}, {}), {})".format(p1, p2, p3) for p1, p2, p3, p4, _, _, _, _, _ in dstats ] d = [dd for _, _, _, _, dd, _, _, _, _ in dstats] # 3 * standard error err = [3 * abs(dd / zz) for _, _, _, _, dd, zz, _, _, _ in dstats] if args.greyscale:
tasks.append( at.headAndTail(preds, sizePred, 'r', ax, tail_length, delay=t0pred) ) # here are the extensions # tasks.append( at.voro_lines(preys, ax) ) tasks.append( at.voro_lines(preys, ax, preds, t0pred) ) tasks.append( at.lineFadingCOM(preys.pos, ax, 30) ) tasks.append( at.circleCOM(preys.pos, 1, 'b', ax) ) # animation partUpdate(f, tasks, 0, time) # ## Advanced Example # create figure: rows = 1 cols = 3 f, axs = plt.subplots(rows, cols, figsize=0.7*min(rows, cols)*plt.figaspect(rows/cols)) f.tight_layout(rect=[0, 0, 1, 0.95]) # rect=[left, bottom, right, top] # partial definition to not repeat arguments (missing: ax, tail-length) preyHeads = partial(at.headAndTail, preys, sizePrey, colors, cmap=cmap) predHeads = partial(at.headAndTail, preds, sizePred, 'r', delay=t0pred) preyHeadsD = partial(at.headAndTail, preysD, sizePrey, 'b', delay=t0pred) predHeadsD = partial(at.headAndTail, predsD, sizePred, 'g', delay=t0pred) # Collect update-tasks tasks = at.taskCollector() ax = axs[0] # only prey positions = [preys.pos, preds.pos] tasks.append( at.Limits4Pos(positions, ax) ) tasks.append( preyHeads(ax, tail_length) )
from sim.cameras import Camera import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D s = 8 c1 = Camera(pose=np.array([-4, 0, 0, 0, 0, 0]) / s) c2 = Camera(pose=np.array([-2, -3, 0, 0, -30, 0]) / s) fig = plt.figure(1, figsize=plt.figaspect(1)) # Square figure fig2 = plt.figure(2, figsize=plt.figaspect(1)) # Square figure ax1 = fig.add_subplot(111, projection='3d') ax2 = fig2.add_subplot(111, projection='3d') axes = [ax1, ax2] pts = np.array([[0.1, 0.05, .05], [.1, -.05, .05], [-.0, -.05, -.05], [-.0, .05, -.05]]) * 20 / s i = 0 for ax in axes: if i == 0: c1.plot_covariance_ellipsoids_at_points(pts[1:], ax, show=False, color='r') c2.plot_covariance_ellipsoids_at_points(pts, ax, show=False, color='b') else: C1 = c1.estimate_covariance(pts) C2 = c2.estimate_covariance(pts) j = 0 for pt in pts: if j == 0: C_net = C2[0]