def correl_single_window(sbwA, sbwB): """sbwA and sbwB are obtained as subwindowsA[:,n,:,:], with n marching through all the windows. Indexes - 0 -> epochs 1 -> subwindows 2 -> start/stop """ N0 = sbwA.shape[0] N1 = sbwA.shape[1] spk_countA = pylab.zeros((N0,N1)) spk_countB = pylab.zeros((N0,N1)) for n in xrange(N0): #Epochs for m in xrange(N1): #subwindows spk_countA[n,m] = sbwA[n,m,1] - sbwA[n,m,0] spk_countB[n,m] = sbwB[n,m,1] - sbwB[n,m,0] spk_countA = spk_countA.flatten() - spk_countA.mean() spk_countB = spk_countB.flatten() - spk_countB.mean() R = pylab.corrcoef(spk_countA, spk_countB) if R.size: r = R[0,1] else: r = 0 return r
def _get_angles(steps,track_length): angles = pl.zeros(track_length-2) polar = pl.zeros(pl.shape(steps)) for i in range(track_length-1): polar[i,0] = pl.norm(steps[i,:]) polar[i,1] = pl.arctan(steps[i,0]/steps[i,1]) if pl.isnan( polar[i,1]): polar[i,1] = 0 if (steps[i,0] >= 0): if (steps[i,1] >= 0): pass elif (steps[i,1] < 0): polar[i,1] += 2.*pl.pi elif (steps[i,0] < 0): if (steps[i,1] >= 0): polar[i,1] += pl.pi elif (steps[i,1] < 0): polar[i,1] += pl.pi for i in range(track_length-2): angles[i] = polar[i+1,1] - polar[i,1] return angles
def spikefano(timestamps, start_time=0, zero_times=0, end_time=None, window_len=.1, subwindow_len=None): """Given the time stamps compute the fano factor with a jumping window. Inputs: timestamps - the spike timestamps window_len - length of window to look at ff (same units as timestamps). One window gets us one ff estimate The fano factor is the LS fit of fano_windows (variance,mean) points subwindow_len - length of one spike count computation window Outputs: t - time array ff - fano factors """ window_edges, windows, subwindows = window_spike_train(timestamps, start_time, zero_times, end_time, window_len=window_len, subwindow_len=subwindow_len) t = pylab.zeros(windows.shape[1]) ff = pylab.zeros(windows.shape[1]) for n in xrange(windows.shape[1]): spk_count = pylab.zeros(subwindows.shape[1]*subwindows.shape[2]) for m in xrange(subwindows.shape[0]):#Epochs for l in xrange(subwindows.shape[2]):#Subwindows #FF computation sbw0 = subwindows[m,n,l,0] sbw1 = subwindows[m,n,l,1] spk_count[m*subwindows.shape[2]+l] = sbw1 - sbw0 mean = spk_count.mean() std = spk_count.std() ff[n] = std**2/mean t[n] = window_len * (n+.5) return t, ff
def SCpm(SC_0=SC_0, i=i, r=r, f=f, m_all_cause=m_all_cause, age_mesh=dm.get_param_age_mesh()): SC = pl.zeros([2, len(age_mesh)]) p = pl.zeros(len(age_mesh)) m = pl.zeros(len(age_mesh)) SC[:, 0] = SC_0 p[0] = SC_0[1] / (SC_0[0] + SC_0[1]) m[0] = dismod3.utils.trim( m_all_cause[age_mesh[0]] - f[age_mesh[0]] * p[0], 0.1 * m_all_cause[age_mesh[0]], 1 - dismod3.settings.NEARLY_ZERO, ) # trim m[0] to avoid numerical instability for ii, a in enumerate(age_mesh[:-1]): A = pl.array([[-i[a] - m[ii], r[a]], [i[a], -r[a] - m[ii] - f[a]]]) * (age_mesh[ii + 1] - age_mesh[ii]) SC[:, ii + 1] = pl.dot(scipy.linalg.expm(A), SC[:, ii]) p[ii + 1] = dismod3.utils.trim( SC[1, ii + 1] / (SC[0, ii + 1] + SC[1, ii + 1]), dismod3.settings.NEARLY_ZERO, 1 - dismod3.settings.NEARLY_ZERO, ) m[ii + 1] = dismod3.utils.trim( m_all_cause[age_mesh[ii + 1]] - f[age_mesh[ii + 1]] * p[ii + 1], 0.1 * m_all_cause[age_mesh[ii + 1]], pl.inf, ) SCpm = pl.zeros([4, len(age_mesh)]) SCpm[0:2, :] = SC SCpm[2, :] = p SCpm[3, :] = m return SCpm
def grad(self,data,weightcost): grad = zeros(0) if type(data)!=type([]): data = [data] numcases = len(data) numscoretypes = len(self.scorefuncs) if not type(weightcost) == type([]): weightcost = [weightcost] * numscoretypes posgrad = [None]*numscoretypes neggrad = [None]*numscoretypes for k in range(numscoretypes): if isscalar(weightcost[k]): weightcost[k] = \ array([weightcost[k]]*len(self.scorefuncs[k].params)) posgrad[k] = zeros(self.scorefuncs[k].params.shape,dtype=float) neggrad[k] = zeros(self.scorefuncs[k].params.shape,dtype=float) for i in range(numcases): poscliques = self.posdata(data[i]) negcliques = self.negdata(data[i]) for k in range(numscoretypes): for posclique in poscliques[k]: posgrad[k] += self.scorefuncs[k].grad(*posclique) if self.normalizeacrosscliques: posgrad[k] = posgrad[k]/double(len(poscliques[k])) for weighting, negclique in negcliques[k]: for w, neginst in zip(weighting,negclique): neggrad[k] += w * self.scorefuncs[k].grad(*neginst) if self.normalizeacrosscliques: neggrad[k] = neggrad[k]/double(len(poscliques[k])) for k in range(numscoretypes): grad = concatenate((grad,(posgrad[k]-neggrad[k])/double(numcases)\ -weightcost[k]*self.scorefuncs[k].params)) return -grad
def jetWoGn(reverse=False): """ jetWoGn(reverse=False) - returning a colormap similar to cm.jet, but without green. if reverse=True, the map starts with red instead of blue. """ m=18 # magic number, which works fine m0=pylab.floor(m*0.0) m1=pylab.floor(m*0.2) m2=pylab.floor(m*0.2) m3=pylab.floor(m/2)-m2-m1 b_ = pylab.hstack( (0.4*pylab.arange(m1)/(m1-1.)+0.6, pylab.ones((m2+m3,)) ) ) g_ = pylab.hstack( (pylab.zeros((m1,)),pylab.arange(m2)/(m2-1.),pylab.ones((m3,))) ) r_ = pylab.hstack( (pylab.zeros((m1,)),pylab.zeros((m2,)),pylab.arange(m3)/(m3-1.))) r = pylab.hstack((r_,pylab.flipud(b_))) g = pylab.hstack((g_,pylab.flipud(g_))) b = pylab.hstack((b_,pylab.flipud(r_))) if reverse: r = pylab.flipud(r) g = pylab.flipud(g) b = pylab.flipud(b) ra = pylab.linspace(0.0,1.0,m) cdict = {'red': zip(ra,r,r), 'green': zip(ra,g,g), 'blue': zip(ra,b,b)} return LinearSegmentedColormap('new_RdBl',cdict,256)
def homog2D(xPrime, x): """ Compute the 3x3 homography matrix mapping a set of N 2D homogeneous points (3xN) to another set (3xN) """ numPoints = xPrime.shape[1] assert numPoints >= 4 A = None for i in range(0, numPoints): xiPrime = xPrime[:, i] xi = x[:, i] Ai_row0 = pl.concatenate((pl.zeros(3), -xiPrime[2] * xi, xiPrime[1] * xi)) Ai_row1 = pl.concatenate((xiPrime[2] * xi, pl.zeros(3), -xiPrime[0] * xi)) Ai = pl.row_stack((Ai_row0, Ai_row1)) if A is None: A = Ai else: A = pl.vstack((A, Ai)) U, S, V = pl.svd(A) V = V.T h = V[:, -1] H = pl.reshape(h, (3, 3)) return H
def homog3D(points2d, points3d): """ Compute a matrix relating homogeneous 3D points (4xN) to homogeneous 2D points (3xN) Not sure why anyone would do this. Note that the returned transformation *NOT* an isometry. But it's here... so deal with it. """ numPoints = points2d.shape[1] assert numPoints >= 4 A = None for i in range(0, numPoints): xiPrime = points2d[:, i] xi = points3d[:, i] Ai_row0 = pl.concatenate((pl.zeros(4), -xiPrime[2] * xi, xiPrime[1] * xi)) Ai_row1 = pl.concatenate((xiPrime[2] * xi, pl.zeros(4), -xiPrime[0] * xi)) Ai = pl.row_stack((Ai_row0, Ai_row1)) if A is None: A = Ai else: A = pl.vstack((A, Ai)) U, S, V = pl.svd(A) V = V.T h = V[:, -1] P = pl.reshape(h, (3, 4)) return P
def getMatrix(AllData): # create matrices for all the data numQs = len(AllData.keys()) subjects = 12 #len(AllData[1]['RT']) correct = np.array(py.zeros([numQs, subjects])) confA = np.array(py.zeros([numQs, subjects])) confB = np.array(py.zeros([numQs, subjects])) RTs = np.array(py.zeros([numQs, subjects])) #print(AllData) for i in xrange(subjects): # rows for j in xrange(1,17): # columns correct[j-1,i] = AllData[j]['correct'][i] for i in xrange(subjects): for j in xrange(1,17): confA[j-1,i] = AllData[j]['confA'][i] for i in xrange(subjects): for j in xrange(1,17): confB[j-1,i] = AllData[j]['confB'][i] for i in xrange(subjects): for j in xrange(1,17): RTs[j-1,i] = AllData[j]['RT'][i] print(py.shape(correct), py.shape(confA), py.shape(confB), py.shape(RTs)) return correct, confA, confB, RTs
def beat_track(x, feature=LogFrequencySpectrum, **kwargs): """ Scheirer beat tracker. Use output of comb filter bank on filterbank sub-bands to estimate tempo, and comb filter state to track beats. inputs: x - the audio signal or filename to analyze feature - the feature class to use [LogFrequencySpectrum] **kwargs - parameters to the feature extractor [nbpo=1, nhop=441] outputs: z - per-tempo comb filter summed outputs tempos - the range of tempos in z D - the differentiated half-wave rectified octave-band filterbank outputs """ kwargs.setdefault('nhop', 441) kwargs.setdefault('nbpo', 1) F = feature(x, **kwargs) frame_rate = F.sample_rate / float(F.nhop) D = diff(F.X, axis=1) D[where(D < 0)] = 0 tempos = range(40, 200, 4) z = zeros((len(tempos), D.shape[0])) for i, bpm in enumerate(tempos): # loop over tempos to test t = int(round(frame_rate * 60. / bpm)) # num frames per beat alpha = 0.5**(2.0/t) b = [1 - alpha] a = zeros(t) a[0] = 1.0 a[-1] = alpha z[i, :] = lfilter(b, a, D).sum(1) # filter and sum sub-band onsets return z, tempos, D
def collapse(self): """ SpectrumImage.collapse(), collapses a spectrum image to a spectrum. Takes a spectrum image, averages the background regions and subtracts them from the data regions. The output is a single spectrum as the method assumes all data regions represent the same data. The wavelength list is generated from a given start and end value (assumed to be in nm). Returns the data spectrum. """ try: wavelengths = pylab.linspace(self.start, self.end, self.image.shape[not self.waveaxis]) except TypeError: print 'The starting and ending wavelengths must be specified.' background = pylab.zeros(len(wavelengths)) backgroundlines = 0 data = pylab.zeros(len(wavelengths)) datalines = 0 for region in self.regions: if region['group'] is 0: backgroundlines += region['max'] - region['min'] background += self.image[region['min']:region['max'] + 1, :]\ .sum(axis=self.waveaxis) else: datalines += region['max'] - region['min'] data += self.image[region['min']:region['max'] + 1, :]\ .sum(axis=self.waveaxis) background = [sum/backgroundlines for sum in background] data = [sum/datalines for sum in data] corrected = pylab.array(data) - pylab.array(background) output = Spectrum(list(wavelengths), list(corrected)) return output
def Mesh(self): ''' Generates mesh output: node coodinates: xy connectivity information: element ''' # generate node coodinates: x and y xy = py.zeros(((self.N+1)**2,2)) for k in range (0,self.N+1): for j in range (0,self.N+1): #equations for x and y coordinate from handout x=(self.a+(self.b-self.a)/self.N*k)*py.cos(py.pi*j/2/self.N) y=(self.a+(self.b-self.a)/self.N*k)*py.sin(py.pi*j/2/self.N) xy[j+k*(self.N+1)]=[float(x),float(y)] self.xy = xy # connectivity information: element element = py.zeros((self.N**2*2,3), int) m=0 for i in range (0,(self.N+1)*self.N): if (i+1)%(self.N+1) !=0: #define elements, two at a time element[m]=[i,i+self.N+1,i+1] element[m+1]=[i+self.N+1,i+self.N+2,i+1] m+=2 self.element = element if self.debug: print '\n', 'in mesh: nodes','\n', xy print 'elements', '\n',element
def Dirichlet_BC(self): ''' Apply grounding conditions for i-th DOF by making K[i,:]and K[:,i] zero and K[i,i] = 1. Also i-th load is made zero. ''' # Copy Global Stiffness, Global Load and number of nodes along each polar coordinate K = self.k_global l = self.load n = self.N+1 if self.debug: print '\n','\n','Dirichlet_BC', K, '\n','\n','\n load', l #iteratively apply boundary conditions on all the grounded degrees of freedom for i in range(0,n): if self.debug: print '\n every iteration' , 2*n*i+1, 2*n*(i+1)-2 #Y_displacement = 0 for nodes on X axis K[2*n*i+1,:] = py.zeros((1,self.n_nodes*2)) K[:,2*n*i+1] = py.zeros((1,self.n_nodes*2)) K[2*n*i+1,2*n*i+1] = 1.0 l[2*n*i+1] = 0.0 #X_displacement = 0 for nodes on Y axis K[2*n*(i+1)-2,:] = py.zeros((1,self.n_nodes*2)) K[:,2*n*(i+1)-2] = py.zeros((1,self.n_nodes*2)) K[2*n*(i+1)-2,2*n*(i+1)-2] = 1.0 l[2*n*(i+1)-2] = 0.0 self.k_global = K # copy new global self.load = l # copy new load if self.debug: print '\n','Dirichlet_BC','\n', K, '\n','\n','\n load', l
def read_doscar(self, fname="DOSCAR"): """Read a VASP DOSCAR file.""" f = open(fname) natoms = int(f.readline().split()[0]) [f.readline() for n in range(4)] # Skip next 4 lines. dos = [] for na in xrange(natoms + 1): try: line = f.readline() if line == "": raise Exception except Exception, e: errstr = ( "Failed reading " + str(na) + ":th DOS block, probably " + "this DOSCAR is from some old version of VASP that " + "doesn't " + "first produce a block with integrated DOS. Inserting " + "empty 0:th block." ) sys.stderr.write(errstr) dos.insert(0, pl.zeros((ndos, dos[1].shape[1]))) continue try: ndos = int(line.split()[2]) except: print "Error, line is: " + line + "ENDLINE" line = f.readline().split() cdos = pl.zeros((ndos, len(line))) cdos[0] = pl.array(line) for nd in xrange(1, ndos): line = f.readline().split() cdos[nd] = pl.array(line) dos.append(cdos)
def makebins(im,numbins): # returns the image binned into phase bins # phase2 contains sorted DNO phases # number in each bin im = pl.array(im) num = pl.zeros(numbins,dtype='Float64') #print im.shape[1] imnew = pl.zeros((numbins,im.shape[1]),dtype='Float64') bins = pl.arange(0.0,1.0,1.0/numbins) #print bins # sum spectra that falls into the same phase bin. for i in range(len(phase2)): #print phase2[i] gt = phase2[i] >= bins lt = phase2[i] < bins + 1.0/numbins #print lt*gt imnew[lt*gt] += im[i] num[lt*gt] += 1 # divide by number in each bin to take average for i in range(len(num)): print num[i], imnew[i,:].sum() imnew[i,:] /= num[i] return imnew,num
def Global_Stiffness(self): ''' Generates Global Stiffness Matrix for the plane structure ''' elem = self.element; B = py.zeros((6,6)) for i in range (0,py.size(elem,0)): #for each element find the stifness matrix K = py.zeros((self.n_nodes*2,self.n_nodes*2)) el = elem[i] #nodes formatted for input [node1, node2, node3] = el; node1x = 2*(node1-1);node2x = 2*(node2-1);node3x = 2*(node3-1); node1y = 2*(node1-1)+1;node2y = 2*(node2-1)+1;node3y = 2*(node3-1)+1; #Area, Strain Matrix and E Matrix multiplied to get element stiffness [J,B] = self.B(el) local_k =0.5*abs(J)*py.dot(py.transpose(B),py.dot(self.E_matrix,B)) if self.debug: print 'K for elem', el, '\n', local_k #Element K-Matrix converted into Global K-Matrix format K[py.ix_([node1x,node1y,node2x,node2y,node3x,node3y],[node1x,node1y,node2x,node2y,node3x,node3y])] = K[py.ix_([node1x,node1y,node2x,node2y,node3x,node3y],[node1x,node1y,node2x,node2y,node3x,node3y])]+local_k #Adding contibution into Global Stiffness self.k_global = self.k_global + K if self.debug: print 'Global Stiffness','\n', self.k_global
def estimate_kernel(self, X, P, M): """estimate the ide model's kernel weights from data stored in the ide object""" # form Xi variables Xi_0 = pb.zeros([self.model.nx, self.model.nx]) Xi_1 = pb.zeros([self.model.nx, self.model.nx]) for t in range(1, len(X)): Xi_0 += pb.dot(X[t - 1, :].reshape(self.model.nx, 1), X[t, :].reshape(self.model.nx, 1).T) + M[ t, : ].reshape(self.model.nx, self.model.nx) Xi_1 += pb.dot(X[t - 1, :].reshape(self.model.nx, 1), X[t - 1, :].reshape(self.model.nx, 1).T) + P[ t - 1, : ].reshape(self.model.nx, self.model.nx) # form Upsilon and upsilons Upsilon = pb.zeros([self.model.ntheta, self.model.ntheta]) upsilon0 = pb.zeros([1, self.model.ntheta]) upsilon1 = pb.zeros([1, self.model.ntheta]) for i in range(self.model.nx): for j in range(self.model.nx): Upsilon += Xi_1[i, j] * self.model.Delta_Upsilon[j, i] upsilon0 += Xi_0[i, j] * self.model.Delta_upsilon[j, i] upsilon1 += Xi_1[i, j] * self.model.Delta_upsilon[j, i] upsilon1 = upsilon1 * self.model.xi Upsilon = Upsilon * self.model.Ts * self.model.varsigma weights = pb.dot(pb.inv(Upsilon.T), upsilon0.T - upsilon1.T) return weights
def sample(self, T, g, g0=None): if g0==None: g0 = g v, h = self.v, self.h VH, HH, b_init = self V = zeros((T, v)) H = zeros((T, h)) B = zeros((T, h)) VH_t = 1*VH VH_t[2] = VH[2] + b_init V[[0]], H_t_stoch = rbm.sample(VH_t, g0, 1, self.vis_gauss) H[[0]] = sigmoid(VH_t * V[[0]]) if self.vis_gauss: V[[0]] = VH_t.T() * H_t_stoch else: V[[0]] = sigmoid(VH_t.T() * H_t_stoch) for t in range(1, T): B[[t]] = HH*H[[t-1]] VH_t[2] = VH[2] + B[t] V[[t]], H_t_stoch = rbm.sample(VH_t, g, 1, self.vis_gauss) H[[t]] = sigmoid(VH_t * V[[t]]) if self.vis_gauss: V[[t]] = VH_t.T() * H_t_stoch else: V[[t]] = sigmoid(VH_t.T() * H_t_stoch) return V
def _stft(self): if not self._have_x: print "Error: You need to load a sound file first: use self.load_audio('filename.wav')" return False fp = self._check_feature_params() num_frames = len(self.x) self.STFT = P.zeros((self.nfft/2+1, num_frames), dtype='complex') self.win = P.ones(self.wfft) if self.window=='rect' else P.np.sqrt(P.hanning(self.wfft)) x = P.zeros(self.wfft) buf_frames = 0 for k, nex in enumerate(self.x): x = self._shift_insert(x, nex, self.nhop) if self.nhop >= self.wfft - k*self.nhop : # align buffer on start of audio self.STFT[:,k-buf_frames]=P.rfft(self.win*x, self.nfft).T else: buf_frames+=1 self.STFT = self.STFT / self.nfft self._fftfrqs = P.arange(0,self.nfft/2+1) * self.sample_rate/float(self.nfft) self._have_stft=True if self.verbosity: print "Extracted STFT: nfft=%d, hop=%d" %(self.nfft, self.nhop) self.inverse=self._istftm self.X = abs(self.STFT) if not self.magnitude: self.X = self.X**2 return True
def sample(self, model, evidence): g = evidence['g'] h = evidence['h'] C = evidence['C'] z = evidence['z'] shot_id = evidence['shot_id'] noise_proportion = evidence['noise_proportion'] observation_var_g = evidence['observation_var_g'] observation_var_h = evidence['observation_var_h'] canopy_cover = model.known_params['canopy_cover'] z_min = model.known_params['z_min'] z_max = model.known_params['z_max'] prior_p = model.hyper_params['T']['p'] N = len(z) T = zeros(N) noise_rv = stats.uniform(z_min, z_max - z_min) min_index = min(z.index) for i in shot_id.index: l = zeros(3) index = i-min_index shot_index = shot_id[i]-min(shot_id) l[0] = noise_proportion*noise_rv.pdf(z[i]) g_norm = stats.norm(g[shot_index], sqrt(observation_var_g)) C_i = canopy_cover[C[shot_index]] l[1] = (1-noise_proportion)*(1-C_i)*g_norm.pdf(z[i]) h_norm = stats.norm(h[shot_index] + g[shot_index], sqrt(observation_var_h)) if z[i] > g[shot_index]+3: l[2] = (1-noise_proportion)*(C_i)*h_norm.pdf(z[i]) p = l/sum(l) T[index] = Categorical(p).rvs() return T
def sample(self, T, g, g0=None): if g0==None: g0 = g v, h = self.v, self.h VH, HH, b_init = self V = zeros((T, v)) H = zeros((T, h)) B = zeros((T, h)) VH_t = 1*VH VH_t[2] = VH[2] + b_init V[[0]], H[[0]] = rbm.sample(VH_t, g0, 1, self.vis_gauss) ## mean-fieldize the output: if self.vis_gauss: V[[0]] = VH_t.T() * H[[0]] else: V[[0]] = sigmoid(VH_t.T() * H[[0]]) for t in range(1, T): B[[t]] = HH*H[[t-1]] VH_t[2] = VH[2] + B[t] V[[t]], H[[t]] = rbm.sample(VH_t, g, 1, self.vis_gauss) ## mean-field-ize the output. if self.vis_gauss: V[[t]] = VH_t.T() * H[[t]] else: V[[t]] = sigmoid(VH_t.T() * H[[t]]) return V
def enthalpy(tau,delta,ni,ti,vi,ui,R,ho,so,rho_c,Tc,n_ideal_gas_terms_pow,n_ideal_gas_terms_exp,To,rho_o,N_i,t_i,d_i,p_i,phi_i,Beta_i,gamma_i,D_i,n_power_terms,n_gaussian_terms,n_critical_terms,RES_a,RES_b,RES_B,RES_C,RES_D,RES_A,M_amu,ideal_n,ideal_gamma,ideal_eqn_type): from helmholtz_functions.ideal_helmholtz_energy_dtau_from_Cp_o_over_R import ideal_helmholtz_energy_dtau_from_Cp_o_over_R from helmholtz_functions.d_alpha_d_tau import d_alpha_d_tau from helmholtz_functions.d_alpha_d_delta import d_alpha_d_delta from helmholtz_functions.ideal_helmholtz_from_coef_dtau import ideal_helmholtz_from_coef_dtau from pylab import zeros dalpha_tau=zeros(len(tau)) dalpha_delta=zeros(len(tau)) dalpha_o=zeros(len(tau)) #M_H2=2.01594 T=Tc/tau if(ideal_eqn_type=='Cp'): for i in range(0,len(tau)): dalpha_o[i]=ideal_helmholtz_energy_dtau_from_Cp_o_over_R(ni,ti,vi,ui,R,ho,so,rho_c/M_amu,Tc,tau[i],delta[i],n_ideal_gas_terms_pow,n_ideal_gas_terms_exp,To,rho_o) if(ideal_eqn_type=='Coef'): for i in range(0,len(tau)): dalpha_o[i]=ideal_helmholtz_from_coef_dtau(delta[i],tau[i],ideal_n,ideal_gamma) if(ideal_eqn_type=='none'): dalpha_o[1]==0.0 for i in range(0,len(tau)): dalpha_tau[i]=d_alpha_d_tau(tau[i],delta[i],N_i,t_i,d_i,p_i,phi_i,Beta_i,gamma_i,D_i,n_power_terms,n_gaussian_terms,n_critical_terms,RES_a,RES_b,RES_B,RES_C,RES_D,RES_A) dalpha_delta[i]=d_alpha_d_delta(tau[i],delta[i],N_i,t_i,d_i,p_i,phi_i,Beta_i,gamma_i,D_i,n_power_terms,n_gaussian_terms,n_critical_terms,RES_a,RES_b,RES_B,RES_C,RES_D,RES_A) R_specific=R/M_amu h1=R_specific*T*1.0 h2=R_specific*T*tau*(dalpha_o+dalpha_tau) h3=R_specific*T*delta*dalpha_delta h=h1+h2+h3 return h
def mk_image(galaxy): base = './../../images_v5/GS_2.5as_matched/gs_all_' i_img = pyf.getdata(base+str(galaxy)+'_I.fits') j_img = pyf.getdata(base+str(galaxy)+'_J.fits') h_img = pyf.getdata(base+str(galaxy)+'_H.fits') x = pyl.hstack(i_img) i_lim = scoreatpercentile(x,99) x = pyl.hstack(j_img) j_lim = scoreatpercentile(x,99) x = pyl.hstack(h_img) h_lim = scoreatpercentile(x,99) img = pyl.zeros((h_img.shape[0], h_img.shape[1], 3), dtype=float) img[:,:,0] = img_scale.asinh(h_img, scale_max=h_lim, non_linear=0.5) img[:,:,1] = img_scale.asinh(j_img, scale_max=j_lim, non_linear=0.5) img[:,:,2] = img_scale.asinh(i_img, scale_max=i_lim, non_linear=0.5) img = pyl.zeros((h_img.shape[0], h_img.shape[1], 3), dtype=float) img[:,:,0] = img_scale.asinh(h_img, scale_min=-0.1*h_lim, scale_max=h_lim, non_linear=0.5) img[:,:,1] = img_scale.asinh(j_img, scale_min=-0.1*j_lim, scale_max=j_lim, non_linear=0.5) img[:,:,2] = img_scale.asinh(i_img, scale_min=-0.1*i_lim, scale_max=i_lim, non_linear=0.5) return img
def shiftgrid(lon0,datain,lonsin,start=True): """ shift global lat/lon grid east or west. assumes wraparound (or cyclic point) is included. lon0: starting longitude for shifted grid (ending longitude if start=False). lon0 must be on input grid (with the range of lonsin). datain: original data. lonsin: original longitudes. start[True]: if True, lon0 represents he starting longitude of the new grid. if False, lon0 is the ending longitude. returns dataout,lonsout (data and longitudes on shifted grid). """ if pylab.fabs(lonsin[-1]-lonsin[0]-360.) > 1.e-4: raise ValueError, 'cyclic point not included' if lon0 < lonsin[0] or lon0 > lonsin[-1]: raise ValueError, 'lon0 outside of range of lonsin' i0 = pylab.argsort(pylab.fabs(lonsin-lon0))[0] dataout = pylab.zeros(datain.shape,datain.typecode()) lonsout = pylab.zeros(lonsin.shape,lonsin.typecode()) if start: lonsout[0:len(lonsin)-i0] = lonsin[i0:] else: lonsout[0:len(lonsin)-i0] = lonsin[i0:]-360. dataout[:,0:len(lonsin)-i0] = datain[:,i0:] if start: lonsout[len(lonsin)-i0:] = lonsin[1:i0+1]+360. else: lonsout[len(lonsin)-i0:] = lonsin[1:i0+1] dataout[:,len(lonsin)-i0:] = datain[:,1:i0+1] return dataout,lonsout
def openRomb(integrand, a, b,eps=1e-6,jmax=14,k=5): """ Returns the integral on the _open_interval_ (a,b). Integration is performed by Romberg's method of order 2k, where, e.g., k=2 is Simpson's rule. """ jmaxp=jmax+1 s = 0.*M.zeros(jmaxp) h = 0.*M.zeros(jmaxp+1) ss = 0. dss = 0. h[0]=1.0 for j in range(0,jmax): s[j]=tripleInt(integrand,a,b,s[j],j) if j >= k: ss,dss = interpPoly(h[j-k:j],s[j-k:j],k,0.0) if M.fabs(dss) <= eps*M.fabs(ss): return ss s[j+1]=s[j] h[j+1]=h[j]/9. print 'Non-convergence in openRomb' return ss
def atm(freqGHz,temp,humi,press,height): """Use the ATM model in CASA to calculate the opacity given the surface weather data and frequency. Temperature should be in Kelvin, pressure should be actual surface pressure in mbar (not adjusted to equivalent sea level pressure) and height should be in meters above mean sea level""" tmp = qa.quantity(temp, 'K') pre = qa.quantity(press, 'mbar') hum = humi alt = qa.quantity(height, 'm') h0 = qa.quantity(1.54, 'km') wvl = qa.quantity(-6.5, 'K/km') mxA = qa.quantity(10, 'km') dpr = qa.quantity(10.0, 'mbar') dpm = 1.2 att = 3 # 3 = mid lat, winter myatm = at.initAtmProfile(alt, tmp, pre, mxA, hum, wvl, dpr, dpm, h0, att) # set spectral range to compute values for nb = len(freqGHz) fC = qa.quantity(freqGHz, 'GHz') fW = qa.quantity(pl.ones(nb), 'GHz') fR = qa.quantity(pl.zeros(nb), 'GHz') at.initSpectralWindow(nb, fC, fW, fR) fr=pl.zeros(nb) op=pl.zeros(nb) for i in range(nb): fr[i] = at.getSpectralWindow(i)['value']/1e9 op[i] = at.getDryOpacitySpec(i)[1]+at.getWetOpacitySpec()[1]['value'] return (fr,op)
def findcurve(psi1,psi2,n=3,nn_fit=4,nn_out=100): ''' Function to find the elastica curve for start and end orientations psi1 and psi2. It finds the best curve across all directions from start and end, i.e. the direction independent elastica curve. Inputs ------------ psi1,psi2: start and end orientations. n: degree of estimation polynomial. nn: number of points on the curve. - nn_fit: for fittin purposes - nn_out: for the output Outputs ------------ Returns a tuple (s,psi). s: points on the curve. psi: curvature of the curve as a function of s. E: curvature energy of the curve ''' # # define the starting conditions a0 = pl.zeros(n+1) # Set a high energy: E_best = 10000 # and predfine output curve s = pl.linspace(0,1,nn_out) # points on the curve psi_out = pl.zeros(nn_out) # curvature at points in curve # across all the start and end directions find the curve with the lowest energy for dpsi1 in (-pl.pi,0,pl.pi): for dpsi2 in (-pl.pi,0,pl.pi): # For the starting variables, # the first two polygon variables can be estimated from the Sharon paper derivation # For different starting variables the solution can be hard to find a0[-2] = 4*( pl.arcsin(- (pl.sin(psi1+dpsi1)+ pl.sin(psi2+dpsi2))/4) -(psi1+dpsi1+psi2+dpsi2)/2 ) a0[-1] = 2*a0[-2]/pl.cos( (psi1+dpsi1+psi2+dpsi2)/2 + a0[-2]/4 ) # find the best variables to minimize the elastica energy fit = fsolve(errors,a0,args=(psi1+dpsi1,psi2+dpsi2,nn_fit)) # find the curve and its derivative for the fitted variables a = fit[:-1] psi = Psi(a,s,psi1+dpsi1,psi2+dpsi2) dpsi = dPsi(a,s,psi1+dpsi1,psi2+dpsi2) # find the energy of this curve E = sum(dpsi**2)*s[1] # check against the lowest energy if E_best > E: E_best = E psi_out[:] = pl.copy(psi) return (s,psi_out,E_best)
def main(): plt.ion() fil = FletcherFilter() Niter = 12 logp = plt.zeros((Niter,2)) for k in range(Niter): while True: #print k p = plt.rand(2) if not fil.dominated(p): break logp[k] = p fil.add(p, 0.0, 0.0) ff = fil.values[fil.valid] ff = plt.r_[[[1e-6,1]], ff[plt.argsort(ff[:,0])], [[1,1e-6]]] ww = plt.zeros((ff.shape[0] * 2 - 1, 2)) ww[::2] = ff ww[1::2,0] = ff[1:,0] ww[1::2,1] = ff[:-1,1] plt.loglog(ww[:,0], ww[:,1], '-') plt.loglog(logp[:,0], logp[:,1], 'ys-', lw=2) plt.axis([0,1,0,1]) plt.axis('equal') plt.grid() code.interact()
def gadget_merge_ics( outfile, filename1, filename2, offset1, offset2, voffset1=[0.,0.,0.], voffset2=[0.,0.,0.] ): snap1 = gadget_readsnapname( filename1 ) snap2 = gadget_readsnapname( filename2 ) for i in range(3): snap1.pos[:,i] += offset1[i] snap2.pos[:,i] += offset2[i] for i in range(3): snap1.vel[:,i] += voffset1[i] snap2.vel[:,i] += voffset2[i] npart = snap1.npart + snap2.npart data = {} data[ 'count' ] = npart data[ 'pos' ] = pylab.zeros( [npart, 3] ) data[ 'pos' ][ 0:snap1.npart, : ] = snap1.pos data[ 'pos' ][ snap1.npart:npart, : ] = snap2.pos data[ 'vel' ] = pylab.zeros( [npart, 3] ) data[ 'vel' ][ 0:snap1.npart, : ] = snap1.vel data[ 'vel' ][ snap1.npart:npart, : ] = snap2.vel data[ 'mass' ] = pylab.zeros( npart ) data[ 'mass' ][ 0:snap1.npart ] = snap1.data["mass"] data[ 'mass' ][ snap1.npart:npart ] = snap2.data["mass"] data[ 'u' ] = pylab.zeros( npart ) data[ 'u' ][ 0:snap1.npart ] = snap1.data["u"] data[ 'u' ][ snap1.npart:npart ] = snap2.data["u"] nxnuc = pylab.shape( snap1.data["xnuc"] )[1] data[ 'xnuc' ] = pylab.zeros( [npart, nxnuc] ) data[ 'xnuc' ][ 0:snap1.npart, : ] = snap1.data["xnuc"] data[ 'xnuc' ][ snap1.npart:npart, : ] = snap2.data["xnuc"] gadget_write_ics( outfile, data, transpose=False ) return
def checkmodelgrad(model,e,RETURNGRADS=False,*args): from pylab import norm """Check the correctness of passed-in model in terms of cost-/gradient- computation, using gradient approximations with perturbances of size e. """ def updatemodelparams(model, newparams): model.params *= 0.0 model.params += newparams.copy() def cost(params,*args): paramsold = model.params.copy() updatemodelparams(model,params.copy().flatten()) result = model.cost(*args) updatemodelparams(model,paramsold.copy()) return result def grad(params,*args): paramsold = model.params.copy() updatemodelparams(model, params.copy().flatten()) result = model.grad(*args) updatemodelparams(model, paramsold.copy()) return result dy = model.grad(*args) l = len(model.params) dh = zeros(l,dtype=float) for j in range(l): dx = zeros(l,dtype=float) dx[j] = e y2 = cost(model.params+dx,*args) y1 = cost(model.params-dx,*args) dh[j] = (y2 - y1)/(2*e) print "analytic: \n", dy print "approximation: \n", dh if RETURNGRADS: return dy,dh else: return norm(dh-dy)/norm(dh+dy)
neighbour_sum = 0 for site in self.getneighbours((i,j)): neighbour_sum += self.spins[site] return - self.J * self.spins[i,j] * neighbour_sum def getneighbours(self,(i,j)): """Returns sites connected to site i,j""" result = [(i%self.n,(j-1)%self.n), (i%self.n,(j+1)%self.n), ((i-1)%self.n,j%self.n), ((i+1)%self.n,j%self.n)] return result def getneighbourhood(self,(i,j)): """Gets 3x3 neighbourhood around site i,j""" out = pl.zeros((3,3)) r = 0 for m in xrange(i-1,i+2): s = 0 for n in xrange(j-1,j+2): out[r,s] = self.spins[m%(self.n-1),n%(self.n-1)] s+=1 r+=1 return out def H(self, a = False): """Calculates the total energy of the lattice""" E = 0. Energies = pl.zeros((self.n,self.n))
return xn*w def p2r(mags, phs): return mags*pl.cos(phs) + 1j*mags*pl.sin(phs) N = 1024 D = 4 H = N//D zdbfs = 32768 (sr,in1) = wf.read(sys.argv[1]) (sr,in2) = wf.read(sys.argv[2]) L1 = len(in1) L2 = len(in2) if L2 > L1: L = L2 else: L = L1 signal1 = pl.zeros(L) signal2 = pl.zeros(L) signal1[:len(in1)] = in1/zdbfs signal2[:len(in2)] = in2/zdbfs output = pl.zeros(L) win = pl.hanning(N) scal = 1.5*D/4 for n in range(0,L,H): if(L-n < N): break frame1 = stft(signal1[n:n+N],win,n) frame2 = stft(signal2[n:n+N],win,n) mags1 = abs(frame1) mags2 = abs(frame2) phs = pl.angle(frame1) frame = p2r(mags1*mags2,phs)
def run(self, debug=False, verbose=None, **kwargs): ''' Run the actual scenarios Args: debug (bool): if True, runs a single run instead of multiple, which makes debugging easier verbose (int): level of detail to print, passed to sim.run() kwargs (dict): passed to multi_run() and thence to sim.run() Returns: None (modifies Scenarios object in place) ''' if verbose is None: verbose = self['verbose'] def print_heading(string): ''' Choose whether to print a heading, regular text, or nothing ''' if verbose >= 2: sc.heading(string) elif verbose == 1: print(string) return reskeys = self.reskeys # Shorten since used extensively # Loop over scenarios for scenkey, scen in self.scenarios.items(): scenname = scen['name'] scenpars = scen['pars'] # This is necessary for plotting, and since self.npts is defined prior to run if 'n_days' in scenpars.keys(): errormsg = 'Scenarios cannot be run with different numbers of days; set via basepars instead' raise ValueError(errormsg) # Create and run the simulations print_heading(f'Multirun for {scenkey}') scen_sim = sc.dcp(self.base_sim) scen_sim.update_pars(scenpars) run_args = dict(n_runs=self['n_runs'], noise=self['noise'], noisepar=self['noisepar'], verbose=verbose) if debug: print('Running in debug mode (not parallelized)') run_args.pop( 'n_runs', None) # Remove n_runs argument, not used for a single run scen_sims = [single_run(scen_sim, **run_args, **kwargs)] else: scen_sims = multi_run( scen_sim, **run_args, **kwargs) # This is where the sims actually get run # Process the simulations print_heading(f'Processing {scenkey}') scenraw = {} for reskey in reskeys: scenraw[reskey] = pl.zeros((self.npts, len(scen_sims))) for s, sim in enumerate(scen_sims): scenraw[reskey][:, s] = sim.results[reskey].values scenres = sc.objdict() scenres.best = {} scenres.low = {} scenres.high = {} for reskey in reskeys: scenres.best[reskey] = pl.mean( scenraw[reskey], axis=1) # Changed from median to mean for smoother plots scenres.low[reskey] = pl.quantile(scenraw[reskey], q=self['quantiles']['low'], axis=1) scenres.high[reskey] = pl.quantile(scenraw[reskey], q=self['quantiles']['high'], axis=1) for reskey in reskeys: self.allres[reskey][scenkey]['name'] = scenname for blh in ['best', 'low', 'high']: self.allres[reskey][scenkey][blh] = scenres[blh][reskey] self.sims[scenkey] = scen_sims #%% Print statistics if verbose: print('\nResults for final time point in each scenario:') for reskey in reskeys: print(f'\n{reskey}') for scenkey in list(self.scenarios.keys()): print( f' {scenkey}: {self.allres[reskey][scenkey].best[-1]:0.0f}' ) print() # Add a blank space return
def draw_domain(dom): n1 = "Wikisource_-_pages_%s.png" % dom fig = pylab.figure(1) ax = fig.add_subplot(111) pylab.clf() pylab.hold(True) pylab.grid(True) count = count_array[dom] pylab.fill_between(count[0][1], 0, count[0][0], facecolor="#ffa0a0") #red pylab.fill_between(count[4][1], 0, count[4][0], facecolor="#b0b0ff") #blue pylab.fill_between(count[3][1], 0, count[3][0], facecolor="#dddddd") #gray pylab.fill_between(count[2][1], 0, count[2][0], facecolor="#ffe867") #yellow pylab.fill_between(count[1][1], 0, count[1][0], facecolor="#90ff90") #green x = range(1) b1 = pylab.bar(x, x, color='#ffa0a0') b0 = pylab.bar(x, x, color='#dddddd') b2 = pylab.bar(x, x, color='#b0b0ff') b3 = pylab.bar(x, x, color='#ffe867') b4 = pylab.bar(x, x, color='#90ff90') pylab.legend([b1[0], b3[0], b4[0], b0[0], b2[0]], [ 'not proofread', 'proofread', 'validated', 'without text', 'problematic' ], loc=2) pylab.plot_date(count[0][1], pylab.zeros(len(count[0][1])), 'k-') ax.xaxis.set_major_locator(pylab.YearLocator()) ax.xaxis.set_major_formatter(pylab.DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() pylab.title("%s.wikisource.org" % dom) pylab.ylim(0) pylab.savefig(savepath + n1) n1 = "Wikisource_-_texts_%s.png" % dom pylab.figure(1) pylab.clf() pylab.hold(True) pylab.grid(True) count = count_array[dom] pylab.fill_between(rm29(dom, count[8][1]), 0, rm29(dom, count[8][0]), facecolor="#b0b0ff") pylab.fill_between(rm29(dom, count[7][1]), 0, rm29(dom, count[7][0]), facecolor="#ffa0a0") pylab.fill_between(rm29(dom, count[9][1]), 0, rm29(dom, count[9][0]), facecolor="#dddddd") x = range(1) b1 = pylab.bar(x, x, color='#b0b0ff') b2 = pylab.bar(x, x, color='#ffa0a0') if dom != 'de': pylab.legend([b1[0], b2[0]], ['with scans', 'naked'], loc=3) else: pylab.legend([b1[0], b2[0]], ['with transclusion (PR2)', 'older system (PR1)'], loc=3) pylab.plot_date(rm29(dom, count[8][1]), pylab.zeros(len(rm29(dom, count[8][1]))), 'k-') ax.xaxis.set_major_locator(pylab.YearLocator()) ax.xaxis.set_major_formatter(pylab.DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() pylab.title("%s.wikisource.org" % dom) pylab.ylim(0) pylab.savefig(savepath + n1)
def fileplotline(name): """ A python program for plotting information stored in a .dat file. The file needs to be on the form: ----------------------------------------------- Number of sets #Number of rows with numbers #Info1 #Info2 #Number1 #Number2 #Number1 #Number2 . . . . #Number1 #Number2 #Number3 #Number4 #Number3 #Number4 . . . . #Number3 #Number4 . . . . . . ----------------------------------------------- It plots #Info1 vs #Info2, #Info1 vs #Info3 and so on """ import pylab as p import glob, os #Try except statement to check if the given file excists try: infile = open(name, "r") except: print "Error: '" + name + "', no file with that name" return 1 #Read the information from the top of each coloumn number_of_sets = int(infile.readline()) number_of_rows = int(infile.readline()) info = infile.readline() info = info.split() number_of_coloumns = len(info) #Make the array for storing numbers = p.zeros((number_of_coloumns, number_of_rows * number_of_sets)) #Read all the data from the file and store it coloum by coloumn row = 0 for line in infile: rows = line.split() col = 0 while col < len(info): numbers[col][row] = float(rows[col].replace("D", "e")) col += 1 row += 1 #Close the file file.close #Do stuff with the data #Removing old plots outfile = name[:-4] + ".png" for filename in glob.glob(outfile): os.remove(filename) #Plot the information in the same plot p.clf() i = 1 j = 0 while j < number_of_sets: while i < number_of_coloumns: print j p.plot(numbers[0][number_of_sets * j:number_of_sets * (j + 1)], numbers[i][number_of_sets * j:number_of_sets * (j + 1)]) p.hold("on") j += 1 i += 1 p.xlabel(info[0]) p.ylabel(info[1]) p.legend(info[1:]) p.title(name[:-4]) p.savefig(outfile)
def eval_W_integral_driven(self,slip): def w_func_d1(th,th1,r,b,n,k1,k2): outval = sig_1(th,th1,r,b,n,k1,k2)*py.cos(th) return outval def w_func_d2(th,th_m,th1,th2,r,b,n,k1,k2): outval = sig_2(th,th_m,th1,th2,r,b,n,k1,k2)*py.cos(th) return outval def w_func_d3(th,th1,r,b,n,k1,k2,coh,phi,K,slip): outval = tau_d1(th,th1,r,b,n,k1,k2,coh,phi,K,slip)*py.sin(th) return outval def w_func_d4(th,th_m,th1,th2,r,b,n,k1,k2,coh,K,phi,slip): outval = tau_d2(th,th_m,th1,th2,r,b,n,k1,k2,coh,K,phi,slip)*py.sin(th) return outval # returns error of weight equation, used with fsolve when finding th1 def W_driven_func(th1,th2,W,r,b,n,k1,k2,phi,slip,K,coh,c1,c2): # Eq 10/11 th_m = theta_m(th1,c1,c2,slip) term1 = sci_int.quad(w_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2) ) term2 = sci_int.quad(w_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2) ) term3 = sci_int.quad(w_func_d3,th_m,th1,args=(th1,r,b,n,k1,k2,coh,phi,K,slip) ) term4 = sci_int.quad(w_func_d4,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2,coh,K,phi,slip) ) error = r*b*(term1[0] + term2[0] + term3[0] + term4[0]) - W return error # returns the terms in the weight equation def W_driven_func_terms(th1,th2,W,r,b,n,k1,k2,phi,slip,K,coh,c1,c2): # Eq 10/11 th_m = theta_m(th1,c1,c2,slip) term1 = sci_int.quad(w_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2) ) term2 = sci_int.quad(w_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2,coh,K,phi,slip) ) term3 = sci_int.quad(w_func_d3,th_m,th1,args=(th1,r,b,n,k1,k2,coh,phi,K,slip) ) term4 = sci_int.quad(w_func_d4,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2,coh,K,phi,slip) ) error = r*b*(term1[0] + term2[0] + term3[0] + term4[0]) - W return [error, r*b*term1[0], r*b*term2[0], r*b*term3[0], r*b*term4[0] ] # end helper functions # solve for contact angle, th_1, using equlibrium of vertical forces th2 = self._th2 k1 = self._k1 k2 = self._k2 b = self._width r = self._radius n = self._n coh = self._coh K = self._K phi = self._phi W = self._weight c1 = self._c1 c2 = self._c2 # initial guess for theta 1 th1_initial = degToRad(35.0) if(th1_initial/theta_m(th1_initial,c1,c2,slip) < 1.5): th1_initial = 2.0 * theta_m(th1_initial,c1,c2,slip) # iterate until th1 is found th1 = sci_opt.fsolve(W_driven_func,th1_initial,args=(th2,W,r,b,n,k1,k2,phi,slip,K,coh,c1,c2) ) thm = theta_m(th1,c1,c2,slip) self._thm = thm lg.info('slip rate = ' + str(slip)) lg.info('theta_1, driven [deg] = ' + str(radToDeg(th1)) ) lg.info('theta_m, driven [deg] = ' + str(radToDeg(thm)) ) if( self._plots): # if I want plots, need to find th1 for each value of skid in skid_arr i_range = self._slip_arr th_m_array = py.zeros(len(i_range)) th1_array = py.zeros(len(i_range)) th_ratio = py.zeros(len(i_range)) # t1_arr = py.zeros(len(i_range)) # t2_arr = py.zeros(len(i_range)) # t3_arr = py.zeros(len(i_range)) # t4_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] th1_out = sci_opt.fsolve(W_driven_func,th1,args=(th2,W,r,b,n,k1,k2,phi,slip_curr,K,coh,c1,c2),xtol=1E-5) th1_array[idx] = th1_out th_m_curr = theta_m(th1_out,c1,c2,slip_curr) th_m_array[idx] = th_m_curr th_ratio[idx] = th_m_curr / th1_out # I want to see how each term of the weight function changes # [error,t1,t2,t3,t4] = W_towed_func_terms(th1_out,th0_curr,th2,W,r,b,n,k1,k2,phi,slip_curr,K,c) # t1_arr[idx] = t1 # t2_arr[idx] = t2 # t3_arr[idx] = t3 # t4_arr[idx] = t4 fig=plt.figure() ax = fig.add_subplot(211,title='Fig 3(a), weight = '+str(self._weight)) ax.plot(i_range,radToDeg(th1_array),i_range,radToDeg(th_m_array),linewidth=1.5) ax.set_xlabel('slip ratio') ax.set_ylabel(r'$\theta$ [degrees]' ) ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('theta1','theta0')) ax.grid(True) ax = fig.add_subplot(212) ax.plot(i_range,th_ratio,linewidth=1.5) ax.set_xlabel('slip ratio') ax.set_ylabel('theta_m / theta_1') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.set_ylim([0,0.9]) ax.grid(True) # we will need all the values of th1 for further plots self._th1_arr = th1_array self._thm_arr = th_m_array W_check = W_driven_func(th1,0.0,W,r,b,n,k1,k2,phi,slip,K,coh,c1,c2) lg.info('weight check = ' + str(W_check) + ' for a th_1 of ' +str(th1)) return th1
def eval_T_integral_driven(self,th1,slip,figNum=8): # integral terms def torque_func_d1(th,th1,r,b,n,k1,k2,c,K,phi,slip): outval = tau_d1(th,th1,r,b,n,k1,k2,c,phi,K,slip) return outval def torque_func_d2(th,th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip): outval = tau_d2(th,th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip) return outval # driven torque function def T_driven_func(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(torque_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2,c,K,phi,slip)) term2 = sci_int.quad(torque_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*r*b*(term1[0] + term2[0]) return outval # driven torque function, with each term returned def T_driven_func_terms(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(torque_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2,c,K,phi,slip)) term2 = sci_int.quad(torque_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*r*b*(term1[0] + term2[0]) return [outval, r*r*b*term1[0], r*r*b*term2[0] ] # eval_T_integral_towed HELPER FUNCTIONS END HERE th_m = self._thm th2 = self._th2 r = self._radius b = self._width c = self._coh k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K # should really be solving for th1 w.r.t. W, T and F [calc_torque, t1, t2] = T_driven_func_terms(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip) lg.info('driven Torque = ' + str(calc_torque)) lg.info('driven terms, front = ' + str(t1) + ' , bottom = ' + str(t2) ) if( self._plots): i_range = self._slip_arr thm_array = self._thm_arr th1_array = self._th1_arr torque_arr = py.zeros(len(i_range)) t1_arr = py.zeros(len(i_range)) t2_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] thm_curr = thm_array[idx] th1_curr = th1_array[idx] [torque_curr,t1,t2] = T_driven_func_terms(th1_curr,thm_curr,th2,r,b,n,k1,k2,c,K,phi,slip_curr) torque_arr[idx] = torque_curr t1_arr[idx] = t1 t2_arr[idx] = t2 fig=plt.figure() ax = fig.add_subplot(111,title='Fig.'+str(figNum)+'(c)') ax.plot(i_range,torque_arr,'k--',i_range,t1_arr,i_range,t2_arr,linewidth=1.5) ax.set_xlabel('slip ratio') if( self._units == 'ips'): ax.set_ylabel('Torque [lb-in]' ) else: ax.set_ylabel('Torque [N-m]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('T',r'$\tau_1$',r'$\tau_2$')) ax.grid(True) return calc_torque
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=True) val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=True) # Plotting config plot_data = {} plot_data['train_loss'] = zeros(epochs) plot_data['train_prec1'] = zeros(epochs) plot_data['train_prec5'] = zeros(epochs) plot_data['val_loss'] = zeros(epochs) plot_data['val_prec1'] = zeros(epochs) plot_data['val_prec5'] = zeros(epochs) plot_data['epoch'] = 0 it_axes = arange(epochs) _, ax1 = subplots() ax2 = ax1.twinx() ax1.set_xlabel('epoch') ax1.set_ylabel('train loss (r), val loss (y)') ax2.set_ylabel( 'train prec1 (b), train prec5 (k), val prec1 (g), val prec5 (m)') ax2.set_autoscaley_on(False) ax1.set_ylim([0, 12])
def plot_sigTau_driven(self,th1_cs,slip,figNum=11,plotBekker=False): th_m = self._thm th2 = self._th2 r = self._radius b = self._width k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K c = self._coh incr = (th1_cs - th2) / 100.0 # plot increment th_arr = py.arange(0,th1_cs, incr) # find sigma, tau at these discrete vals sig_arr = py.zeros(len(th_arr)) tau_arr = py.zeros(len(th_arr)) slip_arr = py.zeros(len(th_arr)) for idx in range(0,len(th_arr)): th = th_arr[idx] if(th <= th_m): # we're in the bototm region sig_curr = sig_2(th,th_m,th1_cs,th2,r,b,n,k1,k2) tau_curr = tau_d2(th,th_m,th1_cs,th2,r,b,n,k1,k2,c,K,phi,slip) slip_j = jdriven(th,th1_cs,r,slip) sig_arr[idx] = sig_curr tau_arr[idx] = tau_curr slip_arr[idx] = slip_j else: # we're in the top region () sig_curr = sig_1(th, th1_cs,r,b,n,k1,k2) tau_curr = tau_d1(th,th1_cs,r,b,n,k1,k2,c,phi,K,slip) slip_j = jdriven(th,th1_cs,r,slip) sig_arr[idx] = sig_curr tau_arr[idx] = tau_curr slip_arr[idx] = slip_j if( self._plots): fig = plt.figure() ax = fig.add_subplot(211,title='Fig.'+str(figNum) ) ax.plot(radToDeg(th_arr),sig_arr,radToDeg(th_arr),tau_arr,linewidth=1.5) ax.set_xlabel('theta [deg]') ax.set_ylabel('stress [psi]') ax.legend((r'$\sigma$',r'$\tau$')) ax.grid(True) # can also plot Bekker's solution if(plotBekker): th_bek, sig_bek, tau_bek = self.get_sigTau_Bekker_driven(slip) ax.plot(radToDeg(th_bek),sig_bek, radToDeg(th_bek), tau_bek, linewidth=1.5) ax.legend((r'$\sigma$',r'$\tau$',r'$\sigma_bek$',r'$\tau_bek$')) # take a look at what I"m using for slip displacement also ax = fig.add_subplot(212) ax.plot(radToDeg(th_arr),slip_arr,linewidth=1.5) ax.set_xlabel('theta [deg]') if( self._units == 'ips'): ax.set_ylabel('slip disp.[in]') else: ax.set_ylabel('slip disp.[m]') ax.grid(True) # polar plots fig=plt.figure() ax=fig.add_subplot(111,projection='polar') ax.plot(th_arr,sig_arr,'b',linewidth=1.5) ax.plot(th_arr,tau_arr,'r--',linewidth=1.5) # fix the axes ax.grid(True) if( self._units == 'ips'): leg = ax.legend((r'$\sigma$ [psi]',r'$\tau$')) else: leg = ax.legend((r'$\sigma$ [Pa]',r'$\tau$')) leg.draggable() ax.set_theta_zero_location('S') # also, draw the tire polar_r_offset = py.average(sig_arr) theta = py.arange(0.,2.*py.pi+0.05,0.05) tire_pos = py.zeros(len(theta)) ax.plot(theta,tire_pos,color='k',linewidth=1.0) ax.set_rmin(-polar_r_offset) ax.set_title(r'driven wheel stresses, $\theta_1$ = %4.3f [rad]' %th1_cs) ax.set_thetagrids([-10,0,10,20,30,40,50,60])
def eval_F_integral_driven(self,th1,slip,figNum=8): # integral terms def F_func_d1(th,th1,r,b,n,k1,k2): outval = py.sin(th)*sig_1(th,th1,r,b,n,k1,k2) return outval def F_func_d2(th,th_m,th1,th2,r,b,n,k1,k2): outval = py.sin(th)*sig_2(th,th_m,th1,th2,r,b,n,k1,k2) return outval def F_func_d3(th,th1,r,b,n,k1,k2,c,K,phi,slip): outval = py.cos(th)*tau_d1(th,th1,r,b,n,k1,k2,c,phi,K,slip) return outval def F_func_d4(th,th_m,th1,th2,r,b,n,c,k1,k2,K,phi,slip): outval = py.cos(th)*tau_d2(th,th_m,th1,th2,r,b,n,k1,k2,c,K,phi,slip) return outval # driven wheel force def F_driven_func(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(F_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2)) term2 = sci_int.quad(F_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(F_func_d3,th_m,th1,args=(th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(F_func_d4,th2,th_m,args=(th_m,th1,th2,r,b,n,c,k1,k2,K,phi,slip)) outval = r*b*(-term1[0]-term2[0]+term3[0]+term4[0]) return outval # driven wheel force, with terms def F_driven_func_terms(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(F_func_d1,th_m,th1,args=(th1,r,b,n,k1,k2)) term2 = sci_int.quad(F_func_d2,th2,th_m,args=(th_m,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(F_func_d3,th_m,th1,args=(th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(F_func_d4,th2,th_m,args=(th_m,th1,th2,r,b,n,c,k1,k2,K,phi,slip)) outval = r*b*(-term1[0]-term2[0]+term3[0]+term4[0]) return [outval, r*b*term1[0], r*b*term2[0], r*b*term3[0], r*b*term4[0] ] # eval_F_integral_towed() HELPER FUNCTIONS END HERE th_m = self._thm th2 = self._th2 r = self._radius b = self._width k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K c = self._coh # don't know what this should be apriori calc_force = F_driven_func(th1,th_m,th2,r,b,n,k1,k2,c,K,phi,slip) lg.info('drawbar pull = ' + str(calc_force)) if( self._plots): i_range = self._slip_arr thm_array = self._thm_arr th1_array = self._th1_arr force_arr = py.zeros(len(i_range)) t1_arr = py.zeros(len(i_range)) t2_arr = py.zeros(len(i_range)) t3_arr = py.zeros(len(i_range)) t4_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] thm_curr = thm_array[idx] th1_curr = th1_array[idx] [force_curr,t1,t2,t3,t4] = F_driven_func_terms(th1_curr,thm_curr,th2,r,b,n,k1,k2,c,K,phi,slip_curr) force_arr[idx] = force_curr t1_arr[idx] = t1 t2_arr[idx] = t2 t3_arr[idx] = t3 t4_arr[idx] = t4 fig=plt.figure() ax = fig.add_subplot(211,title='Fig.' + str(figNum) + '(a) [top] and Fig.'+str(figNum) + '(b) [bottom]') ax.plot(i_range,t3_arr+t4_arr,i_range,t1_arr+t2_arr,linewidth=1.5) # ax.set_xlabel('slip ratio') ax.set_ylabel('Force [lb]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('H','R')) ax.grid(True) ax = fig.add_subplot(212,title='H and R') ax.plot(i_range,force_arr,'k--',i_range,t1_arr,i_range,t2_arr,i_range,t3_arr,i_range,t4_arr,linewidth=1.5) ax.set_xlabel('slip ratio') if( self._units == 'ips'): ax.set_ylabel('Force [lb]' ) else: ax.set_ylabel('Force [N]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('D',r'$\sigma_1$',r'$\sigma_2$',r'$\tau_1$',r'$\tau_2$')) ax.grid(True) return calc_force
def eval_F_integral_towed(self,th1,slip,figNum=8): # terms in the F = integral def F_func_t1(th,th1,r,b,n,k1,k2): outval = sig_1(th,th1,r,b,n,k1,k2)*py.sin(th) return outval def F_func_t2(th,th0,th1,th2,r,b,n,k1,k2): outval = sig_2(th,th0,th1,th2,r,b,n,k1,k2)*py.sin(th) return outval def F_func_t3(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t1(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip)*py.cos(th) return outval def F_func_t4(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t2(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)*py.cos(th) return outval # total longitudinal force acting on the wheel def F_towed_func(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(F_func_t1,th0,th1,args=(th1,r,b,n,k1,k2)) term2 = sci_int.quad(F_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(F_func_t3,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(F_func_t4,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*b*(term1[0]+term2[0]-term3[0]+term4[0]) return outval # longitudinal force, and individual terms in the integral def F_towed_func_terms(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(F_func_t1,th0,th1,args=(th1,r,b,n,k1,k2)) term2 = sci_int.quad(F_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(F_func_t3,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(F_func_t4,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*b*(term1[0]+term2[0]-term3[0]+term4[0]) return [outval, r*b*term1[0], r*b*term2[0], r*b*term3[0], r*b*term4[0] ] # eval_F_integral_towed() HELPER FUNCTIONS END HERE th0 = self._th0 th2 = self._th2 r = self._radius b = self._width k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K c = self._coh # don't know what this should be apriori calc_force = F_towed_func(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip) lg.info('towing Force = ' + str(calc_force)) if( self._plots): i_range = self._slip_arr th0_array = self._th0_arr th1_array = self._th1_arr force_arr = py.zeros(len(i_range)) t1_arr = py.zeros(len(i_range)) t2_arr = py.zeros(len(i_range)) t3_arr = py.zeros(len(i_range)) t4_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] th0_curr = th0_array[idx] th1_curr = th1_array[idx] [force_curr,t1,t2,t3,t4] = F_towed_func_terms(th1_curr,th0_curr,th2,r,b,n,k1,k2,c,K,phi,slip_curr) force_arr[idx] = force_curr t1_arr[idx] = t1 t2_arr[idx] = t2 t3_arr[idx] = t3 t4_arr[idx] = t4 fig=plt.figure() ax = fig.add_subplot(211,title='Fig.' + str(figNum) + '(b) [top] and Fig.'+str(figNum) + '(c) [bottom]') ax.plot(i_range,t3_arr-t4_arr,i_range,t1_arr+t2_arr,linewidth=1.5) ax.set_xlabel('skid ratio') if( self._units == 'ips'): ax.set_ylabel('Force [lb]' ) else: ax.set_ylabel('Force [N]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('H','R')) ax.grid(True) ax = fig.add_subplot(212) ax.plot(i_range,force_arr,'k--',i_range,t1_arr,i_range,t2_arr,i_range,t3_arr,i_range,t4_arr,linewidth=1.5) # ax.plot(i_range,force_arr,'k--',linewidth=1.5) ax.set_xlabel('skid ratio') if( self._units == 'ips'): ax.set_ylabel('Force [lb]') else: ax.set_ylabel('Force [N]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('F',r'$\sigma_1$',r'$\sigma_2$',r'$\tau_1$',r'$\tau_2$')) ax.grid(True) return calc_force
ntime1 = dates.index(YYYYMMDDHH1) ntime2 = dates.index(YYYYMMDDHH2) print 'ntime1,ntime2:', ntime1, ntime2 if ntime1 >= ntime2: raise ValueError, 'date2 must be greater than date1' # get sea level pressure and 10-m wind data. slpdata = data['presmsl'] udata = datau['ugrdprs'] vdata = datau['vgrdprs'] # mult slp by 0.01 to put in units of millibars. slpin = 0.01 * p.squeeze(slpdata[ntime1:ntime2 + 1, :, :]) uin = p.squeeze(udata[ntime1:ntime2 + 1, 0, :, :]) vin = p.squeeze(vdata[ntime1:ntime2 + 1, 0, :, :]) datelabels = dates[ntime1:ntime2 + 1] # add cyclic points slp = p.zeros((slpin.shape[0], slpin.shape[1], slpin.shape[2] + 1), p.Float64) slp[:, :, 0:-1] = slpin slp[:, :, -1] = slpin[:, :, 0] u = p.zeros((uin.shape[0], uin.shape[1], uin.shape[2] + 1), p.Float64) u[:, :, 0:-1] = uin u[:, :, -1] = uin[:, :, 0] v = p.zeros((vin.shape[0], vin.shape[1], vin.shape[2] + 1), p.Float64) v[:, :, 0:-1] = vin v[:, :, -1] = vin[:, :, 0] longitudes.append(360.) longitudes = p.array(longitudes) # make 2-d grid of lons, lats lons, lats = p.meshgrid(longitudes, latitudes) print 'min/max slp,u,v' print min(p.ravel(slp)), max(p.ravel(slp)) print min(p.ravel(uin)), max(p.ravel(uin))
# HELLO Assembles HELLO matrix. See Trefethen&Bau Exercise 9.3. from pylab import ones, zeros, spy, show bl = ones((8,6)) H = bl.copy() H[0:3,2:4] = zeros((3,2)) H[5:8,2:4] = zeros((3,2)) E = bl.copy() E[2,2:6] = zeros((1,4)) E[5,2:6] = zeros((1,4)) L = bl.copy() L[0:6,2:6] = zeros((6,4)) O = bl.copy() O[2:6,2:4] = zeros((4,2)) HELLO = zeros((15,40)) HELLO[1:9,1:7] = H HELLO[2:10,9:15] = E HELLO[3:11,17:23] = L HELLO[4:12,25:31] = L HELLO[5:13,33:39] = O spy(HELLO,marker='.'); show()
def eval_T_integral_towed(self,th1,slip,figNum=8): # torque is only affected by tau terms of the T = integral def torque_func_t1(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t1(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip) return outval def torque_func_t2(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t2(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip) return outval # evaluate torque def T_towed_func(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(torque_func_t1,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term2 = sci_int.quad(torque_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*r*b*(term1[0] - term2[0]) # same as the error, when T=0 return outval # eval. torque, return the integral terms also def T_towed_func_terms(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip): term1 = sci_int.quad(torque_func_t1,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term2 = sci_int.quad(torque_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) outval = r*r*b*(term1[0] - term2[0]) return [outval, r*r*b*term1[0], r*r*b*term2[0] ] th0 = self._th0 th2 = self._th2 r = self._radius b = self._width c = self._coh k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K slip = self._skid # should really be solving for th1 w.r.t. W, T and F [calc_torque, t1, t2] = T_towed_func_terms(th1,th0,th2,r,b,n,k1,k2,c,K,phi,slip) lg.info('towed Torque = ' + str(calc_torque)) lg.info('torque front = ' + str(t1) + ' , bottom = ' + str(t2) ) if( self._plots): i_range = self._slip_arr th0_array = self._th0_arr th1_array = self._th1_arr torque_arr = py.zeros(len(i_range)) t1_arr = py.zeros(len(i_range)) t2_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] th0_curr = th0_array[idx] th1_curr = th1_array[idx] [torque_curr,t1,t2] = T_towed_func_terms(th1_curr,th0_curr,th2,r,b,n,k1,k2,c,K,phi,slip_curr) torque_arr[idx] = torque_curr t1_arr[idx] = t1 t2_arr[idx] = t2 fig=plt.figure() ax = fig.add_subplot(111,title='Fig. ' + str(figNum) +'(a)') ax.plot(i_range,torque_arr,'k--',i_range,t1_arr,i_range,t2_arr,linewidth=1.5) ax.set_xlabel('skid ratio') if( self._units == 'ips'): ax.set_ylabel('Torque [lb-in]' ) else: ax.set_ylabel('Torque [N-m]') # ax.set_ylabel('Torque [N-m]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend(('T',r'$\tau_1$',r'$\tau_2$')) #,loc=2) ax.grid(True) return calc_torque
def projectOnFinerGrid_f39(Xc, Yc, q): dx = Xc[1] - Xc[0] dy = Yc[1] - Yc[0] nx = Xc.shape[0] ny = Yc.shape[0] # mesh coordinates Xn = pylab.linspace(0, 2 * math.pi, 3 * nx + 1) # one more Yn = pylab.linspace(0, 2 * math.pi, 3 * ny + 1) # one more XXn, YYn = pylab.meshgrid(Xn, Yn) # data qn = pylab.zeros((3 * Xc.shape[0], 3 * Yc.shape[0]), float) v1 = q[:, :, 0] v2 = q[:, :, 1] v3 = q[:, :, 2] v4 = q[:, :, 3] v5 = q[:, :, 4] v6 = q[:, :, 5] v7 = q[:, :, 6] v8 = q[:, :, 7] vList = [v1, v2, v3, v4, v5, v6, v7, v8] # node 1 c1 = [ .2314814814814815, -.1388888888888889, -.06481481481481481, -.1388888888888889, 0.462962962962963, .09259259259259259, .09259259259259259, 0.462962962962963 ] qn[0:3 * nx:3, 0:3 * ny:3] = evalSum(c1, vList) # node 2 c2 = [ -.1388888888888889, -.1388888888888889, -.1388888888888889, -.1388888888888889, .8333333333333334, .2777777777777778, .1666666666666667, .2777777777777778 ] qn[1:3 * nx:3, 0:3 * ny:3] = evalSum(c2, vList) # node 3 c3 = [ -.1388888888888889, .2314814814814815, -.1388888888888889, -.06481481481481481, 0.462962962962963, 0.462962962962963, .09259259259259259, .09259259259259259 ] qn[2:3 * nx:3, 0:3 * ny:3] = evalSum(c3, vList) # node 4 c4 = [ -.1388888888888889, -.1388888888888889, -.1388888888888889, -.1388888888888889, .2777777777777778, .1666666666666667, .2777777777777778, .8333333333333334 ] qn[0:3 * nx:3, 1:3 * ny:3] = evalSum(c4, vList) # node 5 c5 = [-0.25, -0.25, -0.25, -0.25, 0.5, 0.5, 0.5, 0.5] qn[1:3 * nx:3, 1:3 * ny:3] = evalSum(c5, vList) # node 6 c6 = [ -.1388888888888889, -.1388888888888889, -.1388888888888889, -.1388888888888889, .2777777777777778, .8333333333333334, .2777777777777778, .1666666666666667 ] qn[2:3 * nx:3, 1:3 * ny:3] = evalSum(c6, vList) # node 7 c7 = [ -.1388888888888889, -.06481481481481481, -.1388888888888889, .2314814814814815, .09259259259259259, .09259259259259259, 0.462962962962963, 0.462962962962963 ] qn[0:3 * nx:3, 2:3 * ny:3] = evalSum(c7, vList) # node 8 c8 = [ -.1388888888888889, -.1388888888888889, -.1388888888888889, -.1388888888888889, .1666666666666667, .2777777777777778, .8333333333333334, .2777777777777778 ] qn[1:3 * nx:3, 2:3 * ny:3] = evalSum(c8, vList) # node 9 c9 = [ -.06481481481481481, -.1388888888888889, .2314814814814815, -.1388888888888889, .09259259259259259, 0.462962962962963, 0.462962962962963, .09259259259259259 ] qn[2:3 * nx:3, 2:3 * ny:3] = evalSum(c9, vList) return XXn, YYn, qn
wp = pl.cos(o) + pl.sin(o) * 1j w = 1 n2 = n * 2 for m in range(0, n): for k in range(m, N, n2): i = k + n even, odd = sig[k], w * sig[i] sig[k] = even + odd sig[i] = even - odd w *= wp n = n2 return sig / N T = 128 saw = pl.zeros(T) t = pl.arange(0, T) N = T // 2 for k in range(1, N): saw += (1 / k) * pl.sin(2 * pl.pi * k * t / T) saw *= 2 / (pl.pi) spec = fft(saw) mags = abs(spec) scal = max(mags) pl.figure(figsize=(8, 3)) pl.stem(t, (mags / scal), 'k-') pl.ylim(0, 1.1) pl.xlim(0, T)
def date_calculator(Settings): """Simulates MATS FOV and stars. Used by Mode121-123. Simuates MATS FOV and visible stars for one orbit then skips ahead for *Settings['Timeskip']* amount of days (as defined in the *Configuration File*). Saves the date, pointing RA and Dec, and the magnitude of the brightest visible star at each timestep. Arguments: Settings (dict): Dictionary containing settings for this simulation. Returns: (array): Array containing date in first column and brightest magnitude visible in the second. Contains current Dec and RA in 3rd and 4th column respectively. """ Timeline_settings = OPT_Config_File.Timeline_settings() "To either calculate when stars are visible and schedule from that data or just schedule at a given time given by Mode120_settings['start_date']" if (Settings['automatic'] == False): if (Settings['start_date'] == '0'): date = ephem.Date(Timeline_settings['start_date']) else: try: date = ephem.Date(Settings['start_date']) except: Logger.error( 'Could not get Settings["start_date"], exiting...') sys.exit() return date elif (Settings['automatic'] == True): "Simulation length and timestep" log_timestep = Settings['log_timestep'] Logger.debug('log_timestep: ' + str(log_timestep)) timestep = Settings['timestep'] #In seconds Logger.info('timestep set to: ' + str(timestep) + ' s') if (Settings['TimeToConsider'] <= Timeline_settings['duration']): duration = Settings['TimeToConsider'] else: duration = Timeline_settings['duration'] Logger.info('Duration set to: ' + str(duration) + ' s') timesteps = int(ceil(duration / timestep)) + 2 Logger.info('Maximum number of timesteps set to: ' + str(timesteps)) timeline_start = ephem.Date(Timeline_settings['start_date']) initial_time = ephem.Date(timeline_start + ephem.second * Settings['freeze_start']) Logger.info('initial_time set to: ' + str(initial_time)) "Get relevant stars" result = Vizier(columns=['all'], row_limit=3000).query_constraints( catalog='I/239/hip_main', Vmag=Settings['Vmag']) star_cat = result[0] ROWS = star_cat[0][:].count() stars = [] stars_dec = zeros((ROWS, 1)) stars_ra = zeros((ROWS, 1)) "Insert stars into Pyephem" for t in range(ROWS): s = "{},f|M|F7,{},{},{},2000/01/01 11:58:55.816" s = s.format(star_cat[t]['HIP'], deg2HMS(ra=star_cat[t]['_RA.icrs']), deg2HMS(dec=star_cat[t]['_DE.icrs']), star_cat[t]['Vmag']) stars.append(ephem.readdb(s)) stars[t].compute(epoch='2000/01/01 11:58:55.816') stars_dec[t] = stars[t].dec stars_ra[t] = stars[t].ra Logger.debug('') Logger.debug('List of stars used: ' + str(star_cat)) Logger.debug('') "Calculate unit-vectors of stars" stars_x = cos(stars_dec) * cos(stars_ra) stars_y = cos(stars_dec) * sin(stars_ra) stars_z = sin(stars_dec) stars_r = array([stars_x, stars_y, stars_z]) stars_r = stars_r.transpose() "Prepare the output" "Array containing date in first column and brightest magnitude visible in the second. Contains current Dec and RA in 3rd and 4th column" date_magnitude_array = zeros((timesteps, 4)) "Set magntidues arbitrary large, which will correspond to no star being visible" date_magnitude_array[:, 1] = 100 "Pre-allocate space" lat_MATS = zeros((timesteps, 1)) long_MATS = zeros((timesteps, 1)) optical_axis = zeros((timesteps, 3)) stars_r_V_offset_plane = zeros((ROWS, 3)) stars_r_H_offset_plane = zeros((ROWS, 3)) stars_vert_offset = zeros((timesteps, ROWS)) stars_hori_offset = zeros((timesteps, ROWS)) r_V_offset_normal = zeros((timesteps, 3)) r_H_offset_normal = zeros((timesteps, 3)) star_counter = 0 skip_star_list = [] MATS_P = zeros((timesteps, 1)) Dec_optical_axis = zeros((timesteps, 1)) RA_optical_axis = zeros((timesteps, 1)) angle_between_orbital_plane_and_star = zeros((timesteps, ROWS)) "Constants" pointing_altitude = Settings['pointing_altitude'] / 1000 V_FOV = Settings['V_FOV'] H_FOV = Settings['H_FOV'] #5.67 is actual H_FOV yaw_correction = Timeline_settings['yaw_correction'] Logger.debug('H_FOV set to [degrees]: ' + str(H_FOV)) Logger.debug('V_FOV set to [degrees]: ' + str(V_FOV)) Logger.debug('yaw_correction set to: ' + str(yaw_correction)) TLE = OPT_Config_File.getTLE() Logger.debug('TLE used: ' + TLE[0] + TLE[1]) MATS_skyfield = api.EarthSatellite(TLE[0], TLE[1]) "Loop counter" t = 0 TimeSkips = 0 #time_skip_counter = 0 Timeskip = Settings[ 'TimeSkip'] #Days to skip ahead after each completed orbit current_time = initial_time Logger.info('') Logger.info('Start of simulation of MATS for Mode121/122/123') ################## Start of Simulation ######################################## "Loop and calculate the relevant angle of each star to each direction of MATS's FOV" while (current_time < timeline_start + ephem.second * duration): if (t * timestep % log_timestep == 0): LogFlag = True else: LogFlag = False Satellite_dict = Satellite_Simulator(MATS_skyfield, current_time, Timeline_settings, pointing_altitude, LogFlag, Logger) MATS_P[t] = Satellite_dict['OrbitalPeriod [s]'] lat_MATS[t] = Satellite_dict['Latitude [degrees]'] long_MATS[t] = Satellite_dict['Longitude [degrees]'] optical_axis[t] = Satellite_dict['OpticalAxis'] Dec_optical_axis[t] = Satellite_dict['Dec_OpticalAxis [degrees]'] RA_optical_axis[t] = Satellite_dict['RA_OpticalAxis [degrees]'] r_H_offset_normal[t] = Satellite_dict['Normal2H_offset'] r_V_offset_normal[t] = Satellite_dict['Normal2V_offset'] ############# End of Calculations of orbital and pointing vectors ##### "Add current date to date_magnitude_array" date_magnitude_array[t, 0] = current_time "Add optical axis Dec and RA to date_magnitude_array" date_magnitude_array[t, 2] = Dec_optical_axis[t] date_magnitude_array[t, 3] = RA_optical_axis[t] ###################### Star-mapper #################################### "Check position of stars relevant to pointing direction" for x in range(ROWS): "Skip star if it is not visible during this epoch" if (stars[x].name in skip_star_list): continue "Project 'star vectors' ontop pointing H-offset and V-offset plane" stars_r_V_offset_plane[x] = stars_r[0][x] - ( dot(stars_r[0][x], r_V_offset_normal[t]) * r_V_offset_normal[t]) stars_r_H_offset_plane[x] = stars_r[0][x] - ( dot(stars_r[0][x], r_H_offset_normal[t]) * r_H_offset_normal[t]) "Dot product to get the Vertical and Horizontal angle offset of the star in the FOV" stars_vert_offset[t][x] = arccos( dot(optical_axis[t], stars_r_V_offset_plane[x]) / (norm(optical_axis[t]) * norm(stars_r_V_offset_plane[x]))) / pi * 180 stars_hori_offset[t][x] = arccos( dot(optical_axis[t], stars_r_H_offset_plane[x]) / (norm(optical_axis[t]) * norm(stars_r_H_offset_plane[x]))) / pi * 180 "For first loop of stars, make exception list for stars not visible during this epoch" if (t == 1): "To be able to skip stars far outside the orbital plane of MATS" angle_between_orbital_plane_and_star[t][x] = arccos( dot(stars_r[0][x], stars_r_V_offset_plane[x]) / norm(stars_r_V_offset_plane[x])) / pi * 180 if (abs(angle_between_orbital_plane_and_star[t][x]) > H_FOV / 2 + (duration * 2) / (365 * 24 * 3600) * 360): Logger.debug( 'Skip star: ' + stars[x].name + ', with angle_between_orbital_plane_and_star of: ' + str(angle_between_orbital_plane_and_star[t][x]) + ' degrees') skip_star_list.append(stars[x].name) continue "Check if star is in FOV" if (abs(stars_vert_offset[t][x]) < V_FOV / 2 and abs(stars_hori_offset[t][x]) < H_FOV / 2): #print('Star number:',stars[x].name,'is visible at',stars_vert_offset[t][x],'degrees VFOV and', \ #stars_hori_offset[t][x],'degrees HFOV','during',ephem.Date(current_time)) if (t % log_timestep == 0 or t == 1): Logger.debug('Current time: ' + str(current_time)) Logger.debug('Star: ' + stars[x].name + ', with H-offset: ' + str(stars_hori_offset[t][x]) + ' V-offset: ' + str(stars_vert_offset[t][x]) + ' in degrees is visible') "Check if it is the brightest star spotted in the current FOV at the current date, and if so, replace the current value" if (stars[x].mag < date_magnitude_array[t, 1]): date_magnitude_array[t, 1] = stars[x].mag star_counter = star_counter + 1 ######################### End of star_mapper ############################# "Increase Simulation Time with a timestep, or skip ahead if 1 orbit is completed" t += 1 if (t * timestep >= MATS_P[t - 1] * (TimeSkips + 1)): current_time = ephem.Date(current_time + ephem.second * Timeskip) TimeSkips += 1 else: current_time = ephem.Date(current_time + ephem.second * timestep) ''' "Increment time with timestep or jump ahead in time if a whole orbit was completed" if( (current_time - initial_time)/ephem.second > (timeskip/ephem.second * time_skip_counter + MATS_P[t] * (time_skip_counter+1)) ): "If one orbit has passed -> increment 'current_time' with 'timeskip' amount of days" time_skip_counter = time_skip_counter + 1 current_time = ephem.Date(current_time + timeskip) else: "Else just increment the current_time with timestep" current_time = ephem.Date(current_time + ephem.second * timestep) "Loop counter" t = t + 1 ''' ################## End of Simulation ######################################## return (date_magnitude_array)
def eval_W_integral_towed(self,slip,figNum=3): # individual sigma and tau terms in the weight integral def w_func_t1(th,th1,r,b,n,k1,k2): outval = sig_1(th,th1,r,b,n,k1,k2)*py.cos(th) return outval def w_func_t2(th,th0,th1,th2,r,b,n,k1,k2): outval = sig_2(th,th0,th1,th2,r,b,n,k1,k2)*py.cos(th) return outval def w_func_t3(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t1(th,th0,th1,r,b,n,k1,k2,c,K,phi,slip)*py.sin(th) return outval def w_func_t4(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip): outval = tau_t2(th,th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)*py.sin(th) return outval # weight function, used for fsolve def W_towed_func(th1,th0,th2,W,r,b,n,k1,k2,phi,slip,K,c): term1 = sci_int.quad(w_func_t1,th0,th1,args=(th1,r,b,n,k1,k2) ) term2 = sci_int.quad(w_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(w_func_t3,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(w_func_t4,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) error = r*b*(term1[0] + term2[0] +term3[0] - term4[0]) - W return error # weight function, returns all the individual terms def W_towed_func_terms(th1,th0,th2,W,r,b,n,k1,k2,phi,slip,K,c): term1 = sci_int.quad(w_func_t1,th0,th1,args=(th1,r,b,n,k1,k2) ) term2 = sci_int.quad(w_func_t2,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2)) term3 = sci_int.quad(w_func_t3,th0,th1,args=(th0,th1,r,b,n,k1,k2,c,K,phi,slip)) term4 = sci_int.quad(w_func_t4,th2,th0,args=(th0,th1,th2,r,b,n,k1,k2,c,K,phi,slip)) error = r*b*(term1[0] + term2[0] +term3[0] - term4[0]) - W return [error, r*b*term1[0], r*b*term2[0], r*b*term3[0], r*b*term4[0] ] # end helper functions # solve for contact angle, th_1, using equlibrium of vertical forces th0 = self._th0 th2 = self._th2 k1 = self._k1 k2 = self._k2 b = self._width r = self._radius n = self._n c = self._coh K = self._K phi = self._phi slip = self._skid W = self._weight # initial guess for theta 1 th1_initial = degToRad(45.0) if( th1_initial/th0 < 1.5): th1_initial = th0*2.0 # iterate until th1 is found th1 = sci_opt.fsolve(W_towed_func,th1_initial,args=(th0,th2,W,r,b,n,k1,k2,phi,slip,K,c) ) w_error = W_towed_func(th1,th0,th2,W,r,b,n,k1,k2,phi,slip,K,c) lg.info('theta_1, degrees = ' + str(radToDeg(th1))+', w_error = ' + str(w_error)+'\n') if( self._plots): # if I want plots, need to find th1 for each value of skid in skid_arr i_range = self._slip_arr th0_array = self._th0_arr # th0 = th0(skid) th1_out = th1 th1_array = py.zeros(len(i_range)) t1_arr = py.zeros(len(i_range)) t2_arr = py.zeros(len(i_range)) t3_arr = py.zeros(len(i_range)) t4_arr = py.zeros(len(i_range)) for idx in range(0,len(i_range)): slip_curr = i_range[idx] th0_curr = th0_array[idx] th1_out = sci_opt.fsolve(W_towed_func,th1_out,args=(th0_curr,th2,W,r,b,n,k1,k2,phi,slip_curr,K,c)) th1_array[idx] = th1_out # lg.info('slip= '+str(slip_curr) + ', th1= '+str(th1_out) ) # I want to see how each term of the weight function changes [error,t1,t2,t3,t4] = W_towed_func_terms(th1_out,th0_curr,th2,W,r,b,n,k1,k2,phi,slip_curr,K,c) # lg.info('slip = '+str(slip_curr) + ', error = ' + str(error)) t1_arr[idx] = t1 t2_arr[idx] = t2 t3_arr[idx] = t3 t4_arr[idx] = t4 fig=plt.figure() ax = fig.add_subplot(211,title='Fig. '+str(figNum) + '(d)') ax.plot(i_range,radToDeg(th1_array),i_range,radToDeg(self._th0_arr),linewidth=1.5) ax.set_xlabel('skid ratio') ax.set_ylabel(r'$\theta$ [degrees]' ) ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend((r'$\theta_1$',r'$\theta_0$')) ax.grid(True) ax = fig.add_subplot(212) ax.plot(i_range,t1_arr,i_range,t2_arr,i_range,t3_arr,i_range,t4_arr,linewidth=1.5) ax.set_xlabel('skid ratio') if( self._units == 'ips'): ax.set_ylabel('weight [lb]') else: ax.set_ylabel('weight [kg]') ax.set_xlim([0,i_range[len(i_range)-1]+0.2]) ax.legend((r'$\sigma_1$',r'$\sigma_2$',r'$\tau_1$',r'$\tau2$')) ax.grid(True) # we will need all the values of th1 for further plots self._th1_arr = th1_array # see what we get for weight # i_check = py.arange(20.,50.,1.) # for i in range(0,len(i_check)): # [W_check,ct1,ct2,ct3,ct4] = W_towed_func_terms(degToRad(i_check[i]),degToRad(19.0),th2,W,r,b,n,k1,k2,phi,0.3,K,c) # lg.info('weight check, slip = 30%, w_error='+str(W_check)) # lg.info('term 1='+str(ct1) +', term2= '+str(ct2)) # lg.info('term3= '+str(ct3) + ', term4= '+str(ct4)) return th1
L = 100 # length of side of box M = 20 # length of side of square of particles B = 10 # number of coarse-grainig bins per side nsteps = input('number of steps in walk -> ') steps = range(nsteps) seed = input('random number seed -> ') random.seed(seed) # initial positions of particles form a M*M block in the middle of the box xside = range((L-M)//2, (L+M)//2) yside = range((L-M)//2, (L+M)//2) x = [i for i in xside for j in yside] # x-locations of the particles y = [j for i in xside for j in yside] # y-locations of the particles N = len(xside)*len(yside) # number of particles S = [0.0]*nsteps # entropy P = pylab.zeros((B, B)) # probability of particle being in each bin # setup animated figure pylab.figure(figsize=(6, 6)) (points, ) = pylab.plot(x, y, ',') pylab.xlim(0, L) pylab.ylim(0, L) pylab.xticks(range(0, L+1, L//B)) pylab.yticks(range(0, L+1, L//B)) pylab.xlabel('x') pylab.ylabel('y') pylab.grid() # simulate the random walks for n in steps: # update plot
import pylab as pl xvec = pl.linspace(-10, 10, 100) yvec = pl.linspace(-10, 10, 100) density = pl.zeros([100, 100]) for nx, x in enumerate(xvec): for ny, y in enumerate(yvec): density[nx, ny] = x**2 + y**2 pl.imshow(density, cmap='BuGn', extent=[0, 18, 0, 18]) pl.xlabel("X " + r"$(\AA)$", fontsize=18) pl.ylabel("Y " + r"$(\AA)$", fontsize=18) #pl.xlim([0,18]) #pl.ylim([0,18]) #pl.xticks(range(0,19),range(0,19)) #pl.yticks(range(0,19),range(0,19)) #pl.axis([0, 18, 0, 18]) cbar = pl.colorbar() cbar.set_label("Particle Density" + r"$\left(\frac{Particles}{\AA^3}\right)$", labelpad=30, fontsize=18, rotation=270) pl.title(r"$%s = %s K$" % ('\mu', 35), fontsize=24) pl.show()
R = sc.loadobj('results/rapid_spend_results.obj') #%% Fig. 1 -- DALYs if fig1: sc.heading('Spending figure') interv_category = interv_data['Category 1'].tolist() categories = sorted(set(interv_category)) ncategories = len(categories) nintervs = len(R[0]['alloc']) mapping = [] for i_c in interv_category: for c, cat in enumerate(categories): if i_c == cat: mapping.append(c) allocdata = pl.zeros((2, ncategories)) for country in R.keys(): # tODO: different regions opt_alloc = R[country]['alloc'] orig_alloc = spend_data[country] for i in range(nintervs): c = mapping[i] allocdata[0, c] += orig_alloc[i] allocdata[1, c] += opt_alloc[i] fig = pl.figure() x = pl.arange(2) axlist = [] previous = pl.zeros(2) for c in range(len(categories)): current = allocdata[:, c] / 1e9 ax = pl.bar(x, current, bottom=previous)
import math, pylab, mpl_toolkits.mplot3d eps = 1e-2 # fractional error allowed L = 1.0 # length of each side N = 21 # Number of grid points on a side dy = dx = L / (N - 1.0) xmax = ymax = 1.0 xmin = ymin = 0.0 # setting up arrays x = pylab.array(range(N)) * dx y = pylab.array(range(N)) * dy x, y = pylab.meshgrid(x, y) u0 = pylab.zeros((N, N)) u1 = pylab.zeros((N, N)) Ex = pylab.zeros((N, N)) Ey = pylab.zeros((N, N)) # boundary conditions for j in range(N): u1[j, N - 1] = u0[j, N - 1] = u1[j, 0] = u0[j, 0] = 0.0 for k in range(N): u1[N - 1, k] = u0[N - 1, k] = u1[0, k] = u0[0, k] = 0.0 for j in range(5, 16): u0[j, 5] = -1.0 for k in range(5, 16): u0[k, 15] = 1.0 n = 0 # number of iterations
Mirror=False) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=True) val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=True) plot_data = {} plot_data['train_loss'] = zeros(epochs) plot_data['train_acc'] = zeros(epochs) plot_data['train_acc_hate'] = zeros(epochs) plot_data['train_acc_notHate'] = zeros(epochs) plot_data['train_acc_avg'] = zeros(epochs) plot_data['val_loss'] = zeros(epochs) plot_data['val_acc'] = zeros(epochs) plot_data['val_acc_hate'] = zeros(epochs) plot_data['val_acc_notHate'] = zeros(epochs) plot_data['val_acc_avg'] = zeros(epochs) plot_data['epoch'] = 0 # if evaluate: # t.validate(val_loader, model, criterion, print_freq, plot_data)
import pylab as p from matplotlib.toolkits.basemap import Basemap import os import Scientific.IO.NetCDF as S #--- Get data (assuming lon goes from 0 to 360): Make arrays cyclic # in longitude: time_idx = 5 #@@@ USER ADJUSTABLE f = S.NetCDFFile('qm_seasonal_1yr.nc', mode='r') lat = f.variables['lat'].getValue() lon = f.variables['lon'].getValue() u1_all = f.variables['u1'].getValue() if p.allclose(lon[0], 0): u1 = p.zeros((p.size(lat), p.size(lon) + 1)) u1[:, 0:-1] = u1_all[time_idx, :, :] u1[:, -1] = u1_all[time_idx, :, 0] tmp = copy.copy(lon) lon = p.zeros((p.size(tmp) + 1, )) lon[0:-1] = tmp[:] lon[-1] = tmp[0] + 360 del tmp f.close() #--- Mapping information: map = Basemap(projection='cyl', resolution='l',
def track(input_video_path): """ notation: variables ending with f are in the frequency domain. """ # parameters according to the paper -- padding = 1.0 # extra area surrounding the target #spatial bandwidth (proportional to target) output_sigma_factor = 1 / float(16) sigma = 0.2 # gaussian kernel bandwidth lambda_value = 1e-2 # regularization # linear interpolation factor for adaptation interpolation_factor = 0.075 info = load_video_info(input_video_path) img_files, pos, target_sz, \ should_resize_image, ground_truth, video_path = info # window size, taking padding into account sz = pylab.floor(target_sz * (1 + padding)) # desired output (gaussian shaped), bandwidth proportional to target size output_sigma = pylab.sqrt(pylab.prod(target_sz)) * output_sigma_factor grid_y = pylab.arange(sz[0]) - pylab.floor(sz[0] / 2) grid_x = pylab.arange(sz[1]) - pylab.floor(sz[1] / 2) #[rs, cs] = ndgrid(grid_x, grid_y) rs, cs = pylab.meshgrid(grid_x, grid_y) y = pylab.exp(-0.5 / output_sigma**2 * (rs**2 + cs**2)) yf = pylab.fft2(y) #print("yf.shape ==", yf.shape) #print("y.shape ==", y.shape) # store pre-computed cosine window cos_window = pylab.outer(pylab.hanning(sz[0]), pylab.hanning(sz[1])) total_time = 0 # to calculate FPS positions = pylab.zeros((len(img_files), 2)) # to calculate precision global z, response z = None alphaf = None response = None for frame, image_filename in enumerate(img_files): if True and ((frame % 10) == 0): print("Processing frame", frame) # load image image_path = os.path.join(video_path, image_filename) im = pylab.imread(image_path) if len(im.shape) == 3 and im.shape[2] > 1: im = rgb2gray(im) #print("Image max/min value==", im.max(), "/", im.min()) if should_resize_image: im = scipy.misc.imresize(im, 0.5) start_time = time.time() # extract and pre-process subwindow x = get_subwindow(im, pos, sz, cos_window) is_first_frame = (frame == 0) if not is_first_frame: # calculate response of the classifier at all locations k = dense_gauss_kernel(sigma, x, z) kf = pylab.fft2(k) alphaf_kf = pylab.multiply(alphaf, kf) response = pylab.real(pylab.ifft2(alphaf_kf)) # Eq. 9 # target location is at the maximum response r = response row, col = pylab.unravel_index(r.argmax(), r.shape) pos = pos - pylab.floor(sz / 2) + [row, col] if debug: print("Frame ==", frame) print("Max response", r.max(), "at", [row, col]) pylab.figure() pylab.imshow(cos_window) pylab.title("cos_window") pylab.figure() pylab.imshow(x) pylab.title("x") pylab.figure() pylab.imshow(response) pylab.title("response") pylab.show(block=True) # end "if not first frame" # get subwindow at current estimated target position, # to train classifer x = get_subwindow(im, pos, sz, cos_window) # Kernel Regularized Least-Squares, # calculate alphas (in Fourier domain) k = dense_gauss_kernel(sigma, x) new_alphaf = pylab.divide(yf, (pylab.fft2(k) + lambda_value)) # Eq. 7 new_z = x if is_first_frame: #first frame, train with a single image alphaf = new_alphaf z = x else: # subsequent frames, interpolate model f = interpolation_factor alphaf = (1 - f) * alphaf + f * new_alphaf z = (1 - f) * z + f * new_z # end "first frame or not" # save position and calculate FPS positions[frame, :] = pos total_time += time.time() - start_time # visualization plot_tracking(frame, pos, target_sz, im, ground_truth) # end of "for each image in video" if should_resize_image: positions = positions * 2 print("Frames-per-second:", len(img_files) / total_time) title = os.path.basename(os.path.normpath(input_video_path)) if len(ground_truth) > 0: # show the precisions plot show_precision(positions, ground_truth, video_path, title) return
try: l = re.split(" ", line) number = float(l[0]) NumOfCells = NumOfCells + number if (counter <= number): counter = number crutial_line = line_numb except: pass line_numb = line_numb + 1 #print crutial_line print "There are", int(NumOfCells), "cells in the population" L2 = re.split(" ", theData[crutial_line]) rows = (len(L2) - 4) / 3 genes = p.zeros((rows, 3)) if rows is 1: descr = "T = " + str(T) + "; " + str(rows) + " genes; " perct = counter / NumOfCells * 100 PERC = '%(perc)1.2f %% of population' % {"perc": perct} descr = descr + PERC print descr else: descr = "T = " + str(T) + "; " + str(rows) + " genes; " perct = counter / NumOfCells * 100 PERC = "%(perc)1.2f %% of population" % {"perc": perct} descr = descr + PERC print descr print "Hight (A) , sigma , positions of max (c)" for i in xrange(len(L2) - 4): ii = p.floor(i / 3)
peak_profile = [] for i in range(numLines): lineString = input.readline() lineList = lineString.split() for j in range(10): peak_profile.append(int(lineList[j + 1])) yobs = pylab.array(peak_profile) # Gaussian profile if profile_function == 0: # popt is an array of the optimized parameters # pcov is the covariance matrix p0 = pylab.zeros(5) # initial values of parameters ymax = float(max(yobs)) p0[0] = ymax * 2.5 * sqrt2pi # initial value of aG p0[1] = 2.5 # initial value of sigG p0[2] = yobs.argmax() try: popt, success = leastsq(residuals_func0, p0, args=(yobs, x)) intI = popt[0] sigmaG = popt[1] mu = popt[2] slope = popt[3] constant = popt[4] # Get background counts background_total = 0.0
masslim_catalogs = glob.glob('../data/completeness/masslimits_*_master.dat') masslim_data = [mypy.readcat(mi) for mi in masslim_catalogs] masslim95 = pylab.array([mi.masslim95 for mi in masslim_data]) masslim95_zax = masslim_data[0].z masslim95_average = masslim95.sum(axis=0) / len(masslim95) ### selecting redshift from EAGLE si = 20 simdata = mypy.readcat(sim_catalogs[si]) ### reading voronoi map vmap = fits.getdata('../data/eagle_simulations/medVoronoi.overdens.%02i.fits' % si) dx_map, dy_map = vmap.shape overdens_arr = pylab.zeros(len(simdata.GalaxyID)) for i in range(len(simdata.GalaxyID)): x, y = int(simdata.x_cMpc[i] * dx_map / 100. - 0.5), int(simdata.y_cMpc[i] * dy_map / 100. - 0.5) overdens_arr[i] = vmap[y][x] ### calculating MFs dm = 0.25 lmassbins = pylab.arange(9.5 - dm / 2., 11.5 + dm, dm) lmassbars = (lmassbins[1:] + lmassbins[:-1]) / 2. xlo, xhi = 25. * 100. / dx_map, 100 - 25. * 100. / dx_map ylo, yhi = 25. * 100. / dy_map, 100 - 25. * 100. / dy_map inds0 = pylab.find((overdens_arr > 0.0) & (overdens_arr < 0.5) & (simdata.x_cMpc > xlo) & (simdata.x_cMpc < xhi)
def plot_sigTau_towed(self,th1_cs,skid,figNum=11): th0 = self._th0 th2 = self._th2 r = self._radius b = self._width k1 = self._k1 k2 = self._k2 n = self._n phi = self._phi K = self._K c = self._coh incr = (th1_cs - th2) / 100.0 # plot increment th_arr = py.arange(0,th1_cs + incr, incr) # find sigma, tau at these discrete vals sig_arr = py.zeros(len(th_arr)) tau_arr = py.zeros(len(th_arr)) slip_arr = py.zeros(len(th_arr)) for idx in range(0,len(th_arr)): th = th_arr[idx] if(th < th0): # we're in the bototm region sig_curr = sig_2(th,th0,th1_cs,th2,r,b,n,k1,k2) tau_curr = -tau_t2(th,th0,th1_cs,th2,r,b,n,k1,k2,c,K,phi,skid) slip_j = j2(th,th0,r,skid) sig_arr[idx] = sig_curr tau_arr[idx] = tau_curr slip_arr[idx] = slip_j else: # we're in the top region () sig_curr = sig_1(th, th1_cs,r,b,n,k1,k2) tau_curr = tau_t1(th,th0,th1_cs,r,b,n,k1,k2,c,K,phi,skid) slip_j = j1(th,th0,th1_cs,r,skid) sig_arr[idx] = sig_curr tau_arr[idx] = tau_curr slip_arr[idx] = slip_j if( self._plots): fig = plt.figure() ax = fig.add_subplot(211,title='Fig. ' + str(figNum) +' skid=' + str(skid)) ax.plot(radToDeg(th_arr),sig_arr,radToDeg(th_arr),tau_arr,linewidth=1.5) ax.set_xlabel('theta [deg]') if( self._units == 'ips'): ax.set_ylabel('stress [psi]') else: ax.set_ylabel('stress [Pa]') ax.legend((r'$\sigma$($\theta$)',r'$\tau$($\theta$)')) ax.grid(True) # take a look at what I"m using for slip displacement also ax = fig.add_subplot(212) ax.plot(radToDeg(th_arr),slip_arr,linewidth=1.5) ax.set_xlabel('theta [deg]') if( self._units == 'ips'): ax.set_ylabel('slip disp.[in]') else: ax.set_ylabel('slip disp.[m]') ax.grid(True) # polar plots fig=plt.figure() ax=fig.add_subplot(111,projection='polar') ax.plot(th_arr,sig_arr/1000.,'b',linewidth=1.5) ax.plot(th_arr,tau_arr/1000.,'r--',linewidth=1.5) # fix the axes ax.grid(True) if( self._units == 'ips'): leg = ax.legend((r'$\sigma$ [kip]',r'$\tau$')) else: leg = ax.legend((r'$\sigma$ [kPa]',r'$\tau$')) leg.draggable() ax.set_theta_zero_location('S') # also, draw the tire polar_r_offset = py.average(sig_arr)/1000. theta = py.arange(0.,2.*py.pi+0.05,0.05) tire_pos = py.zeros(len(theta)) ax.plot(theta,tire_pos,color='k',linewidth=1.0) ax.set_rmin(-polar_r_offset) ax.set_title(r'towed wheel stresses, $\theta_1$ = %4.3f [rad]' %th1_cs) ax.set_thetagrids([-10,0,10,20,30,40,50,60]) return [sig_arr, tau_arr]
def calc_psi(self): # combine coil floops with plasma floop r_floops_total_list = list(self.coil_set.r_floops) r_floops_total_list.extend([self.plasma_coil.r_floop]) z_floops_total_list = list(self.coil_set.z_floops) z_floops_total_list.extend([self.plasma_coil.z_floop]) r_floops_total = P.array(r_floops_total_list) z_floops_total = P.array(z_floops_total_list) self.r_floops_total = r_floops_total self.z_floops_total = z_floops_total self.n_floops = len(r_floops_total) # calc coils GFs for floops psi_coils_floops, b_r, b_z = \ self.coil_set.calc_fields(r_range=self.r_floops_total, z_range=self.z_floops_total) self.psi_coils_floops = psi_coils_floops # calc plasma coil GFs for floops r_arr, z_arr, psi_plasma_coil_floops, b_r, b_z, r_out, z_out = \ self.plasma_coil.calc_fields(r_range=self.r_floops_total, z_range=self.z_floops_total) self.psi_plasma_coil_floops = psi_plasma_coil_floops # combine all GFs for floops total_psi_floops_list = list(psi_coils_floops) total_psi_floops_list.append(psi_plasma_coil_floops) total_psi_floops = P.array(total_psi_floops_list) self.total_psi_floops = total_psi_floops # make mutual inductance matrix M = P.zeros([self.n_floops, self.n_floops], dtype=fdtype) # fill up M (NOT RIGHT, /100 AND OFF BY A BIT) M[:, 0:self.n_floops] = total_psi_floops # self.M = M # for some reason we need the transpose of M made this way self.M = M.T # solve for coil currents to make 1 Wb on all flux loops i_floops = P.linalg.solve(self.M, P.ones(self.n_floops, dtype=fdtype)) # make GFs GFs = P.zeros([self.n_floops, 100, 100]) # calc GFs for coils psi_coils, b_r, b_z = \ self.coil_set.calc_fields(r_range=P.array([1e-6, 4.0], dtype=fdtype), z_range=P.array([-1.5, 1.5], dtype=fdtype), r_dim=100, z_dim=100) self.psi_coils = psi_coils # calc GF for plasma coil r_arr, z_arr, psi_plasma_coil, b_r, b_z, r_out, z_out = \ self.plasma_coil.calc_fields(r_range=P.array([1e-6, 4.0], dtype=fdtype), z_range=P.array([-1.5, 1.5], dtype=fdtype), r_dim=100, z_dim=100) self.psi_plasma_coil = psi_plasma_coil # fill up GFs GFs[0:self.coil_set.n_coils, ...] = psi_coils GFs[-1, ...] = psi_plasma_coil self.GFs = GFs # normalize to I_p at 3.2 MA i_fact = 3.2e6 / i_floops[-1] i_floops *= i_fact # calculate flux on mesh psi = 0.0 for ii, i_val in enumerate(i_floops): psi += i_val * GFs[ii, ...] self.i_floops = i_floops self.i_fact = i_fact self.psi = psi return psi