Emit a triangle wave at the given frequency.

def triangle_wave(frequency):
  """Emit a triangle wave at the given frequency."""
  xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
  ts = xs / FLAGS.sample_rate
  #
  # A triangle wave looks like this:
  #
  #      /\      /\
  #     /  \    /  \
  #         \  /    \  /
  #          \/      \/
  #
  # If we look at just half a period (the first four slashes in the
  # diagram above), we can see that it looks like a transformed absolute
  # value function.
  #
  # Let's start by computing the times relative to the start of each
  # half-wave pulse (each individual "mountain" or "valley", of which
  # there are four in the above diagram).
  half_pulse_index = ts * (frequency * 2)
  half_pulse_angle = half_pulse_index % 1.0  # in [0, 1]
  #
  # Now, we can see that each positive half-pulse ("mountain") has
  # amplitude given by A(z) = 0.5 - abs(z - 0.5), and then normalized:
  absolute_amplitude = (0.5 - tf.abs(half_pulse_angle - 0.5)) / 0.5
  #
  # But every other half-pulse is negative, so we should invert these.
  half_pulse_parity = tf.sign(1 - (half_pulse_index % 2.0))
  amplitude = half_pulse_parity * absolute_amplitude
  #
  # This is precisely the desired result, so we're done!
  return amplitude