def transform_points(src, dst, pts, steps): surfaces = [] surf_array = np.zeros((1280, 720, 3)) first_line = poly.fit([src[0][0], dst[0][0]], [src[0][1], dst[0][1]], 1) second_line = poly.fit([src[1][0], dst[1][0]], [src[1][1], dst[1][1]], 1) third_line = poly.fit([src[2][0], dst[2][0]], [src[2][1], dst[2][1]], 1) fourth_line = poly.fit([src[3][0], dst[3][0]], [src[3][1], dst[3][1]], 1) first_points = first_line.linspace(steps) second_points = second_line.linspace(steps) third_points = third_line.linspace(steps) fourth_points = fourth_line.linspace(steps) for i in range(1, steps): dst = np.float32([[first_points[0][-i], first_points[1][-i]], [second_points[0][i], second_points[1][i]], [third_points[0][i], third_points[1][i]], [fourth_points[0][-i], fourth_points[1][-i]]]) M = cv2.getPerspectiveTransform(src, dst) transformed_points = cv2.perspectiveTransform(pts, M) surface = pygame.Surface((1280, 720)) pygame.draw.polygon(surface, (0, 130, 0), np.squeeze(transformed_points, axis=0)) surfaces.append(surface) return surfaces
def experiment(self): self.leg = self.genlegpoly() self.dataset = self.gendataset() self.g2 = Polynomial.fit(self.dataset[0], self.dataset[1], 2, [-1.0, 1.0]) self.g10 = Polynomial.fit(self.dataset[0], self.dataset[1], 10, [-1.0, 1.0]) self.eoutg2 = self.mse4(self.g2, self.leg) self.eoutg10 = self.mse4(self.g10, self.leg)
def momentum_analysis_global_chi2(meas_solver, analysis_B_func, B_name='Mau 13 (nominal)', sigma=1., delta=.2, N_hyp=7, plot_chi2=False): # use circle fit analysis mean to determine test_ps meas_solver.analyze_trajectory(step=25, stride=1, query="z >= 8.41 & z <= 11.66", B=analysis_B_func) circle_fit_mom = meas_solver.df_reco.p.mean() pmin = circle_fit_mom - delta pmax = circle_fit_mom + delta ps_test = np.linspace(pmin, pmax, N_hyp) # run particles for each hypothesis momentum sum_of_impacts2 = global_chi2_ptests(test_ps=ps_test, test_B_func=analysis_B_func, meas_solver=meas_solver, sigma=sigma) # fit quadratic to calculated chi2 values c, b, a = Polynomial.fit(ps_test, sum_of_impacts2, 2).convert().coef # use quadratic parameters to get momentum estimate chi2_fit_mom = -b / (2 * a) # plot (if selected) if plot_chi2: ptrue = meas_solver.init_conds.p0 ps_quad = np.linspace(pmin, pmax, 50) y_quad = a * ps_quad**2 + b * ps_quad + c fig = plt.figure() plt.plot(ps_quad, y_quad, c='gray', label='Quadratic Fit') plt.scatter(ps_test, sum_of_impacts2, c='black', label='Calculated ' + r"$\chi^2$", zorder=100) ymax = np.max(sum_of_impacts2) plt.plot([ptrue, ptrue], [0., ymax], 'r-', linewidth=2, label=f'True Momentum ={ptrue:.3f} MeV/c', zorder=90) plt.plot([chi2_fit_mom, chi2_fit_mom], [0., ymax], 'g--', label='Momentum ' + r'$(\chi^2) =$' + f'{chi2_fit_mom:.3f} MeV/c', zorder=92) plt.plot([circle_fit_mom, circle_fit_mom], [0., ymax], 'b--', label=f'Momentum (circle) = {circle_fit_mom:.3f} MeV/c', zorder=91) plt.xlabel(r"$p$" + " [MeV/c]") plt.ylabel(r"$\chi^2$") plt.title('Global ' + r'$\chi^2$' + f' Momentum Fit: {B_name}') l = plt.legend(loc='upper right') l.set_zorder(110) return chi2_fit_mom, circle_fit_mom, fig # return results return chi2_fit_mom, circle_fit_mom
def measure(self): """Compute some metrics that give an idea of how well each area is doing.""" for aoi in self.aoi.values(): if 'population' not in aoi: print("No population info for", aoi['name']) continue if 'cases' not in aoi['data']: print("No cases for", aoi['name']) continue if len(aoi['data']['cases']) < 2: print("Insufficient cases for", aoi['name']) continue distance = [] pop = aoi['population'] distance = [(v or 0) / pop for v in aoi['data']['cases']] window = min(14, len(distance)) polynomial = Polynomial.fit(range(window), distance[-window:], min(3, window)) coefficients = list(polynomial.convert().coef[1:]) # If the trailing coefficients are 0, they're not included in coef. # Add them back. while len(coefficients) < 3: coefficients.append(0) aoi['velocity'] = coefficients[0] aoi['acceleration'] = coefficients[1] aoi['jerk'] = coefficients[2]
def polyDataFor(arr): ''' t -> vel fit func = Poly.fit(arr[:, 0], arr[:, 1], 1) data = np.empty_like(arr) for i in range(len(arr)): data[i] = [arr[i,0], func(arr[i,0])]''' # before -> vel fit func = Poly.fit(arr[:-1, 1], (arr[1:, 1] - arr[:-1, 1]) / (arr[1:, 0] - arr[:-1, 0]), 1, domain=[]) print("Poly fitted:", func, func.domain, func.window) data = np.empty((arr.shape[0] - 1, arr.shape[1])) prevV = arr[0, 1] for i in range(len(arr) - 1): prevT = arr[i, 0] nextT = arr[i + 1, 0] #nextV = prevV + func(prevV) * (nextT - prevT) #fac = - 0.0305 * prevV # free in air -0.4690 #fac = -227.20539704480407 - 0.03047 * prevV # rollin on ground > 550 vel #fac = func(prevV) nextV = prevV + fac * (nextT - prevT) data[i] = [nextT, nextV] #func(prevV) prevV = nextV return data
def poly_fit_eta(): from numpy.polynomial.polynomial import Polynomial x = np.linspace(1,0,2000) for i in range(10): U1, U2 = [unitary_group.rvs(4) for _ in range(2)] A1,A2 = [np.random.rand(16).reshape(4,4) + 1j*np.random.rand(16).reshape(4,4) for _ in range(2)] H1 = 0.5*(A1 + A1.conj().T) H2 = 0.5*(A2 + A2.conj().T) te1 = expm(1j*H1*0.1) te2 = expm(1j*H2*0.1) U1_ = (te1 @ U1).conj().T U2_ = (te2 @ U2).conj().T RE = RightEnvironment() params = [np.pi/4,0,0,0,0,0] # np.random.rand(6) C = CircuitSolver() M = C.M(params) M_ = RE.circuit(r(U1), r(U2), r(U1_), r(U2_), M) scores = [] for p in x: scores.append(np.linalg.norm(p * M - M_)) coefs = Polynomial.fit(x[:10],scores[:10],deg = 2, domain = (1,0.9)) new_vals = [coefs(a) for a in x] plt.plot(x, scores, label = "Exact") plt.plot(x, new_vals, label = "Poly Fit") plt.legend() plt.show()
def test_poly1D_fit_weighted(): polyOrder = np.random.randint(2, 5) numMeasurements = np.random.randint(50, 100) xValues = np.random.rand(numMeasurements) * 100 - 50 coefficients = np.random.rand(polyOrder + 1) * 5 - 10 yValues = [] for x in xValues: y = 0 for order in range(polyOrder + 1): y += coefficients[order] * x**order yValues.append(y + np.random.randn(1).item()) yValues = np.array(yValues) yValues = yValues.reshape(yValues.size, 1) weights = np.random.rand(numMeasurements) cX = NumCpp.NdArray(1, xValues.size) cY = NumCpp.NdArray(yValues.size, 1) cWeights = NumCpp.NdArray(1, xValues.size) cX.setArray(xValues) cY.setArray(yValues) cWeights.setArray(weights) poly = Polynomial.fit(xValues, yValues.flatten(), polyOrder, w=weights).convert().coef polyC = NumCpp.Poly1d.fitWeighted( cX, cY, cWeights, polyOrder).coefficients().getNumpyArray().flatten() assert np.array_equal(np.round(poly, 1), np.round(polyC, 1))
def fit(x, y, deg, regularization=0): # order = polyfit1d(y, x, deg, regularization) if deg == "best": order = best_fit(x, y) else: order = Polynomial.fit(y, x, deg=deg, domain=[]).coef[::-1] return order
def weighted_linregress(x, y, degree=1, weights=None) -> Tuple[np.ndarray, float]: """ https://en.wikipedia.org/wiki/Coefficient_of_determination#Definitions :param x: :param y: :param degree: :param weights: :return: - coefficients in increasing order of power of x (intercept, linear, quadratic etc.) - coefficient of determination (R^2) """ series, (weighted_sum_of_squares_of_residuals, _, _, _) = Polynomial.fit(x, y, degree, full=True, w=weights) y_predicted = series(x) mean_observed = np.mean(y) # \bar{y} total_sum_of_squares = np.sum((y - mean_observed)**2) # SS_{tot} # variance = total_sum_of_squares / (len(x) - 1) # std_dev = np.sqrt(variance) # std_err = std_dev / np.sqrt(len(x)) # regression_sum_of_squares = np.sum((y_predicted - mean_observed)**2) sum_of_squares_of_residuals = np.sum((y - y_predicted)**2) coeff_determination = 1 - (sum_of_squares_of_residuals / total_sum_of_squares) return series.convert().coef, coeff_determination.squeeze()
def plot_speed(data): speed = (1.0 / 5.0) * data['length'] / (data['time'] / 1000 / 60) x = np.arange(len(speed)) y = speed fig, ax = plt.subplots(2, 1, figsize=(20, 10)) #plt.figure(figsize = (20,10)) # ax[0].set_title("Words per minute", fontsize=24) fit = Polynomial.fit(x, y, deg=12) ax[0].scatter(x, y, linewidth=2, color='limegreen', label='speed (raw data)') ax[0].plot(x, fit(np.array(x).astype(float)), linewidth=4, color='forestgreen', label='speed (polynomial fit)') ax[0].legend(fontsize=24) # ax[0].set_xlabel("sample num", fontsize=24) # ax[0].set_xlabel() ax[0].set_xticklabels([]) ax[0].set_ylabel("Speed, words per min", fontsize=24) ax[0].set_ylim([0, 1.1 * np.max(y)]) ax[0].grid(True) errors = data['errors'] x = np.arange(len(errors)) y = errors fit = Polynomial.fit(x, y, deg=12) ax[1].scatter(x, y, s=2, color='red', label='errors (raw data)') ax[1].plot(x, fit(np.array(x).astype(float)), linewidth=4, color='crimson', label='errors (polynomial fit)') ax[1].legend(fontsize=24) ax[1].set_xlabel("sample num", fontsize=24) ax[1].set_ylabel("Errors", fontsize=24) ax[1].set_ylim([0, 1.1 * np.max(y)]) ax[1].grid(True) plt.subplots_adjust(wspace=None, hspace=None) plt.tight_layout() plt.show(block=True) return fig
def __init__(self, x, y, degree=1, weights=None): self.x = x self.y = y self.degree = degree self.w = weights self.series, (weighted_sum_of_squares_of_residuals, _, _, _) = Polynomial.fit(x, y, degree, full=True, w=weights)
def op(seq): if seq == [1]: return [1] return [ int(i) for i in (rint( Polynomial.fit(range(1, len(seq) + 1), seq, len(seq) - 1).convert().coef[::-1]).tolist()) ]
def getSyncInfo(self): """ unpack everything return: dictionary indexed by channel number """ if self.syncInfo is None: l_allSyncTimes = [] l_allSyncChannels = [] l_allPhaseTimes = [] l_allPhaseChannels = [] l_allPhases = [] for iFile, fileName in enumerate(self.binFnList): print iFile, len(self.binFnList), rv = unpackOneFramesFile.unpackOneFramesFile(fileName) l_allSyncTimes.append(rv['syncTimes']) l_allSyncChannels.append(rv['syncChannels']) l_allPhaseTimes.append(rv['times']) l_allPhaseChannels.append(rv['channels']) l_allPhases.append(rv['phases']) print "now call _ltoa on lists" allSyncTimes = _ltoa(l_allSyncTimes) allSyncChannels = _ltoa(l_allSyncChannels).astype(int) allPhaseTimes = _ltoa(l_allPhaseTimes) allPhaseChannels = _ltoa(l_allPhaseChannels) allPhases = _ltoa(l_allPhases) self.syncInfo = {} st0 = allSyncTimes[0] st = np.unique(allSyncTimes) - st0 self.syncInfo['syncTimes'] = st x = np.arange(len(st)) fit = Polynomial.fit(x, st, 1) print("fit.coef=", fit.coef) n = fit.domain[1] x, yFit = fit.linspace(n=n + 1) resid = st - yFit syncFreq = 1 / fit.convert().coef[1] self.syncInfo['fit'] = fit self.syncInfo['syncTimesFit'] = yFit self.syncInfo['syncFreq'] = syncFreq print "sort by channel" for channel in np.unique(allSyncChannels): if channel > 0: print "channel =", channel sic = {} self.syncInfo[channel] = sic inds = np.where(allPhaseChannels == channel)[0] sic['phaseTimes'] = allPhaseTimes[inds] - st0 sic['phases'] = allPhases[inds] print "write", self.syncInfoFn pickle.dump(self.syncInfo, open(self.syncInfoFn, 'wb')) return self.syncInfo
def image_transition(image, src, dst, steps): surfaces = [] first_line = poly.fit([src[0][0], dst[0][0]], [src[0][1], dst[0][1]], 1) second_line = poly.fit([src[1][0], dst[1][0]], [src[1][1], dst[1][1]], 1) third_line = poly.fit([src[2][0], dst[2][0]], [src[2][1], dst[2][1]], 1) fourth_line = poly.fit([src[3][0], dst[3][0]], [src[3][1], dst[3][1]], 1) first_points = first_line.linspace(steps) second_points = second_line.linspace(steps) third_points = third_line.linspace(steps) fourth_points = fourth_line.linspace(steps) for i in range(1, steps): dst = np.float32([[first_points[0][i], first_points[1][i]], [second_points[0][-i], second_points[1][-i]], [third_points[0][-i], third_points[1][-i]], [fourth_points[0][i], fourth_points[1][i]]]) warped_image = transform_view(image, src, dst) image_surface = pygame.surfarray.make_surface( warped_image.swapaxes(0, 1)) surfaces.append(image_surface) return surfaces
def peak_and_std_via_resample(self, x_start, N=10, factor=0.75): x_peak = self.find_peak(x_start) h = self.dx * factor x_around = np.array([x_peak - h, x_peak, x_peak + h]).reshape(-1, 1) # collect the new posterior mean and variance mu, var = self.predict(x_around, grads=False) fs = np.random.multivariate_normal(mu.flatten(), var, N) ds = [] for ii in range(N): c = Polynomial.fit(x_around.flatten() - x_peak, fs[ii, :], deg=2) c = c.coef dx = -0.5 * c[1] / c[2] ds.append(dx) return x_peak, np.std(ds), mu[1], np.sqrt(np.abs(var[1][1]))
def extrapolate_to_N_inf(): MD_data = get_meta_MD_isotherms() keys = ["N=4000", "N=2048", "N=500", "N=256"] x = np.array([1.0 / 4000.0, 1.0 / 2048.0, 1.0 / 500.0, 1.0 / 256.0]) rho = [] p = [] for i in range(9): j = -5 - i rho.append(MD_data[keys[0]]["rho"][j]) p_of_x = [] for key in keys: p_of_x.append(MD_data[key]["p"][j]) line = Poly.fit(x, p_of_x, deg=1) p.append(line(0.0)) return np.array(rho), np.array(p)
def set_parameters(self, q=0.5, delta=6, gamma=10, death_rate=0.01, Eo_frac=0.00001, coefs=None, beta_0=0.08, degree=6): """ This simple routine simply sets the parameters for the model. Note they are not all unity, I want you to figure out the appropriate parameter values. q - the attenuation of the infectivity, gamma in the population that is E delta - the length of time of asymptomatic exposure gamma - the length of time of infection death_rate - the fraction of infected dying Eo_frac - a small number that is multiplied by the population to give the initially exposed degree - degree of polynomial used for beta(t) coeffs - the set of initial coefficients for the polynomial, None in many cases beta_o - a constant initial value of beta, will be changed in the optimization """ # Set beta as a polynomial object if coefs is None: beta_t = Polynomial.fit(self.days_from_zero, beta_0 * np.ones(self.days_from_zero.size), deg=degree) else: beta_t = Polynomial.basis( degree, domain=[self.days_from_zero[0], self.days_from_zero[-1]]) beta_t.coef = coefs self.p['beta'] = beta_t # Fill out the rest of the parameters from function arguments self.p['q'] = q self.p['delta'] = delta self.p['gamma'] = gamma self.p['d'] = death_rate # Fill out the state vector y S = self.p['N'] E = S * Eo_frac I = 0 R = 0 D = 0 self.y_init = np.array([S, E, I, R, D])
def _fit_polyfit(self, time_series: np.ndarray) -> np.ndarray: """ Utility method which takes in a NumPy array representing a time-series, fit a polynomial of order 'poly_degree' given at construction, and returns the polynomial over the same x-axis range. :param time_series: (NumPy array) The time-series to smooth :return: (NumPy array) The smoothed time-series """ x = np.arange(len(time_series)) poly = Polynomial.fit(x, time_series, deg=self.poly_degree) self.poly = poly fitted_time_series = poly(x) return fitted_time_series
def fit_peaks(self, f, verbose=False): self.fit = Poly.fit(self.peaks[sclen], self.peaks[prof], 2) if verbose: print(f'Fitted 2nd order to measured peaks:\n {self.fit}') x = np.arange(0, 10000) y = self.fit(x) yargmax = y.argmax() self.fit_max = [x[yargmax], y[yargmax]] if f: mask = y > 0 f.add_trace(go.Scatter(x=x[mask], y=y[mask], name='Polynomial Fit')) return f
def scatterplot(x, y, x_label, y_label, x_lim, y_lim, title, fit_poly, phi_insp=None, deg=None): fig = plt.figure() plt.title(title) plt.scatter(x, y) if fit_poly: p = Polynomial.fit(x, y, deg=deg) plt.plot(np.sort(x), p(np.sort(x)), color='r', linewidth=3) if not phi_insp is None: plt.axvline(phi_insp, color='k', linestyle='--') plt.grid(True) plt.xlabel(x_label) plt.ylabel(y_label) if not y_lim is None: plt.ylim(y_lim) if not x_lim is None: plt.xlim(x_lim) # plt.show(block=True) # plt.savefig(path_save_to) return fig
def calculate_midline( rot_seg_img: Union[np.ndarray, xr.DataArray], degree: int = 4, pad: int = 10 ) -> Polynomial: """ Calculate a the midline for a single image by fitting a polynomial to the segmented pharynx Parameters ---------- rot_seg_img: Union[np.ndarray, xr.DataArray] The rotated masked pharynx image degree the degree of the polynomial pad the number of pixels to "pad" the domain of the midline with respect to the boundaries of the segmentation mask Returns ------- Polynomial the estimated midline Notes ----- Right now this only works for images that this have been centered and aligned with their anterior-posterior along the horizontal. """ import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") try: rp = measure.regionprops(measure.label(rot_seg_img))[0] xs, ys = rp.coords[:, 1], rp.coords[:, 0] left_bound, _, _, right_bound = rp.bbox return Polynomial.fit( xs, ys, degree, domain=[left_bound - pad, right_bound + pad] ) except IndexError: # Indicates trying to measure on TL for example return None
def get_spec_arc(x): """ Fits an arc to a set of wavelengths including increasingly high order terms until satisfactory convergence. If an 8th order polynomial still fails, a ValueError is raised. """ #Check px scale is smooth npx = len(x) px = 1 + np.arange(npx) for deg in range(1, 9): arc = Polynomial.fit(px / npx, x, deg=deg) c = arc(px / npx) diff = (c - x)[1:] / np.diff(x) maxdiff = np.max(abs(diff)) #poly fitted pixels within 1% of pixel width from data if maxdiff < 0.01: break else: raise ValueError("Could not adequately fit wavelengths(pixels)") return arc, npx
def plot_prc(phi, delta_phi, model_name, signal=None, scatter=True): fig = plt.figure(figsize=(20, 10)) tmp = list(zip(phi, delta_phi)) tmp.sort(key=lambda a: a[0]) phi, delta_phi = zip(*tmp) p = Polynomial.fit(phi, delta_phi, deg=30) if scatter == True: plt.scatter(np.array(phi), np.array(delta_phi), s=0.5, color='k', label="Integral Phase Change") else: plt.plot(np.array(phi), np.array(delta_phi), linewidth=3, color='k', label="Integral Phase Change") if not signal is None: plt.plot((np.array(phi)), np.pi * scale(signal), ls='-', color='b', linewidth=2, label="signal") plt.xlabel(r"$\phi$, rad", fontsize=24) plt.ylabel(r"$Z(\phi)$, rad", fontsize=24) tcks = [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi] lbls = ["0", r"$\frac{\pi}{2}$", r"$\pi$", r"$\frac{3\pi}{2}$", r"$2\pi$"] plt.xticks(ticks=tcks, labels=lbls, fontsize=20) tcks = [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi] lbls = [r"$-\pi$", r"$-\frac{\pi}{2}$", "0", r"$\frac{\pi}{2}$", r"$\pi$"] plt.yticks(ticks=tcks, labels=lbls, fontsize=20) plt.legend(fontsize=24) ttl = model_name.replace("_", " ") plt.title(f"PRC {ttl}", fontdict={"size": 24}) plt.grid(True) return fig
def frequency_comb(self, comb, wave, lines=None): self.nord, self.ncol = comb.shape # TODO give everything better names pixel, order, wavelengths = [], [], [] n_all, f_all = [], [] comb = np.ma.masked_array(comb, mask=comb <= 0) for i in range(self.nord): # Find Peak positions in current order n, peaks = self._find_peaks(comb[i]) # Determine the n-offset of this order, relative to the anchor frequency # Use the existing absolute wavelength calibration as reference y_ord = np.full(len(peaks), i) w_old = interp1d(np.arange(len(wave[i])), wave[i], kind="cubic")(peaks) # w_old = np.interp(peaks, np.arange(len(wave[i])), wave[i]) # w_old = self.evaluate_solution(peaks, y_ord, wave_solution) f_old = speed_of_light / w_old # fr: repeating frequency # fd: anchor frequency of this order, needs to be shifted to the absolute reference frame res = Polynomial.fit(n, f_old, deg=1, domain=[]) fd, fr = res.coef n = np.round((f_old - fd) / fr) res = Polynomial.fit(n, f_old, deg=1, domain=[]) fd, fr = res.coef # The first order is used as the baseline for all other orders # The choice is arbitrary and doesn't matter if i == 0: f0 = fd # n0: shift in n, relative to the absolute reference # shift n to the absolute grid, so that all peaks are given by the same f0 n_offset = (f0 - fd) / fr n_offset = int(round(n_offset)) n -= n_offset n_all += [n] f_all += [f_old] pixel += [peaks] order += [y_ord] fd += n_offset * fr logger.debug("LFC Order: %i, f0: %.3f, fr: %.5f, n0: %.2f", i, fd, fr, n_offset) # Merge Data n_all = np.concatenate(n_all) f_all = np.concatenate(f_all) # Fit f0 and fr to all data # (fr, f0), cov = np.polyfit(n_all, f_all, deg=1, cov=True) res = Polynomial.fit(n_all, f_all, deg=1, domain=[]) f0, fr = res.coef logger.debug("Laser Frequency Comb Anchor Frequency: %.3f 10**10 Hz", f0) logger.debug( "Laser Frequency Comb Repeating Frequency: %.5f 10**10 Hz", fr) # All peaks are then given by f0 + n * fr wavelengths = speed_of_light / (f0 + n_all * fr) pixel = np.concatenate(pixel) order = np.concatenate(order) flag = np.full(len(wavelengths), True) laser_lines = np.rec.fromarrays( (wavelengths, pixel, pixel, order, flag), names=("wll", "posm", "posc", "order", "flag"), ) # Use now better resolution to find the new solution # A single pass of discarding outliers should be enough coef = self.build_2d_solution(laser_lines) resid = self.calculate_residual(coef, laser_lines) laser_lines["flag"] = np.abs(resid) < self.threshold # laser_lines["flag"] = np.abs(resid) < resid.std() * 5 coef = self.build_2d_solution(laser_lines) new_wave = self.make_wave(coef) aic = self.calculate_AIC(laser_lines, coef) ngood = np.count_nonzero(laser_lines["flag"]) logger.info(f"Laser Frequency Comb solution based on {ngood} lines.") if self.plot: residual = wave - new_wave residual = residual.ravel() area = np.percentile(residual, (32, 50, 68)) area = area[0] - 5 * (area[1] - area[0]), area[0] + 5 * (area[2] - area[1]) plt.hist(residual, bins=100, range=area) plt.title("ThAr - LFC") plt.xlabel(r"$\Delta\lambda$ [Å]") plt.ylabel("N") plt.show() if self.plot: if lines is not None: self.plot_residuals( lines, coef, title= "GasLamp Line Residuals in the Laser Frequency Comb Solution", ) self.plot_residuals( laser_lines, coef, title="Laser Frequency Comb Peak Residuals in the LFC Solution", ) if self.plot: wave_img = wave plt.suptitle( "Difference between GasLamp Solution and Laser Frequency Comb solution\nEach plot shows one order." ) for i in range(len(new_wave)): plt.subplot(len(new_wave) // 4 + 1, 4, i + 1) plt.plot(wave_img[i] - new_wave[i]) plt.show() if self.plot: self.plot_results(new_wave, comb) return new_wave
def plot_prc_experimental(phi, delta_phi, model_name, stim_duration, stim_amp, signal=None, phase=None, scatter=True, fit=False): fig = plt.figure(figsize=(20, 10)) tmp = list(zip(phi, delta_phi)) tmp.sort(key=lambda a: a[0]) phi, delta_phi = zip(*tmp) delta_phi = np.array(delta_phi) / (stim_amp * stim_duration) p = Polynomial.fit(phi, delta_phi, deg=50) # delta_phi = savgol_filter(np.array(delta_phi), 11,5) phi = np.array(phi) if scatter == True: plt.scatter(np.array(phi), np.array(delta_phi), s=0.5, color='k', label="Integral Phase Change") else: plt.plot(np.array(phi), np.array(delta_phi), linewidth=3, color='k', label="Integral Phase Change") if fit == True: plt.plot((np.array(phi)), p(np.sort(np.array(phi))), ls='dashed', color='r', linewidth=2, label="Polynomial Fit") if not signal is None: plt.plot((np.array(phase)), np.pi * scale(signal), ls='-', color='b', linewidth=2, label="signal") plt.xlabel(r"$\phi$, rad", fontsize=24) plt.ylabel(r"$Z(\phi)$, rad", fontsize=24) tcks = [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi] lbls = ["0", r"$\frac{\pi}{2}$", r"$\pi$", r"$\frac{3\pi}{2}$", r"$2\pi$"] plt.xticks(ticks=tcks, labels=lbls, fontsize=20) tcks = [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi] lbls = [r"$-\pi$", r"$-\frac{\pi}{2}$", "0", r"$\frac{\pi}{2}$", r"$\pi$"] plt.yticks(ticks=tcks, labels=lbls, fontsize=20) plt.legend(fontsize=24) ttl = model_name.replace("_", " ") plt.title( f"PRC {ttl}, stim_duration = {stim_duration}, stim_amp = {stim_amp}", fontdict={"size": 24}) plt.grid(True) return fig
#print(f"Type: {type(image_copy)}, and dimensions: {image_copy.shape}") thresh_idx = (image[:, :, 0] < 200) | (image[:, :, 1] < 200) | (image[:, :, 2] < 200) image_copy[thresh_idx] = [0, 0, 0] plt.imshow(image_copy) #mpimg.imsave("image_color_selection.jpg",image_copy) #%% Region mask image_region = image_copy.copy() xsize = image_region.shape[0] ysize = image_region.shape[1] left_buttom = [xsize, 0] right_buttom = [xsize, ysize] apex = [4.2 * xsize / 7, ysize / 2] # Fit lines using Polynomial.fit left_fit = poly.fit((left_buttom[0], apex[0]), (left_buttom[1], apex[1]), 1, []) right_fit = poly.fit((right_buttom[0], apex[0]), (right_buttom[1], apex[1]), 1, []) #buttom_fit = poly.fit((left_buttom[0], right_buttom[0]), (left_buttom[1], right_buttom[1]), 0, []) X, Y = np.meshgrid( np.arange(0, xsize), np.arange(0, ysize), sparse=False, indexing='ij' ) # xy indexing by default means you should make it ij to get X = len(x)*len(y) otherwise you get X = len(y)*len(x) region_mask = (Y > left_fit(X)) & (Y < right_fit(X)) & (X < left_buttom[0]) image_region[~region_mask] = [50, 50, 250] plt.imshow(image_region) #mpimg.imsave("image_region_mask.jpg",image_region) #%% image_lines = image.copy() image_lines[~thresh_idx & region_mask] = [255, 0, 0] plt.imshow(image_lines)
def fit(x, y, deg, regularization=0): # order = polyfit1d(y, x, deg, regularization) order = Polynomial.fit(y, x, deg=deg, domain=[]).coef[::-1] return order
def fit(points): if type(points) == list: points = np.array(points) poly = P.fit(points[:, 0], points[:, 1], 1, domain=[-1, 1]) return Line.from_polynomial(poly)
def get_calibration_polynomial(calibration_table): u"""From calibration points, computes a best-fit quadratic equation.""" return Polynomial.fit( [x['reading'] for x in calibration_table], [y['diameter'] for y in calibration_table], 2)
import plotly.graph_objects as go import plotly.express as px #https://repository.upenn.edu/cgi/viewcontent.cgi?article=1000&context=scn_tooldata s1805 = [[500, 1.287], [1000, 0.914], [1500, 0.742], [2000, 0.644], [2500, 0.569], [3000, 0.524], [3500, 0.490], [4000, 0.459], [4500, 0.438], [5000, 0.420], [5500, 0.409], [6000, 0.399]] s1805 = pd.DataFrame(s1805, columns=['Speed', 'Thickness']) from scipy.optimize import curve_fit # %% def spin_asymptote(x, a, b, c, d): return (a / (((x * c) + b)**2)) # %% s1805_fit = Poly.fit(s1805['Speed'], s1805['Thickness'], 2) x = np.linspace(500, 6000) y = s1805_fit(x) f = px.scatter(s1805, 'Speed', 'Thickness') f.add_trace(go.Scatter(x=x, y=y)) f # %% popt, pcov = curve_fit(spin_asymptote, s1805['Speed'], s1805['Thickness']) # %% f.add_trace(go.Scatter(x=x, y=spin_asymptote(x, *popt))) # %%