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

# 1. NEC-Datei für Azimut-Schnitt (Theta = 68° entspricht 22° Elevation)
# RP 0 1 361 ... rechnet 361 Schritte für Phi von 0° bis 360°
nec_content = """CM 10m Delta Loop Azimuth Pattern
CE
GW 1 11 0 0 5 -1.34 0 9 0.0007
GW 2 9 -1.34 0 9 1.34 0 9 0.0007
GW 3 11 1.34 0 9 0 0 5 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 1 361 1000 68 0 0 1
EN
"""

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

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

# 3. Daten für Azimut (Phi 0° bis 360°) parsen
angles_rad = []
gains_dbi = []

with open("pattern_az.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:
                    phi = float(parts[1])        # Azimut-Winkel (0° bis 360°)
                    total_gain = float(parts[4]) # Total Gain in dBi
                    
                    angles_rad.append(np.radians(phi))
                    gains_dbi.append(total_gain)
                except ValueError:
                    continue

# 4. Vollständiges 360°-Polardiagramm zeichnen
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(7, 7))

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

# Achsen-Konfiguration für Azimut (0° = Nord/Vorne, 90° = Ost/Rechts)
ax.set_theta_zero_location("N")  # 0° oben
ax.set_theta_direction(-1)       # Im Uhrzeigersinn (wie ein Kompass)

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

# Optik & Beschriftung
ax.set_title("10m Delta-Loop – Horizontales Abstrahldiagramm (Azimut bei 22° Elev.)", pad=20, fontsize=12, fontweight='bold')
ax.grid(True, linestyle='--', alpha=0.6)

# Speichern
plt.savefig("delta_loop_azimuth.png", dpi=300, bbox_inches='tight')
print("Horizontaldiagramm erfolgreich gespeichert als 'delta_loop_azimuth.png'!")
 