OncomIA Claude Opus 5.5 commited on
Commit ·
77ba96d
1
Parent(s): 73d940a
Simulador de control clásico del Tema 3
Browse filesLaplace, polos y ceros, diagramas de bloques y controlador PID:
respuesta temporal con especificaciones acotadas, lazo abierto y
cerrado, PID real con anti-windup, asignación de polos y animaciones.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- README.md +46 -7
- animaciones.py +277 -0
- app.py +511 -0
- ayuda.py +252 -0
- bloques.py +335 -0
- estilo.css +210 -0
- graficas.py +864 -0
- nucleo.py +1135 -0
- paneles.py +1234 -0
- requirements.txt +4 -0
README.md
CHANGED
|
@@ -1,13 +1,52 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Simulador de control clásico (Tema 3)
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.50.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
short_description: Laplace, polos y ceros, diagramas de bloques y PID
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Simulador de control clásico — Tema 3
|
| 15 |
+
|
| 16 |
+
Acompaña a los apuntes de teoría del Tema 3 (*Técnicas de optimización y control*).
|
| 17 |
+
Todo se calcula en el dominio de Laplace y se vuelve al tiempo, con la misma notación
|
| 18 |
+
de los apuntes ($\omega_n$, $\zeta$, $\sigma=\zeta\omega_n$, $\omega_d$, $\beta=\arccos\zeta$).
|
| 19 |
+
|
| 20 |
+
| Pestaña | Qué hace |
|
| 21 |
+
|:--|:--|
|
| 22 |
+
| 1 · Respuesta temporal | Dado $G(s)$ (por parámetros de 1.er, 2.º o 3.er orden, o escrita a mano) y una entrada, obtiene $R(s)$, $Y(s)$, las fracciones simples, $y(t)$, los valores inicial y final, y las especificaciones $t_d,t_r,t_p,M_p,t_s$ (fórmula frente a curva). Las especificaciones se acotan sobre la curva, todas juntas y una a una. Explica por qué el sistema es estable y cuál es el polo dominante, y dibuja el camino de Laplace. Animación al variar $\zeta$, $\omega_n$, $K$, $\tau$, $p$ o el cero. |
|
| 23 |
+
| 2 · Diagramas de bloques | Serie, paralelo, realimentación y lazos anidados por ecuaciones de señales; lazo abierto $L(s)$, lazo cerrado y aviso de cancelaciones polo–cero peligrosas. |
|
| 24 |
+
| 3 · Controlador PID | Diagrama del lazo con los valores actuales; simulación exacta con las tres acciones separadas, forma paralela o ISA, filtro derivativo, derivada sobre la medida, saturación, anti-windup, cambios de consigna y perturbación; trayectoria de los polos; diseño por asignación de polos; animaciones del paso de estable a inestable (con el valor crítico) y de las señales en el tiempo. |
|
| 25 |
+
|
| 26 |
+
Cada control y cada figura lleva un **?** con su explicación.
|
| 27 |
+
|
| 28 |
+
## Cómo publicarlo en Hugging Face
|
| 29 |
+
|
| 30 |
+
1. En <https://huggingface.co/new-space> cree un Space con SDK **Gradio** (hardware gratuito *CPU basic*).
|
| 31 |
+
2. Suba todos los ficheros de esta carpeta (`app.py`, `nucleo.py`, `paneles.py`, `graficas.py`,
|
| 32 |
+
`bloques.py`, `animaciones.py`, `ayuda.py`, `estilo.css`, `requirements.txt` y este
|
| 33 |
+
`README.md`), por la web
|
| 34 |
+
(«Files → Add file → Upload files») o con git:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
git clone https://huggingface.co/spaces/<usuario>/<nombre-del-space>
|
| 38 |
+
cp *.py estilo.css requirements.txt README.md <nombre-del-space>/
|
| 39 |
+
cd <nombre-del-space> && git add . && git commit -m "Simulador Tema 3" && git push
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
3. El Space se construye solo en un par de minutos. La cabecera YAML de este fichero fija
|
| 43 |
+
Gradio 5.50 y Python 3.12, que son las versiones con las que se ha probado.
|
| 44 |
+
|
| 45 |
+
## Ejecutarlo en local
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
pip install gradio==5.50.0 -r requirements.txt
|
| 49 |
+
python app.py
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
y abrir <http://127.0.0.1:7860>.
|
animaciones.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Animaciones (GIF) del simulador.
|
| 2 |
+
|
| 3 |
+
Dos tipos:
|
| 4 |
+
- barrido de un parámetro dentro de un rango: en cada fotograma se ven los
|
| 5 |
+
polos en el plano s, la respuesta temporal y una barra con el rango del
|
| 6 |
+
parámetro coloreada según la estabilidad, de modo que se ve el instante
|
| 7 |
+
en que un polo cruza el eje imaginario y el sistema pasa a ser inestable;
|
| 8 |
+
- evolución temporal: las señales del lazo se dibujan a medida que avanza
|
| 9 |
+
el tiempo, con los cambios de consigna y la perturbación.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import math
|
| 13 |
+
import tempfile
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
| 17 |
+
from matplotlib.figure import Figure
|
| 18 |
+
from PIL import Image
|
| 19 |
+
from scipy import signal
|
| 20 |
+
|
| 21 |
+
import graficas as gf
|
| 22 |
+
|
| 23 |
+
COLOR = {"estable": gf.VERDE, "límite": gf.AMBAR, "inestable": gf.ROJO}
|
| 24 |
+
CLARO = {"estable": "#cfe5cf", "límite": "#f1e2b8", "inestable": "#f2cccc"}
|
| 25 |
+
ROTULO = {"estable": "ESTABLE", "límite": "LÍMITE DE ESTABILIDAD", "inestable": "INESTABLE"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def estado_de(polos, tol=1e-7):
|
| 29 |
+
polos = np.asarray(polos, dtype=complex)
|
| 30 |
+
if polos.size == 0:
|
| 31 |
+
return "estable"
|
| 32 |
+
m = float(np.max(polos.real))
|
| 33 |
+
esc = max(1.0, float(np.max(np.abs(polos))))
|
| 34 |
+
if m > tol * esc:
|
| 35 |
+
return "inestable"
|
| 36 |
+
if m > -tol * esc:
|
| 37 |
+
return "límite"
|
| 38 |
+
return "estable"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def respuesta_num(num, den, tt, u=None, impulso=False):
|
| 42 |
+
"""Respuesta numérica de num/den (escalón u, o impulso), recortada si diverge."""
|
| 43 |
+
with np.errstate(all="ignore"):
|
| 44 |
+
try:
|
| 45 |
+
if impulso:
|
| 46 |
+
_, y = signal.impulse((num, den), T=tt)
|
| 47 |
+
else:
|
| 48 |
+
_, y, _ = signal.lsim((num, den), u, tt)
|
| 49 |
+
except Exception: # noqa: BLE001
|
| 50 |
+
y = np.full_like(tt, np.nan)
|
| 51 |
+
y = np.asarray(y, float)
|
| 52 |
+
y[~np.isfinite(y)] = np.nan
|
| 53 |
+
return np.clip(y, -1e6, 1e6)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def criticos(valores, f_maxre):
|
| 57 |
+
"""Valores del parámetro en que la parte real máxima de los polos cruza 0 (bisección)."""
|
| 58 |
+
out = []
|
| 59 |
+
fr = [f_maxre(v) for v in valores]
|
| 60 |
+
for i in range(len(valores) - 1):
|
| 61 |
+
a, b, fa, fb = valores[i], valores[i + 1], fr[i], fr[i + 1]
|
| 62 |
+
if not (np.isfinite(fa) and np.isfinite(fb)) or (fa > 0) == (fb > 0):
|
| 63 |
+
continue
|
| 64 |
+
for _ in range(50):
|
| 65 |
+
m = 0.5 * (a + b)
|
| 66 |
+
fm = f_maxre(m)
|
| 67 |
+
if (fm > 0) == (fa > 0):
|
| 68 |
+
a, fa = m, fm
|
| 69 |
+
else:
|
| 70 |
+
b = m
|
| 71 |
+
vc = 0.5 * (a + b)
|
| 72 |
+
out.append(0.0 if abs(vc) < 1e-7 * max(abs(valores[-1] - valores[0]), 1e-12) else vc)
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _a_imagen(canvas):
|
| 77 |
+
w, h = canvas.get_width_height()
|
| 78 |
+
return Image.frombuffer("RGBA", (w, h), canvas.buffer_rgba(), "raw", "RGBA", 0, 1).convert("RGB")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _guarda_gif(fig, actualiza, n, fps, prefijo):
|
| 82 |
+
canvas = FigureCanvasAgg(fig)
|
| 83 |
+
actualiza(0)
|
| 84 |
+
canvas.draw()
|
| 85 |
+
primera = _a_imagen(canvas)
|
| 86 |
+
paleta = primera.quantize(colors=128, method=Image.Quantize.MEDIANCUT)
|
| 87 |
+
imgs = [primera.quantize(palette=paleta, dither=Image.Dither.NONE)]
|
| 88 |
+
for k in range(1, n):
|
| 89 |
+
actualiza(k)
|
| 90 |
+
canvas.draw()
|
| 91 |
+
imgs.append(_a_imagen(canvas).quantize(palette=paleta, dither=Image.Dither.NONE))
|
| 92 |
+
ruta = tempfile.NamedTemporaryFile(prefix=prefijo, suffix=".gif", delete=False).name
|
| 93 |
+
dur = [int(1000 / fps)] * n
|
| 94 |
+
dur[-1] = 1500 # pausa al final antes de repetir
|
| 95 |
+
imgs[0].save(ruta, save_all=True, append_images=imgs[1:], duration=dur, loop=0, disposal=1)
|
| 96 |
+
return ruta
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _limites_plano(puntos):
|
| 100 |
+
pts = np.asarray([p for p in puntos if np.isfinite(p)], dtype=complex)
|
| 101 |
+
if pts.size == 0:
|
| 102 |
+
return -2.0, 1.0, 1.5
|
| 103 |
+
mag = np.abs(pts)
|
| 104 |
+
lim = np.percentile(mag, 92) * 1.8 + 0.5
|
| 105 |
+
pts = pts[mag <= lim]
|
| 106 |
+
xmin = min(float(np.min(pts.real)), 0.0)
|
| 107 |
+
xmax = max(float(np.max(pts.real)), 0.0)
|
| 108 |
+
ymax = max(float(np.max(np.abs(pts.imag))), 0.0)
|
| 109 |
+
span = max(xmax - xmin, 2 * ymax, 1.0)
|
| 110 |
+
xmin -= 0.15 * span
|
| 111 |
+
xmax += 0.15 * span
|
| 112 |
+
ymax = max(ymax * 1.25, 0.3 * (xmax - xmin))
|
| 113 |
+
R = 1.25
|
| 114 |
+
if (xmax - xmin) / (2 * ymax) < R:
|
| 115 |
+
extra = R * 2 * ymax - (xmax - xmin)
|
| 116 |
+
xmin, xmax = xmin - extra / 2, xmax + extra / 2
|
| 117 |
+
else:
|
| 118 |
+
ymax = (xmax - xmin) / (2 * R)
|
| 119 |
+
return xmin, xmax, ymax
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def gif_barrido(frames, nombre, tt, *, yref=None, ylabel=r"$y(t)$", criticos_=(), fps=8, nota_resp=""):
|
| 123 |
+
"""frames: [{'v', 'polos', 'ceros', 'y', 'estado'}]. Devuelve la ruta del GIF."""
|
| 124 |
+
fig = Figure(figsize=(9.6, 5.0), dpi=84)
|
| 125 |
+
fig.patch.set_facecolor("white")
|
| 126 |
+
ax_s = fig.add_axes([0.075, 0.31, 0.38, 0.56])
|
| 127 |
+
ax_t = fig.add_axes([0.555, 0.31, 0.42, 0.56])
|
| 128 |
+
ax_b = fig.add_axes([0.075, 0.1, 0.9, 0.06])
|
| 129 |
+
|
| 130 |
+
todos = np.concatenate([np.asarray(f["polos"], complex) for f in frames] +
|
| 131 |
+
[np.asarray(f["ceros"], complex) for f in frames])
|
| 132 |
+
xmin, xmax, ymax = _limites_plano(todos)
|
| 133 |
+
ax_s.axvspan(xmin, 0, color="#f5f5f5", zorder=0, lw=0)
|
| 134 |
+
ax_s.axhline(0, color=gf.NEGRO, lw=0.6)
|
| 135 |
+
ax_s.axvline(0, color=gf.NEGRO, lw=0.9)
|
| 136 |
+
ax_s.text(0.02, 0.97, "estable", transform=ax_s.transAxes, fontsize=8.5, va="top", style="italic", color="#555")
|
| 137 |
+
ax_s.text(0.98, 0.97, "inestable", transform=ax_s.transAxes, fontsize=8.5, va="top", ha="right",
|
| 138 |
+
style="italic", color="#555")
|
| 139 |
+
for f in frames:
|
| 140 |
+
p = np.asarray(f["polos"], complex)
|
| 141 |
+
if p.size:
|
| 142 |
+
ax_s.scatter(p.real, p.imag, s=5, color=CLARO[f["estado"]] if f["estado"] != "estable" else "#b9d3e8",
|
| 143 |
+
lw=0, zorder=1)
|
| 144 |
+
pol_line, = ax_s.plot([], [], "x", ms=11, mew=2.3, zorder=5)
|
| 145 |
+
cer_line, = ax_s.plot([], [], "o", ms=9, mfc="white", mew=1.6, color=gf.NEGRO, zorder=5)
|
| 146 |
+
ax_s.set_xlim(xmin, xmax)
|
| 147 |
+
ax_s.set_ylim(-ymax, ymax)
|
| 148 |
+
ax_s.set_aspect("equal", adjustable="box")
|
| 149 |
+
ax_s.set_xlabel(r"Real, $\sigma$")
|
| 150 |
+
ax_s.set_ylabel(r"Imaginario, $j\omega$")
|
| 151 |
+
ax_s.grid(True)
|
| 152 |
+
ax_s.set_title("polos (×) y ceros (○)", fontsize=10)
|
| 153 |
+
|
| 154 |
+
ys_est = [f["y"] for f in frames if f["estado"] == "estable" and np.all(np.isfinite(f["y"]))]
|
| 155 |
+
if ys_est:
|
| 156 |
+
lo = min(0.0, float(min(np.min(y) for y in ys_est)))
|
| 157 |
+
hi = float(max(np.max(y) for y in ys_est))
|
| 158 |
+
else:
|
| 159 |
+
base = abs(yref) if yref else 1.0
|
| 160 |
+
lo, hi = -2 * base, 3 * base
|
| 161 |
+
if yref is not None:
|
| 162 |
+
lo, hi = min(lo, 0.0, yref), max(hi, yref * 1.1)
|
| 163 |
+
span = max(hi - lo, 1e-6)
|
| 164 |
+
lo, hi = lo - 0.1 * span, hi + 0.12 * span
|
| 165 |
+
for f in frames:
|
| 166 |
+
if f["estado"] == "estable":
|
| 167 |
+
ax_t.plot(tt, f["y"], color="#e4e4e4", lw=0.5, zorder=1)
|
| 168 |
+
if yref is not None:
|
| 169 |
+
ax_t.axhline(yref, color=gf.GRIS, ls="--", lw=1.0, zorder=2)
|
| 170 |
+
resp_line, = ax_t.plot([], [], lw=2.0, zorder=4)
|
| 171 |
+
ax_t.axhline(0, color=gf.NEGRO, lw=0.4)
|
| 172 |
+
ax_t.set_xlim(tt[0], tt[-1])
|
| 173 |
+
ax_t.set_ylim(lo, hi)
|
| 174 |
+
ax_t.set_xlabel(r"$t$ (s)")
|
| 175 |
+
ax_t.set_ylabel(ylabel)
|
| 176 |
+
ax_t.grid(True)
|
| 177 |
+
ax_t.set_title("respuesta " + nota_resp, fontsize=10)
|
| 178 |
+
aviso = ax_t.text(0.5, 0.5, "", transform=ax_t.transAxes, ha="center", va="center", fontsize=11,
|
| 179 |
+
color=gf.ROJO, bbox=dict(fc="white", ec=gf.ROJO, lw=0.8, pad=4), zorder=6)
|
| 180 |
+
aviso.set_visible(False)
|
| 181 |
+
|
| 182 |
+
vals = np.array([f["v"] for f in frames])
|
| 183 |
+
dv = (vals[-1] - vals[0]) / max(len(vals) - 1, 1)
|
| 184 |
+
for f in frames:
|
| 185 |
+
ax_b.axvspan(f["v"] - dv / 2, f["v"] + dv / 2, color=CLARO[f["estado"]], lw=0)
|
| 186 |
+
for vc in criticos_:
|
| 187 |
+
vc = 0.0 if abs(vc) < 1e-6 * max(abs(vals[-1] - vals[0]), 1e-12) else vc
|
| 188 |
+
ax_b.axvline(vc, color=gf.NEGRO, lw=1.0)
|
| 189 |
+
ax_b.text(vc, 1.15, f"crítico ≈ {vc:.4g}", fontsize=8.5, ha="center", va="bottom",
|
| 190 |
+
transform=ax_b.get_xaxis_transform())
|
| 191 |
+
marca, = ax_b.plot([], [], "v", ms=11, color=gf.NEGRO, zorder=5, clip_on=False)
|
| 192 |
+
ax_b.set_xlim(vals[0] - dv / 2, vals[-1] + dv / 2)
|
| 193 |
+
ax_b.set_ylim(0, 1)
|
| 194 |
+
ax_b.set_yticks([])
|
| 195 |
+
ax_b.tick_params(axis="y", which="both", left=False, right=False)
|
| 196 |
+
ax_b.set_xlabel(nombre + " (verde: estable · rojo: inestable)", fontsize=9.5)
|
| 197 |
+
titulo = fig.text(0.5, 0.95, "", ha="center", va="center", fontsize=14, weight="bold")
|
| 198 |
+
|
| 199 |
+
def actualiza(k):
|
| 200 |
+
f = frames[k]
|
| 201 |
+
col = COLOR[f["estado"]]
|
| 202 |
+
p = np.asarray(f["polos"], complex)
|
| 203 |
+
z = np.asarray(f["ceros"], complex)
|
| 204 |
+
pol_line.set_data(p.real, p.imag)
|
| 205 |
+
pol_line.set_color(col)
|
| 206 |
+
cer_line.set_data(z.real, z.imag)
|
| 207 |
+
y = np.clip(f["y"], lo - span, hi + span)
|
| 208 |
+
resp_line.set_data(tt, y)
|
| 209 |
+
resp_line.set_color(gf.NEGRO if f["estado"] == "estable" else col)
|
| 210 |
+
aviso.set_visible(f["estado"] != "estable")
|
| 211 |
+
aviso.set_text("diverge: polo en el semiplano derecho" if f["estado"] == "inestable"
|
| 212 |
+
else "oscilación mantenida: polos sobre el eje jω")
|
| 213 |
+
marca.set_data([f["v"]], [1.05])
|
| 214 |
+
titulo.set_text(f"{nombre} = {f['v']:.4g} · {ROTULO[f['estado']]}")
|
| 215 |
+
titulo.set_color(col)
|
| 216 |
+
|
| 217 |
+
return _guarda_gif(fig, actualiza, len(frames), fps, "barrido_")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def gif_temporal(sim, *, nfr=50, fps=12, umin=None, umax=None):
|
| 221 |
+
"""Las señales del lazo se dibujan según avanza el tiempo."""
|
| 222 |
+
tt, y, r, u = sim["t"], sim["y"], sim["r"], sim["u"]
|
| 223 |
+
fig = Figure(figsize=(9.6, 5.6), dpi=84)
|
| 224 |
+
fig.patch.set_facecolor("white")
|
| 225 |
+
a = fig.add_axes([0.08, 0.55, 0.88, 0.36])
|
| 226 |
+
c = fig.add_axes([0.08, 0.1, 0.88, 0.36], sharex=a)
|
| 227 |
+
a.plot(tt, r, color=gf.GRIS, ls="--", lw=1.1, drawstyle="steps-post", label=r"consigna $r(t)$")
|
| 228 |
+
ly, = a.plot([], [], color=gf.NEGRO, lw=2.0, label=r"salida $y(t)$")
|
| 229 |
+
py, = a.plot([], [], "o", color=gf.ROJO, ms=6)
|
| 230 |
+
lo, hi = gf._rango(y, r)
|
| 231 |
+
sp_ = max(hi - lo, 1e-6)
|
| 232 |
+
a.set_ylim(lo - 0.08 * sp_, hi + 0.12 * sp_)
|
| 233 |
+
a.set_ylabel(r"$y(t)$")
|
| 234 |
+
a.legend(loc="lower right")
|
| 235 |
+
a.grid(True)
|
| 236 |
+
series = [("P", sim["P"], gf.AZUL, "--", r"$P$"), ("I", sim["I"], gf.VERDE, "-.", r"$I$"),
|
| 237 |
+
("D", sim["D"], gf.ROJO, ":", r"$D$"), ("u", u, gf.NEGRO, "-", r"$u=P+I+D$")]
|
| 238 |
+
lineas = []
|
| 239 |
+
vals = []
|
| 240 |
+
for _, v, col, ls, lab in series:
|
| 241 |
+
if np.any(np.abs(v) > 1e-12):
|
| 242 |
+
ln, = c.plot([], [], color=col, ls=ls, lw=1.9 if lab.startswith("$u") else 1.3, label=lab)
|
| 243 |
+
lineas.append((ln, v))
|
| 244 |
+
vals.append(v)
|
| 245 |
+
for lim in (umin, umax):
|
| 246 |
+
if lim is not None:
|
| 247 |
+
c.axhline(lim, color=gf.GRIS, ls=(0, (4, 2)), lw=0.8)
|
| 248 |
+
v = np.concatenate([x[np.isfinite(x)] for x in vals]) if vals else np.array([0.0, 1.0])
|
| 249 |
+
q1, q2 = np.percentile(v, [1, 99])
|
| 250 |
+
lo, hi = min(float(np.min(v)), 0.0), max(float(np.max(v)), 0.0)
|
| 251 |
+
if hi - lo > 4 * (q2 - q1 + 1e-9):
|
| 252 |
+
lo, hi = min(q1, 0.0), max(q2, 0.0)
|
| 253 |
+
pad = 0.12 * (hi - lo + 1e-9)
|
| 254 |
+
c.set_ylim(lo - pad, hi + pad)
|
| 255 |
+
c.axhline(0, color=gf.NEGRO, lw=0.4)
|
| 256 |
+
c.set_ylabel(r"$u(t)$ y sus acciones")
|
| 257 |
+
c.set_xlabel(r"$t$ (s)")
|
| 258 |
+
c.legend(loc="upper right", ncol=4, fontsize=8.5)
|
| 259 |
+
c.grid(True)
|
| 260 |
+
a.set_xlim(tt[0], sim.get("t_end", tt[-1]))
|
| 261 |
+
cursores = [ax.axvline(0, color=gf.AMBAR, lw=1.0) for ax in (a, c)]
|
| 262 |
+
titulo = fig.text(0.5, 0.955, "", ha="center", va="center", fontsize=13, weight="bold")
|
| 263 |
+
instantes = np.linspace(tt[0], tt[-1], nfr)
|
| 264 |
+
|
| 265 |
+
def actualiza(k):
|
| 266 |
+
tk = instantes[k]
|
| 267 |
+
i = int(np.searchsorted(tt, tk, side="right"))
|
| 268 |
+
i = max(i, 1)
|
| 269 |
+
ly.set_data(tt[:i], y[:i])
|
| 270 |
+
py.set_data([tt[i - 1]], [y[i - 1]])
|
| 271 |
+
for ln, vv in lineas:
|
| 272 |
+
ln.set_data(tt[:i], vv[:i])
|
| 273 |
+
for cu in cursores:
|
| 274 |
+
cu.set_xdata([tk, tk])
|
| 275 |
+
titulo.set_text(f"t = {tk:.3g} s r = {r[i - 1]:.3g} y = {y[i - 1]:.3g} u = {u[i - 1]:.3g}")
|
| 276 |
+
|
| 277 |
+
return _guarda_gif(fig, actualiza, nfr, fps, "senales_")
|
app.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulador de control clásico — Tema 3: Laplace, polos y ceros, diagramas
|
| 2 |
+
de bloques y el controlador PID. Aplicación Gradio para Hugging Face Spaces."""
|
| 3 |
+
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
import paneles as pn
|
| 9 |
+
from ayuda import script as script_ayuda
|
| 10 |
+
from bloques import BLOQUES_USADOS, TOPOLOGIAS
|
| 11 |
+
from nucleo import ENTRADAS
|
| 12 |
+
|
| 13 |
+
AQUI = Path(__file__).parent
|
| 14 |
+
CSS = (AQUI / "estilo.css").read_text(encoding="utf-8")
|
| 15 |
+
LATEX = [{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}]
|
| 16 |
+
|
| 17 |
+
AZUL = gr.themes.Color(
|
| 18 |
+
c50="#eef3f8", c100="#d9e4ef", c200="#b3c8de", c300="#8dacce", c400="#5f88b5", c500="#1f4e79",
|
| 19 |
+
c600="#1b456b", c700="#173b5c", c800="#12304b", c900="#0d2438", c950="#081826",
|
| 20 |
+
)
|
| 21 |
+
TEMA = gr.themes.Base(
|
| 22 |
+
primary_hue=AZUL,
|
| 23 |
+
secondary_hue=gr.themes.colors.gray,
|
| 24 |
+
neutral_hue=gr.themes.colors.gray,
|
| 25 |
+
font=[gr.themes.GoogleFont("STIX Two Text"), "Times New Roman", "serif"],
|
| 26 |
+
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
|
| 27 |
+
radius_size=gr.themes.sizes.radius_none,
|
| 28 |
+
).set(
|
| 29 |
+
body_background_fill="#ffffff",
|
| 30 |
+
block_background_fill="#ffffff",
|
| 31 |
+
block_border_width="0.6px",
|
| 32 |
+
block_border_color="#d4d4d4",
|
| 33 |
+
block_shadow="none",
|
| 34 |
+
block_label_text_size="*text_sm",
|
| 35 |
+
block_title_text_weight="600",
|
| 36 |
+
button_primary_background_fill="*primary_500",
|
| 37 |
+
button_primary_background_fill_hover="*primary_700",
|
| 38 |
+
button_primary_text_color="#ffffff",
|
| 39 |
+
button_secondary_background_fill="#f3f3f0",
|
| 40 |
+
button_secondary_border_color="#c9c9c9",
|
| 41 |
+
slider_color="*primary_500",
|
| 42 |
+
checkbox_background_color_selected="*primary_500",
|
| 43 |
+
input_border_width="0.6px",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
ORDENES = ["1.er orden: K/(τs+1)", "2.º orden: Kωn²/(s²+2ζωn s+ωn²)", "3.er orden: 2.º orden · p/(s+p)"]
|
| 47 |
+
EJEMPLOS_G = {
|
| 48 |
+
"Segundo orden con un cero: (s+3)/((s+1)(s+2))": "(s+3)/((s+1)*(s+2))",
|
| 49 |
+
"Cero en el semiplano derecho: (−s+3)/((s+1)(s+2))": "(-s+3)/((s+1)*(s+2))",
|
| 50 |
+
"Polos −3 ± j4 (ejemplo tipo de Mp)": "25/(s^2+6*s+25)",
|
| 51 |
+
"Tercer orden, r = 4: 2/((s²+s+1)(s+2))": "2/((s^2+s+1)*(s+2))",
|
| 52 |
+
"Polo doble (caso crítico): 4/(s+2)²": "4/(s+2)^2",
|
| 53 |
+
"Integrador con primer orden: 1/(s(s+1))": "1/(s*(s+1))",
|
| 54 |
+
"Tres polos reales: 1/(s+1)³": "1/(s+1)^3",
|
| 55 |
+
"Dipolo: (s+1.1)/((s+1)(s+5))": "5*(s+1.1)/(1.1*(s+1)*(s+5))",
|
| 56 |
+
"Inestable: 1/(s²−s+4)": "1/(s^2-s+4)",
|
| 57 |
+
}
|
| 58 |
+
EJEMPLOS_PLANTA = {
|
| 59 |
+
"Primer orden 1/(s+1) (figura de la acción integral)": "1/(s+1)",
|
| 60 |
+
"Integrador 1/(s(s+1)) (figura de la acción derivativa)": "1/(s*(s+1))",
|
| 61 |
+
"Dos polos reales 1/((s+1)(s+2))": "1/((s+1)*(s+2))",
|
| 62 |
+
"Tres retardos de primer orden 1/(s+1)³": "1/(s+1)^3",
|
| 63 |
+
"Horno 2/((10s+1)(2s+1))": "2/((10*s+1)*(2*s+1))",
|
| 64 |
+
"Motor de posición 5/(s(0.5s+1))": "5/(s*(0.5*s+1))",
|
| 65 |
+
"Fase no mínima (−s+1)/((s+1)(s+2))": "(-s+1)/((s+1)*(s+2))",
|
| 66 |
+
}
|
| 67 |
+
EJEMPLOS_BLOQUES = {
|
| 68 |
+
"Lazo de control: C = 4, planta 1/(s(s+1))": ("Lazo cerrado (realimentación)", "4", "1/(s*(s+1))", "1", "1"),
|
| 69 |
+
"Ejemplo resuelto de los apuntes (lazos anidados)": ("Lazos anidados", "10", "1/(s+1)", "2", "1"),
|
| 70 |
+
"Realimentación tacométrica: 16 · 1/(s(s+2)), H₁ = 2s": ("Lazos anidados", "16", "1/(s*(s+2))", "2*s", "1"),
|
| 71 |
+
"Sensor con dinámica: H = 1/(0.1s+1)": ("Lazo cerrado (realimentación)", "8", "1/((s+1)*(s+2))", "1/(0.1*s+1)", "1"),
|
| 72 |
+
"Cancelación peligrosa: (s−1) · 1/(s−1)(s+2)": ("Serie", "(s-1)/(s+3)", "1/((s-1)*(s+2))", "1", "1"),
|
| 73 |
+
"Paralelo: 1/(s+1) + 2/(s+3)": ("Paralelo", "1/(s+1)", "2/(s+3)", "1", "1"),
|
| 74 |
+
}
|
| 75 |
+
MODOS_ANIM = ["Barrido de una ganancia (polos y respuesta)", "Señales en el tiempo (consigna y perturbación)"]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def md(texto="", **kw):
|
| 79 |
+
return gr.Markdown(texto, latex_delimiters=LATEX, **kw)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def cap(texto):
|
| 83 |
+
return gr.Markdown(texto, latex_delimiters=LATEX, elem_classes="caption")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def plot(elem_id=None):
|
| 87 |
+
return gr.Plot(show_label=False, format="png", elem_id=elem_id)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def conecta(ins, fn, outs, boton, excluir=()):
|
| 91 |
+
"""Recalcula al pulsar, al soltar un deslizador o al cambiar una opción a mano."""
|
| 92 |
+
boton.click(fn, ins, outs)
|
| 93 |
+
for c in ins:
|
| 94 |
+
if any(c is x for x in excluir) or isinstance(c, gr.State):
|
| 95 |
+
continue
|
| 96 |
+
if isinstance(c, gr.Slider):
|
| 97 |
+
c.release(fn, ins, outs, trigger_mode="always_last", show_progress="minimal")
|
| 98 |
+
elif isinstance(c, (gr.Radio, gr.Dropdown, gr.Checkbox)):
|
| 99 |
+
c.input(fn, ins, outs, trigger_mode="always_last", show_progress="minimal")
|
| 100 |
+
elif isinstance(c, (gr.Textbox, gr.Number)):
|
| 101 |
+
c.submit(fn, ins, outs, show_progress="minimal")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def si_vacia(fn, n_salidas):
|
| 105 |
+
"""Ejecuta fn solo si la pestaña aún no tiene contenido."""
|
| 106 |
+
def envoltura(actual, *args):
|
| 107 |
+
if actual:
|
| 108 |
+
return [gr.update()] * n_salidas
|
| 109 |
+
return fn(*args)
|
| 110 |
+
return envoltura
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ---------------------------------------------------------------------
|
| 114 |
+
# Manejadores de visibilidad y de valores
|
| 115 |
+
# ---------------------------------------------------------------------
|
| 116 |
+
def vis_modo(modo):
|
| 117 |
+
libre = modo == "G(s) libre"
|
| 118 |
+
return gr.update(visible=not libre), gr.update(visible=libre), gr.update(visible=libre)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def vis_orden(orden):
|
| 122 |
+
o = orden[0]
|
| 123 |
+
return (gr.update(visible=o == "1"), gr.update(visible=o != "1"), gr.update(visible=o != "1"),
|
| 124 |
+
gr.update(visible=o == "3"))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def vis_entrada(e):
|
| 128 |
+
return (gr.update(visible=e != "Personalizada"), gr.update(visible=e == "Senoidal"),
|
| 129 |
+
gr.update(visible=e == "Exponencial"), gr.update(visible=e == "Personalizada"))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def vis_topologia(topo):
|
| 133 |
+
usados = BLOQUES_USADOS[topo]
|
| 134 |
+
lazo = topo in ("Lazo cerrado (realimentación)", "Lazos anidados")
|
| 135 |
+
etq_h1 = "H₁(s) (lazo interno, alrededor de G₂)" if topo == "Lazos anidados" else "H₁(s) (realimentación)"
|
| 136 |
+
return (gr.update(visible="H1" in usados, label=etq_h1), gr.update(visible="H2" in usados),
|
| 137 |
+
gr.update(visible=lazo), gr.update(visible=topo == "Paralelo"))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def cambia_forma(forma, Kp, Ki, Kd, Ti, Td):
|
| 141 |
+
isa = forma.startswith("Estándar")
|
| 142 |
+
if isa:
|
| 143 |
+
Ti = round(Kp / Ki, 4) if Ki else 0.0
|
| 144 |
+
Td = round(Kd / Kp, 4) if Kp else 0.0
|
| 145 |
+
else:
|
| 146 |
+
Ki = round(Kp / Ti, 4) if Ti else 0.0
|
| 147 |
+
Kd = round(Kp * Td, 4)
|
| 148 |
+
return (gr.update(visible=not isa, value=Ki), gr.update(visible=not isa, value=Kd),
|
| 149 |
+
gr.update(visible=isa, value=Ti), gr.update(visible=isa, value=Td))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def ejemplo_bloques(nombre):
|
| 153 |
+
return EJEMPLOS_BLOQUES[nombre]
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def rango_param1(var, K, tau, zeta, wn, zc, p3):
|
| 157 |
+
"""Rango por defecto para la animación de la pestaña 1."""
|
| 158 |
+
tabla = {"ζ (amortiguamiento)": (-0.3, 1.5), "ωn (frecuencia natural)": (0.2, 3 * wn),
|
| 159 |
+
"K (ganancia)": (-2 * abs(K) - 1, 2 * abs(K) + 1), "τ (constante de tiempo)": (0.1, 3 * tau),
|
| 160 |
+
"p (tercer polo)": (0.1, max(10.0, 3 * p3)), "z (posición del cero)": (-10.0, 10.0)}
|
| 161 |
+
a, b = tabla[var]
|
| 162 |
+
return round(a, 3), round(b, 3)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def rango_ganancia(var, forma, Kp, Ki, Kd, Ti, Td):
|
| 166 |
+
kp, ki, kd = pn.convierte_ganancias(forma, Kp, Ki, Kd, Ti, Td)
|
| 167 |
+
v = {"Kp": kp, "Ki": ki, "Kd": kd}[var]
|
| 168 |
+
return 0.0, round(max(10.0 * v, 10.0) if var == "Ki" else max(4.0 * v, 10.0), 3)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def vis_anim(modo):
|
| 172 |
+
barrido = modo == MODOS_ANIM[0]
|
| 173 |
+
return [gr.update(visible=barrido)] * 4
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def disenar_ui(planta, tipo, Mp, ts, banda, r_extra):
|
| 177 |
+
texto, ganancias, esp = pn.disenar_para_pid(planta, tipo, Mp, ts, banda, r_extra)
|
| 178 |
+
acc = gr.update(visible=True, open=True)
|
| 179 |
+
if not ganancias:
|
| 180 |
+
return [texto, acc, None] + [gr.update()] * 9
|
| 181 |
+
kp, ki, kd = ganancias
|
| 182 |
+
usar = {"P": (True, False, False), "PI": (True, True, False), "PD": (True, False, True),
|
| 183 |
+
"PID": (True, True, True)}[tipo]
|
| 184 |
+
|
| 185 |
+
def pon(v, base):
|
| 186 |
+
return gr.update(value=round(v, 4), maximum=max(base, 1.5 * abs(v)), visible=True)
|
| 187 |
+
return [texto, acc, esp, "Paralelo: Kp, Ki, Kd", pon(kp, 100), pon(ki, 100), pon(kd, 30),
|
| 188 |
+
gr.update(visible=False), gr.update(visible=False), *usar]
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def anima_ui(modo, var, vmin, vmax, nfr, fps, *ins):
|
| 192 |
+
(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, dmed, saturar, umin, umax, aw,
|
| 193 |
+
r_amp, t_fin, pert_amp, pert_t, cambio_r, r2_amp, r2_t) = ins[:23]
|
| 194 |
+
if modo == MODOS_ANIM[0]:
|
| 195 |
+
return pn.anima_pid(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, r_amp, t_fin,
|
| 196 |
+
var, vmin, vmax, nfr, fps)
|
| 197 |
+
return pn.anima_senales(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, dmed, saturar, umin, umax,
|
| 198 |
+
aw, r_amp, t_fin, pert_amp, pert_t, cambio_r, r2_amp, r2_t, fps)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
GUIA = r"""
|
| 202 |
+
### Cómo se escribe $G(s)$
|
| 203 |
+
|
| 204 |
+
Se escribe como en una calculadora, con $s$ como variable: `10/(s^2+2s+10)`, `4/(s(s+2))`, `(2s+1)/(s+1)^3`,
|
| 205 |
+
`0,5/(2s+1)`. Se admite la multiplicación implícita (`2s`, `s(s+1)`) y la coma decimal. No se admiten retardos
|
| 206 |
+
$e^{-Ls}$. En la pestaña 1, la entrada personalizada $r(t)$ admite `exp`, `sen` (o `sin`), `cos`, `sqrt` y `pi`:
|
| 207 |
+
por ejemplo `1 - exp(-2t)` o `2 + 0,5t`. Cada control y cada figura tiene un **?** con su explicación.
|
| 208 |
+
|
| 209 |
+
### Qué hace cada pestaña
|
| 210 |
+
|
| 211 |
+
| Pestaña | Para qué sirve |
|
| 212 |
+
|:--|:--|
|
| 213 |
+
| 1 · Respuesta temporal | Dado un sistema y una entrada, deriva **todo lo demás**: polos, $R(s)$, $Y(s)$, fracciones simples, $y(t)$, valores inicial y final, y las especificaciones $t_d,t_r,t_p,M_p,t_s$, acotadas sobre la curva una a una y comparadas con las fórmulas. Explica por qué es estable y cuál es el polo dominante, dibuja el camino de Laplace y anima el efecto de variar un parámetro. |
|
| 214 |
+
| 2 · Diagramas de bloques | Resuelve serie, paralelo, realimentación y lazos anidados por ecuaciones de señales; da el lazo abierto $L(s)$, el lazo cerrado y avisa de las cancelaciones polo–cero peligrosas. |
|
| 215 |
+
| 3 · Controlador PID | Diagrama del lazo; simulación con las tres acciones por separado, en forma paralela o estándar, con filtro derivativo, derivada sobre la medida, saturación, anti-windup, cambios de consigna y perturbación; diseño por asignación de polos; y animaciones del paso de estable a inestable. |
|
| 216 |
+
|
| 217 |
+
### Las fórmulas de segundo orden (tabla central del tema)
|
| 218 |
+
|
| 219 |
+
| Magnitud | Fórmula | Fórmula inversa |
|
| 220 |
+
|:--|:--:|:--:|
|
| 221 |
+
| Polos | $s_{1,2}=-\zeta\omega_n\pm j\omega_n\sqrt{1-\zeta^2}$ | — |
|
| 222 |
+
| Tiempo de subida | $t_r=\dfrac{\pi-\beta}{\omega_d}$, $\beta=\arccos\zeta$ | — |
|
| 223 |
+
| Tiempo de pico | $t_p=\dfrac{\pi}{\omega_d}$ | $\omega_d=\dfrac{\pi}{t_p}$ |
|
| 224 |
+
| Sobreoscilación | $M_p=e^{-\pi\zeta/\sqrt{1-\zeta^2}}$ | $\zeta=\dfrac{-\ln M_p}{\sqrt{\pi^2+\ln^2M_p}}$ |
|
| 225 |
+
| Establecimiento (2 %) | $t_s=\dfrac{4}{\zeta\omega_n}$ | $\zeta\omega_n=\dfrac{4}{t_s}$ |
|
| 226 |
+
| Establecimiento (5 %) | $t_s=\dfrac{3}{\zeta\omega_n}$ | $\zeta\omega_n=\dfrac{3}{t_s}$ |
|
| 227 |
+
|
| 228 |
+
### El PID
|
| 229 |
+
|
| 230 |
+
$$C(s)=K_p+\frac{K_i}{s}+K_d\,s=K_p\left(1+\frac{1}{T_is}+T_ds\right),\qquad T_i=\frac{K_p}{K_i},\quad T_d=\frac{K_d}{K_p}.$$
|
| 231 |
+
|
| 232 |
+
| Al aumentar | $t_r$ | $M_p$ | $t_s$ | Error permanente |
|
| 233 |
+
|:--|:--:|:--:|:--:|:--:|
|
| 234 |
+
| $K_p$ | disminuye | aumenta | cambia poco | disminuye |
|
| 235 |
+
| $K_i$ | disminuye | aumenta | aumenta | **se anula** |
|
| 236 |
+
| $K_d$ | cambia poco | disminuye | disminuye | no cambia |
|
| 237 |
+
|
| 238 |
+
<div class="aviso">
|
| 239 |
+
|
| 240 |
+
**La tabla es orientativa, no una ley.** Cerca del límite de estabilidad, subir $K_p$ o $K_i$ empeora todo a la vez.
|
| 241 |
+
Por eso el método fiable no es tantear con la tabla, sino asignar los polos. La animación de la pestaña 3 muestra
|
| 242 |
+
exactamente dónde está ese límite.
|
| 243 |
+
|
| 244 |
+
</div>
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
CABECERA = """
|
| 248 |
+
<div class="portada">
|
| 249 |
+
<div class="serie">Técnicas de optimización y control · Tema 3</div>
|
| 250 |
+
<h1>Simulador de control clásico</h1>
|
| 251 |
+
<div class="subtitulo">La transformada de Laplace, polos y ceros, diagramas de bloques y el controlador PID</div>
|
| 252 |
+
<div class="autor">Acompaña a los apuntes de teoría del Tema 3 · Dr. Jacinto Velasco Rebolledo · Universidad Alfonso X el Sabio</div>
|
| 253 |
+
</div>
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
with gr.Blocks(theme=TEMA, css=CSS, js=script_ayuda(), title="Simulador de control clásico · Tema 3") as demo:
|
| 257 |
+
gr.HTML(CABECERA)
|
| 258 |
+
with gr.Tabs() as tabs:
|
| 259 |
+
# =============================================================
|
| 260 |
+
with gr.Tab("1 · Respuesta temporal", id="resp"):
|
| 261 |
+
md("Elija un sistema y una entrada: el simulador obtiene $R(s)$, $Y(s)=G(s)R(s)$, la descompone en fracciones "
|
| 262 |
+
"simples, vuelve al tiempo y mide sobre la curva lo que predicen las fórmulas. Al soltar un deslizador se "
|
| 263 |
+
"recalcula todo. Pase el ratón por los **?** para ver qué es cada cosa.", elem_classes="nota-controles")
|
| 264 |
+
with gr.Row():
|
| 265 |
+
with gr.Column(scale=1, min_width=290, elem_classes="panel-controles"):
|
| 266 |
+
modo = gr.Radio(["Parámetros", "G(s) libre"], value="Parámetros", label="Cómo se define el sistema",
|
| 267 |
+
elem_id="ay-modo")
|
| 268 |
+
with gr.Group() as grp_par:
|
| 269 |
+
orden = gr.Radio(ORDENES, value=ORDENES[1], label="Modelo", elem_id="ay-orden")
|
| 270 |
+
K = gr.Slider(-10, 10, value=1, step=0.1, label="Ganancia estática K", elem_id="ay-K")
|
| 271 |
+
tau = gr.Slider(0.05, 10, value=1, step=0.05, label="Constante de tiempo τ (s)", visible=False,
|
| 272 |
+
elem_id="ay-tau")
|
| 273 |
+
zeta = gr.Slider(-0.5, 2, value=0.3, step=0.01, label="Amortiguamiento ζ", elem_id="ay-zeta")
|
| 274 |
+
wn = gr.Slider(0.1, 20, value=2, step=0.1, label="Frecuencia natural ωn (rad/s)", elem_id="ay-wn")
|
| 275 |
+
p3 = gr.Slider(0.1, 50, value=4, step=0.1, label="Tercer polo en s = −p", visible=False,
|
| 276 |
+
elem_id="ay-p3")
|
| 277 |
+
cero = gr.Checkbox(False, label="Añadir un cero", elem_id="ay-cero")
|
| 278 |
+
zc = gr.Slider(-20, 20, value=-3, step=0.1, label="Posición del cero, s = z (z > 0: fase no mínima)",
|
| 279 |
+
visible=False, elem_id="ay-zc")
|
| 280 |
+
g_txt = gr.Textbox("(s+3)/((s+1)*(s+2))", label="G(s)", visible=False,
|
| 281 |
+
info="Ej.: 10/(s^2+2s+10) · 4/(s(s+2)) · (2s+1)/(s+1)^3", elem_id="ay-gtxt")
|
| 282 |
+
ej_G = gr.Dropdown(list(EJEMPLOS_G), value=None, label="Ejemplos de los apuntes", visible=False,
|
| 283 |
+
elem_id="ay-ejG")
|
| 284 |
+
entrada = gr.Dropdown(ENTRADAS, value="Escalón", label="Entrada r(t)", elem_id="ay-entrada")
|
| 285 |
+
A = gr.Number(1, label="Amplitud A", elem_id="ay-A")
|
| 286 |
+
w_e = gr.Slider(0.1, 20, value=1, step=0.1, label="Frecuencia ω de la senoidal (rad/s)", visible=False,
|
| 287 |
+
elem_id="ay-we")
|
| 288 |
+
a_e = gr.Slider(-2, 10, value=1, step=0.1, label="Exponente a en A·e^(−at)", visible=False,
|
| 289 |
+
elem_id="ay-ae")
|
| 290 |
+
r_txt = gr.Textbox("1 - exp(-2t)", label="r(t)", visible=False,
|
| 291 |
+
info="Función de t con exp, sen, cos, sqrt, pi", elem_id="ay-rtxt")
|
| 292 |
+
t_max = gr.Number(0, label="Horizonte de simulación (s); 0 = automático", elem_id="ay-tmax")
|
| 293 |
+
btn1 = gr.Button("Calcular", variant="primary")
|
| 294 |
+
with gr.Column(scale=3):
|
| 295 |
+
p_e = plot("ay-fig-esp")
|
| 296 |
+
cap("**Figura 1.1.** La respuesta a escalón y las cinco magnitudes que la definen, acotadas sobre la curva "
|
| 297 |
+
"con su valor: retardo $t_d$, subida $t_r$, pico $t_p$, sobreoscilación $M_p$ y establecimiento $t_s$. "
|
| 298 |
+
"A la derecha, lo medido frente a lo que dan las fórmulas (en azul).")
|
| 299 |
+
p_c = plot("ay-fig-cada")
|
| 300 |
+
cap("**Figura 1.2.** Cada magnitud por separado, sobre la misma curva: (a) cuándo llega al 50 %, (b) cuánto "
|
| 301 |
+
"tarda en subir, (c) cuándo es el pico y cuánto se pasa, (d) desde cuándo ya no sale de la banda del 2 %.")
|
| 302 |
+
p_s = plot("ay-fig-s")
|
| 303 |
+
cap("**Figura 1.3.** El plano $s$: polos (×) y ceros (○). La parte real de un polo mide la rapidez de su "
|
| 304 |
+
"modo; la imaginaria, la frecuencia de oscilación. Rayos de $\\zeta$ constante en gris.")
|
| 305 |
+
p_t = plot("ay-fig-t")
|
| 306 |
+
cap("**Figura 1.4.** La respuesta a la entrada elegida: $r(t)$ en gris y $y(t)$ en negro.")
|
| 307 |
+
p_l = plot("ay-fig-camino")
|
| 308 |
+
cap("**Figura 1.5.** El camino que sigue el desarrollo de abajo: se pasa la entrada al dominio de $s$, se "
|
| 309 |
+
"multiplica por $G(s)$, se descompone $Y(s)$ en fracciones simples y cada una se vuelve al tiempo "
|
| 310 |
+
"con la tabla.")
|
| 311 |
+
p_m = plot("ay-fig-m")
|
| 312 |
+
cap("**Figura 1.6.** Cada polo aporta un modo (un término de $y(t)$); la curva negra es su suma. Los ceros "
|
| 313 |
+
"no crean modos: cambian su peso.")
|
| 314 |
+
p_3 = plot("ay-fig-3d")
|
| 315 |
+
cap("**Figura 1.7.** La transformada de Laplace vista como superficie: $\\log_{10}|G(s)|$ sobre el plano "
|
| 316 |
+
"$s$. Los polos son picos y los ceros, pozos; en rojo, el corte por el eje imaginario.")
|
| 317 |
+
with gr.Accordion("Animación: variar un parámetro dentro de su rango", open=False):
|
| 318 |
+
with gr.Row():
|
| 319 |
+
an1_var = gr.Dropdown(list(pn.PARAMS_SISTEMA), value="ζ (amortiguamiento)",
|
| 320 |
+
label="Parámetro", elem_id="ay-an1-var", min_width=180)
|
| 321 |
+
an1_min = gr.Number(-0.3, label="desde", elem_id="ay-an1-min", min_width=90)
|
| 322 |
+
an1_max = gr.Number(1.5, label="hasta", elem_id="ay-an1-max", min_width=90)
|
| 323 |
+
with gr.Row():
|
| 324 |
+
an1_n = gr.Slider(8, 60, value=30, step=1, label="Fotogramas", elem_id="ay-an1-n")
|
| 325 |
+
an1_fps = gr.Slider(2, 20, value=8, step=1, label="Velocidad (fotogramas/s)",
|
| 326 |
+
elem_id="ay-an1-fps")
|
| 327 |
+
btn_an1 = gr.Button("Generar la animación", variant="primary")
|
| 328 |
+
gif1 = gr.Image(type="filepath", show_label=False, interactive=False, elem_id="ay-an1-gif")
|
| 329 |
+
an1_txt = md()
|
| 330 |
+
out1 = md(elem_classes="desarrollo")
|
| 331 |
+
|
| 332 |
+
modo.change(vis_modo, modo, [grp_par, g_txt, ej_G])
|
| 333 |
+
orden.change(vis_orden, orden, [tau, zeta, wn, p3])
|
| 334 |
+
cero.change(lambda c: gr.update(visible=c), cero, zc)
|
| 335 |
+
entrada.change(vis_entrada, entrada, [A, w_e, a_e, r_txt])
|
| 336 |
+
ins1 = [modo, orden, K, tau, zeta, wn, cero, zc, p3, g_txt, entrada, A, w_e, a_e, r_txt, t_max]
|
| 337 |
+
outs1 = [out1, p_e, p_c, p_s, p_t, p_l, p_m, p_3]
|
| 338 |
+
ej_G.input(lambda k: EJEMPLOS_G.get(k, gr.update()), ej_G, g_txt).then(pn.analizar, ins1, outs1)
|
| 339 |
+
conecta(ins1, pn.analizar, outs1, btn1)
|
| 340 |
+
an1_var.input(rango_param1, [an1_var, K, tau, zeta, wn, zc, p3], [an1_min, an1_max])
|
| 341 |
+
btn_an1.click(pn.anima_sistema, ins1 + [an1_var, an1_min, an1_max, an1_n, an1_fps], [gif1, an1_txt])
|
| 342 |
+
|
| 343 |
+
# =============================================================
|
| 344 |
+
with gr.Tab("2 · Diagramas de bloques", id="bloques") as tab2:
|
| 345 |
+
md("Lazo abierto y lazo cerrado. El diagrama se resuelve por el método infalible de los apuntes: nombrar cada señal, "
|
| 346 |
+
"escribir una ecuación por bloque y por sumador, y eliminar.", elem_classes="nota-controles")
|
| 347 |
+
with gr.Row():
|
| 348 |
+
with gr.Column(scale=1, min_width=290, elem_classes="panel-controles"):
|
| 349 |
+
ej_b = gr.Dropdown(list(EJEMPLOS_BLOQUES), value=None, label="Ejemplos", elem_id="ay-ejb")
|
| 350 |
+
topo = gr.Dropdown(TOPOLOGIAS, value=TOPOLOGIAS[0], label="Configuración", elem_id="ay-topo")
|
| 351 |
+
g1 = gr.Textbox("4", label="G₁(s) (controlador o primer bloque)", elem_id="ay-g1")
|
| 352 |
+
g2 = gr.Textbox("1/(s*(s+1))", label="G₂(s) (planta)", elem_id="ay-g2")
|
| 353 |
+
h1 = gr.Textbox("1", label="H₁(s) (realimentación)", elem_id="ay-h1")
|
| 354 |
+
h2 = gr.Textbox("1", label="H₂(s) (lazo externo)", visible=False, elem_id="ay-h2")
|
| 355 |
+
signo = gr.Radio(["Negativa (−)", "Positiva (+)"], value="Negativa (−)", label="Realimentación",
|
| 356 |
+
elem_id="ay-signo")
|
| 357 |
+
resta = gr.Radio(["G₁ + G₂", "G₁ − G₂"], value="G₁ + G₂", label="Paralelo", visible=False,
|
| 358 |
+
elem_id="ay-resta")
|
| 359 |
+
btn2 = gr.Button("Resolver", variant="primary")
|
| 360 |
+
with gr.Column(scale=3):
|
| 361 |
+
p_d = plot("ay-fig-d")
|
| 362 |
+
cap("**Figura 2.1.** Diagrama de bloques con las señales rotuladas.")
|
| 363 |
+
p_d2 = plot("ay-fig-d2")
|
| 364 |
+
cap("**Figura 2.2.** Polos del lazo cerrado (negro) y del lazo abierto $L(s)$ (gris): la realimentación "
|
| 365 |
+
"lleva los polos de los grises a los negros.")
|
| 366 |
+
p_d3 = plot("ay-fig-d3")
|
| 367 |
+
cap("**Figura 2.3.** Respuesta a escalón del sistema equivalente y, en los lazos, del camino directo "
|
| 368 |
+
"sin realimentar.")
|
| 369 |
+
out2 = md(elem_classes="desarrollo")
|
| 370 |
+
topo.change(vis_topologia, topo, [h1, h2, signo, resta])
|
| 371 |
+
ins2 = [topo, g1, g2, h1, h2, signo, resta]
|
| 372 |
+
outs2 = [out2, p_d, p_d2, p_d3]
|
| 373 |
+
ej_b.input(ejemplo_bloques, ej_b, [topo, g1, g2, h1, h2]).then(
|
| 374 |
+
vis_topologia, topo, [h1, h2, signo, resta]).then(pn.diagrama, ins2, outs2)
|
| 375 |
+
conecta(ins2, pn.diagrama, outs2, btn2)
|
| 376 |
+
|
| 377 |
+
# =============================================================
|
| 378 |
+
with gr.Tab("3 · Controlador PID", id="pid") as tab3:
|
| 379 |
+
md("El lazo completo: mueva $K_p$, $K_i$ y $K_d$ (o $K_p$, $T_i$ y $T_d$) y observe a la vez la salida, el error, "
|
| 380 |
+
"cada una de las tres acciones y cómo se mueven los polos del lazo cerrado. Debajo de los controles, el diseño "
|
| 381 |
+
"por asignación de polos; debajo de las figuras, las animaciones.", elem_classes="nota-controles")
|
| 382 |
+
espec = gr.State(None)
|
| 383 |
+
with gr.Row():
|
| 384 |
+
with gr.Column(scale=1, min_width=310, elem_classes="panel-controles"):
|
| 385 |
+
planta = gr.Textbox("1/((s+1)*(s+2))", label="Planta G(s)", elem_id="ay-planta")
|
| 386 |
+
ej_p = gr.Dropdown(list(EJEMPLOS_PLANTA), value=None, label="Plantas de ejemplo", elem_id="ay-ejp")
|
| 387 |
+
forma = gr.Radio(["Paralelo: Kp, Ki, Kd", "Estándar ISA: Kp, Ti, Td"], value="Paralelo: Kp, Ki, Kd",
|
| 388 |
+
label="Forma del PID", elem_id="ay-forma")
|
| 389 |
+
Kp = gr.Slider(0, 100, value=6, step=0.01, label="Kp (proporcional)", elem_id="ay-Kp")
|
| 390 |
+
Ki = gr.Slider(0, 100, value=4, step=0.01, label="Ki (integral)", elem_id="ay-Ki")
|
| 391 |
+
Kd = gr.Slider(0, 30, value=1, step=0.01, label="Kd (derivativa)", elem_id="ay-Kd")
|
| 392 |
+
Ti = gr.Slider(0, 50, value=1.5, step=0.01, label="Ti (s), tiempo integral; 0 = sin acción I",
|
| 393 |
+
visible=False, elem_id="ay-Ti")
|
| 394 |
+
Td = gr.Slider(0, 10, value=0.1667, step=0.001, label="Td (s), tiempo derivativo", visible=False,
|
| 395 |
+
elem_id="ay-Td")
|
| 396 |
+
with gr.Row():
|
| 397 |
+
usarP = gr.Checkbox(True, label="P", min_width=60, elem_id="ay-usarP")
|
| 398 |
+
usarI = gr.Checkbox(True, label="I", min_width=60, elem_id="ay-usarI")
|
| 399 |
+
usarD = gr.Checkbox(True, label="D", min_width=60, elem_id="ay-usarD")
|
| 400 |
+
comparar = gr.Checkbox(True, label="Comparar con P, PI y PD con las mismas ganancias",
|
| 401 |
+
elem_id="ay-comparar")
|
| 402 |
+
var_tray = gr.Radio(["Kp", "Ki", "Kd"], value="Kp", label="Trayectoria de los polos al variar",
|
| 403 |
+
elem_id="ay-vartray")
|
| 404 |
+
with gr.Accordion("Diseño por asignación de polos", open=False, elem_id="ay-acc-diseno"):
|
| 405 |
+
tipo_d = gr.Radio(["P", "PI", "PD", "PID"], value="PID", label="Controlador", elem_id="ay-d-tipo")
|
| 406 |
+
Mp_d = gr.Slider(0.5, 60, value=10, step=0.5, label="Sobreoscilación máxima Mp (%)",
|
| 407 |
+
elem_id="ay-d-Mp")
|
| 408 |
+
ts_d = gr.Slider(0.1, 30, value=2, step=0.1, label="Tiempo de establecimiento ts (s)",
|
| 409 |
+
elem_id="ay-d-ts")
|
| 410 |
+
banda_d = gr.Radio(["2 %", "5 %"], value="2 %", label="Banda de tolerancia", elem_id="ay-d-banda")
|
| 411 |
+
r_d = gr.Slider(2, 20, value=5, step=0.5, label="Polos adicionales en r · ζωn", elem_id="ay-d-r")
|
| 412 |
+
btn_dis = gr.Button("Calcular las ganancias y aplicarlas", variant="primary")
|
| 413 |
+
btn_quitar = gr.Button("Quitar las especificaciones")
|
| 414 |
+
with gr.Accordion("El PID real: tres problemas prácticos y su solución", open=False,
|
| 415 |
+
elem_id="ay-acc-real"):
|
| 416 |
+
md("El PID de la fórmula no se usa tal cual en una máquina. Aquí se activan las tres correcciones "
|
| 417 |
+
"que lleva todo PID comercial; la **figura 3.3** compara el resultado con el PID ideal.",
|
| 418 |
+
elem_classes="nota-controles")
|
| 419 |
+
md("**① Ruido.** La derivada mide lo deprisa que cambia la señal, y el ruido del sensor cambia muy "
|
| 420 |
+
"deprisa: la acción D lo convierte en golpes. *Solución:* suavizarla con un filtro.",
|
| 421 |
+
elem_classes="nota-controles")
|
| 422 |
+
N = gr.Slider(0, 30, value=0, step=1, label="Filtro de la derivada N (0 = sin filtro · típico 8–20)",
|
| 423 |
+
elem_id="ay-N")
|
| 424 |
+
md("**② Golpe.** Si la consigna salta de repente, el error también salta y su derivada es un pico "
|
| 425 |
+
"instantáneo en el actuador. *Solución:* derivar la medida, que nunca salta.",
|
| 426 |
+
elem_classes="nota-controles")
|
| 427 |
+
dmed = gr.Checkbox(False, label="Derivar la medida y (no el error)", elem_id="ay-dmed")
|
| 428 |
+
md("**③ Límites y windup.** El actuador no da más de lo que tiene (una válvula no pasa del 100 %). "
|
| 429 |
+
"Mientras está al tope, la parte integral se sigue «cargando» y después la salida se pasa mucho. "
|
| 430 |
+
"*Solución:* anti-windup.", elem_classes="nota-controles")
|
| 431 |
+
saturar = gr.Checkbox(False, label="El actuador tiene límites", elem_id="ay-saturar")
|
| 432 |
+
with gr.Row():
|
| 433 |
+
umin = gr.Number(-2.5, label="u mínima", min_width=80, elem_id="ay-umin")
|
| 434 |
+
umax = gr.Number(2.5, label="u máxima", min_width=80, elem_id="ay-umax")
|
| 435 |
+
# el texto visible puede cambiar; el valor interno es corto y estable
|
| 436 |
+
aw = gr.Radio([("Ninguno: el integrador se carga", "Ninguno"),
|
| 437 |
+
("Congelar el integrador mientras satura", "Congelar"),
|
| 438 |
+
("Descargar el integrador (back-calculation)", "Descargar")],
|
| 439 |
+
value="Ninguno", label="Anti-windup", elem_id="ay-aw")
|
| 440 |
+
with gr.Accordion("Ensayo: consigna y perturbación", open=False, elem_id="ay-acc-ensayo"):
|
| 441 |
+
r_amp = gr.Number(1, label="Escalón de consigna r en t = 0", elem_id="ay-ramp")
|
| 442 |
+
cambio_r = gr.Checkbox(False, label="Cambiar la consigna durante el ensayo", elem_id="ay-cambio-r")
|
| 443 |
+
with gr.Row():
|
| 444 |
+
r2_amp = gr.Number(1.5, label="nueva consigna", min_width=80, elem_id="ay-r2")
|
| 445 |
+
r2_t = gr.Number(8, label="en t (s)", min_width=80, elem_id="ay-r2t")
|
| 446 |
+
with gr.Row():
|
| 447 |
+
pert_amp = gr.Number(0, label="perturbación d", min_width=80, elem_id="ay-pert-amp")
|
| 448 |
+
pert_t = gr.Number(6, label="en t (s)", min_width=80, elem_id="ay-pert-t")
|
| 449 |
+
t_fin = gr.Number(0, label="Duración (s); 0 = automática", elem_id="ay-tfin")
|
| 450 |
+
btn3 = gr.Button("Simular", variant="primary")
|
| 451 |
+
with gr.Column(scale=3):
|
| 452 |
+
p_pid0 = plot("ay-fig-pid-diag")
|
| 453 |
+
cap("**Figura 3.1.** El lazo de control con el PID en estructura paralela, con los valores actuales: las tres "
|
| 454 |
+
"acciones se calculan sobre el mismo error y se suman para formar $u(t)$.")
|
| 455 |
+
p_pid = plot("ay-fig-pid")
|
| 456 |
+
cap("**Figura 3.2.** (a) Salida y consigna. (b) Error. (c) Acción de control $u=P+I+D$ y sus tres "
|
| 457 |
+
"componentes por separado.")
|
| 458 |
+
p_real = plot("ay-fig-real")
|
| 459 |
+
cap("**Figura 3.3.** El PID ideal de la fórmula (azul) frente al PID real que usted ha configurado "
|
| 460 |
+
"(negro): (a) salida, (b) acción de control —con límites, también la parte integral, donde se ve "
|
| 461 |
+
"el *windup*— y (c) lo que hace la derivada con el ruido del sensor, sin filtro (rojo) y con filtro "
|
| 462 |
+
"(negro).")
|
| 463 |
+
p_pid2 = plot("ay-fig-pid-s")
|
| 464 |
+
cap("**Figura 3.4.** Polos del lazo cerrado (negro), de la planta (gris) y su trayectoria al barrer la "
|
| 465 |
+
"ganancia elegida desde 0 hasta 2.5 veces su valor (de claro a oscuro).")
|
| 466 |
+
with gr.Accordion("Animación: de estable a inestable, y las señales en el tiempo", open=True):
|
| 467 |
+
an_modo = gr.Radio(MODOS_ANIM, value=MODOS_ANIM[0], label="Qué animar", elem_id="ay-an-modo")
|
| 468 |
+
with gr.Row():
|
| 469 |
+
an_var = gr.Dropdown(["Kp", "Ki", "Kd"], value="Ki", label="Ganancia", elem_id="ay-an-var",
|
| 470 |
+
min_width=110)
|
| 471 |
+
an_min = gr.Number(0, label="desde", elem_id="ay-an-min", min_width=90)
|
| 472 |
+
an_max = gr.Number(60, label="hasta", elem_id="ay-an-max", min_width=90)
|
| 473 |
+
an_n = gr.Slider(8, 60, value=30, step=1, label="Fotogramas", elem_id="ay-an-n", min_width=160)
|
| 474 |
+
with gr.Row():
|
| 475 |
+
an_fps = gr.Slider(2, 20, value=8, step=1, label="Velocidad (fotogramas/s)", elem_id="ay-an-fps")
|
| 476 |
+
btn_an = gr.Button("Generar la animación", variant="primary")
|
| 477 |
+
gif = gr.Image(type="filepath", show_label=False, interactive=False, elem_id="ay-an-gif")
|
| 478 |
+
an_txt = md()
|
| 479 |
+
out3 = md(elem_classes="desarrollo")
|
| 480 |
+
with gr.Accordion("Desarrollo del diseño por asignación de polos", open=True, visible=False) as acc_dis:
|
| 481 |
+
out_dis = md(elem_classes="desarrollo")
|
| 482 |
+
|
| 483 |
+
ins3 = [planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, dmed, saturar, umin, umax, aw,
|
| 484 |
+
r_amp, t_fin, pert_amp, pert_t, cambio_r, r2_amp, r2_t, comparar, var_tray, espec]
|
| 485 |
+
outs3 = [out3, p_pid0, p_pid, p_real, p_pid2]
|
| 486 |
+
forma.input(cambia_forma, [forma, Kp, Ki, Kd, Ti, Td], [Ki, Kd, Ti, Td]).then(pn.simular_pid, ins3, outs3)
|
| 487 |
+
ej_p.input(lambda k: EJEMPLOS_PLANTA.get(k, gr.update()), ej_p, planta).then(pn.simular_pid, ins3, outs3)
|
| 488 |
+
conecta(ins3, pn.simular_pid, outs3, btn3, excluir=(forma,))
|
| 489 |
+
btn_dis.click(disenar_ui, [planta, tipo_d, Mp_d, ts_d, banda_d, r_d],
|
| 490 |
+
[out_dis, acc_dis, espec, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD]
|
| 491 |
+
).then(pn.simular_pid, ins3, outs3)
|
| 492 |
+
btn_quitar.click(lambda: (None, gr.update(visible=False)), None, [espec, acc_dis]).then(
|
| 493 |
+
pn.simular_pid, ins3, outs3)
|
| 494 |
+
an_modo.change(vis_anim, an_modo, [an_var, an_min, an_max, an_n])
|
| 495 |
+
an_var.input(rango_ganancia, [an_var, forma, Kp, Ki, Kd, Ti, Td], [an_min, an_max])
|
| 496 |
+
btn_an.click(anima_ui, [an_modo, an_var, an_min, an_max, an_n, an_fps] + ins3[:23], [gif, an_txt])
|
| 497 |
+
|
| 498 |
+
# =============================================================
|
| 499 |
+
with gr.Tab("Guía rápida", id="guia"):
|
| 500 |
+
md(GUIA, elem_classes="desarrollo")
|
| 501 |
+
|
| 502 |
+
# al abrir la página solo se calcula la primera pestaña; cada una de las
|
| 503 |
+
# demás se calcula la primera vez que se visita (el Space tiene poca CPU)
|
| 504 |
+
demo.load(pn.analizar, ins1, outs1)
|
| 505 |
+
tab2.select(si_vacia(pn.diagrama, len(outs2)), [out2] + ins2, outs2)
|
| 506 |
+
tab3.select(si_vacia(pn.simular_pid, len(outs3)), [out3] + ins3, outs3)
|
| 507 |
+
|
| 508 |
+
demo.queue(default_concurrency_limit=4)
|
| 509 |
+
|
| 510 |
+
if __name__ == "__main__":
|
| 511 |
+
demo.launch()
|
ayuda.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Textos de ayuda «?» de cada control y figura, y el script que los coloca.
|
| 2 |
+
|
| 3 |
+
Cada componente de la interfaz lleva un elem_id; el script busca esos ids,
|
| 4 |
+
añade un «?» junto a su etiqueta (o en la esquina, en las figuras) y muestra
|
| 5 |
+
el texto en un globo al pasar el ratón o al tocarlo.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
AYUDA = {
|
| 11 |
+
# ---------------- pestaña 1 ----------------
|
| 12 |
+
"ay-modo": "Elija cómo se define el sistema: con los parámetros de un modelo de 1.er, 2.º o 3.er orden "
|
| 13 |
+
"(deslizadores), o escribiendo G(s) directamente.",
|
| 14 |
+
"ay-orden": "Modelo normalizado. 1.er orden: un polo en −1/τ. 2.º orden: dos polos en −ζωn ± jωn√(1−ζ²). "
|
| 15 |
+
"3.er orden: el de 2.º orden con un polo real más en −p (con la ganancia ajustada para que el valor "
|
| 16 |
+
"final no cambie).",
|
| 17 |
+
"ay-K": "Ganancia estática G(0): cuánto vale la salida en régimen permanente por cada unidad de entrada "
|
| 18 |
+
"constante. Con K < 0 la salida va en sentido contrario. No mueve los polos.",
|
| 19 |
+
"ay-tau": "Constante de tiempo: lo que tarda la respuesta a escalón en recorrer el 63.2 % del cambio. "
|
| 20 |
+
"El polo está en s = −1/τ, y ts(2 %) = 4τ. Cuanto menor τ, más rápido.",
|
| 21 |
+
"ay-zeta": "Coeficiente de amortiguamiento. ζ = 0: oscila sin parar. 0 < ζ < 1: oscila y se amortigua "
|
| 22 |
+
"(subamortiguado). ζ = 1: crítico, el más rápido sin pasarse. ζ > 1: sobreamortiguado. "
|
| 23 |
+
"Mp depende solo de ζ. Con ζ < 0 el sistema es inestable.",
|
| 24 |
+
"ay-wn": "Frecuencia natural: distancia de los polos al origen del plano s. Con ζ fijo, subir ωn hace la "
|
| 25 |
+
"respuesta más rápida sin cambiar su forma (la comprime en el tiempo).",
|
| 26 |
+
"ay-p3": "Tercer polo real en s = −p. Si p es más de unas 5 veces ζωn, su efecto es despreciable (criterio "
|
| 27 |
+
"de dominancia); si está más cerca, ralentiza la respuesta y reduce la sobreoscilación.",
|
| 28 |
+
"ay-cero": "Añade un cero. Los ceros no crean modos: cambian el peso de cada modo. Pueden aumentar la "
|
| 29 |
+
"sobreoscilación o producir respuesta inversa.",
|
| 30 |
+
"ay-zc": "Posición del cero en el plano s. Negativo (semiplano izquierdo): normal, y si está cerca de los "
|
| 31 |
+
"polos aumenta Mp. Positivo: fase no mínima, la salida arranca al revés. En 0: elimina la componente "
|
| 32 |
+
"continua.",
|
| 33 |
+
"ay-gtxt": "Escriba G(s) como cociente de polinomios en s: 10/(s^2+2s+10), 4/(s(s+2)), (2s+1)/(s+1)^3. "
|
| 34 |
+
"Admite multiplicación implícita y coma decimal. Pulse Intro para calcular.",
|
| 35 |
+
"ay-ejG": "Casos de los apuntes listos para cargar: con cero, de fase no mínima, tercer orden, polo doble, "
|
| 36 |
+
"dipolo, inestable…",
|
| 37 |
+
"ay-entrada": "Señal r(t) que se aplica al sistema. Su transformada R(s) se multiplica por G(s) para obtener "
|
| 38 |
+
"Y(s) = G(s)R(s), que luego se vuelve al tiempo por fracciones simples.",
|
| 39 |
+
"ay-A": "Amplitud de la entrada. En un sistema lineal la salida es proporcional: los tiempos no cambian.",
|
| 40 |
+
"ay-we": "Frecuencia de la entrada senoidal. En régimen permanente la salida es otra senoidal de la misma "
|
| 41 |
+
"frecuencia, con otra amplitud y otra fase.",
|
| 42 |
+
"ay-ae": "Exponente de la entrada A·e^(−at). Con a > 0 la entrada se extingue; con a < 0 crece.",
|
| 43 |
+
"ay-rtxt": "Entrada a medida en función de t: admite exp, sen, cos, sqrt y pi. Debe tener transformada "
|
| 44 |
+
"racional (combinaciones de escalones, rampas, potencias, exponenciales y senos).",
|
| 45 |
+
"ay-tmax": "Duración de la simulación en segundos. Con 0 se elige sola: alrededor de 1.5 veces el tiempo "
|
| 46 |
+
"de establecimiento.",
|
| 47 |
+
"ay-an1-var": "Parámetro que se varía en la animación. Los demás se quedan en su valor actual.",
|
| 48 |
+
"ay-an1-min": "Valor inicial del rango que recorre la animación.",
|
| 49 |
+
"ay-an1-max": "Valor final del rango que recorre la animación.",
|
| 50 |
+
"ay-an1-n": "Número de fotogramas: más fotogramas, animación más suave pero más lenta de generar.",
|
| 51 |
+
"ay-an1-fps": "Velocidad de reproducción, en fotogramas por segundo.",
|
| 52 |
+
"ay-an1-gif": "En cada fotograma: los polos en el plano s (izquierda), la respuesta temporal (derecha) y, "
|
| 53 |
+
"abajo, dónde está el parámetro dentro de su rango (verde: estable; rojo: inestable). La raya "
|
| 54 |
+
"negra marca el valor crítico en que los polos cruzan el eje imaginario.",
|
| 55 |
+
"ay-fig-s": "Plano s: polos (×) y ceros (○). La parte real de un polo mide la rapidez de su modo; la "
|
| 56 |
+
"imaginaria, su frecuencia de oscilación. A la izquierda del eje vertical, estable; a la derecha, "
|
| 57 |
+
"inestable. Las rayas grises son rectas de ζ constante.",
|
| 58 |
+
"ay-fig-t": "Respuesta y(t) a la entrada elegida, con la banda del ±2 % alrededor del valor final y las "
|
| 59 |
+
"magnitudes medidas sobre la curva: td (50 %), tp (pico), Mp (sobreoscilación) y ts "
|
| 60 |
+
"(establecimiento).",
|
| 61 |
+
"ay-fig-esp": "Las cinco magnitudes de la respuesta a escalón con su valor, acotadas como en la figura 5.1 de los "
|
| 62 |
+
"apuntes: td (llega al 50 %), tr (subida), tp (primer máximo), Mp (cuánto se pasa del valor final) y ts "
|
| 63 |
+
"(ya no sale de la banda del ±2 %). La tabla compara lo medido con lo que dan las fórmulas.",
|
| 64 |
+
"ay-fig-cada": "Cada magnitud en su propia gráfica, sobre la misma curva y con su definición: (a) td, cuándo llega "
|
| 65 |
+
"al 50 %; (b) tr, cuánto tarda en subir; (c) tp y Mp, cuándo es el pico y cuánto se pasa; (d) ts, "
|
| 66 |
+
"desde cuándo ya no sale de la banda del ±2 %. Si hay fórmula, se da su valor para comparar.",
|
| 67 |
+
"ay-fig-camino": "El método del tema en cinco pasos: ① la entrada r(t); ② su transformada R(s), con la tabla; "
|
| 68 |
+
"③ la salida en s, Y(s) = G(s)R(s); ④ Y(s) en fracciones simples; ⑤ cada fracción se vuelve al "
|
| 69 |
+
"tiempo con la tabla al revés, y su suma es y(t). Arriba, el tiempo; abajo, el dominio de s.",
|
| 70 |
+
"ay-fig-m":"Descomposición modal: cada fracción simple de Y(s) es un modo en el tiempo. La curva negra es "
|
| 71 |
+
"la suma. Se ve qué polo pesa más y cuál tarda más en extinguirse.",
|
| 72 |
+
"ay-fig-3d": "La transformada de Laplace como superficie: log|G(s)| sobre el plano s. Los polos son picos "
|
| 73 |
+
"(G → ∞) y los ceros, pozos (G = 0). En rojo, el corte por el eje imaginario: la respuesta en "
|
| 74 |
+
"frecuencia |G(jω)|.",
|
| 75 |
+
# ---------------- pestaña 2 ----------------
|
| 76 |
+
"ay-ejb": "Diagramas de ejemplo listos para cargar, incluido el ejemplo resuelto de los apuntes.",
|
| 77 |
+
"ay-topo": "Forma del diagrama. Serie: se multiplican. Paralelo: se suman. Lazo cerrado: G₁G₂/(1 ± G₁G₂H₁). "
|
| 78 |
+
"Lazos anidados: un lazo interno H₁ alrededor de G₂ dentro de otro externo H₂.",
|
| 79 |
+
"ay-g1": "Primer bloque del camino directo; en un lazo de control, el controlador C(s).",
|
| 80 |
+
"ay-g2": "Segundo bloque del camino directo; en un lazo de control, la planta G(s).",
|
| 81 |
+
"ay-h1": "Bloque de realimentación (sensor). Con H₁ = 1 la realimentación es unitaria. En lazos anidados, "
|
| 82 |
+
"es el lazo interno alrededor de G₂ (por ejemplo, un tacómetro: H₁ = k·s).",
|
| 83 |
+
"ay-h2": "Realimentación del lazo externo (normalmente unitaria, H₂ = 1).",
|
| 84 |
+
"ay-signo": "Realimentación negativa: se resta la medida (lo habitual: corrige el error). Positiva: se suma "
|
| 85 |
+
"(tiende a desestabilizar).",
|
| 86 |
+
"ay-resta": "En la asociación en paralelo, si las dos ramas se suman o se restan.",
|
| 87 |
+
"ay-fig-d": "Diagrama de bloques con las señales rotuladas, que son las que aparecen en las ecuaciones de "
|
| 88 |
+
"señales del desarrollo.",
|
| 89 |
+
"ay-fig-d2": "Polos del lazo cerrado (negro) y del lazo abierto L(s) (gris): la realimentación mueve los "
|
| 90 |
+
"polos desde los grises hasta los negros.",
|
| 91 |
+
"ay-fig-d3": "Respuesta a escalón del sistema equivalente; en los lazos, también la del camino directo sin "
|
| 92 |
+
"realimentar, para comparar.",
|
| 93 |
+
# ---------------- pestaña 3: PID ----------------
|
| 94 |
+
"ay-planta": "Función de transferencia del proceso que se controla. Debe ser propia (grado del numerador ≤ "
|
| 95 |
+
"grado del denominador).",
|
| 96 |
+
"ay-ejp": "Plantas de ejemplo, entre ellas las de las figuras de la acción integral y de la acción derivativa "
|
| 97 |
+
"de los apuntes.",
|
| 98 |
+
"ay-forma": "Paralela: C(s) = Kp + Ki/s + Kd·s. Estándar ISA (la de los fabricantes): "
|
| 99 |
+
"C(s) = Kp(1 + 1/(Ti·s) + Td·s), con Ti = Kp/Ki y Td = Kd/Kp. Al cambiar de forma se convierten "
|
| 100 |
+
"los valores.",
|
| 101 |
+
"ay-Kp": "Ganancia proporcional: acción proporcional al error actual. Al subirla, la respuesta es más rápida "
|
| 102 |
+
"y el error permanente menor, pero aumenta la sobreoscilación y, demasiado alta, el lazo se vuelve "
|
| 103 |
+
"inestable.",
|
| 104 |
+
"ay-Ki": "Ganancia integral: acción proporcional al error acumulado. Anula el error permanente ante escalón "
|
| 105 |
+
"(añade un polo en el origen), a costa de más sobreoscilación y menos estabilidad.",
|
| 106 |
+
"ay-Kd": "Ganancia derivativa: acción proporcional a la velocidad del error. Anticipa y amortigua (reduce "
|
| 107 |
+
"Mp), pero amplifica el ruido del sensor y golpea al actuador en los cambios de consigna.",
|
| 108 |
+
"ay-Ti": "Tiempo integral Ti = Kp/Ki (s): cuanto menor, más fuerte es la acción integral. 0 = sin acción "
|
| 109 |
+
"integral.",
|
| 110 |
+
"ay-Td": "Tiempo derivativo Td = Kd/Kp (s): cuanto mayor, más fuerte es la acción derivativa.",
|
| 111 |
+
"ay-usarP": "Activa o desactiva la acción proporcional sin perder su valor.",
|
| 112 |
+
"ay-usarI": "Activa o desactiva la acción integral sin perder su valor.",
|
| 113 |
+
"ay-usarD": "Activa o desactiva la acción derivativa sin perder su valor.",
|
| 114 |
+
"ay-comparar": "Dibuja también la respuesta con solo P, con PI y con PD (mismas ganancias), para ver qué "
|
| 115 |
+
"aporta cada acción.",
|
| 116 |
+
"ay-vartray": "Ganancia que se barre (de 0 a 2.5 veces su valor) para dibujar la trayectoria de los polos "
|
| 117 |
+
"en el plano s.",
|
| 118 |
+
"ay-acc-real": "Las tres correcciones que lleva todo PID comercial, explicadas una a una. Al activarlas, la "
|
| 119 |
+
"figura 3.3 compara el resultado con el PID ideal de la fórmula, y el desarrollo de abajo lo "
|
| 120 |
+
"explica con los números de la simulación.",
|
| 121 |
+
"ay-N": "Suaviza la acción derivativa para que el ruido del sensor no se convierta en golpes al actuador. "
|
| 122 |
+
"0 = sin filtro. Con N entre 8 y 20 se quita casi todo el ruido sin perder el efecto de la derivada. "
|
| 123 |
+
"(Técnicamente, Kd·s se sustituye por Kd·s / (1 + (Td/N)·s).)",
|
| 124 |
+
"ay-dmed": "En lugar de derivar el error e = r − y, se deriva solo la medida y. Como la consigna r ya no se "
|
| 125 |
+
"deriva, sus saltos no producen golpes en el actuador. La estabilidad no cambia.",
|
| 126 |
+
"ay-saturar": "Simula que el actuador tiene un mínimo y un máximo, como una válvula que va de cerrada a "
|
| 127 |
+
"abierta del todo. Si el PID pide más, el actuador se queda en el tope.",
|
| 128 |
+
"ay-umin": "Lo mínimo que puede dar el actuador.",
|
| 129 |
+
"ay-umax": "Lo máximo que puede dar el actuador. Debe ser mayor que lo que hace falta en régimen permanente, "
|
| 130 |
+
"o la salida nunca llegará a la consigna.",
|
| 131 |
+
"ay-aw": "Qué se hace con la parte integral mientras el actuador está al tope. Ninguno: sigue sumando error, "
|
| 132 |
+
"se «carga» (windup) y luego la salida se pasa mucho. Congelar: deja de integrar mientras dura la "
|
| 133 |
+
"saturación. Descargar (back-calculation): la va reduciendo según lo que el actuador no ha podido dar.",
|
| 134 |
+
"ay-fig-real": "Figura 3.3. (a) y (b): el PID ideal de la fórmula (azul) frente a su configuración (negro); si "
|
| 135 |
+
"el actuador tiene límites, también el caso contrario con respecto al anti-windup (rojo), y la "
|
| 136 |
+
"parte integral en raya y punto, que es donde se ve la «carga». (c): la acción derivativa que "
|
| 137 |
+
"produce un ruido de medida del 1 %, sin filtro (rojo) y con filtro (negro).",
|
| 138 |
+
"ay-acc-ensayo": "Condiciones del ensayo: consigna, un segundo cambio de consigna, perturbación y duración.",
|
| 139 |
+
"ay-ramp": "Valor del escalón de consigna en t = 0.",
|
| 140 |
+
"ay-tfin": "Duración de la simulación (s). 0 = automática.",
|
| 141 |
+
"ay-pert-amp": "Perturbación en escalón que se suma a la entrada de la planta (una carga, una fuga…). "
|
| 142 |
+
"Sirve para ver cómo la rechaza el controlador; la acción integral la elimina.",
|
| 143 |
+
"ay-pert-t": "Instante en que entra la perturbación.",
|
| 144 |
+
"ay-cambio-r": "Añade un segundo cambio de consigna durante la simulación.",
|
| 145 |
+
"ay-r2": "Nuevo valor de la consigna.",
|
| 146 |
+
"ay-r2t": "Instante del cambio de consigna.",
|
| 147 |
+
"ay-acc-diseno": "Asignación de polos: de las especificaciones Mp y ts se obtienen ζ y ωn, el polinomio "
|
| 148 |
+
"característico deseado y las ganancias igualando coeficientes. Al pulsar el botón se "
|
| 149 |
+
"aplican al PID y se dibuja la región admisible en el plano s.",
|
| 150 |
+
"ay-d-tipo": "Acciones del controlador que se diseña. Regla de oro: tantas especificaciones como "
|
| 151 |
+
"parámetros. P: 1 condición; PI y PD: ζ y ωn; PID: ζ, ωn y un tercer polo.",
|
| 152 |
+
"ay-d-Mp": "Sobreoscilación máxima admitida. Fija ζ = −ln Mp / √(π² + ln² Mp).",
|
| 153 |
+
"ay-d-ts": "Tiempo de establecimiento exigido. Fija ζωn = 4/ts (banda del 2 %) o 3/ts (5 %).",
|
| 154 |
+
"ay-d-banda": "Banda de tolerancia con la que se define ts: ±2 % o ±5 % del valor final.",
|
| 155 |
+
"ay-d-r": "Los polos que sobran se colocan en s = −r·ζωn. Con r ≥ 5 no interfieren con el par dominante.",
|
| 156 |
+
"ay-an-modo": "Barrido: se varía una ganancia dentro de un rango y se ve cómo se mueven los polos y cambia "
|
| 157 |
+
"la respuesta, hasta que el lazo se vuelve inestable. Señales en el tiempo: se reproduce la "
|
| 158 |
+
"simulación actual, con sus cambios de consigna y la perturbación.",
|
| 159 |
+
"ay-an-var": "Ganancia que se varía en el barrido; las otras dos se quedan en su valor actual.",
|
| 160 |
+
"ay-an-min": "Valor inicial del rango de la ganancia.",
|
| 161 |
+
"ay-an-max": "Valor final del rango de la ganancia. Si sube lo bastante, el lazo acaba siendo inestable.",
|
| 162 |
+
"ay-an-n": "Número de fotogramas del barrido.",
|
| 163 |
+
"ay-an-fps": "Velocidad de reproducción, en fotogramas por segundo.",
|
| 164 |
+
"ay-an-gif": "Animación. En el barrido: polos (izquierda), respuesta del lazo cerrado (derecha) y la barra "
|
| 165 |
+
"del rango (verde: estable, rojo: inestable; la raya negra es el valor crítico). En el modo "
|
| 166 |
+
"temporal: las señales se dibujan según avanza el tiempo.",
|
| 167 |
+
"ay-fig-pid-diag": "Lazo de control con el PID en estructura paralela: las tres acciones se calculan sobre el "
|
| 168 |
+
"mismo error y se suman. Muestra los valores actuales, las acciones apagadas, la "
|
| 169 |
+
"saturación y la perturbación si están activas.",
|
| 170 |
+
"ay-fig-pid": "(a) Salida frente a consigna. (b) Error e = r − y. (c) La acción de control u y sus tres "
|
| 171 |
+
"componentes P, I y D por separado: se ve qué hace cada una en cada instante.",
|
| 172 |
+
"ay-fig-pid-s": "Polos del lazo cerrado (negro), de la planta (gris) y su trayectoria al variar la ganancia "
|
| 173 |
+
"elegida (de claro a oscuro). Si hay un diseño activo, se sombrea la región admisible y se "
|
| 174 |
+
"marcan los polos deseados (cuadrados).",
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def script(ayuda=AYUDA):
|
| 179 |
+
"""Función JS para Blocks(js=...): modo claro y globos de ayuda."""
|
| 180 |
+
return """
|
| 181 |
+
() => {
|
| 182 |
+
const u = new URL(window.location);
|
| 183 |
+
if (u.searchParams.get('__theme') !== 'light') {
|
| 184 |
+
u.searchParams.set('__theme', 'light');
|
| 185 |
+
window.location.href = u.href;
|
| 186 |
+
return;
|
| 187 |
+
}
|
| 188 |
+
const AYUDA = %s;
|
| 189 |
+
const globo = document.createElement('div');
|
| 190 |
+
globo.className = 'globo-ayuda';
|
| 191 |
+
document.body.appendChild(globo);
|
| 192 |
+
let fijo = null;
|
| 193 |
+
const muestra = (el) => {
|
| 194 |
+
globo.textContent = el.dataset.ayuda;
|
| 195 |
+
globo.style.display = 'block';
|
| 196 |
+
const r = el.getBoundingClientRect();
|
| 197 |
+
const w = Math.min(330, window.innerWidth - 24);
|
| 198 |
+
globo.style.width = w + 'px';
|
| 199 |
+
let x = r.left - 10;
|
| 200 |
+
if (x + w > window.innerWidth - 12) x = window.innerWidth - 12 - w;
|
| 201 |
+
let y = r.bottom + 8;
|
| 202 |
+
if (y + globo.offsetHeight > window.innerHeight - 8) y = Math.max(8, r.top - globo.offsetHeight - 8);
|
| 203 |
+
globo.style.left = Math.max(12, x) + 'px';
|
| 204 |
+
globo.style.top = y + 'px';
|
| 205 |
+
};
|
| 206 |
+
const oculta = () => { if (!fijo) globo.style.display = 'none'; };
|
| 207 |
+
const pon = () => {
|
| 208 |
+
const visible = (n) => n && !n.closest('.sr-only, .hide');
|
| 209 |
+
for (const [id, txt] of Object.entries(AYUDA)) {
|
| 210 |
+
const el = document.getElementById(id);
|
| 211 |
+
if (!el) continue;
|
| 212 |
+
// etiqueta propia del componente: la del acordeón, o la primera etiqueta visible que
|
| 213 |
+
// no pertenezca a otro componente con ayuda dentro de este
|
| 214 |
+
let destino = el.querySelector(':scope > .label-wrap > span');
|
| 215 |
+
if (!destino) {
|
| 216 |
+
for (const c of el.querySelectorAll('[data-testid="block-info"], label > span')) {
|
| 217 |
+
const dueno = c.closest('[id^="ay-"]');
|
| 218 |
+
if (visible(c) && dueno === el) { destino = c; break; }
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
const ya = destino ? destino.querySelector(':scope > .ayuda') : el.querySelector(':scope > .ayuda-esquina');
|
| 222 |
+
if (ya) continue;
|
| 223 |
+
const b = document.createElement('span');
|
| 224 |
+
b.className = 'ayuda';
|
| 225 |
+
b.textContent = '?';
|
| 226 |
+
b.dataset.ayuda = txt;
|
| 227 |
+
b.tabIndex = 0;
|
| 228 |
+
b.setAttribute('role', 'button');
|
| 229 |
+
b.setAttribute('aria-label', 'Ayuda: ' + txt);
|
| 230 |
+
b.addEventListener('mouseenter', () => muestra(b));
|
| 231 |
+
b.addEventListener('mouseleave', oculta);
|
| 232 |
+
b.addEventListener('focus', () => muestra(b));
|
| 233 |
+
b.addEventListener('blur', () => { fijo = null; oculta(); });
|
| 234 |
+
b.addEventListener('click', (ev) => {
|
| 235 |
+
ev.preventDefault(); ev.stopPropagation();
|
| 236 |
+
if (fijo === b) { fijo = null; globo.style.display = 'none'; } else { fijo = b; muestra(b); }
|
| 237 |
+
});
|
| 238 |
+
if (destino) {
|
| 239 |
+
destino.appendChild(b);
|
| 240 |
+
} else {
|
| 241 |
+
b.classList.add('ayuda-esquina');
|
| 242 |
+
el.style.position = 'relative';
|
| 243 |
+
el.appendChild(b);
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
};
|
| 247 |
+
pon();
|
| 248 |
+
new MutationObserver(pon).observe(document.body, { childList: true, subtree: true });
|
| 249 |
+
window.addEventListener('scroll', () => { fijo = null; globo.style.display = 'none'; }, true);
|
| 250 |
+
document.addEventListener('click', () => { fijo = null; globo.style.display = 'none'; });
|
| 251 |
+
}
|
| 252 |
+
""" % json.dumps(ayuda, ensure_ascii=False)
|
bloques.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Álgebra de diagramas de bloques: las asociaciones de los apuntes
|
| 2 |
+
(serie, paralelo, realimentación y lazos anidados), resueltas por el
|
| 3 |
+
método infalible de las ecuaciones de señales, y su dibujo."""
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
import sympy as sp
|
| 8 |
+
from matplotlib.figure import Figure
|
| 9 |
+
from matplotlib.patches import Circle, Rectangle
|
| 10 |
+
|
| 11 |
+
from graficas import NEGRO
|
| 12 |
+
from nucleo import FT, s
|
| 13 |
+
|
| 14 |
+
G1, G2, H1, H2, X = sp.symbols("G_1 G_2 H_1 H_2 X")
|
| 15 |
+
E, E1, E2, B, B1, V, Y, Y1, Y2, U = sp.symbols("E E_1 E_2 B B_1 V Y Y_1 Y_2 U")
|
| 16 |
+
|
| 17 |
+
TOPOLOGIAS = ["Lazo cerrado (realimentación)", "Lazos anidados", "Serie", "Paralelo"]
|
| 18 |
+
BLOQUES_USADOS = {
|
| 19 |
+
"Serie": ["G1", "G2"],
|
| 20 |
+
"Paralelo": ["G1", "G2"],
|
| 21 |
+
"Lazo cerrado (realimentación)": ["G1", "G2", "H1"],
|
| 22 |
+
"Lazos anidados": ["G1", "G2", "H1", "H2"],
|
| 23 |
+
}
|
| 24 |
+
SIMB = {"G1": G1, "G2": G2, "H1": H1, "H2": H2}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def ecuaciones(topo, negativa=True, resta_paralelo=False):
|
| 28 |
+
"""Ecuaciones de señales: una por cada bloque y cada punto de suma."""
|
| 29 |
+
sg = -1 if negativa else 1
|
| 30 |
+
if topo == "Serie":
|
| 31 |
+
return [sp.Eq(V, G1 * X), sp.Eq(Y, G2 * V)], [V, Y]
|
| 32 |
+
if topo == "Paralelo":
|
| 33 |
+
return [sp.Eq(Y1, G1 * X), sp.Eq(Y2, G2 * X),
|
| 34 |
+
sp.Eq(Y, Y1 + (-1 if resta_paralelo else 1) * Y2)], [Y1, Y2, Y]
|
| 35 |
+
if topo == "Lazo cerrado (realimentación)":
|
| 36 |
+
return [sp.Eq(E, X + sg * B), sp.Eq(U, G1 * E), sp.Eq(Y, G2 * U), sp.Eq(B, H1 * Y)], [E, U, Y, B]
|
| 37 |
+
return [sp.Eq(E1, X + sg * B1), sp.Eq(B1, H2 * Y), sp.Eq(E2, G1 * E1 + sg * H1 * Y),
|
| 38 |
+
sp.Eq(Y, G2 * E2)], [E1, B1, E2, Y]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def ecuaciones_tex(topo, negativa=True, resta_paralelo=False):
|
| 42 |
+
"""Las mismas ecuaciones, escritas como en la pizarra, y el resultado."""
|
| 43 |
+
m = "-" if negativa else "+"
|
| 44 |
+
p = "+" if negativa else "-"
|
| 45 |
+
if topo == "Serie":
|
| 46 |
+
return [r"V &= G_1X", r"Y &= G_2V"], r"G_1G_2"
|
| 47 |
+
if topo == "Paralelo":
|
| 48 |
+
sg = "-" if resta_paralelo else "+"
|
| 49 |
+
return [r"Y_1 &= G_1X", r"Y_2 &= G_2X", r"Y &= Y_1 " + sg + " Y_2"], r"G_1 " + sg + " G_2"
|
| 50 |
+
if topo == "Lazo cerrado (realimentación)":
|
| 51 |
+
return ([r"E &= X " + m + " B", r"U &= G_1E", r"Y &= G_2U", r"B &= H_1Y"],
|
| 52 |
+
r"\frac{G_1G_2}{1 " + p + r" G_1G_2H_1}")
|
| 53 |
+
return ([r"E_1 &= X " + m + " B_1", r"B_1 &= H_2Y", r"E_2 &= G_1E_1 " + m + " H_1Y", r"Y &= G_2E_2"],
|
| 54 |
+
r"\frac{G_1G_2}{1 " + p + " G_2H_1 " + p + r" G_1G_2H_2}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def formula(topo, negativa=True, resta_paralelo=False):
|
| 58 |
+
ecs, inc = ecuaciones(topo, negativa, resta_paralelo)
|
| 59 |
+
sol = sp.solve(ecs, inc, dict=True)[0]
|
| 60 |
+
F = sp.factor(sp.simplify(sol[Y] / X))
|
| 61 |
+
return F, ecs
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def ganancia_lazo(topo, negativa=True):
|
| 65 |
+
"""Ganancia de lazo abierto (la que aparece en 1 + L = 0)."""
|
| 66 |
+
if topo == "Lazo cerrado (realimentación)":
|
| 67 |
+
return G1 * G2 * H1
|
| 68 |
+
if topo == "Lazos anidados":
|
| 69 |
+
return G1 * G2 * H2 / (1 + (1 if negativa else -1) * G2 * H1)
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def evalua(F, subs):
|
| 74 |
+
"""Sustituye cada bloque por N/D SIN cancelar factores.
|
| 75 |
+
|
| 76 |
+
Se multiplica numerador y denominador de la fórmula por el producto de
|
| 77 |
+
los denominadores de los bloques, de modo que el denominador resultante
|
| 78 |
+
contiene todos los modos de la interconexión. Si después numerador y
|
| 79 |
+
denominador comparten un factor, eso es una cancelación polo-cero que
|
| 80 |
+
hay que vigilar (aviso de los apuntes).
|
| 81 |
+
"""
|
| 82 |
+
A, Bd = sp.fraction(sp.together(F))
|
| 83 |
+
syms = [x for x in subs if A.has(x) or Bd.has(x)]
|
| 84 |
+
deg = {x: max(sp.degree(A, x), sp.degree(Bd, x)) for x in syms}
|
| 85 |
+
|
| 86 |
+
def sustituye(P):
|
| 87 |
+
P = sp.Poly(sp.expand(P), *syms)
|
| 88 |
+
tot = sp.Integer(0)
|
| 89 |
+
for mon, c in P.terms():
|
| 90 |
+
term = c
|
| 91 |
+
for x, k in zip(syms, mon):
|
| 92 |
+
term *= subs[x].N.as_expr() ** k * subs[x].D.as_expr() ** (deg[x] - k)
|
| 93 |
+
tot += term
|
| 94 |
+
return sp.expand(tot)
|
| 95 |
+
|
| 96 |
+
return FT(sustituye(A), sustituye(Bd))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def ganancia_estatica_diagrama(F, subs):
|
| 100 |
+
e = F.subs({x: ft.sym() for x, ft in subs.items()})
|
| 101 |
+
v = sp.limit(sp.together(e), s, 0)
|
| 102 |
+
return complex(v) if v.is_finite else float("inf")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# =====================================================================
|
| 106 |
+
# Dibujo
|
| 107 |
+
# =====================================================================
|
| 108 |
+
def _bloque(ax, x, y, txt, w=1.3, h=0.72):
|
| 109 |
+
ax.add_patch(Rectangle((x - w / 2, y - h / 2), w, h, fc="white", ec=NEGRO, lw=1.0, zorder=3))
|
| 110 |
+
ax.text(x, y, txt, ha="center", va="center", fontsize=12.5, zorder=4)
|
| 111 |
+
return x - w / 2, x + w / 2
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _suma(ax, x, y, r=0.2):
|
| 115 |
+
ax.add_patch(Circle((x, y), r, fc="white", ec=NEGRO, lw=1.0, zorder=3))
|
| 116 |
+
d = r * 0.7071
|
| 117 |
+
ax.plot([x - d, x + d], [y - d, y + d], color=NEGRO, lw=0.8, zorder=4)
|
| 118 |
+
ax.plot([x - d, x + d], [y + d, y - d], color=NEGRO, lw=0.8, zorder=4)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _flecha(ax, pts):
|
| 122 |
+
xs, ys = zip(*pts)
|
| 123 |
+
if len(pts) > 2:
|
| 124 |
+
ax.plot(xs[:-1], ys[:-1], color=NEGRO, lw=1.0, zorder=2)
|
| 125 |
+
ax.annotate("", xy=pts[-1], xytext=pts[-2],
|
| 126 |
+
arrowprops=dict(arrowstyle="-|>", color=NEGRO, lw=1.0, mutation_scale=11,
|
| 127 |
+
shrinkA=0, shrinkB=0), zorder=2)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _linea(ax, pts):
|
| 131 |
+
xs, ys = zip(*pts)
|
| 132 |
+
ax.plot(xs, ys, color=NEGRO, lw=1.0, zorder=2)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _nodo(ax, x, y):
|
| 136 |
+
ax.plot([x], [y], "o", ms=4.2, color=NEGRO, zorder=5)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _t(ax, x, y, txt, **kw):
|
| 140 |
+
kw.setdefault("fontsize", 11)
|
| 141 |
+
kw.setdefault("ha", "center")
|
| 142 |
+
kw.setdefault("va", "bottom")
|
| 143 |
+
ax.text(x, y, txt, zorder=6, **kw)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def dibuja(topo, negativa=True, resta_paralelo=False, h2_unitario=False):
|
| 147 |
+
sgn = "$-$" if negativa else "$+$"
|
| 148 |
+
if topo == "Serie":
|
| 149 |
+
fig = Figure(figsize=(7.0, 1.3))
|
| 150 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 151 |
+
a1, b1 = _bloque(ax, 2.4, 0, "$G_1(s)$")
|
| 152 |
+
a2, b2 = _bloque(ax, 4.9, 0, "$G_2(s)$")
|
| 153 |
+
_flecha(ax, [(0.2, 0), (a1, 0)])
|
| 154 |
+
_t(ax, 0.9, 0.08, "$X(s)$")
|
| 155 |
+
_flecha(ax, [(b1, 0), (a2, 0)])
|
| 156 |
+
_t(ax, (b1 + a2) / 2, 0.08, "$V(s)$")
|
| 157 |
+
_flecha(ax, [(b2, 0), (7.0, 0)])
|
| 158 |
+
_t(ax, 6.4, 0.08, "$Y(s)$")
|
| 159 |
+
ax.set_xlim(0, 7.4)
|
| 160 |
+
ax.set_ylim(-0.75, 0.75)
|
| 161 |
+
elif topo == "Paralelo":
|
| 162 |
+
fig = Figure(figsize=(7.0, 2.6))
|
| 163 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 164 |
+
_flecha(ax, [(0.2, 0), (1.4, 0)])
|
| 165 |
+
_t(ax, 0.7, 0.08, "$X(s)$")
|
| 166 |
+
_nodo(ax, 1.4, 0)
|
| 167 |
+
a1, b1 = _bloque(ax, 3.6, 0.95, "$G_1(s)$")
|
| 168 |
+
a2, b2 = _bloque(ax, 3.6, -0.95, "$G_2(s)$")
|
| 169 |
+
_flecha(ax, [(1.4, 0), (1.4, 0.95), (a1, 0.95)])
|
| 170 |
+
_flecha(ax, [(1.4, 0), (1.4, -0.95), (a2, -0.95)])
|
| 171 |
+
_suma(ax, 5.8, 0)
|
| 172 |
+
_flecha(ax, [(b1, 0.95), (5.8, 0.95), (5.8, 0.2)])
|
| 173 |
+
_flecha(ax, [(b2, -0.95), (5.8, -0.95), (5.8, -0.2)])
|
| 174 |
+
_t(ax, 5.55, 0.28, "$+$", fontsize=10)
|
| 175 |
+
_t(ax, 5.55, -0.5, "$-$" if resta_paralelo else "$+$", fontsize=10)
|
| 176 |
+
_t(ax, 4.9, 1.0, "$Y_1$", fontsize=10)
|
| 177 |
+
_t(ax, 4.9, -0.9, "$Y_2$", fontsize=10)
|
| 178 |
+
_flecha(ax, [(6.0, 0), (7.1, 0)])
|
| 179 |
+
_t(ax, 6.6, 0.08, "$Y(s)$")
|
| 180 |
+
ax.set_xlim(0, 7.4)
|
| 181 |
+
ax.set_ylim(-1.45, 1.45)
|
| 182 |
+
elif topo == "Lazo cerrado (realimentación)":
|
| 183 |
+
fig = Figure(figsize=(7.0, 2.6))
|
| 184 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 185 |
+
_flecha(ax, [(0.1, 0), (0.85, 0)])
|
| 186 |
+
_t(ax, 0.42, 0.08, "$X(s)$")
|
| 187 |
+
_suma(ax, 1.05, 0)
|
| 188 |
+
a1, b1 = _bloque(ax, 2.65, 0, "$G_1(s)$")
|
| 189 |
+
a2, b2 = _bloque(ax, 4.75, 0, "$G_2(s)$")
|
| 190 |
+
_flecha(ax, [(1.25, 0), (a1, 0)])
|
| 191 |
+
_t(ax, (1.25 + a1) / 2, 0.08, "$E$", fontsize=10)
|
| 192 |
+
_flecha(ax, [(b1, 0), (a2, 0)])
|
| 193 |
+
_t(ax, (b1 + a2) / 2, 0.08, "$U$", fontsize=10)
|
| 194 |
+
_nodo(ax, 6.15, 0)
|
| 195 |
+
_flecha(ax, [(b2, 0), (7.15, 0)])
|
| 196 |
+
_t(ax, 6.7, 0.08, "$Y(s)$")
|
| 197 |
+
ah, bh = _bloque(ax, 3.7, -1.25, "$H_1(s)$")
|
| 198 |
+
_flecha(ax, [(6.15, 0), (6.15, -1.25), (bh, -1.25)])
|
| 199 |
+
_flecha(ax, [(ah, -1.25), (1.05, -1.25), (1.05, -0.2)])
|
| 200 |
+
_t(ax, 1.9, -1.2, "$B$", fontsize=10)
|
| 201 |
+
_t(ax, 0.78, 0.18, "$+$", fontsize=10)
|
| 202 |
+
_t(ax, 1.3, -0.55, sgn, fontsize=10)
|
| 203 |
+
ax.set_xlim(0, 7.4)
|
| 204 |
+
ax.set_ylim(-1.75, 0.75)
|
| 205 |
+
else:
|
| 206 |
+
fig = Figure(figsize=(7.0, 3.1))
|
| 207 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 208 |
+
_flecha(ax, [(0.05, 0), (0.7, 0)])
|
| 209 |
+
_t(ax, 0.35, 0.08, "$X$")
|
| 210 |
+
_suma(ax, 0.9, 0)
|
| 211 |
+
a1, b1 = _bloque(ax, 2.15, 0, "$G_1(s)$", w=1.2)
|
| 212 |
+
_flecha(ax, [(1.1, 0), (a1, 0)])
|
| 213 |
+
_t(ax, (1.1 + a1) / 2, 0.08, "$E_1$", fontsize=10)
|
| 214 |
+
_suma(ax, 3.4, 0)
|
| 215 |
+
_flecha(ax, [(b1, 0), (3.2, 0)])
|
| 216 |
+
a2, b2 = _bloque(ax, 4.65, 0, "$G_2(s)$", w=1.2)
|
| 217 |
+
_flecha(ax, [(3.6, 0), (a2, 0)])
|
| 218 |
+
_t(ax, (3.6 + a2) / 2, 0.08, "$E_2$", fontsize=10)
|
| 219 |
+
_nodo(ax, 5.85, 0)
|
| 220 |
+
_nodo(ax, 6.55, 0)
|
| 221 |
+
_flecha(ax, [(b2, 0), (7.3, 0)])
|
| 222 |
+
_t(ax, 7.0, 0.08, "$Y$")
|
| 223 |
+
ah, bh = _bloque(ax, 4.65, -1.05, "$H_1(s)$", w=1.2)
|
| 224 |
+
_flecha(ax, [(5.85, 0), (5.85, -1.05), (bh, -1.05)])
|
| 225 |
+
_flecha(ax, [(ah, -1.05), (3.4, -1.05), (3.4, -0.2)])
|
| 226 |
+
if h2_unitario:
|
| 227 |
+
_linea(ax, [(6.55, 0), (6.55, -2.0), (0.9, -2.0)])
|
| 228 |
+
_flecha(ax, [(0.9, -2.0), (0.9, -0.2)])
|
| 229 |
+
else:
|
| 230 |
+
ah2, bh2 = _bloque(ax, 3.7, -2.0, "$H_2(s)$", w=1.2)
|
| 231 |
+
_flecha(ax, [(6.55, 0), (6.55, -2.0), (bh2, -2.0)])
|
| 232 |
+
_flecha(ax, [(ah2, -2.0), (0.9, -2.0), (0.9, -0.2)])
|
| 233 |
+
for xs_ in (0.9, 3.4):
|
| 234 |
+
_t(ax, xs_ - 0.28, 0.18, "$+$", fontsize=10)
|
| 235 |
+
_t(ax, xs_ + 0.25, -0.55, sgn, fontsize=10)
|
| 236 |
+
_t(ax, 4.65, -1.72, "lazo interno", fontsize=8.5, style="italic", color="#555")
|
| 237 |
+
_t(ax, 2.0, -1.95, "lazo externo", fontsize=8.5, style="italic", color="#555")
|
| 238 |
+
ax.set_xlim(0, 7.4)
|
| 239 |
+
ax.set_ylim(-2.45, 0.7)
|
| 240 |
+
ax.set_aspect("equal")
|
| 241 |
+
ax.axis("off")
|
| 242 |
+
return fig
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _tex_mpl(txt):
|
| 246 |
+
"""LaTeX de KaTeX -> mathtext de matplotlib."""
|
| 247 |
+
return txt.replace(r"\dfrac", r"\frac").replace(r"\left", "").replace(r"\right", "")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _largo(txt):
|
| 251 |
+
return len(re.sub(r"\[a-zA-Z]+|[{}^ ,]", "", txt))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def dibuja_pid(G, kp, ki, kd, usar, *, N=0.0, deriv_medida=False, saturar=False, umin=None, umax=None,
|
| 255 |
+
perturbacion=False):
|
| 256 |
+
"""Lazo de control con el PID en estructura paralela (figura 6.2 de los apuntes),
|
| 257 |
+
rotulado con los valores actuales de las ganancias y de la planta."""
|
| 258 |
+
from nucleo import poly_tex
|
| 259 |
+
fig = Figure(figsize=(7.6, 3.0))
|
| 260 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 261 |
+
gris = "#9a9a9a"
|
| 262 |
+
activo = [usar[0] and kp != 0, usar[1] and ki != 0, usar[2] and kd != 0]
|
| 263 |
+
|
| 264 |
+
def bloque_accion(y, txt, on):
|
| 265 |
+
ax.add_patch(Rectangle((2.75, y - 0.32), 2.7, 0.64, fc="white", ec=NEGRO if on else gris, lw=1.0,
|
| 266 |
+
ls="-" if on else "--", zorder=3))
|
| 267 |
+
ax.text(4.1, y, txt if on else txt + " (apagada)", ha="center", va="center", fontsize=10.5,
|
| 268 |
+
color=NEGRO if on else gris, zorder=4)
|
| 269 |
+
|
| 270 |
+
_flecha(ax, [(0.05, 0), (0.75, 0)])
|
| 271 |
+
_t(ax, 0.38, 0.08, "$r(t)$", fontsize=10)
|
| 272 |
+
_suma(ax, 0.95, 0)
|
| 273 |
+
_t(ax, 0.68, 0.17, "$+$", fontsize=9)
|
| 274 |
+
_t(ax, 1.2, -0.52, "$-$", fontsize=9)
|
| 275 |
+
_linea(ax, [(1.15, 0), (1.95, 0)])
|
| 276 |
+
_t(ax, 1.55, 0.08, "$e(t)$", fontsize=10)
|
| 277 |
+
_nodo(ax, 1.95, 0)
|
| 278 |
+
bloque_accion(1.2, f"P: $K_p={kp:.3g}$", activo[0])
|
| 279 |
+
bloque_accion(0.0, f"I: $K_i/s$, $K_i={ki:.3g}$", activo[1])
|
| 280 |
+
dtxt = (f"D: $K_d s/(1+T_f s)$, $K_d={kd:.3g}$" if (N and N > 0) else f"D: $K_d\\,s$, $K_d={kd:.3g}$")
|
| 281 |
+
bloque_accion(-1.2, dtxt, activo[2])
|
| 282 |
+
_flecha(ax, [(1.95, 0), (1.95, 1.2), (2.75, 1.2)])
|
| 283 |
+
_flecha(ax, [(1.95, 0), (2.75, 0)])
|
| 284 |
+
if deriv_medida:
|
| 285 |
+
_flecha(ax, [(2.35, -2.35), (2.35, -1.2), (2.75, -1.2)])
|
| 286 |
+
_t(ax, 2.2, -1.85, "$-y$", fontsize=9.5, ha="right")
|
| 287 |
+
else:
|
| 288 |
+
_flecha(ax, [(1.95, 0), (1.95, -1.2), (2.75, -1.2)])
|
| 289 |
+
_suma(ax, 6.05, 0)
|
| 290 |
+
_flecha(ax, [(5.45, 1.2), (6.05, 1.2), (6.05, 0.2)])
|
| 291 |
+
_flecha(ax, [(5.45, 0), (5.85, 0)])
|
| 292 |
+
_flecha(ax, [(5.45, -1.2), (6.05, -1.2), (6.05, -0.2)])
|
| 293 |
+
for (x_, y_) in ((6.25, 0.32), (5.72, 0.1), (6.25, -0.55)):
|
| 294 |
+
_t(ax, x_, y_, "$+$", fontsize=9)
|
| 295 |
+
x = 6.25
|
| 296 |
+
if saturar:
|
| 297 |
+
ax.add_patch(Rectangle((6.75, -0.32), 0.8, 0.64, fc="white", ec=NEGRO, lw=1.0, zorder=3))
|
| 298 |
+
ax.plot([6.85, 7.0, 7.3, 7.45], [-0.2, -0.2, 0.2, 0.2], color=NEGRO, lw=1.0, zorder=4)
|
| 299 |
+
_flecha(ax, [(x, 0), (6.75, 0)])
|
| 300 |
+
lim = f"[{umin:.3g}, {umax:.3g}]" if (umin is not None and umax is not None) else ""
|
| 301 |
+
_t(ax, 7.15, 0.38, "saturación " + lim, fontsize=8, style="italic", color="#555")
|
| 302 |
+
x = 7.55
|
| 303 |
+
nume = poly_tex(G.num)
|
| 304 |
+
deno = poly_tex(G.den)
|
| 305 |
+
ancho = max(1.9, 0.17 * max(_largo(nume), _largo(deno)) + 1.0)
|
| 306 |
+
if perturbacion:
|
| 307 |
+
xd = x + 1.0
|
| 308 |
+
_suma(ax, xd, 0)
|
| 309 |
+
_flecha(ax, [(x, 0), (xd - 0.2, 0)])
|
| 310 |
+
_t(ax, (x + xd - 0.2) / 2, 0.08, "$u(t)$", fontsize=10)
|
| 311 |
+
_flecha(ax, [(xd, 0.95), (xd, 0.2)])
|
| 312 |
+
_t(ax, xd, 0.98, "perturbación $d(t)$", fontsize=9.5)
|
| 313 |
+
_t(ax, xd - 0.27, 0.17, "$+$", fontsize=9)
|
| 314 |
+
_t(ax, xd + 0.27, 0.2, "$+$", fontsize=9)
|
| 315 |
+
x = xd + 0.2
|
| 316 |
+
cx = x + 0.6 + ancho / 2
|
| 317 |
+
a, bx = _bloque(ax, cx, 0, "", w=ancho, h=0.95)
|
| 318 |
+
ax.text(cx, 0.0, "$G(s)=" + _tex_mpl(G.tex()) + "$", ha="center", va="center", fontsize=11, zorder=4)
|
| 319 |
+
_t(ax, cx, 0.55, "planta", fontsize=8.5, style="italic", color="#555")
|
| 320 |
+
_flecha(ax, [(x, 0), (a, 0)])
|
| 321 |
+
if not perturbacion:
|
| 322 |
+
_t(ax, (x + a) / 2, 0.08, "$u(t)$", fontsize=10)
|
| 323 |
+
xn = bx + 0.55
|
| 324 |
+
_nodo(ax, xn, 0)
|
| 325 |
+
_flecha(ax, [(bx, 0), (xn + 0.85, 0)])
|
| 326 |
+
_t(ax, xn + 0.45, 0.08, "$y(t)$", fontsize=10)
|
| 327 |
+
_linea(ax, [(xn, 0), (xn, -2.35), (0.95, -2.35)])
|
| 328 |
+
_flecha(ax, [(0.95, -2.35), (0.95, -0.2)])
|
| 329 |
+
_t(ax, (xn + 0.95) / 2, -2.3, "realimentación de la medida", fontsize=8.5, style="italic", color="#555")
|
| 330 |
+
ax.set_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Aspecto de libro de texto (Springer): Times, filetes finos, tablas
|
| 2 |
+
con reglas superior e inferior, pies de figura en negrita. */
|
| 3 |
+
|
| 4 |
+
.gradio-container {
|
| 5 |
+
font-family: "STIX Two Text", "Times New Roman", Times, serif !important;
|
| 6 |
+
max-width: 1320px !important;
|
| 7 |
+
margin: 0 auto !important;
|
| 8 |
+
color: #1a1a1a;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
.gradio-container .prose,
|
| 12 |
+
.gradio-container .prose p,
|
| 13 |
+
.gradio-container .prose li {
|
| 14 |
+
font-size: 1.02rem;
|
| 15 |
+
line-height: 1.55;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
/* ---------- portada ---------- */
|
| 19 |
+
.portada {
|
| 20 |
+
border-top: 3px solid #1f4e79;
|
| 21 |
+
border-bottom: 0.6px solid #1a1a1a;
|
| 22 |
+
padding: 18px 4px 14px 4px;
|
| 23 |
+
margin-bottom: 6px;
|
| 24 |
+
}
|
| 25 |
+
.portada .serie {
|
| 26 |
+
font-size: 0.86rem;
|
| 27 |
+
letter-spacing: 0.08em;
|
| 28 |
+
text-transform: uppercase;
|
| 29 |
+
color: #1f4e79;
|
| 30 |
+
}
|
| 31 |
+
.portada h1 {
|
| 32 |
+
font-size: 2.05rem;
|
| 33 |
+
font-weight: 700;
|
| 34 |
+
margin: 4px 0 2px 0;
|
| 35 |
+
line-height: 1.15;
|
| 36 |
+
}
|
| 37 |
+
.portada .subtitulo {
|
| 38 |
+
font-size: 1.12rem;
|
| 39 |
+
font-style: italic;
|
| 40 |
+
color: #333;
|
| 41 |
+
}
|
| 42 |
+
.portada .autor {
|
| 43 |
+
font-size: 0.9rem;
|
| 44 |
+
color: #555;
|
| 45 |
+
margin-top: 6px;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
/* ---------- títulos del desarrollo ---------- */
|
| 49 |
+
.desarrollo h3 {
|
| 50 |
+
font-size: 1.16rem;
|
| 51 |
+
font-weight: 700;
|
| 52 |
+
margin-top: 1.3em;
|
| 53 |
+
padding-bottom: 2px;
|
| 54 |
+
border-bottom: 0.6px solid #bdbdbd;
|
| 55 |
+
color: #1a1a1a;
|
| 56 |
+
}
|
| 57 |
+
.desarrollo h4 {
|
| 58 |
+
font-size: 1.1rem;
|
| 59 |
+
font-weight: 700;
|
| 60 |
+
color: #1f4e79;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
/* ---------- tablas tipo booktabs ---------- */
|
| 64 |
+
.gradio-container .prose table {
|
| 65 |
+
border-collapse: collapse;
|
| 66 |
+
border-top: 1.4px solid #1a1a1a;
|
| 67 |
+
border-bottom: 1.4px solid #1a1a1a;
|
| 68 |
+
margin: 0.8em 0;
|
| 69 |
+
font-size: 0.96rem;
|
| 70 |
+
}
|
| 71 |
+
.gradio-container .prose thead th {
|
| 72 |
+
border-bottom: 0.7px solid #1a1a1a;
|
| 73 |
+
font-weight: 700;
|
| 74 |
+
background: transparent;
|
| 75 |
+
}
|
| 76 |
+
.gradio-container .prose td,
|
| 77 |
+
.gradio-container .prose th {
|
| 78 |
+
border-left: none !important;
|
| 79 |
+
border-right: none !important;
|
| 80 |
+
border-top: none;
|
| 81 |
+
padding: 4px 12px;
|
| 82 |
+
}
|
| 83 |
+
.gradio-container .prose tbody tr {
|
| 84 |
+
border-bottom: none;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
/* ---------- cajas de los apuntes ---------- */
|
| 88 |
+
.clave {
|
| 89 |
+
background: #f1f1ee;
|
| 90 |
+
border-left: 3px solid #1f4e79;
|
| 91 |
+
padding: 0.35em 1em;
|
| 92 |
+
margin: 0.9em 0;
|
| 93 |
+
}
|
| 94 |
+
.aviso {
|
| 95 |
+
background: #fbf4f4;
|
| 96 |
+
border-left: 3px solid #a4262c;
|
| 97 |
+
padding: 0.35em 1em;
|
| 98 |
+
margin: 0.9em 0;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
/* ---------- pies de figura ---------- */
|
| 102 |
+
.caption,
|
| 103 |
+
.caption p {
|
| 104 |
+
font-size: 0.9rem !important;
|
| 105 |
+
color: #333;
|
| 106 |
+
line-height: 1.35 !important;
|
| 107 |
+
margin-top: -4px;
|
| 108 |
+
}
|
| 109 |
+
.caption strong {
|
| 110 |
+
font-weight: 700;
|
| 111 |
+
color: #1a1a1a;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
/* ---------- KaTeX en el tamaño del texto ---------- */
|
| 115 |
+
.gradio-container .katex {
|
| 116 |
+
font-size: 1.06em;
|
| 117 |
+
}
|
| 118 |
+
.gradio-container .katex-display {
|
| 119 |
+
margin: 0.7em 0;
|
| 120 |
+
overflow-x: auto;
|
| 121 |
+
overflow-y: hidden;
|
| 122 |
+
padding: 2px 0;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/* ---------- controles ---------- */
|
| 126 |
+
.panel-controles {
|
| 127 |
+
border-right: 0.6px solid #d0d0d0;
|
| 128 |
+
padding-right: 10px !important;
|
| 129 |
+
}
|
| 130 |
+
.nota-controles,
|
| 131 |
+
.nota-controles p {
|
| 132 |
+
font-size: 0.88rem !important;
|
| 133 |
+
color: #555;
|
| 134 |
+
}
|
| 135 |
+
footer {
|
| 136 |
+
font-family: "STIX Two Text", "Times New Roman", serif;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
@media (max-width: 760px) {
|
| 140 |
+
.panel-controles {
|
| 141 |
+
border-right: none;
|
| 142 |
+
padding-right: 0 !important;
|
| 143 |
+
}
|
| 144 |
+
.portada h1 {
|
| 145 |
+
font-size: 1.6rem;
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/* ---------- ayuda «?» ---------- */
|
| 150 |
+
.ayuda {
|
| 151 |
+
display: inline-flex;
|
| 152 |
+
align-items: center;
|
| 153 |
+
justify-content: center;
|
| 154 |
+
width: 16px;
|
| 155 |
+
height: 16px;
|
| 156 |
+
margin-left: 6px;
|
| 157 |
+
border: 1px solid #1f4e79;
|
| 158 |
+
border-radius: 50%;
|
| 159 |
+
font: 600 11px/1 "STIX Two Text", "Times New Roman", serif;
|
| 160 |
+
color: #1f4e79;
|
| 161 |
+
background: #ffffff;
|
| 162 |
+
cursor: help;
|
| 163 |
+
vertical-align: middle;
|
| 164 |
+
user-select: none;
|
| 165 |
+
}
|
| 166 |
+
.ayuda:hover,
|
| 167 |
+
.ayuda:focus {
|
| 168 |
+
background: #1f4e79;
|
| 169 |
+
color: #ffffff;
|
| 170 |
+
outline: none;
|
| 171 |
+
}
|
| 172 |
+
.ayuda-esquina {
|
| 173 |
+
position: absolute;
|
| 174 |
+
top: 6px;
|
| 175 |
+
left: 6px;
|
| 176 |
+
z-index: 20;
|
| 177 |
+
margin: 0;
|
| 178 |
+
width: 20px;
|
| 179 |
+
height: 20px;
|
| 180 |
+
font-size: 13px;
|
| 181 |
+
}
|
| 182 |
+
.globo-ayuda {
|
| 183 |
+
display: none;
|
| 184 |
+
position: fixed;
|
| 185 |
+
z-index: 10000;
|
| 186 |
+
max-width: 330px;
|
| 187 |
+
padding: 9px 12px;
|
| 188 |
+
background: #fffef9;
|
| 189 |
+
border: 0.8px solid #8f8f8f;
|
| 190 |
+
border-left: 3px solid #1f4e79;
|
| 191 |
+
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.16);
|
| 192 |
+
font: 14px/1.4 "STIX Two Text", "Times New Roman", serif;
|
| 193 |
+
color: #1a1a1a;
|
| 194 |
+
pointer-events: none;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
/* ---------- controles fijos a la izquierda al bajar por las figuras ---------- */
|
| 198 |
+
@media (min-width: 900px) {
|
| 199 |
+
.panel-controles {
|
| 200 |
+
position: sticky !important;
|
| 201 |
+
top: 8px;
|
| 202 |
+
align-self: flex-start !important;
|
| 203 |
+
max-height: calc(100vh - 16px);
|
| 204 |
+
overflow-y: auto;
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
/* overflow:hidden del contenedor de Gradio impide «position: sticky»; clip recorta igual sin impedirlo */
|
| 208 |
+
.gradio-container {
|
| 209 |
+
overflow: clip !important;
|
| 210 |
+
}
|
graficas.py
ADDED
|
@@ -0,0 +1,864 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Figuras del simulador con aspecto de libro (Springer): tipografía Times
|
| 2 |
+
(STIX), ejes finos con marcas hacia dentro, rejilla tenue y una paleta
|
| 3 |
+
sobria que se distingue también en blanco y negro por el trazo."""
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
import matplotlib
|
| 9 |
+
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
import numpy as np
|
| 12 |
+
from matplotlib.figure import Figure
|
| 13 |
+
from matplotlib.patches import Arc, Polygon, Rectangle
|
| 14 |
+
|
| 15 |
+
NEGRO = "#1a1a1a"
|
| 16 |
+
AZUL = "#1f4e79"
|
| 17 |
+
ROJO = "#a4262c"
|
| 18 |
+
VERDE = "#2e6b30"
|
| 19 |
+
AMBAR = "#b07d12"
|
| 20 |
+
GRIS = "#8c8c8c"
|
| 21 |
+
GRIS_CLARO = "#ececec"
|
| 22 |
+
TRAZOS = [(AZUL, "-"), (ROJO, "--"), (VERDE, ":"), (AMBAR, "-."), (NEGRO, (0, (5, 1, 1, 1, 1, 1)))]
|
| 23 |
+
|
| 24 |
+
matplotlib.rcParams.update({
|
| 25 |
+
"font.family": "serif",
|
| 26 |
+
"font.serif": ["STIXGeneral", "STIX Two Text", "Times New Roman", "DejaVu Serif"],
|
| 27 |
+
"mathtext.fontset": "stix",
|
| 28 |
+
"font.size": 10,
|
| 29 |
+
"axes.labelsize": 10.5,
|
| 30 |
+
"axes.titlesize": 10.5,
|
| 31 |
+
"axes.titleweight": "normal",
|
| 32 |
+
"axes.linewidth": 0.6,
|
| 33 |
+
"axes.edgecolor": NEGRO,
|
| 34 |
+
"axes.labelcolor": NEGRO,
|
| 35 |
+
"xtick.direction": "in",
|
| 36 |
+
"ytick.direction": "in",
|
| 37 |
+
"xtick.top": True,
|
| 38 |
+
"ytick.right": True,
|
| 39 |
+
"xtick.major.width": 0.6,
|
| 40 |
+
"ytick.major.width": 0.6,
|
| 41 |
+
"xtick.minor.visible": True,
|
| 42 |
+
"ytick.minor.visible": True,
|
| 43 |
+
"xtick.minor.width": 0.4,
|
| 44 |
+
"ytick.minor.width": 0.4,
|
| 45 |
+
"xtick.labelsize": 9,
|
| 46 |
+
"ytick.labelsize": 9,
|
| 47 |
+
"legend.fontsize": 8.5,
|
| 48 |
+
"legend.frameon": False,
|
| 49 |
+
"grid.color": "#dcdcdc",
|
| 50 |
+
"grid.linewidth": 0.5,
|
| 51 |
+
"lines.linewidth": 1.5,
|
| 52 |
+
"figure.dpi": 110,
|
| 53 |
+
"savefig.dpi": 160,
|
| 54 |
+
"figure.facecolor": "white",
|
| 55 |
+
"axes.facecolor": "white",
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _fig(w=6.4, h=4.0):
|
| 60 |
+
fig = Figure(figsize=(w, h), layout="constrained")
|
| 61 |
+
return fig
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _rotulo(ax, letra):
|
| 65 |
+
ax.text(0.0, 1.02, f"({letra})", transform=ax.transAxes, ha="left", va="bottom", fontsize=10)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def figura_error(mensaje):
|
| 69 |
+
fig = _fig(6.4, 1.6)
|
| 70 |
+
ax = fig.add_subplot()
|
| 71 |
+
ax.axis("off")
|
| 72 |
+
ax.text(0.5, 0.5, mensaje, ha="center", va="center", fontsize=11, color=ROJO, wrap=True)
|
| 73 |
+
return fig
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# =====================================================================
|
| 77 |
+
# Plano s
|
| 78 |
+
# =====================================================================
|
| 79 |
+
def _limites(puntos, region=None):
|
| 80 |
+
xs = [p.real for p in puntos] + [0.0]
|
| 81 |
+
ys = [abs(p.imag) for p in puntos] + [0.0]
|
| 82 |
+
if region:
|
| 83 |
+
xs.append(-region["sigma"] * 1.6)
|
| 84 |
+
ys.append(region["sigma"] * 1.6 * math.tan(region["beta"]))
|
| 85 |
+
xmin, xmax = min(xs), max(xs)
|
| 86 |
+
span = max(xmax - xmin, 2 * max(ys), 1.0)
|
| 87 |
+
xmin -= 0.18 * span
|
| 88 |
+
xmax += 0.18 * span
|
| 89 |
+
ymax = max(max(ys) * 1.3, 0.35 * (xmax - xmin))
|
| 90 |
+
return xmin, xmax, ymax
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def fig_plano_s(polos, ceros=(), *, titulo=None, polos_ref=None, ref_label="lazo abierto",
|
| 94 |
+
region=None, tray=None, anotar_2o=None, deseados=None, rejilla_zeta=True,
|
| 95 |
+
etiquetar=True, w=6.4, h=4.4):
|
| 96 |
+
"""Mapa de polos (×) y ceros (○) en el plano s."""
|
| 97 |
+
fig = _fig(w, h)
|
| 98 |
+
ax = fig.add_subplot()
|
| 99 |
+
polos = [complex(p) for p in polos]
|
| 100 |
+
ceros = [complex(z) for z in ceros]
|
| 101 |
+
refs = [] if polos_ref is None else [complex(p) for p in polos_ref]
|
| 102 |
+
des = [] if deseados is None else [complex(p) for p in deseados]
|
| 103 |
+
xmin, xmax, ymax = _limites(polos + ceros + refs + des, region)
|
| 104 |
+
# mismas unidades en los dos ejes (los ángulos de beta se leen bien)
|
| 105 |
+
# con una caja de proporción ~1.45; se amplía el eje que se quede corto
|
| 106 |
+
R = 1.45
|
| 107 |
+
if (xmax - xmin) / (2 * ymax) < R:
|
| 108 |
+
extra = R * 2 * ymax - (xmax - xmin)
|
| 109 |
+
izq = extra * (-xmin) / max(xmax - xmin, 1e-9)
|
| 110 |
+
xmin, xmax = xmin - izq, xmax + (extra - izq)
|
| 111 |
+
else:
|
| 112 |
+
ymax = (xmax - xmin) / (2 * R)
|
| 113 |
+
|
| 114 |
+
ax.axvspan(xmin, 0, color="#f5f5f5", zorder=0, lw=0)
|
| 115 |
+
ax.axhline(0, color=NEGRO, lw=0.6, zorder=1)
|
| 116 |
+
ax.axvline(0, color=NEGRO, lw=0.6, zorder=1)
|
| 117 |
+
ax.text(0.015, 0.97, "estable", transform=ax.transAxes, ha="left", va="top", fontsize=8.5,
|
| 118 |
+
color="#555", style="italic")
|
| 119 |
+
ax.text(0.985, 0.97, "inestable", transform=ax.transAxes, ha="right", va="top", fontsize=8.5,
|
| 120 |
+
color="#555", style="italic")
|
| 121 |
+
|
| 122 |
+
if rejilla_zeta:
|
| 123 |
+
R = math.hypot(xmin, ymax) * 1.2
|
| 124 |
+
for z in (0.2, 0.4, 0.6, 0.8):
|
| 125 |
+
b = math.acos(z)
|
| 126 |
+
for sg in (1, -1):
|
| 127 |
+
ax.plot([0, -R * math.cos(b)], [0, sg * R * math.sin(b)], color="#c8c8c8",
|
| 128 |
+
lw=0.5, ls=(0, (2, 2)), zorder=1)
|
| 129 |
+
xr, yr = -0.93 * ymax / math.tan(b), 0.93 * ymax
|
| 130 |
+
if xr < xmin:
|
| 131 |
+
xr, yr = xmin * 0.97, -xmin * 0.97 * math.tan(b)
|
| 132 |
+
ax.text(xr, yr, rf"$\zeta={z}$", fontsize=7.5, color="#888", ha="center", va="center",
|
| 133 |
+
bbox=dict(fc="white", ec="none", pad=0.4, alpha=0.8))
|
| 134 |
+
|
| 135 |
+
if region:
|
| 136 |
+
s0, b = region["sigma"], region["beta"]
|
| 137 |
+
X = xmin
|
| 138 |
+
poly = [(-s0, -s0 * math.tan(b)), (-s0, s0 * math.tan(b)), (X, -X * math.tan(b)), (X, X * math.tan(b))]
|
| 139 |
+
ax.add_patch(Polygon(poly, closed=True, fc="#dde6ef", ec="none", zorder=0.5))
|
| 140 |
+
ax.axvline(-s0, color=AZUL, lw=1.1, zorder=2)
|
| 141 |
+
ax.text(-s0, -0.92 * ymax, r" $\sigma=-4/t_s$" if region.get("banda", 2) == 2 else r" $\sigma=-3/t_s$",
|
| 142 |
+
color=AZUL, fontsize=8.5, ha="left", va="bottom")
|
| 143 |
+
R = math.hypot(xmin, ymax) * 1.2
|
| 144 |
+
for sg in (1, -1):
|
| 145 |
+
ax.plot([0, -R * math.cos(b)], [0, sg * R * math.sin(b)], color=AZUL, lw=1.0, ls="--", zorder=2)
|
| 146 |
+
ax.text(0.02, 0.06, "región admisible", transform=ax.transAxes, fontsize=8.5, color=AZUL)
|
| 147 |
+
|
| 148 |
+
if tray is not None:
|
| 149 |
+
vals, raices = tray
|
| 150 |
+
cmap = matplotlib.colormaps["Blues"]
|
| 151 |
+
for i, rr in enumerate(raices):
|
| 152 |
+
c = cmap(0.25 + 0.75 * i / max(len(raices) - 1, 1))
|
| 153 |
+
sel = [r for r in rr if xmin <= r.real <= xmax and abs(r.imag) <= ymax]
|
| 154 |
+
if sel:
|
| 155 |
+
ax.scatter([r.real for r in sel], [r.imag for r in sel], s=4, color=c, zorder=2, lw=0)
|
| 156 |
+
|
| 157 |
+
if refs:
|
| 158 |
+
ax.plot([p.real for p in refs], [p.imag for p in refs], "x", ms=8, mew=1.3, color=GRIS,
|
| 159 |
+
zorder=3, label=f"polos en {ref_label}")
|
| 160 |
+
if des:
|
| 161 |
+
ax.plot([p.real for p in des], [p.imag for p in des], "s", ms=10, mfc="none", mew=1.1,
|
| 162 |
+
color=AZUL, zorder=3, label="polos deseados")
|
| 163 |
+
if polos:
|
| 164 |
+
ax.plot([p.real for p in polos], [p.imag for p in polos], "x", ms=9.5, mew=1.9, color=NEGRO,
|
| 165 |
+
zorder=4, label="polos")
|
| 166 |
+
if ceros:
|
| 167 |
+
ax.plot([z.real for z in ceros], [z.imag for z in ceros], "o", ms=8.5, mfc="white", mew=1.5,
|
| 168 |
+
color=NEGRO, zorder=4, label="ceros")
|
| 169 |
+
|
| 170 |
+
if etiquetar:
|
| 171 |
+
vistos = {}
|
| 172 |
+
for p in polos:
|
| 173 |
+
k = (round(p.real, 6), round(p.imag, 6))
|
| 174 |
+
vistos[k] = vistos.get(k, 0) + 1
|
| 175 |
+
if len(vistos) <= 6:
|
| 176 |
+
for (re, im), mult in vistos.items():
|
| 177 |
+
txt = f"{re:.3g}" if abs(im) < 1e-9 else f"{re:.3g}{'+' if im > 0 else '−'}j{abs(im):.3g}"
|
| 178 |
+
txt = txt.replace("-", "−")
|
| 179 |
+
if mult > 1:
|
| 180 |
+
txt += f" (×{mult})"
|
| 181 |
+
ax.annotate(txt, (re, im), xytext=(6, 7 if im >= 0 else -12), textcoords="offset points",
|
| 182 |
+
fontsize=8, color=NEGRO)
|
| 183 |
+
|
| 184 |
+
if anotar_2o and anotar_2o.get("wd"):
|
| 185 |
+
sg, wd, wn = anotar_2o["sigma"], anotar_2o["wd"], anotar_2o["wn"]
|
| 186 |
+
ax.plot([0, -sg], [0, wd], color=NEGRO, lw=1.0, zorder=3)
|
| 187 |
+
ax.plot([-sg, -sg], [0, wd], color=GRIS, lw=0.7, ls="--", zorder=2)
|
| 188 |
+
ax.plot([-sg, 0], [wd, wd], color=GRIS, lw=0.7, ls="--", zorder=2)
|
| 189 |
+
rr = 0.3 * wn
|
| 190 |
+
beta = math.degrees(math.acos(min(max(anotar_2o["zeta"], 0), 1)))
|
| 191 |
+
ax.add_patch(Arc((0, 0), 2 * rr, 2 * rr, theta1=180 - beta, theta2=180, color=NEGRO, lw=0.7))
|
| 192 |
+
ax.text(-rr * 1.25 * math.cos(math.radians(beta / 2)), rr * 1.25 * math.sin(math.radians(beta / 2)),
|
| 193 |
+
r"$\beta$", fontsize=9, ha="center", va="center")
|
| 194 |
+
ax.text(-sg / 2 + 0.03 * wn, wd / 2 + 0.06 * wn, r"$\omega_n$", fontsize=9.5, ha="left")
|
| 195 |
+
ax.text(0.02 * wn, wd, r" $\omega_d$", fontsize=9.5, va="center", ha="left")
|
| 196 |
+
ax.text(-sg / 2, -0.07 * wn, r"$\sigma=\zeta\omega_n$", fontsize=9, ha="center", va="top")
|
| 197 |
+
|
| 198 |
+
ax.set_xlim(xmin, xmax)
|
| 199 |
+
ax.set_ylim(-ymax, ymax)
|
| 200 |
+
ax.set_aspect("equal", adjustable="box")
|
| 201 |
+
ax.set_xlabel(r"Real, $\sigma$")
|
| 202 |
+
ax.set_ylabel(r"Imaginario, $j\omega$")
|
| 203 |
+
ax.grid(True, which="major")
|
| 204 |
+
if titulo:
|
| 205 |
+
ax.set_title(titulo)
|
| 206 |
+
hand, lab = ax.get_legend_handles_labels()
|
| 207 |
+
if len(lab) > 1:
|
| 208 |
+
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.12), ncol=len(lab), fontsize=8.5,
|
| 209 |
+
frameon=False, handletextpad=0.3, columnspacing=1.4)
|
| 210 |
+
return fig
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# =====================================================================
|
| 214 |
+
# Respuesta temporal
|
| 215 |
+
# =====================================================================
|
| 216 |
+
def fig_respuesta(tt, y, *, r=None, yinf=None, met=None, ylabel=r"$y(t)$", rlabel=r"$r(t)$",
|
| 217 |
+
ylabel_curve=r"$y(t)$", titulo=None, extra=None, banda=0.02, w=6.4, h=4.0,
|
| 218 |
+
nota=None):
|
| 219 |
+
fig = _fig(w, h)
|
| 220 |
+
ax = fig.add_subplot()
|
| 221 |
+
lo, hi = _rango(y, r)
|
| 222 |
+
span = max(hi - lo, 1e-9)
|
| 223 |
+
visibles, fuera = [], False
|
| 224 |
+
for yy, lab in (extra or []):
|
| 225 |
+
a, b = _rango(yy)
|
| 226 |
+
if a >= lo - 1.5 * span and b <= hi + 1.5 * span:
|
| 227 |
+
visibles.append((yy, lab))
|
| 228 |
+
lo, hi = min(lo, a), max(hi, b)
|
| 229 |
+
else:
|
| 230 |
+
# una curva que diverge (p. ej. una rampa) no debe aplastar a las demás
|
| 231 |
+
visibles.append((yy, lab + " (se sale de la escala)"))
|
| 232 |
+
fuera = True
|
| 233 |
+
for i, (yy, lab) in enumerate(visibles):
|
| 234 |
+
c, ls = TRAZOS[(i + 1) % len(TRAZOS)]
|
| 235 |
+
ax.plot(tt, yy, color=c, ls=ls, lw=1.3, label=lab)
|
| 236 |
+
if r is not None:
|
| 237 |
+
ax.plot(tt, r, color=GRIS, ls="--", lw=1.1, label=rlabel)
|
| 238 |
+
ok = np.isfinite(y)
|
| 239 |
+
ax.plot(tt[ok], y[ok], color=NEGRO, lw=1.8, label=ylabel_curve, zorder=4)
|
| 240 |
+
if fuera:
|
| 241 |
+
hi = hi + 0.25 * span
|
| 242 |
+
if yinf is not None and np.isfinite(yinf) and abs(yinf) > 1e-12:
|
| 243 |
+
ax.axhspan(yinf * (1 - banda), yinf * (1 + banda), color=GRIS_CLARO, zorder=0, lw=0)
|
| 244 |
+
ax.axhline(yinf, color=GRIS, lw=0.7, ls=":")
|
| 245 |
+
lo, hi = min(lo, yinf * (1 - banda)), max(hi, yinf * (1 + banda))
|
| 246 |
+
if met and yinf:
|
| 247 |
+
_marcas(ax, tt, y, yinf, met, lo, hi)
|
| 248 |
+
pad = 0.08 * (hi - lo if hi > lo else 1)
|
| 249 |
+
ax.set_ylim(lo - pad, hi + pad)
|
| 250 |
+
ax.set_xlim(tt[0], tt[-1])
|
| 251 |
+
ax.set_xlabel(r"$t$ (s)")
|
| 252 |
+
ax.set_ylabel(ylabel)
|
| 253 |
+
ax.grid(True)
|
| 254 |
+
ax.axhline(0, color=NEGRO, lw=0.4)
|
| 255 |
+
ax.legend(loc="best")
|
| 256 |
+
if titulo:
|
| 257 |
+
ax.set_title(titulo)
|
| 258 |
+
if nota:
|
| 259 |
+
ax.text(0.99, 0.02, nota, transform=ax.transAxes, ha="right", va="bottom", fontsize=8, color="#555")
|
| 260 |
+
return fig
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _rango(y, r=None, extra=None):
|
| 264 |
+
vals = [np.asarray(y)[np.isfinite(y)]]
|
| 265 |
+
if r is not None:
|
| 266 |
+
vals.append(np.asarray(r))
|
| 267 |
+
for yy, _ in (extra or []):
|
| 268 |
+
vals.append(np.asarray(yy)[np.isfinite(yy)])
|
| 269 |
+
v = np.concatenate([x for x in vals if x.size])
|
| 270 |
+
if v.size == 0:
|
| 271 |
+
return -1.0, 1.0
|
| 272 |
+
lo, hi = float(np.min(v)), float(np.max(v))
|
| 273 |
+
lo, hi = min(lo, 0.0), max(hi, 0.0)
|
| 274 |
+
# si algo diverge, se recorta para que se siga viendo el arranque
|
| 275 |
+
if hi - lo > 1e6:
|
| 276 |
+
hi = min(hi, 1e3)
|
| 277 |
+
lo = max(lo, -1e3)
|
| 278 |
+
return lo, hi
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _marcas(ax, tt, y, yinf, met, lo, hi):
|
| 282 |
+
"""Cotas td, tr, tp, ts y la sobreoscilación, como en la figura 5.1 de los apuntes."""
|
| 283 |
+
base = lo + 0.02 * (hi - lo)
|
| 284 |
+
marcas = []
|
| 285 |
+
if np.isfinite(met.get("td", np.nan)):
|
| 286 |
+
marcas.append(("t_d", met["td"]))
|
| 287 |
+
if met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", np.nan)):
|
| 288 |
+
tp = met["tp"]
|
| 289 |
+
ymax = met["ymax"]
|
| 290 |
+
ax.plot([tp], [ymax], "o", ms=4, color=ROJO, zorder=5)
|
| 291 |
+
ax.annotate("", xy=(tp, ymax), xytext=(tp, yinf),
|
| 292 |
+
arrowprops=dict(arrowstyle="<->", color=ROJO, lw=0.9, shrinkA=0, shrinkB=0))
|
| 293 |
+
ax.text(tp, (ymax + yinf) / 2, f" $M_p={met['Mp']:.3g}\\,\\%$", color=ROJO, fontsize=9, va="center")
|
| 294 |
+
marcas.append(("t_p", tp))
|
| 295 |
+
if np.isfinite(met.get("ts2", np.nan)) and met["ts2"] > 0:
|
| 296 |
+
marcas.append(("t_s", met["ts2"]))
|
| 297 |
+
for nombre, tx in marcas:
|
| 298 |
+
yv = float(np.interp(tx, tt, y))
|
| 299 |
+
ax.plot([tx, tx], [base, yv], color=GRIS, lw=0.7, ls="--", zorder=1)
|
| 300 |
+
ax.text(tx, base, f"${nombre}$", fontsize=9, ha="center", va="bottom",
|
| 301 |
+
bbox=dict(fc="white", ec="none", pad=0.5))
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def fig_modos(tt, modos_y, etiquetas, total, *, w=6.4, h=3.8, titulo=None):
|
| 305 |
+
"""Cada polo aporta un modo: contribución de cada término y su suma."""
|
| 306 |
+
fig = _fig(w, h)
|
| 307 |
+
ax = fig.add_subplot()
|
| 308 |
+
for i, (yy, lab) in enumerate(zip(modos_y, etiquetas)):
|
| 309 |
+
c, ls = TRAZOS[i % len(TRAZOS)]
|
| 310 |
+
ax.plot(tt, yy, color=c, ls=ls, lw=1.25, label=lab)
|
| 311 |
+
ax.plot(tt, total, color=NEGRO, lw=1.9, label=r"suma: $y(t)$", zorder=4)
|
| 312 |
+
ax.axhline(0, color=NEGRO, lw=0.4)
|
| 313 |
+
lo, hi = _rango(total, None, [(m, "") for m in modos_y])
|
| 314 |
+
pad = 0.08 * (hi - lo if hi > lo else 1)
|
| 315 |
+
ax.set_ylim(lo - pad, hi + pad)
|
| 316 |
+
ax.set_xlim(tt[0], tt[-1])
|
| 317 |
+
ax.set_xlabel(r"$t$ (s)")
|
| 318 |
+
ax.set_ylabel("contribución de cada modo")
|
| 319 |
+
ax.grid(True)
|
| 320 |
+
ax.legend(loc="best", fontsize=8)
|
| 321 |
+
if titulo:
|
| 322 |
+
ax.set_title(titulo)
|
| 323 |
+
return fig
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def fig_superficie(G, *, w=6.4, h=4.6, titulo=None):
|
| 327 |
+
"""|G(s)| sobre el plano s: los polos son picos y los ceros, pozos.
|
| 328 |
+
|
| 329 |
+
El corte por el eje imaginario (sigma = 0) es la respuesta en frecuencia
|
| 330 |
+
|G(j omega)|, que se dibuja en rojo encima de la superficie.
|
| 331 |
+
"""
|
| 332 |
+
pts = list(G.polos_np()) + list(G.ceros_np())
|
| 333 |
+
xs = [p.real for p in pts] + [0.0]
|
| 334 |
+
ys = [abs(p.imag) for p in pts] + [0.0]
|
| 335 |
+
span = max(max(xs) - min(xs), 2 * max(ys), 1.0)
|
| 336 |
+
x0, x1 = min(xs) - 0.35 * span, max(xs) + 0.35 * span
|
| 337 |
+
W = max(max(ys) * 1.6, 0.5 * (x1 - x0))
|
| 338 |
+
S, Wg = np.meshgrid(np.linspace(x0, x1, 121), np.linspace(-W, W, 121))
|
| 339 |
+
Z = S + 1j * Wg
|
| 340 |
+
with np.errstate(all="ignore"):
|
| 341 |
+
M = np.abs(np.polyval(G.num, Z) / np.polyval(G.den, Z))
|
| 342 |
+
L = np.log10(M)
|
| 343 |
+
finitos = L[np.isfinite(L)]
|
| 344 |
+
zlo, zhi = np.percentile(finitos, 2), np.percentile(finitos, 97)
|
| 345 |
+
zhi = max(zhi, zlo + 1.0)
|
| 346 |
+
L = np.clip(np.nan_to_num(L, nan=zhi, posinf=zhi, neginf=zlo), zlo, zhi)
|
| 347 |
+
fig = _fig(w, h)
|
| 348 |
+
ax = fig.add_subplot(projection="3d")
|
| 349 |
+
ax.plot_surface(S, Wg, L, cmap="cividis", rstride=2, cstride=2, lw=0.15, edgecolor="#ffffff55",
|
| 350 |
+
antialiased=True, alpha=0.95)
|
| 351 |
+
wj = np.linspace(-W, W, 400)
|
| 352 |
+
with np.errstate(all="ignore"):
|
| 353 |
+
Lj = np.clip(np.log10(np.abs(np.polyval(G.num, 1j * wj) / np.polyval(G.den, 1j * wj))), zlo, zhi)
|
| 354 |
+
if x0 <= 0 <= x1:
|
| 355 |
+
ax.plot(np.zeros_like(wj), wj, Lj, color=ROJO, lw=1.8, zorder=10,
|
| 356 |
+
label=r"$|G(j\omega)|$: corte por $\sigma=0$")
|
| 357 |
+
for p in G.polos_np():
|
| 358 |
+
ax.plot([p.real], [p.imag], [zlo], "x", color=NEGRO, ms=7, mew=1.6)
|
| 359 |
+
for z in G.ceros_np():
|
| 360 |
+
ax.plot([z.real], [z.imag], [zlo], "o", mfc="white", color=NEGRO, ms=6, mew=1.2)
|
| 361 |
+
ax.set_xlabel(r"$\sigma$", labelpad=2)
|
| 362 |
+
ax.set_ylabel(r"$j\omega$", labelpad=2)
|
| 363 |
+
ax.set_zlabel(r"$\log_{10}|G(s)|$", labelpad=2)
|
| 364 |
+
ax.view_init(elev=27, azim=-58)
|
| 365 |
+
ax.tick_params(labelsize=7.5, pad=0)
|
| 366 |
+
ax.xaxis.pane.set_facecolor("white")
|
| 367 |
+
ax.yaxis.pane.set_facecolor("white")
|
| 368 |
+
ax.zaxis.pane.set_facecolor("white")
|
| 369 |
+
if x0 <= 0 <= x1:
|
| 370 |
+
ax.legend(loc="upper left", fontsize=8)
|
| 371 |
+
if titulo:
|
| 372 |
+
ax.set_title(titulo)
|
| 373 |
+
return fig
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
# =====================================================================
|
| 377 |
+
# PID: salida, error y las tres acciones
|
| 378 |
+
# =====================================================================
|
| 379 |
+
def fig_pid(sim, *, comparar=None, umin=None, umax=None, pert_t=None, espec=None, w=6.6, h=7.4):
|
| 380 |
+
"""(a) salida y consigna, (b) error, (c) u y sus tres acciones."""
|
| 381 |
+
tt = sim["t"]
|
| 382 |
+
fig = _fig(w, h)
|
| 383 |
+
axs = fig.subplots(3, 1, sharex=True, height_ratios=[1.25, 0.8, 1.2])
|
| 384 |
+
a, b, c = axs
|
| 385 |
+
|
| 386 |
+
if comparar:
|
| 387 |
+
for i, (lab, d) in enumerate(comparar):
|
| 388 |
+
col, ls = TRAZOS[(i + 1) % len(TRAZOS)]
|
| 389 |
+
a.plot(d["t"], d["y"], color=col, ls=ls, lw=1.15, label=lab)
|
| 390 |
+
r = sim["r"]
|
| 391 |
+
a.plot(tt, r, color=GRIS, ls="--", lw=1.0, label=r"consigna $r(t)$", drawstyle="steps-post")
|
| 392 |
+
a.plot(tt, sim["y"], color=NEGRO, lw=1.9, label=r"salida $y(t)$", zorder=4)
|
| 393 |
+
lo, hi = _rango(sim["y"], r, [(d["y"], "") for _, d in (comparar or [])])
|
| 394 |
+
span = hi - lo if hi > lo else 1.0
|
| 395 |
+
if espec:
|
| 396 |
+
yl = espec["yinf"] * (1 + espec["Mp"] / 100)
|
| 397 |
+
a.axhline(yl, color=ROJO, lw=0.8, ls=(0, (1, 2)))
|
| 398 |
+
a.text(tt[-1], yl, f"límite $M_p$ = {espec['Mp']:.3g} % ", color=ROJO, fontsize=8, ha="right", va="bottom")
|
| 399 |
+
for ax in axs:
|
| 400 |
+
ax.axvline(espec["ts"], color=AZUL, lw=0.8, ls=(0, (1, 2)))
|
| 401 |
+
hi = max(hi, yl)
|
| 402 |
+
a.set_ylim(lo - 0.06 * span, hi + 0.1 * span)
|
| 403 |
+
if espec:
|
| 404 |
+
a.text(espec["ts"], a.get_ylim()[0], " $t_s$ exigido", color=AZUL, fontsize=8, va="bottom")
|
| 405 |
+
if sim.get("diverge") or (np.max(np.abs(sim["y"])) > 50 * max(1.0, np.max(np.abs(r)))):
|
| 406 |
+
a.text(0.5, 0.5, "la salida diverge: el lazo es inestable", transform=a.transAxes, ha="center",
|
| 407 |
+
va="center", fontsize=11, color=ROJO, bbox=dict(fc="white", ec=ROJO, lw=0.8, pad=4))
|
| 408 |
+
a.set_ylabel(r"$y(t)$")
|
| 409 |
+
a.legend(loc="lower right", ncol=2 if comparar else 1)
|
| 410 |
+
_rotulo(a, "a")
|
| 411 |
+
|
| 412 |
+
b.plot(tt, sim["e"], color=AZUL, lw=1.4)
|
| 413 |
+
b.axhline(0, color=NEGRO, lw=0.4)
|
| 414 |
+
lo, hi = _rango(sim["e"])
|
| 415 |
+
b.set_ylim(lo - 0.08 * (hi - lo + 1e-9), hi + 0.08 * (hi - lo + 1e-9))
|
| 416 |
+
b.set_ylabel(r"$e(t)=r-y$")
|
| 417 |
+
_rotulo(b, "b")
|
| 418 |
+
|
| 419 |
+
comps = [("P", sim["P"], AZUL, "--", r"$P=K_p\,e$"),
|
| 420 |
+
("I", sim["I"], VERDE, "-.", r"$I=K_i\!\int e\,d\tau$"),
|
| 421 |
+
("D", sim["D"], ROJO, ":", r"$D=K_d\,\dot e$")]
|
| 422 |
+
vals = [sim["u"]]
|
| 423 |
+
for k, v, col, ls, lab in comps:
|
| 424 |
+
if np.any(np.abs(v) > 1e-12):
|
| 425 |
+
c.plot(tt, v, color=col, ls=ls, lw=1.3, label=lab)
|
| 426 |
+
vals.append(v)
|
| 427 |
+
if umin is not None or umax is not None:
|
| 428 |
+
if np.any(np.abs(sim["u_ns"] - sim["u"]) > 1e-9):
|
| 429 |
+
c.plot(tt, sim["u_ns"], color=GRIS, lw=0.8, label="$u$ pedida (sin saturar)")
|
| 430 |
+
for lim in (umin, umax):
|
| 431 |
+
if lim is not None:
|
| 432 |
+
c.axhline(lim, color=GRIS, ls=(0, (4, 2)), lw=0.8)
|
| 433 |
+
c.plot(tt, sim["u"], color=NEGRO, lw=1.8, label=r"$u=P+I+D$", zorder=4)
|
| 434 |
+
c.axhline(0, color=NEGRO, lw=0.4)
|
| 435 |
+
# un pico inicial muy grande (derivada filtrada) se recorta para que se vea el resto
|
| 436 |
+
v = np.concatenate([x[np.isfinite(x)] for x in vals])
|
| 437 |
+
q_lo, q_hi = np.percentile(v, [1, 99])
|
| 438 |
+
lo, hi = min(float(np.min(v)), 0.0), max(float(np.max(v)), 0.0)
|
| 439 |
+
if hi - lo > 4 * (q_hi - q_lo + 1e-9):
|
| 440 |
+
lo, hi = min(q_lo, 0.0), max(q_hi, 0.0)
|
| 441 |
+
c.text(0.02, 0.96, "pico inicial de la acción derivativa recortado", transform=c.transAxes,
|
| 442 |
+
fontsize=8, color=ROJO, va="top")
|
| 443 |
+
pad = 0.12 * (hi - lo + 1e-9)
|
| 444 |
+
c.set_ylim(lo - pad, hi + pad)
|
| 445 |
+
for ti, area in sim.get("impulsos", []):
|
| 446 |
+
top = hi + 0.6 * pad
|
| 447 |
+
c.annotate("", xy=(ti, top if area > 0 else lo - 0.6 * pad), xytext=(ti, 0),
|
| 448 |
+
arrowprops=dict(arrowstyle="-|>", color=ROJO, lw=1.2, mutation_scale=10))
|
| 449 |
+
c.text(ti, top, f" impulso $K_d\\,\\Delta r\\,\\delta(t)$, área {area:.3g}", color=ROJO,
|
| 450 |
+
fontsize=8, va="top", ha="left")
|
| 451 |
+
c.set_ylabel(r"$u(t)$ y sus acciones")
|
| 452 |
+
c.set_xlabel(r"$t$ (s)")
|
| 453 |
+
c.legend(loc="lower right", fontsize=8, ncol=2)
|
| 454 |
+
_rotulo(c, "c")
|
| 455 |
+
for ax in axs:
|
| 456 |
+
ax.grid(True)
|
| 457 |
+
ax.set_xlim(tt[0], sim.get("t_end", tt[-1]))
|
| 458 |
+
if pert_t is not None:
|
| 459 |
+
ax.axvline(pert_t, color=AMBAR, lw=0.8, ls="--")
|
| 460 |
+
if pert_t is not None:
|
| 461 |
+
a.text(pert_t, a.get_ylim()[1], " perturbación", color=AMBAR, fontsize=8, va="top")
|
| 462 |
+
return fig
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _rango_robusto(series):
|
| 466 |
+
v = np.concatenate([np.asarray(x)[np.isfinite(x)] for x in series if len(x)])
|
| 467 |
+
if v.size == 0:
|
| 468 |
+
return -1.0, 1.0
|
| 469 |
+
q1, q2 = np.percentile(v, [1, 99])
|
| 470 |
+
lo, hi = min(float(np.min(v)), 0.0), max(float(np.max(v)), 0.0)
|
| 471 |
+
if hi - lo > 4 * (q2 - q1 + 1e-9):
|
| 472 |
+
lo, hi = min(q1, 0.0), max(q2, 0.0)
|
| 473 |
+
pad = 0.12 * (hi - lo + 1e-9)
|
| 474 |
+
return lo - pad, hi + pad
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def fig_pid_real(ideal, real, alternativa=None, ruido=None, *, umin=None, umax=None, w=6.6, h=7.8):
|
| 478 |
+
"""El PID de libro frente al PID tal como está configurado.
|
| 479 |
+
|
| 480 |
+
(a) la salida, (b) la acción de control (y la parte integral si hay
|
| 481 |
+
límites, que es donde se ve el windup) y (c) lo que hace la acción
|
| 482 |
+
derivativa con el ruido del sensor, ideal frente a filtrada.
|
| 483 |
+
"""
|
| 484 |
+
if ruido:
|
| 485 |
+
fig = _fig(w, h)
|
| 486 |
+
a, b, c = fig.subplots(3, 1, height_ratios=[1.15, 1.15, 0.9])
|
| 487 |
+
else:
|
| 488 |
+
fig = _fig(w, h * 0.72)
|
| 489 |
+
a, b = fig.subplots(2, 1)
|
| 490 |
+
c = None
|
| 491 |
+
sat = umin is not None or umax is not None
|
| 492 |
+
iguales = (len(ideal["y"]) == len(real["y"]) and np.allclose(ideal["y"], real["y"], atol=1e-6)
|
| 493 |
+
and np.allclose(ideal["u"], real["u"], atol=1e-6))
|
| 494 |
+
if iguales:
|
| 495 |
+
a.text(0.5, 0.5, "Ahora coinciden: active alguna corrección del PID real\n"
|
| 496 |
+
"(filtro, derivar la medida o límites del actuador) para ver la diferencia.",
|
| 497 |
+
transform=a.transAxes, ha="center", va="center", fontsize=9.5, color="#444",
|
| 498 |
+
bbox=dict(fc="white", ec="#bbb", lw=0.6, pad=5), zorder=10)
|
| 499 |
+
|
| 500 |
+
a.plot(real["t"], real["r"], color=GRIS, ls="--", lw=1.0, drawstyle="steps-post", label="consigna")
|
| 501 |
+
a.plot(ideal["t"], ideal["y"], color=AZUL, ls="--", lw=1.5, label="PID ideal (el de la fórmula)")
|
| 502 |
+
if alternativa:
|
| 503 |
+
alt, etq = alternativa
|
| 504 |
+
a.plot(alt["t"], alt["y"], color=ROJO, ls=":", lw=1.8, label=etq)
|
| 505 |
+
a.plot(real["t"], real["y"], color=NEGRO, lw=2.0, label="PID real (su configuración)")
|
| 506 |
+
lo, hi = _rango(real["y"], real["r"], [(ideal["y"], "")] + ([(alternativa[0]["y"], "")] if alternativa else []))
|
| 507 |
+
sp_ = hi - lo if hi > lo else 1.0
|
| 508 |
+
a.set_ylim(lo - 0.06 * sp_, hi + 0.1 * sp_)
|
| 509 |
+
a.set_ylabel("salida $y(t)$")
|
| 510 |
+
a.legend(loc="lower right", fontsize=8)
|
| 511 |
+
_rotulo(a, "a")
|
| 512 |
+
|
| 513 |
+
series = [ideal["u"], real["u"]]
|
| 514 |
+
b.plot(ideal["t"], ideal["u"], color=AZUL, ls="--", lw=1.4, label="$u$ del PID ideal")
|
| 515 |
+
if alternativa:
|
| 516 |
+
b.plot(alternativa[0]["t"], alternativa[0]["u"], color=ROJO, ls=":", lw=1.6, label="$u$ " + alternativa[1])
|
| 517 |
+
series.append(alternativa[0]["u"])
|
| 518 |
+
b.plot(real["t"], real["u"], color=NEGRO, lw=1.9, label="$u$ del PID real")
|
| 519 |
+
if sat:
|
| 520 |
+
# el windup se ve en la parte integral: sin anti-windup sigue creciendo con el actuador al tope
|
| 521 |
+
b.plot(real["t"], real["I"], color=VERDE, lw=1.0, ls="-.", label="parte integral $I$ (real)")
|
| 522 |
+
series.append(real["I"])
|
| 523 |
+
if alternativa:
|
| 524 |
+
b.plot(alternativa[0]["t"], alternativa[0]["I"], color=ROJO, lw=1.0, ls="-.", alpha=0.8,
|
| 525 |
+
label="parte integral $I$ " + ("sin" if "sin" in alternativa[1] else "con") + " anti-windup")
|
| 526 |
+
series.append(alternativa[0]["I"])
|
| 527 |
+
for lim in (umin, umax):
|
| 528 |
+
if lim is not None:
|
| 529 |
+
b.axhline(lim, color=GRIS, ls=(0, (4, 2)), lw=0.9)
|
| 530 |
+
b.text(0.995, (umax if umax is not None else umin), "límite del actuador ", transform=b.get_yaxis_transform(),
|
| 531 |
+
fontsize=8, color="#555", ha="right", va="bottom")
|
| 532 |
+
lo, hi = _rango_robusto(series)
|
| 533 |
+
b.set_ylim(lo, hi)
|
| 534 |
+
for ti, area in ideal.get("impulsos", []):
|
| 535 |
+
b.annotate("", xy=(ti, hi), xytext=(ti, 0), arrowprops=dict(arrowstyle="-|>", color=ROJO, lw=1.3,
|
| 536 |
+
mutation_scale=10))
|
| 537 |
+
b.text(ti, hi, " golpe de la derivada ideal (impulso)", color=ROJO, fontsize=8, va="top")
|
| 538 |
+
b.axhline(0, color=NEGRO, lw=0.4)
|
| 539 |
+
b.set_ylabel("acción de control $u(t)$")
|
| 540 |
+
b.set_xlabel("$t$ (s)")
|
| 541 |
+
b.legend(loc="lower right", fontsize=7.5, ncol=2)
|
| 542 |
+
_rotulo(b, "b")
|
| 543 |
+
for ax in (a, b):
|
| 544 |
+
ax.grid(True)
|
| 545 |
+
ax.set_xlim(real["t"][0], real.get("t_end", real["t"][-1]))
|
| 546 |
+
|
| 547 |
+
if c is None:
|
| 548 |
+
return fig
|
| 549 |
+
tt = ruido["t"]
|
| 550 |
+
c.plot(tt, ruido["ideal"], color=ROJO, lw=0.7, label="derivada sin filtro: $K_d\\,\\dot n$")
|
| 551 |
+
c.plot(tt, ruido["filtro"], color=NEGRO, lw=1.4, label=f"derivada filtrada (N = {ruido['N']:.3g})")
|
| 552 |
+
amp_f = float(np.max(np.abs(ruido["filtro"]))) or 1.0
|
| 553 |
+
amp_i = float(np.max(np.abs(ruido["ideal"])))
|
| 554 |
+
c.set_ylim(-3.2 * amp_f, 3.2 * amp_f)
|
| 555 |
+
c.axhline(0, color=NEGRO, lw=0.4)
|
| 556 |
+
caja_txt = dict(fc="white", ec="none", alpha=0.9, pad=2)
|
| 557 |
+
if amp_i > 3.2 * amp_f:
|
| 558 |
+
c.text(0.99, 0.95, f"sin filtro llega a ±{amp_i:.3g}: se sale de la escala",
|
| 559 |
+
transform=c.transAxes, fontsize=8, color=ROJO, ha="right", va="top", bbox=caja_txt, zorder=10)
|
| 560 |
+
c.set_xlim(tt[0], tt[-1])
|
| 561 |
+
c.set_xlabel("$t$ (s)")
|
| 562 |
+
c.set_ylabel("acción D por el ruido")
|
| 563 |
+
c.legend(loc="lower right", fontsize=8, ncol=2, frameon=True, framealpha=0.92, edgecolor="none")
|
| 564 |
+
c.grid(True)
|
| 565 |
+
_rotulo(c, "c")
|
| 566 |
+
c.set_title("qué hace la derivada con un ruido de medida del 1 %", fontsize=9.5)
|
| 567 |
+
return fig
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _cruce(tt, y, nivel):
|
| 571 |
+
idx = np.nonzero(y >= nivel)[0]
|
| 572 |
+
if idx.size == 0:
|
| 573 |
+
return math.nan
|
| 574 |
+
i = idx[0]
|
| 575 |
+
if i == 0:
|
| 576 |
+
return float(tt[0])
|
| 577 |
+
return float(tt[i - 1] + (nivel - y[i - 1]) * (tt[i] - tt[i - 1]) / (y[i] - y[i - 1]))
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def _num(x, sig=3):
|
| 581 |
+
if x is None or not np.isfinite(x):
|
| 582 |
+
return "—"
|
| 583 |
+
return f"{x:.{sig}g}"
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def fig_especificaciones(tt, y, yinf, met, teor=None, *, nota=None, w=9.6, h=5.2):
|
| 587 |
+
"""Respuesta a escalón con las cinco magnitudes acotadas y sus valores,
|
| 588 |
+
como la figura 5.1 de los apuntes, y una tabla de medido frente a fórmula."""
|
| 589 |
+
fig = _fig(w, h)
|
| 590 |
+
gs = fig.add_gridspec(1, 2, width_ratios=[2.45, 1])
|
| 591 |
+
ax = fig.add_subplot(gs[0])
|
| 592 |
+
tab = fig.add_subplot(gs[1])
|
| 593 |
+
tab.axis("off")
|
| 594 |
+
base = abs(yinf)
|
| 595 |
+
s = 1.0 if yinf > 0 else -1.0
|
| 596 |
+
yn = s * np.asarray(y) # se dibuja siempre hacia arriba
|
| 597 |
+
yf = base
|
| 598 |
+
|
| 599 |
+
ax.axhspan(yf * 0.98, yf * 1.02, color=GRIS_CLARO, lw=0, zorder=0)
|
| 600 |
+
ax.plot(tt, yn, color=NEGRO, lw=2.0, zorder=4)
|
| 601 |
+
ax.axhline(yf, color=GRIS, lw=0.8, ls="--", zorder=1)
|
| 602 |
+
ax.axhline(0, color=NEGRO, lw=0.6, zorder=1)
|
| 603 |
+
guia = dict(color=GRIS, lw=0.8, ls="--", zorder=2)
|
| 604 |
+
|
| 605 |
+
cotas = []
|
| 606 |
+
td = met.get("td", math.nan)
|
| 607 |
+
if np.isfinite(td):
|
| 608 |
+
ax.plot([0, td], [0.5 * yf, 0.5 * yf], **guia)
|
| 609 |
+
ax.plot([td, td], [0, 0.5 * yf], **guia)
|
| 610 |
+
cotas.append(("t_d", 0.0, td, "retardo (50 %)"))
|
| 611 |
+
if met.get("Mp", 0) > 0.05:
|
| 612 |
+
tr = met.get("tr", math.nan)
|
| 613 |
+
if np.isfinite(tr):
|
| 614 |
+
ax.plot([tr, tr], [0, yf], **guia)
|
| 615 |
+
cotas.append(("t_r", 0.0, tr, "subida (0–100 %)"))
|
| 616 |
+
else:
|
| 617 |
+
t10, t90 = _cruce(tt, yn, 0.1 * yf), _cruce(tt, yn, 0.9 * yf)
|
| 618 |
+
if np.isfinite(t10) and np.isfinite(t90):
|
| 619 |
+
ax.plot([0, t90], [0.9 * yf, 0.9 * yf], **guia)
|
| 620 |
+
ax.plot([0, t10], [0.1 * yf, 0.1 * yf], **guia)
|
| 621 |
+
ax.plot([t10, t10], [0, 0.1 * yf], **guia)
|
| 622 |
+
ax.plot([t90, t90], [0, 0.9 * yf], **guia)
|
| 623 |
+
cotas.append(("t_r", t10, t90, "subida (10–90 %)"))
|
| 624 |
+
ymax = float(np.max(yn))
|
| 625 |
+
if met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", math.nan)):
|
| 626 |
+
tp = met["tp"]
|
| 627 |
+
ax.plot([tp, tp], [0, ymax], **guia)
|
| 628 |
+
ax.plot([0, tp], [ymax, ymax], **guia)
|
| 629 |
+
ax.plot([tp], [ymax], "o", ms=5, color=ROJO, zorder=5)
|
| 630 |
+
ax.annotate("", xy=(tp, ymax), xytext=(tp, yf),
|
| 631 |
+
arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.1, shrinkA=0, shrinkB=0))
|
| 632 |
+
ax.text(tp + 0.02 * tt[-1], (ymax + yf) / 2, f"$M_p$ = {_num(met['Mp'])} %", color=ROJO, fontsize=11.5,
|
| 633 |
+
va="center", bbox=dict(fc="white", ec="none", alpha=0.85, pad=1))
|
| 634 |
+
cotas.append(("t_p", 0.0, tp, "pico"))
|
| 635 |
+
ts = met.get("ts2", math.nan)
|
| 636 |
+
if np.isfinite(ts) and ts > 0:
|
| 637 |
+
ax.plot([ts, ts], [0, yf * 1.02], **guia)
|
| 638 |
+
cotas.append(("t_s", 0.0, ts, "establecimiento (2 %)"))
|
| 639 |
+
|
| 640 |
+
paso = 0.13 * yf
|
| 641 |
+
for k, (nombre, a, b, desc) in enumerate(cotas, start=1):
|
| 642 |
+
yc = -k * paso
|
| 643 |
+
ax.annotate("", xy=(b, yc), xytext=(a, yc),
|
| 644 |
+
arrowprops=dict(arrowstyle="<->", color=NEGRO, lw=0.9, shrinkA=0, shrinkB=0))
|
| 645 |
+
ax.plot([b, b], [yc, 0], color=GRIS, lw=0.5, ls=":")
|
| 646 |
+
ax.text(b + 0.012 * tt[-1], yc, f"${nombre}$ = {_num(b - a)} s", fontsize=11, va="center", ha="left",
|
| 647 |
+
bbox=dict(fc="white", ec="none", alpha=0.9, pad=0.5))
|
| 648 |
+
fondo = -(len(cotas) + 0.7) * paso
|
| 649 |
+
techo = max(ymax, yf * 1.02) + 0.12 * yf
|
| 650 |
+
ax.set_ylim(fondo, techo)
|
| 651 |
+
ax.set_xlim(0, tt[-1] * 1.0)
|
| 652 |
+
ax.text(tt[-1], yf * 1.025, f"valor final $y(\\infty)$ = {_num(s * yf)} ", fontsize=9.5, ha="right",
|
| 653 |
+
va="bottom", color="#444")
|
| 654 |
+
ticks = [t for t in ax.get_yticks() if -1e-9 <= t <= techo]
|
| 655 |
+
ax.set_yticks(ticks)
|
| 656 |
+
if s < 0:
|
| 657 |
+
ax.set_yticklabels([_num(-t) for t in ticks])
|
| 658 |
+
ax.set_xlabel("$t$ (s)")
|
| 659 |
+
ax.set_ylabel("$y(t)$" + (" (dibujada con el signo cambiado)" if s < 0 else ""))
|
| 660 |
+
ax.spines["bottom"].set_visible(False)
|
| 661 |
+
ax.tick_params(axis="x", which="both", top=False)
|
| 662 |
+
ax.set_title(nota or "Respuesta a escalón: las magnitudes que la definen", fontsize=10.5)
|
| 663 |
+
|
| 664 |
+
# tabla de valores, con filetes como en los apuntes
|
| 665 |
+
filas = [("t_d", "retardo", met.get("td"), "s", "td"),
|
| 666 |
+
("t_r", "subida " + met.get("tr_def", ""), met.get("tr"), "s", "tr"),
|
| 667 |
+
("t_p", "pico", met.get("tp") if met.get("Mp", 0) > 0.05 else None, "s", "tp"),
|
| 668 |
+
("M_p", "sobreoscilación", met.get("Mp"), "%", "Mp"),
|
| 669 |
+
("t_s", "establec. 2 %", met.get("ts2"), "s", "ts2"),
|
| 670 |
+
("t_s", "establec. 5 %", met.get("ts5"), "s", "ts5")]
|
| 671 |
+
x0, x1, x2 = 0.0, 0.47, 0.76
|
| 672 |
+
yy = 0.93
|
| 673 |
+
tab.text(x0, yy, "Magnitud", fontsize=10, weight="bold", transform=tab.transAxes)
|
| 674 |
+
tab.text(x1, yy, "medido", fontsize=10, weight="bold", transform=tab.transAxes)
|
| 675 |
+
tab.text(x2, yy, "fórmula", fontsize=10, weight="bold", transform=tab.transAxes)
|
| 676 |
+
tab.plot([0, 1], [yy + 0.055, yy + 0.055], color=NEGRO, lw=1.2, transform=tab.transAxes, clip_on=False)
|
| 677 |
+
tab.plot([0, 1], [yy - 0.03, yy - 0.03], color=NEGRO, lw=0.6, transform=tab.transAxes, clip_on=False)
|
| 678 |
+
for nombre, desc, v, u, clave in filas:
|
| 679 |
+
yy -= 0.105
|
| 680 |
+
tab.text(x0, yy, f"${nombre}$ {desc}", fontsize=9.5, transform=tab.transAxes)
|
| 681 |
+
sin_pico = clave == "tp" and v is None
|
| 682 |
+
tab.text(x1, yy, "no hay pico" if sin_pico else f"{_num(v)} {u}", fontsize=9.5, transform=tab.transAxes)
|
| 683 |
+
if teor and clave in teor:
|
| 684 |
+
tv = teor[clave][1]
|
| 685 |
+
tab.text(x2, yy, f"{_num(tv)} {u}", fontsize=9.5, transform=tab.transAxes, color=AZUL)
|
| 686 |
+
else:
|
| 687 |
+
tab.text(x2, yy, "—", fontsize=9.5, transform=tab.transAxes, color=GRIS)
|
| 688 |
+
tab.plot([0, 1], [yy - 0.045, yy - 0.045], color=NEGRO, lw=1.2, transform=tab.transAxes, clip_on=False)
|
| 689 |
+
if teor:
|
| 690 |
+
tab.text(0, yy - 0.12, "En azul, lo que predicen las fórmulas\n" + teor.get("_origen", ""), fontsize=8.5,
|
| 691 |
+
color="#555", transform=tab.transAxes, va="top")
|
| 692 |
+
return fig
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def figura_aviso(mensaje, w=9.6, h=1.8):
|
| 696 |
+
fig = _fig(w, h)
|
| 697 |
+
ax = fig.add_subplot()
|
| 698 |
+
ax.axis("off")
|
| 699 |
+
ax.text(0.5, 0.5, mensaje, ha="center", va="center", fontsize=11, color="#444", wrap=True)
|
| 700 |
+
return fig
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def fig_cada_magnitud(tt, y, yinf, met, teor=None, *, w=11.0, h=7.6):
|
| 704 |
+
"""Una gráfica por magnitud: cómo se mide cada una sobre la misma curva."""
|
| 705 |
+
fig = _fig(w, h)
|
| 706 |
+
axs = fig.subplots(2, 2)
|
| 707 |
+
s = 1.0 if yinf > 0 else -1.0
|
| 708 |
+
yn = s * np.asarray(y)
|
| 709 |
+
yf = abs(yinf)
|
| 710 |
+
ymax = float(np.max(yn))
|
| 711 |
+
teor = teor or {}
|
| 712 |
+
hay_pico = met.get("Mp", 0) > 0.05 and np.isfinite(met.get("tp", math.nan))
|
| 713 |
+
techo = max(ymax, yf * 1.05) + 0.12 * yf
|
| 714 |
+
|
| 715 |
+
def base(ax, titulo, texto):
|
| 716 |
+
ax.plot(tt, yn, color="#9a9a9a", lw=1.4, zorder=2)
|
| 717 |
+
ax.axhline(yf, color=GRIS, lw=0.7, ls="--")
|
| 718 |
+
ax.axhline(0, color=NEGRO, lw=0.5)
|
| 719 |
+
ax.set_xlim(0, tt[-1])
|
| 720 |
+
ax.set_ylim(min(0.0, float(np.min(yn))) - 0.05 * yf, techo)
|
| 721 |
+
ax.set_title(titulo, fontsize=11.5)
|
| 722 |
+
ax.text(0.98, 0.04, texto, transform=ax.transAxes, ha="right", va="bottom", fontsize=9.5,
|
| 723 |
+
bbox=dict(fc="white", ec="#cccccc", lw=0.6, pad=4), zorder=6)
|
| 724 |
+
ax.set_xlabel("$t$ (s)")
|
| 725 |
+
ax.grid(True)
|
| 726 |
+
|
| 727 |
+
def formula(clave, txt):
|
| 728 |
+
if clave in teor:
|
| 729 |
+
return f"\nfórmula: ${teor[clave][0]}$ = {_num(teor[clave][1])}" + (" %" if clave == "Mp" else " s")
|
| 730 |
+
return ""
|
| 731 |
+
|
| 732 |
+
# (a) td
|
| 733 |
+
a = axs[0, 0]
|
| 734 |
+
td = met.get("td", math.nan)
|
| 735 |
+
base(a, f"Tiempo de retardo: $t_d$ = {_num(td)} s",
|
| 736 |
+
"tiempo hasta llegar al 50 % del valor final" + formula("td", ""))
|
| 737 |
+
if np.isfinite(td):
|
| 738 |
+
a.axvspan(0, td, color=AZUL, alpha=0.12, lw=0)
|
| 739 |
+
a.plot(tt[tt <= td], yn[tt <= td], color=AZUL, lw=2.4, zorder=3)
|
| 740 |
+
a.plot([0, td], [0.5 * yf, 0.5 * yf], color=AZUL, ls="--", lw=1)
|
| 741 |
+
a.plot([td], [0.5 * yf], "o", color=AZUL, ms=7, zorder=5)
|
| 742 |
+
a.text(td, 0.5 * yf, " 50 %", color=AZUL, va="top", fontsize=10)
|
| 743 |
+
_rotulo(a, "a")
|
| 744 |
+
|
| 745 |
+
# (b) tr
|
| 746 |
+
b = axs[0, 1]
|
| 747 |
+
if hay_pico:
|
| 748 |
+
tr = met.get("tr", math.nan)
|
| 749 |
+
base(b, f"Tiempo de subida: $t_r$ = {_num(tr)} s",
|
| 750 |
+
"del 0 al 100 % del valor final\n(hay sobreoscilación)" + formula("tr", ""))
|
| 751 |
+
t0, t1 = 0.0, tr
|
| 752 |
+
else:
|
| 753 |
+
t0, t1 = _cruce(tt, yn, 0.1 * yf), _cruce(tt, yn, 0.9 * yf)
|
| 754 |
+
base(b, f"Tiempo de subida: $t_r$ = {_num(t1 - t0)} s",
|
| 755 |
+
"del 10 al 90 % del valor final\n(no hay sobreoscilación)" + formula("tr", ""))
|
| 756 |
+
for nivel in (0.1, 0.9):
|
| 757 |
+
b.plot([0, tt[-1]], [nivel * yf] * 2, color=VERDE, ls=":", lw=1)
|
| 758 |
+
if np.isfinite(t0) and np.isfinite(t1):
|
| 759 |
+
b.axvspan(t0, t1, color=VERDE, alpha=0.13, lw=0)
|
| 760 |
+
m = (tt >= t0) & (tt <= t1)
|
| 761 |
+
b.plot(tt[m], yn[m], color=VERDE, lw=2.4, zorder=3)
|
| 762 |
+
b.plot([t0, t1], [np.interp(t0, tt, yn), np.interp(t1, tt, yn)], "o", color=VERDE, ms=7, zorder=5)
|
| 763 |
+
b.annotate("", xy=(t1, 0.08 * yf), xytext=(t0, 0.08 * yf),
|
| 764 |
+
arrowprops=dict(arrowstyle="<->", color=VERDE, lw=1.2, shrinkA=0, shrinkB=0))
|
| 765 |
+
_rotulo(b, "b")
|
| 766 |
+
|
| 767 |
+
# (c) tp y Mp
|
| 768 |
+
c = axs[1, 0]
|
| 769 |
+
if hay_pico:
|
| 770 |
+
tp, Mp = met["tp"], met["Mp"]
|
| 771 |
+
base(c, f"Pico: $t_p$ = {_num(tp)} s, $M_p$ = {_num(Mp)} %",
|
| 772 |
+
"$t_p$: instante del primer máximo\n$M_p$: cuánto se pasa del valor final" + formula("tp", "")
|
| 773 |
+
+ formula("Mp", ""))
|
| 774 |
+
c.axvspan(0, tp, color=ROJO, alpha=0.08, lw=0)
|
| 775 |
+
c.plot([tp], [ymax], "o", color=ROJO, ms=8, zorder=5)
|
| 776 |
+
c.annotate("", xy=(tp, ymax), xytext=(tp, yf),
|
| 777 |
+
arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.4, shrinkA=0, shrinkB=0))
|
| 778 |
+
c.text(tp + 0.02 * tt[-1], (ymax + yf) / 2, f"$M_p$ = {_num(Mp)} %", color=ROJO, fontsize=11, va="center")
|
| 779 |
+
c.plot([tp, tp], [0, yf], color=ROJO, ls="--", lw=1)
|
| 780 |
+
c.annotate("", xy=(tp, 0.08 * yf), xytext=(0, 0.08 * yf),
|
| 781 |
+
arrowprops=dict(arrowstyle="<->", color=ROJO, lw=1.2, shrinkA=0, shrinkB=0))
|
| 782 |
+
else:
|
| 783 |
+
base(c, "Pico: no hay", "La salida no se pasa del valor final:\nno hay $t_p$ y $M_p$ = 0 %")
|
| 784 |
+
_rotulo(c, "c")
|
| 785 |
+
|
| 786 |
+
# (d) ts
|
| 787 |
+
d = axs[1, 1]
|
| 788 |
+
ts = met.get("ts2", math.nan)
|
| 789 |
+
base(d, f"Establecimiento: $t_s$ = {_num(ts)} s (banda del 2 %)",
|
| 790 |
+
"desde $t_s$ la salida ya no sale\nde la banda del ±2 %" + formula("ts2", ""))
|
| 791 |
+
d.axhspan(yf * 0.98, yf * 1.02, color=AMBAR, alpha=0.25, lw=0)
|
| 792 |
+
if np.isfinite(ts):
|
| 793 |
+
d.axvspan(ts, tt[-1], color=AMBAR, alpha=0.08, lw=0)
|
| 794 |
+
m = tt >= ts
|
| 795 |
+
d.plot(tt[m], yn[m], color=AMBAR, lw=2.4, zorder=3)
|
| 796 |
+
d.plot([ts], [np.interp(ts, tt, yn)], "o", color=AMBAR, ms=7, zorder=5)
|
| 797 |
+
d.annotate("", xy=(ts, 0.08 * yf), xytext=(0, 0.08 * yf),
|
| 798 |
+
arrowprops=dict(arrowstyle="<->", color=AMBAR, lw=1.2, shrinkA=0, shrinkB=0))
|
| 799 |
+
_rotulo(d, "d")
|
| 800 |
+
for ax in axs.flat:
|
| 801 |
+
ax.set_ylabel("$y(t)$")
|
| 802 |
+
return fig
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def _mathtext(txt):
|
| 806 |
+
"""LaTeX de KaTeX -> mathtext; None si matplotlib no sabe dibujarlo."""
|
| 807 |
+
from matplotlib.mathtext import MathTextParser
|
| 808 |
+
t = (txt.replace(r"\dfrac", r"\frac").replace(r"\left[", "[").replace(r"\right]", "]")
|
| 809 |
+
.replace(r"\left(", "(").replace(r"\right)", ")").replace(r"\operatorname{sen}", r"\mathrm{sen}\,")
|
| 810 |
+
.replace(r"\text{c.c.}", r"\mathrm{c.c.}").replace(r"\quad", r"\ "))
|
| 811 |
+
try:
|
| 812 |
+
MathTextParser("agg").parse("$" + t + "$", dpi=72)
|
| 813 |
+
except Exception: # noqa: BLE001
|
| 814 |
+
return None
|
| 815 |
+
return "$" + t + "$"
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def fig_camino_laplace(r_tex, R_tex, G_tex, Y_tex, fs_tex, y_tex, *, w=11.0, h=4.6):
|
| 819 |
+
"""El método del tema en un diagrama: del tiempo a s, multiplicar, descomponer y volver."""
|
| 820 |
+
fig = Figure(figsize=(w, h))
|
| 821 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 822 |
+
ax.set_xlim(0, 11)
|
| 823 |
+
ax.set_ylim(0, 4.6)
|
| 824 |
+
ax.axis("off")
|
| 825 |
+
ax.add_patch(Rectangle((0.05, 2.55), 10.9, 1.95, fc="#f6f6f3", ec="none", zorder=0))
|
| 826 |
+
ax.add_patch(Rectangle((0.05, 0.1), 10.9, 2.3, fc="#eef3f8", ec="none", zorder=0))
|
| 827 |
+
ax.text(0.15, 4.38, "dominio del tiempo", fontsize=10, style="italic", color="#555", va="top")
|
| 828 |
+
ax.text(0.15, 0.18, "dominio de Laplace (variable $s$)", fontsize=10, style="italic", color=AZUL, va="bottom")
|
| 829 |
+
|
| 830 |
+
def caja(x, y, ancho, titulo, expr, generico):
|
| 831 |
+
ax.add_patch(Rectangle((x - ancho / 2, y - 0.5), ancho, 1.0, fc="white", ec=NEGRO, lw=1.0, zorder=2))
|
| 832 |
+
ax.text(x, y + 0.32, titulo, ha="center", va="center", fontsize=11.5, color="#444", zorder=3)
|
| 833 |
+
t = _mathtext(expr) if expr else None
|
| 834 |
+
if t is None:
|
| 835 |
+
t = generico
|
| 836 |
+
# tamaño de letra según lo que quepa en la caja (unos 0.085 cm de ancho por carácter a 10 pt)
|
| 837 |
+
n = max(len(re.sub(r"\\[a-zA-Z]+|[{}^_ ]", "", expr or generico)), 1)
|
| 838 |
+
ajuste = 10.0 * (ancho * 0.92) / (n * 0.075)
|
| 839 |
+
ax.text(x, y - 0.1, t, ha="center", va="center", fontsize=max(9.0, min(17.0, ajuste)), zorder=3)
|
| 840 |
+
|
| 841 |
+
def flecha(p0, p1, texto, lado="arriba"):
|
| 842 |
+
ax.annotate("", xy=p1, xytext=p0, arrowprops=dict(arrowstyle="-|>", color=NEGRO, lw=1.2, mutation_scale=13),
|
| 843 |
+
zorder=1)
|
| 844 |
+
xm, ym = (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2
|
| 845 |
+
if lado == "arriba":
|
| 846 |
+
ax.text(xm, ym + 0.12, texto, ha="center", va="bottom", fontsize=11.5, color=AZUL)
|
| 847 |
+
elif lado == "izq":
|
| 848 |
+
ax.text(xm - 0.1, ym, texto, ha="right", va="center", fontsize=11.5, color=AZUL)
|
| 849 |
+
else:
|
| 850 |
+
ax.text(xm + 0.1, ym, texto, ha="left", va="center", fontsize=11.5, color=AZUL)
|
| 851 |
+
|
| 852 |
+
caja(1.75, 3.45, 3.1, "① la entrada", "r(t)=" + r_tex, "$r(t)$")
|
| 853 |
+
caja(1.75, 1.15, 3.1, "② su transformada", "R(s)=" + R_tex, "$R(s)$")
|
| 854 |
+
caja(5.5, 1.15, 3.6, "③ la salida en $s$", "Y(s)=" + Y_tex, "$Y(s)=G(s)\\,R(s)$")
|
| 855 |
+
caja(9.25, 1.15, 3.2, "④ fracciones simples", "Y(s)=" + fs_tex, "$\\sum\\,A_i/(s-p_i)$")
|
| 856 |
+
caja(7.4, 3.45, 6.6, "⑤ la salida en el tiempo", "y(t)=" + y_tex, "$y(t)=\\sum$ modos")
|
| 857 |
+
flecha((1.75, 2.95), (1.75, 1.65), "tabla de\ntransformadas", "der")
|
| 858 |
+
flecha((3.3, 1.15), (3.7, 1.15), "")
|
| 859 |
+
gt = _mathtext("G(s)=" + G_tex)
|
| 860 |
+
ax.text(3.5, 1.95, "× " + (gt or "$G(s)$"), ha="center", va="bottom", fontsize=12.5, color=AZUL)
|
| 861 |
+
flecha((7.3, 1.15), (7.65, 1.15), "")
|
| 862 |
+
ax.text(7.47, 1.95, "descomponer", ha="center", va="bottom", fontsize=11.5, color=AZUL)
|
| 863 |
+
flecha((9.25, 1.65), (9.25, 2.95), " tabla al revés\n ($\\mathcal{L}^{-1}$)", "der")
|
| 864 |
+
return fig
|
nucleo.py
ADDED
|
@@ -0,0 +1,1135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Núcleo de cálculo del simulador del Tema 3.
|
| 2 |
+
|
| 3 |
+
Funciones de transferencia, polos y ceros, fracciones simples, vuelta al
|
| 4 |
+
tiempo, especificaciones de la respuesta a escalón, simulación del lazo con
|
| 5 |
+
PID y diseño por asignación de polos. La notación es la de los apuntes:
|
| 6 |
+
G(s), wn, zeta, sigma = zeta*wn, wd = wn*sqrt(1-zeta^2), beta = arccos(zeta).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from fractions import Fraction
|
| 10 |
+
import math
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import sympy as sp
|
| 15 |
+
from scipy import signal
|
| 16 |
+
from scipy.integrate import solve_ivp
|
| 17 |
+
from sympy.parsing.sympy_parser import (
|
| 18 |
+
convert_xor,
|
| 19 |
+
implicit_multiplication_application,
|
| 20 |
+
parse_expr,
|
| 21 |
+
standard_transformations,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
s, t = sp.symbols("s t")
|
| 25 |
+
Kp_, Ki_, Kd_ = sp.symbols("K_p K_i K_d")
|
| 26 |
+
|
| 27 |
+
_TRANS = standard_transformations + (implicit_multiplication_application, convert_xor)
|
| 28 |
+
_EPS = 1e-9
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# =====================================================================
|
| 32 |
+
# Formato de números y polinomios en LaTeX
|
| 33 |
+
# =====================================================================
|
| 34 |
+
def fmt(x, sig=4):
|
| 35 |
+
"""Número en LaTeX con `sig` cifras significativas."""
|
| 36 |
+
x = float(np.real(x))
|
| 37 |
+
if math.isnan(x):
|
| 38 |
+
return r"\text{—}"
|
| 39 |
+
if math.isinf(x):
|
| 40 |
+
return r"\infty" if x > 0 else r"-\infty"
|
| 41 |
+
if abs(x) < 1e-10:
|
| 42 |
+
return "0"
|
| 43 |
+
if abs(x - round(x)) < 1e-9 * max(1.0, abs(x)):
|
| 44 |
+
return str(int(round(x)))
|
| 45 |
+
txt = f"{x:.{sig}g}"
|
| 46 |
+
if "e" in txt:
|
| 47 |
+
m, e = txt.split("e")
|
| 48 |
+
return m + r"\cdot 10^{" + str(int(e)) + "}"
|
| 49 |
+
return txt
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def num(x, sig=4):
|
| 53 |
+
"""Número en texto plano (para etiquetas y tablas)."""
|
| 54 |
+
x = float(np.real(x))
|
| 55 |
+
if math.isnan(x):
|
| 56 |
+
return "—"
|
| 57 |
+
if math.isinf(x):
|
| 58 |
+
return "∞" if x > 0 else "−∞"
|
| 59 |
+
if abs(x) < 1e-10:
|
| 60 |
+
return "0"
|
| 61 |
+
if abs(x - round(x)) < 1e-9 * max(1.0, abs(x)):
|
| 62 |
+
return str(int(round(x)))
|
| 63 |
+
return f"{x:.{sig}g}"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def fmtq(x, maxden=100):
|
| 67 |
+
"""Como fmt, pero escribe la fracción exacta si el número es racional sencillo."""
|
| 68 |
+
x = float(np.real(x))
|
| 69 |
+
if abs(x) < 1e-10:
|
| 70 |
+
return "0"
|
| 71 |
+
fr = Fraction(x).limit_denominator(maxden)
|
| 72 |
+
# 6/5 o 91/25 se leen mejor como 1.2 y 3.64; 1/3, 1/2 o 15/4 se dejan como fracción
|
| 73 |
+
if fr.denominator % 5 == 0 and abs(round(x, 4) - x) < 1e-9 * max(1.0, abs(x)):
|
| 74 |
+
return fmt(x)
|
| 75 |
+
if fr.denominator > 1 and abs(float(fr) - x) < 1e-8 * max(1.0, abs(x)):
|
| 76 |
+
sg = "-" if fr < 0 else ""
|
| 77 |
+
return sg + r"\frac{" + str(abs(fr.numerator)) + "}{" + str(fr.denominator) + "}"
|
| 78 |
+
return fmt(x)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def fmtc(z, sig=4):
|
| 82 |
+
"""Número complejo en LaTeX: a + j b."""
|
| 83 |
+
z = complex(z)
|
| 84 |
+
re, im = z.real, z.imag
|
| 85 |
+
if abs(im) < 1e-9:
|
| 86 |
+
return fmt(re, sig)
|
| 87 |
+
jb = r"j\," + fmt(abs(im), sig)
|
| 88 |
+
if abs(re) < 1e-10:
|
| 89 |
+
return ("-" if im < 0 else "") + jb
|
| 90 |
+
return fmt(re, sig) + (" - " if im < 0 else " + ") + jb
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def racional(x):
|
| 94 |
+
"""Float -> Rational exacto (0.1 -> 1/10)."""
|
| 95 |
+
if isinstance(x, sp.Basic):
|
| 96 |
+
return sp.nsimplify(x, rational=True)
|
| 97 |
+
return sp.Rational(Fraction(float(x)).limit_denominator(10**9))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def poly_tex(c, var="s", q=True):
|
| 101 |
+
"""Polinomio (coeficientes de mayor a menor grado) en LaTeX."""
|
| 102 |
+
c = [float(np.real(a)) for a in np.atleast_1d(c)]
|
| 103 |
+
while len(c) > 1 and abs(c[0]) < 1e-12:
|
| 104 |
+
c.pop(0)
|
| 105 |
+
n = len(c) - 1
|
| 106 |
+
f = fmtq if q else fmt
|
| 107 |
+
out = ""
|
| 108 |
+
for i, a in enumerate(c):
|
| 109 |
+
p = n - i
|
| 110 |
+
if abs(a) < 1e-12:
|
| 111 |
+
continue
|
| 112 |
+
mag = f(abs(a))
|
| 113 |
+
v = "" if p == 0 else (var if p == 1 else var + "^{" + str(p) + "}")
|
| 114 |
+
if v and mag == "1":
|
| 115 |
+
body = v
|
| 116 |
+
elif v:
|
| 117 |
+
body = mag + (r"\," if mag.startswith(r"\frac") else "") + v
|
| 118 |
+
else:
|
| 119 |
+
body = mag
|
| 120 |
+
if not out:
|
| 121 |
+
out = ("-" if a < 0 else "") + body
|
| 122 |
+
else:
|
| 123 |
+
out += (" - " if a < 0 else " + ") + body
|
| 124 |
+
return out or "0"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def suma_tex(terminos):
|
| 128 |
+
"""Suma de términos (coeficiente, cuerpo) con los signos bien puestos."""
|
| 129 |
+
out = ""
|
| 130 |
+
for c, body in terminos:
|
| 131 |
+
c = float(c)
|
| 132 |
+
if abs(c) < 1e-10:
|
| 133 |
+
continue
|
| 134 |
+
mag = fmtq(abs(c))
|
| 135 |
+
if body:
|
| 136 |
+
if mag == "1":
|
| 137 |
+
txt = body
|
| 138 |
+
else:
|
| 139 |
+
txt = mag + r"\," + body
|
| 140 |
+
else:
|
| 141 |
+
txt = mag
|
| 142 |
+
if not out:
|
| 143 |
+
out = ("-" if c < 0 else "") + txt
|
| 144 |
+
else:
|
| 145 |
+
out += (" - " if c < 0 else " + ") + txt
|
| 146 |
+
return out or "0"
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def exp_tex(sigma, var="t"):
|
| 150 |
+
"""e^{sigma t} en LaTeX (vacío si sigma = 0)."""
|
| 151 |
+
if abs(sigma) < 1e-10:
|
| 152 |
+
return ""
|
| 153 |
+
a = fmt(abs(sigma))
|
| 154 |
+
a = "" if a == "1" else a
|
| 155 |
+
return "e^{" + ("-" if sigma < 0 else "") + a + var + "}"
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def trig_tex(nombre, w):
|
| 159 |
+
a = fmt(w)
|
| 160 |
+
a = "" if a == "1" else a
|
| 161 |
+
return r"\operatorname{" + nombre + "}" + a + "t" if nombre == "sen" else r"\cos " + a + "t"
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# =====================================================================
|
| 165 |
+
# Raíces con multiplicidad exacta
|
| 166 |
+
# =====================================================================
|
| 167 |
+
def _limpia(z):
|
| 168 |
+
z = complex(z)
|
| 169 |
+
re = 0.0 if abs(z.real) < 1e-9 else z.real
|
| 170 |
+
im = 0.0 if abs(z.imag) < 1e-9 * max(1.0, abs(z)) else z.imag
|
| 171 |
+
return complex(re, im)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def raices(P):
|
| 175 |
+
"""Raíces de un Poly de sympy con su multiplicidad: [(raíz, m)].
|
| 176 |
+
|
| 177 |
+
La multiplicidad sale exacta de la factorización sobre los racionales
|
| 178 |
+
(los factores irreducibles no tienen raíces repetidas), lo que permite
|
| 179 |
+
distinguir sin ambigüedad el caso crítico zeta = 1 del sobreamortiguado.
|
| 180 |
+
"""
|
| 181 |
+
P = sp.Poly(P, s)
|
| 182 |
+
if P.degree() <= 0:
|
| 183 |
+
return []
|
| 184 |
+
_, facs = P.factor_list()
|
| 185 |
+
out = []
|
| 186 |
+
for f, m in facs:
|
| 187 |
+
f = sp.Poly(f, s)
|
| 188 |
+
d = f.degree()
|
| 189 |
+
if d == 0:
|
| 190 |
+
continue
|
| 191 |
+
if d == 1:
|
| 192 |
+
a, b = (complex(c) for c in f.all_coeffs())
|
| 193 |
+
rs = [-b / a]
|
| 194 |
+
elif d == 2:
|
| 195 |
+
rs = np.roots([complex(c) for c in f.all_coeffs()])
|
| 196 |
+
else:
|
| 197 |
+
rs = [complex(r) for r in f.nroots(n=15, maxsteps=200)]
|
| 198 |
+
out += [(_limpia(r), m) for r in rs]
|
| 199 |
+
out.sort(key=lambda z: (-round(z[0].real, 9), -z[0].imag))
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def agrupa(rs):
|
| 204 |
+
"""Deja una sola raíz por par complejo conjugado: [(p, m, 'real'|'par')]."""
|
| 205 |
+
out = []
|
| 206 |
+
for p, m in rs:
|
| 207 |
+
if abs(p.imag) < 1e-12:
|
| 208 |
+
out.append((p, m, "real"))
|
| 209 |
+
elif p.imag > 0:
|
| 210 |
+
out.append((p, m, "par"))
|
| 211 |
+
return out
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def lista_raices_tex(rs, nombre="s"):
|
| 215 |
+
"""'s_1 = -1,\\ s_{2,3} = -1 \\pm j3' a partir de raices()."""
|
| 216 |
+
partes, k = [], 1
|
| 217 |
+
for p, m, tipo in agrupa(rs):
|
| 218 |
+
extra = "" if m == 1 else (r"\ \text{(doble)}" if m == 2 else r"\ \text{(" + str(m) + "ple)}")
|
| 219 |
+
if tipo == "real":
|
| 220 |
+
idx = str(k) if m == 1 else ",".join(str(k + i) for i in range(m))
|
| 221 |
+
partes.append(nombre + "_{" + idx + "} = " + fmt(p.real) + extra)
|
| 222 |
+
k += m
|
| 223 |
+
else:
|
| 224 |
+
idx = f"{k},{k + 1}"
|
| 225 |
+
re = fmt(p.real) if abs(p.real) > 1e-10 else ""
|
| 226 |
+
partes.append(nombre + "_{" + idx + "} = " + re + r" \pm j\," + fmt(p.imag) + extra)
|
| 227 |
+
k += 2 * m
|
| 228 |
+
return r",\quad ".join(partes) if partes else r"\text{ninguno}"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def factor_tex(lc, rs, var="s"):
|
| 232 |
+
"""Forma factorizada lc·Π(...) a partir de las raíces."""
|
| 233 |
+
partes = []
|
| 234 |
+
for p, m, tipo in agrupa(rs):
|
| 235 |
+
if tipo == "real":
|
| 236 |
+
if abs(p.real) < 1e-12:
|
| 237 |
+
f = var
|
| 238 |
+
else:
|
| 239 |
+
f = "(" + var + (" + " if p.real < 0 else " - ") + fmtq(abs(p.real)) + ")"
|
| 240 |
+
else:
|
| 241 |
+
a, w2 = -p.real, p.imag ** 2
|
| 242 |
+
if abs(a) < 1e-12:
|
| 243 |
+
f = "(" + var + "^{2} + " + fmtq(w2) + ")"
|
| 244 |
+
else:
|
| 245 |
+
f = r"\left[(" + var + (" + " if a > 0 else " - ") + fmtq(abs(a)) + ")^{2} + " + fmtq(w2) + r"\right]"
|
| 246 |
+
if m > 1:
|
| 247 |
+
f += "^{" + str(m) + "}"
|
| 248 |
+
partes.append(f)
|
| 249 |
+
if len(partes) == 1 and abs(lc - 1) < 1e-12:
|
| 250 |
+
f = partes[0]
|
| 251 |
+
if f.startswith("(") and f.endswith(")"):
|
| 252 |
+
return f[1:-1]
|
| 253 |
+
if f.startswith(r"\left[") and f.endswith(r"\right]"):
|
| 254 |
+
return f[6:-7]
|
| 255 |
+
lead = "" if abs(lc - 1) < 1e-12 else ("-" if abs(lc + 1) < 1e-12 else fmtq(lc))
|
| 256 |
+
cuerpo = "".join(partes)
|
| 257 |
+
if not cuerpo:
|
| 258 |
+
return fmtq(lc)
|
| 259 |
+
return lead + (r"\," if lead and lead != "-" else "") + cuerpo
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# =====================================================================
|
| 263 |
+
# Función de transferencia
|
| 264 |
+
# =====================================================================
|
| 265 |
+
class FT:
|
| 266 |
+
"""Cociente de polinomios en s con coeficientes racionales exactos."""
|
| 267 |
+
|
| 268 |
+
def __init__(self, num_, den_):
|
| 269 |
+
N = sp.Poly(num_, s)
|
| 270 |
+
D = sp.Poly(den_, s)
|
| 271 |
+
if D.is_zero:
|
| 272 |
+
raise ValueError("El denominador es nulo.")
|
| 273 |
+
if N.is_zero:
|
| 274 |
+
raise ValueError("La función de transferencia es idénticamente nula.")
|
| 275 |
+
if D.LC() < 0:
|
| 276 |
+
N, D = -N, -D
|
| 277 |
+
self.N, self.D = N, D
|
| 278 |
+
|
| 279 |
+
# --- construcción ---
|
| 280 |
+
@classmethod
|
| 281 |
+
def coefs(cls, num_, den_):
|
| 282 |
+
N = sum(racional(c) * s ** i for i, c in enumerate(reversed(list(num_))))
|
| 283 |
+
D = sum(racional(c) * s ** i for i, c in enumerate(reversed(list(den_))))
|
| 284 |
+
return cls(N, D)
|
| 285 |
+
|
| 286 |
+
@classmethod
|
| 287 |
+
def expr(cls, e):
|
| 288 |
+
e = sp.nsimplify(sp.sympify(e), rational=True)
|
| 289 |
+
n_, d_ = sp.fraction(sp.together(e))
|
| 290 |
+
return cls(sp.expand(n_), sp.expand(d_))
|
| 291 |
+
|
| 292 |
+
# --- datos numéricos ---
|
| 293 |
+
@property
|
| 294 |
+
def num(self):
|
| 295 |
+
return np.array([float(c) for c in self.N.all_coeffs()])
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def den(self):
|
| 299 |
+
return np.array([float(c) for c in self.D.all_coeffs()])
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def n(self):
|
| 303 |
+
return self.D.degree()
|
| 304 |
+
|
| 305 |
+
@property
|
| 306 |
+
def m(self):
|
| 307 |
+
return self.N.degree()
|
| 308 |
+
|
| 309 |
+
def polos(self):
|
| 310 |
+
return raices(self.D)
|
| 311 |
+
|
| 312 |
+
def ceros(self):
|
| 313 |
+
return raices(self.N)
|
| 314 |
+
|
| 315 |
+
def polos_np(self):
|
| 316 |
+
return np.array([p for p, mm in self.polos() for _ in range(mm)], dtype=complex)
|
| 317 |
+
|
| 318 |
+
def ceros_np(self):
|
| 319 |
+
return np.array([p for p, mm in self.ceros() for _ in range(mm)], dtype=complex)
|
| 320 |
+
|
| 321 |
+
def tipo(self):
|
| 322 |
+
"""Número de polos en el origen."""
|
| 323 |
+
c = self.den
|
| 324 |
+
k = 0
|
| 325 |
+
while k < len(c) - 1 and abs(c[-1 - k]) < 1e-14:
|
| 326 |
+
k += 1
|
| 327 |
+
return k
|
| 328 |
+
|
| 329 |
+
def ganancia_estatica(self):
|
| 330 |
+
if self.tipo() > 0:
|
| 331 |
+
return math.inf
|
| 332 |
+
return float(self.N.eval(0) / self.D.eval(0))
|
| 333 |
+
|
| 334 |
+
def propia(self):
|
| 335 |
+
return self.m <= self.n
|
| 336 |
+
|
| 337 |
+
def simplificada(self):
|
| 338 |
+
g = sp.gcd(self.N, self.D)
|
| 339 |
+
if g.degree() == 0:
|
| 340 |
+
return self, None
|
| 341 |
+
return FT(sp.quo(self.N, g), sp.quo(self.D, g)), g
|
| 342 |
+
|
| 343 |
+
def sym(self):
|
| 344 |
+
return self.N.as_expr() / self.D.as_expr()
|
| 345 |
+
|
| 346 |
+
# --- LaTeX ---
|
| 347 |
+
def tex(self):
|
| 348 |
+
nu, de = self.num, self.den
|
| 349 |
+
if self.D.degree() == 0:
|
| 350 |
+
return poly_tex(nu / de[0])
|
| 351 |
+
todos = np.abs(np.concatenate([nu, de]))
|
| 352 |
+
todos = todos[todos > 0]
|
| 353 |
+
if todos.max() > 1e4 or todos.min() < 1e-4:
|
| 354 |
+
# coeficientes de ganancias con muchos decimales: se normaliza el denominador
|
| 355 |
+
nu, de = nu / de[0], de / de[0]
|
| 356 |
+
return r"\dfrac{" + poly_tex(nu, q=False) + "}{" + poly_tex(de, q=False) + "}"
|
| 357 |
+
return r"\dfrac{" + poly_tex(nu) + "}{" + poly_tex(de) + "}"
|
| 358 |
+
|
| 359 |
+
def tex_factor(self):
|
| 360 |
+
lcn, lcd = float(self.N.LC()), float(self.D.LC())
|
| 361 |
+
k = lcn / lcd
|
| 362 |
+
top = factor_tex(1.0, self.ceros()) if self.m > 0 else "1"
|
| 363 |
+
bot = factor_tex(1.0, self.polos()) if self.n > 0 else "1"
|
| 364 |
+
lead = "" if abs(k - 1) < 1e-12 else fmtq(k)
|
| 365 |
+
if bot == "1":
|
| 366 |
+
return lead + top if top != "1" else (lead or "1")
|
| 367 |
+
if top == "1":
|
| 368 |
+
if r"\frac" in lead:
|
| 369 |
+
return lead + r"\cdot\dfrac{1}{" + bot + "}"
|
| 370 |
+
return r"\dfrac{" + (lead or "1") + "}{" + bot + "}"
|
| 371 |
+
return (lead + r"\," if lead else "") + r"\dfrac{" + top + "}{" + bot + "}"
|
| 372 |
+
|
| 373 |
+
# --- álgebra ---
|
| 374 |
+
def __mul__(self, o):
|
| 375 |
+
return FT(self.N * o.N, self.D * o.D)
|
| 376 |
+
|
| 377 |
+
def evalua(self, z):
|
| 378 |
+
return complex(np.polyval(self.num, z) / np.polyval(self.den, z))
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
_TOKEN = re.compile(r"\s*(?:(\d+\.?\d*|\.\d+)|([A-Za-z]+)|([-+*/^()]))")
|
| 382 |
+
_FUNCIONES = {"exp": sp.exp, "sin": sp.sin, "sen": sp.sin, "cos": sp.cos, "sqrt": sp.sqrt,
|
| 383 |
+
"pi": sp.pi, "ln": sp.log, "log": sp.log, "e": sp.E}
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def parse_seguro(texto, variables, permitidas=()):
|
| 387 |
+
"""Analiza una expresión del usuario sin ejecutar nada que no sea aritmética.
|
| 388 |
+
|
| 389 |
+
La app es pública: el texto se comprueba con una lista blanca de símbolos
|
| 390 |
+
antes de pasarlo a SymPy (que internamente usa eval), y se rechazan las
|
| 391 |
+
potencias desmesuradas que colgarían el servidor.
|
| 392 |
+
"""
|
| 393 |
+
txt = (str(texto).replace("·", "*").replace("−", "-").replace("²", "^2").replace("³", "^3")
|
| 394 |
+
.replace("**", "^").replace(",", ".").strip())
|
| 395 |
+
if not txt:
|
| 396 |
+
raise ValueError("Expresión vacía.")
|
| 397 |
+
if len(txt) > 160:
|
| 398 |
+
raise ValueError("Expresión demasiado larga.")
|
| 399 |
+
pos = 0
|
| 400 |
+
nombres = set(variables) | set(permitidas)
|
| 401 |
+
while pos < len(txt):
|
| 402 |
+
mt = _TOKEN.match(txt, pos)
|
| 403 |
+
if not mt or mt.end() == pos:
|
| 404 |
+
raise ValueError(f"Carácter no permitido en «{texto}»: «{txt[pos:].strip()[:1]}».")
|
| 405 |
+
if mt.group(2) and mt.group(2) not in nombres:
|
| 406 |
+
raise ValueError(f"No se reconoce «{mt.group(2)}» en «{texto}».")
|
| 407 |
+
pos = mt.end()
|
| 408 |
+
if txt[pos:].strip() == "":
|
| 409 |
+
break
|
| 410 |
+
loc = {v: sp.Symbol(v) for v in variables}
|
| 411 |
+
loc.update({k: _FUNCIONES[k] for k in permitidas})
|
| 412 |
+
try:
|
| 413 |
+
arbol = parse_expr(txt, local_dict=loc, transformations=_TRANS, evaluate=False)
|
| 414 |
+
except Exception:
|
| 415 |
+
raise ValueError(f"No se entiende «{texto}».") from None
|
| 416 |
+
for nodo in sp.preorder_traversal(arbol):
|
| 417 |
+
if isinstance(nodo, sp.Pow):
|
| 418 |
+
ex = nodo.exp
|
| 419 |
+
if not ex.is_Number or abs(float(ex)) > 20:
|
| 420 |
+
raise ValueError("Solo se admiten exponentes numéricos pequeños (|n| ≤ 20).")
|
| 421 |
+
elif nodo.is_Number and abs(float(nodo)) > 1e9:
|
| 422 |
+
raise ValueError("Número demasiado grande.")
|
| 423 |
+
return sp.sympify(arbol)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def parse_ft(texto):
|
| 427 |
+
"""Texto del usuario -> FT. Admite 2s+1, s(s+1), s^2, 0,5 ..."""
|
| 428 |
+
if not texto or not str(texto).strip():
|
| 429 |
+
raise ValueError("Escriba una función de transferencia, por ejemplo 10/(s^2+2s+10).")
|
| 430 |
+
try:
|
| 431 |
+
e = parse_seguro(texto, ["s"]).subs(sp.Symbol("s"), s)
|
| 432 |
+
except ValueError as err:
|
| 433 |
+
raise ValueError(
|
| 434 |
+
f"{err} Use s como variable, * para multiplicar y ^ para potencias. Ejemplo: 4/(s*(s+2))."
|
| 435 |
+
) from None
|
| 436 |
+
libres = e.free_symbols - {s}
|
| 437 |
+
if libres:
|
| 438 |
+
raise ValueError("Solo se admite la variable s (y números). Sobra: " + ", ".join(map(str, libres)) + ".")
|
| 439 |
+
e = sp.nsimplify(e, rational=True)
|
| 440 |
+
n_, d_ = sp.fraction(sp.together(e))
|
| 441 |
+
if not (n_.is_polynomial(s) and d_.is_polynomial(s)):
|
| 442 |
+
raise ValueError("G(s) debe ser un cociente de polinomios en s (este simulador no trata retardos e^{-Ls}).")
|
| 443 |
+
if sp.expand(n_) == 0:
|
| 444 |
+
raise ValueError("La función es idénticamente nula.")
|
| 445 |
+
return FT(sp.expand(n_), sp.expand(d_))
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# =====================================================================
|
| 449 |
+
# Fracciones simples y vuelta al tiempo
|
| 450 |
+
# =====================================================================
|
| 451 |
+
def fracciones_simples(Y):
|
| 452 |
+
"""Descompone Y(s) = N/D. Devuelve (parte_entera, modos).
|
| 453 |
+
|
| 454 |
+
Cada modo es un dict con el polo p, su multiplicidad m, el tipo
|
| 455 |
+
('real' o 'par') y los coeficientes A_k de A_k/(s-p)^k, k = 1..m.
|
| 456 |
+
Los coeficientes se obtienen identificando potencias de s, que es el
|
| 457 |
+
paso 4 del método de los apuntes y vale también con polos múltiples.
|
| 458 |
+
"""
|
| 459 |
+
q, r = sp.div(Y.N, Y.D)
|
| 460 |
+
rs = Y.polos()
|
| 461 |
+
n = Y.D.degree()
|
| 462 |
+
lc = float(Y.D.LC())
|
| 463 |
+
cols, claves = [], []
|
| 464 |
+
for i, (p, m) in enumerate(rs):
|
| 465 |
+
for k in range(1, m + 1):
|
| 466 |
+
lista = []
|
| 467 |
+
for j, (pj, mj) in enumerate(rs):
|
| 468 |
+
lista += [pj] * (mj if j != i else m - k)
|
| 469 |
+
pol = lc * (np.poly(lista) if lista else np.array([1.0]))
|
| 470 |
+
col = np.zeros(n, complex)
|
| 471 |
+
col[n - len(pol):] = pol
|
| 472 |
+
cols.append(col)
|
| 473 |
+
claves.append((i, k))
|
| 474 |
+
rv = np.zeros(n, complex)
|
| 475 |
+
if not r.is_zero:
|
| 476 |
+
rc = [complex(c) for c in r.all_coeffs()]
|
| 477 |
+
rv[n - len(rc):] = rc
|
| 478 |
+
A = np.linalg.solve(np.array(cols).T, rv) if n > 0 else np.array([])
|
| 479 |
+
modos = []
|
| 480 |
+
for i, (p, m) in enumerate(rs):
|
| 481 |
+
if p.imag < -1e-12:
|
| 482 |
+
continue
|
| 483 |
+
coefs = [A[claves.index((i, k))] for k in range(1, m + 1)]
|
| 484 |
+
tipo = "real" if abs(p.imag) < 1e-12 else "par"
|
| 485 |
+
if tipo == "real":
|
| 486 |
+
coefs = [complex(c.real, 0) for c in coefs]
|
| 487 |
+
modos.append({"p": p, "m": m, "tipo": tipo, "A": coefs})
|
| 488 |
+
entera = [float(c) for c in q.all_coeffs()] if not q.is_zero else []
|
| 489 |
+
return entera, modos
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def _den_modo_tex(p, k, tipo):
|
| 493 |
+
if tipo == "real":
|
| 494 |
+
if abs(p.real) < 1e-12:
|
| 495 |
+
base = "s"
|
| 496 |
+
else:
|
| 497 |
+
base = "(s" + (" + " if p.real < 0 else " - ") + fmtq(abs(p.real)) + ")"
|
| 498 |
+
if k == 1:
|
| 499 |
+
return base[1:-1] if base.startswith("(") else base
|
| 500 |
+
return base + "^{" + str(k) + "}" if base != "s" else "s^{" + str(k) + "}"
|
| 501 |
+
a, w = -p.real, p.imag
|
| 502 |
+
cuad = ("s" if abs(a) < 1e-12 else "(s" + (" + " if a > 0 else " - ") + fmtq(abs(a)) + ")") + "^{2} + " + fmtq(w * w)
|
| 503 |
+
return cuad if k == 1 else r"\left[" + cuad + r"\right]^{" + str(k) + "}"
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def fracciones_tex(entera, modos):
|
| 507 |
+
"""Y(s) escrita como suma de fracciones simples (en LaTeX)."""
|
| 508 |
+
partes = []
|
| 509 |
+
if entera:
|
| 510 |
+
partes.append(poly_tex(entera))
|
| 511 |
+
for md in modos:
|
| 512 |
+
p, tipo = md["p"], md["tipo"]
|
| 513 |
+
for k, A in enumerate(md["A"], start=1):
|
| 514 |
+
if abs(A) < 1e-10:
|
| 515 |
+
continue
|
| 516 |
+
if tipo == "real":
|
| 517 |
+
c = A.real
|
| 518 |
+
partes.append(("-" if c < 0 else "+") + r"\dfrac{" + fmtq(abs(c)) + "}{" + _den_modo_tex(p, k, tipo) + "}")
|
| 519 |
+
elif k == 1:
|
| 520 |
+
B = 2 * A.real
|
| 521 |
+
C = -2 * (A * np.conj(p)).real
|
| 522 |
+
neg = B < -1e-10 or (abs(B) <= 1e-10 and C < 0)
|
| 523 |
+
if neg:
|
| 524 |
+
B, C = -B, -C
|
| 525 |
+
nume = poly_tex([B, C]) if abs(B) > 1e-10 else fmtq(C)
|
| 526 |
+
partes.append(("-" if neg else "+") + r"\dfrac{" + nume + "}{" + _den_modo_tex(p, 1, tipo) + "}")
|
| 527 |
+
else:
|
| 528 |
+
partes.append(r"+\dfrac{" + fmtc(A) + "}{(s - (" + fmtc(p) + "))^{" + str(k) + r"}} + \text{c.c.}")
|
| 529 |
+
txt = " ".join(partes).strip()
|
| 530 |
+
if txt.startswith("+"):
|
| 531 |
+
txt = txt[1:]
|
| 532 |
+
return txt or "0"
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def terminos_tiempo(modos):
|
| 536 |
+
"""Lista de términos (coef, potencia de t, sigma, omega, 'exp'|'cos'|'sen', índice de modo)."""
|
| 537 |
+
out = []
|
| 538 |
+
for i, md in enumerate(modos):
|
| 539 |
+
p = md["p"]
|
| 540 |
+
for k, A in enumerate(md["A"], start=1):
|
| 541 |
+
f = math.factorial(k - 1)
|
| 542 |
+
if md["tipo"] == "real":
|
| 543 |
+
out.append((A.real / f, k - 1, p.real, 0.0, "exp", i))
|
| 544 |
+
else:
|
| 545 |
+
out.append((2 * A.real / f, k - 1, p.real, p.imag, "cos", i))
|
| 546 |
+
out.append((-2 * A.imag / f, k - 1, p.real, p.imag, "sen", i))
|
| 547 |
+
return [x for x in out if abs(x[0]) > 1e-12]
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def evalua_terminos(terms, tt, n_modos):
|
| 551 |
+
"""Contribución de cada modo y suma total sobre la malla tt."""
|
| 552 |
+
tt = np.asarray(tt, float)
|
| 553 |
+
modos = np.zeros((n_modos, tt.size))
|
| 554 |
+
with np.errstate(over="ignore", invalid="ignore"):
|
| 555 |
+
for c, k, sg, w, kind, i in terms:
|
| 556 |
+
base = c * tt ** k * np.exp(sg * tt)
|
| 557 |
+
if kind == "cos":
|
| 558 |
+
base = base * np.cos(w * tt)
|
| 559 |
+
elif kind == "sen":
|
| 560 |
+
base = base * np.sin(w * tt)
|
| 561 |
+
modos[i] += base
|
| 562 |
+
return modos, modos.sum(axis=0)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def tiempo_tex(entera, modos):
|
| 566 |
+
"""y(t) en LaTeX a partir de los modos, agrupando seno y coseno de cada par."""
|
| 567 |
+
terms = []
|
| 568 |
+
for j, c in enumerate(reversed(entera or [])):
|
| 569 |
+
terms.append((c, r"\delta(t)" if j == 0 else r"\delta^{(" + str(j) + r")}(t)"))
|
| 570 |
+
for i, md in enumerate(modos):
|
| 571 |
+
p = md["p"]
|
| 572 |
+
for k, A in enumerate(md["A"], start=1):
|
| 573 |
+
f = math.factorial(k - 1)
|
| 574 |
+
tpow = "" if k == 1 else ("t" if k == 2 else "t^{" + str(k - 1) + "}")
|
| 575 |
+
if md["tipo"] == "real":
|
| 576 |
+
body = (tpow + (r"\," if tpow and exp_tex(p.real) else "") + exp_tex(p.real))
|
| 577 |
+
terms.append((A.real / f, body))
|
| 578 |
+
else:
|
| 579 |
+
B, D = 2 * A.real / f, -2 * A.imag / f
|
| 580 |
+
e = exp_tex(p.real)
|
| 581 |
+
pref = tpow + (r"\," if tpow and e else "") + e
|
| 582 |
+
cos_, sen_ = trig_tex("cos", p.imag), trig_tex("sen", p.imag)
|
| 583 |
+
if abs(B) > 1e-10 and abs(D) > 1e-10:
|
| 584 |
+
r = D / B
|
| 585 |
+
dentro = cos_ + (" - " if r < 0 else " + ") + (fmtq(abs(r)) + r"\," if fmtq(abs(r)) != "1" else "") + sen_
|
| 586 |
+
terms.append((B, pref + r"\left(" + dentro + r"\right)"))
|
| 587 |
+
elif abs(B) > 1e-10:
|
| 588 |
+
terms.append((B, pref + cos_))
|
| 589 |
+
else:
|
| 590 |
+
terms.append((D, pref + sen_))
|
| 591 |
+
return suma_tex(terms)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
# =====================================================================
|
| 595 |
+
# Señales de entrada
|
| 596 |
+
# =====================================================================
|
| 597 |
+
ENTRADAS = ["Escalón", "Impulso", "Rampa", "Parábola", "Senoidal", "Exponencial", "Personalizada"]
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class Entrada:
|
| 601 |
+
def __init__(self, nombre, r_tex, R, r_num, limite, es_escalon=False, impulso=False, w=None):
|
| 602 |
+
self.nombre, self.r_tex, self.R, self.r_num = nombre, r_tex, R, r_num
|
| 603 |
+
self.limite, self.es_escalon, self.impulso, self.w = limite, es_escalon, impulso, w
|
| 604 |
+
|
| 605 |
+
def ft(self):
|
| 606 |
+
return FT.expr(self.R)
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def crea_entrada(tipo, A=1.0, w=1.0, a=1.0, texto=""):
|
| 610 |
+
A = racional(A)
|
| 611 |
+
Af = float(A)
|
| 612 |
+
At = "" if Af == 1 else fmtq(Af) + r"\,"
|
| 613 |
+
if tipo == "Escalón":
|
| 614 |
+
return Entrada("escalón", At + r"u(t)", A / s, lambda x: Af * np.ones_like(x), Af, es_escalon=True)
|
| 615 |
+
if tipo == "Impulso":
|
| 616 |
+
return Entrada("impulso", At + r"\delta(t)", A, lambda x: np.zeros_like(x), 0.0, impulso=True)
|
| 617 |
+
if tipo == "Rampa":
|
| 618 |
+
return Entrada("rampa", At + "t", A / s ** 2, lambda x: Af * x, None)
|
| 619 |
+
if tipo == "Parábola":
|
| 620 |
+
return Entrada("parábola", At + r"\dfrac{t^{2}}{2}", A / s ** 3, lambda x: Af * x ** 2 / 2, None)
|
| 621 |
+
if tipo == "Senoidal":
|
| 622 |
+
wr = racional(w)
|
| 623 |
+
wf = float(wr)
|
| 624 |
+
if wf <= 0:
|
| 625 |
+
raise ValueError("La frecuencia de la senoidal debe ser positiva.")
|
| 626 |
+
return Entrada("senoidal", At + trig_tex("sen", wf), A * wr / (s ** 2 + wr ** 2),
|
| 627 |
+
lambda x: Af * np.sin(wf * x), None, w=wf)
|
| 628 |
+
if tipo == "Exponencial":
|
| 629 |
+
ar = racional(a)
|
| 630 |
+
af = float(ar)
|
| 631 |
+
return Entrada("exponencial", At + (exp_tex(-af) or "1"), A / (s + ar),
|
| 632 |
+
lambda x: Af * np.exp(-af * x), 0.0 if af > 0 else None)
|
| 633 |
+
# personalizada
|
| 634 |
+
if not texto or not texto.strip():
|
| 635 |
+
raise ValueError("Escriba r(t), por ejemplo 2 - exp(-t) o 1 + 0.5*t.")
|
| 636 |
+
e = parse_seguro(texto, ["t"], ("exp", "sin", "sen", "cos", "sqrt", "pi")).subs(sp.Symbol("t"), t)
|
| 637 |
+
if e.free_symbols - {t}:
|
| 638 |
+
raise ValueError("r(t) solo puede depender de t.")
|
| 639 |
+
e = sp.nsimplify(e, rational=True)
|
| 640 |
+
try:
|
| 641 |
+
R = sp.laplace_transform(e, t, s, noconds=True)
|
| 642 |
+
except Exception:
|
| 643 |
+
raise ValueError("No se ha podido transformar esa r(t).") from None
|
| 644 |
+
R = sp.simplify(R)
|
| 645 |
+
n_, d_ = sp.fraction(sp.together(R))
|
| 646 |
+
if not (n_.is_polynomial(s) and d_.is_polynomial(s)):
|
| 647 |
+
raise ValueError("La transformada de esa r(t) no es racional. Combine escalones, rampas, "
|
| 648 |
+
"potencias de t, exponenciales, senos y cosenos.")
|
| 649 |
+
f = sp.lambdify(t, e, "numpy")
|
| 650 |
+
try:
|
| 651 |
+
lim = float(sp.limit(e, t, sp.oo))
|
| 652 |
+
except (TypeError, ValueError):
|
| 653 |
+
lim = None
|
| 654 |
+
return Entrada("personalizada", sp.latex(e).replace(r"\sin", r"\operatorname{sen}"), R,
|
| 655 |
+
lambda x: np.broadcast_to(np.asarray(f(x), float), np.shape(x)).copy(), lim)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
# =====================================================================
|
| 659 |
+
# Caracterización del sistema
|
| 660 |
+
# =====================================================================
|
| 661 |
+
def estabilidad(rs):
|
| 662 |
+
"""'estable', 'límite' o 'inestable' a partir de raices()."""
|
| 663 |
+
est = "estable"
|
| 664 |
+
for p, m in rs:
|
| 665 |
+
if p.real > 1e-9:
|
| 666 |
+
return "inestable"
|
| 667 |
+
if abs(p.real) <= 1e-9:
|
| 668 |
+
if m > 1:
|
| 669 |
+
return "inestable"
|
| 670 |
+
est = "límite"
|
| 671 |
+
return est
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def segundo_orden(den):
|
| 675 |
+
"""wn y zeta del denominador a2 s^2 + a1 s + a0 (None si no procede)."""
|
| 676 |
+
a2, a1, a0 = [float(c) for c in den]
|
| 677 |
+
if a2 == 0 or a0 / a2 <= 0:
|
| 678 |
+
return None
|
| 679 |
+
wn = math.sqrt(a0 / a2)
|
| 680 |
+
zeta = a1 / (2 * a2 * wn)
|
| 681 |
+
return wn, zeta
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def parametros_2o(wn, zeta):
|
| 685 |
+
"""Tabla central de los apuntes: fórmulas de la respuesta de segundo orden."""
|
| 686 |
+
d = {"wn": wn, "zeta": zeta, "sigma": zeta * wn}
|
| 687 |
+
if 0 < zeta < 1:
|
| 688 |
+
wd = wn * math.sqrt(1 - zeta ** 2)
|
| 689 |
+
beta = math.acos(zeta)
|
| 690 |
+
d.update(
|
| 691 |
+
wd=wd, beta=beta,
|
| 692 |
+
td=(1 + 0.7 * zeta) / wn,
|
| 693 |
+
tr=(math.pi - beta) / wd,
|
| 694 |
+
tp=math.pi / wd,
|
| 695 |
+
Mp=100 * math.exp(-math.pi * zeta / math.sqrt(1 - zeta ** 2)),
|
| 696 |
+
ts2=4 / (zeta * wn), ts5=3 / (zeta * wn),
|
| 697 |
+
nosc=2 / math.pi * math.sqrt(1 - zeta ** 2) / zeta,
|
| 698 |
+
)
|
| 699 |
+
elif zeta == 0:
|
| 700 |
+
d.update(wd=wn, beta=math.pi / 2, tp=math.pi / wn, Mp=100.0)
|
| 701 |
+
return d
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
def zeta_de_Mp(Mp_pct):
|
| 705 |
+
"""Fórmula inversa: zeta = -ln Mp / sqrt(pi^2 + ln^2 Mp)."""
|
| 706 |
+
M = Mp_pct / 100
|
| 707 |
+
if M <= 0:
|
| 708 |
+
return 1.0
|
| 709 |
+
L = math.log(M)
|
| 710 |
+
return -L / math.sqrt(math.pi ** 2 + L ** 2)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def regimen(zeta):
|
| 714 |
+
if abs(zeta) < 1e-9:
|
| 715 |
+
return "no amortiguado"
|
| 716 |
+
if zeta < 0:
|
| 717 |
+
return "inestable (amortiguamiento negativo)"
|
| 718 |
+
if zeta < 1 - 1e-9:
|
| 719 |
+
return "subamortiguado"
|
| 720 |
+
if abs(zeta - 1) <= 1e-9:
|
| 721 |
+
return "crítico"
|
| 722 |
+
return "sobreamortiguado"
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def dominantes(rs):
|
| 726 |
+
"""Polo (o par) dominante estable y cociente r de los apuntes."""
|
| 727 |
+
estables = [(p, m) for p, m in rs if p.real < -1e-9]
|
| 728 |
+
if not estables:
|
| 729 |
+
return None
|
| 730 |
+
estables.sort(key=lambda z: -z[0].real)
|
| 731 |
+
pd = estables[0][0]
|
| 732 |
+
resto = [p for p, _ in estables if abs(p.real - pd.real) > 1e-9 or abs(abs(p.imag) - abs(pd.imag)) > 1e-9]
|
| 733 |
+
r = (min(-p.real for p in resto) / -pd.real) if resto else math.inf
|
| 734 |
+
return pd, r
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
# =====================================================================
|
| 738 |
+
# Medidas sobre la respuesta a escalón
|
| 739 |
+
# =====================================================================
|
| 740 |
+
def metricas_escalon(tt, y, yinf):
|
| 741 |
+
"""td, tr, tp, Mp, ts(2 %), ts(5 %) medidos sobre la curva."""
|
| 742 |
+
if yinf is None or not np.isfinite(yinf) or abs(yinf) < 1e-12 or not np.all(np.isfinite(y)):
|
| 743 |
+
return None
|
| 744 |
+
yn = np.asarray(y) / yinf
|
| 745 |
+
|
| 746 |
+
def cruce(nivel):
|
| 747 |
+
idx = np.nonzero(yn >= nivel)[0]
|
| 748 |
+
if idx.size == 0:
|
| 749 |
+
return math.nan
|
| 750 |
+
i = idx[0]
|
| 751 |
+
if i == 0:
|
| 752 |
+
return tt[0]
|
| 753 |
+
y0, y1 = yn[i - 1], yn[i]
|
| 754 |
+
return tt[i - 1] + (nivel - y0) * (tt[i] - tt[i - 1]) / (y1 - y0)
|
| 755 |
+
|
| 756 |
+
out = {"td": cruce(0.5)}
|
| 757 |
+
imax = int(np.argmax(yn))
|
| 758 |
+
if yn[imax] > 1.0005 and imax < len(yn) - 1:
|
| 759 |
+
out.update(Mp=100 * (yn[imax] - 1), tp=tt[imax], tr=cruce(1.0), tr_def="0–100 %")
|
| 760 |
+
else:
|
| 761 |
+
out.update(Mp=0.0, tp=math.nan, tr=cruce(0.9) - cruce(0.1), tr_def="10–90 %")
|
| 762 |
+
for banda, clave in ((0.02, "ts2"), (0.05, "ts5")):
|
| 763 |
+
fuera = np.nonzero(np.abs(yn - 1) > banda)[0]
|
| 764 |
+
if fuera.size == 0:
|
| 765 |
+
out[clave] = 0.0
|
| 766 |
+
elif fuera[-1] + 1 < len(tt) and fuera[-1] < 0.97 * len(tt):
|
| 767 |
+
out[clave] = tt[fuera[-1] + 1]
|
| 768 |
+
else:
|
| 769 |
+
out[clave] = math.nan
|
| 770 |
+
out["ymax"] = float(np.max(y)) if yinf > 0 else float(np.min(y))
|
| 771 |
+
return out
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
def horizonte(polos, w_entrada=None, minimo=1.0):
|
| 775 |
+
"""Tiempo de simulación razonable: ~1.5 veces el establecimiento."""
|
| 776 |
+
re = [-p.real for p in polos if abs(p) > 1e-9]
|
| 777 |
+
est = [x for x in re if x > 1e-9]
|
| 778 |
+
T = 6.0 / min(est) if est else 10.0
|
| 779 |
+
ims = [abs(p.imag) for p in polos if abs(p.imag) > 1e-9]
|
| 780 |
+
if ims:
|
| 781 |
+
T = max(T, 3 * 2 * math.pi / max(ims))
|
| 782 |
+
if any(x < -1e-9 for x in re):
|
| 783 |
+
T = min(T, 4.0 / min(-x for x in re if x < -1e-9))
|
| 784 |
+
if w_entrada:
|
| 785 |
+
T = max(T, 3 * 2 * math.pi / w_entrada)
|
| 786 |
+
return float(np.clip(T, minimo, 400.0))
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
# =====================================================================
|
| 790 |
+
# Lazo de control con PID
|
| 791 |
+
# =====================================================================
|
| 792 |
+
def pid_ft(Kp, Ki, Kd, N=0.0, usar=(True, True, True)):
|
| 793 |
+
"""C(s) = Kp + Ki/s + Kd s/(1 + Tf s), con Tf = Td/N (Tf = 0 si N = 0)."""
|
| 794 |
+
Kp = Kp if usar[0] else 0.0
|
| 795 |
+
Ki = Ki if usar[1] else 0.0
|
| 796 |
+
Kd = Kd if usar[2] else 0.0
|
| 797 |
+
Kpr, Kir, Kdr = racional(Kp), racional(Ki), racional(Kd)
|
| 798 |
+
Tf = 0
|
| 799 |
+
if N and N > 0 and Kd > 0:
|
| 800 |
+
Td = Kd / Kp if Kp > 0 else Kd
|
| 801 |
+
Tf = racional(Td / N)
|
| 802 |
+
C = Kpr + (Kir / s if Ki else 0) + (Kdr * s / (1 + Tf * s) if Kd else 0)
|
| 803 |
+
if C == 0:
|
| 804 |
+
C = sp.Integer(0)
|
| 805 |
+
return C, (Kp, Ki, Kd)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def lazo_cerrado(G, C_expr, H=None):
|
| 809 |
+
"""T(s) = CG/(1+CGH) sin cancelar factores, y la ecuación característica."""
|
| 810 |
+
Cn, Cd = sp.fraction(sp.together(C_expr))
|
| 811 |
+
Cn, Cd = sp.Poly(sp.expand(Cn), s), sp.Poly(sp.expand(Cd), s)
|
| 812 |
+
Hn, Hd = (sp.Poly(1, s), sp.Poly(1, s)) if H is None else (H.N, H.D)
|
| 813 |
+
car = Cd * G.D * Hd + Cn * G.N * Hn
|
| 814 |
+
if Cn.is_zero:
|
| 815 |
+
return None, None, car
|
| 816 |
+
return FT(Cn * G.N * Hd, car), FT(Cn * G.N * Hn, Cd * G.D * Hd), car
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def constantes_error(L):
|
| 820 |
+
"""Tipo del lazo y constantes de error de posición, velocidad y aceleración."""
|
| 821 |
+
Ls, _ = L.simplificada()
|
| 822 |
+
tipo = Ls.tipo()
|
| 823 |
+
e = Ls.sym()
|
| 824 |
+
out = {"tipo": tipo}
|
| 825 |
+
for k, nombre in ((0, "Kpos"), (1, "Kv"), (2, "Ka")):
|
| 826 |
+
val = sp.limit(s ** k * e, s, 0)
|
| 827 |
+
out[nombre] = math.inf if (val.is_infinite or val == sp.zoo) else float(val)
|
| 828 |
+
out["e_escalon"] = 1 / (1 + out["Kpos"]) if np.isfinite(out["Kpos"]) else 0.0
|
| 829 |
+
out["e_rampa"] = (math.inf if out["Kv"] == 0 else (0.0 if math.isinf(out["Kv"]) else 1 / out["Kv"]))
|
| 830 |
+
out["e_parabola"] = (math.inf if out["Ka"] == 0 else (0.0 if math.isinf(out["Ka"]) else 1 / out["Ka"]))
|
| 831 |
+
return out
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def simula_pid(G, Kp, Ki, Kd, *, N=0.0, usar=(True, True, True), deriv_medida=False,
|
| 835 |
+
umin=None, umax=None, antiwindup="Ninguno", r_amp=1.0, t_end=10.0,
|
| 836 |
+
pert_amp=0.0, pert_t=None, r2_amp=None, r2_t=None, n=None):
|
| 837 |
+
"""Simulación temporal exacta del lazo r -> e -> PID -> u -> G -> y.
|
| 838 |
+
|
| 839 |
+
Se integra el lazo continuo (planta en espacio de estados + estados del
|
| 840 |
+
controlador) con un integrador de EDO, de modo que la simulación es
|
| 841 |
+
estable exactamente cuando lo son las raíces de 1 + C(s)G(s) = 0. Con
|
| 842 |
+
derivada ideal, el término derivativo es -Kd·dy/dt, que depende de u:
|
| 843 |
+
ese bucle algebraico se resuelve en cada instante, y el impulso Kd·Δr·δ(t)
|
| 844 |
+
de cada escalón de consigna se aplica como un salto del estado de la planta.
|
| 845 |
+
Admite filtro derivativo, derivada sobre la medida, saturación con
|
| 846 |
+
anti-windup, un segundo escalón de consigna y una perturbación en la
|
| 847 |
+
entrada de la planta.
|
| 848 |
+
"""
|
| 849 |
+
if not G.propia():
|
| 850 |
+
raise ValueError("La planta G(s) no es propia (grado del numerador mayor que el del denominador).")
|
| 851 |
+
Kp = float(Kp) if usar[0] else 0.0
|
| 852 |
+
Ki = float(Ki) if usar[1] else 0.0
|
| 853 |
+
Kd = float(Kd) if usar[2] else 0.0
|
| 854 |
+
A, B, Cm, Dm = signal.tf2ss(G.num, G.den)
|
| 855 |
+
nx = A.shape[0]
|
| 856 |
+
b = B[:, 0] if nx else np.zeros(0)
|
| 857 |
+
c = Cm[0] if nx else np.zeros(0)
|
| 858 |
+
dp = float(Dm[0, 0]) if Dm.size else 0.0
|
| 859 |
+
nota = None
|
| 860 |
+
Tf = 0.0
|
| 861 |
+
if Kd and N and N > 0:
|
| 862 |
+
Tf = (Kd / Kp if Kp else Kd) / N
|
| 863 |
+
ideal = bool(Kd) and Tf == 0.0
|
| 864 |
+
if ideal and abs(dp) > 1e-12:
|
| 865 |
+
Tf, ideal = (Kd / Kp if Kp else Kd) / 100.0, False
|
| 866 |
+
nota = "planta bipropia: la derivada se filtra con N = 100"
|
| 867 |
+
sat = umin is not None or umax is not None
|
| 868 |
+
lo = -np.inf if umin is None else float(umin)
|
| 869 |
+
hi = np.inf if umax is None else float(umax)
|
| 870 |
+
cb = float(c @ b) if nx else 0.0
|
| 871 |
+
cA = c @ A if nx else np.zeros(0)
|
| 872 |
+
Ti = Kp / Ki if (Ki and Kp) else 1.0
|
| 873 |
+
Tt = math.sqrt(abs(Ti * Kd / Kp)) if (Kd and Kp) else abs(Ti)
|
| 874 |
+
|
| 875 |
+
C_expr, _ = pid_ft(Kp, Ki, Kd, N if not nota else 100.0)
|
| 876 |
+
T_cl, _, car = lazo_cerrado(G, C_expr)
|
| 877 |
+
pc = np.roots([float(x) for x in car.all_coeffs()]) if car.degree() > 0 else np.array([])
|
| 878 |
+
|
| 879 |
+
def consigna(tk):
|
| 880 |
+
return r2_amp if (r2_t is not None and r2_amp is not None and tk >= r2_t) else r_amp
|
| 881 |
+
|
| 882 |
+
def perturbacion(tk):
|
| 883 |
+
return pert_amp if (pert_t is not None and tk >= pert_t) else 0.0
|
| 884 |
+
|
| 885 |
+
def salidas(tk, z):
|
| 886 |
+
x, xi, xf = z[:nx], z[nx], z[nx + 1]
|
| 887 |
+
r, d = consigna(tk), perturbacion(tk)
|
| 888 |
+
y0 = (c @ x if nx else 0.0) + dp * d # salida sin la parte que depende de u
|
| 889 |
+
e0 = r - y0
|
| 890 |
+
if ideal:
|
| 891 |
+
d0 = -Kd * ((cA @ x if nx else 0.0) + cb * d)
|
| 892 |
+
bd = Kd * cb
|
| 893 |
+
elif Kd:
|
| 894 |
+
ed0 = -y0 if deriv_medida else e0
|
| 895 |
+
d0 = Kd / Tf * (ed0 - xf)
|
| 896 |
+
bd = Kd / Tf * dp
|
| 897 |
+
else:
|
| 898 |
+
d0, bd = 0.0, 0.0
|
| 899 |
+
v = Kp * e0 + Ki * xi + d0
|
| 900 |
+
beta = Kp * dp + bd
|
| 901 |
+
if 1 + beta <= 1e-9:
|
| 902 |
+
raise ValueError("El lazo está mal planteado: 1 + (ganancia directa) ≤ 0.")
|
| 903 |
+
u = v / (1 + beta)
|
| 904 |
+
if sat:
|
| 905 |
+
u = min(max(u, lo), hi)
|
| 906 |
+
u_ns = v - beta * u
|
| 907 |
+
y = y0 + dp * u
|
| 908 |
+
return r, d, y, r - y, u, u_ns, d0 - bd * u, xi, xf
|
| 909 |
+
|
| 910 |
+
# franja en la que el anti-windup «congelar» pasa de integrar a no integrar: un corte
|
| 911 |
+
# brusco hace que el integrador numérico se quede dando pasos minúsculos en la frontera
|
| 912 |
+
rango = (hi - lo) if np.isfinite(hi - lo) else max(abs(lo) if np.isfinite(lo) else 0, abs(hi) if np.isfinite(hi) else 0, 1.0)
|
| 913 |
+
franja = 0.01 * rango
|
| 914 |
+
evaluaciones = [0]
|
| 915 |
+
|
| 916 |
+
def f(tk, z):
|
| 917 |
+
evaluaciones[0] += 1
|
| 918 |
+
if evaluaciones[0] > 400_000:
|
| 919 |
+
raise RuntimeError("La simulación no converge con estos valores (el integrador numérico no avanza).")
|
| 920 |
+
r, d, y, e, u, u_ns, D, xi, xf = salidas(tk, z)
|
| 921 |
+
x = z[:nx]
|
| 922 |
+
dx = A @ x + b * (u + d) if nx else np.zeros(0)
|
| 923 |
+
dxi = e
|
| 924 |
+
if sat and abs(u - u_ns) > 1e-12:
|
| 925 |
+
if antiwindup.startswith(("Integración", "Congelar")) and np.sign(e) == np.sign(u_ns - u):
|
| 926 |
+
dxi = e * (1.0 - min(abs(u_ns - u) / franja, 1.0))
|
| 927 |
+
elif antiwindup.startswith(("Back", "Descargar")) and Ki:
|
| 928 |
+
dxi = e + (u - u_ns) / (Ki * Tt)
|
| 929 |
+
dxf = ((-y if deriv_medida else e) - xf) / Tf if (Kd and not ideal) else 0.0
|
| 930 |
+
return np.concatenate([dx, [dxi, dxf]])
|
| 931 |
+
|
| 932 |
+
tope = 1e6 * max(1.0, abs(r_amp), abs(r2_amp or 0), abs(pert_amp))
|
| 933 |
+
|
| 934 |
+
def diverge(tk, z):
|
| 935 |
+
return tope - abs(salidas(tk, z)[2])
|
| 936 |
+
diverge.terminal = True
|
| 937 |
+
|
| 938 |
+
n = n or 1500
|
| 939 |
+
tt = np.linspace(0.0, t_end, n + 1)
|
| 940 |
+
cortes = sorted({x for x in (r2_t, pert_t) if x is not None and 0 < x < t_end})
|
| 941 |
+
limites = [0.0] + cortes + [t_end]
|
| 942 |
+
z = np.zeros(nx + 2)
|
| 943 |
+
impulsos, Ts, Zs = [], [], []
|
| 944 |
+
escala = float(np.max(np.abs(pc))) if pc.size else 1.0
|
| 945 |
+
max_paso = min(t_end / 300, 0.5 / max(escala, 1e-6))
|
| 946 |
+
roto = False
|
| 947 |
+
for a, bnd in zip(limites[:-1], limites[1:]):
|
| 948 |
+
# impulso de la derivada ideal sobre el error en cada escalón de consigna
|
| 949 |
+
if ideal and not deriv_medida and not sat and nx:
|
| 950 |
+
salto = consigna(a) - (consigna(a - 1e-9) if a > 0 else 0.0)
|
| 951 |
+
if abs(salto) > 0:
|
| 952 |
+
# con grado relativo 1 el salto de y vuelve por la derivada: área Kd·Δr/(1 + Kd·CB)
|
| 953 |
+
area = Kd * salto / (1 + Kd * cb)
|
| 954 |
+
z[:nx] = z[:nx] + b * area
|
| 955 |
+
impulsos.append((a, area))
|
| 956 |
+
malla = tt[(tt >= a) & (tt <= bnd)]
|
| 957 |
+
if malla.size == 0 or malla[0] > a:
|
| 958 |
+
malla = np.concatenate([[a], malla])
|
| 959 |
+
if malla[-1] < bnd:
|
| 960 |
+
malla = np.concatenate([malla, [bnd]])
|
| 961 |
+
sol = solve_ivp(f, (a, bnd), z, method="LSODA", t_eval=malla, rtol=1e-7, atol=1e-10,
|
| 962 |
+
max_step=max_paso, events=diverge)
|
| 963 |
+
Ts.append(sol.t)
|
| 964 |
+
Zs.append(sol.y)
|
| 965 |
+
if sol.status == 1 or not sol.success:
|
| 966 |
+
roto = True
|
| 967 |
+
break
|
| 968 |
+
z = sol.y[:, -1].copy()
|
| 969 |
+
tsim = np.concatenate(Ts)
|
| 970 |
+
zsim = np.concatenate(Zs, axis=1)
|
| 971 |
+
_, idx = np.unique(tsim, return_index=True)
|
| 972 |
+
tsim, zsim = tsim[idx], zsim[:, idx]
|
| 973 |
+
campos = np.array([salidas(tk, zsim[:, k]) for k, tk in enumerate(tsim)])
|
| 974 |
+
return {"t": tsim, "r": campos[:, 0], "y": campos[:, 2], "e": campos[:, 3], "u": campos[:, 4],
|
| 975 |
+
"u_ns": campos[:, 5], "D": campos[:, 6], "P": Kp * campos[:, 3], "I": Ki * campos[:, 7],
|
| 976 |
+
"polos_cl": pc, "T": T_cl, "r_amp": r_amp, "impulsos": impulsos, "diverge": roto,
|
| 977 |
+
"nota": nota, "t_end": t_end}
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
def trayectoria_polos(G, Kp, Ki, Kd, N, usar, variable="K_p", puntos=160):
|
| 981 |
+
"""Polos del lazo cerrado al barrer una ganancia de 0 a 2.5 veces su valor."""
|
| 982 |
+
base = {"K_p": Kp, "K_i": Ki, "K_d": Kd}
|
| 983 |
+
v0 = base[variable]
|
| 984 |
+
vmax = 2.5 * v0 if v0 > 0 else 10.0
|
| 985 |
+
vals = np.linspace(0, vmax, puntos)
|
| 986 |
+
tray = []
|
| 987 |
+
for v in vals:
|
| 988 |
+
b = dict(base)
|
| 989 |
+
b[variable] = v
|
| 990 |
+
C, _ = pid_ft(b["K_p"], b["K_i"], b["K_d"], N, usar)
|
| 991 |
+
_, _, car = lazo_cerrado(G, C)
|
| 992 |
+
c = [float(x) for x in car.all_coeffs()]
|
| 993 |
+
tray.append(np.roots(c) if len(c) > 1 else np.array([]))
|
| 994 |
+
return vals, tray
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
# =====================================================================
|
| 998 |
+
# Diseño por asignación de polos
|
| 999 |
+
# =====================================================================
|
| 1000 |
+
def especificaciones_a_polos(Mp_pct, ts, banda=2):
|
| 1001 |
+
zeta = zeta_de_Mp(Mp_pct)
|
| 1002 |
+
sigma = (4.0 if banda == 2 else 3.0) / ts
|
| 1003 |
+
wn = sigma / zeta
|
| 1004 |
+
wd = wn * math.sqrt(max(1 - zeta ** 2, 0.0))
|
| 1005 |
+
return {"zeta": zeta, "sigma": sigma, "wn": wn, "wd": wd, "beta": math.acos(min(zeta, 1.0))}
|
| 1006 |
+
|
| 1007 |
+
|
| 1008 |
+
_ORDEN_SIMB = {"K_p": 0, "K_i": 1, "K_d": 2}
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def _clave_monomio(mon):
|
| 1012 |
+
if mon == 1:
|
| 1013 |
+
return (9, "")
|
| 1014 |
+
nombres = sorted(str(x) for x in mon.free_symbols)
|
| 1015 |
+
return (min(_ORDEN_SIMB.get(n, 5) for n in nombres), ",".join(nombres))
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def lin_tex(e):
|
| 1019 |
+
"""Coeficiente en función de las incógnitas (Kp, Ki, Kd, m_i) -> (LaTeX, n.º de términos)."""
|
| 1020 |
+
e = sp.expand(e)
|
| 1021 |
+
if e == 0:
|
| 1022 |
+
return "0", 0
|
| 1023 |
+
dic = e.as_coefficients_dict()
|
| 1024 |
+
terms = []
|
| 1025 |
+
for mon in sorted(dic, key=_clave_monomio):
|
| 1026 |
+
c = float(dic[mon])
|
| 1027 |
+
terms.append((c, "" if mon == 1 else sp.latex(mon)))
|
| 1028 |
+
return suma_tex(terms), len(terms)
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
def poly_sym_tex(P, var="s"):
|
| 1032 |
+
"""Polinomio en s con coeficientes que dependen de las incógnitas, por potencias."""
|
| 1033 |
+
P = sp.Poly(sp.expand(P), s)
|
| 1034 |
+
out = ""
|
| 1035 |
+
for k in range(P.degree(), -1, -1):
|
| 1036 |
+
c = P.coeff_monomial(s ** k)
|
| 1037 |
+
if c == 0:
|
| 1038 |
+
continue
|
| 1039 |
+
txt, nt = lin_tex(c)
|
| 1040 |
+
v = "" if k == 0 else (var if k == 1 else var + "^{" + str(k) + "}")
|
| 1041 |
+
neg = nt == 1 and txt.startswith("-")
|
| 1042 |
+
if neg:
|
| 1043 |
+
txt = txt[1:]
|
| 1044 |
+
if v:
|
| 1045 |
+
if txt == "1":
|
| 1046 |
+
body = v
|
| 1047 |
+
elif nt > 1:
|
| 1048 |
+
body = r"\left(" + txt + r"\right)" + v
|
| 1049 |
+
else:
|
| 1050 |
+
body = txt + (r"\," if txt.startswith(r"\frac") or txt[-1].isalpha() or txt.endswith("}") else "") + v
|
| 1051 |
+
else:
|
| 1052 |
+
body = txt
|
| 1053 |
+
if not out:
|
| 1054 |
+
out = ("-" if neg else "") + body
|
| 1055 |
+
else:
|
| 1056 |
+
out += (" - " if neg else " + ") + body
|
| 1057 |
+
return out or "0"
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
def _a_float(v):
|
| 1061 |
+
v = complex(sp.N(v))
|
| 1062 |
+
if abs(v.imag) > 1e-7 * max(1.0, abs(v)):
|
| 1063 |
+
raise TypeError("solución compleja")
|
| 1064 |
+
return v.real
|
| 1065 |
+
|
| 1066 |
+
|
| 1067 |
+
def asigna_polos(G, tipo_ctrl, Mp_pct, ts, banda=2, r_extra=5.0):
|
| 1068 |
+
"""Asignación de polos: iguala 1 + C(s)G(s) = 0 al polinomio deseado.
|
| 1069 |
+
|
| 1070 |
+
Si el lazo cerrado tiene más polos que parámetros el controlador (regla de
|
| 1071 |
+
oro: tantas especificaciones como parámetros), se fija el par dominante y
|
| 1072 |
+
tantos polos en r·zeta·wn como se pueda, y los restantes se dejan libres:
|
| 1073 |
+
sus coeficientes m_i pasan a ser incógnitas y se comprueba después dónde caen.
|
| 1074 |
+
"""
|
| 1075 |
+
esp = especificaciones_a_polos(Mp_pct, ts, banda)
|
| 1076 |
+
zeta, sigma, wn = esp["zeta"], esp["sigma"], esp["wn"]
|
| 1077 |
+
incog = {"P": [Kp_], "PI": [Kp_, Ki_], "PD": [Kp_, Kd_], "PID": [Kp_, Ki_, Kd_]}[tipo_ctrl]
|
| 1078 |
+
C = Kp_ + (Ki_ / s if Ki_ in incog else 0) + (Kd_ * s if Kd_ in incog else 0)
|
| 1079 |
+
Cn, Cd = sp.fraction(sp.together(C))
|
| 1080 |
+
car = sp.expand(Cd * G.D.as_expr() + Cn * G.N.as_expr())
|
| 1081 |
+
Pc = sp.Poly(car, s)
|
| 1082 |
+
nc = Pc.degree()
|
| 1083 |
+
lc = Pc.LC()
|
| 1084 |
+
zf, wf = sp.Float(zeta, 15), sp.Float(wn, 15)
|
| 1085 |
+
libres_m = []
|
| 1086 |
+
if nc >= 2:
|
| 1087 |
+
par = s ** 2 + 2 * zf * wf * s + wf ** 2
|
| 1088 |
+
p3 = sp.Float(r_extra * sigma, 15)
|
| 1089 |
+
f = nc - len(incog)
|
| 1090 |
+
if f > 0 and len(incog) >= 2:
|
| 1091 |
+
libres_m = list(sp.symbols(f"m_1:{f + 1}"))
|
| 1092 |
+
M = s ** f + sum(libres_m[i] * s ** (f - 1 - i) for i in range(f))
|
| 1093 |
+
else:
|
| 1094 |
+
f, M = 0, sp.Integer(1)
|
| 1095 |
+
extra = nc - 2 - f
|
| 1096 |
+
deseado = sp.expand(par * (s + p3) ** extra * M)
|
| 1097 |
+
else:
|
| 1098 |
+
deseado = s + sp.Float(sigma, 15)
|
| 1099 |
+
extra, p3, f = 0, None, 0
|
| 1100 |
+
Pd = sp.Poly(deseado, s)
|
| 1101 |
+
ecs, pares = [], []
|
| 1102 |
+
for k in range(nc - 1, -1, -1):
|
| 1103 |
+
izq = Pc.coeff_monomial(s ** k)
|
| 1104 |
+
der = sp.expand(lc * Pd.coeff_monomial(s ** k))
|
| 1105 |
+
pares.append((izq, der))
|
| 1106 |
+
ecs.append(sp.Eq(izq, der))
|
| 1107 |
+
ecs_utiles = [e for e in ecs if e is not sp.true]
|
| 1108 |
+
incognitas = incog + libres_m
|
| 1109 |
+
libres_fijadas = []
|
| 1110 |
+
if any(e is sp.false for e in ecs_utiles):
|
| 1111 |
+
sols = []
|
| 1112 |
+
else:
|
| 1113 |
+
sols = sp.solve(ecs_utiles, incognitas, dict=True) if ecs_utiles else []
|
| 1114 |
+
estado, valores, m_vals = "imposible", None, None
|
| 1115 |
+
for sol in sols:
|
| 1116 |
+
fijadas = [v for v in incognitas if v not in sol]
|
| 1117 |
+
val = {v: (sol[v].subs({x: 0 for x in fijadas}) if v in sol else sp.Integer(0)) for v in incognitas}
|
| 1118 |
+
try:
|
| 1119 |
+
val = {k: _a_float(v) for k, v in val.items()}
|
| 1120 |
+
except TypeError:
|
| 1121 |
+
continue
|
| 1122 |
+
valores = {v: val[v] for v in incog}
|
| 1123 |
+
m_vals = [val[v] for v in libres_m]
|
| 1124 |
+
libres_fijadas = [v for v in fijadas if v in incog]
|
| 1125 |
+
estado = "subdeterminado" if libres_fijadas else ("parcial" if libres_m else "ok")
|
| 1126 |
+
break
|
| 1127 |
+
polos_libres = []
|
| 1128 |
+
if m_vals:
|
| 1129 |
+
polos_libres = list(np.roots([1.0] + m_vals))
|
| 1130 |
+
return {
|
| 1131 |
+
"esp": esp, "incog": incog, "C": C, "car": car, "nc": nc, "deseado": deseado,
|
| 1132 |
+
"extra": extra, "p3": float(p3) if p3 is not None else None, "ecs": pares,
|
| 1133 |
+
"valores": valores, "estado": estado, "fijadas": libres_fijadas, "lc": lc,
|
| 1134 |
+
"libres": libres_m, "m_vals": m_vals, "polos_libres": polos_libres,
|
| 1135 |
+
}
|
paneles.py
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cada pestaña del simulador: compone el desarrollo paso a paso (Markdown
|
| 2 |
+
con LaTeX) y las figuras a partir del núcleo de cálculo."""
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import sympy as sp
|
| 8 |
+
from scipy import signal
|
| 9 |
+
|
| 10 |
+
import animaciones as an
|
| 11 |
+
import bloques as bl
|
| 12 |
+
import graficas as gf
|
| 13 |
+
from nucleo import (
|
| 14 |
+
FT, Kd_, Ki_, Kp_, agrupa, asigna_polos, constantes_error, crea_entrada, dominantes,
|
| 15 |
+
especificaciones_a_polos, estabilidad, evalua_terminos, exp_tex, factor_tex, fmt, fmtc, fmtq, fracciones_simples,
|
| 16 |
+
fracciones_tex, horizonte, lazo_cerrado, lista_raices_tex, metricas_escalon, num,
|
| 17 |
+
parametros_2o, parse_ft, pid_ft, poly_sym_tex, poly_tex, racional, raices, regimen, s,
|
| 18 |
+
segundo_orden, simula_pid, terminos_tiempo, tiempo_tex, trayectoria_polos,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def eq(tex):
|
| 23 |
+
return "$$" + tex + "$$"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def caja(tipo, titulo, cuerpo):
|
| 27 |
+
"""Caja de los apuntes: 'clave' (gris) o 'aviso' (borde rojo)."""
|
| 28 |
+
return f'<div class="{tipo}">\n\n**{titulo}.** {cuerpo}\n\n</div>'
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def error_md(e):
|
| 32 |
+
return caja("aviso", "No se puede calcular", str(e))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# =====================================================================
|
| 36 |
+
# Utilidades comunes
|
| 37 |
+
# =====================================================================
|
| 38 |
+
def respuesta(G, R_ft, tt):
|
| 39 |
+
"""y(t) = L^-1{G(s) R(s)} por fracciones simples, evaluada en tt."""
|
| 40 |
+
Y, _ = (G * R_ft).simplificada()
|
| 41 |
+
entera, modos = fracciones_simples(Y)
|
| 42 |
+
terms = terminos_tiempo(modos)
|
| 43 |
+
mods, y = evalua_terminos(terms, tt, len(modos))
|
| 44 |
+
return Y, entera, modos, mods, y
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def valor_final(Y):
|
| 48 |
+
"""Teorema del valor final, con su condición de validez."""
|
| 49 |
+
sY, _ = FT(Y.N * sp.Poly(s, s), Y.D).simplificada()
|
| 50 |
+
pol = sY.polos()
|
| 51 |
+
valido = all(p.real < -1e-9 for p, _ in pol)
|
| 52 |
+
if not valido:
|
| 53 |
+
return False, None, sY
|
| 54 |
+
return True, float(sY.N.eval(0) / sY.D.eval(0)), sY
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def valor_inicial(Y):
|
| 58 |
+
v = sp.limit(s * Y.sym(), s, sp.oo)
|
| 59 |
+
if v.is_infinite:
|
| 60 |
+
return math.inf
|
| 61 |
+
return float(v)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def etiqueta_modo(md):
|
| 65 |
+
p = md["p"]
|
| 66 |
+
if md["tipo"] == "real":
|
| 67 |
+
if abs(p.real) < 1e-12:
|
| 68 |
+
return "polo en el origen (régimen permanente)" if md["m"] == 1 else f"polo múltiple en el origen (×{md['m']})"
|
| 69 |
+
return (f"polo s = {num(p.real)}" + (f" (×{md['m']})" if md["m"] > 1 else "")).replace("-", "−")
|
| 70 |
+
return f"par s = {num(p.real)} ± j{num(p.imag)}".replace("-", "−")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _nombre_polo(p, tipo):
|
| 74 |
+
if tipo == "real":
|
| 75 |
+
return f"$s={fmt(p.real)}$"
|
| 76 |
+
re = fmt(p.real) if abs(p.real) > 1e-10 else ""
|
| 77 |
+
return f"$s={re}\\pm j\\,{fmt(p.imag)}$"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def explica_polos(S):
|
| 81 |
+
"""Por qué el sistema S(s) es estable o no, y cuál es su polo dominante y por qué.
|
| 82 |
+
|
| 83 |
+
El dominante geométrico es el más cercano al eje imaginario; pero si su
|
| 84 |
+
modo apenas pesa en la respuesta a escalón (un cero casi encima, dipolo),
|
| 85 |
+
se dice también cuál domina en la práctica, mirando los residuos.
|
| 86 |
+
"""
|
| 87 |
+
pol = S.polos()
|
| 88 |
+
gr_ = agrupa(pol)
|
| 89 |
+
est = estabilidad(pol)
|
| 90 |
+
md = []
|
| 91 |
+
cab = {"estable": "Porque **todos** los polos tienen parte real negativa, así que todos los modos se extinguen:",
|
| 92 |
+
"inestable": "Porque hay al menos un polo con parte real positiva (o uno múltiple sobre el eje imaginario), y basta uno:",
|
| 93 |
+
"límite": "Porque hay polos simples sobre el eje imaginario, cuyo modo ni crece ni se extingue:"}[est]
|
| 94 |
+
filas = []
|
| 95 |
+
for p, m, tipo in gr_:
|
| 96 |
+
mult = f" (×{m})" if m > 1 else ""
|
| 97 |
+
if p.real < -1e-9:
|
| 98 |
+
v = f"parte real ${fmt(p.real)}<0$: su modo $e^{{{fmt(p.real)}t}}$ se extingue"
|
| 99 |
+
elif p.real > 1e-9:
|
| 100 |
+
v = f"parte real ${fmt(p.real)}>0$: su modo $e^{{{fmt(p.real)}t}}$ **crece sin límite**"
|
| 101 |
+
else:
|
| 102 |
+
v = ("parte real nula y polo múltiple: su modo **crece** como una potencia de $t$" if m > 1
|
| 103 |
+
else "parte real nula: su modo " + ("oscila sin amortiguarse" if tipo == "par" else "queda constante"))
|
| 104 |
+
filas.append(f"- {_nombre_polo(p, tipo)}{mult}: {v}.")
|
| 105 |
+
md.append(f"**¿Por qué es {est}?** {cab}\n" + "\n".join(filas))
|
| 106 |
+
if est != "estable":
|
| 107 |
+
md.append("**Polo dominante.** Con un modo que no se extingue no tiene sentido buscar el dominante: "
|
| 108 |
+
"a la larga ese modo lo tapa todo, porque los demás desaparecen y él sigue.")
|
| 109 |
+
return md
|
| 110 |
+
if not gr_:
|
| 111 |
+
return md
|
| 112 |
+
# pesos de cada modo en la respuesta a escalón (residuos)
|
| 113 |
+
# amplitud de cada modo: |A| si es real, 2|A| si es un par (A e^{pt} + conjugado)
|
| 114 |
+
try:
|
| 115 |
+
_, modos = fracciones_simples(FT(S.N, S.D * sp.Poly(s, s)))
|
| 116 |
+
pesos = []
|
| 117 |
+
for p, m, tipo in gr_:
|
| 118 |
+
cand = [md_ for md_ in modos if abs(md_["p"] - p) < 1e-6 * max(1, abs(p))]
|
| 119 |
+
amp = max(abs(a) for a in cand[0]["A"]) if cand else 0.0
|
| 120 |
+
pesos.append(2 * amp if tipo == "par" else amp)
|
| 121 |
+
final = [abs(md_["A"][0]) for md_ in modos if abs(md_["p"]) < 1e-9]
|
| 122 |
+
except Exception: # noqa: BLE001
|
| 123 |
+
pesos, final = [1.0] * len(gr_), []
|
| 124 |
+
orden = sorted(range(len(gr_)), key=lambda i: -gr_[i][0].real)
|
| 125 |
+
i0 = orden[0]
|
| 126 |
+
p0, m0, t0 = gr_[i0]
|
| 127 |
+
sg = -p0.real
|
| 128 |
+
que = "El par" if t0 == "par" else "El polo"
|
| 129 |
+
md_dom = (f"**¿Cuál es el polo dominante y por qué?** {que} {_nombre_polo(p0, t0)} es el más cercano al eje "
|
| 130 |
+
f"imaginario: su parte real, $|\\sigma|={fmt(sg)}$, es la menor de todas. Su modo $e^{{-{fmt(sg)}t}}$ es el que más "
|
| 131 |
+
f"tarda en extinguirse (constante de tiempo $1/|\\sigma|={fmt(1 / sg)}$ s), así que es el que marca la duración "
|
| 132 |
+
f"del transitorio: $t_s\\approx4/|\\sigma|={fmt(4 / sg)}$ s.")
|
| 133 |
+
if t0 == "par":
|
| 134 |
+
z0 = sg / abs(p0)
|
| 135 |
+
md_dom += f" Como es un par complejo, oscila con $\\omega_d={fmt(p0.imag)}$ rad/s y amortiguamiento $\\zeta=|\\sigma|/\\omega_n={fmt(z0)}$."
|
| 136 |
+
if len(orden) > 1:
|
| 137 |
+
p1, _, t1 = gr_[orden[1]]
|
| 138 |
+
r = -p1.real / sg
|
| 139 |
+
if r >= 5:
|
| 140 |
+
md_dom += (f" El siguiente, {_nombre_polo(p1, t1)}, está ${fmt(r)}$ veces más lejos del eje (≥ 5): su modo se "
|
| 141 |
+
"extingue mucho antes y se puede despreciar.")
|
| 142 |
+
else:
|
| 143 |
+
md_dom += (f" El siguiente, {_nombre_polo(p1, t1)}, está solo ${fmt(r)}$ veces más lejos (< 5): **compite** con el "
|
| 144 |
+
"dominante y no se puede despreciar.")
|
| 145 |
+
md.append(md_dom)
|
| 146 |
+
wmax = max(pesos + final) if pesos else 0
|
| 147 |
+
if wmax > 0 and pesos[i0] < 0.15 * wmax:
|
| 148 |
+
efectivo = next((i for i in orden if pesos[i] >= 0.15 * wmax), None)
|
| 149 |
+
if efectivo is not None and efectivo != i0:
|
| 150 |
+
pe, _, te = gr_[efectivo]
|
| 151 |
+
ceros_cerca = [z for z, _ in S.ceros() if abs(z - p0) < 0.3 * max(abs(p0), 1e-3)]
|
| 152 |
+
causa = (f"porque tiene un cero casi encima (${fmtc(ceros_cerca[0])}$): forman un **dipolo**"
|
| 153 |
+
if ceros_cerca else "por la posición de los ceros")
|
| 154 |
+
md.append(caja("clave", "Dominante en el papel, no en la práctica",
|
| 155 |
+
f"En la respuesta a escalón el modo de {_nombre_polo(p0, t0)} tiene una amplitud de solo "
|
| 156 |
+
f"{num(pesos[i0])} (frente a {num(wmax)}), {causa}. Su efecto es una cola lenta pero pequeña; "
|
| 157 |
+
f"la forma de la curva la marca {_nombre_polo(pe, te)}, con $t_s\\approx4/{fmt(-pe.real)}"
|
| 158 |
+
f"={fmt(4 / -pe.real)}$ s."))
|
| 159 |
+
return md
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def lectura_polos_ceros(polos, ceros):
|
| 163 |
+
"""Lo que se observa y lo que significa (tabla resumen de los apuntes)."""
|
| 164 |
+
out = []
|
| 165 |
+
for z, _ in ceros:
|
| 166 |
+
if z.real > 1e-9 and abs(z.imag) < 1e-9:
|
| 167 |
+
out.append(f"Cero en el semiplano derecho, $s={fmt(z.real)}$: **respuesta inversa** (fase no mínima). Limita de forma fundamental la rapidez alcanzable.")
|
| 168 |
+
if abs(z) < 1e-9:
|
| 169 |
+
out.append("Cero en el origen: elimina la componente continua, la salida vuelve a cero ante escalón.")
|
| 170 |
+
for z, _ in ceros:
|
| 171 |
+
for p, _ in polos:
|
| 172 |
+
if abs(z - p) < 0.1 * max(abs(p), 1e-3) and abs(z - p) > 1e-12:
|
| 173 |
+
out.append(f"El cero ${fmtc(z)}$ está pegado al polo ${fmtc(p)}$: forman un **dipolo** y ambos se anulan casi por completo.")
|
| 174 |
+
return out
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# =====================================================================
|
| 178 |
+
# Pestaña 1: dada la entrada, derivar todo lo demás
|
| 179 |
+
# =====================================================================
|
| 180 |
+
def construye_G(modo, orden, K, tau, zeta, wn, con_cero, zc, p3, texto):
|
| 181 |
+
if modo == "G(s) libre":
|
| 182 |
+
return parse_ft(texto)
|
| 183 |
+
K = racional(K)
|
| 184 |
+
if orden.startswith("1"):
|
| 185 |
+
if tau <= 0:
|
| 186 |
+
raise ValueError("La constante de tiempo τ debe ser positiva.")
|
| 187 |
+
G = K / (racional(tau) * s + 1)
|
| 188 |
+
else:
|
| 189 |
+
if wn <= 0:
|
| 190 |
+
raise ValueError("La frecuencia natural ωn debe ser positiva.")
|
| 191 |
+
w, z = racional(wn), racional(zeta)
|
| 192 |
+
G = K * w ** 2 / (s ** 2 + 2 * z * w * s + w ** 2)
|
| 193 |
+
if orden.startswith("3"):
|
| 194 |
+
if p3 <= 0:
|
| 195 |
+
raise ValueError("El tercer polo debe estar en el semiplano izquierdo (p > 0).")
|
| 196 |
+
pr = racional(p3)
|
| 197 |
+
G = G * pr / (s + pr)
|
| 198 |
+
if con_cero:
|
| 199 |
+
zr = racional(zc)
|
| 200 |
+
G = G * (s if zr == 0 else (1 - s / zr))
|
| 201 |
+
return FT.expr(G)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def analizar(modo, orden, K, tau, zeta, wn, con_cero, zc, p3, texto, tipo_e, A, w_e, a_e, r_txt, t_max):
|
| 205 |
+
try:
|
| 206 |
+
G = construye_G(modo, orden, K, tau, zeta, wn, con_cero, zc, p3, texto)
|
| 207 |
+
ent = crea_entrada(tipo_e, A, w_e, a_e, r_txt)
|
| 208 |
+
if not G.propia():
|
| 209 |
+
raise ValueError("G(s) no es propia: el grado del numerador supera al del denominador y no es físicamente realizable.")
|
| 210 |
+
except Exception as e: # noqa: BLE001
|
| 211 |
+
f = gf.figura_error(str(e))
|
| 212 |
+
return (error_md(e),) + (f,) * (len(ANALISIS) - 1)
|
| 213 |
+
polos, ceros = G.polos(), G.ceros()
|
| 214 |
+
T = t_max if t_max and t_max > 0 else horizonte(G.polos_np(), ent.w)
|
| 215 |
+
tt = np.linspace(0, T, 1600)
|
| 216 |
+
R = ent.ft()
|
| 217 |
+
Y, entera, modos, mods, y = respuesta(G, R, tt)
|
| 218 |
+
r = None if ent.impulso else ent.r_num(tt)
|
| 219 |
+
ok_vf, yinf, _ = valor_final(Y)
|
| 220 |
+
met = metricas_escalon(tt, y, yinf) if (ent.es_escalon and ok_vf) else None
|
| 221 |
+
|
| 222 |
+
md = []
|
| 223 |
+
# ---------- 1. el sistema ----------
|
| 224 |
+
md.append("### 1. El sistema")
|
| 225 |
+
md.append(eq("G(s) = " + G.tex() + (" = " + G.tex_factor() if G.tex_factor() != G.tex() else "")))
|
| 226 |
+
tipo = G.tipo()
|
| 227 |
+
est = estabilidad(polos)
|
| 228 |
+
K0 = G.ganancia_estatica()
|
| 229 |
+
md.append(f"- Orden $n={G.n}$ (grado del denominador), $m={G.m}$ ceros; "
|
| 230 |
+
f"tipo {tipo} ({tipo} polo{'s' if tipo != 1 else ''} en el origen).")
|
| 231 |
+
md.append(f"- Polos (raíces del denominador): ${lista_raices_tex(polos)}$.")
|
| 232 |
+
md.append(f"- Ceros (raíces del numerador): ${lista_raices_tex(ceros, 'z')}$.")
|
| 233 |
+
md.append(f"- Ganancia estática: $G(0)={fmt(K0)}$." if np.isfinite(K0)
|
| 234 |
+
else "- Ganancia estática infinita: hay un integrador (polo en el origen).")
|
| 235 |
+
md.append(f"- Estabilidad: **{est}**.")
|
| 236 |
+
for txt in lectura_polos_ceros(polos, ceros):
|
| 237 |
+
md.append("- " + txt)
|
| 238 |
+
md += explica_polos(G)
|
| 239 |
+
|
| 240 |
+
# ---------- 2. parámetros característicos ----------
|
| 241 |
+
md.append("### 2. Parámetros característicos")
|
| 242 |
+
md += parametros_md(G, polos, ceros)
|
| 243 |
+
|
| 244 |
+
# ---------- 3. entrada ----------
|
| 245 |
+
md.append("### 3. La entrada y su transformada")
|
| 246 |
+
md.append(eq(r"r(t) = " + ent.r_tex + r"\quad\Longrightarrow\quad R(s) = " + R.tex()))
|
| 247 |
+
# ---------- 4. salida en s ----------
|
| 248 |
+
md.append("### 4. La salida en el dominio de $s$")
|
| 249 |
+
Ysin = G * R
|
| 250 |
+
md.append(eq(r"Y(s) = G(s)\,R(s) = " + Ysin.tex() + " = " + Y.tex_factor()))
|
| 251 |
+
if Ysin.n != Y.n:
|
| 252 |
+
md.append("Se ha simplificado un factor común entre numerador y denominador de $Y(s)$.")
|
| 253 |
+
# ---------- 5. fracciones simples ----------
|
| 254 |
+
md.append("### 5. Fracciones simples")
|
| 255 |
+
md += fracciones_md(Y, entera, modos)
|
| 256 |
+
# ---------- 6. vuelta al tiempo ----------
|
| 257 |
+
md.append("### 6. Vuelta al tiempo")
|
| 258 |
+
md.append("Cada término se antitransforma con la tabla: $\\frac{A}{s+a}\\to Ae^{-at}$, "
|
| 259 |
+
"$\\frac{A}{(s+a)^{k}}\\to A\\frac{t^{k-1}}{(k-1)!}e^{-at}$, "
|
| 260 |
+
"$\\frac{s+a}{(s+a)^2+\\omega^2}\\to e^{-at}\\cos\\omega t$, "
|
| 261 |
+
"$\\frac{\\omega}{(s+a)^2+\\omega^2}\\to e^{-at}\\operatorname{sen}\\omega t$.")
|
| 262 |
+
md.append(eq(r"\boxed{\ y(t) = " + tiempo_tex(entera, modos) + r"\ } \qquad t \ge 0"))
|
| 263 |
+
if entera:
|
| 264 |
+
md.append("Los impulsos $\\delta(t)$ proceden de la parte entera (grado del numerador igual al del denominador) y no se dibujan.")
|
| 265 |
+
# ---------- 7. valores inicial y final ----------
|
| 266 |
+
md.append("### 7. Comprobación: valores inicial y final")
|
| 267 |
+
y0 = valor_inicial(Y)
|
| 268 |
+
md.append(eq(r"y(0^{+}) = \lim_{s\to\infty} s\,Y(s) = " + fmt(y0)))
|
| 269 |
+
if ok_vf:
|
| 270 |
+
md.append(eq(r"y(\infty) = \lim_{s\to 0} s\,Y(s) = " + fmt(yinf)))
|
| 271 |
+
if ent.limite is not None:
|
| 272 |
+
ess = ent.limite - yinf
|
| 273 |
+
md.append(f"Error en régimen permanente: $e(\\infty) = r(\\infty) - y(\\infty) = {fmt(ent.limite)} - {fmt(yinf)} = {fmt(ess)}$.")
|
| 274 |
+
else:
|
| 275 |
+
md.append("El teorema del valor final **no se puede aplicar**: $sY(s)$ tiene polos con parte real nula o positiva "
|
| 276 |
+
"(sistema inestable, en el límite, o entrada que no se estabiliza: rampa, senoidal…). "
|
| 277 |
+
"Aplicarlo daría un resultado sin sentido.")
|
| 278 |
+
# ---------- 8. especificaciones ----------
|
| 279 |
+
if met:
|
| 280 |
+
md.append("### 8. Especificaciones medidas sobre la respuesta a escalón")
|
| 281 |
+
md += tabla_especificaciones(G, met, ent)
|
| 282 |
+
|
| 283 |
+
# ---------- figuras ----------
|
| 284 |
+
d2 = None
|
| 285 |
+
if G.n == 2 and G.m == 0:
|
| 286 |
+
so = segundo_orden(G.den)
|
| 287 |
+
if so and 0 < so[1] < 1:
|
| 288 |
+
d2 = parametros_2o(*so)
|
| 289 |
+
f_s = gf.fig_plano_s(G.polos_np(), G.ceros_np(), anotar_2o=d2, w=9.0, h=5.6)
|
| 290 |
+
nota = "impulso: no se dibuja r(t)" if ent.impulso else None
|
| 291 |
+
f_t = gf.fig_respuesta(tt, y, r=r, yinf=yinf if ok_vf else None, met=met, nota=nota,
|
| 292 |
+
rlabel=f"entrada r(t): {ent.nombre}", w=10.0, h=4.6)
|
| 293 |
+
f_m = gf.fig_modos(tt, mods, [etiqueta_modo(m_) for m_ in modos], y, w=10.0, h=4.6)
|
| 294 |
+
f_3d = gf.fig_superficie(G, w=9.0, h=6.0)
|
| 295 |
+
f_e, f_c = figuras_especificaciones(G, ent, tt, y, yinf if ok_vf else None, met)
|
| 296 |
+
f_l = gf.fig_camino_laplace(ent.r_tex, R.tex(), G.tex(), Y.tex_factor(), fracciones_tex(entera, modos),
|
| 297 |
+
tiempo_tex(entera, modos))
|
| 298 |
+
return "\n\n".join(md), f_e, f_c, f_s, f_t, f_l, f_m, f_3d
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
ANALISIS = ["md", "especificaciones", "cada", "plano", "respuesta", "camino", "modos", "superficie"]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def figuras_especificaciones(G, ent, tt, y, yinf, met):
|
| 305 |
+
"""td, tr, tp, Mp y ts sobre la respuesta a escalón (que es donde se definen):
|
| 306 |
+
la figura con todas acotadas y la de cada magnitud por separado."""
|
| 307 |
+
teor = teoricos(G)
|
| 308 |
+
if ent.es_escalon and met:
|
| 309 |
+
datos = (tt, y, yinf, met, f"Respuesta a un escalón de amplitud {num(ent.limite)}: las magnitudes que la definen")
|
| 310 |
+
else:
|
| 311 |
+
aviso = None
|
| 312 |
+
if estabilidad(G.polos()) != "estable":
|
| 313 |
+
aviso = ("Las especificaciones $t_d$, $t_r$, $t_p$, $M_p$ y $t_s$ solo tienen sentido si el sistema es "
|
| 314 |
+
"estable:\nla respuesta tiene que llegar a un valor final.")
|
| 315 |
+
elif G.tipo() > 0:
|
| 316 |
+
aviso = ("Hay un integrador (polo en el origen): ante escalón la salida crece sin parar y no hay valor final,\n"
|
| 317 |
+
"así que no se pueden medir $t_p$, $M_p$ ni $t_s$.")
|
| 318 |
+
else:
|
| 319 |
+
te = np.linspace(0, horizonte(G.polos_np(), minimo=1.0), 1600)
|
| 320 |
+
_, _, _, _, ye = respuesta(G, crea_entrada("Escalón").ft(), te)
|
| 321 |
+
k0 = G.ganancia_estatica()
|
| 322 |
+
me = metricas_escalon(te, ye, k0)
|
| 323 |
+
if not me:
|
| 324 |
+
aviso = "La ganancia estática es nula: la salida vuelve a cero y no se definen las especificaciones."
|
| 325 |
+
datos = (te, ye, k0, me, "Respuesta a un escalón unitario (las especificaciones se definen siempre sobre ella)")
|
| 326 |
+
if aviso:
|
| 327 |
+
return gf.figura_aviso(aviso), gf.figura_aviso(aviso)
|
| 328 |
+
t_, y_, yi, me, nota = datos
|
| 329 |
+
return (gf.fig_especificaciones(t_, y_, yi, me, teor, nota=nota, w=9.4, h=5.0),
|
| 330 |
+
gf.fig_cada_magnitud(t_, y_, yi, me, teor, w=9.6, h=6.8))
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def parametros_md(G, polos, ceros):
|
| 334 |
+
md = []
|
| 335 |
+
n, m = G.n, G.m
|
| 336 |
+
a = G.den
|
| 337 |
+
b = G.num
|
| 338 |
+
if n == 1:
|
| 339 |
+
if abs(a[1]) < 1e-14:
|
| 340 |
+
K = b[-1] / a[0]
|
| 341 |
+
md.append(f"Integrador puro: $G(s)={fmt(K)}/s$. Ante escalón la salida crece como una rampa de pendiente ${fmt(K)}$.")
|
| 342 |
+
return md
|
| 343 |
+
tau = a[0] / a[1]
|
| 344 |
+
K = b[-1] / a[1]
|
| 345 |
+
md.append(eq(r"G(s) = \frac{K" + (r"(\tau_z s + 1)" if m == 1 else "") + r"}{\tau s + 1},\qquad K = " + fmt(K)
|
| 346 |
+
+ r",\quad \tau = " + fmt(tau) + r"\ \text{s}"
|
| 347 |
+
+ (r",\quad \tau_z = " + fmt(b[0] / b[1]) + r"\ \text{s}" if m == 1 and abs(b[1]) > 1e-14 else "")))
|
| 348 |
+
if tau > 0:
|
| 349 |
+
md.append(f"Polo único en $s=-1/\\tau={fmt(-1 / tau)}$, modo $e^{{-t/\\tau}}$: no oscila nunca, no hay $t_p$ ni $M_p$.")
|
| 350 |
+
md.append(eq(r"t_s(2\%) = 4\tau = " + fmt(4 * tau) + r",\quad t_s(5\%) = 3\tau = " + fmt(3 * tau)
|
| 351 |
+
+ r",\quad t_r = 2.2\tau = " + fmt(2.2 * tau) + r",\quad t_d = 0.69\tau = " + fmt(0.69 * tau)))
|
| 352 |
+
if m == 1 and abs(b[1]) > 1e-14:
|
| 353 |
+
tz = b[0] / b[1]
|
| 354 |
+
md.append(f"Con el cero, el salto inicial ante escalón unitario es $c(0^+)=K\\,\\tau_z/\\tau={fmt(K * tz / tau)}$"
|
| 355 |
+
+ (": la salida **se pasa** sin oscilar." if tz > tau else
|
| 356 |
+
(": **respuesta inversa**." if tz < 0 else ".")))
|
| 357 |
+
else:
|
| 358 |
+
md.append(f"Pendiente inicial $c'(0)=K/\\tau={fmt(K / tau)}$: la tangente en el origen corta al valor final en $t=\\tau$.")
|
| 359 |
+
else:
|
| 360 |
+
md.append("La constante de tiempo es negativa: el polo está en el semiplano derecho y el modo crece sin límite.")
|
| 361 |
+
return md
|
| 362 |
+
if n == 2:
|
| 363 |
+
so = segundo_orden(a)
|
| 364 |
+
if so is None:
|
| 365 |
+
md.append("El denominador no tiene la forma $s^2+2\\zeta\\omega_n s+\\omega_n^2$ con $\\omega_n^2>0$ "
|
| 366 |
+
"(hay un polo en el origen o polos reales de signo opuesto).")
|
| 367 |
+
dom = dominantes(polos)
|
| 368 |
+
if dom:
|
| 369 |
+
md.append(f"Polo dominante estable: ${fmtc(dom[0])}$.")
|
| 370 |
+
return md
|
| 371 |
+
wn, z = so
|
| 372 |
+
d = parametros_2o(wn, z)
|
| 373 |
+
md.append(eq(r"\omega_n = \sqrt{a_0/a_2} = " + fmt(wn) + r"\ \text{rad/s},\qquad \zeta = \frac{a_1}{2a_2\omega_n} = " + fmt(z)
|
| 374 |
+
+ r"\qquad(\text{" + regimen(z) + "})"))
|
| 375 |
+
if 0 < z < 1:
|
| 376 |
+
md.append(eq(r"s_{1,2} = -\zeta\omega_n \pm j\,\omega_n\sqrt{1-\zeta^2} = -" + fmt(d["sigma"]) + r" \pm j\," + fmt(d["wd"])
|
| 377 |
+
+ r",\qquad \sigma = " + fmt(d["sigma"]) + r",\ \ \omega_d = " + fmt(d["wd"])
|
| 378 |
+
+ r",\ \ \beta = \arccos\zeta = " + fmt(math.degrees(d["beta"])) + r"^{\circ}"))
|
| 379 |
+
md.append("$M_p$ depende solo de $\\zeta$; $t_s$ solo de $\\sigma=\\zeta\\omega_n$; $t_p$ solo de $\\omega_d$.")
|
| 380 |
+
elif abs(z - 1) < 1e-9:
|
| 381 |
+
md.append(f"Polo doble en $-\\omega_n={fmt(-wn)}$: la respuesta más rápida **sin** sobreoscilación.")
|
| 382 |
+
elif z > 1:
|
| 383 |
+
md.append(f"Dos polos reales distintos: lenta, sin sobreoscilación; domina el más cercano al origen.")
|
| 384 |
+
elif abs(z) < 1e-12:
|
| 385 |
+
md.append(f"Polos sobre el eje imaginario $\\pm j{fmt(wn)}$: oscilación mantenida, no se estabiliza.")
|
| 386 |
+
if m >= 1:
|
| 387 |
+
for zz, _, _ in agrupa(ceros):
|
| 388 |
+
if abs(zz.imag) < 1e-9 and zz.real < -1e-9 and z > 0:
|
| 389 |
+
rz = -zz.real / (z * wn)
|
| 390 |
+
if rz > 10:
|
| 391 |
+
txt = "despreciable: valen las fórmulas de la tabla"
|
| 392 |
+
elif rz >= 2:
|
| 393 |
+
txt = "$M_p$ aumenta apreciablemente y $t_r$ disminuye"
|
| 394 |
+
else:
|
| 395 |
+
txt = "$M_p$ puede duplicarse o más respecto de lo previsto"
|
| 396 |
+
md.append(f"Cero en $s={fmt(zz.real)}$, a ${fmt(rz)}$ veces $\\zeta\\omega_n$: efecto {txt}.")
|
| 397 |
+
return md
|
| 398 |
+
dom = dominantes(polos)
|
| 399 |
+
if dom:
|
| 400 |
+
pd, r = dom
|
| 401 |
+
md.append(f"Sistema de orden {n}. Polo (o par) dominante: ${fmtc(pd)}$" + (f", par con $\\zeta={fmt(-pd.real / abs(pd))}$ y $\\omega_n={fmt(abs(pd))}$" if abs(pd.imag) > 1e-9 else "") + ".")
|
| 402 |
+
if np.isfinite(r):
|
| 403 |
+
if r >= 10:
|
| 404 |
+
txt = "el resto de polos es invisible: a todos los efectos se comporta como el par dominante"
|
| 405 |
+
elif r >= 5:
|
| 406 |
+
txt = "$M_p$ baja algo y $t_s$ sube un 10–20 % respecto del par dominante"
|
| 407 |
+
else:
|
| 408 |
+
txt = "el resto de polos **compite**: no vale la aproximación de segundo orden"
|
| 409 |
+
md.append(f"Cociente $r = p/\\zeta\\omega_n = {fmt(r)}$: {txt}.")
|
| 410 |
+
else:
|
| 411 |
+
md.append(f"Sistema de orden {n} sin polos estables dominantes.")
|
| 412 |
+
return md
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def fracciones_md(Y, entera, modos):
|
| 416 |
+
md = []
|
| 417 |
+
if entera:
|
| 418 |
+
md.append("El grado del numerador no es menor que el del denominador: se divide antes y queda una parte entera $"
|
| 419 |
+
+ poly_tex(entera) + "$.")
|
| 420 |
+
md.append(f"Polos de $Y(s)$: ${lista_raices_tex(Y.polos())}$.")
|
| 421 |
+
sencillos = [m_ for m_ in modos if m_["tipo"] == "real" and m_["m"] == 1]
|
| 422 |
+
if sencillos:
|
| 423 |
+
lineas = []
|
| 424 |
+
for i, m_ in enumerate(sencillos, start=1):
|
| 425 |
+
p = m_["p"].real
|
| 426 |
+
fac = "s" if abs(p) < 1e-12 else "(s" + (" + " if p < 0 else " - ") + fmtq(abs(p)) + ")"
|
| 427 |
+
lineas.append(r"A_{" + str(i) + r"} = \Bigl[" + fac + r"\,Y(s)\Bigr]_{s=" + fmt(p) + "} = " + fmtq(m_["A"][0].real))
|
| 428 |
+
md.append("Polos reales simples: basta tapar el factor y evaluar,")
|
| 429 |
+
md.append(eq(r"\begin{aligned}" + r"\\ ".join(lineas) + r"\end{aligned}"))
|
| 430 |
+
if any(m_["tipo"] == "par" for m_ in modos):
|
| 431 |
+
md.append("Pares complejos: el término $\\frac{Bs+C}{(s+a)^2+\\omega^2}$ se escribe completando cuadrados como "
|
| 432 |
+
"$B\\frac{s+a}{(s+a)^2+\\omega^2}+\\frac{C-Ba}{\\omega}\\frac{\\omega}{(s+a)^2+\\omega^2}$.")
|
| 433 |
+
if any(m_["m"] > 1 for m_ in modos):
|
| 434 |
+
md.append("Polos múltiples: un término por cada potencia, $\\frac{A_1}{s-p}+\\dots+\\frac{A_m}{(s-p)^m}$; "
|
| 435 |
+
"los coeficientes se obtienen identificando potencias de $s$.")
|
| 436 |
+
md.append(eq("Y(s) = " + fracciones_tex(entera, modos)))
|
| 437 |
+
return md
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def teoricos(G):
|
| 441 |
+
"""Lo que predicen las fórmulas de los apuntes (1.er orden o 2.º orden subamortiguado)."""
|
| 442 |
+
if G.n == 1 and abs(G.den[1]) > 1e-14 and G.m == 0:
|
| 443 |
+
tau = G.den[0] / G.den[1]
|
| 444 |
+
if tau > 0:
|
| 445 |
+
return {"td": (r"0.69\tau", 0.69 * tau), "tr": (r"2.2\tau", 2.2 * tau),
|
| 446 |
+
"ts2": (r"4\tau", 4 * tau), "ts5": (r"3\tau", 3 * tau), "Mp": ("0", 0.0),
|
| 447 |
+
"_origen": "de primer orden."}
|
| 448 |
+
elif G.n == 2:
|
| 449 |
+
so = segundo_orden(G.den)
|
| 450 |
+
if so and 0 < so[1] < 1:
|
| 451 |
+
d = parametros_2o(*so)
|
| 452 |
+
return {"td": (r"\frac{1+0.7\zeta}{\omega_n}", d["td"]), "tr": (r"\frac{\pi-\beta}{\omega_d}", d["tr"]),
|
| 453 |
+
"tp": (r"\frac{\pi}{\omega_d}", d["tp"]),
|
| 454 |
+
"Mp": (r"e^{-\pi\zeta/\sqrt{1-\zeta^2}}", d["Mp"]),
|
| 455 |
+
"ts2": (r"\frac{4}{\zeta\omega_n}", d["ts2"]), "ts5": (r"\frac{3}{\zeta\omega_n}", d["ts5"]),
|
| 456 |
+
"_origen": "de segundo orden" + (" puro (aquí hay ceros)." if G.m > 0 else ".")}
|
| 457 |
+
return {}
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def tabla_especificaciones(G, met, ent):
|
| 461 |
+
A = float(ent.limite) if ent.limite else 1.0
|
| 462 |
+
teor = teoricos(G)
|
| 463 |
+
filas = [("td", "Tiempo de retardo $t_d$ (50 %)", "s"), ("tr", f"Tiempo de subida $t_r$ ({met['tr_def']})", "s"),
|
| 464 |
+
("tp", "Tiempo de pico $t_p$", "s"), ("Mp", "Sobreoscilación $M_p$", "%"),
|
| 465 |
+
("ts2", "Establecimiento $t_s$ (2 %)", "s"), ("ts5", "Establecimiento $t_s$ (5 %)", "s")]
|
| 466 |
+
md = ["| Magnitud | Fórmula | Teórico | Medido sobre la curva |", "|:--|:--:|:--:|:--:|"]
|
| 467 |
+
for k, nombre, u in filas:
|
| 468 |
+
f, v = teor.get(k, ("—", None))
|
| 469 |
+
med = met.get(k, math.nan)
|
| 470 |
+
mtxt = "—" if (med is None or (isinstance(med, float) and math.isnan(med))) else f"{num(med)} {u}"
|
| 471 |
+
if k == "tp" and met.get("Mp", 0) == 0:
|
| 472 |
+
mtxt = "no hay pico"
|
| 473 |
+
md.append(f"| {nombre} | {'$' + f + '$' if f != '—' else '—'} | {('—' if v is None else num(v) + ' ' + u)} | {mtxt} |")
|
| 474 |
+
nota = ("Las fórmulas de segundo orden suponen un sistema **puro**, sin ceros ni más polos: "
|
| 475 |
+
"la diferencia con lo medido es justo el efecto de lo que se ha añadido.") if G.m > 0 or G.n > 2 else \
|
| 476 |
+
("Las fórmulas de $t_s$ usan la envolvente $e^{-\\zeta\\omega_n t}$ y por eso son algo conservadoras." if G.n == 2 else "")
|
| 477 |
+
if A != 1:
|
| 478 |
+
nota += f" Los tiempos no dependen de la amplitud del escalón ({num(A)}); $M_p$ se mide respecto del valor final."
|
| 479 |
+
return ["\n".join(md)] + ([nota] if nota else [])
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# =====================================================================
|
| 483 |
+
# Pestaña 2: diagramas de bloques, lazo abierto y lazo cerrado
|
| 484 |
+
# =====================================================================
|
| 485 |
+
def diagrama(topo, g1, g2, h1, h2, negativa, resta):
|
| 486 |
+
negativa = negativa.startswith("Negativa")
|
| 487 |
+
resta = resta == "G₁ − G₂"
|
| 488 |
+
textos = {"G1": g1, "G2": g2, "H1": h1, "H2": h2}
|
| 489 |
+
try:
|
| 490 |
+
subs = {bl.SIMB[k]: parse_ft(textos[k]) for k in bl.BLOQUES_USADOS[topo]}
|
| 491 |
+
F, ecs = bl.formula(topo, negativa, resta)
|
| 492 |
+
T = bl.evalua(F, subs)
|
| 493 |
+
Tm, g = T.simplificada()
|
| 494 |
+
except Exception as e: # noqa: BLE001
|
| 495 |
+
f = gf.figura_error(str(e))
|
| 496 |
+
return error_md(e), f, f, f
|
| 497 |
+
h2_uno = topo == "Lazos anidados" and subs[bl.H2].sym() == 1
|
| 498 |
+
md = ["### 1. Los bloques"]
|
| 499 |
+
for k in bl.BLOQUES_USADOS[topo]:
|
| 500 |
+
sub = k[0] + "_" + k[1]
|
| 501 |
+
md.append(eq(sub + "(s) = " + subs[bl.SIMB[k]].tex()))
|
| 502 |
+
md.append("### 2. Ecuaciones de señales (el método que nunca falla)")
|
| 503 |
+
md.append("Se nombra cada señal intermedia y se escribe una ecuación por cada bloque y cada punto de suma:")
|
| 504 |
+
lineas, F_tex = bl.ecuaciones_tex(topo, negativa, resta)
|
| 505 |
+
md.append(eq(r"\begin{aligned}" + r"\\ ".join(lineas) + r"\end{aligned}"))
|
| 506 |
+
md.append("Sustituyendo hacia atrás y eliminando las señales intermedias:")
|
| 507 |
+
md.append(eq(r"\frac{Y(s)}{X(s)} = " + F_tex))
|
| 508 |
+
md += pasos_reduccion(topo, negativa, resta)
|
| 509 |
+
md.append("### 4. Sustitución de los bloques")
|
| 510 |
+
md.append(eq(r"\frac{Y(s)}{X(s)} = " + T.tex() + ((" = " + Tm.tex()) if g is not None else "")))
|
| 511 |
+
if g is not None:
|
| 512 |
+
rc = raices(g)
|
| 513 |
+
md.append(f"Al simplificar se cancela el factor común ${factor_tex(1.0, rc)}$ (raíces ${lista_raices_tex(rc, 'p')}$).")
|
| 514 |
+
if any(p.real >= -1e-9 for p, _ in rc):
|
| 515 |
+
md.append(caja("aviso", "Cancelación en el semiplano derecho",
|
| 516 |
+
"Se ha cancelado un polo con parte real no negativa. Sobre el papel la expresión se simplifica, "
|
| 517 |
+
"pero el modo inestable sigue ahí y el sistema real se dispara. Nunca se cancela un polo "
|
| 518 |
+
"inestable con un cero."))
|
| 519 |
+
else:
|
| 520 |
+
md.append("La cancelación es estable, legítima sobre el papel; en la planta real el polo sigue ahí y, si el modelo "
|
| 521 |
+
"tiene error, reaparece como un modo lento de amplitud pequeña.")
|
| 522 |
+
md.append(eq(r"\frac{Y(s)}{X(s)} = " + Tm.tex_factor()))
|
| 523 |
+
pc = Tm.polos()
|
| 524 |
+
md.append(f"Polos: ${lista_raices_tex(pc)}$. Ceros: ${lista_raices_tex(Tm.ceros(), 'z')}$. "
|
| 525 |
+
f"Estabilidad: **{estabilidad(pc)}**.")
|
| 526 |
+
md += explica_polos(Tm)
|
| 527 |
+
if Tm.n == 2 and Tm.m <= 1:
|
| 528 |
+
so = segundo_orden(Tm.den)
|
| 529 |
+
if so and so[1] > 0:
|
| 530 |
+
md.append(f"Segundo orden con $\\omega_n={fmt(so[0])}$ rad/s y $\\zeta={fmt(so[1])}$ ({regimen(so[1])})"
|
| 531 |
+
+ (f", $M_p={fmt(parametros_2o(*so)['Mp'])}\\,\\%$ si no hubiera ceros." if so[1] < 1 else "."))
|
| 532 |
+
Lsym = bl.ganancia_lazo(topo, negativa)
|
| 533 |
+
Lft = None
|
| 534 |
+
if Lsym is not None:
|
| 535 |
+
Lft, _ = bl.evalua(Lsym, subs).simplificada()
|
| 536 |
+
md.append("### 5. Lazo abierto y ecuación característica")
|
| 537 |
+
md.append(eq(r"L(s) = " + sp.latex(Lsym) + " = " + Lft.tex()))
|
| 538 |
+
md.append(eq(r"1 " + ("+" if negativa else "-") + r" L(s) = 0 \quad\Longrightarrow\quad " + poly_tex(T.den) + " = 0"))
|
| 539 |
+
md.append(f"Polos en lazo abierto: ${lista_raices_tex(Lft.polos())}$. La realimentación los desplaza a los de lazo cerrado.")
|
| 540 |
+
md.append(f"### {6 if Lsym is not None else 5}. Comprobación de la ganancia estática")
|
| 541 |
+
k0 = Tm.ganancia_estatica()
|
| 542 |
+
kd = bl.ganancia_estatica_diagrama(F, subs)
|
| 543 |
+
md.append(f"$G_{{eq}}(0) = {fmt(k0)}$, y recorriendo el diagrama con $s=0$ se obtiene ${fmt(kd.real if isinstance(kd, complex) else kd)}$"
|
| 544 |
+
+ (" ✓." if (np.isfinite(k0) and abs(k0 - (kd.real if isinstance(kd, complex) else kd)) < 1e-6 * max(1, abs(k0))) else "."))
|
| 545 |
+
|
| 546 |
+
# figuras
|
| 547 |
+
fd = bl.dibuja(topo, negativa, resta, h2_uno)
|
| 548 |
+
refs = Lft.polos_np() if Lft is not None else None
|
| 549 |
+
fp = gf.fig_plano_s(Tm.polos_np(), Tm.ceros_np(), polos_ref=refs, ref_label="lazo abierto", w=9.0, h=5.6)
|
| 550 |
+
T_hor = horizonte(list(Tm.polos_np()))
|
| 551 |
+
tt = np.linspace(0, T_hor, 1400)
|
| 552 |
+
R = crea_entrada("Escalón").ft()
|
| 553 |
+
if not Tm.propia():
|
| 554 |
+
return "\n\n".join(md), fd, fp, gf.figura_error("Y/X no es propia: no se puede simular.")
|
| 555 |
+
_, _, _, _, y = respuesta(Tm, R, tt)
|
| 556 |
+
ok, yinf, _ = valor_final(Tm * R)
|
| 557 |
+
extra = []
|
| 558 |
+
if topo in ("Lazo cerrado (realimentación)", "Lazos anidados"):
|
| 559 |
+
Gd = subs[bl.G1] * subs[bl.G2]
|
| 560 |
+
if Gd.propia():
|
| 561 |
+
_, _, _, _, yd = respuesta(Gd, R, tt)
|
| 562 |
+
extra.append((yd, "sin realimentar: $G_1G_2$"))
|
| 563 |
+
met = metricas_escalon(tt, y, yinf) if ok else None
|
| 564 |
+
fr = gf.fig_respuesta(tt, y, r=np.ones_like(tt), yinf=yinf if ok else None, met=met, extra=extra,
|
| 565 |
+
ylabel_curve=r"lazo cerrado $y(t)$", rlabel=r"escalón $x(t)$", w=10.0, h=4.8)
|
| 566 |
+
return "\n\n".join(md), fd, fp, fr
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def pasos_reduccion(topo, negativa, resta):
|
| 570 |
+
sg = "+" if negativa else "-"
|
| 571 |
+
md = ["### 3. Reducción con las reglas de asociación"]
|
| 572 |
+
if topo == "Serie":
|
| 573 |
+
md.append("La salida de cada bloque es la entrada del siguiente: las ganancias se multiplican, $G_{eq}=G_1G_2$.")
|
| 574 |
+
elif topo == "Paralelo":
|
| 575 |
+
md.append(f"$Y_1=XG_1$ e $Y_2=XG_2$, luego $Y = X(G_1 {'-' if resta else '+'} G_2)$.")
|
| 576 |
+
elif topo == "Lazo cerrado (realimentación)":
|
| 577 |
+
md.append(eq(r"\frac{Y}{X} = \frac{\text{camino directo}}{1 " + sg + r" \text{ganancia de lazo}} = \frac{G_1G_2}{1 " + sg + r" G_1G_2H_1}"))
|
| 578 |
+
md.append(f"con signo {'+' if negativa else '−'} en el denominador porque la realimentación es {'negativa' if negativa else 'positiva'}.")
|
| 579 |
+
else:
|
| 580 |
+
md.append("Los lazos están **anidados**, no cruzados. Paso 2: el interno se reduce primero,")
|
| 581 |
+
md.append(eq(r"G_{\text{int}} = \frac{G_2}{1 " + sg + r" G_2H_1}"))
|
| 582 |
+
md.append("Paso 3: en cascada con $G_1$, $\\;G_1G_{\\text{int}}$. Paso 2 de nuevo, con el lazo externo:")
|
| 583 |
+
md.append(eq(r"\frac{Y}{X} = \frac{G_1G_{\text{int}}}{1 " + sg + r" G_1G_{\text{int}}H_2} = \frac{G_1G_2}{1 " + sg + " G_2H_1 " + sg + " G_1G_2H_2}"))
|
| 584 |
+
return md
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# =====================================================================
|
| 588 |
+
# Pestaña 3: el controlador PID
|
| 589 |
+
# =====================================================================
|
| 590 |
+
def convierte_ganancias(forma, Kp, Ki, Kd, Ti, Td):
|
| 591 |
+
if forma.startswith("Estándar"):
|
| 592 |
+
Ki = Kp / Ti if Ti and Ti > 0 else 0.0
|
| 593 |
+
Kd = Kp * Td
|
| 594 |
+
return Kp, Ki, Kd
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def simular_pid(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, dmed, saturar, umin, umax,
|
| 598 |
+
aw, r_amp, t_fin, pert_amp, pert_t, cambio_r, r2_amp, r2_t, comparar, var_tray, espec=None):
|
| 599 |
+
"""Pestaña del PID: diagrama, señales, plano s y desarrollo."""
|
| 600 |
+
try:
|
| 601 |
+
G = parse_ft(planta)
|
| 602 |
+
Kp, Ki, Kd = convierte_ganancias(forma, Kp, Ki, Kd, Ti, Td)
|
| 603 |
+
usar = (usarP, usarI, usarD)
|
| 604 |
+
C, (kp, ki, kd) = pid_ft(Kp, Ki, Kd, N, usar)
|
| 605 |
+
if C == 0:
|
| 606 |
+
raise ValueError("Con todas las acciones desactivadas no hay controlador: active al menos una.")
|
| 607 |
+
T, L, car = lazo_cerrado(G, C)
|
| 608 |
+
pc = T.polos()
|
| 609 |
+
T_hor = t_fin if t_fin and t_fin > 0 else horizonte(T.polos_np(), minimo=2.0)
|
| 610 |
+
lims = dict(umin=umin if saturar else None, umax=umax if saturar else None)
|
| 611 |
+
pt = pert_t if (pert_amp and pert_amp != 0) else None
|
| 612 |
+
r2t = r2_t if cambio_r else None
|
| 613 |
+
for x in (pt, r2t):
|
| 614 |
+
if x is not None and x >= 0.75 * T_hor:
|
| 615 |
+
T_hor = x * 1.6
|
| 616 |
+
sim = simula_pid(G, Kp, Ki, Kd, N=N, usar=usar, deriv_medida=dmed, antiwindup=aw, r_amp=r_amp,
|
| 617 |
+
t_end=T_hor, pert_amp=pert_amp, pert_t=pt, r2_amp=r2_amp if cambio_r else None,
|
| 618 |
+
r2_t=r2t, **lims)
|
| 619 |
+
except Exception as e: # noqa: BLE001
|
| 620 |
+
f = gf.figura_error(str(e))
|
| 621 |
+
return error_md(e), f, f, f, f
|
| 622 |
+
md = []
|
| 623 |
+
md.append("### 1. El controlador")
|
| 624 |
+
nombre = "".join(k for k, u_, g_ in zip("PID", usar, (kp, ki, kd)) if u_ and g_)
|
| 625 |
+
md.append(f"Controlador **{nombre or '—'}** en forma paralela $C(s)=K_p+\\frac{{K_i}}{{s}}+K_d\\,s$ y en forma estándar (ISA) "
|
| 626 |
+
"$C(s)=K_p\\left(1+\\frac{1}{T_is}+T_ds\\right)$, con $T_i=K_p/K_i$ y $T_d=K_d/K_p$:")
|
| 627 |
+
Ti_ = kp / ki if ki else math.inf
|
| 628 |
+
Td_ = kd / kp if kp else (math.inf if kd else 0.0)
|
| 629 |
+
md.append(eq(r"K_p = " + fmt(kp) + r",\quad K_i = " + fmt(ki) + r",\quad K_d = " + fmt(kd)
|
| 630 |
+
+ r"\qquad\Longleftrightarrow\qquad T_i = " + fmt(Ti_) + r"\ \text{s},\quad T_d = " + fmt(Td_) + r"\ \text{s}"))
|
| 631 |
+
Cft = FT.expr(C)
|
| 632 |
+
md.append(eq(r"C(s) = " + Cft.tex() + (r" = " + Cft.tex_factor() if Cft.m > 0 and Cft.tex_factor() != Cft.tex() else "")))
|
| 633 |
+
if ki:
|
| 634 |
+
md.append("La acción integral pone un polo en el origen: sube el tipo del lazo en una unidad y anula el error "
|
| 635 |
+
"permanente ante escalón.")
|
| 636 |
+
if Cft.m > 0:
|
| 637 |
+
md.append(f"Ceros del controlador: ${lista_raices_tex(Cft.ceros(), 'z')}$. Son los que atraen a los polos del lazo "
|
| 638 |
+
"cerrado al subir la ganancia (figura del plano $s$).")
|
| 639 |
+
if N and N > 0 and kd:
|
| 640 |
+
md.append(f"Derivada filtrada: $K_d s/(1+T_f s)$ con $T_f=T_d/N={fmt(Td_ / N)}$ s ($N={fmt(N)}$), que limita la "
|
| 641 |
+
"ganancia a alta frecuencia y añade un polo rápido en $-1/T_f$.")
|
| 642 |
+
if sim.get("nota"):
|
| 643 |
+
md.append("Nota: " + sim["nota"] + ".")
|
| 644 |
+
if dmed and kd:
|
| 645 |
+
md.append("Derivada **sobre la medida**: se deriva $-y(t)$ en vez de $e(t)$. Los polos son los mismos, pero los "
|
| 646 |
+
"cambios de consigna ya no golpean al actuador (desaparece el impulso derivativo).")
|
| 647 |
+
md.append("### 2. Lazo abierto y lazo cerrado")
|
| 648 |
+
md.append(eq(r"G(s) = " + G.tex() + r",\qquad L(s) = C(s)G(s) = " + L.tex()))
|
| 649 |
+
md.append(eq(r"T(s) = \frac{Y(s)}{R(s)} = \frac{C(s)G(s)}{1 + C(s)G(s)} = " + T.tex()))
|
| 650 |
+
md.append("Ecuación característica:")
|
| 651 |
+
md.append(eq(r"1 + C(s)G(s) = 0 \quad\Longrightarrow\quad " + poly_tex([float(c) for c in car.all_coeffs()], q=False) + " = 0"))
|
| 652 |
+
est = estabilidad(pc)
|
| 653 |
+
md.append(f"Polos del lazo cerrado (raíces de la ecuación característica): ${lista_raices_tex(pc)}$.")
|
| 654 |
+
md += explica_polos(T)
|
| 655 |
+
dom = dominantes(pc)
|
| 656 |
+
if est == "estable" and dom and abs(dom[0].imag) > 1e-9:
|
| 657 |
+
pd, rr = dom
|
| 658 |
+
zeta, wn = -pd.real / abs(pd), abs(pd)
|
| 659 |
+
mp2 = parametros_2o(wn, zeta).get("Mp", math.nan)
|
| 660 |
+
md.append(f"Si el lazo fuera un segundo orden puro con ese par, tendría $M_p={fmt(mp2)}\\,\\%$ y $t_s\\approx{fmt(4 / -pd.real)}$ s; "
|
| 661 |
+
"la diferencia con lo medido abajo es el efecto de los ceros y de los demás polos.")
|
| 662 |
+
md.append("### 3. Régimen permanente")
|
| 663 |
+
if est == "estable":
|
| 664 |
+
ce = constantes_error(L)
|
| 665 |
+
md.append(f"Tipo del lazo: **{ce['tipo']}** (número de integradores de $L(s)$). Constantes de error: "
|
| 666 |
+
f"$K_{{pos}}=\\lim_{{s\\to0}}L(s)={fmt(ce['Kpos'])}$, $K_v=\\lim_{{s\\to0}}sL(s)={fmt(ce['Kv'])}$, "
|
| 667 |
+
f"$K_a=\\lim_{{s\\to0}}s^2L(s)={fmt(ce['Ka'])}$.")
|
| 668 |
+
md.append("| Entrada | Error permanente |\n|:--|:--:|\n"
|
| 669 |
+
f"| escalón | $\\frac{{1}}{{1+K_{{pos}}}}={fmt(ce['e_escalon'])}$ |\n"
|
| 670 |
+
f"| rampa | $\\frac{{1}}{{K_v}}={fmt(ce['e_rampa'])}$ |\n"
|
| 671 |
+
f"| parábola | $\\frac{{1}}{{K_a}}={fmt(ce['e_parabola'])}$ |")
|
| 672 |
+
else:
|
| 673 |
+
md.append("El lazo no es estable: no tiene sentido hablar de régimen permanente (el teorema del valor final no se aplica).")
|
| 674 |
+
# medidas sobre el primer escalón
|
| 675 |
+
tt = sim["t"]
|
| 676 |
+
yinf = float(T.N.eval(0) / T.D.eval(0)) * r_amp if (est == "estable" and T.D.eval(0) != 0) else None
|
| 677 |
+
t_corte = min([x for x in (pt, r2t) if x is not None] + [math.inf])
|
| 678 |
+
corte = tt < t_corte
|
| 679 |
+
met = metricas_escalon(tt[corte], sim["y"][corte], yinf) if yinf else None
|
| 680 |
+
md.append("### 4. Lo que se mide en la simulación")
|
| 681 |
+
if met:
|
| 682 |
+
umax_ = float(np.max(np.abs(sim["u"])))
|
| 683 |
+
md.append(f"| $M_p$ | $t_p$ | $t_r$ ({met['tr_def']}) | $t_s$ (2 %) | $y(\\infty)$ | error final | $\\max|u|$ |\n"
|
| 684 |
+
"|:--:|:--:|:--:|:--:|:--:|:--:|:--:|\n"
|
| 685 |
+
f"| {num(met['Mp'])} % | {num(met['tp'])} s | {num(met['tr'])} s | {num(met['ts2'])} s | {num(yinf)} | "
|
| 686 |
+
f"{num(r_amp - yinf)} | {num(umax_)} |")
|
| 687 |
+
if sim["impulsos"]:
|
| 688 |
+
md.append(f"Con derivada ideal sobre el error, cada escalón de consigna produce en $u$ un impulso $K_d\\,\\Delta r\\,\\delta(t)$ "
|
| 689 |
+
f"(área {num(sim['impulsos'][0][1])}): es el «golpe» al actuador que evitan el filtro y la derivada sobre la medida.")
|
| 690 |
+
if espec:
|
| 691 |
+
ok_m = met["Mp"] <= espec["Mp"] * 1.02 + 0.2
|
| 692 |
+
tsm = met["ts2" if espec["banda"] == 2 else "ts5"]
|
| 693 |
+
ok_t = np.isfinite(tsm) and tsm <= espec["ts"] * 1.02
|
| 694 |
+
md.append(f"Especificaciones del diseño: $M_p\\le{num(espec['Mp'])}$ % {'✓' if ok_m else '✗'} · "
|
| 695 |
+
f"$t_s\\le{num(espec['ts'])}$ s {'✓' if ok_t else '✗'}.")
|
| 696 |
+
elif est != "estable":
|
| 697 |
+
md.append("Respuesta divergente u oscilación mantenida: no se miden especificaciones.")
|
| 698 |
+
# el PID de libro frente al configurado
|
| 699 |
+
comunes = dict(usar=usar, r_amp=r_amp, t_end=T_hor, pert_amp=pert_amp, pert_t=pt,
|
| 700 |
+
r2_amp=r2_amp if cambio_r else None, r2_t=r2t)
|
| 701 |
+
try:
|
| 702 |
+
ideal = simula_pid(G, Kp, Ki, Kd, N=0, deriv_medida=False, **comunes)
|
| 703 |
+
except Exception: # noqa: BLE001
|
| 704 |
+
ideal = sim
|
| 705 |
+
alternativa = None
|
| 706 |
+
if saturar:
|
| 707 |
+
sin_aw = aw.startswith("Ninguno")
|
| 708 |
+
otro = "Congelar el integrador mientras satura" if sin_aw else "Ninguno"
|
| 709 |
+
try:
|
| 710 |
+
alt = simula_pid(G, Kp, Ki, Kd, N=N, deriv_medida=dmed, antiwindup=otro, **comunes, **lims)
|
| 711 |
+
alternativa = (alt, "con límites y anti-windup" if sin_aw else "con límites, sin anti-windup")
|
| 712 |
+
except Exception: # noqa: BLE001
|
| 713 |
+
alternativa = None
|
| 714 |
+
ruido = ruido_derivada(kd, kp, N, T_hor, r_amp)
|
| 715 |
+
md += pid_real_md(kd, N, dmed, saturar, umin, umax, aw, sim, ideal, alternativa, ruido, yinf, t_corte)
|
| 716 |
+
md += consejos_pid(est, met, r_amp, yinf, kp, ki, kd, espec)
|
| 717 |
+
# comparación
|
| 718 |
+
comps = []
|
| 719 |
+
if comparar:
|
| 720 |
+
for lab, us in (("solo P", (True, False, False)), ("PI", (True, True, False)), ("PD", (True, False, True))):
|
| 721 |
+
if us == tuple(u_ and g_ != 0 for u_, g_ in zip(usar, (kp, ki, kd))):
|
| 722 |
+
continue
|
| 723 |
+
if (us[1] and not ki) or (us[2] and not kd) or not kp:
|
| 724 |
+
continue
|
| 725 |
+
try:
|
| 726 |
+
comps.append((lab, simula_pid(G, Kp, Ki, Kd, N=N, usar=us, deriv_medida=dmed, antiwindup=aw, r_amp=r_amp,
|
| 727 |
+
t_end=T_hor, pert_amp=pert_amp, pert_t=pt,
|
| 728 |
+
r2_amp=r2_amp if cambio_r else None, r2_t=r2t, **lims)))
|
| 729 |
+
except Exception: # noqa: BLE001
|
| 730 |
+
pass
|
| 731 |
+
esp_fig = None
|
| 732 |
+
if espec and yinf:
|
| 733 |
+
esp_fig = {"Mp": espec["Mp"], "ts": espec["ts"], "yinf": yinf}
|
| 734 |
+
f1 = gf.fig_pid(sim, comparar=comps, pert_t=pt, espec=esp_fig, **lims)
|
| 735 |
+
var = {"Kp": "K_p", "Ki": "K_i", "Kd": "K_d"}[var_tray]
|
| 736 |
+
try:
|
| 737 |
+
tray = trayectoria_polos(G, kp, ki, kd, N, (True, True, True), var)
|
| 738 |
+
except Exception: # noqa: BLE001
|
| 739 |
+
tray = None
|
| 740 |
+
region = None
|
| 741 |
+
deseados = None
|
| 742 |
+
if espec:
|
| 743 |
+
region = {"sigma": espec["sigma"], "beta": espec["beta"], "banda": espec["banda"]}
|
| 744 |
+
deseados = [complex(-espec["sigma"], espec["wd"]), complex(-espec["sigma"], -espec["wd"])]
|
| 745 |
+
f2 = gf.fig_plano_s(T.polos_np(), T.ceros_np(), polos_ref=G.polos_np(), ref_label="la planta", tray=tray,
|
| 746 |
+
region=region, deseados=deseados, w=9.0, h=5.6)
|
| 747 |
+
f0 = bl.dibuja_pid(G, kp, ki, kd, usar, N=N, deriv_medida=dmed, saturar=saturar, umin=umin, umax=umax,
|
| 748 |
+
perturbacion=bool(pt is not None))
|
| 749 |
+
f3 = gf.fig_pid_real(ideal, sim, alternativa, ruido, **lims)
|
| 750 |
+
return "\n\n".join(md), f0, f1, f3, f2
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def consejos_pid(est, met, r_amp, yinf, kp, ki, kd, espec):
|
| 754 |
+
"""Qué ganancia mover a la vista de la respuesta (resumen operativo de los apuntes)."""
|
| 755 |
+
md = ["### 6. ¿Qué tocar ahora?"]
|
| 756 |
+
pasos = []
|
| 757 |
+
if est != "estable":
|
| 758 |
+
pasos.append("El lazo es **inestable**: baje $K_p$ o $K_i$ (o suba $K_d$). La animación *barrido de una ganancia* "
|
| 759 |
+
"dice exactamente a partir de qué valor se pierde la estabilidad.")
|
| 760 |
+
elif met:
|
| 761 |
+
err = abs(r_amp - yinf) if yinf is not None else 0.0
|
| 762 |
+
if err > 1e-3 * max(1.0, abs(r_amp)):
|
| 763 |
+
pasos.append(f"Queda un **error permanente** de {num(err)}: active o suba la acción integral ($K_i$). "
|
| 764 |
+
"Subir $K_p$ lo reduce, pero no lo anula nunca.")
|
| 765 |
+
mp_lim = espec["Mp"] if espec else 20.0
|
| 766 |
+
if met["Mp"] > mp_lim:
|
| 767 |
+
pasos.append(f"**Se pasa demasiado** ($M_p$ = {num(met['Mp'])} %): suba $K_d$ para amortiguar, o baje $K_i$ "
|
| 768 |
+
"o $K_p$.")
|
| 769 |
+
lento = espec and np.isfinite(met["ts2"]) and met["ts2"] > espec["ts"] * 1.02
|
| 770 |
+
if lento:
|
| 771 |
+
pasos.append(f"**Tarda más de lo exigido** ($t_s$ = {num(met['ts2'])} s): suba $K_p$, y $K_d$ si con ello "
|
| 772 |
+
"aparece sobreoscilación.")
|
| 773 |
+
elif met["Mp"] < 0.5 and not espec:
|
| 774 |
+
pasos.append("No hay sobreoscilación: si quiere una respuesta **más rápida**, suba $K_p$ (aparecerá algo de "
|
| 775 |
+
"sobreoscilación, que puede compensar con $K_d$).")
|
| 776 |
+
if not pasos:
|
| 777 |
+
pasos.append("La respuesta es razonable: llega a la consigna sin error y sin pasarse demasiado. Pruebe a mover "
|
| 778 |
+
"cada ganancia por separado y compare con la tabla.")
|
| 779 |
+
else:
|
| 780 |
+
pasos.append("No se ha podido medir la respuesta (no hay un valor final claro).")
|
| 781 |
+
md.append("\n".join("- " + p for p in pasos))
|
| 782 |
+
md.append("| Al aumentar | $t_r$ | $M_p$ | $t_s$ | Error permanente |\n|:--|:--:|:--:|:--:|:--:|\n"
|
| 783 |
+
"| $K_p$ | disminuye | aumenta | cambia poco | disminuye |\n"
|
| 784 |
+
"| $K_i$ | disminuye | aumenta | aumenta | **se anula** |\n"
|
| 785 |
+
"| $K_d$ | cambia poco | disminuye | disminuye | no cambia |")
|
| 786 |
+
md.append("La tabla es orientativa: cerca del límite de estabilidad, subir $K_p$ o $K_i$ empeora todo a la vez. "
|
| 787 |
+
"Para cumplir unas especificaciones concretas, use el **diseño por asignación de polos**.")
|
| 788 |
+
return md
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def ruido_derivada(kd, kp, N, T, amp):
|
| 792 |
+
"""Acción derivativa que produce un ruido de medida del 1 %: ideal frente a filtrada."""
|
| 793 |
+
if not kd:
|
| 794 |
+
return None
|
| 795 |
+
Tw = max(T * 0.3, 1e-3)
|
| 796 |
+
tt = np.linspace(0.0, Tw, 1201)
|
| 797 |
+
dt = tt[1] - tt[0]
|
| 798 |
+
rng = np.random.default_rng(7)
|
| 799 |
+
n = 0.01 * max(abs(amp), 1e-3) * rng.standard_normal(tt.size)
|
| 800 |
+
ideal = kd * np.gradient(n, dt)
|
| 801 |
+
Nu = N if (N and N > 0) else 10.0
|
| 802 |
+
Td = kd / kp if kp else kd
|
| 803 |
+
Tf = Td / Nu
|
| 804 |
+
_, filtro, _ = signal.lsim(([kd, 0.0], [Tf, 1.0]), n, tt)
|
| 805 |
+
return {"t": tt, "ideal": ideal, "filtro": filtro, "N": Nu, "usado": bool(N and N > 0)}
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def pid_real_md(kd, N, dmed, saturar, umin, umax, aw, sim, ideal, alternativa, ruido, yinf, t_corte):
|
| 809 |
+
"""Los tres problemas prácticos del PID, explicados con lo que se mide en la simulación."""
|
| 810 |
+
md = ["### 5. El PID real, explicado sin fórmulas",
|
| 811 |
+
"El PID «de libro» (el de la fórmula $K_p+K_i/s+K_d s$) no se pone nunca tal cual en una máquina, por tres "
|
| 812 |
+
"problemas prácticos. La **figura 3.3** compara ese PID ideal (azul, discontinuo) con el que usted ha configurado "
|
| 813 |
+
"(negro)."]
|
| 814 |
+
# 1. ruido
|
| 815 |
+
if not kd:
|
| 816 |
+
md.append("**① La derivada amplifica el ruido del sensor.** Ahora no hay acción derivativa, así que este problema no existe.")
|
| 817 |
+
else:
|
| 818 |
+
si = float(np.std(ruido["ideal"]))
|
| 819 |
+
sf = float(np.std(ruido["filtro"]))
|
| 820 |
+
txt = ("**① La derivada amplifica el ruido del sensor.** Toda medida real tiene un poco de ruido. La derivada "
|
| 821 |
+
"mide lo deprisa que cambia la señal, y el ruido cambia muy deprisa, así que la acción D lo convierte en "
|
| 822 |
+
"golpes continuos al actuador (figura 3.3c, en rojo). **Solución:** filtrar la derivada, es decir, "
|
| 823 |
+
"suavizarla (control *N*). ")
|
| 824 |
+
if ruido["usado"]:
|
| 825 |
+
txt += (f"Con su filtro ($N={fmt(N)}$), un ruido del 1 % produce una acción D de unos ±{num(sf, 2)} en lugar de "
|
| 826 |
+
f"±{num(si, 2)}: **{si / sf:.1f} veces menos**." if sf else "")
|
| 827 |
+
else:
|
| 828 |
+
txt += (f"Ahora no hay filtro ($N=0$): el ruido del 1 % produce una acción D de unos ±{num(si, 2)}. En la figura "
|
| 829 |
+
f"se ve cómo quedaría con un filtro típico $N=10$: ±{num(sf, 2)}.")
|
| 830 |
+
md.append(txt)
|
| 831 |
+
# 2. golpe por cambio de consigna
|
| 832 |
+
if not kd:
|
| 833 |
+
md.append("**② El golpe al cambiar la consigna.** Sin acción derivativa tampoco hay golpe.")
|
| 834 |
+
else:
|
| 835 |
+
txt = ("**② Al cambiar la consigna, la derivada da un golpe.** Si la consigna salta de repente, el error también "
|
| 836 |
+
"salta, y la derivada de un salto es un pico instantáneo (un impulso): la flecha roja de la figura 3.3b. "
|
| 837 |
+
"Una válvula o un motor no deben recibir eso. **Solución:** derivar solo la medida $y$, que nunca salta, "
|
| 838 |
+
"en lugar del error (casilla «Derivar la medida»). ")
|
| 839 |
+
if dmed:
|
| 840 |
+
txt += ("Está activado: el golpe desaparece. Los polos del lazo son los mismos, aunque la salida arranca algo más "
|
| 841 |
+
"despacio porque la acción D ya no empuja al principio.")
|
| 842 |
+
elif N and N > 0:
|
| 843 |
+
txt += (f"Con el filtro, el golpe ya no es infinito: el pico de $u$ queda en {num(float(np.max(np.abs(sim['u']))))}. "
|
| 844 |
+
"Derivando la medida desaparecería del todo.")
|
| 845 |
+
elif sim["impulsos"]:
|
| 846 |
+
txt += f"Ahora el actuador recibe un impulso de área {num(sim['impulsos'][0][1])}."
|
| 847 |
+
md.append(txt)
|
| 848 |
+
# 3. saturación y windup
|
| 849 |
+
txt = ("**③ El actuador tiene límites y el integrador se «carga» (windup).** Una válvula no abre más del 100 %, ni un "
|
| 850 |
+
"motor da más par del que tiene. Mientras el actuador está al tope, el error sigue ahí y la parte integral lo "
|
| 851 |
+
"sigue sumando: se «carga». Cuando por fin la salida llega a la consigna, esa carga acumulada la empuja de más, "
|
| 852 |
+
"y se pasa mucho y tarda en volver. **Solución:** el *anti-windup*, que deja de integrar mientras el actuador "
|
| 853 |
+
"está al tope. ")
|
| 854 |
+
if not saturar:
|
| 855 |
+
txt += "Ahora el actuador no tiene límites (casilla desactivada), así que este problema no aparece."
|
| 856 |
+
md.append(txt)
|
| 857 |
+
return md
|
| 858 |
+
md.append(txt)
|
| 859 |
+
|
| 860 |
+
def mide(s):
|
| 861 |
+
if yinf is None:
|
| 862 |
+
return None
|
| 863 |
+
m = s["t"] < t_corte
|
| 864 |
+
return metricas_escalon(s["t"][m], s["y"][m], yinf)
|
| 865 |
+
filas = [("PID ideal, sin límites", mide(ideal))]
|
| 866 |
+
sin_aw = aw.startswith("Ninguno")
|
| 867 |
+
if alternativa:
|
| 868 |
+
if sin_aw:
|
| 869 |
+
filas += [("con límites, sin anti-windup (su configuración)", mide(sim)), (alternativa[1], mide(alternativa[0]))]
|
| 870 |
+
else:
|
| 871 |
+
filas += [(alternativa[1], mide(alternativa[0])), ("con límites y anti-windup (su configuración)", mide(sim))]
|
| 872 |
+
else:
|
| 873 |
+
filas.append(("su configuración", mide(sim)))
|
| 874 |
+
if all(m for _, m in filas):
|
| 875 |
+
tabla = ["| Caso | $M_p$ | $t_s$ (2 %) |", "|:--|:--:|:--:|"]
|
| 876 |
+
tabla += [f"| {n_} | {num(m['Mp'])} % | {num(m['ts2'])} s |" for n_, m in filas]
|
| 877 |
+
md.append(f"Con el actuador limitado a [{num(umin)}, {num(umax)}]:\n\n" + "\n".join(tabla))
|
| 878 |
+
md.append("En la figura 3.3b se ve la causa: la parte integral (raya y punto) sigue creciendo mientras $u$ está "
|
| 879 |
+
"pegada al límite si no hay anti-windup, y se queda quieta si lo hay.")
|
| 880 |
+
return md
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def disenar_para_pid(planta, tipo, Mp, ts, banda, r_extra):
|
| 884 |
+
"""Asignación de polos dentro de la pestaña del PID: desarrollo, ganancias y especificaciones."""
|
| 885 |
+
md, _, _, ganancias = disenar(planta, tipo, Mp, ts, banda, r_extra, 0)
|
| 886 |
+
bnd = 2 if banda.startswith("2") else 5
|
| 887 |
+
esp = None
|
| 888 |
+
try:
|
| 889 |
+
e = especificaciones_a_polos(Mp, ts, bnd)
|
| 890 |
+
esp = {"Mp": Mp, "ts": ts, "banda": bnd, "sigma": e["sigma"], "beta": e["beta"], "wd": e["wd"], "tipo": tipo}
|
| 891 |
+
except Exception: # noqa: BLE001
|
| 892 |
+
pass
|
| 893 |
+
return md, ganancias, esp
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
# =====================================================================
|
| 897 |
+
# Pestaña 4: diseño por asignación de polos
|
| 898 |
+
# =====================================================================
|
| 899 |
+
def disenar(planta, tipo, Mp, ts, banda, r_extra, N_sim):
|
| 900 |
+
banda = 2 if banda.startswith("2") else 5
|
| 901 |
+
try:
|
| 902 |
+
G = parse_ft(planta)
|
| 903 |
+
if Mp <= 0 or Mp >= 100:
|
| 904 |
+
raise ValueError("La sobreoscilación debe estar entre 0 y 100 %.")
|
| 905 |
+
if ts <= 0:
|
| 906 |
+
raise ValueError("El tiempo de establecimiento debe ser positivo.")
|
| 907 |
+
d = asigna_polos(G, tipo, Mp, ts, banda, r_extra)
|
| 908 |
+
except Exception as e: # noqa: BLE001
|
| 909 |
+
f = gf.figura_error(str(e))
|
| 910 |
+
return error_md(e), f, f, None
|
| 911 |
+
esp = d["esp"]
|
| 912 |
+
z, sg, wn, wd = esp["zeta"], esp["sigma"], esp["wn"], esp["wd"]
|
| 913 |
+
md = ["### 1. La planta"]
|
| 914 |
+
md.append(eq("G(s) = " + G.tex() + (" = " + G.tex_factor() if G.tex_factor() != G.tex() else "")))
|
| 915 |
+
md.append("### 2. De las especificaciones a $\\zeta$ y $\\omega_n$")
|
| 916 |
+
lnM = math.log(Mp / 100)
|
| 917 |
+
md.append(eq(r"\zeta = \frac{-\ln M_p}{\sqrt{\pi^2+\ln^2 M_p}} = \frac{" + fmt(-lnM) + r"}{\sqrt{9.870 + " + fmt(lnM ** 2) + "}} = "
|
| 918 |
+
+ fmt(z) + r",\qquad \zeta\omega_n = \frac{" + str(4 if banda == 2 else 3) + "}{t_s} = " + fmt(sg)
|
| 919 |
+
+ r",\qquad \omega_n = " + fmt(wn) + r"\ \text{rad/s}"))
|
| 920 |
+
md.append(eq(r"s_{1,2} = -\zeta\omega_n \pm j\,\omega_n\sqrt{1-\zeta^2} = -" + fmt(sg) + r" \pm j\," + fmt(wd)
|
| 921 |
+
+ r",\qquad \beta = \arccos\zeta = " + fmt(math.degrees(esp["beta"])) + r"^{\circ}"))
|
| 922 |
+
md.append("Los polos tienen que quedar dentro del cono de semiángulo $\\beta$ y a la izquierda de la vertical "
|
| 923 |
+
f"$\\sigma=-{fmt(sg)}$ (zona sombreada de la figura).")
|
| 924 |
+
md.append("### 3. Polinomio característico deseado")
|
| 925 |
+
nc = d["nc"]
|
| 926 |
+
if nc >= 2:
|
| 927 |
+
base = r"\left(" + poly_tex([1, 2 * z * wn, wn ** 2], q=False) + r"\right)"
|
| 928 |
+
if d["libres"]:
|
| 929 |
+
fl = len(d["libres"])
|
| 930 |
+
M = s ** fl + sum(d["libres"][i] * s ** (fl - 1 - i) for i in range(fl))
|
| 931 |
+
ext = (r"\left(s + " + fmt(d["p3"]) + r"\right)" + ("^{" + str(d["extra"]) + "}" if d["extra"] > 1 else "")) if d["extra"] else ""
|
| 932 |
+
md.append(f"El lazo cerrado tiene {nc} polos, pero el {tipo} solo tiene {len(d['incog'])} parámetros: no se pueden fijar todos "
|
| 933 |
+
"(regla de oro: tantas especificaciones como parámetros). Se fija el par dominante"
|
| 934 |
+
+ (f", {d['extra']} polo{'s' if d['extra'] > 1 else ''} en $s=-{fmt(d['p3'])}$ ($r={fmt(r_extra)}$)" if d["extra"] else "")
|
| 935 |
+
+ f" y se {'deja libre' if fl == 1 else 'dejan libres'} {fl} polo{'s' if fl > 1 else ''}: "
|
| 936 |
+
f"{'su coeficiente pasa' if fl == 1 else 'sus coeficientes pasan'} a ser incógnita, y después se comprueba dónde cae{'n' if fl > 1 else ''}.")
|
| 937 |
+
md.append(eq(r"P_d(s) = " + base + ext + r"\left(" + poly_sym_tex(M) + r"\right) = " + poly_sym_tex(d["deseado"])))
|
| 938 |
+
elif d["extra"]:
|
| 939 |
+
ext = r"\left(s + " + fmt(d["p3"]) + r"\right)" + ("^{" + str(d["extra"]) + "}" if d["extra"] > 1 else "")
|
| 940 |
+
md.append(f"El lazo cerrado tiene {nc} polos: además del par dominante hace falta colocar {d['extra']} más. "
|
| 941 |
+
f"Se ponen en $s=-{fmt(d['p3'])}$, a $r={fmt(r_extra)}$ veces $\\zeta\\omega_n$ "
|
| 942 |
+
"(criterio de dominancia: $p_3\\ge5\\,\\zeta\\omega_n$).")
|
| 943 |
+
md.append(eq(r"P_d(s) = " + base + ext + " = " + poly_tex([float(c) for c in sp.Poly(d["deseado"], s).all_coeffs()], q=False)))
|
| 944 |
+
else:
|
| 945 |
+
md.append(eq(r"P_d(s) = s^{2} + 2\zeta\omega_n s + \omega_n^{2} = " + poly_tex([1, 2 * z * wn, wn ** 2], q=False)))
|
| 946 |
+
else:
|
| 947 |
+
md.append(f"El lazo cerrado es de primer orden: solo se puede fijar un polo, en $s=-{fmt(sg)}$ (la especificación de $M_p$ no se aplica).")
|
| 948 |
+
md.append(eq(r"P_d(s) = s + " + fmt(sg)))
|
| 949 |
+
md.append("### 4. Ecuación característica real")
|
| 950 |
+
C = d["C"]
|
| 951 |
+
md.append(eq(r"C(s) = " + sp.latex(C) + r",\qquad 1 + C(s)G(s) = 0 \;\Longrightarrow\; " + poly_sym_tex(d["car"]) + " = 0"))
|
| 952 |
+
md.append("### 5. Igualación de coeficientes")
|
| 953 |
+
lc = d["lc"]
|
| 954 |
+
if lc != 1:
|
| 955 |
+
md.append(f"El coeficiente principal es ${poly_sym_tex(lc * s ** 0) if lc.free_symbols else fmtq(float(lc))}$; se compara con $P_d(s)$ multiplicado por él.")
|
| 956 |
+
lineas = []
|
| 957 |
+
for izq, der in d["ecs"]:
|
| 958 |
+
lineas.append(poly_sym_tex(izq) + " &= " + poly_sym_tex(der))
|
| 959 |
+
if lineas:
|
| 960 |
+
md.append(eq(r"\begin{aligned}" + r"\\ ".join(lineas) + r"\end{aligned}"))
|
| 961 |
+
nparam = len(d["incog"])
|
| 962 |
+
if d["estado"] == "imposible":
|
| 963 |
+
md.append(caja("aviso", "No hay solución",
|
| 964 |
+
f"El polinomio característico es de grado {nc} y hay que fijar {nc} coeficientes, pero el controlador "
|
| 965 |
+
f"{tipo} solo tiene {nparam} parámetro{'s' if nparam > 1 else ''}. Regla de oro: tantas especificaciones "
|
| 966 |
+
"como parámetros. Pruebe con un controlador con más acciones (PI → PID, P → PD)."))
|
| 967 |
+
f = gf.fig_plano_s(G.polos_np(), G.ceros_np(), region={"sigma": sg, "beta": esp["beta"], "banda": banda},
|
| 968 |
+
deseados=[complex(-sg, wd), complex(-sg, -wd)], polos_ref=None)
|
| 969 |
+
return "\n\n".join(md), f, gf.figura_error("Sin solución con este controlador."), None
|
| 970 |
+
v = d["valores"]
|
| 971 |
+
kp, ki, kd = v.get(Kp_, 0.0), v.get(Ki_, 0.0), v.get(Kd_, 0.0)
|
| 972 |
+
if d["fijadas"]:
|
| 973 |
+
md.append("Hay más parámetros que ecuaciones; se fija " + ", ".join("$" + sp.latex(x) + "=0$" for x in d["fijadas"])
|
| 974 |
+
+ " (no hace falta esa acción para cumplir las especificaciones).")
|
| 975 |
+
caja_k = [r"K_p = " + fmt(kp)]
|
| 976 |
+
isa = []
|
| 977 |
+
if Ki_ in d["incog"]:
|
| 978 |
+
caja_k.append(r"K_i = " + fmt(ki))
|
| 979 |
+
isa.append(r"T_i = K_p/K_i = " + fmt(kp / ki if ki else math.inf) + r"\ \text{s}")
|
| 980 |
+
if Kd_ in d["incog"]:
|
| 981 |
+
caja_k.append(r"K_d = " + fmt(kd))
|
| 982 |
+
isa.append(r"T_d = K_d/K_p = " + fmt(kd / kp if kp else 0) + r"\ \text{s}")
|
| 983 |
+
md.append(eq(r"\boxed{\ " + r",\quad ".join(caja_k) + r"\ }" + (r"\qquad " + r",\quad ".join(isa) if isa else "")))
|
| 984 |
+
if d["estado"] == "parcial":
|
| 985 |
+
pl = d["polos_libres"]
|
| 986 |
+
md.append("Coeficientes libres: " + ", ".join(f"${sp.latex(m_)} = {fmt(v_)}$" for m_, v_ in zip(d["libres"], d["m_vals"]))
|
| 987 |
+
+ ", es decir, polo" + ("s" if len(pl) > 1 else "") + " libre" + ("s" if len(pl) > 1 else "") + " en "
|
| 988 |
+
+ ", ".join(f"$s={fmtc(p_)}$" for p_ in pl) + ".")
|
| 989 |
+
if any(p_.real >= -1e-9 for p_ in pl):
|
| 990 |
+
md.append(caja("aviso", "El polo libre cae en el semiplano derecho",
|
| 991 |
+
"Con este controlador y estas especificaciones el lazo cerrado sería inestable: la suma de los polos "
|
| 992 |
+
"está fijada por la planta y no da para todos. Pruebe un $r$ menor, unas especificaciones más lentas "
|
| 993 |
+
"o un controlador con más acciones."))
|
| 994 |
+
else:
|
| 995 |
+
rl = min(-p_.real for p_ in pl) / sg
|
| 996 |
+
if rl < 5:
|
| 997 |
+
md.append(caja("aviso", "Polo libre cercano al par dominante",
|
| 998 |
+
f"El polo libre está a ${fmt(rl)}$ veces $\\zeta\\omega_n$ del eje imaginario (menos de 5): "
|
| 999 |
+
"compite con el par dominante y la respuesta real se apartará de las especificaciones."))
|
| 1000 |
+
md += casos_apuntes(G, tipo, z, wn)
|
| 1001 |
+
if min(kp, ki, kd) < -1e-9:
|
| 1002 |
+
md.append(caja("aviso", "Ganancia negativa",
|
| 1003 |
+
"Alguna ganancia sale negativa: la especificación pide un lazo más lento o más oscilante que lo que la planta "
|
| 1004 |
+
"ya hace por sí sola. Es realizable, pero conviene revisar la especificación."))
|
| 1005 |
+
# comprobación
|
| 1006 |
+
Cn, _ = pid_ft(kp, ki, kd, 0)
|
| 1007 |
+
T, L, car = lazo_cerrado(G, Cn)
|
| 1008 |
+
pc = T.polos()
|
| 1009 |
+
md.append("### 6. Comprobación")
|
| 1010 |
+
md.append(eq(r"T(s) = " + T.tex()))
|
| 1011 |
+
md.append(f"Polos del lazo cerrado: ${lista_raices_tex(pc)}$ — estabilidad **{estabilidad(pc)}**. "
|
| 1012 |
+
f"Ceros de $T(s)$: ${lista_raices_tex(T.ceros(), 'z')}$.")
|
| 1013 |
+
md += explica_polos(T)
|
| 1014 |
+
for zz, _ in T.ceros():
|
| 1015 |
+
if zz.real < 0 and abs(zz.real) < 4 * sg:
|
| 1016 |
+
md.append(caja("aviso", "Cuidado con el cero del controlador",
|
| 1017 |
+
f"$T(s)$ tiene un cero en ${fmtc(zz)}$, con $|z|<4\\,\\zeta\\omega_n={fmt(4 * sg)}$: la sobreoscilación real "
|
| 1018 |
+
"puede ser varias veces la que predice la fórmula de $M_p$. Compruébelo en la figura."))
|
| 1019 |
+
break
|
| 1020 |
+
est = estabilidad(pc)
|
| 1021 |
+
if est != "estable":
|
| 1022 |
+
return "\n\n".join(md), gf.figura_error("Lazo cerrado no estable."), gf.figura_error("—"), (kp, ki, kd)
|
| 1023 |
+
T_hor = max(2.5 * ts, horizonte(T.polos_np()))
|
| 1024 |
+
sim = simula_pid(G, kp, ki, kd, N=N_sim, t_end=T_hor)
|
| 1025 |
+
yinf = float(T.N.eval(0) / T.D.eval(0))
|
| 1026 |
+
met = metricas_escalon(sim["t"], sim["y"], yinf)
|
| 1027 |
+
cumpleM = met["Mp"] <= Mp * 1.02 + 0.2
|
| 1028 |
+
cumpleT = met["ts2" if banda == 2 else "ts5"] <= ts * 1.02
|
| 1029 |
+
md.append(f"| | Especificación | Obtenido en simulación | |\n|:--|:--:|:--:|:--:|\n"
|
| 1030 |
+
f"| $M_p$ | $\\le {num(Mp)}$ % | {num(met['Mp'])} % | {'✓' if cumpleM else '✗'} |\n"
|
| 1031 |
+
f"| $t_s$ ({banda} %) | $\\le {num(ts)}$ s | {num(met['ts2' if banda == 2 else 'ts5'])} s | {'✓' if cumpleT else '✗'} |\n"
|
| 1032 |
+
f"| error ante escalón | — | {num(1 - yinf)} | |")
|
| 1033 |
+
if not (cumpleM and cumpleT):
|
| 1034 |
+
md.append("Si no se cumple, la causa casi siempre es un cero del controlador o un tercer polo demasiado cercano: "
|
| 1035 |
+
"aumente $r$ o recoloque el par algo más a la izquierda y con algo más de amortiguamiento.")
|
| 1036 |
+
fp = gf.fig_plano_s(T.polos_np(), T.ceros_np(), region={"sigma": sg, "beta": esp["beta"], "banda": banda},
|
| 1037 |
+
deseados=[complex(-sg, wd), complex(-sg, -wd)] if wd > 0 else [complex(-sg, 0)],
|
| 1038 |
+
polos_ref=G.polos_np(), ref_label="la planta")
|
| 1039 |
+
ft = gf.fig_pid(sim)
|
| 1040 |
+
a = ft.axes[0]
|
| 1041 |
+
a.axhline(yinf * (1 + Mp / 100), color=gf.ROJO, lw=0.8, ls=(0, (1, 2)))
|
| 1042 |
+
a.text(sim["t"][-1], yinf * (1 + Mp / 100), f"límite $M_p$ = {num(Mp)} % ", color=gf.ROJO, fontsize=8, ha="right", va="bottom")
|
| 1043 |
+
for ax in ft.axes:
|
| 1044 |
+
ax.axvline(ts, color=gf.AZUL, lw=0.8, ls=(0, (1, 2)))
|
| 1045 |
+
a.text(ts, a.get_ylim()[0], f" $t_s$ exigido", color=gf.AZUL, fontsize=8, va="bottom")
|
| 1046 |
+
return "\n\n".join(md), fp, ft, (kp, ki, kd)
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
def casos_apuntes(G, tipo, z, wn):
|
| 1050 |
+
"""Si la planta es uno de los dos casos resueltos de los apuntes, se muestra la fórmula cerrada."""
|
| 1051 |
+
md = []
|
| 1052 |
+
if G.m != 0:
|
| 1053 |
+
return md
|
| 1054 |
+
a, b = G.den, G.num
|
| 1055 |
+
if G.n == 1 and tipo == "PI" and abs(a[1]) > 1e-14:
|
| 1056 |
+
tau, K = a[0] / a[1], b[-1] / a[1]
|
| 1057 |
+
md.append("Es el **caso 2** de los apuntes (primer orden y PI), con fórmula cerrada:")
|
| 1058 |
+
md.append(eq(r"K_p = \frac{2\zeta\omega_n\tau - 1}{K} = \frac{2(" + fmt(z) + ")(" + fmt(wn) + ")(" + fmt(tau) + ") - 1}{" + fmt(K)
|
| 1059 |
+
+ "} = " + fmt((2 * z * wn * tau - 1) / K) + r",\qquad K_i = \frac{\tau\omega_n^2}{K} = " + fmt(tau * wn ** 2 / K)))
|
| 1060 |
+
if G.n == 2 and tipo == "PD" and abs(a[2]) < 1e-14 and abs(a[1]) > 1e-14:
|
| 1061 |
+
tau, K = a[0] / a[1], b[-1] / a[1]
|
| 1062 |
+
Kp = tau * wn ** 2 / K
|
| 1063 |
+
md.append("Es el **caso 1** de los apuntes (planta con integrador y PD, $C=K_p(1+T_ds)$), con fórmula cerrada:")
|
| 1064 |
+
md.append(eq(r"K_p = \frac{\tau\omega_n^2}{K} = " + fmt(Kp) + r",\qquad T_d = \frac{2\zeta\omega_n\tau - 1}{K K_p} = "
|
| 1065 |
+
+ fmt((2 * z * wn * tau - 1) / (K * Kp))))
|
| 1066 |
+
return md
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
# =====================================================================
|
| 1070 |
+
# Animaciones
|
| 1071 |
+
# =====================================================================
|
| 1072 |
+
PARAMS_PID = {"Kp": "K_p", "Ki": "K_i", "Kd": "K_d"}
|
| 1073 |
+
PARAMS_SISTEMA = {"ζ (amortiguamiento)": "zeta", "ωn (frecuencia natural)": "wn", "K (ganancia)": "K",
|
| 1074 |
+
"τ (constante de tiempo)": "tau", "p (tercer polo)": "p3", "z (posición del cero)": "zc"}
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
def _resumen_criticos(nombre, frames, crit, polos_de):
|
| 1078 |
+
"""Texto: en qué valores cambia la estabilidad y con qué frecuencia cruzan los polos."""
|
| 1079 |
+
est = [f["estado"] for f in frames]
|
| 1080 |
+
if not crit:
|
| 1081 |
+
if all(e == "estable" for e in est):
|
| 1082 |
+
return f"En todo el rango de ${nombre}$ el sistema es **estable**: ningún polo llega a cruzar el eje imaginario."
|
| 1083 |
+
if all(e == "inestable" for e in est):
|
| 1084 |
+
return f"En todo el rango de ${nombre}$ el sistema es **inestable**."
|
| 1085 |
+
return f"La estabilidad cambia dentro del rango de ${nombre}$ (vea la barra de colores)."
|
| 1086 |
+
partes = []
|
| 1087 |
+
for vc in crit:
|
| 1088 |
+
pc = np.asarray(polos_de(vc), complex)
|
| 1089 |
+
i = int(np.argmax(pc.real))
|
| 1090 |
+
w = abs(pc[i].imag)
|
| 1091 |
+
if w > 1e-6:
|
| 1092 |
+
cruce = (f"un par de polos cruza el eje imaginario en $s=\\pm j\\,{fmt(w)}$ rad/s: justo ahí el sistema "
|
| 1093 |
+
f"oscila sin amortiguarse, con periodo $2\\pi/\\omega={fmt(2 * math.pi / w)}$ s")
|
| 1094 |
+
else:
|
| 1095 |
+
cruce = "un polo real cruza el eje imaginario por el origen"
|
| 1096 |
+
partes.append(f"para ${nombre}\\approx{fmt(vc)}$ {cruce}")
|
| 1097 |
+
return (f"El sistema es **{est[0]}** al principio del rango y **{est[-1]}** al final: " + "; ".join(partes)
|
| 1098 |
+
+ ". Ese es el valor crítico del parámetro, la frontera que daría el criterio de Routh.")
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
def anima_pid(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, r_amp, t_fin, var, vmin, vmax, nfr, fps):
|
| 1102 |
+
try:
|
| 1103 |
+
G = parse_ft(planta)
|
| 1104 |
+
Kp, Ki, Kd = convierte_ganancias(forma, Kp, Ki, Kd, Ti, Td)
|
| 1105 |
+
usar = (usarP, usarI, usarD)
|
| 1106 |
+
if vmax <= vmin:
|
| 1107 |
+
raise ValueError("El valor final del rango debe ser mayor que el inicial.")
|
| 1108 |
+
nfr = int(np.clip(nfr, 5, 80))
|
| 1109 |
+
base = {"Kp": Kp, "Ki": Ki, "Kd": Kd}
|
| 1110 |
+
|
| 1111 |
+
def lazo(v):
|
| 1112 |
+
g = dict(base)
|
| 1113 |
+
g[var] = v
|
| 1114 |
+
C, _ = pid_ft(g["Kp"], g["Ki"], g["Kd"], N, usar)
|
| 1115 |
+
if C == 0:
|
| 1116 |
+
return None, np.array([])
|
| 1117 |
+
T, _, car = lazo_cerrado(G, C)
|
| 1118 |
+
return T, np.roots([float(c) for c in car.all_coeffs()])
|
| 1119 |
+
|
| 1120 |
+
T0, p0 = lazo(base[var] if vmin <= base[var] <= vmax else vmin)
|
| 1121 |
+
T_hor = t_fin if t_fin and t_fin > 0 else (horizonte(list(p0), minimo=2.0) if T0 is not None else 10.0)
|
| 1122 |
+
tt = np.linspace(0, T_hor, 500)
|
| 1123 |
+
frames = []
|
| 1124 |
+
for v in np.linspace(vmin, vmax, nfr):
|
| 1125 |
+
T, pc = lazo(v)
|
| 1126 |
+
if T is None:
|
| 1127 |
+
continue
|
| 1128 |
+
y = an.respuesta_num(T.num, T.den, tt, u=np.full_like(tt, r_amp))
|
| 1129 |
+
frames.append({"v": v, "polos": pc, "ceros": T.ceros_np(), "y": y, "estado": an.estado_de(pc)})
|
| 1130 |
+
if not frames:
|
| 1131 |
+
raise ValueError("No hay ningún controlador válido en ese rango.")
|
| 1132 |
+
|
| 1133 |
+
def maxre(v):
|
| 1134 |
+
pc = lazo(v)[1]
|
| 1135 |
+
return float(np.max(pc.real)) if pc.size else -1.0
|
| 1136 |
+
crit = an.criticos([f["v"] for f in frames], maxre)
|
| 1137 |
+
nombre = PARAMS_PID[var]
|
| 1138 |
+
ruta = an.gif_barrido(frames, f"${nombre}$", tt, yref=r_amp, criticos_=crit, fps=fps,
|
| 1139 |
+
nota_resp="del lazo cerrado a un escalón de consigna")
|
| 1140 |
+
return ruta, _resumen_criticos(nombre, frames, crit, lambda v: lazo(v)[1])
|
| 1141 |
+
except Exception as e: # noqa: BLE001
|
| 1142 |
+
return None, error_md(e)
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def anima_senales(planta, forma, Kp, Ki, Kd, Ti, Td, usarP, usarI, usarD, N, dmed, saturar, umin, umax, aw,
|
| 1146 |
+
r_amp, t_fin, pert_amp, pert_t, cambio_r, r2_amp, r2_t, fps):
|
| 1147 |
+
try:
|
| 1148 |
+
G = parse_ft(planta)
|
| 1149 |
+
Kp, Ki, Kd = convierte_ganancias(forma, Kp, Ki, Kd, Ti, Td)
|
| 1150 |
+
usar = (usarP, usarI, usarD)
|
| 1151 |
+
C, _ = pid_ft(Kp, Ki, Kd, N, usar)
|
| 1152 |
+
if C == 0:
|
| 1153 |
+
raise ValueError("Active al menos una acción del PID.")
|
| 1154 |
+
T, _, _ = lazo_cerrado(G, C)
|
| 1155 |
+
T_hor = t_fin if t_fin and t_fin > 0 else horizonte(T.polos_np(), minimo=2.0)
|
| 1156 |
+
pt = pert_t if (pert_amp and pert_amp != 0) else None
|
| 1157 |
+
r2t = r2_t if cambio_r else None
|
| 1158 |
+
for x in (pt, r2t):
|
| 1159 |
+
if x is not None and x >= 0.75 * T_hor:
|
| 1160 |
+
T_hor = x * 1.6
|
| 1161 |
+
lims = dict(umin=umin if saturar else None, umax=umax if saturar else None)
|
| 1162 |
+
sim = simula_pid(G, Kp, Ki, Kd, N=N, usar=usar, deriv_medida=dmed, antiwindup=aw, r_amp=r_amp, t_end=T_hor,
|
| 1163 |
+
pert_amp=pert_amp, pert_t=pt, r2_amp=r2_amp if cambio_r else None, r2_t=r2t, **lims)
|
| 1164 |
+
ruta = an.gif_temporal(sim, nfr=60, fps=fps, **lims)
|
| 1165 |
+
est = estabilidad(T.polos())
|
| 1166 |
+
txt = (f"Lazo **{est}**. La animación recorre {fmt(T_hor)} s de simulación: consigna {fmt(r_amp)}"
|
| 1167 |
+
+ (f", cambio a {fmt(r2_amp)} en $t={fmt(r2_t)}$ s" if cambio_r else "")
|
| 1168 |
+
+ (f", perturbación de {fmt(pert_amp)} en $t={fmt(pert_t)}$ s" if pt is not None else "") + ".")
|
| 1169 |
+
return ruta, txt
|
| 1170 |
+
except Exception as e: # noqa: BLE001
|
| 1171 |
+
return None, error_md(e)
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def anima_sistema(modo, orden, K, tau, zeta, wn, con_cero, zc, p3, texto, tipo_e, A, w_e, a_e, r_txt, t_max,
|
| 1175 |
+
var, vmin, vmax, nfr, fps):
|
| 1176 |
+
try:
|
| 1177 |
+
if modo == "G(s) libre":
|
| 1178 |
+
raise ValueError("En el modo «G(s) libre» no hay parámetros que barrer: elija el modo «Parámetros».")
|
| 1179 |
+
clave = PARAMS_SISTEMA[var]
|
| 1180 |
+
if clave == "tau" and not orden.startswith("1"):
|
| 1181 |
+
raise ValueError("τ solo interviene en el modelo de primer orden.")
|
| 1182 |
+
if clave in ("zeta", "wn") and orden.startswith("1"):
|
| 1183 |
+
raise ValueError("ζ y ωn solo intervienen en los modelos de segundo y tercer orden.")
|
| 1184 |
+
if clave == "p3" and not orden.startswith("3"):
|
| 1185 |
+
raise ValueError("El tercer polo solo existe en el modelo de tercer orden.")
|
| 1186 |
+
if clave == "zc" and not con_cero:
|
| 1187 |
+
raise ValueError("Active «Añadir un cero» para barrer su posición.")
|
| 1188 |
+
if vmax <= vmin:
|
| 1189 |
+
raise ValueError("El valor final del rango debe ser mayor que el inicial.")
|
| 1190 |
+
nfr = int(np.clip(nfr, 5, 80))
|
| 1191 |
+
ent = crea_entrada(tipo_e, A, w_e, a_e, r_txt)
|
| 1192 |
+
par = {"K": K, "tau": tau, "zeta": zeta, "wn": wn, "zc": zc, "p3": p3}
|
| 1193 |
+
|
| 1194 |
+
def sistema(v):
|
| 1195 |
+
q = dict(par)
|
| 1196 |
+
q[clave] = v
|
| 1197 |
+
return construye_G(modo, orden, q["K"], q["tau"], q["zeta"], q["wn"], con_cero, q["zc"], q["p3"], texto)
|
| 1198 |
+
|
| 1199 |
+
G0 = construye_G(modo, orden, K, tau, zeta, wn, con_cero, zc, p3, texto)
|
| 1200 |
+
T_hor = t_max if t_max and t_max > 0 else horizonte(G0.polos_np(), ent.w)
|
| 1201 |
+
tt = np.linspace(0, T_hor, 500)
|
| 1202 |
+
u = None if ent.impulso else ent.r_num(tt)
|
| 1203 |
+
frames, saltados = [], 0
|
| 1204 |
+
for v in np.linspace(vmin, vmax, nfr):
|
| 1205 |
+
try:
|
| 1206 |
+
G = sistema(v)
|
| 1207 |
+
except ValueError:
|
| 1208 |
+
saltados += 1
|
| 1209 |
+
continue
|
| 1210 |
+
pc = G.polos_np()
|
| 1211 |
+
y = an.respuesta_num(G.num, G.den, tt, u=u, impulso=ent.impulso)
|
| 1212 |
+
frames.append({"v": v, "polos": pc, "ceros": G.ceros_np(), "y": y, "estado": an.estado_de(pc)})
|
| 1213 |
+
if not frames:
|
| 1214 |
+
raise ValueError("Ningún valor del rango da un sistema válido (τ, ωn y p deben ser positivos).")
|
| 1215 |
+
|
| 1216 |
+
def maxre(v):
|
| 1217 |
+
try:
|
| 1218 |
+
return float(np.max(sistema(v).polos_np().real))
|
| 1219 |
+
except ValueError:
|
| 1220 |
+
return float("nan")
|
| 1221 |
+
crit = an.criticos([f["v"] for f in frames], maxre)
|
| 1222 |
+
nombre = {"zeta": r"\zeta", "wn": r"\omega_n", "K": "K", "tau": r"\tau", "p3": "p", "zc": "z"}[clave]
|
| 1223 |
+
ruta = an.gif_barrido(frames, f"${nombre}$", tt, yref=None if ent.impulso else ent.limite, criticos_=crit,
|
| 1224 |
+
fps=fps, nota_resp=f"a la entrada: {ent.nombre}")
|
| 1225 |
+
txt = _resumen_criticos(nombre, frames, crit, lambda v: sistema(v).polos_np())
|
| 1226 |
+
if clave == "zeta":
|
| 1227 |
+
txt += (" Al variar $\\zeta$ con $\\omega_n$ fijo, los polos complejos recorren la circunferencia de radio "
|
| 1228 |
+
"$\\omega_n$; en $\\zeta=1$ se juntan en el eje real (polo doble), para $\\zeta>1$ se separan, y "
|
| 1229 |
+
"con $\\zeta<0$ pasan al semiplano derecho.")
|
| 1230 |
+
if saltados:
|
| 1231 |
+
txt += f" Se han omitido {saltados} valores no válidos del rango."
|
| 1232 |
+
return ruta, txt
|
| 1233 |
+
except Exception as e: # noqa: BLE001
|
| 1234 |
+
return None, error_md(e)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.5.4
|
| 2 |
+
scipy==1.18.1
|
| 3 |
+
sympy==1.14.0
|
| 4 |
+
matplotlib==3.11.2
|