def magnification(self,X): target=np.zeros(X.shape[0]) J = np.zeros((X.shape[0],X.shape[1],self.output_dim)) J=self.jacobian(X) for i in range(X.shape[0]): target[i]=np.sqrt(pb.det(np.dot(J[i,:,:],np.transpose(J[i,:,:])))) return target
def magnification(self, X): target = np.zeros(X.shape[0]) J = np.zeros((X.shape[0], X.shape[1], self.output_dim)) J = self.jacobian(X) for i in range(X.shape[0]): target[i] = np.sqrt( pb.det(np.dot(J[i, :, :], np.transpose(J[i, :, :])))) return target
def bin_matrix(x, P): M = np.zeros((xmax, ymax)) sigma = plt.det(P) d_pos = np.zeros((P.shape[0], 1)) P_inv = np.linalg.inv(P) sum1 = 0 for i in range(xmax): for j in range(ymax): d_pos[0, 0] = x[0] - (i * scale) d_pos[1, 0] = x[1] - (j * scale) exp_value = -0.5 * (d_pos.transpose() * P_inv * d_pos) M[i, j] = 1. / (np.sqrt(2 * np.pi * sigma)) * np.exp(exp_value) sum1 = sum1 + M[i, j] for i in range(xmax): for j in range(ymax): M[i, j] = M[i, j] / sum1 return M
def __init__(self,SIG): self.Sigma = SIG #------------------------------------------------------------------------------ # 2x2 sigma matrices self.SigX = self.Sigma[0:2,0:2]; self.SigY = self.Sigma[2:4,2:4]; self.SigZ = self.Sigma[4:6,4:6]; #------------------------------------------------------------------------------ # Emittance in each phase place # self.EpsilonX = self.Sigma[0,0]*self.Sigma[1,1] - self.Sigma[0,1]**2 self.EmittenceX = sqrt(math.fabs(det(self.SigX))) self.EmittenceY = sqrt(math.fabs(det(self.SigY))) self.EmittenceZ = sqrt(math.fabs(det(self.SigZ))) #------------------------------------------------------------------------------ # Ellipse (Twiss) parameters in each phase plane self.TwissXX1 = array([-(self.SigX[0,1]),self.SigX[0,0],self.SigX[1,1],self.EmittenceX**2]/self.EmittenceX) self.TwissYY1 = array([-(self.SigY[0,1]),self.SigY[0,0],self.SigY[1,1],self.EmittenceY**2]/self.EmittenceY) self.TwissZZ1 = array([-(self.SigZ[0,1]),self.SigZ[0,0],self.SigZ[1,1],self.EmittenceZ**2]/self.EmittenceZ) #------------------------------------------------------------------------------ # Beam's spatial width in each phase plane self.WidthX = sqrt(self.TwissXX1[1]*self.TwissXX1[3]) self.WidthY = sqrt(self.TwissYY1[1]*self.TwissYY1[3]) self.WidthZ = sqrt(self.TwissZZ1[1]*self.TwissZZ1[3]) #------------------------------------------------------------------------------ # Beam's angular envelope in each phase plane self.DivergenceX = sqrt(self.TwissXX1[2]*self.TwissXX1[3]) self.DivergenceY = sqrt(self.TwissYY1[2]*self.TwissYY1[3]) self.DivergenceZ = sqrt(self.TwissZZ1[2]*self.TwissZZ1[3]) #------------------------------------------------------------------------------ # Ellipse parameter in the transverse spatial plane self.EmittenceXY = sqrt( det(matrix([[SIG[0,0],SIG[0,2]] ,[SIG[2,0],SIG[2,2]] ])) ) self.TwissXY = array([-SIG[0,2],SIG[0,0],SIG[2,2],self.EmittenceXY**2])/self.EmittenceXY self.EmittenceXZ = sqrt( det(matrix([[SIG[0,0],SIG[0,4]] ,[SIG[4,0],SIG[4,4]] ])) ) self.TwissXZ = array([-SIG[0,4],SIG[0,0],SIG[4,4],self.EmittenceXZ**2])/self.EmittenceXZ self.EmittenceYZ = sqrt( det(matrix([[SIG[2,2],SIG[2,4]] ,[SIG[4,2],SIG[4,4]] ])) ) self.TwissYZ = array([-SIG[2,4],SIG[2,2],SIG[4,4],self.EmittenceYZ**2])/self.EmittenceYZ #------------------------------------------------------------------------------ # Plotting Attributes self.LineColor = 'r' self.LineWidth = 1 self.LineStyle = '-'
def ellfit(x, y, wt=None): import pylab as pl # Calculate the best fit ellipse for an X and Y distribution, allowing # for weighting. # OUTPUTS: # MAJOR - major axis in same units as x and y # MINOR - minor axis in same units as x and y # POSANG - the position angle CCW from the X=0 line of the coordinates # # Adam: The intensity weighted major and minor values are equal to the # second moment. # For equal weighting by pixel (of the sort that # might be done for blob analysis) the ellipse fit to the # half-maximum area will have semimajor axis equal to 1./1.69536 the # second moment. For the quarter maximum surface this is 1./1.19755. # # i.e. if you run this with x,y down to zero intensity (like integrating # to infinity), and wt=intensity, you get the second moments sig_major, # sig_minor back # if you run this with x,y down to half-intensity, and wt=None, you get # sigx/1.6986 back (not sure why my integra differs from his slightly) # # but adam did not have the factor of 4 to turn eigenval into major axis # # translation: if we run this with intensity weight, we get # the second moment back (a sigma). for flat weights i think he means # the halfmax contour semimajor axis if type(wt) == type(None): wt = x * 0.0 + 1.0 tot_wt = wt.sum() # WEIGHTED X AND Y CENTERS x_ctr = (wt * x).sum() / tot_wt y_ctr = (wt * y).sum() / tot_wt # BUILD THE MATRIX i11 = (wt * (x - x_ctr)**2).sum() / tot_wt i22 = (wt * (y - y_ctr)**2).sum() / tot_wt i12 = (wt * (x - x_ctr) * (y - y_ctr)).sum() / tot_wt mat = [[i11, i12], [i12, i22]] # CATCH THE CASE OF ZERO DETERMINANT if pl.det(mat) == 0: return pl.nan, pl.nan, pl.nan if pl.any(pl.isnan(mat)): return pl.nan, pl.nan, pl.nan # WORK OUT THE EIGENVALUES evals, evec = pl.eig(mat) # PICK THE MAJOR AXIS absvals = pl.absolute(evals) major = absvals.max() maj_ind = pl.where(absvals == major)[0][0] major_vec = evec[maj_ind] min_ind = 1 - maj_ind # WORK OUT THE ORIENTATION OF THE MAJOR AXIS posang = pl.arctan2(major_vec[1], major_vec[0]) # compared to the original idl code, this code is returning # pi-the desired angle, so: # posang=pl.pi-posang # if posang<0: posang = posang+pl.pi # MAJOR AND MINOR AXIS SIZES # turn into real half-max major/minor axis major = pl.sqrt(evals[maj_ind]) * 4. minor = pl.sqrt(evals[min_ind]) * 4. return major, minor, posang
def main(): # do we want an image of the loops in 3D for different A? loops = False # do we want to make a movie of the stability multipliers in the complex plane? mk_stab_mov = True if loops: fig3d = pl.figure d3ax = fig.add_subplot(111,projection='3d') #os.mkdir('LoopImgs') # make a directory for the stability multiplier images --> this will be a movie as a function of # A if mk_stab_mov: os.mkdir('StabMovie') # this variable just exsits so we dont print the A value of the bifurcation point more than # once. found_bif = False # make file to store q (periodicity) q_file = open("qdata.txt","w") # make file to store stability multipliers eig_file = open("data.txt","w") eig_file.write("eig1 eig2 A\n") dt = .001 # total number of iterations to perform # totIter = 10000000 totIter = 50000 totTime = totIter*dt time = pl.arange(0.0,totTime,dt) beta = .6 qq = 1.0 # how many cells is till periodicity use x = n*pi/k (n must be even #) modNum = 2*pl.pi/k modNum = 2.0*pl.pi # initial conditions for p1 and p2 p1_init_x = pl.pi p1_init_vx = 0.0 p2_init_x = 0.0 p2_init_vx = 0.0 A_start = 0.2 A = A_start A_max = .8 A_step = .01 count = 0 # make arrays to keep eigen values. There willl be four eigen values for N=2 so lets hve two seperate # arrays for them eigs1 = pl.array([]) eigs2 = pl.array([]) eigs3 = pl.array([]) eigs4 = pl.array([]) # file to write final poition of particle to final = open("final_position.txt","w") final.write("Last position of orbit, A\n") x0 = pl.array([p1_init_vx,p2_init_vx,p1_init_x,p2_init_x]) previous_q = 0.0 while A < A_max: # initial conditions vector # set up: [xdot,ydot,x,y] apx = Two_Particle_Sin1D(A,beta,qq,dt) sol = odeint(apx.f,x0,time) print("x0") print(x0) #sol[:,2]=sol[:,2]%(2*pl.pi) # find a single loop of the limit cycle. Might be periodoc over more than one cycle # returns the solution of just that loop AND the periodicity of the loop # takes a threshhold number. If it cant find a solution where the begining and end of the # trajectroy lye within this threshold value than it quits and prints an error #thresh is distance in the phase place #thresh = .01 thresh = .00005 # change this back for bifrucation other than FIRST PI BIF #loop = find_one_full_closed(sol,thresh,dt) loop = pl.zeros([int(2.0*pl.pi/dt),4]) loop[:,2]+=pl.pi # the other particle needs to be at zero. Already is if "stop" in loop: break loop_t = pl.arange(0.0,(len(loop))*dt,dt) if loops : d3ax.plot(pl.zeros(len(loop))+A,loop[:,2],loop[:,0],color="Black") #fig = pl.figure() #ax = fig.add_subplot(111) ##ax.scatter([0.0,pl.pi,2.0*pl.pi],[0.0,0.0,0.0],color="Red") ##ax.plot(loop[:,2],loop[:,0],":",color="Black") #ax.plot(loop[:,2],loop[:,0],color="Black") #ax.set_xlabel("$x_1$",fontsize=25) #ax.set_ylabel("$x_2$",fontsize=25) ##ax.set_xlim([pl.pi-pl.pi/3.0,pl.pi+pl.pi/3.0]) ##ax.set_ylim([-.3,.3]) #fig.tight_layout() #fig.savefig("LoopImgs/"+str(A)+".png",dpi = 300,transparent=True) ##os.system("open LoopImgs/" +str(A)+".png") #pl.close(fig) apx.set_sol(loop) # solution matrix at t=0 is identity matrix -> we need it in 1d arrar form for odeint though # -> reshape takes care of the the form w0 = pl.identity(4).reshape(-1) w_of_t = odeint(apx.mw,w0,loop_t,hmax=dt,hmin=dt) #w_of_t = odeint(apx.mw,w0,loop_t) current_q = loop_t[-1]/(2.0*pl.pi) # print the period of the orbit we are working on print("q: " + str(current_q)) q_file.write(str(loop_t[-1]/(2.0*pl.pi))+" "+str(A)+"\n") if current_q > (previous_q+1.0): print("bifurcation point. A = " +str(A)) previous_q=current_q # make the matrix form of w_of_t matrix = w_of_t[-1,:].reshape(4,4) print('solution matrix is:') for i in range(len(matrix)): print(str(matrix[i,:])) # print('solution matrix times the initial conditions vector:') # This is wrong because the x0 needs to be re-ordered to b e consistant with the way the # Jacobian is set up. # print(pl.dot(matrix,x0)) # use linalg to get the eigen values of the W(t=q) where q is the period time of the orbit vals,vect = numpy.linalg.eig(matrix) print('the trace is' + str(matrix.trace())) print('determinant is: '+ str(pl.det(matrix))) if((abs(vals[0])<=1.0) and (not found_bif)): print("this is the bifurcation point (l1)") print(A) found_bif = True if(abs(vals[1])<=1.0 and (not found_bif)): print("this is the bifurcation point (l2)") print(A) found_bif = True print('number of eigen values is: ' + str(len(vals))) eigs1 = pl.append(eigs1,vals[0]) eigs2 = pl.append(eigs2,vals[1]) eigs3 = pl.append(eigs3,vals[2]) eigs4 = pl.append(eigs4,vals[3]) eig_file.write(str(vals[0])+" "+str(vals[1])+" "+str(vals[2])+" "+str(vals[3])+" "+str(A)+"\n") count+=1 x0 = loop[-1,:] final.write(str(x0)[1:-1]+" "+str(A) +"\n") A += A_step print("A: "+str(A)) theta = pl.arange(0,10,.05) A_arr = pl.arange(A_start,A,A_step) print('we are above') while len(A_arr)>len([k.real for k in eigs1]): A_arr = A_arr[:-1] while len(A_arr)<len([k.real for k in eigs1]): A_arr = pl.append(A_arr,A_arr[-1]+A_step) print('we are below') fig1 = pl.figure() ax1 = fig1.add_subplot(111) ax1.plot(pl.cos(theta),pl.sin(theta)) ax1.plot([k.real for k in eigs1],[l.imag for l in eigs1]) ax1.set_xlabel("Re[$\lambda_1$]",fontsize=25) ax1.set_ylabel("Im[$\lambda_1$]",fontsize=25) fig1.tight_layout() fig1.savefig("eig1.png") os.system("open eig1.png") fig2 = pl.figure() ax2 = fig2.add_subplot(111) ax2.plot(pl.cos(theta),pl.sin(theta)) ax2.plot([k.real for k in eigs2],[l.imag for l in eigs2]) ax2.set_xlabel("Re[$\lambda_2$]",fontsize=25) ax2.set_ylabel("Im[$\lambda_2$]",fontsize=25) fig2.tight_layout() fig2.savefig("eig2.png") os.system("open eig2.png") fig3, ax3 = pl.subplots(2,sharex=True) ax3[0].plot(A_arr,[k.real for k in eigs1],color='k') ax3[1].plot(A_arr,[k.imag for k in eigs1],color='k') ax3[0].set_ylabel("Re[$\lambda_1$]",fontsize = 25) ax3[1].set_ylabel("Im[$\lambda_1$]",fontsize = 25) ax3[1].set_xlabel("$A$",fontsize = 25) fig3.tight_layout() fig3.savefig("A_vs_eig1.png") os.system("open A_vs_eig1.png") fig4, ax4 = pl.subplots(2,sharex=True) ax4[0].plot(A_arr,[k.real for k in eigs2], color = 'k') ax4[1].plot(A_arr,[k.imag for k in eigs2], color = 'k') ax4[0].set_ylabel("Re[$\lambda_2$]",fontsize = 25) ax4[1].set_ylabel("Im[$\lambda_2$]",fontsize = 25) ax4[1].set_xlabel("$A$",fontsize = 25) fig4.tight_layout() fig4.savefig("A_vs_eig2.png") os.system("open A_vs_eig2.png") eig_file.close() final.close() ## make text file with all extra information #outFile = open("info.dat","w") #outFile.write("Info \n coefficient: " + str(coef) \ # + "\nwave number: " +str(k)\ # + "\nomega: " + str(w)\ # + "\ndamping: " + str(damp)\ # + "\ng: " + str(g)\ # + "\ntime step: " + str(dt)\ # + "\ntotal time: " + str(dt*totIter)\ # + "\ntotal iterations: " + str(totIter)\ # + "\nInitial Conditions: \n" + # "initial x: " +str(initx) \ # +"\ninitial y: " +str(inity) \ # +"\ninitial vx: " +str(initvx)\ # +"\ninitial vy: " +str(initvy) ) #outFile.close() # line for stable static point if loops: line = pl.arange(start_A-.01,start_A,A_step) pi_line = pl.zeros(len(line))+pl.pi z_line = pl.zeros(len(line)) d3ax.plot(line,pi_line,z_line,color="Black") d3ax.set_xlabel("$A$",fontsize=25) d3ax.set_ylabel("$x_1$",fontsize=25) d3ax.set_zlabel("$x_2$",fontsize=25) d3fig.tight_layout() d3fig.savefig("loops.png",dpi=300) if mk_stab_mov: for i in range(len(eigs1)): s_fig = pl.figure() s_ax = s_fig.add_subplot(111) s_ax.plot(pl.cos(theta),pl.sin(theta)) s_ax.scatter(eigs1[i].real,eigs1[i].imag,c='r',s=20) s_ax.scatter(eigs2[i].real,eigs2[i].imag,c='b',s=20) s_ax.scatter(eigs3[i].real,eigs3[i].imag,c='b',s=20) s_ax.scatter(eigs4[i].real,eigs4[i].imag,c='b',s=20) s_ax.set_xlabel("Re[$\lambda$]",fontsize=25) s_ax.set_ylabel("Im[$\lambda$]",fontsize=25) s_fig.tight_layout() s_fig.savefig("StabMovie/%(num)0.5d_stbl.png"%{"num":i}) pl.close(s_fig)
if len(s)==4: if s[0]==1: # cube has the trailing stokes axis which turns into a leading degenerate axis in python datacube=datacube[0] fluxmap=fits.getdata(fluxfile) hdr=fits.getheader(datafile) bmaj=hdr['bmaj'] # degrees bmin=hdr['bmin'] # degrees bpa=hdr['bpa']*pl.pi/180 # ->rad from astropy import wcs w = wcs.WCS(hdr) pix=pl.sqrt(-pl.det(w.celestial.pixel_scale_matrix)) # degrees bmaj_pix=bmaj/pix bmin_pix=bmin/pix bm_pix=[bmaj_pix,bmin_pix,bpa] import time x=time.localtime() datestr=str(x.tm_year)+("%02i"%x.tm_mon)+("%02i"%x.tm_mday) import pickle from cube_to_moments import cube_to_moments assigncube=fits.getdata(assignfile) moments,mcmoments=cube_to_moments(datacube,assigncube,montecarlo=montecarlo,bm_pix=bm_pix,fluxmap=fluxmap)