def pulse_profile(f_pulse, times, counts, shift, no_phase_bins): """ Calculating the pulse profile for the observation. Goes from 0 to 2! Thoughts on 1/14/2020: I wonder if the count rate is calculated from times[-1]-times[0]? If so, this is WRONG! I should be using the total from the GTIs! f_pulse - the frequency of the pulse times - the array of time values counts - the array of counts values shift - how much to shift the pulse by in the phase axis. It only affects how it is presented. no_phase_bins - number of phase bins desired """ period = 1 / f_pulse phases = foldAt(times, period, T0=shift * period) index_sort = np.argsort(phases) phases = list(phases[index_sort]) + list(phases[index_sort] + 1) counts = list(counts[index_sort]) * 2 phase_bins = np.linspace(0, 2, no_phase_bins * 2 + 1) summed_profile, bin_edges, binnumber = stats.binned_statistic( phases, counts, statistic='mean', bins=phase_bins) return phases, phase_bins, summed_profile
def compute_nRV_GP(GPtheta, keptheta, sigRV_phot, sigK_target, duration=100): assert len(GPtheta) == 5 assert len(keptheta) == 2 a, l, G, Pgp, s = GPtheta P, K = keptheta # search for target sigma by iterating over Nrv coarsely Nrvs = np.arange(10, 1001, 90) sigKs = np.zeros(Nrvs.size) for i in range(Nrvs.size): # get rv activity model gp = george.GP(a*(george.kernels.ExpSquaredKernel(l) + \ george.kernels.ExpSine2Kernel(G,Pgp))) t = _uniform_window_function(duration, Nrvs[i]) erv = np.repeat(sigRV_phot, t.size) gp.compute(t, np.sqrt(erv**2 + s**2)) rv_act = gp.sample(t) # get planet model rv_kep = -K*np.sin(2*np.pi*foldAt(t, P)) # get total rv signal with noise rv = rv_act + rv_kep + np.random.randn(t.size) * sigRV_phot # compute sigK theta = P, 0, K, a, l, G, Pgp, s sigKs[i] = compute_sigmaK_GP(theta, t, rv, erv) # fit powerlaw in log space to estimate Nrv for the target sigK g = np.isfinite(sigKs) p = np.poly1d(np.polyfit(np.log(sigKs[g]), np.log(Nrvs[g]), 1)) Nrv = np.exp(p(np.log(sigK_target))) return Nrv
def sanity_foldAtExample(self): """ Checking `flotAt` example. """ from PyAstronomy.pyasl import foldAt import matplotlib.pylab as plt import numpy as np # Generate some data ... time = np.random.random(1000) * 100. flux = 0.05 * np.sin(time*(2.*np.pi/21.5) + 15) # ... and add some noise flux += np.random.normal(0, 0.02, len(flux)) # Obtain the phases with respect to some # reference point (in this case T0=217.4) phases = foldAt(time, 21.5, T0=217.4) # Sort with respect to phase # First, get the order of indices ... sortIndi = np.argsort(phases) # ... and, second, rearrange the arrays. phases = phases[sortIndi] flux = flux[sortIndi] # Plot the result plt.plot(phases, flux, 'bp')
def pholdata(npjdmag, P): phases = foldAt(npjdmag[:, 0], P) sortIndi = np.argsort(phases) phases = phases[sortIndi] resultmag = npjdmag[:, 1][sortIndi] return phases, resultmag
def stringlength_dat(x, m, tps, norm='default', isFreq=False, closed=True): """ Compute string length for data set. Parameters ---------- x, m : arrays x and y coordinates of data points. tps : tuple or array The trial periods (or frequencies): Either a three-tuple specifying (pmin, pmax, nperiods) used by numpy's linspace or an array of trial periods. If isFreq is True, tps is interpreted as frequencies. isFreq : boolean, optional If True, the input tps will be assumed to refer to frequencies instead of periods. norm : string, {default, no} If 'default' (default), the data points (mi) will be renormalized according to Eq. 3 in Dworetsky 1983, i.e., using mnew = (mi - min(m)) / (2*(max(m) - min(m))). If 'no' is specified, the data will not be changed. closed : boolean, optional If True (default), first and last point on the phase axis will be connected (close the loop). Returns ------- Trial periods/frequencies : array The tested periods (or frequencies if isFreq is True). String length : array Associated string lengths """ if isinstance(tps, tuple) and len(tps) == 3: pers = np.linspace(*tps) elif isinstance(tps, np.ndarray): pers = tps else: raise(PE.PyAValError("Unrecognized specification of trial periods or frequencies (tps).", \ where="stringlength_dat")) if isFreq: # The input is frequencies. Still need the periods. pers = 1.0 / pers ms = stringlength_norm(m, norm) sls = np.zeros(len(pers)) for i, p in enumerate(pers): phase = pyasl.foldAt(x, p) indi = np.argsort(phase) sls[i] = stringlength_pm(phase[indi], ms[indi], norm='no', closed=closed) if isFreq: return 1.0 / pers, sls return pers, sls
def ztf_2(CSV_FILE_PATH, P): dfdata = pd.read_csv(CSV_FILE_PATH) hjd = dfdata['HJD'] mag = dfdata['mag'] rg = dfdata['band'].value_counts() try: lenr = rg['r'] except: return [0, 0], 0, 0 nphjd = np.array(hjd) npmag = np.array(mag) hang = rg['g'] nphjd = nphjd[hang:] npmag = npmag[hang:] - np.mean(npmag[hang:]) phases = foldAt(nphjd, P) sortIndi = np.argsort(phases) phases = phases[sortIndi] resultmag = npmag[sortIndi] listmag = resultmag.tolist() listmag.extend(listmag) listphrase = phases.tolist() listphrase.extend(listphrase + np.max(1)) dexin = int(1 * lenr / 2) indexmag = listmag.index(max(listmag[0:dexin])) nplistphrase = np.array(listphrase) nplistphrase = nplistphrase - nplistphrase[indexmag] nplistmag = np.array(listmag) phasemag = np.vstack((nplistphrase, nplistmag)) #纵向合并矩阵 phasemag = phasemag.T phasemag = phasemag[phasemag[:, 0] >= 0] phasemag = phasemag[phasemag[:, 0] <= 1] #去除异常点 mendata = np.mean(phasemag[:, 1]) stddata = np.std(phasemag[:, 1]) sigmamax = mendata + 4 * stddata sigmamin = mendata - 4 * stddata phasemag = phasemag[phasemag[:, 1] > sigmamin] phasemag = phasemag[phasemag[:, 1] < sigmamax] dmag1 = np.diff(phasemag, 2).std() / np.sqrt(6) dmag2 = np.diff(phasemag, 2).std() / np.sqrt(6) return phasemag, dmag1, dmag2
def get_phases(eventfile, f_pulse, shift): """ Folding the time series by the pulse frequency to obtain phase values eventfile - path to the event file. f_pulse - the frequency of the pulse shift - how much to shift the pulse by in the phase axis. """ raw_times = fits.open(eventfile)[1].data['TIME'] times = raw_times - raw_times[0] period = 1 / f_pulse phases = foldAt(times, period, T0=shift * period) return phases
def PhaseFolderOfAwesomeness(): global phases, data2 # Obtain the phases with respect to some # reference point (in this case T0=first centroid time plus a half-period) phases = foldAt(time, period, T0=(koi.koi_time0bk + period / 2)) # Sort with respect to phase # First, get the order of indices ... sortIndi = np.argsort(phases) # ... and, second, rearrange the arrays. phases = phases[sortIndi] data2 = data[sortIndi] # Plot the result fig = plt.figure(figsize=(21, 16)) ax = fig.add_axes([0.05, 0.1, 0.8, 0.85]) plt.hlines(1.000000, 0, 1, 'r', label="Normalized Flux") plt.title("Phase-Folded Light Curves for {}".format(koi)) plt.xlabel("Phase Position ( 0 to 1)") plt.ylabel("Normalized Flux") plt.plot(phases, data2, 'bp') plt.ylim(ymax=1.007, ymin=np.nanmin(data2)) try: hours = period % int(period) * 24 minutes = hours % int(hours) * 60 seconds = minutes % int(minutes) * 60 txt3 = str( str(int(period)) + " d : " + str(int(hours)) + ' m: ' + str(int(seconds)) + ' s') except ZeroDivisionError: txt3 = period myTimeZone = str(strftime("%z", gmtime())) charText = " CHARACTERISTICS \n\nPeriod: {} days \n {}\n\nFirst Centroid: {}d\n\nDispostion: {}\n\nNext Predicted Transit (UTC):\n {}".format( round(period, 3), txt3, round(koi.koi_time0bk, 3), koi.koi_disposition, FindNextEclipse().iso) plt.figtext(0.865, .76, charText, color='black', backgroundcolor='white', weight='roman', size=14) plt.legend() plt.show()
def setup_simv2(bjd0, Ms, Ps, ePs, T0s, eT0s, mps, emps, eccs, incs_deg, outname, interval_yrs, NRhill_to_stop=1, random=True, DeltaOmegamax=180): '''Create a simulation of a 2-planet system with custom input for the planetary parameters in the form of 1d arrays. example T0s = np.array([7264.49, 7264.39142]) ''' # Initialize sim = rebound.Simulation() sim.integrator = "whfast" sim.units = ('AU','Msun','yr') sim.automateSimulationArchive('%s.bin'%outname, interval=interval_yrs, deletefile=True) # Get keplerian parameters Psin, ePs = np.ascontiguousarray(Ps) + 0, np.ascontiguousarray(ePs) assert Ps[0] < Ps[1] Ps, Ks = np.zeros(2), np.zeros(2) while np.any(Ps<=0): Ps = Psin if random: Ps += np.array([np.random.randn()*ePs[0], np.random.randn()*ePs[1]]) if random: T0s += 2450000 + np.array([np.random.randn()*eT0s[0], np.random.randn()*eT0s[1]]) if random: mps += np.array([np.random.randn()*emps[0], np.random.randn()*emps[1]]) smas =rvs.semimajoraxis(Ps, Ms, mps) mps = rvs.kg2Msun(rvs.Mearth2kg(mps)) nplanets = Ps.size omegas = np.random.uniform(-np.pi, np.pi, nplanets) Omegas = np.random.uniform(-np.pi, np.pi, nplanets) thetas = 2*np.pi * foldAt(bjd0, Ps, T0s) - np.pi # Add star sim.add(m=Ms, hash='star') # Add planets for i in range(nplanets): sim.add(m=mps[i], a=smas[i], inc=np.deg2rad(incs_deg[i]-90), e=eccs[i], omega=omegas[i], Omega=Omegas[i], theta=thetas[i]) sim.move_to_com() RHill = (mps.sum()/(3.*Ms))**(1./3) * smas.mean() sim.exit_min_distance = float(RHill) * NRhill_to_stop return sim
def _compute_Fisher_information_GP(theta, t_arr, rv_arr, erv_arr): '''Compute the Fisher information matrix term-by-term for a circular keplerian RV model and a QP GP red noise model. theta = list of parameter values (P, T0, Krv, a, l, G, Pgp, s) ''' # get orbital phase array assert len(theta) == 8 P, T0 = theta[:2] sort = np.argsort(t_arr) t_arr, rv_arr, erv_arr = t_arr[sort], rv_arr[sort], erv_arr[sort] rv_arr -= np.median(rv_arr) # roughly center on zero phi_arr = 2*np.pi * foldAt(t_arr, P, T0) thetavals = theta[2:] # define variables Krv, a, l, G, P, s = sympy.symbols('Krv a lambda Gamma P s') symbol_vals = Krv, a, l, G, P, s assert len(symbol_vals) == len(thetavals) # define time-series symbols dt, phi, rv, erv, deltafunc = sympy.symbols('dt phi RV sigma delta') y = rv - (-Krv * sympy.sin(phi)) # residual vector # compute QP covariance function k = a*a*sympy.exp(-.5*dt**2 / l**2 - G*G*sympy.sin(np.pi*abs(dt)/P)**2) + \ deltafunc * (erv**2 + s**2) symbol_arrs = dt, phi, rv, erv, y, k, deltafunc # get arrays Kinv = np.linalg.inv(_covariance_matrix(theta[3:], t_arr, erv_arr)) thetaarrs = t_arr, phi_arr, rv_arr, erv_arr, Kinv # compute the element-wise Fisher matrix Nparams = len(thetavals) B = np.zeros((Nparams, Nparams)) for i in range(Nparams): for j in range(Nparams): if i > j: B[i,j] = B[j,i] else: B[i,j] = _compute_Fisher_entry(symbol_vals[i], symbol_vals[j], symbol_vals, symbol_arrs, thetavals, thetaarrs) return B
def pulse_profile(f_pulse, times, counts, shift, no_phase_bins): """ Calculating the pulse profile for the observation. Goes from 0 to 2! f_pulse - the frequency of the pulse times - the array of time values counts - the array of counts values shift - how much to shift the pulse by in the phase axis. It only affects how it is presented. no_phase_bins - number of phase bins desired """ period = 1 / f_pulse phases = foldAt(times, period, T0=shift * period) index_sort = np.argsort(phases) phases = list(phases[index_sort]) + list(phases[index_sort] + 1) counts = list(counts[index_sort]) * 2 phase_bins = np.linspace(0, 2, no_phase_bins * 2 + 1) summed_profile, bin_edges, binnumber = stats.binned_statistic( phases, counts, statistic='sum', bins=phase_bins) return phases, phase_bins, summed_profile
"""# Investigating TOIs ## Check periodicity """ !pip install PyAstronomy from PyAstronomy.pyasl import foldAt period = 0.2185 dur = np.nanmax(time1) - np.nanmin(time1) # Obtain the phases with respect to some # reference point phases = foldAt(time1[1:], period, T0=np.nanmin(time1)) # Sort with respect to phase # First, get the order of indices ... sortIndi = np.argsort(phases) # ... and, second, rearrange the arrays. phases = phases[sortIndi] # Plot the result plt.plot(phases-0.5, flux1norm[sortIndi], 'k.') plt.plot(phases+0.5, flux1norm[sortIndi], 'k.') #plt.plot(p-0.5, quadfit, c='cyan') #plt.plot(p+0.5, quadfit, c='cyan') plt.xlabel('Phase') plt.ylabel('Standardized Flux')
path = 'E:\\shunbianyuan\\phometry\\pipelinecode\\pipeline\\LiXZ\\kongphometry\\' #path = 'E:\\shunbianyuan\\phometry\\pipelinecode\\pipeline\\LiXZ\\psfphpmetry\\' light = np.loadtxt(path+'arrayjiaocha.txt') time = np.loadtxt(path+'datatime.txt') hang = 0 flux = light[hang,2:] plt.figure(0) plt.plot(time, flux, '.') ax = plt.gca() ax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边 ax.invert_yaxis() #y轴反向 phases = foldAt(time, 0.4263955927751531) sortIndi = np.argsort(phases) # ... and, second, rearrange the arrays. phases = phases[sortIndi] flux = flux[sortIndi] plt.figure(1) plt.plot(phases, flux, '.') ax = plt.gca() ax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边 ax.invert_yaxis() #y轴反向 plt.xlabel('Phrase',fontsize=14) plt.ylabel('mag',fontsize=14) '''
#plt.semilogy(freqs[1:int(N/2)],power_spec[1:int(N/2)]/np.mean(power_spec[1:int(N/2)]),'r-') #plt.xlabel('Hz') #plt.ylabel('Some normalized power spectrum') #plt.xlim([29.632,29.634]) #plt.axvline(x=29.63271,color='k',alpha=0.5,lw=0.5) ############################################################################### ############################ FOLDING LIGHT CURVE ############################## ############################################################################### #https://www.hs.uni-hamburg.de/DE/Ins/Per/Czesla/PyA/PyA/pyaslDoc/aslDoc/folding.html from PyAstronomy.pyasl import foldAt #f_pulsation = 29.63271 f_pulsation = 0.208 period = 1.0 / f_pulsation phases = foldAt(times_1, period, T0=0.45 * period) # index_sort = np.argsort(phases) phases = list(phases[index_sort]) + list(phases[index_sort] + 1) counts = list(counts_1[index_sort]) * 2 phase_bins = np.linspace(0, 2, 1001) summed_phases, bin_edges, binnumber = stats.binned_statistic(phases, counts, statistic='sum', bins=phase_bins) # plt.figure(figsize=(10, 8)) # plt.plot(phase_bins[:-1], summed_phases, 'rx')
def setup_sim(Ms, planettheta, bjd0, randomOmega=True, eccupperlim=0): ''' Setup a simulation with a central star and planets. Parameters ---------- `Ms` : float The mass of the central star in solar masses. `planettheta` : tuple of dict Tuple containing 5 or 6 dictionaries of each planet's 1) orbital period in days, 2) time of inferior conjuction in BJD, 3) RV semi-amplitude in m/s, 4) h = sqrt(e)*cos(omega), 5) k = sqrt(e)*sin(omega). If there are 6 dictionaries, the sixth and last is 6) orbital inclination in degrees. `bjd0` : scalar Reference epoch to begin the simulation at. `randomOmega` : bool If True, randomly sample the value of each planet's longitude of the ascending node from U(0,2pi). `eccupperlim` : float The upper limit of eccentricities to sample from. If `eccupperlim` is 0, then don't resample the eccentricities. Returns ------- `sim` : rebound simulation object The rebound.Simulation containing the all injected particles. Example ------- >>> Ms, planettheta = .1, initialize_system_parameters() >>> sim = setup_sim(Ms, planettheta, 2450000) ''' # Initialize simulation sim = rebound.Simulation() sim.integrator = "whfast" sim.units = ('AU', 'Msun', 'yr') # Set timestep if len(planettheta) == 5: Ps, T0s, Ks, hs, ks = planettheta incs = {} for p in Ps.keys(): incs[p] = 90. else: Ps, T0s, Ks, hs, ks, incs = planettheta hs, ks = np.array(hs.values()), np.array(ks.values()) eccstmp, omegastmp = hs * hs + ks * ks, np.arctan2(ks, hs) eccs, omegas, ind = {}, {}, 0 for p in Ps.keys(): eccs[p], omegas[p] = eccstmp[ind], omegastmp[ind] ind += 1 # Add star sim.add(m=Ms, hash='star') # Add planets for p in Ps.keys(): print Ps[p], Ms, Ks[p], eccs[p] mp = rvs.kg2Msun( rvs.Mearth2kg(rvs.RV_mp(Ps[p], Ms, Ks[p], ecc=eccs[p]))) Pp = Ps[p] ap = rvs.m2AU(rvs.semimajoraxis(Pp, Ms, 0)) thetap = 2 * np.pi * foldAt(bjd0, Pp, T0s[p]) eccp, omegap, incp = eccs[p], omegas[p], np.deg2rad(incs[p]) if eccupperlim != 0: eccp = np.random.uniform(0, eccupperlim) omegap = np.random.uniform(0, 2 * np.pi) Omegap = np.random.uniform(0, 2 * np.pi) if randomOmega else 0. sim.add(m=mp, a=ap, inc=incp, e=eccp, omega=omegap, Omega=Omegap, theta=thetap, hash=p) sim.move_to_com() return sim
if (file == "comp.dat"): ct = np.loadtxt(root + '/' + file)[0] #Loads composite light curve information cv = np.loadtxt(root + '/' + file)[1] t0 = np.min(ct) if not os.path.isfile( root + '/pgram.dat' ): #Computes Generalised L-S periodogram if it doesn't exist frequency, power = LombScargle( ct * u.day, cv * u.mag).autopower(minimum_frequency=2 / ((np.max(ct) - np.min(ct)) * u.day)) np.savetxt(root + '/pgram.dat', (power, frequency)) else: #If pgram.dat exists, this star has been looked at so skip continue P = foldAt(ct * u.day, 1 / frequency[np.argmax(power)] ) #Phase-folds on day at maximum power maxp = 1 / frequency[np.argmax(power)] pout, pcov = cf( curve, P, cv) #Least-squares fit sine wave to phase-folded LC perr = np.sqrt( np.diag(pcov)) #Square root of diag(covariance) for errors bins = bn( P, cv, statistic='median', bins=15) #Sets up 15 bins to plot general form of pfolded LC binsites = np.array([]) for i in range(len(bins[1]) - 1): binsites = np.append(binsites, np.median([bins[1][i], bins[1][i + 1]])) f, ([ax1, ax2], [ax3, ax4]) = plt.subplots(2, 2, sharex=False,
lighttime = np.loadtxt(pathfile) light = lighttime[1,:] time = lighttime[0,:] hang = 0 flux = light plt.figure(0) plt.plot(time, flux, '.') ax = plt.gca() ax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边 ax.invert_yaxis() #y轴反向 phases = foldAt(time, 0.6025294184988582) sortIndi = np.argsort(phases) # ... and, second, rearrange the arrays. phases = phases[sortIndi] flux = flux[sortIndi] plt.figure(1) plt.plot(phases, flux, '.') ax = plt.gca() ax.yaxis.set_ticks_position('left') #将y轴的位置设置在右边 ax.invert_yaxis() #y轴反向 plt.xlabel('Phrase',fontsize=14) plt.ylabel('mag',fontsize=14) '''
''' fig = plt.figure(figsize=(10, 10)) plt.clf() plt.errorbar(time, Radial_Velocity, marker='o', color='red', label='Data', linestyle='') plt.errorbar(time, model_full, color='blue', label='Model') plt.xlabel('time [days]', fontsize=18) plt.ylabel('RV [m/s]', fontsize=18) plt.title('Raw Data vs Model', fontsize=22) plt.legend(numpoints=1) plt.draw() plt.show() ''' #phase-fold phases = foldAt(time, 4.23, T0=0.) # folds at the Period found sortIndi = sp.argsort(phases) # sorts the points Phases = phases[sortIndi] # gets the indices so we sort the RVs correspondingly(?) rv_phased = Radial_Velocity[sortIndi] err_phased = Err[sortIndi] time_phased = Phases * 4.23 #After anti-logging P!!! model_phased = model(65, 4.23, 2.05, 2.05, 0.00, -9.3, 6.099, time_phased) fig2 = plt.figure(figsize=(10, 10)) plt.clf() plt.errorbar(time_phased, rv_phased, err_phased, color='red', marker='o', linestyle="", label='Data') plt.errorbar(time_phased, model_phased, color='blue', label='Model') plt.xlabel('time [days]', fontsize=18) plt.ylabel('RV [m/s]', fontsize=18)
print(psd[psd>=0.98*np.max(psd)],freq[psd>=0.98*np.max(psd)]) plt.figure() plt.plot(freq,psd,'rx-') plt.xlabel('Frequency (Hz)',fontsize=12) plt.ylabel('Normalized Power',fontsize=12) plt.axhline(y=prob3,lw=0.5,alpha=0.5) plt.axhline(y=prob4,lw=0.5,alpha=0.5) plt.axhline(y=prob5,lw=0.5,alpha=0.5) plt.show() """ nphase = 20 ##### using foldAt phases = foldAt(x, pb, T0=0) ##### using phase mod 1 phase_mod = (1 / pb * x) % 1 #or shift by -0.7*pb ##### using stingray.pulse.pulsar phase_stingray = pulse_phase(x, [1 / pb]) #,ph0=1-0.7) expocorr = Lv2_phase.phase_exposure(times[0] - times[0], times[-1] - times[0], period=pb, nbin=nphase, gtis=gtis_conform) ################################################################################
rg = dfdata['band'].value_counts() lenr = rg['r'] nphjd = np.array(hjd) npmag = np.array(mag) #hang = 151 #nphjd = nphjd[0:hang] #npmag = npmag[0:hang]-np.mean(npmag[0:hang]) hang = rg['g'] nphjd = nphjd[hang:] npmag = npmag[hang:]-np.mean(npmag[hang:]) P = 0.2557214 phases = foldAt(nphjd, P) sortIndi = np.argsort(phases) phases = phases[sortIndi] resultmag = npmag[sortIndi] plt.figure(5) plt.plot(phases, resultmag,'.') ax1 = plt.gca() ax1.yaxis.set_ticks_position('left') #将y轴的位置设置在右边 ax1.invert_yaxis() #y轴反向 listmag = resultmag.tolist() listmag.extend(listmag) listphrase = phases.tolist() #listphrase.extend(listphrase+np.max(listphrase))
period = pardict[f'planet{i}_period'] corrected_data = np.array(data_noact) # Substract contribution of the other planets for j in range(1, nplanets + 1): if j == i: continue model_planet = mod.modelk(pardict, np.array(data['rjd']), planet=str(j)) corrected_data -= model_planet prediction = mod.modelk(pardict, np.array(data['rjd']), planet=str(i)) # Calculate reference point with maximum t_ref = np.array(data['rjd'])[np.argmax(prediction)] phases = foldAt(np.array(data['rjd']), period, T0=t_ref) sortIndi = np.argsort(phases) # Sort by phase idx = names[round(period, 0)][1] # Get index for each planet name = names[round(period, 0)][0] # Get name for each planet # Plot data and prediction in corresponding subplot # H03 data in scralet red err03 = np.sqrt(data['svrad'][:239]**2 + pardict['harps_jitter']**2) ax[idx].errorbar(phases[:239], corrected_data[:239], yerr=err03, fmt='.', color='xkcd:scarlet', elinewidth=1, barsabove=True)
def mcmc(Time, Radial_Velocity, Err, limits, nwalkers=30, chainlength=40, BURNIN=True, CHAINS=True, POST= True, CORNER=True, PHASEFOLD=True, SAVE=True): global pbar start_chrono = chrono.time() # Chronometer ndim = 7 # 28000 con nwalkers = 100, chainlength = 300 chain_length = chainlength * nwalkers print('The chain length is = '+str(chain_length)) if BURNIN: burn_out = nwalkers*chain_length // 10 pbar=tqdm(total= nwalkers*chain_length - burn_out) else: pbar=tqdm(total= nwalkers*chain_length) ################################## # Run the Sampler # # Evenly spaced over the prior # ################################## pos = [np.zeros(ndim) for i in range(nwalkers)] k = 0 #Create the starting positions!! for j in xrange(0, ndim): if j > 0: k += 2 fact = np.absolute(limits[k] - limits[k+1])/nwalkers dif = np.arange(nwalkers) * fact for i in xrange(0, nwalkers): pos[i][j] = limits[k] + (dif[i] + fact/2.0) print("The MCMC Starting Positions for Walker1 for A, ln(P), w, Phase, e, Jitt and Offset are: ") print(pos[0]) print(" ") sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(Time, Radial_Velocity, Err)) sampler.run_mcmc(pos, chain_length) ##CAMBIOS AQUI, (pos, nwalks) el 100 funciona ########### # Burn-in # ########### if BURNIN: samples = sampler.chain[:, burn_out:, :].reshape((-1, ndim)) ############ # Plotting # ############ print("Mean acceptance fraction: {0:.3f}" .format(np.mean(sampler.acceptance_fraction))) ''' print "The estimated Autocorrelation times for each of the model parameters are:" for i in range(ndim): print sampler.acor[i] ''' ln_post = sampler.flatlnprobability ############################################################# ############# # P L O T S # ############# titles = np.array(["Amplitude","Period","Longitude", "Phase","Eccentricity", "Jitter","Offset"]) # Plot the chains out to investigate the walkers!! # with cmap = <color> you can change the colormap # like cmap=plt.cm.hot, gist_heat, binary, autumn, etc if CHAINS: for i in range(ndim): pointnum = len(sampler.flatchain[:,i]) fig1 = plt.figure(figsize=(10, 10)) sorting = np.arange(pointnum) if i == 1: plt.scatter(np.arange(pointnum), np.exp(sampler.flatchain[:,i]), c=sorting, lw=0.01) # After anti-logging P!!! else: plt.scatter(np.arange(pointnum), sampler.flatchain[:,i], c=sorting, lw=0.01) plt.colorbar() plt.ylabel(titles[i]) plt.xlabel("N") plt.title(titles[i]) if SAVE: fig1.savefig("chains"+str(i)+".jpg") # Plot the Posteriors out for each parameter, to check the areas of high probability!! if POST: for i in range(ndim): fig2 = plt.figure(figsize=(10, 10)) sorting = np.arange(len(sampler.flatchain[:,i])) if i == 1: plt.scatter(np.exp(sampler.flatchain[:,i]),abs(ln_post), c=sorting, lw=0.01) #After anti-logging P!!! else: plt.scatter(sampler.flatchain[:,i],abs(ln_post), c=sorting, lw=0.01) plt.colorbar() plt.yscale('log') plt.xlabel(titles[i]) plt.ylabel("Posterior") plt.title(titles[i]) if SAVE: fig2.savefig("posteriors"+str(i)+".jpg") ######################################################## ######################################################## A_max = sampler.flatchain[ln_post == np.max(ln_post),0][0] P_max = sampler.flatchain[ln_post == np.max(ln_post),1][0] w_max = sampler.flatchain[ln_post == np.max(ln_post),2][0] phase_max = sampler.flatchain[ln_post == np.max(ln_post),3][0] ecc_max = sampler.flatchain[ln_post == np.max(ln_post),4][0] jitt_max = sampler.flatchain[ln_post == np.max(ln_post),5][0] offset_max = sampler.flatchain[ln_post == np.max(ln_post),6][0] print('--------------------------------------------------------') print("The most probable flatchain values are as follows...") print('A [JD]: ', A_max) print('P [days]: ', np.exp(P_max)) #After anti-logging P!!! print('Longitude: ', w_max) print('Phase [m/s]: ', phase_max) print('Eccentricity: ', ecc_max) print('Jitter [m/s]: ', jitt_max) print('Offset [m/s]: ', offset_max) print('--------------------------------------------------------') # Plotting #fullmodel modeltime = np.linspace(0, Time[len(Time)-1], len(Time)) model_full = model(A_max,P_max,w_max,phase_max,ecc_max, offset_max, jitt_max, modeltime) fig = plt.figure(figsize=(10, 10)) plt.clf() plt.errorbar(Time, Radial_Velocity, marker='o', color='red', label='Data', linestyle='') plt.errorbar(Time, model_full, color='blue', label='Model') plt.xlabel('Time [days]', fontsize=18) plt.ylabel('RV [m/s]', fontsize=18) plt.title('Raw Data vs Model', fontsize=22) plt.legend(numpoints=1) if SAVE: plt.savefig("notphase_folded_rv.jpg") plt.draw() plt.show() #phase-fold if PHASEFOLD: per_max = np.exp(P_max) phases = foldAt(Time, per_max, T0=0.) # folds at the Period found sortIndi = np.argsort(phases) # sorts the points Phases = phases[sortIndi] # gets the indices so we sort the RVs correspondingly(?) rv_phased = Radial_Velocity[sortIndi] err_phased = Err[sortIndi] time_phased = Phases * per_max #After anti-logging P!!! model_phased = model(A_max, per_max, w_max, phase_max, ecc_max, offset_max, jitt_max, time_phased) fig2 = plt.figure(figsize=(10, 10)) plt.clf() plt.errorbar(time_phased, rv_phased, err_phased, color='red', marker='o', linestyle="", label='Data') plt.errorbar(time_phased, model_phased, color='blue', label='Model') plt.xlabel('Time [days]', fontsize=18) plt.ylabel('RV [m/s]', fontsize=18) plt.title('Phase Fold', fontsize=22) plt.legend(numpoints=1) if SAVE: plt.savefig("phase_folded_rv.jpg") plt.draw() plt.show() chronometer = np.round(chrono.time() - start_chrono) minutes = chronometer // 60 seconds = chronometer % 60 pbar.close() print("--- %s minutes and %s seconds ---" % (minutes, seconds)) # Chronometer
def setupTOI175simv2(bjd0, Ms, eccs, incs_deg, outname, interval_yrs, random=True, DeltaOmegamax=180): '''Create a simulation of TOI175 with custom input for the planetary parameters in the form of 1d arrays.''' # Initialize sim = rebound.Simulation() sim.integrator = "whfast" sim.units = ('AU', 'Msun', 'yr') sim.automateSimulationArchive("%s.bin" % outname, interval=interval_yrs) # Get keplerian parameters assert eccs.size == 3 assert incs_deg.size == 3 Ps = np.array([2.2531, 3.6904, 7.4512]) if random: Ps += np.array([ np.random.randn() * 4e-4, np.random.randn() * 3e-4, np.random.randn() * 8e-4 ]) while np.any(Ps <= 0): Ps = np.array([2.2531, 3.6904, 7.4512]) + np.array([ np.random.randn() * 4e-4, np.random.randn() * 3e-4, np.random.randn() * 8e-4 ]) T0s = np.array([1366.1708, 1367.2752, 1362.7376]) + 2457000 if random: T0s += np.array([ np.random.randn() * 1e-4, np.random.randn() * 6e-4, np.random.randn() * 9e-4 ]) # sample mass of the smallest planet directly from the PDF since it's not gaussian (i.e. a non-detection) mp_175d03 = np.random.choice(np.load( 'toi175d03_2d25_planetmass_PDF.npy')) + np.random.randn() * 5e-4 mps = np.array([mp_175d03, 2.6, 2.4]) if random: mps += np.array([0, np.random.randn() * 0.4, np.random.randn() * 0.6]) while np.any(mps <= 0): mps = np.array([0.34, 2.6, 2.4]) + np.array([ np.random.randn() * .42, np.random.randn() * 0.4, np.random.randn() * 0.6 ]) smas = rvs.m2AU(rvs.semimajoraxis(Ps, Ms, mps)) mps = rvs.kg2Msun(rvs.Mearth2kg(mps)) nplanets = Ps.size omegas = np.random.uniform(-np.pi, np.pi, nplanets) Omegas = np.random.uniform(-np.pi, np.pi, nplanets) thetas = 2 * np.pi * foldAt(bjd0, Ps, T0s) - np.pi # Add star sim.add(m=Ms, hash='star') # Add planets for i in range(nplanets): sim.add(m=mps[i], a=smas[i], inc=np.deg2rad(incs_deg[i] - 90), e=eccs[i], omega=omegas[i], Omega=Omegas[i], theta=thetas[i]) sim.move_to_com() RHill1 = (mps[:2].sum() / (3. * Ms))**(1. / 3) * smas[:2].mean() RHill2 = (mps[1:].sum() / (3. * Ms))**(1. / 3) * smas[1:].mean() sim.exit_min_distance = float(np.max([RHill1, RHill2])) return sim
def compute_nRV_GP(GPtheta, keptheta, sig_phot, sigK_target, fname='', duration=100): ''' Compute nRV for TESS planets including a GP activity model (i.e. non-white noise model. ''' assert len(GPtheta) == 5 assert len(keptheta) == 2 a, l, G, Pgp, s = GPtheta P, K = keptheta # search for target sigma by iterating over Nrv coarsely at first Nrvs = np.arange(10, 1001, 90) sigKs = np.zeros(Nrvs.size) for i in range(Nrvs.size): # get rv activity model gp = george.GP(a*(george.kernels.ExpSquaredKernel(l) + \ george.kernels.ExpSine2Kernel(G,Pgp))) t = _uniform_window_function(duration, Nrvs[i]) erv = np.repeat(sig_phot, t.size) gp.compute(t, np.sqrt(erv**2 + s**2)) rv_act = gp.sample(t) ##if rv_act.std() > 0: ## rv_act *= a / rv_act.std() # get planet model rv_kep = -K * np.sin(2 * np.pi * foldAt(t, P)) # get total rv signal with noise rv = rv_act + rv_kep + np.random.randn(t.size) * sig_phot # compute sigK theta = P, 0, K, a, l, G, Pgp, s sigKs[i] = compute_sigmaK_GP(theta, t, rv, erv) # fit powerlaw to Nrv vs sigK ##g = np.isfinite(sigKs) ##alpha0 = np.polyfit(np.log10(sigKs[g]), np.log10(Nrvs[g]), 1)[0] ##A0 = Nrvs.max() / sigKs[g].min()**alpha0 ##bounds = [-np.inf,-np.inf,0], [np.inf]*3 ##popt,_ = curve_fit(powerlawfunc, sigKs[g], Nrvs[g], p0=[A0, alpha0, 0], ## bounds=bounds) ##Nrv1 = float(powerlawfunc(sigK_target, *popt)) # fit power in log space g = np.isfinite(sigKs) p = np.poly1d(np.polyfit(np.log(sigKs[g]), np.log(Nrvs[g]), 1)) Nrv = np.exp(p(np.log(sigK_target))) # save diagnostic plot if fname != '': label = fname.split('/')[-1].split('.')[0] starnum = label.split('_')[0].split('t')[-1] try: os.mkdir('plots/star%s' % starnum) except OSError: pass sigKs_temp = np.logspace(np.log10(sigKs.min()), np.log10(sigKs.max()), 100) # dont plot!! #plt.scatter(sigKs, Nrvs), plt.plot(sigKs_temp, np.exp(p(np.log(sigKs_temp))), '-') #plt.xlabel('sigK (m/s)'), plt.ylabel('nRV'), plt.xscale('log'), plt.yscale('log') #plt.savefig('plots/star%s/%s.png'%(starnum, label)), plt.close('all') np.savetxt('plots/star%s/%s_datapoints.dat' % (starnum, label), np.array([sigKs, Nrvs]).T, fmt='%.5e', delimiter='\t') np.savetxt('plots/star%s/%s_fit.dat' % (starnum, label), np.array([sigKs_temp, np.exp(p(np.log(sigKs_temp)))]).T, fmt='%.5e', delimiter='\t') return Nrv
ax.plot(phase, rv1, color='red') ax.plot(phase, -rv2, color='red', alpha=0.5) # rv_file = 'KOREL/HeI4009_HeI4026/korel.rv' rv_file = 'KOREL/6678/korel.rv_6678_2048_merged' #N, t, vr1, oc1 = np.loadtxt(rv_file, unpack=True, skiprows=1) N, t, vr1, oc1, vr2, oc2 = np.loadtxt(rv_file, unpack=True, skiprows=1) # N, t, vr1, oc1, vr2, oc2, vr3, oc3 = np.loadtxt(rv_file, unpack=True, skiprows=1) # with open('RVs_korel_C.dat', 'a') as f: # for i in range(len(N)): # f.write('t, ') phases = pyasl.foldAt(t, P, T0=t0, getEpoch=False) ax.axhline(y=0, ls=':', color='black') ax.scatter(phases, vr1, marker='.', color='black') # ax.scatter(phases, vr1-oc1, marker='.', color='red') ax.scatter(phases, vr2, marker='.', color='grey') # ax.scatter(phases, vr2-oc2, marker='.', color='red', alpha=0.5) # plt.scatter(phases, vr3, marker='+', color='blue') # plt.scatter(phases, vr3-oc3, marker='+', color='green') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-60, 60) ax.set_xlabel('phase') ax.set_ylabel('RV (km/s)')