def _single_peak(values, relative_cutoff, minval, invalidate_distance):
  """Takes a single peak if it is high enough compared to all other peaks.

  Args:
    values: 1D tensor of values to take the peaks on.
    relative_cutoff: The fraction of the highest peak which all other peaks
      should be below.
    minval: The peak should have at least this value.
    invalidate_distance: Exclude values that are up to invalidate_distance away
      from the peak.

  Returns:
    The index of the single peak in `values`, or -1 if there is not a single
        peak that satisfies `relative_cutoff`.
  """
  relative_cutoff = tf.convert_to_tensor(relative_cutoff, tf.float32)

  # argmax is safe because the histogram is always non-empty.
  peak = tf.to_int32(tf.argmax(values))
  # Take values > minval away from the peak.
  other_values = tf.boolean_mask(
      values,
      tf.greater(
          tf.abs(tf.range(tf.shape(values)[0]) - peak), invalidate_distance))
  should_take_peak = tf.logical_and(
      tf.greater_equal(values[peak], minval),
      # values[peak] * relative_cutoff must be >= other_values.
      tf.reduce_all(
          tf.greater_equal(
              tf.to_float(values[peak]) * relative_cutoff,
              tf.to_float(other_values))))
  return tf.cond(should_take_peak, lambda: peak, lambda: -1)