def plotNewtonStats(movelens, its, functionValues, max_vals, max_names, difs, numOfIts): i = [] for s in range(its.shape[0]): if not functionValues[s] == 0: i.append(int(its[s])) #print("movelens:") #print(movelens) plt.plot(i, np.split(movelens, [len(i), movelens.shape[0] - len(i)])[0]) plt.title("movelens") plt.show() plt.plot( i, np.split(functionValues, [len(i), movelens.shape[0] - len(i)])[0]) plt.title("funtion values") plt.show() plt.plot(i, np.split(max_vals, [len(i), movelens.shape[0] - len(i)])[0]) plt.title("maxvals") plt.show() #print("names:") #print(max_names) #print("difs:") #print(difs) plt.plot(i, np.split(difs, [len(i), movelens.shape[0] - len(i)])[0]) plt.title("difs") plt.show()
def spindens(self,lrgm_out): from scipy import split,pi,complex128,zeros,repeat number_of_lattice_points = self.canvas.shape[0]*self.canvas.shape[1] number_of_nodes = len(self.tuple_canvas_coordinates) if number_of_nodes == number_of_lattice_points: if self.order == 'even': Gup, Gdown = split(lrgm_out.reshape(self.canvas.shape[0],self.canvas.shape[1]*2),2,axis=1) if self.order == 'odd': Gup, Gdown = split(lrgm_out.reshape(-1,2),2,axis=1) Gup, Gdown = Gup.reshape(self.canvas.shape), Gdown.reshape(self.canvas.shape) else: print "Please specify order of Nodes, i.e 'even' for allspinup-allspindown per sclice or odd for spinup-spindown-spinup-..." Sz = self.p.upar.hbar/(4*pi*1j*self.p.upar.a**2)*(Gup-Gdown) elif number_of_nodes < number_of_lattice_points: Sz= zeros(self.canvas.shape,dtype=complex128) print 'calculating spin density for sparse structure' lrgm_out = self.p.hbar/(4*pi*1j*self.p.upar.a**2)*lrgm_out expanded_array_of_coords = repeat(self.tuple_canvas_coordinates,2,axis=0) for index,node_name in enumerate(self.nodelist): if node_name % 2 == 0: sign = 1 else: sign = -1 Sz[tuple(expanded_array_of_coords[node_name])] += sign * lrgm_out[index] else: print 'Number of nodes larger than canvas, something is wrong!' print 'max Spin Split: ', Sz.real.max()-Sz.real.min() #Realteil scheint wahrscheinlicher, imag oszilliert wie bloed return Sz.real
def splitTargetChunk(self): ## create mosaic data-structure + list of 'pointers' to the tiles in ## this structure self.mosaic = scipy.zeros((self.sliceDim[1]*self.Tiles[1]/self.NPlacers, self.sliceDim[0]*self.Tiles[0], 3), dtype='i') VertSplitFinalArrs = scipy.split(self.mosaic, self.Tiles[0], axis=1) for VertSplitFinalArr in VertSplitFinalArrs: SplitFinalArrs = scipy.split(VertSplitFinalArr, self.Tiles[1]/self.NPlacers, axis=0) for SplitFinalArr in SplitFinalArrs: self.mosaicTiles.append(SplitFinalArr)
def getTargetChunk(self): #print "P{} > listening".format(self.rank) NodeArr = self.comm.recv(source=0, tag=1, status=self.status) #print "P{} < listening".format(self.rank) #%% Divide the NodeArr into tiles #print "P{} > dividing".format(self.rank) VertSplitArrs = scipy.split(NodeArr, self.Tiles[0], axis=1) for VertSplitArr in VertSplitArrs: SplitArrs = scipy.split(VertSplitArr,self.Tiles[1]/self.NPlacers, axis=0) for splitArr in SplitArrs: self.targetPieces.append(splitArr)
def detect_signals(): vector, label = weeklydataset_sg_ndata( "/media/4AC0AB31C0AB21E5/Documents and Settings/Claudio/Documenti/Thesis/Workloads/MSClaudio/ews/access_log-20110805.csv", [], ) x, target = aggregatebymins_sg_ndata(vector[1]) starttime = time.time() y = array(target) t = array(x) thr = max(y) * 2 / 3 print thr I = pylab.find(y > thr) # print I # pylab.plot(t,y, 'b',label='signal') # pylab.plot(t[I], y[I],'ro',label='detections') # pylab.plot([0, t[len(t)-1]], [thr,thr], 'g--') J = pylab.find(diff(I) > 1) argpeak = [] targetpeak = [] for K in split(I, J + 1): ytag = y[K] peak = pylab.find(ytag == max(ytag)) # pylab.plot(peak+K[0],ytag[peak],'sg',ms=7) argpeak.append(peak + K[0]) targetpeak.append(ytag[peak]) eta = time.time() - starttime print "time elapsed %f" % eta return list(itertools.chain(*argpeak)), list(itertools.chain(*targetpeak))
def get_HRRR_data(filename): grbs = pygrib.open(filename) msgs = [str(grb) for grb in grbs] string = 'Geopotential Height:gpm' temp = [ msg for msg in msgs if msg.find(string) > -1 and msg.find('isobaricInhPa') > -1 ] pressure_levels_Pa = s.array([int(s.split(' ')[3]) for s in temp]) geo_pot_height_grbs = grbs.select(name = 'Geopotential Height', \ typeOfLevel='isobaricInhPa', level=lambda l: l > 0) temperature_grbs = grbs.select(name = 'Temperature', \ typeOfLevel='isobaricInhPa', level=lambda l: l > 0) rh_grbs = grbs.select(name = 'Relative humidity', \ typeOfLevel='isobaricInhPa', level=lambda l: l > 0) lat, lon = geo_pot_height_grbs[0].latlons() geo_pot_height = s.stack([grb.values for grb in geo_pot_height_grbs]) temperature = s.stack([grb.values for grb in temperature_grbs]) rh = s.stack([grb.values for grb in rh_grbs]) return lat, lon, geo_pot_height, temperature, rh, pressure_levels_Pa
def crossvalidation(self, fold, v, k): error = 0 data = Data(k, 0, 0) data.importDataFromMat() data.normalize() n = data.train_cat.shape[1] all_indices = sp.arange(n) data.shuffleData() sq = SquaredErrorLinearClassifier(v,k) dataset_indices = sp.split(all_indices, fold) for i in range(fold): set_without_D_i_indices = sp.concatenate(dataset_indices[0:i]+dataset_indices[i+1:fold]) #print "-"*30+"train"+"-"*30 sq.train(data.train_left[:,set_without_D_i_indices], data.train_right[:,set_without_D_i_indices], data.train_cat[:,set_without_D_i_indices]) #print "-"*30+"classify"+"-"*30 results, classes = sq.classify(data.train_left[:,dataset_indices[i]], data.train_right[:,dataset_indices[i]]) #print "-"*30+"error"+"-"*30 err, _ = sq.error(results, data.train_cat[:,dataset_indices[i]].T) error += fold/(n*1.0)*err error = error / fold with open("results/crossvalidation.txt", "a") as myfile: toWrite = "v="+str(v)+" error="+str(error) myfile.write(toWrite)
def Merge_pores(network, pores, Neighbor,Cordinate, trimradius, labels=['merged']): # Assert that `pores` is list of lists try: len(pores[0]) except (TypeError, IndexError): pores = [pores] N = len(pores) NBs, XYZs = [], [] for Ps in pores: NBs.append(Neighbor) XYZs.append(Cordinate) op.topotools.extend(network, pore_coords=XYZs, labels=labels) Pnew = network.Ps[-N::] pores_set = [set(items) for items in pores] NBs_set = [set(items) for items in NBs] ps1, ps2 = [], [] from itertools import combinations for i, j in combinations(range(N), 2): if not NBs_set[i].isdisjoint(pores_set[j]): ps1.append([network.Ps[-N+i]]) ps2.append([network.Ps[-N+j]]) # Add (possible) connections between the new pores op.topotools.connect_pores(network, pores1=ps1, pores2=ps2, labels=labels) # Add connections between the new pores and the rest of the network op.topotools.connect_pores(network, pores2=sp.split(Pnew, N), pores1=NBs, labels=labels) # Trim merged pores from the network op.topotools.trim(network=network, pores=sp.concatenate(pores)) Ps = network.find_nearby_pores(pores=network.Ps[-len(pores)::], r=trimradius, flatten=True) op.topotools.trim(network=network, pores=Ps)
def chunk(A, n_chunks=10): """ split A into n chunks, ignore overhaning samples """ chunk_size = sp.floor(A.shape[0] / n_chunks) drop = int(A.shape[0] % chunk_size) if drop != 0: A = A[:-drop] A_chunks = sp.split(A, n_chunks) return A_chunks
def weights(self, new_weights): sections = shapesToSections(self.shapes) syn_wo, inter_ws, syn_wi, wi, wo = split(new_weights.copy(), sections) shapes = self.shapes self.syn_wo = syn_wo.reshape(shapes['syn_wo']) self.inter_ws = inter_ws self.syn_wi = syn_wi.reshape(shapes['syn_wi']) self.wi = wi.reshape(shapes['wi']) self.wo = wo.reshape(shapes['wo'])
def animate(frame): updated = [Sun.point, Sun.patch] #sun doesnt move for planet in LargeList[1:]: #large bodies after sun planet.pos = planet.orbitPos(times[frame]) updated.extend(planet.update()) Demo2.pos, Demo2.vel = sp.split(path.sol(times[frame]), 2)# x, y, v_x, v_y updated.extend(Demo2.update()) focus(ax2, Demo2) return tuple(updated)
def fastKineticsCrop(self, rawArray, n): """in fast kinetic picture we have one large array and then need to crop it into n equal arrays vertically. Uses scipy split function which returns a python list of the arrays returned list has the order of first picture taken --> last picture taken. i.e. [atomsImage,lightImage]""" try: return scipy.split(rawArray, n, axis=0) except ValueError as e: logger.error( "fastKinetics crop couldn't equally divide the image into n=%s. This will fail. You must crop the image to a divisble size first." % n) raise e
def edens(self, lrgm_out): from scipy import split, pi, asarray, sum # TODO implement sparse and noncoliear structure mapping number_of_lattice_points = self.canvas.shape[0] * self.canvas.shape[1] number_of_nodes = len(self.tuple_canvas_coordinates) if number_of_nodes == number_of_lattice_points: print 'Using stride bases reshape, Attention !!! Probably not what you want!' if self.p.multi == 1: edensity = lrgm_out.reshape(asarray(self.canvas.shape) + [0, 0]) * 2 / (2 * pi * self.p.upar.a** 2) #times 2 for spin if self.p.multi == 2: if self.order == 'even': Gup, Gdown = split(lrgm_out.reshape(self.canvas.shape[0], self.canvas.shape[1] * 2), 2, axis=1) edensity = 1 / (2 * pi * self.upar.p.a**2) * (Gup + Gdown) if self.order == 'odd': edensity = 1 / (2 * pi * self.p.upar.a**2) * sum( lrgm_out.reshape(-1, 2), axis=1).reshape(self.canvas.shape) else: print "Please specify order of Nodes, i.e 'even' for allspinup-allspindown per sclice or odd for spinup-spindown-spinup-..." elif number_of_nodes < number_of_lattice_points: from scipy import zeros, complex128, repeat edensity_spin_up = zeros(self.canvas.shape, dtype=complex128) edensity_spin_down = zeros(self.canvas.shape, dtype=complex128) if self.p.multi == 1: print 'calculating electron density without SO' lrgm_out = lrgm_out * 2 / (2 * pi * self.p.upar.a**2) for index, node_name in enumerate(self.nodelist): edensity_spin_up[ self.tuple_canvas_coordinates[node_name]] = lrgm_out[index] if self.p.multi == 2: print 'calculating electron density with SO' lrgm_out = lrgm_out * 1 / (2 * pi * self.p.upar.a**2) expanded_array_of_coords = repeat(self.tuple_canvas_coordinates, 2, axis=0) for index, node_name in enumerate(self.nodelist): if node_name % 2 == 0: edensity_spin_up[tuple( expanded_array_of_coords[node_name])] = lrgm_out[index] else: edensity_spin_down[tuple( expanded_array_of_coords[node_name])] = lrgm_out[index] edensity = edensity_spin_up + edensity_spin_down edensity = (edensity.real, edensity_spin_up.real, edensity_spin_down.real) else: print 'Number of nodes larger than canvas, something is wrong!' # print 'max Electron Density: ', edensity.max() return edensity
def Grafica(x, y, vx, vy, Np): x1 = sp.zeros(Np // 2) x2 = sp.zeros(Np // 2) vx1 = sp.zeros(Np // 2) vx2 = sp.zeros(Np // 2) y1 = sp.zeros(Np // 2) y2 = sp.zeros(Np // 2) vy1 = sp.zeros(Np // 2) vy2 = sp.zeros(Np // 2) x1, x2 = sp.split(x, 2) vx1, vx2 = sp.split(vx, 2) [y1, y2] = sp.split(y, 2) [vy1, vy2] = sp.split(vy, 2) plt.figure('Malla') plt.plot(x, y, '.', markersize=1) plt.figure('Velocidades x') plt.plot(x1, vx1, '.', markersize=1, c='m') plt.plot(x2, vx2, '.', markersize=1, c='c') plt.figure('Velocidades y') plt.plot(y1, vy1, '.', markersize=1, c='m') plt.plot(y2, vy2, '.', markersize=1, c='c')
def spindens(self, lrgm_out): from scipy import split, pi, complex128, zeros, repeat number_of_lattice_points = self.canvas.shape[0] * self.canvas.shape[1] number_of_nodes = len(self.tuple_canvas_coordinates) if number_of_nodes == number_of_lattice_points: if self.order == 'even': Gup, Gdown = split(lrgm_out.reshape(self.canvas.shape[0], self.canvas.shape[1] * 2), 2, axis=1) if self.order == 'odd': Gup, Gdown = split(lrgm_out.reshape(-1, 2), 2, axis=1) Gup, Gdown = Gup.reshape(self.canvas.shape), Gdown.reshape( self.canvas.shape) else: print "Please specify order of Nodes, i.e 'even' for allspinup-allspindown per sclice or odd for spinup-spindown-spinup-..." Sz = self.p.upar.hbar / (4 * pi * 1j * self.p.upar.a**2) * (Gup - Gdown) elif number_of_nodes < number_of_lattice_points: Sz = zeros(self.canvas.shape, dtype=complex128) print 'calculating spin density for sparse structure' lrgm_out = self.p.hbar / (4 * pi * 1j * self.p.upar.a**2) * lrgm_out expanded_array_of_coords = repeat(self.tuple_canvas_coordinates, 2, axis=0) for index, node_name in enumerate(self.nodelist): if node_name % 2 == 0: sign = 1 else: sign = -1 Sz[tuple( expanded_array_of_coords[node_name])] += sign * lrgm_out[index] else: print 'Number of nodes larger than canvas, something is wrong!' print 'max Spin Split: ', Sz.real.max() - Sz.real.min() #Realteil scheint wahrscheinlicher, imag oszilliert wie bloed return Sz.real
def fastKineticsCrop(self, rawArray, n): """in fast kinetic picture we have one large array and then need to crop it into n equal arrays vertically. Uses scipy split function which returns a python list of the arrays returned list has the order of first picture taken --> last picture taken. i.e. [atomsImage,lightImage]""" if self.cut_white_line: # split the image, but remove some lines, which are usually very bright, we are not quite sure about the reason cut1 = 509 padding = 3 pic1, pic2 = rawArray[:cut1], rawArray[cut1 + padding:2 * cut1 + padding] return pic1, pic2 else: try: return scipy.split(rawArray, n, axis=0) except ValueError as e: print "Kinetics crop did not work"
def shred_data_run_pnc(): iplist=sorted(glob.glob('*matrix.txt')) pheno=pd.read_csv('phenotypes_info.csv') df_filter=pheno[['SUBJID','pmat_cr']] df_filter=df_filter.dropna() subs_mats=[i.split('_')[0] for i in iplist] subs_pheno=list(map(str,df_filter.SUBJID.unique())) subs_pheno=[sp.split('.')[0] for sp in subs_pheno] substouse=sorted(list(set(subs_mats) & set(subs_pheno))) iplist=[ip for ip in iplist if any([s in ip for s in substouse])] mats=[pd.read_csv(m,sep='\t',header=None).dropna(axis=1).values for m in iplist] ipmats=np.stack(mats,axis=2) pmatvals=df_filter.sort_values('SUBJID').pmat_cr.values return ipmats,pmatvals,substouse
def animate(frame): updated = [Sun.point, Sun.patch] #sun doesnt move for planet in LargeList[1:]: #large bodies after sun planet.pos = planet.orbitPos(t[frame]) updated.extend(planet.update()) Demo2.pos, Demo2.vel = sp.split(path.sol(t[frame]), 2)#x, y, v_x, v_y # vel_text.set_text('velocity = %.1f' % Demo2.vel) #¢€€€€€ updated.extend(Demo2.update()) #updated.extend(vel_text) #ax2.title(vel_text) #plt.title(vel_text) ax2.legend(["velocty = %.1f" %(mag(Demo2.vel[0] , Demo2.vel[1])) ]) # ax2.title("test") #updated.extend(vel_text) focus(Earth) return tuple(updated)
def edens(self,lrgm_out): from scipy import split,pi,asarray,sum # TODO implement sparse and noncoliear structure mapping number_of_lattice_points = self.canvas.shape[0]*self.canvas.shape[1] number_of_nodes = len(self.tuple_canvas_coordinates) if number_of_nodes == number_of_lattice_points: print 'Using stride bases reshape, Attention !!! Probably not what you want!' if self.p.multi ==1: edensity = lrgm_out.reshape(asarray(self.canvas.shape)+[0,0])*2/(2*pi*self.p.upar.a**2) #times 2 for spin if self.p.multi ==2: if self.order == 'even': Gup, Gdown = split(lrgm_out.reshape(self.canvas.shape[0],self.canvas.shape[1]*2),2,axis=1) edensity = 1/(2*pi*self.upar.p.a**2)*(Gup+Gdown) if self.order == 'odd': edensity = 1/(2*pi*self.p.upar.a**2)*sum(lrgm_out.reshape(-1,2), axis=1).reshape(self.canvas.shape) else: print "Please specify order of Nodes, i.e 'even' for allspinup-allspindown per sclice or odd for spinup-spindown-spinup-..." elif number_of_nodes < number_of_lattice_points: from scipy import zeros,complex128,repeat edensity_spin_up = zeros(self.canvas.shape,dtype=complex128) edensity_spin_down = zeros(self.canvas.shape,dtype=complex128) if self.p.multi ==1: print 'calculating electron density without SO' lrgm_out = lrgm_out *2/(2*pi*self.p.upar.a**2) for index,node_name in enumerate(self.nodelist): edensity_spin_up[self.tuple_canvas_coordinates[node_name]]= lrgm_out[index] if self.p.multi ==2: print 'calculating electron density with SO' lrgm_out = lrgm_out*1/(2*pi*self.p.upar.a**2) expanded_array_of_coords = repeat(self.tuple_canvas_coordinates,2,axis=0) for index,node_name in enumerate(self.nodelist): if node_name % 2 ==0: edensity_spin_up[tuple(expanded_array_of_coords[node_name])] = lrgm_out[index] else: edensity_spin_down[tuple(expanded_array_of_coords[node_name])] = lrgm_out[index] edensity = edensity_spin_up + edensity_spin_down edensity = (edensity.real, edensity_spin_up.real , edensity_spin_down.real) else: print 'Number of nodes larger than canvas, something is wrong!' # print 'max Electron Density: ', edensity.max() return edensity
def gen(kf,upper,lower,r=25): X=sp.matrix(sp.ndarray([0,2])) xv=sp.linspace(lower[0],upper[0],r) yv=sp.linspace(lower[1],upper[1],r) for y in yv: for x in xv: p=sp.matrix([[x,y]]) X=sp.vstack([X,p]) K= sp.array(buildKsym(kf,X)) m=sp.zeros([K.shape[0]]) zv = sp.random.multivariate_normal(m,K) f=spi.interp2d(xv,yv,sp.vstack(sp.split(zv,r))) g = lambda x:f(x[0,0],x[0,1])[0] return g
def transfersigma(self, ind_contact, E): from scipy.linalg import eig, inv from scipy.sparse import lil_matrix from aux import SparseBlocks from scipy import argsort, dot, eye, hstack, vstack, zeros, complex128, asarray, split E = E + self.zplus Ndim = len(self.p.tuple_canvas_coordinates) block = ind_contact.length Hblock = SparseBlocks(self.H, self.block_sizes) self.Hblock = Hblock I = eye(block * self.p.multi) Zeros = zeros((block * self.p.multi, block * self.p.multi)) #if ind_contact.SO is False: # H00 = 4*self.t0*eye(block) -self.t0*eye(block,k=1) -self.t0*eye(block,k=-1) # Hhop = -self.t0*I #no Bfield as of now # inv_Hhop = -1/self.t0*I #no Bfield as of now if ind_contact.index == 0: H00 = asarray(Hblock[0, 0].todense()) #H10 = asarray(Hblock[1,0].todense()) H01 = asarray(Hblock[0, 1].todense()) inv_H01 = inv(H01) if ind_contact.index == 1: H00 = asarray(Hblock[-1, -1].todense()) #H10 = asarray(Hblock[-1,-2].todense()) H01 = asarray(Hblock[-2, -1].todense()) """indices switch because hopping matrices go the other direction x --> -x, better results this way altough not much difference""" inv_H01 = inv(H01) TransMatrix = vstack((hstack( (dot(inv_H01, E * I - H00), dot(-inv_H01, H01.conj().T))), hstack( (I, Zeros)))) v, S = eig(TransMatrix) ndx = argsort(abs(v)) S = S[:, ndx] v = v[ndx] self.S = S self.v = v Sleft, Sright = split(S, 2, axis=1) S4, S3 = split(Sright, 2, axis=0) S2, S1 = split(Sleft, 2, axis=0) #S2 =S[:block*self.p.multi,:block*self.p.multi] #S1= S[block*self.p.multi:,:block*self.p.multi] self.S2 = S2 self.S1 = S1 self.S4 = S4 self.S3 = S3 print 'S1 shape: ', S1.shape print 'S2 shape: ', S2.shape if ind_contact.index == 0: dotted = dot(S2, inv(S1)) if ind_contact.index == 1: dotted = dot(S3, inv(S4)) invBracket = inv(E * I - H00 - dot(H01, dotted)) SigmaRet = self.t0**2 * invBracket if ind_contact.index == 0: self.SigmaRet1 = SigmaRet #temp = zeros((60,60),dtype=complex128) #temp[30:60,30:60] =SigmaRet[:30,:30] #SigmaRet=temp else: self.SigmaRet2 = SigmaRet print 'SigaRet shape: ', SigmaRet.shape sigma = lil_matrix((self.p.multi * Ndim, self.p.multi * Ndim), dtype=complex128) print 'sigma shape: ', sigma.shape if ind_contact.index == 0: sigma[0:SigmaRet.shape[0], 0:SigmaRet.shape[1]] = SigmaRet self.sigma1 = sigma elif ind_contact.index == 1: sigma[-SigmaRet.shape[0]:, -SigmaRet.shape[1]:] = SigmaRet self.sigma2 = sigma import pudb pudb.set_trace() return sigma
arrival_times, service_times = getRandomArrivalServiceTimes(n_process, arrival_rate, service_rate) server_prob = array([0.2, 0.2, 0.2, 0.2, 0.2]) n_server = server_prob.size # maps kth process to ith server server_address_table = digitize(uniform.rvs(size = n_process), cumsum(server_prob)) server_arrival_times = [arrival_times[server_address_table == i] for i in range(n_server)] server_service_times = [service_times[server_address_table == i] for i in range(n_server)] results = map(mm1, server_arrival_times, server_service_times) print "Mean Wait(1)", array([mean(result['wait_times']) for result in results]) print "Mean QueueSize(1)", array([mean(result['queue_size']) for result in results]) server_prob_matrix = array([[ 0.2, 0.2, 0.2, 0.2, 0.2], [ 0.2, 0.2, 0.2, 0.2, 0.2], [ 0.2, 0.2, 0.2, 0.2, 0.2], [ 0.2, 0.2, 0.2, 0.2, 0.2], [ 0.2, 0.2, 0.2, 0.2, 0.2]]) server_prob_matrix_cumsumed = cumsum(server_prob_matrix, axis = 1) server_address_tables = [ digitize(uniform.rvs(size = len(server_arrival_times[i])), server_prob_matrix_cumsumed[i]) for i in range(n_server) ] server_arrival_times = [ sort(concatenate([results[i]['completion_times'][server_address_tables[i] == k] for i in range(n_server)])) for k in range(n_server) ] new_service_times = getRandomArrivalServiceTimes(n_process, arrival_rate, service_rate)[1] server_service_times = split(new_service_times, cumsum([x.size for x in server_arrival_times]))[:-1] results2 = map(mm1, server_arrival_times, server_service_times) print "Mean Wait(2)", array([mean(result['wait_times']) for result in results2]) print "Mean QueueSize(2)", array([mean(result['queue_size']) for result in results2])
output_hdulist.writeto(progenitor_image_name.replace("coadd", "fakestars1_" + str(h) + "_" + str(g))) # Call Source Extractor in two-image mode for both sky apertures and weight # apertures. make_sex_cat_fake_stars(progenitor_image_name.replace("coadd", "fakestars1_" + str(h) + "_" + str(g)), progenitor_image_name, weight_image_name, aperture_size) make_sex_cat_fake_stars_no_weight( progenitor_image_name.replace("coadd", "fakestars1_" + str(h) + "_" + str(g)), weight_image_name, aperture_size) # Delete the fakestars image, we don't need it anymore. system("rm " + progenitor_image_name.replace("coadd", "fakestars1_" + str(h) + "_" + str(g))) # Read the SEX catalogs into data lists. The format of the sex_file is: # ra, dec, inst_mag, e_inst_mag, flags, fwhm, signal, noise temp_array = loadtxt(file(progenitor_image_name.replace(".fits", ".sex"))) aperture_data = append(aperture_data, temp_array) aperture_data = split(aperture_data, len(aperture_data)/8) flux_array = append(flux_array, (temp_array[:,6])) temp_array = loadtxt(file(weight_image_name.replace(".fits", ".sex"))) weight_aperture_data = append(weight_aperture_data, temp_array) weight_aperture_data = split(weight_aperture_data, len(weight_aperture_data)/8) for g in range(order): for h in range(order): fake_star_data = zeros([height,width]) for i in range(int(width/aperture_size/order)-1): for j in range(int(height/aperture_size/order)-1): fake_star_data[int((j+1-1./(order*2))*spacing+aperture_size*h)][int((i+1-1./(order*2))*spacing+aperture_size*g)] = peak blurred_fake_star_data = zeros([height,width]) gaussian_filter(fake_star_data*weight_mask_expanded, 0.7,
def generate_sigma(self): import networkx as nx from scipy.linalg import inv,schur,eig from scipy.sparse import lil_matrix from numpy import asarray_chkfinite,isfinite,inf from aux import SparseBlocks, eigenvector_from_eigenvalue, all_elements_are_unique from scipy import argsort,dot,eye,hstack,vstack,zeros,complex128,split,asarray,diag,array # should be able to turn zplus off, but then i need better eigenvalue comparison E= self.p.E+self.p.zplus Ndim = len(self.p.tuple_canvas_coordinates) block=self.graph.order()/2 I=eye(block) Zeros = zeros((block,block)) Hlead = nx.to_numpy_matrix(self.graph,nodelist=self.nodelist,dtype=complex128) self.Hlead = Hlead #import pudb; pudb.set_trace() # add 4*self.t0 because the matrix from graph lacks diagonal (no self-loops) try: H00 = asarray_chkfinite(Hlead[:block,:block])+4*self.p.t0 * I self.H00 = H00 except ValueError: print 'H00 contains infs or NaNs' import pudb; pudb.set_trace() try: H01 = asarray_chkfinite(Hlead[:block,block:]) self.H01 = H01 except ValueError: print 'H01 contains infs or NaNs' import pudb; pudb.set_trace() inv_H01 = inv(H01) while not isfinite(inv_H01).all(): print 'inv_H01 contains infs or NaNs, repeating' inv_H01 = inv(H01) #import pudb; pudb.set_trace() self.inv_H01 = inv_H01 CompanionMatrix_array =vstack((hstack((Zeros,I)),hstack((dot(-inv_H01,H01.conj().T),dot(inv_H01,E*I-H00))))) if not isfinite(CompanionMatrix_array).all(): print 'CompanionMatrix contains infs or NaNs' import pudb; pudb.set_trace() #CompanionMatrix_array =vstack((hstack((dot(inv_H01,E*I-H00),dot(-inv_H01,H01.conj().T))),hstack((I,Zeros)))) # the following 'complex' might be superfluous and only for real input matrices. T,Z,number_sorted= schur(CompanionMatrix_array,sort='iuc') eigenvalues = diag(T) # propagating_eigenvalues = [] # propagating_eigenvectors = [] # for eigenvalue in eigenvalues: # if abs(abs(eigenvalue)-1) < 0.01: # propagating_eigenvalues.append(eigenvalue) # eigenvector = eigenvector_from_eigenvalue(CompanionMatrix_array, eigenvalue) # propagating_eigenvectors.append(eigenvector) # prop_eig_array = array(propagating_eigenvectors).T if not all_elements_are_unique(eigenvalues): print "--------------WARNING!!!!!---------------" print "One or more eigenvalues are identical, please rotate eigenvectors, I don't know how to do that" #v,d = eig(CompanionMatrix_array) #ndx = argsort(v) #S=d[:,ndx] #v=v[ndx] #Sleft,Sright = split(S,2,axis=1) #S4,S3 = split(Sright,2,axis=0) #S2,S1 = split(Sleft,2,axis=0) #S2 =S[:block*self.p.multi,:block*self.p.multi] #S1= S[block*self.p.multi:,:block*self.p.multi] #self.S2 = S2 #self.S1 = S1 #self.S4 = S4 #self.S3 = S3 #print 'S1 shape: ',S1.shape #print 'S2 shape: ',S2.shape # sort eigenvalues and Z according to acending abs(eigenvalue), TODO: do better sorting, now it # depends on luck. sort using the calulated eigenvectors above # sorting_indices = abs(eigenvalues).argsort() #T = T[:,sorting_indices][sorting_indices,:] #Z = Z[:,sorting_indices][sorting_indices,:] Zleft,Zright = split(Z,2,axis=1) #S4,S3 = split(Sright,2,axis=0) Z11,Z21 = split(Zleft,2,axis=0) self.Z11 = Z11 self.Z21 = Z21 if self.index == 0: SigmaRet = dot(H01,dot(Z21,inv(Z11))) else: SigmaRet = dot(H01.conj(),dot(Z21,inv(Z11))) self.SigmaRet = SigmaRet print '- SimgaRet (',self.index,') shape: ',SigmaRet.shape sigma = lil_matrix((self.p.multi*Ndim,self.p.multi*Ndim), dtype=complex128) print '- sigma shape: ',sigma.shape #implement polarization like (for spin up) reshape(-1,2) --> [:,1] = 0 --> reshape(shape(SigmaRet)) if self.index == 0: if 'up' in self.current: print 'Up polarized input' SigmaRet.reshape(-1,2)[:,1] = 0 elif 'down' in self.current: print 'Down polarized input' SigmaRet.reshape(-1,2)[:,0] = 0 sigma[0:SigmaRet.shape[0], 0:SigmaRet.shape[1]] = SigmaRet elif self.index == 1: sigma[-SigmaRet.shape[0]:, -SigmaRet.shape[1]:] = SigmaRet self.sigma=sigma return sigma
def solve(self, wls): """Anisotropic solver. INPUT wls = wavelengths to scan (any asarray-able object). OUTPUT self.DEO1, self.DEE1, self.DEO3, self.DEE3 = power reflected and transmitted. """ self.wls = S.atleast_1d(wls) LAMBDA = self.LAMBDA n = self.n multilayer = self.multilayer alpha = self.alpha delta = self.delta psi = self.psi phi = self.phi nlayers = len(multilayer) i = S.arange(-n, n + 1) nood = 2 * n + 1 hmax = nood - 1 DEO1 = S.zeros((nood, self.wls.size)) DEO3 = S.zeros_like(DEO1) DEE1 = S.zeros_like(DEO1) DEE3 = S.zeros_like(DEO1) c1 = S.array([1., 0., 0.]) c3 = S.array([1., 0., 0.]) # grating on the xy plane K = 2 * pi / LAMBDA * \ S.array([S.sin(phi), 0., S.cos(phi)], dtype=complex) dirk1 = S.array([S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha)]) # D polarization vector u = S.array([S.cos(psi) * S.cos(alpha) * S.cos(delta) - S.sin(psi) * S.sin(delta), S.cos(psi) * S.cos(alpha) * S.sin(delta) + S.sin(psi) * S.cos(delta), -S.cos(psi) * S.sin(alpha)]) kO1i = S.zeros((3, i.size), dtype=complex) kE1i = S.zeros_like(kO1i) kO3i = S.zeros_like(kO1i) kE3i = S.zeros_like(kO1i) Mp = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex) M = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex) dlt = (i == 0).astype(int) for iwl, wl in enumerate(self.wls): nO1 = nE1 = multilayer[0].mat.n(wl).item() nO3 = nE3 = multilayer[-1].mat.n(wl).item() # wavevectors k = 2 * pi / wl eps1 = S.diag(S.asarray([nE1, nO1, nO1]) ** 2) eps3 = S.diag(S.asarray([nE3, nO3, nO3]) ** 2) # ordinary wave abskO1 = k * nO1 # abskO3 = k * nO3 # extraordinary wave # abskE1 = k * nO1 *nE1 / S.sqrt(nO1**2 + (nE1**2 - nO1**2) * S.dot(-c1, dirk1)**2) # abskE3 = k * nO3 *nE3 / S.sqrt(nO3**2 + (nE3**2 - nO3**2) * S.dot(-c3, dirk1)**2) k1 = abskO1 * dirk1 kO1i[0, :] = k1[0] - i * K[0] kO1i[1, :] = k1[1] * S.ones_like(i) kO1i[2, :] = - \ dispersion_relation_ordinary(kO1i[0, :], kO1i[1, :], k, nO1) kE1i[0, :] = kO1i[0, :] kE1i[1, :] = kO1i[1, :] kE1i[2, :] = -dispersion_relation_extraordinary(kE1i[0, :], kE1i[1, :], k, nO1, nE1, c1) kO3i[0, :] = kO1i[0, :] kO3i[1, :] = kO1i[1, :] kO3i[ 2, :] = dispersion_relation_ordinary( kO3i[ 0, :], kO3i[ 1, :], k, nO3) kE3i[0, :] = kO1i[0, :] kE3i[1, :] = kO1i[1, :] kE3i[ 2, :] = dispersion_relation_extraordinary( kE3i[ 0, :], kE3i[ 1, :], k, nO3, nE3, c3) # k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [k1[2] - i * K[2]]] k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [- i * K[2]]] # aliases for constant wavevectors kx = kO1i[0, :] # o kE1i(1,;), tanto e' lo stesso ky = k1[1] # matrices I = S.eye(nood, dtype=complex) ZERO = S.zeros((nood, nood), dtype=complex) Kx = S.diag(kx / k) Ky = ky / k * I Kz = S.diag(k2i[2, :] / k) KO1z = S.diag(kO1i[2, :] / k) KE1z = S.diag(kE1i[2, :] / k) KO3z = S.diag(kO3i[2, :] / k) KE3z = S.diag(kE3i[2, :] / k) ARO = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KO1z * eps1[2, 0] BRO = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KO1z * eps1[2, 1] CRO_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KO1z * eps1[2, 2]) ARE = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KE1z * eps1[2, 0] BRE = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KE1z * eps1[2, 1] CRE_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KE1z * eps1[2, 2]) ATO = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KO3z * eps3[2, 0] BTO = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KO3z * eps3[2, 1] CTO_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KO3z * eps3[2, 2]) ATE = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KE3z * eps3[2, 0] BTE = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KE3z * eps3[2, 1] CTE_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KE3z * eps3[2, 2]) DRE = c1[1] * KE1z - c1[2] * Ky ERE = c1[2] * Kx - c1[0] * KE1z FRE = c1[0] * Ky - c1[1] * Kx DTE = c3[1] * KE3z - c3[2] * Ky ETE = c3[2] * Kx - c3[0] * KE3z FTE = c3[0] * Ky - c3[1] * Kx b = S.r_[u[0] * dlt, u[1] * dlt, (k1[1] / k * u[2] - k1[2] / k * u[1]) * dlt, ( k1[2] / k * u[0] - k1[0] / k * u[2]) * dlt] Ky_CRO_1 = ky / k * CRO_1 Ky_CRE_1 = ky / k * CRE_1 Kx_CRO_1 = kx[:, S.newaxis] / k * CRO_1 Kx_CRE_1 = kx[:, S.newaxis] / k * CRE_1 MR31 = -S.dot(Ky_CRO_1, ARO) MR32 = -S.dot(Ky_CRO_1, BRO) - KO1z MR33 = -S.dot(Ky_CRE_1, ARE) MR34 = -S.dot(Ky_CRE_1, BRE) - KE1z MR41 = S.dot(Kx_CRO_1, ARO) + KO1z MR42 = S.dot(Kx_CRO_1, BRO) MR43 = S.dot(Kx_CRE_1, ARE) + KE1z MR44 = S.dot(Kx_CRE_1, BRE) MR = S.asarray(S.bmat([[I, ZERO, I, ZERO], [ZERO, I, ZERO, I], [MR31, MR32, MR33, MR34], [MR41, MR42, MR43, MR44]])) Ky_CTO_1 = ky / k * CTO_1 Ky_CTE_1 = ky / k * CTE_1 Kx_CTO_1 = kx[:, S.newaxis] / k * CTO_1 Kx_CTE_1 = kx[:, S.newaxis] / k * CTE_1 MT31 = -S.dot(Ky_CTO_1, ATO) MT32 = -S.dot(Ky_CTO_1, BTO) - KO3z MT33 = -S.dot(Ky_CTE_1, ATE) MT34 = -S.dot(Ky_CTE_1, BTE) - KE3z MT41 = S.dot(Kx_CTO_1, ATO) + KO3z MT42 = S.dot(Kx_CTO_1, BTO) MT43 = S.dot(Kx_CTE_1, ATE) + KE3z MT44 = S.dot(Kx_CTE_1, BTE) MT = S.asarray(S.bmat([[I, ZERO, I, ZERO], [ZERO, I, ZERO, I], [MT31, MT32, MT33, MT34], [MT41, MT42, MT43, MT44]])) Mp.fill(0.0) M.fill(0.0) for nlayer in range(nlayers - 2, 0, -1): # internal layers layer = multilayer[nlayer] thickness = layer.thickness EPS2, EPS21 = layer.getEPSFourierCoeffs( wl, n, anisotropic=True) # Exx = S.squeeze(EPS2[0, 0, :]) # Exx = toeplitz(S.flipud(Exx[0:hmax + 1]), Exx[hmax:]) Exy = S.squeeze(EPS2[0, 1, :]) Exy = toeplitz(S.flipud(Exy[0:hmax + 1]), Exy[hmax:]) Exz = S.squeeze(EPS2[0, 2, :]) Exz = toeplitz(S.flipud(Exz[0:hmax + 1]), Exz[hmax:]) Eyx = S.squeeze(EPS2[1, 0, :]) Eyx = toeplitz(S.flipud(Eyx[0:hmax + 1]), Eyx[hmax:]) Eyy = S.squeeze(EPS2[1, 1, :]) Eyy = toeplitz(S.flipud(Eyy[0:hmax + 1]), Eyy[hmax:]) Eyz = S.squeeze(EPS2[1, 2, :]) Eyz = toeplitz(S.flipud(Eyz[0:hmax + 1]), Eyz[hmax:]) Ezx = S.squeeze(EPS2[2, 0, :]) Ezx = toeplitz(S.flipud(Ezx[0:hmax + 1]), Ezx[hmax:]) Ezy = S.squeeze(EPS2[2, 1, :]) Ezy = toeplitz(S.flipud(Ezy[0:hmax + 1]), Ezy[hmax:]) Ezz = S.squeeze(EPS2[2, 2, :]) Ezz = toeplitz(S.flipud(Ezz[0:hmax + 1]), Ezz[hmax:]) Exx_1 = S.squeeze(EPS21[0, 0, :]) Exx_1 = toeplitz(S.flipud(Exx_1[0:hmax + 1]), Exx_1[hmax:]) Exx_1_1 = inv(Exx_1) # lalanne Ezz_1 = inv(Ezz) Ky_Ezz_1 = ky / k * Ezz_1 Kx_Ezz_1 = kx[:, S.newaxis] / k * Ezz_1 Exz_Ezz_1 = S.dot(Exz, Ezz_1) Eyz_Ezz_1 = S.dot(Eyz, Ezz_1) H11 = 1j * S.dot(Ky_Ezz_1, Ezy) H12 = 1j * S.dot(Ky_Ezz_1, Ezx) H13 = S.dot(Ky_Ezz_1, Kx) H14 = I - S.dot(Ky_Ezz_1, Ky) H21 = 1j * S.dot(Kx_Ezz_1, Ezy) H22 = 1j * S.dot(Kx_Ezz_1, Ezx) H23 = S.dot(Kx_Ezz_1, Kx) - I H24 = -S.dot(Kx_Ezz_1, Ky) H31 = S.dot(Kx, Ky) + Exy - S.dot(Exz_Ezz_1, Ezy) H32 = Exx_1_1 - S.dot(Ky, Ky) - S.dot(Exz_Ezz_1, Ezx) H33 = 1j * S.dot(Exz_Ezz_1, Kx) H34 = -1j * S.dot(Exz_Ezz_1, Ky) H41 = S.dot(Kx, Kx) - Eyy + S.dot(Eyz_Ezz_1, Ezy) H42 = -S.dot(Kx, Ky) - Eyx + S.dot(Eyz_Ezz_1, Ezx) H43 = -1j * S.dot(Eyz_Ezz_1, Kx) H44 = 1j * S.dot(Eyz_Ezz_1, Ky) H = 1j * S.diag(S.repeat(S.diag(Kz), 4)) + \ S.asarray(S.bmat([[H11, H12, H13, H14], [H21, H22, H23, H24], [H31, H32, H33, H34], [H41, H42, H43, H44]])) q, W = eig(H) W1, W2, W3, W4 = S.split(W, 4) # # boundary conditions # # x = [R T] # R = [ROx ROy REx REy] # T = [TOx TOy TEx TEy] # b + MR.R = M1p.c # M1.c = M2p.c # ... # ML.c = MT.T # therefore: b + MR.R = (M1p.M1^-1.M2p.M2^-1. ...).MT.T # missing equations from (46)..(49) in glytsis_rigorous # [b] = [-MR Mtot.MT] [R] # [0] [...........] [T] z = S.zeros_like(q) z[S.where(q.real > 0)] = -thickness D = S.exp(k * q * z) Sy0 = W1 * D[S.newaxis, :] Sx0 = W2 * D[S.newaxis, :] Uy0 = W3 * D[S.newaxis, :] Ux0 = W4 * D[S.newaxis, :] z = thickness * S.ones_like(q) z[S.where(q.real > 0)] = 0 D = S.exp(k * q * z) D1 = S.exp(-1j * k2i[2, :] * thickness) Syd = D1[:, S.newaxis] * W1 * D[S.newaxis, :] Sxd = D1[:, S.newaxis] * W2 * D[S.newaxis, :] Uyd = D1[:, S.newaxis] * W3 * D[S.newaxis, :] Uxd = D1[:, S.newaxis] * W4 * D[S.newaxis, :] Mp[:, :, nlayer] = S.r_[Sx0, Sy0, -1j * Ux0, -1j * Uy0] M[:, :, nlayer] = S.r_[Sxd, Syd, -1j * Uxd, -1j * Uyd] Mtot = S.eye(4 * nood, dtype=complex) for nlayer in range(1, nlayers - 1): Mtot = S.dot( S.dot(Mtot, Mp[:, :, nlayer]), inv(M[:, :, nlayer])) BC_b = S.r_[b, S.zeros_like(b)] BC_A1 = S.c_[-MR, S.dot(Mtot, MT)] BC_A2 = S.asarray(S.bmat( [[(c1[0] * I - c1[2] * S.dot(CRO_1, ARO)), (c1[1] * I - c1[2] * S.dot(CRO_1, BRO)), ZERO, ZERO, ZERO, ZERO, ZERO, ZERO], [ZERO, ZERO, (DRE - S.dot(S.dot(FRE, CRE_1), ARE)), (ERE - S.dot(S.dot(FRE, CRE_1), BRE)), ZERO, ZERO, ZERO, ZERO], [ZERO, ZERO, ZERO, ZERO, (c3[0] * I - c3[2] * S.dot(CTO_1, ATO)), (c3[1] * I - c3[2] * S.dot(CTO_1, BTO)), ZERO, ZERO], [ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, (DTE - S.dot(S.dot(FTE, CTE_1), ATE)), (ETE - S.dot(S.dot(FTE, CTE_1), BTE))]])) BC_A = S.r_[BC_A1, BC_A2] x = linsolve(BC_A, BC_b) ROx, ROy, REx, REy, TOx, TOy, TEx, TEy = S.split(x, 8) ROz = -S.dot(CRO_1, (S.dot(ARO, ROx) + S.dot(BRO, ROy))) REz = -S.dot(CRE_1, (S.dot(ARE, REx) + S.dot(BRE, REy))) TOz = -S.dot(CTO_1, (S.dot(ATO, TOx) + S.dot(BTO, TOy))) TEz = -S.dot(CTE_1, (S.dot(ATE, TEx) + S.dot(BTE, TEy))) denom = (k1[2] - S.dot(u, k1) * u[2]).real DEO1[:, iwl] = -((S.absolute(ROx) ** 2 + S.absolute(ROy) ** 2 + S.absolute(ROz) ** 2) * S.conj(kO1i[2, :]) - (ROx * kO1i[0, :] + ROy * kO1i[1, :] + ROz * kO1i[2, :]) * S.conj(ROz)).real / denom DEE1[:, iwl] = -((S.absolute(REx) ** 2 + S.absolute(REy) ** 2 + S.absolute(REz) ** 2) * S.conj(kE1i[2, :]) - (REx * kE1i[0, :] + REy * kE1i[1, :] + REz * kE1i[2, :]) * S.conj(REz)).real / denom DEO3[:, iwl] = ((S.absolute(TOx) ** 2 + S.absolute(TOy) ** 2 + S.absolute(TOz) ** 2) * S.conj(kO3i[2, :]) - (TOx * kO3i[0, :] + TOy * kO3i[1, :] + TOz * kO3i[2, :]) * S.conj(TOz)).real / denom DEE3[:, iwl] = ((S.absolute(TEx) ** 2 + S.absolute(TEy) ** 2 + S.absolute(TEz) ** 2) * S.conj(kE3i[2, :]) - (TEx * kE3i[0, :] + TEy * kE3i[1, :] + TEz * kE3i[2, :]) * S.conj(TEz)).real / denom # save the results self.DEO1 = DEO1 self.DEE1 = DEE1 self.DEO3 = DEO3 self.DEE3 = DEE3 return self
TilesHor = (TargetSize[0]*PixPerTile[1]*TilesVert)/(TargetSize[1]*PixPerTile[0]) Tiles = scipy.array((TilesHor, TilesVert), dtype=int) TilesPerNode = scipy.array((TilesHor, TilesVert/NPlacers), dtype=int) TotalTilesPerNode = scipy.prod(TilesPerNode) Pixels = Tiles*PixPerTile UnscaledWidth = (TargetSize[1]*Tiles[0])/Tiles[1]# the width of the original size image to yield the correct aspect ratio CropMargin = (TargetSize[0] - UnscaledWidth)/2 #TargetImg.crop((0,0,)) #TargetImg.resize(Pixels) CroppedImg = TargetImg.transform((UnscaledWidth,TargetSize[1]), Image.EXTENT, (CropMargin,0, CropMargin+UnscaledWidth,TargetImg.size[1])) CroppedArr = scipy.array(CroppedImg) #%% reduce CroppedArr to NPlacers NodeArrs NodeHeightInCroppedArr = float(TargetSize[1])/NPlacers sections = scipy.array(scipy.arange(NodeHeightInCroppedArr, TargetSize[1], NodeHeightInCroppedArr), dtype=int) NodeArrs = scipy.split(CroppedArr, sections, axis=0) # each tile in the image #%% reduce NodeArr to TilesPerNode TileArrs NodeArr = NodeArrs.pop(0) pm = photo_match.photoMatch() TileArrs = [] # each tile in the image TileCompacts = [] # each tile in the image whichSources = scipy.zeros((TotalTilesPerNode), dtype=int) Distances = scipy.ones((TotalTilesPerNode))*scipy.Inf # the quality of the current fit for each tile (put at infinity to start with) TileWidthInCroppedArr = float(UnscaledWidth)/Tiles[0] vertSections = scipy.array(scipy.arange(TileWidthInCroppedArr, UnscaledWidth-.5*TileWidthInCroppedArr, TileWidthInCroppedArr), dtype=int) VertSplitArrs = scipy.split(NodeArr, vertSections, axis=1) for VertSplitArr in VertSplitArrs: TileHeightInCroppedArr = float(VertSplitArr.shape[0])/Tiles[1]*NPlacers
def solve(self, wls): """Isotropic solver. INPUT wls = wavelengths to scan (any asarray-able object). OUTPUT self.DE1, self.DE3 = power reflected and transmitted. NOTE see: Moharam, "Formulation for stable and efficient implementation of the rigorous coupled-wave analysis of binary gratings", JOSA A, 12(5), 1995 Lalanne, "Highly improved convergence of the coupled-wave method for TM polarization", JOSA A, 13(4), 1996 Moharam, "Stable implementation of the rigorous coupled-wave analysis for surface-relief gratings: enhanced trasmittance matrix approach", JOSA A, 12(5), 1995 """ self.wls = S.atleast_1d(wls) LAMBDA = self.LAMBDA n = self.n multilayer = self.multilayer alpha = self.alpha delta = self.delta psi = self.psi phi = self.phi nlayers = len(multilayer) i = S.arange(-n, n + 1) nood = 2 * n + 1 hmax = nood - 1 # grating vector (on the xz plane) # grating on the xy plane K = 2 * pi / LAMBDA * np.array( [S.sin(phi), 0., S.cos(phi)], dtype=complex) DE1 = S.zeros((nood, self.wls.size)) DE3 = S.zeros_like(DE1) dirk1 = np.array([ S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha) ]) # usefull matrices I = S.eye(i.size) I2 = S.eye(i.size * 2) ZERO = S.zeros_like(I) X = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex) MTp1 = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex) MTp2 = S.zeros_like(MTp1) EPS2 = S.zeros(2 * hmax + 1, dtype=complex) EPS21 = S.zeros_like(EPS2) dlt = (i == 0).astype(int) for iwl, wl in enumerate(self.wls): # free space wavevector k = 2 * pi / wl n1 = multilayer[0].mat.n(wl).item() n3 = multilayer[-1].mat.n(wl).item() # incident plane wave wavevector k1 = k * n1 * dirk1 # all the other wavevectors tmp_x = k1[0] - i * K[0] tmp_y = k1[1] * S.ones_like(i) tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n1) k1i = S.r_[[tmp_x], [tmp_y], [tmp_z]] # k2i = S.r_[[k1[0] - i*K[0]], [k1[1] - i * K[1]], [-i * K[2]]] tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n3) k3i = S.r_[[k1i[0, :]], [k1i[1, :]], [tmp_z]] # aliases for constant wavevectors kx = k1i[0, :] ky = k1[1] # angles of reflection # phi_i = S.arctan2(ky,kx) phi_i = S.arctan2(ky, kx.real) # OKKIO Kx = S.diag(kx / k) Ky = ky / k * I Z1 = S.diag(k1i[2, :] / (k * n1**2)) Y1 = S.diag(k1i[2, :] / k) Z3 = S.diag(k3i[2, :] / (k * n3**2)) Y3 = S.diag(k3i[2, :] / k) # Fc = S.diag(S.cos(phi_i)) fc = S.cos(phi_i) # Fs = S.diag(S.sin(phi_i)) fs = S.sin(phi_i) MR = S.asarray( S.bmat([[I, ZERO], [-1j * Y1, ZERO], [ZERO, I], [ZERO, -1j * Z1]])) MT = S.asarray( S.bmat([[I, ZERO], [1j * Y3, ZERO], [ZERO, I], [ZERO, 1j * Z3]])) # internal layers (grating or layer) X.fill(0.0) MTp1.fill(0.0) MTp2.fill(0.0) for nlayer in range(nlayers - 2, 0, -1): # internal layers layer = multilayer[nlayer] d = layer.thickness EPS2, EPS21 = layer.getEPSFourierCoeffs(wl, n, anisotropic=False) E = toeplitz(EPS2[hmax::-1], EPS2[hmax:]) E1 = toeplitz(EPS21[hmax::-1], EPS21[hmax:]) E11 = inv(E1) # B = S.dot(Kx, linsolve(E,Kx)) - I B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I # A = S.dot(Kx, Kx) - E A = S.diag((kx / k)**2) - E # Note: solution bug alfredo # randomizzo Kx un po' a caso finche' cond(A) e' piccolo (<1e10) # soluzione sporca... :-( # per certi kx, l'operatore di helmholtz ha 2 autovalori nulli e A, B # non sono invertibili --> cambio leggermente i kx... ma dovrei invece # trattare separatamente (analiticamente) questi casi if cond(A) > 1e10: warning("BAD CONDITIONING: randomization of kx") while cond(A) > 1e10: Kx = Kx * (1 + 1e-9 * S.rand()) B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I A = S.diag((kx / k)**2) - E if S.absolute(K[2] / k) > 1e-10: raise ValueError( "First Order Helmholtz Operator not implemented, yet!") elif ky == 0 or S.allclose(S.diag(Ky / ky * k), 1): # lalanne # H_U_reduced = S.dot(Ky, Ky) + A H_U_reduced = (ky / k)**2 * I + A # H_S_reduced = S.dot(Ky, Ky) + S.dot(Kx, linsolve(E, S.dot(Kx, E11))) - E11 H_S_reduced = ((ky / k)**2 * I + kx[:, S.newaxis] / k * linsolve(E, kx[:, S.newaxis] / k * E11) - E11) q1, W1 = eig(H_U_reduced) q1 = S.sqrt(q1) q2, W2 = eig(H_S_reduced) q2 = S.sqrt(q2) # boundary conditions # V11 = S.dot(linsolve(A, W1), S.diag(q1)) V11 = linsolve(A, W1) * q1[S.newaxis, :] V12 = (ky / k) * S.dot(linsolve(A, Kx), W2) V21 = (ky / k) * S.dot(linsolve(B, Kx), linsolve(E, W1)) # V22 = S.dot(linsolve(B, W2), S.diag(q2)) V22 = linsolve(B, W2) * q2[S.newaxis, :] # Vss = S.dot(Fc, V11) Vss = fc[:, S.newaxis] * V11 # Wss = S.dot(Fc, W1) + S.dot(Fs, V21) Wss = fc[:, S.newaxis] * W1 + fs[:, S.newaxis] * V21 # Vsp = S.dot(Fc, V12) - S.dot(Fs, W2) Vsp = fc[:, S.newaxis] * V12 - fs[:, S.newaxis] * W2 # Wsp = S.dot(Fs, V22) Wsp = fs[:, S.newaxis] * V22 # Wpp = S.dot(Fc, V22) Wpp = fc[:, S.newaxis] * V22 # Vpp = S.dot(Fc, W2) + S.dot(Fs, V12) Vpp = fc[:, S.newaxis] * W2 + fs[:, S.newaxis] * V12 # Wps = S.dot(Fc, V21) - S.dot(Fs, W1) Wps = fc[:, S.newaxis] * V21 - fs[:, S.newaxis] * W1 # Vps = S.dot(Fs, V11) Vps = fs[:, S.newaxis] * V11 Mc2bar = S.asarray( S.bmat([ [Vss, Vsp, Vss, Vsp], [Wss, Wsp, -Wss, -Wsp], [Wps, Wpp, -Wps, -Wpp], [Vps, Vpp, Vps, Vpp], ])) x = S.r_[S.exp(-k * q1 * d), S.exp(-k * q2 * d)] # Mc1 = S.dot(Mc2bar, S.diag(S.r_[S.ones_like(x), x])) xx = S.r_[S.ones_like(x), x] Mc1 = Mc2bar * xx[S.newaxis, :] X[:, :, nlayer] = S.diag(x) MTp = linsolve(Mc2bar, MT) MTp1[:, :, nlayer] = MTp[0:2 * nood, :] MTp2 = MTp[2 * nood:, :] MT = S.dot( Mc1, S.r_[I2, S. dot(MTp2, linsolve(MTp1[:, :, nlayer], X[:, :, nlayer])), ], ) else: ValueError( "Second Order Helmholtz Operator not implemented, yet!" ) # M = S.asarray(S.bmat([-MR, MT])) M = S.c_[-MR, MT] b = S.r_[S.sin(psi) * dlt, 1j * S.sin(psi) * n1 * S.cos(alpha) * dlt, -1j * S.cos(psi) * n1 * dlt, S.cos(psi) * S.cos(alpha) * dlt, ] x = linsolve(M, b) R, T = S.split(x, 2) Rs, Rp = S.split(R, 2) for ii in range(1, nlayers - 1): T = S.dot(linsolve(MTp1[:, :, ii], X[:, :, ii]), T) Ts, Tp = S.split(T, 2) DE1[:, iwl] = (k1i[2, :] / (k1[2])).real * S.absolute(Rs)**2 + ( k1i[2, :] / (k1[2] * n1**2)).real * S.absolute(Rp)**2 DE3[:, iwl] = (k3i[2, :] / (k1[2])).real * S.absolute(Ts)**2 + ( k3i[2, :] / (k1[2] * n3**2)).real * S.absolute(Tp)**2 # save the results self.DE1 = DE1 self.DE3 = DE3 return self
def process(pars, data=None): #%% load the parameters that CAN be specified from the command line NPlacers = pars['NPlacers'] NScrapers = pars['NScrapers'] iters = pars['iters'] MaxTilesVert = pars['MaxTilesVert'] per_page = pars['per_page'] fidelity = pars['fidelity'] poolSize = pars['poolSize'] if (data != None): tags = data['search'].split(', ') else: #tags = ('Minimalism',) tags = ('Face','Leuven','Belgium','Computer') #tags = ('Bussum','Football','PSV','Minimalism','urbex') #%% MPI stuff comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() status = MPI.Status() #%% initiate plogger #execfile('../mosaic_gui/daemon/params.par') logger = plogger.PLogger(rank, host_url=LOGGER_HOST) #%% print the values of those parameters that CAN be specified via the command line #for key, value in pars.iteritems(): #print "M{}: {} is now {}".format(rank, key, value) #%% identify oneself #print "Master, process {} out of {}".format(rank, size) #print "M{}: > init".format(rank) logger.write('Initializing', status=plogger.INIT) #%% initialize the photo matcher pmPars = {'fidelity': fidelity} pm = photo_match.photoMatch(pmPars) # create empty save-path if not pars['useDB']: if (os.path.exists(pars['savepath'])): shutil.rmtree(pars['savepath'], ignore_errors=True) os.mkdir(pars['savepath']) #%% call the scrapers right at the beginning, as it is probably the slowest PixPerTile = scipy.array((75,75)) ComparePixPerTile = scipy.array((fidelity,fidelity)) scraperPars = {'pm': pm, 'tags': tags, 'PixPerTile': PixPerTile, 'poolSize': poolSize} for scraper in range(1,1+NScrapers): comm.send(scraperPars, dest=scraper, tag=0) TilesVert = int(MaxTilesVert/NPlacers) * NPlacers TargetImg = Image.open('./output/doesnotmatter.jpg') #TargetImg = Image.open('./Matilda.JPG') #TargetImg = Image.open('./rainbow_flag_by_kelly.jpg') #TargetImg = Image.open('./korneel_test.jpg') TargetSize = TargetImg.size TilesHor = (TargetSize[0]*PixPerTile[1]*TilesVert)/(TargetSize[1]*PixPerTile[0]) Tiles = scipy.array((TilesHor, TilesVert), dtype=int) TilesPerNode = scipy.array((TilesHor, TilesVert/NPlacers), dtype=int) Pixels = Tiles*PixPerTile ratio = 2.0 / 3.0 TargetChunkPixels = Tiles*scipy.int_(PixPerTile*ratio) ComparePixels = Tiles*scipy.int_(ComparePixPerTile*ratio) #%% adjust the image to have the correct shape (aspect ratio) for turning it into a mosaic UnscaledWidth = (TargetSize[1]*Tiles[0])/Tiles[1]# the width of the original size image to yield the correct aspect ratio CropMargin = (TargetSize[0] - UnscaledWidth)/2 #TargetImg.crop((0,0,)) #TargetImg.resize(Pixels) CroppedImg = TargetImg.transform((ComparePixels[0],ComparePixels[1]), Image.EXTENT, (CropMargin,0, CropMargin+UnscaledWidth,TargetImg.size[1])) CroppedArr = color.rgb2lab(scipy.array(CroppedImg)) #%% send each placer some parameters placerPars = {'TilesPerNode': TilesPerNode, 'UnscaledWidth': UnscaledWidth, 'Tiles': Tiles, 'pm': pm, 'iters': iters, 'PixPerTile': PixPerTile, 'ComparePixPerTile' : ComparePixPerTile} for placer in range(NPlacers): comm.send(placerPars, dest=1+NScrapers+placer, tag=0) #print "M{}: < init".format(rank) #print "M{}: > dividing image".format(rank) #%% reduce CroppedArr to NPlacers NodeArrs NodeArrs = scipy.split(CroppedArr, NPlacers, axis=0) #%% send each of the placers its piece of the picture for placer in range(NPlacers): comm.send(NodeArrs[placer], dest=1+NScrapers+placer, tag=1) #%% create the final image and divide it into pieces for the placers to FinalArr = CroppedArr.copy() # now the division has to be accurate! FinalArr = scipy.zeros((TargetChunkPixels[1], TargetChunkPixels[0], 3), dtype='i') # FinalArr = scipy.zeros((Tiles[1]*PixPerTile[1], Tiles[0]*PixPerTile[0], 3), dtype='i') NodeFinalArrs = scipy.split(FinalArr, NPlacers, axis=0) #print "M{}: < dividing image".format(rank) #%% listen to the placers' intermediate results tempNodeFinalArr = NodeFinalArrs[0].copy() # for receiving the data, before it is known whence it came for it in range(iters): #print "M{}: > not listening to the placer to scraper broadcast".format(rank) dummy_arrs = scipy.zeros((per_page, PixPerTile[1], PixPerTile[0], 3), dtype=scipy.uint8) for scraper in range(1, 1+NScrapers): #print "M{}: not listening to scraper {}".format(rank, scraper) comm.Bcast(dummy_arrs, root=scraper) #print "M{}: < not listening to the placer to scraper broadcast".format(rank) #print "M{}: now listening for placer results at iter {} out of {}".format(rank, it, iters) #print "M{}: > listening for results".format(rank) logger.write('Listening for placers', status=plogger.RECEIVING) for p in range(NPlacers): # listen for the placers #print "M{}: NodeFinalArrs[{}] has shape ".format(rank, placer), NodeFinalArrs[placer].shape #print "M{}: NodeFinalArrs[{}] has type ".format(rank, placer), type(NodeFinalArrs[placer][0,0,0]) comm.Recv([tempNodeFinalArr, MPI.INT], source=MPI.ANY_SOURCE, tag=4, status=status) placer = status.Get_source() NodeFinalArrs[placer-(1+NScrapers)][:,:,:] = tempNodeFinalArr #print "M{}: < listening for results".format(rank) #print "M{}: > writing image".format(rank) partial_filename = 'output/mosaic_{}.png'.format(it) FinalImg = Image.fromarray(scipy.array(FinalArr, dtype=scipy.uint8), 'RGB') FinalImg.save(partial_filename) # for fewer output images # Notify gui logger.emit_partial(partial_filename) #print "M{}: < writing image at iter {}".format(rank, it) writepars = pars.copy() del(writepars['savepath']) strrep = '_'.join(['{}{:d}'.format(item, value) for item, value in sorted(writepars.items())]) final_filename = 'output/final{}_{}.png'.format(strrep, int(time.time())) FinalImg.save(final_filename) os.chmod(final_filename, 0744) print "M{}: Final image saved".format(rank) shutil.copy('log', 'output/log_'+strrep) # email result if (data != None): msg = MIMEMultipart() msg['Subject'] = "KU Leuven openbedrijvendag - uw mozaiek" msg['From'] = "SuperPi <*****@*****.**>" msg['To'] = data['email'] fp = open(final_filename, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) s = smtplib.SMTP('mail4.cs.kuleuven.be') s.sendmail('*****@*****.**', [msg['To']], msg.as_string()) s.quit() logger.emit_finished(final_filename) #%% signal completion logger.write('Finished', status=plogger.FINISHED) comm.barrier()
def solve(self, wls): """Isotropic solver. INPUT wls = wavelengths to scan (any asarray-able object). OUTPUT self.DE1, self.DE3 = power reflected and transmitted. NOTE see: Moharam, "Formulation for stable and efficient implementation of the rigorous coupled-wave analysis of binary gratings", JOSA A, 12(5), 1995 Lalanne, "Highly improved convergence of the coupled-wave method for TM polarization", JOSA A, 13(4), 1996 Moharam, "Stable implementation of the rigorous coupled-wave analysis for surface-relief gratings: enhanced trasmittance matrix approach", JOSA A, 12(5), 1995 """ self.wls = S.atleast_1d(wls) LAMBDA = self.LAMBDA n = self.n multilayer = self.multilayer alpha = self.alpha delta = self.delta psi = self.psi phi = self.phi nlayers = len(multilayer) i = S.arange(-n, n + 1) nood = 2 * n + 1 hmax = nood - 1 # grating vector (on the xz plane) # grating on the xy plane K = 2 * pi / LAMBDA * \ S.array([S.sin(phi), 0., S.cos(phi)], dtype=complex) DE1 = S.zeros((nood, self.wls.size)) DE3 = S.zeros_like(DE1) dirk1 = S.array([S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha)]) # usefull matrices I = S.eye(i.size) I2 = S.eye(i.size * 2) ZERO = S.zeros_like(I) X = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex) MTp1 = S.zeros((2 * nood, 2 * nood, nlayers), dtype=complex) MTp2 = S.zeros_like(MTp1) EPS2 = S.zeros(2 * hmax + 1, dtype=complex) EPS21 = S.zeros_like(EPS2) dlt = (i == 0).astype(int) for iwl, wl in enumerate(self.wls): # free space wavevector k = 2 * pi / wl n1 = multilayer[0].mat.n(wl).item() n3 = multilayer[-1].mat.n(wl).item() # incident plane wave wavevector k1 = k * n1 * dirk1 # all the other wavevectors tmp_x = k1[0] - i * K[0] tmp_y = k1[1] * S.ones_like(i) tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n1) k1i = S.r_[[tmp_x], [tmp_y], [tmp_z]] # k2i = S.r_[[k1[0] - i*K[0]], [k1[1] - i * K[1]], [-i * K[2]]] tmp_z = dispersion_relation_ordinary(tmp_x, tmp_y, k, n3) k3i = S.r_[[k1i[0, :]], [k1i[1, :]], [tmp_z]] # aliases for constant wavevectors kx = k1i[0, :] ky = k1[1] # angles of reflection # phi_i = S.arctan2(ky,kx) phi_i = S.arctan2(ky, kx.real) # OKKIO Kx = S.diag(kx / k) Ky = ky / k * I Z1 = S.diag(k1i[2, :] / (k * n1 ** 2)) Y1 = S.diag(k1i[2, :] / k) Z3 = S.diag(k3i[2, :] / (k * n3 ** 2)) Y3 = S.diag(k3i[2, :] / k) # Fc = S.diag(S.cos(phi_i)) fc = S.cos(phi_i) # Fs = S.diag(S.sin(phi_i)) fs = S.sin(phi_i) MR = S.asarray(S.bmat([[I, ZERO], [-1j * Y1, ZERO], [ZERO, I], [ZERO, -1j * Z1]])) MT = S.asarray(S.bmat([[I, ZERO], [1j * Y3, ZERO], [ZERO, I], [ZERO, 1j * Z3]])) # internal layers (grating or layer) X.fill(0.0) MTp1.fill(0.0) MTp2.fill(0.0) for nlayer in range(nlayers - 2, 0, -1): # internal layers layer = multilayer[nlayer] d = layer.thickness EPS2, EPS21 = layer.getEPSFourierCoeffs( wl, n, anisotropic=False) E = toeplitz(EPS2[hmax::-1], EPS2[hmax:]) E1 = toeplitz(EPS21[hmax::-1], EPS21[hmax:]) E11 = inv(E1) # B = S.dot(Kx, linsolve(E,Kx)) - I B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I # A = S.dot(Kx, Kx) - E A = S.diag((kx / k) ** 2) - E # Note: solution bug alfredo # randomizzo Kx un po' a caso finche' cond(A) e' piccolo (<1e10) # soluzione sporca... :-( # per certi kx, l'operatore di helmholtz ha 2 autovalori nulli e A, B # non sono invertibili --> cambio leggermente i kx... ma dovrei invece # trattare separatamente (analiticamente) questi casi if cond(A) > 1e10: warning('BAD CONDITIONING: randomization of kx') while cond(A) > 1e10: Kx = Kx * (1 + 1e-9 * S.rand()) B = kx[:, S.newaxis] / k * linsolve(E, Kx) - I A = S.diag((kx / k) ** 2) - E if S.absolute(K[2] / k) > 1e-10: raise ValueError( 'First Order Helmholtz Operator not implemented, yet!') elif ky == 0 or S.allclose(S.diag(Ky / ky * k), 1): # lalanne # H_U_reduced = S.dot(Ky, Ky) + A H_U_reduced = (ky / k) ** 2 * I + A # H_S_reduced = S.dot(Ky, Ky) + S.dot(Kx, linsolve(E, S.dot(Kx, E11))) - E11 H_S_reduced = (ky / k) ** 2 * I + kx[:, S.newaxis] / k * linsolve(E, kx[:, S.newaxis] / k * E11) - E11 q1, W1 = eig(H_U_reduced) q1 = S.sqrt(q1) q2, W2 = eig(H_S_reduced) q2 = S.sqrt(q2) # boundary conditions # V11 = S.dot(linsolve(A, W1), S.diag(q1)) V11 = linsolve(A, W1) * q1[S.newaxis, :] V12 = (ky / k) * S.dot(linsolve(A, Kx), W2) V21 = (ky / k) * S.dot(linsolve(B, Kx), linsolve(E, W1)) # V22 = S.dot(linsolve(B, W2), S.diag(q2)) V22 = linsolve(B, W2) * q2[S.newaxis, :] # Vss = S.dot(Fc, V11) Vss = fc[:, S.newaxis] * V11 # Wss = S.dot(Fc, W1) + S.dot(Fs, V21) Wss = fc[:, S.newaxis] * W1 + fs[:, S.newaxis] * V21 # Vsp = S.dot(Fc, V12) - S.dot(Fs, W2) Vsp = fc[:, S.newaxis] * V12 - fs[:, S.newaxis] * W2 # Wsp = S.dot(Fs, V22) Wsp = fs[:, S.newaxis] * V22 # Wpp = S.dot(Fc, V22) Wpp = fc[:, S.newaxis] * V22 # Vpp = S.dot(Fc, W2) + S.dot(Fs, V12) Vpp = fc[:, S.newaxis] * W2 + fs[:, S.newaxis] * V12 # Wps = S.dot(Fc, V21) - S.dot(Fs, W1) Wps = fc[:, S.newaxis] * V21 - fs[:, S.newaxis] * W1 # Vps = S.dot(Fs, V11) Vps = fs[:, S.newaxis] * V11 Mc2bar = S.asarray(S.bmat([[Vss, Vsp, Vss, Vsp], [Wss, Wsp, -Wss, -Wsp], [Wps, Wpp, -Wps, -Wpp], [Vps, Vpp, Vps, Vpp]])) x = S.r_[S.exp(-k * q1 * d), S.exp(-k * q2 * d)] # Mc1 = S.dot(Mc2bar, S.diag(S.r_[S.ones_like(x), x])) xx = S.r_[S.ones_like(x), x] Mc1 = Mc2bar * xx[S.newaxis, :] X[:, :, nlayer] = S.diag(x) MTp = linsolve(Mc2bar, MT) MTp1[:, :, nlayer] = MTp[0:2 * nood, :] MTp2 = MTp[2 * nood:, :] MT = S.dot( Mc1, S.r_[ I2, S.dot( MTp2, linsolve( MTp1[ :, :, nlayer], X[ :, :, nlayer]))]) else: ValueError( 'Second Order Helmholtz Operator not implemented, yet!') # M = S.asarray(S.bmat([-MR, MT])) M = S.c_[-MR, MT] b = S.r_[S.sin(psi) * dlt, 1j * S.sin(psi) * n1 * S.cos(alpha) * dlt, -1j * S.cos(psi) * n1 * dlt, S.cos(psi) * S.cos(alpha) * dlt] x = linsolve(M, b) R, T = S.split(x, 2) Rs, Rp = S.split(R, 2) for ii in range(1, nlayers - 1): T = S.dot(linsolve(MTp1[:, :, ii], X[:, :, ii]), T) Ts, Tp = S.split(T, 2) DE1[:, iwl] = (k1i[2, :] / (k1[2])).real * S.absolute(Rs) ** 2 + \ (k1i[2, :] / (k1[2] * n1 ** 2)).real * \ S.absolute(Rp) ** 2 DE3[:, iwl] = (k3i[2, :] / (k1[2])).real * S.absolute(Ts) ** 2 + \ (k3i[2, :] / (k1[2] * n3 ** 2)).real * \ S.absolute(Tp) ** 2 # save the results self.DE1 = DE1 self.DE3 = DE3 return self
def generate_sigma(self): import networkx as nx from scipy.linalg import inv, schur, eig from scipy.sparse import lil_matrix from numpy import asarray_chkfinite, isfinite, inf from aux import SparseBlocks, eigenvector_from_eigenvalue, all_elements_are_unique from scipy import argsort, dot, eye, hstack, vstack, zeros, complex128, split, asarray, diag, array # should be able to turn zplus off, but then i need better eigenvalue comparison E = self.p.E + self.p.zplus Ndim = len(self.p.tuple_canvas_coordinates) block = self.graph.order() / 2 I = eye(block) Zeros = zeros((block, block)) Hlead = nx.to_numpy_matrix(self.graph, nodelist=self.nodelist, dtype=complex128) self.Hlead = Hlead #import pudb; pudb.set_trace() # add 4*self.t0 because the matrix from graph lacks diagonal (no self-loops) try: H00 = asarray_chkfinite(Hlead[:block, :block]) + 4 * self.p.t0 * I self.H00 = H00 except ValueError: print 'H00 contains infs or NaNs' import pudb pudb.set_trace() try: H01 = asarray_chkfinite(Hlead[:block, block:]) self.H01 = H01 except ValueError: print 'H01 contains infs or NaNs' import pudb pudb.set_trace() inv_H01 = inv(H01) while not isfinite(inv_H01).all(): print 'inv_H01 contains infs or NaNs, repeating' inv_H01 = inv(H01) #import pudb; pudb.set_trace() self.inv_H01 = inv_H01 CompanionMatrix_array = vstack( (hstack((Zeros, I)), hstack((dot(-inv_H01, H01.conj().T), dot(inv_H01, E * I - H00))))) if not isfinite(CompanionMatrix_array).all(): print 'CompanionMatrix contains infs or NaNs' import pudb pudb.set_trace() #CompanionMatrix_array =vstack((hstack((dot(inv_H01,E*I-H00),dot(-inv_H01,H01.conj().T))),hstack((I,Zeros)))) # the following 'complex' might be superfluous and only for real input matrices. T, Z, number_sorted = schur(CompanionMatrix_array, sort='iuc') eigenvalues = diag(T) # propagating_eigenvalues = [] # propagating_eigenvectors = [] # for eigenvalue in eigenvalues: # if abs(abs(eigenvalue)-1) < 0.01: # propagating_eigenvalues.append(eigenvalue) # eigenvector = eigenvector_from_eigenvalue(CompanionMatrix_array, eigenvalue) # propagating_eigenvectors.append(eigenvector) # prop_eig_array = array(propagating_eigenvectors).T if not all_elements_are_unique(eigenvalues): print "--------------WARNING!!!!!---------------" print "One or more eigenvalues are identical, please rotate eigenvectors, I don't know how to do that" #v,d = eig(CompanionMatrix_array) #ndx = argsort(v) #S=d[:,ndx] #v=v[ndx] #Sleft,Sright = split(S,2,axis=1) #S4,S3 = split(Sright,2,axis=0) #S2,S1 = split(Sleft,2,axis=0) #S2 =S[:block*self.p.multi,:block*self.p.multi] #S1= S[block*self.p.multi:,:block*self.p.multi] #self.S2 = S2 #self.S1 = S1 #self.S4 = S4 #self.S3 = S3 #print 'S1 shape: ',S1.shape #print 'S2 shape: ',S2.shape # sort eigenvalues and Z according to acending abs(eigenvalue), TODO: do better sorting, now it # depends on luck. sort using the calulated eigenvectors above # sorting_indices = abs(eigenvalues).argsort() #T = T[:,sorting_indices][sorting_indices,:] #Z = Z[:,sorting_indices][sorting_indices,:] Zleft, Zright = split(Z, 2, axis=1) #S4,S3 = split(Sright,2,axis=0) Z11, Z21 = split(Zleft, 2, axis=0) self.Z11 = Z11 self.Z21 = Z21 if self.index == 0: SigmaRet = dot(H01, dot(Z21, inv(Z11))) else: SigmaRet = dot(H01.conj(), dot(Z21, inv(Z11))) self.SigmaRet = SigmaRet print '- SimgaRet (', self.index, ') shape: ', SigmaRet.shape sigma = lil_matrix((self.p.multi * Ndim, self.p.multi * Ndim), dtype=complex128) print '- sigma shape: ', sigma.shape #implement polarization like (for spin up) reshape(-1,2) --> [:,1] = 0 --> reshape(shape(SigmaRet)) if self.index == 0: if 'up' in self.current: print 'Up polarized input' SigmaRet.reshape(-1, 2)[:, 1] = 0 elif 'down' in self.current: print 'Down polarized input' SigmaRet.reshape(-1, 2)[:, 0] = 0 sigma[0:SigmaRet.shape[0], 0:SigmaRet.shape[1]] = SigmaRet elif self.index == 1: sigma[-SigmaRet.shape[0]:, -SigmaRet.shape[1]:] = SigmaRet self.sigma = sigma return sigma
def to_dataframe(cls, network=None, phases=[], join=False, delim=' | '): r""" Convert the Network (and optionally Phase) data to Pandas DataFrames. Parameters ---------- network: OpenPNM Network Object The network containing the data to be stored phases : list of OpenPNM Phase Objects The data on each supplied phase will be added to DataFrame join : boolean If ``False`` (default), two DataFrames are returned with *pore* data in one, and *throat* data in the other. If ``True`` the pore and throat data are combined into a single DataFrame. This can be problematic as it will put NaNs into all the *pore* columns which are shorter than the *throat* columns. Returns ------- Pandas ``DataFrame`` object containing property and label data in each column. If ``join`` was False (default) the two DataFrames are returned i a named tuple, or else a single DataFrame with pore and throat data in the same file, despite the column length being different. """ project, network, phases = cls._parse_args(network=network, phases=phases) # Initialize pore and throat data dictionary using Dict class pdata = Dict.to_dict(network=network, phases=phases, element='pore', interleave=True, flatten=True, categorize_by=['object']) tdata = Dict.to_dict(network=network, phases=phases, element='throat', interleave=True, flatten=True, categorize_by=['object']) pdata = FlatDict(pdata, delimiter=delim) tdata = FlatDict(tdata, delimiter=delim) # Scan data and convert non-1d arrays to multiple columns for key in list(pdata.keys()): if sp.shape(pdata[key]) != (network[0].Np, ): arr = pdata.pop(key) tmp = sp.split(arr, arr.shape[1], axis=1) cols = range(len(tmp)) pdata.update( {key + '[' + str(i) + ']': tmp[i].squeeze() for i in cols}) for key in list(tdata.keys()): if sp.shape(tdata[key]) != (network[0].Nt, ): arr = tdata.pop(key) tmp = sp.split(arr, arr.shape[1], axis=1) cols = range(len(tmp)) tdata.update( {key + '[' + str(i) + ']': tmp[i].squeeze() for i in cols}) # Convert sanitized dictionaries to DataFrames pdata = pd.DataFrame(sanitize_dict(pdata)) tdata = pd.DataFrame(sanitize_dict(tdata)) # Prepare DataFrames to be returned if join: data = tdata.join(other=pdata, how='left') else: nt = namedtuple('dataframes', ('pore', 'throat')) data = nt(pore=pdata, throat=tdata) return data
def transfersigma(self,ind_contact,E): from scipy.linalg import eig,inv from scipy.sparse import lil_matrix from aux import SparseBlocks from scipy import argsort,dot,eye,hstack,vstack,zeros,complex128,asarray,split E= E+self.zplus Ndim = len(self.p.tuple_canvas_coordinates) block=ind_contact.length Hblock = SparseBlocks(self.H,self.block_sizes) self.Hblock = Hblock I=eye(block*self.p.multi) Zeros = zeros((block*self.p.multi,block*self.p.multi)) #if ind_contact.SO is False: # H00 = 4*self.t0*eye(block) -self.t0*eye(block,k=1) -self.t0*eye(block,k=-1) # Hhop = -self.t0*I #no Bfield as of now # inv_Hhop = -1/self.t0*I #no Bfield as of now if ind_contact.index == 0: H00 = asarray(Hblock[0,0].todense()) #H10 = asarray(Hblock[1,0].todense()) H01 = asarray(Hblock[0,1].todense()) inv_H01 = inv(H01) if ind_contact.index == 1: H00 = asarray(Hblock[-1,-1].todense()) #H10 = asarray(Hblock[-1,-2].todense()) H01 = asarray(Hblock[-2,-1].todense()) """indices switch because hopping matrices go the other direction x --> -x, better results this way altough not much difference""" inv_H01 = inv(H01) TransMatrix =vstack((hstack((dot(inv_H01,E*I-H00),dot(-inv_H01,H01.conj().T))),hstack((I,Zeros)))) v,S = eig(TransMatrix) ndx = argsort(abs(v)) S=S[:,ndx] v=v[ndx] self.S=S self.v =v Sleft,Sright = split(S,2,axis=1) S4,S3 = split(Sright,2,axis=0) S2,S1 = split(Sleft,2,axis=0) #S2 =S[:block*self.p.multi,:block*self.p.multi] #S1= S[block*self.p.multi:,:block*self.p.multi] self.S2 = S2 self.S1 = S1 self.S4 = S4 self.S3 = S3 print 'S1 shape: ',S1.shape print 'S2 shape: ',S2.shape if ind_contact.index == 0: dotted = dot(S2,inv(S1)) if ind_contact.index == 1: dotted = dot(S3,inv(S4)) invBracket =inv(E*I-H00-dot(H01,dotted)) SigmaRet=self.t0**2*invBracket if ind_contact.index == 0: self.SigmaRet1 = SigmaRet #temp = zeros((60,60),dtype=complex128) #temp[30:60,30:60] =SigmaRet[:30,:30] #SigmaRet=temp else : self.SigmaRet2 = SigmaRet print 'SigaRet shape: ',SigmaRet.shape sigma = lil_matrix((self.p.multi*Ndim,self.p.multi*Ndim), dtype=complex128) print 'sigma shape: ',sigma.shape if ind_contact.index == 0: sigma[0:SigmaRet.shape[0], 0:SigmaRet.shape[1]] = SigmaRet self.sigma1=sigma elif ind_contact.index == 1: sigma[-SigmaRet.shape[0]:, -SigmaRet.shape[1]:] = SigmaRet self.sigma2=sigma import pudb; pudb.set_trace() return sigma
def solve(self, wls): """Anisotropic solver. INPUT wls = wavelengths to scan (any asarray-able object). OUTPUT self.DEO1, self.DEE1, self.DEO3, self.DEE3 = power reflected and transmitted. """ self.wls = S.atleast_1d(wls) LAMBDA = self.LAMBDA n = self.n multilayer = self.multilayer alpha = self.alpha delta = self.delta psi = self.psi phi = self.phi nlayers = len(multilayer) i = S.arange(-n, n + 1) nood = 2 * n + 1 hmax = nood - 1 DEO1 = S.zeros((nood, self.wls.size)) DEO3 = S.zeros_like(DEO1) DEE1 = S.zeros_like(DEO1) DEE3 = S.zeros_like(DEO1) c1 = np.array([1., 0., 0.]) c3 = np.array([1., 0., 0.]) # grating on the xy plane K = 2 * pi / LAMBDA * np.array( [S.sin(phi), 0., S.cos(phi)], dtype=complex) dirk1 = np.array([ S.sin(alpha) * S.cos(delta), S.sin(alpha) * S.sin(delta), S.cos(alpha) ]) # D polarization vector u = np.array([ S.cos(psi) * S.cos(alpha) * S.cos(delta) - S.sin(psi) * S.sin(delta), S.cos(psi) * S.cos(alpha) * S.sin(delta) + S.sin(psi) * S.cos(delta), -S.cos(psi) * S.sin(alpha), ]) kO1i = S.zeros((3, i.size), dtype=complex) kE1i = S.zeros_like(kO1i) kO3i = S.zeros_like(kO1i) kE3i = S.zeros_like(kO1i) Mp = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex) M = S.zeros((4 * nood, 4 * nood, nlayers), dtype=complex) dlt = (i == 0).astype(int) for iwl, wl in enumerate(self.wls): nO1 = nE1 = multilayer[0].mat.n(wl).item() nO3 = nE3 = multilayer[-1].mat.n(wl).item() # wavevectors k = 2 * pi / wl eps1 = S.diag(S.asarray([nE1, nO1, nO1])**2) eps3 = S.diag(S.asarray([nE3, nO3, nO3])**2) # ordinary wave abskO1 = k * nO1 # abskO3 = k * nO3 # extraordinary wave # abskE1 = k * nO1 *nE1 / S.sqrt(nO1**2 + (nE1**2 - nO1**2) * S.dot(-c1, dirk1)**2) # abskE3 = k * nO3 *nE3 / S.sqrt(nO3**2 + (nE3**2 - nO3**2) * S.dot(-c3, dirk1)**2) k1 = abskO1 * dirk1 kO1i[0, :] = k1[0] - i * K[0] kO1i[1, :] = k1[1] * S.ones_like(i) kO1i[2, :] = -dispersion_relation_ordinary(kO1i[0, :], kO1i[1, :], k, nO1) kE1i[0, :] = kO1i[0, :] kE1i[1, :] = kO1i[1, :] kE1i[2, :] = -dispersion_relation_extraordinary( kE1i[0, :], kE1i[1, :], k, nO1, nE1, c1) kO3i[0, :] = kO1i[0, :] kO3i[1, :] = kO1i[1, :] kO3i[2, :] = dispersion_relation_ordinary(kO3i[0, :], kO3i[1, :], k, nO3) kE3i[0, :] = kO1i[0, :] kE3i[1, :] = kO1i[1, :] kE3i[2, :] = dispersion_relation_extraordinary( kE3i[0, :], kE3i[1, :], k, nO3, nE3, c3) # k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [k1[2] - i * K[2]]] k2i = S.r_[[k1[0] - i * K[0]], [k1[1] - i * K[1]], [-i * K[2]]] # aliases for constant wavevectors kx = kO1i[0, :] # o kE1i(1,;), tanto e' lo stesso ky = k1[1] # matrices I = S.eye(nood, dtype=complex) ZERO = S.zeros((nood, nood), dtype=complex) Kx = S.diag(kx / k) Ky = ky / k * I Kz = S.diag(k2i[2, :] / k) KO1z = S.diag(kO1i[2, :] / k) KE1z = S.diag(kE1i[2, :] / k) KO3z = S.diag(kO3i[2, :] / k) KE3z = S.diag(kE3i[2, :] / k) ARO = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KO1z * eps1[2, 0] BRO = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KO1z * eps1[2, 1] CRO_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KO1z * eps1[2, 2]) ARE = Kx * eps1[0, 0] + Ky * eps1[1, 0] + KE1z * eps1[2, 0] BRE = Kx * eps1[0, 1] + Ky * eps1[1, 1] + KE1z * eps1[2, 1] CRE_1 = inv(Kx * eps1[0, 2] + Ky * eps1[1, 2] + KE1z * eps1[2, 2]) ATO = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KO3z * eps3[2, 0] BTO = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KO3z * eps3[2, 1] CTO_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KO3z * eps3[2, 2]) ATE = Kx * eps3[0, 0] + Ky * eps3[1, 0] + KE3z * eps3[2, 0] BTE = Kx * eps3[0, 1] + Ky * eps3[1, 1] + KE3z * eps3[2, 1] CTE_1 = inv(Kx * eps3[0, 2] + Ky * eps3[1, 2] + KE3z * eps3[2, 2]) DRE = c1[1] * KE1z - c1[2] * Ky ERE = c1[2] * Kx - c1[0] * KE1z FRE = c1[0] * Ky - c1[1] * Kx DTE = c3[1] * KE3z - c3[2] * Ky ETE = c3[2] * Kx - c3[0] * KE3z FTE = c3[0] * Ky - c3[1] * Kx b = S.r_[u[0] * dlt, u[1] * dlt, (k1[1] / k * u[2] - k1[2] / k * u[1]) * dlt, (k1[2] / k * u[0] - k1[0] / k * u[2]) * dlt, ] Ky_CRO_1 = ky / k * CRO_1 Ky_CRE_1 = ky / k * CRE_1 Kx_CRO_1 = kx[:, S.newaxis] / k * CRO_1 Kx_CRE_1 = kx[:, S.newaxis] / k * CRE_1 MR31 = -S.dot(Ky_CRO_1, ARO) MR32 = -S.dot(Ky_CRO_1, BRO) - KO1z MR33 = -S.dot(Ky_CRE_1, ARE) MR34 = -S.dot(Ky_CRE_1, BRE) - KE1z MR41 = S.dot(Kx_CRO_1, ARO) + KO1z MR42 = S.dot(Kx_CRO_1, BRO) MR43 = S.dot(Kx_CRE_1, ARE) + KE1z MR44 = S.dot(Kx_CRE_1, BRE) MR = S.asarray( S.bmat([ [I, ZERO, I, ZERO], [ZERO, I, ZERO, I], [MR31, MR32, MR33, MR34], [MR41, MR42, MR43, MR44], ])) Ky_CTO_1 = ky / k * CTO_1 Ky_CTE_1 = ky / k * CTE_1 Kx_CTO_1 = kx[:, S.newaxis] / k * CTO_1 Kx_CTE_1 = kx[:, S.newaxis] / k * CTE_1 MT31 = -S.dot(Ky_CTO_1, ATO) MT32 = -S.dot(Ky_CTO_1, BTO) - KO3z MT33 = -S.dot(Ky_CTE_1, ATE) MT34 = -S.dot(Ky_CTE_1, BTE) - KE3z MT41 = S.dot(Kx_CTO_1, ATO) + KO3z MT42 = S.dot(Kx_CTO_1, BTO) MT43 = S.dot(Kx_CTE_1, ATE) + KE3z MT44 = S.dot(Kx_CTE_1, BTE) MT = S.asarray( S.bmat([ [I, ZERO, I, ZERO], [ZERO, I, ZERO, I], [MT31, MT32, MT33, MT34], [MT41, MT42, MT43, MT44], ])) Mp.fill(0.0) M.fill(0.0) for nlayer in range(nlayers - 2, 0, -1): # internal layers layer = multilayer[nlayer] thickness = layer.thickness EPS2, EPS21 = layer.getEPSFourierCoeffs(wl, n, anisotropic=True) # Exx = S.squeeze(EPS2[0, 0, :]) # Exx = toeplitz(S.flipud(Exx[0:hmax + 1]), Exx[hmax:]) Exy = S.squeeze(EPS2[0, 1, :]) Exy = toeplitz(S.flipud(Exy[0:hmax + 1]), Exy[hmax:]) Exz = S.squeeze(EPS2[0, 2, :]) Exz = toeplitz(S.flipud(Exz[0:hmax + 1]), Exz[hmax:]) Eyx = S.squeeze(EPS2[1, 0, :]) Eyx = toeplitz(S.flipud(Eyx[0:hmax + 1]), Eyx[hmax:]) Eyy = S.squeeze(EPS2[1, 1, :]) Eyy = toeplitz(S.flipud(Eyy[0:hmax + 1]), Eyy[hmax:]) Eyz = S.squeeze(EPS2[1, 2, :]) Eyz = toeplitz(S.flipud(Eyz[0:hmax + 1]), Eyz[hmax:]) Ezx = S.squeeze(EPS2[2, 0, :]) Ezx = toeplitz(S.flipud(Ezx[0:hmax + 1]), Ezx[hmax:]) Ezy = S.squeeze(EPS2[2, 1, :]) Ezy = toeplitz(S.flipud(Ezy[0:hmax + 1]), Ezy[hmax:]) Ezz = S.squeeze(EPS2[2, 2, :]) Ezz = toeplitz(S.flipud(Ezz[0:hmax + 1]), Ezz[hmax:]) Exx_1 = S.squeeze(EPS21[0, 0, :]) Exx_1 = toeplitz(S.flipud(Exx_1[0:hmax + 1]), Exx_1[hmax:]) Exx_1_1 = inv(Exx_1) # lalanne Ezz_1 = inv(Ezz) Ky_Ezz_1 = ky / k * Ezz_1 Kx_Ezz_1 = kx[:, S.newaxis] / k * Ezz_1 Exz_Ezz_1 = S.dot(Exz, Ezz_1) Eyz_Ezz_1 = S.dot(Eyz, Ezz_1) H11 = 1j * S.dot(Ky_Ezz_1, Ezy) H12 = 1j * S.dot(Ky_Ezz_1, Ezx) H13 = S.dot(Ky_Ezz_1, Kx) H14 = I - S.dot(Ky_Ezz_1, Ky) H21 = 1j * S.dot(Kx_Ezz_1, Ezy) H22 = 1j * S.dot(Kx_Ezz_1, Ezx) H23 = S.dot(Kx_Ezz_1, Kx) - I H24 = -S.dot(Kx_Ezz_1, Ky) H31 = S.dot(Kx, Ky) + Exy - S.dot(Exz_Ezz_1, Ezy) H32 = Exx_1_1 - S.dot(Ky, Ky) - S.dot(Exz_Ezz_1, Ezx) H33 = 1j * S.dot(Exz_Ezz_1, Kx) H34 = -1j * S.dot(Exz_Ezz_1, Ky) H41 = S.dot(Kx, Kx) - Eyy + S.dot(Eyz_Ezz_1, Ezy) H42 = -S.dot(Kx, Ky) - Eyx + S.dot(Eyz_Ezz_1, Ezx) H43 = -1j * S.dot(Eyz_Ezz_1, Kx) H44 = 1j * S.dot(Eyz_Ezz_1, Ky) H = 1j * S.diag(S.repeat(S.diag(Kz), 4)) + S.asarray( S.bmat([ [H11, H12, H13, H14], [H21, H22, H23, H24], [H31, H32, H33, H34], [H41, H42, H43, H44], ])) q, W = eig(H) W1, W2, W3, W4 = S.split(W, 4) # # boundary conditions # # x = [R T] # R = [ROx ROy REx REy] # T = [TOx TOy TEx TEy] # b + MR.R = M1p.c # M1.c = M2p.c # ... # ML.c = MT.T # therefore: b + MR.R = (M1p.M1^-1.M2p.M2^-1. ...).MT.T # missing equations from (46)..(49) in glytsis_rigorous # [b] = [-MR Mtot.MT] [R] # [0] [...........] [T] z = S.zeros_like(q) z[S.where(q.real > 0)] = -thickness D = S.exp(k * q * z) Sy0 = W1 * D[S.newaxis, :] Sx0 = W2 * D[S.newaxis, :] Uy0 = W3 * D[S.newaxis, :] Ux0 = W4 * D[S.newaxis, :] z = thickness * S.ones_like(q) z[S.where(q.real > 0)] = 0 D = S.exp(k * q * z) D1 = S.exp(-1j * k2i[2, :] * thickness) Syd = D1[:, S.newaxis] * W1 * D[S.newaxis, :] Sxd = D1[:, S.newaxis] * W2 * D[S.newaxis, :] Uyd = D1[:, S.newaxis] * W3 * D[S.newaxis, :] Uxd = D1[:, S.newaxis] * W4 * D[S.newaxis, :] Mp[:, :, nlayer] = S.r_[Sx0, Sy0, -1j * Ux0, -1j * Uy0] M[:, :, nlayer] = S.r_[Sxd, Syd, -1j * Uxd, -1j * Uyd] Mtot = S.eye(4 * nood, dtype=complex) for nlayer in range(1, nlayers - 1): Mtot = S.dot(S.dot(Mtot, Mp[:, :, nlayer]), inv(M[:, :, nlayer])) BC_b = S.r_[b, S.zeros_like(b)] BC_A1 = S.c_[-MR, S.dot(Mtot, MT)] BC_A2 = S.asarray( S.bmat([ [ (c1[0] * I - c1[2] * S.dot(CRO_1, ARO)), (c1[1] * I - c1[2] * S.dot(CRO_1, BRO)), ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ], [ ZERO, ZERO, (DRE - S.dot(S.dot(FRE, CRE_1), ARE)), (ERE - S.dot(S.dot(FRE, CRE_1), BRE)), ZERO, ZERO, ZERO, ZERO, ], [ ZERO, ZERO, ZERO, ZERO, (c3[0] * I - c3[2] * S.dot(CTO_1, ATO)), (c3[1] * I - c3[2] * S.dot(CTO_1, BTO)), ZERO, ZERO, ], [ ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, (DTE - S.dot(S.dot(FTE, CTE_1), ATE)), (ETE - S.dot(S.dot(FTE, CTE_1), BTE)), ], ])) BC_A = S.r_[BC_A1, BC_A2] x = linsolve(BC_A, BC_b) ROx, ROy, REx, REy, TOx, TOy, TEx, TEy = S.split(x, 8) ROz = -S.dot(CRO_1, (S.dot(ARO, ROx) + S.dot(BRO, ROy))) REz = -S.dot(CRE_1, (S.dot(ARE, REx) + S.dot(BRE, REy))) TOz = -S.dot(CTO_1, (S.dot(ATO, TOx) + S.dot(BTO, TOy))) TEz = -S.dot(CTE_1, (S.dot(ATE, TEx) + S.dot(BTE, TEy))) denom = (k1[2] - S.dot(u, k1) * u[2]).real DEO1[:, iwl] = (-( (S.absolute(ROx)**2 + S.absolute(ROy)**2 + S.absolute(ROz)**2) * S.conj(kO1i[2, :]) - (ROx * kO1i[0, :] + ROy * kO1i[1, :] + ROz * kO1i[2, :]) * S.conj(ROz)).real / denom) DEE1[:, iwl] = (-( (S.absolute(REx)**2 + S.absolute(REy)**2 + S.absolute(REz)**2) * S.conj(kE1i[2, :]) - (REx * kE1i[0, :] + REy * kE1i[1, :] + REz * kE1i[2, :]) * S.conj(REz)).real / denom) DEO3[:, iwl] = ( (S.absolute(TOx)**2 + S.absolute(TOy)**2 + S.absolute(TOz)**2) * S.conj(kO3i[2, :]) - (TOx * kO3i[0, :] + TOy * kO3i[1, :] + TOz * kO3i[2, :]) * S.conj(TOz)).real / denom DEE3[:, iwl] = ( (S.absolute(TEx)**2 + S.absolute(TEy)**2 + S.absolute(TEz)**2) * S.conj(kE3i[2, :]) - (TEx * kE3i[0, :] + TEy * kE3i[1, :] + TEz * kE3i[2, :]) * S.conj(TEz)).real / denom # save the results self.DEO1 = DEO1 self.DEE1 = DEE1 self.DEO3 = DEO3 self.DEE3 = DEE3 return self
p=8 lista=[] for i in range(1,p+1): lista.append(i) k=10 Y=sy.array(y) Y=sy.arange(Y.shape[0]) test=sy.array(sy.split(Y,len(x)/k)) medias=[] for s in lista: traierror=[] for i in test: trainingy=sy.array(y) trainingx=sy.array(x) trainingy=sy.delete(trainingy,i) trainingx=sy.delete(trainingx,i)