From 0b2e75d1ce8c3d3cb8d24675967efc92c5f67095 Mon Sep 17 00:00:00 2001 From: PhotonPower Date: Fri, 6 Nov 2026 11:31:59 +0100 Subject: [PATCH] Kristalle im Materialeditor und Jones-/Mueller-Matrizen (hp-FEM M19 S8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fem_materials: Typ "crystal" (einachsig mit Achse θ/φ, zweiachsig mit Euler-Winkeln, voller symmetrischer Tensor) im Laborsystem; tensor_at, principal_values, is_crystal; eps_at gibt für Kristalle den größten Hauptwert (Netzweiten). * fem_ui: Kristall-Editor mit Hauptindizes; nur im periodischen Modus angeboten. * fem_worker: Material.anisotropic, AnisotropicStack bei Kristallschichten/-substrat, nur Löser grating; Option solver.jones über grating.jones, results "jones" je Ordnung. * fem_post / fem_app: Reiter "Jones / Mueller" (Mueller-Karte bzw. 4x4 Kurven, Jones-Tabelle, CSV); Bibliotheksmerkmale crystals und jones. * Rotationskörper und Einfallsmedium lehnen Kristalle ab. Gegen die analytische Jones-Matrix einer flachen Kristallplatte auf Kristallsubstrat über Worker und grating.jones: 3e-16. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++ README.md | 2 +- docs/ARCHITEKTUR.md | 8 +-- fem_gui/fem_app.py | 51 ++++++++++++++++--- fem_gui/fem_axi_worker.py | 3 ++ fem_gui/fem_geometry.py | 2 + fem_gui/fem_materials.py | 72 ++++++++++++++++++++++++++- fem_gui/fem_post.py | 93 +++++++++++++++++++++++++++++++++++ fem_gui/fem_run.py | 4 +- fem_gui/fem_ui.py | 78 +++++++++++++++++++++++++---- fem_gui/fem_worker.py | 43 ++++++++++++++-- tests/test_crystals.py | 100 ++++++++++++++++++++++++++++++++++++++ 12 files changed, 438 insertions(+), 29 deletions(-) create mode 100644 tests/test_crystals.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 66e5ca1..be8ce0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Änderungen +## Unveröffentlicht + +* Neu: **Kristalle (anisotrope Materialien)** im Materialeditor (hp-FEM M19, ADR-0015): einachsig (n_o, n_e, Achse über θ gegen die Normale und φ + gegen x), zweiachsig (drei Hauptindizes, Euler-Winkel z-x-z) oder voller symmetrischer Tensor, im Laborsystem (x quer zu den Linien, y längs, z die + Normale); in Formen, Schichten und Substrat, das Einfallsmedium bleibt isotrop. Nur mit dem Löser `hpfem.grating` (Schichten oder Substrat aus + Kristall: `AnisotropicStack`); Rotationskörper lehnen Kristalle ab. +* Neu: **Jones- und Mueller-Matrizen** je ausbreitungsfähiger Ordnung (`hpfem.grating.jones`, Option „Jones- und Mueller-Matrizen berechnen“): + Reiter „Jones / Mueller“ mit der Mueller-Matrix (Einzelpunkt als Karte, Durchlauf als 4×4 Kurven, normiert auf m_00) und der Jones-Tabelle + (Betrag, Phase, Effizienz); bei einem Kristallsubstrat sind die Zeilen der transmittierten Matrix die beiden Moden. Gegen die analytische + Jones-Matrix einer flachen Kristallplatte auf Kristallsubstrat: 3·10⁻¹⁶. + ## 0.3.0 (2026-10-09) * Neu: **Radial unendliche Schichten** bei Rotationskörpern (durch die PML bis zur Wand): planare Spiegel, Membranen, Schichtwellenleiter; DBR-Generator diff --git a/README.md b/README.md index 2faf350..b7d16c6 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Die App startet die Rechnung (Worker) als eigenen Prozess in einem Python mit `h | Teil | Python | Pakete | |---|---|---| | App (Oberfläche, Gmsh, Auswertung) | beliebiges Python ≥ 3.10 | `pip install -r requirements.txt` | -| Rechnung (Worker) | ein Python mit `hpfem` | [hp-FEM](https://github.com/PhotonPower/hp-FEM) **ab 0.4** empfohlen (`hpfem.grating`, Resonanzen, Prüfungen; Ableitungen ab dem Stand M16 auf `main`). Ältere Versionen mit `ConicalScattering` gehen mit den klassischen Lösern. | +| Rechnung (Worker) | ein Python mit `hpfem` | [hp-FEM](https://github.com/PhotonPower/hp-FEM) **ab 0.4** empfohlen (`hpfem.grating`, Resonanzen, Prüfungen; Ableitungen ab dem Stand M16, Kristalle und Jones-/Mueller-Matrizen ab M19 auf `main`). Ältere Versionen mit `ConicalScattering` gehen mit den klassischen Lösern. | ## Installation und Start (Windows, eine Umgebung für App und Rechnung) diff --git a/docs/ARCHITEKTUR.md b/docs/ARCHITEKTUR.md index 5f2db05..c67b607 100644 --- a/docs/ARCHITEKTUR.md +++ b/docs/ARCHITEKTUR.md @@ -19,7 +19,7 @@ |---|---| | `fem_app.py` | Streamlit-Seite mit fünf Reitern (Modell, Netz, Rechnung, Ergebnisse, Info) und Seitenleiste. Prüft beim Start, dass alle Module zur gleichen Version gehören. | | `fem_geometry.py` | Modell (Schichten, Formen, Beleuchtung, Gebiet), Vorlagen, Validierung, PML-Auslegung, Gmsh-Netz (physikalische Gruppen für den hpfem-Reader), Vorschau und Netzbilder. | -| `fem_materials.py` | Optische Konstanten ohne hpfem: Bibliothek (CSV aus `python/hpfem/data` und Sellmeier), n+ik, ε, Drude, Tabelle. Gleiche Werte wie `hpfem.materials`. | +| `fem_materials.py` | Optische Konstanten ohne hpfem: Bibliothek (CSV aus `python/hpfem/data` und Sellmeier), n+ik, ε, Drude, Tabelle, Kristall (`tensor_at`: 3×3-Tensor im Laborsystem; `eps_at` gibt für Kristalle den größten Hauptwert für Netzweiten). Gleiche Werte wie `hpfem.materials`. | | `fem_run.py` | Durchlaufwerte, Job-Datei, Start des Workers als Hintergrundprozess (PYTHONPATH nur für einen Quell-Build mit gebautem Modul), Abbruchdatei, Prüflauf (`--check`), Bibliotheksprüfung (Version, Funktionen), Log- und Fortschrittsauswertung. | | `fem_worker.py` | Läuft im hpfem-Python. Liest `job.json` und `mesh.msh`, rechnet je Durchlaufpunkt (Streuung oder Resonanzen), schreibt Ergebnisse nach jedem Punkt. Mit `--check` nur Prüfungen und Speicherschätzung. | | `fem_ui.py` | Gemeinsame Streamlit-Bausteine beider Modi (Materialeditor, Tabellen, Bilder mit Download, CSV). | @@ -31,8 +31,8 @@ ## Schnittstelle App ↔ Worker * Der App-Prozess schreibt `/run/job.json` (Modell, Schichtlage, Beleuchtung, Durchlauf, Löser, Karten, Konvergenzstudie) und `mesh.msh` (Gmsh 4.1, ASCII). -* `job.json` enthält außerdem `task` (`scattering` oder `resonances`) und `resonance` (`num_modes`, `krylov_dimension`); `solver.engine` ist `grating`, `grating_hp`, `conical`, `inplane` oder `inplane_hp`, dazu `jacobian`, `scalar`, `check` und unter `adaptive` `estimator` (`residual`/`dwr`) und `mirror_periodic`. -* Der Worker schreibt `log.txt` mit den Zeilen `PROGRESS i/n`, `STEP s/S`, `PHASE name`, `ESTIMATE …`, `DIAG severity code: text`, `WARN …`, `ERROR …`, `CANCELLED` und `DONE`, danach `results.json` (nach jedem Punkt aktualisiert; bei `grating` zusätzlich `diagnostics`, `timing`, `flux_balance`, `A_exact`, `amplitudes`, `jacobian`), `maps_.npz` (Raster, mit `H` und `S`), `tri_.npz` (Elemente, exakt, mit `values_H` und `values_S`), `hpmesh_.npz` (Endnetz der hp-Adaptivität) und bei Resonanzen `mode__.npz`. +* `job.json` enthält außerdem `task` (`scattering` oder `resonances`) und `resonance` (`num_modes`, `krylov_dimension`); `solver.engine` ist `grating`, `grating_hp`, `conical`, `inplane` oder `inplane_hp`, dazu `jacobian`, `scalar`, `check`, `jones` (Jones-/Mueller-Matrizen über `grating.jones`) und unter `adaptive` `estimator` (`residual`/`dwr`) und `mirror_periodic`. +* Der Worker schreibt `log.txt` mit den Zeilen `PROGRESS i/n`, `STEP s/S`, `PHASE name`, `ESTIMATE …`, `DIAG severity code: text`, `WARN …`, `ERROR …`, `CANCELLED` und `DONE`, danach `results.json` (nach jedem Punkt aktualisiert; bei `grating` zusätzlich `diagnostics`, `timing`, `flux_balance`, `A_exact`, `amplitudes`, `jacobian` und mit `solver.jones` `jones`: je Ordnung `"R0"`, `"T-1"`, … ein Dict mit `J` (2×2, Paare [Re, Im]; Spalten einfallend s, p), `M` (4×4 Mueller) und `channels` (Zeilennamen, `s`/`p` oder die Moden eines Kristallsubstrats)), `maps_.npz` (Raster, mit `H` und `S`), `tri_.npz` (Elemente, exakt, mit `values_H` und `values_S`), `hpmesh_.npz` (Endnetz der hp-Adaptivität) und bei Resonanzen `mode__.npz`. * Abbruch: die App legt `/cancel` an; der Worker fragt die Datei zwischen den Phasen eines Lösungsschritts (Fortschritts-Callback von hpfem) und zwischen den Punkten ab und endet mit `CANCELLED`. * Ein erneutes Ausführen der Streamlit-Seite beendet den Worker nicht: die App findet ihn über das Prozessobjekt und die Logdatei wieder. @@ -52,4 +52,4 @@ H_sca = H − `incident_h_field`), in homogener Umgebung `conical_cross_sections Das Gmsh-Netz trägt die Ränder als `hpfem.box_tag` (1 links, 2 rechts, 3 unten, 4 oben), damit `hpfem.grating` es direkt nimmt; die Materialflächen sind 1 bis N. -Die Löser `grating` und `grating_hp`, Resonanzen und der Prüflauf brauchen hp-FEM ab 0.4 (`hpfem.grating`), die Ableitungen den Stand mit `grating.jacobian` (M16 S1). Die App fragt die Bibliothek beim Start ab (`fem_run.probe_library`) und bietet nur an, was vorhanden ist. Der klassische Löser nutzt neuere Funktionen, wenn vorhanden (`AdaptiveMesh.set_periodic`, `problem.sample`, `problem.triangulate`, `absorbed_power_by_tag`, `sample(quantity="H"/"S")`) und fällt sonst auf Schleife und Rasterintegration zurück. Das Protokoll nennt dann den Grund. +Die Löser `grating` und `grating_hp`, Resonanzen und der Prüflauf brauchen hp-FEM ab 0.4 (`hpfem.grating`), die Ableitungen den Stand mit `grating.jacobian` (M16 S1), Kristalle und Jones-/Mueller-Matrizen den Stand M19 (`AnisotropicStack`, `Material.anisotropic`, `grating.jones`; Merkmale `crystals` und `jones` der Bibliotheksprüfung). Die App fragt die Bibliothek beim Start ab (`fem_run.probe_library`) und bietet nur an, was vorhanden ist. Der klassische Löser nutzt neuere Funktionen, wenn vorhanden (`AdaptiveMesh.set_periodic`, `problem.sample`, `problem.triangulate`, `absorbed_power_by_tag`, `sample(quantity="H"/"S")`) und fällt sonst auf Schleife und Rasterintegration zurück. Das Protokoll nennt dann den Grund. diff --git a/fem_gui/fem_app.py b/fem_gui/fem_app.py index b0e1fca..b5af81e 100644 --- a/fem_gui/fem_app.py +++ b/fem_gui/fem_app.py @@ -33,13 +33,13 @@ # ---- all files of the app must come from the same version: name what is missing instead of a traceback _REQUIRED = { - "fem_materials.py": (fm, ["library_available", "eps_at", "nk", "describe", "valid_range", "LIBRARY"]), + "fem_materials.py": (fm, ["library_available", "eps_at", "nk", "describe", "valid_range", "LIBRARY", "is_crystal", "tensor_at", "principal_values"]), "fem_geometry.py": (fg, ["presets", "validate", "layout", "preview_figure", "mesh_figure", "build_mesh", "suggest_domain", "pml_plan", "shift_shapes", "centering_shift", "shapes_x_extent", "material_index_map", "load_model", "new_shape", "parse_points", "shape_polygon", "reader_check"]), "fem_post.py": (fp, ["load_results", "results_dataframe", "fig_spectrum", "fig_pscan", "load_map", "derived", "fig_map", "fig_cut", "fig_absorption", "fig_absorption_sweep", "fig_adaptive_steps", "fig_hpmesh", "load_tri", "derived_tri", "fig_map_tri", "fig_materials", "available_quantities", "jacobian_dataframe", "fig_jacobian", "resonances_dataframe", "fig_resonances", "timing_dataframe", - "balance_dataframe"]), + "balance_dataframe", "jones_orders", "jones_dataframe", "mueller_dataframe", "fig_mueller"]), "fem_run.py": (fr, ["sweep_values", "wavelength_range", "make_job", "write_job", "start_worker", "read_log", "progress_info", "log_flags", "library_warnings", "default_python", "probe_library", "run_check", "request_cancel", "estimate_line", "diagnostics_lines"]), } @@ -51,7 +51,7 @@ if not (HERE / _f).is_file(): _old.append(f"{_f}: nicht gefunden (muss neben fem_app.py liegen)") _wmiss = [k for k in ("absorbed_exact", "triangulation_data", "set_periodic", "symmetrise_periodic", "design_pml", "GratingRun", "adaptive_grating_point", - "resonance_point", "check_job", "jacobian_data") if k not in _wtext] + "resonance_point", "check_job", "jacobian_data", "jones_data") if k not in _wtext] if _wmiss: _old.append(f"fem_worker.py: veraltet (es fehlt {', '.join(_wmiss)})") else: @@ -104,7 +104,7 @@ def init_state(): ensure_uids(S.model) S.mesh_settings = dict(cells_per_wavelength=3.0, skin_cells=1.0, interface_factor=0.7, curved=True, pml_cells_per_wavelength=6.0) S.solver = dict(order=4, backend="AUTO", pml_target=1e-3, pml_angle_cap_deg=80.0, orders_max=3, order_points=64, engine="grating", - jacobian=False, scalar="auto", check=True, + jacobian=False, scalar="auto", check=True, jones=False, adaptive=dict(p0=3, steps=12, max_dofs=150000, dorfler=0.5, tol=1e-4, reuse_mesh=True, estimator="residual", mirror_periodic=True)) S.maps = dict(enabled=True, indices=[0], res_nm=4.0, triangulate=True, subdiv=3, hs=True) S.task, S.resonance = "scattering", dict(num_modes=6, krylov_dimension=0) @@ -509,7 +509,10 @@ def iso_results(view, res, rmodel, mode): def _bump(): S.ver += 1 - ui.material_editor(model, ver, inc["wavelength_nm"], used_materials(model), rename_material, _bump) + ui.material_editor(model, ver, inc["wavelength_nm"], used_materials(model), rename_material, _bump, + crystals=bool(FEATS.get("crystals")) or any(fm.is_crystal(v) for v in model["materials"].values())) + if not FEATS.get("crystals"): + st.caption("Kristalle (anisotrope Materialien) brauchen hp-FEM mit M19 (AnisotropicStack).") names = list(model["materials"]) # ---------------------------------------------------------------- stack @@ -725,12 +728,36 @@ def _bump(): elif not errors: st.info("Noch kein Netz erzeugt.") +def jones_view(res, mode): + """Results tab of the Jones and Mueller matrices (hpfem.grating.jones): order and point, the Mueller figure, the Jones table.""" + pts = [p for p in res["points"] if "error" not in p and p.get("jones")] + if not pts: + st.info("Keine Jones-Matrizen in dieser Rechnung (Reiter 3: Löser „hpfem.grating“, „Jones- und Mueller-Matrizen berechnen“).") + return + keys = fp.jones_orders(pts) + c = st.columns(3) + key = c[0].selectbox("Ordnung", keys, key="jones_order", format_func=lambda k: f"{'reflektiert' if k[0] == 'R' else 'transmittiert'} m = {k[1:]}") + show_fig(fp.fig_mueller(pts, mode, key), f"mueller_{key}.png", "dl_mueller") + which = c[1].selectbox("Punkt Nr.", [p["index"] for p in pts], key="jones_pt") if len(pts) > 1 else pts[0]["index"] + pt = next(p for p in pts if p["index"] == which) + st.markdown("**Jones-Matrix**") + jdf = fp.jones_dataframe(pt, key) + table_show(jdf) + st.markdown("**Mueller-Matrix (normiert auf m_00)**") + table_show(fp.mueller_dataframe(pt, key)) + st.download_button("Jones-Matrix (CSV)", csv_bytes(jdf), file_name=f"jones_{key}_{which}.csv", mime="text/csv", key="dl_jones_csv") + st.caption("Leistungsnormiert: die Spaltensummen von |J|² sind die Effizienzen der Ordnung für einfallendes s bzw. p. Basis s, p nach " + "conical_polarisation von hp-FEM (ŝ = k̂ × n̂, p̂ = ŝ × k̂ im Lösersystem; gegenüber dem Laborsystem wechseln J_sp und J_ps das Vorzeichen). " + "Stokes (I, Q, U, V) mit Q = |E_s|² − |E_p|²; m_00 ist die Effizienz für unpolarisiertes Licht. Bei einem Kristallsubstrat sind die " + "Zeilen der transmittierten Matrix die beiden Moden (ordentlich, außerordentlich).") + + # ================================================================================================================== 3 Rechnung with t_run: sv, mp_ = S.solver, S.maps mp_.setdefault("triangulate", True) mp_.setdefault("subdiv", 3) - for k_, v_ in dict(jacobian=False, scalar="auto", check=True).items(): + for k_, v_ in dict(jacobian=False, scalar="auto", check=True, jones=False).items(): sv.setdefault(k_, v_) for k_, v_ in dict(estimator="residual", mirror_periodic=True).items(): sv["adaptive"].setdefault(k_, v_) @@ -833,6 +860,14 @@ def _bump(): sv["check"] = c[2].checkbox("Prüfungen der Bibliothek: Fehler stoppen den Punkt", value=bool(sv["check"]), key="sv_check", help="hpfem.diagnostics vor jeder Rechnung (Netz, periodische Ränder, PML, Auflösung, Materialbereich, streifende " "Ordnungen …). Warnungen erscheinen im Protokoll und unter Ergebnisse.") + sv["jones"] = st.checkbox("Jones- und Mueller-Matrizen berechnen", value=bool(sv["jones"]) and bool(FEATS.get("jones")), key="sv_jones", + disabled=not FEATS.get("jones"), + help="hpfem.grating.jones (M19): löst je Punkt für s und p und liefert für jede ausbreitungsfähige Ordnung die " + "leistungsnormierte Jones-Matrix (Spalten: einfallend s, p; Zeilen: ausfallend s, p bzw. die beiden Moden eines " + "Kristallsubstrats) und die Mueller-Matrix (Stokes I, Q, U, V). Doppelte Rechenzeit.") + crystal_names = [n for n, v in S.model["materials"].items() if fm.is_crystal(v)] + if crystal_names and not (sv["engine"] == "grating" and S.task == "scattering"): + st.error(f"Kristalle ({', '.join(crystal_names)}) rechnet nur der Löser „hpfem.grating“ (Streuung); bitte diesen Löser wählen.") if S.task == "resonances": rs_ = S.resonance c = st.columns(3) @@ -1067,7 +1102,7 @@ def prepare_job(folder): st.caption(f"Ordner mit allen Dateien: {view}") elif res is not None: sub = st.tabs(["Spektrum / Ordnungen", "Feldkarten", "Schnitte", "Absorption", "Prüfung, Bilanz, Zeit", "Ableitungen", "Konvergenz in p", - "hp-Adaptivität", "Tabelle und Export"]) + "hp-Adaptivität", "Tabelle und Export", "Jones / Mueller"]) with sub[0]: if len(df) and "R" in df: show_fig(fp.fig_spectrum(df, mode), "spektrum.png", "dl_spec") @@ -1159,6 +1194,8 @@ def prepare_job(folder): if len(tdf): st.markdown("**Rechenzeit je Phase (s)**") table_show(tdf) + with sub[9]: + jones_view(res, mode) with sub[5]: jac_pts = [p for p in res["points"] if p.get("jacobian")] if not jac_pts: diff --git a/fem_gui/fem_axi_worker.py b/fem_gui/fem_axi_worker.py index a4b8b55..d4ba6d5 100644 --- a/fem_gui/fem_axi_worker.py +++ b/fem_gui/fem_axi_worker.py @@ -68,6 +68,9 @@ def cancelled(self): def materials(self, lam_nm): """MaterialMap at lam_nm for every tag of the mesh (the emitter box carries 101 + index with the material of 1 + index); the background of the map is the surrounding medium (the contrast source of the scattered-field formulation is measured against it).""" + bad = [n for n in self.names if fm.is_crystal(self.model["materials"][n])] + if bad: + raise ValueError(f"Kristalle ({', '.join(bad)}) sind bei Rotationskörpern nicht möglich") e_bg = fm.eps_at(self.model["materials"][self.model["background"]], lam_nm) mm = self.h.MaterialMap(self.h.Material(complex(e_bg))) eps = {} diff --git a/fem_gui/fem_geometry.py b/fem_gui/fem_geometry.py index 80ac023..0647e28 100644 --- a/fem_gui/fem_geometry.py +++ b/fem_gui/fem_geometry.py @@ -258,6 +258,8 @@ def validate(model, lam_nm=None): f"y {lay['y_sub_bottom']:.0f} … {lay['y_cover_top']:.0f} nm).")) if lam_nm is not None: try: + if fm.is_crystal(model["materials"][model["cover"]]): + msgs.append(("error", "Das Einfallsmedium muss isotrop sein (kein Kristall).")) e = fm.eps_at(model["materials"][model["cover"]], lam_nm) if abs(e.imag) > 1e-9 or e.real < 1: msgs.append(("error", "Das Einfallsmedium muss verlustfrei sein (ε reell, ≥ 1).")) diff --git a/fem_gui/fem_materials.py b/fem_gui/fem_materials.py index acf1ca9..bc3850b 100644 --- a/fem_gui/fem_materials.py +++ b/fem_gui/fem_materials.py @@ -7,6 +7,16 @@ * ``eps``: ``{"type": "eps", "re": 2.25, "im": 0.0}`` * ``drude``: ``{"type": "drude", "eps_inf": 1.0, "omega_p_eV": 9.0, "gamma_eV": 0.07}`` * ``table``: ``{"type": "table", "rows": [[lambda_nm, n, k], ...]}`` (linear interpoliert, keine Extrapolation) +* ``crystal``: anisotroper Kristall (hp-FEM M19, ADR-0015), konstante Hauptindizes, Tensor im Laborsystem + (x quer zu den Linien, y längs der Linien, z die Normale nach oben): + + - ``{"type": "crystal", "kind": "uniaxial", "n_o": .., "k_o": .., "n_e": .., "k_e": .., "theta_deg": .., "phi_deg": ..}``: + optische Achse a = (sin θ cos φ, sin θ sin φ, cos θ) (θ gegen die Normale, φ gegen x), ε = ε_o I + (ε_e − ε_o) a aᵀ + - ``{"type": "crystal", "kind": "biaxial", "n": [nx, ny, nz], "k": [..], "euler_deg": [α, β, γ]}``: + ε = R diag(ε1, ε2, ε3) Rᵀ mit R = R_z(α) R_x(β) R_z(γ) (Hauptachsen gedreht, z-x-z) + - ``{"type": "crystal", "kind": "tensor", "re": 3×3, "im": 3×3}``: voller symmetrischer Tensor + + ``eps_at`` gibt für Kristalle den Hauptwert mit dem größten Realteil (Netzweiten, Schätzungen); den Tensor liefert ``tensor_at``. Konvention exp(-i omega t): ε = (n + ik)², Verlust bedeutet Im ε > 0. Wellenlängen überall in nm (Vakuum). @@ -34,6 +44,7 @@ _CONSTANT = {"vacuum": 1.0, "air": 1.000293**2} LIBRARY = ["Si", "Ag", "Au", "Al", "GaAs", "MAPbI3", "SiO2", "TiO2", "water", "air", "vacuum"] +CRYSTAL_KINDS = ("uniaxial", "biaxial", "tensor") _data_dir: Path | None = None _cache: dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]] = {} @@ -113,10 +124,61 @@ def valid_range(spec): return None +def is_crystal(spec) -> bool: + """True für einen anisotropen Kristall (Typ ``crystal``).""" + return spec.get("type") == "crystal" + + +def _rot_z(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) + + +def _rot_x(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]) + + +def tensor_at(spec, lam_nm: float) -> np.ndarray: + """Komplexer 3×3-Tensor der relativen Permittivität im Laborsystem (x quer, y längs der Linien, z die Normale); isotrope Materialien + geben ε·I. Kristalle sind nicht dispersiv (``lam_nm`` wird dann nicht gebraucht).""" + if not is_crystal(spec): + return eps_at(spec, lam_nm) * np.eye(3, dtype=complex) + kind = spec.get("kind") + if kind == "uniaxial": + e_o = complex(spec["n_o"], spec["k_o"]) ** 2 + e_e = complex(spec["n_e"], spec["k_e"]) ** 2 + t, p = np.radians(spec["theta_deg"]), np.radians(spec["phi_deg"]) + a = np.array([np.sin(t) * np.cos(p), np.sin(t) * np.sin(p), np.cos(t)]) + return e_o * np.eye(3, dtype=complex) + (e_e - e_o) * np.outer(a, a) + if kind == "biaxial": + e = [complex(n, k) ** 2 for n, k in zip(spec["n"], spec["k"])] + al, be, ga = np.radians(spec["euler_deg"]) + r = _rot_z(al) @ _rot_x(be) @ _rot_z(ga) + return r @ np.diag(e) @ r.T + if kind == "tensor": + m = np.array(spec["re"], dtype=float) + 1j * np.array(spec["im"], dtype=float) + if m.shape != (3, 3): + raise ValueError("Kristall: der Tensor braucht 3×3 Einträge") + if not np.allclose(m, m.T, atol=1e-12): + raise ValueError("Kristall: der Tensor muss symmetrisch sein (ε = εᵀ, keine gyrotropen Medien)") + return m + raise KeyError(f"unbekannte Kristallart '{kind}'") + + +def principal_values(spec, lam_nm: float) -> np.ndarray: + """Hauptwerte des Tensors (Eigenwerte), nach dem Realteil sortiert.""" + w = np.linalg.eigvals(tensor_at(spec, lam_nm)) + return w[np.argsort(w.real)] + + def eps_at(spec, lam_nm: float) -> complex: - """Komplexe relative Permittivität bei der Vakuumwellenlänge ``lam_nm`` [nm].""" + """Komplexe relative Permittivität bei der Vakuumwellenlänge ``lam_nm`` [nm]; für einen Kristall der Hauptwert mit dem größten + Realteil (für Netzweiten und Schätzungen, der Löser bekommt ``tensor_at``).""" lam = float(lam_nm) t = spec["type"] + if t == "crystal": + return complex(principal_values(spec, lam)[-1]) if t == "eps": return complex(spec["re"], spec["im"]) if t == "index": @@ -169,4 +231,12 @@ def describe(spec) -> str: return f"Drude (ε∞ = {spec['eps_inf']:g}, ħωp = {spec['omega_p_eV']:g} eV, ħγ = {spec['gamma_eV']:g} eV)" if t == "table": return f"Tabelle ({len(spec['rows'])} Zeilen)" + if t == "crystal": + kind = spec.get("kind") + if kind == "uniaxial": + return (f"einachsig (n_o = {spec['n_o']:g}, n_e = {spec['n_e']:g}, Achse θ = {spec['theta_deg']:g}°, " + f"φ = {spec['phi_deg']:g}°)") + if kind == "biaxial": + return f"zweiachsig (n = {', '.join(f'{v:g}' for v in spec['n'])}; Euler {', '.join(f'{v:g}°' for v in spec['euler_deg'])})" + return "Kristall (voller Tensor)" return t diff --git a/fem_gui/fem_post.py b/fem_gui/fem_post.py index b68eead..565b688 100644 --- a/fem_gui/fem_post.py +++ b/fem_gui/fem_post.py @@ -575,6 +575,99 @@ def jacobian_dataframe(pt): return df +def jones_orders(points): + """The order keys ("R0", "T-1", ...) with Jones matrices in any of the points, reflected first, then by m.""" + keys = {k for p in points if "error" not in p for k in (p.get("jones") or {})} + return sorted(keys, key=lambda k: (k[0] != "R", int(k[1:]))) + + +def jones_matrix(pt, key): + """The complex 2x2 Jones matrix of order ``key`` of one point (None if missing).""" + d = (pt.get("jones") or {}).get(key) + if not d: + return None + return np.array([[complex(re, im) for re, im in row] for row in d["J"]]) + + +def jones_dataframe(pt, key): + """Jones matrix of one order as a table: rows = outgoing channel (s, p or the substrate modes), columns = incident s, p; magnitude, + phase (°), real and imaginary part.""" + j = jones_matrix(pt, key) + if j is None: + return pd.DataFrame() + rows = pt["jones"][key].get("channels", ["s", "p"]) + out = [] + for r, name in enumerate(rows): + for c, inc in enumerate(("s", "p")): + v = j[r, c] + out.append({"Element": f"J_{name[0]}{inc}", "aus": name, "ein": inc, "|J|": abs(v), "Phase (°)": float(np.degrees(np.angle(v))), + "Re": v.real, "Im": v.imag, "|J|² (Effizienz)": abs(v) ** 2}) + return pd.DataFrame(out) + + +def mueller_dataframe(pt, key, normalised=True): + """Mueller matrix (Stokes I, Q, U, V) of one order; normalised by M00 (the efficiency for unpolarised light) if asked.""" + d = (pt.get("jones") or {}).get(key) + if not d: + return pd.DataFrame() + m = np.asarray(d["M"], dtype=float) + if normalised and abs(m[0, 0]) > 0: + m = m / m[0, 0] + df = pd.DataFrame(m, columns=["I", "Q", "U", "V"]) + df.insert(0, "aus \\ ein", ["I", "Q", "U", "V"]) + return df + + +def fig_mueller(points, mode, key): + """The 16 Mueller elements m_ij / m_00 of order ``key`` (m_00 itself as the efficiency): a 4x4 heat map for a single point, curves + along a sweep.""" + import matplotlib.pyplot as plt + + pts = [p for p in points if "error" not in p and (p.get("jones") or {}).get(key)] + if not pts: + fig, ax = plt.subplots(figsize=(7, 2.5)) + ax.text(0.5, 0.5, "keine Jones-Matrizen", ha="center") + ax.axis("off") + return fig + ms = np.array([np.asarray(p["jones"][key]["M"], dtype=float) for p in pts]) + norm = ms / np.where(np.abs(ms[:, :1, :1]) > 0, ms[:, :1, :1], 1.0) + norm[:, 0, 0] = ms[:, 0, 0] + labels = "IQUV" + if mode == "none" or len(pts) == 1: + fig, ax = plt.subplots(figsize=(5.2, 4.4)) + shown = norm[0].copy() + shown[0, 0] = 1.0 + im = ax.imshow(shown, cmap="RdBu_r", vmin=-1, vmax=1) + for i in range(4): + for j in range(4): + txt = f"{ms[0, 0, 0]:.4f}" if i == j == 0 else f"{norm[0, i, j]:+.3f}" + ax.text(j, i, txt, ha="center", va="center", fontsize=8) + ax.set_xticks(range(4), labels) + ax.set_yticks(range(4), labels) + ax.set_xlabel("einfallend") + ax.set_ylabel("ausfallend") + ax.set_title(f"Mueller-Matrix {key} (m_ij / m_00; m_00 = Effizienz unpolarisiert)", fontsize=9) + fig.colorbar(im, ax=ax, shrink=0.8) + fig.tight_layout() + return fig + xs = [p.get("value") if mode != "none" else p.get("index", 0) for p in pts] + fig, axs = plt.subplots(4, 4, figsize=(11, 8.5), sharex=True) + for i in range(4): + for j in range(4): + a = axs[i, j] + a.plot(xs, norm[:, i, j], "o-", ms=2.5, color="#1f77b4" if (i, j) != (0, 0) else "#d62728") + a.set_title("m_00 (Effizienz)" if i == j == 0 else f"m_{labels[i]}{labels[j]} / m_00", fontsize=8) + if (i, j) != (0, 0): + a.set_ylim(-1.05, 1.05) + a.grid(alpha=0.3) + a.tick_params(labelsize=7) + for a in axs[-1]: + a.set_xlabel(SWEEP_LABEL.get(mode, mode), fontsize=8) + fig.suptitle(f"Mueller-Matrix der Ordnung {key}", fontsize=10) + fig.tight_layout() + return fig + + def jacobian_sweep(points, mode): """{column label: (x values, dR/dp, dT/dp or None)} of the total R and T along the sweep.""" out = {} diff --git a/fem_gui/fem_run.py b/fem_gui/fem_run.py index 644a90f..e342e06 100644 --- a/fem_gui/fem_run.py +++ b/fem_gui/fem_run.py @@ -128,8 +128,10 @@ def run_check(py, repo, folder, threads=0, timeout=600): feats["grating"] = hasattr(g, "solve") feats["jacobian"] = hasattr(g, "jacobian") feats["resonances"] = hasattr(g, "resonances") + feats["jones"] = hasattr(g, "jones") except Exception: - feats["grating"] = feats["jacobian"] = feats["resonances"] = False + feats["grating"] = feats["jacobian"] = feats["resonances"] = feats["jones"] = False + feats["crystals"] = hasattr(hpfem, "AnisotropicStack") and hasattr(getattr(hpfem, "Material", None), "anisotropic") feats["dwr"] = hasattr(hpfem, "conical_dwr_estimate") feats["sample"] = hasattr(getattr(hpfem, "ConicalScattering", None), "sample") feats["h_field"] = hasattr(getattr(hpfem, "ConicalScattering", None), "h_field") diff --git a/fem_gui/fem_ui.py b/fem_gui/fem_ui.py index 710080c..1457e49 100644 --- a/fem_gui/fem_ui.py +++ b/fem_gui/fem_ui.py @@ -8,11 +8,17 @@ import fem_materials as fm -TYPE_LABELS = {"library": "Bibliothek (hpfem)", "index": "n + ik (konstant)", "eps": "ε (konstant)", "drude": "Drude-Metall", "table": "Tabelle λ, n, k"} +TYPE_LABELS = {"library": "Bibliothek (hpfem)", "index": "n + ik (konstant)", "eps": "ε (konstant)", "drude": "Drude-Metall", "table": "Tabelle λ, n, k", + "crystal": "Kristall (anisotrop)"} +CRYSTAL_LABELS = {"uniaxial": "einachsig (n_o, n_e, Achse)", "biaxial": "zweiachsig (nx, ny, nz, Euler-Winkel)", "tensor": "voller Tensor ε_ij"} +CRYSTAL_DEFAULT = {"uniaxial": {"type": "crystal", "kind": "uniaxial", "n_o": 1.658, "k_o": 0.0, "n_e": 1.486, "k_e": 0.0, "theta_deg": 45.0, "phi_deg": 0.0}, + "biaxial": {"type": "crystal", "kind": "biaxial", "n": [1.53, 1.54, 1.55], "k": [0.0, 0.0, 0.0], "euler_deg": [0.0, 0.0, 0.0]}, + "tensor": {"type": "crystal", "kind": "tensor", "re": [[2.25, 0.0, 0.0], [0.0, 2.25, 0.0], [0.0, 0.0, 2.25]], + "im": [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]}} LIB_CHOICES = ["Si", "Ag", "Au", "Al", "GaAs", "MAPbI3", "SiO2", "TiO2", "water", "air", "vacuum"] DEFAULT_SPEC = {"library": {"type": "library", "name": "SiO2"}, "index": {"type": "index", "n": 1.5, "k": 0.0}, "eps": {"type": "eps", "re": 2.25, "im": 0.0}, "drude": {"type": "drude", "eps_inf": 1.0, "omega_p_eV": 9.0, "gamma_eV": 0.07}, - "table": {"type": "table", "rows": [[400.0, 1.5, 0.0], [800.0, 1.5, 0.0]]}} + "table": {"type": "table", "rows": [[400.0, 1.5, 0.0], [800.0, 1.5, 0.0]]}, "crystal": CRYSTAL_DEFAULT["uniaxial"]} def table_show(obj): @@ -43,16 +49,65 @@ def unique_name(model, base): return n -def material_editor(model, ver, lam0, used, rename, changed, prefix=""): +def crystal_editor(spec, key, changed): + """Parameters of a crystal spec (fem_materials, type "crystal"): kind, principal indices and orientation in the laboratory frame.""" + kind = st.selectbox("Kristallart", list(CRYSTAL_LABELS), index=list(CRYSTAL_LABELS).index(spec.get("kind", "uniaxial")), format_func=CRYSTAL_LABELS.get, + key=f"{key}_kind", help="Laborsystem: x quer zu den Gitterlinien, y längs der Linien, z die Normale (nach oben). " + "Konstante Hauptindizes (keine Dispersion).") + if kind != spec.get("kind"): + spec.clear() + spec.update(copy.deepcopy(CRYSTAL_DEFAULT[kind])) + changed() + st.rerun() + if kind == "uniaxial": + c = st.columns(4) + spec["n_o"] = float(c[0].number_input("n_o (ordentlich)", value=float(spec["n_o"]), step=0.01, format="%.5g", key=f"{key}_no")) + spec["k_o"] = float(c[1].number_input("k_o", value=float(spec["k_o"]), min_value=0.0, step=0.01, format="%.5g", key=f"{key}_ko")) + spec["n_e"] = float(c[2].number_input("n_e (außerordentlich)", value=float(spec["n_e"]), step=0.01, format="%.5g", key=f"{key}_ne")) + spec["k_e"] = float(c[3].number_input("k_e", value=float(spec["k_e"]), min_value=0.0, step=0.01, format="%.5g", key=f"{key}_ke")) + c = st.columns(2) + spec["theta_deg"] = float(c[0].number_input("Achse θ (°, gegen die Normale z)", value=float(spec["theta_deg"]), min_value=0.0, max_value=180.0, + step=5.0, key=f"{key}_th", help="θ = 0: c-Schnitt (Achse senkrecht zur Oberfläche).")) + spec["phi_deg"] = float(c[1].number_input("Achse φ (°, gegen x quer zu den Linien)", value=float(spec["phi_deg"]), step=5.0, key=f"{key}_ph", + help="Azimut der Achse in der Ebene: φ = 90° legt sie längs der Linien.")) + elif kind == "biaxial": + c = st.columns(3) + for i, ax in enumerate("123"): + spec["n"][i] = float(c[i].number_input(f"n{ax}", value=float(spec["n"][i]), step=0.01, format="%.5g", key=f"{key}_n{ax}")) + spec["k"][i] = float(c[i].number_input(f"k{ax}", value=float(spec["k"][i]), min_value=0.0, step=0.01, format="%.5g", key=f"{key}_k{ax}")) + c = st.columns(3) + for i, lab in enumerate(("α (°, um z)", "β (°, um x')", "γ (°, um z'')")): + spec["euler_deg"][i] = float(c[i].number_input(lab, value=float(spec["euler_deg"][i]), step=5.0, key=f"{key}_eu{i}")) + st.caption("Hauptachsen 1, 2, 3 zunächst längs x, y, z; dann gedreht mit R = R_z(α) R_x(β) R_z(γ): ε = R diag(ε1, ε2, ε3) Rᵀ.") + else: + st.caption("Symmetrischer Tensor ε_ij (Real- und Imaginärteil, Verlust: positiv semidefiniter Imaginärteil). Eingabe des oberen Dreiecks; " + "das untere wird gespiegelt.") + for part, lab in (("re", "Re"), ("im", "Im")): + c = st.columns(6) + for k, (i, j) in enumerate(((0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2))): + v = float(c[k].number_input(f"{lab} ε_{'xyz'[i]}{'xyz'[j]}", value=float(spec[part][i][j]), step=0.1, format="%.5g", + key=f"{key}_{part}{i}{j}")) + spec[part][i][j] = spec[part][j][i] = v + try: + w = fm.principal_values(spec, 500.0) + n = [complex(v) ** 0.5 for v in w] + st.caption("Hauptindizes: " + ", ".join(f"{v.real:.4f}" + (f" + {v.imag:.4f} i" if abs(v.imag) > 1e-12 else "") for v in n)) + except Exception as exc: + st.error(str(exc)) + + +def material_editor(model, ver, lam0, used, rename, changed, prefix="", crystals=False): """Editor of model["materials"]: one expander per material (name, type, parameters, n and k at lam0, rename, delete) and the buttons to add a library or an own material. rename(model, old, new) renames everywhere; changed() is called before every st.rerun (bumps the widget - version).""" + version). crystals: offer the anisotropic type (only the periodic mode with hpfem.grating supports it).""" + types = [t for t in TYPE_LABELS if crystals or t != "crystal"] for name in list(model["materials"]): spec = model["materials"][name] with st.expander(f"{name}: {fm.describe(spec)}"): c1, c2 = st.columns(2) newname = c1.text_input("Name", value=name, key=f"{prefix}mn_{ver}_{name}") - typ = c2.selectbox("Typ", list(TYPE_LABELS), index=list(TYPE_LABELS).index(spec["type"]), format_func=TYPE_LABELS.get, + opts = types if spec["type"] in types else types + [spec["type"]] + typ = c2.selectbox("Typ", opts, index=opts.index(spec["type"]), format_func=TYPE_LABELS.get, key=f"{prefix}mt_{ver}_{name}") if typ != spec["type"]: model["materials"][name] = copy.deepcopy(DEFAULT_SPEC[typ]) @@ -81,6 +136,8 @@ def material_editor(model, ver, lam0, used, rename, changed, prefix=""): key=f"{prefix}md_p_{ver}_{name}")) spec["gamma_eV"] = float(c3.number_input("ħγ (eV)", value=float(spec["gamma_eV"]), min_value=0.0, step=0.01, format="%.5g", key=f"{prefix}md_g_{ver}_{name}")) + elif typ == "crystal": + crystal_editor(spec, f"{prefix}mc_{ver}_{name}", changed) else: txt = st.text_area("Zeilen: Wellenlänge (nm), n, k", value="\n".join(f"{a:g}, {b:g}, {c:g}" for a, b, c in spec["rows"]), key=f"{prefix}mtab_{ver}_{name}", height=120, help="Linear interpoliert, keine Extrapolation.") @@ -92,11 +149,12 @@ def material_editor(model, ver, lam0, used, rename, changed, prefix=""): st.error("Mindestens zwei Zeilen mit je drei Zahlen.") except ValueError: st.error("Zahlen nicht lesbar.") - try: - n_, k_ = fm.nk(spec, lam0) - st.caption(f"bei {lam0:g} nm: n = {n_:.4f}, k = {k_:.4f}, ε = {fm.eps_at(spec, lam0).real:.4f} {fm.eps_at(spec, lam0).imag:+.4f} i") - except Exception as exc: - st.caption(f"bei {lam0:g} nm: {exc}") + if not fm.is_crystal(spec): # a crystal shows its principal indices in crystal_editor + try: + n_, k_ = fm.nk(spec, lam0) + st.caption(f"bei {lam0:g} nm: n = {n_:.4f}, k = {k_:.4f}, ε = {fm.eps_at(spec, lam0).real:.4f} {fm.eps_at(spec, lam0).imag:+.4f} i") + except Exception as exc: + st.caption(f"bei {lam0:g} nm: {exc}") b1, b2 = st.columns(2) if newname != name and newname.strip(): if newname in model["materials"]: diff --git a/fem_gui/fem_worker.py b/fem_gui/fem_worker.py index e0bc99f..135ff1f 100644 --- a/fem_gui/fem_worker.py +++ b/fem_gui/fem_worker.py @@ -154,14 +154,27 @@ def prepare(case, lam_nm): lam = lam_nm * 1e-9 k0 = 2 * np.pi / lam eps = {n: fm.eps_at(model["materials"][n], lam_nm) for n in case.names} - mat = {n: h.Material(complex(e)) for n, e in eps.items()} + crystals = [n for n in case.names if fm.is_crystal(model["materials"][n])] + if crystals: + # anisotropic materials (hp-FEM M19): tensors in the laboratory frame, only through hpfem.grating (solve / jones) + if case.job["solver"].get("engine") != "grating": + raise ValueError(f"Kristalle ({', '.join(crystals)}) rechnet nur der Löser hpfem.grating") + if not (hasattr(h, "AnisotropicStack") and hasattr(h.Material, "anisotropic")): + raise ValueError("Kristalle brauchen hp-FEM mit anisotropen Materialien (M19, AnisotropicStack)") + if model["cover"] in crystals: + raise ValueError("Das Einfallsmedium muss isotrop sein") + mat = {n: (h.Material.anisotropic(fm.tensor_at(model["materials"][n], lam_nm)) if n in crystals else h.Material(complex(e))) + for n, e in eps.items()} e_cover, e_sub = eps[model["cover"]], eps[model["substrate"]] if abs(e_cover.imag) > 1e-9 or e_cover.real < 1: raise ValueError("Einfallsmedium nicht verlustfrei") layers = [h.Layer(mat[l["material"]], case.interfaces[i] - case.interfaces[i + 1]) for i, l in enumerate(model["layers"])] - stack = h.LayerStack2D(mat[model["cover"]], layers, mat[model["substrate"]], case.interfaces[0]) + in_stack = [model["cover"], model["substrate"]] + [l["material"] for l in model["layers"]] + make = h.AnisotropicStack if any(n in crystals for n in in_stack) else h.LayerStack2D # crystal layers / substrate: the 4x4 stack + stack = make(mat[model["cover"]], layers, mat[model["substrate"]], case.interfaces[0]) + lossless_sub = float(np.abs(fm.tensor_at(model["materials"][model["substrate"]], lam_nm).imag).max()) < 1e-9 return SimpleNamespace(lam_nm=lam_nm, k0=k0, omega=k0 * h.constants.c0, eps=eps, mat=mat, stack=stack, e_sub=e_sub, - n_cover=float(np.sqrt(e_cover).real), n_sub=np.sqrt(e_sub + 0j), lossless_sub=abs(e_sub.imag) < 1e-9) + n_cover=float(np.sqrt(e_cover).real), n_sub=np.sqrt(e_sub + 0j), lossless_sub=lossless_sub, crystals=crystals) def design_pml(case, ctx, theta, kx0, beta, solver): @@ -553,8 +566,15 @@ def __init__(self, case, ctx, theta, phi, pol, order, solver, mesh=None, keep=Fa kwargs["extra_quadrature_order"] = int(solver["extra_quadrature_order"]) t0 = time.time() Control.last_phase = None - self.result = r = grating.solve(self.mesh, materials, ctx.stack, "s" if pol == "TE" else "p", np.radians(theta), np.radians(phi), ctx.omega, - **opts, **kwargs) + self.jones = None + if solver.get("jones") and hasattr(grating, "jones"): + # Jones / Mueller matrices (hp-FEM M19): the solves for s and p; the point's own polarisation is one of them + kwargs.pop("scalar") + self.jones = grating.jones(self.mesh, materials, ctx.stack, np.radians(theta), np.radians(phi), ctx.omega, scalar=scalar, **opts, **kwargs) + self.result = r = self.jones.s if pol == "TE" else self.jones.p + else: + self.result = r = grating.solve(self.mesh, materials, ctx.stack, "s" if pol == "TE" else "p", np.radians(theta), np.radians(phi), ctx.omega, + **opts, **kwargs) self.t_solve = time.time() - t0 self.h, self.case, self.ctx = h, case, ctx self.problem, self.solution, self.wave = r.problem, r.solution, r.wave @@ -592,9 +612,22 @@ def extra(self): a = np.asarray(o.amplitude, dtype=complex) amps[f"{side}{int(o.m)}"] = [[float(c.real), float(c.imag)] for c in a] out["amplitudes"] = amps + if self.jones is not None: + out["jones"] = jones_data(self.jones) return out +def jones_data(jr): + """Jones (2x2 complex, as [re, im] pairs) and Mueller (4x4) matrix of every propagating order of an hpfem.grating.jones result, keyed + "R0", "T-1", ...; columns: incident s, p; rows: outgoing s, p or the two mode channels of a crystal substrate.""" + out = {} + for o in list(jr.R_orders) + list(jr.T_orders): + j = np.asarray(o.jones, dtype=complex) + out[f"{o.side}{int(o.m)}"] = dict(J=[[[float(v.real), float(v.imag)] for v in row] for row in j], + M=np.asarray(o.mueller, dtype=float).tolist(), channels=[str(c) for c in o.channels]) + return out + + JAC_UNITS = {"wavelength": ("λ", 1e-9, "1/nm"), "theta": ("θ", np.pi / 180, "1/°"), "phi": ("φ", np.pi / 180, "1/°")} diff --git a/tests/test_crystals.py b/tests/test_crystals.py new file mode 100644 index 0000000..f59663d --- /dev/null +++ b/tests/test_crystals.py @@ -0,0 +1,100 @@ +"""Crystal materials (hp-FEM M19) and the Jones / Mueller display: pure Python, no hpfem.""" +import matplotlib + +matplotlib.use("Agg") + +import numpy as np +import pytest + +import fem_materials as fm +import fem_post as fp +import fem_worker as fw + +UNIAXIAL = {"type": "crystal", "kind": "uniaxial", "n_o": 1.5, "k_o": 0.0, "n_e": 2.0, "k_e": 0.1, "theta_deg": 90.0, "phi_deg": 90.0} + + +def test_uniaxial_axis_and_principal_values(): + t = fm.tensor_at(UNIAXIAL, 600) + # axis theta = 90°, phi = 90°: along y (the lines) + assert t == pytest.approx(np.diag([2.25, complex(2.0, 0.1) ** 2, 2.25])) + w = fm.principal_values(UNIAXIAL, 600) + assert w[-1] == pytest.approx(complex(2.0, 0.1) ** 2) + assert fm.eps_at(UNIAXIAL, 600) == pytest.approx(complex(2.0, 0.1) ** 2) # the largest, for mesh sizes + assert fm.nk(UNIAXIAL, 600) == pytest.approx((2.0, 0.1)) + assert fm.is_crystal(UNIAXIAL) and not fm.is_crystal({"type": "index", "n": 1.5, "k": 0.0}) + + +def test_tilted_axis_is_symmetric_with_off_diagonals(): + spec = dict(UNIAXIAL, theta_deg=30.0, phi_deg=20.0) + t = fm.tensor_at(spec, 600) + assert np.allclose(t, t.T) + assert abs(t[0, 2]) > 0.1 and abs(t[1, 2]) > 0.01 + a = np.array([np.sin(np.radians(30)) * np.cos(np.radians(20)), np.sin(np.radians(30)) * np.sin(np.radians(20)), np.cos(np.radians(30))]) + assert t @ a == pytest.approx(complex(2.0, 0.1) ** 2 * a) # the axis is the extraordinary eigenvector + + +def test_biaxial_euler_rotation(): + spec = {"type": "crystal", "kind": "biaxial", "n": [1.5, 1.6, 1.7], "k": [0.0, 0.0, 0.0], "euler_deg": [0.0, 0.0, 0.0]} + assert fm.tensor_at(spec, 500) == pytest.approx(np.diag([2.25, 2.56, 2.89])) + spec["euler_deg"] = [90.0, 0.0, 0.0] # principal axis 1 turned from x to y + assert fm.tensor_at(spec, 500) == pytest.approx(np.diag([2.56, 2.25, 2.89])) + spec["euler_deg"] = [10.0, 35.0, -20.0] + t = fm.tensor_at(spec, 500) + assert np.allclose(t, t.T) and np.sort(np.linalg.eigvalsh(t.real)) == pytest.approx([2.25, 2.56, 2.89]) + + +def test_full_tensor_must_be_symmetric(): + spec = {"type": "crystal", "kind": "tensor", "re": [[2.0, 0.1, 0.0], [0.1, 2.5, 0.0], [0.0, 0.0, 3.0]], "im": [[0.0] * 3] * 3} + assert fm.tensor_at(spec, 500)[0, 1] == pytest.approx(0.1) + spec["re"] = [[2.0, 0.1, 0.0], [0.0, 2.5, 0.0], [0.0, 0.0, 3.0]] + with pytest.raises(ValueError): + fm.tensor_at(spec, 500) + + +def test_isotropic_tensor_and_describe(): + assert fm.tensor_at({"type": "index", "n": 1.5, "k": 0.0}, 500) == pytest.approx(2.25 * np.eye(3)) + assert fm.CRYSTAL_KINDS == ("uniaxial", "biaxial", "tensor") + assert "einachsig" in fm.describe(UNIAXIAL) + + +class _Order: + def __init__(self, m, side, j, channels=("s", "p")): + self.m, self.side, self.jones, self.channels = m, side, np.asarray(j, dtype=complex), channels + a = np.array([[1, 0, 0, 1], [1, 0, 0, -1], [0, 1, 1, 0], [0, 1j, -1j, 0]]) + self.mueller = (a @ np.kron(self.jones, self.jones.conj()) @ np.linalg.inv(a)).real + + +class _JonesResult: + def __init__(self): + self.R_orders = [_Order(0, "R", [[0.3, 0.05j], [-0.05j, -0.2]]), _Order(-1, "R", [[0.1, 0.0], [0.0, 0.1]])] + self.T_orders = [_Order(0, "T", [[0.8, 0.1], [0.05, 0.7]], ("ordinary", "extraordinary"))] + + +def test_jones_data_round_trip_and_tables(): + data = fw.jones_data(_JonesResult()) + assert set(data) == {"R0", "R-1", "T0"} + pt = {"index": 0, "value": 600.0, "jones": data} + j = fp.jones_matrix(pt, "R0") + assert j == pytest.approx(np.array([[0.3, 0.05j], [-0.05j, -0.2]])) + assert fp.jones_orders([pt]) == ["R-1", "R0", "T0"] + df = fp.jones_dataframe(pt, "T0") + assert list(df["aus"]) == ["ordinary", "ordinary", "extraordinary", "extraordinary"] + # power normalisation: the column sum of |J|^2 is the efficiency for that incident polarisation, M00 the unpolarised mean + eff_s = df[df["ein"] == "s"]["|J|² (Effizienz)"].sum() + assert eff_s == pytest.approx(0.8**2 + 0.05**2) + m = np.asarray(data["T0"]["M"]) + assert m[0, 0] == pytest.approx(0.5 * np.sum(np.abs(np.array([[0.8, 0.1], [0.05, 0.7]])) ** 2)) + mdf = fp.mueller_dataframe(pt, "R0") + assert mdf.iloc[0, 1] == pytest.approx(1.0) + assert fp.jones_dataframe({"index": 1}, "R0").empty + + +def test_mueller_figures_single_point_and_sweep(): + data = fw.jones_data(_JonesResult()) + pts = [{"index": i, "value": 500.0 + 10 * i, "jones": data} for i in range(3)] + fig = fp.fig_mueller(pts[:1], "none", "R0") + assert fig is not None + fig = fp.fig_mueller(pts, "wavelength", "R0") + assert len(fig.axes) == 16 + fig = fp.fig_mueller([{"index": 0, "error": "x"}], "wavelength", "R0") + assert fig is not None