def test_testUfuncs1(self): # Test various functions such as sin, cos. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d assert_(eq(np.cos(x), cos(xm))) assert_(eq(np.cosh(x), cosh(xm))) assert_(eq(np.sin(x), sin(xm))) assert_(eq(np.sinh(x), sinh(xm))) assert_(eq(np.tan(x), tan(xm))) assert_(eq(np.tanh(x), tanh(xm))) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(np.sqrt(abs(x)), sqrt(xm))) assert_(eq(np.log(abs(x)), log(xm))) assert_(eq(np.log10(abs(x)), log10(xm))) assert_(eq(np.exp(x), exp(xm))) assert_(eq(np.arcsin(z), arcsin(zm))) assert_(eq(np.arccos(z), arccos(zm))) assert_(eq(np.arctan(z), arctan(zm))) assert_(eq(np.arctan2(x, y), arctan2(xm, ym))) assert_(eq(np.absolute(x), absolute(xm))) assert_(eq(np.equal(x, y), equal(xm, ym))) assert_(eq(np.not_equal(x, y), not_equal(xm, ym))) assert_(eq(np.less(x, y), less(xm, ym))) assert_(eq(np.greater(x, y), greater(xm, ym))) assert_(eq(np.less_equal(x, y), less_equal(xm, ym))) assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym))) assert_(eq(np.conjugate(x), conjugate(xm))) assert_(eq(np.concatenate((x, y)), concatenate((xm, ym)))) assert_(eq(np.concatenate((x, y)), concatenate((x, y)))) assert_(eq(np.concatenate((x, y)), concatenate((xm, y)))) assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def check_sph_ortho(l1, m1, l2, m2): q, _ = integrate.dblquad( # arguments to lambda need to be reversed from args to dblquad (wtf?) lambda phi, theta: # scipy sph_harm takes order/degree (wtf?) special.sph_harm(m1, l1, theta, phi) * ma.conjugate( special.sph_harm(m2, l2, theta, phi)) * sin(phi), 0, 2 * pi, # range of theta lambda x: 0, lambda y: pi # range of phi ) return q
def incident_beam(wg, k): nx = len(wg) dx = wg[1] - wg[0] f = zeros(nx) ##pos = 0.6 ##wid = .5 pos = wg[nx / 2] wid = 10 * dx E_0 = 1 for m in range(0, nx): x = wg[m] #f[m] = E_0*cos(k*x) #can be modified to create different beam profile f[m] = E_0 * exp(-((x - pos) / wid)**2) #gaussian beam profile f = conjugate(f) f = transpose(f) return f
def calc_modes(wg, k, eps, wid): nx = len(wg) dx = wg[1] - wg[0] c = 3e14 #microns/s eps = conjugate(eps) eps = transpose(eps) #calc matrix of hermitian wave operator L Ljj = array(((-2 * ones(nx) / (dx**2 * k**2)))) maindiag = array((Ljj + eps)) offdiag = array(((1 * ones(nx - 1) / (dx**2 * k**2)))) L = diag(offdiag, -1) + diag(maindiag, 0) + diag(offdiag, 1) #ev are eigenvalues, effective permitivites (beta / k)^2 #em are corresponding eigenmodes ev, em = eig(L) return ev, em
def test_testOddFeatures(self): # Test of other odd features x = arange(20) x = x.reshape(4, 5) x.flat[5] = 12 assert_(x[1, 0] == 12) z = x + 10j * x assert_(eq(z.real, x)) assert_(eq(z.imag, 10 * x)) assert_(eq((z * conjugate(z)).real, 101 * x * x)) z.imag[...] = 0.0 x = arange(10) x[3] = masked assert_(str(x[3]) == str(masked)) c = x >= 8 assert_(count(where(c, masked, masked)) == 0) assert_(shape(where(c, masked, masked)) == c.shape) z = where(c, x, masked) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is masked) assert_(z[7] is masked) assert_(z[8] is not masked) assert_(z[9] is not masked) assert_(eq(x, z)) z = where(c, masked, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) z = masked_where(c, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) assert_(eq(x, z)) x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) c[0] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2))) assert_(eq(masked_where(greater_equal(x, 2), x), masked_greater_equal(x, 2))) assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2))) assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4])) assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])) assert_(eq(masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0])) assert_(eq(masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1])) assert_(eq(masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0])) assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1])) assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]), [99, 99, 3, 4, 5])) atest = ones((10, 10, 10), dtype=np.float32) btest = zeros(atest.shape, MaskType) ctest = masked_where(btest, atest) assert_(eq(atest, ctest)) z = choose(c, (-x, x)) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) x = arange(6) x[5] = masked y = arange(6) * 10 y[2] = masked c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0]) cm = c.filled(1) z = where(c, x, y) zm = where(cm, x, y) assert_(eq(z, zm)) assert_(getmask(zm) is nomask) assert_(eq(zm, [0, 1, 2, 30, 40, 50])) z = where(c, masked, 1) assert_(eq(z, [99, 99, 99, 1, 1, 1])) z = where(c, 1, masked) assert_(eq(z, [99, 1, 1, 99, 99, 99]))
images = [im / norm(im) for im in images] # cosine window images = [cosine_window(im) for im in images] # fft of images images = [fft.fft2(im) for im in images] targetImages = [fft.fft2(ti) for ti in targetImages] print "calculating filter" # calculate filter top = numpy.zeros((height, width)) top = top.astype('complex') bottom = numpy.zeros((height, width)) bottom = bottom.astype('complex') for r in range(len(images)): top += targetImages[r] * conjugate(images[r]) bottom += images[r] * conjugate(images[r]) filter = top / bottom filres = fft.ifft2(filter) fil = filres.real minf = numpy.min(fil) fil -= minf maxf = numpy.max(fil) fil *= (255 / maxf) fil = numpy.floor(fil) # write out to javascript file fo = {} fo['width'] = width
def build_patches(data, c, bool): filters = [] for r in range(0, num_patches): print "training patch:"+str(r) images = [] targetImages = [] # load positive examples i = 0 for filename, values in data.iteritems(): im = Image.open("./cropped/"+filename, "r") # convert image to grayscale im = im.convert("L") #generate random offset to target to generate better filters xof = random.randint(-3,3) yof = random.randint(-3,3) if not numpy.isnan(values[r][0]): # TODO : check that there is not missing data: points = values[r]+(numpy.array(im.size)/2) points = numpy.around(points) points = points.astype(numpy.uint8) left = points[0]-(patch_size/2)-xof top = points[1]-(patch_size/2)-yof nux = points[0]-left nuy = points[1]-top p_crop = im.crop((left,top,left+patch_size,top+patch_size)) Image.fromarray(numpy.asarray(p_crop).astype('int')).convert("L").save("./pcropped/mosse"+filename+".bmp") images.append(numpy.array(p_crop)) # create target images targetImage = array([0.]*(patch_size*patch_size)).reshape((patch_size,patch_size)) for xr in range(0,patch_size): for yr in range(0,patch_size): targetImage[yr,xr] = math.exp(-(((xr-nux)*(xr-nux))+((yr-nuy)*(yr-nuy)))/(0.5*0.5)) #Image.fromarray((targetImage*255).astype('int')).convert("L").save("test_target.bmp") targetImages.append(targetImage) if i % 1000 == 0: print i i += 1 # preprocess images = [im.astype(numpy.uint16) for im in images] images = [numpy.log(im+1) for im in images] # normalize images = [im-mean(im) for im in images] images = [im/norm(im) for im in images] # cosine windows images = [cosine_window(im) for im in images] # fft of images images = [fft.fft2(im) for im in images] targetImages = [fft.fft2(ti) for ti in targetImages] print "calculating filter" # calculate filter top = numpy.zeros((patch_size, patch_size)) top = top.astype('complex') bottom = numpy.zeros((patch_size, patch_size)) bottom = bottom.astype('complex') for ir in range(len(images)): if numpy.any(numpy.isnan(targetImages[ir])) or numpy.any(numpy.isnan(conjugate(images[ir]))) or numpy.any(numpy.isnan(images[ir])): import pdb;pdb.set_trace() top += targetImages[ir]*conjugate(images[ir]) bottom += images[ir]*conjugate(images[ir]) filter = top/bottom # optionally store filters as normalized images, for validation filres = fft.ifft2(filter) fil = filres.real minf = numpy.min(fil) fil -= minf maxf = numpy.max(fil) fil *= (255/maxf) fil = numpy.floor(fil) Image.fromarray(fil.astype('int')).convert("L").save("./svmImages/svm"+str(r)+".bmp") # #fi = open("./svmFilters/filter"+str(r)+".pickle", "w") #pickle.dump(clf.coef_, fi) #fi.close() filter_real = map(lambda x: x.real, filter.flatten().tolist()) filter_imag = map(lambda x: x.imag, filter.flatten().tolist()) filter = [filter_real, filter_imag] filters.append(filter) # output for standard model: #filteroutput = [filters[f][r] for r in range(0, patch_size*patch_size) for f in range(0, num_patches)] filteroutput = filters # output result as dictionary with entries patchModel = {} patchModel['patchSize'] = [patch_size, patch_size] patchModel['weights'] = filteroutput patchModel['numPatches'] = num_patches patchModel['patchType'] = 'MOSSE' return patchModel
def CN(wg, eps, k, ib, z_len, nz): z = linspace(0, z_len, nz) dz = z[1] - z[0] n0 = cmath.sqrt(eps[0]) #refractive index of layer nx = len(wg) dx = wg[1] - wg[0] #Generate Propagation operator matrix (P) eps = conjugate(eps) eps = transpose(eps) maindiag = array((-2 * ones(nx) / dx**2 / (2 * k * n0)), 'complex') #((For a single slab/substrate)) ##maindiag = array(( (-2*ones(nx) / dx**2 + k**2 * (eps - n0**2)) / (2*k*n0) ),'complex') offdiag = array((ones(nx - 1) / dx**2 / (2 * k * n0)), 'complex') P = array((diag(offdiag, -1) + diag(maindiag, 0) + diag(offdiag, 1)), 'complex') #Forward & backward propagation Forw = identity((nx), 'complex') + 1j * dz * P / 2 Back = identity((nx), 'complex') - 1j * dz * P / 2 ib_z = zeros((nx, nz), 'complex') thresh = 1e-5 #cutoff for electric field ib_z[:, 0] = ib #incident field at E(x,z=0) #Solve for ib_z at each z value, modify according to Hadley BC #that is, transparent boundary for evanescent fields for m in range(1, nz): FF = Forw BB = Back #update fields at lower boundary if (abs(ib[0]) > thresh): k0 = 1j / dx * log(ib[1] / ib[0]) if real(k0) <= 0: k0 = 1j * imag(k0) TBC = exp(1j * k0 * dx) / dx**2 * 1j * dz / 2 / (2 * k * n0) FF[0, 0] = FF[0, 0] + TBC BB[0, 0] = BB[0, 0] - TBC #and on upper boundary if (abs(ib[nx - 1]) > thresh): k0 = -1j / dx * log(ib[nx - 1] / ib[nx - 2]) if real(k0) <= 0: k0 = 1j * imag(k0) TBC = exp(1j * k0 * dx) / dx**2 * 1j * dz / 2 / (2 * k * n0) FF[nx - 1, nx - 1] = FF[nx - 1, nx - 1] + TBC BB[nx - 1, nx - 1] = BB[nx - 1, nx - 1] - TBC #solve for incident field at z with the transparent BC ib = solve(BB, dot(FF, ib)) ib_z[:, m] = real(ib) X, Z = meshgrid(z, wg) #visualize propagation of power through waveguide pwrplt = contour(X, Z, abs(ib_z)**2, 32) return ib_z
def calc_absorp(gm, wid): #Make everything positive gm = sqrt(conjugate(gm) * gm) nModes = len(gm.shape) nLayers = len(wid) if nModes > 1: #more than one guided mode (need to count columns) nModes = gm.shape[1] if nModes == 1: dy = len(gm[:]) elif nModes > 1: dy = len(gm[:, 0]) #number of points gm is evaluated at axis = cumsum(wid) axis = insert(axis, 0, 0) A = zeros( (nLayers, nModes), 'complex') #array holds absorption values in each layer for each mode A_s = zeros((nLayers, nModes), 'complex') #Integrate guided modes to find absorption in each layer for m in range(0, nModes): for i in range(0, nLayers): nx = (axis[i + 1] - axis[i] ) / axis[-1] * dy #num of pts evaluated at within layer x0 = (axis[i] - axis[0]) / axis[-1] * dy #pt that layer starts at #Approximate by cutting off at float pt values nx = round(nx) x0 = round(x0) xf = x0 + nx #pt that layer ends at ## xaxis = linspace(axis[i],axis[i+1],nx) xaxis = linspace(x0, xf, nx) ##a_t = trapz(gm[:,m],xaxis) if nModes == 1: a_s = simps(gm[x0:xf], xaxis) #use simpson's rule to approx integral elif nModes > 1: a_s = simps(gm[x0:xf, m], xaxis) ##A[i,m] = a_t #Trapezoidal & Simpson's rule agree A_s[i, m] = a_s A_tot = zeros((nLayers), 'complex') #total absorption in a layer across all GMs for i in range(0, nLayers): a_tot = A_s[i, :].sum() A_tot[i] = a_tot #normalize layer absorption to 1 norm = cumsum(A_tot)[nLayers - 1] A_tot = A_tot / norm #gives % absorption for GMs in each layer ## A_gm = A_s #each column reps % of GM absorbed in a layer ## for m in range(0,nModes): ## norm = cumsum(A_gm[:,m])[nLayers - 1] ## A_gm[:,m] = A_gm[:,m] / norm #A_tot returns absorption of layers in the order incident medium -> substrate (top -> bottom) return real(A_tot) #neglect very small imaginary part
def EME(wg, ib, ev, em, eps, callCode): cc = conjugate(em) cc = transpose(cc) c = dot(cc, ib) #coefficients for expansion f_all = dot(em, c) #expansion of incident E field in terms of all modes ##sigma_c = cumsum(sqrt(conjugate(c)*c)) sigma_c = cumsum(c) #show the expansion in terms of all calculated modes ##plot(wg, f_all) ##show() nx = len(eps) ep_substrate = eps[0] ep_cover = eps[nx - 1] ep_thresh = amax([ep_substrate, ep_cover ]) #guided modes must be greater than this threshold #find eigenvectors that correspond to guided mode eigenvalues gm = em[:, ev > ep_thresh] ee = ev[ev > ep_thresh] #Normalize to 1 for i in range(0, gm.shape[1]): norm = amax(gm[:, i]) gm[:, i] /= norm #calculate coefficients (c) for decomposition in terms of guided modes cc = conjugate(gm) cc = transpose(cc) c = dot(cc, ib) #gives percentage of coupling into each of the gm c_frac = real((conjugate(c) * c) / (conjugate( (sigma_c[-1])) * sigma_c[-1])) f_gm = dot(gm, c) #expansion in terms of only guided modes norm = amax(f_gm) f_gm /= norm #show the expansion and/or the guided modes IFF any exist ##plot(wg, f_gm, wg, f_all) ##show() if gm.shape[0] > 0 and callCode == "plotgm": gmplot = plot(real(gm), wg) xlabel('Normalized field distribution') ylabel('Structure thickness') title('Guided modes') ## fgmplot = plot(ib,wg,f_gm,wg) ## ylabel('Structure thickness') ## xlabel('Incident field distribution') ## title('Guided Mode Expansion') #Normalize all vectors to avoid overflow error norm = amax(f_all) f_all /= norm norm = amax(ib) ib /= norm norm = amax(f_gm) f_gm /= norm #Overlap between all modes and incident electric field ##R_all = real(dot(conjugate(dot(conjugate(f_all),ib)),dot(conjugate(f_all),ib)) / \ ## ( dot(conjugate(f_all),f_all) * dot(conjugate(ib),ib) )) R_all = real(dot(conjugate(dot(conjugate(f_all),ib)),dot(conjugate(f_all),ib)) / \ ( dot(conjugate(f_all),f_all) * dot(conjugate(ib),ib) )) R = real(dot(conjugate(dot(conjugate(f_gm),ib)),dot(conjugate(f_gm),ib)) / \ ( dot(conjugate(f_gm),f_gm) * dot(conjugate(ib),ib) )) #Is this necesary for complex guided modes? gm = sqrt(conjugate(gm) * gm) # 1 - R represents losses if callCode == "doopt": return R, gm if callCode == "plotgm" or callCode == "slabwg": return gm, ee, c_frac if callCode == "doeme": return gm, ee, c, c_frac, R
def plane_wave(wid, nx, nArray, k, theta, I, pLayer): lambda_0 = (2 * pi) / k #wavelength of incoming light nLayers = len(wid) d = cumsum(wid) ns = nArray[0] #substrate index of refraction n0 = nArray[nLayers - 1] #incident medium index (air) #Calculate terms needed for TMM k_x = zeros((nLayers), 'complex') cos_theta = zeros((nLayers), 'complex') phi = zeros((nLayers), 'complex') D = zeros((nLayers, 4), 'complex') P = zeros((nLayers, 4), 'complex') #Total E field over all betas E_tot = zeros((nx, len(theta)), 'complex') #A, B coeffs for electric field at each layer AB = zeros((nLayers, 4), 'complex') AB[0, 0] = 1 #A_0 for TE AB[0, 1] = 0 #B_0 AB[0, 2] = 0 #For TM AB[0, 3] = 1 #Calc E at every beta value, integrate over intensities of diffraction angles for nn in range(0, len(theta)): #Calculate transfer matrix for TE & TM waves for i in range(0, 2): for l in range(0, nLayers): #Beta is 0 until light hits perturbed layer (zero refraction, no z propagation) #perturbation -> non-zero beta #propagation constant, wavenumber in layer, cosine of ray angle #num pts in the layer, phase beta = cmath.sqrt(k**2 * conjugate(nArray[l])*nArray[l] - \ k**2 * conjugate(nArray[l])*nArray[l]*cos(theta[nn])) k_x[l] = cmath.sqrt(k**2 * conjugate(nArray[l]) * nArray[l] - beta**2) cos_theta[l] = real(k_x[l] / (k * nArray[l])) nx_l = (wid[l] / d[nLayers - 1]) * nx phi[l] = k_x[l] * nx_l #Fill in dynamical matrix for TE waves if i == 0: D[l, 0] = 1 D[l, 1] = 1 D[l, 2] = nArray[l] * cos_theta[l] D[l, 3] = -nArray[l] * cos_theta[l] #Dynamical matrix for TM waves if i == 1: D[l, 0] = cos_theta[l] D[l, 1] = cos_theta[l] D[l, 2] = nArray[l] D[l, 3] = -nArray[l] #Fill in propagation matrix P[l, 0] = exp(1j * phi[l]) P[l, 1] = 0 P[l, 2] = 0 P[l, 3] = exp(-1j * phi[l]) cos_s = real(cos_theta[0]) #for use in transmittance calculation cos_0 = real(cos_theta[nLayers - 1]) transfer_mat = zeros((2, 2), 'complex') D_l = zeros((2, 2), 'complex') P_l = zeros((2, 2), 'complex') for l in range(1, nLayers - 2): D_l[0, 0] = D[l, 0] D_l[0, 1] = D[l, 1] D_l[1, 0] = D[l, 2] D_l[1, 1] = D[l, 3] P_l[0, 0] = P[l, 0] P_l[0, 1] = P[l, 1] P_l[1, 0] = P[l, 2] P_l[1, 1] = P[l, 3] if l == 1: transfer_mat = D_l.dot(P_l).dot(inv(D_l)) if i == 0: M_TE = transfer_mat AB[l, 0:2] = dot(M_TE, AB[l - 1, 0:2]) #A_m & B_m for TE if i == 1: M_TM = transfer_mat AB[l, 2:4] = dot(M_TM, AB[l - 1, 2:4]) #A_m & B_m for TM if l > 1: A = D_l.dot(P_l).dot(inv(D_l)) transfer_mat = dot(transfer_mat, A) if i == 0: M_TE = transfer_mat AB[l, 0:2] = dot(M_TE, AB[l - 1, 0:2]) #A_m & B_m for TE if i == 1: M_TM = transfer_mat AB[l, 2:4] = dot(M_TM, AB[l - 1, 2:4]) #A_m & B_m for TM #Must apply TMM at this step to get coeffs for each layer #incident medium D_l[0, 0] = D[nLayers - 1, 0] D_l[0, 1] = D[nLayers - 1, 1] D_l[1, 0] = D[nLayers - 1, 2] D_l[1, 1] = D[nLayers - 1, 3] transfer_mat = dot(inv(D_l), transfer_mat) #substrate D_l[0, 0] = D[0, 0] D_l[0, 1] = D[0, 1] D_l[1, 0] = D[0, 2] D_l[1, 1] = D[0, 3] #completed transfer matrix transfer_mat = dot(transfer_mat, D_l) #Store if i == 0: M_TE = transfer_mat AB[-1, 0:2] = dot(M_TE, AB[nLayers - 3, 0:2]) if i == 1: M_TM = transfer_mat AB[-1, 2:4] = dot(M_TM, AB[nLayers - 3, 2:4]) ##for M in (M_TE,M_TM): ##R = real((conjugate(M[1,0])*M[1,0]) / (conjugate(M[0,0])*M[0,0])) #Reflectance ##if R > 1: ##R = 1.0 #correct for slight numerical error ##if cos_0 > 0: ##T = real((ns*cos_s)/(n0*cos_0) * (1/(conjugate(M[0,0])*M[0,0]))) #Transmittance ##print("T", T, "R", R, M) #Set up incident plane wave electric field d = cumsum(wid) #thickness of structure E_m = zeros((), 'complex') #Get A and B constant coeffs for each layer for m in range(0, nLayers): ## #Initial conditions ## if m == 0: ## AB[0,0] = 1 #A_0 for TE ## AB[0,1] = 0 #B_0 ## AB[0,2] = 0 #For TM ## AB[0,3] = 1 ## nx_m = ((d[0]) / d[nLayers-1]) * nx ## ## elif m > 0: ## AB[m,0:2] = dot(M_TE,AB[m-1,0:2]) #A_m & B_m for TE ## AB[m,2:4] = dot(M_TM,AB[m-1,2:4]) #A_m & B_m for TM ## AB[m,0] = dot(M_TE,AB[m-1,0])[0,0] #A_m ## AB[m,1] = dot(M_TE,AB[m-1,1])[1,0] #B_m ## AB[m,2] = dot(M_TM,AB[m-1,2])[0,0] ## AB[m,3] = dot(M_TM,AB[m-1,3])[1,0] ## nx_m = ((d[nLayers-m]-d[nLayers-m-1])/d[nLayers-1]) * nx #num pts in layer #Get number of points in each layer if m == 0: nx_m = ((d[0]) / d[nLayers - 1]) * nx elif m > 0: nx_m = ((d[nLayers - m] - d[nLayers - m - 1]) / d[nLayers - 1]) * nx #Deal with float nx_m nx_m = round(nx_m) x_m = linspace(0, wid[m], nx_m) #x space in incident layer E_m = AB[m, 0] * exp(-1j * k_x[m] * x_m) + AB[m, 1] * exp( 1j * k_x[m] * x_m) if m == 0: E_struct = E_m #Incident electric field @ E(x,z=0) elif m > 0: E_struct = append(E_struct, E_m) #Trim or pad edges if len(real(E_struct)) > nx: overflow = len(E_struct) - nx for i in range(0, overflow): E_struct = delete(E_struct, i) if len(real(E_struct)) < nx: while len(E_struct) < nx: E_struct = insert(E_struct, -1, E_struct[len(E_struct) - 1]) #E_struct is unperturbed solution, now include diffraction angles (non-zero beta) #due to periodic perturbation E_tot[:, nn] = (E_struct ) #throw out time-dependent phase (imaginary part) #E_struct is weighted average of E @ each beta from diffraction orders #weighted by intensity of diffraction order nn = 0 E_struct = zeros((nx), 'complex') for nn in range(0, len(theta)): E_struct += I[nn] * E_tot[:, nn] return E_struct, M_TE, M_TM, AB
def TM0_calc(wid, nx, nArray, k): lambda_0 = (2 * pi) / k #wavelength of incoming light nLayers = len(wid) d = cumsum(wid) beta_tm0 = 0 AB = zeros((nLayers, 2), 'complex') #Coeffs for TM field ns = nArray[0] #substrate index of refraction n0 = nArray[nLayers - 1] #incident medium index (air) #Storage needed for TMM k_x = zeros((nLayers), 'complex') cos_theta = zeros((nLayers), 'complex') phi = zeros((nLayers), 'complex') D = zeros((nLayers, 4), 'complex') P = zeros((nLayers, 4), 'complex') #Window for effective epsilons for guided modes epseff_0 = real(conjugate(n0) * n0) epseff_s = real(conjugate(ns) * ns) dEff = .01 for eps_eff in arange(epseff_0 + dEff, epseff_s - dEff, (epseff_s - epseff_0 - 2 * dEff) / 100000): for l in range(0, nLayers): #Terms for TMM beta = k * sqrt(eps_eff) k_x[l] = cmath.sqrt(k**2 * conjugate(nArray[l]) * nArray[l] - beta**2) cos_theta[l] = k_x[l] / (k * nArray[l]) nx_l = (wid[l] / d[nLayers - 1]) * nx phi[l] = k_x[l] * nx_l #Dynamical matrix for TM waves D[l, 0] = cos_theta[l] D[l, 1] = cos_theta[l] D[l, 2] = nArray[l] D[l, 3] = -nArray[l] #Fill in propagation matrix P[l, 0] = exp(1j * phi[l]) P[l, 1] = 0 P[l, 2] = 0 P[l, 3] = exp(-1j * phi[l]) transfer_mat = zeros((2, 2), 'complex') D_l = zeros((2, 2), 'complex') P_l = zeros((2, 2), 'complex') for l in range(1, nLayers - 2): D_l[0, 0] = D[l, 0] D_l[0, 1] = D[l, 1] D_l[1, 0] = D[l, 2] D_l[1, 1] = D[l, 3] P_l[0, 0] = P[l, 0] P_l[0, 1] = P[l, 1] P_l[1, 0] = P[l, 2] P_l[1, 1] = P[l, 3] if l == 1: transfer_mat = D_l.dot(P_l).dot(inv(D_l)) if l > 1: A = D_l.dot(P_l).dot(inv(D_l)) transfer_mat = dot(transfer_mat, A) tm = transfer_mat ## D_l[0,0] = D[nLayers-1,0] ## D_l[0,1] = D[nLayers-1,1] ## D_l[1,0] = D[nLayers-1,2] ## D_l[1,1] = D[nLayers-1,3] ## ## ## tm = dot(inv(D_l),tm) ## #substrate ## D_l[0,0] = D[0,0] ## D_l[0,1] = D[0,1] ## D_l[1,0] = D[0,2] ## D_l[1,1] = D[0,3] ## ## #completed transfer matrix ## tm = dot(tm,D_l) AB[0, 0] = 0 AB[0, 1] = 1 ##AB[l,0] = dot(tm,AB[l-1,0])[0,0] ##AB[l,1] = dot(tm,AB[l-1,1])[1,0] AB[l, :] = dot(tm, AB[l - 1, :]) #incident medium D_l[0, 0] = D[nLayers - 1, 0] D_l[0, 1] = D[nLayers - 1, 1] D_l[1, 0] = D[nLayers - 1, 2] D_l[1, 1] = D[nLayers - 1, 3] transfer_mat = dot(inv(D_l), transfer_mat) #substrate D_l[0, 0] = D[0, 0] D_l[0, 1] = D[0, 1] D_l[1, 0] = D[0, 2] D_l[1, 1] = D[0, 3] #completed transfer matrix transfer_mat = dot(transfer_mat, D_l) M_TM = transfer_mat AB[nLayers - 1, :] = dot(M_TM, AB[nLayers - 2, :]) ##AB[nLayers-1,0] = dot(M_TM, AB[nLayers-2,0])[0,0] ##AB[nLayers-1,1] = dot(M_TM, AB[nLayers-2,0])[1,0] #Mode condition for TM modes is that M[0,0] == 0 #Give a little wiggle room for computational error if abs(real(M_TM[0, 0])) < .001: M_TM[0, 0] = 0 #correct computational error beta_tm0 = beta #Calc TM field for this beta E_m = zeros((), 'complex') #Get A and B constant coeffs for each layer for m in range(0, nLayers): #Initial conditions if m == 0: AB[0, 0] = 0 #A_0 for TM confined mode that vanish at infinity AB[0, 1] = 1 #B_0 nx_m = ((d[0]) / d[nLayers - 1]) * nx elif m > 0: ##AB[m,:] = dot(M_TM,AB[m-1,:]) #A_m & B_m nx_m = ((d[nLayers - m] - d[nLayers - m - 1]) / d[nLayers - 1]) * nx #num pts in layer #Deal with float nx_m nx_m = round(nx_m) x_m = linspace(0, wid[m], nx_m) #x space in incident layer E_m = AB[m, 0] * exp(-1j * k_x[m] * x_m) + AB[m, 1] * exp( 1j * k_x[m] * x_m) if m == 0: E_struct = E_m #Incident electric field @ E(x,z=0) elif m > 0: E_struct = append(E_struct, E_m) #Trim or pad edges if len(real(E_struct)) > nx: overflow = len(E_struct) - nx for i in range(0, overflow): E_struct = delete(E_struct, i) if len(real(E_struct)) < nx: while len(E_struct) < nx: E_struct = insert(E_struct, -1, E_struct[len(E_struct) - 1]) norm = amax(E_struct) #normalize to 1 TM0 = E_struct / norm return beta_tm0, TM0 break #No mode found if beta_tm0 == 0: return 0, 0
def calc_Axz(nArray, p_layer, gm, ee, k, del_e, T, z, c): nModes = len(ee) betas = zeros((nModes), 'complex') for i in range(0, nModes): betas[i] = real(k * cmath.sqrt( ee[i])) #propagation constants - discard 0 imaginary part if p_layer - 2 > 0: amp = real(nArray[p_layer - 2])**2 #magnitude of dielectric perturbation elif p_layer - 2 < 0: amp = 1.0 c0 = 3 * 10**8 #speed of light in vacuum omega = k * c0 #freq of incoming light #need to do nCr (nModes Choose 2) number of calculations? #No - calculate A's in pairs A = zeros((len(z), nModes), 'complex') #hold all A(z) A_int = zeros((nModes), 'complex') #hold each |A(z)|**2 for m in range(0, nModes - 1): n = m + 1 gm_m = gm[:, m] gm_n = gm[:, n] c_m = c[ m] #unperturbed coupling coeffs to be used as initial conditions c_n = c[n] gm_m = conjugate(gm_m) gm_m = transpose(gm_m) ovlap_mn = real( dot(gm_m, gm_n) ) #overlap integral between modes - neglect small imaginary part del_beta = real(betas[m] - betas[n] - (2 * pi / T)) #mode matching condition kappa_mn = (omega / 4) * amp * ovlap_mn #represents coupling between modes #Soln for Am, An diff eqs comes from Mathematica #Need two coeffs, c1, c2, from initial conditions alpha_1 = (1j / (2 * kappa_mn)) * ( 1j * del_beta - cmath.sqrt(-4 * kappa_mn**2 - del_beta**2)) alpha_2 = (1j / (2 * kappa_mn)) * ( 1j * del_beta + cmath.sqrt(-4 * kappa_mn**2 - del_beta**2)) coeffMat = array(([1, 1], [alpha_1, alpha_2]), 'complex') solnMat = array(([c_m, c_n]), 'complex') #Solve system of linear eqs for constant coeffs for A_m(z), A_n(z) new_c = solve(coeffMat, solnMat) c1 = (new_c[0]) #Real or complex? c2 = (new_c[1]) A_m = array((len(z)), 'complex') A_n = array((len(z)), 'complex') #These expressions come from soln to {dAm/dz ~ An ; dAn/dz ~ Am} A_m = c1*exp( (-1/2)*z*(cmath.sqrt(-4*kappa_mn**2 - del_beta**2) - 1j*del_beta)) \ + c2 * exp( (1/2)*z*(cmath.sqrt(-4*kappa_mn**2 - del_beta**2) + 1j*del_beta)) A_n = (1j / (2*kappa_mn)) * ( c1*(1j*del_beta - cmath.sqrt(-4*kappa_mn**2 - del_beta**2)) \ * exp( (-1/2)*z*(cmath.sqrt(-4*kappa_mn**2 - del_beta**2) + 1j*del_beta) ) \ + c2*(cmath.sqrt(-4*kappa_mn**2 - del_beta**2) + 1j*del_beta) \ * exp((1/2)*z*(cmath.sqrt(-4*kappa_mn**2 - del_beta**2)-1j*del_beta)) ) A_m = (betas[m] / abs(betas[m])) * A_m #sign indicates propagation direction A_n = (betas[n] / abs(betas[n])) * A_n ccm = transpose(A_m) ccm = conjugate(ccm) ccn = transpose(A_n) ccn = conjugate(ccn) ##A[:,m] = real(A_m) #Am(z) values are complex... ##A[:,n] = real(A_n) A_int[m] = real(dot(ccm, A_m)) # |A(z)|**2 A_int[n] = real(dot(ccn, A_n)) ##print(real(A_int)) norm = cumsum(real(A_int))[nModes - 1] A_int = real(A_int / norm) #normalize coeffs to sum to 1 return betas, A_int
def calc_cz(wg, eps, ib, k, z_len, nz): #unperturbed eps eps = eps[:, 1] ev, em = calc_modes(wg, k, eps) num = len(ev) pos_ev = zeros((num), 'complex') count = 0 #pick out only positive effective permittivities, i.e. forward propagating modes for m in range(0, num): if ev[m] > 0: pos_ev[count] = ev[m] count += 1 pos_ev = trim_zeros(pos_ev) #forward propagating modes pos_m = em[:, ev > 0] #positive, real-valued propagation constants betas = k * sqrt(pos_ev) pos_m = conjugate(pos_m) pos_m = transpose(pos_m) z = linspace(0, z_len, nz) num = len(pos_ev) c = dot(pos_m, ib) cz = zeros((num, nz)) for m in range(0, num): cz[m, :] = real(c[m] * exp(1j * betas[m] * z)) pos_m = conjugate(pos_m) pos_m = transpose(pos_m) #pick out gm from pos_m nx = len(eps) gm_markers = zeros((nx)) ep_substrate = eps[0] ep_cover = eps[nx - 1] ep_thresh = amax([ep_substrate, ep_cover ]) #guided modes must be greater than this threshold #find eigenvectors that correspond to guided mode eigenvalues count = 0 for m in range(0, num): if pos_ev[m] > ep_thresh: gm_markers[count] = m count += 1 gm_markers = trim_zeros(gm_markers) gm_markers = gm_markers.astype(int) #A(x,z) coupling coeffs for guided modes gm_xz_coeffs = cz[gm_markers, :] gm_xz_coeffs = transpose(gm_xz_coeffs) ib_z = dot(pos_m, cz) X, Z = meshgrid(z, wg) #visualize propagation of power through waveguide contour(X, Z, abs(ib_z)**2, 20) show()
def build_patches(data): filters = [] for r in range(0, num_patches): print "training patch:" + str(r) images = [] targetImages = [] # load positive examples i = 0 for filename, values in data.iteritems(): im = Image.open(join(data_folder, "cropped/", filename), "r") # convert image to grayscale im = im.convert("L") #generate random offset to target to generate better filters xof = random.randint(-3, 3) yof = random.randint(-3, 3) if not numpy.isnan(values[r][0]): # TODO : check that there is not missing data: points = values[r] + (numpy.array(im.size) / 2) points = numpy.around(points) points = points.astype(numpy.uint8) left = points[0] - (patch_size / 2) - xof top = points[1] - (patch_size / 2) - yof nux = points[0] - left nuy = points[1] - top p_crop = im.crop( (left, top, left + patch_size, top + patch_size)) Image.fromarray( numpy.asarray(p_crop).astype('int')).convert("L").save( join(data_folder, "pcropped/", "mosse" + filename + ".bmp")) images.append(numpy.array(p_crop)) # create target images targetImage = array([0.] * (patch_size * patch_size)).reshape( (patch_size, patch_size)) for xr in range(0, patch_size): for yr in range(0, patch_size): targetImage[yr, xr] = math.exp( -(((xr - nux) * (xr - nux)) + ((yr - nuy) * (yr - nuy))) / (0.5 * 0.5)) #Image.fromarray((targetImage*255).astype('int')).convert("L").save("test_target.bmp") targetImages.append(targetImage) if i % 1000 == 0: print i i += 1 # preprocess images = [im.astype(numpy.uint16) for im in images] images = [numpy.log(im + 1) for im in images] # normalize images = [im - mean(im) for im in images] images = [im / norm(im) for im in images] # cosine windows images = [cosine_window(im) for im in images] # fft of images images = [fft.fft2(im) for im in images] targetImages = [fft.fft2(ti) for ti in targetImages] print "calculating filter" # calculate filter top = numpy.zeros((patch_size, patch_size)) top = top.astype('complex') bottom = numpy.zeros((patch_size, patch_size)) bottom = bottom.astype('complex') for ir in range(len(images)): if numpy.any(numpy.isnan(targetImages[ir])) or numpy.any( numpy.isnan(conjugate(images[ir]))) or numpy.any( numpy.isnan(images[ir])): import pdb pdb.set_trace() top += targetImages[ir] * conjugate(images[ir]) bottom += images[ir] * conjugate(images[ir]) filter = top / bottom # optionally store filters as normalized images, for validation filres = fft.ifft2(filter) fil = filres.real minf = numpy.min(fil) fil -= minf maxf = numpy.max(fil) fil *= (255 / maxf) fil = numpy.floor(fil) Image.fromarray(fil.astype('int')).convert("L").save( join(data_folder, "svmImages/", "svm" + str(r) + ".bmp")) # #fi = open("./svmFilters/filter"+str(r)+".pickle", "w") #pickle.dump(clf.coef_, fi) #fi.close() filter_real = map(lambda x: x.real, filter.flatten().tolist()) filter_imag = map(lambda x: x.imag, filter.flatten().tolist()) filter = [filter_real, filter_imag] filters.append(filter) # output for standard model: #filteroutput = [filters[f][r] for r in range(0, patch_size*patch_size) for f in range(0, num_patches)] filteroutput = filters # output result as dictionary with entries patchModel = {} patchModel['patchSize'] = [patch_size, patch_size] patchModel['weights'] = filteroutput patchModel['numPatches'] = num_patches patchModel['patchType'] = 'MOSSE' return patchModel