Ejemplo n.º 1
0
def fit_select(function: str = 'gaussian',
               fit_type: str = 'spectrum',
               **kwargs):
    if fit_type == 'spectrum':
        file_name = pkg_resources.resource_filename(
            'ifscube', 'examples/manga_onedspec.fits')
        spec = onedspec.Spectrum(file_name,
                                 primary='PRIMARY',
                                 scidata='F_OBS',
                                 variance='F_VAR',
                                 flags='F_FLAG',
                                 stellar='F_SYN')
        fit = modeling.LineFit(spec,
                               function=function,
                               fitting_window=(6400.0, 6800.0),
                               **kwargs)
    elif fit_type == 'cube':
        file_name = pkg_resources.resource_filename(
            'ifscube', 'examples/ngc3081_cube.fits')
        cube = datacube.Cube(file_name, variance='ERR')
        fit = modeling.LineFit3D(cube,
                                 function=function,
                                 fitting_window=(6400.0, 6800.0),
                                 **kwargs)
    else:
        raise RuntimeError(f'fit_type "{fit_type}" not understood.')
    return fit
Ejemplo n.º 2
0
def test_missing_k_group():
    file_name = pkg_resources.resource_filename(
        'ifscube', 'examples/manga_onedspec.fits')
    spec = onedspec.Spectrum(file_name,
                             primary='PRIMARY',
                             scidata='F_OBS',
                             variance='F_VAR',
                             flags='F_FLAG',
                             stellar='F_SYN')
    fit = modeling.LineFit(spec,
                           function='gaussian',
                           fitting_window=(6400.0, 6800.0))
    fit.add_feature(name='line_a',
                    rest_wavelength=6548,
                    amplitude=1,
                    velocity=0.0,
                    sigma=100.0)
    fit.add_feature(name='line_b',
                    rest_wavelength=6563,
                    amplitude=1,
                    velocity=0.0,
                    sigma=100.0,
                    kinematic_group=1)
    fit.pack_groups()
    assert True
Ejemplo n.º 3
0
def setup_fit(data: Union[onedspec.Spectrum, datacube.Cube], **line_fit_args):

    if isinstance(data, datacube.Cube):
        general_fit_args = {
            _: line_fit_args[_]
            for _ in [
                'function', 'fitting_window', 'instrument_dispersion',
                'individual_spec', 'spiral_loop', 'spiral_center', 'refit',
                'refit_radius', 'bounds_change'
            ] if _ in line_fit_args.keys()
        }
        fit = modeling.LineFit3D(data, **general_fit_args)
    elif isinstance(data, onedspec.Spectrum):
        general_fit_args = {
            _: line_fit_args[_]
            for _ in ['function', 'fitting_window', 'instrument_dispersion']
            if _ in line_fit_args.keys()
        }
        fit = modeling.LineFit(data, **general_fit_args)
    else:
        raise RuntimeError(f'Data instance "{str(data)}" not recognized.')

    for feature in line_fit_args['features']:
        fit.add_feature(**feature)
    for bounds in line_fit_args['bounds']:
        fit.set_bounds(*bounds)
    for constraint in line_fit_args['constraints']:
        fit.add_constraint(*constraint)
    if line_fit_args['optimize_fit']:
        fit.optimize_fit(width=line_fit_args['optimization_window'])

    return fit
Ejemplo n.º 4
0
def test_skip_feature():
    file_name = pkg_resources.resource_filename('ifscube',
                                                'examples/ngc6300_nuc.fits')
    spec = onedspec.Spectrum(file_name)
    fit = modeling.LineFit(spec, fitting_window=(6400.0, 6700.0))
    with pytest.warns(UserWarning):
        fit.add_feature(name='hb',
                        rest_wavelength=4861.0,
                        amplitude=0,
                        velocity=0,
                        sigma=10)
    fit.add_feature(name='ha',
                    rest_wavelength=6562.8,
                    amplitude=1.0e-14,
                    velocity=0.0,
                    sigma=100.0)
    fit.fit()
    assert 1
Ejemplo n.º 5
0
def test_fixed_features():
    file_name = pkg_resources.resource_filename('ifscube',
                                                'examples/ngc6300_nuc.fits')
    spec = onedspec.Spectrum(file_name)
    fit = modeling.LineFit(spec,
                           function='gaussian',
                           fitting_window=(6400.0, 6800.0))
    names = ['n2_6548', 'ha', 'n2_6583', 's2_6716', 's2_6731']
    r_wl = [6548.04, 6562.8, 6583.46, 6716.44, 6730.86]

    for name, wl, k in zip(names, r_wl, [0, 1, 0, 2, 2]):
        amp = 1e-14 if name == 'n2_6548' else 3.e-14
        fit.add_feature(name=name,
                        rest_wavelength=wl,
                        amplitude=amp,
                        velocity=0.0,
                        sigma=100.0,
                        fixed='n2' in name,
                        kinematic_group=k)
    fit.fit()
    assert 1
Ejemplo n.º 6
0
def load_fit(file_name):
    """
    Loads the result of a previous fit, and put it in the
    appropriate variables for the plot function.

    Parameters
    ----------
    file_name : string
        Name of the FITS file containing the fit results.

    Returns
    -------
    Nothing.
    """
    with fits.open(file_name, mode='readonly') as h:
        if len(h['FITSPEC'].data.shape) == 3:
            data = datacube.Cube(file_name,
                                 scidata='FITSPEC',
                                 variance='VAR',
                                 flags='FLAGS',
                                 stellar='STELLAR',
                                 primary='PRIMARY',
                                 spatial_mask='MASK2D',
                                 wavelength='RESTWAVE',
                                 redshift=0.0)
        # Redshift is set to zero because LineFit already puts everything in the rest frame.
        elif len(h['FITSPEC'].data.shape) == 1:
            data = onedspec.Spectrum(file_name,
                                     scidata='FITSPEC',
                                     variance='VAR',
                                     flags='FLAGS',
                                     stellar='STELLAR',
                                     primary='PRIMARY',
                                     wavelength='RESTWAVE',
                                     redshift=0.0)
        else:
            raise RuntimeError(
                f'Data dimensions are expected to be either 1 or 3, got "{len(h["FITSPEC"].data.shape)}".'
            )

        if 'FITCONFIG' in h:
            config = table_to_config(table.Table(h['FITCONFIG'].data))
            line_fit_config = parser.LineFitParser(config).get_vars()
            line_fit_config['refit'] = False
            fit = setup_fit(data, **line_fit_config)
            fit.pack_groups()
        else:
            if len(h['FITSPEC'].data.shape) == 3:
                fit = modeling.LineFit3D(data)
            elif len(h['FITSPEC'].data.shape) == 1:
                fit = modeling.LineFit(data)
            fit = features_from_table(fit,
                                      parameter_names=h['parnames'].data,
                                      solution=h['solution'].data,
                                      rest_wavelength=h['featwl'].data)

        translate_extensions = {
            'pseudo_continuum': 'fitcont',
            'model': 'model',
            'eqw_model': 'eqw_m',
            'eqw_direct': 'eqw_d',
            'flux_model': 'flux_m',
            'flux_direct': 'flux_d',
            'status': 'status',
            'reduced_chi_squared': 'red_chi'
        }
        # Backwards compatibility
        key = 'solution'
        if len(fit.parameter_names) == (len(h[key].data) - 1):
            warnings.warn(
                'It seems you are trying to read a file from IFSCube v1.0. '
                'Removing last plane from solution extension.',
                stacklevel=2)
            setattr(fit, key, h[key].data[:-1])
        else:
            setattr(fit, key, h[key].data)
        for key in translate_extensions:
            value = translate_extensions[key]
            if value in h:
                setattr(fit, key, h[translate_extensions[key]].data)
            else:
                warnings.warn(
                    f'Extension {value} not found in file {h.filename()}. Adding place holder data to this extension.'
                )
                if key == 'reduced_chi_squared':
                    setattr(fit, key, np.zeros(data.data.shape[1:]))
                else:
                    warnings.warn(
                        f'No behaviour set for extension {key}. Leaving empty.'
                    )

    return fit