Ejemplo n.º 1
0
def test_shape_of_ocm(host):
    gammas = np.arange(2)

    ocm = one_comp_model(host.xaxis, host.flux, gammas=gammas)
    assert isinstance(ocm, sp.interpolate.interp1d)

    ocm_eval = ocm(host.xaxis)  # Evaluate at host.xaxis
    assert ocm_eval.shape == (len(host.xaxis), len(gammas))
Ejemplo n.º 2
0
def test_ocm_and_tcm_models_are_same_with_no_companion(host, gamma, rv):
    """To compare models give equivalent output.

    If alpha=0 then there is no companion.
    """
    ocm = one_comp_model(host.xaxis, host.flux, gammas=gamma)
    ocm_eval = ocm(host.xaxis).squeeze()
    tcm = two_comp_model(host.xaxis,
                         host.flux,
                         np.ones_like(host.flux),
                         alphas=0,
                         rvs=rv,
                         gammas=gamma)
    tcm_eval = tcm(host.xaxis).squeeze()

    assert ocm_eval.shape == tcm_eval.shape

    o_ravel = ocm_eval.ravel()
    t_ravel = ocm_eval.ravel()
    assert np.allclose(o_ravel[~np.isnan(o_ravel)],
                       t_ravel[~np.isnan(t_ravel)])
def fake_bhm_simulation(wav,
                        params,
                        gamma,
                        limits=(2070, 2180),
                        noise=None,
                        header=False):
    """Make a fake spectrum with binary params and radial velocities."""

    mod_spec = load_starfish_spectrum(params,
                                      limits=limits,
                                      hdr=True,
                                      normalize=True,
                                      wav_scale=True)

    bhm_grid_func = one_comp_model(mod_spec.xaxis, mod_spec.flux, gammas=gamma)

    if wav is None:
        delta = spec_max_delta(mod_spec, 0, gamma)
        assert np.all(np.isfinite(mod_spec.xaxis))
        mask = (mod_spec.xaxis > mod_spec.xaxis[0] + 2 * delta) * (
            mod_spec.xaxis < mod_spec.xaxis[-1] - 2 * delta)
        wav = mod_spec.xaxis[mask]

    bhm_grid_values = bhm_grid_func(wav).squeeze()

    logging.debug(
        __("number of bhm nans = {}", np.sum(~np.isfinite(bhm_grid_values))))

    if noise is not None or noise is not 0:
        bhm_grid_values = add_noise(bhm_grid_values, noise)
    else:
        logging.warning(
            "\n!!!\n\nNot adding any noise to bhm fake simulation!!!!!\n\n!!!!!\n"
        )
        print("\n!!!!\n\nNot adding any noise to fake simulation!!!!\n\n!\n")

    if header:
        return wav, bhm_grid_values.squeeze(), mod_spec.header
    else:
        return wav, bhm_grid_values.squeeze()
Ejemplo n.º 4
0
def compare_spectra(table, params):
    """Plot the min chi2 result against the observations."""
    extractor = DBExtractor(table)
    gamma_df = extractor.simple_extraction(columns=["gamma"])
    extreme_gammas = [min(gamma_df.gamma.values), max(gamma_df.gamma.values)]
    for ii, chi2_val in enumerate(chi2_names[0:-2]):
        df = extractor.ordered_extraction(
            columns=["teff_1", "logg_1", "feh_1", "gamma", chi2_val],
            order_by=chi2_val,
            limit=1,
            asc=True)

        params1 = [
            df["teff_1"].values[0], df["logg_1"].values[0],
            df["feh_1"].values[0]
        ]

        params1 = [float(param1) for param1 in params1]

        gamma = df["gamma"].values

        obs_name, obs_params, output_prefix = bhm_helper_function(
            params["star"], params["obsnum"], ii + 1)
        print(obs_name)
        obs_spec = load_spectrum(obs_name)

        # Mask out bad portion of observed spectra
        # obs_spec = spectrum_masking(obs_spec, params["star"], params["obsnum"], ii + 1)

        # Barycentric correct spectrum
        _obs_spec = barycorr_crires_spectrum(obs_spec, extra_offset=None)
        normalization_limits = [obs_spec.xaxis[0] - 5, obs_spec.xaxis[-1] + 5]
        # models
        # print("params for models", params1)
        mod1 = load_starfish_spectrum(params1,
                                      limits=normalization_limits,
                                      hdr=True,
                                      normalize=False,
                                      area_scale=True,
                                      flux_rescale=True)

        bhm_grid_func = one_comp_model(mod1.xaxis, mod1.flux, gammas=gamma)
        bhm_upper_gamma = one_comp_model(mod1.xaxis,
                                         mod1.flux,
                                         gammas=extreme_gammas[1])
        bhm_lower_gamma = one_comp_model(mod1.xaxis,
                                         mod1.flux,
                                         gammas=extreme_gammas[0])

        bhm_grid_model = bhm_grid_func(obs_spec.xaxis).squeeze()
        bhm_grid_model_full = bhm_grid_func(mod1.xaxis).squeeze()
        bhm_upper_gamma = bhm_upper_gamma(obs_spec.xaxis).squeeze()
        bhm_lower_gamma = bhm_lower_gamma(obs_spec.xaxis).squeeze()

        model_spec_full = Spectrum(flux=bhm_grid_model_full, xaxis=mod1.xaxis)
        model_spec = Spectrum(flux=bhm_grid_model, xaxis=obs_spec.xaxis)
        bhm_upper_gamma = Spectrum(flux=bhm_upper_gamma, xaxis=obs_spec.xaxis)
        bhm_lower_gamma = Spectrum(flux=bhm_lower_gamma, xaxis=obs_spec.xaxis)

        model_spec = model_spec.remove_nans()
        model_spec = model_spec.normalize(method="exponential")
        model_spec_full = model_spec_full.remove_nans()
        model_spec_full = model_spec_full.normalize(method="exponential")
        bhm_lower_gamma = bhm_lower_gamma.remove_nans()
        bhm_lower_gamma = bhm_lower_gamma.normalize(method="exponential")
        bhm_upper_gamma = bhm_upper_gamma.remove_nans()
        bhm_upper_gamma = bhm_upper_gamma.normalize(method="exponential")

        from mingle.utilities.chisqr import chi_squared
        chisqr = chi_squared(obs_spec.flux, model_spec.flux)

        print("Recomputed chi^2 = {0}".format(chisqr))
        print("Database chi^2 = {0}".format(df[chi2_val]))
        fig, ax = plt.subplots(1, 1, figsize=(15, 8))
        plt.plot(obs_spec.xaxis,
                 obs_spec.flux + 0.01,
                 label="0.05 + Observation, {}".format(obs_name))
        plt.plot(model_spec.xaxis,
                 model_spec.flux,
                 label="Minimum \chi^2 model")
        plt.plot(model_spec_full.xaxis,
                 model_spec_full.flux,
                 "--",
                 label="Model_full_res")
        plt.plot(bhm_lower_gamma.xaxis,
                 bhm_lower_gamma.flux,
                 "-.",
                 label="gamma={}".format(extreme_gammas[0]))
        plt.plot(bhm_upper_gamma.xaxis,
                 bhm_upper_gamma.flux,
                 ":",
                 label="gamma={}".format(extreme_gammas[1]))
        plt.title("bhm spectrum")
        plt.legend()

        fig.tight_layout()
        name = "{0}-{1}_{2}_{3}_bhm_min_chi2_spectrum_comparison_{4}.png".format(
            params["star"], params["obsnum"], params["chip"], chi2_val,
            params["suffix"])
        plt.savefig(os.path.join(params["path"], "plots", name))
        plt.close()

        plt.plot(obs_spec.xaxis, obs_spec.flux, label="Observation")
        plt.show()
Ejemplo n.º 5
0
def bhm_analysis(obs_spec, model_pars, gammas=None, errors=None, prefix=None, verbose=False, chip=None, norm=False,
                 wav_scale=True, norm_method="scalar"):
    """Run one component model over all parameter combinations in model_pars."""
    # Gammas
    if gammas is None:
        gammas = np.array([0])
    elif isinstance(gammas, (float, int)):
        gammas = np.asarray(gammas, dtype=np.float32)

    if isinstance(model_pars, list):
        logging.debug(__("Number of close model_pars returned {0}", len(model_pars)))

    # Solution Grids to return
    model_chisqr_vals = np.empty(len(model_pars))
    model_xcorr_vals = np.empty(len(model_pars))
    model_xcorr_rv_vals = np.empty(len(model_pars))
    bhm_grid_chisqr_vals = np.empty(len(model_pars))
    bhm_grid_gamma = np.empty(len(model_pars))
    full_bhm_grid_chisquare = np.empty((len(model_pars), len(gammas)))

    normalization_limits = [2105, 2185]  # small as possible?

    for ii, params in enumerate(tqdm(model_pars)):
        if prefix is None:
            save_name = os.path.join(
                simulators.paths["output_dir"], obs_spec.header["OBJECT"].upper(), "bhm",
                "bhm_{0}_{1}_{3}_part{2}.csv".format(
                    obs_spec.header["OBJECT"].upper(), obs_spec.header["MJD-OBS"], ii, chip))
        else:
            save_name = os.path.join("{0}_part{1}.csv".format(prefix, ii))

        if verbose:
            print("Starting iteration with parameter:s\n{}".format(params))

        mod_spec = load_starfish_spectrum(params, limits=normalization_limits, hdr=True,
                                          normalize=True, wav_scale=wav_scale)

        # Wavelength selection
        mod_spec.wav_select(np.min(obs_spec.xaxis) - 5,
                            np.max(obs_spec.xaxis) + 5)  # +- 5nm of obs

        obs_spec = obs_spec.remove_nans()

        # One component model with broadcasting over gammas
        bhm_grid_func = one_comp_model(mod_spec.xaxis, mod_spec.flux, gammas=gammas)
        bhm_grid_values = bhm_grid_func(obs_spec.xaxis)

        assert ~np.any(np.isnan(obs_spec.flux)), "Observation is nan"

        # RENORMALIZATION
        if chip == 4:
            # Quadratically renormalize anyway
            obs_spec = renormalization(obs_spec, bhm_grid_values, normalize=True, method="quadratic")
        obs_flux = renormalization(obs_spec, bhm_grid_values, normalize=norm, method=norm_method)

        # Simple chi2
        bhm_grid_chisquare_old = chi_squared(obs_flux, bhm_grid_values, error=errors)

        # Applying arbitrary scalar normalization to continuum
        bhm_norm_grid_values, arb_norm = arbitrary_rescale(bhm_grid_values,
                                                           *simulators.sim_grid["arb_norm"])

        # Calculate Chi-squared
        obs_flux = np.expand_dims(obs_flux, -1)  # expand on last axis to match rescale
        bhm_norm_grid_chisquare = chi_squared(obs_flux, bhm_norm_grid_values, error=errors)

        # Take minimum chi-squared value along Arbitrary normalization axis
        bhm_grid_chisquare, arbitrary_norms = arbitrary_minimums(bhm_norm_grid_chisquare, arb_norm)

        assert np.any(
            bhm_grid_chisquare_old >= bhm_grid_chisquare), "All chi2 values are not better or same with arbitrary scaling"

        # Interpolate to obs
        mod_spec.spline_interpolate_to(obs_spec)
        org_model_chi_val = chi_squared(obs_spec.flux, mod_spec.flux)

        model_chisqr_vals[ii] = org_model_chi_val  # This is gamma = 0 version

        # New parameters to explore
        bhm_grid_chisqr_vals[ii] = bhm_grid_chisquare[np.argmin(bhm_grid_chisquare)]
        bhm_grid_gamma[ii] = gammas[np.argmin(bhm_grid_chisquare)]
        full_bhm_grid_chisquare[ii, :] = bhm_grid_chisquare

        ################
        #  Find cross correlation RV
        # Should run though all models and find best rv to apply uniformly
        rvoffset, cc_max = xcorr_peak(obs_spec, mod_spec, plot=False)
        if verbose:
            print("Cross correlation RV = {}".format(rvoffset))
            print("Cross correlation max = {}".format(cc_max))

        model_xcorr_vals[ii] = cc_max
        model_xcorr_rv_vals[ii] = rvoffset
        ###################

        npix = obs_flux.shape[0]
        # print("bhm shape", bhm_grid_chisquare.shape)
        save_full_bhm_chisqr(save_name, params, gammas, bhm_grid_chisquare, arbitrary_norms,
                             npix, rvoffset)

    return (model_chisqr_vals, model_xcorr_vals, model_xcorr_rv_vals,
            bhm_grid_chisqr_vals, bhm_grid_gamma, full_bhm_grid_chisquare)