"""Corre las simulaciones de la lección 0.1 y genera los gráficos SVG.
Uso:  ~/software/curso-amplificadores/.venv/bin/python graficar.py   (desde esta carpeta)
"""
import subprocess, sys, pathlib
import numpy as np
aqui = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(aqui.parents[2] / "herramientas"))
import estilo_graficos as eg
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter

for cir in ("divisor_con_carga.cir", "equivalente_thevenin.cir", "ampli_y_parlante.cir"):
    subprocess.run(["ngspice", "-b", cir], cwd=aqui, check=True, capture_output=True)

eg.aplicar()
fig_dir = aqui.parent / "figuras"
ohm = EngFormatter(unit="Ω")
hz = EngFormatter(unit="Hz")

# 1) Divisor real contra su equivalente de Thevenin
d = np.loadtxt(aqui / "divisor_con_carga.dat")
e = np.loadtxt(aqui / "equivalente_thevenin.dat")
fig, ax = plt.subplots(figsize=(7, 4))
ax.semilogx(d[:, 0], d[:, 1], color=eg.AZUL, lw=3, label="divisor real (12 V, 10k, 10k)")
sel = np.unique(np.round(np.logspace(np.log10(e[0, 0]), np.log10(e[-1, 0]), 25) / 100) * 100)
idx = np.searchsorted(e[:, 0], sel).clip(0, len(e) - 1)
ax.semilogx(e[idx, 0], e[idx, 1], "o", color=eg.NARANJA, ms=6, label="equivalente: 6 V en serie con 5k")
ax.axhline(6, color=eg.GRIS, ls="--", lw=1)
ax.text(120, 6.15, "sin carga: 6 V", color=eg.GRIS)
ax.plot([5000], [3], "s", color=eg.TINTA, ms=7)
ax.annotate("$R_L = R_{TH}$ = 5 kΩ\n→ 3 V, la mitad", (5000, 3), (30000, 1.6),
            arrowprops=dict(arrowstyle="->", color=eg.TINTA))
ax.set_xlabel("resistencia de carga $R_L$")
ax.set_ylabel("tensión en OUT [V]")
ax.xaxis.set_major_formatter(ohm)
ax.set_ylim(0, 6.8)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.2), ncol=1)
eg.guardar(fig, fig_dir / "graf_divisor_vs_thevenin.svg")

# 2) Amplificador con dos impedancias de salida sobre el mismo parlante
a = np.loadtxt(aqui / "ampli_rout_005.dat")
b = np.loadtxt(aqui / "ampli_rout_2.dat")
z = np.loadtxt(aqui / "ampli_rout_2_z.dat")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 6), sharex=True)
ax1.semilogx(z[:, 0], z[:, 1], color=eg.TINTA, lw=2)
ax1.set_ylabel("impedancia del parlante [Ω]")
ax1.set_ylim(0, 50)
ax1.set_title("La carga no es una resistencia fija")
ax2.semilogx(a[:, 0], a[:, 1], color=eg.AZUL, lw=2.5, label="$R_{out}$ = 0,05 Ω (transistorizado)")
ax2.semilogx(b[:, 0], b[:, 1], color=eg.NARANJA, lw=2.5, label="$R_{out}$ = 2 Ω (valvular típico)")
ax2.set_ylabel("nivel en el parlante [dB]")
ax2.set_xlabel("frecuencia")
ax2.xaxis.set_major_formatter(hz)
ax2.set_ylim(-3, 0.5)
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.25), ncol=1)
ax2.set_title("Misma señal, distinta impedancia de salida")
eg.guardar(fig, fig_dir / "graf_ampli_parlante.svg")
print("listo")
