def his(im): ''' 直方图均衡化处理 ''' r = im[:, :, 0] g = im[:, :, 1] b = im[:, :, 2] imhist_r, bins_r = pl.histogram(r, 256, normed=True) imhist_g, bins_g = pl.histogram(g, 256, normed=True) imhist_b, bins_b = pl.histogram(b, 256, normed=True) cdf_r = imhist_r.cumsum() cdf_g = imhist_g.cumsum() cdf_b = imhist_b.cumsum() cdf_r = cdf_r * 255 / cdf_r[-1] cdf_g = cdf_g * 255 / cdf_g[-1] cdf_b = cdf_b * 255 / cdf_b[-1] im_r = pl.interp(r.flatten(), bins_r[:256], cdf_r) im_g = pl.interp(g.flatten(), bins_g[:256], cdf_g) im_b = pl.interp(b.flatten(), bins_b[:256], cdf_b) #原始通道图 #均衡化之后的通道图 im_r = im_r.reshape([im.shape[0], im.shape[1]]) im_g = im_g.reshape([im.shape[0], im.shape[1]]) im_b = im_b.reshape([im.shape[0], im.shape[1]]) im_p = copy.deepcopy(im) im_p[:, :, 0] = im_r im_p[:, :, 1] = im_g im_p[:, :, 2] = im_b return im_p
def loadMaterial(name, llam): ## Loads a given material from a list of text files found in the materials folder # # @name The name (stirng) of the text file without the .txt exetension # !If a non-string is given as input (i.e. a constant), that value is just returned # @llam The list of wavelengths (in nm) that the material parameters should be evaluated at # # @return Complex refractive index (absorbing material having negative imaginary part) if not type(name) == str: return name f = open(PATH + name + ".txt", 'r') f.next() lam = [] n = [] k = [] for line in f: try: tmp = [float(elm) for elm in line.split()] lam += [tmp[0]] n += [tmp[1]] k += [tmp[2]] except: break n = pl.interp(llam, lam, n) k = pl.interp(llam, lam, k) return n - 1.j * k
def average_gaunt_vanregemorter(deg, Eo, T): ''' Interpolate the maxwellian average of the Gaunt factor for electron collisions according to Van Regemorter 1962, ApJ deg: ionization degree Eo: transition energy [eV] T: temperature [K] ''' x = [0.01, 0.02, 0.04, 0.1, 0.2, 0.4, 1., 2., 4., 10.] av_gi = [1.160, 0.956, 0.758, 0.493, 0.331, 0.209, 0.100, 0.063, 0.040, 0.023] av_gii = [1.160, 0.977, 0.788, 0.554, 0.403, 0.290, 0.214, 0.201, 0.200, 0.200] x0 = Eo * Cst.Q / (Cst.K * T) if x0 <= 0.005: return 0.276 * (-0.57722 - pl.log(x0)) if deg.upper().strip() == 'I': if x0 > 10.: return 0.066 * x0**-0.5 else: return pl.interp(x0, x, av_gi) elif deg.upper().strip() == 'II': if x0 > 10.: return 0.200 else: return pl.interp(x0, x, av_gii) else: print("Z must be 'I' or 'II'") quit(1)
def createLinearOverlay(acts, out): import pylab x = numpy.arange(acts.shape[1]) / float(acts.shape[1] - 1) xx = numpy.arange(out.shape[1]) / float(out.shape[1] - 1) for i in range(acts.shape[0]): out[i] = pylab.interp(xx, x, acts[i]) for i in range(out.shape[1]): out[:, i] = pylab.interp(xx, x, out[:acts.shape[0], i]) return out
def draw_rand_gaussian_pos(self, min_r=pl.array([])): '''optional min_r, array or tuple of arrays on the form array([[r0,r1,...,rn],[z0,z1,...,zn]])''' x = pl.normal(0, self.radius, self.n) y = pl.normal(0, self.radius, self.n) z = pl.normal(0, self.radius, self.n) min_r_z = {} if pl.size(min_r) > 0: # != False: if type(min_r) == type(()): for j in xrange(pl.shape(min_r)[0]): min_r_z[j] = pl.interp(z, min_r[j][0, ], min_r[j][1, ]) if j > 0: [w] = pl.where(min_r_z[j] < min_r_z[j - 1]) min_r_z[j][w] = min_r_z[j - 1][w] minrz = min_r_z[j] else: minrz = pl.interp(z, min_r[0], min_r[1]) R_z = pl.sqrt(x**2 + y**2) [u] = pl.where(R_z < minrz) while len(u) > 0: for i in xrange(len(u)): x[u[i]] = pl.normal(0, self.radius, 1) y[u[i]] = pl.normal(0, self.radius, 1) z[u[i]] = pl.normal(0, self.radius, 1) if type(min_r) == type(()): for j in xrange(pl.shape(min_r)[0]): min_r_z[j][u[i]] = pl.interp( z[u[i]], min_r[j][0, ], min_r[j][1, ]) if j > 0: [w] = pl.where(min_r_z[j] < min_r_z[j - 1]) min_r_z[j][w] = min_r_z[j - 1][w] minrz = min_r_z[j] else: minrz[u[i]] = pl.interp(z[u[i]], min_r[0, ], min_r[1, ]) R_z = pl.sqrt(x**2 + y**2) [u] = pl.where(R_z < minrz) soma_pos = { 'xpos': x, 'ypos': y, 'zpos': z, } return soma_pos
def postprocessCpData(data,geo,newxcount): x = data[:,0] y = geo[:,1] Cp = data[:,1] n = data.shape[0] # compute finite difference of x to classify points as upper and lower airfoil surface dx = pl.diff(x) dy = pl.diff(y) L = pl.sqrt(dx**2+dy**2) Tx = dx/L Ty = dy/L Nx = -Ty Ny = +Tx T = pl.array((Tx,Ty)) T = T.transpose() N = pl.array((Nx,Ny)) N = N.transpose() midx = (x[0:n-1]+x[1:n])/2.0 midy = (y[0:n-1]+y[1:n])/2.0 midcp = (Cp[0:n-1]+Cp[1:n])/2.0 Tnode = pl.zeros( (n,2), pl.float64) Nnode = pl.zeros( (n,2), pl.float64) for i in range(1,n-1): Tnode[i,:] = bisector( T[i-1,:], T[i,:] ) Nnode[i,:] = bisector( N[i-1,:], N[i,:] ) Tnode[0,:] = bisector( T[0,:], T[-1,:] ) Tnode[-1,:] = bisector( T[0,:], T[-1,:] ) Nnode[0,:] = bisector( N[i-1,:], N[i,:] ) Nnode[-1,:] = bisector( N[i-1,:], N[i,:] ) # determine (safe) limits of x for interpolation xmin = min( min(x[dx<0]),min(x[dx>=0]) ) xmax = max( max(x[dx<0]),max(x[dx>=0]) ) # re-compute lower and upper Cp at new abscissae if ChebyshevSpacing: xnew = pl.linspace(pl.pi, 0, newxcount) xnew = (pl.cos(xnew)+1)/2.0 else: xnew = pl.linspace(xmin, xmax, newxcount) newCpUpper = pl.interp(xnew, pl.flipud(x[dx<0]), pl.flipud(Cp[dx<0])) newCpLower = pl.interp(xnew, x[dx>=0], Cp[dx>=0]) return (x,y,Cp,L,T,N,midx,midy,midcp,Tnode,Nnode,xnew,newCpUpper,newCpLower)
def cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: Number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ cdict = cmap._segmentdata.copy() # N colors colors_i = np.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) #I = interpolate.interp1d(D[:,0], D[:,1]) #I = interpolate.interp1d(D[:,0],D[:,1]) colors = interp(colors_i,D[:,0],D[:,1]) # Place these colors at the correct indices. A = np.zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) # Return colormap object. return plt.matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)
def f_PSD_from_file(filename, fLow, fNyq, deltaF): """ Read a detector ascii ASD file and return the PSD and frequency vector for use with ffts. """ f_in, S_in = numpy.loadtxt(filename, unpack=True) f = numpy.linspace(fLow, fNyq, scipy.ceil((fNyq - fLow) / deltaF) + 1) S = pylab.interp(f, f_in, S_in) # packing is of the form: # [0 deltaF 2*deltaF ... fNyquist-deltaF fNyquist -fNyquist+deltaF ... -2*deltaF -deltaF] PSD = scipy.zeros(2 * (fNyq / deltaF), dtype='float') + scipy.inf PSD[round(fLow / deltaF):fNyq / deltaF + 1] = S**2 if -round(fLow / deltaF) == 0: PSD[fNyq / deltaF + 1:] = S[-2:0:-1]**2 else: PSD[fNyq / deltaF + 1:-round(fLow / deltaF)] = S[-2:0:-1]**2 f = f_for_fft(fLow, fNyq, deltaF) nNyq = round(fNyq / deltaF) nLow = round(fLow / deltaF) PSD = scipy.zeros(2 * nNyq) + scipy.inf PSD[nLow:nNyq + 1] = S**2 if -nLow == 0: PSD[nNyq + 1:] = S[-2:0:-1]**2 else: PSD[nNyq + 1:-nLow] = S[-2:0:-1]**2 return f, PSD
def extraplinpoint(x, y, xi): """ Extrapolate yi from arrays x,y and point xi using linear interpolation. @param x: Array of x values. @param y: Array of x values. @param xi: Scalar x value - must be less than min(x) or greater than max(x). @return: yi, the y value corresponding to xi. """ xmax = max(x) xmin = min(x) ymax = max(y) ymin = min(y) if xi <= xmax and xi >= xmin: raise Exception, "xi must be outside range of x!" dx = (xmax - xmin) / 1000.0 #interpolate a point just inside the range if xi > xmax: xt = xmax - dx if xi < xmin: xt = xmin + dx yt = interp(xt, x, y) #Then assume that the point outside the range is linear with respect to x and x+dx if xi > xmax: m = (ymax - yt) / (xmax - xt) else: m = (yt - ymin) / (xt - xmax) b = yt - m * xt yi = m * xi + b return yi
def extraplinpoint(x,y,xi): """ Extrapolate yi from arrays x,y and point xi using linear interpolation. @param x: Array of x values. @param y: Array of x values. @param xi: Scalar x value - must be less than min(x) or greater than max(x). @return: yi, the y value corresponding to xi. """ xmax = max(x) xmin = min(x) ymax = max(y) ymin = min(y) if xi <= xmax and xi >= xmin: raise Exception,"xi must be outside range of x!" dx = (xmax - xmin)/1000.0 #interpolate a point just inside the range if xi > xmax: xt = xmax - dx if xi < xmin: xt = xmin + dx yt = interp(xt,x,y) #Then assume that the point outside the range is linear with respect to x and x+dx if xi > xmax: m = (ymax - yt)/(xmax - xt) else: m = (yt - ymin)/(xt - xmax) b = yt - m * xt yi = m * xi + b return yi
def f_PSD_from_file(filename, fLow, fNyq, deltaF): """ Read a detector ascii ASD file and return the PSD and frequency vector for use with ffts. """ f_in,S_in = numpy.loadtxt(filename, unpack=True) f = numpy.linspace(fLow,fNyq,scipy.ceil((fNyq-fLow)/deltaF)+1) S = pylab.interp(f, f_in, S_in) # packing is of the form: # [0 deltaF 2*deltaF ... fNyquist-deltaF fNyquist -fNyquist+deltaF ... -2*deltaF -deltaF] PSD = scipy.zeros(2*(fNyq/deltaF), dtype='float')+scipy.inf PSD[round(fLow/deltaF):fNyq/deltaF+1] = S**2 if -round(fLow/deltaF) == 0: PSD[fNyq/deltaF+1:] = S[-2:0:-1]**2 else: PSD[fNyq/deltaF+1:-round(fLow/deltaF)] = S[-2:0:-1]**2 f = f_for_fft(fLow, fNyq, deltaF) nNyq = round(fNyq/deltaF) nLow = round(fLow/deltaF) PSD = scipy.zeros(2*nNyq)+scipy.inf PSD[nLow:nNyq+1] = S**2 if -nLow == 0: PSD[nNyq+1:] = S[-2:0:-1]**2 else: PSD[nNyq+1:-nLow] = S[-2:0:-1]**2 return f,PSD
def process_timeseries_parallel(elev): try: e = interp(nhours,hours,elev) tides = tt.t_tide(e,dt=dthours,out_style=None) except: tides=None return tides
def process_point(i): try: e = interp(nhours,hours,ncv['elev'][:,i]) tides = tt.t_tide(e,dt=dthours,out_style=None) except: tides=None return tides
def histeq(im, nbr_bins = 256): """ Histogram equalization of a grayscale image. """ # get image histogram imhist, bins = pl.histogram(im.flatten(), nbr_bins, normed = True) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values im2 = pl.interp(im.flatten(), bins[:-1], cdf) return im2.reshape(im.shape)
def resample(target_frequency, source_frequency, data): source_period = 1.0 / source_frequency stop = len(data) * source_period source_xs = pylab.arange(0.0, stop, source_period) target_period = 1.0 / target_frequency target_xs = pylab.arange(0.0, stop, target_period) if len(source_xs) > len(data): source_xs = source_xs[:-1] return pylab.interp(target_xs, source_xs, data)
def process_chunk_parallel(elev): tides=[] for i in range(elev.shape[1]): try: e = interp(nhours,hours,elev[:,i]) tides.append(tt.t_tide(e,dt=dthours,out_style=None)) except: tides.append(None) return tides
def process_parallel(i): try: nnc = netCDF4.Dataset('schout_2.nc') e = interp(nhours,hours,nnc.variables['elev'][:,i]) nnc.close() tides = tt.t_tide(e,dt=dthours,out_style=None) except: tides=None return tides
def calculate_blade_bending(use_HAWC=False): # Loading blade section data sections = read_files.get_sectional_data() if (use_HAWC): HAWC_data = read_baseline_data() EI_X_intap = lambda r: py.interp(r, HAWC_data["r"], HAWC_data["E"] * HAWC_data["I_x"]) # Load blade shape c_fun, th_fun, tc_fun, w_fun = load_blade_shape.get_shape_functions() # Load blade loads r_i = py.array([16.68, 33.46, 51.35, 68.28, 85.43]) sections["r_i"] = r_i F_i = py.array([210.5, 252.8, 289.0, 316.8, 191.0]) * 1e3 sections["F_i"] = F_i # Calculating section bending for i_sec in range(1, sections["n_sec"]): # Getting ABD matrix for each section sections[i_sec] = ABD_matrix.fib2ABD(sections[i_sec]) # Section shape sections[i_sec]["cap_width"] = w_fun(sections[i_sec]["r_start"]) sections[i_sec]["height"] = th_fun(sections[i_sec]["r_start"]) sections[i_sec]["sec_length"] = sections[i_sec]["r_end"] - sections[ i_sec]["r_start"] # Calculating Inertia moment (I_xx) sections[i_sec]["I_xx"] = 1.0 / 12.0 * sections[i_sec]["cap_width"] * ( sections[i_sec]["height"]**3 - (sections[i_sec]["height"] - 2 * sections[i_sec]["thickness"])**3) # Calculating EI if (use_HAWC): sections[i_sec]["EI_x"] = EI_X_intap(sections[i_sec]["r_start"]) else: sections[i_sec][ "EI_x"] = sections[i_sec]["E_x"] * sections[i_sec]["I_xx"] # Calculating moment sections[i_sec]["M"] = sum((r_i[r_i > sections[i_sec]["r_start"]] - sections[i_sec]["r_start"]) * F_i[r_i > sections[i_sec]["r_start"]]) # Setting start values sections[i_sec][ "kappa"] = -sections[i_sec]["M"] / sections[i_sec]["EI_x"] delta_new = kappa_integration(sections)[1] for i_sec in range(1, sections["n_sec"]): sections[i_sec]["delta_start"] = delta_new[i_sec - 1] sections[i_sec]["delta_end"] = delta_new[i_sec] return (sections)
def deltaG(self, xValue): """INTERPOLATES THE DATA Keyword arguments: xValue -- conductance value Return: interpolated conductivity change """ return pylab.interp(xValue, self.xDistribution, self.yDistribution)
def get_kin_apex(self, phases, return_times = False): """ returns the kinematic state at the apices which are close to the given phases. Apex is re-calculated. :args: self: kin object (-> later: "self") phases (list): list of lists of apex phases. must match with length of "kin.raw_data". The n'th list of apex phases will be assigned to the nth "<object>.raw_data" element. return_times (bool): if true, return only the times at which apex occurred. :returns: if lr_split is True: [[r_apices], [l_apices]] else: [[apices], ] where apices is the kinematic (from <object>.selection at the apices *around* the given phases. *NOTE* The apices themselves are re-computed for higher accuracy. """ all_kin = [] all_kin_orig = self.get_kin() all_apex_times = [] if len(self.raw_dat) != len(phases): raise ValueError("length of phases list does not match number of datasets") for raw, phase, kin_orig in zip(self.raw_dat, phases, all_kin_orig): kin_apex = [] kin_time = arange(len(raw['phi2'].squeeze()), dtype=float) / 250. # 1st: compute apex *times* apex_times = [] for phi_apex in phase: # 1a: get "rough" estimate idx_apex = argmin(abs(raw['phi2'].squeeze() - phi_apex)) # 1b: fit quadratic function to com_y idx_low = max(0, idx_apex - 4) idx_high = min(raw['com'].shape[0] - 1, idx_apex + 4) com_y_pt = raw['com'][idx_low:idx_high + 1, 2] tp = arange(idx_high - idx_low + 1) # improve numerical accuracy: do not take absolute time p = polyfit(tp, com_y_pt, 2) # p: polynomial, highest power coeff first t0 = -p[1] / (2.*p[0]) # "real" index of apex (offset is 2: a value of 2 # indicates that apex is exactly at the measured frame t_apex = kin_time[idx_apex] + (t0 - 4.) / 250. apex_times.append(t_apex) if return_times: all_apex_times.append(array(apex_times)) else: # 2nd: interpolate data dat = vstack([interp(apex_times, kin_time, kin_orig[row, :]) for row in arange(kin_orig.shape[0])]) all_kin.append(dat) if return_times: return all_apex_times return all_kin
def auto_trim_sails(data): wind_angle = data.data # rospy.loginfo("auto_trim_sails.py: recieved wind angle: %i" %wind_angle) wind_angle = abs((wind_angle + 180) % 360 - 180) rospy.loginfo("auto_trim_sails.py: simplified (10-180) wind angle: %i" %wind_angle) points_of_sail = [0, 45, 60, 90, 135, 180] sail_points = [0, 0.5, 2, 4, 8, 9] sail_setting = pl.interp(wind_angle, points_of_sail, sail_points) sail_angle = myround(sail_setting*(170/10) + 10) # PUT CODE HERE THAT TRANSFORMS A 0-10 SCALE TO ACTUAL FULL-IN FULL-OUT ON THE SERVO rospy.loginfo("auto_trim_sails.py: sail servo is being set to: %i" %sail_angle) sail_pub.publish(UInt16(sail_angle))
def adapt(f,X): ddf=f.diff(x).diff(x) print ddf DDF=lambda a:abs(ddf.evalf(subs={x:a})) XX=p.linspace(X[0],X[-1],1001) h=XX[1]-XX[0] M=p.zeros(1001) for k,Y in enumerate(XX[:-1]): M[k+1]=M[k]+h/6.0*(DDF(Y)+4.0*DDF(Y+0.5*h)+DDF(Y+h)) m=p.linspace(0,M[-1],len(X)) return p.interp(m,M,XX)
def histeq(im, nbr_bins=256): #get image histogram imhist, bins = histogram(im.flatten(), nbr_bins, normed=True) cdf = imhist.cumsum() #cumulative distribution function cdf = 255 * cdf / cdf[-1] #normalize #use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(), bins[:-1], cdf) return im2.reshape(im.shape)
def histeq(img, nb_bins=256): """ Histogram equalization of a grayscale image.""" # get image histogram img_hist, bins = pl.histogram(img.flatten(), nb_bins, normed=True) cdf = img_hist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values img2 = pl.interp(img.flatten(), bins[:-1], cdf) return img2.reshape(img.shape), cdf
def ScaleDelayError(ScaleNDelay): # x1 and x2 must exist in calling namespace scale = ScaleNDelay[0] delay = ScaleNDelay[1] t1 = arange(len(x1)) t2 = arange(len(x2)) t1s = scale * t1 + delay # resample the scaled x1 onto t2 x1r = interp(t2, t1s, x1) err = x1r - x2 RMSError = sqrt(average(err**2)) return RMSError
def equalize(image, bins=256): ''' Given an image, equalize it based on the generated histogram so all the intensities are balanced. :param image: The image to equalize :param bins: The number of bins for the histogram :returns: The equalized image ''' im_hist, bins = pl.histogram(image.flatten(), bins, normed=True) cdf = im_hist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize im_norm = pl.interp(image.flatten(), bins[:-1], cdf) # linear interpolate new pixel values return im_norm.reshape(image.shape) # restore to the correct shape
def Histeq(img, nbr_bins=256): """ 图像直方图均衡化 :param img: 图像 :param nbr_bins:像素值范围[0~255] :return:均衡化直方图后的图像 """ # 获取直方图p(r) imhist, bins = pl.histogram(img.flatten(), nbr_bins, normed=True) # 获取T(r) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # 获取s,并用s替换原始图像对应的灰度值 result = pl.interp(img.flatten(), bins[:-1], cdf) return result.reshape(img.shape)
def sail_update_on_wind_direction_change(): wind_angle = sensors.wind_angle.angle rospy.loginfo("fast_sail_angle.py: Wind sensor sent %f" % (wind_angle)) # This command takes an angle and converts it to 0-180 range # necessary because it doesn't matter which side the wind is coming from for sail setting - wind 90 deg. off the starboard OR port bow both result in the same sail setting wind_angle = abs((wind_angle + 180) % 360 - 180) points_of_sail = [0, 45, 60, 90, 135, 180] sail_points = [0, 0, 15, 40, 60, 80] sail_angle = pl.interp(wind_angle, points_of_sail,sail_points) rospy.loginfo("fast_sail_angle.py: sail angle should be:" + str(sail_angle)) # Sets the sail servo servos.sail.set_position(sail_angle)
def auto_trim_sails(data): wind_angle = data.data # rospy.loginfo("auto_trim_sails.py: recieved wind angle: %i" %wind_angle) wind_angle = abs((wind_angle + 180) % 360 - 180) rospy.loginfo("auto_trim_sails.py: simplified (10-180) wind angle: %i" % wind_angle) points_of_sail = [0, 45, 60, 90, 135, 180] sail_points = [0, 0.5, 2, 4, 8, 9] sail_setting = pl.interp(wind_angle, points_of_sail, sail_points) sail_angle = myround( sail_setting * (170 / 10) + 10 ) # PUT CODE HERE THAT TRANSFORMS A 0-10 SCALE TO ACTUAL FULL-IN FULL-OUT ON THE SERVO rospy.loginfo("auto_trim_sails.py: sail servo is being set to: %i" % sail_angle) sail_pub.publish(UInt16(sail_angle))
def px_smooth(idx, e, x, idx_table, N_HE0, N_US, N_US_HE, WC): """Over sample, smooth and undersample photoionization cross-sections """ i, nmin, ntot, m, l, p, pos = idx_table[idx] try: # case of TOPBASE data nmin.index(".") nmin = pl.nan except ValueError: nmin = int(nmin) # Keep sampling for high energy values where the variation follow Kramer's law if isinstance(int(ntot) - nmin, int): N_HE = int(ntot) - nmin else: N_HE = N_HE0 if N_HE >= e.size: N_HE = -e.size print("Warning: N_HE is larger than photoionization table, select all the table.") e_sel = e[:-N_HE] e_sel_log = pl.log10(e_sel) x_sel = x[:-N_HE] # Interpolate and smooth data # e_i = pl.linspace(min(e_sel), max(e_sel), 10000) e_i_log = pl.linspace(min(e_sel_log), max(e_sel_log), 10000) e_i = 10 ** e_i_log x_i = pl.interp(e_i, e_sel, x_sel) x_is = smooth(x_i, WC) e_us = pl.concatenate([e_i[0:10], e_i[::N_US], e[int(ntot) - N_HE :: N_US_HE]]) x_us = pl.concatenate([x_is[0:10], x_is[::N_US], x[int(ntot) - N_HE :: N_US_HE]]) if x_us.any() == 0.0: print("x_us = 0") quit(1) # Conservation of area # area = pl.trapz( x_Mb, e_eV) # total # area = pl.trapz( e_sel, x_sel) # selected area_i = pl.trapz(x_i, e_i) # selected interpolated area_is = pl.trapz(x_is, e_i) # selected interpolated and sampled # area_us = pl.trapz(x_us, e_us) return e_us, x_us, area_i, area_is
def ReSample(data,phase,nps): """ re-samples the data with nps frames per stride. phase gives the phase information at a given cycle. the output will be truncated towards an integer number of strides. The last stride will usually be removed. Data must be given in a D x N-format, D: number of Dimensions, N: number of samples """ minPhi = ceil(phase[0]/(2.*pi))*2.*pi maxPhi = floor(phase[-1]/(2.*pi))*2.*pi nFrames = round((maxPhi-minPhi)/(2.*pi)*nps) phi_new = linspace(minPhi, maxPhi, nFrames, endpoint=False) return vstack([interp(phi_new,phase,data[row,:]) for row in range(data.shape[0])])
def WindConversion(data, c): """Conversion of wind speed to wind power""" wind10m = data[0] #Turbine data H = c['H'] #Hub height V = c['V'] #Power curve velocities POW = c['POW'] #power from the power curves #Convert wind speed to hub height H from a height 10m above the ground #0.143 is power law index which depends on roughness of the surface and assumed to be constant for the time being. wind = wind10m * ((H / 10)**0.143) #Apply power curve P = interp(wind, V, POW) #interpolation using power curve data return P
def testnx(dotiming=False): xtbl, tbl, idx0, dx = init_nx_table() if dotiming: import cProfile x = pylab.linspace(-10,10,1000000) cProfile.runctx('nx(x)',globals(),locals()) cProfile.runctx('nx_lookup(x, 0, tbl, idx0, dx)',globals(),locals()) cProfile.runctx('pylab.interp(x, xtbl, tbl, left=0, right=0)',globals(),locals()) else: x = pylab.linspace(-10,10,1000) x0 = nx(x) x1 = nx_lookup(x, 0, tbl, idx0, dx) x2 = pylab.interp(x, xtbl, tbl, left=0, right=0) pylab.plot(x, x0-x1) pylab.plot(x, x0-x2) pylab.ylabel('Error')
def histeq(im, nb_bins=256): """ This function equalises the histogram of im (numpy array), distributing the pixels accross nbr_bins bins. Returns the equalised image as a numpy array (same shape as input). Largely copied from https://stackoverflow.com/a/28520445 (author: Trilarion, 17/07/2017) """ # get image histogram imhist, bins = pl.histogram(im.flatten(), nb_bins, normed=True) cdf = imhist.cumsum() #cumulative distribution function cdf = 65535 * cdf / cdf[-1] #normalize # use linear interpolation of cdf to find new pixel values im2 = pl.interp(im.flatten(), bins[:-1], cdf) return im2.reshape(im.shape)
def WindConversion(data,c): """Conversion of wind speed to wind power""" wind10m = data[0] #Turbine data H = c['H'] #Hub height V = c['V'] #Power curve velocities POW = c['POW'] #power from the power curves #Convert wind speed to hub height H from a height 10m above the ground #0.143 is power law index which depends on roughness of the surface and assumed to be constant for the time being. wind = wind10m*((H/10)**0.143) #Apply power curve P = interp(wind,V,POW) #interpolation using power curve data return P
def testnx(dotiming=False): xtbl, tbl, idx0, dx = init_nx_table() if dotiming: import cProfile x = pylab.linspace(-10, 10, 1000000) cProfile.runctx('nx(x)', globals(), locals()) cProfile.runctx('nx_lookup(x, 0, tbl, idx0, dx)', globals(), locals()) cProfile.runctx('pylab.interp(x, xtbl, tbl, left=0, right=0)', globals(), locals()) else: x = pylab.linspace(-10, 10, 1000) x0 = nx(x) x1 = nx_lookup(x, 0, tbl, idx0, dx) x2 = pylab.interp(x, xtbl, tbl, left=0, right=0) pylab.plot(x, x0 - x1) pylab.plot(x, x0 - x2) pylab.ylabel('Error')
def ReSample(data, phase, nps): """ re-samples the data with nps frames per stride. phase gives the phase information at a given cycle. the output will be truncated towards an integer number of strides. The last stride will usually be removed. Data must be given in a D x N-format, D: number of Dimensions, N: number of samples """ minPhi = ceil(phase[0] / (2. * pi)) * 2. * pi maxPhi = floor(phase[-1] / (2. * pi)) * 2. * pi nFrames = round((maxPhi - minPhi) / (2. * pi) * nps) phi_new = linspace(minPhi, maxPhi, nFrames, endpoint=False) return vstack( [interp(phi_new, phase, data[row, :]) for row in range(data.shape[0])])
def plot_blade_deflection(use_plotly=True): sections = blade_bending.calculate_blade_bending() sections_HAWC = blade_bending.calculate_blade_bending(True) # Radial vector r = blade_bending.sections2value(sections, "r_start", True) # Deflection vector delta = blade_bending.sections2value(sections, "delta_start", True) delta_HAWC = blade_bending.sections2value(sections_HAWC, "delta_start", True) # Moment vector M = blade_bending.sections2value(sections, "M") # Curvature vector kappa = blade_bending.sections2value(sections, "kappa") r2M = lambda r_in: py.interp(r_in, r[:-1], M) fig, ax = py.subplots(2, 1, gridspec_kw={'hspace': 0}, figsize=(6, 4)) ax[0].plot(r[:-1], M) ax[0].quiver(sections["r_i"], r2M(sections["r_i"]), [0] * len(sections["F_i"]), -sections["F_i"], label="Force arrows") ax[0].set_ylabel("Moment [Nm]") ax[0].grid("on") ax[0].legend() ax[0].set_ylim([-2e7, 7e7]) ax[1].grid("on") ax[1].plot(r, delta, label="Only Spar Caps") ax[1].plot(r, delta_HAWC, label="Using HAWC $EI_x$") ax[1].plot(r, [-18.26] * len(r), label="Tower clearance", ls="--", lw=0.9) ax[1].set_xlabel("Radius [m]") ax[1].set_ylabel("Deflection [m]") ax[1].legend(loc=0) py.tight_layout() fig.savefig(path.join(fig_path, "Deflection.png")) if use_plotly: plotly.offline.plot_mpl(fig) else: py.show()
def sigdiff(t, y, t_ref, y_ref): """ returns the difference y - y_ref at the corresponding times of t. y can be sampled at different times t_ref. ========== Parameter: ========== t : *array* (1-D) time vector of the signal y (must have same length as y) y : *array* (1-D) input signal from which y_ref should be subtracted. ======== Returns: ======== y' : y - y_ref at times t """ y_1 = interp(t, t_ref, y_ref) return y - y_1
def cmap_discretize(cmap, N): """ Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: Number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ import numpy as np from pylab import interp import pylab as pl import pylab as plt cdict = cmap._segmentdata.copy() # N colors colors_i = np.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) #I = interpolate.interp1d(D[:,0], D[:,1]) #I = interpolate.interp1d(D[:,0],D[:,1]) colors = interp(colors_i,D[:,0],D[:,1]) # Place these colors at the correct indices. A = np.zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) # Return colormap object. return plt.matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)
def px_combine(i_list, e_list, x_list, level, qm_levels): """ Combine differents photoionization cross-sections if necessary and adjust the statistical weight i_list: index list of qm_levels for the level considered e_list: smoothed and undersampled photoionization energies x_list: smoothed and undersampled photoionization cross-sections """ if len(i_list) == 1: g_theo = qm_levels[i_list[0]].g if MPI: g = g_theo else: g = level.g e = e_list[0] x = g / g_theo * x_list[0] else: e_set = set(pl.flatten(e_list)) eilg = pl.linspace(min(pl.log10(list(e_set))), max(pl.log10(list(e_set))), 50000) ei = 10 ** eilg xi_list = [] for i, x in enumerate(x_list): xi = pl.interp(ei, e_list[i], x) xi_list.append(xi[::N_US]) g_theo = pl.sum([qm_levels[i].g for i in i_list]) if MPI: g = g_theo else: g = level.g e = ei[::N_US] x = g / g_theo * pl.sum([xi for xi in xi_list], axis=0) return e, x
def uniform_wave(x, y, xmin, xmax, n=6000): '''Set an uniform x scale by interpolation of x ''' eps = 0.001 # Tolerance on the constant step bla = False if x.size >= n: print "Warning: the number of wavelengths is greater than the default number of interpolated points." print " : use -nu option to increase the number of interpolated points." n = x.size print " Number of points: ", x.size dx = x[:x.size - 1] - wave[1:x.size] dxmax = abs(max(dx)) dxmin = abs(min(dx)) if bla: print min(dx), max(dx) crit = dxmax - dxmin < eps if crit: print " Uniformed step of: ", dxmax.__format__('7.4f') else: print " Non-uniformed step." print " Min and max steps: ", dxmin.__format__( '7.4f'), dxmax.__format__('7.4f') xlin = pl.linspace(xmin, xmax, n) y = pl.interp(xlin, x, y) x = xlin print " Number of interpolated points:", x.size.__format__('7g') return x, y
def uniform_wave(x, y, xmin, xmax, n=6000): '''Set an uniform x scale by interpolation of x ''' eps = 0.001 # Tolerance on the constant step bla = False if x.size >= n: print "Warning: the number of wavelengths is greater than the default number of interpolated points." print " : use -nu option to increase the number of interpolated points." n = x.size print " Number of points: ", x.size dx = x[:x.size-1] - wave[1:x.size] dxmax = abs(max(dx)) dxmin = abs(min(dx)) if bla: print min(dx), max(dx) crit = dxmax - dxmin < eps if crit: print " Uniformed step of: ", dxmax.__format__('7.4f') else: print " Non-uniformed step." print " Min and max steps: ", dxmin.__format__('7.4f'), dxmax.__format__('7.4f') xlin = pl.linspace(xmin, xmax, n) y = pl.interp(xlin, x, y) x = xlin print " Number of interpolated points:", x.size.__format__('7g') return x, y
# AVERAGE FLUX. THEN RECORDS THE AVERAGE X-COORD FOR THE LINE. tmp = [ flx_above_medi0[0] ] for i in range(1,len(flx_above_medi0)): if flx_above_medi0[i] - tmp[-1] < 2: tmp.append( flx_above_medi0[i] ) else: if len(tmp)>=5: f.xpeaks.append( pl.average(tmp) ) tmp = [ flx_above_medi0[i] ] if f==fibers[0]: continue # NOW WE NEED TO FIND THE RESCALING FACTOR (s) AND OFFSET (m) f.s = pl.average( (pl.array(fibers[0].xpeaks)-fibers[0].xpeaks[0]+1) / (pl.array(f.xpeaks)-f.xpeaks[0]+1) ) f.m = fibers[0].xpeaks[0] - f.xpeaks[0]*f.s # pl.fill_between( f.xaxis*f.s+f.m, f.flux, 0, color='k', alpha=0.01 ) outer_pass2.append( pl.interp( f.xaxis , f.xaxis*f.s+f.m , f.flux ) ) stack_f += pl.interp( f.xaxis , f.xaxis*f.s+f.m , f.flux ) stack_f /= len(fibers) outer_txt = open('outer_stack.txt','w') for i in range(len(stack_f)): outer_txt.write( str(stack_x[i]) +' '+ str(stack_f[i]) +'\n' ) outer_txt.close() outer_pass2.append( pl.arange(len(fib.flux))*0 ) outer_pass2.append( pl.arange(len(fib.flux))*0 ) outer_pass2.append( pl.arange(len(fib.flux))*0 ) try: pf.writeto(sys.argv[1][:-5]+'_spec_pass2.fits', pl.array(outer_pass2) ) except: pass
def make_1D(self, nps, phase='phi2', fps=250, phases_list=None): """ interpolate the data with <nps> frames per stride *Note* The <object>.selection attribute must contain a valid list of selection items. A selection item can either be a single coordinate (e.g. 'com_z', 'r_anl_y') or the difference between two coordinates (e.g. 'l_anl_y - com_y') :args: nps (int): how many frames per stride should be sampled phase (str): 'phi1' or 'phi2' : which phase to use. Note: previous data mostly used 'phi2'. fps (int): how many frames per second do the original data have? This is only required for correct scaling of the velocities. phases_list (list of list of int): If present, use given phases instead of predefined sections. Data will *not* be sampled exactly at the given phases; instead there will be _nps_ sections per stride, and strides start (on average only) at the given phases. """ if len(self.raw_dat) == 0: print "No data loaded." return if len(self.selection) == 0: print "No data selected. Set <object>.selection to something!" # gather phases for each trial: i_phases =[] if not phases_list: # typical call: omit first and last strides; # strides go from phase 0 to phase 2pi (exluding 2pi) for raw in self.raw_dat: phi = raw[phase].squeeze() # cut lower phase and upper phase by ~4pi each first_step = (phi[0] + 6. * pi) // (2. * pi) last_step = (phi[-1] - 4. * pi) // (2. * pi) i_phases.append(linspace(first_step, last_step + 1, (last_step - first_step + 1) * nps, endpoint=False) * 2. *pi) else: # phases are explicitely given avg_phasemod = mean([mean(mod(elem, 2.*pi)) for elem in phases_list]) for elem in phases_list: firstphase = (elem[0] // (2. * pi)) * 2.*pi + avg_phasemod lastphase = (elem[-1] // (2. * pi)) * 2.*pi + avg_phasemod i_phases.append(linspace(firstphase, lastphase + 2*pi, len(elem) * nps, endpoint=False)) self.i_phases = i_phases # walk through each element of "selection" all_pos = [] all_vel = [] for elem in self.selection: items = [x.strip() for x in elem.split('-')] # 1 item if no "-" present dims = [] markers = [] for item in items: if item.endswith('_x'): dims.append(0) elif item.endswith('_y'): dims.append(1) elif item.endswith('_z'): dims.append(2) else: print "invalid marker suffix: ", item continue markers.append(item[:-2]) all_elem_pos = [] all_elem_vel = [] for raw, phi in zip(self.raw_dat, self.i_phases): if len(items) == 1: # only a single marker dat = raw[markers[0]][:, dims[0]] else: # differences between two markers dat = raw[markers[0]][:, dims[0]] - raw[markers[1]][:, dims[1]] all_elem_pos.append(interp(phi, raw[phase].squeeze(), dat)) all_elem_vel.append(interp(phi, raw[phase].squeeze(), gradient(dat) * fps)) all_pos.append(hstack(all_elem_pos)) all_vel.append(hstack(all_elem_vel)) dat_2D = vstack([all_pos, all_vel]) return mi.twoD_oneD(dat_2D, nps)
name='square_rnd_phase-%03dh-G2-(i).wav'): '''Generate a series of basic additive waveforms with a varying number of harmonics.''' f0 = 49.0 w0 = pl.round(sr / f0) f0 = sr / w0 pl.clf() for ii, N in enumerate(N_harmonics): H = 1.0 + 2 * pl.arange(N) waev = beep(pl.c_[f0 * H, pl.random(N) * tau, 1 / H], 8 * w0) pl.subplot(3,4,ii+1) pl.plot(waev) write(waev, path + (name % N)) def ADSR((A, D, S, R)=(100, 500, .7, 100), L=2000): 'ADSR envelope.' return pl.interp(pl.arange(L), [0, A, A+D, L-R, L-1], [0, 1, S, S, 0]) def saw_bass(n, L=4400, env=(100, 500, .7, 100), N_harmonics=32): '''Generate a sawtooth beep with ADSR envelope.''' H = 1.0 + pl.arange(N_harmonics) f0 = 440 * 2**((n - 69) / 12.0) saw = beep(pl.c_[f0 * H, H*0, 1 / H], L) saw *= ADSR(env, L) return saw def play_melody(notes, samples): ch = pygame.mixer.find_channel(True) EV = pygame.USEREVENT + 1 ch.set_endevent(EV) for n in notes: while ch.get_busy() and pygame.event.wait() != EV:
def load_video_info(video_path): """ Loads all the relevant information for the video in the given path: the list of image files (cell array of strings), initial position (1x2), target size (1x2), whether to resize the video to half (boolean), and the ground truth information for precision calculations (Nx2, for N frames). The ordering of coordinates is always [y, x]. The path to the video is returned, since it may change if the images are located in a sub-folder (as is the default for MILTrack's videos). """ # load ground truth from text file (MILTrack's format) text_files = glob.glob(os.path.join(video_path, "*_gt.txt")) assert text_files, \ "No initial position and ground truth (*_gt.txt) to load." first_file_path = text_files[0] #f = open(first_file_path, "r") #ground_truth = textscan(f, '%f,%f,%f,%f') # [x, y, width, height] #ground_truth = cat(2, ground_truth{:}) ground_truth = pylab.loadtxt(first_file_path, delimiter=",") #f.close() # set initial position and size first_ground_truth = ground_truth[0, :] # target_sz contains height, width target_sz = pylab.array([first_ground_truth[3], first_ground_truth[2]]) # pos contains y, x center pos = [first_ground_truth[1], first_ground_truth[0]] \ + pylab.floor(target_sz / 2) #try: if True: # interpolate missing annotations # 4 out of each 5 frames is filled with zeros for i in range(4): # x, y, width, height xp = range(0, ground_truth.shape[0], 5) fp = ground_truth[xp, i] x = range(ground_truth.shape[0]) ground_truth[:, i] = pylab.interp(x, xp, fp) # store positions instead of boxes ground_truth = ground_truth[:, [1, 0]] + ground_truth[:, [3, 2]] / 2 #except Exception as e: else: print("Failed to gather ground truth data") #print("Error", e) # ok, wrong format or we just don't have ground truth data. ground_truth = [] # list all frames. first, try MILTrack's format, where the initial and # final frame numbers are stored in a text file. if it doesn't work, # try to load all png/jpg files in the folder. text_files = glob.glob(os.path.join(video_path, "*_frames.txt")) if text_files: first_file_path = text_files[0] #f = open(first_file_path, "r") #frames = textscan(f, '%f,%f') frames = pylab.loadtxt(first_file_path, delimiter=",", dtype=int) #f.close() # see if they are in the 'imgs' subfolder or not test1_path_to_img = os.path.join(video_path, "imgs/img%05i.png" % frames[0]) test2_path_to_img = os.path.join(video_path, "img%05i.png" % frames[0]) if os.path.exists(test1_path_to_img): video_path = os.path.join(video_path, "imgs/") elif os.path.exists(test2_path_to_img): video_path = video_path # no need for change else: raise Exception("Failed to find the png images") # list the files img_files = ["img%05i.png" % i for i in range(frames[0], frames[1] + 1)] #img_files = num2str((frames{1} : frames{2})', 'img%05i.png') #img_files = cellstr(img_files); else: # no text file, just list all images img_files = glob.glob(os.path.join(video_path, "*.png")) if len(img_files) == 0: img_files = glob.glob(os.path.join(video_path, "*.jpg")) assert len(img_files), "Failed to find png or jpg images" img_files.sort() # if the target is too large, use a lower resolution # no need for so much detail if pylab.sqrt(pylab.prod(target_sz)) >= 100: pos = pylab.floor(pos / 2) target_sz = pylab.floor(target_sz / 2) resize_image = True else: resize_image = False ret = [img_files, pos, target_sz, resize_image, ground_truth, video_path] return ret
def fill_nan(data, max_len=None, fill_ends=True): """ Fills the "nan" fields of a 1D array with linear interpolated values. At the edges, constant values are assumed. :args: data (1d array): the input data max_len (int or None): maximal length of gaps to fill fill_ends (bool): whether or not to fill the ends :returns: data' (1d array): a copy of the input data, where `nan`-values are replaced by a linear interpolation between adjacent values """ res = data.copy() if all(isnan(data)): return res missing_idx = find(isnan(data)) # group to missing segments missing_segs = [] gap_lengths = [] lastidx = -2 # some invalid index: idx == lastidx + 1 cannot be true for this! startidx = -2 # some invalid index gaplen = 0 for idx in missing_idx: if idx == lastidx + 1: # all right, the segment continues lastidx = idx gaplen += 1 else: # a new segment has started # first: "close" old segment if exists if startidx >= 0: missing_segs.append([startidx, lastidx]) gap_lengths.append(gaplen) # now: initialize new segment gaplen = 1 startidx = idx lastidx = idx # manually close the last segment if exists if startidx >= 0: if lastidx < len(data) - 1 or fill_ends: # skip edge if not fill_ends missing_segs.append([startidx, lastidx]) # fill missing segments for seg in missing_segs: start_idx, stop_idx = seg if max_len is not None: if stop_idx - start_idx > max_len: continue # if startpoint is missing: constant value if start_idx == 0 and fill_ends: res[:stop_idx + 1] = res[stop_idx + 1] # if endpoint is missing: use constant value elif stop_idx == len(data)-1 and fill_ends: res[start_idx:] = res[start_idx - 1] # else: linear interpolation else: res[start_idx: stop_idx+1] = interp(range(start_idx, stop_idx + 1), [start_idx - 1, stop_idx + 1], data[[start_idx - 1, stop_idx + 1]]) return res
s = schism_setup(hgrid_file='hgrid.gr3') def dump_gr3(self,filename,const=0.0,comment='gr3 by create_ic.py'): f = open(filename,'w') f.write('%s\n'%comment) f.write('%d %d\n'%(self.nelements,self.nnodes)) for i,x,y in zip(self.inodes,self.x,self.y): f.write('%d %0.2f %0.2f %0.5f\n'%(i,x,y,const)) f.close() f = open('salt.ic','w') f.write('salt initial condition\n') f.write('%d %d\n'%(s.nelements,s.nnodes)) for i,x,y in zip(s.inodes,s.x,s.y): salt = interp(y,[49000.,51000.],[30.,10.]) f.write('%d %0.2f %0.2f %0.5f\n'%(i,x,y,salt)) f.close() f = open('elev.ic','w') f.write('initial surface elevation\n') f.write('%d %d\n'%(s.nelements,s.nnodes)) for i,x,y in zip(s.inodes,s.x,s.y): elev = interp(x,[0.,100000.],[1.0,-1.0]) f.write('%d %0.2f %0.2f %0.5f\n'%(i,x,y,elev)) f.close() f = open('tvd.prop','w') for i in s.ielement: f.write('%d 1\n'%i) f.close()
def sim_until(IC, params, stop_fcn, tmax = 2.): """ simulated the SLIP_ode until stop_fcn has a zero-crossing includes a refinement of the time at this instant stop_fcn must be a function of the system state, e.g. stop_fcn(IC) must exist this function is especially adapted to the SLIP state, so it uses dot(x1) = x3, dot(x2) = x4 tmax: maximal simulation time [s] """ init_sign = sign(stop_fcn(IC)) #1st: evaluate a certain fraction tvec_0 = .001*arange(50) sim_results = [] sim_tvecs = [] newIC = IC sim_results.append (odeint(SLIP_ode,newIC,tvec_0, args=(params,),rtol=1e-9)) sim_tvecs.append(tvec_0) check_vec = [init_sign*stop_fcn(x) for x in sim_results[-1]] t_tot = 0. while min(check_vec) > 0: newIC = sim_results[-1][-1,:] sim_results.append ( odeint(SLIP_ode, newIC, tvec_0, args=(params,),rtol=1e-9)) sim_tvecs.append(tvec_0) check_vec = [init_sign*stop_fcn(x) for x in sim_results[-1]] t_tot += tvec_0[-1] # time exceeded or ground hit if t_tot > tmax or min(sim_results[-1][:,1] < 0): raise SimFailError, "simulation failed" # now: zero-crossing detected # -> refine! minidx = find(array(check_vec) < 0)[0] if minidx == 0: # this should not happen because the first value in # check_vec should be BEFORE the zero_crossing by # construction raise ValueError, "ERROR: this should not happen!" # refine simulation by factor 50, but only for two # adjacent original time frames newIC = sim_results[-1][minidx-1,:] sim_results[-1] = sim_results[-1][:minidx,:] sim_tvecs[-1] = sim_tvecs[-1][:minidx] # avoid that last position can be the zero-crossing n_refine = 100 tvec_0 = linspace(tvec_0[0], tvec_0[1] + 2./n_refine, n_refine+2) sim_results.append ( odeint(SLIP_ode, newIC, tvec_0, args=(params,),rtol=1e-9)) sim_tvecs.append(tvec_0) # linearly interpolate to zero check_vec = [init_sign*stop_fcn(x) for x in sim_results[-1]] minidx = find(array(check_vec) < 0)[0] if minidx == 0: # this should not happen because the first value in # check_vec should be BEFORE the zero_crossing by # construction raise ValueError, "ERROR: this should not happen! (2)" # compute location of zero-crossing y0 = sim_results[-1][minidx-1,:] y1 = sim_results[-1][minidx,:] fcn0 = stop_fcn(y0) fcn1 = stop_fcn(y1) t0 = tvec_0[minidx-1] t1 = tvec_0[minidx] t_zero = t0 - (t1-t0)*fcn0/(fcn1 - fcn0) # cut last simulation result and replace last values # by interpolated values sim_results[-1] = sim_results[-1][:minidx+1,:] sim_tvecs[-1] = sim_tvecs[-1][:minidx+1] for coord in arange(sim_results[-1].shape[1]): sim_results[-1][-1,coord] = interp( t_zero, [t0,t1], [sim_results[-1][-2,coord], sim_results[-1][-1,coord]] ) sim_tvecs[-1][-1] = t_zero #newIC = sim_results[-1][minidx-1,:] #sim_results[-1] = sim_results[-1][:minidx,:] #sim_tvecs[-1] = sim_tvecs[-1][:minidx] #tvec_0 = linspace(tvec_0[0],tvec_0[1],100) #sim_results.append ( odeint(SLIP_ode, newIC, tvec_0, # args=(params,),rtol=1e-9)) #sim_tvecs.append(tvec_0) # concatenate lists sim_data = vstack( [x[:-1,:] for x in sim_results[:-1] if x.shape[0] > 1] + [sim_results[-1],]) sim_time = [sim_tvecs[0],] for idx in arange(1,len(sim_tvecs)): sim_time.append(sim_tvecs[idx] + sim_time[-1][-1]) sim_time = hstack([x[:-1] for x in sim_time[:-1]] + [sim_time[-1],]) return sim_data, sim_time
def plotweather(vis='', seasonal_weight=0.5, doPlot=True, plotName = ''): myMS=vis if plotName == '': plotName = myMS+'.plotweather.png' # check for weather table if osp.isdir(myMS+'/WEATHER'): try: tb.open(myMS+'/WEATHER') firstTime = tb.getcol('TIME')[0] tb.close() WEATHER_table_exists = True except: print 'could not open weather table, using seasonal model only and turning off plots' WEATHER_table_exists = False doPlot=False seasonal_weight = 1.0 else: print 'could not find a weather table, using seasonal model only and turning off plots' WEATHER_table_exists = False doPlot=False seasonal_weight = 1.0 ##retrieve center frequency for each sub-band tb.open(myMS+'/SPECTRAL_WINDOW') spwFreqs=tb.getcol('REF_FREQUENCY') * 1e-9 tb.close() ##retrieve stuff from weather table, if exists if WEATHER_table_exists: tb.open(myMS+'/WEATHER') mytime=tb.getcol('TIME') mytemp=tb.getcol('TEMPERATURE') - 273.15 mydew=tb.getcol('DEW_POINT') - 273.15 mywinds=tb.getcol('WIND_SPEED') # Text starts at 90 degrees, whereas the wind direction starts at 0 # Hence the wind direction is adjusted 90 degrees counterclockwise # to make the arrows point to right direction mywindd=270-tb.getcol('WIND_DIRECTION')*(180.0/pi) mypres=tb.getcol('PRESSURE') myhum=tb.getcol('REL_HUMIDITY') tb.close() else: ms.open(myMS) mytime_range = ms.range(["time"]) mytime = [mytime_range['time'][0]] ##calculate the elevation of the sun sunEL=[] for time in mytime: t1= qa.quantity(time,'s') myday=qa.convert(t1,'d') sunEL1=jm_sunEL(myday) sunEL.append(sunEL1) ##convert time to a string of date/time myTimestr = [] myTimestr2=[] for time in mytime: q1=qa.quantity(time,'s') time1=qa.time(q1,form='ymd')[0] time2=qa.time(q1,form='local')[0] myTimestr.append(time1) myTimestr2.append(time2) ##convert time to a decimal numtime=pl.datestr2num(myTimestr) ##### calculate opacity as in EVLA memo 143 thisday= 30*(float(myTimestr[0][5:7])-1)+float(myTimestr[0][8:10]) thisday=thisday + 5 * (thisday / 365.) if WEATHER_table_exists: # get 22 GHz zenith opacity and pwv estimate from weatherstation (myPWV) myTauZ, myPWV1 = Tau_K_Calc(mydew,mytemp,thisday) myTauZ1, myPWV = Tau_K_Calc(mydew,mytemp,thisday, weights=(0,1.0)) myTauZ2, myPWV = Tau_K_Calc(mydew,mytemp,thisday, weights=(1.0,0)) # estimate pwv from seasonal model zenith opacity myPWV2 = -1.71 + 1.3647*myTauZ1 myPWV = (1-seasonal_weight)*myPWV1 + seasonal_weight*myPWV2 else: day = thisday*1.0 if day > 199: day = day - 365. m = day + 165. # modified day of the year myTauZ = 22.1 - 0.178*m + 0.00044*m**2 # tau from seaonal model, in % myPWV = -1.71 + 1.3647*myTauZ myPWV1, myPWV2 = myPWV, myPWV myTauZ1, myTauZ2 = myTauZ, myTauZ tmp = qa.quantity(270.0,'K') pre = qa.quantity(790.0,'mbar') alt = qa.quantity(2125,'m') h0 = qa.quantity(2.0,'km') wvl = qa.quantity(-5.6, 'K/km') mxA = qa.quantity(48,'km') dpr = qa.quantity(10.0,'mbar') dpm = 1.2 att = 1 nb = 1 fC=qa.quantity(25.0,'GHz') fW=qa.quantity(50.,'GHz') fR=qa.quantity(0.25,'GHz') at=casac.atmosphere() hum=20.0 myatm=at.initAtmProfile(alt,tmp,pre,mxA,hum,wvl,dpr,dpm,h0,att) at.initSpectralWindow(nb,fC,fW,fR) sg=at.getSpectralWindow() mysg = sg['value'] nstep = 20 pwv = [] opac = pl.zeros((len(mysg),nstep)) for i in range(nstep): hum = 20.0*(i+1) myatm = at.initAtmProfile(alt,tmp,pre,mxA,hum,wvl,dpr,dpm,h0,att) w=at.getGroundWH2O() pwv.append(w['value'][0]) at.initSpectralWindow(nb,fC,fW,fR) at.setUserWH2O(w) sg=at.getSpectralWindow() mysg = sg['value'] sdry=at.getDryOpacitySpec() swet=at.getWetOpacitySpec() sd=sdry[1] sw=swet[1]['value'] stot = pl.array(sd)+pl.array(sw) opac[:,i]=stot pwv_coef=pl.zeros((len(mysg),2)) for i in range(len(mysg)): myfit=pl.polyfit(pwv,opac[i,:],1) pwv_coef[i,:]=myfit freqs=pl.array(mysg)/1e9 coef0=pwv_coef[:,1]/1e-3 coef1=pwv_coef[:,0]/1e-3 #interpolate between nearest table entries for each spw center frequency meanTau=[] for i in range(len(spwFreqs)): mysearch=(pl.array(freqs)-spwFreqs[i])**2 hits=pl.find(mysearch == min(mysearch)) if len(hits) > 1: hits=hits[0] tau_interp = (pl.array(coef0[hits-2:hits+2])+pl.array(coef1[hits-2:hits+2])*pl.mean(myPWV)) * 1e-1 #percent tau_F = pl.interp(spwFreqs[i],freqs[hits-2:hits+2],tau_interp) meanTau.append(pl.mean(tau_F*.01)) #nepers tau_allF = (pl.array(coef0) + pl.array(coef1)*pl.mean(myPWV)) * 1e-1 #percent tau_allF1 = (pl.array(coef0) + pl.array(coef1)*pl.mean(myPWV1)) *1e-1 tau_allF2 = (pl.array(coef0) + pl.array(coef1)*pl.mean(myPWV2)) *1e-1 casalog.post('SPW : Frequency (GHz) : Zenith opacity (nepers)') for i in range(len(meanTau)): myStr = str(i).rjust(3) + ' : ' myStr2 = '%.3f'%(spwFreqs[i]) myStr += myStr2.rjust(7) + ' : ' +str(round(meanTau[i], 3)) casalog.post(myStr) ##make the plots if doPlot==False: return meanTau pl.ioff() myColor2='#A6A6A6' myColorW='#92B5F2' myColor1='#4D4DFF' myOrangeColor='#FF6600' myYellowColor='#FFCC00' myWeirdColor='#006666' myLightBrown='#996633' myDarkGreay='#333333' thisfig=pl.figure(1) thisfig.clf() thisfig.set_size_inches(8.5,10) Xrange=numtime[-1]-numtime[0] Yrange=max(mywinds)-min(mywinds) Xtextoffset=-Xrange*.01 Ytextoffset=-Yrange*.08 Xplotpad=Xrange*.03 Yplotpad=Yrange*.03 sp1=thisfig.add_axes([.13,.8,.8,.15]) pl.ylabel('solar el') nsuns=30 myj=pl.array(pl.linspace(0,len(sunEL)-1,nsuns),dtype='int') for i in myj: if sunEL[i]<0: pl.plot([numtime[i],numtime[i]],[(180/pi)*sunEL[i],(180/pi)*sunEL[i]],'kH') else: pl.plot([numtime[i],numtime[i]],[(180/pi)*sunEL[i],(180/pi)*sunEL[i]],'H',color=myYellowColor) pl.plot([numtime[0],numtime[-1]],[0,0],'-',color='brown') xa=pl.gca(); xa.set_xticklabels('') jm_set_Ylim_ticks(myMin=-90,myMax=90) jm_set_Ylabel_pos(pos=(0,.5)) pl.title('Weather Summary for '+myMS) pl.xlim(numtime[0]-Xplotpad,numtime[-1]+Xplotpad) xa.set_xticks(pl.linspace(min(numtime),max(numtime),3)) sp2=thisfig.add_axes([.13,.65,.8,.15]) pl.ylabel('wind (m/s)') nwind=60 myj=pl.array(pl.linspace(0,len(mywinds)-1,nwind),dtype='int') for i in myj: pl.text(numtime[i]+Xtextoffset,Ytextoffset+mywinds[i],'-->',rotation=mywindd[i], alpha=1,color='purple',fontsize=12) pl.plot(numtime, .3+mywinds,'.', color='black', ms=2, alpha=0) jm_set_Ylabel_pos(pos=(0,.5)) jm_set_Yvar_ticks(5) xa=pl.gca(); xa.set_xticklabels('') pl.xlim(numtime[0]-Xplotpad,numtime[-1]+Xplotpad) pl.ylim(min(mywinds)-Yplotpad,max(mywinds)+Yplotpad) xa.set_xticks(pl.linspace(min(numtime),max(numtime),3)) sp4=thisfig.add_axes([.13,.5,.8,.15]) pl.plot(numtime, mytemp,'-', color=myOrangeColor,lw=2) pl.plot(numtime, mydew,'-', color=myWeirdColor,lw=2) pl.ylabel('temp,dew') jm_set_Ylabel_pos(pos=(0, .5)) xa=pl.gca(); xa.set_xticklabels('') jm_set_Yvar_ticks(5) pl.xlim(numtime[0]-Xplotpad,numtime[-1]+Xplotpad) xa.set_xticks(pl.linspace(min(numtime),max(numtime),3)) sp7=thisfig.add_axes([.13,.35,.8,.15]) pl.ylabel('PWV (mm)') pl.plot(numtime, myPWV2, color=myColor2, lw=2, label='seasonal model') pl.plot(numtime, myPWV1, color=myColor1, lw=2, label='weather station') pl.plot(numtime, myPWV, color=myColorW,lw=2, label='weighted') thismin=min([min(myPWV),min(myPWV1),min(myPWV2)]) thismax=max([max(myPWV),max(myPWV1),max(myPWV2)]) pl.ylim(.8*thismin,1.2*thismax) jm_set_Ylabel_pos(pos=(0,.5)) jm_set_Yvar_ticks(5) xa=pl.gca(); xa.set_xticklabels('') pl.xlim(numtime[0]-Xplotpad,numtime[-1]+Xplotpad) middletimei=int(floor(len(myTimestr)/2.)) middletimes=str(myTimestr[middletimei])[11:] endtimes=myTimestr[-1][11:] ax=pl.gca() axt=ax.get_xticks() ax.set_xticks(pl.linspace(min(numtime),max(numtime),3)) ax.set_xticklabels([myTimestr[0],middletimes,endtimes ]) sp8=thisfig.add_axes([.13,.1,.8,.2]) pl.plot(freqs,.01*tau_allF2,'-', color=myColor2, lw=2, label='seasonal model') pl.plot(freqs,.01*tau_allF1,'-', color=myColor1, lw=2, label='weather station') pl.plot(freqs,.01*tau_allF,'-', color=myColorW, lw=2,label='weighted') sp8.legend(loc=2, borderaxespad=0) pl.ylabel('Tau_Z (nepers)') pl.xlabel('Frequency (GHz)') pl.ylim(0,.25) jm_set_Yvar_ticks(6) jm_set_Ylabel_pos(pos=(0,.5)) pl.savefig( plotName, dpi=150) pl.close() casalog.post('wrote weather figure: '+plotName) return meanTau
def prepare_trial(bhv, trl, options): """From the bhv file extract all the information necessary for plotting a trial. 1. Extract the trial object image data 2. Interpret the plotting options 3. Create a timeline setting out what objects must be shown for each frame and where they are to be shown including eye position 4. Package all this data into a dictionary that can be passed on to subsequent functions """ scr_col = bhv['ScreenBackgroundColor'] ppd = bhv['PixelsPerDegree'] scr_size = (bhv['ScreenXresolution']/ppd, bhv['ScreenYresolution']/ppd) osr_status = bhv['ObjectStatusRecord']['Status'][trl] osr_data = bhv['ObjectStatusRecord']['Data'][trl] osr_time = bhv['ObjectStatusRecord']['Time'][trl] rew = [bhv['RewardRecord']['RewardOnTime'][trl], bhv['RewardRecord']['RewardOffTime'][trl]] eyex = bhv['XEye'][trl] eyey = bhv['YEye'][trl] fs = bhv['AnalogInputFrequency'] objects, pos = parse_task_object_data(bhv) ocount = len(objects) object_size = pylab.zeros((ocount,2)) for n in xrange(ocount): object_size[n,0] = objects[n].shape[0]/ppd object_size[n,1] = objects[n].shape[1]/ppd tstep = options['tstep'] #ms between frames tstart = bhv['CodeTimes'][trl][2] tend = bhv['CodeTimes'][trl][-3] fcount = int(tend/tstep) logger.debug(str(fcount) + ' frames') tframe = pylab.arange(fcount)*tstep #in ms eyex_i = pylab.interp(tframe, 1000*pylab.arange(eyex.size)/fs, eyex)#1000x to get ms eyey_i = pylab.interp(tframe, 1000*pylab.arange(eyey.size)/fs, eyey) frame_data = pylab.zeros((fcount,1+ocount,3)) #frame_data tells us, for each frame, which objects are visible #and where they are located #index 0 - frame number #index 1 - object number 0=eye, 1 ... ocount = objects #index 2 -> [0] - visible (1) or not (0) # [1,2] - xy position in degrees cur_ev = 0 #This keeps track of which is the next event in the object status record we are hoing to hit #Fill in the eye data frame_data[:,0,0] = 1 #Eye is always present frame_data[:,0,1] = eyex_i frame_data[:,0,2] = eyey_i for fr in xrange(fcount): while tframe[fr] >= osr_time[cur_ev]: for n,ojst in enumerate(osr_status[cur_ev]): if ojst == 0: frame_data[fr:,n+1,0] = 0 #Switch it off elif ojst == 1: frame_data[fr:,n+1,0] = 1 #Switch it on frame_data[fr:,n+1,1:] = pos[n,:] elif ojst == 2: #Move it pos[n,:] = osr_data[cur_ev][0] frame_data[fr:,n+1,1:] = pos[n,:] cur_ev += 1 if cur_ev >= len(osr_time): break if cur_ev >= len(osr_time): break movie_data = { 'speed': options['speed'], 'screen color': scr_col, 'screen size': scr_size, 'pixels per degree': ppd, 'frame data': frame_data, 'tstart': tstart, 'tframe': tframe, 'objects': objects, 'object size': object_size } return movie_data