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
77 changes: 77 additions & 0 deletions fem_gui/fem_axi.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,83 @@ def fig_pattern(pt):
return fig


# ------------------------------------------------------------------------------------------------------------ far field of emitters
FAR_PHIS = 8 # azimuths for the mean over phi (orders +-1 give |F|^2 harmonics up to 2: 8 samples integrate it exactly)


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."
lay = layout(model)
r = np.linspace(0.0, lay["r_plane"], n)
z = np.linspace(lay["z_plane_bottom"], lay["z_plane_top"], n)
pts = [(rr, lay["z_plane_top"]) for rr in r] + [(rr, lay["z_plane_bottom"]) for rr in r] + [(lay["r_plane"], zz) for zz in z]
bad = [(rr, zz) for rr, zz in pts if material_at(model, rr, zz) != model["background"]]
if bad:
return False, (f"Die Messbox (r <= {lay['r_plane']:g} nm, z = {lay['z_plane_bottom']:g} ... {lay['z_plane_top']:g} nm) schneidet die Struktur "
f"(z. B. bei r = {bad[0][0]:g}, z = {bad[0][1]:g} nm): Abstand zur PML (Gebiet, Reiter 1) vergrößern.")
return True, ""


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
medium (I(0) / (p_bulk / 4 pi)), half-angle at which the mean intensity falls to half of its on-axis value (None if it does not),
and the collected fractions at some half-angles."""
th = np.asarray(theta, float)
I = np.asarray(intensity_mean, float)
seg = 0.5 * (I[1:] * np.sin(th[1:]) + I[:-1] * np.sin(th[:-1])) * np.diff(th)
cum = np.concatenate([[0.0], np.cumsum(seg)]) * 2.0 * np.pi
frac = cum / p_total if p_total else np.full_like(cum, np.nan)
gain0 = float(I[0] / (p_bulk / (4.0 * np.pi))) if p_bulk else None
half = None
if I[0] > 0:
below = np.nonzero(I < 0.5 * I[0])[0]
if len(below):
j = int(below[0])
t0, t1, i0, i1 = th[j - 1], th[j], I[j - 1], I[j]
half = float(np.degrees(t0 + (t1 - t0) * (i0 - 0.5 * I[0]) / (i0 - i1))) if j > 0 and i0 != i1 else float(np.degrees(th[j]))
at = {f"{c:g}": float(np.interp(np.radians(c), th, frac)) for c in cones_deg}
return dict(cone_fraction=frac.tolist(), axis_gain=gain0, half_angle_fwhm_deg=half, fraction_within_deg=at, power_total=float(cum[-1]))


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."""
import matplotlib.pyplot as plt

far = pt["far"]
th = np.asarray(far["theta"])
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(1, 2, 1, projection="polar")
axial = far.get("orientation") == "axial"
planes = ((("xz", "x-z (E-Ebene des Dipols)", "C0"), ("yz", "y-z (H-Ebene)", "C1")) if not axial else (("xz", "Meridianebene (alle gleich)", "C0"),))
for key, lab, col in planes:
a, b = np.asarray(far[f"gain_{key}_0"]), np.asarray(far[f"gain_{key}_pi"])
ang = np.concatenate([th, 2 * np.pi - th[::-1]])
val = np.concatenate([a, b[::-1]])
if log:
val = 10 * np.log10(np.maximum(val, 1e-6))
ax.plot(ang, val, color=col, label=lab)
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
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.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")
bx.set_ylabel("Anteil der emittierten Leistung P(<θ) / P")
bx.grid(alpha=0.3)
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
49 changes: 47 additions & 2 deletions fem_gui/fem_axi_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,18 @@ def tab_run(model, work, ctx):
help="P_bulk aus derselben Quelle auf demselben Netz mit dem Emittermaterial überall, statt der Larmor-Formel: der "
"Diskretisierungsfehler der schmalen Gauß-Quelle kürzt sich heraus. An einer GaAs-Membran gegen die exakte "
"Sommerfeld-Lösung: Abweichung 1,4·10⁻³ statt 5,7·10⁻³ (σ = 10 nm, p = 3).")
if S.ax_task == "emitter":
c2 = st.columns([3, 1])
sv["far_field"] = c2[0].checkbox("Fernfeld berechnen (Winkelverteilung der Abstrahlung)", value=bool(sv.get("far_field", False)), key="ax_far_field",
help="Nah-zu-Fern-Transformation (Stratton-Chu, hpfem.axisymmetric_far_field) auf der geschlossenen Messbox um die Struktur, "
"die ganz im Umgebungsmedium liegen muss (kein Substrat, keine durchlaufenden Schichten). Der Dipol senkrecht zur Achse "
"braucht eine zweite Lösung (m = -1): doppelte Rechenzeit je Wellenlänge.")
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)
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 All @@ -450,7 +462,8 @@ def tab_run(model, work, ctx):
for f in ("mesh.msh", "mesh_plot.npz"):
shutil.copy(Path(mesh["dir"]) / f, run_dir / f)
job = dict(model=copy.deepcopy(model), task=S.ax_task, solver=dict(order=sv["order"], backend=sv["backend"], bulk_fem=bool(sv.get("bulk_fem"))), subdivisions=sv["subdivisions"],
fields=bool(sv["fields"]), field_at_centre=bool(sv["fields"]))
fields=bool(sv["fields"]), field_at_centre=bool(sv["fields"]),
far_field=bool(sv.get("far_field")) and S.ax_task == "emitter", far_theta_samples=int(sv.get("far_theta_samples", 721)))
(run_dir / "job.json").write_text(json.dumps(job, indent=1), encoding="utf-8")
S.run_proc = fr.start_worker(ctx["py"], ctx["repo"], run_dir, int(ctx["threads"]), script="fem_axi_worker.py")
S.run_dir, S.run_msg, S.cancel_requested, S.run_kind = str(run_dir), "", False, "axi"
Expand Down Expand Up @@ -532,7 +545,11 @@ def tab_results(work):
st.info(f"Resonanz (m = {rsn['m']}): λ = {chosen['lam_nm']:.3f} nm, Q = {chosen['Q']:.4g}, Linienbreite {chosen['lam_nm'] / chosen['Q']:.3f} nm. "
"Das Spektrum liegt symmetrisch darum.")
has_modal = any(p.get("modal") for p in ok)
sub = st.tabs(["Purcell und Abstrahlung", "Feld", "Tabelle und Export"] + (["Modenzerlegung"] if has_modal else []))
has_far = any(p.get("far") for p in ok)
sub = st.tabs(["Purcell und Abstrahlung", "Feld", "Tabelle und Export"] + (["Modenzerlegung"] if has_modal else []) + (["Fernfeld"] if has_far else []))
if has_far:
with sub[3 + int(has_modal)]:
far_results(ok)
if has_modal:
with sub[3]:
ui.show_fig(fa.fig_modal(ok, chosen), "modenzerlegung.png", "ax_dl_modal")
Expand Down Expand Up @@ -579,6 +596,34 @@ def tab_results(work):
st.caption(f"Ordner: {view}")


def far_results(ok):
fp = [p for p in ok if p.get("far")]
lab = {p["index"]: f"Punkt {p['index']}: λ = {p['lam_nm']:.3f} nm, F_P = {p['purcell']:.3g}" for p in fp}
pick = st.selectbox("Wellenlänge", list(lab), format_func=lab.get, index=len(fp) // 2, key="ax_far_pick")
pt = next(p for p in fp if p["index"] == pick)
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")
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 "–",
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}")
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.")
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"]})
st.download_button("Fernfeld (CSV)", ui.csv_bytes(df), file_name=f"fernfeld_{pick}.csv", mime="text/csv", key="ax_dl_far_csv")


def scattering_results(view, res, model):
pts = res.get("points", [])
ok = [p for p in pts if "error" not in p]
Expand Down
74 changes: 73 additions & 1 deletion fem_gui/fem_axi_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,56 @@ def plane_surface(job, z_nm, direction):
return s


def emitter_far_raw(job, setup, field, m, axial, omega, mm, box, sigma_m, em):
"""Far field of the emitter on the closed box in the background (near-to-far transform, Stratton-Chu): the axial dipole is the single order
m = 0; the transverse dipole (along x) needs both orders m = +1 (already solved: `field`) and m = -1 (a second solve with the mirrored
source). Returns the intensity [W/sr] at the azimuths phi_k = 2 pi k / FAR_PHIS for |p| = 1 A m, and the radiated power of the orders.
`setup` is restored before returning (the caller re-uses it)."""
h = job.h
n_th = max(int(job.job.get("far_theta_samples", 721)), 181)
thetas = np.linspace(0.0, np.pi, n_th).tolist()
orders, fields = [m], [field]
if not axial:
keep_m, keep_cur = setup.azimuthal_order, setup.current
try:
setup.azimuthal_order = -1
setup.current = h.axisymmetric_gaussian_dipole(float(em["z_nm"]) * NM, 1.0, h.AxisDipole.TRANSVERSE, sigma_m, omega, -1)
t0 = time.time()
f_minus = h.AxisymmetricScattering(job.nd, job.h1, setup).solve()
say(f" far field: second solve for m = -1 in {time.time() - t0:.1f} s")
finally:
setup.azimuthal_order, setup.current = keep_m, keep_cur
orders.append(-1)
fields.append(f_minus)
t0 = time.time()
patterns = [h.axisymmetric_far_field(job.nd, job.h1, f.meridian, f.azimuthal, mo, omega, mm, box, thetas) for mo, f in zip(orders, fields)]
impedance = float(patterns[0].impedance)
p_far = float(sum(pt.radiated_power() for pt in patterns))
phis = [2 * np.pi * k / fa.FAR_PHIS for k in range(fa.FAR_PHIS)]
inten = []
for phi in phis:
F = h.superpose_far_field(patterns, orders, float(phi))
inten.append((np.abs(np.asarray(F.f_theta)) ** 2 + np.abs(np.asarray(F.f_phi)) ** 2) / (2.0 * impedance))
say(f" far field: {len(thetas)} angles, orders {orders}, {time.time() - t0:.1f} s")
return dict(theta=np.asarray(thetas), inten=np.asarray(inten), p_far=p_far, orders=orders)


def emitter_far_final(raw, p_total, p_bulk, axial):
"""Gain patterns (relative to the isotropic emitter of the same medium, P_bulk / 4 pi), metrics and the power check as a JSON-able dict."""
th, inten = raw["theta"], raw["inten"]
mean = inten.mean(axis=0)
iso = p_bulk / (4.0 * np.pi)
n = fa.FAR_PHIS
idx = {"xz_0": 0, "yz_0": n // 4, "xz_pi": n // 2, "yz_pi": 3 * n // 4}
out = dict(theta=th.tolist(), orientation="axial" if axial else "transverse", orders=raw["orders"], P_far=raw["p_far"],
P_total=p_total, balance=raw["p_far"] / p_total if p_total else None)
for key, i in idx.items():
out[f"gain_{key}"] = (inten[i] / iso).tolist()
out["gain_mean"] = (mean / iso).tolist()
out.update(fa.far_pattern_metrics(th, mean, p_total, p_bulk))
return out


def emitter_point(job, lam_nm, surfaces, em, want_field=False):
"""One wavelength: emitted power, Purcell factor, fractions through the planes (and the field)."""
h = job.h
Expand Down Expand Up @@ -227,6 +277,12 @@ def flux(surface):
return factor * float(h.axisymmetric_poynting_flux(job.nd, job.h1, field.meridian, field.azimuthal, m, omega, mm, surface))

total = flux(surfaces["around"])
far_raw = None
if surfaces.get("box") is not None:
try:
far_raw = emitter_far_raw(job, setup, field, m, axial, omega, mm, surfaces["box"], sigma, em)
except Exception as exc:
say(f"WARN Fernfeld nicht berechnet: {exc}")
top = flux(surfaces["top"]) if surfaces.get("top") is not None and len(surfaces["top"]) else 0.0
bottom = flux(surfaces["bottom"]) if surfaces.get("bottom") is not None and len(surfaces["bottom"]) else 0.0
n_em = float(np.sqrt(eps[surfaces["emitter_material"]] + 0j).real)
Expand All @@ -246,6 +302,10 @@ def flux(surface):
res = dict(lam_nm=lam_nm, P_total=total, P_top=top, P_bottom=bottom, P_bulk=bulk, P_bulk_analytic=bulk_analytic, purcell=total / bulk,
purcell_radiative=(top + bottom) / bulk, beta_top=top / total if total else None, beta_bottom=bottom / total if total else None,
n_emitter=n_em, dofs=job.dofs, time_s=t_solve)
if far_raw is not None:
res["far"] = emitter_far_final(far_raw, total, bulk, axial)
say(f" far field power / flux = {res['far']['balance']:.4f}; on-axis gain {res['far']['axis_gain']:.3g}"
+ (f"; half-angle {res['far']['half_angle_fwhm_deg']:.2f} deg" if res["far"]["half_angle_fwhm_deg"] is not None else ""))
fld = export_field(job, field.meridian, field.azimuthal, job.job.get("subdivisions", 2)) if want_field else None
if fld is not None:
fld.update(lam_nm=lam_nm, m=m, kind="emitter", purcell=res["purcell"])
Expand Down Expand Up @@ -415,7 +475,19 @@ def emitter_surfaces(job):
say(f"surfaces: around the emitter {len(around)} facets, top plane {len(top)}, bottom plane {len(bottom)}")
if not len(top):
say("WARN keine Facetten auf der oberen Messebene: β nicht messbar")
return dict(around=around, top=top, bottom=bottom, emitter_material=job.names[(src_tags[0] - 1) % fa.TAG_SOURCE], z=float(em["z_nm"]))
box = None
if job.job.get("far_field"):
ok, why = fa.box_in_background(job.model)
if not ok:
say(f"WARN Fernfeld übersprungen: {why}")
else:
box = box_surface(job)
if not len(box):
say("WARN Fernfeld übersprungen: keine Facetten auf der Messbox (Netz mit der Aufgabe „Emitter“ neu erzeugen)")
box = None
else:
say(f"far-field box: {len(box)} facets")
return dict(around=around, top=top, bottom=bottom, box=box, emitter_material=job.names[(src_tags[0] - 1) % fa.TAG_SOURCE], z=float(em["z_nm"]))


# ------------------------------------------------------------------------------------------------------------------ main
Expand Down
Loading
Loading