def analisisHR(hrValues, miliValues, sample_size): plt.plot(miliValues, hrValues) #plt.show(); smoothed_values = [ data for data, i in smooth_curve_simple(hrValues, sample_size) ] average = [] peaks = fp(smoothed_values)[0] previous = peaks[0] peakplotX = [miliValues[previous]] peakplotY = [smoothed_values[previous]] for id in peaks[1:]: average.append(miliValues[id] - miliValues[previous]) previous = id peakplotX.append(miliValues[previous]) peakplotY.append(smoothed_values[previous]) plt.plot(smoothed_values) #plt.scatter(peakplotY , marker='+', c='Red') #plt.show() print("Picos: ", len(peaks), " Longitud: ", miliValues[-1] - miliValues[0]) len(peaks) valorHR = (60000) / ((miliValues[-1] - miliValues[0]) / len(peaks)) return valorHR
def peak_detection(y,show = False): '''Function which detects te number of peaks in a curve, according to a certain threshold. First peak must be 1/2 of the max and second peak must be 1/2 or more of the main peak, with a 1/4 minimum prominence''' from scipy.signal import find_peaks as fp ydet = np.concatenate((y[-12:],y,y[:12])) # we repeat the curve a little bit such that peaks at borders are not neglected by algo p, prop = fp( ydet, height=0, distance=4, prominence = (np.amax(y)/6,y.max())) idx = ((p-12 > -1) & (p-12 < 24)) p = (p - 12)[idx] for key in prop.keys(): prop[key] = prop[key][idx] return p, prop
def analisisHR2(hrValues, miliValues, sample_size): #smoothed_values = smooth_curve_simple(hrValues, sample_size) smoothed_values = [ data for data, i in smooth_curve_simple(hrValues, sample_size) ] peaks = fp(smoothed_values)[0] average = [] for id in range(0, len(peaks) - 1, 2): current = peaks[id + 1] * sample_size + sample_size previous = peaks[id] * sample_size + sample_size average.append(miliValues[current] - miliValues[previous]) # previous = id*sample_size plt.plot(smoothed_values) plt.scatter(peaks, [smoothed_values[j] for j in peaks], marker='+', c='Red') #plt.show() valorHR = (60000 * len(peaks)) / (miliValues[-1] - miliValues[0]) # valorHR=(60000)/(sum(average)/len(average)) return valorHR
def find_peaks(points, threshold=0.5): """ Finds the peaks in a signal. Parameters ---------- points : ndarray 1-D array of normalized data points. threshold : float Limit to filter peaks; those below that value are discarded. Returns ------- ndarray : 1-D array with the indices corresponding to the peaks of points. """ # Find the peaks peaks, _ = fp(points, distance=15) # Filter the peaks based on threshold valid_peaks = np.argwhere(points[peaks] > threshold) return peaks[valid_peaks.ravel()]
def theta_color_correction(shadow_corrected_img, mask, save_ccimg_deg=False, cd_save='./ccimg_deg_', SNR_return=False, save_SNR=False, cd_SNR='./SNR_img'): import cv2 from scipy.signal import find_peaks as fp from functools import reduce import numpy as np import math ''' Color Correction Using Degrees: I_i^(shadow free) = ((r + 1)/(k_i*r + 1))I_i r = L_d/L_e; L_d = intensity of non-shadow pixels L_e = intensity of shadow pixels k_i = t_i*cos(theta_i); t_i = 1 if object in sunshine region and 0 if object in shadow region (attenuation factor of direct light) theta_i = angle between direct lighting direction and the surface normal I_i = pixel at i^th value mask already gives us if object is in a sunshine region, where t_i = 1, and if object is in a shadow region, where t_i = 0. Then iterate through varying values of theta to see how these affect the outcome of the color correction to the image. Need to find L_d and L_e, which seem to be global variables. This doesn't seem like an especially smart move as there will be many different intensities throughout the image, especially with a very busy image. Purpose of k_i is that if point is in a direct sunshine region, no angle between direct light and ambient light, then that pixels value will not change as k_i will equal 1 due to being in a sunshine region and having a theta_i = 0. If a pixel is in a shadow region, then pixel intensity should be brought up slightly to match sunshine region. ''' ##shadow_corrected_image should come from ycbcr_color_correction function ##mask is needed for SNR calculation ##save_ccimg_deg is optional to save all of the output pictures ##cd_save is where you want to save the 181 output pictures, as this function ##runs through all the angles from 0 to 180 to test on further correcting the colors of the image ##SNR_return will allow a return of the SNR calculated for each image ##Convert output image to HSI space to get purely intensity values of shadow to non-shadow pixels result_HSI = cv2.cvtColor(shadow_corrected_img.copy(), cv2.COLOR_RGB2HSV) ##for SNR sf_SNR = [] mask_rep = np.repeat(mask[:, :, np.newaxis], 3, axis=2) ##range of degrees from 0 to 180 deg_range = 181 for i in range(deg_range): ##intensity of shadow pixels L_e_I = np.sum(np.multiply(result_HSI[:, :, 2], mask.copy())) / (mask == 1).sum() ##intensity of non-shadow pixels L_d_I = np.sum( np.multiply(result_HSI[:, :, 2], np.logical_not( mask.copy()))) / (mask == 0).sum() ##ratio of non-shadow pixel intensities to shadow pixel intensities r_I = L_d_I / L_e_I k_i = mask.copy() * math.cos(math.radians(i)) k_i[k_i == 0] = 1 result_shadow_free_I = np.uint8( ((r_I + 1) / (k_i * r_I + 1)) * result_HSI[:, :, 2].copy()) result_HSI[:, :, 2] = result_shadow_free_I.copy() result_sf = cv2.cvtColor(result_HSI.copy(), cv2.COLOR_HSV2RGB) result_sf = cv2.cvtColor(result_sf, cv2.COLOR_BGR2RGB) ##note that any pixels within the shadow region that are intrinsically ##zero will be discarded using this methodology, but this was the only way ##I figured to calculate SNR, specifically in the mask areas result_sf_mask_area_mult = np.multiply(result_sf.copy(), mask_rep) result_sf_mask_area_flat = result_sf_mask_area_mult.flat result_sf_mask_area_fl8 = result_sf_mask_area_flat[ result_sf_mask_area_flat != 0] sf_mean = np.mean(result_sf_mask_area_fl8.copy()) sf_std = np.std(result_sf_mask_area_fl8.copy()) ratio = sf_mean / sf_std sf_SNR.append(ratio) if save_ccimg_deg == True: ccimg_deg = cd_save + str(i) + '.jpg' cv2.imwrite(ccimg_deg, result_sf) ##finds mean of sf_SNR and divides by max value of sf_SNR to get unique threshold thresh = (reduce(lambda x, y: x + y, sf_SNR) / 181) / (np.amax(sf_SNR)) SNR_peaks = fp(sf_SNR, height=np.amax(sf_SNR) - thresh, distance=10) degrees = np.linspace(0, 180, 181) plt.plot(degrees, sf_SNR) plt.xlabel('degrees') plt.ylabel('SNR') plt.title('SNR vs degrees of ambient light to reflected light') for i in range(SNR_peaks[0].shape[0]): y_max = sf_SNR[SNR_peaks[0][i]] x_max = SNR_peaks[0][i] text_max = "x={:.3f}".format(x_max) plt.annotate(text_max, xy=(x_max, y_max)) y_min = np.amin(sf_SNR) x_min = sf_SNR.index(min(sf_SNR)) text_min = "x={:.3f}".format(x_min) plt.annotate(text_min, xy=(x_min, y_min)) if save_SNR == True: plt.savefig(cd_SNR + '.png', bbox_inches='tight') if SNR_return == True: return sf_SNR
r_v = np.array([(vel1)[zero_crossings], (vel1)[zero_crossings]]) Radial_Velocity = np.mean(r_v) vel1 = vel1 - Radial_Velocity vel2 = vel2 - Radial_Velocity frequency, power = LombScargle(data[:, 0], vel1).autopower(minimum_frequency=0.1, maximum_frequency=2) f_opt = frequency[np.where(power == np.max(power))] def sine(x, V, f): return V * np.sin(2 * np.pi * f * x) indices1 = fp(np.abs(vel1), height=15) v1 = np.mean(np.abs(vel1[indices1[0]])) indices2 = fp(np.abs(vel2), height=12) v2 = np.mean(np.abs(vel2[indices2[0]])) p_opt = np.array([-v1, f_opt]) plt.subplot(2, 1, 1) plt.title('Star 1') plt.plot(data[:, 0], sine(data[:, 0], *p_opt), label='Best Fit', color='g') plt.scatter(data[:, 0], vel1, s=0.1, color='darkorange') p_opt = np.array([v2, f_opt]) plt.subplot(2, 1, 2) plt.title('Star 2') plt.plot(data[:, 0], sine(data[:, 0], *p_opt), label='Best Fit', color='g')
(s.h * s.c) / (l * s.k * T)) - 1)) return t plt.plot(wvl, dat) plt.show() inp = input("Where to cut:\n") if inp == 'max': cut = np.argmax(dat) else: cut = wvl.tolist().index(int(inp)) cut = int(cut) spec = wvl.tolist().index(3500) val, var = cfit(B, l[cut:], dat[cut:], p0=[1000, 1]) peaks, _ = fp((B(l, val[0], val[1]) - dat), height=0, prominence=0.05) wvlpk = (peaks * 5 + 1150) specpk = [] for i in range(len(peaks)): if wvlpk[i] > 6550 and wvlpk[i] < 6650: specpk.append(wvlpk[i]) elif wvlpk[i] > 4750 and wvlpk[i] < 4850: specpk.append(wvlpk[i]) elif wvlpk[i] > 4300 and wvlpk[i] < 4400: specpk.append(wvlpk[i]) specpk = (np.array(specpk) + (-1150)) / 5 wvlpk = np.array(specpk).astype(int) plt.plot((peaks * 5 + 1150), dat[peaks], "x") plt.plot((wvlpk * 5 + 1150), dat[wvlpk], "o") plt.plot(wvl, B(l, val[0], val[1]) - dat) plt.plot(wvl, dat)
@author: Ryan """ import numpy as np import matplotlib.pyplot as plt from scipy.signal import find_peaks as fp lc = np.genfromtxt("lightcurve_data.txt") rv = np.genfromtxt("RV_data.txt") jd = lc[:, 0] - lc[0, 0] peaks = (lc[:, 1] - 1) * -1 # find peaks and subtract their x value to create folded rotation curve. t = fp(peaks, height=0.007, width=5) light = [] phase = [] for ind, i in enumerate(lc[:, 1]): for ind2, j in enumerate(t[0]): if j == ind: for k in lc[ind - 10:ind + 10, 1]: light.append(k) for l in jd[ind - 10:ind + 10] - jd[ind]: phase.append(l) else: continue # plot the resulting light curve
for sat in range(CLASS[l].shape[1]): nb_peaks1[K, sat] = P_HSENS1[l][K, sat, 0].shape[0] nb_peaks2[K, sat] = P_HSENS2[l][K, sat, 0].shape[0] nb_peaks3[K, sat] = P_HSENS3[l][K, sat, 0].shape[0] nb_peaks4[K, sat] = P_HSENS4[l][K, sat, 0].shape[0] NB_peaks1.append(nb_peaks1) NB_peaks2.append(nb_peaks2) NB_peaks3.append(nb_peaks3) NB_peaks4.append(nb_peaks4) Hue = np.arange(0, 2 * np.pi, 2 * np.pi / 24) y = MM1[-1][29, -1, :] ydet = np.concatenate((y[-2:], y)) fp(ydet, height=(np.amax(y)) / 2, distance=4, prominence=(np.amax(y) / 8, y.max())) R1 = F.peak_detection(y, show=False) prop_null = np.zeros(len(CLASS)) prop_1 = np.zeros(len(CLASS)) prop_2 = np.zeros(len(CLASS)) prop_3 = np.zeros(len(CLASS)) prop_4 = np.zeros(len(CLASS)) for l in range(0, len(CLASS)): a1 = np.amax(M_HSENS1[l], axis=-1) > t2 a2 = np.amax(M_HSENS2[l], axis=-1) > t2 a3 = np.amax(M_HSENS3[l], axis=-1) > t2 a4 = np.amax(M_HSENS4[l], axis=-1) > t2 ar = np.amax(M_ROT[l], axis=-1) > t2