import numpy as np
import matplotlib.pyplot as plt

file_path = r"F:\esim\stagger\gain_data_2stage.txt"
data = np.loadtxt(file_path)

freq = data[:, 0]
vin = data[:, 4]
stage1 = data[:, 6]
stage2 = data[:, 8]

# Voltage gain
Av_stage1 = stage1 / vin
Av_stage2 = stage2 / vin

# Gain in dB
stage1_db = 20 * np.log10(Av_stage1)
stage2_db = 20 * np.log10(Av_stage2)

# Maximum gain values
max_Av_stage1 = np.max(Av_stage1)
max_Av_stage2 = np.max(Av_stage2)

max_db_stage1 = np.max(stage1_db)
max_db_stage2 = np.max(stage2_db)

f_stage1 = freq[np.argmax(stage1_db)]
f_stage2 = freq[np.argmax(stage2_db)]

print("Stage 1 Maximum Voltage Gain (Av):", max_Av_stage1)
print("Stage 1 Maximum Gain (dB):", max_db_stage1)
print("Stage 1 Resonant Frequency:", f_stage1, "Hz")

print("Stage 2 Maximum Voltage Gain (Av):", max_Av_stage2)
print("Stage 2 Maximum Gain (dB):", max_db_stage2)
print("Stage 2 Resonant Frequency:", f_stage2, "Hz")

plt.figure(figsize=(8, 5))
plt.semilogx(freq, stage1_db, label="Stage 1 Output", linewidth=2)
plt.semilogx(freq, stage2_db, label="Stage 2 Output", linewidth=2)
plt.xlabel("Frequency (Hz)")
plt.ylabel("Gain (dB)")
plt.title("Stagger Tuned Amplifier Response")
plt.legend()
plt.grid(True, which="both")
plt.tight_layout()
plt.savefig(r"F:\esim\stagger\output_2stage.png", dpi=300)
print("Graph saved as output_2stage.png")