File size: 39,860 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
"""Figuras del simulador con aspecto de libro (Springer): tipografía Times
(STIX), ejes finos con marcas hacia dentro, rejilla tenue y una paleta
sobria que se distingue también en blanco y negro por el trazo."""

import math
import re

import matplotlib

matplotlib.use("Agg")
import numpy as np
from matplotlib.figure import Figure
from matplotlib.patches import Arc, Polygon, Rectangle

NEGRO = "#1a1a1a"
AZUL = "#1f4e79"
ROJO = "#a4262c"
VERDE = "#2e6b30"
AMBAR = "#b07d12"
GRIS = "#8c8c8c"
GRIS_CLARO = "#ececec"
TRAZOS = [(AZUL, "-"), (ROJO, "--"), (VERDE, ":"), (AMBAR, "-."), (NEGRO, (0, (5, 1, 1, 1, 1, 1)))]

matplotlib.rcParams.update({
    "font.family": "serif",
    "font.serif": ["STIXGeneral", "STIX Two Text", "Times New Roman", "DejaVu Serif"],
    "mathtext.fontset": "stix",
    "font.size": 10,
    "axes.labelsize": 10.5,
    "axes.titlesize": 10.5,
    "axes.titleweight": "normal",
    "axes.linewidth": 0.6,
    "axes.edgecolor": NEGRO,
    "axes.labelcolor": NEGRO,
    "xtick.direction": "in",
    "ytick.direction": "in",
    "xtick.top": True,
    "ytick.right": True,
    "xtick.major.width": 0.6,
    "ytick.major.width": 0.6,
    "xtick.minor.visible": True,
    "ytick.minor.visible": True,
    "xtick.minor.width": 0.4,
    "ytick.minor.width": 0.4,
    "xtick.labelsize": 9,
    "ytick.labelsize": 9,
    "legend.fontsize": 8.5,
    "legend.frameon": False,
    "grid.color": "#dcdcdc",
    "grid.linewidth": 0.5,
    "lines.linewidth": 1.5,
    "figure.dpi": 110,
    "savefig.dpi": 160,
    "figure.facecolor": "white",
    "axes.facecolor": "white",
})


def _fig(w=6.4, h=4.0):
    fig = Figure(figsize=(w, h), layout="constrained")
    return fig


def _rotulo(ax, letra):
    ax.text(0.0, 1.02, f"({letra})", transform=ax.transAxes, ha="left", va="bottom", fontsize=10)


def figura_error(mensaje):
    fig = _fig(6.4, 1.6)
    ax = fig.add_subplot()
    ax.axis("off")
    ax.text(0.5, 0.5, mensaje, ha="center", va="center", fontsize=11, color=ROJO, wrap=True)
    return fig


# =====================================================================
#  Plano s
# =====================================================================
def _limites(puntos, region=None):
    xs = [p.real for p in puntos] + [0.0]
    ys = [abs(p.imag) for p in puntos] + [0.0]
    if region:
        xs.append(-region["sigma"] * 1.6)
        ys.append(region["sigma"] * 1.6 * math.tan(region["beta"]))
    xmin, xmax = min(xs), max(xs)
    span = max(xmax - xmin, 2 * max(ys), 1.0)
    xmin -= 0.18 * span
    xmax += 0.18 * span
    ymax = max(max(ys) * 1.3, 0.35 * (xmax - xmin))
    return xmin, xmax, ymax


def fig_plano_s(polos, ceros=(), *, titulo=None, polos_ref=None, ref_label="lazo abierto",
                region=None, tray=None, anotar_2o=None, deseados=None, rejilla_zeta=True,
                etiquetar=True, w=6.4, h=4.4):
    """Mapa de polos (×) y ceros (○) en el plano s."""
    fig = _fig(w, h)
    ax = fig.add_subplot()
    polos = [complex(p) for p in polos]
    ceros = [complex(z) for z in ceros]
    refs = [] if polos_ref is None else [complex(p) for p in polos_ref]
    des = [] if deseados is None else [complex(p) for p in deseados]
    xmin, xmax, ymax = _limites(polos + ceros + refs + des, region)
    # mismas unidades en los dos ejes (los ángulos de beta se leen bien)
    # con una caja de proporción ~1.45; se amplía el eje que se quede corto
    R = 1.45
    if (xmax - xmin) / (2 * ymax) < R:
        extra = R * 2 * ymax - (xmax - xmin)
        izq = extra * (-xmin) / max(xmax - xmin, 1e-9)
        xmin, xmax = xmin - izq, xmax + (extra - izq)
    else:
        ymax = (xmax - xmin) / (2 * R)

    ax.axvspan(xmin, 0, color="#f5f5f5", zorder=0, lw=0)
    ax.axhline(0, color=NEGRO, lw=0.6, zorder=1)
    ax.axvline(0, color=NEGRO, lw=0.6, zorder=1)
    ax.text(0.015, 0.97, "estable", transform=ax.transAxes, ha="left", va="top", fontsize=8.5,
            color="#555", style="italic")
    ax.text(0.985, 0.97, "inestable", transform=ax.transAxes, ha="right", va="top", fontsize=8.5,
            color="#555", style="italic")

    if rejilla_zeta:
        R = math.hypot(xmin, ymax) * 1.2
        for z in (0.2, 0.4, 0.6, 0.8):
            b = math.acos(z)
            for sg in (1, -1):
                ax.plot([0, -R * math.cos(b)], [0, sg * R * math.sin(b)], color="#c8c8c8",
                        lw=0.5, ls=(0, (2, 2)), zorder=1)
            xr, yr = -0.93 * ymax / math.tan(b), 0.93 * ymax
            if xr < xmin:
                xr, yr = xmin * 0.97, -xmin * 0.97 * math.tan(b)
            ax.text(xr, yr, rf"$\zeta={z}$", fontsize=7.5, color="#888", ha="center", va="center",
                    bbox=dict(fc="white", ec="none", pad=0.4, alpha=0.8))

    if region:
        s0, b = region["sigma"], region["beta"]
        X = xmin
        poly = [(-s0, -s0 * math.tan(b)), (-s0, s0 * math.tan(b)), (X, -X * math.tan(b)), (X, X * math.tan(b))]
        ax.add_patch(Polygon(poly, closed=True, fc="#dde6ef", ec="none", zorder=0.5))
        ax.axvline(-s0, color=AZUL, lw=1.1, zorder=2)
        ax.text(-s0, -0.92 * ymax, r"  $\sigma=-4/t_s$" if region.get("banda", 2) == 2 else r"  $\sigma=-3/t_s$",
                color=AZUL, fontsize=8.5, ha="left", va="bottom")
        R = math.hypot(xmin, ymax) * 1.2
        for sg in (1, -1):
            ax.plot([0, -R * math.cos(b)], [0, sg * R * math.sin(b)], color=AZUL, lw=1.0, ls="--", zorder=2)
        ax.text(0.02, 0.06, "región admisible", transform=ax.transAxes, fontsize=8.5, color=AZUL)

    if tray is not None:
        vals, raices = tray
        cmap = matplotlib.colormaps["Blues"]
        for i, rr in enumerate(raices):
            c = cmap(0.25 + 0.75 * i / max(len(raices) - 1, 1))
            sel = [r for r in rr if xmin <= r.real <= xmax and abs(r.imag) <= ymax]
            if sel:
                ax.scatter([r.real for r in sel], [r.imag for r in sel], s=4, color=c, zorder=2, lw=0)

    if refs:
        ax.plot([p.real for p in refs], [p.imag for p in refs], "x", ms=8, mew=1.3, color=GRIS,
                zorder=3, label=f"polos en {ref_label}")
    if des:
        ax.plot([p.real for p in des], [p.imag for p in des], "s", ms=10, mfc="none", mew=1.1,
                color=AZUL, zorder=3, label="polos deseados")
    if polos:
        ax.plot([p.real for p in polos], [p.imag for p in polos], "x", ms=9.5, mew=1.9, color=NEGRO,
                zorder=4, label="polos")
    if ceros:
        ax.plot([z.real for z in ceros], [z.imag for z in ceros], "o", ms=8.5, mfc="white", mew=1.5,
                color=NEGRO, zorder=4, label="ceros")

    if etiquetar:
        vistos = {}
        for p in polos:
            k = (round(p.real, 6), round(p.imag, 6))
            vistos[k] = vistos.get(k, 0) + 1
        if len(vistos) <= 6:
            for (re, im), mult in vistos.items():
                txt = f"{re:.3g}" if abs(im) < 1e-9 else f"{re:.3g}{'+' if im > 0 else '−'}j{abs(im):.3g}"
                txt = txt.replace("-", "−")
                if mult > 1:
                    txt += f"  (×{mult})"
                ax.annotate(txt, (re, im), xytext=(6, 7 if im >= 0 else -12), textcoords="offset points",
                            fontsize=8, color=NEGRO)

    if anotar_2o and anotar_2o.get("wd"):
        sg, wd, wn = anotar_2o["sigma"], anotar_2o["wd"], anotar_2o["wn"]
        ax.plot([0, -sg], [0, wd], color=NEGRO, lw=1.0, zorder=3)
        ax.plot([-sg, -sg], [0, wd], color=GRIS, lw=0.7, ls="--", zorder=2)
        ax.plot([-sg, 0], [wd, wd], color=GRIS, lw=0.7, ls="--", zorder=2)
        rr = 0.3 * wn
        beta = math.degrees(math.acos(min(max(anotar_2o["zeta"], 0), 1)))
        ax.add_patch(Arc((0, 0), 2 * rr, 2 * rr, theta1=180 - beta, theta2=180, color=NEGRO, lw=0.7))
        ax.text(-rr * 1.25 * math.cos(math.radians(beta / 2)), rr * 1.25 * math.sin(math.radians(beta / 2)),
                r"$\beta$", fontsize=9, ha="center", va="center")
        ax.text(-sg / 2 + 0.03 * wn, wd / 2 + 0.06 * wn, r"$\omega_n$", fontsize=9.5, ha="left")
        ax.text(0.02 * wn, wd, r" $\omega_d$", fontsize=9.5, va="center", ha="left")
        ax.text(-sg / 2, -0.07 * wn, r"$\sigma=\zeta\omega_n$", fontsize=9, ha="center", va="top")

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(-ymax, ymax)
    ax.set_aspect("equal", adjustable="box")
    ax.set_xlabel(r"Real, $\sigma$")
    ax.set_ylabel(r"Imaginario, $j\omega$")
    ax.grid(True, which="major")
    if titulo:
        ax.set_title(titulo)
    hand, lab = ax.get_legend_handles_labels()
    if len(lab) > 1:
        ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.12), ncol=len(lab), fontsize=8.5,
                  frameon=False, handletextpad=0.3, columnspacing=1.4)
    return fig


# =====================================================================
#  Respuesta temporal
# =====================================================================
def fig_respuesta(tt, y, *, r=None, yinf=None, met=None, ylabel=r"$y(t)$", rlabel=r"$r(t)$",
                  ylabel_curve=r"$y(t)$", titulo=None, extra=None, banda=0.02, w=6.4, h=4.0,
                  nota=None):
    fig = _fig(w, h)
    ax = fig.add_subplot()
    lo, hi = _rango(y, r)
    span = max(hi - lo, 1e-9)
    visibles, fuera = [], False
    for yy, lab in (extra or []):
        a, b = _rango(yy)
        if a >= lo - 1.5 * span and b <= hi + 1.5 * span:
            visibles.append((yy, lab))
            lo, hi = min(lo, a), max(hi, b)
        else:
            # una curva que diverge (p. ej. una rampa) no debe aplastar a las demás
            visibles.append((yy, lab + " (se sale de la escala)"))
            fuera = True
    for i, (yy, lab) in enumerate(visibles):
        c, ls = TRAZOS[(i + 1) % len(TRAZOS)]
        ax.plot(tt, yy, color=c, ls=ls, lw=1.3, label=lab)
    if r is not None:
        ax.plot(tt, r, color=GRIS, ls="--", lw=1.1, label=rlabel)
    ok = np.isfinite(y)
    ax.plot(tt[ok], y[ok], color=NEGRO, lw=1.8, label=ylabel_curve, zorder=4)
    if fuera:
        hi = hi + 0.25 * span
    if yinf is not None and np.isfinite(yinf) and abs(yinf) > 1e-12:
        ax.axhspan(yinf * (1 - banda), yinf * (1 + banda), color=GRIS_CLARO, zorder=0, lw=0)
        ax.axhline(yinf, color=GRIS, lw=0.7, ls=":")
        lo, hi = min(lo, yinf * (1 - banda)), max(hi, yinf * (1 + banda))
    if met and yinf:
        _marcas(ax, tt, y, yinf, met, lo, hi)
    pad = 0.08 * (hi - lo if hi > lo else 1)
    ax.set_ylim(lo - pad, hi + pad)
    ax.set_xlim(tt[0], tt[-1])
    ax.set_xlabel(r"$t$ (s)")
    ax.set_ylabel(ylabel)
    ax.grid(True)
    ax.axhline(0, color=NEGRO, lw=0.4)
    ax.legend(loc="best")
    if titulo:
        ax.set_title(titulo)
    if nota:
        ax.text(0.99, 0.02, nota, transform=ax.transAxes, ha="right", va="bottom", fontsize=8, color="#555")
    return fig


def _rango(y, r=None, extra=None):
    vals = [np.asarray(y)[np.isfinite(y)]]
    if r is not None:
        vals.append(np.asarray(r))
    for yy, _ in (extra or []):
        vals.append(np.asarray(yy)[np.isfinite(yy)])
    v = np.concatenate([x for x in vals if x.size])
    if v.size == 0:
        return -1.0, 1.0
    lo, hi = float(np.min(v)), float(np.max(v))
    lo, hi = min(lo, 0.0), max(hi, 0.0)
    # si algo diverge, se recorta para que se siga viendo el arranque
    if hi - lo > 1e6:
        hi = min(hi, 1e3)
        lo = max(lo, -1e3)
    return lo, hi


def _marcas(ax, tt, y, yinf, met, lo, hi):
    """Cotas td, tr, tp, ts y la sobreoscilación, como en la figura 5.1 de los apuntes."""
    base = lo + 0.02 * (hi - lo)
    marcas = []
    if np.isfinite(met.get("td", np.nan)):
        marcas.append(("t_d", met["td"]))
    if met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", np.nan)):
        tp = met["tp"]
        ymax = met["ymax"]
        ax.plot([tp], [ymax], "o", ms=4, color=ROJO, zorder=5)
        ax.annotate("", xy=(tp, ymax), xytext=(tp, yinf),
                    arrowprops=dict(arrowstyle="<->", color=ROJO, lw=0.9, shrinkA=0, shrinkB=0))
        ax.text(tp, (ymax + yinf) / 2, f"  $M_p={met['Mp']:.3g}\\,\\%$", color=ROJO, fontsize=9, va="center")
        marcas.append(("t_p", tp))
    if np.isfinite(met.get("ts2", np.nan)) and met["ts2"] > 0:
        marcas.append(("t_s", met["ts2"]))
    for nombre, tx in marcas:
        yv = float(np.interp(tx, tt, y))
        ax.plot([tx, tx], [base, yv], color=GRIS, lw=0.7, ls="--", zorder=1)
        ax.text(tx, base, f"${nombre}$", fontsize=9, ha="center", va="bottom",
                bbox=dict(fc="white", ec="none", pad=0.5))


def fig_modos(tt, modos_y, etiquetas, total, *, w=6.4, h=3.8, titulo=None):
    """Cada polo aporta un modo: contribución de cada término y su suma."""
    fig = _fig(w, h)
    ax = fig.add_subplot()
    for i, (yy, lab) in enumerate(zip(modos_y, etiquetas)):
        c, ls = TRAZOS[i % len(TRAZOS)]
        ax.plot(tt, yy, color=c, ls=ls, lw=1.25, label=lab)
    ax.plot(tt, total, color=NEGRO, lw=1.9, label=r"suma: $y(t)$", zorder=4)
    ax.axhline(0, color=NEGRO, lw=0.4)
    lo, hi = _rango(total, None, [(m, "") for m in modos_y])
    pad = 0.08 * (hi - lo if hi > lo else 1)
    ax.set_ylim(lo - pad, hi + pad)
    ax.set_xlim(tt[0], tt[-1])
    ax.set_xlabel(r"$t$ (s)")
    ax.set_ylabel("contribución de cada modo")
    ax.grid(True)
    ax.legend(loc="best", fontsize=8)
    if titulo:
        ax.set_title(titulo)
    return fig


def fig_superficie(G, *, w=6.4, h=4.6, titulo=None):
    """|G(s)| sobre el plano s: los polos son picos y los ceros, pozos.

    El corte por el eje imaginario (sigma = 0) es la respuesta en frecuencia
    |G(j omega)|, que se dibuja en rojo encima de la superficie.
    """
    pts = list(G.polos_np()) + list(G.ceros_np())
    xs = [p.real for p in pts] + [0.0]
    ys = [abs(p.imag) for p in pts] + [0.0]
    span = max(max(xs) - min(xs), 2 * max(ys), 1.0)
    x0, x1 = min(xs) - 0.35 * span, max(xs) + 0.35 * span
    W = max(max(ys) * 1.6, 0.5 * (x1 - x0))
    S, Wg = np.meshgrid(np.linspace(x0, x1, 121), np.linspace(-W, W, 121))
    Z = S + 1j * Wg
    with np.errstate(all="ignore"):
        M = np.abs(np.polyval(G.num, Z) / np.polyval(G.den, Z))
        L = np.log10(M)
    finitos = L[np.isfinite(L)]
    zlo, zhi = np.percentile(finitos, 2), np.percentile(finitos, 97)
    zhi = max(zhi, zlo + 1.0)
    L = np.clip(np.nan_to_num(L, nan=zhi, posinf=zhi, neginf=zlo), zlo, zhi)
    fig = _fig(w, h)
    ax = fig.add_subplot(projection="3d")
    ax.plot_surface(S, Wg, L, cmap="cividis", rstride=2, cstride=2, lw=0.15, edgecolor="#ffffff55",
                    antialiased=True, alpha=0.95)
    wj = np.linspace(-W, W, 400)
    with np.errstate(all="ignore"):
        Lj = np.clip(np.log10(np.abs(np.polyval(G.num, 1j * wj) / np.polyval(G.den, 1j * wj))), zlo, zhi)
    if x0 <= 0 <= x1:
        ax.plot(np.zeros_like(wj), wj, Lj, color=ROJO, lw=1.8, zorder=10,
                label=r"$|G(j\omega)|$: corte por $\sigma=0$")
    for p in G.polos_np():
        ax.plot([p.real], [p.imag], [zlo], "x", color=NEGRO, ms=7, mew=1.6)
    for z in G.ceros_np():
        ax.plot([z.real], [z.imag], [zlo], "o", mfc="white", color=NEGRO, ms=6, mew=1.2)
    ax.set_xlabel(r"$\sigma$", labelpad=2)
    ax.set_ylabel(r"$j\omega$", labelpad=2)
    ax.set_zlabel(r"$\log_{10}|G(s)|$", labelpad=2)
    ax.view_init(elev=27, azim=-58)
    ax.tick_params(labelsize=7.5, pad=0)
    ax.xaxis.pane.set_facecolor("white")
    ax.yaxis.pane.set_facecolor("white")
    ax.zaxis.pane.set_facecolor("white")
    if x0 <= 0 <= x1:
        ax.legend(loc="upper left", fontsize=8)
    if titulo:
        ax.set_title(titulo)
    return fig


# =====================================================================
#  PID: salida, error y las tres acciones
# =====================================================================
def fig_pid(sim, *, comparar=None, umin=None, umax=None, pert_t=None, espec=None, w=6.6, h=7.4):
    """(a) salida y consigna, (b) error, (c) u y sus tres acciones."""
    tt = sim["t"]
    fig = _fig(w, h)
    axs = fig.subplots(3, 1, sharex=True, height_ratios=[1.25, 0.8, 1.2])
    a, b, c = axs

    if comparar:
        for i, (lab, d) in enumerate(comparar):
            col, ls = TRAZOS[(i + 1) % len(TRAZOS)]
            a.plot(d["t"], d["y"], color=col, ls=ls, lw=1.15, label=lab)
    r = sim["r"]
    a.plot(tt, r, color=GRIS, ls="--", lw=1.0, label=r"consigna $r(t)$", drawstyle="steps-post")
    a.plot(tt, sim["y"], color=NEGRO, lw=1.9, label=r"salida $y(t)$", zorder=4)
    lo, hi = _rango(sim["y"], r, [(d["y"], "") for _, d in (comparar or [])])
    span = hi - lo if hi > lo else 1.0
    if espec:
        yl = espec["yinf"] * (1 + espec["Mp"] / 100)
        a.axhline(yl, color=ROJO, lw=0.8, ls=(0, (1, 2)))
        a.text(tt[-1], yl, f"límite $M_p$ = {espec['Mp']:.3g} % ", color=ROJO, fontsize=8, ha="right", va="bottom")
        for ax in axs:
            ax.axvline(espec["ts"], color=AZUL, lw=0.8, ls=(0, (1, 2)))
        hi = max(hi, yl)
    a.set_ylim(lo - 0.06 * span, hi + 0.1 * span)
    if espec:
        a.text(espec["ts"], a.get_ylim()[0], " $t_s$ exigido", color=AZUL, fontsize=8, va="bottom")
    if sim.get("diverge") or (np.max(np.abs(sim["y"])) > 50 * max(1.0, np.max(np.abs(r)))):
        a.text(0.5, 0.5, "la salida diverge: el lazo es inestable", transform=a.transAxes, ha="center",
               va="center", fontsize=11, color=ROJO, bbox=dict(fc="white", ec=ROJO, lw=0.8, pad=4))
    a.set_ylabel(r"$y(t)$")
    a.legend(loc="lower right", ncol=2 if comparar else 1)
    _rotulo(a, "a")

    b.plot(tt, sim["e"], color=AZUL, lw=1.4)
    b.axhline(0, color=NEGRO, lw=0.4)
    lo, hi = _rango(sim["e"])
    b.set_ylim(lo - 0.08 * (hi - lo + 1e-9), hi + 0.08 * (hi - lo + 1e-9))
    b.set_ylabel(r"$e(t)=r-y$")
    _rotulo(b, "b")

    comps = [("P", sim["P"], AZUL, "--", r"$P=K_p\,e$"),
             ("I", sim["I"], VERDE, "-.", r"$I=K_i\!\int e\,d\tau$"),
             ("D", sim["D"], ROJO, ":", r"$D=K_d\,\dot e$")]
    vals = [sim["u"]]
    for k, v, col, ls, lab in comps:
        if np.any(np.abs(v) > 1e-12):
            c.plot(tt, v, color=col, ls=ls, lw=1.3, label=lab)
            vals.append(v)
    if umin is not None or umax is not None:
        if np.any(np.abs(sim["u_ns"] - sim["u"]) > 1e-9):
            c.plot(tt, sim["u_ns"], color=GRIS, lw=0.8, label="$u$ pedida (sin saturar)")
        for lim in (umin, umax):
            if lim is not None:
                c.axhline(lim, color=GRIS, ls=(0, (4, 2)), lw=0.8)
    c.plot(tt, sim["u"], color=NEGRO, lw=1.8, label=r"$u=P+I+D$", zorder=4)
    c.axhline(0, color=NEGRO, lw=0.4)
    # un pico inicial muy grande (derivada filtrada) se recorta para que se vea el resto
    v = np.concatenate([x[np.isfinite(x)] for x in vals])
    q_lo, q_hi = 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 * (q_hi - q_lo + 1e-9):
        lo, hi = min(q_lo, 0.0), max(q_hi, 0.0)
        c.text(0.02, 0.96, "pico inicial de la acción derivativa recortado", transform=c.transAxes,
               fontsize=8, color=ROJO, va="top")
    pad = 0.12 * (hi - lo + 1e-9)
    c.set_ylim(lo - pad, hi + pad)
    for ti, area in sim.get("impulsos", []):
        top = hi + 0.6 * pad
        c.annotate("", xy=(ti, top if area > 0 else lo - 0.6 * pad), xytext=(ti, 0),
                   arrowprops=dict(arrowstyle="-|>", color=ROJO, lw=1.2, mutation_scale=10))
        c.text(ti, top, f"  impulso $K_d\\,\\Delta r\\,\\delta(t)$, área {area:.3g}", color=ROJO,
               fontsize=8, va="top", ha="left")
    c.set_ylabel(r"$u(t)$ y sus acciones")
    c.set_xlabel(r"$t$ (s)")
    c.legend(loc="lower right", fontsize=8, ncol=2)
    _rotulo(c, "c")
    for ax in axs:
        ax.grid(True)
        ax.set_xlim(tt[0], sim.get("t_end", tt[-1]))
        if pert_t is not None:
            ax.axvline(pert_t, color=AMBAR, lw=0.8, ls="--")
    if pert_t is not None:
        a.text(pert_t, a.get_ylim()[1], " perturbación", color=AMBAR, fontsize=8, va="top")
    return fig


def _rango_robusto(series):
    v = np.concatenate([np.asarray(x)[np.isfinite(x)] for x in series if len(x)])
    if v.size == 0:
        return -1.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)
    return lo - pad, hi + pad


def fig_pid_real(ideal, real, alternativa=None, ruido=None, *, umin=None, umax=None, w=6.6, h=7.8):
    """El PID de libro frente al PID tal como está configurado.

    (a) la salida, (b) la acción de control (y la parte integral si hay
    límites, que es donde se ve el windup) y (c) lo que hace la acción
    derivativa con el ruido del sensor, ideal frente a filtrada.
    """
    if ruido:
        fig = _fig(w, h)
        a, b, c = fig.subplots(3, 1, height_ratios=[1.15, 1.15, 0.9])
    else:
        fig = _fig(w, h * 0.72)
        a, b = fig.subplots(2, 1)
        c = None
    sat = umin is not None or umax is not None
    iguales = (len(ideal["y"]) == len(real["y"]) and np.allclose(ideal["y"], real["y"], atol=1e-6)
               and np.allclose(ideal["u"], real["u"], atol=1e-6))
    if iguales:
        a.text(0.5, 0.5, "Ahora coinciden: active alguna corrección del PID real\n"
               "(filtro, derivar la medida o límites del actuador) para ver la diferencia.",
               transform=a.transAxes, ha="center", va="center", fontsize=9.5, color="#444",
               bbox=dict(fc="white", ec="#bbb", lw=0.6, pad=5), zorder=10)

    a.plot(real["t"], real["r"], color=GRIS, ls="--", lw=1.0, drawstyle="steps-post", label="consigna")
    a.plot(ideal["t"], ideal["y"], color=AZUL, ls="--", lw=1.5, label="PID ideal (el de la fórmula)")
    if alternativa:
        alt, etq = alternativa
        a.plot(alt["t"], alt["y"], color=ROJO, ls=":", lw=1.8, label=etq)
    a.plot(real["t"], real["y"], color=NEGRO, lw=2.0, label="PID real (su configuración)")
    lo, hi = _rango(real["y"], real["r"], [(ideal["y"], "")] + ([(alternativa[0]["y"], "")] if alternativa else []))
    sp_ = hi - lo if hi > lo else 1.0
    a.set_ylim(lo - 0.06 * sp_, hi + 0.1 * sp_)
    a.set_ylabel("salida $y(t)$")
    a.legend(loc="lower right", fontsize=8)
    _rotulo(a, "a")

    series = [ideal["u"], real["u"]]
    b.plot(ideal["t"], ideal["u"], color=AZUL, ls="--", lw=1.4, label="$u$ del PID ideal")
    if alternativa:
        b.plot(alternativa[0]["t"], alternativa[0]["u"], color=ROJO, ls=":", lw=1.6, label="$u$ " + alternativa[1])
        series.append(alternativa[0]["u"])
    b.plot(real["t"], real["u"], color=NEGRO, lw=1.9, label="$u$ del PID real")
    if sat:
        # el windup se ve en la parte integral: sin anti-windup sigue creciendo con el actuador al tope
        b.plot(real["t"], real["I"], color=VERDE, lw=1.0, ls="-.", label="parte integral $I$ (real)")
        series.append(real["I"])
        if alternativa:
            b.plot(alternativa[0]["t"], alternativa[0]["I"], color=ROJO, lw=1.0, ls="-.", alpha=0.8,
                   label="parte integral $I$ " + ("sin" if "sin" in alternativa[1] else "con") + " anti-windup")
            series.append(alternativa[0]["I"])
        for lim in (umin, umax):
            if lim is not None:
                b.axhline(lim, color=GRIS, ls=(0, (4, 2)), lw=0.9)
        b.text(0.995, (umax if umax is not None else umin), "límite del actuador ", transform=b.get_yaxis_transform(),
               fontsize=8, color="#555", ha="right", va="bottom")
    lo, hi = _rango_robusto(series)
    b.set_ylim(lo, hi)
    for ti, area in ideal.get("impulsos", []):
        b.annotate("", xy=(ti, hi), xytext=(ti, 0), arrowprops=dict(arrowstyle="-|>", color=ROJO, lw=1.3,
                                                                   mutation_scale=10))
        b.text(ti, hi, "  golpe de la derivada ideal (impulso)", color=ROJO, fontsize=8, va="top")
    b.axhline(0, color=NEGRO, lw=0.4)
    b.set_ylabel("acción de control $u(t)$")
    b.set_xlabel("$t$ (s)")
    b.legend(loc="lower right", fontsize=7.5, ncol=2)
    _rotulo(b, "b")
    for ax in (a, b):
        ax.grid(True)
        ax.set_xlim(real["t"][0], real.get("t_end", real["t"][-1]))

    if c is None:
        return fig
    tt = ruido["t"]
    c.plot(tt, ruido["ideal"], color=ROJO, lw=0.7, label="derivada sin filtro: $K_d\\,\\dot n$")
    c.plot(tt, ruido["filtro"], color=NEGRO, lw=1.4, label=f"derivada filtrada (N = {ruido['N']:.3g})")
    amp_f = float(np.max(np.abs(ruido["filtro"]))) or 1.0
    amp_i = float(np.max(np.abs(ruido["ideal"])))
    c.set_ylim(-3.2 * amp_f, 3.2 * amp_f)
    c.axhline(0, color=NEGRO, lw=0.4)
    caja_txt = dict(fc="white", ec="none", alpha=0.9, pad=2)
    if amp_i > 3.2 * amp_f:
        c.text(0.99, 0.95, f"sin filtro llega a ±{amp_i:.3g}: se sale de la escala",
               transform=c.transAxes, fontsize=8, color=ROJO, ha="right", va="top", bbox=caja_txt, zorder=10)
    c.set_xlim(tt[0], tt[-1])
    c.set_xlabel("$t$ (s)")
    c.set_ylabel("acción D por el ruido")
    c.legend(loc="lower right", fontsize=8, ncol=2, frameon=True, framealpha=0.92, edgecolor="none")
    c.grid(True)
    _rotulo(c, "c")
    c.set_title("qué hace la derivada con un ruido de medida del 1 %", fontsize=9.5)
    return fig


def _cruce(tt, y, nivel):
    idx = np.nonzero(y >= nivel)[0]
    if idx.size == 0:
        return math.nan
    i = idx[0]
    if i == 0:
        return float(tt[0])
    return float(tt[i - 1] + (nivel - y[i - 1]) * (tt[i] - tt[i - 1]) / (y[i] - y[i - 1]))


def _num(x, sig=3):
    if x is None or not np.isfinite(x):
        return "—"
    return f"{x:.{sig}g}"


def fig_especificaciones(tt, y, yinf, met, teor=None, *, nota=None, w=9.6, h=5.2):
    """Respuesta a escalón con las cinco magnitudes acotadas y sus valores,
    como la figura 5.1 de los apuntes, y una tabla de medido frente a fórmula."""
    fig = _fig(w, h)
    gs = fig.add_gridspec(1, 2, width_ratios=[2.45, 1])
    ax = fig.add_subplot(gs[0])
    tab = fig.add_subplot(gs[1])
    tab.axis("off")
    base = abs(yinf)
    s = 1.0 if yinf > 0 else -1.0
    yn = s * np.asarray(y)                      # se dibuja siempre hacia arriba
    yf = base

    ax.axhspan(yf * 0.98, yf * 1.02, color=GRIS_CLARO, lw=0, zorder=0)
    ax.plot(tt, yn, color=NEGRO, lw=2.0, zorder=4)
    ax.axhline(yf, color=GRIS, lw=0.8, ls="--", zorder=1)
    ax.axhline(0, color=NEGRO, lw=0.6, zorder=1)
    guia = dict(color=GRIS, lw=0.8, ls="--", zorder=2)

    cotas = []
    td = met.get("td", math.nan)
    if np.isfinite(td):
        ax.plot([0, td], [0.5 * yf, 0.5 * yf], **guia)
        ax.plot([td, td], [0, 0.5 * yf], **guia)
        cotas.append(("t_d", 0.0, td, "retardo (50 %)"))
    if met.get("Mp", 0) > 0.05:
        tr = met.get("tr", math.nan)
        if np.isfinite(tr):
            ax.plot([tr, tr], [0, yf], **guia)
            cotas.append(("t_r", 0.0, tr, "subida (0–100 %)"))
    else:
        t10, t90 = _cruce(tt, yn, 0.1 * yf), _cruce(tt, yn, 0.9 * yf)
        if np.isfinite(t10) and np.isfinite(t90):
            ax.plot([0, t90], [0.9 * yf, 0.9 * yf], **guia)
            ax.plot([0, t10], [0.1 * yf, 0.1 * yf], **guia)
            ax.plot([t10, t10], [0, 0.1 * yf], **guia)
            ax.plot([t90, t90], [0, 0.9 * yf], **guia)
            cotas.append(("t_r", t10, t90, "subida (10–90 %)"))
    ymax = float(np.max(yn))
    if met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", math.nan)):
        tp = met["tp"]
        ax.plot([tp, tp], [0, ymax], **guia)
        ax.plot([0, tp], [ymax, ymax], **guia)
        ax.plot([tp], [ymax], "o", ms=5, color=ROJO, zorder=5)
        ax.annotate("", xy=(tp, ymax), xytext=(tp, yf),
                    arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.1, shrinkA=0, shrinkB=0))
        ax.text(tp + 0.02 * tt[-1], (ymax + yf) / 2, f"$M_p$ = {_num(met['Mp'])} %", color=ROJO, fontsize=11.5,
                va="center", bbox=dict(fc="white", ec="none", alpha=0.85, pad=1))
        cotas.append(("t_p", 0.0, tp, "pico"))
    ts = met.get("ts2", math.nan)
    if np.isfinite(ts) and ts > 0:
        ax.plot([ts, ts], [0, yf * 1.02], **guia)
        cotas.append(("t_s", 0.0, ts, "establecimiento (2 %)"))

    paso = 0.13 * yf
    for k, (nombre, a, b, desc) in enumerate(cotas, start=1):
        yc = -k * paso
        ax.annotate("", xy=(b, yc), xytext=(a, yc),
                    arrowprops=dict(arrowstyle="<->", color=NEGRO, lw=0.9, shrinkA=0, shrinkB=0))
        ax.plot([b, b], [yc, 0], color=GRIS, lw=0.5, ls=":")
        ax.text(b + 0.012 * tt[-1], yc, f"${nombre}$ = {_num(b - a)} s", fontsize=11, va="center", ha="left",
                bbox=dict(fc="white", ec="none", alpha=0.9, pad=0.5))
    fondo = -(len(cotas) + 0.7) * paso
    techo = max(ymax, yf * 1.02) + 0.12 * yf
    ax.set_ylim(fondo, techo)
    ax.set_xlim(0, tt[-1] * 1.0)
    ax.text(tt[-1], yf * 1.025, f"valor final $y(\\infty)$ = {_num(s * yf)}  ", fontsize=9.5, ha="right",
            va="bottom", color="#444")
    ticks = [t for t in ax.get_yticks() if -1e-9 <= t <= techo]
    ax.set_yticks(ticks)
    if s < 0:
        ax.set_yticklabels([_num(-t) for t in ticks])
    ax.set_xlabel("$t$ (s)")
    ax.set_ylabel("$y(t)$" + (" (dibujada con el signo cambiado)" if s < 0 else ""))
    ax.spines["bottom"].set_visible(False)
    ax.tick_params(axis="x", which="both", top=False)
    ax.set_title(nota or "Respuesta a escalón: las magnitudes que la definen", fontsize=10.5)

    # tabla de valores, con filetes como en los apuntes
    filas = [("t_d", "retardo", met.get("td"), "s", "td"),
             ("t_r", "subida " + met.get("tr_def", ""), met.get("tr"), "s", "tr"),
             ("t_p", "pico", met.get("tp") if met.get("Mp", 0) > 0.05 else None, "s", "tp"),
             ("M_p", "sobreoscilación", met.get("Mp"), "%", "Mp"),
             ("t_s", "establec. 2 %", met.get("ts2"), "s", "ts2"),
             ("t_s", "establec. 5 %", met.get("ts5"), "s", "ts5")]
    x0, x1, x2 = 0.0, 0.47, 0.76
    yy = 0.93
    tab.text(x0, yy, "Magnitud", fontsize=10, weight="bold", transform=tab.transAxes)
    tab.text(x1, yy, "medido", fontsize=10, weight="bold", transform=tab.transAxes)
    tab.text(x2, yy, "fórmula", fontsize=10, weight="bold", transform=tab.transAxes)
    tab.plot([0, 1], [yy + 0.055, yy + 0.055], color=NEGRO, lw=1.2, transform=tab.transAxes, clip_on=False)
    tab.plot([0, 1], [yy - 0.03, yy - 0.03], color=NEGRO, lw=0.6, transform=tab.transAxes, clip_on=False)
    for nombre, desc, v, u, clave in filas:
        yy -= 0.105
        tab.text(x0, yy, f"${nombre}$  {desc}", fontsize=9.5, transform=tab.transAxes)
        sin_pico = clave == "tp" and v is None
        tab.text(x1, yy, "no hay pico" if sin_pico else f"{_num(v)} {u}", fontsize=9.5, transform=tab.transAxes)
        if teor and clave in teor:
            tv = teor[clave][1]
            tab.text(x2, yy, f"{_num(tv)} {u}", fontsize=9.5, transform=tab.transAxes, color=AZUL)
        else:
            tab.text(x2, yy, "—", fontsize=9.5, transform=tab.transAxes, color=GRIS)
    tab.plot([0, 1], [yy - 0.045, yy - 0.045], color=NEGRO, lw=1.2, transform=tab.transAxes, clip_on=False)
    if teor:
        tab.text(0, yy - 0.12, "En azul, lo que predicen las fórmulas\n" + teor.get("_origen", ""), fontsize=8.5,
                 color="#555", transform=tab.transAxes, va="top")
    return fig


def figura_aviso(mensaje, w=9.6, h=1.8):
    fig = _fig(w, h)
    ax = fig.add_subplot()
    ax.axis("off")
    ax.text(0.5, 0.5, mensaje, ha="center", va="center", fontsize=11, color="#444", wrap=True)
    return fig


def fig_cada_magnitud(tt, y, yinf, met, teor=None, *, w=11.0, h=7.6):
    """Una gráfica por magnitud: cómo se mide cada una sobre la misma curva."""
    fig = _fig(w, h)
    axs = fig.subplots(2, 2)
    s = 1.0 if yinf > 0 else -1.0
    yn = s * np.asarray(y)
    yf = abs(yinf)
    ymax = float(np.max(yn))
    teor = teor or {}
    hay_pico = met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", math.nan))
    techo = max(ymax, yf * 1.05) + 0.12 * yf

    def base(ax, titulo, texto):
        ax.plot(tt, yn, color="#9a9a9a", lw=1.4, zorder=2)
        ax.axhline(yf, color=GRIS, lw=0.7, ls="--")
        ax.axhline(0, color=NEGRO, lw=0.5)
        ax.set_xlim(0, tt[-1])
        ax.set_ylim(min(0.0, float(np.min(yn))) - 0.05 * yf, techo)
        ax.set_title(titulo, fontsize=11.5)
        ax.text(0.98, 0.04, texto, transform=ax.transAxes, ha="right", va="bottom", fontsize=9.5,
                bbox=dict(fc="white", ec="#cccccc", lw=0.6, pad=4), zorder=6)
        ax.set_xlabel("$t$ (s)")
        ax.grid(True)

    def formula(clave, txt):
        if clave in teor:
            return f"\nfórmula: ${teor[clave][0]}$ = {_num(teor[clave][1])}" + (" %" if clave == "Mp" else " s")
        return ""

    # (a) td
    a = axs[0, 0]
    td = met.get("td", math.nan)
    base(a, f"Tiempo de retardo:  $t_d$ = {_num(td)} s",
         "tiempo hasta llegar al 50 % del valor final" + formula("td", ""))
    if np.isfinite(td):
        a.axvspan(0, td, color=AZUL, alpha=0.12, lw=0)
        a.plot(tt[tt <= td], yn[tt <= td], color=AZUL, lw=2.4, zorder=3)
        a.plot([0, td], [0.5 * yf, 0.5 * yf], color=AZUL, ls="--", lw=1)
        a.plot([td], [0.5 * yf], "o", color=AZUL, ms=7, zorder=5)
        a.text(td, 0.5 * yf, "  50 %", color=AZUL, va="top", fontsize=10)
    _rotulo(a, "a")

    # (b) tr
    b = axs[0, 1]
    if hay_pico:
        tr = met.get("tr", math.nan)
        base(b, f"Tiempo de subida:  $t_r$ = {_num(tr)} s",
             "del 0 al 100 % del valor final\n(hay sobreoscilación)" + formula("tr", ""))
        t0, t1 = 0.0, tr
    else:
        t0, t1 = _cruce(tt, yn, 0.1 * yf), _cruce(tt, yn, 0.9 * yf)
        base(b, f"Tiempo de subida:  $t_r$ = {_num(t1 - t0)} s",
             "del 10 al 90 % del valor final\n(no hay sobreoscilación)" + formula("tr", ""))
        for nivel in (0.1, 0.9):
            b.plot([0, tt[-1]], [nivel * yf] * 2, color=VERDE, ls=":", lw=1)
    if np.isfinite(t0) and np.isfinite(t1):
        b.axvspan(t0, t1, color=VERDE, alpha=0.13, lw=0)
        m = (tt >= t0) & (tt <= t1)
        b.plot(tt[m], yn[m], color=VERDE, lw=2.4, zorder=3)
        b.plot([t0, t1], [np.interp(t0, tt, yn), np.interp(t1, tt, yn)], "o", color=VERDE, ms=7, zorder=5)
        b.annotate("", xy=(t1, 0.08 * yf), xytext=(t0, 0.08 * yf),
                   arrowprops=dict(arrowstyle="<->", color=VERDE, lw=1.2, shrinkA=0, shrinkB=0))
    _rotulo(b, "b")

    # (c) tp y Mp
    c = axs[1, 0]
    if hay_pico:
        tp, Mp = met["tp"], met["Mp"]
        base(c, f"Pico:  $t_p$ = {_num(tp)} s,   $M_p$ = {_num(Mp)} %",
             "$t_p$: instante del primer máximo\n$M_p$: cuánto se pasa del valor final" + formula("tp", "")
             + formula("Mp", ""))
        c.axvspan(0, tp, color=ROJO, alpha=0.08, lw=0)
        c.plot([tp], [ymax], "o", color=ROJO, ms=8, zorder=5)
        c.annotate("", xy=(tp, ymax), xytext=(tp, yf),
                   arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.4, shrinkA=0, shrinkB=0))
        c.text(tp + 0.02 * tt[-1], (ymax + yf) / 2, f"$M_p$ = {_num(Mp)} %", color=ROJO, fontsize=11, va="center")
        c.plot([tp, tp], [0, yf], color=ROJO, ls="--", lw=1)
        c.annotate("", xy=(tp, 0.08 * yf), xytext=(0, 0.08 * yf),
                   arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.2, shrinkA=0, shrinkB=0))
    else:
        base(c, "Pico: no hay", "La salida no se pasa del valor final:\nno hay $t_p$ y $M_p$ = 0 %")
    _rotulo(c, "c")

    # (d) ts
    d = axs[1, 1]
    ts = met.get("ts2", math.nan)
    base(d, f"Establecimiento:  $t_s$ = {_num(ts)} s  (banda del 2 %)",
         "desde $t_s$ la salida ya no sale\nde la banda del ±2 %" + formula("ts2", ""))
    d.axhspan(yf * 0.98, yf * 1.02, color=AMBAR, alpha=0.25, lw=0)
    if np.isfinite(ts):
        d.axvspan(ts, tt[-1], color=AMBAR, alpha=0.08, lw=0)
        m = tt >= ts
        d.plot(tt[m], yn[m], color=AMBAR, lw=2.4, zorder=3)
        d.plot([ts], [np.interp(ts, tt, yn)], "o", color=AMBAR, ms=7, zorder=5)
        d.annotate("", xy=(ts, 0.08 * yf), xytext=(0, 0.08 * yf),
                   arrowprops=dict(arrowstyle="<->", color=AMBAR, lw=1.2, shrinkA=0, shrinkB=0))
    _rotulo(d, "d")
    for ax in axs.flat:
        ax.set_ylabel("$y(t)$")
    return fig


def _mathtext(txt):
    """LaTeX de KaTeX -> mathtext; None si matplotlib no sabe dibujarlo."""
    from matplotlib.mathtext import MathTextParser
    t = (txt.replace(r"\dfrac", r"\frac").replace(r"\left[", "[").replace(r"\right]", "]")
         .replace(r"\left(", "(").replace(r"\right)", ")").replace(r"\operatorname{sen}", r"\mathrm{sen}\,")
         .replace(r"\text{c.c.}", r"\mathrm{c.c.}").replace(r"\quad", r"\ "))
    try:
        MathTextParser("agg").parse("$" + t + "$", dpi=72)
    except Exception:  # noqa: BLE001
        return None
    return "$" + t + "$"


def fig_camino_laplace(r_tex, R_tex, G_tex, Y_tex, fs_tex, y_tex, *, w=11.0, h=4.6):
    """El método del tema en un diagrama: del tiempo a s, multiplicar, descomponer y volver."""
    fig = Figure(figsize=(w, h))
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, 11)
    ax.set_ylim(0, 4.6)
    ax.axis("off")
    ax.add_patch(Rectangle((0.05, 2.55), 10.9, 1.95, fc="#f6f6f3", ec="none", zorder=0))
    ax.add_patch(Rectangle((0.05, 0.1), 10.9, 2.3, fc="#eef3f8", ec="none", zorder=0))
    ax.text(0.15, 4.38, "dominio del tiempo", fontsize=10, style="italic", color="#555", va="top")
    ax.text(0.15, 0.18, "dominio de Laplace (variable $s$)", fontsize=10, style="italic", color=AZUL, va="bottom")

    def caja(x, y, ancho, titulo, expr, generico):
        ax.add_patch(Rectangle((x - ancho / 2, y - 0.5), ancho, 1.0, fc="white", ec=NEGRO, lw=1.0, zorder=2))
        ax.text(x, y + 0.32, titulo, ha="center", va="center", fontsize=11.5, color="#444", zorder=3)
        t = _mathtext(expr) if expr else None
        if t is None:
            t = generico
        # tamaño de letra según lo que quepa en la caja (unos 0.085 cm de ancho por carácter a 10 pt)
        n = max(len(re.sub(r"\\[a-zA-Z]+|[{}^_ ]", "", expr or generico)), 1)
        ajuste = 10.0 * (ancho * 0.92) / (n * 0.075)
        ax.text(x, y - 0.1, t, ha="center", va="center", fontsize=max(9.0, min(17.0, ajuste)), zorder=3)

    def flecha(p0, p1, texto, lado="arriba"):
        ax.annotate("", xy=p1, xytext=p0, arrowprops=dict(arrowstyle="-|>", color=NEGRO, lw=1.2, mutation_scale=13),
                    zorder=1)
        xm, ym = (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2
        if lado == "arriba":
            ax.text(xm, ym + 0.12, texto, ha="center", va="bottom", fontsize=11.5, color=AZUL)
        elif lado == "izq":
            ax.text(xm - 0.1, ym, texto, ha="right", va="center", fontsize=11.5, color=AZUL)
        else:
            ax.text(xm + 0.1, ym, texto, ha="left", va="center", fontsize=11.5, color=AZUL)

    caja(1.75, 3.45, 3.1, "① la entrada", "r(t)=" + r_tex, "$r(t)$")
    caja(1.75, 1.15, 3.1, "② su transformada", "R(s)=" + R_tex, "$R(s)$")
    caja(5.5, 1.15, 3.6, "③ la salida en $s$", "Y(s)=" + Y_tex, "$Y(s)=G(s)\\,R(s)$")
    caja(9.25, 1.15, 3.2, "④ fracciones simples", "Y(s)=" + fs_tex, "$\\sum\\,A_i/(s-p_i)$")
    caja(7.4, 3.45, 6.6, "⑤ la salida en el tiempo", "y(t)=" + y_tex, "$y(t)=\\sum$ modos")
    flecha((1.75, 2.95), (1.75, 1.65), "tabla de\ntransformadas", "der")
    flecha((3.3, 1.15), (3.7, 1.15), "")
    gt = _mathtext("G(s)=" + G_tex)
    ax.text(3.5, 1.95, "× " + (gt or "$G(s)$"), ha="center", va="bottom", fontsize=12.5, color=AZUL)
    flecha((7.3, 1.15), (7.65, 1.15), "")
    ax.text(7.47, 1.95, "descomponer", ha="center", va="bottom", fontsize=11.5, color=AZUL)
    flecha((9.25, 1.65), (9.25, 2.95), "  tabla al revés\n  ($\\mathcal{L}^{-1}$)", "der")
    return fig