# Tactiverge Academy — companion code for "Writing and testing functions"
# Lesson: https://tactiverge.win/academy/computational-engineering/python-fundamentals/writing-and-testing-functions/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def show_speed(rpm):
    print(f"Speed: {rpm} rpm")

result = show_speed(120)
print(result)


# ── Example 2 ────────────────────────────────────────
def adc_to_volts(counts, vref=3.3, max_count=1023):
    """Convert a raw analog-to-digital converter reading to volts.

    counts: the integer reading, from 0 to max_count.
    vref: the reference voltage in volts, which gives max_count.
    max_count: the largest reading the converter can produce.
    Returns the voltage as a float.
    """
    return counts * vref / max_count

print(adc_to_volts(1023))
print(f"{adc_to_volts(2048, vref=5.0, max_count=4095):.3f}")


# ── Example 3 ────────────────────────────────────────
def min_max(values):
    """Return the smallest and largest of a non-empty list of numbers."""
    return min(values), max(values)

low, high = min_max([12.1, 12.4, 11.9, 12.6])
print(low, high)
print(f"Spread: {high - low:.1f}")


# ── Example 4 ────────────────────────────────────────
import math

def wheel_distance_mm(ticks, ticks_per_rev, diameter_mm):
    """Distance rolled by a wheel, in mm, from encoder ticks.

    Negative ticks mean the wheel turned backwards.
    """
    revolutions = ticks / ticks_per_rev
    return revolutions * math.pi * diameter_mm

def test_wheel_distance():
    # No ticks: no distance.
    assert wheel_distance_mm(0, 360, 65) == 0
    # One revolution: one circumference, worked out by hand.
    assert math.isclose(wheel_distance_mm(360, 360, 65), 204.2035, rel_tol=1e-6)
    # Half a revolution: half the distance.
    assert math.isclose(wheel_distance_mm(180, 360, 65), 0.5 * math.pi * 65)
    # Backwards: same size, opposite sign.
    assert math.isclose(wheel_distance_mm(-360, 360, 65), -math.pi * 65)

test_wheel_distance()
print("wheel_distance_mm: all tests passed")


# ── Example 5 ────────────────────────────────────────
def clamp(value, low, high):
    """Limit value to the range low to high."""
    if value < low:
        return low
    if value > high:
        return low      # bug: should be high
    return value

def test_clamp():
    assert clamp(50, 0, 100) == 50, "inside the range"
    assert clamp(-20, 0, 100) == 0, "below the range"
    assert clamp(150, 0, 100) == 100, "above the range"
    assert clamp(0, 0, 100) == 0, "exactly on the lower edge"
    assert clamp(100, 0, 100) == 100, "exactly on the upper edge"

try:
    test_clamp()
    print("clamp: all tests passed")
except AssertionError as error:
    print("clamp: test FAILED:", error)
