Exemple #1
0
def test_empirical_prior():
    # set up some emprical prior
    x = np.linspace(0, 40, 100) / 180 * np.pi
    g1 = Gaussian1D(amplitude=.2, mean=21 / 180 * np.pi, stddev=0.05)
    g1.bounding_box.amplitude = (0, 1.)
    g1.bounding_box.mean = (0, np.pi / 2)
    g2 = Gaussian1D(amplitude=0.05, mean=23 / 180 * np.pi, stddev=.05)
    g2.bounding_box.amplitude = (.0, 1.)
    g2.bounding_box.mean = (0, np.pi / 2)

    # g is astropy CompoundModel
    g = g1 + g2

    # integration works
    assert g(21 / 180 * np.pi) == pytest.approx(0.239186373422815)
    assert empirical_prior(21 / 180 * np.pi, g) == np.log(0.239186373422815)

    # 0. is included
    assert g(0.) < 1e-12
    assert g(0.) > 0.
    assert empirical_prior(0., g) == np.log(g(0.))

    # bounding box works
    assert g(50. / 180. * np.pi) < 1e-12
    assert g(50. / 180. * np.pi) > 0.
    assert empirical_prior(50. / 180. * np.pi,
                           g) == np.log(g(50. / 180. * np.pi))

    # outside of allowed inclination of pi/2
    assert g(np.pi * .6) == pytest.approx(0.)
    assert ~np.isfinite(empirical_prior(1.1 * np.pi, g))

    # nan returns nan
    assert np.isnan(g(np.nan))
    assert np.isnan(empirical_prior(np.nan, g))

    # cannot pass nan or float as g
    with pytest.raises(TypeError) as e:
        empirical_prior(0., np.nan)

    with pytest.raises(TypeError) as e:
        empirical_prior(0., 4.)

    # g will accept a function like sqrt though
    assert empirical_prior(1.2, np.sqrt) == pytest.approx(0.09116077839697724)
Exemple #2
0
def test_inherit_constraints():
    """
    Various tests for copying of constraint values between compound models and
    their members.

    Regression test for https://github.com/astropy/astropy/issues/3481
    """
    model = (Gaussian1D(bounds={'stddev': (0, 0.3)}, fixed={'mean': True}) +
             Gaussian1D(fixed={'mean': True}))

    # Lots of assertions in this test as there are multiple interfaces to
    # parameter constraints

    assert 'stddev_0' in model.bounds
    assert model.bounds['stddev_0'] == (0, 0.3)
    assert model.stddev_0.bounds == (0, 0.3)
    assert 'mean_0' in model.fixed
    assert model.fixed['mean_0'] is True
    assert model.mean_0.fixed is True
    assert 'mean_1' in model.fixed
    assert model.fixed['mean_1'] is True
    assert model.mean_1.fixed is True

    assert model.stddev_0 is model[0].stddev
    # Great, all the constraints were inherited properly
    # Now what about if we update them through the sub-models?
    model.stddev_0.bounds = (0, 0.4)
    assert model[0].stddev.bounds == (0, 0.4)
    assert model[0].bounds['stddev'] == (0, 0.4)

    model.stddev_0.bounds = (0.1, 0.5)
    assert model[0].stddev.bounds == (0.1, 0.5)
    assert model[0].bounds['stddev'] == (0.1, 0.5)

    model[1].mean.fixed = False
    assert model.mean_1.fixed is False
    assert model[1].mean.fixed is False

    # Now turn off syncing of constraints
    assert model.bounds['stddev_0'] == (0.1, 0.5)
    model.sync_constraints = False
    model[0].stddev.bounds = (0, 0.2)
    assert model.bounds['stddev_0'] == (0.1, 0.5)
    model.sync_constraints = True
    assert model.bounds['stddev_0'] == (0, 0.2)
Exemple #3
0
def test_expression_formatting():
    """
    Test that the expression strings from compound models are formatted
    correctly.
    """

    # For the purposes of this test it doesn't matter a great deal what
    # model(s) are used in the expression, I don't think
    G = Gaussian1D(1, 1, 1)
    G2 = Gaussian2D(1, 2, 3, 4, 5, 6)

    M = G + G
    assert M._format_expression() == '[0] + [1]'

    M = G + G + G
    assert M._format_expression() == '[0] + [1] + [2]'

    M = G + G * G
    assert M._format_expression() == '[0] + [1] * [2]'

    M = G * G + G
    assert M._format_expression() == '[0] * [1] + [2]'

    M = G + G * G + G
    assert M._format_expression() == '[0] + [1] * [2] + [3]'

    M = (G + G) * (G + G)
    assert M._format_expression() == '([0] + [1]) * ([2] + [3])'

    # This example uses parentheses in the expression, but those won't be
    # preserved in the expression formatting since they technically aren't
    # necessary, and there's no way to know that they were originally
    # parenthesized (short of some deep, and probably not worthwhile
    # introspection)
    M = (G * G) + (G * G)
    assert M._format_expression() == '[0] * [1] + [2] * [3]'

    M = G**G
    assert M._format_expression() == '[0] ** [1]'

    M = G + G**G
    assert M._format_expression() == '[0] + [1] ** [2]'

    M = (G + G)**G
    assert M._format_expression() == '([0] + [1]) ** [2]'

    M = G + G | G
    assert M._format_expression() == '[0] + [1] | [2]'

    M = G + (G | G)
    assert M._format_expression() == '[0] + ([1] | [2])'

    M = G & G | G2
    assert M._format_expression() == '[0] & [1] | [2]'

    M = G & (G | G)
    assert M._format_expression() == '[0] & ([1] | [2])'
Exemple #4
0
def test_gaussian1d_n_models():
    g = Gaussian1D(
        amplitude=[1 * u.J, 2. * u.J],
        mean=[1 * u.m, 5000 * u.AA],
        stddev=[0.1 * u.m, 100 * u.AA],
        n_models=2)
    assert_quantity_allclose(g(1.01 * u.m), [0.99501248, 0.] * u.J)
    assert_quantity_allclose(
        g(u.Quantity([1.01 * u.m, 5010 * u.AA])), [0.99501248, 1.990025] * u.J)
Exemple #5
0
def fit_data_with_gaussian(x_values, y_values, amplitude=1., mean=0, stddev=1.):
    g_init = Gaussian1D(amplitude, mean, stddev)
    lpost = PSDLogLikelihood(x_values, y_values, g_init)
    parest = ParameterEstimation()
    res = parest.fit(lpost, [amplitude, mean, stddev], neg=True)
    opt_amplitude = res.p_opt[0]
    opt_mean = res.p_opt[1]
    opt_stddev = res.p_opt[2]
    return opt_amplitude, opt_mean, opt_stddev
def _init_knotmodel(amp_init=0.01, v_init=-60.0):
    """Initialize model for knot: a single Gaussian"""
    bounds = {
        'amplitude': [0, None],
        'stddev': [KNOT_WMIN, KNOT_WMAX],
        'mean': [KNOT_VMIN, KNOT_VMAX]
    }
    knotmodel = Gaussian1D(amp_init, v_init, 5.0, bounds=bounds)
    return knotmodel
Exemple #7
0
    def update(self):
        HaB_gauss = Gaussian1D(amplitude=self.HaB_amp,
                               stddev=vel2wl(6562.8, self.HaB_vel) / 2.35,
                               mean=self.Ha_mean +
                               vel2wl(self.Ha_mean, self.Ha_shift))
        HaB_fl = HaB_gauss(self.wl)
        self.HaB_spec.set_ydata(gauss_fl)

        HaN_gauss = Gaussian1D(
            amplitude=self.HaN_gauss,
            sttdev=vel2wl(self.Ha_mean, self.HaN_vel) / 2.35,
            mean=self.Ha_mean + vel2wl(self.Ha_mean, self.Ha_shift))
        HaN_fl = HaN_gauss(self.wl)
        self.HaN_spec.set_ydata(HaN_fl)

        comp = HaN_fl + HaB_fl
        self.comp_spec.set_ydata(comp)

        self.fig.canvas.draw()
Exemple #8
0
def test_from_list_list():
    g1 = Gaussian1D(1, 4.6, 0.2)
    g2 = Gaussian1D(2.5, 5.5, 0.1)
    g3 = Gaussian1D(-1.7, 8.2, 0.1)

    x = np.linspace(0, 10, 200)
    y = g1(x) + g2(x) + g3(x)

    spectrum = Spectrum1D(flux=y * u.Jy, spectral_axis=x * u.um)

    lines = find_lines_derivative(spectrum, flux_threshold=0.01)

    spec_reg = SpectralRegion.from_line_list(lines)
    expected = [(4.072864321608041 * u.um, 5.072864321608041 * u.um),
                (4.977386934673367 * u.um, 5.977386934673367 * u.um),
                (7.690954773869347 * u.um, 8.690954773869347 * u.um)]

    for i, reg in enumerate(expected):
        assert_quantity_allclose(reg, (spec_reg[i].lower, spec_reg[i].upper))
Exemple #9
0
def test_parameter_add_units():
    """
    On the other hand, if starting from a parameter with no units, we should be
    able to add units since this is unambiguous.
    """

    g = Gaussian1D(1, 3, 0.1)

    g.amplitude = 2 * u.Jy
    assert_quantity_allclose(g.amplitude, 2 * u.Jy)
Exemple #10
0
 def test_model_1D_kernel(self):
     """
     Check Model1DKernel against Gaussian1Dkernel
     """
     stddev = 5.
     gauss = Gaussian1D(1. / np.sqrt(2 * np.pi * stddev**2), 0, stddev)
     model_gauss_kernel = Model1DKernel(gauss, x_size=21)
     gauss_kernel = Gaussian1DKernel(stddev, x_size=21)
     assert_almost_equal(model_gauss_kernel.array, gauss_kernel.array,
                         decimal=12)
Exemple #11
0
def test_quantity_call():
    """
    Test that if constructed with Quanties models must be called with quantities.
    """
    g = Gaussian1D(mean=3 * u.m, stddev=3 * u.cm, amplitude=3 * u.Jy)

    g(10 * u.m)

    with pytest.raises(u.UnitsError):
        g(10)
Exemple #12
0
def test_compound_evaluate_named_param(expr):
    """
    Tests that compound evaluate function produces the same
    result as the models with the operator applied
    """
    x = np.linspace(-5, 5, 10)
    p1 = np.array([1, 0, 0.2])
    p2 = np.array([3, 0.5, 0.5])

    model1 = Gaussian1D(2, 1, 5)
    model2 = Gaussian1D(2, 1, 5)
    compound = expr(model1, model2)

    assert_array_equal(
        compound.evaluate(
            x, *p2, amplitude_0=p1[0], mean_0=p1[1], stddev_0=p1[2]
        ),
        expr(model1.evaluate(x, *p1), model2.evaluate(x, *p2)),
    )
Exemple #13
0
def test_PoissonLikelihoodFitter():
    model = Gaussian1D(amplitude=1000, mean=2, stddev=3)
    x = np.arange(-10, 20, 0.1)
    dx = 0.1 * np.ones_like(x)
    np.random.seed(0)
    y = np.random.poisson(dx * model(x))

    fitter = PoissonLikelihoodFitter()
    model = fitter(model, x, y, dx)
    expected = [995.29239606, 1.99019548, 3.00869128]
    assert_allclose(model.parameters, expected, rtol=1e-3)
Exemple #14
0
def test_inherit_constraints():
    """
    Various tests for copying of constraint values between compound models and
    their members.

    Regression test for https://github.com/astropy/astropy/issues/3481
    """
    model = (Gaussian1D(bounds={'stddev': (0, 0.3)}, fixed={'mean': True}) +
             Gaussian1D(fixed={'mean': True}))
    # We have to copy the model before modifying it, otherwise the test fails
    # if it is run twice in a row, because the state of the model instance
    # would be preserved from one run to the next.
    model = deepcopy(model)
    model.map_parameters()
    # Lots of assertions in this test as there are multiple interfaces to
    # parameter constraints

    assert 'stddev_0' in model.bounds
    assert model.bounds['stddev_0'] == (0, 0.3)
    assert model.stddev_0.bounds == (0, 0.3)
    assert 'mean_0' in model.fixed
    assert model.fixed['mean_0'] is True
    assert model.mean_0.fixed is True
    assert 'mean_1' in model.fixed
    assert model.fixed['mean_1'] is True
    assert model.mean_1.fixed is True

    assert model.stddev_0 is model[0].stddev
    # Great, all the constraints were inherited properly
    # Now what about if we update them through the sub-models?
    model.stddev_0.bounds = (0, 0.4)
    assert model[0].stddev.bounds == (0, 0.4)
    assert model[0].bounds['stddev'] == (0, 0.4)

    model.stddev_0.bounds = (0.1, 0.5)
    assert model[0].stddev.bounds == (0.1, 0.5)
    assert model[0].bounds['stddev'] == (0.1, 0.5)

    model[1].mean.fixed = False
    assert model.mean_1.fixed is False
    assert model[1].mean.fixed is False
Exemple #15
0
def test_indexing_on_instance():
    """Test indexing on compound model instances."""

    m = Gaussian1D(1, 0, 0.1) + Const1D(2)
    assert isinstance(m[0], Gaussian1D)
    assert isinstance(m[1], Const1D)
    # assert isinstance(m['Gaussian1D'], Gaussian1D)
    # assert isinstance(m['Const1D'], Const1D)

    # Test parameter equivalence
    assert m[0].amplitude == 1
    assert m[0].mean == 0
    assert m[0].stddev == 0.1
    assert m[1].amplitude == 2

    # Similar couple of tests, but now where the compound model was created
    # from model instances
    g = Gaussian1D(1, 2, 3, name='g')
    p = Polynomial1D(2, name='p')
    m = g + p
    assert m[0].name == 'g'
    assert m[1].name == 'p'
    assert m['g'].name == 'g'
    assert m['p'].name == 'p'

    # Test negative indexing
    assert isinstance(m[-1], Polynomial1D)
    assert isinstance(m[-2], Gaussian1D)

    with pytest.raises(IndexError):
        m[42]

    with pytest.raises(IndexError):
        m['foobar']

    # Test string slicing
    A = Const1D(1.1, name='A')
    B = Const1D(2.1, name='B')
    C = Const1D(3.1, name='C')
    M = A + B * C
    assert_allclose(M['B':'C'](1), 6.510000000000001)
def test_n_submodels():
    """
    Test that CompoundModel.n_submodels properly returns the number
    of components.
    """
    g2 = Gaussian1D() + Gaussian1D()
    assert g2.n_submodels() == 2

    g3 = g2 + Gaussian1D()
    assert g3.n_submodels() == 3

    g5 = g3 | g2
    assert g5.n_submodels() == 5

    g7 = g5 / g2
    assert g7.n_submodels() == 7

    # make sure it works as class method
    p = Polynomial1D + Polynomial1D

    assert p.n_submodels() == 2
Exemple #17
0
def test_parameter_quantity():
    """
    Basic tests for initializing general models (that do not require units)
    with parameters that have units attached.
    """
    g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
    assert g.amplitude.value == 1.0
    assert g.amplitude.unit is u.J
    assert g.mean.value == 1.0
    assert g.mean.unit is u.m
    assert g.stddev.value == 0.1
    assert g.stddev.unit is u.m
Exemple #18
0
def test_fitting_incompatible_units():
    """
    Raise an error if the data and model have incompatible units
    """

    g_init = Gaussian1D(amplitude=1. * u.Jy, mean=3 * u.m, stddev=2 * u.cm)
    fit_g = fitting.LevMarLSQFitter()

    with pytest.raises(UnitsError) as exc:
        fit_g(g_init, [1, 2, 3] * u.Hz, [4, 5, 6] * u.Jy)
    assert exc.value.args[0] == (
        "'Hz' (frequency) and 'm' (length) are not convertible")
def test_indexing_on_instance():
    """Test indexing on compound model instances."""

    M = Gaussian1D + Const1D
    m = M(1, 0, 0.1, 2)
    assert isinstance(m[0], Gaussian1D)
    assert isinstance(m[1], Const1D)
    assert isinstance(m['Gaussian1D'], Gaussian1D)
    assert isinstance(m['Const1D'], Const1D)

    # Test parameter equivalence
    assert m[0].amplitude == 1 == m.amplitude_0
    assert m[0].mean == 0 == m.mean_0
    assert m[0].stddev == 0.1 == m.stddev_0
    assert m[1].amplitude == 2 == m.amplitude_1

    # Test that parameter value updates are symmetric between the compound
    # model and the submodel returned by indexing
    const = m[1]
    m.amplitude_1 = 42
    assert const.amplitude == 42
    const.amplitude = 137
    assert m.amplitude_1 == 137

    # Similar couple of tests, but now where the compound model was created
    # from model instances
    g = Gaussian1D(1, 2, 3, name='g')
    p = Polynomial1D(2, name='p')
    m = g + p
    assert m[0].name == 'g'
    assert m[1].name == 'p'
    assert m['g'].name == 'g'
    assert m['p'].name == 'p'

    poly = m[1]
    m.c0_1 = 12345
    assert poly.c0 == 12345
    poly.c1 = 6789
    assert m.c1_1 == 6789

    # Ensure this did *not* modify the original models we used as templates
    assert p.c0 == 0
    assert p.c1 == 0

    # Test negative indexing
    assert isinstance(m[-1], Polynomial1D)
    assert isinstance(m[-2], Gaussian1D)

    with pytest.raises(IndexError):
        m[42]

    with pytest.raises(IndexError):
        m['foobar']
Exemple #20
0
def gauss_removal(img, mask, linspace, where='bkg'):
    """
    An additional step to remove cosmic rays. This fits a Gaussian to
    the background (or a skewed Gaussian to the orders) and masks data
    points which are above a certain sigma.   

    Parameters
    ----------
    img : np.ndarray
       Single exposure image.
    mask : np.ndarray       
       An approximate mask for the orders.
    linspace : array               
       Sets the lower and upper bin bounds for the
       pixel values. Should be of length = 2.    
    where : str, optional                        
       Sets where the mask is covering. Default is `bkg`.
       Other option is `order`.  

    Returns    
    -------    
    img : np.ndarray
       The same input image, now masked for newly identified
       outliers.   
    """
    n, bins = np.histogram((img * mask).flatten(),
                           bins=np.linspace(linspace[0], linspace[1], 100))
    bincenters = (bins[1:] + bins[:-1]) / 2

    if where == 'bkg':
        g = Gaussian1D(mean=0, amplitude=100, stddev=10)
        rmv = np.where(np.abs(bincenters) <= 5)[0]
    elif where == 'order':
        GaussianSkewed = custom_model(skewed_gaussian)
        g = GaussianSkewed(eta=0, omega=20, alpha=4, scale=100)
        rmv = np.where(np.abs(bincenters) == 0)[0]

    # finds bin centers and removes bincenter = 0 (because this bin
    #   seems to be enormous and we don't want to skew the best-fit
    bincenters, n = np.delete(bincenters, rmv), np.delete(n, rmv)

    # fit the model to the histogram bins
    fitter = LevMarLSQFitter()
    gfit = fitter(g, bincenters, n)

    if where == 'bkg':
        xcr, ycr = np.where(np.abs(img * mask) >= gfit.mean + 2 * gfit.stddev)
    elif where == 'order':
        xcr, ycr = np.where(img * mask <= gfit.eta - 1 * gfit.omega)

    # returns an image that is nan-masked
    img[xcr, ycr] = np.nan
    return img
Exemple #21
0
def test_fittable_compound():
    m = Identity(1) | Mapping((0, )) | Gaussian1D(1, 5, 4)
    x = np.arange(10)
    y_real = m(x)
    dy = 0.005
    with NumpyRNGContext(1234567):
        n = np.random.normal(0., dy, x.shape)
    y_noisy = y_real + n
    pfit = LevMarLSQFitter()
    new_model = pfit(m, x, y_noisy)
    y_fit = new_model(x)
    assert_allclose(y_fit, y_real, atol=dy)
def test_evaluate_with_quantities():
    """
    Test evaluation of a single model with Quantity parameters that do
    not explicitly require units.
    """

    # We create two models here - one with quantities, and one without. The one
    # without is used to create the reference values for comparison.

    g = Gaussian1D(1, 1, 0.1)
    gq = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)

    # We first check that calling the Gaussian with quantities returns the
    # expected result
    assert_quantity_allclose(gq(1 * u.m), g(1) * u.J)

    # Units have to be specified for the Gaussian with quantities - if not, an
    # error is raised
    with pytest.raises(UnitsError) as exc:
        gq(1)
    assert exc.value.args[0] == (
        "Gaussian1D: Units of input 'x', (dimensionless), could not be "
        "converted to required input units of m (length)")

    # However, zero is a special case
    assert_quantity_allclose(gq(0), g(0) * u.J)

    # We can also evaluate models with equivalent units
    assert_allclose(gq(0.0005 * u.km).value, g(0.5))

    # But not with incompatible units
    with pytest.raises(UnitsError) as exc:
        gq(3 * u.s)
    assert exc.value.args[0] == (
        "Gaussian1D: Units of input 'x', s (time), could not be "
        "converted to required input units of m (length)")

    # We also can't evaluate the model without quantities with a quantity
    with pytest.raises(UnitsError) as exc:
        g(3 * u.m)
Exemple #23
0
    def __init__(self, *args, file_path=None, file_loader=None, embedded=False,
                 dev=False, skip_splash=False, **kwargs):
        super(Application, self).__init__(*args, **kwargs)

        # Set application icon
        self.setWindowIcon(QIcon(":/icons/specviz.icns"))

        # Load local plugins
        self.load_local_plugins()

        # cache the line lists for speedier access
        from .core import linelist
        linelist.populate_linelists_cache()

        # Show splash
        if not skip_splash:
            self._splash_dialog = SplashDialog(2000)
            self._splash_dialog.exec()

        # If specviz is not being embded in another application, go ahead and
        # perform the normal gui setup procedure.
        if not embedded:
            # Cache a reference to the currently active window
            self.current_workspace = self.add_workspace()

            # Add an initially empty plot
            self.current_workspace.add_plot_window()

            # Set embed mode state
            self.current_workspace.set_embedded(embedded)

        if dev:
            y = Gaussian1D(mean=50, stddev=10)(np.arange(100)) + np.random.sample(100) * 0.1

            spec1 = Spectrum1D(flux=y * u.Jy,
                            spectral_axis=np.arange(100) * u.AA)
            spec2 = Spectrum1D(flux=np.random.sample(100) * u.erg,
                            spectral_axis=np.arange(100) * u.Hz)
            spec3 = Spectrum1D(flux=np.random.sample(100) * u.erg,
                            spectral_axis=np.arange(100) * u.Hz)

            data_item = self.current_workspace.model.add_data(spec1, "Spectrum 1")
            self.current_workspace.model.add_data(spec2, "Spectrum 2")
            self.current_workspace.model.add_data(spec3, "Spectrum 3")

            # Set the first item as selected
            self.current_workspace.force_plot(data_item)

        # If a file path has been given, automatically add data
        if file_path is not None:
            self.current_workspace.load_data(
                file_path, file_loader, display=True)
Exemple #24
0
    def evaluate(self, position):
        """Evaluate model at a given position.

        Parameters
        ----------
        position : `~astropy.coordinates.SkyCoord`
            Position on the sky.
        """
        glon, glat = position.galactic.l, position.galactic.b
        width = self.width(glon)
        amplitude = self.peak_brightness(glon)
        mean = self.peak_latitude(glon)
        return Gaussian1D.evaluate(glat, amplitude=amplitude, mean=mean, stddev=width)
Exemple #25
0
def test_fitting_missing_model_units():
    """
    Proceed if the data has units but the model doesn't
    """

    x, y = _fake_gaussian_data()

    g_init = Gaussian1D(amplitude=1., mean=3, stddev=2)
    fit_g = fitting.LevMarLSQFitter()
    g = fit_g(g_init, x, y)

    assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
    assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
    assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)

    g_init = Gaussian1D(amplitude=1., mean=3 * u.m, stddev=2 * u.m)
    fit_g = fitting.LevMarLSQFitter()
    g = fit_g(g_init, x, y)

    assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
    assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
    assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
Exemple #26
0
    def evaluate(self, position):
        """Evaluate model at a given position.

        Parameters
        ----------
        position : `~astropy.coordinates.SkyCoord`
            Position on the sky.
        """
        glon, glat = position.galactic.l, position.galactic.b
        width = self.width(glon)
        amplitude = self.peak_brightness(glon)
        mean = self.peak_latitude(glon)
        return Gaussian1D.evaluate(glat, amplitude=amplitude, mean=mean, stddev=width)
Exemple #27
0
def psf1d(x,
          y,
          amplitude1=1.0,
          stddev1=1.0,
          amplitude2=0.5,
          stddev2=5.0,
          amplitude3=0.1,
          stddev3=10.,
          mean=0.,
          offset=0.):
    if amplitude1 < 0:
        amplitude1 = 1e12
    if amplitude2 < 0:
        amplitude2 = 1e12
    if amplitude3 < 0:
        amplitude3 = 1e12
    g1 = Gaussian1D(amplitude=amplitude1, mean=mean, stddev=stddev1)
    g2 = Gaussian1D(amplitude=amplitude2, mean=mean, stddev=stddev2)
    g3 = Gaussian1D(amplitude=amplitude3, mean=mean, stddev=stddev3)
    y1 = g1.evaluate(x, amplitude=amplitude1, mean=mean, stddev=stddev1)
    y2 = g2.evaluate(x, amplitude=amplitude2, mean=mean, stddev=stddev2)
    y3 = g3.evaluate(x, amplitude=amplitude3, mean=mean, stddev=stddev3)
    return y1 + y2 + y3 + offset
Exemple #28
0
def test_fitting_with_initial_values():

    x, y = _fake_gaussian_data()

    # Fit the data using a Gaussian with units
    g_init = Gaussian1D(amplitude=1. * u.mJy, mean=3 * u.cm, stddev=2 * u.mm)
    fit_g = fitting.LevMarLSQFitter()
    g = fit_g(g_init, x, y)

    # TODO: update actual numerical results once implemented, but these should
    # be close to the values below.
    assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
    assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
    assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
def test_pickle_compound():
    """
    Regression test for
    https://github.com/astropy/astropy/issues/3867#issuecomment-114547228
    """

    # Test pickling a compound model class
    GG = Gaussian1D + Gaussian1D
    GG2 = pickle.loads(pickle.dumps(GG))
    assert GG.param_names == GG2.param_names
    assert GG.__name__ == GG2.__name__
    # Test that it works, or at least evaluates successfully
    assert GG()(0.12345) == GG2()(0.12345)

    # Test pickling a compound model instance
    g1 = Gaussian1D(1.0, 0.0, 0.1)
    g2 = Gaussian1D([2.0, 3.0], [0.0, 0.0], [0.2, 0.3])
    m = g1 + g2
    m2 = pickle.loads(pickle.dumps(m))
    assert m.param_names == m2.param_names
    assert m.__class__.__name__ == m2.__class__.__name__
    assert np.all(m.parameters == m2.parameters)
    assert np.all(m(0) == m2(0))

    # Test pickling a concrete class
    p = pickle.dumps(_TestPickleModel, protocol=0)
    # Note: This is very dependent on the specific protocol, but the point of
    # this test is that the "concrete" model is pickled in a very simple way
    # that only specifies the module and class name, and is unpickled by
    # re-importing the class from the module in which it was defined.  This
    # should still work for concrete subclasses of compound model classes that
    # were dynamically generated through an expression
    exp = b'castropy.modeling.tests.test_compound\n_TestPickleModel\np0\n.'
    # When testing against the expected value we drop the memo length field
    # at the end, which may differ between runs
    assert p[:p.rfind(b'p')] == exp[:exp.rfind(b'p')]
    assert pickle.loads(p) is _TestPickleModel
Exemple #30
0
def gaussfit1d(y):
    global click, ii
    click = np.zeros((2,2))
    ii=0

    
    def on_key(event):
        global click, ii
        #print 'event.key=%s,  event.x=%d, event.y=%d, event.xdata=%f, \
        #event.ydata=%f'%(event.key, event.x, event.y, event.xdata, event.ydata)
        click[ii,0] = event.xdata
        click[ii,1] = event.ydata
        ii = ii + 1
        return

    
    x = np.array(range(len(y)))
    print('Press any key at two points for specifying the '+\
          'fitting region and the baselevel.')
    fig=plt.figure()
    cid = fig.canvas.mpl_connect('key_press_event', on_key)
    plt.plot(x,y)
    plt.draw()
    while ii != 2:
        plt.pause(0.1)

    x1 = int(np.min(click[:,0])+0.5)
    x2 = int(np.max(click[:,0])+0.5)

    m = (click[1,1]-click[0,1])/(click[1,0]-click[0,0])
    yy = y - m * ( x - click[0,0]) - click[0,1]
    
    # Fit the data using a Gaussian
    g_init = Gaussian1D(amplitude=np.min(yy[x1:x2+1]), \
                               mean=(x1+x2)/2.0, stddev=1.)
    fit_g = LevMarLSQFitter()
    g = fit_g(g_init, x[x1:x2+1], yy[x1:x2+1])
    #print(g)

    plt.plot((x1,x2), (y[x1],y[x2]))
    xx = np.linspace(x1,x2,100)
    yy = g(xx) + m * (xx - click[0,0]) + click[0,1]
    plt.plot(xx,yy)
    plt.draw()
    try:
        plt.pause(-1)
    except:
        pass
    return g
Exemple #31
0
def test_parameter_lose_units():
    """
    Check that parameters that have been set to a quantity that are then set to
    a value with no units raise an exception. We do this because setting a
    parameter to a value with no units is ambiguous if units were set before:
    if a parameter is 1 * u.Jy and the parameter is then set to 4, does this mean
    2 without units, or 2 * u.Jy?
    """

    g = Gaussian1D(1 * u.Jy, 3, 0.1)

    with pytest.raises(UnitsError) as exc:
        g.amplitude = 2
    assert exc.value.args[0] == ("The 'amplitude' parameter should be given as "
                                 "a Quantity because it was originally "
                                 "initialized as a Quantity")
Exemple #32
0
 def _eval_y(self, y, pars):
     """Evaluate Gaussian model at a given ``y`` position.
     """
     return Gaussian1D.eval(y, **pars)
Exemple #33
0
 def evaluate(self, x, y, sigma, c0, c1, c2, c3):
     self.polynomial.coef = np.array([c0, c1, c2, c3])
     poly_eval = self.polynomial(x)
     poly_eval = (poly_eval + (self.window[0] + 1)) * self.window_delta / 2.
     return Gaussian1D.evaluate(y, 1., poly_eval, sigma)