def load_phoenix_spectrum(phoenix_name, limits=None, normalize=False):
    wav_dir = simulators.starfish_grid["raw_path"]
    wav_model = fits.getdata(
        os.path.join(wav_dir, "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits"))
    wav_model /= 10  # turn into nanometers
    flux = fits.getdata(phoenix_name)
    spec = Spectrum(flux=flux, xaxis=wav_model)

    # Limit to K band
    spec.wav_select(2070, 2350)
    if normalize:
        spec = spec_local_norm(spec, method="exponential")

    if limits is not None:
        spec.wav_select(*limits)
    return spec
def load_model_spec(pathwave, specpath, limits=None, normalize=False):
    """Load model spec from given path to file and wavefile."""
    w_mod = fits.getdata(pathwave)
    w_mod /= 10  # turn into nm
    flux = fits.getdata(specpath)
    hdr = fits.getheader(specpath)
    spec = Spectrum(xaxis=w_mod, flux=flux, header=hdr)

    logging.debug(pv("spec.xaxis"))
    if limits is not None:
        """Apply wavelength limits with slicing."""
        spec.wav_select(*limits)

    if normalize:
        """Apply normalization to loaded spectrum."""
        if limits is None:
            print("Warning! Limits should be given when using normalization")
            print("specturm for normalize", spec)
        spec = spec_local_norm(spec)
    return spec
plt.show()

# In[ ]:

# ARTUCUS 1000nm
artucus_1 = "/home/jneal/Phd/data/artucus/10097-10155_s-obs.fits"
data, hdr = fits.getdata(artucus_1, header=True)
artucus_1 = Spectrum(xaxis=get_wavelength(hdr) / 10, flux=data, header=hdr)
artucus_1 = artucus_1.normalize("linear")

# In[ ]:

#limits = [2100, 2200]
limits = [artucus_1.xaxis[0] - 2, artucus_1.xaxis[-1] + 2]
print(limits)
next_spec.wav_select(*limits)
next_spec = next_spec.normalize("exponential")
dusty_spec.wav_select(*limits)
dusty_spec = dusty_spec.normalize("exponential")
settl_spec.wav_select(*limits)
settl_spec = settl_spec.normalize("exponential")
cond_spec.wav_select(*limits)
cond_spec = cond_spec.normalize("exponential")
aces_spec.wav_select(*limits)
aces_spec = aces_spec.normalize("exponential")

# In[ ]:

print(np.mean(vac2air(aces_spec.xaxis * 10) / 10 - aces_spec.xaxis) * 3e5)

artucus_1 = align2model(artucus_1, aces_spec)
raw_flux = fits.getdata(phoenix)
wav = fits.getdata(phoenix_wav)
plt.plot(wav, raw_flux, label="raw")
plt.plot(wl, flux * 5e7, label="starfish")
plt.legend()
plt.show()

params2 = [5200, 4.5, 0.0]
flux = myHDF5.load_flux(np.array(params2))

# Load direct phoenix spectra

path = simulators.starfish_grid["raw_path"]

phoenix = os.path.join(
    path, "Z-0.0",
    "lte{:05d}-{:0.2f}-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits".format(
        params2[0], params2[1]))
phoenix_wav = os.path.join(path, "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits")

print(phoenix)
raw_flux = fits.getdata(phoenix)
wav = fits.getdata(phoenix_wav)
phoenix_spec = Spectrum(xaxis=wav, flux=raw_flux)
phoenix_spec.wav_select(wl[0], wl[-1])
plt.plot(wav, raw_flux, label="raw")
plt.plot(phoenix_spec.xaxis, phoenix_spec.flux, "--", label="spec")
plt.plot(wl, flux * 4e6, label="starfish")
plt.legend()
plt.show()
예제 #5
0
           "HD30501b-lte02500-5.00-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
star_model = "/home/jneal/Phd/data/phoenixmodels/" \
             "HD30501-lte05200-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"

i_bdmod = fits.getdata(bd_model)
i_star = fits.getdata(star_model)
hdr_bd = fits.getheader(bd_model)
hdr_star = fits.getheader(star_model)
w_mod = fits.getdata(pathwave)

w_mod /= 10  # turn into nm

test_rv = -15.205  # km/s

template_spectrum = Spectrum(xaxis=w_mod, flux=i_star, calibrated=True)
template_spectrum.wav_select(2100, 2200)

obs_spectrum = Spectrum(xaxis=w_mod, flux=i_star, calibrated=True)
obs_spectrum.doppler_shift(test_rv)
obs_spectrum.wav_select(2100, 2200)

print(len(obs_spectrum.xaxis))

rv, cc = pyasl.crosscorrRV(obs_spectrum.xaxis,
                           obs_spectrum.flux,
                           template_spectrum.xaxis,
                           template_spectrum.flux,
                           rvmin=-60.,
                           rvmax=60.0,
                           drv=0.1,
                           mode='doppler',
예제 #6
0
host_phoenix = os.path.join(
    base, ("Z-0.0/lte{:05d}-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
           ).format(host_temp))

comp_phoenix = os.path.join(
    base, ("Z-0.0/lte{:05d}-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
           ).format(comp_temp))

unnorm_host_spec = Spectrum(flux=fits.getdata(host_phoenix), xaxis=phoenix_wl)
unnorm_comp_spec = Spectrum(flux=fits.getdata(comp_phoenix), xaxis=phoenix_wl)

min_wav = 2050
max_wav = 2250

unnorm_host_spec.wav_select(min_wav, max_wav)
unnorm_comp_spec.wav_select(min_wav, max_wav)

# local normalization
norm_host_flux = local_normalization(unnorm_host_spec.xaxis,
                                     unnorm_host_spec.flux,
                                     method="exponential",
                                     plot=False)
norm_comp_flux = local_normalization(unnorm_comp_spec.xaxis,
                                     unnorm_comp_spec.flux,
                                     method="exponential",
                                     plot=False)

norm_host_spec = spec_local_norm(unnorm_host_spec, method="exponential")
norm_comp_spec = spec_local_norm(unnorm_comp_spec, method="exponential")
make_dirs(source_path, output_path)  # This is completed now.

folders = glob.glob(os.path.join(source_path, "*"))

phoenix_wave = os.path.join(source_path, "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits")
wave = fits.getdata(phoenix_wave) / 10  # Convert to nm

for folder in folders:
    # Now have a specific directory with phoenix fits files.
    phoenix_files = glob.glob(os.path.join(folder, "*.fits"))

    for f in phoenix_files:
        print(f)
        # Load in file
        spectrum = fits.getdata(f)

        # Wavelenght narrow to K band only 2.07, 2.35 micron
        phoenix_spectrum = Spectrum(flux=spectrum, xaxis=wave)
        phoenix_spectrum.wav_select(*band_limits)

        # Convolutions
        # Convolution in spectrum overload?
        # phoenix_spectrum.convolution(R, ...)

        # Save result to fits file in new directory.

        new_f = f.replace(".fits", "_R{0:d}k.fits".format(int(resolution / 1000)))
        new_f = new_f.replace(source_path, output_path)
        print(new_f)
def load_starfish_spectrum(params,
                           limits=None,
                           hdr=False,
                           normalize=False,
                           area_scale=False,
                           flux_rescale=False,
                           wav_scale=True):
    """Load spectrum from hdf5 grid file.

    Parameters
    ----------
    params: list
        Model parameters [teff, logg, Z]
    limits= List[float, float] default=None
        Wavelength limits.
    hdr: bool
       Include the model header. Default False.
    normalize: bool
        Locally normalize the spectrum. Default False.
    area_scale: bool
        Multiply by stellar surface area pi*R**2 (towards Earth)
    flux_rescale: bool
        Convert from /cm to /nm by dividing by 1e7
    wav_scale: bool
        Multiply by wavelength to turn into [erg/s/cm^2]

    Returns
    -------
    spec: Spectrum
        The loaded spectrum as Spectrum object.
    """
    my_hdf5 = HDF5Interface()
    my_hdf5.wl = my_hdf5.wl / 10  # Turn into Nanometer

    if hdr:
        flux, myhdr = my_hdf5.load_flux_hdr(np.array(params))
        spec = Spectrum(flux=flux, xaxis=my_hdf5.wl, header=myhdr)
    else:
        flux = my_hdf5.load_flux(np.array(params))
        spec = Spectrum(flux=flux, xaxis=my_hdf5.wl)

    if flux_rescale:
        spec = spec * 1e-7  # convert flux unit from /cm to /nm

    if area_scale:
        if hdr:
            emitting_area = phoenix_area(spec.header)
            spec = spec * emitting_area
            spec.header["emit_area"] = (emitting_area, "pi*r^2")
        else:
            raise ValueError("No header provided for stellar area scaling")

    if wav_scale:
        # Convert into photon counts, (constants ignored)
        spec = spec * spec.xaxis

    if normalize:
        spec = spec_local_norm(spec, method="exponential")

    if limits is not None:
        if limits[0] > spec.xaxis[-1] or limits[-1] < spec.xaxis[0]:
            logging.warning(
                "Warning: The wavelength limits do not overlap the spectrum."
                "There is no spectrum left... Check your wavelength, or limits."
            )
        spec.wav_select(*limits)

    return spec
예제 #9
0
                             "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits")
    wav_model /= 10  # turn into nm

    temp_store = []
    rv_store = []
    cc_store = []
    chi2_store = []

    for model in tqdm(phoenix_names):
        temp_store.append(int(model.split("/")[-1][3:8]))
        phoenix_data = fits.getdata(model)
        phoenix_spectrum = Spectrum(flux=phoenix_data,
                                    xaxis=wav_model,
                                    calibrated=True)

        phoenix_spectrum.wav_select(*wl_limits)
        phoenix_spectrum = spec_local_norm(phoenix_spectrum)
        phoenix_spectrum = apply_convolution(phoenix_spectrum,
                                             R=obs_resolution,
                                             chip_limits=wl_limits)
        rv, cc = observed_spectra.crosscorr_rv(phoenix_spectrum,
                                               rvmin=-100.,
                                               rvmax=100.0,
                                               drv=0.1,
                                               mode='doppler',
                                               skipedge=50)

        maxind = np.argmax(cc)
        # print("Cross-correlation function is maximized at dRV = ", rv[maxind], " km/s")

        rv_store.append(rv[maxind])
예제 #10
0

# Manually load Phoenix spectra
#phoenix_path = simulators...
phoenix_path = "/home/jneal/Phd/data/PHOENIX-ALL/PHOENIX/"

phoenix_1 = "Z-0.0/lte06000-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
phoenix_2 = "Z-0.0/lte05800-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"

wav = fits.getdata(phoenix_path + "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits")
phoenix1 = fits.getdata(phoenix_path + phoenix_1)
phoenix2 = fits.getdata(phoenix_path + phoenix_2)

spec1 = Spectrum(xaxis=wav/10, flux=phoenix1)
spec2 = Spectrum(xaxis=wav/10, flux=phoenix2)
spec1.wav_select(2000,2200)
spec2.wav_select(2000,2200)
spec1.plot(label="1")
spec2.plot(label="2")

plt.legend()
plt.show()



# In[4]:


from Convolution.IP_multi_Convolution import convolve_spectrum

# Convolve to 50000
def main():
    """Main function."""
    star = "HD30501"
    host_parameters = load_param_file(star)
    obsnum = 1
    chip = 1
    obs_name = select_observation(star, obsnum, chip)

    # Load observation
    # uncorrected_spectra = load_spectrum(obs_name)
    observed_spectra = load_spectrum(obs_name)
    _observed_spectra = barycorr_crires_spectrum(observed_spectra,
                                                 extra_offset=None)
    observed_spectra.flux /= 1.02

    obs_resolution = crires_resolution(observed_spectra.header)

    wav_model = fits.getdata(
        os.path.join(wav_dir, "WAVE_PHOENIX-ACES-AGSS-COND-2011.fits"))
    wav_model /= 10  # turn into nm
    logging.debug(__("Phoenix wav_model = {0}", wav_model))

    closest_model = phoenix_name_from_params(model_base_dir, host_parameters)
    original_model = "Z-0.0/lte05200-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits"
    logging.debug(__("closest_model {0}", closest_model))
    logging.debug(__("original_model {0}", original_model))

    # Function to find the good models I need
    models = find_phoenix_model_names(model_base_dir, original_model)
    if isinstance(models, list):
        logging.debug(__("Number of close models returned {0}", len(models)))

    model_chisqr_vals = np.empty_like(models)
    model_xcorr_vals = np.empty_like(models)
    model_xcorr_rv_vals = np.empty_like(models)

    for ii, model_name in enumerate(models):
        mod_flux = fits.getdata(model_name)
        mod_header = fits.getheader(model_name)
        mod_spectrum = Spectrum(xaxis=wav_model,
                                flux=mod_flux,
                                header=mod_header,
                                calibrated=True)

        # Normalize Phoenix Spectrum
        # mod_spectrum.wav_select(2080, 2200)  # limits for simple normalization
        mod_spectrum.wav_select(2105, 2165)  # limits for simple normalization
        # norm_mod_spectrum = simple_normalization(mod_spectrum)
        norm_mod_spectrum = spec_local_norm(mod_spectrum, plot=False)

        # Wav select
        norm_mod_spectrum.wav_select(
            np.min(observed_spectra.xaxis) - 5,
            np.max(observed_spectra.xaxis) +
            5)  # +- 5nm of obs for convolution

        # Convolve to resolution of instrument
        conv_mod_spectrum = convolve_models([norm_mod_spectrum],
                                            obs_resolution,
                                            chip_limits=None)[0]

        # Find crosscorrelation RV
        # # Should run though all models and find best rv to apply uniformly
        rvoffset, cc_max = xcorr_peak(observed_spectra,
                                      conv_mod_spectrum,
                                      plot=False)

        # Interpolate to obs
        conv_mod_spectrum.spline_interpolate_to(observed_spectra)
        # conv_mod_spectrum.interpolate1d_to(observed_spectra)
        model_chi_val = chi_squared(observed_spectra.flux,
                                    conv_mod_spectrum.flux)

        # argmax = np.argmax(cc_max)
        model_chisqr_vals[ii] = model_chi_val
        model_xcorr_vals[ii] = cc_max
        model_xcorr_rv_vals[ii] = rvoffset

    logging.debug(pv("model_chisqr_vals"))
    logging.debug(pv("model_xcorr_vals"))
    chisqr_argmin_indx = np.argmin(model_chisqr_vals)
    xcorr_argmax_indx = np.argmax(model_xcorr_vals)

    logging.debug(pv("chisqr_argmin_indx"))
    logging.debug(pv("xcorr_argmax_indx"))

    logging.debug(pv("model_chisqr_vals"))
    print("Minimum  Chisqr value =",
          model_chisqr_vals[chisqr_argmin_indx])  # , min(model_chisqr_vals)
    print("Chisqr at max correlation value",
          model_chisqr_vals[chisqr_argmin_indx])

    print("model_xcorr_vals = {}".format(model_xcorr_vals))
    print("Maximum Xcorr value =",
          model_xcorr_vals[xcorr_argmax_indx])  # , max(model_xcorr_vals)
    print("Xcorr at min Chiqsr", model_xcorr_vals[chisqr_argmin_indx])

    logging.debug(pv("model_xcorr_rv_vals"))
    print("RV at max xcorr =", model_xcorr_rv_vals[xcorr_argmax_indx])
    # print("Median RV val =", np.median(model_xcorr_rv_vals))
    print(pv("model_xcorr_rv_vals[chisqr_argmin_indx]"))
    # print(pv("sp.stats.mode(np.around(model_xcorr_rv_vals))"))

    print("Max Correlation model = ",
          models[xcorr_argmax_indx].split("/")[-2:])
    print("Min Chisqr model = ", models[chisqr_argmin_indx].split("/")[-2:])

    limits = [2110, 2160]
    best_model = models[chisqr_argmin_indx]
    best_model_spec = load_phoenix_spectrum(best_model,
                                            limits=limits,
                                            normalize=True)
    best_model_spec = convolve_models([best_model_spec],
                                      obs_resolution,
                                      chip_limits=None)[0]

    best_xcorr_model = models[xcorr_argmax_indx]
    best_xcorr_model_spec = load_phoenix_spectrum(best_xcorr_model,
                                                  limits=limits,
                                                  normalize=True)
    best_xcorr_model_spec = convolve_models([best_xcorr_model_spec],
                                            obs_resolution,
                                            chip_limits=None)[0]

    close_model_spec = load_phoenix_spectrum(closest_model[0],
                                             limits=limits,
                                             normalize=True)
    close_model_spec = convolve_models([close_model_spec],
                                       obs_resolution,
                                       chip_limits=None)[0]

    plt.plot(observed_spectra.xaxis,
             observed_spectra.flux,
             label="Observations")
    plt.plot(best_model_spec.xaxis, best_model_spec.flux, label="Best Model")
    plt.plot(best_xcorr_model_spec.xaxis,
             best_xcorr_model_spec.flux,
             label="Best xcorr Model")
    plt.plot(close_model_spec.xaxis,
             close_model_spec.flux,
             label="Close Model")
    plt.legend()
    plt.xlim(*limits)
    plt.show()
    print("After plot")