code: '''
  metrics
  
  Contact: adalca@csail.mit.edu
  '''
  
  #  imports
  import numpy as np
  
  
  def dice(vol1, vol2, labels=None, nargout=1):
      '''
      Dice [1] volume overlap metric
  
      The default is to *not* return a measure for the background layer (label = 0)
  
      [1] Dice, Lee R. "Measures of the amount of ecologic association between species."
      Ecology 26.3 (1945): 297-302.
  
      Parameters
      ----------
      vol1 : nd array. The first volume (e.g. predicted volume)
      vol2 : nd array. The second volume (e.g. "true" volume)
      labels : optional vector of labels on which to compute Dice.
          If this is not provided, Dice is computed on all non-background (non-0) labels
      nargout : optional control of output arguments. if 1, output Dice measure(s).
          if 2, output tuple of (Dice, labels)
  
      Output
      ------
      if nargout == 1 : dice : vector of dice measures for each labels
      if nargout == 2 : (dice, labels) : where labels is a vector of the labels on which
          dice was computed
      '''
      if labels is None:
          labels = np.unique(np.concatenate((vol1, vol2)))
          labels = np.delete(labels, np.where(labels == 0))  # remove background
  
      dicem = np.zeros(len(labels))
      for idx, lab in enumerate(labels):
          top = 2 * np.sum(np.logical_and(vol1 == lab, vol2 == lab))
          bottom = np.sum(vol1 == lab) + np.sum(vol2 == lab)
          bottom = np.maximum(bottom, np.finfo(float).eps)  # add epsilon.
          dicem[idx] = top / bottom
  
      if nargout == 1:
          return dicem
      else:
          return (dicem, labels)
  
apis: numpy.sum numpy.finfo numpy.concatenate numpy.logical_and numpy.where