import subprocess
import numpy as np
import matplotlib.pyplot as plt

# 1. NEC-Datei für vertikales Strahlungsdiagramm (2m Aufbauhöhe)
nec_content = """CM 10m Delta Loop Elevation 2m Setup
CE
GW 1 11 0 0 2 -1.34 0 6.5 0.0007
GW 2 9 -1.34 0 6.5 1.34 0 6.5 0.0007
GW 3 11 1.34 0 6.5 0 0 2 0.0007
GE 1
GN 2 0 0 0 13 0.005
EK
EX 0 1 1 0 1 0
FR 0 1 0 0 28.5 0
RP 0 91 2 1000 0 0 1 180
EN
"""

with open("pattern_elev_2m.nec", "w") as f:
    f.write(nec_content)

# 2. Simulation ausführen
subprocess.run(["nec2c", "-i", "pattern_elev_2m.nec", "-o", "pattern_elev_2m.out"], stdout=subprocess.DEVNULL)

# 3. Daten parsen für Phi = 0° (rechts) und Phi = 180° (links)
data_phi0 = {}
data_phi180 = {}

with open("pattern_elev_2m.out", "r") as f:
    lines = f.readlines()
    in_pattern = False
    for line in lines:
        if "RADIATION PATTERNS" in line:
            in_pattern = True
            continue
        
        if in_pattern:
            parts = line.strip().split()
            if len(parts) >= 8:
                try:
                    theta = float(parts[0])
                    phi = float(parts[1])
                    total_gain = float(parts[4])
                    
                    if abs(phi - 0.0) < 0.1:
                        data_phi0[theta] = total_gain
                    elif abs(phi - 180.0) < 0.1:
                        data_phi180[theta] = total_gain
                except ValueError:
                    continue

# 4. Daten zusammenfügen (von rechts 0° nach links 180°)
angles_deg = []
gains_dbi = []

# Rechts (0° bis 90° Elevation)
for theta in sorted(data_phi0.keys(), reverse=True):
    elevation = 90.0 - theta
    angles_deg.append(elevation)
    gains_dbi.append(data_phi0[theta])

# Links (90° bis 180° Elevation)
for theta in sorted(data_phi180.keys()):
    if theta == 0: continue
    elevation = 90.0 + theta
    angles_deg.append(elevation)
    gains_dbi.append(data_phi180[theta])

angles_rad = np.radians(angles_deg)

# 5. Polardiagramm zeichnen
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(8, 5))

ax.plot(angles_rad, gains_dbi, color='crimson', linewidth=2.5, label='Gain (dBi)')

# Achsen-Konfiguration
ax.set_theta_zero_location("E")  # 0° Horizont rechts
ax.set_theta_direction(1)        # Nach oben bis 180° links
ax.set_thetamin(0)
ax.set_thetamax(180)

# Dynamikbereich beschränken
ax.set_rlim(-30, 10)
ax.set_rticks([-30, -20, -10, 0, 10])
ax.set_rlabel_position(45)

ax.set_title("10m Delta-Loop (Speisung: 2m) – Vertikales Abstrahldiagramm", pad=20, fontsize=12, fontweight='bold')
ax.grid(True, linestyle='--', alpha=0.6)

plt.savefig("delta_loop_elevation_2m.png", dpi=300, bbox_inches='tight')
print("Vertikaldiagramm gespeichert als 'delta_loop_elevation_2m.png'!")
