def plot_direction(xmin, xmax, ymin, ymax): dx = (xmax - xmin) dy = (ymax - ymin) x_arrow = dx * 1.5 / 10. + xmin y_arrow = dy * 1.5 / 10. + ymin dxy_arrow = dx * 1. / 35. x_N0 = x_arrow y_N0 = y_arrow dx_N1 = -dxy_arrow * np.tan(np.radians(69)) dy_N1 = dxy_arrow hw_arrow = (xmax - xmin) * 1. / 50. hl_arrow = (ymax - ymin) * 1. / 50. plt.arrow(x_N0,y_N0,dx_N1,dy_N1,fc='black',ec='black',\ linewidth=1,head_width=hw_arrow,head_length=hl_arrow) plt.text(x_N0 + dx_N1 * 1.4, y_N0 + dy_N1 * 1.3, 'N', rotation=69, fontsize=10) dx_E1 = -dxy_arrow dy_E1 = -dxy_arrow * np.tan(np.radians(69)) plt.arrow(x_N0,y_N0,dx_E1,dy_E1,fc='black',ec='black',\ linewidth=1,head_width=hw_arrow,head_length=hl_arrow) plt.text(x_N0 + dx_E1 * 0.9, y_N0 + dy_E1 * 1.5, 'E', rotation=69, fontsize=10) return
def plot_prof(obj): '''Function that plots a vertical profile of scattering from TOC to BOC. Input: rt_layer instance object. Output: plot of scattering. ''' I = obj.Inodes[:,1,:] \ / -obj.mu_s y = np.linspace(obj.Lc, 0., obj.K + 1) x = obj.views * 180. / np.pi xm = np.array([]) for i in np.arange(0, len(x) - 1): nx = x[i] + (x[i + 1] - x[i]) / 2. xm = np.append(xm, nx) xm = np.insert(xm, 0, 0.) xm = np.append(xm, 180.) xx, yy = np.meshgrid(xm, y) plt.pcolormesh(xx, yy, I) plt.colorbar() plt.title('Canopy Fluxes') plt.xlabel('Exit Zenith Angle') plt.ylabel('Cumulative LAI (0=soil)') plt.arrow(135.,3.5,0.,-3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(140., 2.5, 'Downwelling Flux', rotation=90) plt.arrow(45.,.5,0.,3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(35., 2.5, 'Upwelling Flux', rotation=270) plt.show()
def plot(self): #draw vertecies L = [self.V[k]['inout'][0]-self.V[k]['inout'][1] for k in self.V] max_deg,min_deg,ave_deg = max(L),min(L),np.mean(L) for k in self.V.keys(): deg = self.V[k]['inout'][0]-self.V[k]['inout'][1] if(np.sign(deg)>0): #sink more in than out c,a,s = 'r',min(1.0,max(0.4,deg/max_deg)),20.0 elif(np.sign(deg)<0): #source more out than in c,a,s = 'g',min(1.0,max(0.4,deg/min_deg)),20.0 else: c,a,s = 'b',min(0.4,max(0.1,deg/(ave_deg+1))),2.0 plt.plot(self.V[k]['pos'][0],self.V[k]['pos'][1],marker='.',color=c, markersize=s,alpha=a) counts = [self.E[k]['count'] for k in self.E.keys()] max_c,min_c,ave_c = max(counts),min(counts),np.mean(counts) means = [self.E[k]['mean'] for k in self.E.keys()] max_m,min_m,ave_m = max(means),min(means),np.mean(means) for k in self.E.keys(): a_w,e_w = 0.008,0.1 a = min(0.4,max(0.01,self.E[k]['mean']/(max_m*ave_m))) P,K = tuple(k.split('@')) p1 = {'x':self.V[P]['pos'][0],'y':self.V[P]['pos'][1]} p2 = {'x':self.V[K]['pos'][0],'y':self.V[K]['pos'][1]} dx,dy = p2['x']-p1['x'],p2['y']-p1['y'] plt.arrow(p1['x'],p1['y'],dx,dy,fc="k",ec="k",alpha=a, lw=e_w, head_width=a_w, head_length=a_w,length_includes_head=True) plt.show()
def plot_prof(obj): '''Function that plots a vertical profile of scattering from TOC to BOC. Input: rt_layer instance object. Output: plot of scattering. ''' I = obj.Inodes[:,1,:] \ / -obj.mu_s y = np.linspace(obj.Lc, 0., obj.K+1) x = obj.views*180./np.pi xm = np.array([]) for i in np.arange(0,len(x)-1): nx = x[i] + (x[i+1]-x[i])/2. xm = np.append(xm,nx) xm = np.insert(xm,0,0.) xm = np.append(xm,180.) xx, yy = np.meshgrid(xm, y) plt.pcolormesh(xx,yy,I) plt.colorbar() plt.title('Canopy Fluxes') plt.xlabel('Exit Zenith Angle') plt.ylabel('Cumulative LAI (0=soil)') plt.arrow(135.,3.5,0.,-3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(140.,2.5,'Downwelling Flux',rotation=90) plt.arrow(45.,.5,0.,3.,head_width=5.,head_length=.2,\ fc='k',ec='k') plt.text(35.,2.5,'Upwelling Flux',rotation=270) plt.show()
def plot_features_arrow(img, locs, length=20): pylab.imshow(img) x, y = locs[:, 0].astype('int'), locs[:, 1].astype('int') dx, dy = length * np.cos(locs[:, -1]), length * np.sin(locs[:, -1]) for i in range(x.shape[0]): pylab.arrow(x[i], y[i], dx[i], dy[i], width=1, color='c', head_width=4) pylab.axis('off')
def draw_path(u, v, arrow_length=.1, color=(.8, .8, .8), lw=1): du = u.direction plt.arrow(u.pose[X], u.pose[Y], du[0] * arrow_length, du[1] * arrow_length, head_width=.05, head_length=.1, fc=color, ec=color) dv = v.direction plt.arrow(v.pose[X], v.pose[Y], dv[0] * arrow_length, dv[1] * arrow_length, head_width=.05, head_length=.1, fc=color, ec=color) center, radius = find_circle(u, v) du = u.position - center theta1 = np.arctan2(du[1], du[0]) dv = v.position - center theta2 = np.arctan2(dv[1], dv[0]) # Check if the arc goes clockwise. if np.cross(u.direction, du).item() > 0.: theta1, theta2 = theta2, theta1 ax.add_patch( patches.Arc(center, radius * 2., radius * 2., theta1=theta1 / np.pi * 180., theta2=theta2 / np.pi * 180., color=color, lw=lw))
def test(args): data = multivariate_normal([0, 0], [[1, 2], [2, 5]], int(args[1])) print(data) # PCA result = pca(data, base_num=int(args[2])) pc_base = result[0] print(pc_base) # Plotting fig = plt.figure() fig.add_subplot(1, 1, 1) plt.axvline(x=0, color="#000000") plt.axhline(y=0, color="#000000") # Plot data plt.scatter(data[:, 0], data[:, 1]) # Draw the 1st principal axis pc_line = sp.array([-3.0, 3.0]) * (pc_base[1] / pc_base[0]) plt.arrow(0, 0, -pc_base[0] * 2, -pc_base[1] * 2, fc="r", width=0.15, head_width=0.45) plt.plot([-3, 3], pc_line, "r") # Settings plt.xticks(size=15) plt.yticks(size=15) plt.xlim([-3, 3]) plt.tight_layout() plt.show() plt.savefig("image.png") return 0
def plotState(self,q,v=None,color='r'): if v is None: v= q[2:]; q = q[:2] SCALE = 10. l = norm(v) if l<0.05: return plt.arrow(q[0,0],q[1,0],v[0,0]/SCALE,v[1,0]/SCALE, fc='r', ec='r', alpha=0.5, width=0.02, head_width=0.05, head_length=0.05, head_starts_at_zero=False, shape='right',length_includes_head=True)
def draw_path(u, v, arrow_length=.1, color=(.8, .8, .8), lw=1): du = u.direction plt.arrow(u.pose[X], u.pose[Y], du[0] * arrow_length, du[1] * arrow_length, head_width=.05, head_length=.1, fc=color, ec=color) dv = v.direction plt.arrow(v.pose[X], v.pose[Y], dv[0] * arrow_length, dv[1] * arrow_length, head_width=.05, head_length=.1, fc=color, ec=color) plt.plot([u.pose[X], v.pose[X]], [u.pose[Y], v.pose[Y]], color=color)
def plot_arrow(xmin, xmax, ymin, ymax): x_arrow = (xmax - xmin) * 4.4 / 10. + xmin y_arrow = (ymax - ymin) * 20. / 100. + ymin dxy_arrow = (xmax - xmin) * 1. / 9. hw_arrow = (xmax - xmin) * 1. / 20. hl_arrow = (ymax - ymin) * 1. / 15. plt.arrow(x_arrow,y_arrow,dxy_arrow,-0*dxy_arrow,fc='black',ec='black',\ linewidth=3,head_width=hw_arrow,head_length=hl_arrow) return
def plotEdges(self): for e in self.edges: n1 = self.nodes[e[0]] n2 = self.nodes[e[1]] x1 = n1[0] + self.Delta x2 = n2[0] + self.Delta y1 = n1[1] + self.Delta y2 = n2[1] + self.Delta plt.arrow(x1, y1, (x2 - x1), (y2 - y1), fc='k', ec='k')
def riemann(): # grid info xmin = 0.0 xmax = 1.0 nzones = 2 ng = 0 gr = gp.FVGrid(nzones, xmin=xmin, xmax=xmax) #------------------------------------------------------------------------ # plot a domain without ghostcells gr.draw_grid() gr.label_center(0, r"$i$", fontsize="medium") gr.label_center(1, r"$i+1$", fontsize="medium") gr.label_edge(1, r"$i+1/2$", fontsize="medium") plt.arrow(gr.xc[0]+0.05*gr.dx, 0.5, 0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) plt.arrow(gr.xc[1]-0.1*gr.dx, 0.5, -0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) gr.mark_cell_left_state(1, r"$a_{i+1/2,L}^{n+1/2}$", fontsize="large", color="b") gr.mark_cell_right_state(0, r"$a_{i+1/2,R}^{n+1/2}$", fontsize="large", color="b") gr.label_cell_center(0, r"$a_i$") gr.label_cell_center(1, r"$a_{i+1}$") plt.xlim(gr.xl[0]-0.125*gr.dx,gr.xr[2*ng+nzones-1]+0.125*gr.dx) plt.ylim(-0.25, 1.0) plt.axis("off") plt.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95) f = plt.gcf() f.set_size_inches(7.0,2.0) plt.tight_layout() plt.savefig("riemann-adv.pdf")
def plot_arrow(xmin,xmax,ymin,ymax): x_arrow = (xmax-xmin)*4.4/10.+xmin y_arrow = (ymax-ymin)*20./100.+ymin dxy_arrow = (xmax-xmin)*1./9. hw_arrow = (xmax-xmin)*1./20. hl_arrow = (ymax-ymin)*1./15. plt.arrow(x_arrow,y_arrow,dxy_arrow,-0*dxy_arrow,fc='black',ec='black',\ linewidth=3,head_width=hw_arrow,head_length=hl_arrow) return
def plotDdpResult(x, y, theta): arrow_len = 0.08 count = 0 for i in range(len(x)): if count % 10 == 0: c, s = np.cos(theta[i]), np.sin(theta[i]) plt.arrow(x[i], y[i], c * arrow_len, s * arrow_len, head_width=.05) count += 1 plt.plot(x, y)
def illustrate(Colors=Colors): if hasattr(Colors, 'colors'): Colors = Colors.colors from matplotlib import pylab rcParams = pylab.rcParams rcParams['pdf.fonttype'] = 42 rcParams['ps.fonttype'] = 42 rcParams['text.usetex'] = False rcParams['xtick.labelsize'] = 20 rcParams['ytick.labelsize'] = 20 rcParams['legend.fontsize'] = 25 import bnpy Data = get_data(T=1000, nDocTotal=8) for k in xrange(K): zmask = Data.TrueParams['Z'] == k pylab.plot(Data.X[zmask, 0], Data.X[zmask, 1], '.', color=Colors[k], markeredgecolor=Colors[k], alpha=0.4) sigEdges = np.flatnonzero(transPi[k] > 0.0001) for j in sigEdges: if j == k: continue dx = mus[j, 0] - mus[k, 0] dy = mus[j, 1] - mus[k, 1] pylab.arrow(mus[k, 0], mus[k, 1], 0.8 * dx, 0.8 * dy, head_width=2, head_length=4, facecolor=Colors[k], edgecolor=Colors[k]) tx = 0 - mus[k, 0] ty = 0 - mus[k, 1] xy = (mus[k, 0] - 0.2 * tx, mus[k, 1] - 0.2 * ty) ''' pylab.annotate( u'\u27F2', xy=(mus[k,0], mus[k,1]), color=Colors[k], fontsize=35, ) ''' pylab.gca().yaxis.set_ticks_position('left') pylab.gca().xaxis.set_ticks_position('bottom') pylab.axis('image') pylab.ylim([-38, 38]) pylab.xlim([-38, 38])
def vis_Bat(xx, yy, yyp, name): fig = plt.figure(1, figsize=(20, 40)) for i in range(8): x = xx[i] y = yy[i] yp = yyp[i] ax = fig.add_subplot(8, 4, i * 4 + 1) plt.scatter(x[:, 0], x[:, 1], label="source", s=5, c="r") plt.scatter(y[:, 0], y[:, 1], label="target", s=20, c="b", marker='x') plt.ylim(-3.5, 3.5) plt.xlim(-3.5, 3.5) ax.axis('off') ax = fig.add_subplot(8, 4, i * 4 + 2) plt.scatter(x[:, 0], x[:, 1], label="source", s=5, c="r") plt.scatter(yp[:, 0], yp[:, 1], label="transformed", s=5, c="r") for ii in range(len(x)): plt.arrow(x[ii, 0], x[ii, 1], (yp[ii, 0] - x[ii, 0]), (yp[ii, 1] - x[ii, 1]), head_width=0.03, head_length=0.08, fc='k', ec='k') plt.ylim(-3.5, 3.5) plt.xlim(-3.5, 3.5) ax.axis('off') ax = fig.add_subplot(8, 4, i * 4 + 3) plt.scatter(y[:, 0], y[:, 1], label="target", s=20, c="b", marker="x") plt.scatter(yp[:, 0], yp[:, 1], label="transformed", s=5, c="r") plt.ylim(-3.5, 3.5) plt.xlim(-3.5, 3.5) ax.axis('off') ax = fig.add_subplot(8, 4, i * 4 + 4) plt.scatter(x[:20, 0], x[:20, 1], label="source", s=5, c="r") plt.scatter(yp[:20, 0], yp[:20, 1], label="transformed", s=5, c="r") for ii in range(20): plt.arrow(x[ii, 0], x[ii, 1], (yp[ii, 0] - x[ii, 0]), (yp[ii, 1] - x[ii, 1]), head_width=0.04, head_length=0.04, fc='k', ec='k') # plt.ylim(-3.5, 3.5) # plt.xlim(-3.5, 3.5) ax.axis('off') # plt.show() plt.savefig(name, transparent=True) plt.close('all')
def plot_policy(self, policy, prefix, folder=None): if folder is None: folder = self.summary_path plt.clf() for idx in range(len(policy)): i, j = self.env.get_state_xy(idx) dx = 0 dy = 0 if policy[idx] == 0: # up dy = 0.35 elif policy[idx] == 1: # right dx = 0.35 elif policy[idx] == 2: # down dy = -0.35 elif policy[idx] == 3: # left dx = -0.35 elif self.env.not_wall(i, j) and policy[idx] == 4: # termination circle = plt.Circle( (j + 0.5, self.config.input_size[0] - i + 0.5 - 1), 0.025, color='k') plt.gca().add_artist(circle) if self.env.not_wall(i, j): plt.arrow(j + 0.5, self.config.input_size[0] - i + 0.5 - 1, dx, dy, head_width=0.05, head_length=0.05, fc='k', ec='k') else: plt.gca().add_patch( patches.Rectangle( (j, self.config.input_size[0] - i - 1), # (x,y) 1.0, # width 1.0, # height facecolor="gray")) plt.xlim([0, self.config.input_size[1]]) plt.ylim([0, self.config.input_size[0]]) for i in range(self.config.input_size[1]): plt.axvline(i, color='k', linestyle=':') plt.axvline(self.config.input_size[1], color='k', linestyle=':') for j in range(self.config.input_size[0]): plt.axhline(j, color='k', linestyle=':') plt.axhline(self.config.input_size[0], color='k', linestyle=':') plt.savefig( os.path.join(folder, "SuccessorFeatures_" + prefix + 'policy.png')) plt.close()
def plotPolicy(self, policy, prefix): plt.clf() for idx in range(len(policy)): i, j = self.env.getStateXY(idx) dx = 0 dy = 0 if policy[idx] == 0: # up dy = 0.35 elif policy[idx] == 1: # right dx = 0.35 elif policy[idx] == 2: # down dy = -0.35 elif policy[idx] == 3: # left dx = -0.35 elif self.matrixMDP[i][j] != -1 and policy[idx] == 4: # termination circle = plt.Circle((j + 0.5, self.numRows - i + 0.5 - 1), 0.025, color="k") plt.gca().add_artist(circle) if self.matrixMDP[i][j] != -1: plt.arrow( j + 0.5, self.numRows - i + 0.5 - 1, dx, dy, head_width=0.05, head_length=0.05, fc="k", ec="k", ) else: plt.gca().add_patch( patches.Rectangle( (j, self.numRows - i - 1), # (x,y) 1.0, # width 1.0, # height facecolor="gray", )) plt.xlim([0, self.numCols]) plt.ylim([0, self.numRows]) for i in range(self.numCols): plt.axvline(i, color="k", linestyle=":") plt.axvline(self.numCols, color="k", linestyle=":") for j in range(self.numRows): plt.axhline(j, color="k", linestyle=":") plt.axhline(self.numRows, color="k", linestyle=":") plt.savefig(self.outputPath + prefix + "policy.png") plt.close()
def loadings_plot(PCA_data, coeff, labels=None, x_comp=0, y_comp=1, alpha_level=0.5, arrow_colour="r", text_colour="g", dots_per_inch=500, size=1, text_size="small"): """loadings_plot Create a loadings plot to show the influence of each feature on a component Arguments: PCA_data """ #get the PC scores to plot x_score = PCA_data[:, x_comp] y_score = PCA_data[:, y_comp] scale_x = 1.0 / (x_score.max() - x_score.min()) scale_y = 1.0 / (y_score.max() - y_score.min()) n_features = coeff.shape[0] plt.subplots(dpi=dots_per_inch) plt.scatter(x_score * scale_x, y_score * scale_y, s=size) #set the text for the arrow if none is given if labels is None: labels = ["Var" + str(feat + 1) for feat in range(n_features)] #plot each feature arrow with label for feature in range(n_features): #plot the arrow plt.arrow(0, 0, coeff[feature, x_comp], coeff[feature, y_comp], alpha=alpha_level, color=arrow_colour) #plot the text for the arrow plt.text(coeff[feature, x_comp] * 1.15, coeff[feature, y_comp] * 1.15, labels[feature], color=text_colour, ha='center', va='center', size=text_size)
def riemann(with_time=True): # grid info xmin = 0.0 xmax = 1.0 nzones = 1 ng = 0 gr = gp.FVGrid(nzones, xmin=xmin, xmax=xmax) plt.clf() #------------------------------------------------------------------------ # plot a domain without ghostcells gr.draw_grid() gr.label_center(0, r"$i$", fontsize="medium") gr.label_edge(0, r"$i-\myhalf$", fontsize="medium") gr.label_edge(0, r"$i+\myhalf$", fontsize="medium", right_edge=True) plt.arrow(gr.xc[0]+0.05*gr.dx, 0.5, 0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) plt.arrow(gr.xc[0]-0.05*gr.dx, 0.5, -0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) gr.mark_cell_left_state(0, r"$a_{i-\myhalf,R}$", fontsize="large", color="b") gr.mark_cell_right_state(0, r"$a_{i+\myhalf,L}$", fontsize="large", color="b") gr.label_cell_center(0, r"$a_i$") gr.clean_axes(pad_fac=0.125, ylim=(-0.25, 1.0)) f = plt.gcf() f.set_size_inches(5.0,2.0) plt.tight_layout() plt.savefig("advection-states.png")
def plotOptControlTranslate(xs,posf): X,Y = [],[] arrow_len = 0.05 count = 0 for state in xs: x, y, th = np.asscalar(state[0])-posf[0], np.asscalar(state[1])-posf[1], np.asscalar(state[2]) if count%30 == 0: c, s = np.cos(th), np.sin(th) plt.arrow(x, y, c * arrow_len, s * arrow_len, head_width=.03) X.append(x) Y.append(y) count += 1 plt.arrow(x, y, np.cos(th) * arrow_len, np.sin(th) * arrow_len) plt.plot(X,Y)
def plotOptControl(xs): X,Y = [],[] arrow_len = 0.08 count = 0 for state in xs: x, y, th = np.asscalar(state[0]), np.asscalar(state[1]), np.asscalar(state[2]) if count%10 == 0: c, s = np.cos(th), np.sin(th) plt.arrow(x, y, c * arrow_len, s * arrow_len, head_width=.05) X.append(x) Y.append(y) count += 1 plt.arrow(x, y, np.cos(th) * arrow_len, np.sin(th) * arrow_len) plt.plot(X,Y)
def plot_measures(measure_point: geom.Point, vectors: List[geom.Vector], robot_vector: geom.Vector): for vector in vectors: res = vector.apply_to_point(measure_point) # print([measure_point.x, res.x], [measure_point.y, res.y]) pl.plot([measure_point.x, res.x], [measure_point.y, res.y], "b-") robot_vector.apply_to_point(measure_point) # pl.plot([measure_point.x, measure_point.x+robot_vector.x], [measure_point.y, measure_point.y+robot_vector.y]) pl.arrow(measure_point.x, measure_point.y, robot_vector.x, robot_vector.y, width=1)
def plotClothoid(clothoid, title): x, y, theta = clothoid[:, 0], clothoid[:, 1], clothoid[:, 2] plt.plot(x, y, lw=1) plt.title(title) arrow_len = 0.08 count = 0 for i in range(0, len(x)): if count % 100 == 0: c, s = np.cos(theta[i]), np.sin(theta[i]) plt.arrow(x[i], y[i], c * arrow_len, s * arrow_len, head_width=.05) count += 1 plt.arrow(x[-1], y[-1], np.cos(theta[-1]) * arrow_len, np.sin(theta[-1]) * arrow_len)
def show_compass(self, xw, yw, size=10.,color='red', head_width=20, **kwargs): if type(xw) == str: xw = self.hms2deg(xw) if type(yw) == str: yw = self.dms2deg(yw) r = xw + size/3600.*numpy.array([0,1,0]) d = yw + size/3600.*numpy.array([0,0,1]) rp, dp = self.world2pixel (r,d) arrow(rp[0], dp[0],rp[1]-rp[0], dp[1]-dp[0], color=color, head_width=head_width, **kwargs) arrow(rp[0], dp[0],rp[2]-rp[0], dp[2]-dp[0], color=color, head_width=head_width, **kwargs)
def plot_them_all_with_angle(x0, y0, colors, f, theta, Half_Field_of_view): plt.figure() # MY POSITION plt.scatter(x0, y0, color='black', marker='X', label=r'Your position', s=200) # RANGE OF WHAT WE SEE angle_max_right = theta + Half_Field_of_view angle_max_left = theta - Half_Field_of_view right_line_x = [] right_line_y = [] left_line_x = [] left_line_y = [] radius = np.linspace(0.01, x * 2, 100) for i in range(len(radius)): right_line_x.append(x0 + radius[i] * np.cos(angle_max_right)) left_line_x.append(x0 + radius[i] * np.cos(angle_max_left)) right_line_y.append(y0 + radius[i] * np.sin(angle_max_right)) left_line_y.append(y0 + radius[i] * np.sin(angle_max_left)) plt.plot(right_line_x, right_line_y, color='black') plt.plot(left_line_x, left_line_y, color='black') plt.xlabel(r'$X_0$') plt.ylabel(r'$Y_0$') plt.title(r'Real position') #plot CORNERS for i in range(len(colors)): plt.scatter(colors[i][0], colors[i][1], color=colors[i][3], s=100) #PLOT ARROW u = f * np.cos(theta) v = f * np.sin(theta) plt.arrow(x0, y0, u, v, head_width=0.05, head_length=0.1, fc='k', ec='k') plt.legend() plt.axis([-x * 1.3, x * 1.3, -x * 1.3, x * 1.3]) plt.savefig('img1.png', bbox='tight')
def myplot(score,coeff,labels=None): xs = score[:,0] ys = score[:,1] n = coeff.shape[0] scalex = 1.0/(xs.max() - xs.min()) scaley = 1.0/(ys.max() - ys.min()) plt.scatter(xs * scalex,ys * scaley, c = y) for i in range(n): plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5) if labels is None: plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center') else: plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center') plt.xlim(-1,1) plt.ylim(-1,1) plt.xlabel("PC{}".format(1)) plt.ylabel("PC{}".format(2)) plt.grid()
def subgraph_plot(self,GS): for g in GS.keys(): for i in GS[g]['V']: c,a,s = 'r',0.5,5 k = self.IV[i] plt.plot(self.V[k]['pos'][0],self.V[k]['pos'][1],marker='.',color=c, markersize=s,alpha=a) for i in GS[g]['E']: k = self.IE[i] P,K = tuple(k.split('@')) p1 = {'x':self.V[P]['pos'][0],'y':self.V[P]['pos'][1]} p2 = {'x':self.V[K]['pos'][0],'y':self.V[K]['pos'][1]} dx,dy = p2['x']-p1['x'],p2['y']-p1['y'] dist = pow(pow(dx,2)+pow(dy,2),0.5) a_w = dist/10 e_w = dist a = 0.01 plt.arrow(p1['x'],p1['y'],dx,dy,fc="k",ec="k",alpha=a, lw=e_w, head_width=a_w, head_length=a_w,length_includes_head=True)
def biplot(ranks, coeff, pc1, pc2, n_feats, rep, file_type): """ biplot function - specify output file type""" cmap = sns.color_palette("husl", len(uniqueDrugs)) sns.set_style('whitegrid') pcs = ('PC_%d' % (pc1), 'PC_%d' % (pc2)) for pc in range(len(pcs)): if pc == 1: for i in range(n_feats): plt.arrow(0,0,\ coeff[np.flip(pcs,axis=0)[pc]].iloc[ranks[pcs[pc]].index[i]], \ coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]],\ color = cmap[pc], alpha = 1, label = pcs[pc]) if coeff is None: continue else: plt.text (coeff[np.flip(pcs,axis =0)[pc]].iloc[ranks[pcs[pc]].index[i]]*3, \ coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]]*1.5, \ coeff['features'].iloc[ranks[pcs[pc]].index[i]], color = cmap[pc],\ ha = 'center', va='center') else: for i in range(n_feats): plt.arrow(0,0, coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]],\ coeff[np.flip(pcs,axis=0)[pc]].iloc[ranks[pcs[pc]].index[i]],\ color = cmap[pc], alpha = 1, label = pcs[pc]) if coeff is None: continue else: plt.text (coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]]*4, \ coeff[np.flip(pcs,axis =0)[pc]].iloc[ranks[pcs[pc]].index[i]]*3,\ coeff['features'].iloc[ranks[pcs[pc]].index[i]], color = cmap[pc],\ ha = 'center', va='center') plt.xlim(-1, 1) plt.ylim(-1, 1) #plt.axis('equal') plt.xlabel('PC_1') plt.ylabel('PC_2') plt.legend() plt.savefig(os.path.join(directory[0:-7], 'Figures', rep + '_biplot.' + file_type), dpi=200) plt.show()
def test(): data = multivariate_normal([0, 0], [[1, 2], [2, 5]], 100) ### PCA pc_base = pca(data, base_num = 1)[0] ### Plotting fig = pl.figure() fig.add_subplot(1,1,1) pl.axvline(x=0, color = "#000000") pl.axhline(y=0, color = "#000000") ### Plot data pl.scatter(data[:, 0], data[:, 1]) ### Draw the 1st principal axis pc_line = array([-3., 3.]) * (pc_base[1] / pc_base[0]) pl.arrow(0, 0, -pc_base[0] * 2, -pc_base[1] * 2, fc = "r", width = 0.15, head_width = 0.45) pl.plot([-3, 3], pc_line, "r") ### Settings pl.xticks(size = 15) pl.yticks(size = 15) pl.xlim([-3, 3]) pl.tight_layout() pl.show()
def plot_direction(xmin,xmax,ymin,ymax): dx = (xmax-xmin) dy = (ymax-ymin) x_arrow = dx*1.5/10.+xmin y_arrow = dy*1.5/10.+ymin dxy_arrow = dx*1./35. x_N0 = x_arrow y_N0 = y_arrow dx_N1 = -dxy_arrow*np.tan(np.radians(69)) dy_N1 = dxy_arrow hw_arrow = (xmax-xmin)*1./50. hl_arrow = (ymax-ymin)*1./50. plt.arrow(x_N0,y_N0,dx_N1,dy_N1,fc='black',ec='black',\ linewidth=1,head_width=hw_arrow,head_length=hl_arrow) plt.text(x_N0+dx_N1*1.4,y_N0+dy_N1*1.3,'N',rotation=69,fontsize=10) dx_E1 = -dxy_arrow dy_E1 = -dxy_arrow*np.tan(np.radians(69)) plt.arrow(x_N0,y_N0,dx_E1,dy_E1,fc='black',ec='black',\ linewidth=1,head_width=hw_arrow,head_length=hl_arrow) plt.text(x_N0+dx_E1*0.9,y_N0+dy_E1*1.5,'E',rotation=69,fontsize=10) return
def biplot(ranks, coeff, pc1, pc2, n_feats, rep): """ biplot function """ pcs = ('PC_%d' % (pc1), 'PC_%d' % (pc2)) for pc in range(len(pcs)): if pc == 1: for i in range(n_feats): plt.arrow(0,0,\ coeff[np.flip(pcs,axis=0)[pc]].iloc[ranks[pcs[pc]].index[i]], \ coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]],\ color = cmap[pc], alpha = 1, label = pcs[pc]) if coeff is None: continue else: plt.text (coeff[np.flip(pcs,axis =0)[pc]].iloc[ranks[pcs[pc]].index[i]]*1.5, \ coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]]*1.5, \ coeff['features'].iloc[ranks[pcs[pc]].index[i]], color = cmap[pc],\ ha = 'center', va='center') else: for i in range(n_feats): plt.arrow(0,0, coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]],\ coeff[np.flip(pcs,axis=0)[pc]].iloc[ranks[pcs[pc]].index[i]],\ color = cmap[pc], alpha = 1, label = pcs[pc]) if coeff is None: continue else: plt.text (coeff[pcs[pc]].iloc[ranks[pcs[pc]].index[i]]*4, \ coeff[np.flip(pcs,axis =0)[pc]].iloc[ranks[pcs[pc]].index[i]]*1.5,\ coeff['features'].iloc[ranks[pcs[pc]].index[i]], color = cmap[pc],\ ha = 'center', va='center') plt.xlim(-1, 1) plt.ylim(-1, 1) #plt.axis('equal') plt.xlabel('PC_1') plt.ylabel('PC_2') plt.legend() plt.savefig(os.path.join(directory[0:-7], 'Figures', rep + '_biplot.tif'), dpi=200) plt.show()
def regress_plot(): F = open('regressdata.pkl', 'rb') x, y, r, m, b = pickle.load(F) fig, ax = plt.subplots() plt.scatter(x, y) plt.plot(x, r) plt.xlim(x[0], x[-1]) plt.ylim(.94, .96) ax_left, ax_right, ax_lo, ax_hi = plt.axis() region_below = matplotlib.patches.Rectangle((x[0], ax_lo), x[-1] - x[0], .95 - ax_lo, color='red', alpha=.3) ax.add_patch(region_below) region_above = matplotlib.patches.Rectangle((x[0], 0.95), x[-1] - x[0], ax_hi - .95, color='green', alpha=.3) ax.add_patch(region_above) plt.xlabel('Sample Size') plt.ylabel('Confidence Level') rstar = (0.95 - b) / m plt.arrow(rstar, .948, 0., .0013, fc='k', ec='k', head_width=20, head_length=.0003) plt.text(rstar, .9474, 'Estimate of Needed Sample Size') plt.text(9600, .9593, 'True Model Has n=100 Channels') plt.text(9600, .9587, 'Alternative Has 99 Channels') plt.text(9600, .9581, 'Probability of Opening: p=0.1') plt.show() return fig, ax
def plot(self): ax = plt.gca() reject = matplotlib.patches.Rectangle((-12, 0), 12, 12, color='red', alpha=.3) accept = matplotlib.patches.Rectangle((0, 0), 2, 12, color='green', alpha=.3) ax.add_patch(reject) ax.add_patch(accept) plt.hist(H.AIC.T, 1000, normed=True, color='black') plt.axis([-3, 1, 0, 12]) plt.title('Histogram of AIC Differences') plt.xlabel('AIC Difference') plt.ylabel('Density') mAIC = numpy.mean(H.AIC) plt.arrow(mAIC, 3.5, 0, -2.1, fc="k", ec="k", head_width=0.05, head_length=0.1) plt.text(mAIC - .1, 3.75, "Mean \n= $2 D_{KL}$") plt.text(-2.5, 11.4, "Alternative Incorrectly Selected") percenttrue = (numpy.sum(H.AIC > 0) * 100) / numpy.size(H.AIC) plt.text(-1.75, 11, str(100 - percenttrue) + '%') plt.text(.1, 11.4, "True Selected") plt.text(.35, 11, str(percenttrue) + '%') # props = dict(boxstyle='round',facecolor='wheat',alpha=0.5) # ax.text(-2.2,5,"Comparing 3-state true model:\n $C_1$ --> $C_0$ --> $O$; $q_1$ = 1/4, $q_0$ = 1/2\n\nTo 2-state alternative:\n $C$ --> $O$; $q$ = 1/6",bbox=props) plt.show()
def rh(): # grid info xl = 0.0 xr = 1.0 dx = xr - xl xc = 0.5*(xl + xr) t0 = 0.0 t1 = 1.0 dt = t1 - t0 # plot a square representing [x, x+dx] x [t, t+dt] # x-axis plt.arrow(0, 0, 1.3*dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(1.35*dx, 0, r"$x$", fontsize=20, verticalalignment="center") plt.text(dx, -0.1, r"$x_r$", fontsize=20) plt.text(0, -0.1, r"$x_l$", fontsize=20) # time axis plt.arrow(0, 0, 0, 1.3*dt, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(0, 1.35*dt, r"$t$", fontsize=20, horizontalalignment="center") plt.text(-0.17, dt, r"$t^{n+1}$", fontsize=20) plt.text(-0.17, 0, r"$t^n$", fontsize=20) # space-time volume plt.plot([dx,dx], [0,dt], ls="--", color="0.5", lw=2) plt.plot([0,dx], [dt,dt], ls="--", color="0.5", lw=2) # diagonal representing S plt.plot([0,dx], [0,dt], color="k", lw=5, solid_capstyle="butt") plt.annotate(r"shock: $S = \Delta x / \Delta t$", xy=(0.74*dx,0.76*dt), xytext=(0.2*dx, 1.2*dt), textcoords="data", fontsize=18, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # states plt.text(0.66*dx, 0.33*dt, r"$u_r$", color="k", fontsize=20) plt.text(0.33*dx, 0.66*dt, r"$u_l$", color="k", fontsize=20) # fluxes plt.arrow(-0.1*dx, 0.5*dt, 0.2*dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, edgecolor="r", facecolor="r", length_includes_head=True, zorder=100) plt.text(-0.12*dx, 0.5*dt, r"$f = f(u_l)$", horizontalalignment="right", verticalalignment="center", color="r", fontsize=18) plt.arrow(0.9*dx, 0.5*dt, 0.2*dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, edgecolor="r", facecolor="r", length_includes_head=True, zorder=100) plt.text(1.12*dx, 0.5*dt, r"$f = f(u_r)$", horizontalalignment="left", verticalalignment="center", color="r", fontsize=18) plt.axis("off") plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) plt.xlim(-0.4,1.4*dx) plt.ylim(-0.1,1.4*dx) f = plt.gcf() f.set_size_inches(7.0,6.0) plt.savefig("rh.pdf")
def decision_boundary_plot(svm, features, vectors, labels, kernel, fileName = None, **args) : title = None if 'title' in args : title = args['title'] xlabel = None if 'xlabel' in args : xlabel = args['xlabel'] ylabel = None if 'ylabel' in args : ylabel = args['ylabel'] fontsize = 'medium' if 'fontsize' in args : fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args : contourFontsize = args['contourFontsize'] showColorbar = True if 'showColorbar' in args : showColorbar = args['showColorbar'] show = True if fileName is not None : show = False if 'show' in args : show = args['show'] # setting up the grid delta = 0.005 x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float_) gridX = numpy.zeros((len(x) *len(y), 2), numpy.float_) n = 0 for i in range(len(x)) : for j in range(len(y)) : gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if kernel.get_name() == 'Linear' and 'customwandb' in args: kernel.init_optimization_svm(svm) b=svm.get_bias() w=kernel.get_w() kernel.set_w(args['customwandb'][0]) svm.set_bias(args['customwandb'][1]) if kernel.get_name() == 'Linear' and 'drawarrow' in args: kernel.init_optimization_svm(svm) b=svm.get_bias() w=kernel.get_w() s=1.0/numpy.dot(w,w)/1.17 pylab.arrow(0,-b/w[1], w[0]*s,s*w[1], width=0.01, fc='#dddddd', ec='k') grid_features = RealFeatures(numpy.transpose(gridX)) results = svm_test(svm, kernel, features, grid_features) n = 0 for i in range(len(x)) : for j in range(len(y)) : Z[i][j] = results[n] n += 1 cdict = {'red' :((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), 'green':((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), 'blue' :((0.0, 0.6, 0.6),(0.5, 0.8, 0.8),(1.0, 1.0, 1.0)), } my_cmap = matplotlib.colors.LinearSegmentedColormap('lightgray',cdict,256) im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=my_cmap, extent=(xmin,xmax,ymin,ymax) ) if 'decisionboundaryonly' in args: C1 = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors = ['k'], extent=(xmin,xmax,ymin,ymax)) else: C1 = pylab.contour(numpy.transpose(Z), [-1,0,1], origin='lower', linewidths=(1,3,1), colors = ['k','k'], extent=(xmin,xmax,ymin,ymax)) pylab.clabel(C1, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data lab=labels.get_labels() vec=numpy.array(vectors) idx=numpy.where(lab==-1)[0] pylab.scatter(vec[idx,0], vec[idx,1], s=300, c='#4444ff', marker='o', alpha=0.8, zorder=100) idx=numpy.where(lab==+1)[0] pylab.scatter(vec[idx,0], vec[idx,1], s=500, c='#ff4444', marker='s', alpha=0.8, zorder=100) # plot SVs if not 'decisionboundaryonly' in args: training_outputs = svm_test(svm, kernel, features, features) sv_idx=numpy.where(abs(training_outputs)<=1.01)[0] pylab.scatter(vec[sv_idx,0], vec[sv_idx,1], s=100, c='k', marker='o', alpha=0.8, zorder=100) if 'showmovedpoint' in args: x=-0.779838709677 y=-0.1375 pylab.scatter([x], [y], s=300, c='#4e4e61', marker='o', alpha=1, zorder=100, edgecolor='#454548') pylab.arrow(x,y-0.1, 0, -0.8/1.5, width=0.01, fc='#dddddd', ec='k') #pylab.show() if title is not None : pylab.title(title, fontsize=fontsize) if ylabel: pylab.ylabel(ylabel,fontsize=fontsize) if xlabel: pylab.xlabel(xlabel,fontsize=fontsize) if showColorbar : pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None : pylab.savefig(fileName) if show : pylab.show()
def rh(): # grid info xl = 0.0 xr = 1.0 dx = xr - xl xc = 0.5 * (xl + xr) t0 = 0.0 t1 = 1.0 dt = t1 - t0 # plot a square representing [x, x+dx] x [t, t+dt] # x-axis plt.arrow(0, 0, 1.3 * dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(1.35 * dx, 0, r"$x$", fontsize=20, verticalalignment="center") plt.text(dx, -0.1, r"$x_r$", fontsize=20) plt.text(0, -0.1, r"$x_l$", fontsize=20) # time axis plt.arrow(0, 0, 0, 1.3 * dt, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(0, 1.35 * dt, r"$t$", fontsize=20, horizontalalignment="center") plt.text(-0.17, dt, r"$t^{n+1}$", fontsize=20) plt.text(-0.17, 0, r"$t^n$", fontsize=20) # space-time volume plt.plot([dx, dx], [0, dt], ls="--", color="0.5", lw=2) plt.plot([0, dx], [dt, dt], ls="--", color="0.5", lw=2) # diagonal representing S plt.plot([0, dx], [0, dt], color="k", lw=5, solid_capstyle="butt") plt.annotate(r"shock: $S = \Delta x / \Delta t$", xy=(0.74 * dx, 0.76 * dt), xytext=(0.2 * dx, 1.2 * dt), textcoords="data", fontsize=18, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # states plt.text(0.66 * dx, 0.33 * dt, r"$u_r$", color="k", fontsize=20) plt.text(0.33 * dx, 0.66 * dt, r"$u_l$", color="k", fontsize=20) # fluxes plt.arrow(-0.1 * dx, 0.5 * dt, 0.2 * dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, edgecolor="r", facecolor="r", length_includes_head=True, zorder=100) plt.text(-0.12 * dx, 0.5 * dt, r"$f = f(u_l)$", horizontalalignment="right", verticalalignment="center", color="r", fontsize=18) plt.arrow(0.9 * dx, 0.5 * dt, 0.2 * dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, edgecolor="r", facecolor="r", length_includes_head=True, zorder=100) plt.text(1.12 * dx, 0.5 * dt, r"$f = f(u_r)$", horizontalalignment="left", verticalalignment="center", color="r", fontsize=18) plt.axis("off") plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) plt.xlim(-0.4, 1.4 * dx) plt.ylim(-0.1, 1.4 * dx) f = plt.gcf() f.set_size_inches(7.0, 6.0) plt.savefig("rh.pdf")
def main(w,idl,corrr): ############################The constants&variables######################################## n2 = 2.5e-20 #Silica 1.1225783990826979e-20 # nonlinear coefficient lamda_c = 1.5508e-6 # the central freequency that the betas are calculated around seeds = 100 num_eval = 1000 num_steps = 1000 # initial number of steps for the integrator d = 1e3 # propagation distance monte_carlo_average = True print "monte_carlo_average" , monte_carlo_average if monte_carlo_average: noise_floor = -60+30.5-1.6897557023157006 #[dbm] The lowest that the detector is seeing noise_floor = dbm2w(noise_floor) else: noise_floor = 0 zmin =0 #starting point of the fibre zmax = d #end point of interest z = np.linspace(zmin,zmax,num_steps) #linearly spaced propagation vector dz = 1 * (z[1] - z[0]) num_steps = (zmax - zmin) / dz +1 lam_meas = np.loadtxt('convers/pump_wavelengths.csv') #w = 0 # which pump2 wavelength? meas = read_csv(w) if monte_carlo_average: FWM_func = FWM_monte else: FWM_func = FWM # Loading the conversion effiency data #What beam is in what mode B = [] B.append('lp01') #pump1 B.append('lp11') #pump2 B.append('lp01') #sigal B.append('lp11') #Idler LP01_cor = 0.6152567345983897 #[dBm] LP11_cor = -1.77386603355#[dBm] #The power and wavelength inputs P_vec1 = dbm2w(np.array([30.5 + LP01_cor])) P_vec2 = dbm2w(np.array([30.5 + LP11_cor - corrr])) P_signal_vec = dbm2w(np.array([30.5-25 +LP01_cor])) lamp1 = np.array([1549]) * 1e-9 lamp2 = np.array([lam_meas[w]])*1e-9 lams =np.array([1548.8]) * 1e-9 # guess lam_variation = np.linspace(1.549,1.5525,512)*1e-6 ########################################################################################## if idl == 'bs': P_vec1,P_signal_vec = P_signal_vec,P_vec1 ###############################Find the overlaps#################################### w_vec = np.loadtxt('../loading_data/widths.dat') w_vec *=1e6 overlap1,overlap2,zeroing = calc_overlaps(B,w_vec) print('calculated the overlaps going for the ode') #################################################################################### ###########Find where the optimum freequency for signal is and plot the waves in vecor format for that freequency######################################################## mat_lp = loadmat('../loading_data/coeffs.mat') lami = [] lams_min = fsolve(effective_phase_matching,lams,args = (n2,P_vec1,P_vec2,P_signal_vec,lamp1,lamp2,lami,dz,num_steps,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2)) ########################################################################################################################################################################## #################################################Do the FWM for the optimum wavelength################################################################# lams = lams_min AB_final = np.zeros([4,len(P_vec1),len(P_vec2),len(P_signal_vec),len(lamp1),len(lamp2),len(lams)],dtype='complex') Dk_vec = np.zeros([len(lamp1),len(lamp2),len(lams)]) AB_final,lami,Dk = FWM(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lams[0],0,lamp2,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2,noise_floor,seeds,num_eval,idl) ######################################################################################################################################################## ###############################################################Plot the arrows########################################################################## lam_arrows = np.array([lamp1[0],lamp2[0],lams[0],lami[-1::][0]]) lam_arrows *=1e6 powers_arrows = [] for i in range(4): powers_arrows.append(w2dbm(np.abs(AB_final[i,0,0,0,0,0,0])**2)) powers_arrows = np.asanyarray(powers_arrows) colours = ['red','green','blue','black'] waves = ['pump1','pump2','signal','idler'] fig = plt.figure(figsize=(20.0, 10.0)) plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) #fig.set_size_inches(100,100) plt.ylim(-40,35) plt.xlim(min(lam_arrows)- min(lam_arrows)*0.001,max(lam_arrows)+max(lam_arrows)*0.001) plt.xlabel(r'$\lambda ( \mu m)$') plt.ylabel(r'$P(dBm)$') arrow = [1,2,3,4] for i in range(4): arrow[i] = plt.arrow(lam_arrows[i],-40,0,powers_arrows[i]+40,head_width=1e-4,head_length=1,width = 1e-12,length_includes_head=True,color=colours[i]) plt.legend([arrow[0],arrow[1],arrow[2],arrow[3]], [waves[0]+','+B[0],waves[1]+','+B[1],waves[2]+','+B[2],waves[3]+','+B[3]],loc=0) plt.title('Linear phase matching:'+ r'$\lambda_s = $'+str(lams_min[0]*1e6)+r'$\mu m$') plt.savefig('arrows.png',bbox_inches='tight') plt.close(fig) ######################################################################################################################################################### #############################################################################Do the calculations for a wide grid################################################################################### #if idl=='bs': # lamp1 = lam_variation #else: # lams = lam_variation ##sys.exit() lams = lam_variation AB_final = np.zeros([4,len(P_vec1),len(P_vec2),len(P_signal_vec),len(lamp1),len(lamp2),len(lams)],dtype='complex') Dk_vec = np.zeros([len(lamp1),len(lamp2),len(lams)]) #A = Parallel(n_jobs=6)(delayed(FWM)(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lams_,n,lamp2,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2,noise_floor) for n,lams_ in enumerate(lams)) #if idl == 'pc': A = Parallel(n_jobs=6)(delayed(FWM_func)(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lams_,n,lamp2,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2,noise_floor,seeds,num_eval,idl) for n,lams_ in enumerate(lams)) A = np.asanyarray(A) #AB_final = A[:,0] lami = np.zeros(len(lam_variation)) Dk = np.zeros([len(lamp2)]) for i in range(len(lams)): lami[i] = A[:,1][i][1] for j in range(4): AB_final[j,0,0,0,0,0,i] =A[i,0][j][0][0][0][0][0][i] print "Energy conservation check. Worst case senario:", energy_conservation(P_vec1,P_vec2,P_signal_vec,AB_final) #sys.exit() Powers = np.zeros(np.shape(AB_final)) Powers = w2dbm(np.abs(AB_final)**2) Powers -= np.max(Powers) #AB_final = dbm2w(w2dbm(AB_final) - np.max(w2dbm(AB_final))) #maxim = 0#np.max(w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2)) conv_eff = np.zeros(len(lams)) if idl == 'pc': #conv_eff[:] = w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2) - w2dbm(np.abs(AB_final[2,0,0,0,0,0,:])**2) conv_eff[:] = Powers[3,0,0,0,0,0,:] - Powers[2,0,0,0,0,0,:] else: #conv_eff[:] = w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2) - w2dbm(np.abs(AB_final[0,0,0,0,0,0,:])**2) conv_eff[:] = Powers[3,0,0,0,0,0,:] - Powers[0,0,0,0,0,0,:] #plotter(lams,lami,Powers[3,0,0,0,0,0,:],'idler_large') #plotter(lams,lami,Powers[2,0,0,0,0,0,:],'signal_large') #plotter(lams,lami,Powers[1,0,0,0,0,0,:],'pump2_large') #plotter(lams,lami,Powers[0,0,0,0,0,0,:],'pump1_large') plotter(lams,lami,Powers[3,0,0,0,0,0,:],'idler_large') plotter(lams,lami,Powers[2,0,0,0,0,0,:],'signal_large') plotter(lams,lami,Powers[1,0,0,0,0,0,:],'pump2_large') plotter(lams,lami,Powers[0,0,0,0,0,0,:],'pump1_large') #plotter(lams,lami,w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2),'idler_large') #plotter(lami,lams,w2dbm(np.abs(AB_final[2,0,0,0,0,0,:])**2),'signal_large') #plotter(lams,lami,w2dbm(np.abs(AB_final[1,0,0,0,0,0,:])**2),'pump2_large') #plotter(lams,lami,w2dbm(np.abs(AB_final[0,0,0,0,0,0,:])**2),'pump1_large') """ #else: A = Parallel(n_jobs=6)(delayed(FWM_func)(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lams,lamp1_,l,lamp2,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2,noise_floor,seeds,num_eval) for l,lamp1_ in enumerate(lamp1)) A = np.asanyarray(A) #AB_final = A[:,0] lami = np.zeros(len(lam_variation)) Dk = np.zeros([len(lamp2)]) for i in range(len(lams)): lami[i] = A[:,1][i][1] for j in range(4): AB_final[j,0,0,0,i,0,0] =A[i,0][j][0][0][0][i][0][0] AB_final = dbm2w(w2dbm(AB_final) - np.max(w2dbm(AB_final))) maxim = 0#np.max(w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2)) conv_eff = np.zeros(len(lams)) conv_eff[:] = w2dbm(np.abs(AB_final[3,0,0,0,:,0,0])**2) - w2dbm(np.abs(AB_final[2,0,0,0,:,0,0])**2) plotter(lams,lami,w2dbm(np.abs(AB_final[3,0,0,0,:,0,0])**2),'idler_large') plotter(lams,lami,w2dbm(np.abs(AB_final[0,0,0,0,:,0,0])**2),'power_large') """ plotter(lams,lami,conv_eff,'conv_large') #plotter_deturing(, , 'conv_deturing_large') plotter_deturing(np.abs(lami-lamp2),conv_eff,meas.lam,eval('meas.'+idl),'det2'+str(-1*corrr)+'/conversion_effieicny_det_'+idl+'_'+str(w)) #plotter(lams,lami[::-1],w2dbm(np.abs(AB_final[3,0,0,0,0,0,:])**2),'idler_large') #plotter(lams,lami[::-1],w2dbm(conv_eff),'conv_large') #plotter_deturing(lami[::-1]-lams, w2dbm(conv_eff), 'conv_deturing_large') ################################################################################################################################################################################################### return AB_final
def plot(self, P): ax = plt.gca() reject = matplotlib.patches.Rectangle((0, 75), 50, 20, color='red', alpha=.3) accept = matplotlib.patches.Rectangle((0, 95), 50, 5, color='green', alpha=.3) ax.add_patch(reject) ax.add_patch(accept) plt.plot(range(1, 51), numpy.array(self.prop) * 100, '*') plt.xlabel("Number of Independent Repetitions of Experiment (N)") plt.ylabel("P(True Model Selected), ($P_N$, Percent)") plt.text(.5, 99, "Selection Correct Sufficiently Often") plt.text(.5, 94, "Selection Correct Insufficiently Often") P.theoretical() v = plt.axis() plt.plot(range(1, 51), numpy.array(P.PNtheo) * 100, 'b') plt.axis(v) P.theo2(PN) plt.plot(range(1, 51), numpy.array(P.PNtheo2) * 100, 'b--') plt.legend( ("Monte Carlo estimate (considered exact)", "Central Limit Theorem (CLT) estimate", "Adjusted CLT estimate"), loc=4) N0 = numpy.where(numpy.array(P.PNtheo) >= 0.95)[0][0] + 1 N1 = numpy.where(numpy.array(P.PNtheo2) >= 0.95)[0][0] + 1 Ns = numpy.where(numpy.array(self.prop) >= 0.95)[0][0] + 1 plt.arrow(N0, 87.6, 0, 4.5, fc="k", ec="k", head_width=0.5, head_length=0.7) # plt.arrow(N1,89.1,0,5, fc="k", ec="k", head_width=0.5, head_length=0.7) plt.arrow(N1, 87.6, 0, 6, fc="k", ec="k", head_width=0.5, head_length=0.7) plt.arrow(Ns, 89.1, 0, 4.5, fc="k", ec="k", head_width=0.5, head_length=0.7) plt.text(N0 - .6, 86.7, "$N_0$") plt.text(N1 - .6, 86.7, "$N_1$") plt.text(Ns - .6, 88.3, "$N^*$") plt.show()
def decision_boundary_plot(svm, features, vectors, labels, kernel, fileName=None, **args): title = None if 'title' in args: title = args['title'] xlabel = None if 'xlabel' in args: xlabel = args['xlabel'] ylabel = None if 'ylabel' in args: ylabel = args['ylabel'] fontsize = 'medium' if 'fontsize' in args: fontsize = args['fontsize'] contourFontsize = 10 if 'contourFontsize' in args: contourFontsize = args['contourFontsize'] showColorbar = True if 'showColorbar' in args: showColorbar = args['showColorbar'] show = True if fileName is not None: show = False if 'show' in args: show = args['show'] # setting up the grid delta = 0.005 x = arange(xmin, xmax, delta) y = arange(ymin, ymax, delta) Z = numpy.zeros((len(x), len(y)), numpy.float_) gridX = numpy.zeros((len(x) * len(y), 2), numpy.float_) n = 0 for i in range(len(x)): for j in range(len(y)): gridX[n][0] = x[i] gridX[n][1] = y[j] n += 1 if kernel.get_name() == 'Linear' and 'customwandb' in args: kernel.init_optimization_svm(svm) b = svm.get_bias() w = kernel.get_w() kernel.set_w(args['customwandb'][0]) svm.set_bias(args['customwandb'][1]) if kernel.get_name() == 'Linear' and 'drawarrow' in args: kernel.init_optimization_svm(svm) b = svm.get_bias() w = kernel.get_w() s = 1.0 / numpy.dot(w, w) / 1.17 pylab.arrow(0, -b / w[1], w[0] * s, s * w[1], width=0.01, fc='#dddddd', ec='k') grid_features = RealFeatures(numpy.transpose(gridX)) results = svm_test(svm, kernel, features, grid_features) n = 0 for i in range(len(x)): for j in range(len(y)): Z[i][j] = results[n] n += 1 cdict = { 'red': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.6, 0.6), (0.5, 0.8, 0.8), (1.0, 1.0, 1.0)), } my_cmap = matplotlib.colors.LinearSegmentedColormap( 'lightgray', cdict, 256) im = pylab.imshow(numpy.transpose(Z), interpolation='bilinear', origin='lower', cmap=my_cmap, extent=(xmin, xmax, ymin, ymax)) if 'decisionboundaryonly' in args: C1 = pylab.contour(numpy.transpose(Z), [0], origin='lower', linewidths=(3), colors=['k'], extent=(xmin, xmax, ymin, ymax)) else: C1 = pylab.contour(numpy.transpose(Z), [-1, 0, 1], origin='lower', linewidths=(1, 3, 1), colors=['k', 'k'], extent=(xmin, xmax, ymin, ymax)) pylab.clabel(C1, inline=1, fmt='%1.1f', fontsize=contourFontsize) # plot the data lab = labels.get_labels() vec = numpy.array(vectors) idx = numpy.where(lab == -1)[0] pylab.scatter(vec[idx, 0], vec[idx, 1], s=300, c='#4444ff', marker='o', alpha=0.8, zorder=100) idx = numpy.where(lab == +1)[0] pylab.scatter(vec[idx, 0], vec[idx, 1], s=500, c='#ff4444', marker='s', alpha=0.8, zorder=100) # plot SVs if not 'decisionboundaryonly' in args: training_outputs = svm_test(svm, kernel, features, features) sv_idx = numpy.where(abs(training_outputs) <= 1.01)[0] pylab.scatter(vec[sv_idx, 0], vec[sv_idx, 1], s=100, c='k', marker='o', alpha=0.8, zorder=100) if 'showmovedpoint' in args: x = -0.779838709677 y = -0.1375 pylab.scatter([x], [y], s=300, c='#4e4e61', marker='o', alpha=1, zorder=100, edgecolor='#454548') pylab.arrow(x, y - 0.1, 0, -0.8 / 1.5, width=0.01, fc='#dddddd', ec='k') #pylab.show() if title is not None: pylab.title(title, fontsize=fontsize) if ylabel: pylab.ylabel(ylabel, fontsize=fontsize) if xlabel: pylab.xlabel(xlabel, fontsize=fontsize) if showColorbar: pylab.colorbar(im) # colormap: pylab.hot() if fileName is not None: pylab.savefig(fileName) if show: pylab.show()
def domains(method="FTCS"): # grid info xl = 0.0 xc = 1.0 xr = 2.0 dx = xr - xc t0 = 0.0 t1 = 1.0 dt = t1 - t0 C = 0.6 xp = xc - C*dx plt.clf() # plot a square representing [x, x+dx] x [t, t+dt] # x-axis plt.arrow(0, 0, 2.5*dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(2.55*dx, 0, r"$x$", fontsize=16, verticalalignment="center") # x points labeled for p, l in [((xc, 0), r"$x_i$"), ((xl, 0), r"$x_{i-1}$"), ((xr, 0), r"$x_{i+1}$")]: plt.text(p[0], p[1]-0.07, l, fontsize=16, horizontalalignment="center", verticalalignment="top") plt.plot([p[0], p[0]], [p[1], p[1]-0.04], color="k") plt.text(xp, -0.07, r"$x_i - C \Delta x$", fontsize=16, horizontalalignment="center", verticalalignment="top") plt.plot([xp, xp], [0, -0.04], color="k") # points plt.scatter([xl, xc, xr, xc], [0, 0, 0, dt], color="C3", marker="o", s=40, zorder=1000, alpha=1.0) # data points eps = 0.02*dx for p, l in [((xl, 0), r"$a_{i-1}^n$"), ((xc, 0), r"$a_{i}^n$"), ((xr, 0), r"$a_{i+1}^n$"), ((xc, dt), r"$a_{i}^{n+1}$")]: plt.text(p[0]+eps, p[1]+eps, l, horizontalalignment="left", verticalalignment="bottom", fontsize=16, color="C3", zorder=1000) # time axis plt.arrow(0, 0, 0, 1.3*dt, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(0, 1.35*dt, r"$t$", fontsize=16, horizontalalignment="center") plt.text(-0.25, dt, r"$t^{n+1}$", fontsize=16) plt.plot([-0.04, 0], [dt, dt], color="k") plt.text(-0.25, 0, r"$t^n$", fontsize=16) plt.plot([-0.04, 0], [0, 0], color="k") plt.plot([0, 2.0*dx], [dt, dt], ls=":", color="0.5") plt.plot([dx, dx], [0, dt], ls=":", color="0.5") plt.plot([2.0*dx, 2.0*dx], [0, dt], ls=":", color="0.5") # domain of dependence if method == "upwind": plt.fill([0, xc, xc, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) elif method == "FTCS": plt.fill([0, xc, xr, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) elif method == "downwind": plt.fill([xc, xc, xr, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) # true domain of dependence plt.fill([xp, xc, xc, 0], [0, dt, 0, 0], color="C1", lw=2, alpha=0.5) # label plt.text(xr+0.1*dx, 0.5*dt, method, fontsize=16, horizontalalignment="left") plt.axis("off") plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) plt.xlim(-0.4,2.8*dx) plt.ylim(-0.1,1.4*dx) f = plt.gcf() f.set_size_inches(9.0,5.0) plt.tight_layout() plt.savefig("domains_{}.pdf".format(method), bbox_inches="tight")
def main(): ############### The constants n2 = 1.1225783990826979e-20 # nonlinear coefficient lamda_c = 1.5508e-6 # the central freequency that the betas are calculated around ############### num_steps = 10 # initial number of steps for the integrator d = 1e3 # propagation distance zmin =0 #starting point of the fibre zmax = d #end point of interest z = np.linspace(zmin,zmax,num_steps) #linearly spaced propagation vector dz = 1 * (z[1] - z[0]) num_steps = (zmax - zmin) / dz +1 ############## What beam is in what mode B = [] B.append('lp01') #pump1 B.append('lp11') #pump2 B.append('lp01') #sigal B.append('lp11') #Idler ############# w_vec = np.loadtxt('../loading_data/widths.dat') w_vec *=1e6 overlap1,overlap2,zeroing = calc_overlaps(B,w_vec) print('calculated the overlaps going for the ode') #sys.exit() #P_vec1,P_vec2, P_signal_vec, lamp1,lamp2,lams,lami = input_powers_wavelengths() lami = [] ############ For the brag scattering inputs P_vec1 = dbm2w(np.array([18.0+3.3+10])) P_vec2 = dbm2w(np.array([13.8+3.3+10]))#dbm2w(np.array([-5]))*np.ones(len(P_vec2))+ dbm2w(10) P_signal_vec = dbm2w(np.array([-15.0+10]))#dbm2w(np.array([-7.5]))*np.ones(len(P_vec2)) - dbm2w(np.array([-42,-43,-45,-46,-45])) #P_signal_vec = dbm2w(P_signal_vec) lamp1 = np.array([1549.8]) * 1e-9 lamp2 = np.array([1553.8e-9]) # guess lams =np.array([1548.8]) * 1e-9 ########### ########### Find where the optimum freequency for pump2 is and plot the waves in vecor format for that freequency mat_lp = loadmat('../loading_data/coeffs.mat') lamp_min = fsolve(effective_phase_matching,lamp2,args = (n2,P_vec1,P_vec2,P_signal_vec,lamp1,lams,lami,dz,num_steps,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2)) lamp2 = lamp_min#np.arange(1.546,1.558,0.0001)*1e-6##np.array([1552.6,1553.7,1553.9,1554.1,1554.2]) * 1e-9# AB_final = np.zeros([4,len(P_vec1),len(P_vec2),len(P_signal_vec),len(lamp1),len(lamp2),len(lams)],dtype='complex') Dk_vec = np.zeros([len(lamp1),len(lamp2),len(lams)]) AB_final,lami,Dk = FWM(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lamp2,0,lams,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2) #plt.plot(lamp2*1e6,Dk[0,:,0]) #plt.show() lam_arrows = np.array([lamp1[0],lamp2[0],lams[0],lami[-1::][0]]) lam_arrows *=1e6 powers_arrows = [] for i in range(4): powers_arrows.append(w2dbm(np.abs(AB_final[i,0,0,0,0,0,0])**2)) powers_arrows = np.asanyarray(powers_arrows) colours = ['red','green','blue','black'] waves = ['pump1','pump2','signal','idler'] fig = plt.figure() plt.ylim(-40,35) plt.xlim(1.548,1.555) plt.xlabel(r'$\lambda ( \mu m)$') plt.ylabel(r'$P(dBm)$') arrow = [1,2,3,4] for i in range(4): arrow[i] = plt.arrow(lam_arrows[i],-40,0,powers_arrows[i]+40,head_width=1e-4,head_length=1,width = 1e-12,length_includes_head=True,color=colours[i]) plt.legend([arrow[0],arrow[1],arrow[2],arrow[3]], [waves[0]+','+B[0],waves[1]+','+B[1],waves[2]+','+B[2],waves[3]+','+B[3]],loc=0) plt.title('Linear phase matching:'+ r'$\lambda_p = $'+str(lamp_min[0]*1e6)+r'$\mu m$') #plt.savefig('plots/arrows_linear.png', bbox_inches='tight') plt.show() """ lam_vec = np.array([lamp1[0],lamp2[0],lams[0],1]) omega = 2*pi*c/(lam_vec[:]) omega[3] = omega[0] + omega[1] -omega[2] xpm0 = np.loadtxt('0.txt') xpm1 = np.loadtxt('1.txt') xpm2 = np.loadtxt('2.txt') xpm3 = np.loadtxt('3.txt') z_plot = np.loadtxt('z.txt') dknl0 = xpm2 + xpm3 - xpm1 dknl1 = xpm2+xpm1 -xpm0 dknl2 = xpm1+xpm0 -xpm3 dknl3 = xpm2+xpm1 -xpm2 fig = plt.figure() plt.plot(z_plot,dknl0) plt.xlabel(r'$z(m)$') plt.ylabel(r'$\Delta k_{NL}$') plt.title('pump1 XPM_SPM') plt.show() fig = plt.figure() plt.plot(z_plot,dknl1) plt.title('pump2 XPM_SPM') plt.xlabel(r'$z(m)$') plt.ylabel(r'$\Delta k_{NL}$') plt.show() fig = plt.figure() plt.plot(z_plot,dknl2) plt.title('signal XPM_SPM') plt.xlabel(r'$z(m)$') plt.ylabel(r'$\Delta k_{NL}$') plt.show() fig = plt.figure() plt.plot(z_plot,dknl3) plt.title('idler XPM_SPM') plt.xlabel(r'$z(m)$') plt.ylabel(r'$\Delta k_{NL}$') plt.show() sys.exit() """ """ dzs = [] dz =0.1 for i in range(6): dzs.append(dz) dz *=0.5 del dz lamp2 = np.asanyarray([lamp_min + 0.1*lamp_min]) converge = [] for dz in dzs: print dz AB_final,lami,Dk = FWM(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lamp2,lams,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2) converge.append(np.abs(AB_final[3,0,0,0,0,0,0])**2) plt.plot(dzs,converge) plt.show() sys.exit() """ lamp2 = np.linspace(lamp_min - 0.001*lamp_min,lamp_min + 0.001*lamp_min,1024) AB_final = np.zeros([4,len(P_vec1),len(P_vec2),len(P_signal_vec),len(lamp1),len(lamp2),len(lams)],dtype='complex') Dk_vec = np.zeros([len(lamp1),len(lamp2),len(lams)]) #sys.exit # = FWM(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lamp2,lams,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2) from joblib import Parallel, delayed A = Parallel(n_jobs=6)(delayed(FWM)(n2,AB_final,Dk_vec,P_vec1,P_vec2,P_signal_vec,lamp1,lamp2_,m,lams,lami,dz,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2) for m,lamp2_ in enumerate(lamp2)) A = np.asanyarray(A) #AB_final = A[:,0] Dk = np.zeros([len(lamp2)]) for i in range(len(lamp2)): for j in range(4): AB_final[j,0,0,0,0,i,0] =A[i,0][j][0][0][0][0][i][0] Dk[i] = A[i,2][0][i][0] fig = plt.figure() plt.plot(lamp2*1e6,w2dbm(np.abs(AB_final[3,0,0,0,0,:,0])**2)) plt.ylabel(r'$Power (dBm)$') plt.xlabel(r'$\lambda_{p2}(\mu m)$') plt.title('Effective phase match for varying pump2 wavelength') plt.show() fig = plt.figure() plt.plot(lamp2*1e6,Dk) plt.ylabel(r'$\Delta k(1/m)$') plt.xlabel(r'$\lambda_{p2}(\mu m)$') plt.show() Dk_vec,Dk_vec_nl = effective_phase_matching_general(lamp2,n2,P_vec1,P_vec2,P_signal_vec,lamp1,lams,lami,dz,num_steps,lamda_c,mat_lp,B,zmin,zmax,zeroing,overlap1,overlap2) fig =plt.figure() plt.plot(lamp2*1e6,Dk_vec[0,:,0],label = 'L') plt.plot(lamp2*1e6,Dk_vec_nl[0,:,0],label = 'NL') #plt.plot(lamp2*1e6,Dk_vec_nl[0,:,0] - Dk_vec[0,:,0],label = 'NL - L') plt.ylabel(r'$\Delta k(1/m)$') plt.xlabel(r'$\lambda_{p2}(\mu m)$') plt.legend() plt.show() fig =plt.figure() #plt.plot(lamp2*1e6,Dk_vec[0,:,0],label = 'L') #plt.plot(lamp2*1e6,Dk_vec_nl[0,:,0],label = 'NL') plt.plot(lamp2*1e6,Dk_vec_nl[0,:,0] - Dk_vec[0,:,0],label = 'NL - L') plt.ylabel(r'$(\Delta k_L - \Delta k_{NL} )(1/m)$') plt.xlabel(r'$\lambda_{p2}(\mu m)$') plt.legend() plt.show() return
print('normaliced angular momentum', round(float(J_norm[0]), 2), round(float(J_norm[1]), 2), round(float(J_norm[2]), 2)) im_nodust = pp.stars.render( s, width=50, mag_range=(18, 30), #dynamic_range=5.0 with_dust=False, b_scale=1.5, ret_im=True) plt.savefig(simname + '.nodust_feature_sideplus_x' + str(anglex) + '_y' + str(angley) + '_z' + str(anglez) + '.png') plt.arrow(0, 0, 10 * float(J_norm[0]), 10 * float(J_norm[1]), head_width=1.5, head_length=2, fc='g', ec='g') plt.savefig(simname + '.nodust_check_ivu_x' + str(anglex) + '_y' + str(angley) + '_z' + str(anglez) + '.png') plt.close() im_dust = pp.stars.render( s, width=50, mag_range=(18, 30), #dynamic_range=5.0 with_dust=True, b_scale=1.5, ret_im=True) plt.savefig(simname + '.dust_feature_sideplus_x' + str(anglex) +