Exemplo n.º 1
0
 def lnlike_rv():
     if len(all_rv_instruments) == 1:
         model = rv_model.pl_rv_array(xrv,parameters['mu']['object'].value,parameters['K']['object'].value,\
                         parameters['omega']['object'].value*np.pi/180.,parameters['ecc']['object'].value,\
                         parameters['t0']['object'].value,parameters['P']['object'].value)
         residuals = (yrv - model)
         taus = 1.0 / ((yerrrv)**2 +
                       (parameters['sigma_w_rv']['object'].value)**2)
         log_like = -0.5 * (
             n_data_rvs[0] * log2pi +
             np.sum(np.log(1. / taus) + taus * (residuals**2)))
         return log_like
     else:
         log_like = 0.0
         for i in range(len(all_rv_instruments)):
             model = rv_model.pl_rv_array(xrv[all_rv_instruments_idxs[i]],parameters['mu_'+all_rv_instruments[i]]['object'].value,\
                             parameters['K']['object'].value, parameters['omega']['object'].value*np.pi/180.,parameters['ecc']['object'].value,\
                             parameters['t0']['object'].value,parameters['P']['object'].value)
             residuals = (yrv[all_rv_instruments_idxs[i]] - model)
             taus = 1.0 / (
                 (yerrrv[all_rv_instruments_idxs[i]])**2 +
                 (parameters['sigma_w_rv_' +
                             all_rv_instruments[i]]['object'].value)**2)
             log_like = log_like - 0.5 * (n_data_rvs[i] * log2pi + np.sum(
                 np.log(1. / taus) + taus * (residuals**2)))
         return log_like
Exemplo n.º 2
0
 def lnlike_rv():
     if len(all_rv_instruments) == 1:
         model = rv_model.pl_rv_array(xrv,parameters['mu']['object'].value,parameters['K']['object'].value,\
                         parameters['omega']['object'].value*np.pi/180.,parameters['ecc']['object'].value,\
                         parameters['t0']['object'].value,parameters['P']['object'].value)
         residuals = (yrv-model)
         taus = 1.0/((yerrrv)**2 + (parameters['sigma_w_rv']['object'].value)**2)
         log_like = -0.5*(n_data_rvs[0]*log2pi+np.sum(np.log(1./taus)+taus*(residuals**2)))
         return log_like
     else:
         log_like = 0.0
         for i in range(len(all_rv_instruments)):
             model = rv_model.pl_rv_array(xrv[all_rv_instruments_idxs[i]],parameters['mu_'+all_rv_instruments[i]]['object'].value,\
                             parameters['K']['object'].value, parameters['omega']['object'].value*np.pi/180.,parameters['ecc']['object'].value,\
                             parameters['t0']['object'].value,parameters['P']['object'].value)
             residuals = (yrv[all_rv_instruments_idxs[i]]-model)
             taus = 1.0/((yerrrv[all_rv_instruments_idxs[i]])**2 + (parameters['sigma_w_rv_'+all_rv_instruments[i]]['object'].value)**2)
             log_like = log_like -0.5*(n_data_rvs[i]*log2pi+np.sum(np.log(1./taus)+taus*(residuals**2)))
         return log_like
Exemplo n.º 3
0
def plot_transit_and_rv(t,f,trv,rv,rv_err,parameters,ld_law,rv_jitter,transit_instruments,rv_instruments,\
                        resampling = False, phase_max = 0.025, texp = 0.01881944, N_resampling = 5):
    # Extract parameters:
    P = parameters['P']['object'].value
    inc = parameters['inc']['object'].value
    a = parameters['a']['object'].value
    p = parameters['p']['object'].value
    t0 = parameters['t0']['object'].value
    q1 = parameters['q1']['object'].value
    q2 = parameters['q2']['object'].value
    K = parameters['K']['object'].value
    ecc = parameters['ecc']['object'].value
    omega = parameters['omega']['object'].value
    all_rv_instruments,all_rv_instruments_idxs,n_data_rvs = count_instruments(rv_instruments)
    if len(all_rv_instruments)>1:
        mu = {}
        for instrument in all_rv_instruments:
            mu[instrument] = parameters['mu_'+instrument]['object'].value
    else:
        mu = parameters['mu']['object'].value

    # Get data phases:
    phases = get_phases(t,P,t0)

    # Generate model times by super-sampling the times:
    model_t = np.linspace(np.min(t),np.max(t),len(t)*2)
    model_phase = get_phases(model_t,P,t0)

    # Initialize the parameters of the transit model, 
    # and prepare resampling data if resampling is True:
    if resampling:
        idx_resampling = np.where((model_phase>-phase_max)&(model_phase<phase_max))[0]
        t_resampling = np.array([])
        for i in range(len(idx_resampling)):
            tij = np.zeros(N_resampling)
            for j in range(1,N_resampling+1):
                # Eq (35) in Kipping (2010)    
                tij[j-1] = model_t[idx_resampling[i]] + ((j - ((N_resampling+1)/2.))*(texp/np.double(N_resampling)))
            t_resampling = np.append(t_resampling, np.copy(tij))    

        idx_resampling_pred = np.where((phases>-phase_max)&(phases<phase_max))[0]
        t_resampling_pred = np.array([])
        for i in range(len(idx_resampling_pred)):
            tij = np.zeros(N_resampling)
            for j in range(1,N_resampling+1):
                tij[j-1] = t[idx_resampling_pred[i]] + ((j - ((N_resampling+1)/2.))*(texp/np.double(N_resampling)))
            t_resampling_pred = np.append(t_resampling_pred, np.copy(tij))
        params,m = init_batman(t_resampling, law=ld_law)
        params2,m2 = init_batman(t_resampling_pred, law=ld_law)
        transit_flat = np.ones(len(model_t))
        transit_flat[idx_resampling] = np.zeros(len(idx_resampling))
        transit_flat_pred = np.ones(len(t))
        transit_flat_pred[idx_resampling_pred] = np.zeros(len(idx_resampling_pred))

    else:
        params,m = init_batman(model_t,law=ld_law)
        params2,m2 = init_batman(t,law=ld_law)

    coeff1,coeff2 = reverse_ld_coeffs(ld_law, q1, q2)
    params.t0 = t0
    params.per = P
    params.rp = p
    params.a = a
    params.inc = inc
    params.ecc = ecc
    params.omega = omega
    params.u = [coeff1,coeff2]

    # Generate model and predicted lightcurves:
    if resampling:
        model = m.light_curve(params)
        for i in range(len(idx_resampling)):
            transit_flat[idx_resampling[i]] = np.mean(model[i*N_resampling:N_resampling*(i+1)])
        model_lc = transit_flat

        model = m2.light_curve(params)
        for i in range(len(idx_resampling_pred)):
            transit_flat_pred[idx_resampling_pred[i]] = np.mean(model[i*N_resampling:N_resampling*(i+1)])
        model_pred = transit_flat_pred
    else:
        model_lc = m.light_curve(params)
        model_pred = m2.light_curve(params)

    # Now plot:
    plt.style.use('ggplot')
    plt.subplot(211)
    #plt.xlabel('Phase')
    plt.title('exonailer final fit + data')
    plt.ylabel('Relative flux')
    idx = np.argsort(model_phase)
    plt.plot(phases,f,'.',color='black',alpha=0.4)
    plt.plot(model_phase[idx],model_lc[idx])
    plt.plot(phases,f-model_pred+(1-1.8*(p**2)),'.',color='black',alpha=0.4)

    plt.subplot(212)
    plt.ylabel('Radial velocity (m/s)')
    plt.xlabel('Phase')
    model_rv = rv_model.pl_rv_array(model_t,0.0,K,omega*np.pi/180.,ecc,t0,P)
    if len(all_rv_instruments)>1:
        for i in range(len(all_rv_instruments)):
            rv_phases = get_phases(trv[all_rv_instruments_idxs[i]],P,t0)
            plt.errorbar(rv_phases,(rv[all_rv_instruments_idxs[i]]-mu[all_rv_instruments[i]])*1e3,yerr=rv_err[all_rv_instruments_idxs[i]]*1e3,fmt='o',label='RVs from '+all_rv_instruments[i])
        plt.legend()
    else:
        rv_phases = get_phases(trv,P,t0)
        plt.errorbar(rv_phases,(rv-mu)*1e3,yerr=rv_err*1e3,fmt='o')
    plt.plot(model_phase[idx],(model_rv[idx])*1e3)
    plt.show()
    opt = raw_input('\t Save lightcurve and RV data and models? (y/n)')
    if opt == 'y':
        fname = raw_input('\t Output filename (without extension): ')   
        fout = open('results/'+fname+'_lc_data.dat','w')
        fout.write('# Time    Phase     Normalized flux \n')
        for i in range(len(phases)):
            fout.write(str(t[i])+' '+str(phases[i])+' '+str(f[i])+'\n')
        fout.close()
        fout = open('results/'+fname+'_lc_model.dat','w')
        fout.write('# Phase     Normalized flux \n')
        for i in range(len(model_phase[idx])):
            fout.write(str(model_phase[idx][i])+' '+str(model_lc[idx][i])+'\n')
        fout.close() 
        fout = open('results/'+fname+'_rvs_data.dat','w')
        fout.write('# Phase     RV (m/s)  Error (m/s)  Instrument\n')
        for i in range(len(all_rv_instruments)):
            rv_phases = get_phases(trv[all_rv_instruments_idxs[i]],P,t0)
            for j in range(len(rv_phases)):
                fout.write(str(rv_phases[j])+' '+str(((rv[all_rv_instruments_idxs[i]]-mu[all_rv_instruments[i]])*1e3)[j])+\
                                ' '+str(((rv_err[all_rv_instruments_idxs[i]])*1e3)[j])+\
                                ' '+all_rv_instruments[i]+'\n')
        fout.close()
        fout = open('results/'+fname+'_rvs_model.dat','w')
        fout.write('# Phase     RV (m/s) \n')
        for i in range(len(model_phase[idx])):
            fout.write(str(model_phase[idx][i])+' '+str(((model_rv[idx])*1e3)[i])+'\n')
        fout.close()
            t = np.append(t,np.mean(tsampling))
            f = np.append(f,np.mean(fsampling))
            if tcurrent >= tend:
                break
        f = f + np.random.normal(0,sigma_w[i]*1e-6,len(t))
    else:
        tstart = t0 + (tr_ncycle[i]-tr_phases[i])*P
        tend = t0 + (tr_ncycle[i]+tr_ncycles[i]+tr_phases[i])*P
        t = np.arange(tstart,tend,texp[i])
        fsampling = get_transit_model(t,\
                    t0,P,p[i],a[i],inc,q1[i],q2[i],ld_law)
        f = fsampling + np.random.normal(0,sigma_w[i]*1e-6,len(t))
    for ii in range(len(t)):
            fout_lc.write('{0:.10f} {1:.10f} {2:.10f} '.format(t[ii],f[ii],sigma_w[i]*1e-6)+tr_instrument_names[i]+'\n')

fout_lc.close()
fout_rv = open(fname_rv,'w')
# Now RV data:
for i in range(len(rv_ncycle)):
        tstart = t0 + (rv_ncycle[i])*P
        tend = t0 + (rv_ncycle[i]+rv_ncycles[i])*P
        t = np.arange(tstart,tend,rv_texp[i]) 
        t = t + np.random.uniform(-0.25,0.25,len(t))
        rvs = rv_model.pl_rv_array(t,rv_mu[i],K,\
                                omega*np.pi/180.,ecc,\
                                t0,P)
        rvs = rvs + np.random.normal(0,sigma_w_rv[i],len(t))
        for ii in range(len(t)):
            fout_rv.write('{0:.10f} {1:.10f} {2:.10f} '.format(t[ii],rvs[ii],sigma_w_rv[i])+rv_instrument_names[i]+'\n')
fout_rv.close()
Exemplo n.º 5
0
import ajplanet
from numpy import pi,arange

t = 2 * 30.433 * arange(10)/999

v0 = 0
K = 968.6
w = 189.1 * pi / 180.
e = 0.5170
t0 = 0.0
P = 5.633

K=1000.0
w=0
e=0
t0=0
P=1
t=arange(11)/10.
print t

for i in range(10):
    y = ajplanet.pl_rv(t[i], v0, K, w, e, t0, P)
    print y

res = ajplanet.pl_rv_array(t,v0, K, w, e, t0, P)
print res
Exemplo n.º 6
0
def main():
    """Main."""
    star = "HD30501"
    obsnum = "1"
    chip = 1
    obs_name = select_observation(star, obsnum, chip)

    # Load observation
    observed_spectra = load_spectrum(obs_name)
    if chip == 4:
        # Ignore first 40 pixels
        observed_spectra.wav_select(observed_spectra.xaxis[40], observed_spectra.xaxis[-1])

    # Load models
    host_spectrum_model, companion_spectrum_model = load_PHOENIX_hd30501(limits=[2100, 2200], normalize=True)

    obs_resolution = crires_resolution(observed_spectra.header)

    # Convolve models to resolution of instrument
    host_spectrum_model, companion_spectrum_model = convolve_models((host_spectrum_model, companion_spectrum_model),
                                                                    obs_resolution, chip_limits=None)

    plot_obs_with_model(observed_spectra, host_spectrum_model, companion_spectrum_model,
                        show=False, title="Before BERV Correction")

    # Berv Correct
    # Calculate the star RV relative to synthetic spectum
    #                        [mean_val, K1, omega,   e,     Tau,       Period, starmass (Msun), msini(Mjup), i]
    parameters = {"HD30501": [23.710, 1703.1, 70.4, 0.741, 53851.5, 2073.6, 0.81, 90],
                  "HD211847": [6.689, 291.4, 159.2, 0.685, 62030.1, 7929.4, 0.94, 19.2, 7]}
    try:
        host_params = parameters[star]
    except ValueError:
        print("Parameters for {} are not in parameters list. Improve this.".format(star))
        raise
    host_params[1] = host_params[1] / 1000  # Convert K! to km/s
    host_params[2] = np.deg2rad(host_params[2])  # Omega needs to be in radians for ajplanet

    obs_time = observed_spectra.header["DATE-OBS"]
    print(obs_time, isinstance(obs_time, str))
    print(obs_time.replace("T", " ").split("."))
    jd = ephem.julian_date(obs_time.replace("T", " ").split(".")[0])
    host_rv = pl_rv_array(jd, *host_params[0:6])[0]
    print("host_rv", host_rv, "km/s")

    offset = -host_rv
    # offset = 0
    _berv_corrected_observed_spectra = barycorr_crires_spectrum(observed_spectra, offset)  # Issue with air/vacuum
    # This introduces nans into the observed spectrum
    berv_corrected_observed_spectra.wav_select(*berv_corrected_observed_spectra.xaxis[
        np.isfinite(berv_corrected_observed_spectra.flux)][[0, -1]])
    # Shift to star RV

    plot_obs_with_model(berv_corrected_observed_spectra, host_spectrum_model,
                        companion_spectrum_model, title="After BERV Correction")

    # print("\nWarning!!!\n BERV is not good have added a offset to get rest working\n")

    # Chisquared fitting
    alphas = 10 ** np.linspace(-4, 0.1, 100)
    rvs = np.arange(-50, 50, 0.05)

    # chisqr_store = np.empty((len(alphas), len(rvs)))
    observed_limits = [np.floor(berv_corrected_observed_spectra.xaxis[0]),
                       np.ceil(berv_corrected_observed_spectra.xaxis[-1])]
    print("Observed_limits ", observed_limits)

    n_jobs = 1
    if n_jobs is None:
        n_jobs = mprocess.cpu_count() - 1
    start_time = dt.now()

    if np.all(np.isnan(host_spectrum_model.flux)):
        print("Host spectrum is all Nans")
    if np.all(np.isnan(companion_spectrum_model.flux)):
        print("Companion spectrum is all Nans")

    print("Now performing the Chisqr grid analaysis")
    obs_chisqr_parallel = parallel_chisqr(alphas, rvs, berv_corrected_observed_spectra, alpha_model2,
                                          (host_spectrum_model, companion_spectrum_model,
                                           observed_limits, berv_corrected_observed_spectra), n_jobs=n_jobs)
    # chisqr_parallel = parallel_chisqr(alphas, rvs, simlulated_obs, alpha_model, (org_star_spec,
    #                                   org_bd_spec, new_limits), n_jobs=4)

    end_time = dt.now()
    print("Time to run parallel chisquared = {}".format(end_time - start_time))
    # Plot memmap
    # plt.subplot(2, 1, 1)
    x, y = np.meshgrid(rvs, alphas)
    fig = plt.figure(figsize=(7, 7))
    cf = plt.contourf(x, y, np.log10(obs_chisqr_parallel.reshape(len(alphas), len(rvs))), 100)
    fig.colorbar(cf)
    plt.title("Sigma chisquared")
    plt.ylabel("Flux ratio")
    plt.xlabel("RV (km/s)")
    plt.show()

    # Locate minimum and plot resulting model next to observation
    def find_min_chisquared(x, y, z):
        """Find minimum vlaue in chisqr grid."""
        min_loc = np.argmin(z)
        print("min location", min_loc)

        x_sol = x.ravel()[min_loc]
        y_sol = y.ravel()[min_loc]
        z_sol = z.ravel()[min_loc]
        return x_sol, y_sol, z_sol, min_loc

    rv_solution, alpha_solution, min_chisqr, min_loc = find_min_chisquared(x, y, obs_chisqr_parallel)
    print("Minium Chisqr value {2}\n RV sol = {0}\nAlpha Sol = {1}".format(rv_solution, alpha_solution, min_chisqr))

    solution_model = alpha_model2(alpha_solution, rv_solution, host_spectrum_model, companion_spectrum_model,
                                  observed_limits)
    # alpha_model2(alpha, rv, host, companion, limits, new_x=None):

    plt.plot(solution_model.xaxis, solution_model.flux, label="Min chisqr solution")
    plt.plot(berv_corrected_observed_spectra.xaxis, berv_corrected_observed_spectra.flux, label="Observation")
    plt.legend(loc=0)
    plt.show()

    # Dump the results into a pickle file
    pickle_path = "/home/jneal/.chisqrpickles/"
    pickle_name = "Chisqr_results_{0}_{1}_chip_{2}.pickle".format(star, obsnum, chip)
    with open(os.path.join(pickle_path, pickle_name), "wb") as f:
        # Pickle all the necessary parameters to store.
        pickle.dump((rvs, alphas, berv_corrected_observed_spectra, host_spectrum_model, companion_spectrum_model,
                     rv_solution, alpha_solution, min_chisqr, min_loc, solution_model), f)
Exemplo n.º 7
0
def plot_transit_and_rv(t,f,trv,rv,rv_err,parameters,ld_law,rv_jitter,transit_instruments,rv_instruments,\
                        resampling = False, phase_max = 0.025, texp = 0.01881944, N_resampling = 5):
    # Extract parameters:
    P = parameters['P']['object'].value
    inc = parameters['inc']['object'].value
    a = parameters['a']['object'].value
    p = parameters['p']['object'].value
    t0 = parameters['t0']['object'].value
    q1 = parameters['q1']['object'].value
    q2 = parameters['q2']['object'].value
    K = parameters['K']['object'].value
    ecc = parameters['ecc']['object'].value
    omega = parameters['omega']['object'].value
    all_rv_instruments, all_rv_instruments_idxs, n_data_rvs = count_instruments(
        rv_instruments)
    if len(all_rv_instruments) > 1:
        mu = {}
        for instrument in all_rv_instruments:
            mu[instrument] = parameters['mu_' + instrument]['object'].value
    else:
        mu = parameters['mu']['object'].value

    # Get data phases:
    phases = get_phases(t, P, t0)

    # Generate model times by super-sampling the times:
    model_t = np.linspace(np.min(t), np.max(t), len(t) * 2)
    model_phase = get_phases(model_t, P, t0)

    # Initialize the parameters of the transit model,
    # and prepare resampling data if resampling is True:
    if resampling:
        idx_resampling = np.where((model_phase > -phase_max)
                                  & (model_phase < phase_max))[0]
        t_resampling = np.array([])
        for i in range(len(idx_resampling)):
            tij = np.zeros(N_resampling)
            for j in range(1, N_resampling + 1):
                # Eq (35) in Kipping (2010)
                tij[j - 1] = model_t[idx_resampling[i]] + (
                    (j - ((N_resampling + 1) / 2.)) *
                    (texp / np.double(N_resampling)))
            t_resampling = np.append(t_resampling, np.copy(tij))

        idx_resampling_pred = np.where((phases > -phase_max)
                                       & (phases < phase_max))[0]
        t_resampling_pred = np.array([])
        for i in range(len(idx_resampling_pred)):
            tij = np.zeros(N_resampling)
            for j in range(1, N_resampling + 1):
                tij[j - 1] = t[idx_resampling_pred[i]] + (
                    (j - ((N_resampling + 1) / 2.)) *
                    (texp / np.double(N_resampling)))
            t_resampling_pred = np.append(t_resampling_pred, np.copy(tij))
        params, m = init_batman(t_resampling, law=ld_law)
        params2, m2 = init_batman(t_resampling_pred, law=ld_law)
        transit_flat = np.ones(len(model_t))
        transit_flat[idx_resampling] = np.zeros(len(idx_resampling))
        transit_flat_pred = np.ones(len(t))
        transit_flat_pred[idx_resampling_pred] = np.zeros(
            len(idx_resampling_pred))

    else:
        params, m = init_batman(model_t, law=ld_law)
        params2, m2 = init_batman(t, law=ld_law)

    coeff1, coeff2 = reverse_ld_coeffs(ld_law, q1, q2)
    params.t0 = t0
    params.per = P
    params.rp = p
    params.a = a
    params.inc = inc
    params.ecc = ecc
    params.omega = omega
    params.u = [coeff1, coeff2]

    # Generate model and predicted lightcurves:
    if resampling:
        model = m.light_curve(params)
        for i in range(len(idx_resampling)):
            transit_flat[idx_resampling[i]] = np.mean(
                model[i * N_resampling:N_resampling * (i + 1)])
        model_lc = transit_flat

        model = m2.light_curve(params)
        for i in range(len(idx_resampling_pred)):
            transit_flat_pred[idx_resampling_pred[i]] = np.mean(
                model[i * N_resampling:N_resampling * (i + 1)])
        model_pred = transit_flat_pred
    else:
        model_lc = m.light_curve(params)
        model_pred = m2.light_curve(params)

    # Now plot:
    plt.style.use('ggplot')
    plt.subplot(211)
    #plt.xlabel('Phase')
    plt.title('exonailer final fit + data')
    plt.ylabel('Relative flux')
    idx = np.argsort(model_phase)
    plt.plot(phases, f, '.', color='black', alpha=0.4)
    plt.plot(model_phase[idx], model_lc[idx])
    plt.plot(phases,
             f - model_pred + (1 - 1.8 * (p**2)),
             '.',
             color='black',
             alpha=0.4)

    plt.subplot(212)
    plt.ylabel('Radial velocity (m/s)')
    plt.xlabel('Phase')
    model_rv = rv_model.pl_rv_array(model_t, 0.0, K, omega * np.pi / 180., ecc,
                                    t0, P)
    if len(all_rv_instruments) > 1:
        for i in range(len(all_rv_instruments)):
            rv_phases = get_phases(trv[all_rv_instruments_idxs[i]], P, t0)
            plt.errorbar(
                rv_phases,
                (rv[all_rv_instruments_idxs[i]] - mu[all_rv_instruments[i]]) *
                1e3,
                yerr=rv_err[all_rv_instruments_idxs[i]] * 1e3,
                fmt='o',
                label='RVs from ' + all_rv_instruments[i])
        plt.legend()
    else:
        rv_phases = get_phases(trv, P, t0)
        plt.errorbar(rv_phases, (rv - mu) * 1e3, yerr=rv_err * 1e3, fmt='o')
    plt.plot(model_phase[idx], (model_rv[idx]) * 1e3)
    plt.show()
    opt = raw_input('\t Save lightcurve and RV data and models? (y/n)')
    if opt == 'y':
        fname = raw_input('\t Output filename (without extension): ')
        fout = open('results/' + fname + '_lc_data.dat', 'w')
        fout.write('# Time    Phase     Normalized flux \n')
        for i in range(len(phases)):
            fout.write(
                str(t[i]) + ' ' + str(phases[i]) + ' ' + str(f[i]) + '\n')
        fout.close()
        fout = open('results/' + fname + '_lc_model.dat', 'w')
        fout.write('# Phase     Normalized flux \n')
        for i in range(len(model_phase[idx])):
            fout.write(
                str(model_phase[idx][i]) + ' ' + str(model_lc[idx][i]) + '\n')
        fout.close()
        fout = open('results/' + fname + '_rvs_data.dat', 'w')
        fout.write('# Phase     RV (m/s)  Error (m/s)  Instrument\n')
        for i in range(len(all_rv_instruments)):
            rv_phases = get_phases(trv[all_rv_instruments_idxs[i]], P, t0)
            for j in range(len(rv_phases)):
                fout.write(str(rv_phases[j])+' '+str(((rv[all_rv_instruments_idxs[i]]-mu[all_rv_instruments[i]])*1e3)[j])+\
                                ' '+str(((rv_err[all_rv_instruments_idxs[i]])*1e3)[j])+\
                                ' '+all_rv_instruments[i]+'\n')
        fout.close()
        fout = open('results/' + fname + '_rvs_model.dat', 'w')
        fout.write('# Phase     RV (m/s) \n')
        for i in range(len(model_phase[idx])):
            fout.write(
                str(model_phase[idx][i]) + ' ' +
                str(((model_rv[idx]) * 1e3)[i]) + '\n')
        fout.close()