<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 (pystan2_refitting_xr)=
Refitting PyStan (2.x) models with ArviZ (and xarray)
ArviZ is backend agnostic and therefore does not sample directly. In order to take advantage of algorithms that require refitting models several times, ArviZ uses {class}~arviz.SamplingWrappers to convert the API of the sampling backend to a common set of functions. Hence, functions like Leave Future Out Cross Validation can be used in ArviZ independently of the sampling backend used.
Below there is an example of SamplingWrapper usage for PyStan (2.x).
Step1:  For the example, we will use a linear regression model.
Step3:  Now we will write the Stan code, keeping in mind to include only the array shapes as parameters.
Step4:  We have defined a dictionary sample_kwargs that will be passed to the SamplingWrapper in order to make sure that all
refits use the same sampler parameters. We follow the same pattern with {func}~arviz.from_pystan.
Step5:  We are now missing the log_likelihood group because we have not used the log_likelihood argument in idata_kwargs. We are doing this to ease the job of the sampling wrapper. Instead of going out of our way to get Stan to calculate the pointwise log likelihood values for each refit and for the excluded observation at every refit, we will compromise and manually write a function to calculate the pointwise log likelihood.
Even though it is not ideal to lose part of the straight out of the box capabilities of PyStan-ArviZ integration, this should generally not be a problem. We are basically moving the pointwise log likelihood calculation from the Stan code to the Python code, in both cases, we need to manually write the function to calculate the pointwise log likelihood.
Moreover, the Python computation could even be written to be compatible with Dask. Thus it will work even in cases where the large number of observations makes it impossible to store pointwise log likelihood values (with shape n_samples * n_observations) in memory.
Step6:  This function should work for any shape of the input arrays as long as their shapes are compatible and can broadcast. There is no need to loop over each draw in order to calculate the pointwise log likelihood using scalars.
Therefore, we can use {func}xr.apply_ufunc &lt;xarray.apply_ufunc&gt; to handle the broadcasting and preserve the dimension names
Step7:  The first argument is the function, followed by as many positional arguments as needed by the function, 5 in our case. As this case does not have many different dimensions nor combinations of these, we do not need to use any extra kwargs passed to xarray.apply_ufunc.
We are now passing the arguments to calculate_log_lik initially as {class}xarray
Step8:  If you are still curious about the magic of xarray and apply_ufunc, you can also try to modify the dims used to generate the InferenceData a couple of cells before
Step9:  We will create a subclass of {class}~arviz.SamplingWrapper. Therefore, instead of having to implement all functions required by {func}~arviz.reloo we only have to implement {func}~arviz.SamplingWrapper.sel_observations (we are cloning  {func}~arviz.SamplingWrapper.sample and {func}~arviz.SamplingWrapper.get_inference_data from the {class}~arviz.SamplingWrapper in order to use apply_ufunc instead of assuming the log likelihood is calculated within Stan). 
Let's check the 2 outputs of sel_observations.
1. data__i is a dictionary because it is an argument of sample which will pass it as is to model.sampling.
2. data_ex is a list because it is an argument to log_likelihood__i which will pass it as *data_ex to  apply_ufunc.
More on data_ex and apply_ufunc integration is given below.
Step10:  In this case, the Leave-One-Out Cross Validation (LOO-CV) approximation using Pareto Smoothed Importance Sampling (PSIS) works for all observations, so we will use modify loo_orig in order to make {func}~arviz.reloo believe that PSIS failed for some observations. This will also serve as a validation of our wrapper, as the PSIS LOO-CV already returned the correct value.
Step11:  We initialize our sampling wrapper. Let's stop and analyze each of the arguments. 
We use the log_lik_fun and posterior_vars argument to tell the wrapper how to call {func}~xarray
Step12:  And eventually, we can use this wrapper to call az.reloo, and compare the results with the PSIS LOO-CV results.
<ASSISTANT_TASK:>
Python Code:
import arviz as az
import pystan
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import xarray as xr
Explanation: (pystan2_refitting_xr)=
Refitting PyStan (2.x) models with ArviZ (and xarray)
ArviZ is backend agnostic and therefore does not sample directly. In order to take advantage of algorithms that require refitting models several times, ArviZ uses {class}~arviz.SamplingWrappers to convert the API of the sampling backend to a common set of functions. Hence, functions like Leave Future Out Cross Validation can be used in ArviZ independently of the sampling backend used.
Below there is an example of SamplingWrapper usage for PyStan (2.x).
End of explanation
np.random.seed(26)
xdata = np.linspace(0, 50, 100)
b0, b1, sigma = -2, 1, 3
ydata = np.random.normal(loc=b1 * xdata + b0, scale=sigma)
plt.plot(xdata, ydata)
Explanation: For the example, we will use a linear regression model.
End of explanation
refit_lr_code = 
data {
  // Define data for fitting
  int<lower=0> N;
  vector[N] x;
  vector[N] y;
}
parameters {
  real b0;
  real b1;
  real<lower=0> sigma_e;
}
model {
  b0 ~ normal(0, 10);
  b1 ~ normal(0, 10);
  sigma_e ~ normal(0, 10);
  for (i in 1:N) {
    y[i] ~ normal(b0 + b1 * x[i], sigma_e);  // use only data for fitting
  }
  
}
generated quantities {
    vector[N] y_hat;
    
    for (i in 1:N) {
        // pointwise log likelihood will be calculated outside Stan, 
        // posterior predictive however will be generated here, there are 
        // no restrictions on adding more generated quantities
        y_hat[i] = normal_rng(b0 + b1 * x[i], sigma_e);
    }
}
sm = pystan.StanModel(model_code=refit_lr_code)
data_dict = {
    "N": len(ydata),
    "y": ydata,
    "x": xdata,
}
sample_kwargs = {"iter": 1000, "chains": 4}
fit = sm.sampling(data=data_dict, **sample_kwargs)
Explanation: Now we will write the Stan code, keeping in mind to include only the array shapes as parameters.
End of explanation
dims = {"y": ["time"], "x": ["time"], "y_hat": ["time"]}
idata_kwargs = {
    "posterior_predictive": ["y_hat"],
    "observed_data": "y",
    "constant_data": "x",
    "dims": dims,
}
idata = az.from_pystan(posterior=fit, **idata_kwargs)
Explanation: We have defined a dictionary sample_kwargs that will be passed to the SamplingWrapper in order to make sure that all
refits use the same sampler parameters. We follow the same pattern with {func}~arviz.from_pystan.
End of explanation
def calculate_log_lik(x, y, b0, b1, sigma_e):
    mu = b0 + b1 * x
    return stats.norm(mu, sigma_e).logpdf(y)
Explanation: We are now missing the log_likelihood group because we have not used the log_likelihood argument in idata_kwargs. We are doing this to ease the job of the sampling wrapper. Instead of going out of our way to get Stan to calculate the pointwise log likelihood values for each refit and for the excluded observation at every refit, we will compromise and manually write a function to calculate the pointwise log likelihood.
Even though it is not ideal to lose part of the straight out of the box capabilities of PyStan-ArviZ integration, this should generally not be a problem. We are basically moving the pointwise log likelihood calculation from the Stan code to the Python code, in both cases, we need to manually write the function to calculate the pointwise log likelihood.
Moreover, the Python computation could even be written to be compatible with Dask. Thus it will work even in cases where the large number of observations makes it impossible to store pointwise log likelihood values (with shape n_samples * n_observations) in memory.
End of explanation
log_lik = xr.apply_ufunc(
    calculate_log_lik,
    idata.constant_data["x"],
    idata.observed_data["y"],
    idata.posterior["b0"],
    idata.posterior["b1"],
    idata.posterior["sigma_e"],
)
idata.add_groups(log_likelihood=log_lik)
Explanation: This function should work for any shape of the input arrays as long as their shapes are compatible and can broadcast. There is no need to loop over each draw in order to calculate the pointwise log likelihood using scalars.
Therefore, we can use {func}xr.apply_ufunc &lt;xarray.apply_ufunc&gt; to handle the broadcasting and preserve the dimension names:
End of explanation
calculate_log_lik(
    idata.constant_data["x"].values,
    idata.observed_data["y"].values,
    idata.posterior["b0"].values,
    idata.posterior["b1"].values,
    idata.posterior["sigma_e"].values
)
Explanation: The first argument is the function, followed by as many positional arguments as needed by the function, 5 in our case. As this case does not have many different dimensions nor combinations of these, we do not need to use any extra kwargs passed to xarray.apply_ufunc.
We are now passing the arguments to calculate_log_lik initially as {class}xarray:xarray.DataArrays. What is happening here behind the scenes is that {func}~xarray:xarray.apply_ufunc is broadcasting and aligning the dimensions of all the DataArrays involved and afterwards passing NumPy arrays to calculate_log_lik. Everything works automagically. 
Now let's see what happens if we were to pass the arrays directly to calculate_log_lik instead:
End of explanation
idata
Explanation: If you are still curious about the magic of xarray and apply_ufunc, you can also try to modify the dims used to generate the InferenceData a couple of cells before:
dims = {"y": ["time"], "x": ["time"]}
What happens to the result if you use a different name for the dimension of x?
End of explanation
class LinearRegressionWrapper(az.SamplingWrapper):
    def sel_observations(self, idx):
        xdata = self.idata_orig.constant_data["x"]
        ydata = self.idata_orig.observed_data["y"]
        mask = np.isin(np.arange(len(xdata)), idx)
        data__i = {"x": xdata[~mask], "y": ydata[~mask], "N": len(ydata[~mask])}
        data_ex = [ary[mask] for ary in (xdata, ydata)]
        return data__i, data_ex
    
    def sample(self, modified_observed_data):
        #Cloned from PyStan2SamplingWrapper.
        fit = self.model.sampling(data=modified_observed_data, **self.sample_kwargs)
        return fit
    def get_inference_data(self, fit):
        # Cloned from PyStan2SamplingWrapper.
        idata = az.from_pystan(posterior=fit, **self.idata_kwargs)
        return idata
loo_orig = az.loo(idata, pointwise=True)
loo_orig
Explanation: We will create a subclass of {class}~arviz.SamplingWrapper. Therefore, instead of having to implement all functions required by {func}~arviz.reloo we only have to implement {func}~arviz.SamplingWrapper.sel_observations (we are cloning  {func}~arviz.SamplingWrapper.sample and {func}~arviz.SamplingWrapper.get_inference_data from the {class}~arviz.SamplingWrapper in order to use apply_ufunc instead of assuming the log likelihood is calculated within Stan). 
Let's check the 2 outputs of sel_observations.
1. data__i is a dictionary because it is an argument of sample which will pass it as is to model.sampling.
2. data_ex is a list because it is an argument to log_likelihood__i which will pass it as *data_ex to  apply_ufunc.
More on data_ex and apply_ufunc integration is given below.
End of explanation
loo_orig.pareto_k[[13, 42, 56, 73]] = np.array([0.8, 1.2, 2.6, 0.9])
Explanation: In this case, the Leave-One-Out Cross Validation (LOO-CV) approximation using Pareto Smoothed Importance Sampling (PSIS) works for all observations, so we will use modify loo_orig in order to make {func}~arviz.reloo believe that PSIS failed for some observations. This will also serve as a validation of our wrapper, as the PSIS LOO-CV already returned the correct value.
End of explanation
pystan_wrapper = LinearRegressionWrapper(
    sm, 
    log_lik_fun=calculate_log_lik, 
    posterior_vars=("b0", "b1", "sigma_e"),
    idata_orig=idata, 
    sample_kwargs=sample_kwargs, 
    idata_kwargs=idata_kwargs
)
Explanation: We initialize our sampling wrapper. Let's stop and analyze each of the arguments. 
We use the log_lik_fun and posterior_vars argument to tell the wrapper how to call {func}~xarray:xarray.apply_ufunc. log_lik_fun is the function to be called, which is then called with the following positional arguments:
log_lik_fun(*data_ex, *[idata__i.posterior[var_name] for var_name in posterior_vars]
where data_ex is the second element returned by sel_observations and idata__i is the InferenceData object result of get_inference_data which contains the fit on the subsetted data. We have generated data_ex to be a tuple of DataArrays so it plays nicely with this call signature.
We use idata_orig as a starting point, and mostly as a source of observed and constant data which is then subsetted in sel_observations.
Finally, sample_kwargs and idata_kwargs are used to make sure all refits and corresponding InferenceData are generated with the same properties.
End of explanation
loo_relooed = az.reloo(pystan_wrapper, loo_orig=loo_orig)
loo_relooed
loo_orig
Explanation: And eventually, we can use this wrapper to call az.reloo, and compare the results with the PSIS LOO-CV results.
End of explanation
<END_TASK>