def test_coerce_units(): model = models.Polynomial1D(1, c0=1, c1=2) with pytest.raises(u.UnitsError): model(u.Quantity(10, u.m)) with_input_units = model.coerce_units({"x": u.m}) result = with_input_units(u.Quantity(10, u.m)) assert np.isclose(result, 21.0) with_input_units_tuple = model.coerce_units((u.m, )) result = with_input_units_tuple(u.Quantity(10, u.m)) assert np.isclose(result, 21.0) with_return_units = model.coerce_units(return_units={"y": u.s}) result = with_return_units(10) assert np.isclose(result.value, 21.0) assert result.unit == u.s with_return_units_tuple = model.coerce_units(return_units=(u.s, )) result = with_return_units_tuple(10) assert np.isclose(result.value, 21.0) assert result.unit == u.s with_both = model.coerce_units({"x": u.m}, {"y": u.s}) result = with_both(u.Quantity(10, u.m)) assert np.isclose(result.value, 21.0) assert result.unit == u.s with pytest.raises(ValueError, match=r"input_units keys.*do not match model inputs"): model.coerce_units({"q": u.m}) with pytest.raises(ValueError, match=r"input_units length does not match n_inputs"): model.coerce_units((u.m, u.s)) model_with_existing_input_units = models.BlackBody() with pytest.raises( ValueError, match= r"Cannot specify input_units for model with existing input units"): model_with_existing_input_units.coerce_units({"x": u.m}) with pytest.raises(ValueError, match=r"return_units keys.*do not match model outputs"): model.coerce_units(return_units={"q": u.m}) with pytest.raises(ValueError, match=r"return_units length does not match n_outputs"): model.coerce_units(return_units=(u.m, u.s))
def test_subtract_overscan_model(ccd_data, transpose): # create the overscan region size = ccd_data.shape[0] oscan_region = (slice(None), slice(0, 10)) science_region = (slice(None), slice(10, None)) yscan, xscan = np.mgrid[0:size, 0:size] / 10.0 + 300.0 if transpose: oscan_region = oscan_region[::-1] science_region = science_region[::-1] scan = xscan overscan_axis = 0 else: overscan_axis = 1 scan = yscan original_mean = ccd_data.data[science_region].mean() ccd_data.data[oscan_region] = 0. # only want overscan in that region ccd_data.data = ccd_data.data + scan ccd_data = subtract_overscan(ccd_data, overscan=ccd_data[oscan_region], overscan_axis=overscan_axis, median=False, model=models.Polynomial1D(2)) np.testing.assert_almost_equal(ccd_data.data[science_region].mean(), original_mean) # Set the overscan_axis explicitly to None, and let the routine # figure it out. ccd_data = subtract_overscan(ccd_data, overscan=ccd_data[oscan_region], overscan_axis=None, median=False, model=models.Polynomial1D(2)) np.testing.assert_almost_equal(ccd_data.data[science_region].mean(), original_mean)
def _fit_background_model(image, x, j, bkglim, bkg_order): # extract pixel values along the column that are within # background limits: y, val, wht = _extract_colpix(image, x, j, bkglim) # find indices of "good" (finite) values: good = np.isfinite(val) npts = good.shape[0] if npts == 0 or not np.any(good): return (models.Polynomial1D(0), 0) # filter-out bad values: val = val[good] wht = wht[good] y = y[good] lsqfitter = fitting.LinearLSQFitter() bkg_model = lsqfitter(models.Polynomial1D(min(bkg_order, npts - 1)), y, val, weights=wht) return (bkg_model, npts)
def test_linear_fit_fixed_parameter(self): """ Tests fitting a polynomial model with a fixed parameter (issue #6135). """ init_model = models.Polynomial1D(degree=2, c1=1) init_model.c1.fixed = True x = np.arange(10) y = 2 + x + 0.5*x*x fitter = LinearLSQFitter() fitted_model = fitter(init_model, x, y) assert_allclose(fitted_model.parameters, [2., 1., 0.5], atol=1e-14)
def iterate_spatial_profile(P, DmS, V, f,\ smoothing=5, order=3, minpixels=50,\ sigma=4, nclip=2, verbose=True): poly0 = models.Polynomial1D(degree=order) fit_poly = fitting.LinearLSQFitter() Pnew = np.zeros(P.shape) for i,row in enumerate(P): weights = f**2/V[i] weights.mask = weights.mask | np.isnan(weights) srow = np.ma.MaskedArray(data=signal.medfilt(row, smoothing),\ mask=(np.isnan(signal.medfilt(row, smoothing)) | weights.mask)) xcoord = np.ma.MaskedArray(data=np.arange(0,len(row),1),\ mask=srow.mask) for iter in range(nclip+1): nrej_before = np.sum(srow.mask) fitted_poly = fit_poly(poly0,\ xcoord[~xcoord.mask], srow[~srow.mask],\ weights=weights[~weights.mask]) fit = np.array([fitted_poly(x) for x in xcoord]) resid = (DmS[i]-f*srow)**2 / V[i] newmask = (resid > sigma) weights.mask = weights.mask | newmask srow.mask = srow.mask | newmask xcoord.mask = xcoord.mask | newmask nrej_after = np.sum(srow.mask) if nrej_after > nrej_before: if verbose:\ info('Row {:3d}: Rejected {:d} pixels on clipping '+\ 'iteration {:d}'.format(\ i, nrej_after-nrej_before, iter)) ## Reject row if too few pixels are availabel for the fit if (srow.shape[0] - nrej_after) < minpixels: if verbose: warning('Row {:3d}: WARNING! Only {:d} pixels remain after '+\ 'clipping and masking'.format(\ i, srow.shape[0] - nrej_after)) fit = np.zeros(fit.shape) ## Set negative values to zero if np.sum((fit<0)) > 0 and verbose: info('Row {:3d}: Reset {:d} negative pixels in fit to 0'.format(\ i, np.sum((fit<0)))) fit[(fit < 0)] = 0 Pnew[i] = fit return Pnew
def test_LevMar_with_weights(self): """ Tests that issue #11581 has been solved. """ np.random.seed(42) norder = 2 fitter1 = LevMarLSQFitter() fitter2 = LinearLSQFitter() model = models.Polynomial1D(norder) npts = 10000 c = [2.0, -10.0, 7.0] tw = np.random.uniform(0.0, 10.0, npts) tx = np.random.uniform(0.0, 10.0, npts) ty = c[0] + c[1] * tx + c[2] * (tx ** 2) ty += np.random.normal(0.0, 1.5, npts) with pytest.warns(AstropyUserWarning, match=r'Model is linear in parameters'): tf1 = fitter1(model, tx, ty, weights=tw) tf2 = fitter2(model, tx, ty, weights=tw) assert_allclose(tf1.parameters, tf2.parameters, atol=10 ** (-16)) assert_allclose(tf1.parameters, c, rtol=10 ** (-2), atol=10 ** (-2)) model = models.Gaussian1D() fitter1(model, tx, ty, weights=tw) model = models.Polynomial2D(norder) nxpts = 100 nypts = 150 npts = nxpts * nypts c = [1.0, 4.0, 7.0, -8.0, -9.0, -3.0] tw = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) tx = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) ty = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) tz = c[0] + c[1] * tx + c[2] * (tx ** 2) + c[3] * ty + c[4] * (ty ** 2) + c[5] * tx * ty tz += np.random.normal(0.0, 1.5, npts).reshape(nxpts, nypts) with pytest.warns(AstropyUserWarning, match=r'Model is linear in parameters'): tf1 = fitter1(model, tx, ty, tz, weights=tw) tf2 = fitter2(model, tx, ty, tz, weights=tw) assert_allclose(tf1.parameters, tf2.parameters, atol=10 ** (-16)) assert_allclose(tf1.parameters, c, rtol=10 ** (-2), atol=10 ** (-2))
def test_correct_tilt(): """ Example provided by Catarina. """ xtilt = 0.35896975 ytilt = 0.1343827 #ztilt = None corrected_theta_x = 0.02942671219861111 corrected_theta_y = 0.00018649006677464447 #corrected_theta_z = -0.2523269848788889 disp = { 'gwa_tiltx': { 'temperatures': [39.58], 'tilt_model': astmodels.Polynomial1D(1, c0=3307.85402614, c1=-9182.87552123), 'unit': 'arcsec', 'zeroreadings': [0.35972327] }, 'gwa_tilty': { 'temperatures': [39.58], 'tilt_model': astmodels.Polynomial1D(1, c0=0.0, c1=0.0), 'unit': 'arcsec', 'zeroreadings': [0.0] }, 'instrument': 'NIRSPEC', 'reftype': 'DISPERSER', 'theta_x': 0.02942671219861111, 'theta_y': -0.0007745488724972222, #'theta_z': -0.2523269848788889, 'tilt_x': 0.0, 'tilt_y': -8.8 } disp_corrected = nirspec.correct_tilt(disp, xtilt, ytilt) #, ztilt) assert np.isclose(disp_corrected['theta_x'], corrected_theta_x) #assert(np.isclose(disp_corrected['theta_z'], corrected_theta_z)) assert np.isclose(disp_corrected['theta_y'], corrected_theta_y)
def extract_from_file(image_list, clim=None): all_traces = [] dispersion = 0 for image in image_list: print(image) ccd = read_fits(image) spatial, dispersion = ccd.data.shape print(spatial, dispersion) try: target = identify_targets(ccd=ccd) except AssertionError: print("Can't identify targets on data of OBSTYPE = " "{:s}".format(ccd.header['OBSTYPE'])) return print(target[0]) trace_model = models.Polynomial1D(degree=2) trace_fitter = fitting.LevMarLSQFitter() traces = trace(ccd=ccd, model=target[0], trace_model=trace_model, model_fitter=trace_fitter, sampling_step=5) all_traces.append([traces, image]) print(traces) extracted = extraction(ccd=ccd, target_trace=traces, spatial_profile=target[0], extraction_name='fractional') # print(traces) print(np.median(ccd.data), np.mean(ccd.data)) plt.title(image) plt.plot(traces(range(dispersion)), color='r') if clim is None: clim = (0.3 * np.median(ccd.data), 0.3 * np.mean(ccd.data)) plt.imshow(ccd.data, clim=clim) plt.show() plt.plot(extracted.data) plt.show() for single_trace, image in all_traces: plt.plot(single_trace(range(dispersion)), label=image) plt.legend(loc='best') plt.title("Target Traces") plt.xlabel("Dispersion Axis") plt.ylabel("Spatial Axis") plt.show()
def test_1d_with_weights_with_sigma_clip(self): """smoke test for #7020 - fails without fitting.py patch because weights does not propagate""" model = models.Polynomial1D(0) fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip, niter=3, sigma=3.) fit, filtered = fitter(model, self.x1d, self.z1d, weights=self.weights1d) assert (fit.parameters[0] > 10**(-2)) # weights pulled it > 0 assert ( fit.parameters[0] < 1.0 ) # outliers didn't pull it out of [-1:1] because they had been removed
def test_linear_fit_fixed_parameter(self): """ Tests fitting a polynomial model with a fixed parameter (issue #6135). """ init_model = models.Polynomial1D(degree=2, c1=1) init_model.c1.fixed = True x = np.arange(10) y = 2 + x + 0.5 * x * x fitter = LinearLSQFitter() with pytest.warns(AstropyUserWarning, match=r'The fit may be poorly conditioned'): fitted_model = fitter(init_model, x, y) assert_allclose(fitted_model.parameters, [2., 1., 0.5], atol=1e-14)
def test_backward_transform(): """ Test backward transform raises an error when an analytical inverse is not available. """ # Test that an error is raised when one of the models has not inverse. poly = models.Polynomial1D(1, c0=4) w = wcs.WCS(forward_transform=poly & models.Scale(2), output_frame='sky') with pytest.raises(NotImplementedError): w.backward_transform # test backward transform poly.inverse = models.Shift(-4) w = wcs.WCS(forward_transform=poly & models.Scale(2), output_frame='sky') assert_allclose(w.backward_transform(1, 2), (-3, 1))
def align_spectrum(self, xspec=None, yspec=None): """ Try to compute alignment of the reference image using cross correlation """ from astropy.modeling import models, fitting clean_cutout = self.cutout_sci * 1. clean_cutout[self.cutout_dq > 0] = 0 #max = np.percentile(clean_cutout[clean_cutout != 0], clip_percentile) #clean_cutout[(clean_cutout > max) | (clean_cutout < -3*self.cutout_err)] = 0 clean_cutout[(clean_cutout < -3 * self.cutout_err) | ~np.isfinite(self.cutout_err)] = 0. self.compute_model(self.thumb, xspec=xspec, yspec=yspec) ### Cross correlation cc = nd.correlate(self.model / self.model.sum(), clean_cutout / clean_cutout.sum()) sh = cc.shape shx = sh[1] / 2. shy = sh[0] / 2. yp, xp = np.indices(cc.shape) shx = sh[1] / 2 shy = sh[0] / 2 xp = (xp - shx) yp = (yp - shy) cc[:, :shx - shy] = 0 cc[:, shx + shy:] = 0 ccy = cc.sum(axis=1) ccx = cc.sum(axis=0) #fit = fitting.LevMarLSQFitter() #mod = models.Polynomial1D(degree=6) #(1, 0, 1) fit = fitting.LinearLSQFitter() ix = np.argmax(ccx) p2 = models.Polynomial1D(degree=2) px = fit(p2, xp[0, ix - 1:ix + 2], ccx[ix - 1:ix + 2] / ccx.max()) dx = -px.parameters[1] / (2 * px.parameters[2]) iy = np.argmax(ccy) py = fit(p2, yp[iy - 1:iy + 2, 0], ccy[iy - 1:iy + 2] / ccy.max()) dy = -py.parameters[1] / (2 * py.parameters[2]) return dx, dy, ccx, ccy
def test_linear_fit_model_set(self): """Tests fitting multiple models simultaneously.""" init_model = models.Polynomial1D(degree=2, c0=[1, 1], n_models=2) x = np.arange(10) y_expected = init_model(x, model_set_axis=False) assert y_expected.shape == (2, 10) # Add a bit of random noise with NumpyRNGContext(_RANDOM_SEED): y = y_expected + np.random.normal(0, 0.01, size=y_expected.shape) fitter = LinearLSQFitter() fitted_model = fitter(init_model, x, y) assert_allclose(fitted_model(x, model_set_axis=False), y_expected, rtol=1e-1)
def test_coordinate_all_mismatches(): # Test that when no stars match stuff goes badly. n_stars = 100 true_relationship = models.Polynomial1D(1, c0=0.5, c1=0.75) instrumental, catalog_table = generate_tables(n_stars, true_relationship) # Mess up the coordinates of half of the stars so that they don't match. catalog_table['RAJ2000'] = catalog_table['RAJ2000'] + 0.5 * u.degree calib_mags, stars_with_match, transform = \ transform_magnitudes(instrumental, catalog_table, catalog_table[:50], order=2) assert not any(stars_with_match)
def test_linear_fit_model_set_fixed_parameter(self): """ Tests fitting a polynomial model set with a fixed parameter (#6135). """ init_model = models.Polynomial1D(degree=2, c1=[1, -2], n_models=2) init_model.c1.fixed = True x = np.arange(10) yy = np.array([2 + x + 0.5*x*x, -2*x]) fitter = LinearLSQFitter() fitted_model = fitter(init_model, x, yy) assert_allclose(fitted_model.c0, [2., 0.], atol=1e-14) assert_allclose(fitted_model.c1, [1., -2.], atol=1e-14) assert_allclose(fitted_model.c2, [0.5, 0.], atol=1e-14)
def test_nset_domain(self): """ Test model set with negative model_set_axis. In this case model_set_axis=-1 is identical to model_set_axis=1. """ xx = np.array([self.x1, self.x1]).T xx[0, 0] = 100 xx[1, 0] = 100 xx[2, 0] = 99 p1 = models.Polynomial1D(5, c0=[1, 2], c1=[3, 4], n_models=2) yy = p1(xx, model_set_axis=-1) assert_allclose(xx.shape, yy.shape) yy1 = p1(xx, model_set_axis=1) assert_allclose(yy, yy1)
def fit_poly_n(data, deg=1, sigma_factor=0): """Fit a Polynomial 1D model to the data. Parameters ---------- data: float array should be a 1d or 2d array deg: int The degree of polynomial to fit sigma_factor: float (optional) If sigma_factor > 0 then clipping will be performed on the data during the model fit Returns ------- The the polynomial fit model for the function """ if len(data) < deg + 1: raise ValueError("fit_poly_n: Need more data for fit") # define the model poly = models.Polynomial1D(deg) # set the axis range for fitting ax = np.arange(len(data)) # define the fitter fitter = fitting.LinearLSQFitter() if sigma_factor > 0: fit = fitting.FittingWithOutlierRemoval(fitter, sigma_clip, sigma=sigma_factor, niter=3) else: fit = fitter try: result = fit(poly, ax, data) except ValueError: result = None if sigma_factor > 0: result = result[1] return result
def fit_poly_n(data, x=None, y=None, deg=1): """Fit a Polynomial 1D model to the data.""" # define the model poly = models.Polynomial1D(deg) # set the axis range for fitting ax = np.arange(len(data)) # define the fitter fit = fitting.LinearLSQFitter() try: result = fit(poly, ax, data) except: ValueError result = None return result
def test_coordinates_composite(): spec = cf.SpectralFrame(name='wavelength', unit=(u.micron, ), axes_order=(2, ), axes_names=('lambda', )) icrs = cf.CelestialFrame(reference_frame=coord.ICRS(), axes_order=(0, 1)) frame = cf.CompositeFrame([icrs, spec]) transform = models.Mapping( [0, 0, 1]) | models.Identity(2) & models.Polynomial1D(1, c0=.2, c1=.3) w = wcs.WCS(forward_transform=transform, output_frame=frame, input_frame=det) x = np.arange(3) result = getattr(w, w.output_frame).coordinates(x, x) assert_allclose(result[0].ra.value, w(x, x)[0]) assert_allclose(result[0].ra.value, w(x, x)[1]) assert_allclose(result[1].value, w(x, x)[2])
def gwa_to_ymsa(msa2gwa_model): """ Determine the linear relation d_y(beta_in) for the aperture on the detector. Parameters ---------- msa2gwa_model : `astropy.modeling.core.Model` The transform from the MSA to the GWA. """ dy = np.linspace(-.55, .55, 1000) dx = np.zeros(dy.shape) cosin_grating_k = msa2gwa_model(dx, dy) fitter = fitting.LinearLSQFitter() model = models.Polynomial1D(1) poly1d_model = fitter(model, cosin_grating_k[1], dy) poly_model = poly1d_model.rename('interpolation') return poly_model
def oscan_trim_file(fname, datahdus=0): hdulist = fits.open(fname) nhdus = len(hdulist) if nhdus > 1: istart = 1 else: istart = 0 # loop from first-data to last HDU, unless datahdus is set hduindexes = list(range(nhdus))[istart:] if datahdus != 0: hduindexes = datahdus for i in hduindexes: hdulist = fits.open(fname) data1 = ccdproc.CCDData(hdulist[i].data, unit="adu") data1.header = hdulist[i].header # What happens if file is already overscan-subtracted? # We should probably default to using a model if modeling: oscan1 = ccdproc.subtract_overscan( data1, fits_section=data1.header['BIASSEC'], add_keyword={ 'overscan': True, 'calstat': 'O' }, model=models.Polynomial1D(1)) else: oscan1 = ccdproc.subtract_overscan( data1, fits_section=data1.header['BIASSEC'], add_keyword={ 'overscan': True, 'calstat': 'O' }, model=None) trim1 = ccdproc.trim_image(oscan1, fits_section=oscan1.header['TRIMSEC'], add_keyword={ 'trimmed': True, 'calstat': 'OT' }) fits.update(fname, trim1.data, header=trim1.header, ext=i) hdulist.close() mylog("Overscan and trim {0}".format(fname)) return
def test_set_constraints(): g = models.Gaussian1D() p = models.Polynomial1D(1) # Set bounds before model combination g.stddev.bounds = (0, 3) m = g + p assert m.bounds == { 'amplitude_0': (None, None), 'mean_0': (None, None), 'stddev_0': (0.0, 3.0), 'c0_1': (None, None), 'c1_1': (None, None) } # Set bounds on the compound model m.stddev_0.bounds = (1, 3) assert m.bounds == { 'amplitude_0': (None, None), 'mean_0': (None, None), 'stddev_0': (1.0, 3.0), 'c0_1': (None, None), 'c1_1': (None, None) } # Set the bounds of a Parameter directly in the bounds dict m.bounds['stddev_0'] = (4, 5) assert m.bounds == { 'amplitude_0': (None, None), 'mean_0': (None, None), 'stddev_0': (4, 5), 'c0_1': (None, None), 'c1_1': (None, None) } # Set the bounds of a Parameter on the child model bounds dict g.bounds['stddev'] = (1, 5) m = g + p assert m.bounds == { 'amplitude_0': (None, None), 'mean_0': (None, None), 'stddev_0': (1, 5), 'c0_1': (None, None), 'c1_1': (None, None) }
def test_linear_fit_model_set_fixed_parameter(self): """ Tests fitting a polynomial model set with a fixed parameter (#6135). """ init_model = models.Polynomial1D(degree=2, c1=[1, -2], n_models=2) init_model.c1.fixed = True x = np.arange(10) yy = np.array([2 + x + 0.5 * x * x, -2 * x]) fitter = LinearLSQFitter() with pytest.warns(AstropyUserWarning, match=r'The fit may be poorly conditioned'): fitted_model = fitter(init_model, x, yy) assert_allclose(fitted_model.c0, [2., 0.], atol=1e-14) assert_allclose(fitted_model.c1, [1., -2.], atol=1e-14) assert_allclose(fitted_model.c2, [0.5, 0.], atol=1e-14)
def getmod(self): """ Return model for current attributes """ if self.type == 'poly': mod = models.Polynomial1D(degree=self.degree) elif self.type == 'chebyshev': mod = models.Chebyshev1D(degree=self.degree) elif self.type == 'chebyshev2D': sz = self.spectrum.data.shape mod = models.Chebyshev2D(x_degree=self.degree, y_degree=self.ydegree, x_domain=[0, sz[1]], y_domain=[0, sz[0]]) else: raise ValueError('unknown fitting type: ' + self.type) return return mod
def test_1d_set_fitting_with_outlier_removal(): """Test model set fitting with outlier removal (issue #6819)""" poly_set = models.Polynomial1D(2, n_models=2) fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip, sigma=2.5, niter=3, cenfunc=np.ma.mean, stdfunc=np.ma.std) x = np.arange(10) y = np.array([2.5*x - 4, 2*x*x + x + 10]) y[1, 5] = -1000 # outlier poly_set, filt_y = fitter(poly_set, x, y) assert_allclose(poly_set.c0, [-4., 10.], atol=1e-14) assert_allclose(poly_set.c1, [2.5, 1.], atol=1e-14) assert_allclose(poly_set.c2, [0., 2.], atol=1e-14)
def test_coordinate_mismatches(): # Test that stars without close coordinate matches end up # marked appropriately. n_stars = 100 true_relationship = models.Polynomial1D(1, c0=0.5, c1=0.75) instrumental, catalog_table = generate_tables(n_stars, true_relationship) # Mess up the coordinates of half of the stars so that they don't match. catalog_table['RAJ2000'][50:] = (catalog_table['RAJ2000'][50:] + 0.5 * u.degree) calib_mags, stars_with_match, transform = \ transform_magnitudes(instrumental, catalog_table, catalog_table[:50], order=2) assert all(stars_with_match[:50]) assert all(~stars_with_match[50:])
def fit_moffat_1d(data, gamma=2., alpha=1.): """Fit a 1D moffat profile to the data and return the fit.""" # data is assumed to already be chunked to a reasonable size ldata = len(data) x = np.arange(ldata) # Fit model to data fit = fitting.LevMarLSQFitter() # Moffat1D + constant model = (models.Moffat1D( amplitude=max(data), x_0=ldata / 2, gamma=gamma, alpha=alpha) + models.Polynomial1D(c0=data.min(), degree=0)) with warnings.catch_warnings(): # Ignore model linearity warning from the fitter warnings.simplefilter('ignore') results = fit(model, x, data) # previous yield amp, ycenter, xcenter, sigma, offset return results
def simple_normalization(spectrum): """Simple normalization of pheonix spectra.""" from astropy.modeling import models, fitting p1 = models.Polynomial1D(1) p1.c0 = spectrum.flux[0] p1.c1 = ((spectrum.flux[-1] - spectrum.flux[0]) / (spectrum.xaxis[-1] - spectrum.xaxis[0])) # print("Printing p1", p1) pfit = fitting.LinearLSQFitter() new_model = pfit(p1, spectrum.xaxis, spectrum.flux) # print(new_model) fit_norm = new_model(spectrum.xaxis) norm_spectrum = spectrum / fit_norm flux = norm_spectrum.flux # Normalization (use first 50 points below 1.2 as continuum) maxes = flux[(flux < 1.2)].argsort()[-50:][::-1] norm_spectrum = norm_spectrum / np.median(flux[maxes]) return norm_spectrum
def test_linear_fit_model_set_masked_values(self): """ Tests model set fitting with masked value(s) (#4824, #6819). """ # NB. For single models, there is an equivalent doctest. init_model = models.Polynomial1D(degree=1, n_models=2) x = np.arange(10) y = np.ma.masked_array([2*x+1, x-2], mask=np.zeros_like([x, x])) y[0, 7] = 100. # throw off fit coefficients if unmasked y.mask[0, 7] = True y[1, 1:3] = -100. y.mask[1, 1:3] = True fitter = LinearLSQFitter() fitted_model = fitter(init_model, x, y) assert_allclose(fitted_model.c0, [1., -2.], atol=1e-14) assert_allclose(fitted_model.c1, [2., 1.], atol=1e-14)
def polynomial_from_coeffs_matrix(coefficients, name=None): n_dim = coefficients.ndim if n_dim == 1: model = models.Polynomial1D(coefficients.size - 1, name=name) model.parameters = coefficients elif n_dim == 2: shape = coefficients.shape degree = shape[0] - 1 if shape[0] != shape[1]: raise TypeError("Coefficients must be an (n+1, n+1) matrix") coeffs = {} for i in range(shape[0]): for j in range(shape[0]): if i + j < degree + 1: cname = 'c' + str(i) + '_' + str(j) coeffs[cname] = coefficients[i, j] model = models.Polynomial2D(degree, name=name, **coeffs) return model