diff --git a/fem_gui/fem_axi.py b/fem_gui/fem_axi.py index d836dbf..cb654db 100644 --- a/fem_gui/fem_axi.py +++ b/fem_gui/fem_axi.py @@ -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) @@ -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 @@ -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"] @@ -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")} diff --git a/fem_gui/fem_axi_app.py b/fem_gui/fem_axi_app.py index 3e0ddbd..2e0293f 100644 --- a/fem_gui/fem_axi_app.py +++ b/fem_gui/fem_axi_app.py @@ -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)) @@ -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"]}) diff --git a/fem_gui/fem_axi_worker.py b/fem_gui/fem_axi_worker.py index f3635d3..a4b8b55 100644 --- a/fem_gui/fem_axi_worker.py +++ b/fem_gui/fem_axi_worker.py @@ -198,14 +198,30 @@ 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. +def layer_stack(job, lam_nm): + """hpfem.LayerStack3D of the planar background at lam_nm (cover = background medium, layers from top to bottom, substrate) and whether the + substrate is lossless (then the far field into it exists). Coordinates in metres; the stack's z is the y of the meridian mesh.""" + h, model = job.h, job.model + plan = fa.stack_layers(model) + + def mat(name): + return h.Material(complex(fm.eps_at(model["materials"][name], lam_nm))) + + cover = mat(model["background"]) + layers = [h.Layer(mat(n), float(t) * NM) for n, t in plan["layers"]] + lossless = abs(complex(fm.eps_at(model["materials"][plan["substrate"]], lam_nm)).imag) < 1e-9 + return h.LayerStack3D(cover, layers, mat(plan["substrate"]), float(plan["top_nm"]) * NM), lossless + + +def emitter_far_raw(job, setup, field, m, axial, omega, mm, box, sigma_m, em, mode="homogeneous", lam_nm=None): + """Far field of the emitter on the closed box. mode "homogeneous": near-to-far transform (Stratton-Chu) in the background medium. mode "layered" + (substrate and layers through the box): by reciprocity with the plane waves of the stack, separately in the cover (theta < 90 deg) and in a + lossless substrate (theta > 90 deg; a lossy substrate has no far field, only the upper half is returned). 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] in the medium of each half-space at the azimuths phi_k = 2 pi k / FAR_PHIS for |p| = 1 A m and the radiated powers. `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 @@ -220,16 +236,39 @@ def emitter_far_raw(job, setup, field, m, axial, omega, mm, box, sigma_m, em): 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)) + halves = [] # (theta, [pattern per order]) per half-space + down_available = True + if mode == "layered": + stack, lossless = layer_stack(job, lam_nm) + n_half = max(n_th // 2, 91) + th_up = np.linspace(0.0, np.pi / 2 - 1e-6, n_half) + th_dn = np.linspace(np.pi / 2 + 1e-6, np.pi, n_half) if lossless else np.array([]) + down_available = bool(lossless) + if not lossless: + say(" far field: lossy substrate, only the upper half-space (no far field into an absorbing substrate)") + res = [h.axisymmetric_layered_far_field(job.nd, job.h1, f.meridian, f.azimuthal, mo, omega, mm, box, stack, th_up.tolist(), th_dn.tolist()) + for mo, f in zip(orders, fields)] + halves.append((th_up, [r.up for r in res])) + if down_available: + halves.append((th_dn, [r.down for r in res])) + else: + thetas = np.linspace(0.0, np.pi, n_th) + halves.append((thetas, [h.axisymmetric_far_field(job.nd, job.h1, f.meridian, f.azimuthal, mo, omega, mm, box, thetas.tolist()) + for mo, f in zip(orders, fields)])) 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) + th_all, inten_parts, powers = [], [], [] + for th, patterns in halves: + impedance = float(patterns[0].impedance) # of the medium of this half-space + powers.append(float(sum(pt.radiated_power() for pt in patterns))) + rows = [] + for phi in phis: + F = h.superpose_far_field(patterns, orders, float(phi)) + rows.append((np.abs(np.asarray(F.f_theta)) ** 2 + np.abs(np.asarray(F.f_phi)) ** 2) / (2.0 * impedance)) + th_all.append(th) + inten_parts.append(np.asarray(rows)) + say(f" far field ({mode}): {sum(len(t) for t in th_all)} angles, orders {orders}, {time.time() - t0:.1f} s") + return dict(theta=np.concatenate(th_all), inten=np.concatenate(inten_parts, axis=1), p_far=float(sum(powers)), orders=orders, + layered=(mode == "layered"), p_up=powers[0], p_down=powers[1] if len(powers) > 1 else 0.0, down_available=down_available) def emitter_far_final(raw, p_total, p_bulk, axial): @@ -239,12 +278,20 @@ def emitter_far_final(raw, p_total, p_bulk, axial): 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} + layered = bool(raw.get("layered")) 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) + P_total=p_total, balance=raw["p_far"] / p_total if p_total else None, layered=layered) 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)) + if raw.get("down_available", True) and th[-1] > np.pi - 1e-3: # the cone around -z: the same metrics on the reversed grid + dn = fa.far_pattern_metrics(np.pi - th[::-1], mean[::-1], p_total, p_bulk) + out.update(cone_fraction_down=dn["cone_fraction"], axis_gain_down=dn["axis_gain"], half_angle_down_deg=dn["half_angle_fwhm_deg"]) + if layered: + out.update(P_up=raw["p_up"], P_down=raw["p_down"], frac_up=raw["p_up"] / p_total if p_total else None, + frac_down=raw["p_down"] / p_total if p_total else None, down_available=bool(raw.get("down_available", True))) + out["frac_guided_absorbed"] = 1.0 - out["balance"] if out["balance"] is not None else None # rest: guided along the layers, absorbed return out @@ -280,7 +327,7 @@ def flux(surface): 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) + far_raw = emitter_far_raw(job, setup, field, m, axial, omega, mm, surfaces["box"], sigma, em, mode=surfaces.get("far_mode", "homogeneous"), lam_nm=lam_nm) 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 @@ -304,7 +351,8 @@ def flux(surface): 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}" + say((f" far field up {res['far']['frac_up']:.4f}, down {res['far']['frac_down']:.4f} of the emitted power (rest guided / absorbed); " + if res["far"]["layered"] else f" far field power / flux = {res['far']['balance']:.4f}; ") + f"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: @@ -476,9 +524,10 @@ def emitter_surfaces(job): if not len(top): say("WARN keine Facetten auf der oberen Messebene: β nicht messbar") box = None + far_mode = None if job.job.get("far_field"): - ok, why = fa.box_in_background(job.model) - if not ok: + far_mode, why = fa.far_field_plan(job.model) + if far_mode is None: say(f"WARN Fernfeld übersprungen: {why}") else: box = box_surface(job) @@ -486,8 +535,8 @@ def emitter_surfaces(job): 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"])) + say(f"far-field box: {len(box)} facets, mode {far_mode}") + return dict(around=around, top=top, bottom=bottom, box=box, far_mode=far_mode, emitter_material=job.names[(src_tags[0] - 1) % fa.TAG_SOURCE], z=float(em["z_nm"])) # ------------------------------------------------------------------------------------------------------------------ main diff --git a/tests/test_axi.py b/tests/test_axi.py index 375b5d4..f20d45c 100644 --- a/tests/test_axi.py +++ b/tests/test_axi.py @@ -225,3 +225,66 @@ def test_box_in_background_lens_and_substrate(): lay["layers"] = [dict(material="Glas", z_bottom=-100.0, height=50.0)] assert not fa.box_in_background(lay)[0] # the box (r_max + margin/2, z_struct +- margin/2) encloses every part by construction: only substrate and layers can cross it + + +# ------------------------------------------------------------------------------------------------ far field on a layer stack (without hpfem) +def _stack_model(layers, substrate=None): + m = fa.default_model() + m["materials"].update({"GaAs": {"type": "index", "n": 3.53, "k": 0.0}, "AlAs": {"type": "index", "n": 2.95, "k": 0.0}}) + m["parts"], m["layers"], m["substrate"] = [], layers, substrate + return m + + +def test_stack_layers_membrane_substrate_and_merge(): + assert fa.stack_layers(fa.default_model()) is None + mem = fa.stack_layers(_stack_model([dict(material="GaAs", z_bottom=0.0, height=200.0)])) # membrane in air + assert mem["top_nm"] == 200.0 and mem["layers"] == [("GaAs", 200.0)] and mem["substrate"] == "Luft" + sub = fa.stack_layers(_stack_model([], "Glas")) # bare substrate: no layers + assert sub["top_nm"] == 0.0 and sub["layers"] == [] and sub["substrate"] == "Glas" + two = fa.stack_layers(_stack_model([dict(material="GaAs", z_bottom=0.0, height=100.0), dict(material="AlAs", z_bottom=100.0, height=50.0), + dict(material="AlAs", z_bottom=150.0, height=25.0)], "Glas")) + assert two["top_nm"] == 175.0 and two["layers"] == [("AlAs", 75.0), ("GaAs", 100.0)] and two["substrate"] == "Glas" # same neighbours merged + gap = fa.stack_layers(_stack_model([dict(material="GaAs", z_bottom=100.0, height=50.0)], "Glas")) # air gap above the substrate + assert gap["layers"] == [("GaAs", 50.0), ("Luft", 100.0)] and gap["top_nm"] == 150.0 + total = sum(t for _, t in gap["layers"]) + assert gap["top_nm"] - total == pytest.approx(0.0) # lowest interface at z = 0 + for name, m in fa.presets().items(): + if m.get("layers") or m.get("substrate"): + st = fa.stack_layers(m) + assert st["substrate"] in m["materials"] and all(t > 0 for _, t in st["layers"]), name + + +def test_far_field_plan_modes(): + base = fa.default_model() + base["parts"] = [dict(type="sphere", material="Glas", z_center=0.0, radius=500.0)] + base["emitter"]["z_nm"] = 700.0 + assert fa.far_field_plan(base)[0] == "homogeneous" + sub = copy.deepcopy(base) + sub["substrate"] = "Glas" + mode, text = fa.far_field_plan(sub) + assert mode == "layered" and "Substrat" in text + + +def test_emitter_far_final_layered_fractions_and_down_cone(): + import fem_axi_worker as fw + + up = np.linspace(0.0, np.pi / 2 - 1e-6, 181) + dn = np.linspace(np.pi / 2 + 1e-6, np.pi, 181) + th = np.concatenate([up, dn]) + inten = np.array([np.where(th < np.pi / 2, 2.0, 1.0)] * fa.FAR_PHIS) / (4 * np.pi) # 2/(4 pi) up, 1/(4 pi) down: powers 1 and 0.5 + raw = dict(theta=th, inten=inten, p_far=1.5, orders=[1, -1], layered=True, p_up=1.0, p_down=0.5, down_available=True) + out = fw.emitter_far_final(raw, 2.0, 2.0, False) + assert out["layered"] and out["frac_up"] == pytest.approx(0.5) and out["frac_down"] == pytest.approx(0.25) + assert out["frac_guided_absorbed"] == pytest.approx(0.25) + assert out["axis_gain"] == pytest.approx(2.0 / (4 * np.pi) / (2.0 / (4 * np.pi)), rel=1e-6) # I(0) / (P_bulk / 4 pi) = 1 + assert out["axis_gain_down"] == pytest.approx(0.5 * out["axis_gain"], rel=1e-6) + assert len(out["cone_fraction_down"]) == len(th) + json.dumps(out) + import matplotlib.pyplot as plt + fig = fa.fig_far_pattern(dict(lam_nm=450.0, far=out)) + plt.close(fig) + # lossy substrate: only the upper half + raw2 = dict(theta=up, inten=inten[:, :181], p_far=1.0, orders=[1, -1], layered=True, p_up=1.0, p_down=0.0, down_available=False) + out2 = fw.emitter_far_final(raw2, 2.0, 2.0, False) + assert "cone_fraction_down" not in out2 and out2["down_available"] is False + plt.close(fa.fig_far_pattern(dict(lam_nm=450.0, far=out2)))