# Tactiverge Academy — companion code for "Practical control: saturation, windup, noise and delay"
# Lesson: https://tactiverge.win/academy/robotics-foundations/introduction-to-feedback-control/practical-control-issues/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def simulate(anti_windup, kp=5.0, ki=10.0, u_max=1.5, dt=0.01, t_end=10.0):
    y, integral, peak = 0.0, 0.0, 0.0
    for _ in range(int(t_end / dt)):
        error = 1.0 - y
        u_wanted = kp * error + ki * integral
        u = max(-u_max, min(u_max, u_wanted))     # the actuator's limit
        pinned = u != u_wanted and (u_wanted > 0) == (error > 0)
        if not (anti_windup and pinned):
            integral += error * dt
        y += dt * (-y + u)                        # first-order plant, K = 1, tau = 1 s
        peak = max(peak, y)
    return peak

print(f"peak without anti-windup: {simulate(False):.3f}")
print(f"peak with anti-windup:    {simulate(True):.3f}")


# ── Example 2 ────────────────────────────────────────
def run(kp, delay, steps=8):
    pos = [0.0]
    for k in range(steps):
        seen = pos[max(0, k - delay)]      # the controller sees an old reading
        pos.append(pos[k] + kp * (100 - seen))
    return pos

for kp in (0.5, 1.0):
    for delay in (0, 1):
        print(f"Kp={kp} delay={delay}:", " ".join(f"{p:6.1f}" for p in run(kp, delay)))
