# Synthetic 2D Example¶

## Description¶

This demos a simple two dimensional model using only default parameters.

## Code¶

### Imports¶

Let’s start by importing the essential modules that we will need in the following:

```import dense1 as de
import numpy as np
import matplotlib.pyplot as plt
```

The python package dense1 contains the actual density estimator. The additional version number which is part of the name of the python package allows you to install multiple versions of the package at the same time. It even enables you to use them concurrently in the same program.

### Model Building¶

Next, we will initialize our density estimator:

```model = de.build_density_estimator((128, 128))
```

There is the option to configure a lot more than just the shape of the output but let’s stick to the most simplistic version of the estimator for now. The default values for the parameters in the density estimator are chosen conservatively and thus should work for a broad range of problemsets.

### Creating Synthetic Data¶

In the absence of data, let us artificially generate some:

```data, synth_truth = de.draw_synthetic_sample(model, seed=60, pretty=True)
```

### Model Fitting¶

Having both a model and some data to test the model on, we can invoke the actual fitting process:

```# Fit the model to the data and retrieve samples of the approximate posterior
# of the density
samples, _ = de.fit(model, data, n_max_iterations=5)
```

All methods are stateless and thus model is never modified. Instead we get posterior samples for the density from the model. The second return value which is discarded here, would allow us to access the samples in the latent space of the model.

### Visualization¶

Let’s plot the result:

```post_density_mean = np.mean(samples, axis=0)
post_density_std = np.std(samples, axis=0)

im_kw = {"vmin": synth_truth.min(), "vmax": synth_truth.max()}
fig, axs = plt.subplots(2, 2, figsize=(16, 10))
im = axs.flat[0].imshow(synth_truth, **im_kw)
axs.flat[0].set_title("Synthetic Truth")
im = axs.flat[1].imshow(data, **im_kw)
axs.flat[1].set_title("Data")
im = axs.flat[2].imshow(post_density_mean, **im_kw)
axs.flat[2].set_title("Posterior Mean")
im = axs.flat[3].imshow(post_density_std, **im_kw)
axs.flat[3].set_title("Posterior Std")
fig.tight_layout()
fig.colorbar(im, ax=axs.ravel().tolist(), orientation='vertical', shrink=0.75)
fig.savefig("synthetic_example.png")
plt.close()
```

By inferring the correlation structure jointly with the excitation of the expected count rate, the model is able to reconstruct the ground truth to high accuracy. This holds even though each individual count provides only little information on the overall distribution.