def findcurve(psi1,psi2,n=3,nn_fit=4,nn_out=100): ''' Function to find the elastica curve for start and end orientations psi1 and psi2. It finds the best curve across all directions from start and end, i.e. the direction independent elastica curve. Inputs ------------ psi1,psi2: start and end orientations. n: degree of estimation polynomial. nn: number of points on the curve. - nn_fit: for fittin purposes - nn_out: for the output Outputs ------------ Returns a tuple (s,psi). s: points on the curve. psi: curvature of the curve as a function of s. E: curvature energy of the curve ''' # # define the starting conditions a0 = pl.zeros(n+1) # Set a high energy: E_best = 10000 # and predfine output curve s = pl.linspace(0,1,nn_out) # points on the curve psi_out = pl.zeros(nn_out) # curvature at points in curve # across all the start and end directions find the curve with the lowest energy for dpsi1 in (-pl.pi,0,pl.pi): for dpsi2 in (-pl.pi,0,pl.pi): # For the starting variables, # the first two polygon variables can be estimated from the Sharon paper derivation # For different starting variables the solution can be hard to find a0[-2] = 4*( pl.arcsin(- (pl.sin(psi1+dpsi1)+ pl.sin(psi2+dpsi2))/4) -(psi1+dpsi1+psi2+dpsi2)/2 ) a0[-1] = 2*a0[-2]/pl.cos( (psi1+dpsi1+psi2+dpsi2)/2 + a0[-2]/4 ) # find the best variables to minimize the elastica energy fit = fsolve(errors,a0,args=(psi1+dpsi1,psi2+dpsi2,nn_fit)) # find the curve and its derivative for the fitted variables a = fit[:-1] psi = Psi(a,s,psi1+dpsi1,psi2+dpsi2) dpsi = dPsi(a,s,psi1+dpsi1,psi2+dpsi2) # find the energy of this curve E = sum(dpsi**2)*s[1] # check against the lowest energy if E_best > E: E_best = E psi_out[:] = pl.copy(psi) return (s,psi_out,E_best)
def arc_haversinus(forhold): """Den inverse haversinus funksjonen Brukes for å regne ut vinkelen mellom to punkt på et kuleskall Du kan lese om denne funksjonen her https://en.wikipedia.org/wiki/Versine """ return 2 * arcsin(sqrt(forhold))
def eq_to_hor(ra, dec, lat, lst): H = lst - ra el = arcsin(sin(dec) * sin(lat) + cos(dec) * cos(lat) * cos(H)) az = arccos((sin(dec) - sin(lat) * sin(el)) / (cos(lat) * cos(el))) flag = sin(H) > 0 if type(flag) is ndarray: az[flag] = 2.0 * pi - az[flag] elif flag: az = 2.0 * pi - az return az, el
def my_hor_to_eq(az, el, lat, lsts): dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) argument = (sin(el) - sin(lat) * sin(dec)) / (cos(lat) * cos(dec)) argument = clip(argument, -1.0, 1.0) H = arccos(argument) flag = sin(az) > 0 H[flag] = 2.0*pi - H[flag] ra = lsts - H ra %= 2*pi return ra,dec
def hor_to_eq(az, el, lat, lst): dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) argument = (sin(el) - sin(lat) * sin(dec)) / (cos(lat) * cos(dec)) argument = pylab.clip(argument, -1.0, 1.0) H = arccos(argument) flag = sin(az) > 0 if type(flag) is ndarray: H[flag] = 2.0 * pi - H[flag] elif flag: H = 2.0 * pi - H ra = lst - H ra %= 2 * pi return ra, dec
def det_rotationangles2(cell, segment1, segment2): '''return rotationangles around x- and y-axis, so the line between two chosen segments is aligned in parallell to the z-axis, corrected to soma.''' R = pl.sqrt((cell.xmid[segment1]-cell.xmid[segment2])**2 \ + (cell.ymid[segment1]-cell.ymid[segment2])**2 \ + (cell.zmid[segment1]-cell.zmid[segment2])**2) rot_x = pl.pi+pl.arctan2(cell.ymid[segment1]-cell.ymid[segment2],\ cell.zmid[segment1]-cell.zmid[segment2]) rot_y = -pl.pi + pl.arcsin((cell.xmid[segment1] - cell.xmid[segment2]) / R) rotation = {'x': rot_x, 'y': rot_y} return rotation
def det_rotationangles2(cell, segment1, segment2): """return rotationangles around x- and y-axis, so the line between two chosen segments is aligned in parallell to the z-axis, corrected to soma.""" R = pl.sqrt( (cell.xmid[segment1] - cell.xmid[segment2]) ** 2 + (cell.ymid[segment1] - cell.ymid[segment2]) ** 2 + (cell.zmid[segment1] - cell.zmid[segment2]) ** 2 ) rot_x = pl.pi + pl.arctan2(cell.ymid[segment1] - cell.ymid[segment2], cell.zmid[segment1] - cell.zmid[segment2]) rot_y = -pl.pi + pl.arcsin((cell.xmid[segment1] - cell.xmid[segment2]) / R) rotation = {"x": rot_x, "y": rot_y} return rotation
def eq_to_gal(ra, dec): """ expects dec between -pi/2 and pi/2 compares to pyephem within 0.45 arcsec returns lon, lat in radians """ alpha = galactic_north_equatorial[0] delta = galactic_north_equatorial[1] la = angles.from_degrees(122.932 - 90.0) b = arcsin(sin(dec) * sin(delta) + cos(dec) * cos(delta) * cos(ra - alpha)) l = arctan2( sin(dec) * cos(delta) - cos(dec) * sin(delta) * cos(ra - alpha), cos(dec) * sin(ra - alpha)) + la l += 2.0 * pylab.pi * (l < 0) l = l % (2.0 * pylab.pi) return l, b
def gal_to_eq(l, b): """ Inputs: l: galactic longitude b: galactic latitude Returns: ra, dec compares to pyephem within 0.45 arcsec """ alpha = galactic_north_equatorial[0] delta = galactic_north_equatorial[1] la = angles.from_degrees(122.932 - 90.0) dec = arcsin(sin(b) * sin(delta) + cos(b) * cos(delta) * sin(l - la)) ra = arctan2( cos(b) * cos(l - la), sin(b) * cos(delta) - cos(b) * sin(delta) * sin(l - la)) + alpha ra += 2.0 * pylab.pi * (ra < 0) ra = ra % (2.0 * pylab.pi) return ra, dec
def _matrix2State(self, R, T): ''' calculate euler angle from rotation matrix and form the vector state from angle and w_T_L ''' if R[2,0]!=1 or R[2,0]!=-1: pitch=-pl.arcsin(R[2,0])#another solution is pi-pitch roll=pl.arctan2(R[2,1]/cos(pitch), R[2,2]/cos(pitch)) yaw=pl.arctan2(R[1,0]/cos(pitch), R[0,0]/cos(pitch)) else: yaw=0 if R[2,0]==-1: pitch=pi/2 roll=yaw+pl.arctan2(R[0,1],R[0,2]) else: pitch=-pi/2 roll=-yaw+pl.arctan2(-R[0,1],-R[0,2]) state = pl.array([T[0],T[1],T[2],roll*RAD2DEG,pitch*RAD2DEG,yaw*RAD2DEG]) return state
def _matrix2State(self, R, T): ''' calculate euler angle from rotation matrix and form the vector state from angle and w_T_L ''' if R[2, 0] != 1 or R[2, 0] != -1: pitch = -pl.arcsin(R[2, 0]) #another solution is pi-pitch roll = pl.arctan2(R[2, 1] / cos(pitch), R[2, 2] / cos(pitch)) yaw = pl.arctan2(R[1, 0] / cos(pitch), R[0, 0] / cos(pitch)) else: yaw = 0 if R[2, 0] == -1: pitch = pi / 2 roll = yaw + pl.arctan2(R[0, 1], R[0, 2]) else: pitch = -pi / 2 roll = -yaw + pl.arctan2(-R[0, 1], -R[0, 2]) state = pl.array( [T[0], T[1], T[2], roll * RAD2DEG, pitch * RAD2DEG, yaw * RAD2DEG]) return state
def AnglesFromRot(R): # Hypothesis 1 h2a = arcsin(R[0, 2]) cos2 = cos(h2a) if abs(cos2) < 1e-8: cos2 += 1e-8 h1a = arctan2(-R[1, 2] / cos2, R[2, 2] / cos2) h3a = arctan2(-R[0, 1] / cos2, R[0, 0] / cos2) # Hypothesis 2 h2b = pi - h2a cos2 = cos(h2b) if abs(cos2) < 1e-8: cos2 += 1e-8 h1b = arctan2(-R[1, 2] / cos2, R[2, 2] / cos2) h3b = arctan2(-R[0, 1] / cos2, R[0, 0] / cos2) # Testing resa = abs(sum(R - RotFromAngles([h1a, h2a, h3a]))) resb = abs(sum(R - RotFromAngles([h1b, h2b, h3b]))) if resa < resb: return [h1a, h2a, h3a] else: return [h1b, h2b, h3b]
def _xy2pt(x,y,oh=False): """ Convert x,y coordinates to phi,theta, assuming a spherical surface with radius equal to 1. x,y are assumed to have been rotated to be consistent with the desired/ expected POV. However, there still exists the issue of whether x,y are for the nearer hemisphere, or the "opposite hemisphere". If oh==True, adjust theta accordingly. In actuality, floating point round-off error leads to a grid of phi,theta that is not regular (i.e., it is not a perfect meshgrid). This error does not hurt numerics much, but can cause issues with plotting algorithms, so we choose to enforce a regular meshgrid in phi,theta based on the first columns,rows of x and y. THIS IS ANOTHER CONSEQUENCE OF STRANGE DESIGN CHOICES FOR THE MIX FILE FORMAT. """ phis = p.arctan2(y[:,-1],x[:,-1]) phis[phis<0] = phis[phis<0] + 2*p.pi if oh: phis[0] = 2*p.pi phis[-1] = 0 else: phis[0] = 0 phis[-1] = 2*p.pi thetas = p.arcsin(x[0,:]) # assumes x[0,:] corresponds to y==0 phi,theta = p.meshgrid(phis, thetas, indexing='ij') if oh: theta = p.pi - theta return (phi, theta)
def asEuler(self): q1, q2, q3, q4 = self.q yaw = atan2(2*q2*q3-2*q1*q4, 2*q1*q1+2*q2*q2-1) ##Yaw, psi, Euler[0] pitch = -arcsin(2*q2*q4+2*q1*q3) ##Pitch, theta roll = atan2(2*q3*q4-2*q1*q2, 2*q1*q1+2*q4*q4-1) ##Roll, phi return (roll, pitch, yaw)
from collections import Counter import pylab as pl import random as rd import math as mt from shapely.geometry import LineString from igraph import * from datetime import datetime,timedelta gall = lambda x: [6371000.*pl.pi*x[1]/(180.*pl.sqrt(2)), 6371000.*pl.sqrt(2)*pl.sin(pl.pi*(x[0]/180.))] invgall = lambda x: [(180./pl.pi)*pl.arcsin(x[1]/(6371000.*pl.sqrt(2))) , x[0]*180*pl.sqrt(2)/(6371000.*pl.pi)] to_str = lambda x: str(x[0][0])+' '+str(x[0][1]) dist = lambda x: pl.sqrt( (x[0][0]-x[1][0])**2 + (x[0][1]-x[1][1])**2 ) to_coord = lambda z: gall([float(z.split(' ')[0]),float(z.split(' ')[1])]) pday = lambda x: datetime.strftime(x,"%Y-%m-%d") def select_heigths(th): coin=rd.choice(['up','down','both']) if coin=='up' : th.sort() if coin=='down': th.sort(reverse=True) if coin=='both': a=th[:len(th)/2] a.sort() b=th[len(th)/2:] b.sort(reverse=True) th=a+b return th def rettifica(route,Eff,D,soglia):
def lmcextinct(ra, dec, **kw): """Use the Zaritsky & Harris (ZH) map to get A_V extinction in the LMC. INPUT: ra -- decimal degrees of right ascension dec -- decimal degrees of declination OPTIONAL INPUT: method='griddata' /'nearest' -- interpolation method map='both' /'hot'/'cool' -- Which ZH map to use hot='lmc_hotav.fits' -- filename of hot map cool='lmc_coolav.fits' -- filename of cool map null=0.0 -- "no data" value in map verbose=False / True -- print out some spam and eggs EXAMPLE: ra = hms('05:51:56.6') dec = dms('-66:25:08.5') lmcextinct(ra, dec) If their map returns null, interpolate from the surroundings. Note that these calculations are definitely _not_ optimized. SEE ALSO: hms, dms""" # 2009-02-15 22:11 IJC: Created and tested. try: from astropy.io import fits as pyfits except: import pyfits from matplotlib.mlab import griddata from pylab import meshgrid, arange, array, sqrt, cos, sin, arctan2, arcsin ra = array([ra]).copy().ravel() dec = array([dec]).copy().ravel() defaults = dict(method='griddata', map='hot', hot='lmc_hotav_clean2.fits', cool='lmc_coolav.fits', null=0.0, verbose=False) for key in defaults: if (not kw.has_key(key)): kw[key] = defaults[key] if kw['map']=='both': kw['map'] = 'hot' ret1 = lmcextinct(ra, dec, **kw) kw['map'] = 'cool' ret2 = lmcextinct(ra, dec, **kw) return (ret1, ret2) else: map = kw[kw['map']] verbose = kw['verbose'] avmap = pyfits.getdata(map) avhdr = pyfits.getheader(map) nx = avhdr['naxis1'] ny = avhdr['naxis2'] cx = avhdr['crpix1'] cy = avhdr['crpix2'] x0 = avhdr['crval1'] y0 = avhdr['crval2'] dx = avhdr['cd1_1'] dy = avhdr['cd2_2'] xx,yy = meshgrid(arange(nx),arange(ny)) goodind = (avmap<>kw['null']) # I don't know how the following WCS calculation works, but it # does -- thank you, Calabretta & Greisen 2002! d2r = pi/180. phi = arctan2( xx-cx+1, yy-cy+1) + pi theta = arctan2(1./(d2r*dy), sqrt((yy-cy)**2 + (xx-cx)**2)) mapdec = arcsin(sin(theta)*sin(y0*d2r) - cos(theta)*cos(phi)*cos(y0*d2r))/d2r mapra = arcsin(cos(theta) * sin(phi) / cos(mapdec*d2r))/d2r + x0 if kw['method']=='griddata': ragood = mapra[goodind] decgood = mapdec[goodind] avgood = avmap[goodind] if verbose>0: print 'ra.shape>>' + str(ra.shape) # TBD: Vectorize this calculation; an interpolative solution # should exist. avlist = [] for ii in range(len(ra)): if verbose>0: print 'ra, dec>>' + str((ra[ii], dec[ii])) if kw['method']=='nearest': distmap = (mapra-ra[ii])**2 + (mapdec-dec[ii])**2 # If multiple values are equally near, average them: val = avmap[distmap==distmap.min()].mean() avlist.append(val) elif kw['method']=='griddata': avlist.append(griddata(ragood, decgood, avgood, array([ra[ii]]), array([dec[ii]]))) else: print "Invalid method specified!" avlist.append(-1) return avlist
def __init__(self,model,lam,nIn=1.,nOut=1.,thetaIn=0,pol='Ey',interpolationType='materialBased', nInName="top interface",nOutName="bottom interface"): M = model self.M = M self.lam = lam self.nIn = nIn self.nOut = nOut self.thetaIn = thetaIn self.pol = pol self.interpolationType = interpolationType self.materials = [self.nIn,self.nOut] self.materialNames = [nInName,nOutName] if self.nIn.imag != 0: warnings.warn("Input refractive index HAS to be real! Expect wrong results.",Warning) if self.nOut.imag != 0: pass #warnings.warn("Warning, it is not thorougly tested if a complex epsOut works",Warning) #Seems to work.. but I guess transmission parameters make little meaning ##################### ##Derived parameters ##################### self.k0 = 2*pi/self.lam #Wave number self.freq = self.k0/(2*pi) #Frequency self.epsIn = self.nIn**2 self.epsOut = self.nOut**2 self.kIn = self.nIn*self.k0 #Wavenumber for top material self.kOut = self.nOut*self.k0 #Wavenumber for bottom material wavefrac = self.lam/(M.elmsize*max(self.nIn,self.nOut)) if wavefrac < 10: warnings.warn("You are using less than 10 elm per wavelength (may be okay"+ "for highly absorptive/reflective materials",Warning) if wavefrac < 6: warnings.warn("SERIOUSLY?? You are using less than 6 elm per wavelength (may be okay"+ "for highly absorptive/reflective materials",Warning) self.kInx = self.kIn*sin(self.thetaIn) #Inc wave vector component self.kInz = self.kIn*cos(self.thetaIn) # -||- ################################## #Precalculated sizes for FE solver ################################## self.alpha0 = self.kInx self.alpha = pl.zeros(M.NM) #print "Det ser ud til at chi er defineret forkert i Diaz vs Dossou (den skal ikke konjugeres)" self.chiIn = pl.zeros(M.NM,dtype='complex') self.chiOut = pl.zeros(M.NM,dtype='complex') for m in range(-M.Nm,M.Nm+1): idx = m+M.Nm self.alpha[idx] = self.alpha0+2*pi*m/M.lx self.chiIn[idx] = pl.conj(sqrt(0.j+self.kIn**2-self.alpha[idx]**2)) self.chiOut[idx] = pl.conj(sqrt(0.j+self.kOut**2-self.alpha[idx]**2)) self.thetaModesIn = pl.arcsin(0.j+self.alpha/self.kIn) self.thetaModesOut = pl.arcsin(0.j+self.alpha/self.kOut) self.propModesIn = abs(self.thetaModesIn.imag) < 1e-8 #Slice of incoming propagating modes self.propModesOut = abs(self.thetaModesOut.imag) < 1e-8 #Slice of outgoing propagating modes
def main(): lam = 505 thetain = -30 / 180 * pl.pi nIn = 2.8 nMaterial1 = 5.9 nMaterial2 = 4.2 #nMaterial2 = nIn #When nMaterial2 == nIn, the methods works nOut = 4.3 #If nOut<nIn, we can have values in the S matrix exceeding 1 nOut = 2.1 #nOut = nMaterial2 pol = 'Ey' nelx = 80 ##Reference model (one circle + one burried circle) Mres = model(lx=lam, lz=2 * lam, nelx=nelx) Pres = physics(Mres, lam, nIn, nOut, thetaIn=thetain, pol=pol) if 1: #Put to zero to avoid re-simulation and use last saved results materialRes1 = Pres.newMaterial(nMaterial1) materialRes2 = Pres.newMaterial(nMaterial2) materialResOut = Pres.newMaterial(nOut) xres = Mres.generateEmptyDesign() makeSlab(xres, Mres, 0, 0.5 * lam, materialResOut) makeSlab(xres, Mres, 0.5 * lam, 1.5 * lam, materialRes2) makeCircle(xres, Mres, 250, 200, materialRes1) makeCircle(xres, Mres, 250 + lam, 200, materialRes1) if 0: #Show design pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("full_structure.png", bbox_inches='tight') pl.show() exit() res = FE(Mres, Pres, xres) saveDicts("SmatrixRIInternalReference.h5", res, 'w') else: res = loadDicts("SmatrixRIInternalReference.h5")[0] mR, thetaR, R, mT, thetaT, T = calcRT(Mres, Pres, res["r"], res["t"]) Rres = R Tres = T ##Scattering matrix model 1 (one burried circle) M = model(lx=lam, lz=lam, nelx=nelx) #Notice how nOut here is nMaterial2 P = physics(M, lam, nIn, nMaterial2, thetaIn=thetain, pol=pol) material1 = P.newMaterial(nMaterial1) material2 = P.newMaterial(nMaterial2) x = M.generateEmptyDesign() makeSlab(x, M, 0, .5 * lam, material2) makeCircle(x, M, 250, 200, material1) if 0: #Show design pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("upper_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S1real = matL * S1 * matR ##Scattering matrix model 2 (one burried circle) M = model(lx=lam, lz=lam, nelx=nelx) thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetain)) P = physics(M, lam, nMaterial2, nOut, thetaIn=thetainNew, pol=pol) material1 = P.newMaterial(nMaterial1) material2 = P.newMaterial(nMaterial2) materialOut = P.newMaterial(nOut) x = M.generateEmptyDesign() makeSlab(x, M, .5 * lam, lam, material2) makeSlab(x, M, 0, .5 * lam, materialOut) makeCircle(x, M, 250, 200, material1) if 0: #Show design pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("lower_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S2real = matL * S2 * matR if 0: #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. tmp = S2 * einc rnew = tmp[:M.NM].view(pl.ndarray).flatten() tnew = tmp[M.NM:].view(pl.ndarray).flatten() mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(M, P, rnew, tnew) tmp = S2real * einc r = tmp[:M.NM].view(pl.ndarray).flatten() t = tmp[M.NM:].view(pl.ndarray).flatten() idx = P.propModesIn R = abs(r[idx])**2 idx = P.propModesOut T = abs(t[idx])**2 print "-" * 50 print R print Rnew print T print Tnew print abs(R - Rnew).max() print abs(T - Tnew).max() exit() #Stack the two scattering elements Stot = stackElements(S1, S2) #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. tmp = Stot * einc rnew = tmp[:M.NM].view(pl.ndarray).flatten() tnew = tmp[M.NM:].view(pl.ndarray).flatten() mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew) print("-" * 32) print(Rres) print(Rnew) print("-" * 10) print(Tres) print(Tnew) print("-" * 32) print("Error in reflection : {:.2e}".format(abs(Rnew - Rres).max())) print("Error in transmission: {:.2e}".format(abs(Tnew - Tres).max())) #print("(note: since the significant numbers are in general between 0.01 and 1") #print(" we required a much lower error (1e-6 or better) to confirm that it works)") #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. Stotreal = stackElements(S1real, S2real) #Stotreal = S1real if 1: pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1) print abs(S1real).max() pl.colorbar() pl.show() pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1) print abs(S2real).max() pl.colorbar() pl.show() tmp = Stotreal * einc r = tmp[:M.NM].view(pl.ndarray).flatten() t = tmp[M.NM:].view(pl.ndarray).flatten() idx = Pres.propModesIn R = abs(r[idx])**2 idx = Pres.propModesOut T = abs(t[idx])**2 print "-" * 50 print Rres print Rnew print R print("Error in reflection : {:.2e}".format(abs(R - Rres).max())) print("Error in transmission: {:.2e}".format(abs(T - Tres).max()))
def asEuler(self): qw, qx, qy, qz = self.q head = atan2(2*qy*qw-2*qx*qz, 1-2*qy*qy-2*qz*qz) att = arcsin(2*qx*qy+2*qz*qw) bank = atan(2*qx*qw-2*qy*qz, 1-2*qx*qx-2*qz*qz) return (head, att, bank)
def lossCone( fieldRatio = 2.0 ): return 1.0/pylab.arcsin( pylab.sqrt( fieldRatio ) )
def calcCrossSectionNodes(self): ''' @brief: find the (x,y) nodal locations in the tire cross section, where x is the longitudinal (forward), y is the lateral dirs. Appends: _OA_nodes: number of nodes in arc OA _th_incr: last rotation along arc OA _r_AB: if set XYoffsets for AB, we'll be finding the radius, _phi0: the angle of the last node in the swept arc OA _AB_nodes: number of nodes in arc AB _phi_incr: increment of the sweep angle along arc AB _xOA, _yOA, _xAB, _yAB: the nodal locations ''' w = self._w_tire ys = self._ds # *** OA *** OA_ymax = w/2.0 # how far in the y-dir does section OA extend? OA_rad = self._r_OA # radius for OA curve OA_x_offset = self._r_tire - OA_rad # if we change the radius of the circle swept, need # to move center of circle when finding coords OA_nodes = int(OA_ymax / ys) + 1 self._OA_nodes = OA_nodes self._xOA = py.zeros((2,OA_nodes)) self._yOA = py.zeros((2,OA_nodes)) th = th_old = th_incr = 0.0 # rotation angle # just move each node over ys in the x-dir for i in range(0, OA_nodes): self._yOA[0,i] = ys * i # right side of curve self._yOA[1,i] = -ys * i # left side of curve th_old = th th = py.arcsin(ys*i / OA_rad) # find theta based on y_i th_incr = th - th_old # theta increment, this step self._xOA[0,i] = self._xOA[1,i] = OA_x_offset + OA_rad*py.cos(th) # x is also on the circle # keep the last th_incr, for plotting self._th_incr = th_incr # *** AB *** # this is how I usually do it, but use the input XY offset for AB instead if(self._useABoffset): # AB_y_off = w/2.0 / 2.0 # essentially the CM of circle that defines AB, use as offsets AB_y_off = self._AB_y_off # AB_x_off = r - w/2.0 AB_x_off = self._AB_x_off AB_rad = py.sqrt((self._yOA[0,OA_nodes-1]-AB_y_off)**2 + (self._xOA[0,OA_nodes-1]-AB_x_off)**2) # new radius of curve to sweep, AB self._r_AB = AB_rad # set the AB_rad, now that we know it phi0 = py.arcsin((self._yOA[0,OA_nodes-1]-AB_y_off) / AB_rad) self._phi0 = phi0 arc_len = AB_rad*(self._sw_sweep_ang - phi0) AB_nodes = int( arc_len / ys ) self._AB_nodes = AB_nodes self._xAB = py.zeros((2,AB_nodes)) self._yAB = py.zeros((2,AB_nodes)) # angle increment based on sweeping about 20% past 90 degrees from x-plane phi_incr = (self._sw_sweep_ang - phi0) / AB_nodes self._phi_incr = phi_incr for j in range(0,AB_nodes): # don't re-do first node on arc, we're starting from last swept OA node phi_j = phi0 + (1+j)*phi_incr self._yAB[0,j] = AB_y_off + AB_rad * py.sin(phi_j) self._yAB[1,j] = -AB_y_off - AB_rad * py.sin(phi_j) self._xAB[0,j] = self._xAB[1,j] = AB_x_off + AB_rad * py.cos(phi_j) # I'll figure this out later else: arg = 2
def lambert(r1vec,r2vec,tf,m,muC): # original documentation: # ············································· # # This routine implements a new algorithm that solves Lambert's problem. The # algorithm has two major characteristics that makes it favorable to other # existing ones. # # 1) It describes the generic orbit solution of the boundary condition # problem through the variable X=log(1+cos(alpha/2)). By doing so the # graph of the time of flight become defined in the entire real axis and # resembles a straight line. Convergence is granted within few iterations # for all the possible geometries (except, of course, when the transfer # angle is zero). When multiple revolutions are considered the variable is # X=tan(cos(alpha/2)*pi/2). # # 2) Once the orbit has been determined in the plane, this routine # evaluates the velocity vectors at the two points in a way that is not # singular for the transfer angle approaching to pi (Lagrange coefficient # based methods are numerically not well suited for this purpose). # # As a result Lambert's problem is solved (with multiple revolutions # being accounted for) with the same computational effort for all # possible geometries. The case of near 180 transfers is also solved # efficiently. # # We note here that even when the transfer angle is exactly equal to pi # the algorithm does solve the problem in the plane (it finds X), but it # is not able to evaluate the plane in which the orbit lies. A solution # to this would be to provide the direction of the plane containing the # transfer orbit from outside. This has not been implemented in this # routine since such a direction would depend on which application the # transfer is going to be used in. # # please report bugs to [email protected] # # adjusted documentation: # ······················· # # By default, the short-way solution is computed. The long way solution # may be requested by giving a negative value to the corresponding # time-of-flight [tf]. # # For problems with |m| > 0, there are generally two solutions. By # default, the right branch solution will be returned. The left branch # may be requested by giving a negative value to the corresponding # number of complete revolutions [m]. # Authors # .·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·. # Name : Dr. Dario Izzo # E-mail : [email protected] # Affiliation: ESA / Advanced Concepts Team (ACT) # Made readible and optimized for speed by Rody P.S. Oldenhuis # Code available in MGA.M on http://www.esa.int/gsp/ACT/inf/op/globopt.htm # last edited 12/Dec/2009 # ADJUSTED FOR EML-COMPILATION 24/Dec/2009 # initial values tol = 1e-12 bad = False days = 1 # work with non-dimensional units r1 = norm(r1vec) #sqrt(r1vec*r1vec.'); r1vec = r1vec/r1; r1vec = r1vec / r1 r2vec = r2vec / r1 V = sqrt(muC/r1) T = r1/V tf= tf*days/T # also transform to seconds # relevant geometry parameters (non dimensional) mr2vec = norm(r2vec) # make 100# sure it's in (-1 <= dth <= +1) dth = arccos( max(-1, min(1, (r1vec.dot(r2vec)/mr2vec)))) # decide whether to use the left or right branch (for multi-revolution # problems), and the long- or short way leftbranch = sign(m) longway = sign(tf) m = abs(m) tf = abs(tf) if (longway < 0): dth = 2*pi - dth # derived quantities c = sqrt(1.0 + mr2vec**2 - 2*mr2vec*cos(dth)) # non-dimensional chord s = (1.0 + mr2vec + c)/2.0 # non-dimensional semi-perimeter a_min = s/2.0 # minimum energy ellipse semi major axis Lambda = sqrt(mr2vec)*cos(dth/2.0)/s # lambda parameter (from BATTIN's book) crossprd = cross(r1vec,r2vec) mcr = norm(crossprd) # magnitues thereof nrmunit = crossprd/mcr # unit vector thereof # Initial values # ························································· # ELMEX requires this variable to be declared OUTSIDE the IF-statement logt = log(tf); # avoid re-computing the same value # single revolution (1 solution) if (m == 0): # initial values inn1 = -0.5233 # first initial guess inn2 = +0.5233 # second initial guess x1 = log(1 + inn1)# transformed first initial guess x2 = log(1 + inn2)# transformed first second guess # multiple revolutions (0, 1 or 2 solutions) # the returned soltuion depends on the sign of [m] else: # select initial values if (leftbranch < 0): inn1 = -0.5234 # first initial guess, left branch inn2 = -0.2234 # second initial guess, left branch else: inn1 = +0.7234 # first initial guess, right branch inn2 = +0.5234 # second initial guess, right branch x1 = tan(inn1*pi/2)# transformed first initial guess x2 = tan(inn2*pi/2)# transformed first second guess # since (inn1, inn2) < 0, initial estimate is always ellipse xx = array([inn1, inn2]) aa = a_min/(1 - xx**2) bbeta = longway * 2*arcsin(sqrt((s-c)/2./aa)) # make 100.4% sure it's in (-1 <= xx <= +1) if xx[0] > 1: xx[0] = 1 if xx[0] < -1: xx[0] = -1 if xx[1] > 1: xx[1] = 1 if xx[1] < -1: xx[1] = -1 aalfa = 2*arccos( xx ) # evaluate the time of flight via Lagrange expression y12 = aa*sqrt(aa)*((aalfa - sin(aalfa)) - (bbeta-sin(bbeta)) + 2*pi*m) # initial estimates for y if m == 0: y1 = log(y12[0]) - logt y2 = log(y12[1]) - logt else: y1 = y12[0] - tf y2 = y12[1] - tf # Solve for x # ························································· # Newton-Raphson iterations # NOTE - the number of iterations will go to infinity in case # m > 0 and there is no solution. Start the other routine in # that case err = 1e99 iterations = 0 xnew = 0 while (err > tol): # increment number of iterations iterations += 1 # new x xnew = (x1*y2 - y1*x2) / (y2-y1); # copy-pasted code (for performance) if m == 0: x = exp(xnew) - 1 else: x = arctan(xnew)*2/pi a = a_min/(1 - x**2); if (x < 1): # ellipse beta = longway * 2*arcsin(sqrt((s-c)/2/a)) # make 100.4% sure it's in (-1 <= xx <= +1) alfa = 2*arccos( max(-1, min(1, x)) ) else: # hyperbola alfa = 2*arccosh(x); beta = longway * 2*arcsinh(sqrt((s-c)/(-2*a))) # evaluate the time of flight via Lagrange expression if (a > 0): tof = a*sqrt(a)*((alfa - sin(alfa)) - (beta-sin(beta)) + 2*pi*m) else: tof = -a*sqrt(-a)*((sinh(alfa) - alfa) - (sinh(beta) - beta)) # new value of y if m ==0: ynew = log(tof) - logt else: ynew = tof - tf # save previous and current values for the next iterarion # (prevents getting stuck between two values) x1 = x2; x2 = xnew; y1 = y2; y2 = ynew; # update error err = abs(x1 - xnew); # escape clause if (iterations > 15): bad = True break # If the Newton-Raphson scheme failed, try to solve the problem # with the other Lambert targeter. if bad: # NOTE: use the original, UN-normalized quantities #[V1, V2, extremal_distances, exitflag] = ... # lambert_high_LancasterBlanchard(r1vec*r1, r2vec*r1, longway*tf*T, leftbranch*m, muC); print "FAILZ0r" return # convert converged value of x if m==0: x = exp(xnew) - 1 else: x = arctan(xnew)*2/pi #{ # The solution has been evaluated in terms of log(x+1) or tan(x*pi/2), we # now need the conic. As for transfer angles near to pi the Lagrange- # coefficients technique goes singular (dg approaches a zero/zero that is # numerically bad) we here use a different technique for those cases. When # the transfer angle is exactly equal to pi, then the ih unit vector is not # determined. The remaining equations, though, are still valid. #} # Solution for the semi-major axis a = a_min/(1-x**2); # Calculate psi if (x < 1): # ellipse beta = longway * 2*arcsin(sqrt((s-c)/2/a)) # make 100.4# sure it's in (-1 <= xx <= +1) alfa = 2*arccos( max(-1, min(1, x)) ) psi = (alfa-beta)/2 eta2 = 2*a*sin(psi)**2/s eta = sqrt(eta2); else: # hyperbola beta = longway * 2*arcsinh(sqrt((c-s)/2/a)) alfa = 2*arccosh(x) psi = (alfa-beta)/2 eta2 = -2*a*sinh(psi)**2/s eta = sqrt(eta2) # unit of the normalized normal vector ih = longway * nrmunit; # unit vector for normalized [r2vec] r2n = r2vec/mr2vec; # cross-products # don't use cross() (emlmex() would try to compile it, and this way it # also does not create any additional overhead) #crsprd1 = [ih(2)*r1vec(3)-ih(3)*r1vec(2),... # ih(3)*r1vec(1)-ih(1)*r1vec(3),... # ih(1)*r1vec(2)-ih(2)*r1vec(1)]; crsprd1 = cross(ih,r1vec) #crsprd2 = [ih(2)*r2n(3)-ih(3)*r2n(2),... # ih(3)*r2n(1)-ih(1)*r2n(3),... # ih(1)*r2n(2)-ih(2)*r2n(1)]; crsprd2 = cross(ih,r2n) # radial and tangential directions for departure velocity Vr1 = 1/eta/sqrt(a_min) * (2*Lambda*a_min - Lambda - x*eta) Vt1 = sqrt(mr2vec/a_min/eta2 * sin(dth/2)**2) # radial and tangential directions for arrival velocity Vt2 = Vt1/mr2vec Vr2 = (Vt1 - Vt2)/tan(dth/2) - Vr1 # terminal velocities V1 = (Vr1*r1vec + Vt1*crsprd1)*V V2 = (Vr2*r2n + Vt2*crsprd2)*V # exitflag #exitflag = 1 # (success) #print "V1:",V1 #print "V2:",V2 return V1,V2
def asEuler(self): qw, qx, qy, qz = self.q head = atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz) att = arcsin(2 * qx * qy + 2 * qz * qw) bank = atan(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz) return (head, att, bank)
ra = float(groups[groups['target'] ==True]['ra'].unique()[0]) if ra < 0: ra = ra * -1. dec = float(groups[groups['target'] ==True]['dec'].unique()[0]) correctedList.append((ra,dec,0)) for i in pointing.query('go == "%s"'%name).rowNum.values: row = rows[i] dRA,dDec = [[p[0].get(),p[1].get()] for p in row.sourceOffset() ][row.numSample()/2] # if dRA == 0. or dDec == 0.: # print "no Offset positions in the Pointing Table" # print "Is this EB a MultiSource?" # sys.exit(1) Pl = [pl.cos(dRA)*pl.cos(dDec), pl.sin(dRA)*pl.cos(dDec), pl.sin(dDec)] Ps = rot(Pl, ra, dec) correctedList.append((pl.arctan2(Ps[1], Ps[0]) % (2.*pl.pi), pl.arcsin(Ps[2]), i)) correctedAll = pd.DataFrame(correctedList, columns=['ra','dec', 'row']) corrected = correctedAll[['ra','dec']] corrected['series'] = 'Corrected (Pointing.bin)' corrected = corrected.drop_duplicates() corrected = corrected.reset_index(drop=True) observed = field[field['target'] == True][['fieldId','ra','dec']] observed.ra = observed.ra.astype(float) observed.dec = observed.dec.astype(float) observed['ra'] = observed.apply(lambda x: x['ra']*-1. if x['ra'] < 0.0 else x['ra'], axis = 1) observed = observed.loc[observed['fieldId'].isin(fullbar) ] observed = observed.reset_index(drop=True) observed['series'] = 'Field.xml'
def calcdp(rep_no, thetainput): rep_no = rep_no wav = 505 lam = 400 thetain = thetainput / 180 * pl.pi nAir = 1.0 nBac = 1.38 nMed = 1.34 pol = 'Ey' nelx = 40 z_uc = 2.0 * math.sqrt(3) ##Reference model FE_start_time = time.time() Mres = model(lx=2 * lam, lz=(1 + rep_no) * (z_uc) * lam, nelx=nelx) Pres = physics(Mres, wav, nAir, nBac, thetaIn=thetain, pol=pol) if 1: #Put to zero to avoid re-simulation and use last saved results materialResAir = Pres.newMaterial(nAir) materialResBac = Pres.newMaterial(nBac) materialResMed = Pres.newMaterial(nMed) xres = Mres.generateEmptyDesign() makeSlab(xres, Mres, (rep_no) * (z_uc) * lam, (1 + rep_no) * (z_uc) * lam, materialResAir) makeSlab(xres, Mres, 0 * (z_uc) * lam, (rep_no) * (z_uc) * lam, materialResMed) for x in range(0, rep_no): makeCircle(xres, Mres, lam, x * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, 0, (x + 1 / 2) * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, 2 * lam, (x + 1 / 2) * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, lam, (rep_no) * (z_uc) * lam, lam, materialResBac) if 0: #Show design pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("full_structure.png", bbox_inches='tight') pl.show() exit() res = FE(Mres, Pres, xres) #saveDicts("SmatrixRIInternalReference.h5",res,'a') #else: #res = loadDicts("SmatrixRIInternalReference.h5")[0] mR, thetaR, R, mT, thetaT, T = calcRT(Mres, Pres, res["r"], res["t"]) Rres = R Tres = T FE_time = time.time() - FE_start_time CSM_start_time = time.time() ##Scattering matrix model air-material boundary M = model(lx=2.0 * lam, lz=1 * (z_uc) * lam, nelx=nelx) P = physics(M, wav, nAir, nBac, thetaIn=thetain, pol=pol) materialAir = P.newMaterial(nAir) materialBac = P.newMaterial(nBac) materialMed = P.newMaterial(nMed) x = M.generateEmptyDesign() makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialAir) makeCircle(x, M, lam, 0, lam, materialBac) if 0: #Show design pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("upper_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S1real = matL * S1 * matR Stot = S1 Stotreal = S1real thetainNew = thetain ##Scattering matrix model unit cell M = model(lx=2.0 * lam, lz=(z_uc) * lam, nelx=nelx) thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetainNew)) P = physics(M, wav, nBac, nBac, thetaIn=thetainNew, pol=pol) # materialAir = P.newMaterial(nAir) materialBac = P.newMaterial(nBac) materialMed = P.newMaterial(nMed) x = M.generateEmptyDesign() makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialMed) makeCircle(x, M, lam, 0, lam, materialBac) makeCircle(x, M, lam, 1.0 * (z_uc) * lam, lam, materialBac) makeCircle(x, M, 0, (1 / 2) * (z_uc) * lam, lam, materialBac) makeCircle(x, M, 2 * lam, (1 / 2) * (z_uc) * lam, lam, materialBac) if 0: #Show design pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("lower_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S2real = matL * S2 * matR for x in range(1, rep_no + 1): Stot = stackElements(Stot, S2) Stotreal = stackElements(Stotreal, S2real) CSM_time = time.time() - CSM_start_time #Stack the two scattering elements #Stot = stackElements(S1,S2) RIn, TIn, TOut, ROut = StoRT(Stot) results = {} results["RIn"] = RIn results["TIn"] = TIn results["ROut"] = ROut results["TOut"] = TOut results.update(M.getParameters()) results.update(P.getParameters()) #saveDicts("SmatrixRICalculations.h5",results,'a') #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. tmp = Stot * einc rnew = tmp[:M.NM].view(pl.ndarray).flatten() tnew = tmp[M.NM:].view(pl.ndarray).flatten() mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew) title = "speed_wrt_rep_no_FE.csv" txtdata = open(title, "a") txtdata.write("{:f}, {:.8f}\n".format(rep_no, FE_time)) title = "speed_wrt_rep_no_CSM.csv" txtdata = open(title, "a") txtdata.write("{:f}, {:.8f}\n".format(rep_no, CSM_time)) print("rep_no={:f}, FE_time={:.8f}, CSM_time={:.8f}".format( rep_no, FE_time, CSM_time)) txtdata.close() #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. #Stotreal = S1real if 0: pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1) print abs(S1real).max() pl.colorbar() pl.show() pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1) print abs(S2real).max() pl.colorbar() pl.show() tmp = Stotreal * einc r = tmp[:M.NM].view(pl.ndarray).flatten() t = tmp[M.NM:].view(pl.ndarray).flatten() idx = Pres.propModesIn R = abs(r[idx])**2 idx = Pres.propModesOut T = abs(t[idx])**2 return
dec = float(source[source['target'] ==True]['dec'].unique()[0]) geo = pd.merge(antenna,station, left_on='stationId', right_on = 'stationId', how = 'inner') geo['pos'] = geo.apply(lambda x: arrayParser(x['position'],1) , axis = 1 ) geo['lat'], geo['lon'], geo['alt'] = zip(*geo.apply(lambda x: gh.turn_xyz_into_llh(float(x.pos[0]),float(x.pos[1]),float(x.pos[2]), 'wgs84'),axis=1)) field['ra'],field['dec'] = zip(*field.apply(lambda x: arrayParser(x['referenceDir'],2)[0], axis = 1)) correctedList = list() correctedList.append((ra,dec,0)) for i in pointing.query('go == True').rowNum.values: row = rows[i] dRA,dDec = [[float(str(p[0]).replace('rad','').replace(',','.')),float(str(p[1]).replace('rad','').replace(',','.'))] for p in row.sourceOffset() ][row.numSample()/2] Pl = [pl.cos(dRA)*pl.cos(dDec), pl.sin(dRA)*pl.cos(dDec), pl.sin(dDec)] Ps = rot(Pl, ra, dec) correctedList.append((pl.arctan2(Ps[1], Ps[0]) % (2.*pl.pi), pl.arcsin(Ps[2]), i)) correctedAll = pd.DataFrame(correctedList, columns=['ra','dec', 'row']) corrected = correctedAll[['ra','dec']] corrected['series'] = 'Corrected (Pointing)' observed = field[field['target'] == True][['fieldId','ra','dec']] observed.ra = observed.ra.astype(float) observed.dec = observed.dec.astype(float) observed = observed.loc[observed['fieldId'].isin(bar) ] observed = observed.reset_index(drop=True) corrected = corrected.drop_duplicates() corrected = corrected.reset_index(drop=True) cat = SkyCoord(observed.ra.values * u.rad, observed.dec.values * u.rad, frame='icrs') cat2 = SkyCoord(corrected.ra.values * u.rad, corrected.dec.values *u.rad, frame='icrs') match, separ, dist = cat2.match_to_catalog_sky(cat)
def calcCrossSectionNodes(self): ''' @brief: find the (x,y) nodal locations in the tire cross section, where x is the longitudinal (forward), y is the lateral dirs. Appends: _OA_nodes: number of nodes in arc OA _th_incr: last rotation along arc OA _r_AB: if set XYoffsets for AB, we'll be finding the radius, _phi0: the angle of the last node in the swept arc OA _AB_nodes: number of nodes in arc AB _phi_incr: increment of the sweep angle along arc AB _xOA, _yOA, _xAB, _yAB: the nodal locations ''' w = self._w_tire ys = self._ds # *** OA *** OA_ymax = w / 2.0 # how far in the y-dir does section OA extend? OA_rad = self._r_OA # radius for OA curve OA_x_offset = self._r_tire - OA_rad # if we change the radius of the circle swept, need # to move center of circle when finding coords OA_nodes = int(OA_ymax / ys) + 1 self._OA_nodes = OA_nodes self._xOA = py.zeros((2, OA_nodes)) self._yOA = py.zeros((2, OA_nodes)) th = th_old = th_incr = 0.0 # rotation angle # just move each node over ys in the x-dir for i in range(0, OA_nodes): self._yOA[0, i] = ys * i # right side of curve self._yOA[1, i] = -ys * i # left side of curve th_old = th th = py.arcsin(ys * i / OA_rad) # find theta based on y_i th_incr = th - th_old # theta increment, this step self._xOA[0, i] = self._xOA[1, i] = OA_x_offset + OA_rad * py.cos( th) # x is also on the circle # keep the last th_incr, for plotting self._th_incr = th_incr # *** AB *** # this is how I usually do it, but use the input XY offset for AB instead if (self._useABoffset): # AB_y_off = w/2.0 / 2.0 # essentially the CM of circle that defines AB, use as offsets AB_y_off = self._AB_y_off # AB_x_off = r - w/2.0 AB_x_off = self._AB_x_off AB_rad = py.sqrt((self._yOA[0, OA_nodes - 1] - AB_y_off)**2 + (self._xOA[0, OA_nodes - 1] - AB_x_off)** 2) # new radius of curve to sweep, AB self._r_AB = AB_rad # set the AB_rad, now that we know it phi0 = py.arcsin((self._yOA[0, OA_nodes - 1] - AB_y_off) / AB_rad) self._phi0 = phi0 arc_len = AB_rad * (self._sw_sweep_ang - phi0) AB_nodes = int(arc_len / ys) self._AB_nodes = AB_nodes self._xAB = py.zeros((2, AB_nodes)) self._yAB = py.zeros((2, AB_nodes)) # angle increment based on sweeping about 20% past 90 degrees from x-plane phi_incr = (self._sw_sweep_ang - phi0) / AB_nodes self._phi_incr = phi_incr for j in range(0, AB_nodes): # don't re-do first node on arc, we're starting from last swept OA node phi_j = phi0 + (1 + j) * phi_incr self._yAB[0, j] = AB_y_off + AB_rad * py.sin(phi_j) self._yAB[1, j] = -AB_y_off - AB_rad * py.sin(phi_j) self._xAB[0, j] = self._xAB[1, j] = AB_x_off + AB_rad * py.cos(phi_j) # I'll figure this out later else: arg = 2
def calcdp(wavinput, thetainput): rep_no = 50 wav = wavinput lam = 400 thetain = thetainput / 180 * pl.pi nAir = 1.0 nBac = 1.38 nMed = 1.34 #nMaterial2 = nIn #When nMaterial2 == nIn, the methods works #nOut = nMaterial2 pol = 'Ey' nelx = 40 z_uc = 2.0 * math.sqrt(3) ##Scattering matrix model air-material boundary Mres = model(lx=2 * lam, lz=(1 + rep_no) * (z_uc) * lam, nelx=nelx) Pres = physics(Mres, wav, nAir, nBac, thetaIn=thetain, pol=pol) if 1: #Put to zero to avoid re-simulation and use last saved results materialResAir = Pres.newMaterial(nAir) materialResBac = Pres.newMaterial(nBac) materialResMed = Pres.newMaterial(nMed) xres = Mres.generateEmptyDesign() makeSlab(xres, Mres, (rep_no) * (z_uc) * lam, (1 + rep_no) * (z_uc) * lam, materialResAir) makeSlab(xres, Mres, 0 * (z_uc) * lam, (rep_no) * (z_uc) * lam, materialResMed) for x in range(0, rep_no): makeCircle(xres, Mres, lam, x * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, 0, (x + 1 / 2) * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, 2 * lam, (x + 1 / 2) * (z_uc) * lam, lam, materialResBac) makeCircle(xres, Mres, lam, (rep_no) * (z_uc) * lam, lam, materialResBac) if 0: #Show design pl.imshow(xres.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("full_structure.png", bbox_inches='tight') pl.show() exit() ##Scattering matrix model air-material boundary M = model(lx=2.0 * lam, lz=1 * (z_uc) * lam, nelx=nelx) #Notice how nOut here is nMaterial2 P = physics(M, wav, nAir, nBac, thetaIn=thetain, pol=pol) materialAir = P.newMaterial(nAir) materialBac = P.newMaterial(nBac) materialMed = P.newMaterial(nMed) x = M.generateEmptyDesign() makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialAir) makeCircle(x, M, lam, 0, lam, materialBac) if 0: #Show design pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("upper_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S1 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S1real = matL * S1 * matR Stot = S1 Stotreal = S1real thetainNew = thetain ##Scattering matrix model unit cell M = model(lx=2.0 * lam, lz=(z_uc) * lam, nelx=nelx) thetainNew = pl.arcsin(P.nIn / P.nOut * pl.sin(thetainNew)) P = physics(M, wav, nBac, nBac, thetaIn=thetainNew, pol=pol) # materialAir = P.newMaterial(nAir) materialBac = P.newMaterial(nBac) materialMed = P.newMaterial(nMed) x = M.generateEmptyDesign() makeSlab(x, M, 0, 1.0 * (z_uc) * lam, materialMed) makeCircle(x, M, lam, 0, lam, materialBac) makeCircle(x, M, lam, 1.0 * (z_uc) * lam, lam, materialBac) makeCircle(x, M, 0, (1 / 2) * (z_uc) * lam, lam, materialBac) makeCircle(x, M, 2 * lam, (1 / 2) * (z_uc) * lam, lam, materialBac) if 0: pl.imshow(x.T, interpolation='none', vmin=0, vmax=4) pl.colorbar() pl.savefig("lower_half.png", bbox_inches='tight') pl.show() exit() res = calcScatteringMatrix(M, P, x) S2 = RTtoS(res["RIn"], res["TIn"], res["TOut"], res["ROut"]) matL = pl.bmat([[pl.diag(pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(pl.sqrt(P.chiOut))]]) matR = pl.bmat([[pl.diag(1 / pl.sqrt(P.chiIn)), pl.zeros((M.NM, M.NM))], [pl.zeros((M.NM, M.NM)), pl.diag(1 / pl.sqrt(P.chiOut))]]) S2real = matL * S2 * matR for x in range(1, rep_no + 1): Stot = stackElements(Stot, S2) Stotreal = stackElements(Stotreal, S2real) RIn, TIn, TOut, ROut = StoRT(Stot) results = {} results["RIn"] = RIn results["TIn"] = TIn results["ROut"] = ROut results["TOut"] = TOut results.update(M.getParameters()) results.update(P.getParameters()) #saveDicts("SmatrixRICalculations.h5",results,'a') #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. tmp = Stot * einc rnew = tmp[:M.NM].view(pl.ndarray).flatten() tnew = tmp[M.NM:].view(pl.ndarray).flatten() mR, thetaR, Rnew, mT, thetaT, Tnew = calcRT(Mres, Pres, rnew, tnew) for i in range(len(mR)): title = "reflect_mode_n_equals_{:d}_50.csv".format(mR[i]) txtdata = open(title, "a") txtdata.write("{:d}, {:f}, {:.8f}\n".format(wavinput, thetainput, Rnew[i])) #print("m={:d}, theta={:f}, mode={:d}, R={:.8f}".format(wavinput,thetainput,mR[i],Rnew[i])) txtdata.close() for i in range(len(mT)): title = "trans_mode_n_equals_{:d}_50.csv".format(mT[i]) txtdata = open(title, "a") txtdata.write("{:d}, {:f}, {:.8f}\n".format(wavinput, thetainput, Tnew[i])) #print("m={:d}, theta={:f}, mode={:d}, T={:.8f}".format(wavinput,thetainput,mT[i],Tnew[i])) txtdata.close() #Define incident wave as a plane wave einc = pl.zeros((2 * M.NM, 1), dtype='complex').view(pl.matrix) einc[M.NM // 2, 0] = 1. #Stotreal = S1real if 0: pl.imshow(abs(S1real), interpolation='none', vmin=0, vmax=1) print abs(S1real).max() pl.colorbar() pl.show() pl.imshow(abs(S2real), interpolation='none', vmin=0, vmax=1) print abs(S2real).max() pl.colorbar() pl.show() tmp = Stotreal * einc r = tmp[:M.NM].view(pl.ndarray).flatten() t = tmp[M.NM:].view(pl.ndarray).flatten() idx = Pres.propModesIn R = abs(r[idx])**2 idx = Pres.propModesOut T = abs(t[idx])**2 return
def initFromStateVectors(self,epoch,pV,vV): self.epoch = epoch # 1) Calculate auxilary vector h hV = cross(pV,vV) # 2) Normalize position,velocity, specific angular momentum, calculate radial velocity p = linalg.norm(pV) v = linalg.norm(vV) h = linalg.norm(hV) print "H:",h radv = pV.dot(vV) / p hVu = hV / h pVu = pV / p nV = cross(array([0,0,1]),hV) n = linalg.norm(nV) if n == 0: nVu = array([0,0,0]) else: nVu = nV/n # 3) Calculate inclination #self.i = arccos(hV[2]/h) self.i = arcsin(linalg.norm(cross(array([0,0,1]),hVu))) print "i1",self.i print "RADVEL",radv self.i = arccos(array([0,0,1]).dot(hV)/h) #if radv < 0: # self.i = PI2 - self.i print "i2",self.i # 4) Calculate node line # 5) Calculate longitude of ascending node = right ascension of ascending node ''' if self.i == 0: self.lan=0 elif nV[1] >= 0: self.lan = arccos(nV[0] / n) else: self.lan = PI2 - arccos(nV[0] / n) ''' if self.i == 0: self.lan = 0 else: self.lan = arcsin(cross(array([1,0,0]),nVu).dot(array([0,0,1]))) print "lan1",self.lan self.lan = arccos(array([1,0,0]).dot(nV)/n) if nV[1] < 0: self.lan = PI2-self.lan print "lan2",self.lan # 6) Eccentricity vector #eV = (1.0 / self.ref.mu)*((v**2 - (self.ref.mu / p))*pV - radv*vV) #eV2 = (1.0 / self.ref.mu) * ( hV - self.ref.mu * (pV/p)) #eV3 = hV/self.ref.mu - (pV/p) # Source: cdeagle eV = cross(vV,hV)/self.ref.mu - pVu #print "eV1:",eV,linalg.norm(eV) #print "eV2:",eV2,linalg.norm(eV2) #print "eV3:",eV3,linalg.norm(eV3) print "eV3:",eV,linalg.norm(eV) self._e = linalg.norm(eV) #eVu = eV / self.e print "h",h print "u",self.ref.mu print "v",v print "r",p print "alte:",sqrt(1+(h**2/self.ref.mu**2)*(v**2-(2*self.ref.mu)/p)**2) # 7) Argument of perigree ''' if self.e == 0: self.aop = 0 elif self.i == 0: self.aop = arccos(eV[0] / self.e) elif eV[2] >= 0: print "AOP AOP AOP" #self.aop = arccos(nV.dot(eV) / (n*self.e)) print cross(nV,eV).dot(hV) self.aop = arcsin(cross(nVu,eVu).dot(hVu)) #self.aop = arccos(n*self.e) else: self.aop = PI2 - arccos(nV.dot(eV) / (n*self.e)) ''' #CDEagle method # TODO CHECK how KSP handles this. if self.e == 0: self.aop = 0 elif self.i == 0 and self.e != 0: #self.aop = arccos(eV[0] / self.e) #self.aop = arctan2(eV[1],eV[0]) self.aop = arccos(array([1,0,0]).dot(eV) / self.e) print eV if eV[2] < 0: #self.aop = -self.aop self.aop = PI2-self.aop #print "BOOM",eV #if eV[2] < 0: # print "BAM N***A" # self.aop = PI2 - self.aop elif self.i == 0 and self.e == 0: #raise AttributeError("Perfectly circular orbits are not supported atm") self.aop = 0 else: #self.aop = arcsin(cross(nVu,eVu).dot(hVu)) self.aop = arccos(nV.dot(eV)/(n*self.e)) if eV[2] < 0: self.aop = PI2-self.aop # 8) Semi major axis aE = v**2/2.0 - self.ref.mu / p self._a = -self.ref.mu / (2*aE) print "Old method for semi-major",self.a self._a = h**2 / (self.ref.mu * (1-self.e**2)) print "New method for semi-major",self.a #if self.e > 1: # self._a = h**2 / (self.ref.mu * (self.e**2 - 1)) if self.e == 0: if self.i == 0: #TODO update document to this print "JEA JEA JEA JEA"*10 ta = arccos(array([1,0,0]).dot(pV) / p) if pV[1] < 0: # Vallado pg. 111 ta = PI2 - ta else: #TODO VERIFY THIS CASE ta = arccos((nV.dot(pV))/(n*p)) if pV[2] < 0: # Vallado pg. 110 ta = PI2 - ta E = ta self.M0 = E elif self.e < 1: # 9) True anomaly, eccentric anomaly and mean anomaly if radv >= 0: ta = arccos((eV / self.e).dot(pV/p)) else: ta = PI2 - arccos((eV / self.e).dot(pV/p)) E = arccos((self.e+cos(ta))/(1+ self.e*cos(ta))) if radv < 0: E = PI2 - E self.M0 = E - self.e * sin(E) elif self.e > 1: # 9) Hyperbolic True anomaly, eccentric anomaly and mean anomaly # http://scienceworld.wolfram.com/physics/HyperbolicOrbit.html V = arccos((abs(self.a)*(self.e**2 - 1)) /(self.e * p) - 1/self.e) ta = arccos((eV / self.e).dot(pV/p)) if radv < 0: #TODO: Should affect F too? # Negative = heading towards periapsis print "PI2" V = PI2 - V ta = PI2-ta print "V",V print "TA",ta # http://www.bogan.ca/orbits/kepler/orbteqtn.html In you I trust # Hyperbolic eccentric anomaly cosV = cos(V) F = arccosh((self.e+cosV)/(1+self.e*cosV)) if radv < 0: F = -F F2 = arcsinh((sqrt(self.e-1)*sin(V))/(1+self.e*cos(V))) ##F1 = F2 print "F1:",F print "F2:",F2 self.M0 = self.e * sinh(F) - F self.h = h print "Semi-major:",self.a print "Eccentricity:",self.e print "Inclination:",degrees(self.i),"deg" print "LAN:",degrees(self.lan),"deg" print "AoP:",degrees(self.aop),"deg" print "Mean anomaly:",self.M0 print "Specific angular momentum:",self.h if self.e < 1: print "Eccentric anomaly",E print "True anomaly",ta else: print "Hyperbolic eccentric anomaly",F print "Hyperbolic true anomaly",degrees(V) print "Distance from object:",p print "Velocity:",v