Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 50 additions & 6 deletions fem_gui/fem_axi.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def box_in_background(model, n=60):
"""(ok, text): lies the closed measurement box (top / bottom plane, side) completely in the background medium? The near-to-far transform
on it is only valid then (homogeneous, lossless medium on the surface). Substrate and radially infinite layers run through it."""
if model.get("substrate") or model.get("layers"):
return False, "Substrat oder radial unendliche Schichten laufen durch die Messbox: das Fernfeld (Stratton-Chu im homogenen Hintergrund) ist dann nicht definiert."
return False, "Substrat oder radial unendliche Schichten laufen durch die Messbox: die Transformation im homogenen Hintergrund (Stratton-Chu) ist dann nicht definiert; das Fernfeld geht über den Schichtstapel (Reziprozität)."
lay = layout(model)
r = np.linspace(0.0, lay["r_plane"], n)
z = np.linspace(lay["z_plane_bottom"], lay["z_plane_top"], n)
Expand All @@ -603,6 +603,47 @@ def box_in_background(model, n=60):
return True, ""


def stack_layers(model):
"""The planar background (substrate, radially infinite layers) as a layer stack for the far field by reciprocity, from top to bottom:
dict(top_nm, layers = [(material, thickness_nm), ...], substrate = material); None without substrate and layers. The incidence medium
above `top_nm` is the background; adjacent regions of the same material are merged, and regions equal to the background (at the top) or to the
substrate (at the bottom) are absorbed into them."""
if not model.get("substrate") and not model.get("layers"):
return None
bounds = set()
if model.get("substrate"):
bounds.add(0.0)
for ly in model.get("layers", []):
bounds.update((round(float(ly["z_bottom"]), 6), round(float(ly["z_bottom"]) + float(ly["height"]), 6)))
B = sorted(bounds, reverse=True)
regions = [[base_material(model, 0.5 * (B[i] + B[i + 1])), B[i] - B[i + 1]] for i in range(len(B) - 1)]
substrate = base_material(model, B[-1] - 1.0)
top = B[0]
while regions and regions[0][0] == model["background"]: # a region of the cover medium at the top belongs to the cover
top -= regions[0][1]
regions.pop(0)
while regions and regions[-1][0] == substrate: # and one of the substrate material at the bottom to the substrate
regions.pop()
merged = []
for name, t in regions:
if merged and merged[-1][0] == name:
merged[-1][1] += t
else:
merged.append([name, t])
return dict(top_nm=float(top), layers=[(n, float(t)) for n, t in merged], substrate=substrate)


def far_field_plan(model):
"""(mode, text) of the far field of an emitter: "homogeneous" (near-to-far transform on the box in the background medium), "layered" (substrate
and layers: by reciprocity with the plane waves of the stack, hpfem.axisymmetric_layered_far_field) or None with the reason."""
if model.get("substrate") or model.get("layers"):
st = stack_layers(model)
desc = " | ".join([model["background"]] + [f"{n} {t:g} nm" for n, t in st["layers"]] + [f"{st['substrate']} (Substrat)"])
return "layered", f"Schichtstapel von oben nach unten: {desc}; Oberkante bei z = {st['top_nm']:g} nm."
ok, why = box_in_background(model)
return ("homogeneous", "") if ok else (None, why)


def far_pattern_metrics(theta, intensity_mean, p_total, p_bulk, cones_deg=(2.0, 5.0, 10.0, 20.0, 30.0)):
"""Metrics of an emitter pattern from the azimuthal mean of the intensity [W/sr] on theta in [0, pi] (ascending):
cumulative power fraction within the half-angle theta (power / p_total), on-axis gain relative to the isotropic emitter of the same
Expand All @@ -627,7 +668,7 @@ def far_pattern_metrics(theta, intensity_mean, p_total, p_bulk, cones_deg=(2.0,

def fig_far_pattern(pt, log=False, figsize=(11, 5)):
"""Far field of the emitter: polar plot of the gain dP/dOmega / (P_bulk / 4 pi) in the E plane (x-z, dipole along x) and the H plane (y-z),
and the power collected within the half-angle theta."""
and the power collected within the half-angle around +z (up) and, if available, around -z (down)."""
import matplotlib.pyplot as plt

far = pt["far"]
Expand All @@ -648,18 +689,21 @@ def fig_far_pattern(pt, log=False, figsize=(11, 5)):
ax.set_title(("Gewinn in dB" if log else "Gewinn") + f" dP/dΩ / (P_bulk/4π) bei λ = {pt['lam_nm']:.1f} nm; 0° = +z", fontsize=9)
ax.legend(fontsize=8, loc="lower left", bbox_to_anchor=(-0.15, -0.14))
bx = fig.add_subplot(1, 2, 2)
bx.plot(np.degrees(th), np.asarray(far["cone_fraction"]), color="C2")
bx.plot(np.degrees(th), np.asarray(far["cone_fraction"]), color="C2", label="nach oben (+z)")
if far.get("cone_fraction_down") is not None:
bx.plot(np.degrees(np.pi - th[::-1]), np.asarray(far["cone_fraction_down"]), color="C3", label="nach unten (−z)")
bx.set_xlim(0, 90)
bx.set_ylim(0, max(1.0, float(np.nanmax(far["cone_fraction"][: len(th) // 2 + 1])) * 1.02))
bx.set_xlabel("Halbwinkel θ (°) um die +z-Achse")
top = max(float(np.nanmax(far["cone_fraction"][: len(th) // 2 + 1])), float(np.nanmax(far["cone_fraction_down"][: len(th) // 2 + 1])) if far.get("cone_fraction_down") is not None else 0.0)
bx.set_ylim(0, 1.02 if not far.get("layered") else max(top * 1.05, 1e-3)) # on a stack part of the power is guided or absorbed
bx.set_xlabel("Halbwinkel um die Achse (°)")
bx.set_ylabel("Anteil der emittierten Leistung P(<θ) / P")
bx.grid(alpha=0.3)
bx.legend(fontsize=8)
bx.set_title("In den Kegel gesammelte Leistung", fontsize=9)
fig.tight_layout()
return fig



SCATTER_QUANTITIES = {"|E| gesamt": ("tot", "abs"), "|E| Streufeld": ("sca", "abs"), "|E_x| gesamt": ("tot", 0), "|E_y| gesamt": ("tot", 1),
"|E_z| gesamt": ("tot", 2), "Re E_x gesamt": ("tot", "r0"), "Re E_y gesamt": ("tot", "r1"), "Re E_z gesamt": ("tot", "r2")}

Expand Down
31 changes: 22 additions & 9 deletions fem_gui/fem_axi_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,9 +434,12 @@ def tab_run(model, work, ctx):
sv["far_theta_samples"] = int(c2[1].number_input("Winkel", 181, 3601, int(sv.get("far_theta_samples", 721)), step=180, key="ax_far_n",
disabled=not sv["far_field"], help="Stützstellen von 0 bis 180° (721: Schritt 0,25°; schmale Strahlen brauchen feine Schritte)."))
if sv["far_field"]:
ok_box, why_box = fa.box_in_background(model)
if not ok_box:
st.warning("Fernfeld nicht möglich: " + why_box)
mode_far, text_far = fa.far_field_plan(model)
if mode_far is None:
st.warning("Fernfeld nicht möglich: " + text_far)
elif mode_far == "layered":
st.info("Substrat oder Schichten: das Fernfeld wird nach Reziprozität mit den ebenen Wellen des Stapels berechnet (hpfem.axisymmetric_layered_far_field), "
"getrennt nach oben (Umgebungsmedium) und unten (Substrat). " + text_far + " Ein verlustbehaftetes Substrat hat kein Fernfeld nach unten.")
errs = [t for lvl, t in fa.validate(model, S.ax_task) if lvl == "error"]
mesh = S.ax_mesh
mesh_ok = bool(mesh and not mesh.get("err") and mesh["sig"] == signature(model, S.ax_ms))
Expand Down Expand Up @@ -604,20 +607,30 @@ def far_results(ok):
far = pt["far"]
log = st.checkbox("Gewinn in dB", value=False, key="ax_far_log")
ui.show_fig(fa.fig_far_pattern(pt, log=log), f"fernfeld_{pick}.png", "ax_dl_far")
layered = bool(far.get("layered"))
c = st.columns(4)
c[0].metric("Gewinn auf der Achse", f"{far['axis_gain']:.3g}" if far.get("axis_gain") is not None else "–",
c[0].metric("Gewinn auf der Achse (+z)", f"{far['axis_gain']:.3g}" if far.get("axis_gain") is not None else "–",
help="I(0) / (P_bulk / 4π): Intensität in +z-Richtung gegenüber dem isotropen Strahler gleicher Leistung im homogenen Medium. Ein freier "
"Dipol hat höchstens 1,5.")
c[1].metric("Halbwertshalbwinkel", f"{far['half_angle_fwhm_deg']:.2f}°" if far.get("half_angle_fwhm_deg") is not None else "–",
help="Winkel, bei dem die azimutal gemittelte Intensität auf die Hälfte des Wertes auf der Achse fällt.")
c[2].metric("Fernfeldleistung / Fluss", f"{far['balance']:.4f}" if far.get("balance") is not None else "–",
help="Leistung aus dem Fernfeld (Integral von |F|²/2Z) durch den Fluss durch die Fläche um den Emitter. Sollte bei verlustfreier Struktur "
"nahe 1 liegen (Abweichungen: Diskretisierung, Verluste, PML).")
c[3].metric("Leistung in 10°-Kegel", f"{far['fraction_within_deg'].get('10', float('nan')):.3f}")
if layered:
c[2].metric("abgestrahlt oben / unten", f"{far['frac_up']:.3f} / {far['frac_down']:.3f}" if far.get("frac_up") is not None else "–",
help="Anteil der vom Dipol abgegebenen Leistung, der im Fernfeld in das Umgebungsmedium (oben) und in das Substrat (unten) gelangt.")
c[3].metric("geführt + absorbiert", f"{far['frac_guided_absorbed']:.3f}" if far.get("frac_guided_absorbed") is not None else "–",
help="Rest: 1 − (oben + unten). Geführte Moden der Schichten (laufen in die PML) und Absorption in verlustbehafteten Schichten.")
if not far.get("down_available", True):
st.info("Das Substrat ist verlustbehaftet: es gibt kein Fernfeld nach unten, die Diagramme zeigen nur die obere Halbebene.")
else:
c[2].metric("Fernfeldleistung / Fluss", f"{far['balance']:.4f}" if far.get("balance") is not None else "–",
help="Leistung aus dem Fernfeld (Integral von |F|²/2Z) durch den Fluss durch die Fläche um den Emitter. Sollte bei verlustfreier Struktur "
"nahe 1 liegen (Abweichungen: Diskretisierung, Verluste, PML).")
c[3].metric("Leistung in 10°-Kegel", f"{far['fraction_within_deg'].get('10', float('nan')):.3f}")
st.caption("Fernfeld per Nah-zu-Fern-Transformation (Stratton–Chu) auf der geschlossenen Messbox (hpfem.axisymmetric_far_field, Summe der Azimutordnungen "
"mit superpose_far_field). Der Dipol zeigt in x-Richtung: E-Ebene = x–z, H-Ebene = y–z. Der Gewinn bezieht sich auf P_bulk/4π desselben "
"Dipols im unbegrenzten Umgebungsmedium (mit derselben Gauß-Glättung). Der Anteil „in den Kegel“ ist auf die gesamte vom Dipol abgegebene "
"Leistung bezogen.")
"Leistung bezogen." + (" Auf einem Schichtstapel gilt das Fernfeld je Halbraum im eigenen Medium (Brechzahl n, Impedanz Z); der Gewinn nach unten "
"ist ebenfalls auf P_bulk/4π des Dipols bezogen." if layered else ""))
th = np.degrees(np.asarray(far["theta"]))
df = pd.DataFrame({"θ (°)": th, "Gewinn x-z (φ=0)": far["gain_xz_0"], "Gewinn x-z (φ=180°)": far["gain_xz_pi"], "Gewinn y-z (φ=90°)": far["gain_yz_0"],
"Gewinn y-z (φ=270°)": far["gain_yz_pi"], "Gewinn azimutal gemittelt": far["gain_mean"], "Anteil im Kegel": far["cone_fraction"]})
Expand Down
Loading
Loading