def get_librosa_pitch(signal, fs, window): pitches, magnitudes = librosa.piptrack(y=signal.astype('float'), sr=fs, n_fft=int(window), hop_length=int(window/10)) pitch_pos = np.argmax(magnitudes, axis=0) pitches_final = [] for i in range(len(pitch_pos)): pitches_final.append(pitches[pitch_pos[i], i]) pitches_final = np.array(pitches_final) pitches_final[pitches_final > 2000] = 0 # cut high pitches return mf(pitches_final, 3) # use medfilt for smoothing
def __init__(self, position, amplitude, cadence, flux, window_width=100): """ Parameters ---------- position : float Approximate position of the discontinuity. amplitude : float Approximate amplitude of the discontinuity. cadence : 1D array Cadence array flux : 1D array Flux array window_width : int (> 25) Size of the local window """ assert isinstance(cadence, (tuple, list, ndarray)) assert isinstance(flux, (tuple, list, ndarray)) assert isinstance(window_width, int) and window_width > 25 assert len(flux) == len(cadence) assert all( flux[isfinite(flux)] > 0), "Flux array contains negative values." self.position = float(position) # Approximate discontinuity position self._amplitude_g = float( amplitude) # Approximate discontinuity amplitude self._cadence_g = cadence # Global cadence array self._flux_g = flux # Global flux array self.use_gp = False self.gp = None self.hp = None # Initialize discontinuity models # ------------------------------- self.type = UnclassifiedDiscontinuity(self) self.models = [M(self) for M in self._available_models] self.bics = zeros(len(self.models)) # Create local cadence and flux arrays # ------------------------------------ self._ww = window_width self._hw = self._ww // 2 self.npt = self._ww idx = np.argmin(np.abs(self._cadence_g - self.position)) self._sl = sl = np.s_[max(0, idx - self._hw ):min(idx + self._hw, self._cadence_g.size)] self.cadence = self._cadence_g[sl].copy() self.flux = self._flux_g[sl].copy() self.local_median = median(self.flux) self.flux[:] = self.global_to_local(self.flux) self.wn_estimate = (self.flux - mf(self.flux, 5)).std() self.amplitude = self._amplitude_g / self.local_median
def __init__(self, position, amplitude, cadence, flux, window_width=100): """ Parameters ---------- position : float Approximate position of the discontinuity. amplitude : float Approximate amplitude of the discontinuity. cadence : 1D array Cadence array flux : 1D array Flux array window_width : int (> 25) Size of the local window """ assert isinstance(cadence, (tuple, list, ndarray)) assert isinstance(flux, (tuple, list, ndarray)) assert isinstance(window_width, int) and window_width > 25 assert len(flux) == len(cadence) assert all(flux[isfinite(flux)] > 0), "Flux array contains negative values." self.position = float(position) # Approximate discontinuity position self._amplitude_g = float(amplitude) # Approximate discontinuity amplitude self._cadence_g = cadence # Global cadence array self._flux_g = flux # Global flux array self.use_gp = False self.gp = None self.hp = None # Initialize discontinuity models # ------------------------------- self.type = UnclassifiedDiscontinuity(self) self.models = [M(self) for M in self._available_models] self.bics = zeros(len(self.models)) # Create local cadence and flux arrays # ------------------------------------ self._ww = window_width self._hw = self._ww//2 self.npt = self._ww idx = np.argmin(np.abs(self._cadence_g-self.position)) self._sl = sl = np.s_[max(0, idx-self._hw) : min(idx+self._hw, self._cadence_g.size)] self.cadence = self._cadence_g[sl].copy() self.flux = self._flux_g[sl].copy() self.local_median = median(self.flux) self.flux[:] = self.global_to_local(self.flux) self.wn_estimate = (self.flux - mf(self.flux, 5)).std() self.amplitude = self._amplitude_g / self.local_median
def smoothExpData(expData,rmax,Nr): x1 = x=expData['x']*1e6 y1=expData['y']*1e6 a_xy = np.sqrt(expData['F_xy']) # interpolator from experimental data F = RectBivariateSpline(y1,x1,a_xy) phi_func = RectBivariateSpline(y1,x1,expData['phi_xy']) # build polar coords Nm = 180 r = np.linspace(0,rmax,num=Nr) theta = np.linspace(-pi,pi,num=2*Nm) [R,T] = np.meshgrid(r,theta) # and cartesian versions X = R*np.cos(T) Y = R*np.sin(T) F_rt = F(Y*1e6,X*1e6,grid=False) # reduced cartesian coords x2 = np.linspace(-rmax,rmax,num=Nr) y2 = np.linspace(-rmax,rmax,num=Nr) [X2,Y2] = np.meshgrid(x2,y2) R2 = np.sqrt(X2**2+Y2**2) T2 = np.arctan2(Y2,X2) F_rt = mf(F_rt,(1,11))*(1-np.tanh((R-rmax*0.5)/(rmax*0.1)))/2 # interpolate from r,t to x,y reduced G = RectBivariateSpline(theta,r,F_rt) F_reduced = G(T2,R2,grid=False) expData2 = copy.deepcopy(expData) expData2['x'] = x2 expData2['y'] = y2 expData2['F_xy'] = (F_reduced/np.max(F_reduced))**2 expData2['phi_xy'] = phi_func(y2*1e6,x2*1e6) return expData2
output = np.zeros(image.shape, np.uint8) thres = 1 - prob for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() if rdn < prob: output[i][j] = 0 elif rdn > thres: output[i][j] = 255 else: output[i][j] = image[i][j] return output noise_img = sp_noise(img, 0.05) amf = mf(noise_img, 3) plt.subplot(1, 3, 1) plt.imshow(img, cmap='gray') plt.title('Original Image') plt.subplot(1, 3, 2) plt.imshow(noise_img, cmap='gray') plt.title('Noisy Image') plt.subplot(1, 3, 3) plt.imshow(amf, cmap='gray') plt.title('Using Function') plt.subplots_adjust(hspace=0.25, wspace=0.35) img1 = np.pad(noise_img, 1, mode='constant') a1 = np.zeros([512, 512]) a2 = np.zeros([512, 512]) a3 = np.zeros([512, 512])
plt.plot(t2, 'g-') #plt.plot(t2a,'g--') t3 = t3 / t3.max() - 1. t3a = t3a / t3a.max() - 1. plt.plot(t3, 'r-') plt.subplot(413) spec = specs[burst_loc, :] spec = np.mean(spec.reshape((412, 4)), axis=1) plt.plot(spec) spec3 = specs[3, :] spec3 = np.mean(spec3.reshape((412, 4)), axis=1) plt.plot(spec3, '--') tspec = spec - spec3 madd = 1.4826 * np.median(np.abs(tspec - np.median(tspec))) vals = np.abs(tspec) / madd medfi = mf(vals, kernel_size=25) S2 = 1. / (np.sum(vals) - np.sum(medfi)) plt.subplot(414) plt.plot(vals) plt.plot(medfi, '--') # print STATs print 'STATS', S1, S2 plt.savefig(oname + '.png', bbox_inches='tight') plt.close()
def calc_2dbkg(flux, qual, time): q = qual == 0 med = np.percentile(flux[:, :, :], 1, axis=(2)) med = med - mf(med, 25) g = np.ma.masked_where(med < np.percentile(med, 70.), med) modes = 21 pca = PCA(n_components=modes) pca.fit(flux[g.mask]) pv = pca.components_[0:modes].T[q] vv = np.column_stack((pv.T)) for i in range(-15, 15, 6): if i != 0: if i > 0: rolled = np.pad(pv.T, ((0, 0), (i, 0)), mode='constant')[:, :-i].T else: rolled = np.pad(pv.T, ((0, 0), (0, -i)), mode='constant')[:, -i:].T vv = np.column_stack((vv, rolled)) vv = np.column_stack((vv, np.ones_like(vv[:, 0]))) maskvals = np.ma.masked_array(data=np.zeros((104, 148, np.shape(vv)[1])), mask=np.zeros((104, 148, np.shape(vv)[1]))) GD = np.zeros_like(maskvals) for i in range(len(g)): for j in range(len(g[0])): if g.mask[i][j] == True: maskvals.data[i, j] = do_pca(i, j, flux, vv, q) noval = maskvals.data[:, :, :] == 0 maskvals.mask[noval] = True outmeasure = np.zeros_like(maskvals[:, :, 0]) for i in range(len(maskvals[0, 0])): outmeasure += (np.abs(maskvals.data[:, :, i] - np.nanmean(maskvals.data[:, :, i]))) / np.nanstd( maskvals.data[:, :, i]) metric = outmeasure / len(maskvals.data[0, 0]) maskvals.mask[metric > 1.00, :] = True x = np.arange(0, maskvals.data.shape[1]) y = np.arange(0, maskvals.data.shape[0]) xx, yy = np.meshgrid(x, y) for i in range(np.shape(vv)[1]): array = np.ma.masked_invalid(maskvals[:, :, i]) x1 = xx[~array.mask] y1 = yy[~array.mask] newarr = array[~array.mask] GD[:, :, i] = interpolate.griddata((x1, y1), newarr.ravel(), (xx, yy), method='linear') array = np.ma.masked_invalid(GD[:, :, i]) xx, yy = np.meshgrid(x, y) x1 = xx[~array.mask] y1 = yy[~array.mask] newarr = array[~array.mask] GD[:, :, i] = interpolate.griddata((x1, y1), newarr.ravel(), (xx, yy), method='nearest') bkg_arr = np.zeros_like(flux) for i in range(104): for j in range(148): bkg_arr[i, j, q] = np.dot(GD[i, j, :], vv.T) bkg_arr[i, j, q] = lowpass(bkg_arr[i, j, q]) f = interp1d(time[q], bkg_arr[:, :, q], kind='linear', axis=2, bounds_error=False, fill_value='extrapolate') fout = f(time) return fout