|
| 1 | +from collections.abc import Callable, Sequence, Mapping |
| 2 | + |
| 3 | +import matplotlib |
| 4 | +import matplotlib.pyplot as plt |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import pandas as pd |
| 8 | +import seaborn as sns |
| 9 | + |
| 10 | + |
| 11 | +from .plot_quantity import _prepare_values |
| 12 | + |
| 13 | + |
| 14 | +def pairs_quantity( |
| 15 | + values: Mapping[str, np.ndarray] | np.ndarray | Callable, |
| 16 | + targets: Mapping[str, np.ndarray] | np.ndarray, |
| 17 | + *, |
| 18 | + variable_keys: Sequence[str] = None, |
| 19 | + variable_names: Sequence[str] = None, |
| 20 | + estimates: Mapping[str, np.ndarray] | np.ndarray | None = None, |
| 21 | + test_quantities: dict[str, Callable] = None, |
| 22 | + height: float = 2.5, |
| 23 | + cmap: str | matplotlib.colors.Colormap = "viridis", |
| 24 | + alpha: float = 0.9, |
| 25 | + markersize: float = 8.0, |
| 26 | + marker: str = "o", |
| 27 | + label: str = None, |
| 28 | + label_fontsize: int = 14, |
| 29 | + tick_fontsize: int = 12, |
| 30 | + colorbar_label_fontsize: int = 14, |
| 31 | + colorbar_tick_fontsize: int = 12, |
| 32 | + colorbar_width: float = 1.8, |
| 33 | + colorbar_height: float = 0.06, |
| 34 | + colorbar_offset: float = 0.06, |
| 35 | + vmin: float = None, |
| 36 | + vmax: float = None, |
| 37 | + default_name: str = "v", |
| 38 | + **kwargs, |
| 39 | +) -> sns.PairGrid: |
| 40 | + """ |
| 41 | + A pair plot function to plot quantities against their generating |
| 42 | + parameter values. |
| 43 | +
|
| 44 | + The value is indicated by a colormap. The marginal distribution for |
| 45 | + each parameter is plotted on the diagonal. Each column displays the |
| 46 | + values of corresponding to the parameter in the column. |
| 47 | +
|
| 48 | + The function supports the following different combinations to pass |
| 49 | + or compute the values: |
| 50 | +
|
| 51 | + 1. pass `values` as an array of shape (num_datasets,) or (num_datasets, num_variables) |
| 52 | + 2. pass `values` as a dictionary with the keys 'values', 'metric_name' and 'variable_names' |
| 53 | + as provided by the metrics functions. Note that the functions have to be called |
| 54 | + without aggregation to obtain value per dataset. |
| 55 | + 3. pass a function to `values`, as well as `estimates`. The function should have the |
| 56 | + signature fn(estimates, targets, [aggregation]) and return an object like the |
| 57 | + `values` described in the previous options. |
| 58 | +
|
| 59 | + Parameters |
| 60 | + ---------- |
| 61 | + values : dict[str, np.ndarray] | np.ndarray | Callable, |
| 62 | + The value of the quantity to plot. One of the following: |
| 63 | +
|
| 64 | + 1. an array of shape (num_datasets,) or (num_datasets, num_variables) |
| 65 | + 2. a dictionary with the keys 'values', 'metric_name' and 'variable_names' |
| 66 | + as provided by the metrics functions. Note that the functions have to be called |
| 67 | + without aggregation to obtain value per dataset. |
| 68 | + 3. a callable, requires passing `estimates` as well. The function should have the |
| 69 | + signature fn(estimates, targets, [aggregation]) and return an object like the |
| 70 | + ones described in the previous options. |
| 71 | + targets : dict[str, np.ndarray] | np.ndarray, |
| 72 | + The parameter values plotted on the axis. |
| 73 | + variable_keys : list or None, optional, default: None |
| 74 | + Select keys from the dictionary provided in samples. |
| 75 | + By default, select all keys. |
| 76 | + variable_names : list or None, optional, default: None |
| 77 | + The parameter names for nice plot titles. Inferred if None |
| 78 | + estimates : np.ndarray of shape (n_data_sets, n_post_draws, n_params), optional, default: None |
| 79 | + The posterior draws obtained from n_data_sets. Can only be supplied if |
| 80 | + `values` is of type Callable. |
| 81 | + test_quantities : dict or None, optional, default: None |
| 82 | + A dict that maps plot titles to functions that compute |
| 83 | + test quantities based on estimate/target draws. |
| 84 | + Can only be supplied if `values` is a function. |
| 85 | +
|
| 86 | + The dict keys are automatically added to ``variable_keys`` |
| 87 | + and ``variable_names``. |
| 88 | + Test quantity functions are expected to accept a dict of draws with |
| 89 | + shape ``(batch_size, ...)`` as the first (typically only) |
| 90 | + positional argument and return an NumPy array of shape |
| 91 | + ``(batch_size,)``. |
| 92 | + The functions do not have to deal with an additional |
| 93 | + sample dimension, as appropriate reshaping is done internally. |
| 94 | + height : float, optional, default: 2.5 |
| 95 | + The height of the pair plot |
| 96 | + cmap : str or Colormap, default: "viridis" |
| 97 | + The colormap for the plot. |
| 98 | + alpha : float in [0, 1], optional, default: 0.9 |
| 99 | + The opacity of the plot |
| 100 | + markersize : float, optional, default: 8.0 |
| 101 | + The marker size in points**2 for the scatter plot. |
| 102 | + marker : str, optional, default: 'o' |
| 103 | + The marker for the scatter plot. |
| 104 | + label : str, optional, default: None |
| 105 | + Label for the dataset to plot. |
| 106 | + label_fontsize : int, optional, default: 14 |
| 107 | + The font size of the x and y-label texts (parameter names) |
| 108 | + tick_fontsize : int, optional, default: 12 |
| 109 | + The font size of the axis tick labels |
| 110 | + colorbar_label_fontsize : int, optional, default: 14 |
| 111 | + The font size of the colorbar label |
| 112 | + colorbar_tick_fontsize : int, optional, default: 12 |
| 113 | + The font size of the colorbar tick labels |
| 114 | + colorbar_width : float, optional, default: 1.8 |
| 115 | + The width of the colorbar in inches |
| 116 | + colorbar_height : float, optional, default: 0.06 |
| 117 | + The height of the colorbar in inches |
| 118 | + colorbar_offset : float, optional, default: 0.06 |
| 119 | + The vertical offset of the colorbar in inches |
| 120 | + vmin : float, optional, default: None |
| 121 | + Minimum value for the colormap. If None, the minimum value is |
| 122 | + determined from `values`. |
| 123 | + vmax : float, optional, default: None |
| 124 | + Maximum value for the colormap. If None, the maximum value is |
| 125 | + determined from `values`. |
| 126 | + default_name : str, optional (default = "v") |
| 127 | + The default name to use for estimates if None provided |
| 128 | + **kwargs : dict, optional |
| 129 | + Additional keyword arguments passed to the sns.PairGrid constructor |
| 130 | +
|
| 131 | + Returns |
| 132 | + ------- |
| 133 | + plt.Figure |
| 134 | + The figure instance |
| 135 | +
|
| 136 | + Raises |
| 137 | + ------ |
| 138 | + ValueError |
| 139 | + If a callable is supplied as `values`, but `estimates` is None. |
| 140 | + """ |
| 141 | + |
| 142 | + if isinstance(values, Callable) and estimates is None: |
| 143 | + raise ValueError("Supplied a callable as `values`, but no `estimates`.") |
| 144 | + if not isinstance(values, Callable) and test_quantities is not None: |
| 145 | + raise ValueError( |
| 146 | + "Supplied `test_quantities`, but `values` is not a function. " |
| 147 | + "As the values have to be calculated for the test quantities, " |
| 148 | + "passing a function is required." |
| 149 | + ) |
| 150 | + |
| 151 | + d = _prepare_values( |
| 152 | + values=values, |
| 153 | + targets=targets, |
| 154 | + estimates=estimates, |
| 155 | + variable_keys=variable_keys, |
| 156 | + variable_names=variable_names, |
| 157 | + test_quantities=test_quantities, |
| 158 | + label=label, |
| 159 | + default_name=default_name, |
| 160 | + ) |
| 161 | + (values, targets, variable_keys, variable_names, test_quantities, label) = ( |
| 162 | + d["values"], |
| 163 | + d["targets"], |
| 164 | + d["variable_keys"], |
| 165 | + d["variable_names"], |
| 166 | + d["test_quantities"], |
| 167 | + d["label"], |
| 168 | + ) |
| 169 | + |
| 170 | + # Convert samples to pd.DataFrame |
| 171 | + data_to_plot = pd.DataFrame(targets, columns=variable_names) |
| 172 | + |
| 173 | + # initialize plot |
| 174 | + g = sns.PairGrid( |
| 175 | + data_to_plot, |
| 176 | + height=height, |
| 177 | + vars=variable_names, |
| 178 | + **kwargs, |
| 179 | + ) |
| 180 | + |
| 181 | + vmin = values.min() if vmin is None else vmin |
| 182 | + vmax = values.max() if vmax is None else vmax |
| 183 | + |
| 184 | + # Generate grids |
| 185 | + dim = g.axes.shape[0] |
| 186 | + for i in range(dim): |
| 187 | + for j in range(dim): |
| 188 | + # if one value for each variable is supplied, use it for the corresponding column |
| 189 | + row_values = values[:, j] if values.ndim == 2 else values |
| 190 | + |
| 191 | + if i == j: |
| 192 | + ax = g.axes[i, j].twinx() |
| 193 | + ax.scatter( |
| 194 | + targets[:, i], |
| 195 | + values[:, i], |
| 196 | + c=row_values, |
| 197 | + cmap=cmap, |
| 198 | + s=markersize, |
| 199 | + marker=marker, |
| 200 | + vmin=vmin, |
| 201 | + vmax=vmax, |
| 202 | + alpha=alpha, |
| 203 | + ) |
| 204 | + ax.spines["left"].set_visible(False) |
| 205 | + ax.spines["top"].set_visible(False) |
| 206 | + ax.tick_params(axis="both", which="major", labelsize=tick_fontsize) |
| 207 | + ax.tick_params(axis="both", which="minor", labelsize=tick_fontsize) |
| 208 | + ax.set_ylim(vmin, vmax) |
| 209 | + |
| 210 | + if i > 0: |
| 211 | + g.axes[i, j].get_yaxis().set_visible(False) |
| 212 | + g.axes[i, j].spines["left"].set_visible(False) |
| 213 | + if i == dim - 1: |
| 214 | + ax.set_ylabel(label, size=label_fontsize) |
| 215 | + else: |
| 216 | + g.axes[i, j].grid(alpha=0.5) |
| 217 | + g.axes[i, j].set_axisbelow(True) |
| 218 | + g.axes[i, j].scatter( |
| 219 | + targets[:, j], |
| 220 | + targets[:, i], |
| 221 | + c=row_values, |
| 222 | + cmap=cmap, |
| 223 | + s=markersize, |
| 224 | + vmin=vmin, |
| 225 | + vmax=vmax, |
| 226 | + alpha=alpha, |
| 227 | + marker=marker, |
| 228 | + ) |
| 229 | + |
| 230 | + def inches_to_figure(fig, values): |
| 231 | + return fig.transFigure.inverted().transform(fig.dpi_scale_trans.transform(values)) |
| 232 | + |
| 233 | + # position and draw colorbar |
| 234 | + _, yoffset = inches_to_figure(g.figure, [0, colorbar_offset]) |
| 235 | + cwidth, cheight = inches_to_figure(g.figure, [colorbar_width, colorbar_offset]) |
| 236 | + cax = g.figure.add_axes([0.5 - cwidth / 2, -yoffset - cheight, cwidth, cheight]) |
| 237 | + |
| 238 | + norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) |
| 239 | + cbar = plt.colorbar( |
| 240 | + matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap), |
| 241 | + cax=cax, |
| 242 | + location="bottom", |
| 243 | + label=label, |
| 244 | + alpha=alpha, |
| 245 | + ) |
| 246 | + |
| 247 | + cbar.set_label(label, size=colorbar_label_fontsize) |
| 248 | + cax.tick_params(labelsize=colorbar_tick_fontsize) |
| 249 | + |
| 250 | + dim = g.axes.shape[0] |
| 251 | + for i in range(dim): |
| 252 | + # Modify tick sizes |
| 253 | + for j in range(i + 1): |
| 254 | + g.axes[i, j].tick_params(axis="both", which="major", labelsize=tick_fontsize) |
| 255 | + g.axes[i, j].tick_params(axis="both", which="minor", labelsize=tick_fontsize) |
| 256 | + |
| 257 | + # adjust the font size of labels |
| 258 | + # the labels themselves remain the same as before, i.e., variable_names |
| 259 | + g.axes[i, 0].set_ylabel(variable_names[i], fontsize=label_fontsize) |
| 260 | + g.axes[dim - 1, i].set_xlabel(variable_names[i], fontsize=label_fontsize) |
| 261 | + |
| 262 | + return g |
0 commit comments