code: def plot_engine_status(
      engine: Engine,
      logger: Any,
      title: str = "Training Log",
      yscale: str = "log",
      avg_keys: tuple[str] = (LOSS_NAME,),
      window_fraction: int = 20,
      image_fn: Callable[[str, torch.Tensor], Any]
      | None = tensor_to_images,
      fig: plt.Figure | None = None,
      selected_inst: int = 0,
  ) -> tuple[plt.Figure, list]:
      """
      Plot the status of the given Engine with its logger. The plot will consist of a graph of loss values and metrics
      taken from the logger, and images taken from the `output` and `batch` members of `engine.state`. The images are
      converted to Numpy arrays suitable for input to `Axes.imshow` using `image_fn`, if this is None then no image
      plotting is done.
  
      Args:
          engine: Engine to extract images from
          logger: MetricLogger to extract loss and metric data from
          title: graph title
          yscale: for metric plot, scale for y-axis compatible with `Axes.set_yscale`
          avg_keys: for metric plot, tuple of keys in `graphmap` to provide running average plots for
          window_fraction: for metric plot, what fraction of the graph value length to use as the running average window
          image_fn: callable converting tensors keyed to a name in the Engine to a tuple of images to plot
          fig: Figure object to plot into, reuse from previous plotting for flicker-free refreshing
          selected_inst: index of the instance to show in the image plot
  
      Returns:
          Figure object (or `fig` if given), list of Axes objects for graph and images
      """
      if fig is not None:
          fig.clf()
      else:
          fig = plt.Figure(
              figsize=(20, 10), tight_layout=True, facecolor="white"
          )
  
      graphmap: dict[str, list[float]] = {LOSS_NAME: logger.loss}
      graphmap.update(logger.metrics)
  
      imagemap: dict = {}
      if (
          image_fn is not None
          and engine.state is not None
          and engine.state.batch is not None
      ):
          for src in (engine.state.batch, engine.state.output):
              label = "Batch" if src is engine.state.batch else "Output"
              batch_selected_inst = selected_inst  # selected batch index, set to 0 when src is decollated
  
              # if the src object is a list of elements, ie. a decollated batch, select an element and keep it as
              # a dictionary of tensors with a batch dimension added
              if isinstance(src, list):
                  selected_dict = src[
                      selected_inst
                  ]  # select this element
                  batch_selected_inst = 0  # set the selection to be the single index in the batch dimension
                  # store each tensor that is interpretable as an image with an added batch dimension
                  src = {
                      k: v[None]
                      for k, v in selected_dict.items()
                      if isinstance(v, torch.Tensor) and v.ndim >= 3
                  }
  
              # images will be generated from the batch item selected above only, or from the single item given as `src`
  
              if isinstance(src, dict):
                  for k, v in src.items():
                      if isinstance(v, torch.Tensor) and v.ndim >= 4:
                          image = image_fn(k, v[batch_selected_inst])
  
                          # if we have images add each one separately to the map
                          if image is not None:
                              for i, im in enumerate(image):
                                  imagemap[f"{k}_{i}"] = im
  
              elif isinstance(src, torch.Tensor):
                  image = image_fn(label, src)
                  if image is not None:
                      imagemap[f"{label}_{i}"] = image
  
      axes = plot_metric_images(
          fig,
          title,
          graphmap,
          imagemap,
          yscale,
          avg_keys,
          window_fraction,
      )
  
      if logger.loss:
          axes[0].axhline(
              logger.loss[-1][1], c="k", ls=":"
          )  # draw dotted horizontal line at last loss value
  
      return fig, axes
  
imports: from __future__ import annotations
  import copy
  from collections.abc import Callable, Mapping
  from enum import Enum
  from threading import RLock, Thread
  from typing import TYPE_CHECKING, Any
  import numpy
  import torch
  from monai.config import IgniteInfo
  from monai.utils.module import min_version, optional_import
label_desc: Use image node_id 4 for calling a global function with example usage: plot_engine_status(engine, logger, title, yscale, avg_keys, window_fraction, image_fn, fig, selected_inst) and returns: fig,  axes