<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 If you have not already read it, you may want to start with the first tutorial
Step1:  Here we will again load some pre-generated data meant to represent well-sampled, precise radial velocity observations of a single luminous source with  a single companion (we again downsample the data set here just for demonstration)
Step2:  We will use the default prior, but feel free to play around with these values
Step3:  The data above look fairly constraining
Step4:  The sample that was returned by The Joker does look like it is a reasonable fit to the RV data, but to fully explore the posterior pdf we will use standard MCMC through pymc3. Here we will use the NUTS sampler, but you could also experiment with other backends (e.g., Metropolis-Hastings, or even emcee by following this blog post)
Step5:  If you get warnings from running the sampler above, they usually indicate that we should run the sampler for many more steps to tune the sampler and for our main run, but let's ignore that for now. With the MCMC traces in hand, we can summarize the properties of the chains using pymc3.summary
Step6:  To convert the trace into a JokerSamples instance, we can use the TheJoker.trace_to_samples() method. Note here that the sign of K is arbitrary, so to compare to the true value, we also call wrap_K() to store only the absolute value of K (which also increases omega by π, to stay consistent)
Step7:  We can now compare the samples we got from MCMC to the true orbital parameters used to generate this data
<ASSISTANT_TASK:>
Python Code:
import astropy.coordinates as coord
import astropy.table as at
from astropy.time import Time
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import corner
import pymc3 as pm
import pymc3_ext as pmx
import exoplanet as xo
import arviz as az
import thejoker as tj
# set up a random number generator to ensure reproducibility
rnd = np.random.default_rng(seed=42)
Explanation: If you have not already read it, you may want to start with the first tutorial: Getting started with The Joker.
Continue generating samples with standard MCMC
When many prior samples are used with The Joker, and the sampler returns one sample, or the samples returned are within the same mode of the posterior, the posterior pdf is likely unimodal. In these cases, we can use standard MCMC methods to generate posterior samples, which will typically be much more efficient than The Joker itself. In this example, we will use pymc3 to "continue" sampling for data that are very constraining.
First, some imports we will need later:
End of explanation
data_tbl = at.QTable.read('data.ecsv')
sub_tbl = data_tbl[rnd.choice(len(data_tbl), size=18, replace=False)]  # downsample data
data = tj.RVData.guess_from_table(sub_tbl, t_ref=data_tbl.meta['t_ref'])
_ = data.plot()
Explanation: Here we will again load some pre-generated data meant to represent well-sampled, precise radial velocity observations of a single luminous source with  a single companion (we again downsample the data set here just for demonstration):
End of explanation
prior = tj.JokerPrior.default(
    P_min=2*u.day, P_max=1e3*u.day,
    sigma_K0=30*u.km/u.s,
    sigma_v=100*u.km/u.s)
Explanation: We will use the default prior, but feel free to play around with these values:
End of explanation
prior_samples = prior.sample(size=250_000, 
                             random_state=rnd)
joker = tj.TheJoker(prior, random_state=rnd)
joker_samples = joker.rejection_sample(data, prior_samples, 
                                       max_posterior_samples=256)
joker_samples
joker_samples.tbl
_ = tj.plot_rv_curves(joker_samples, data=data)
Explanation: The data above look fairly constraining: it would be hard to draw many distinct orbital solutions through the RV data plotted above. In cases like this, we will often only get back 1 or a few samples from The Joker even if we use a huge number of prior samples. Since we are only going to use the samples from The Joker to initialize standard MCMC, we will only use a moderate number of prior samples:
End of explanation
with prior.model:
    mcmc_init = joker.setup_mcmc(data, joker_samples)
    
    trace = pmx.sample(tune=500, draws=500, 
                       start=mcmc_init,
                       cores=1, chains=2)
Explanation: The sample that was returned by The Joker does look like it is a reasonable fit to the RV data, but to fully explore the posterior pdf we will use standard MCMC through pymc3. Here we will use the NUTS sampler, but you could also experiment with other backends (e.g., Metropolis-Hastings, or even emcee by following this blog post):
End of explanation
az.summary(trace, var_names=prior.par_names)
Explanation: If you get warnings from running the sampler above, they usually indicate that we should run the sampler for many more steps to tune the sampler and for our main run, but let's ignore that for now. With the MCMC traces in hand, we can summarize the properties of the chains using pymc3.summary:
End of explanation
mcmc_samples = joker.trace_to_samples(trace, data)
mcmc_samples.wrap_K()
mcmc_samples
Explanation: To convert the trace into a JokerSamples instance, we can use the TheJoker.trace_to_samples() method. Note here that the sign of K is arbitrary, so to compare to the true value, we also call wrap_K() to store only the absolute value of K (which also increases omega by π, to stay consistent):
End of explanation
import pickle
with open('true-orbit.pkl', 'rb') as f:
    truth = pickle.load(f)
    
# make sure the angles are wrapped the same way
if np.median(mcmc_samples['omega']) < 0:
    truth['omega'] = coord.Angle(truth['omega']).wrap_at(np.pi*u.radian)
    
if np.median(mcmc_samples['M0']) < 0:
    truth['M0'] = coord.Angle(truth['M0']).wrap_at(np.pi*u.radian)
df = mcmc_samples.tbl.to_pandas()
truths = []
colnames = []
for name in df.columns:
    if name in truth:
        colnames.append(name)
        truths.append(truth[name].value)
_ = corner.corner(df[colnames], truths=truths)
Explanation: We can now compare the samples we got from MCMC to the true orbital parameters used to generate this data:
End of explanation
<END_TASK>