File size: 11,628 Bytes
77ba96d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""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_")