def _clamp_transpose(transpose_amount, ns_min_pitch, ns_max_pitch,
                     min_allowed_pitch, max_allowed_pitch):
  """Clamps the specified transpose amount to keep a ns in the desired bounds.

  Args:
    transpose_amount: Number of steps to transpose up or down.
    ns_min_pitch: The lowest pitch in the target note sequence.
    ns_max_pitch: The highest pitch in the target note sequence.
    min_allowed_pitch: The lowest pitch that should be allowed in the transposed
      note sequence.
    max_allowed_pitch: The highest pitch that should be allowed in the
      transposed note sequence.

  Returns:
    A new transpose amount that, if applied to the target note sequence, will
    keep all notes within the range [MIN_PITCH, MAX_PITCH]
  """
  if transpose_amount < 0:
    transpose_amount = -min(ns_min_pitch - min_allowed_pitch,
                            abs(transpose_amount))
  else:
    transpose_amount = min(max_allowed_pitch - ns_max_pitch, transpose_amount)
  return transpose_amount