"""Animaciones (GIF) del simulador. Dos tipos: - barrido de un parámetro dentro de un rango: en cada fotograma se ven los polos en el plano s, la respuesta temporal y una barra con el rango del parámetro coloreada según la estabilidad, de modo que se ve el instante en que un polo cruza el eje imaginario y el sistema pasa a ser inestable; - evolución temporal: las señales del lazo se dibujan a medida que avanza el tiempo, con los cambios de consigna y la perturbación. """ import math import tempfile import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure from PIL import Image from scipy import signal import graficas as gf COLOR = {"estable": gf.VERDE, "límite": gf.AMBAR, "inestable": gf.ROJO} CLARO = {"estable": "#cfe5cf", "límite": "#f1e2b8", "inestable": "#f2cccc"} ROTULO = {"estable": "ESTABLE", "límite": "LÍMITE DE ESTABILIDAD", "inestable": "INESTABLE"} def estado_de(polos, tol=1e-7): polos = np.asarray(polos, dtype=complex) if polos.size == 0: return "estable" m = float(np.max(polos.real)) esc = max(1.0, float(np.max(np.abs(polos)))) if m > tol * esc: return "inestable" if m > -tol * esc: return "límite" return "estable" def respuesta_num(num, den, tt, u=None, impulso=False): """Respuesta numérica de num/den (escalón u, o impulso), recortada si diverge.""" with np.errstate(all="ignore"): try: if impulso: _, y = signal.impulse((num, den), T=tt) else: _, y, _ = signal.lsim((num, den), u, tt) except Exception: # noqa: BLE001 y = np.full_like(tt, np.nan) y = np.asarray(y, float) y[~np.isfinite(y)] = np.nan return np.clip(y, -1e6, 1e6) def criticos(valores, f_maxre): """Valores del parámetro en que la parte real máxima de los polos cruza 0 (bisección).""" out = [] fr = [f_maxre(v) for v in valores] for i in range(len(valores) - 1): a, b, fa, fb = valores[i], valores[i + 1], fr[i], fr[i + 1] if not (np.isfinite(fa) and np.isfinite(fb)) or (fa > 0) == (fb > 0): continue for _ in range(50): m = 0.5 * (a + b) fm = f_maxre(m) if (fm > 0) == (fa > 0): a, fa = m, fm else: b = m vc = 0.5 * (a + b) out.append(0.0 if abs(vc) < 1e-7 * max(abs(valores[-1] - valores[0]), 1e-12) else vc) return out def _a_imagen(canvas): w, h = canvas.get_width_height() return Image.frombuffer("RGBA", (w, h), canvas.buffer_rgba(), "raw", "RGBA", 0, 1).convert("RGB") def _guarda_gif(fig, actualiza, n, fps, prefijo): canvas = FigureCanvasAgg(fig) actualiza(0) canvas.draw() primera = _a_imagen(canvas) paleta = primera.quantize(colors=128, method=Image.Quantize.MEDIANCUT) imgs = [primera.quantize(palette=paleta, dither=Image.Dither.NONE)] for k in range(1, n): actualiza(k) canvas.draw() imgs.append(_a_imagen(canvas).quantize(palette=paleta, dither=Image.Dither.NONE)) ruta = tempfile.NamedTemporaryFile(prefix=prefijo, suffix=".gif", delete=False).name dur = [int(1000 / fps)] * n dur[-1] = 1500 # pausa al final antes de repetir imgs[0].save(ruta, save_all=True, append_images=imgs[1:], duration=dur, loop=0, disposal=1) return ruta def _limites_plano(puntos): pts = np.asarray([p for p in puntos if np.isfinite(p)], dtype=complex) if pts.size == 0: return -2.0, 1.0, 1.5 mag = np.abs(pts) lim = np.percentile(mag, 92) * 1.8 + 0.5 pts = pts[mag <= lim] xmin = min(float(np.min(pts.real)), 0.0) xmax = max(float(np.max(pts.real)), 0.0) ymax = max(float(np.max(np.abs(pts.imag))), 0.0) span = max(xmax - xmin, 2 * ymax, 1.0) xmin -= 0.15 * span xmax += 0.15 * span ymax = max(ymax * 1.25, 0.3 * (xmax - xmin)) R = 1.25 if (xmax - xmin) / (2 * ymax) < R: extra = R * 2 * ymax - (xmax - xmin) xmin, xmax = xmin - extra / 2, xmax + extra / 2 else: ymax = (xmax - xmin) / (2 * R) return xmin, xmax, ymax def gif_barrido(frames, nombre, tt, *, yref=None, ylabel=r"$y(t)$", criticos_=(), fps=8, nota_resp=""): """frames: [{'v', 'polos', 'ceros', 'y', 'estado'}]. Devuelve la ruta del GIF.""" fig = Figure(figsize=(9.6, 5.0), dpi=84) fig.patch.set_facecolor("white") ax_s = fig.add_axes([0.075, 0.31, 0.38, 0.56]) ax_t = fig.add_axes([0.555, 0.31, 0.42, 0.56]) ax_b = fig.add_axes([0.075, 0.1, 0.9, 0.06]) todos = np.concatenate([np.asarray(f["polos"], complex) for f in frames] + [np.asarray(f["ceros"], complex) for f in frames]) xmin, xmax, ymax = _limites_plano(todos) ax_s.axvspan(xmin, 0, color="#f5f5f5", zorder=0, lw=0) ax_s.axhline(0, color=gf.NEGRO, lw=0.6) ax_s.axvline(0, color=gf.NEGRO, lw=0.9) ax_s.text(0.02, 0.97, "estable", transform=ax_s.transAxes, fontsize=8.5, va="top", style="italic", color="#555") ax_s.text(0.98, 0.97, "inestable", transform=ax_s.transAxes, fontsize=8.5, va="top", ha="right", style="italic", color="#555") for f in frames: p = np.asarray(f["polos"], complex) if p.size: ax_s.scatter(p.real, p.imag, s=5, color=CLARO[f["estado"]] if f["estado"] != "estable" else "#b9d3e8", lw=0, zorder=1) pol_line, = ax_s.plot([], [], "x", ms=11, mew=2.3, zorder=5) cer_line, = ax_s.plot([], [], "o", ms=9, mfc="white", mew=1.6, color=gf.NEGRO, zorder=5) ax_s.set_xlim(xmin, xmax) ax_s.set_ylim(-ymax, ymax) ax_s.set_aspect("equal", adjustable="box") ax_s.set_xlabel(r"Real, $\sigma$") ax_s.set_ylabel(r"Imaginario, $j\omega$") ax_s.grid(True) ax_s.set_title("polos (×) y ceros (○)", fontsize=10) ys_est = [f["y"] for f in frames if f["estado"] == "estable" and np.all(np.isfinite(f["y"]))] if ys_est: lo = min(0.0, float(min(np.min(y) for y in ys_est))) hi = float(max(np.max(y) for y in ys_est)) else: base = abs(yref) if yref else 1.0 lo, hi = -2 * base, 3 * base if yref is not None: lo, hi = min(lo, 0.0, yref), max(hi, yref * 1.1) span = max(hi - lo, 1e-6) lo, hi = lo - 0.1 * span, hi + 0.12 * span for f in frames: if f["estado"] == "estable": ax_t.plot(tt, f["y"], color="#e4e4e4", lw=0.5, zorder=1) if yref is not None: ax_t.axhline(yref, color=gf.GRIS, ls="--", lw=1.0, zorder=2) resp_line, = ax_t.plot([], [], lw=2.0, zorder=4) ax_t.axhline(0, color=gf.NEGRO, lw=0.4) ax_t.set_xlim(tt[0], tt[-1]) ax_t.set_ylim(lo, hi) ax_t.set_xlabel(r"$t$ (s)") ax_t.set_ylabel(ylabel) ax_t.grid(True) ax_t.set_title("respuesta " + nota_resp, fontsize=10) aviso = ax_t.text(0.5, 0.5, "", transform=ax_t.transAxes, ha="center", va="center", fontsize=11, color=gf.ROJO, bbox=dict(fc="white", ec=gf.ROJO, lw=0.8, pad=4), zorder=6) aviso.set_visible(False) vals = np.array([f["v"] for f in frames]) dv = (vals[-1] - vals[0]) / max(len(vals) - 1, 1) for f in frames: ax_b.axvspan(f["v"] - dv / 2, f["v"] + dv / 2, color=CLARO[f["estado"]], lw=0) for vc in criticos_: vc = 0.0 if abs(vc) < 1e-6 * max(abs(vals[-1] - vals[0]), 1e-12) else vc ax_b.axvline(vc, color=gf.NEGRO, lw=1.0) ax_b.text(vc, 1.15, f"crítico ≈ {vc:.4g}", fontsize=8.5, ha="center", va="bottom", transform=ax_b.get_xaxis_transform()) marca, = ax_b.plot([], [], "v", ms=11, color=gf.NEGRO, zorder=5, clip_on=False) ax_b.set_xlim(vals[0] - dv / 2, vals[-1] + dv / 2) ax_b.set_ylim(0, 1) ax_b.set_yticks([]) ax_b.tick_params(axis="y", which="both", left=False, right=False) ax_b.set_xlabel(nombre + " (verde: estable · rojo: inestable)", fontsize=9.5) titulo = fig.text(0.5, 0.95, "", ha="center", va="center", fontsize=14, weight="bold") def actualiza(k): f = frames[k] col = COLOR[f["estado"]] p = np.asarray(f["polos"], complex) z = np.asarray(f["ceros"], complex) pol_line.set_data(p.real, p.imag) pol_line.set_color(col) cer_line.set_data(z.real, z.imag) y = np.clip(f["y"], lo - span, hi + span) resp_line.set_data(tt, y) resp_line.set_color(gf.NEGRO if f["estado"] == "estable" else col) aviso.set_visible(f["estado"] != "estable") aviso.set_text("diverge: polo en el semiplano derecho" if f["estado"] == "inestable" else "oscilación mantenida: polos sobre el eje jω") marca.set_data([f["v"]], [1.05]) titulo.set_text(f"{nombre} = {f['v']:.4g} · {ROTULO[f['estado']]}") titulo.set_color(col) return _guarda_gif(fig, actualiza, len(frames), fps, "barrido_") def gif_temporal(sim, *, nfr=50, fps=12, umin=None, umax=None): """Las señales del lazo se dibujan según avanza el tiempo.""" tt, y, r, u = sim["t"], sim["y"], sim["r"], sim["u"] fig = Figure(figsize=(9.6, 5.6), dpi=84) fig.patch.set_facecolor("white") a = fig.add_axes([0.08, 0.55, 0.88, 0.36]) c = fig.add_axes([0.08, 0.1, 0.88, 0.36], sharex=a) a.plot(tt, r, color=gf.GRIS, ls="--", lw=1.1, drawstyle="steps-post", label=r"consigna $r(t)$") ly, = a.plot([], [], color=gf.NEGRO, lw=2.0, label=r"salida $y(t)$") py, = a.plot([], [], "o", color=gf.ROJO, ms=6) lo, hi = gf._rango(y, r) sp_ = max(hi - lo, 1e-6) a.set_ylim(lo - 0.08 * sp_, hi + 0.12 * sp_) a.set_ylabel(r"$y(t)$") a.legend(loc="lower right") a.grid(True) series = [("P", sim["P"], gf.AZUL, "--", r"$P$"), ("I", sim["I"], gf.VERDE, "-.", r"$I$"), ("D", sim["D"], gf.ROJO, ":", r"$D$"), ("u", u, gf.NEGRO, "-", r"$u=P+I+D$")] lineas = [] vals = [] for _, v, col, ls, lab in series: if np.any(np.abs(v) > 1e-12): ln, = c.plot([], [], color=col, ls=ls, lw=1.9 if lab.startswith("$u") else 1.3, label=lab) lineas.append((ln, v)) vals.append(v) for lim in (umin, umax): if lim is not None: c.axhline(lim, color=gf.GRIS, ls=(0, (4, 2)), lw=0.8) v = np.concatenate([x[np.isfinite(x)] for x in vals]) if vals else np.array([0.0, 1.0]) q1, q2 = np.percentile(v, [1, 99]) lo, hi = min(float(np.min(v)), 0.0), max(float(np.max(v)), 0.0) if hi - lo > 4 * (q2 - q1 + 1e-9): lo, hi = min(q1, 0.0), max(q2, 0.0) pad = 0.12 * (hi - lo + 1e-9) c.set_ylim(lo - pad, hi + pad) c.axhline(0, color=gf.NEGRO, lw=0.4) c.set_ylabel(r"$u(t)$ y sus acciones") c.set_xlabel(r"$t$ (s)") c.legend(loc="upper right", ncol=4, fontsize=8.5) c.grid(True) a.set_xlim(tt[0], sim.get("t_end", tt[-1])) cursores = [ax.axvline(0, color=gf.AMBAR, lw=1.0) for ax in (a, c)] titulo = fig.text(0.5, 0.955, "", ha="center", va="center", fontsize=13, weight="bold") instantes = np.linspace(tt[0], tt[-1], nfr) def actualiza(k): tk = instantes[k] i = int(np.searchsorted(tt, tk, side="right")) i = max(i, 1) ly.set_data(tt[:i], y[:i]) py.set_data([tt[i - 1]], [y[i - 1]]) for ln, vv in lineas: ln.set_data(tt[:i], vv[:i]) for cu in cursores: cu.set_xdata([tk, tk]) titulo.set_text(f"t = {tk:.3g} s r = {r[i - 1]:.3g} y = {y[i - 1]:.3g} u = {u[i - 1]:.3g}") return _guarda_gif(fig, actualiza, nfr, fps, "senales_")