# step5_satellite.py — the satellite signal.
# A radar satellite takes a picture before and a picture after. Water looks dark.
# We subtract the two pictures. Every cell that changed a lot is "changed".
# New here: changed_fraction() and satellite_score().

# Two tiny radar pictures, 6 by 6 cells. 9 is bright (dry land), 0 is dark (water).
BEFORE = [
    [7, 8, 7, 6, 8, 7],
    [8, 7, 2, 6, 7, 8],   # the river is the dark 2 in the middle
    [7, 6, 2, 7, 8, 7],
    [8, 7, 2, 6, 7, 6],
    [7, 8, 3, 7, 8, 7],
    [8, 7, 2, 7, 7, 8],
]
AFTER = [
    [7, 8, 7, 6, 8, 7],
    [8, 2, 1, 2, 7, 8],   # the dark water is wider now
    [7, 1, 1, 2, 2, 7],
    [2, 1, 1, 2, 1, 6],
    [7, 2, 1, 1, 2, 7],
    [8, 7, 2, 2, 7, 8],
]
BIG_CHANGE = 4   # a cell that changed by 4 or more is a real change, not noise


def ramp(value, low, high):
    """0 below low, 1 above high, a straight line between them."""
    if value <= low:
        return 0.0
    if value >= high:
        return 1.0
    return (value - low) / (high - low)


def changed_fraction(before, after):
    """What part of the picture changed? 0.0 is nothing, 1.0 is everything."""
    changed = 0
    total = 0
    for row_before, row_after in zip(before, after):
        for old, new in zip(row_before, row_after):
            total += 1
            if abs(new - old) >= BIG_CHANGE:
                changed += 1
    return changed / total


def satellite_score(fraction):
    """5 percent changed is noise. 30 percent changed is a flood."""
    return ramp(fraction, 0.05, 0.30)


def main():
    fraction = changed_fraction(BEFORE, AFTER)
    print(f"changed: {fraction:.0%} of the picture")
    print(f"satellite score: {satellite_score(fraction):.2f}")
    for row_before, row_after in zip(BEFORE, AFTER):
        pairs = zip(row_before, row_after)
        marks = ["#" if abs(new - old) >= BIG_CHANGE else "." for old, new in pairs]
        print(" ".join(marks))


if __name__ == "__main__":
    main()
