def _estimate_staffline_thickness(columns, values, lengths, staffline_distance):
  """Estimates the staffline thickness of a music score.

  Args:
    columns: 1D array. The column indices of each consecutive vertical run.
    values: 1D array. The value (0 or 1) of each vertical run.
    lengths: 1D array. The length of each vertical run.
    staffline_distance: A 1D tensor of the possible staffline distances in the
      image. One of the distances may be chosen arbitrarily.

  Returns:
    A scalar tensor with the staffline thickness for the entire page, or -1 if
      it could not be estimated (staffline_distance is empty, or there are not
      enough runs to estimate the staffline thickness).
  """

  with tf.name_scope('estimate_staffline_thickness'):

    def do_estimate():
      """Compute the thickness if distance detection was successful."""
      run_pair_lengths = lengths[:-1] + lengths[1:]
      # Use the smallest staffline distance to estimate the staffline thickness.
      keep_pair = tf.logical_and(
          tf.equal(columns[:-1], columns[1:]),
          tf.equal(run_pair_lengths, staffline_distance[0]))

      run_pair_lengths = tf.boolean_mask(run_pair_lengths, keep_pair)
      start_values = tf.boolean_mask(values[:-1], keep_pair)
      start_lengths = tf.boolean_mask(lengths[:-1], keep_pair)
      end_lengths = tf.boolean_mask(lengths[1:], keep_pair)

      staffline_thickness_values = tf.where(
          tf.not_equal(start_values, 0), start_lengths, end_lengths)
      staffline_thickness_histogram = tf.bincount(
          staffline_thickness_values,
          minlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE,
          maxlength=_MAX_STAFFLINE_DISTANCE_THICKNESS_VALUE)

      return _single_peak(
          staffline_thickness_histogram,
          _PEAK_CUTOFF,
          minval=1,
          invalidate_distance=_STAFFLINE_THICKNESS_INVALIDATE_DISTANCE)

    return tf.cond(
        tf.greater(tf.shape(staffline_distance)[0], 0), do_estimate,
        lambda: tf.constant(-1, tf.int32))