def imshow_logpolars(fig, spectra): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg logpolars_extent = (0, 0.5, 0, 180) grid = axg.ImageGrid( fig, 111, nrows_ncols=(2, 1), add_all=True, aspect=False, axes_pad=0.4, label_mode="L", cbar_pad=0.05, cbar_mode="each", cbar_size="3.5%", ) ims = [np.log(np.abs(im)) for im in spectra] vmin = min([np.percentile(im, 2) for im in ims]) vmax = max([np.percentile(im, 98) for im in ims]) for ii, im in enumerate(ims): im = grid[ii].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax, aspect="auto", extent=logpolars_extent) grid[ii].set_xlabel("log radius") grid[ii].set_ylabel("azimuth / degrees") grid.cbar_axes[ii].colorbar(im) return fig
def imshow_plain(fig, images, what, also_common=False): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg ncols = len(images) nrows = 1 if also_common: nrows = 2 elif len(images) == 4: # not also_common and we have 4 images --- we make a grid of 2x2 nrows = ncols = 2 grid = axg.ImageGrid( fig, 111, nrows_ncols=(nrows, ncols), add_all=True, axes_pad=0.4, label_mode="L", ) images = [im.real for im in images] for ii, im in enumerate(images): vmin = np.percentile(im, 2) vmax = np.percentile(im, 98) grid[ii].set_title(_t(what[ii])) img = grid[ii].imshow(im, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) if also_common: vmin = min([np.percentile(im, 2) for im in images]) vmax = max([np.percentile(im, 98) for im in images]) for ii, im in enumerate(images): grid[ii + ncols].set_title(_t(what[ii])) im = grid[ii + ncols].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax) return fig
def imshow_spectra(fig, spectra): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg dfts_filt_extent = (-0.5, 0.5, -0.5, 0.5) grid = axg.ImageGrid( fig, 111, nrows_ncols=(1, 2), add_all=True, axes_pad=0.4, label_mode="L", cbar_pad=0.05, cbar_mode="each", cbar_size="3.5%", ) what = ("template", "subject") for ii, im in enumerate(spectra): grid[ii].set_title("log abs dfts - %s" % what[ii]) im = grid[ii].imshow( np.log(np.abs(im)), cmap=plt.cm.viridis, extent=dfts_filt_extent, ) grid[ii].set_xlabel("X / px") grid[ii].set_ylabel("Y / px") grid.cbar_axes[ii].colorbar(im) return fig
def imshow_logpolars(fig, spectra, log_base, im_shape): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg low = 1.0 high = log_base ** spectra[0].shape[1] logpolars_extent = (low, high, 0, 180) grid = axg.ImageGrid( fig, 111, nrows_ncols=(2, 1), add_all=True, aspect=False, axes_pad=0.4, label_mode="L", ) ims = [np.log(np.abs(im)) for im in spectra] for ii, im in enumerate(ims): vmin = np.percentile(im, 1) vmax = np.percentile(im, 99) grid[ii].set_xscale("log", basex=log_base) grid[ii].get_xaxis().set_major_formatter(plt.ScalarFormatter()) im = grid[ii].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax, aspect="auto", extent=logpolars_extent) grid[ii].set_xlabel(_t("log radius")) grid[ii].set_ylabel(_t("azimuth / degrees")) xticklabels = ["{:.3g}".format(tick * 2 / im_shape[0]) for tick in grid[ii].get_xticks()] grid[ii].set_xticklabels( xticklabels, rotation=40, rotation_mode="anchor", ha="right" ) return fig
def setup_axes(): # We'll set up the axes a bit differently here so that they'll all be the # same height even though the aspect will be set and adjustable is "box". fig = plt.figure(figsize=(6,3)) axes = axes_grid1.ImageGrid(fig, [0, 0, .93, 1], (1, 3), axes_pad=0) for ax in axes: ax.set(xticks=[], yticks=[]) return fig, axes
def imshow_pcorr_translation(fig, cpss, extent, results, successes): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg ncols = 2 grid = axg.ImageGrid( fig, 111, # similar to subplot(111) nrows_ncols=(1, ncols), add_all=True, axes_pad=0.4, aspect=False, cbar_pad=0.05, label_mode="L", cbar_mode="single", cbar_size="3.5%", ) vmax = max(cpss[0].max(), cpss[1].max()) imshow_kwargs = dict( vmin=0, vmax=vmax, aspect="auto", origin="lower", extent=extent, cmap=plt.cm.viridis, ) titles = (_t(u"CPS — translation 0°"), _t(u"CPS — translation 180°")) labels = (_t("translation y / px"), _t("translation x / px")) for idx, pl in enumerate(grid): # TODO: Code duplication with imshow_pcorr pl.set_title(titles[idx]) center = np.array(results[idx]) im = pl.imshow(cpss[idx], **imshow_kwargs) # Otherwise plot would change xlim pl.autoscale(False) pl.plot(center[0], center[1], "o", color="r", fillstyle="none", markersize=18, lw=8) pl.annotate(_t("succ: {:.3g}".format(successes[idx])), xy=center, xytext=(0, 9), textcoords='offset points', color="red", va="bottom", ha="center") pl.annotate(_t("({:.3g}, {:.3g})".format(* center)), xy=center, xytext=(0, -9), textcoords='offset points', color="red", va="top", ha="center") pl.grid(c="w") pl.set_xlabel(labels[1]) grid.cbar_axes[0].colorbar(im) grid[0].set_ylabel(labels[0]) return fig
def imshow_spectra(fig, spectra): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg dfts_filt_extent = (-1, 1, -1, 1) grid = axg.ImageGrid( fig, 111, nrows_ncols=(1, 2), add_all=True, axes_pad=0.4, label_mode="L", ) what = ("template", "subject") for ii, im in enumerate(spectra): grid[ii].set_title(_t("log abs dfts - %s" % what[ii])) im = grid[ii].imshow(np.log(np.abs(im)), cmap=plt.cm.viridis, extent=dfts_filt_extent, ) grid[ii].set_xlabel(_t("2 X / px")) grid[ii].set_ylabel(_t("2 Y / px")) return fig
def imshow_plain(fig, images, what, also_common=False): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg ncols = len(images) nrows = 1 if also_common: nrows = 2 grid = axg.ImageGrid( fig, 111, nrows_ncols=(nrows, ncols), add_all=True, axes_pad=0.4, label_mode="L", cbar_pad=0.05, cbar_mode="each", cbar_size="3.5%", ) images = [im.real for im in images] for ii, im in enumerate(images): vmin = np.percentile(im, 2) vmax = np.percentile(im, 98) grid[ii].set_title("individual cmap --- {}".format(what[ii])) img = grid[ii].imshow(im, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) grid.cbar_axes[ii].colorbar(img) if also_common: vmin = min([np.percentile(im, 2) for im in images]) vmax = max([np.percentile(im, 98) for im in images]) for ii, im in enumerate(images): grid[ii + ncols].set_title("common cmap --- {}".format(what[ii])) im = grid[ii + ncols].imshow(im, cmap=plt.cm.viridis, vmin=vmin, vmax=vmax) grid.cbar_axes[ii + ncols].colorbar(im) return fig
def imshow_pcorr(fig, raw, filtered, extent, result, success, log_base=None): import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axg grid = axg.ImageGrid( fig, 111, # similar to subplot(111) nrows_ncols=(1, 2), add_all=True, axes_pad=0.4, aspect=False, cbar_pad=0.05, label_mode="L", cbar_mode="single", cbar_size="3.5%", ) vmax = raw.max() imshow_kwargs = dict( vmin=0, vmax=vmax, aspect="auto", origin="lower", extent=extent, cmap=plt.cm.viridis, ) grid[0].set_title("pcorr --- original") labels = ("translation y / px", "translation x / px") grid[0].imshow(raw, **imshow_kwargs) center = np.array(result) # Otherwise plot would change xlim grid[0].autoscale(False) grid[0].plot(center[0], center[1], "o", color="r", fillstyle="none", markersize=18, lw=8) grid[0].annotate("succ: {:.3g}".format(success), xy=center, xytext=(0, 8), textcoords='offset points', color="red", va="bottom", ha="center") grid[1].set_title("pcorr --- constrained and filtered") im = grid[1].imshow(filtered, **imshow_kwargs) grid.cbar_axes[0].colorbar(im) if log_base is not None: for dim in range(2): grid[dim].set_xscale("log", basex=log_base) grid[dim].get_xaxis().set_major_formatter(plt.ScalarFormatter()) xlabels = grid[dim].get_xticklabels(False, "both") for x in xlabels: x.set_ha("right") x.set_rotation_mode("anchor") x.set_rotation(40) labels = ("rotation / degrees", "scale change") # The common stuff for idx in range(2): grid[idx].grid(c="w") grid[idx].set_xlabel(labels[1]) grid[0].set_ylabel(labels[0]) return fig
fld0[fld_i[nfld + j, 0], fld_i[nfld + j, 1], :]) vf = [ -np.max([np.absolute(vf_m), np.absolute(vf_p)]), np.max([np.absolute(vf_m), np.absolute(vf_p)]) ] vdf_m = np.min(dfld[fld_i[nfld + j, 0], fld_i[nfld + j, 1], :].T - dfld0[fld_i[nfld + j, 0], fld_i[nfld + j, 1], :]) vdf_p = np.max(dfld[fld_i[nfld + j, 0], fld_i[nfld + j, 1], :].T - dfld0[fld_i[nfld + j, 0], fld_i[nfld + j, 1], :]) vdf = [ -np.max([np.absolute(vdf_m), np.absolute(vdf_p)]), np.max([np.absolute(vdf_m), np.absolute(vdf_p)]) ] ax = axg.ImageGrid(fig, 211 + j, nrows_ncols=(nr, nc), axes_pad=0.05, cbar_location='right', cbar_mode='single') for i in range(0, nc): hist, xe, ye = np.histogram2d( fld[fld_i[nfld + j, 0], fld_i[nfld + j, 1], t_i[i]] - fld0[fld_i[nfld + j, 0], fld_i[nfld + j, 1], t_i[i]], dfld[fld_i[nfld + j, 0], fld_i[nfld + j, 1], t_i[i]] - dfld0[fld_i[nfld + j, 0], fld_i[nfld + j, 1], t_i[i]], bins=n_bins, range=[vf, vdf], density=True) f_slice = ax[i].imshow(hist, cmap='viridis', aspect='equal', origin='lower') #, vmin=v[0], vmax=v[1])
def plot_error_transfer_matrix(pulse: Optional['PulseSequence'] = None, spectrum: Optional[ndarray] = None, omega: Optional[Coefficients] = None, error_transfer_matrix: Optional[ndarray] = None, n_oper_identifiers: Optional[ Sequence[int]] = None, basis_labels: Optional[Sequence[str]] = None, colorscale: str = 'linear', linthresh: Optional[float] = None, cbar_label: str = 'Error transfer matrix', basis_labelsize: Optional[int] = None, fig: Optional[Figure] = None, grid: Optional[Grid] = None, cmap: Optional[Colormap] = None, grid_kw: Optional[dict] = None, cbar_kw: Optional[dict] = None, imshow_kw: Optional[dict] = None, **figure_kw) -> FigureGrid: """ Plot the error transfer matrix for a given noise spectrum as an image. The function may be called with either a ``PulseSequence``, a spectrum, and a list of frequencies in which case the error transfer matrix is calculated for those parameters, or with a precomputed error transfer matrix. As of now, only auto-correlated spectra are implemented. Parameters ---------- pulse: 'PulseSequence' The pulse sequence. spectrum: ndarray The two-sided noise spectrum. omega: array_like The frequencies for which to evaluate the error transfer matrix. error_transfer_matrix: ndarray, shape A precomputed error transfer matrix. If given, *pulse*, *spectrum*, *omega* are not required. n_oper_identifiers: array_like, optional The identifiers of the noise operators for which the error transfer matrix should be plotted. All identifiers can be accessed via ``pulse.n_oper_identifiers``. Defaults to all. basis_labels: array_like (str), optional Labels for the elements of the error transfer matrix (the basis elements). colorscale: str, optional The scale of the color code ('linear' or 'log' (default)) linthresh: float, optional The threshold below which the colorscale will be linear (only for 'log') colorscale cbar_label: str, optional The label for the colorbar. Default: 'Error transfer matrix'. basis_labelsize: int, optional The size in points for the basis labels. fig: matplotlib figure, optional A matplotlib figure instance to plot in grid: matplotlib ImageGrid, optional An ImageGrid instance to use for plotting. cmap: matplotlib colormap, optional The colormap for the matrix plot. grid_kw: dict, optional Dictionary with keyword arguments passed to the ImageGrid constructor. cbar_kw: dict, optional Dictionary with keyword arguments passed to the colorbar constructor. imshow_kw: dict, optional Dictionary with keyword arguments passed to imshow. figure_kw: optional Keyword argument dictionaries that are fed into the :func:`matplotlib.pyplot.figure` function if no *fig* instance is specified. Returns ------- fig: matplotlib figure The matplotlib figure instance used for plotting. grid: matplotlib ImageGrid The ImageGrid instance used for plotting. """ U = error_transfer_matrix if U is not None: if U.ndim == 2: U = np.array([U]) n_oper_inds = np.arange(len(U)) if n_oper_identifiers is None: if pulse is not None and len(pulse.n_oper_identifiers) == len(U): n_oper_identifiers = pulse.n_oper_identifiers else: n_oper_identifiers = [ f'$B_{{{i}}}$' for i in range(len(n_oper_inds)) ] else: if pulse is None or spectrum is None or omega is None: raise ValueError('Require either precomputed error transfer ' + 'matrix or pulse, spectrum, and omega as args.') n_oper_inds = util.get_indices_from_identifiers( pulse, n_oper_identifiers, 'noise') n_oper_identifiers = pulse.n_oper_identifiers[n_oper_inds] # Get the error transfer matrix U = numeric.error_transfer_matrix(pulse, spectrum, omega, n_oper_identifiers) if U.ndim == 4: # Only autocorrelated noise supported U = U[range(len(n_oper_inds)), range(len(n_oper_inds))] # Only autocorrelated noise implemented for now, ie U is real U = U.real if basis_labels is None: btype = pulse.basis.btype if pulse is not None else '' if btype == 'Pauli': n_qubits = int(np.log(U.shape[-1]) / np.log(4)) basis_labels = [ ''.join(tup) for tup in product(['I', 'X', 'Y', 'Z'], repeat=n_qubits) ] else: basis_labels = [f'$C_{{{i}}}$' for i in range(U.shape[-1])] else: if len(basis_labels) != U.shape[-1]: raise ValueError('Invalid number of basis_labels given') if grid is None: aspect_ratio = 2 / 3 n_rows = int(np.round(np.sqrt(aspect_ratio * len(n_oper_inds)))) n_cols = int(np.ceil(len(n_oper_inds) / n_rows)) grid_kw = grid_kw or {} grid_kw.setdefault('rect', 111) grid_kw.setdefault('nrows_ncols', (n_rows, n_cols)) grid_kw.setdefault('axes_pad', 0.3) grid_kw.setdefault('label_mode', 'L') grid_kw.setdefault('share_all', True) grid_kw.setdefault('direction', 'row') grid_kw.setdefault('cbar_mode', 'single') grid_kw.setdefault('cbar_pad', 0.3) if fig is None: figsize = figure_kw.pop('figsize', (8 * n_cols, 6 * n_rows)) fig = plt.figure(figsize=figsize, **figure_kw) grid = axes_grid1.ImageGrid(fig, **grid_kw) else: if len(grid) != len(n_oper_inds): raise ValueError('Size of supplied ImageGrid instance does not ' + 'match the number of n_oper_identifiers given!') fig = grid[0].get_figure() # Parse default arguments if cmap is not None: plt.get_cmap(cmap) else: cmap = plt.get_cmap('RdBu') Umax = U.max() Umin = -Umax if colorscale == 'log': linthresh = linthresh or np.abs(U).mean() / 10 norm = colors.SymLogNorm(linthresh=linthresh, vmin=Umin, vmax=Umax) else: # colorscale == 'linear' norm = colors.Normalize(vmin=Umin, vmax=Umax) imshow_kw = imshow_kw or {} imshow_kw.setdefault('origin', 'upper') imshow_kw.setdefault('interpolation', 'nearest') imshow_kw.setdefault('cmap', cmap) imshow_kw.setdefault('norm', norm) basis_labelsize = basis_labelsize or 8 # Draw the images for i, n_oper_identifier in enumerate(n_oper_identifiers): ax = grid[i] im = ax.imshow(U[i], **imshow_kw) ax.set_title(n_oper_identifier) ax.set_xticks(np.arange(U.shape[-1])) ax.set_yticks(np.arange(U.shape[-1])) ax.set_xticklabels(basis_labels, fontsize=basis_labelsize, rotation='vertical') ax.set_yticklabels(basis_labels, fontsize=basis_labelsize) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) # Set up the colorbar cbar_kw = cbar_kw or {} cbar_kw.setdefault('orientation', 'vertical') cbar = fig.colorbar(im, cax=grid.cbar_axes[0], **cbar_kw) cbar.set_label(cbar_label) return fig, grid
plotting the first 25 images. The samplers provide a `get_slice(begin, size)` method that allows us to easily select a block of samples. Alternatively, we can use the `generate_batch()` method to yield a batch. This can allow us to check that a batch contains the expected number of classes and examples per class. """ num_cols = num_rows = 5 # Get the first 25 examples. x_slice, y_slice = train_ds.get_slice(begin=0, size=num_cols * num_rows) fig = plt.figure(figsize=(6.0, 6.0)) grid = axes_grid1.ImageGrid(fig, 111, nrows_ncols=(num_cols, num_rows), axes_pad=0.1) for ax, im, label in zip(grid, x_slice, y_slice): ax.imshow(im) ax.axis("off") """ ## Embedding model Next we define a `SimilarityModel` using the Keras Functional API. The model is a standard convnet with the addition of a `MetricEmbedding` layer that applies L2 normalization. The metric embedding layer is helpful when using `Cosine` distance as we only care about the angle between the vectors. Additionally, the `SimilarityModel` provides a number of helper methods for:
def plot_oxz_many( data_list, grid, nrows, ncols, title_list=None, suptitle=None, draw_colorbar=True, figsize=None, savefig=None, clim=None, filename=None, y_title=1.0, y_suptitle=1.0, axes_pad=0.1, **plot_oxz_kwargs, ): """ Plot many Oxz plots on the same figure. Parameters ---------- data_list : List[ndarray] Data are plotted from top left to bottom right, row per row. grid : Grid nrows : int ncols : int title_list : List[str] or None suptitle : str or None draw_colorbar : boolean Default: True figsize : List[Float] or None Default: ``conf['plot_oxz_many.figsize']`` savefig: boolean Default: ``conf['savefig']`` clim : Color limit. Common for all plots. filename y_title : float Adjust y location of the titles. y_suptitle : float Adjust y location of the titles. axes_pad : float Pad between images in inches plot_oxz_kwargs Returns ------- axes_grid : axes_grid1.ImageGrid im_list """ if savefig is None: savefig = conf["savefig"] if figsize is None: figsize = conf["plot_oxz_many.figsize"] if title_list is None: title_list = [None] * len(data_list) # must use a common clim (otherwise the figure does not make sense) if clim is None: clim = ( min(np.nanmin(x) for x in data_list), max(np.nanmax(x) for x in data_list), ) if draw_colorbar: cbar_mode = "single" else: cbar_mode = None fig = plt.figure(figsize=figsize) axes_grid = axes_grid1.ImageGrid( fig, 111, nrows_ncols=(nrows, ncols), axes_pad=axes_pad, share_all=True, cbar_mode=cbar_mode, ) images = [] for data, title, ax in zip(data_list, title_list, axes_grid): # the current function handles saving fig, drawing the cbar and displaying the title # so we prevent plot_oxz to do it. ax, im = plot_oxz( data, grid, ax=ax, clim=clim, draw_cbar=False, savefig=False, **plot_oxz_kwargs, title=None, ) images.append(im) if title is not None: ax.set_title(title, y=y_title) if suptitle is not None: fig.suptitle(suptitle, y=y_suptitle, size="x-large") if draw_colorbar: cax = axes_grid.cbar_axes[0] fig.colorbar(im, cax=cax) cax.set_aspect(20, adjustable="box") if savefig: if filename is None: raise ValueError("filename must be provided when savefig is true") fig.savefig(filename) return axes_grid, images
def plot_cumulant_function(pulse: Optional['PulseSequence'] = None, spectrum: Optional[ndarray] = None, omega: Optional[Coefficients] = None, cumulant_function: Optional[ndarray] = None, n_oper_identifiers: Optional[Sequence[int]] = None, second_order: bool = False, colorscale: str = 'linear', linthresh: Optional[float] = None, basis_labels: Optional[Sequence[str]] = None, basis_labelsize: Optional[int] = None, cbar_label: str = 'Cumulant Function', cbar_labelsize: Optional[int] = None, fig: Optional[Figure] = None, grid: Optional[Grid] = None, cmap: Optional[Colormap] = None, grid_kw: Optional[dict] = None, cbar_kw: Optional[dict] = None, imshow_kw: Optional[dict] = None, **figure_kw) -> FigureGrid: r"""Plot the cumulant function for a given noise spectrum as an image. The cumulant function generates the error transfer matrix :math:`\tilde{\mathcal{U}}` exactly for Gaussian noise and to second order for non-Gaussian noise. The function may be called with either a ``PulseSequence``, a spectrum, and a list of frequencies in which case the cumulant function is calculated for those parameters, or with a precomputed cumulant function. As of now, only auto-correlated spectra are implemented. Parameters ---------- pulse: 'PulseSequence' The pulse sequence. spectrum: ndarray The two-sided noise spectrum. omega: array_like The frequencies for which to evaluate the error transfer matrix. cumulant_function: ndarray, shape (n_nops, d**2, d**2) A precomputed cumulant function. If given, *pulse*, *spectrum*, *omega* are not required. n_oper_identifiers: array_like, optional The identifiers of the noise operators for which the cumulant function should be plotted. All identifiers can be accessed via ``pulse.n_oper_identifiers``. Defaults to all. second_order: bool, optional Also take into account the frequency shifts :math:`\Delta` that correspond to second order Magnus expansion and constitute unitary terms. Default ``False``. colorscale: str, optional The scale of the color code ('linear' or 'log' (default)) linthresh: float, optional The threshold below which the colorscale will be linear (only for 'log') colorscale basis_labels: array_like (str), optional Custom labels for the elements of the cumulant function (the basis elements). Grabbed from the basis by default. basis_labelsize: int, optional The size in points for the basis labels. cbar_label: str, optional The label for the colorbar. Default: 'Cumulant Function'. cbar_labelsize: int, optional The size in points for the colorbar label. fig: matplotlib figure, optional A matplotlib figure instance to plot in grid: matplotlib ImageGrid, optional An ImageGrid instance to use for plotting. cmap: matplotlib colormap, optional The colormap for the matrix plot. grid_kw: dict, optional Dictionary with keyword arguments passed to the ImageGrid constructor. cbar_kw: dict, optional Dictionary with keyword arguments passed to the colorbar constructor. imshow_kw: dict, optional Dictionary with keyword arguments passed to imshow. figure_kw: optional Keyword argument dictionaries that are fed into the :func:`matplotlib.pyplot.figure` function if no *fig* instance is specified. Returns ------- fig: matplotlib figure The matplotlib figure instance used for plotting. grid: matplotlib ImageGrid The ImageGrid instance used for plotting. """ K = cumulant_function if K is not None: if K.ndim == 2: K = np.array([K]) n_oper_inds = np.arange(len(K)) if n_oper_identifiers is None: if pulse is not None and len(pulse.n_oper_identifiers) == len(K): n_oper_identifiers = pulse.n_oper_identifiers else: n_oper_identifiers = [ f'$B_{{{i}}}$' for i in range(len(n_oper_inds)) ] else: if len(n_oper_identifiers) != len(K): raise ValueError( 'Both precomputed cumulant function and n_oper_identifiers ' + f'given but not same len: {len(K)} != {len(n_oper_identifiers)}' ) else: if pulse is None or spectrum is None or omega is None: raise ValueError('Require either precomputed cumulant function ' + 'or pulse, spectrum, and omega as arguments.') n_oper_inds = util.get_indices_from_identifiers( pulse.n_oper_identifiers, n_oper_identifiers) n_oper_identifiers = pulse.n_oper_identifiers[n_oper_inds] K = numeric.calculate_cumulant_function(pulse, spectrum, omega, n_oper_identifiers, 'total', second_order) if K.ndim == 4: # Only autocorrelated noise supported K = K[tuple(n_oper_inds), tuple(n_oper_inds)] # Only autocorrelated noise implemented for now, ie K is real K = K.real if basis_labels is None: if pulse is not None: basis_labels = pulse.basis.labels else: basis_labels = [f'$C_{{{i}}}$' for i in range(K.shape[-1])] else: if basis_labels is not None and len(basis_labels) != K.shape[-1]: raise ValueError('Invalid number of basis_labels given') basis_labels = [_make_str_tex_compatible(bl) for bl in basis_labels] if grid is None: aspect_ratio = 2 / 3 n_rows = int(np.round(np.sqrt(aspect_ratio * len(n_oper_inds)))) n_cols = int(np.ceil(len(n_oper_inds) / n_rows)) grid_kw = grid_kw or {} grid_kw.setdefault('rect', 111) grid_kw.setdefault('nrows_ncols', (n_rows, n_cols)) grid_kw.setdefault('axes_pad', 0.3) grid_kw.setdefault('label_mode', 'L') grid_kw.setdefault('share_all', True) grid_kw.setdefault('direction', 'row') grid_kw.setdefault('cbar_mode', 'single') grid_kw.setdefault('cbar_pad', 0.3) if fig is None: figsize = figure_kw.pop('figsize', (8 * n_cols, 6 * n_rows)) fig = plt.figure(figsize=figsize, **figure_kw) grid = axes_grid1.ImageGrid(fig, **grid_kw) else: if len(grid) != len(n_oper_inds): raise ValueError('Size of supplied ImageGrid instance does not ' + 'match the number of n_oper_identifiers given!') fig = grid[0].get_figure() # Parse default arguments if cmap is not None: plt.get_cmap(cmap) else: cmap = plt.get_cmap('RdBu') Kmax = np.abs(K).max() Kmin = -Kmax if colorscale == 'log': linthresh = np.abs(K).mean() / 10 if linthresh is None else linthresh norm = colors.SymLogNorm(linthresh=linthresh, vmin=Kmin, vmax=Kmax) else: # colorscale == 'linear' norm = colors.Normalize(vmin=Kmin, vmax=Kmax) imshow_kw = imshow_kw or {} imshow_kw.setdefault('origin', 'upper') imshow_kw.setdefault('interpolation', 'nearest') imshow_kw.setdefault('cmap', cmap) imshow_kw.setdefault('norm', norm) basis_labelsize = basis_labelsize or 8 cbar_labelsize = cbar_labelsize or plt.rcParams['axes.labelsize'] # Draw the images for i, n_oper_identifier in enumerate(n_oper_identifiers): ax = grid[i] im = ax.imshow(K[i], **imshow_kw) ax.set_title(n_oper_identifier, loc='left') ax.set_xticks(np.arange(K.shape[-1])) ax.set_yticks(np.arange(K.shape[-1])) ax.set_xticklabels(basis_labels, fontsize=basis_labelsize, rotation='vertical') ax.set_yticklabels(basis_labels, fontsize=basis_labelsize) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) # Set up the colorbar cbar_kw = cbar_kw or {} cbar_kw.setdefault('orientation', 'vertical') cbar = fig.colorbar(im, cax=grid.cbar_axes[0], **cbar_kw) cbar.set_label(_make_str_tex_compatible(cbar_label), fontsize=cbar_labelsize) return fig, grid
def plotFigure(f, opt, canvas): if opt['axesgrid'] is not None: fig = plt.figure(figsize=opt['figSize']) grid = axesgrid.AxesGrid(fig, 111, **opt['axesgrid']) axs = [] for r in range(opt['nrows']): for c in range(opt['ncols']): index = r * opt['ncols'] + c axs.append(grid[index]) axis = canvas[index]['axis'] if 'projection' in axis and axis['projection'] is not None: apy.shell.exit( 'Projection needs to be implemented for the axesgrid (plot.py)' ) elif opt['imagegrid'] is not None: fig = plt.figure(figsize=opt['figSize']) if 'nrows_ncols' not in opt['imagegrid']: opt['imagegrid']['nrows_ncols'] = (opt['nrows'], opt['ncols']) grid = axesgrid.ImageGrid(fig, 111, **opt['imagegrid']) axs = [] for r in range(opt['nrows']): for c in range(opt['ncols']): index = r * opt['ncols'] + c axs.append(grid[index]) axis = canvas[index]['axis'] if 'projection' in axis and axis['projection'] is not None: apy.shell.exit( 'Projection needs to be implemented for the axesgrid (plot.py)' ) elif opt['gridspec'] is not None: # Create a figure using gridspec to get a tight layout fig = plt.figure(figsize=opt['figSize']) gs = mpl.gridspec.GridSpec(opt['nrows'], opt['ncols'], **opt['gridspec']) #if isinstance(opt['gridspec'],dict): # gs.update(**opt['gridspec']) axs = [] for r in range(opt['nrows']): for c in range(opt['ncols']): index = r * opt['ncols'] + c if opt['merge'] and opt['merge'][0] == index: ax = fig.add_subplot(gs[r, :]) axs.append(ax) elif opt['merge'] and opt['merge'][1] == index: continue else: axs.append(plt.subplot(gs[index])) axis = canvas[index]['axis'] if 'projection' in axis and axis['projection'] is not None: apy.shell.exit( 'Projection needs to be implemented for the gridspec (plot.py)' ) else: # Create a figure and plot all subplots fig = plt.figure(figsize=opt['figSize']) axs = [] for r in range(opt['nrows']): for c in range(opt['ncols']): index = r * opt['ncols'] + c projection = '3d' if canvas[index]['subplot'][3] else None figure = fig.add_subplot(opt['nrows'], opt['ncols'], index + 1, projection=projection) axs.append(figure) for canv in canvas: spIndex, spRows, spCols, spXYZ = canv['subplot'] plotSubplot(axs[spIndex], opt, canv, f) if opt['gridspec'] is None and opt['axesgrid'] is None: plt.tight_layout() # Create a new directory and save the figure apy.shell.mkdir(opt['dirResults'], 'u') plt.savefig(opt['fileName'] % f, bbox_inches='tight') # Close figure plt.close(fig)