""" Simulate '%cell%' cell from %source% """

# Imports
import os
from pathlib import Path

import yaml
import matplotlib.pyplot as plt
import numpy as np
import sax
import %name%
import gdsfactoryplus as gfp
LIB_PATH = Path(%name%.__file__).resolve().parent

# Pdk Configuration
pdk = gfp.get_pdk()
gfp.register_cells()

# Extract Netlist
%extractNetlist%

# Create SAX Circuit
circuit, circuit_info = sax.circuit(netlist, models=pdk.models)

# Simulate and get S-Dictionary
wl = np.linspace(%wl_min%, %wl_max%, %wl_num%)
result = circuit(wl=wl) # you can add extra simulation arguments here...
sdict = sax.sdict(result)  # ensure the result is in S-Dictionary format.

# optional: filter out zero entries from sdict:
sdict = {k: v for k, v in sdict.items() if not (v < 1e-5).all()}

# Plot
fig, (ax_power, ax_phase) = plt.subplots(
    nrows=2,
    ncols=1,
    # sharex=True, # use this if you want both plots to share the x-axis
    tight_layout=True,
)

ax_power.set_title("Power")
ax_power.grid(True)
ax_power.set_xlabel("λ [μm]")
ax_power.set_ylabel("Power [dB]")
for (p_in, p_out), value in sdict.items():
    ax_power.plot(wl, 20 * np.log10(abs(value)), label=f"{p_in}↔{p_out}")

ax_phase.set_title("Phase")
ax_phase.grid(True)
ax_phase.set_xlabel("λ [μm]")
ax_phase.set_ylabel("Phase [rad]")
for (p_in, p_out), value in sdict.items():
    ax_phase.plot(wl, np.unwrap(np.angle(value)))

# you can move the legend with bbox_to_anchor:
plt.figlegend(bbox_to_anchor=(1.0, 1.0), framealpha=1)
# plt.savefig("simulate_%cell%.png", bbox_inches="tight") # uncomment to save figure as well

# plt.show()
gfp.show()  # use gfp.show in stead of plt.show to show the plot in a VSCode panel.
