diff --git a/CHANGELOG.md b/CHANGELOG.md index a08ba13..82f4e41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unveröffentlicht +* Neu: **Wärme und Mechanik in 3D** (Modus „Wärme und Mechanik“, Schalter „Raumdimension“ 2D/3D; hpfem 0.5, `Scattering3D`, `Thermal3D`, `ThermoOptical3D`, `Elasticity3D`). + Fall **Kugel**: ebene Welle (E längs x, Ausbreitung +z) auf eine Kugel in verlustfreier Matrix (`box_with_ball`, PML) → absorbierte Leistung → Temperatur (Wärmesenke T = T_ref an den + Außenflächen der Box) → optional selbstkonsistent mit ε(T) (`ThermoOptical3D`, Relaxation, Toleranz, Konvergenzverlauf) → optional Wärmespannung (`Elasticity3D`, Wärmeausdehnung je + Material, Schrumpfung der Kugel, Außenflächen eingespannt oder frei); wählbar das **Viertelmodell** (x > 0, y > 0, Leistung und Energie ×4, Felder gespiegelt). Fall **Quader**: Randbedingungen je + Fläche (frei, eingespannt, Symmetrie, Zug/Druck), Temperaturänderung und Schrumpfung linear in z (damit auch das Schrumpfblock-Beispiel R7 der Bibliothek, Viertelmodell mit Substrat) oder eine + gleichmäßige **Wärmequelle** (mW/µm³) mit Wärmesenken auf gewählten Flächen (`Thermal3D`, Rest adiabatisch), deren Temperaturfeld die Wärmedehnung treibt. Ergebnis: Kennzahlen, Schnitte + senkrecht zu x, y oder z für T, |E|/E₀, u, σ-Komponenten und Von Mises, Linienschnitte, verformtes Raster eines Schnitts mit Überhöhung, Konvergenz. **Vor jedem Lauf** zeigt die App Zellen, + Unbekannte, Speicher (`hpfem.estimate_memory`) und Zeit; der Worker bricht ab, wenn die Schätzung die einstellbare Speichergrenze (Vorgabe 8 GB) überschreitet. Eingebaute Prüfungen + (gemessen): Quader mit Symmetrieebenen unter Zug, gleichmäßiger Temperatur und Schrumpfung gegen die geschlossene Lösung (exakt in 3D, relative Abweichung < 1e-12); Wärmequelle zwischen + zwei Senken gegen T_ref + qW²/(8κ) (< 1e-12); Kugel gegen ΔT ≈ P/(4πκ)(1/R − 1/R_s) mit der Kapazität des Würfels als R_s (Vorlage n = 1, p = 2, 1500 Zellen: 30,8 K gegen 32,0 K, −3,7 %). + Gemessene Kosten (hpfemenv, SparseLU, ein Thread): Kugel-Vorlage 14 s Optik und Wärme, 6 s Mechanik, 10 790 optische Unbekannte; selbstkonsistent mit 5 Iterationen 65 s; Elastizität am + Quader 2 187 Unbekannte 2 s, 6 591 10 s, 14 739 48 s (590 MB), p = 3 mit 12 288 Unbekannten 60 s (800 MB) – daraus die Faustformel der App (für die Kugel zu hoch, etwa Faktor 3). + Grenzen: die Temperatur gilt für das gewählte Gebiet (Senke an der Box); Standardnetz grob (die Bibliothek warnt vor unteraufgelöster PML); stationär, keine temperaturabhängigen Materialdaten + außer ε(T), Optik auf dem unverformten Netz; Maxima sind Rasterwerte; Kette nicht gegen Literaturwerte für konkrete Partikel validiert; `absorbed_power_by_tag` und Lastbilanz weichen bei grobem + Netz um etwa 2e-3 voneinander ab; die Kugelschrumpfung wird an Quadraturpunkten ausgewertet. Neue Module `fem_thermo3d.py`, `fem_thermo3d_app.py`, `fem_thermo3d_worker.py`, Tests + `tests/test_thermo3d.py`; Eingriff in `fem_thermo_app.py` (Schalter 2D/3D), `fem_app.py` (Dateiliste, Modusname), `fem_run.py` (`feats["thermo3d"]`). * Neu: Modus **„Wärme und Mechanik (2D)“** (Seitenleiste; hpfem 0.5, `Thermal2D`, `ThermoOptical2D`, `Elasticity2D`). Fall **Nanodraht**: ebene Welle auf einen Draht in verlustfreier Matrix (`square_with_disc`, PML) → absorbierte Leistung → Temperatur (Wärmesenke T = T_ref am äußeren Rand; Leitfähigkeit je Material) → optional selbstkonsistent mit ε(T) = ε + (dε/dT)(T − T_ref) (`ThermoOptical2D`, Relaxation, Toleranz, Konvergenzverlauf) → optional Wärmespannung in ebener @@ -25,8 +41,29 @@ n = 1, p = 2: 2 526 Unbekannte, 2 s, +5 %; n = 2, p = 3 braucht 5,5 GB und über 2 min. Resonanzen ε = 12, n = 1, p = 2: 9 324 Unbekannte, 72 s (λ ≈ 715 nm, Q ≈ 12,6, nicht validiert). Bandstruktur: das leere Gitter trifft bei X die exakten Werte (0,5 ×4, 1,118), aber ein k-Punkt kostet schon bei 2 936 Unbekannten 17 bis 75 s; die Bibliothek meldet bei den Gittern ihrer Generatoren, dass gegenüberliegende Facetten weder gleich noch geschachtelt seien (Hinweis im Protokoll, die Rechnung ist trotzdem richtig). - Nicht dabei: Substrate und Schichtstapel in 3D, Ports in 3D, hp-adaptive Verfeinerung, Gmsh-Netze, 3D-Wärme und -Mechanik. + Nicht dabei: 3D-Wärme und -Mechanik. +* Neu: **3D-Strukturen erweitert** (hp-FEM 0.5): (1) **Substrat und Schichtstapel** (Streuung, Gmsh-Geometrie): `LayerStack3D` als geschichteter Hintergrund der Streufeld-Formulierung (`ScatteringSetup3D.background`), + ebene Welle unter beliebigem Einfallswinkel, s oder p, Azimut (`LayeredPlaneWave3D.field`), R, T, A des Stapels ohne Objekt, Objekt (Kugel, Zylinder, Quader) mit Abstand über der Oberkante z = 0. + (2) **Gmsh-Netze**: eigene Geometrie (neues Modul `fem_threed_gmsh.py`: Box, jede Schicht ein Volumen, Objekt, Elemente zweiter Ordnung, Maschenfelder am Objekt und je Schicht; physikalische Gruppen für Volumina und + die sechs Boxseiten) oder hochgeladene `.msh`-Datei mit Tabelle Zellmarke → Material, Wahl der Streukörper-Marken, Flächenmarken ohne Eintrag werden zu den Boxseiten (Worker-Aufruf `inspect` meldet die Marken). + (3) **hp-adaptive Verfeinerung der Streuung**: `AdaptiveMesh3D` + `Scattering3D.estimate` + `dorfler_marking` + `hp_decide_by_prediction` + `hp_refine` + `predict_indicators`, Abbruch bei Schrittzahl, Obergrenze + Unbekannte, Speichergrenze oder η/η₀; Konvergenzdiagramm (η, Q_sca gegen Unbekannte), Schritttabelle, Netz gefärbt nach Ordnung. (4) Neue Aufgabe **Wellenleiter und Ports (S-Parameter)** + (`fem_ports3d.py`, `fem_ports3d_app.py`, `fem_ports3d_worker.py`): Streifenwellenleiter und Richtkoppler zwischen modalen Ports (`s_parameters`, `WaveguidePort`; Stirnflächen z = 0 und z = L, PEC-Seitenwände), + Netze als Tensorgitter mit Gitterlinien auf den Kernkanten (`hpfem.box` auf Indexkoordinaten, dann Knoten verschoben; `hpfem.box` selbst ist gleichmäßig), S-Matrix, R, T, Verlust, n_eff der Portmoden, |E|² im Längs- und Querschnitt, + Referenzen aus dem 2D-Modenlöser (β der Grundmode bzw. Supermoden; Theorie gekoppelter Moden) auf demselben und auf einem feineren Netz (halbe Zelle, p + 2); oder ein Gmsh-Netz mit Flächenmarken als PEC-Wand oder Port. + Neue Tests `tests/test_threed_ext.py` (9) und `tests/test_ports3d.py` (11). + **Gemessen (Wheel 0.5.0, SparseLU):** Gmsh-Kugel n = 2, ka = 1, p = 2, hw = 200 nm, PML 300 nm = 2 ferne Zellen (150 nm), 18 000 Unbekannte, 82 s: Q_sca = 0,7948 gegen 0,7969 (Mie, −0,3 %), Q_abs = −0,002; + mit nur einer Zelle im PML (250 nm) 0,60 (−24 %), mit 1,6 Zellen 0,17: das PML braucht mindestens zwei bis drei Zellen. Derselbe Fall mit einem „Stapel“ aus Luft (Einfallsmedium = Substrat = Luft): Q_sca = 0,811 (+1,7 % gegen Mie, + 20 856 Unbekannte, 127 s); die Datei desselben Netzes liefert dieselben σ (1e-6). Stapel Luft/Glas bei 30°, p: R = 0,02525 stimmt mit der Fresnel-Formel überein. Silizium-Zylinder auf Glas (grobes Netz, 3 800 Unbekannte, 2,6 s): + Q_sca = 6,05 bei p = 1 gegen 8,67 bei p = 2 (19 500 Unbekannte, 127 s): p = 1 ist hier nicht konvergiert. Gold-Kugel auf Schicht (Vorlage, p = 1, 14 000 Unbekannte, 18 s): nur ein Mechanik-Test, die Zahlen sind nicht konvergiert (feineres Netz: Q_sca 0,35 statt 1,10). + hp-adaptiv (Kugel n = 2, ka = 2, Viertelmodell, n = 1, p = 2, 4 bis 5 Schritte, 16 s): η fällt von 0,133 auf 0,042 (2 526 → 10 638 Unbekannte), Q_sca 4,51 → 4,44 (Mie 4,77), nicht monoton; Q_abs ≈ −0,49 (PML unteraufgelöst, die Bibliothek warnt): + der residuale Schätzer sieht den PML-Fehler nur teilweise. Streifen Si/SiO₂ 450 × 220 nm, λ = 1550 nm: n_eff der Portmode 2,136 bei p = 1 und 150-nm-Zellen, 2,343 bei p = 2, 2,356 bei p = 3 (2D, 150 nm): bei p = 1 9 % zu klein; 3D mit p = 1: T = 0,995, R = 0,005 + (8 s, 5 000 Unbekannte), mit p = 2 und 150 × 400 nm Zellen 10 000 Unbekannte, 198 s. Richtkoppler (Lücke 200 nm, L = 1 µm, p = 1, 150-nm-Zellen, Supermoden-Ports): cross = 0,038, Kopplungslänge 10,3 µm auf dem Netz der Rechnung gegen 24,6 µm auf dem feinen + Referenznetz (cross_Ref = 0,004): das grobe Netz koppelt viel zu stark, cross ist bei kurzen Kopplern empfindlich auf den Phasenfehler (0,12 bis 0,20 rad). Ein Gmsh-Streifen (ungeordnetes Netz, p = 1) liefert n_eff = 2,27. + **Grenzen:** das PML ist für den Index 1 ausgelegt (Substrat und Schichten höher: Richtwerte); der Querschnitt aus dem Fluss um das Objekt ist an verlustbehafteten, berührenden Schichten nicht eindeutig; Objekte, die eine Grenzfläche schneiden, gibt es nicht; + ein Stapel geht nur mit Gmsh-Geometrie; Q der Datei beruht auf der Projektion der Oberfläche mit geraden Facetten; 3D-Wellenleiter sind mit p = 1 nicht konvergiert und mit p ≥ 2 teuer; keine Ringresonator-Vorlage (große Netze, `ring_mesh.py` der Bibliothek erzeugt die Datei); + Resonanzen (auch mit Gmsh-Netzen) und 3D-Bänder bleiben nicht gegen analytische Lösungen validiert; kein Export; keine 3D-Wärme und -Mechanik. * Neu: Modus **„Zeitbereich: Pulse, Sonden, Spektren“** (Seitenleiste; hpfem 0.5, `TimeDomain2D` und `TimeDomain3D`, Newmark-β, implizit): 2D-Schnitt (Rechteck mit den Formen des Wellenleiter-Modus, E in der Ebene, je Meter in z) oder 3D-Kasten mit Kugel (`box_with_ball`, sehr grobes Netz, Grenze 30 000 Freiheitsgrade). Quelle: Gauß- förmige Stromdichte mit Position, Größe und Polarisation; Zeitsignal modulierter Gauß-Puls (`modulated_gaussian`), Gauß-Puls (`gaussian_pulse`) oder Dauerstrich mit diff --git a/README.md b/README.md index fc73681..c618efb 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,9 @@ Es sind keine BEM- oder RCWA-Daten nötig. * **Emitter (neu, hp-FEM 0.5):** (1) **in der Gitterzelle** (Aufgabe „Emitter“): Gauß-Dipol mit Array-Scan (Purcell-Faktor je Orientierung, Anteile, Sammelaperturen, Bloch-Array, Abstrahlmuster), mit Kostenschätzung vorab; (2) **Rotationskörper außerhalb der Achse**: Abstände ρ, alle Azimutordnungen, Purcell-Tensor und Detektoranteile. * **Zeitbereich (neu, hp-FEM 0.5):** Pulse und Dauerstrich einer Stromquelle in einer 2D-Struktur (oder einem 3D-Kasten mit Kugel) mit PEC-, absorbierenden und PMC-Rändern: Feldfilm, Sonden E(t), Spektren per FFT, Energie über der Zeit (`TimeDomain2D/3D`, Newmark-β). * **Bandstruktur (neu, hp-FEM 0.5):** Bänder, Bandlücken und Modenfelder eines 2D-photonischen Kristalls (quadratisches oder hexagonales Gitter, Floquet-Bloch, Polarisation mit E in der Ebene) entlang Γ–X–M–Γ bzw. Γ–M–K–Γ, mit dem leeren Gitter als Referenz. -* **Wärme und Mechanik (neu, hp-FEM 0.5):** absorbierte Leistung eines Nanodrahts → Temperatur (auch selbstkonsistent mit ε(T)) → Wärmespannung (ebene Dehnung), dazu Block und rotationssymmetrischer Zylinder mit Randbedingungen je Seite, Temperaturänderung und Schrumpfung; Prüfung gegen geschlossene Lösungen und die Linienquelle. +* **Wärme und Mechanik (neu, hp-FEM 0.5):** absorbierte Leistung eines Nanodrahts → Temperatur (auch selbstkonsistent mit ε(T)) → Wärmespannung (ebene Dehnung), dazu Block und rotationssymmetrischer Zylinder mit Randbedingungen je Seite, Temperaturänderung und Schrumpfung; Prüfung gegen geschlossene Lösungen und die Linienquelle. **3D:** Kugel (Optik → Wärme → Spannung, auch selbstkonsistent, Viertelmodell) und Quader (Wärmequelle mit Senken, Mechanik je Fläche) mit Speicherschätzung vor jedem Lauf; Prüfung gegen geschlossene Lösungen. * **3D-Strukturen (neu, hp-FEM 0.5):** Streuung an Kugel oder Würfel (Wirkungsquerschnitte mit Mie-Referenz, Feldschnitte), Resonanzen (Q) und die Bandstruktur eines kubischen Kristalls mit den 3D-Lösern; mit Speicherschätzung vor jedem Lauf (3D ist speicherintensiv, nur der direkte Löser SparseLU im Wheel, Minuten bei feinen Netzen). Resonanzen und Bänder sind in der Oberfläche nicht gegen analytische Lösungen validiert. +* **3D-Strukturen erweitert (neu):** Schichtstapel und Substrat unter dem Objekt (schräger Einfall, s und p, R/T/A), Gmsh-Geometrien (Kugel, Zylinder, Quader) und eigene `.msh`-Dateien mit Tabelle Zellmarke → Material, hp-adaptive Verfeinerung der Streuung (Konvergenzdiagramm), Wellenleiter und Ports in 3D (Streifen, Richtkoppler, eigene Gmsh-Netze: S-Matrix, Referenz aus dem 2D-Modenlöser). 3D bleibt teuer; die Vorlagen sind klein und teils nicht konvergiert (siehe Info im Modus). * **Wellenleiter und Ports (neu, hp-FEM 0.5):** Bauteile in der Chipebene zwischen modalen Ports (Streifen, Stufen, Ringe, Polygone): leistungsnormierte S-Matrix, Transmission, Reflexion, Verlust, Portmoden und Feld einer Anregung; dazu die Moden des Querschnitts (effektive Indizes, Felder E_t und E_z). * **Ergebnisse:** Spektren, Beugungsordnungen (R, T, A), Feldkarten (exakt auf den Elementen) für E, H und den Poynting-Vektor, Schnitte, Absorption je Material, Energie- und Flussbilanz, Zeit je Phase, Ableitungen, Resonanzen/Bänder mit Modenfeldern, hp-Adaptivität, CSV-Export. diff --git a/docs/ANLEITUNG.md b/docs/ANLEITUNG.md index 767dfc1..0ccd422 100644 --- a/docs/ANLEITUNG.md +++ b/docs/ANLEITUNG.md @@ -240,6 +240,36 @@ Grenzen: Der Wheel hat nur den direkten Löser SparseLU (ein Thread); 18 000 Unb des Lösers, das PML sei unteraufgelöst, erscheint bei diesen groben Netzen im Protokoll (so auch in der Validierung der Bibliothek). Resonanzen frieren das Material bei der Zielwellenlänge ein und sind, wie die Bandstruktur, nicht gegen analytische Lösungen validiert; ein k-Punkt der Bandstruktur dauert schon bei sehr kleinen Netzen Sekunden bis eine Minute. +### 3D-Strukturen: Schichtstapel, Gmsh-Netze, hp-Adaptivität, Wellenleiter + +**Netz** (Reiter 1, Streuung und Resonanzen): *Bibliotheksnetz* (wie oben), *Gmsh-Geometrie* (Kugel, Zylinder mit Achse z oder Quader in einer Box mit PML-Rand) oder *Eigene Gmsh-Datei*. +Bei der Gmsh-Geometrie stehen in Reiter 2 Innenraum (halbe Breite), PML-Dicke, Abstand nach oben, Zelle am Objekt, Zelle fern, Übergangslänge und Geometrieordnung; „Maschenweiten vorschlagen“ +setzt Richtwerte aus der kürzesten Wellenlänge. **Das PML braucht mindestens zwei bis drei ferne Zellen Dicke** (gemessen: Kugel n = 2, ka = 1, p = 2: PML = 2 Zellen: Q_sca 0,3 % neben der Mie-Reihe; +eine Zelle: 24 % daneben); die Anzeige „PML = x ferne Zellen“ und die Warnung aus dem Protokoll helfen beim Prüfen. Voraussetzung: das Python-Modul `gmsh` im hpfem-Python. + +**Schichtstapel** (Streuung mit Gmsh-Geometrie): Haken „Objekt über einem Schichtstapel“, Einfallsmedium (verlustfrei), Schichten (Material, Dicke; Hinzufügen und Entfernen), Substrat, Abstand +des Objekts zur Oberkante (0 = aufliegend; Kugeln brauchen Abstand), Tiefe des Substrats bis zum PML, Einfallswinkel, Polarisation s oder p, Azimut. Die Hintergrundlösung ist der analytische Stapel (`LayerStack3D`), +das Objekt streut nur die Abweichung. Die Tabelle zeigt R, T, A des Stapels ohne Objekt; σ sind auf die Intensität der einfallenden Welle bezogen, Q auf die Projektion des Objekts auf die x-y-Ebene. +Ein Stapel aus Luft liefert dieselbe Kugel wie ohne Stapel (Q_sca +1,7 % gegen Mie bei 21 000 Unbekannten); R einer Luft/Glas-Grenzfläche bei 30° (p) stimmt mit der Fresnel-Formel überein. +Das PML ist für den Index 1 ausgelegt: bei Substrat und Schichten mit höherem Index sind die Querschnitte Richtwerte, Substrat und Schichten sollten bis in den PML-Bereich reichen (Tiefe einstellen). + +**Eigene Datei:** Datei hochladen (Gmsh 4.1 ASCII), Einheit der Koordinaten wählen, „Datei lesen“ (zeigt Zellmarken mit Zellzahl, Flächenmarken, Ausdehnung), jeder Zellmarke ein Material zuweisen, die +Zellmarken des Streukörpers ankreuzen, PML-Dicke einstellen (das PML liegt in der äußersten Schicht der Box). Randflächen ohne Marke werden zu den Seiten der Box (PEC). Streuung, Resonanzen und die +hp-Verfeinerung laufen wie bei den eingebauten Netzen; Q bezieht sich auf die Projektion des Objekts (aus der Oberfläche mit geraden Facetten, bei gekrümmten Körpern ungenau, σ ist davon unabhängig). + +**hp-Adaptivität** (Reiter 2, Streuung): Haken „hp-adaptive Verfeinerung“, Schritte, Dörfler-Anteil θ, Obergrenze Unbekannte, optional η/η₀. Je Schritt wird gelöst, der residuale Fehlerschätzer +ausgewertet, markiert und h- oder p-verfeinert; die Startordnung p ist die kleinste. Reiter 3 „hp-Verfeinerung“: Diagramm η und Q_sca gegen Unbekannte, Tabelle je Schritt; Reiter „Netz“: Schnitt, auf Wunsch +nach Ordnung gefärbt. η fällt, Q_sca konvergiert bei grobem PML nicht monoton (Kugel n = 2, ka = 2: η 0,133 → 0,042, Q_sca 4,51 → 4,44, Mie 4,77, in 16 s). + +**Wellenleiter und Ports (Aufgabe „Wellenleiter und Ports (S-Parameter)“):** Bauteil Streifenwellenleiter, Richtkoppler oder eigene Gmsh-Datei. Kern (Breite, Höhe), Länge, Rand, Materialien Kern und Mantel +(dispersiv auswertbar), beim Koppler Spalt und Portart (vier Halbflächen-Ports oder ein Port mit zwei Moden je Stirnfläche); Reiter 2: Wellenlängen, Zelle (und Zelle längs z, gröber spart viel), Ordnung, +Anregung (Port und Mode), Feld der Anregung. Ergebnis: Transmission, Reflexion, Verlust (Leistungsbilanz, Fehler der Portnormierung), S-Matrix (|S|², Spalte = Anregung), n_eff der Portmoden mit feiner 2D-Referenz, +beim Koppler cross, bar, Kopplungslänge nach der Theorie gekoppelter Moden (Netz der Rechnung und feines Referenznetz) sowie |E|² im Längs- und Querschnitt. Eigene Datei: Flächenmarken als PEC-Wand oder Port +(mit Modenzahl) zuweisen (z. B. der Ringresonator `examples/ring_resonator_3d/ring_mesh.py` der Bibliothek, dort jeweils Port 11 und 12). +**Grenzen:** 3D-Wellenleiter sind teuer. n_eff des 450 × 220 nm Si/SiO₂-Streifens ist mit p = 1 und 150-nm-Zellen um 9 % zu klein (2,14 gegen 2,36); mit p = 2 und 10 000 Unbekannten dauert die Rechnung 3 Minuten. +Ein Richtkoppler mit p = 1 und 150-nm-Zellen koppelt viel zu stark (Kopplungslänge 10 µm gegen 25 µm auf dem feinen Netz), cross ist bei kurzen Kopplern sehr empfindlich auf den Phasenfehler. Die Vorlagen +zeigen also die Mechanik, keine konvergierten Bauteile; Netz und Ordnung muss man prüfen (die Tabelle zeigt dafür die Referenzen). Halbflächen-Ports verfälschen cross zusätzlich um einige Prozent. + ## Wellenleiter und Ports (Seitenleiste „Art des Modells“ → „Wellenleiter und Ports“) Ein zweidimensionales Bauteil in der Ebene (x, y), vier Reiter wie bei den anderen Modi. Reiter 1: Materialien (isotrop), Hintergrund (Mantel), Gebiet (Länge L in x, Breite B in y) und @@ -260,11 +290,11 @@ n_eff = 1,98555 gegen 1,98555 aus der Dispersionsgleichung des Schichtwellenleit 450 × 220 nm, n = 3,48 in 1,44 (2148 Dreiecke, 29 s): n_eff = 2,356, 1,731, 1,447, 1,367 (der Grundmode liegt im üblichen Bereich von 2,3 bis 2,4 für einen Siliziumdraht in Quarz). **Grenzen.** Gerade Elemente an den Rändern der Formen (Merkmale unter etwa einem Drittel der Zellgröße werden nicht aufgelöst, Gitterzähne und kleine Spalte brauchen „Faktor an Grenzflächen“ ≈ 0,5), -isotrope Materialien, nur Ports links und rechts (keine Ports an den oberen und unteren Wänden), keine dreidimensionalen Ports (`PortModes3D`). Resonante Bauteile (Ringe, Koppler) sind +isotrope Materialien, nur Ports links und rechts (keine Ports an den oberen und unteren Wänden); dreidimensionale Ports (`PortModes3D`) gibt es im Modus „3D-Strukturen“. Resonante Bauteile (Ringe, Koppler) sind nicht vorbereitet; sie brauchen feine Netze (Spalt und Steg aufgelöst) und viele Wellenlängen. Eine Vorlage dafür ist nicht mitgeliefert, weil ich eine Resonanz hier nicht nachgerechnet habe. -## Wärme und Mechanik (Seitenleiste „Art des Modells“ → „Wärme und Mechanik (2D)“) -Der Modus koppelt drei hpfem-Löser in zwei Dimensionen (Ergebnisse je Meter in der unendlichen Richtung). Reiter 1 wählt den Fall. +## Wärme und Mechanik (Seitenleiste „Art des Modells“ → „Wärme und Mechanik (2D und 3D)“) +Der Modus koppelt drei hpfem-Löser in zwei Dimensionen (Ergebnisse je Meter in der unendlichen Richtung); über den Schalter „Raumdimension“ oben gibt es dieselbe Kette in 3D (siehe unten). Reiter 1 wählt den Fall. * **Nanodraht: Optik → Wärme → Spannung.** Materialien (optische Daten wie sonst, dazu je Material Wärmeleitfähigkeit κ, E-Modul, Querkontraktion ν, Ausdehnung α und das thermo-optische dε/dT), Draht und Matrix (die Matrix muss verlustfrei sein), Wellenlänge, Feldamplitude E₀ (die App zeigt die Intensität), Radius und Gebiet. Das @@ -280,6 +310,26 @@ Draht ohne Rückkopplung gegen die Linienquelle), Feldkarten, Schnitte und das v Wichtig: Die Temperatur gilt für das gewählte Gebiet (in 2D wächst sie logarithmisch mit dem Abstand der Senke). Temperatur und Schrumpfung wirken als Eigendehnung in der Ebene (ε*_zz = 0), die Von-Mises-Spannung nimmt σ_zz = ν(σ_xx + σ_yy). Es gibt nur den stationären Fall, keine Konvektion und Strahlung, keine temperaturabhängigen Materialdaten außer ε(T), und die Optik rechnet auf dem unverformten Netz. Die Materialvorgaben sind grobe Richtwerte; die Vorlage „selbstkonsistent“ trägt ein Beispiel-dε/dT, keinen Messwert. + +### 3D (Schalter „Raumdimension“ = 3D) +Zwei Fälle mit `Scattering3D`, `Thermal3D`, `ThermoOptical3D` und `Elasticity3D` (Ergebnisse in W, J, K, nm, MPa). + +* **Kugel: Optik → Wärme → Spannung.** Materialien wie in 2D (optische Daten, κ, E, ν, α, dε/dT), Kugel und Matrix (verlustfrei), Wellenlänge, E₀, Radius, Innenbreite und Außenbreite in Radien + (der Rest ist die PML; **an den Außenflächen der Box sitzt die Wärmesenke**), Zellen je Radius. Die Welle läuft in +z, E längs x. Das **Viertelmodell** rechnet nur x > 0, y > 0 (Faktor 4 für Leistung und Energie, + die Felder werden gespiegelt) und spart etwa einen Faktor 4 an Speicher. „Selbstkonsistent“ löst die Optik je Iteration neu (bei der Vorlage 5 Iterationen, rund 65 s). „Wärmespannung“ rechnet `Elasticity3D` + (Außenflächen eingespannt oder frei, Schrumpfung der Kugel optional). +* **Quader.** Breite, Tiefe, Höhe und Zellen je Richtung; Randbedingungen je Fläche (frei, eingespannt, Symmetrie, Zug/Druck in MPa); ΔT bei z = 0 und z = H (linear) und Schrumpfung bei z = 0 und z = H + (linear; „Schrumpfblock auf dem Substrat“ ist das Viertelmodell aus Beispiel R7 der Bibliothek) **oder** eine **Wärmequelle** q (mW/µm³) mit Wärmesenken auf den gewählten Flächen (`Thermal3D`; die übrigen + Flächen sind adiabatisch), deren Temperatur die Wärmedehnung treibt. + +Reiter 2: Polynomordnung, Auflösung der Schnitte, **Speichergrenze** und der Knopf „Netz prüfen und Speicher schätzen“ (Zellen, Unbekannte, `estimate_memory`, Zeitrichtwerte; rot, wenn die Schätzung die Grenze +überschreitet, gelb ab 60 % des freien Hauptspeichers). Reiter 3: Kennzahlen mit den Prüfungen (Quader gegen die geschlossene Lösung, Wärmequelle gegen die eindimensionale Lösung, Kugel gegen die Schätzung +ΔT ≈ P/(4πκ)(1/R − 1/R_s)), Schnitte senkrecht zu x, y oder z mit Schieber, Linienschnitte, das verformte Raster eines Schnitts und die Konvergenz der Schleife. + +Wichtig: 3D ist teuer (nur SparseLU, ein Thread; 15 000 Unbekannte der Mechanik brauchen etwa 50 s und 0,6 GB; die Zeitangabe der App ist eine Faustformel). Das Standardnetz ist grob (die Bibliothek meldet eine +unteraufgelöste PML); Konvergenz prüfen. Die Temperatur gilt für das gewählte Gebiet. Wie in 2D: stationär, keine Konvektion und Strahlung, Materialdaten außer ε(T) unabhängig von T, Optik auf dem unverformten +Netz, Maxima sind Rasterwerte, Materialvorgaben sind grobe Richtwerte, die Kette ist nicht gegen Literaturwerte für konkrete Partikel validiert. + ## Zeitbereich (Seitenleiste „Art des Modells“ → „Zeitbereich“) Der Modus löst die Wellengleichung im Zeitbereich mit `hpfem.TimeDomain2D/3D` (hp-Elemente im Raum, implizite Newmark-Regel in der Zeit). Reiter 1: Vorlage, Dimension (2D-Schnitt oder 3D-Kasten mit Kugel), Materialien (konstante, reelle ε bei λ₀, dazu eine Leitfähigkeit σ in S/m je Material), Gebiet und Formen (2D wie im Wellenleiter-Modus), Rand je Seite diff --git a/docs/ARCHITEKTUR.md b/docs/ARCHITEKTUR.md index a2a77d1..5389b28 100644 --- a/docs/ARCHITEKTUR.md +++ b/docs/ARCHITEKTUR.md @@ -37,12 +37,19 @@ | `fem_thermo.py` | Wärme und Mechanik ohne hpfem und ohne Streamlit: Modell (Fälle `wire`, `block`, `axi`, Materialdaten je Material in `props`), Vorlagen, Prüfung, geschlossene Vergleichswerte (`analytic_checks`), Linienquellen-Näherung (`heat_line_estimate`), Abbildungen (Feldkarte, Schnitt, verformtes Netz, Konvergenz). | | `fem_thermo_app.py` | Seite des Modus „Wärme und Mechanik“ (`render_thermo`, vier Reiter, eigener Prozess `th_proc`, Ordner `/thermo`). | | `fem_thermo_worker.py` | Läuft im hpfem-Python: `Scattering2D` + `absorbed_power_load` + `Thermal2D` oder `ThermoOptical2D`, `Elasticity2D` (ebene Dehnung bzw. `axisymmetric`), Felder auf einem Raster (`PointLocator2D`), `deformed_mesh`. | +| `fem_thermo3d.py` | Wärme und Mechanik in 3D ohne hpfem und ohne Streamlit: Modell (Fälle `particle`, `block`; Materialdaten aus `fem_thermo`), Vorlagen, Prüfung, geschlossene Lösungen (`analytic_checks`, `heat_checks`, `particle_heat_estimate`), Faustformel `mech_estimate`, Schnitt-, Linien- und Verformungsfiguren. | +| `fem_thermo3d_app.py` | Seite „Wärme und Mechanik (3D)“ (`render_thermo3d`, aufgerufen aus `fem_thermo_app.render_thermo` über den Schalter `th_dim`; vier Reiter, eigener Prozess `th3_proc`, Ordner `/thermo3d`), Schätzung vor dem Lauf (`run_estimate`). | +| `fem_thermo3d_worker.py` | Läuft im hpfem-Python: `Scattering3D` + `absorbed_power_load` + `Thermal3D` oder `ThermoOptical3D` (Kugel, optional Viertelmodell), `Thermal3D` (Quader mit Quelle), `Elasticity3D`, Raster der Felder (gespiegelt beim Viertelmodell), Aktion `estimate`, Speichergrenze `max_gb`. | | `fem_bands.py` | Bandstruktur ohne hpfem und ohne Streamlit: Modell (maßstabsfrei in a, quadratisch/hexagonal, Formen mit Gitterbildern), Prüfung, k-Pfad (Γ–X–M–Γ, Γ–M–K–Γ), Gmsh-Netz (`build_mesh`: Zelle als Parallelogramm um den Ursprung, Formen und ihre Gitterbilder geschnitten und fragmentiert, Randkurven 101/102 und 103/104 mit `setPeriodic` gepaart), Lücken (`band_gaps`), Tabellen, Abbildungen. | | `fem_bands_app.py` | Seite des Modus „Bandstruktur“ (`render_bands`, vier Reiter, eigener Prozess `bd_proc`, Ordner `/bands`). | | `fem_bands_worker.py` | Läuft im hpfem-Python: `BandStructureSetup2D` mit je einem `PeriodicPair2D` je Gittervektor, `BandStructure2D.bands(k)` je k-Punkt (feste Krylov-Dimension, ein Band mehr für den zweiten Nullwert bei Γ), Modenfelder über `keep_modes` und `subdivide` + `sample_hcurl`. | -| `fem_threed.py` | 3D-Strukturen ohne hpfem und ohne Streamlit: Modell (Aufgaben `scatter`/`resonance`/`bands`, Kugel oder Würfel), Prüfung (Ganzzahligkeit von n·Innenraum, n·Außenrand), Job, Speicherschätzung über Unterprozess (`run_estimate`), Zeitrichtwert, Schnitt durch das Tetraedernetz (`section_polygons`), Feld- und Effizienzdiagramme, leeres kubisches Gitter. | +| `fem_threed.py` | 3D-Strukturen ohne hpfem und ohne Streamlit: Modell (Aufgaben `scatter`/`resonance`/`bands`/`ports`; Netzarten `builtin`/`gmsh`/`file`; Schichtstapel, hp-Adaptivität; Kugel, Würfel, Zylinder, Quader), Prüfung (Ganzzahligkeit von n·Innenraum, n·Außenrand), Job, Speicherschätzung über Unterprozess (`run_estimate`), Zeitrichtwert, Schnitt durch das Tetraedernetz (`section_polygons`), Feld- und Effizienzdiagramme, leeres kubisches Gitter. | | `fem_threed_app.py` | Seite des Modus „3D-Strukturen“ (`render_threed`, vier Reiter, eigener Prozess `td_proc`, Ordner `/threed`, Schätzordner `threed/estimate`). | | `fem_threed_worker.py` | Läuft im hpfem-Python: Netze (`box_with_ball`, `box`, Viertelmodell über `extract`), `Scattering3D` + `cross_sections` + `mie_sphere`, `Resonance3D`, `BandStructure3D`; Aufruf mit `estimate` meldet nur `ESTIMATE{json}` und schreibt `mesh_.npz`; vor jedem Lauf wird der Speicher geschätzt und bei Überschreitung von `max_gb` abgebrochen. | +| `fem_threed_gmsh.py` | Gmsh-Netze der 3D-Modi (nur `gmsh` und NumPy, kein hpfem): `scene(g, Pfad)` baut Box mit PML-Rand, Schichtplatten (jede Region ein Volumen), Objekt (Kugel, Zylinder, Quader), Maschenfelder (Distance/Threshold am Objekt, Box je Region, Min), physikalische Gruppen 2 (Objekt), 11 + k (Region k von oben) und 1 bis 6 (Boxseiten wie `hpfem.box_tag`); `layout` (Ebenen). | +| `fem_ports3d.py` | Wellenleiter und Ports in 3D ohne hpfem und ohne Streamlit: Modell (Streifen, Koppler, Datei), Prüfung, Job, Tensorgitter-Linien, Ergebnistabellen, Abbildungen (S-Parameter, Felder). | +| `fem_ports3d_app.py` | Oberfläche der Aufgabe „Wellenleiter und Ports“ im Modus „3D-Strukturen“ (`tab_model`, `tab_params`, `results`). | +| `fem_ports3d_worker.py` | Läuft im hpfem-Python: Tensorgitter (`grid_box`: `hpfem.box` auf Indexkoordinaten, Knoten verschoben), `Scattering3D` mit `WaveguidePort`, `s_parameters`, 2D-Referenzen (`section_modes`, feines Netz p + 2), Feld der Anregung; Aufrufe `estimate`, `inspect`. | | `fem_time.py` | Zeitbereich ohne hpfem und ohne Streamlit: Modell (2D mit Formen des Wellenleiter-Moduls oder 3D `box_with_ball`), Prüfung, Schätzungen (`estimate`: Träger, höchste Frequenz, Δt, Schritte), Signale (`signal_value`/`signal_derivative`), Netz (2D über `fem_wg.build_mesh`), Job, Spektrum (`spectrum`, `transfer`), Laufzeit (`arrival_time` über die Hüllkurve) und Bilder. | | `fem_time_app.py` | Seite des Modus „Zeitbereich“ (`render_time`, fünf Reiter, eigener Prozess `tm_proc`, Ordner `/time`). | | `fem_time_worker.py` | Läuft im hpfem-Python: `TimeDomainSetup2D/3D` (Materialien und σ je Tag, PEC- und absorbierende Facetten, Stromdichte, `TimeSignal`), `TimeDomain2D/3D.run` in Blöcken mit Beobachter (Energie, Sonden über `PointLocator` und `sample_hcurl`, Feldbilder), `results.json` und `field_frames.npz`. | @@ -62,10 +69,11 @@ ## Emitter, Wellenleiter +* **Wärme und Mechanik (3D):** `/thermo3d/job.json` (Modell aus `fem_thermo3d.job`, mit `max_gb`) → `results.json` (`scalars`, `history`, `probes`, `converged`, `meta.estimate`) und `fields3d.npz` (Achsen x, y, z, 3D-Felder, NaN außerhalb des Netzes); Abbruchdatei `cancel`. * **Wärme und Mechanik:** `/thermo/job.json` (das Modell aus `fem_thermo`) → `results.json` (`scalars`, `history`, `probes`, `converged`, `finished`), `fields.npz` (Raster `x`, `y`, Felder `T`, `Eabs`, `ux`, `uy`, `umag`, `sxx`, `syy`, `sxy`, `szz`, `svm`, verformtes Netz), `log.txt`, `cancel`. * **Zeitbereich:** `/time/job.json` (Modell aus `fem_time.job`: SI-Größen, Quelle, Sonden, Rand-Tags), `mesh.msh` (nur 2D, nm, Tags 1 + Index, 101 … 104), `results.json` (`t_fs`, `t_energy_fs`, `energy`, `drive`, `probes`), `field_frames.npz` (2D: `points`, `simplices`, `ex`, `ey`; 3D: `gx`, `gy`, `ex`, `ey`, `ez`, `times_fs`). * **Bandstruktur:** `/bands/job.json` (Modell aus `fem_bands.job` mit `k`, `x`, `ticks`, `corner_idx`), `mesh.msh` (Einheiten a; Flächen-Tag = 1 + Index des Materials, Linien 101/102 links/rechts und 103/104 unten/oben) → `results.json` (je k-Punkt `f`, `residual`, `time_s`, `modes_file`), `mode_.npz` (Felder der Eckpunkte), `log.txt`, `cancel`. -* **3D-Strukturen:** `/threed/job.json` (aus `fem_threed.job`: `task`, `shape`, `radius_nm` bzw. `radius` (Bänder, in a), `n`, `order`, `half_width`, `outer`, `quarter`, `max_gb`, `wavelengths_nm` + `eps` je Wellenlänge bzw. `lam0_nm`, `num_modes` bzw. `eps`, `eps_bg`, `bands`, `n_seg`, `cells`), `results.json` (`meta` mit `cells`, `dofs`, `bytes`; `points` bzw. `modes`; Bänder: `x`, `ticks`), `field_.npz` (`xs`, `ys`, `zs`, `xz`, `xy` = |E|², Streuung im Quadranten x, y ≥ 0), `mesh_.npz` (Knoten, Zellen, Tags). +* **3D-Strukturen:** `/threed/job.json` (aus `fem_threed.job`; Erweiterungen: `mesh_kind`, `g` (Gmsh-Parameter in nm), `stack` (`eps` je Region und Wellenlänge, `thickness_nm`, `pol`, `angle_deg`, `azimuth_deg`), `file` (`path`, `scale`, `object_tags`, `pml_nm`, `tag_eps`), `adaptive` (`theta`, `max_steps`, `max_dofs`, `tol`; Punkte tragen dann `steps`), Aufgabe `ports` mit `fem_ports3d.job` (Gerät, Geometrie, `eps_core`/`eps_clad` je Wellenlänge, Ports) und `fem_ports3d_worker.py`; Basis: `task`, `shape`, `radius_nm` bzw. `radius` (Bänder, in a), `n`, `order`, `half_width`, `outer`, `quarter`, `max_gb`, `wavelengths_nm` + `eps` je Wellenlänge bzw. `lam0_nm`, `num_modes` bzw. `eps`, `eps_bg`, `bands`, `n_seg`, `cells`), `results.json` (`meta` mit `cells`, `dofs`, `bytes`; `points` bzw. `modes`; Bänder: `x`, `ticks`), `field_.npz` (`xs`, `ys`, `zs`, `xz`, `xy` = |E|², Streuung im Quadranten x, y ≥ 0), `mesh_.npz` (Knoten, Zellen, Tags). * **Wellenleiter und Ports:** `/waveguide/job.json` (Modell aus `fem_wg.job` mit `wavelengths_nm`), `mesh.msh` (Gmsh 4.1; Flächen-Tag = 1 + Index des Materials, Linien 101 bis 104) → `fem_wg_worker.py` → `results.json` (`meta`; Aufgabe `ports`: je Wellenlänge `channels` (`port`, `side`, `mode`, `beta`), `S_re`, `S_im`, `port_modes`, `excitation`, `R`, `T`, `loss`, `field`; Aufgabe `modes`: `n_eff`, `beta`, `modes_file`), `field_.npz` (`points` in nm, `simplices`, `values` = E_x, E_y, `tag`), `mode_.npz` (`points`, `simplices`, `et_`, `ez_`). Log: `PROGRESS i/n`, `CANCELLED`, `DONE`. * **Gitterzelle:** `job["task"] = "emitter"`, `job["model"]["emitter"]` (`x_nm`, `y_nm`, `sigma_nm`, `moment`, `stage` A/B/C, `scan`, `apertures`, `directions`, `calibrate`, `dry_run`). Die Wellenlängen sind die des Durchlaufs über λ, sonst die der Beleuchtung. `results.json` hat `task = "emitter"`, `emitter`, `cost` (auch im Log als `COST {…}`) und `points` (je Wellenlänge die Felder der Stufe: B `purcell_by_orientation`, `fractions`, `aperture`, A `orders_up`/`orders_down`, C `dP_dOmega`). `model["emitter"]` verfeinert das Netz (Gmsh-Ballfeld, `fem_geometry.build_mesh`); in der Netzsignatur zählen nur `x_nm`, `y_nm`, `sigma_nm`. * **Rotationskörper außerhalb der Achse:** `model["emitter"]["radii_nm"]` (und `offaxis_na`) → ein Emitterkasten (±6σ) je Abstand im Meridiannetz (Tag 101 + Index). Der Worker (`offaxis_run`) schreibt das Netz mit verschobenen z-Koordinaten (`shift_msh`: die Oberkante des Stapels liegt bei z = 0, ohne Schichten die untere Grenze des Innengebiets), nimmt eine Position an, die der Punktsucher findet, und ruft `dataports.axisymmetric_emitter_response` mit `radii` je Wellenlänge. `results.json`: `points[i]` mit `offaxis`, `radii_nm`, `A_tot`, `A_rad`, `A_det` (je Abstand 3×3 bzw. je Detektor), `detectors`, `convergence`; `table_.json` der Umschlag. diff --git a/fem_gui/fem_app.py b/fem_gui/fem_app.py index e1bc358..fc5a121 100644 --- a/fem_gui/fem_app.py +++ b/fem_gui/fem_app.py @@ -58,7 +58,8 @@ _wtext = _worker.read_text(encoding="utf-8", errors="replace") for _f in ("fem_axi.py", "fem_axi_worker.py", "fem_axi_app.py", "fem_ui.py", "fem_study.py", "fem_study_app.py", "fem_emit.py", "fem_emit_app.py", "fem_emit_worker.py", "fem_wg.py", "fem_wg_app.py", "fem_wg_worker.py", "fem_disp.py", "fem_bands.py", "fem_bands_app.py", "fem_bands_worker.py", "fem_study_worker.py", - "fem_thermo.py", "fem_thermo_app.py", "fem_thermo_worker.py", "fem_threed.py", "fem_threed_app.py", "fem_threed_worker.py", + "fem_thermo.py", "fem_thermo_app.py", "fem_thermo_worker.py", "fem_thermo3d.py", "fem_thermo3d_app.py", "fem_thermo3d_worker.py", + "fem_threed.py", "fem_threed_app.py", "fem_threed_worker.py", "fem_threed_gmsh.py", "fem_ports3d.py", "fem_ports3d_app.py", "fem_ports3d_worker.py", "fem_time.py", "fem_time_app.py", "fem_time_worker.py"): if not (HERE / _f).is_file(): _old.append(f"{_f}: nicht gefunden (muss neben fem_app.py liegen)") @@ -212,14 +213,14 @@ def add_layer(): st.sidebar.title("FEM-Modellwerkstatt") MODES = {"periodic": "Periodische Struktur (Gitter, Metaoberfläche)", "axi": "Rotationskörper: Resonator, Emitter", "study": "Studie: Optimierung, Rekonstruktion, UQ", "waveguide": "Wellenleiter und Ports", "bands": "Bandstruktur (photonischer Kristall)", - "thermo": "Wärme und Mechanik (2D)", + "thermo": "Wärme und Mechanik (2D und 3D)", "threed": "3D-Strukturen (Kugel, Würfel, kubischer Kristall)", "time": "Zeitbereich: Pulse, Sonden, Spektren"} app_mode = st.sidebar.radio("Art des Modells", list(MODES), format_func=MODES.get, key="app_mode", help="Periodisch: Elementarzelle mit Bloch-Rändern, ebene Welle (Streuung, Beugung). Rotationskörper: Struktur mit " "Rotationssymmetrie um z (Mikrosäule, Kugel, Scheibe), Resonanzen und Emission eines Dipols. Studie: Optimierung, " "Parameterrekonstruktion und Unsicherheiten einer Gitterzelle mit dem Job-Runner der Bibliothek. Wellenleiter und Ports: Bauteil in der Chipebene " - "zwischen modalen Ports (S-Matrix) und Moden des Querschnitts. Wärme und Mechanik: absorbierte Leistung → Temperatur → Wärmespannung (2D), auch selbstkonsistent, sowie Block und Zylinder unter Last. 3D-Strukturen: Streuung an Kugel oder Würfel, Resonanzen und kubische Bandstruktur mit den 3D-Lösern (speicherintensiv, mit Schätzung vor dem Lauf). Zeitbereich: Pulse und Dauerstrich mit Sonden, Spektren und Feldfilmen. Bandstruktur: Bänder und Lücken eines 2D-photonischen Kristalls (Floquet-Bloch). Emitter in einer Gitterzelle: im Modus „Periodische Struktur“ " + "zwischen modalen Ports (S-Matrix) und Moden des Querschnitts. Wärme und Mechanik: absorbierte Leistung → Temperatur → Wärmespannung (2D und 3D: Draht, Kugel), auch selbstkonsistent, sowie Block, Zylinder und Quader unter Last. 3D-Strukturen: Streuung an Kugel oder Würfel, Resonanzen und kubische Bandstruktur mit den 3D-Lösern (speicherintensiv, mit Schätzung vor dem Lauf). Zeitbereich: Pulse und Dauerstrich mit Sonden, Spektren und Feldfilmen. Bandstruktur: Bänder und Lücken eines 2D-photonischen Kristalls (Floquet-Bloch). Emitter in einer Gitterzelle: im Modus „Periodische Struktur“ " "(Reiter 1 und Aufgabe „Emitter“).") if app_mode == "axi": fem_axi_app.sidebar_model() diff --git a/fem_gui/fem_ports3d.py b/fem_gui/fem_ports3d.py new file mode 100644 index 0000000..4d5f6bd --- /dev/null +++ b/fem_gui/fem_ports3d.py @@ -0,0 +1,266 @@ +"""Waveguides and ports in 3D (hp-FEM 0.5): models, job, checks and figures. Pure Python (no hpfem needed); worker: fem_ports3d_worker.py, user interface: +fem_threed_app.py (task ``ports`` of the mode "3D-Strukturen"). + +Devices (z along the guide, x across, y up; PEC walls on the four side faces, modal ports on the two end faces z = 0 and z = L, as in the library example +``directional_coupler_3d``): + +* ``straight``: one rectangular core (width x height) in a cladding; one port per end face with ``num_modes`` modes; reference: the fundamental mode of the + same cross-section from the 2D mode solver (``PropagatingMode``): n_eff, and the phase of the transmission against beta L. +* ``coupler``: two parallel cores with a gap (directional coupler); ``ports = "half"`` splits each end face into two ports (core A / core B, one mode each), + ``"full"`` uses one two-mode port per face (even and odd supermode); reference: coupled-mode theory P_cross = sin^2(kappa L), kappa = (beta_e - beta_o) / 2 from the + supermodes of the cross-section. +* ``file``: a Gmsh mesh of the user (physical volumes = materials, physical surfaces = PEC walls and ports), e.g. the ring resonator of the library + (examples/ring_resonator_3d/ring_mesh.py); no reference. + +Structured meshes (hpfem.box, tetrahedra, cells aligned with the core edges) so that no Gmsh is needed for the first two. +""" +from __future__ import annotations + +import copy + +import numpy as np +import pandas as pd + +import fem_materials as fm + +DEVICES = {"straight": "Streifenwellenleiter", "coupler": "Richtkoppler (zwei Kerne)", "file": "Eigene Gmsh-Datei (.msh)"} +PORT_STYLES = {"half": "vier Halbflächen-Ports (Kern A, Kern B je Stirnfläche, eine Mode)", "full": "ein Port je Stirnfläche mit zwei Moden (gerade und ungerade Supermode)"} +SCRIPT = "fem_ports3d_worker.py" +TAG_CLAD, TAG_A, TAG_B = 1, 2, 3 +PORT_TAGS = (11, 12, 13, 14) +GB = 1e9 + + +def default_model(): + return {"name": "Streifenwellenleiter Si/SiO2, λ = 1550 nm", "device": "straight", + "materials": {"Kern": {"type": "index", "n": 3.48, "k": 0.0}, "Mantel": {"type": "index", "n": 1.44, "k": 0.0}}, "core": "Kern", "clad": "Mantel", + "width_nm": 450.0, "height_nm": 220.0, "gap_nm": 200.0, "length_nm": 1200.0, "margin_x_nm": 600.0, "margin_y_nm": 450.0, "cell_nm": 150.0, "cell_z_nm": 0.0, + "order": 1, "ports": "full", "num_modes": 1, "excite_port": 0, "excite_mode": 0, + "sweep": {"start": 1550.0, "stop": 1550.0, "count": 1}, "field": True, "max_gb": 16.0, + "file": {"name": "", "scale": "nm", "tag_material": {}, "pec_tags": [], "ports": [], "tags": {}}} + + +def presets(): + p = {} + m = default_model() + p[m["name"]] = m + m = default_model() + m.update(name="Richtkoppler Si/SiO2 (Halbflächen-Ports, klein)", device="coupler", ports="half", gap_nm=200.0, length_nm=1000.0, cell_nm=150.0) + p[m["name"]] = m + m = default_model() + m.update(name="Richtkoppler Si/SiO2 (Supermoden-Ports)", device="coupler", ports="full", num_modes=2, gap_nm=200.0, length_nm=1000.0, cell_nm=150.0) + p[m["name"]] = m + return p + + +def wavelengths(m): + s = m["sweep"] + return [float(v) for v in np.linspace(s["start"], s["stop"], int(s["count"]))] if int(s["count"]) > 1 else [float(s["start"])] + + +def eps_pair(m, name, lam): + e = fm.eps_at(m["materials"][name], lam) + return [float(e.real), float(e.imag)] + + +def grid_lines(edges, cell): + """Grid lines through all edges with about `cell` spacing in between (same rule as the worker).""" + lines = [edges[0]] + for a, b in zip(edges[:-1], edges[1:]): + n = max(1, round((b - a) / cell)) + lines.extend(a + (b - a) * (i + 1) / n for i in range(n)) + return np.array(lines) + + +def x_edges(m): + w, g, mx = m["width_nm"], m["gap_nm"], m["margin_x_nm"] + if m["device"] == "straight": + return [-w / 2 - mx, -w / 2, w / 2, w / 2 + mx] + a0, b1 = -g / 2 - w, g / 2 + w + return [a0 - mx, a0, -g / 2, g / 2, b1, b1 + mx] + + +def y_edges(m): + return [-m["margin_y_nm"], 0.0, m["height_nm"], m["height_nm"] + m["margin_y_nm"]] + + +def cell_count(m): + """Approximate number of hexahedral cells of the structured mesh (each is split into tetrahedra) for a quick size hint.""" + if m["device"] == "file": + return None + cell = m["cell_nm"] + nx, ny = len(grid_lines(x_edges(m), cell)) - 1, len(grid_lines(y_edges(m), cell)) - 1 + nz = max(1, round(m["length_nm"] / (m["cell_z_nm"] or cell))) + return nx * ny * nz + + +def validate(m): + out = [] + d = m["device"] + if d == "file": + f = m["file"] + if not f.get("name"): + out.append(("error", "Bitte eine .msh-Datei hochladen (Gmsh 4.1 ASCII).")) + elif not f.get("tags"): + out.append(("error", "Die Datei wurde noch nicht gelesen: „Datei lesen“ im Reiter 2.")) + elif not f["ports"]: + out.append(("error", "Mindestens ein Port (Flächenmarke) wird gebraucht.")) + if not f.get("pec_tags"): + out.append(("warning", "Keine PEC-Wand gewählt: die Seitenflächen sind dann natürlich (PMC).")) + else: + if min(m["width_nm"], m["height_nm"], m["length_nm"], m["cell_nm"]) <= 0: + out.append(("error", "Breite, Höhe, Länge und Zelle müssen positiv sein.")) + if m["cell_nm"] > 0.6 * min(m["width_nm"], m["height_nm"]) * 1.0 and m["order"] == 1: + out.append(("warning", "Die Zelle ist größer als etwa 60 % der kleineren Kernkante: mit p = 1 ist der Kern kaum aufgelöst (Reflexion und Phasenfehler groß).")) + if d == "coupler" and m["gap_nm"] < m["cell_nm"]: + out.append(("warning", "Der Spalt ist kleiner als eine Zelle: er wird mit einer Zelle vernetzt (der Spalt im Modell ist dann die Zellkante).")) + if d == "coupler" and m["ports"] == "full" and int(m["num_modes"]) < 2: + out.append(("error", "Supermoden-Ports brauchen zwei Moden je Port.")) + if m["length_nm"] < 2 * m["cell_nm"]: + out.append(("error", "Die Länge muss mindestens zwei Zellen umfassen.")) + n = cell_count(m) + if n and n > 60000: + out.append(("warning", f"Etwa {n} Würfelzellen (je sechs Tetraeder): das wird ein großes Problem, vorher Speicher schätzen.")) + try: + for lam in wavelengths(m): + if d != "file": + ec, ek = fm.eps_at(m["materials"][m["core"]], lam), fm.eps_at(m["materials"][m["clad"]], lam) + if ec.real <= ek.real: + out.append(("warning", f"Bei {lam:g} nm ist Re ε des Kerns nicht größer als der des Mantels: es gibt keine geführte Mode.")) + break + except Exception as exc: + out.append(("error", f"Material: {exc}")) + if m["order"] < 1: + out.append(("error", "Ordnung ≥ 1.")) + return out + + +def job(m, max_gb=None): + j = {"task": "ports", "name": m["name"], "device": m["device"], "order": int(m["order"]), "max_gb": float(max_gb if max_gb is not None else m["max_gb"]), + "wavelengths_nm": wavelengths(m), "field": bool(m["field"]), "excite_port": int(m["excite_port"]), "excite_mode": int(m["excite_mode"])} + if m["device"] == "file": + f = m["file"] + j.update(path=f.get("path", ""), scale=_scale(f["scale"]), + pec_tags=[int(t) for t in f["pec_tags"]], ports=[dict(tag=int(p["tag"]), modes=int(p["modes"])) for p in f["ports"]], + tag_eps={str(t): [eps_pair(m, nm, lam) for lam in j["wavelengths_nm"]] for t, nm in f["tag_material"].items() if nm in m["materials"]}) + return j + lams = j["wavelengths_nm"] + j.update(width_nm=float(m["width_nm"]), height_nm=float(m["height_nm"]), gap_nm=float(m["gap_nm"]), length_nm=float(m["length_nm"]), + margin_x_nm=float(m["margin_x_nm"]), margin_y_nm=float(m["margin_y_nm"]), cell_nm=float(m["cell_nm"]), cell_z_nm=float(m["cell_z_nm"]), + style=m["ports"], num_modes=int(m["num_modes"]) if m["device"] == "straight" or m["ports"] == "full" else 1, + eps_core=[eps_pair(m, m["core"], lam) for lam in lams], eps_clad=[eps_pair(m, m["clad"], lam) for lam in lams]) + return j + + +def _scale(unit): + return {"nm": 1e-9, "µm": 1e-6, "mm": 1e-3, "m": 1.0}[unit] + + +def channel_label(c): + return f"P{c['port'] + 1}·M{c['mode'] + 1}" + + +# ===================================================================================================================== results +def results_dataframe(points, device, style): + rows = [] + for p in points: + r = {"λ (nm)": p["lam_nm"]} + if "error" in p: + r["Fehler"] = p["error"] + rows.append(r) + continue + r["n_eff (Port 1, Mode 1)"] = p.get("n_eff0", np.nan) + if "n_eff_ref" in p: + r["n_eff Referenz (2D, fein)"] = p["n_eff_ref"] + r["Reflexion R"] = p["R"] + r["Transmission T"] = p["T"] + r["Verlust 1−R−T"] = p["loss"] + if "bar" in p: + r["Durchgang (bar)"] = p["bar"] + r["Kopplung (cross)"] = p["cross"] + r["cross (gekoppelte Moden)"] = p.get("cross_cmt", np.nan) + if "cross_cmt_ref" in p: + r["cross Referenz (fein)"] = p["cross_cmt_ref"] + r["Rückkopplung"] = p.get("back", np.nan) + if "phase_error" in p: + r["Phasenfehler (rad)"] = p["phase_error"] + r["Unbekannte"] = p.get("dofs", np.nan) + r["Zeit (s)"] = p.get("seconds", np.nan) + rows.append(r) + return pd.DataFrame(rows) + + +def s_matrix_dataframe(p): + ch = p["channels"] + labels = [channel_label(c) for c in ch] + s = np.array(p["S_re"]) + 1j * np.array(p["S_im"]) + df = pd.DataFrame(np.abs(s) ** 2, columns=[f"nach {lab}" for lab in labels]) + df.insert(0, "Anregung", [f"aus {lab}" for lab in labels]) + return df + + +def fig_sparams(points): + import matplotlib.pyplot as plt + + ok = [p for p in points if "R" in p] + lam = [p["lam_nm"] for p in ok] + fig, ax = plt.subplots(figsize=(6.2, 4.0)) + if "bar" in ok[0]: + ax.plot(lam, [p["bar"] for p in ok], "o-", label="Durchgang (bar)") + ax.plot(lam, [p["cross"] for p in ok], "s-", label="Kopplung (cross)") + if all("cross_cmt" in p for p in ok): + ax.plot(lam, [p["cross_cmt"] for p in ok], "k--", label="cross (gekoppelte Moden)") + else: + ax.plot(lam, [p["T"] for p in ok], "o-", label="Transmission T") + ax.plot(lam, [p["R"] for p in ok], "^-", color="C3", label="Reflexion R") + ax.set_xlabel("Wellenlänge (nm)") + ax.set_ylabel("Leistungsanteil der Anregung") + ax.set_ylim(-0.02, 1.05) + ax.grid(alpha=0.3) + ax.legend(fontsize=8) + fig.tight_layout() + return fig + + +def fig_field(npz, key, outline=None, title=""): + """|E|^2 (arbitrary scale) on the x-z plane through the cores (key xz: z horizontal, x vertical) or the x-y section at mid length (key xy).""" + import matplotlib.pyplot as plt + + f = np.asarray(npz[key], dtype=float) + xs = np.asarray(npz["xs"]) * 1e9 + other = np.asarray(npz["zs"] if key == "xz" else npz["ys"]) * 1e9 + fig, ax = plt.subplots(figsize=(6.4, 3.6) if key == "xz" else (5.4, 4.2)) + if key == "xz": + im = ax.pcolormesh(other, xs, f, shading="auto", cmap="inferno") + ax.set_xlabel("z, längs des Wellenleiters (nm)") + ax.set_ylabel("x (nm)") + else: + im = ax.pcolormesh(xs, other, f.T, shading="auto", cmap="inferno") + ax.set_xlabel("x (nm)") + ax.set_ylabel("y (nm)") + ax.set_aspect("equal") + fig.colorbar(im, ax=ax, label="|E|² (willkürliche Einheit)") + if outline: + for seg in outline.get(key, []): + ax.plot(*seg, "w--", lw=0.9) + ax.set_title(title) + fig.tight_layout() + return fig + + +def outline(m): + """Core outlines [nm] for the two cut views: dict key -> list of (xs, ys) to plot.""" + if m["device"] == "file": + return {} + h, L = m["height_nm"], m["length_nm"] + ex = x_edges(m) + cores = [(ex[1], ex[2])] if m["device"] == "straight" else [(ex[1], ex[2]), (ex[3], ex[4])] + xz, xy = [], [] + for a, b in cores: + xz += [([0, L], [a, a]), ([0, L], [b, b])] + xy.append(([a, b, b, a, a], [0, 0, h, h, 0])) + return {"xz": xz, "xy": xy} + + +def copy_model(m): + return copy.deepcopy(m) diff --git a/fem_gui/fem_ports3d_app.py b/fem_gui/fem_ports3d_app.py new file mode 100644 index 0000000..c250091 --- /dev/null +++ b/fem_gui/fem_ports3d_app.py @@ -0,0 +1,212 @@ +"""User interface of the task "Wellenleiter und Ports (3D)" of the mode "3D-Strukturen" (hp-FEM 0.5): model, parameters, results. Called from fem_threed_app.py +(``tab_model``, ``tab_params``, ``results``). Model, job and figures: fem_ports3d.py; worker: fem_ports3d_worker.py. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import streamlit as st + +import fem_ports3d as fp +import fem_run as fr +import fem_ui as ui + +S = st.session_state + + +def _num(col, label, key, value, step=10.0, lo=0.0, hi=1e7, help=None, fmt="%.5g"): + return float(col.number_input(label, lo, hi, float(value), step, key=key, format=fmt, help=help)) + + +def _rename(m, old, new): + m["materials"] = {(new if k == old else k): v for k, v in m["materials"].items()} + for key in ("core", "clad"): + if m[key] == old: + m[key] = new + f = m["file"] + f["tag_material"] = {t: (new if nm == old else nm) for t, nm in f["tag_material"].items()} + + +def tab_model(m, ver, bump, ctx, work): + """Model editor of the ports model m (S.td_model["p3"]).""" + left, right = st.columns([6, 5]) + with left: + m["device"] = st.radio("Bauteil", list(fp.DEVICES), index=list(fp.DEVICES).index(m["device"]), format_func=fp.DEVICES.get, key=f"p3_dev_{ver}", horizontal=True) + if m["device"] != "file": + c = st.columns(3) + m["width_nm"] = _num(c[0], "Kernbreite (nm)", f"p3_w_{ver}", m["width_nm"], 10.0, 20.0, 5000.0) + m["height_nm"] = _num(c[1], "Kernhöhe (nm)", f"p3_h_{ver}", m["height_nm"], 10.0, 20.0, 5000.0) + m["length_nm"] = _num(c[2], "Länge (nm)", f"p3_l_{ver}", m["length_nm"], 100.0, 100.0, 200000.0, "Länge des Bauteils zwischen den Ports (z).") + if m["device"] == "coupler": + c = st.columns(2) + m["gap_nm"] = _num(c[0], "Spalt zwischen den Kernen (nm)", f"p3_g_{ver}", m["gap_nm"], 10.0, 10.0, 5000.0) + m["ports"] = c[1].radio("Ports", list(fp.PORT_STYLES), index=list(fp.PORT_STYLES).index(m["ports"]), format_func=lambda k: fp.PORT_STYLES[k].split(" (")[0], + key=f"p3_pst_{ver}", help="Halbflächen: " + fp.PORT_STYLES["half"] + ". Supermoden: " + fp.PORT_STYLES["full"] + ".") + c = st.columns(2) + m["margin_x_nm"] = _num(c[0], "Rand seitlich (nm)", f"p3_mx_{ver}", m["margin_x_nm"], 50.0, 50.0, 20000.0, "Mantel neben den Kernen bis zur PEC-Wand (x).") + m["margin_y_nm"] = _num(c[1], "Rand oben und unten (nm)", f"p3_my_{ver}", m["margin_y_nm"], 50.0, 50.0, 20000.0, "Mantel unter und über den Kernen bis zur PEC-Wand (y).") + st.subheader("Materialien") + lam0 = fp.wavelengths(m)[0] + ui.material_editor(m, ver, lam0, {m["core"], m["clad"]}, _rename, bump, prefix="p3_") + names = list(m["materials"]) + c = st.columns(2) + m["core"] = c[0].selectbox("Kern", names, index=names.index(m["core"]) if m["core"] in names else 0, key=f"p3_core_{ver}") + m["clad"] = c[1].selectbox("Mantel", names, index=names.index(m["clad"]) if m["clad"] in names else 0, key=f"p3_clad_{ver}") + else: + _file_editor(m, ver, bump, ctx, work) + with right: + for lvl, text in fp.validate(m): + (st.error if lvl == "error" else st.warning)(text) + if m["device"] == "file": + st.markdown("**Aufbau.** Ein Gmsh-Netz (Version 4.1, ASCII) mit physikalischen Volumina (Materialien) und Flächen (PEC-Wände, Ports), z. B. der Ringresonator der Bibliothek " + "(`examples/ring_resonator_3d/ring_mesh.py`). Die Ports sind Flächenmarken; jeder Port löst seine Moden mit dem 2D-Modenlöser.") + else: + st.markdown("**Aufbau.** z längs des Wellenleiters, x quer, y nach oben. Seitenflächen: ideale Leiter (PEC), die Moden fallen innerhalb der Ränder ab. Stirnflächen z = 0 und z = L: " + "modale Ports. Strukturiertes Tetraedernetz, Zellkanten treffen die Kernkanten.") + st.caption("Referenz: Streifenwellenleiter: β der Grundmode des Querschnitts (2D-Modenlöser) gegen die Phase der Transmission; Koppler: Theorie gekoppelter Moden " + "P_cross = sin²(κL) mit κ = (β_gerade − β_ungerade)/2 aus den Supermoden.") + + +def _file_editor(m, ver, bump, ctx, work): + f = m["file"] + up = st.file_uploader("Gmsh-Datei (.msh, Version 4.1 ASCII)", type=["msh"], key=f"p3_up_{ver}") + if up is not None and up.name != f.get("name"): + folder = Path(work) / "ports_files" + folder.mkdir(parents=True, exist_ok=True) + path = folder / "mesh.msh" + path.write_bytes(up.getvalue()) + f.update(name=up.name, path=str(path), tags={}, tag_material={}, pec_tags=[], ports=[]) + bump() + st.rerun() + if not f.get("name"): + return + st.caption(f"Datei: {f['name']}") + c = st.columns([1, 1, 1]) + f["scale"] = c[0].selectbox("Einheit der Koordinaten", ["nm", "µm", "mm", "m"], index=["nm", "µm", "mm", "m"].index(f["scale"]), key=f"p3_unit_{ver}") + if c[1].button("Datei lesen", key=f"p3_read_{ver}"): + import fem_threed as ft + + info = ft.run_inspect(ctx["py"], ctx["repo"], Path(work) / "ports_files" / "inspect", f["path"], f["scale"], "ports", int(ctx["threads"])) + if "error" in info: + st.error(info["error"]) + else: + f["tags"] = info + names = list(m["materials"]) + for tag in info["cells"]: + f["tag_material"].setdefault(tag, names[0]) + bump() + st.rerun() + info = f.get("tags") + if not info: + return + st.caption(f"{info['n_cells']} Zellen, Geometrieordnung {info.get('geometry_order', '?')}; Ausdehnung " + + " × ".join(f"{(b - a) / 1e-9:.0f}" for a, b in zip(info['bbox'][0], info['bbox'][1])) + " nm") + st.markdown("**Zellmarken → Material**") + ui.material_editor(m, ver, fp.wavelengths(m)[0], set(f["tag_material"].values()), _rename, bump, prefix="p3f_") + names = list(m["materials"]) + for tag, count in info["cells"].items(): + cur = f["tag_material"].get(tag, names[0]) + f["tag_material"][tag] = st.selectbox(f"Zellmarke {tag} ({count} Zellen)", names, index=names.index(cur) if cur in names else 0, key=f"p3_tm_{ver}_{tag}") + st.markdown("**Flächenmarken → Rolle**") + roles = {"none": "ungenutzt", "pec": "PEC-Wand", "port": "Port"} + cur_ports = {str(p["tag"]): p["modes"] for p in f["ports"]} + pec, ports = [], [] + for tag, count in info["facets"].items(): + role = "port" if tag in cur_ports else ("pec" if int(tag) in f["pec_tags"] else "none") + c = st.columns([2, 1]) + role = c[0].selectbox(f"Flächenmarke {tag} ({count} Flächen)", list(roles), index=list(roles).index(role), format_func=roles.get, key=f"p3_fr_{ver}_{tag}") + if role == "pec": + pec.append(int(tag)) + elif role == "port": + n = int(c[1].number_input("Moden", 1, 8, int(cur_ports.get(tag, 1)), key=f"p3_fm_{ver}_{tag}")) + ports.append(dict(tag=int(tag), modes=n)) + f["pec_tags"], f["ports"] = pec, ports + m["excite_port"] = int(st.number_input("Anregung: Port (Reihenfolge der Ports oben, ab 1)", 1, max(len(ports), 1), int(m["excite_port"]) + 1, key=f"p3_xp_{ver}")) - 1 + + +def tab_params(m, ver): + """Wavelengths, mesh and order of the ports model.""" + st.subheader("Wellenlängen") + s = m["sweep"] + c = st.columns(3) + s["start"] = _num(c[0], "von (nm)", f"p3_s0_{ver}", s["start"], 10.0, 200.0, 20000.0) + s["stop"] = _num(c[1], "bis (nm)", f"p3_s1_{ver}", s["stop"], 10.0, 200.0, 20000.0) + s["count"] = int(c[2].number_input("Zahl der Wellenlängen", 1, 100, int(s["count"]), key=f"p3_sn_{ver}", help="Jede Wellenlänge ist eine eigene Faktorisierung (mit allen Anregungskanälen).")) + st.subheader("Netz und Ordnung") + c = st.columns(4) + if m["device"] != "file": + m["cell_nm"] = _num(c[0], "Zelle (nm)", f"p3_cell_{ver}", m["cell_nm"], 10.0, 20.0, 2000.0, "Zellkante des Tetraedernetzes (Würfelzellen, je sechs Tetraeder); die Gitterlinien treffen die Kernkanten.") + m["cell_z_nm"] = _num(c[1], "Zelle längs z (nm, 0 = wie Zelle)", f"p3_cellz_{ver}", m["cell_z_nm"], 10.0, 0.0, 5000.0, "Gröber längs des Wellenleiters spart viele Zellen (die Felder variieren dort langsam).") + m["order"] = int(c[2].number_input("Ordnung p", 1, 4, int(m["order"]), key=f"p3_p_{ver}")) + if m["device"] == "straight": + m["num_modes"] = int(c[3].number_input("Moden je Port", 1, 6, int(m["num_modes"]), key=f"p3_nm_{ver}")) + c = st.columns(3) + m["excite_port"] = int(c[0].number_input("Anregung: Port", 1, 4 if m["device"] != "file" else 8, int(m["excite_port"]) + 1, key=f"p3_ep_{ver}", disabled=m["device"] == "file")) - 1 if m["device"] != "file" else m["excite_port"] + m["excite_mode"] = int(c[1].number_input("Anregung: Mode", 1, 6, int(m["excite_mode"]) + 1, key=f"p3_em_{ver}")) - 1 + m["field"] = c[2].checkbox("Feld der Anregung speichern", value=bool(m["field"]), key=f"p3_fld_{ver}", help="Eine zusätzliche Lösung bei der ersten Wellenlänge: |E|² im Längsschnitt und im Querschnitt.") + n = fp.cell_count(m) + if n: + st.caption(f"Etwa {n} Würfelzellen, das sind rund {6 * n} Tetraeder; die genaue Zahl und der Speicher stehen nach „Netz prüfen“.") + + +# ===================================================================================================================== results +def results(res, work, model): + pts = res["points"] + meta = res["meta"] + for p in pts: + if "error" in p: + st.error(f"λ = {p['lam_nm']:g} nm: {p['error']}") + ok = [p for p in pts if "R" in p] + if not ok: + return + m = model["p3"] + sub = st.tabs(["Transmission", "S-Matrix", "Felder", "Tabelle"]) + with sub[0]: + if len(ok) > 1: + ui.show_fig(fp.fig_sparams(ok), "sparameter.png", "p3_dl_sp") + df = fp.results_dataframe(ok, meta.get("device"), m["ports"]) + ui.table_show(df.round(5)) + p = ok[0] + notes = [] + if "phase_error" in p: + ref = f", feines Referenznetz (p + 2, halbe Zelle): {p['n_eff_ref']:.4f}" if "n_eff_ref" in p else "" + notes.append(f"n_eff der Portmode {p['n_eff0']:.4f} (2D-Modenlöser auf demselben Netz{ref}): der Unterschied ist der Diskretisierungsfehler des Querschnitts. Phasenfehler " + f"|arg(t · e^(iβL))| = {p['phase_error']:.3f} rad: numerische Dispersion längs z, wächst mit der Länge, fällt mit kleinerer Zelle und höherem p (bei p = 1 groß).") + if "cross_cmt" in p: + ref = f"; mit dem feinen Referenznetz {p['coupling_length_ref_nm'] / 1000:.1f} µm und cross = {p['cross_cmt_ref']:.4f}" if "cross_cmt_ref" in p else "" + notes.append(f"Gekoppelte Moden auf dem Netz der 3D-Rechnung: Kopplungslänge {p['coupling_length_nm'] / 1000:.1f} µm, cross = {p['cross_cmt']:.4f}{ref}. Ein großer Abstand zwischen beiden " + "heißt: das Netz ist für die Supermoden nicht aufgelöst (p = 1 mit 150-nm-Zellen koppelt viel zu stark).") + if "phase_error_even" in p: + notes.append(f"Supermoden-Ports: Phasenfehler gerade/ungerade {p['phase_error_even']:.3f} / {p['phase_error_odd']:.3f} rad. cross wird aus der Phasendifferenz der beiden Supermoden " + "gewonnen und ist bei kurzen Kopplern (cross klein) sehr empfindlich auf ihren Fehler.") + else: + notes.append("Halbflächen-Ports: die Anregung ist die Mode des halben Querschnitts (PEC an der Port-Ebene im Spalt); das verfälscht cross bei kurzen Kopplern um einige Prozent " + "(Bibliothek: etwa 1 % absolut), Supermoden-Ports sind genauer.") + notes.append("Leistungsbilanz R + T + Verlust = 1: ein Verlust ungleich 0 bei verlustfreien Materialien ist der Fehler der Portnormierung.") + st.caption(" ".join(notes)) + with sub[1]: + i = st.selectbox("Wellenlänge", range(len(ok)), format_func=lambda i: f"{ok[i]['lam_nm']:g} nm", key="p3_s_lam") if len(ok) > 1 else 0 + df = fp.s_matrix_dataframe(ok[i]) + ui.table_show(df.round(5)) + st.caption("|S|² zwischen den Kanälen (Port · Mode): Leistungsanteile; Zeile = Anregung, Spalte = Ziel. Port-Moden: " + + "; ".join(f"Port {int(k) + 1}: " + ", ".join(f"n_eff = {mm['n_eff']:.4f}{'' if mm['propagating'] else ' (abklingend)'}" for mm in v) for k, v in ok[i]["port_modes"].items())) + with sub[2]: + withf = [p for p in ok if p.get("field_file")] + if not withf: + st.info("Kein Feld gespeichert.") + else: + npz = np.load(Path(work) / withf[0]["field_file"]) + ol = fp.outline(m) + c = st.columns(2) + with c[0]: + ui.show_fig(fp.fig_field(npz, "xz", ol, f"Längsschnitt durch die Kerne, λ = {withf[0]['lam_nm']:g} nm"), "ports_xz.png", "p3_dl_xz") + with c[1]: + ui.show_fig(fp.fig_field(npz, "xy", ol, "Querschnitt bei halber Länge"), "ports_xy.png", "p3_dl_xy") + st.caption("|E|² der Lösung mit Anregung des gewählten Kanals (Port und Mode in Reiter 2), Skala beliebig. Weiß gestrichelt: Kernkanten.") + with sub[3]: + df = fp.results_dataframe(ok, meta.get("device"), m["ports"]) + c = st.columns(2) + c[0].download_button("Tabelle (CSV)", ui.csv_bytes(df), file_name="ports_3d.csv", mime="text/csv", key="p3_dl_csv") + c[1].download_button("Modell (JSON)", json.dumps(m, indent=1, ensure_ascii=False).encode("utf-8"), file_name="wellenleiter_3d.json", mime="application/json", key="p3_dl_model") diff --git a/fem_gui/fem_ports3d_worker.py b/fem_gui/fem_ports3d_worker.py new file mode 100644 index 0000000..59497cf --- /dev/null +++ b/fem_gui/fem_ports3d_worker.py @@ -0,0 +1,356 @@ +"""Worker for waveguides and ports in 3D (hp-FEM 0.5): runs in the Python that has hpfem, called by the app. + + python fem_ports3d_worker.py [estimate | inspect] + +Reads /job.json (fem_ports3d.job). Devices: ``straight`` (one core), ``coupler`` (two cores), both on the structured tetrahedral mesh of hpfem.box with PEC +side walls and modal ports on the end faces z = 0, z = L; ``file`` (Gmsh mesh of the user: physical surfaces PEC / ports, physical volumes materials). +Per wavelength: hpfem.s_parameters (power-normalised S-matrix of all propagating channels), reflection / transmission of the excited channel, n_eff of the port +modes, for ``straight`` the phase of the transmission against beta L of the 2D mode solver, for ``coupler`` the coupled-mode reference +P_cross = sin^2(kappa L) from the supermodes of the cross-section, and (optional) |E|^2 of the excitation on two cut planes. +``estimate``: only the mesh and hpfem.estimate_memory (``ESTIMATE{json}``); ``inspect``: tags of a mesh file (``INSPECT{json}``). + +Writes /results.json after every wavelength and log lines on stdout (PROGRESS i/n, ERROR ..., CANCELLED, DONE). Cancellation: file /cancel. +""" +from __future__ import annotations + +import json +import sys +import time +import traceback +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +NM = 1e-9 +TAG_CLAD, TAG_A, TAG_B = 1, 2, 3 +PORT_TAGS = (11, 12, 13, 14) +GRID = 61 + + +def say(*a): + print(*a, flush=True) + + +def grid_lines(edges, cell): + lines = [edges[0]] + for a, b in zip(edges[:-1], edges[1:]): + n = max(1, round((b - a) / cell)) + lines.extend(a + (b - a) * (i + 1) / n for i in range(n)) + return np.array(lines) + + +def grid_box(h, xs, ys, zs): + """Tetrahedral mesh (Kuhn subdivision, sides tagged with box_tag) of the tensor grid xs x ys x zs: hpfem.box on index coordinates, then the vertices moved to the grid + lines, so the cell faces meet the core edges exactly (hpfem.box itself is uniform).""" + mesh = h.box(len(xs) - 1, len(ys) - 1, len(zs) - 1, [0, 0, 0], [len(xs) - 1, len(ys) - 1, len(zs) - 1]) + for i, v in enumerate(np.asarray(mesh.vertices)): + mesh.set_vertex(i, [xs[int(round(v[0]))], ys[int(round(v[1]))], zs[int(round(v[2]))]]) + return mesh + + +def grid_rectangle(h, xs, ys): + mesh = h.rectangle(len(xs) - 1, len(ys) - 1, [0, 0], [len(xs) - 1, len(ys) - 1]) + for i, v in enumerate(np.asarray(mesh.vertices)): + mesh.set_vertex(i, [xs[int(round(v[0]))], ys[int(round(v[1]))]]) + return mesh + + +def edges_of(job): + w, g, mx, my, hgt = (job[k] * NM for k in ("width_nm", "gap_nm", "margin_x_nm", "margin_y_nm", "height_nm")) + if job["device"] == "straight": + xe = [-w / 2 - mx, -w / 2, w / 2, w / 2 + mx] + else: + a0, b1 = -g / 2 - w, g / 2 + w + xe = [a0 - mx, a0, -g / 2, g / 2, b1, b1 + mx] + return xe, [-my, 0.0, hgt, hgt + my] + + +def tag_cores(job, mesh): + xe, _ = edges_of(job) + hgt = job["height_nm"] * NM + cores = [(xe[1], xe[2], TAG_A)] if job["device"] == "straight" else [(xe[1], xe[2], TAG_A), (xe[3], xe[4], TAG_B)] + for c, x in enumerate(np.asarray(mesh.cell_centroids)): + tag = TAG_CLAD + if 0.0 < x[1] < hgt: + for a, b, t in cores: + if a < x[0] < b: + tag = t + mesh.set_cell_tag(c, tag) + + +def build_mesh(h, job): + """(mesh, info) in SI units.""" + if job["device"] == "file": + mesh = h.read_gmsh(job["path"], float(job["scale"]), 3) + return mesh, dict(kind="file") + xe, ye = edges_of(job) + cell = job["cell_nm"] * NM + xs, ys = grid_lines(xe, cell), grid_lines(ye, cell) + L = job["length_nm"] * NM + nz = max(1, round(L / ((job.get("cell_z_nm") or job["cell_nm"]) * NM))) + mesh = grid_box(h, xs, ys, np.linspace(0.0, L, nz + 1)) + tag_cores(job, mesh) + half = job["device"] == "coupler" and job["style"] == "half" + if half: + for face, (left, right) in ((h.box_tag.Z_MIN, PORT_TAGS[:2]), (h.box_tag.Z_MAX, PORT_TAGS[2:])): + for f in mesh.facets_with_tag(face): + x = np.mean([mesh.vertex(int(v)) for v in mesh.facet_vertices(int(f))], axis=0) + mesh.set_facet_tag(int(f), left if x[0] < 0 else right) + return mesh, dict(kind=job["device"], half=half, length=L) + + +def inspect_mesh(h, path, scale): + mesh = h.read_gmsh(path, float(scale), 3) + cells = np.asarray(mesh.cell_tags) + ftags = np.asarray(mesh.facet_tags) + v = np.asarray(mesh.vertices) + return dict(n_cells=int(mesh.num_cells), cells={str(int(t)): int((cells == t).sum()) for t in np.unique(cells)}, + facets={str(int(t)): int((ftags == t).sum()) for t in np.unique(ftags) if int(t) != int(h.NO_TAG)}, + bbox=[v.min(axis=0).tolist(), v.max(axis=0).tolist()], geometry_order=int(mesh.geometry_order)) + + +def port_tags(h, job): + if job["device"] == "file": + return [(int(p["tag"]), int(p["modes"])) for p in job["ports"]] + if job["device"] == "coupler" and job["style"] == "half": + return [(t, 1) for t in PORT_TAGS] + return [(int(h.box_tag.Z_MIN), int(job["num_modes"])), (int(h.box_tag.Z_MAX), int(job["num_modes"]))] + + +def wall_tags(h, job): + if job["device"] == "file": + return [int(t) for t in job["pec_tags"]] + t = h.box_tag + return [t.X_MIN, t.X_MAX, t.Y_MIN, t.Y_MAX] + + +def material_map(h, job, mesh, i): + if job["device"] == "file": + mm = h.MaterialMap(h.Material(1.0)) + for t, lst in job.get("tag_eps", {}).items(): + e = lst[i] + mm.set(int(t), h.Material(complex(e[0], e[1]))) + return mm + ec, el = job["eps_core"][i], job["eps_clad"][i] + mm = h.MaterialMap(h.Material(complex(el[0], el[1]))) + mm.set(TAG_A, h.Material(complex(ec[0], ec[1]))) + mm.set(TAG_B, h.Material(complex(ec[0], ec[1]))) + return mm + + +def estimate(h, job, mesh): + nd = h.NedelecDofMap3D(mesh, int(job["order"])) + e = h.estimate_memory(nd) + return dict(cells=int(mesh.num_cells), dofs=int(nd.num_dofs), bytes=int(e.total_bytes), text=e.describe(), human=h.format_bytes(int(e.total_bytes))) + + +def save_mesh(folder, mesh): + np.savez_compressed(folder / "mesh_ports.npz", vertices=np.asarray(mesh.vertices), cells=np.asarray(mesh.cells), tags=np.asarray(mesh.cell_tags)) + + +def section_modes(h, job, i, omega, count, refine=False): + """beta (descending) of the cross-section modes (2D mode solver, PEC on the four sides): straight: the core; coupler: the two-core section. refine: half the cell + and order p + 2 (at most 4): a reference that is nearly free of the discretisation error of the 3D problem.""" + xe, ye = edges_of(job) + cell = job["cell_nm"] * NM * (0.5 if refine else 1.0) + xs, ys = grid_lines(xe, cell), grid_lines(ye, cell) + mesh = grid_rectangle(h, xs, ys) + hgt = job["height_nm"] * NM + cores = [(xe[1], xe[2], TAG_A)] if job["device"] == "straight" else [(xe[1], xe[2], TAG_A), (xe[3], xe[4], TAG_B)] + for c, x in enumerate(np.asarray(mesh.cell_centroids)): + tag = TAG_CLAD + if 0.0 < x[1] < hgt: + for a, b, t in cores: + if a < x[0] < b: + tag = t + mesh.set_cell_tag(c, tag) + p = min(int(job["order"]) + 2, 4) if refine else int(job["order"]) + nd, h1 = h.NedelecDofMap2D(mesh, p), h.DofMap2D(mesh, p) + setup = h.WaveguideSetup() + setup.omega = omega + setup.materials = material_map(h, job, mesh, i) + t = h.box_tag + setup.pec_tags = [t.X_MIN, t.X_MAX, t.Y_MIN, t.Y_MAX] + setup.num_modes = count + modes = h.PropagatingMode(nd, h1, setup).solve() + return sorted((complex(m.beta).real for m in modes), reverse=True) + + +def field_planes(job, info, mesh): + """Points of the two cut views: xz at y = mid height of the cores (z horizontal) and xy at z = L / 2, as (xs, zs / ys, pts_xz, pts_xy).""" + v = np.asarray(mesh.vertices) + lo, hi = v.min(axis=0), v.max(axis=0) + eps = 1e-6 * float(np.max(hi - lo)) + xs = np.linspace(lo[0] + eps, hi[0] - eps, GRID // 2 + 1) + zs = np.linspace(lo[2] + eps, hi[2] - eps, GRID) + ys = np.linspace(lo[1] + eps, hi[1] - eps, GRID // 2 + 1) + y_mid = job["height_nm"] * NM / 2 if job["device"] != "file" else 0.5 * (lo[1] + hi[1]) + z_mid = 0.5 * (lo[2] + hi[2]) + X, Z = np.meshgrid(xs, zs, indexing="ij") + pxz = np.stack([X.ravel(), np.full(X.size, y_mid), Z.ravel()], axis=1) + X2, Y2 = np.meshgrid(xs, ys, indexing="ij") + pxy = np.stack([X2.ravel(), Y2.ravel(), np.full(X2.size, z_mid)], axis=1) + return xs, zs, ys, pxz, X.shape, pxy, X2.shape + + +def run(h, job, folder, mesh, info, est, out, flush): + p = int(job["order"]) + nd = h.NedelecDofMap3D(mesh, p) + ports = port_tags(h, job) + lams = job["wavelengths_nm"] + coupler = job["device"] == "coupler" + straight = job["device"] == "straight" + L = info.get("length", 0.0) + locator = h.PointLocator3D(mesh) if job.get("field", True) else None + planes = field_planes(job, info, mesh) if locator is not None else None + ex_port, ex_mode = int(job.get("excite_port", 0)), int(job.get("excite_mode", 0)) + for i, lam in enumerate(lams): + if (folder / "cancel").exists(): + say("CANCELLED") + out["cancelled"] = True + flush() + return + say(f"PROGRESS {i + 1}/{len(lams)} lambda = {lam:g} nm") + t0 = time.time() + pt = dict(index=i, lam_nm=float(lam), dofs=int(nd.num_dofs)) + try: + omega = 2 * np.pi * h.constants.c0 / (lam * NM) + + def make_setup(incoming=None): + s = h.ScatteringSetup3D() + s.omega = omega + s.materials = material_map(h, job, mesh, i) + s.pec_tags = wall_tags(h, job) + lst = [] + for k, (tag, nm) in enumerate(ports): + if incoming is not None and incoming[0] == k: + amp = [0.0] * nm + amp[min(incoming[1], nm - 1)] = 1.0 + lst.append(h.WaveguidePort(tag, nm, amp)) + else: + lst.append(h.WaveguidePort(tag, nm)) + s.ports = lst + return s + + setup = make_setup() + probe = h.Scattering3D(nd, setup) + port_modes = {} + for k in range(len(ports)): + pm = probe.port_modes(k) + port_modes[str(k)] = [dict(n_eff=float(complex(m.effective_index).real), propagating=bool(m.propagating)) for m in pm.modes] + say(f" ports: {port_modes}") + sp = h.s_parameters(nd, setup) + ch = [dict(port=int(c.port), mode=int(c.mode), beta=float(complex(c.beta).real)) for c in sp.channels] + S = np.asarray(sp.s) + cands = [k for k, c in enumerate(ch) if c["port"] == ex_port and c["mode"] == ex_mode] + c0 = cands[0] if cands else 0 + col = np.abs(S[:, c0]) ** 2 + refl = float(sum(col[k] for k, c in enumerate(ch) if c["port"] == ch[c0]["port"])) + trans = float(sum(col[k] for k, c in enumerate(ch) if c["port"] != ch[c0]["port"])) + pt.update(channels=ch, S_re=S.real.tolist(), S_im=S.imag.tolist(), port_modes=port_modes, R=refl, T=trans, loss=float(1.0 - refl - trans), + n_eff0=float(port_modes["0"][0]["n_eff"]) if port_modes.get("0") else float("nan"), excitation=ch[c0]) + if straight: + beta = section_modes(h, job, i, omega, 1)[0] + tcol = [k for k, c in enumerate(ch) if c["port"] != ch[c0]["port"] and c["mode"] == ch[c0]["mode"]] + if tcol: + pt["phase_error"] = float(abs(np.angle(S[tcol[0], c0] * np.exp(1j * beta * L)))) + pt["beta_2d"] = float(beta) + pt["n_eff_2d"] = float(beta / (omega / h.constants.c0)) + if job.get("reference", True): + pt["n_eff_ref"] = float(section_modes(h, job, i, omega, 1, True)[0] / (omega / h.constants.c0)) + if coupler: + be, bo = section_modes(h, job, i, omega, 2)[:2] + kappa = 0.5 * (be - bo) + pt.update(beta_even=float(be), beta_odd=float(bo), kappa=float(kappa), cross_cmt=float(np.sin(kappa * L) ** 2), coupling_length_nm=float(np.pi / (2 * kappa) / NM)) + if job.get("reference", True): + re_, ro_ = section_modes(h, job, i, omega, 2, True)[:2] + kr = 0.5 * (re_ - ro_) + pt.update(cross_cmt_ref=float(np.sin(kr * L) ** 2), coupling_length_ref_nm=float(np.pi / (2 * kr) / NM), n_eff_even_ref=float(re_ / (omega / h.constants.c0)), + n_eff_odd_ref=float(ro_ / (omega / h.constants.c0))) + if job["style"] == "half": + # ports 0, 1 at z = 0 (core A, core B), 2, 3 at z = L + idx = {(c["port"], c["mode"]): k for k, c in enumerate(ch)} + if (2, 0) in idx and (3, 0) in idx and (0, 0) in idx: + pt.update(bar=float(abs(S[idx[(2, 0)], idx[(0, 0)]]) ** 2), cross=float(abs(S[idx[(3, 0)], idx[(0, 0)]]) ** 2), + back=float(abs(S[idx[(1, 0)], idx[(0, 0)]]) ** 2)) + else: + idx = {(c["port"], c["mode"]): k for k, c in enumerate(ch)} + if all(key in idx for key in ((0, 0), (0, 1), (1, 0), (1, 1))): + te, to = S[idx[(1, 0)], idx[(0, 0)]], S[idx[(1, 1)], idx[(0, 1)]] + cross = float(np.sin(np.angle(te * np.conj(to)) / 2) ** 2) + pt.update(bar=1.0 - cross, cross=cross, back=float(abs(S[idx[(0, 1)], idx[(0, 0)]]) ** 2), t_even=[te.real, te.imag], t_odd=[to.real, to.imag], + phase_error_even=float(abs(np.angle(te * np.exp(-1j * be * L)))), phase_error_odd=float(abs(np.angle(to * np.exp(-1j * bo * L))))) + if locator is not None and (i == 0 or job.get("field_all")): + prob = h.Scattering3D(nd, make_setup((ch[c0]["port"], ch[c0]["mode"]))) + sol = prob.solve() + xs, zs, ys, pxz, sxz, pxy, sxy = planes + fields = {} + for key, pts, shp in (("xz", pxz, sxz), ("xy", pxy, sxy)): + vals, cells = prob.sample(sol, locator, pts) + e2 = np.sum(np.abs(np.asarray(vals)) ** 2, axis=1) + e2[np.asarray(cells) < 0] = np.nan + fields[key] = e2.reshape(shp) + np.savez_compressed(folder / f"field_{i}.npz", xs=xs, ys=ys, zs=zs, xz=fields["xz"], xy=fields["xy"]) + pt["field_file"] = f"field_{i}.npz" + pt["seconds"] = time.time() - t0 + except Exception as exc: + pt["error"] = f"{type(exc).__name__}: {exc}" + say(f"ERROR wavelength {lam:g} nm: {pt['error']}") + say(traceback.format_exc()) + out["points"].append(pt) + flush() + + +def main(argv=None) -> int: + argv = list(argv or sys.argv[1:]) + if not argv: + print(__doc__) + return 2 + folder = Path(argv[0]) + job = json.loads((folder / "job.json").read_text(encoding="utf-8")) + import hpfem + hpfem.set_log_level("warn") + if len(argv) > 1 and argv[1] == "inspect": + try: + print("INSPECT" + json.dumps(inspect_mesh(hpfem, job["path"], job["scale"])), flush=True) + return 0 + except Exception as exc: + say(f"ERROR inspect: {type(exc).__name__}: {exc}") + return 1 + try: + mesh, info = build_mesh(hpfem, job) + est = estimate(hpfem, job, mesh) + save_mesh(folder, mesh) + except Exception as exc: + say(f"ERROR mesh: {type(exc).__name__}: {exc}") + return 1 + if len(argv) > 1 and argv[1] == "estimate": + print("ESTIMATE" + json.dumps(est), flush=True) + return 0 + say(f"hpfem {getattr(hpfem, '__version__', '?')}, mesh: {est['cells']} cells, {est['dofs']} unknowns, memory estimate {est['human']}: {est['text']}") + if est["bytes"] > float(job.get("max_gb", 16.0)) * 1e9: + say(f"ERROR memory estimate {est['human']} exceeds the limit of {job.get('max_gb', 16.0)} GB: reduce the mesh or the order (or raise the limit).") + return 1 + out = dict(meta=dict(name=job.get("name", ""), task="ports", device=job["device"], started=time.strftime("%Y-%m-%d %H:%M:%S"), + hpfem=str(getattr(hpfem, "__version__", "?")), order=int(job["order"]), **est), points=[], modes=[]) + path = folder / "results.json" + + def flush(): + path.write_text(json.dumps(out, default=float), encoding="utf-8") + + flush() + try: + run(hpfem, job, folder, mesh, info, est, out, flush) + except Exception as exc: + say(f"ERROR {type(exc).__name__}: {exc}") + say(traceback.format_exc()) + return 1 + flush() + say("DONE") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/fem_gui/fem_run.py b/fem_gui/fem_run.py index 4004a26..7da0719 100644 --- a/fem_gui/fem_run.py +++ b/fem_gui/fem_run.py @@ -169,7 +169,15 @@ def run_check(py, repo, folder, threads=0, timeout=600): feats["dataports"] = feats["offaxis"] = False feats["bands"] = all(hasattr(hpfem, n) for n in ("BandStructure2D", "BandStructureSetup2D", "PeriodicPair2D")) feats["thermo"] = all(hasattr(hpfem, n) for n in ("Thermal2D", "ThermoOptical2D", "Elasticity2D", "ElasticitySetup2D")) + feats["thermo3d"] = all(hasattr(hpfem, n) for n in ("Thermal3D", "ThermoOptical3D", "Elasticity3D", "ElasticitySetup3D", "Scattering3D", "box_with_ball", "estimate_memory")) feats["threed"] = all(hasattr(hpfem, n) for n in ("Scattering3D", "Resonance3D", "BandStructure3D", "MieSphere", "box_with_ball", "estimate_memory")) + feats["threed_ext"] = all(hasattr(hpfem, n) for n in ("LayerStack3D", "AdaptiveMesh3D", "PortModes3D", "WaveguidePort", "s_parameters", "read_gmsh", "hp_refine")) + try: + import gmsh # noqa: F401 + + feats["gmsh"] = True + except Exception: + feats["gmsh"] = False feats["time"] = all(hasattr(hpfem, n) for n in ("TimeDomain2D", "TimeDomainSetup2D", "modulated_gaussian", "TimeSignal")) feats["ports"] = all(hasattr(hpfem, n) for n in ("WaveguidePort", "s_parameters", "PropagatingMode", "subdivide")) feats["crystals"] = hasattr(hpfem, "AnisotropicStack") and hasattr(getattr(hpfem, "Material", None), "anisotropic") diff --git a/fem_gui/fem_thermo3d.py b/fem_gui/fem_thermo3d.py new file mode 100644 index 0000000..e291ae1 --- /dev/null +++ b/fem_gui/fem_thermo3d.py @@ -0,0 +1,449 @@ +"""Heat and mechanics in 3D for the FEM model builder, hp-FEM 0.5, without hpfem and without Streamlit: models, presets, validation, closed-form checks, +estimates, result handling and figures. Solvers: hpfem ``Scattering3D`` / ``ThermoOptical3D`` / ``Thermal3D`` / ``Elasticity3D`` (worker: fem_thermo3d_worker.py). +The 2D module fem_thermo.py supplies the material data (``PROPS``, ``default_props``), the boundary-condition kinds and the intensity formula. + +Two cases: + +* ``particle``: a sphere (tag 2) in a matrix (tag 0) in a box with PML (``hpfem.box_with_ball``). Chain: plane wave (E along x, along +z) -> absorbed power + -> temperature (heat sink T = T_ref on the outer faces of the box) -> optional feedback eps(T) = eps + (d eps/dT)(T - T_ref) (``ThermoOptical3D``) -> optional + thermal stress (``Elasticity3D``; outer box faces clamped or free). Optionally the quarter model x > 0, y > 0 (mirror symmetry, as in fem_threed). +* ``block``: box [0, W] x [0, D] x [0, H], boundary conditions per face (free, clamped, symmetry, traction), temperature change and shrinkage linear along z, or + a volumetric heat source with heat sinks on chosen faces (``Thermal3D``, the other faces adiabatic) whose temperature drives the thermal expansion. + +Units in the model: nm (particle), um (block), MV/m, K, W/(m K), GPa, 1e-6/K, MPa, mW/um^3 (heat source, 1 mW/um^3 = 1e15 W/m^3). The solver gets SI. +Conventions: time factor exp(-i omega t), Im eps > 0 loss. In 3D the thermal strain alpha (T - T_ref) acts in all three directions. +""" +from __future__ import annotations + +import copy +import math + +import numpy as np +import pandas as pd + +import fem_thermo as ft + +CASES = {"particle": "Kugel: Optik → Wärme → Spannung", "block": "Quader: Wärmeleitung und Mechanik"} +SIDES = {"xmin": "x = 0", "xmax": "x = W", "ymin": "y = 0", "ymax": "y = D", "zmin": "z = 0", "zmax": "z = H"} +SIDE_TAGS = {"xmin": 1, "xmax": 2, "ymin": 3, "ymax": 4, "zmin": 5, "zmax": 6} # hpfem.box_tag.X_MIN ... Z_MAX +SIDE_NORMAL = {"xmin": (-1.0, 0.0, 0.0), "xmax": (1.0, 0.0, 0.0), "ymin": (0.0, -1.0, 0.0), "ymax": (0.0, 1.0, 0.0), "zmin": (0.0, 0.0, -1.0), "zmax": (0.0, 0.0, 1.0)} +BC_KINDS = ft.BC_KINDS +WALL_BC = {"clamped": "eingespannt (u = 0 an den Außenflächen)", "free": "frei (Starrkörperbewegung entfernt)"} +FIELDS = { + "T": ("Temperatur (K)", "inferno"), "Eabs": ("|E| / E₀ (Feldüberhöhung)", "viridis"), "umag": ("|u| (nm)", "viridis"), "ux": ("u_x (nm)", "RdBu_r"), + "uy": ("u_y (nm)", "RdBu_r"), "uz": ("u_z (nm)", "RdBu_r"), "svm": ("Von-Mises-Spannung (MPa)", "magma"), "sxx": ("σ_xx (MPa)", "RdBu_r"), + "syy": ("σ_yy (MPa)", "RdBu_r"), "szz": ("σ_zz (MPa)", "RdBu_r"), "sxy": ("σ_xy (MPa)", "RdBu_r"), "syz": ("σ_yz (MPa)", "RdBu_r"), "sxz": ("σ_xz (MPa)", "RdBu_r"), +} +SYMMETRIC_FIELDS = ("ux", "uy", "uz", "sxx", "syy", "szz", "sxy", "syz", "sxz") +EQUIV_CUBE = 0.6606785 # capacity of a cube of edge L is that of a sphere of radius EQUIV_CUBE * L (used for the plausibility check) +PML_THICK_MIN = 1.5 # radii; thinner PML layers are warned about + + +# ===================================================================================================================== estimates +def mech_estimate(h1_dofs): + """Rough single-thread SparseLU cost of Elasticity3D from measurements on a box (p = 2 and 3, 2 187 to 14 739 unknowns, polymer or steel data): + seconds ~ 2 (N / 2187)^1.8, peak MB ~ 45 + 54 (N / 2187)^1.2 with N = 3 x the H1 unknowns. A guide, not a bound (other meshes factor differently).""" + n = 3.0 * float(h1_dofs) + ratio = max(n / 2187.0, 1e-9) + return dict(dofs=int(n), seconds=2.0 * ratio**1.8, bytes=(45.0 + 54.0 * ratio**1.2) * 1024.0 * 1024.0) + + +def available_gb(): + """Free main memory in GB (MemAvailable), None if unknown.""" + try: + for line in open("/proc/meminfo", encoding="utf-8"): + if line.startswith("MemAvailable:"): + return int(line.split()[1]) / 1048576.0 + except OSError: + pass + return None + + +# ===================================================================================================================== models +def _side_dict(default=None): + return {s: dict(default or {"kind": "free", "value": 0.0}) for s in SIDE_TAGS} + + +def default_model(): + """Gold sphere r = 50 nm in glass at 520 nm, 1 MV/m, heat sink at 5 r, quarter model, coarse mesh (n = 1, p = 2): the plasmon region, a few seconds of solving.""" + mats = {"Gold": {"type": "library", "name": "Au"}, "Glas": {"type": "library", "name": "SiO2"}} + return { + "name": "Goldkugel in Glas: Erwärmung", "dim": 3, "case": "particle", "materials": mats, "background": "Glas", "inclusion": "Gold", + "props": {"Gold": ft.default_props(mats["Gold"]), "Glas": ft.default_props(mats["Glas"])}, + "optics": {"wavelength_nm": 520.0, "E0_MVm": 1.0}, + "particle": {"radius_nm": 50.0, "half_factor": 3, "outer_factor": 5, "n": 1, "quarter": True}, + "block": {"W_um": 4.0, "D_um": 2.0, "H_um": 1.0, "nx": 4, "ny": 2, "nz": 2}, + "thermal": {"T_ref": 300.0, "selfconsistent": False, "relaxation": 1.0, "tolerance": 1e-3, "max_iter": 20, "heat": False, "q_mWum3": 1.0, + "sinks": {"xmin": True, "xmax": True, "ymin": False, "ymax": False, "zmin": False, "zmax": False}}, + "mech": {"on": False, "wall": "clamped", "bc": _side_dict(), "dT_a": 0.0, "dT_b": 0.0, "shrink_a_pct": 0.0, "shrink_b_pct": 0.0}, + "order": 2, "grid": 36, "max_gb": 8.0, + } + + +def _block(name, bc, dT=(0.0, 0.0), shrink=(0.0, 0.0), heat=False, sinks=("xmin", "xmax"), q=1.0, size=(4.0, 2.0, 1.0), cells=(4, 2, 2), + material=("Material", {"type": "eps", "re": 2.25, "im": 0.0}, None), order=2): + mat_name, spec, props = material + m = default_model() + m.update(name=name, case="block", materials={mat_name: spec}, background=mat_name, inclusion=mat_name, props={mat_name: props or ft.default_props(spec)}) + m["block"] = dict(W_um=size[0], D_um=size[1], H_um=size[2], nx=cells[0], ny=cells[1], nz=cells[2]) + m["thermal"].update(heat=heat, q_mWum3=q, sinks={s: s in sinks for s in SIDE_TAGS}) + m["mech"] = {"on": True, "wall": "clamped", "bc": {s: dict(bc.get(s, {"kind": "free", "value": 0.0})) for s in SIDE_TAGS}, "dT_a": dT[0], "dT_b": dT[1], + "shrink_a_pct": shrink[0], "shrink_b_pct": shrink[1]} + m["order"] = order + return m + + +_STEEL = ("Stahl-ähnlich", {"type": "eps", "re": 1.0, "im": 0.0}, {"kappa": 50.0, "E_GPa": 200.0, "nu": 0.3, "alpha": 12.0, "deps_re": 0.0, "deps_im": 0.0}) +_RESIN = ("Harz", {"type": "eps", "re": 2.25, "im": 0.0}, {"kappa": 0.2, "E_GPa": 4.5, "nu": 0.35, "alpha": 0.0, "deps_re": 0.0, "deps_im": 0.0}) +_SYM3 = {"xmin": {"kind": "symmetry", "value": 0.0}, "ymin": {"kind": "symmetry", "value": 0.0}, "zmin": {"kind": "symmetry", "value": 0.0}} + + +def presets(): + base = default_model() + out = {base["name"]: base} + stress = copy.deepcopy(base) + stress.update(name="Goldkugel in Glas: Erwärmung und Wärmespannung") + stress["mech"]["on"] = True + out[stress["name"]] = stress + sc = copy.deepcopy(base) + sc.update(name="Goldkugel: selbstkonsistent mit dε/dT (Beispielwert)") + sc["thermal"]["selfconsistent"] = True + sc["props"]["Gold"].update(deps_re=-0.01, deps_im=0.0) + out[sc["name"]] = sc + tens = "Quader unter Zug (Prüfung gegen die geschlossene Lösung)" + out[tens] = _block(tens, {**_SYM3, "xmax": {"kind": "traction", "value": 100.0}}, material=_STEEL) + heat = "Quader: Wärmequelle zwischen zwei Senken (Prüfung gegen die geschlossene Lösung)" + out[heat] = _block(heat, _SYM3, heat=True, q=1.0, material=_STEEL) + hot = "Quader eingespannt, Erwärmung um 50 K" + out[hot] = _block(hot, {"xmin": {"kind": "clamped", "value": 0.0}}, dT=(50.0, 50.0), material=_STEEL) + shr = "Schrumpfblock auf dem Substrat (Viertelmodell)" + out[shr] = _block(shr, {"xmin": {"kind": "symmetry", "value": 0.0}, "ymin": {"kind": "symmetry", "value": 0.0}, "zmin": {"kind": "clamped", "value": 0.0}}, + shrink=(2.0, 4.0), size=(20.0, 20.0, 2.0), cells=(4, 4, 2), material=_RESIN) + return out + + +def normalise(m): + """Fill keys that older or hand-made models miss.""" + d = default_model() + for k, v in d.items(): + if k not in m: + m[k] = copy.deepcopy(v) + for k in ("optics", "particle", "block", "thermal"): + for kk, vv in d[k].items(): + m[k].setdefault(kk, copy.deepcopy(vv)) + for kk, vv in d["mech"].items(): + m["mech"].setdefault(kk, copy.deepcopy(vv)) + for s in SIDE_TAGS: + m["mech"]["bc"].setdefault(s, {"kind": "free", "value": 0.0}) + m["thermal"]["sinks"].setdefault(s, False) + for n, spec in m["materials"].items(): + m["props"].setdefault(n, ft.default_props(spec)) + return m + + +def used_materials(m): + return {m["background"], m["inclusion"]} if m["case"] == "particle" else {m["background"]} + + +def block_size_m(m): + b = m["block"] + return b["W_um"] * 1e-6, b["D_um"] * 1e-6, b["H_um"] * 1e-6 + + +def validate(m): + """[(level, text)] with level 'error' or 'warn'.""" + import fem_materials as fm + + out = [] + names = set(m["materials"]) + for key in ("background", "inclusion"): + if m[key] not in names: + out.append(("error", f"Material „{m[key]}“ fehlt.")) + if out: + return out + case = m["case"] + th, mech = m["thermal"], m["mech"] + if int(m["order"]) < 1: + out.append(("error", "Die Polynomordnung muss mindestens 1 sein.")) + if case == "particle": + p = m["particle"] + if p["radius_nm"] <= 0: + out.append(("error", "Der Radius muss positiv sein.")) + if not (isinstance(p["half_factor"], int) and isinstance(p["outer_factor"], int)) or p["half_factor"] < 2 or p["outer_factor"] <= p["half_factor"]: + out.append(("error", "Gebiet: ganzzahlige Faktoren mit 2 ≤ Innenbreite/Radius < Außenbreite/Radius (der Rest ist die PML-Schicht).")) + elif p["outer_factor"] - p["half_factor"] < PML_THICK_MIN: + out.append(("warn", "Die PML-Schicht ist dünner als anderthalb Radien: Reflexionen wahrscheinlich.")) + if int(p["n"]) < 1: + out.append(("error", "Zellen je Radius: mindestens 1.")) + if m["optics"]["wavelength_nm"] <= 0 or m["optics"]["E0_MVm"] <= 0: + out.append(("error", "Wellenlänge und Feldamplitude müssen positiv sein.")) + try: + bg = fm.eps_at(m["materials"][m["background"]], m["optics"]["wavelength_nm"]) + if abs(bg.imag) > 1e-9: + out.append(("error", "Das Matrixmaterial muss verlustfrei sein (Im ε = 0): die einfallende Welle ist eine ebene Welle im Hintergrund.")) + if fm.is_crystal(m["materials"][m["background"]]) or fm.is_crystal(m["materials"][m["inclusion"]]): + out.append(("error", "Kristalle (anisotrop) gibt es in diesem Modus nicht.")) + except Exception as exc: + out.append(("error", f"Material bei λ nicht auswertbar: {exc}")) + if th["selfconsistent"] and not (0 < th["relaxation"] <= 1): + out.append(("error", "Relaxation zwischen 0 (ausgeschlossen) und 1.")) + if th["selfconsistent"] and not any(abs(m["props"][n]["deps_re"]) + abs(m["props"][n]["deps_im"]) > 0 for n in used_materials(m)): + out.append(("warn", "Selbstkonsistent ohne dε/dT: die Schleife bricht nach einem Durchlauf ab (Ergebnis wie ohne Rückkopplung).")) + if m["props"][m["background"]]["kappa"] <= 0 or m["props"][m["inclusion"]]["kappa"] <= 0: + out.append(("error", "Die Wärmeleitfähigkeit muss positiv sein.")) + if th["selfconsistent"]: + out.append(("warn", f"Selbstkonsistent: jede der bis zu {th['max_iter']} Iterationen löst die Optik neu (je Iteration etwa so lange wie ohne Rückkopplung).")) + else: + b = m["block"] + if min(b["W_um"], b["D_um"], b["H_um"]) <= 0 or min(b["nx"], b["ny"], b["nz"]) < 1: + out.append(("error", "Abmessungen und Zellzahlen müssen positiv sein.")) + if th["heat"]: + if th["q_mWum3"] == 0: + out.append(("warn", "Wärmequelle q = 0: die Temperatur bleibt überall T_ref.")) + if not any(th["sinks"].values()): + out.append(("error", "Wärmequelle ohne Wärmesenke: die stationäre Gleichung hat dann keine Lösung. Mindestens eine Seite als Senke wählen.")) + if m["props"][m["background"]]["kappa"] <= 0: + out.append(("error", "Die Wärmeleitfähigkeit muss positiv sein.")) + if mech["dT_a"] != 0 or mech["dT_b"] != 0: + out.append(("warn", "Mit Wärmequelle gilt das berechnete Temperaturfeld; ΔT (linear) wird ignoriert.")) + if case == "block" or mech["on"]: + names_used = [m["background"]] if case == "block" else [m["background"], m["inclusion"]] + for n in names_used: + p = m["props"][n] + if p["E_GPa"] <= 0 or not (-0.99 < p["nu"] < 0.5): + out.append(("error", f"{n}: E > 0 und −1 < ν < 0,5 nötig.")) + if m["materials"][n].get("type") == "library" and m["materials"][n].get("name") in ft.FLUIDS: + out.append(("warn", f"{n} ist ein Fluid: es hat keine Schubsteifigkeit, die elastischen Werte sind nur ein Platzhalter.")) + if case == "block": + bc = mech["bc"] + kinds = [bc[s]["kind"] for s in SIDE_TAGS] + fixed = any(k in ("clamped", "symmetry") for k in kinds) + loaded = any(bc[s]["kind"] == "traction" and bc[s]["value"] != 0 for s in SIDE_TAGS) + if not fixed and loaded: + out.append(("error", "Alle Seiten frei oder belastet: die Last muss im Gleichgewicht sein, sonst weist der Löser sie ab. Mindestens eine Seite festhalten oder eine Symmetrie wählen.")) + if not fixed and not loaded: + out.append(("warn", "Alles frei und ohne Last: nur Temperatur und Schrumpfung, der Körper dehnt sich frei (Starrkörperbewegung wird entfernt).")) + return out + + +# ===================================================================================================================== closed-form checks +def analytic_checks(m): + """[(label, expected, key)] for the textbook block setups; ``key`` looks up the value in the results' ``probes``. Uniaxial traction on x = W (or none) with the + symmetry planes x = 0, y = 0, z = 0 and free other faces, uniform temperature change and shrinkage: all strains are uniform, so the closed form is exact + in 3D. [] otherwise.""" + if m["case"] != "block" or not m["mech"]["on"]: + return [] + bc, p, th, mech = m["mech"]["bc"], m["props"][m["background"]], m["thermal"], m["mech"] + k = {s: bc[s]["kind"] for s in SIDE_TAGS} + if th["heat"] or mech["dT_a"] != mech["dT_b"] or mech["shrink_a_pct"] != mech["shrink_b_pct"]: + return [] + if not (k["xmin"] == "symmetry" and k["ymin"] == "symmetry" and k["zmin"] == "symmetry" and k["ymax"] == "free" and k["zmax"] == "free" + and k["xmax"] in ("traction", "free")): + return [] + E, nu, al = p["E_GPa"] * 1e9, p["nu"], p["alpha"] * 1e-6 + W, D, H = block_size_m(m) + s = bc["xmax"]["value"] * 1e6 if k["xmax"] == "traction" else 0.0 + e_th = al * mech["dT_a"] - mech["shrink_a_pct"] / 100.0 + return [("u_x(W, D/2, H/2), m", (s / E + e_th) * W, "ux_end"), ("u_y(W/2, D, H/2), m", (-nu * s / E + e_th) * D, "uy_end"), + ("u_z(W/2, D/2, H), m", (-nu * s / E + e_th) * H, "uz_end")] + + +def heat_checks(m): + """Closed forms for the block with a uniform source q between the sink faces x = 0 / x = W (other faces adiabatic, so the problem is one-dimensional): + both sinks T_max = T_ref + q W^2 / (8 kappa) at x = W/2; only x = 0: T_max = T_ref + q W^2 / (2 kappa) at x = W. [(label, expected, key)] or [].""" + th = m["thermal"] + if m["case"] != "block" or not th["heat"]: + return [] + sinks = {s for s, v in th["sinks"].items() if v} + kappa = m["props"][m["background"]]["kappa"] + q = th["q_mWum3"] * 1e15 + W = block_size_m(m)[0] + if kappa <= 0: + return [] + if sinks == {"xmin", "xmax"}: + return [("T(W/2, D/2, H/2), K", th["T_ref"] + q * W * W / (8 * kappa), "T_mid")] + if sinks == {"xmin"}: + return [("T(W, D/2, H/2), K", th["T_ref"] + q * W * W / (2 * kappa), "T_end")] + return [] + + +def particle_heat_estimate(m, power_full_w): + """Plausibility value of the sphere temperature rise: a small isothermal sphere (radius R, power P) in a matrix (kappa) with the heat sink on a surface that + acts like a sphere of radius R_s: dT = P / (4 pi kappa) (1/R - 1/R_s). The cube of half-width a (the outer box) has the capacity radius 0.6607 * 2 a. Valid for a + well-conducting sphere without feedback; the cube-as-sphere substitution makes it an estimate (a few percent).""" + p = m["particle"] + kappa = m["props"][m["background"]]["kappa"] + r, a = p["radius_nm"] * 1e-9, p["outer_factor"] * p["radius_nm"] * 1e-9 + if kappa <= 0 or power_full_w <= 0: + return float("nan") + return power_full_w / (4 * math.pi * kappa) * (1.0 / r - 1.0 / (2 * EQUIV_CUBE * a)) + + +def rename_material(m, old, new): + ft.rename_material(m, old, new) + + +# ===================================================================================================================== job +def job(m, max_gb=None): + j = copy.deepcopy(m) + j["max_gb"] = float(max_gb if max_gb is not None else m.get("max_gb", 8.0)) + return j + + +# ===================================================================================================================== results +def summary_table(res): + return pd.DataFrame([(k, v) for k, v in res.get("scalars", {}).items()], columns=["Größe", "Wert"]) + + +def field_keys(files): + return [k for k in FIELDS if k in files] + + +def _unit_label(npz): + u = str(npz["unit"]) + return "µm" if u == "um" else u + + +# ===================================================================================================================== figures +def _plt(): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + return plt + + +def fig_preview(m): + plt = _plt() + fig, ax = plt.subplots(figsize=(5.2, 4.4)) + if m["case"] == "particle": + p = m["particle"] + r = p["radius_nm"] + h, o = p["half_factor"] * r, p["outer_factor"] * r + ax.add_patch(plt.Rectangle((-o, -o), 2 * o, 2 * o, fc="#e8e8e8", ec="k", lw=1.0)) + ax.add_patch(plt.Rectangle((-h, -h), 2 * h, 2 * h, fc="#f7f7f7", ec="#888", lw=0.8, ls="--")) + ax.add_patch(plt.Circle((0, 0), r, fc="#e0a800", ec="k")) + ax.text(0, 0, m["inclusion"], ha="center", va="center", fontsize=8) + ax.text(-o * 0.97, o * 0.9, "PML (außen)", fontsize=8, color="#555") + ax.text(-h * 0.95, h * 0.85, m["background"], fontsize=8) + ax.annotate("", xy=(-o * 0.5, -o * 0.55), xytext=(-o * 0.5, -o * 0.95), arrowprops=dict(arrowstyle="->", color="#2060c0")) + ax.text(-o * 0.45, -o * 0.8, f"Welle in +z, E ∥ x, λ = {m['optics']['wavelength_nm']:g} nm", fontsize=8, color="#2060c0") + if p["quarter"]: + ax.axvline(0, color="#c03030", lw=1.2) + ax.text(o * 0.02, o * 0.9, "Viertelmodell: x > 0, y > 0 (Schnitt y = 0)", fontsize=7, color="#c03030") + ax.set(xlim=(-o * 1.05, o * 1.05), ylim=(-o * 1.05, o * 1.05), xlabel="x (nm)", ylabel="z (nm)", title="Schnitt y = 0; Wärmesenke T = T_ref an den Außenflächen") + else: + b = m["block"] + W, H = b["W_um"], b["H_um"] + ax.add_patch(plt.Rectangle((0, 0), W, H, fc="#e8e8e8", ec="k")) + col = {"free": "#aaa", "clamped": "#c03030", "symmetry": "#2060c0", "traction": "#208040"} + pos = {"xmin": [(0, 0), (0, H)], "xmax": [(W, 0), (W, H)], "zmin": [(0, 0), (W, 0)], "zmax": [(0, H), (W, H)]} + mid = {"xmin": (0, H / 2), "xmax": (W, H / 2), "zmin": (W / 2, 0), "zmax": (W / 2, H)} + for s, pts in pos.items(): + c = m["mech"]["bc"][s] + lab = {"free": "", "clamped": "fest", "symmetry": "Symm.", "traction": f"σ = {c['value']:g} MPa"}[c["kind"]] + ax.plot(*zip(*pts), color=col[c["kind"]], lw=3) + x, y = mid[s] + dx = {"xmin": -0.02, "xmax": 0.02}.get(s, 0) * W + dy = {"zmin": -0.06, "zmax": 0.04}.get(s, 0) * H + ax.text(x + dx, y + dy, lab + (" · Senke" if m["thermal"]["heat"] and m["thermal"]["sinks"].get(s) else ""), fontsize=8, + ha="right" if s == "xmin" else ("left" if s == "xmax" else "center"), va="center", color=col[c["kind"]]) + ylab = ", ".join(f"y-{'min' if s == 'ymin' else 'max'}: {BC_KINDS[m['mech']['bc'][s]['kind']].split(' ')[0]}" for s in ("ymin", "ymax")) + ax.set(xlim=(-0.25 * W, 1.35 * W), ylim=(-0.25 * H, 1.25 * H), xlabel="x (µm)", ylabel="z (µm)", title=f"Ansicht x–z · {ylab}"[:90]) + ax.set_aspect("equal") + fig.tight_layout() + return fig + + +def _axes(npz): + return {"x": npz["x"], "y": npz["y"], "z": npz["z"]} + + +def slice_of(npz, key, axis, frac): + """(array in plot order, horizontal axis name, vertical axis name, coordinate of the cut): cut perpendicular to ``axis`` at the grid plane nearest to the + fraction ``frac`` of the extent. x-cut -> (y, z), y-cut -> (x, z), z-cut -> (x, y).""" + ax_ = _axes(npz) + c = ax_[axis] + i = int(round(frac * (len(c) - 1))) + f = npz[key] + if axis == "x": + return f[i, :, :].T, "y", "z", float(c[i]) + if axis == "y": + return f[:, i, :].T, "x", "z", float(c[i]) + return f[:, :, i].T, "x", "y", float(c[i]) + + +def fig_slice(npz, key, axis="y", frac=0.5): + """Colour map of a 3D grid field on the plane perpendicular to ``axis`` (NaN outside the mesh is left empty); the sphere's outline for the particle case.""" + plt = _plt() + f, hn, vn, c0 = slice_of(npz, key, axis, frac) + ax_ = _axes(npz) + title, cmap = FIELDS[key] + fig, ax = plt.subplots(figsize=(6.2, 5.0)) + full = npz[key] + sym = key in SYMMETRIC_FIELDS + vmax = float(np.nanmax(np.abs(full))) if np.isfinite(full).any() else 1.0 + kw = dict(vmin=-vmax, vmax=vmax) if sym and vmax > 0 else {} + im = ax.pcolormesh(ax_[hn], ax_[vn], f, cmap=cmap, shading="auto", **kw) + fig.colorbar(im, ax=ax, label=title) + unit = _unit_label(npz) + ax.set(xlabel=f"{hn} ({unit})", ylabel=f"{vn} ({unit})", title=f"{title} · Schnitt {axis} = {c0:.4g} {unit}") + ax.set_aspect("equal") + r = float(npz["sphere_r"]) if "sphere_r" in npz.files else 0.0 + if r > 0 and abs(c0) < r: + rr = math.sqrt(r * r - c0 * c0) + t = np.linspace(0, 2 * np.pi, 200) + ax.plot(rr * np.cos(t), rr * np.sin(t), "w-", lw=0.8, alpha=0.85) # a plane cut of a sphere about the origin is a circle about the origin + fig.tight_layout() + return fig + + +def fig_line(npz, key, axis="x", fa=0.5, fb=0.5): + """Values along ``axis`` through the grid point nearest to the fractions (fa, fb) of the two other axes (in the order x, y, z without ``axis``).""" + plt = _plt() + ax_ = _axes(npz) + others = [a for a in "xyz" if a != axis] + ia = int(round(fa * (len(ax_[others[0]]) - 1))) + ib = int(round(fb * (len(ax_[others[1]]) - 1))) + f = npz[key] + idx = {others[0]: ia, others[1]: ib} + sl = tuple(slice(None) if a == axis else idx[a] for a in "xyz") + fig, ax = plt.subplots(figsize=(5.6, 3.4)) + ax.plot(ax_[axis], f[sl]) + unit = _unit_label(npz) + ax.set_xlabel(f"{axis} ({unit}) bei {others[0]} = {ax_[others[0]][ia]:.4g}, {others[1]} = {ax_[others[1]][ib]:.4g}") + ax.set_ylabel(FIELDS[key][0]) + ax.grid(alpha=0.3) + fig.tight_layout() + return fig + + +def fig_deformed(npz, axis, frac, scale): + """Sample grid of the cut plane before (grey) and after (red) the displacement, in-plane components times ``scale``.""" + plt = _plt() + ax_ = _axes(npz) + ux, hn, vn, c0 = slice_of(npz, "u" + {"x": "y", "y": "x", "z": "x"}[axis], axis, frac) + uv, _, _, _ = slice_of(npz, "u" + {"x": "z", "y": "z", "z": "y"}[axis], axis, frac) + H, V = np.meshgrid(ax_[hn], ax_[vn]) + # the stored displacements are in nm, the axes in the unit of the grid + conv = 1.0 / (1.0 if str(npz["unit"]) == "nm" else 1e3) + Hd, Vd = H + scale * ux * conv, V + scale * uv * conv + fig, ax = plt.subplots(figsize=(6.2, 5.0)) + step = max(1, len(ax_[hn]) // 24) + stepv = max(1, len(ax_[vn]) // 24) + for arrs, col, lw in (((H, V), "#bbbbbb", 0.5), ((Hd, Vd), "#c03030", 0.6)): + a, b = arrs + for j in range(0, a.shape[0], stepv): + ax.plot(a[j, :], b[j, :], color=col, lw=lw) + for i in range(0, a.shape[1], step): + ax.plot(a[:, i], b[:, i], color=col, lw=lw) + unit = _unit_label(npz) + ax.set(xlabel=f"{hn} ({unit})", ylabel=f"{vn} ({unit})", title=f"Verformtes Raster, Schnitt {axis} = {c0:.4g} {unit} (Verschiebung × {scale:g})") + ax.set_aspect("equal") + fig.tight_layout() + return fig + + +def fig_history(history): + return ft.fig_history(history) diff --git a/fem_gui/fem_thermo3d_app.py b/fem_gui/fem_thermo3d_app.py new file mode 100644 index 0000000..2f90073 --- /dev/null +++ b/fem_gui/fem_thermo3d_app.py @@ -0,0 +1,443 @@ +"""Heat and mechanics in 3D in the FEM model builder (Streamlit), hp-FEM 0.5. Called from fem_thermo_app.py (choice 3D): ``render_thermo3d(ctx)``. + +Sphere in a PML box: optics -> absorbed power -> temperature (Thermal3D / ThermoOptical3D) -> thermal stress (Elasticity3D); box: heat conduction with a +volumetric source and mechanics with boundary conditions per face. Models, figures: fem_thermo3d.py; worker: fem_thermo3d_worker.py. +""" +from __future__ import annotations + +import copy +import json +import subprocess +import time +from pathlib import Path + +import numpy as np +import pandas as pd +import streamlit as st + +import fem_run as fr +import fem_thermo as ft +import fem_thermo3d as t3 +import fem_ui as ui + +S = st.session_state +GB = 1024.0**3 + +INFO = """ +**Was gerechnet wird.** Zwei Fälle, dreidimensional (Ergebnisse in W, J, K, nm, MPa): + +1. **Kugel: Optik → Wärme → Spannung.** Eine ebene Welle (E längs x, Ausbreitung längs +z) trifft eine Kugel in einer verlustfreien Matrix (`box_with_ball`, PML). + Aus dem Feld folgt die absorbierte Leistung, daraus die Temperatur (`Thermal3D`, Wärmesenke T = T_ref an den Außenflächen der Box). **Selbstkonsistent** folgt die + Permittivität der Temperatur, ε(T) = ε + (dε/dT)(T − T_ref), und die Optik wird neu gerechnet, bis sich die Temperatur nicht mehr ändert (`ThermoOptical3D`). Optional + folgt die **Wärmespannung** (`Elasticity3D`; Wärmeausdehnung α je Material, Schrumpfung der Kugel; Außenflächen eingespannt oder frei). Mit dem **Viertelmodell** + (x > 0, y > 0; Spiegelsymmetrie der Welle) rechnet die App ein Viertel des Gebiets, Leistung und Energie werden mit 4 multipliziert und die Felder gespiegelt. +2. **Quader: Wärmeleitung und Mechanik.** Quader [0, W] × [0, D] × [0, H]: Randbedingungen je Fläche (frei, eingespannt, Symmetrie, Zug/Druck), Temperaturänderung und + Schrumpfung (linear in z) oder eine **Wärmequelle** (gleichmäßig, mW/µm³) mit Wärmesenken auf gewählten Flächen (`Thermal3D`, die übrigen Flächen adiabatisch); + das berechnete Temperaturfeld treibt dann die Wärmeausdehnung. + +**Prüfungen.** Quader mit Symmetrieebenen x = 0, y = 0, z = 0 und Zug auf x = W (oder frei) bei gleichmäßiger Temperatur und Schrumpfung: die Verschiebungen werden mit der +geschlossenen Lösung verglichen (die Dehnungen sind gleichmäßig, die Lösung ist in 3D exakt; gemessen bis 1e-13 relativ). Wärmequelle zwischen den Senken x = 0 und x = W: +T_max = T_ref + qW²/(8κ), nur bei x = 0: qW²/(2κ) (eindimensional, exakt; gemessen bis 1e-12 relativ). Kugel ohne Rückkopplung: der Temperaturanstieg im Mittelpunkt wird mit der +Schätzung ΔT ≈ P/(4πκ)·(1/R − 1/R_s) verglichen (R_s = 0,6607·2a, die Kapazität des Würfels der Halbbreite a); das ist eine Näherung (gut leitende Kugel, Würfel +als Kugel ersetzt) und stimmt auf wenige Prozent. + +**Grenzen, die man kennen muss.** +- **3D kostet.** Die Bibliothek im Wheel hat nur den direkten Löser SparseLU (ein Thread). Die App zeigt vor jedem Lauf die Schätzung (Zellen, Unbekannte, Speicher, Zeit) und der Worker + bricht ab, wenn die Schätzung die eingestellte Speichergrenze überschreitet. Die Zeit der Mechanik ist eine grobe Faustformel aus Messungen am Quader (die Kugel war etwa dreimal + schneller als geschätzt). Selbstkonsistent löst jede Iteration die Optik neu: bei 10 790 Unbekannten rund 65 s für 5 Iterationen. +- **Der Rand bestimmt die Temperatur.** Die Senke sitzt an den Außenflächen der Box (die PML-Schicht gehört thermisch und mechanisch zum Gebiet); die Temperatur gilt für genau dieses + Gebiet und keine Aussage über eine Kugel im unendlichen Raum oder auf einem Substrat. (In 3D wächst der Anstieg einer Punktquelle nicht über alle Grenzen, hängt aber vom Senkenabstand ab.) +- **Netz und PML.** Das Standardnetz (1 Zelle je Radius, p = 2) ist grob; die Bibliothek meldet dann eine unteraufgelöste PML (Protokoll). Leistung und Temperatur ändern sich mit dem Netz; + die Konvergenz muss der Nutzer prüfen (Zellen je Radius oder p erhöhen). +- **Nur stationär.** Keine Zeitabhängigkeit, keine Konvektion, keine Strahlung; Wärmeleitfähigkeit und Elastizität hängen nicht von T ab. Die Optik rechnet auf dem unverformten Netz. +- **Wärmedehnung in 3D** wirkt in allen drei Richtungen (α(T − T_ref) I); Von Mises aus dem vollen Spannungstensor. +- **Felder** werden auf einem regelmäßigen Raster der Zellmitten ausgewertet (außerhalb des Netzes leer); Maximalwerte sind Rasterwerte und können Spitzen verfehlen. Spannungen sind Zellwerte der + Lösung (unstetig über Materialgrenzen). Das optische Feld in der PML ist nicht physikalisch. +- **Materialwerte.** κ, E, ν, α sind grobe Richtwerte; dε/dT der Vorlage ist ein Beispielwert, kein Messwert. Fluide haben keine Schubsteifigkeit (Platzhalterwerte). +- **Schrumpfung der Kugel** wird an den Quadraturpunkten ausgewertet (die Kugeloberfläche nur näherungsweise). +- **Nicht validiert** ist die Kette gegen Literaturwerte für konkrete Partikel (geprüft sind die Bausteine gegen geschlossene Lösungen und die Schätzung oben); in der Bibliothek weicht die absorbierte + Leistung zwischen `absorbed_power_by_tag` und der Lastbilanz bei grobem Netz um etwa 2·10⁻³ ab. +""" + + +def _init(): + if "th3_model" in S: + return + S.th3_model = copy.deepcopy(t3.default_model()) + S.th3_ver, S.th3_proc, S.th3_dir, S.th3_msg, S.th3_est = 0, None, None, None, None + + +def _bump(): + S.th3_ver += 1 + S.th3_est = None + + +def _num(col, label, key, value, step=0.1, lo=-1e9, hi=1e9, fmt="%.5g", help=None): + return float(col.number_input(label, float(lo), float(hi), float(value), float(step), key=key, format=fmt, help=help)) + + +def run_estimate(py, repo, folder, jb, threads=0, timeout=300): + """Mesh and memory estimate from the library (no solve): dict as printed by the worker, or {'error': ...}.""" + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + (folder / "job.json").write_text(json.dumps(jb), encoding="utf-8") + try: + r = subprocess.run([str(py), str(fr.HERE / "fem_thermo3d_worker.py"), str(folder), "estimate"], cwd=fr._cwd(repo, folder), + env=fr.worker_env(repo, threads), capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return {"error": "Zeitüberschreitung beim Vernetzen."} + for line in r.stdout.splitlines(): + if line.startswith("ESTIMATE"): + return json.loads(line[len("ESTIMATE"):]) + txt = (r.stdout + r.stderr).strip() + return {"error": txt.splitlines()[-1] if txt else "keine Ausgabe"} + + +def render_thermo3d(ctx): + """ctx: py, repo, work (Path), threads, lib, FEATS.""" + _init() + work = Path(ctx["work"]) / "thermo3d" + st.title("FEM-Modellwerkstatt: Wärme und Mechanik (3D)") + st.caption("Kugel: absorbierte Leistung → Temperatur (auch selbstkonsistent mit ε(T)) → Wärmespannung; Quader: Wärmeleitung und Mechanik. " + "hp-FEM: Scattering3D, Thermal3D, ThermoOptical3D, Elasticity3D. 3D ist speicher- und zeitintensiv: vor dem Rechnen die Schätzung ansehen.") + if S.th3_proc is not None: + return _running() + if not (ctx["FEATS"].get("thermo3d") or ctx["lib"].get("error")): + st.warning("Das eingestellte Python hat kein hpfem mit Thermal3D, ThermoOptical3D und Elasticity3D. Anzeigen geht trotzdem.") + t1, t2, t3_, t4 = st.tabs(["1 Modell", "2 Rechnung", "3 Ergebnisse", "4 Info"]) + with t1: + _tab_model() + with t2: + _tab_run(ctx, work) + with t3_: + _tab_results(work) + with t4: + st.markdown(INFO) + + +# ===================================================================================================================== model tab +def _props_editor(m, ver, names, particle): + for n in names: + p = m["props"].setdefault(n, ft.default_props(m["materials"][n])) + with st.expander(f"Wärme- und Elastizitätsdaten: {n}", expanded=False): + c = st.columns(4) + p["kappa"] = _num(c[0], "κ (W/(m K))", f"t3_k_{ver}_{n}", p["kappa"], 1.0, 0.0, 1e4, "%.5g", "Wärmeleitfähigkeit") + p["E_GPa"] = _num(c[1], "E (GPa)", f"t3_E_{ver}_{n}", p["E_GPa"], 5.0, 0.0001, 2000.0, "%.5g", "Elastizitätsmodul") + p["nu"] = _num(c[2], "ν", f"t3_nu_{ver}_{n}", p["nu"], 0.01, -0.99, 0.499, "%.4g", "Querkontraktionszahl") + p["alpha"] = _num(c[3], "α (10⁻⁶/K)", f"t3_al_{ver}_{n}", p["alpha"], 1.0, -100.0, 500.0, "%.5g", "Linearer Wärmeausdehnungskoeffizient") + if particle: + c = st.columns(2) + p["deps_re"] = _num(c[0], "Re dε/dT (1/K)", f"t3_der_{ver}_{n}", p["deps_re"], 1e-3, -10.0, 10.0, "%.4g", + "Thermo-optischer Koeffizient: ε(T) = ε + (dε/dT)(T − T_ref). Nur mit „selbstkonsistent“ wirksam.") + p["deps_im"] = _num(c[1], "Im dε/dT (1/K)", f"t3_dei_{ver}_{n}", p["deps_im"], 1e-3, -10.0, 10.0, "%.4g", + "Änderung der Absorption mit der Temperatur (Im ε > 0 ist Verlust).") + spec = m["materials"][n] + if spec.get("type") == "library" and spec.get("name") in ft.PROPS and st.button("Richtwerte der Bibliothek laden", key=f"t3_def_{ver}_{n}"): + m["props"][n] = ft.default_props(spec) + _bump() + st.rerun() + + +def _bc_editor(m, ver): + mech, th = m["mech"], m["thermal"] + st.markdown("**Randbedingungen je Fläche**") + for s in t3.SIDE_TAGS: + c = st.columns([2, 3, 2, 2]) if th["heat"] else st.columns([2, 3, 2]) + bc = mech["bc"][s] + c[0].markdown(f"
{t3.SIDES[s]}
", unsafe_allow_html=True) + kinds = list(t3.BC_KINDS) + bc["kind"] = c[1].selectbox("Art", kinds, index=kinds.index(bc["kind"]) if bc["kind"] in kinds else 0, format_func=t3.BC_KINDS.get, key=f"t3_bck_{ver}_{s}") + if bc["kind"] == "traction": + bc["value"] = _num(c[2], "σ (MPa)", f"t3_bcv_{ver}_{s}", bc["value"], 10.0, -1e6, 1e6, "%.5g", "Normalspannung auf der Fläche; positiv = Zug (nach außen), negativ = Druck.") + if th["heat"]: + th["sinks"][s] = c[-1].checkbox("Wärmesenke (T_ref)", value=bool(th["sinks"][s]), key=f"t3_sink_{ver}_{s}", + help="Feste Temperatur T_ref auf dieser Fläche; nicht gewählte Flächen sind adiabatisch.") + + +def _tab_model(): + m, ver = S.th3_model, S.th3_ver + t3.normalise(m) + left, right = st.columns([6, 5]) + with left: + presets = t3.presets() + c = st.columns([3, 1]) + pick = c[0].selectbox("Vorlage", ["– auswählen –"] + list(presets), key="t3_preset") + if c[1].button("Laden", key="t3_preset_load", disabled=pick.startswith("–")): + S.th3_model = copy.deepcopy(presets[pick]) + _bump() + st.rerun() + m["name"] = st.text_input("Name", value=m["name"], key=f"t3_name_{ver}") + cases = list(t3.CASES) + new_case = st.radio("Fall", cases, index=cases.index(m["case"]) if m["case"] in cases else 0, format_func=t3.CASES.get, key=f"t3_case_{ver}", horizontal=True) + if new_case != m["case"]: + fresh = copy.deepcopy(presets[next(k for k, v in presets.items() if v["case"] == new_case)]) + fresh["name"] = m["name"] + S.th3_model = fresh + _bump() + st.rerun() + particle = m["case"] == "particle" + lam0 = float(m["optics"]["wavelength_nm"]) if particle else 500.0 + st.subheader("Materialien" + (" (optische Daten)" if particle else "")) + ui.material_editor(m, ver, lam0, t3.used_materials(m), t3.rename_material, _bump, prefix="t3_") + names = list(m["materials"]) + if particle: + c = st.columns(2) + m["inclusion"] = c[0].selectbox("Kugel", names, index=names.index(m["inclusion"]) if m["inclusion"] in names else 0, key=f"t3_inc_{ver}") + m["background"] = c[1].selectbox("Matrix", names, index=names.index(m["background"]) if m["background"] in names else 0, key=f"t3_bg_{ver}", + help="Muss verlustfrei sein (Im ε = 0): in ihr läuft die einfallende ebene Welle.") + else: + m["background"] = m["inclusion"] = st.selectbox("Material", names, index=names.index(m["background"]) if m["background"] in names else 0, key=f"t3_bg_{ver}") + used = t3.used_materials(m) + _props_editor(m, ver, sorted(used, key=names.index) if all(n in names for n in used) else [], particle) + th, mech = m["thermal"], m["mech"] + if particle: + st.subheader("Optik und Gebiet") + c = st.columns(3) + m["optics"]["wavelength_nm"] = _num(c[0], "Wellenlänge (nm)", f"t3_lam_{ver}", m["optics"]["wavelength_nm"], 10.0, 100.0, 20000.0) + m["optics"]["E0_MVm"] = _num(c[1], "Feldamplitude E₀ (MV/m)", f"t3_e0_{ver}", m["optics"]["E0_MVm"], 0.1, 1e-6, 1e4, + help="Amplitude der einfallenden ebenen Welle in der Matrix, E ∥ x, Ausbreitung in +z.") + inten = ft.intensity_W_m2(m) + c[2].metric("Intensität", f"{inten * 1e-4 * 1e-6:.3g} MW/cm²" if inten == inten else "–", help="½ n ε₀ c E₀² in der Matrix") + p = m["particle"] + c = st.columns(4) + p["radius_nm"] = _num(c[0], "Radius (nm)", f"t3_r_{ver}", p["radius_nm"], 5.0, 1.0, 5000.0) + p["half_factor"] = int(c[1].number_input("Innenbreite / Radius", 2, 20, int(p["half_factor"]), key=f"t3_hf_{ver}", help="Halbbreite des physikalischen Gebiets in Radien (ganzzahlig).")) + p["outer_factor"] = int(c[2].number_input("Außenbreite / Radius", 3, 40, int(p["outer_factor"]), key=f"t3_of_{ver}", + help="Halbbreite der Box in Radien. Der Rest bis zur Innenbreite ist die PML-Schicht; hier sitzt auch die Wärmesenke (T = T_ref).")) + p["n"] = int(c[3].number_input("Zellen je Radius", 1, 6, int(p["n"]), key=f"t3_n_{ver}", help="Mehr Zellen: genauer, aber der Speicher wächst steil (siehe Schätzung im Reiter 2).")) + p["quarter"] = st.checkbox("Viertelmodell (x > 0, y > 0, Spiegelsymmetrie)", value=bool(p["quarter"]), key=f"t3_q_{ver}", + help="Rechnet ein Viertel des Gebiets (x = 0 ideal leitend für die Optik, y = 0 magnetisch; Symmetrieebenen für Wärme und Mechanik); Leistung und Energie ×4.") + st.subheader("Wärme") + c = st.columns(2) + th["T_ref"] = _num(c[0], "Temperatur der Wärmesenke / Referenz T_ref (K)", f"t3_tref_{ver}", th["T_ref"], 10.0, 1.0, 5000.0, + help="Die Außenflächen der Box werden auf diese Temperatur gesetzt; sie ist auch die Referenz für ε(T) und die Wärmedehnung.") + th["selfconsistent"] = c[1].checkbox("selbstkonsistent (ε hängt von T ab)", value=bool(th["selfconsistent"]), key=f"t3_sc_{ver}", + help="ThermoOptical3D: Festpunktiteration Optik ↔ Wärme mit den dε/dT oben. Jede Iteration löst die Optik neu (Minuten).") + if th["selfconsistent"]: + c = st.columns(3) + th["relaxation"] = _num(c[0], "Relaxation", f"t3_rel_{ver}", th["relaxation"], 0.1, 0.01, 1.0, "%.3g", "1 = volle Schritte; kleiner dämpft bei starker Kopplung.") + th["tolerance"] = _num(c[1], "Toleranz (K)", f"t3_tol_{ver}", th["tolerance"], 1e-3, 1e-9, 10.0, "%.3g") + th["max_iter"] = int(c[2].number_input("max. Iterationen", 1, 100, int(th["max_iter"]), key=f"t3_mi_{ver}")) + st.subheader("Mechanik") + mech["on"] = st.checkbox("Wärmespannung berechnen (Elasticity3D)", value=bool(mech["on"]), key=f"t3_mon_{ver}") + if mech["on"]: + c = st.columns(2) + walls = list(t3.WALL_BC) + mech["wall"] = c[0].radio("Außenflächen der Box", walls, index=walls.index(mech["wall"]) if mech["wall"] in walls else 0, format_func=t3.WALL_BC.get, key=f"t3_wall_{ver}") + mech["shrink_a_pct"] = _num(c[1], "Schrumpfung der Kugel (%)", f"t3_shr_{ver}", mech["shrink_a_pct"], 0.1, -50.0, 50.0, "%.4g", + "Isotrope Eigendehnung −s in der Kugel (positiv = Schrumpfung), zusätzlich zur Wärmedehnung.") + else: + b = m["block"] + st.subheader("Geometrie") + c = st.columns(3) + b["W_um"] = _num(c[0], "Breite W (µm)", f"t3_w_{ver}", b["W_um"], 0.5, 0.001, 1e4) + b["D_um"] = _num(c[1], "Tiefe D (µm)", f"t3_d_{ver}", b["D_um"], 0.5, 0.001, 1e4) + b["H_um"] = _num(c[2], "Höhe H (µm)", f"t3_h_{ver}", b["H_um"], 0.5, 0.001, 1e4) + c = st.columns(3) + b["nx"] = int(c[0].number_input("Zellen in x", 1, 40, int(b["nx"]), key=f"t3_nx_{ver}")) + b["ny"] = int(c[1].number_input("Zellen in y", 1, 40, int(b["ny"]), key=f"t3_ny_{ver}")) + b["nz"] = int(c[2].number_input("Zellen in z", 1, 40, int(b["nz"]), key=f"t3_nz_{ver}")) + mech["on"] = True + st.subheader("Wärme") + c = st.columns(3) + th["T_ref"] = _num(c[0], "Referenztemperatur T_ref (K)", f"t3_tref_{ver}", th["T_ref"], 10.0, 1.0, 5000.0) + th["heat"] = c[1].checkbox("Wärmequelle und Senken (Thermal3D)", value=bool(th["heat"]), key=f"t3_heat_{ver}", + help="Gleichmäßige Wärmequelle q im Quader; die gewählten Flächen (Reiter Mechanik) sind Senken bei T_ref, die übrigen adiabatisch. Das berechnete Temperaturfeld treibt die Wärmedehnung.") + if th["heat"]: + th["q_mWum3"] = _num(c[2], "Wärmequelle q (mW/µm³)", f"t3_q_{ver}", th["q_mWum3"], 0.1, -1e6, 1e6, "%.5g", "1 mW/µm³ = 10¹⁵ W/m³.") + st.subheader("Mechanik") + _bc_editor(m, ver) + if not th["heat"]: + c = st.columns(2) + mech["dT_a"] = _num(c[0], "ΔT bei z = 0 (K)", f"t3_dta_{ver}", mech["dT_a"], 10.0, -2000.0, 2000.0, help="Temperaturänderung gegenüber T_ref, linear in z interpoliert.") + mech["dT_b"] = _num(c[1], "ΔT bei z = H (K)", f"t3_dtb_{ver}", mech["dT_b"], 10.0, -2000.0, 2000.0) + c = st.columns(2) + mech["shrink_a_pct"] = _num(c[0], "Schrumpfung bei z = 0 (%)", f"t3_sha_{ver}", mech["shrink_a_pct"], 0.1, -50.0, 50.0, "%.4g", "Isotrope Eigendehnung −s (positiv = Schrumpfung), linear in z.") + mech["shrink_b_pct"] = _num(c[1], "Schrumpfung bei z = H (%)", f"t3_shb_{ver}", mech["shrink_b_pct"], 0.1, -50.0, 50.0, "%.4g") + with right: + for lvl, text in t3.validate(m): + (st.error if lvl == "error" else st.warning)(text) + try: + ui.show_fig(t3.fig_preview(m), "geometrie3d.png", f"t3_prev_dl_{ver}") + except Exception as exc: + st.error(f"Vorschau nicht möglich: {exc}") + + +# ===================================================================================================================== run tab +def _estimate_box(est, m): + if est is None: + return + if "error" in est: + st.error(f"Netz oder Schätzung nicht möglich: {est['error']}") + return + parts = [f"**{est['cells']} Zellen, {est['h1_dofs']} H1-Unbekannte**"] + if "nd_dofs" in est: + parts.append(f"Optik {est['nd_dofs']} Unbekannte, {est['optics_text']}, Zeit je Optik-Lauf grob {est['optics_seconds']:.0f} s") + if m["case"] == "block" or m["mech"]["on"]: + parts.append(f"Mechanik ≈ {est['mech_dofs']} Unbekannte, grob {est['mech_seconds']:.0f} s und {est['mech_bytes'] / GB:.2f} GB (Faustformel, eher zu hoch)") + st.info(" · ".join(parts) + f" · Spitzenspeicher ≈ {est['human']}") + gb = est["bytes"] / GB + avail = t3.available_gb() + if gb > float(m["max_gb"]): + st.error(f"Die Schätzung ({gb:.1f} GB) liegt über der eingestellten Grenze von {m['max_gb']:g} GB: der Worker würde abbrechen. Netz oder Ordnung verkleinern oder die Grenze anheben.") + elif avail is not None and gb > 0.6 * avail: + st.warning(f"Die Schätzung ({gb:.1f} GB) beansprucht mehr als 60 % des freien Hauptspeichers ({avail:.0f} GB); andere Prozesse könnten gestört werden.") + + +def _tab_run(ctx, work): + m, ver = S.th3_model, S.th3_ver + t3.normalise(m) + st.subheader("Ordnung, Ausgabe und Speichergrenze") + c = st.columns(3) + m["order"] = int(c[0].number_input("Polynomordnung p", 1, 6, int(m["order"]), key=f"t3_p_{ver}")) + m["grid"] = int(c[1].number_input("Auflösung der Feldschnitte (Punkte entlang der längsten Achse)", 12, 120, int(m["grid"]), 6, key=f"t3_grid_{ver}", + help="Die Felder werden auf einem regelmäßigen 3D-Raster ausgewertet (Zellmitten). Das Raster ändert die Rechnung nicht.")) + m["max_gb"] = float(c[2].number_input("Speichergrenze (GB)", 0.1, 4096.0, float(m["max_gb"]), 1.0, key=f"t3_maxgb_{ver}", + help="Der Worker bricht vor dem Rechnen ab, wenn die Schätzung darüber liegt.")) + errs = [t for lvl, t in t3.validate(m) if lvl == "error"] + for e in errs: + st.error(e) + est_work = work / "estimate" + if st.button("Netz prüfen und Speicher schätzen", key="t3_est", disabled=bool(errs)): + with st.spinner("Vernetze …"): + S.th3_est = run_estimate(ctx["py"], ctx["repo"], est_work, t3.job(m), int(ctx["threads"])) + _estimate_box(S.get("th3_est"), m) + if st.button("Rechnen", type="primary", key="t3_run", disabled=bool(errs)): + try: + work.mkdir(parents=True, exist_ok=True) + (work / "job.json").write_text(json.dumps(t3.job(m), ensure_ascii=False), encoding="utf-8") + S.th3_proc = fr.start_worker(ctx["py"], ctx["repo"], work, int(ctx["threads"]), script="fem_thermo3d_worker.py") + S.th3_dir, S.th3_cancel = str(work), False + S.th3_run_model = copy.deepcopy(m) + st.rerun() + except Exception as exc: + st.error(f"Start fehlgeschlagen: {exc}") + if S.get("th3_msg"): + (st.success if S.th3_msg[0] == "ok" else st.error)(S.th3_msg[1] + (" Die Ergebnisse stehen im Reiter 3." if S.th3_msg[0] == "ok" else "")) + if (work / "log.txt").is_file(): + with st.expander("Protokoll der letzten Rechnung"): + st.code(fr.read_log(work, tail=40)) + + +def _running(): + proc, folder = S.th3_proc, Path(S.th3_dir) + log = fr.read_log(folder) + st.subheader("Rechnung läuft …") + if proc.poll() is None: + frac, label = fr.progress_info(log) + st.progress(frac, text=label) + st.code("\n".join(log.splitlines()[-10:]) or "(noch keine Ausgabe)") + if S.get("th3_cancel"): + st.info("Abbruch angefordert: die Rechnung hält nach dem laufenden Schritt an (ein einzelner Löserlauf lässt sich nicht unterbrechen).") + elif st.button("Abbrechen", key="t3_cancel_btn"): + fr.request_cancel(folder) + S.th3_cancel = True + st.rerun() + time.sleep(1.5) + st.rerun() + else: + flags = fr.log_flags(log) + S.th3_proc = None + ok = proc.returncode == 0 and not flags["errors"] + S.th3_msg = ("ok", "Abgebrochen." if flags["cancelled"] else "Fertig.") if ok else ("error", f"Beendet mit Code {proc.returncode}: " + "; ".join(flags["errors"][:3])) + st.rerun() + + +# ===================================================================================================================== results +def _fmt(v): + if isinstance(v, (int, np.integer)): + return str(v) + if isinstance(v, float): + return f"{v:.5g}" + return str(v) + + +def _tab_results(work): + res_file = work / "results.json" + if not res_file.is_file(): + st.info("Noch keine Ergebnisse: im Reiter 2 rechnen.") + return + res = json.loads(res_file.read_text(encoding="utf-8")) + if res.get("error"): + st.error(res["error"]) + return + meta = res["meta"] + model = S.get("th3_run_model") or S.th3_model + st.caption(f"{meta.get('name', '')} · {meta.get('cells')} Zellen, p = {meta.get('order')} · hpfem {meta.get('hpfem', '?')} · Start {meta.get('started', '')}" + + (f" · {meta['total_s']:.1f} s" if "total_s" in meta else "")) + if res.get("cancelled"): + st.warning("Die Rechnung wurde abgebrochen.") + return + if not res.get("finished"): + st.info("Die Rechnung ist noch nicht fertig.") + return + npz_path = work / "fields3d.npz" + npz = np.load(npz_path) if npz_path.is_file() else None + if res.get("converged") is False: + st.warning("Die thermo-optische Schleife hat die Toleranz nicht erreicht: Relaxation verkleinern oder mehr Iterationen zulassen.") + sub = st.tabs(["Kennzahlen und Prüfung", "Schnitte", "Linien", "Verformung", "Konvergenz"]) + with sub[0]: + sc, probes = res["scalars"], res.get("probes", {}) + ui.table_show(pd.DataFrame([(k, _fmt(v)) for k, v in sc.items()], columns=["Größe", "Wert"])) + if model["case"] == "particle" and not model["thermal"]["selfconsistent"] and "Absorbierte Leistung (W)" in sc and "T_center" in probes: + est = t3.particle_heat_estimate(model, float(sc["Absorbierte Leistung (W)"])) + got = probes["T_center"] - float(model["thermal"]["T_ref"]) + st.markdown(f"**Prüfung Schätzung:** ΔT ≈ P/(4πκ)·(1/R − 1/R_s) = {est:.4g} K gegen {got:.4g} K im Kugelmittelpunkt aus der FEM-Rechnung " + f"(Abweichung {100 * (got - est) / est:+.1f} %). Näherung für eine gut leitende Kugel; das Netz ({meta.get('cells')} Zellen) beeinflusst beide Werte.") + rows = [] + for lab, exp, key in t3.analytic_checks(model) + t3.heat_checks(model): + if key in probes: + got = probes[key] + rows.append((lab, f"{got:.6g}", f"{exp:.6g}", f"{abs(got - exp) / abs(exp):.2e}" if exp else "–")) + if rows: + st.markdown("**Prüfung gegen die geschlossene Lösung:**") + ui.table_show(pd.DataFrame(rows, columns=["Größe", "FEM", "geschlossen", "rel. Abweichung"])) + elif model["case"] == "block": + st.caption("Für diese Randbedingungen gibt es hier keine geschlossene Vergleichslösung (sie gilt für Symmetrieebenen x = 0, y = 0, z = 0, Zug nur auf x = W, gleichmäßige Temperatur; " + "Wärmequelle: Senken auf x = 0 und x = W oder nur auf x = 0).") + if model["case"] == "particle": + st.caption("Leistung und Energie für das ganze Gebiet (beim Viertelmodell ×4). Die Box endet an der Wärmesenke: die Temperatur gilt nur für diesen Abstand.") + if npz is None: + for t in sub[1:4]: + with t: + st.info("Keine Felddaten.") + else: + keys = t3.field_keys(npz.files) + with sub[1]: + c = st.columns(3) + k = c[0].selectbox("Feld", keys, format_func=lambda k: t3.FIELDS[k][0], key="t3_field") + axis = c[1].radio("Schnitt senkrecht zu", ["x", "y", "z"], index=1, horizontal=True, key="t3_axis") + frac = c[2].slider("Lage (Anteil der Ausdehnung)", 0.0, 1.0, 0.5, 0.01, key="t3_frac") + ui.show_fig(t3.fig_slice(npz, k, axis, frac), f"{k}_{axis}.png", "t3_dl_field") + st.caption("Raster der Zellmitten, außerhalb des Netzes leer. Spannungen sind Zellwerte der Lösung (unstetig über Materialgrenzen). " + + ("Die PML-Schicht gehört zum Gebiet; das optische Feld dort ist nicht physikalisch." if model["case"] == "particle" else "")) + with sub[2]: + c = st.columns(4) + k2 = c[0].selectbox("Feld", keys, format_func=lambda k: t3.FIELDS[k][0], key="t3_line_field") + axis2 = c[1].radio("Richtung", ["x", "y", "z"], index=2, horizontal=True, key="t3_line_axis") + fa = c[2].slider("Lage 1", 0.0, 1.0, 0.5, 0.01, key="t3_line_fa", help="Anteil der Ausdehnung der ersten übrigen Achse (in der Reihenfolge x, y, z)") + fb = c[3].slider("Lage 2", 0.0, 1.0, 0.5, 0.01, key="t3_line_fb", help="Anteil der Ausdehnung der zweiten übrigen Achse") + ui.show_fig(t3.fig_line(npz, k2, axis2, fa, fb), "linie3d.png", "t3_dl_line") + with sub[3]: + if "umag" in npz.files: + c = st.columns(3) + axis3 = c[0].radio("Schnitt senkrecht zu", ["x", "y", "z"], index=1, horizontal=True, key="t3_def_axis") + frac3 = c[1].slider("Lage (Anteil der Ausdehnung)", 0.0, 1.0, 0.5, 0.01, key="t3_def_frac") + span = float(max(np.ptp(npz["x"]), np.ptp(npz["y"]), np.ptp(npz["z"]))) + conv = 1.0 if str(npz["unit"]) == "nm" else 1e-3 + dmax = float(np.nanmax(npz["umag"])) * conv + auto = max(1.0, 0.05 * span / dmax) if dmax > 0 else 1.0 + scale = c[2].number_input("Überhöhung der Verschiebung", 0.0, 1e9, float(f"{auto:.2g}"), format="%.6g", key=f"t3_def_scale_{auto:.3g}", + help="Vorgabe: größte Verschiebung ≈ 5 % der Gebietsgröße. Die Verformung ist winzig (nm) und wird stark überhöht gezeichnet.") + ui.show_fig(t3.fig_deformed(npz, axis3, frac3, scale), "verformt3d.png", "t3_dl_def") + else: + st.info("Ohne Mechanik keine Verformung.") + with sub[4]: + if res.get("history"): + ui.show_fig(t3.fig_history(res["history"]), "konvergenz3d.png", "t3_dl_hist") + ui.table_show(pd.DataFrame({"Iteration": list(range(1, len(res["history"]) + 1)), "größte Temperaturänderung (K)": res["history"]}).round(6)) + st.caption("Größte Temperaturänderung zwischen zwei Iterationen; die erste Zeile enthält den Sprung vom Startfeld (0 K) auf die erste Lösung.") + else: + st.info("Keine Iteration (nicht selbstkonsistent oder nur Mechanik).") + st.download_button("Modell (JSON)", json.dumps(model, indent=1, ensure_ascii=False).encode("utf-8"), file_name="waerme_mechanik_3d_modell.json", + mime="application/json", key="t3_dl_model") diff --git a/fem_gui/fem_thermo3d_worker.py b/fem_gui/fem_thermo3d_worker.py new file mode 100644 index 0000000..7b8c4c9 --- /dev/null +++ b/fem_gui/fem_thermo3d_worker.py @@ -0,0 +1,460 @@ +"""Worker for heat and mechanics in 3D (hp-FEM 0.5): runs in the Python that has hpfem, called by the app. + + python fem_thermo3d_worker.py [estimate] + +Reads /job.json (the model of fem_thermo3d plus ``max_gb``; SI is derived here) and writes /results.json and /fields3d.npz. + +* case ``particle``: ScatteringSetup3D on hpfem.box_with_ball (plane wave along +z, E along x, in the matrix, PML) -> absorbed power load -> Thermal3D + (T = T_ref on the outer faces); with ``selfconsistent`` the loop hpfem.ThermoOptical3D (eps(T) = eps + d eps / dT (T - T_ref)); optional Elasticity3D + (thermal expansion alpha per tag from the temperature, shrinkage inside the sphere; outer faces clamped or free). With ``quarter`` the model x > 0, y > 0 + (x = 0 PEC for the optics, y = 0 natural; heat and elasticity use the symmetry planes) and the power and energy multiplied by 4. +* case ``block``: hpfem.box; optional Thermal3D (uniform volumetric source, sink faces at T_ref, others adiabatic); Elasticity3D with boundary conditions per face, + temperature change (linear along z or the heat solution) and shrinkage (linear along z). + +With ``estimate`` only the mesh is built and the memory estimate is printed (``ESTIMATE{json}``); a run whose estimate exceeds ``max_gb`` stops with ERROR. + +fields3d.npz: x, y, z (cell centres of a regular grid, unit nm for the particle and um for the block), 3D arrays (NaN outside the mesh) of T, Eabs, ux, uy, uz, umag, +sxx, syy, szz, sxy, syz, sxz, svm; sphere_r. Stress in MPa, displacement in nm. For the quarter model the grid is mirrored to the full box (displacement +components and shears with the sign of the mirror). Log lines on stdout: PROGRESS i/n stage, ERROR ..., CANCELLED, DONE. Cancellation: the file /cancel, +checked between the stages (a single solve cannot be interrupted). +""" +from __future__ import annotations + +import json +import math +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import fem_disp as fd # noqa: E402 + +NM, UM = 1e-9, 1e-6 +C0 = 299792458.0 +GB = 1024.0**3 +TAG_SPHERE, TAG_SYM_X, TAG_SYM_Y = 2, 7, 8 +SIDE_TAGS = {"xmin": 1, "xmax": 2, "ymin": 3, "ymax": 4, "zmin": 5, "zmax": 6} +SIDE_NORMAL = {"xmin": (-1.0, 0.0, 0.0), "xmax": (1.0, 0.0, 0.0), "ymin": (0.0, -1.0, 0.0), "ymax": (0.0, 1.0, 0.0), "zmin": (0.0, 0.0, -1.0), "zmax": (0.0, 0.0, 1.0)} +ODD_X, ODD_Y = ("ux", "sxy", "sxz"), ("uy", "sxy", "syz") +FIELD_NAMES = ["T", "Eabs", "ux", "uy", "uz", "umag", "sxx", "syy", "szz", "sxy", "syz", "sxz", "svm"] + + +def say(*a): + print(*a, flush=True) + + +class Cancelled(Exception): + pass + + +def check_cancel(folder): + if (folder / "cancel").exists(): + raise Cancelled() + + +def material_at(job, name, omega): + return fd.dispersive_model(job["materials"][name]).at(omega) + + +def elastic(h, props): + return h.ElasticMaterial(float(props["E_GPa"]) * 1e9, float(props["nu"])) + + +# ---------------------------------------------------------------------------------------------------------------------- meshes +def build_mesh(h, job): + """(mesh, info): SI units; for the quarter model the cut planes x = 0 / y = 0 get the facet tags 7 / 8.""" + if job["case"] == "block": + b = job["block"] + mesh = h.box(int(b["nx"]), int(b["ny"]), int(b["nz"]), [0.0, 0.0, 0.0], [b["W_um"] * UM, b["D_um"] * UM, b["H_um"] * UM]) + return mesh, dict(quarter=False) + p = job["particle"] + r = p["radius_nm"] * NM + hw, outer = p["half_factor"] * r, p["outer_factor"] * r + mesh = h.box_with_ball(int(p["n"]), r, hw, outer, TAG_SPHERE) + quarter = bool(p["quarter"]) + if quarter: + mesh = h.extract(mesh, lambda x: bool(x[0] > 0 and x[1] > 0)) + tol = 1e-9 * r + for f in mesh.boundary_facets: + if mesh.facet_tag(int(f)) != h.NO_TAG: + continue + vs = [mesh.vertex(int(v)) for v in mesh.facet_vertices(int(f))] + if all(abs(v[0]) < tol for v in vs): + mesh.set_facet_tag(int(f), TAG_SYM_X) + elif all(abs(v[1]) < tol for v in vs): + mesh.set_facet_tag(int(f), TAG_SYM_Y) + return mesh, dict(quarter=quarter, r=r, hw=hw, outer=outer) + + +def time_hint(dofs): + """Rough time of one optical solve (SparseLU, one thread): about 70 s at 18 000 unknowns, ~ N^1.7 (as measured for fem_threed).""" + return 70.0 * (max(dofs, 1) / 18264.0) ** 1.7 + + +def estimate(h, job, mesh): + import fem_thermo3d as t3 + + order = int(job["order"]) + h1 = h.DofMap3D(mesh, order) + me = t3.mech_estimate(h1.num_dofs) + est = dict(cells=int(mesh.num_cells), h1_dofs=int(h1.num_dofs), mech_dofs=me["dofs"], mech_seconds=me["seconds"], mech_bytes=int(me["bytes"])) + nbytes = me["bytes"] if (job["case"] == "block" or job["mech"]["on"]) else 0.0 + if job["case"] == "particle": + nd = h.NedelecDofMap3D(mesh, order) + e = h.estimate_memory(nd) + est.update(nd_dofs=int(nd.num_dofs), optics_bytes=int(e.total_bytes), optics_text=e.describe(), optics_seconds=time_hint(nd.num_dofs)) + nbytes = max(nbytes, float(e.total_bytes)) + est["bytes"] = int(nbytes) + est["human"] = h.format_bytes(int(nbytes)) + return est + + +# ---------------------------------------------------------------------------------------------------------------------- optics and heat +def sink_tags(info): + t = SIDE_TAGS + return [t["xmax"], t["ymax"], t["zmin"], t["zmax"]] if info["quarter"] else list(t.values()) + + +def run_optics_heat(h, job, mesh, info, nd, h1, out): + """Returns (temperature coefficients, total E coefficients, omega).""" + pj, optics, th = job["particle"], job["optics"], job["thermal"] + lam = optics["wavelength_nm"] * NM + omega = 2 * math.pi * C0 / lam + k0 = omega / C0 + bg_name, in_name = job["background"], job["inclusion"] + mat_bg, mat_in = material_at(job, bg_name, omega), material_at(job, in_name, omega) + n_bg = math.sqrt(complex(mat_bg.eps_r).real) + hw, outer = info["hw"], info["outer"] + d = outer - hw + prof = h.PmlProfile(3, 1e-8) + s = h.ScatteringSetup3D() + s.omega = omega + s.materials = h.MaterialMap(mat_bg) + s.materials.set(TAG_SPHERE, mat_in) + s.incident = h.plane_wave(np.array([optics["E0_MVm"] * 1e6, 0.0, 0.0], dtype=complex), np.array([0.0, 0.0, n_bg * k0])) + s.formulation = h.Formulation.SCATTERED_FIELD + t = SIDE_TAGS + if info["quarter"]: + s.pml = h.PmlBox3D(np.array([0.0, 0.0, -hw]), np.array([hw, hw, hw]), [0.0, d, 0.0, d, d, d], k0, n_bg, prof) + s.pec_tags = [t["xmax"], t["ymax"], t["zmin"], t["zmax"], TAG_SYM_X] + else: + s.pml = h.PmlBox3D.uniform(np.full(3, -hw), np.full(3, hw), d, k0, n_bg, prof) + s.pec_tags = list(t.values()) + tp = h.ThermalSetup() + tp.background_conductivity = float(job["props"][bg_name]["kappa"]) + tp.conductivity = {TAG_SPHERE: float(job["props"][in_name]["kappa"])} + tref = float(th["T_ref"]) + tp.fixed_temperature = [(tg, tref) for tg in sink_tags(info)] + mult = 4.0 if info["quarter"] else 1.0 + out["scalars"]["Freiheitsgrade Optik (Nédélec)"] = int(nd.num_dofs) + out["scalars"]["Freiheitsgrade Wärme"] = int(h1.num_dofs) + if th["selfconsistent"]: + to = h.ThermoOpticalSetup3D() + to.optical, to.thermal, to.reference_temperature = s, tp, tref + to.relaxation, to.tolerance, to.max_iterations = float(th["relaxation"]), float(th["tolerance"]), int(th["max_iter"]) + coeff = {} + for tag, name in ((0, bg_name), (TAG_SPHERE, in_name)): + c = complex(job["props"][name]["deps_re"], job["props"][name]["deps_im"]) + if c != 0: + coeff[tag] = c + to.thermo_optic = coeff + prob = h.ThermoOptical3D(nd, h1, to) + state = prob.solve() + temp = np.asarray(state.temperature, dtype=complex) + e_tot = np.asarray(prob.total_field(state.solution), dtype=complex) + out["history"] = [float(v) for v in state.history] + out["scalars"]["Schleife konvergiert"] = "ja" if state.converged else "NEIN (Toleranz nicht erreicht)" + out["scalars"]["Iterationen"] = int(state.iterations) + out["scalars"]["Absorbierte Leistung (W)"] = float(state.absorbed_power) * mult + out["converged"] = bool(state.converged) + else: + prob = h.Scattering3D(nd, s) + sol = prob.solve() + e_tot = np.asarray(sol.unknown, dtype=complex) + np.asarray(h.interpolate(nd, s.incident.value), dtype=complex) + ap = h.absorbed_power_by_tag(prob, sol) + load = h.absorbed_power_load(nd, e_tot, omega, s.materials, h1) + temp = np.asarray(h.Thermal3D(h1, tp).solve_load(load), dtype=complex) + out["scalars"]["Absorbierte Leistung (W)"] = float(ap.total) * mult + for tag, w in dict(ap.by_tag).items(): + if tag == TAG_SPHERE: + out["scalars"][" davon in der Kugel (W)"] = float(w) * mult + return temp, e_tot + + +def run_block_heat(h, job, mesh, h1, out): + """Thermal3D of the block: uniform source q, sink faces at T_ref, the others adiabatic. Returns the temperature coefficients.""" + th = job["thermal"] + tp = h.ThermalSetup() + tp.background_conductivity = float(job["props"][job["background"]]["kappa"]) + tp.fixed_temperature = [(SIDE_TAGS[s], float(th["T_ref"])) for s, v in th["sinks"].items() if v] + q = float(th["q_mWum3"]) * 1e15 + qc = np.asarray(h.interpolate(h1, lambda x: complex(q)), dtype=complex) + prob = h.Thermal3D(h1, tp) + t = np.asarray(prob.solve(qc), dtype=complex) + out["scalars"]["Freiheitsgrade Wärme"] = int(h1.num_dofs) + out["scalars"]["Wärmeleistung im Quader (W)"] = float(prob.total_power(qc)) + return t + + +# ---------------------------------------------------------------------------------------------------------------------- mechanics +def side_conditions(h, job): + """(displacement conditions, traction conditions, any_fixed) from the per-face boundary conditions of the block.""" + disp, trac, fixed = [], [], False + for side, tag in SIDE_TAGS.items(): + c = job["mech"]["bc"][side] + kind = c["kind"] + n = SIDE_NORMAL[side] + if kind == "clamped": + disp.append(h.DisplacementCondition3D(tag, [True, True, True])) + fixed = True + elif kind == "symmetry": + disp.append(h.DisplacementCondition3D(tag, [abs(v) > 0 for v in n])) + fixed = True + elif kind == "traction" and float(c["value"]) != 0.0: + sg = float(c["value"]) * 1e6 + tv = np.array([n[0] * sg, n[1] * sg, n[2] * sg], dtype=complex) + trac.append(h.TractionCondition3D(tag, lambda x, tv=tv: tv)) + return disp, trac, fixed + + +def solve_mechanics(h, job, mesh, info, h1, temp): + """Elasticity3D for the job: returns (problem, u).""" + case, mech, props = job["case"], job["mech"], job["props"] + es = h.ElasticitySetup3D() + tref = float(job["thermal"]["T_ref"]) + es.reference_temperature = tref + es.static_condensation = False + if case == "particle": + r = info["r"] + s = float(mech["shrink_a_pct"]) / 100.0 + es.background = elastic(h, props[job["background"]]) + es.materials = {TAG_SPHERE: elastic(h, props[job["inclusion"]])} + es.background_expansion = float(props[job["background"]]["alpha"]) * 1e-6 + es.thermal_expansion = {TAG_SPHERE: float(props[job["inclusion"]]["alpha"]) * 1e-6} + es.temperature = temp + if s: + es.shrinkage = lambda x, r=r, s=s: s if (x[0] ** 2 + x[1] ** 2 + x[2] ** 2) < r * r else 0.0 + disp = [] + if info["quarter"]: + disp += [h.DisplacementCondition3D(TAG_SYM_X, [True, False, False]), h.DisplacementCondition3D(TAG_SYM_Y, [False, True, False])] + if mech["wall"] == "clamped": + disp += [h.DisplacementCondition3D(tg, [True, True, True]) for tg in sink_tags(info)] + else: + es.remove_rigid_modes = True + es.displacements = disp + else: + p = props[job["background"]] + es.background = elastic(h, p) + es.background_expansion = float(p["alpha"]) * 1e-6 + W, D, H = job["block"]["W_um"] * UM, job["block"]["D_um"] * UM, job["block"]["H_um"] * UM + if temp is not None: + es.temperature = temp + else: + da, db = float(mech["dT_a"]), float(mech["dT_b"]) + if da != 0 or db != 0: + es.temperature = np.asarray(h.interpolate(h1, lambda x: complex(tref + da + (db - da) * x[2] / H)), dtype=complex) + sa, sb = float(mech["shrink_a_pct"]) / 100.0, float(mech["shrink_b_pct"]) / 100.0 + if sa or sb: + es.shrinkage = lambda x, sa=sa, sb=sb, H=H: sa + (sb - sa) * x[2] / H + disp, trac, fixed = side_conditions(h, job) + es.displacements, es.tractions = disp, trac + if not fixed: + es.remove_rigid_modes = True + prob = h.Elasticity3D(h1, es) + u = np.asarray(prob.solve(), dtype=complex) + return prob, u + + +# ---------------------------------------------------------------------------------------------------------------------- fields +def von_mises(s): + sx, sy, sz, sxy, syz, sxz = s[0, 0], s[1, 1], s[2, 2], s[0, 1], s[1, 2], s[0, 2] + return math.sqrt(0.5 * ((sx - sy) ** 2 + (sy - sz) ** 2 + (sz - sx) ** 2) + 3.0 * (sxy**2 + syz**2 + sxz**2)) + + +def grid_axes(job, mesh, info): + """Cell-centre axes (SI) of the sample grid: the whole box; for the quarter model only the quadrant x, y > 0 (mirrored afterwards).""" + v = np.asarray(mesh.vertices) + lo, hi = v.min(axis=0), v.max(axis=0) + g = int(job["grid"]) + ext = hi - lo + if info["quarter"]: + ext_full = np.array([2 * ext[0], 2 * ext[1], ext[2]]) + n_full = np.maximum(4, np.round(g * ext_full / ext_full.max()).astype(int)) + n = np.array([max(2, n_full[0] // 2), max(2, n_full[1] // 2), n_full[2]]) + else: + n = np.maximum(3, np.round(g * ext / ext.max()).astype(int)) + return [lo[i] + (np.arange(n[i]) + 0.5) * ext[i] / n[i] for i in range(3)] + + +def sample_fields(h, job, mesh, info, nd, h1, temp, e_tot, mech): + xs, ys, zs = grid_axes(job, mesh, info) + loc = h.PointLocator3D(mesh) + shape = (len(xs), len(ys), len(zs)) + f = {k: np.full(shape, np.nan) for k in FIELD_NAMES} + prob, u = mech if mech else (None, None) + e0 = float(job["optics"]["E0_MVm"]) * 1e6 if job["case"] == "particle" else 1.0 + for i, x in enumerate(xs): + for j, y in enumerate(ys): + for k, z in enumerate(zs): + lp = loc.locate(np.array([x, y, z])) + if lp is None: + continue + c, xi = lp.cell, np.asarray(lp.xi) + if temp is not None: + f["T"][i, j, k] = h.evaluate_h1(h1, temp, c, xi).real + if e_tot is not None: + ev = np.asarray(h.evaluate_hcurl(nd, e_tot, c, xi)) + f["Eabs"][i, j, k] = math.sqrt(float(np.sum(np.abs(ev) ** 2))) / e0 + if prob is not None: + d = np.asarray(prob.displacement(u, c, xi)).real / NM + f["ux"][i, j, k], f["uy"][i, j, k], f["uz"][i, j, k] = d + f["umag"][i, j, k] = float(np.linalg.norm(d)) + s = np.asarray(prob.stress(u, c, xi)).real / 1e6 + f["sxx"][i, j, k], f["syy"][i, j, k], f["szz"][i, j, k] = s[0, 0], s[1, 1], s[2, 2] + f["sxy"][i, j, k], f["syz"][i, j, k], f["sxz"][i, j, k] = s[0, 1], s[1, 2], s[0, 2] + f["svm"][i, j, k] = von_mises(s) + return [xs, ys, zs], f + + +def mirror(axes, f, info): + """Quarter model -> full box: mirror about x = 0 and y = 0 (displacement components and shears flip sign across their mirror).""" + if not info["quarter"]: + return axes, f + xs, ys, zs = axes + out = {} + for k, a in f.items(): + sx = -1.0 if k in ODD_X else 1.0 + a = np.concatenate([sx * a[::-1, :, :], a], axis=0) + sy = -1.0 if k in ODD_Y else 1.0 + out[k] = np.concatenate([sy * a[:, ::-1, :], a], axis=1) + return [np.concatenate([-xs[::-1], xs]), np.concatenate([-ys[::-1], ys]), zs], out + + +def main(argv=None) -> int: + argv = list(argv or sys.argv[1:]) + if not argv: + print(__doc__) + return 2 + folder = Path(argv[0]) + job = json.loads((folder / "job.json").read_text(encoding="utf-8")) + import hpfem as h + h.set_log_level("warn") + case = job["case"] + particle = case == "particle" + order = int(job["order"]) + heat_on = particle or bool(job["thermal"]["heat"]) + mech_on = bool(job["mech"]["on"]) or not particle + out = dict(meta=dict(name=job.get("name", ""), case=case, dim=3, started=time.strftime("%Y-%m-%d %H:%M:%S"), hpfem=str(getattr(h, "__version__", "?")), order=order), + scalars={}, history=None, probes={}) + path = folder / "results.json" + + def flush(): + path.write_text(json.dumps(out, default=float, ensure_ascii=False), encoding="utf-8") + + stages = (["Optik und Wärme"] if particle else (["Wärme"] if heat_on else [])) + (["Mechanik"] if mech_on else []) + ["Felder"] + + def stage(i): + check_cancel(folder) + say(f"PROGRESS {i + 1}/{len(stages)} {stages[i]}") + + try: + t0 = time.time() + if not (len(argv) > 1 and argv[1] == "estimate"): + f3 = folder / "fields3d.npz" + if f3.exists(): + f3.unlink() + mesh, info = build_mesh(h, job) + est = estimate(h, job, mesh) + if len(argv) > 1 and argv[1] == "estimate": + print("ESTIMATE" + json.dumps(est), flush=True) + return 0 + say(f"hpfem {getattr(h, '__version__', '?')}, mesh: {est['cells']} cells, p = {order}, {est['h1_dofs']} H1 unknowns" + + (f", {est['nd_dofs']} optical unknowns ({est['optics_text']})" if particle else "") + + (f", elasticity ~{est['mech_dofs']} unknowns (~{est['mech_seconds']:.0f} s, ~{est['mech_bytes'] / GB:.2f} GB)" if mech_on else "")) + if est["bytes"] / GB > float(job.get("max_gb", 8.0)): + say(f"ERROR memory estimate {est['human']} exceeds the limit of {job.get('max_gb', 8.0)} GB: reduce the mesh or the order (or raise the limit).") + out["error"] = f"Speicherschätzung {est['human']} über der Grenze von {job.get('max_gb', 8.0)} GB" + flush() + return 1 + out["meta"].update(cells=int(est["cells"]), dofs_h1=int(est["h1_dofs"]), estimate=est) + h1 = h.DofMap3D(mesh, order) + nd = h.NedelecDofMap3D(mesh, order) if particle else None + i = 0 + temp = e_tot = None + if heat_on: + stage(i) + t1 = time.time() + if particle: + temp, e_tot = run_optics_heat(h, job, mesh, info, nd, h1, out) + out["time_optics_s"] = time.time() - t1 + say(f" {time.time() - t1:.1f} s, P_abs = {out['scalars'].get('Absorbierte Leistung (W)', float('nan')):.4g} W") + else: + temp = run_block_heat(h, job, mesh, h1, out) + say(f" {time.time() - t1:.1f} s") + flush() + i += 1 + mech = None + if mech_on: + stage(i) + t1 = time.time() + prob, u = solve_mechanics(h, job, mesh, info, h1, temp if (heat_on or particle) else None) + mech = (prob, u) + mult = 4.0 if info["quarter"] else 1.0 + out["scalars"]["Dehnungsenergie (J)"] = float(prob.strain_energy(u)) * mult + out["scalars"]["Freiheitsgrade Mechanik"] = int(prob.num_dofs) + say(f" {time.time() - t1:.1f} s") + flush() + i += 1 + stage(i) + loc = h.PointLocator3D(mesh) + if particle: + r = info["r"] + lp = loc.locate(np.array([1e-3 * r, 1e-3 * r, 1e-3 * r])) + if lp is not None and temp is not None: + out["probes"]["T_center"] = float(h.evaluate_h1(h1, temp, lp.cell, np.asarray(lp.xi)).real) + else: + b = job["block"] + W, D, H = b["W_um"] * UM, b["D_um"] * UM, b["H_um"] * UM + if temp is not None: + for name, pt in (("T_mid", [W / 2, D / 2, H / 2]), ("T_end", [W * (1 - 1e-9), D / 2, H / 2])): + lp = loc.locate(np.array(pt)) + if lp is not None: + out["probes"][name] = float(h.evaluate_h1(h1, temp, lp.cell, np.asarray(lp.xi)).real) + if mech: + d = np.asarray(mech[0].displacements_at(mech[1], np.array([[W, D / 2, H / 2], [W / 2, D, H / 2], [W / 2, D / 2, H]]))).real + out["probes"].update(ux_end=float(d[0, 0]), uy_end=float(d[1, 1]), uz_end=float(d[2, 2])) + axes, f = sample_fields(h, job, mesh, info, nd, h1, temp, e_tot, mech) + axes, f = mirror(axes, f, info) + arrays = {k: v for k, v in f.items() if np.isfinite(v).any()} + scale = 1.0 / (NM if particle else UM) + if "T" in arrays: + tmax = float(np.nanmax(arrays["T"])) + out["scalars"]["Maximale Temperatur auf dem Raster (K)"] = tmax + out["scalars"]["Temperaturanstieg max. auf dem Raster (K)"] = tmax - float(job["thermal"]["T_ref"]) + if "T_center" in out["probes"]: + out["scalars"]["Temperaturanstieg im Kugelmittelpunkt (K)"] = out["probes"]["T_center"] - float(job["thermal"]["T_ref"]) + if "umag" in arrays: + out["scalars"]["Größte Verschiebung auf dem Raster (nm)"] = float(np.nanmax(arrays["umag"])) + out["scalars"]["Größte Von-Mises-Spannung auf dem Raster (MPa)"] = float(np.nanmax(arrays["svm"])) + np.savez_compressed(folder / "fields3d.npz", x=axes[0] * scale, y=axes[1] * scale, z=axes[2] * scale, unit=np.array("nm" if particle else "um"), + sphere_r=np.array(job["particle"]["radius_nm"] if particle else 0.0), **arrays) + out["meta"]["total_s"] = time.time() - t0 + out["finished"] = True + flush() + say("DONE") + except Cancelled: + say("CANCELLED") + out["cancelled"] = True + flush() + except Exception as exc: + say(f"ERROR {type(exc).__name__}: {exc}") + out["error"] = f"{type(exc).__name__}: {exc}" + flush() + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/fem_gui/fem_thermo_app.py b/fem_gui/fem_thermo_app.py index b6f7c93..c628035 100644 --- a/fem_gui/fem_thermo_app.py +++ b/fem_gui/fem_thermo_app.py @@ -69,6 +69,13 @@ def render_thermo(ctx): """ctx: py, repo, work (Path), threads, lib, FEATS.""" _init() work = Path(ctx["work"]) / "thermo" + busy3 = S.get("th3_proc") is not None + dim = "3D" if busy3 else ("2D" if S.get("th_proc") is not None else st.radio("Raumdimension", ["2D", "3D"], horizontal=True, key="th_dim", + help="2D: Draht, Block, Zylinder (je Meter). 3D: Kugel und Quader.")) + if dim == "3D": + import fem_thermo3d_app + + return fem_thermo3d_app.render_thermo3d(ctx) st.title("FEM-Modellwerkstatt: Wärme und Mechanik") st.caption("Absorbierte Leistung → Temperatur (auch selbstkonsistent mit ε(T)) → Wärmespannung, und Mechanik von Block und Zylinder (2D, ebene Dehnung bzw. " "rotationssymmetrisch). hp-FEM: Thermal2D, ThermoOptical2D, Elasticity2D.") diff --git a/fem_gui/fem_threed.py b/fem_gui/fem_threed.py index 739c6d6..7d6ccc6 100644 --- a/fem_gui/fem_threed.py +++ b/fem_gui/fem_threed.py @@ -4,6 +4,11 @@ Three tasks with the 3D solvers of the library: ``scatter`` (Scattering3D: plane wave on a sphere or cube in a PML box, cross sections, Mie series as the reference for the sphere), ``resonance`` (Resonance3D: complex eigenfrequencies, Q) and ``bands`` (BandStructure3D: simple-cubic photonic crystal). Meshes come from the generators of the library (box_with_ball: curved sphere; box: cube aligned with the grid), no Gmsh needed. + +Extensions (hp-FEM 0.5): (1) a planar layer stack under the object (``stack``: LayerStack3D as the background of the scattered-field formulation, oblique +incidence, s / p, R / T / A of the bare stack), (2) task ``ports``: waveguides and couplers between modal ports (fem_ports3d.py), (3) hp-adaptive refinement of +the scattering problem (``adaptive``: AdaptiveMesh3D, residual estimator, Doerfler marking, hp decision by prediction), (4) Gmsh meshes: own geometry (sphere, +cylinder, block; fem_threed_gmsh.py) or an uploaded .msh file with a tag to material table (``mesh_kind``). """ from __future__ import annotations @@ -16,23 +21,53 @@ import pandas as pd import fem_materials as fm +import fem_ports3d as fp3 import fem_run as fr - -TASKS = {"scatter": "Streuung an Kugel oder Würfel (Wirkungsquerschnitte)", "resonance": "Resonanzen (Quasi-Normalmoden, Q-Faktor)", - "bands": "Bandstruktur (kubisches photonisches Kristallgitter)"} +import fem_threed_gmsh as gm + +TASKS = {"scatter": "Streuung (Wirkungsquerschnitte, optional auf Schichtstapel, hp-adaptiv)", "resonance": "Resonanzen (Quasi-Normalmoden, Q-Faktor)", + "bands": "Bandstruktur (kubisches photonisches Kristallgitter)", "ports": "Wellenleiter und Ports (S-Parameter)"} +MESH_KINDS = {"builtin": "Bibliotheksnetz (Kugel, Würfel)", "gmsh": "Gmsh-Geometrie (Kugel, Zylinder, Quader)", "file": "Eigene Gmsh-Datei (.msh)"} +POLS = {"p": "p (TM)", "s": "s (TE)"} +UNIT_SCALE = {"nm": 1e-9, "µm": 1e-6, "mm": 1e-3, "m": 1.0} +AIR, GLASS = "Luft", "Glas" SHAPES = {"sphere": "Kugel (gekrümmte Elemente)", "cube": "Würfel (an das Gitter angepasst)"} SYM = {False: "ganzes Modell", True: "Viertelmodell (x > 0, y > 0, Spiegelsymmetrie)"} GB = 1e9 OBJ = "Objekt" +OBJ_TAG = gm.TAG_OBJ def default_model(): return {"name": "Kugel in Luft", "task": "scatter", "shape": "sphere", "radius_nm": 100.0, - "materials": {OBJ: {"type": "index", "n": 2.0, "k": 0.0}}, "object": OBJ, + "materials": {OBJ: {"type": "index", "n": 2.0, "k": 0.0}, AIR: {"type": "index", "n": 1.0, "k": 0.0}, GLASS: {"type": "index", "n": 1.5, "k": 0.0}}, + "object": OBJ, "half_width": 2.0, "outer": 3.0, "n": 2, "order": 2, "quarter": True, "fields": True, "max_gb": 16.0, "sweep": {"start": 314.159, "stop": 314.159, "count": 1}, "resonance": {"lam0_nm": 700.0, "num_modes": 3, "krylov": 0}, - "bands": {"radius": 0.25, "eps": 12.0, "eps_bg": 1.0, "bands": 6, "n_seg": 2, "cells": 4, "krylov": 0}} + "bands": {"radius": 0.25, "eps": 12.0, "eps_bg": 1.0, "bands": 6, "n_seg": 2, "cells": 4, "krylov": 0}, + "mesh_kind": "builtin", + "gmsh": {"kind": "sphere", "height_nm": 200.0, "lx_nm": 200.0, "ly_nm": 200.0, "lz_nm": 100.0, "hw_nm": 250.0, "pml_nm": 200.0, "clear_nm": 150.0, + "h_obj_nm": 45.0, "h_far_nm": 140.0, "grade_nm": 250.0, "order": 2}, + "stack": {"enabled": False, "layers": [], "substrate": GLASS, "incidence": AIR, "gap_nm": 50.0, "depth_nm": 150.0, "angle_deg": 0.0, "pol": "p", + "azimuth_deg": 0.0}, + "file": {"name": "", "scale": "nm", "tag_material": {}, "object_tags": [], "pml_nm": 200.0, "tags": {}}, + "adaptive": {"enabled": False, "theta": 0.5, "max_steps": 4, "max_dofs": 15000, "tol": 0.0}, + "p3": fp3.default_model()} + + +def ensure(m): + """Fills keys that models of older versions lack (loaded files); returns m.""" + d = default_model() + for k, v in d.items(): + if k not in m: + m[k] = copy.deepcopy(v) + elif isinstance(v, dict) and k in ("gmsh", "stack", "file", "adaptive"): + for kk, vv in v.items(): + m[k].setdefault(kk, copy.deepcopy(vv)) + for name, spec in ((AIR, {"type": "index", "n": 1.0, "k": 0.0}), (GLASS, {"type": "index", "n": 1.5, "k": 0.0})): + m["materials"].setdefault(name, spec) + return m def presets(): @@ -54,6 +89,36 @@ def presets(): m.update(name="Kubischer Kristall: Würfel ε = 12 in Luft", task="bands", shape="cube", bands={"radius": 0.25, "eps": 12.0, "eps_bg": 1.0, "bands": 6, "n_seg": 2, "cells": 4, "krylov": 0}, order=2) p[m["name"]] = m + # --- hp-adaptive + m = default_model() + m.update(name="Kugel n = 2: hp-adaptiv (Viertelmodell, klein)", n=1, order=2, adaptive={"enabled": True, "theta": 0.5, "max_steps": 4, "max_dofs": 12000, "tol": 0.0}) + m["half_width"], m["outer"] = 2.0, 3.0 + p[m["name"]] = m + # --- Gmsh geometries and layer stacks (sizes in nm; deliberately coarse so that a run takes seconds to a few minutes) + m = default_model() + m.update(name="Kugel n = 2, Gmsh-Netz (Mie-Referenz, ca. 1,5 min)", mesh_kind="gmsh", order=2, quarter=False, sweep={"start": 628.3, "stop": 628.3, "count": 1}) + m["gmsh"].update(hw_nm=200.0, pml_nm=300.0, clear_nm=100.0, h_obj_nm=60.0, h_far_nm=150.0, grade_nm=200.0) + p[m["name"]] = m + m = default_model() + m.update(name="Silizium-Zylinder auf Glas, schräger Einfall (p, 30°; grob, p = 1)", mesh_kind="gmsh", order=1, quarter=False, radius_nm=100.0, + sweep={"start": 700.0, "stop": 700.0, "count": 1}, materials={OBJ: {"type": "library", "name": "Si"}, AIR: {"type": "index", "n": 1.0, "k": 0.0}, + GLASS: {"type": "index", "n": 1.5, "k": 0.0}}) + m["gmsh"].update(kind="cylinder", height_nm=120.0, hw_nm=250.0, pml_nm=300.0, clear_nm=150.0, h_obj_nm=45.0, h_far_nm=240.0, grade_nm=250.0) + m["stack"].update(enabled=True, layers=[], substrate=GLASS, gap_nm=0.0, depth_nm=250.0, angle_deg=30.0, pol="p") + p[m["name"]] = m + m = default_model() + m.update(name="Gold-Kugel auf SiO2-Schicht über Glas (Stapel, grob)", mesh_kind="gmsh", order=1, quarter=False, radius_nm=40.0, + sweep={"start": 560.0, "stop": 560.0, "count": 1}, + materials={OBJ: {"type": "library", "name": "Au"}, AIR: {"type": "index", "n": 1.0, "k": 0.0}, GLASS: {"type": "index", "n": 1.5, "k": 0.0}, + "SiO2-Schicht": {"type": "index", "n": 1.45, "k": 0.0}}) + m["gmsh"].update(kind="sphere", hw_nm=200.0, pml_nm=300.0, clear_nm=120.0, h_obj_nm=20.0, h_far_nm=180.0, grade_nm=150.0) + m["stack"].update(enabled=True, layers=[{"material": "SiO2-Schicht", "thickness_nm": 100.0}], substrate=GLASS, gap_nm=20.0, depth_nm=150.0, angle_deg=0.0, pol="p") + p[m["name"]] = m + # --- waveguides + for name, pm in fp3.presets().items(): + m = default_model() + m.update(name=name, task="ports", p3=pm) + p[name] = m return p @@ -69,19 +134,196 @@ def lam_check(m): return wavelengths(m) if m["task"] == "scatter" else [] +def object_material(m): + """Name of the material of the object: the chosen one; for a mesh file the material of its first object tag.""" + if m["mesh_kind"] == "file" and m["task"] != "bands": + f = m["file"] + for tag in f["object_tags"]: + nm = f["tag_material"].get(str(tag)) + if nm in m["materials"]: + return nm + return m["object"] + + +def object_cell_tags(m): + """Cell tags of the object(s) for the mesh view (orange): the object tag; the cores of a waveguide; the chosen tags of a mesh file.""" + if m["task"] == "ports": + return (fp3.TAG_A, fp3.TAG_B) + if m["task"] != "bands" and m["mesh_kind"] == "file": + return tuple(int(x) for x in m["file"]["object_tags"]) + return (OBJ_TAG,) + + def eps_list(m): - spec = m["materials"][m["object"]] + spec = m["materials"][object_material(m)] return [fm.eps_at(spec, lam) for lam in lam_check(m)] +def stack_regions(m): + """Material names from the top: incidence medium, the layers, the substrate.""" + st = m["stack"] + return [st["incidence"]] + [layer["material"] for layer in st["layers"]] + [st["substrate"]] + + +def region_eps(m, name, lams): + return [[float(e.real), float(e.imag)] for e in (fm.eps_at(m["materials"][name], lam) for lam in lams)] + + +def lam_min_nm(m): + ls = lam_check(m) + return min(ls) if ls else 500.0 + + +def index_max(m): + """Largest |n| of the object and of the stack regions at the shortest wavelength (for the mesh size suggestions).""" + lam = lam_min_nm(m) + names = [object_material(m)] + (stack_regions(m) if m["stack"]["enabled"] else []) + vals = [] + for nm in names: + if nm in m["materials"]: + vals.append(abs(np.sqrt(fm.eps_at(m["materials"][nm], lam)))) + return max(vals + [1.0]) + + +def suggest_sizes(m): + """Mesh sizes [nm] for the Gmsh geometry: fine near the object (about lambda / (3 n) and a third of the radius), coarse far away (lambda / 2.5), PML half a wavelength.""" + lam = lam_min_nm(m) + lam_max = max(lam_check(m) or [lam]) + r = float(m["radius_nm"]) + n_obj = abs(np.sqrt(fm.eps_at(m["materials"][object_material(m)], lam))) + h_obj = max(min(r / 2.5, lam / (3.0 * max(n_obj, 1.0))), 1.0) + h_far = lam / 2.5 + return dict(h_obj_nm=round(h_obj, 1), h_far_nm=round(h_far, 1), grade_nm=round(max(1.5 * h_far, 2 * r), 1), pml_nm=round(0.5 * lam_max, 1), hw_nm=round(max(1.5 * r, 0.3 * lam), 1)) + + +def gmsh_params(m): + """The parameter dict of fem_threed_gmsh.scene (nm) for the model.""" + g, st = m["gmsh"], m["stack"] + d = dict(kind=g["kind"], r=float(m["radius_nm"]), h=float(g["height_nm"]), lx=float(g["lx_nm"]), ly=float(g["ly_nm"]), lz=float(g["lz_nm"]), hw=float(g["hw_nm"]), + pml=float(g["pml_nm"]), clear=float(g["clear_nm"]), h_obj=float(g["h_obj_nm"]), h_far=float(g["h_far_nm"]), grade=float(g["grade_nm"]), order=int(g["order"]), + stack=bool(st["enabled"]) and m["task"] == "scatter") + if d["stack"]: + lam = lam_min_nm(m) + d.update(layers=[float(x["thickness_nm"]) for x in st["layers"]], depth=float(st["depth_nm"]), gap=float(st["gap_nm"])) + d["region_n"] = [float(abs(np.sqrt(fm.eps_at(m["materials"][nm], lam)))) for nm in stack_regions(m)] + else: + d["region_n"] = [1.0] + return d + + +def object_dims(m): + """(half extent in x, y, height) of the Gmsh object [nm].""" + return gm.object_extent(gmsh_params(m)) + + def _frac_int(x, tol=1e-9): return abs(x - round(x)) < tol +def validate_gmsh(m): + out = [] + g, st = m["gmsh"], m["stack"] + r = float(m["radius_nm"]) + if g["kind"] in ("sphere", "cylinder") and r <= 0: + out.append(("error", "Radius > 0.")) + if g["kind"] == "cylinder" and g["height_nm"] <= 0: + out.append(("error", "Höhe > 0.")) + if g["kind"] == "block" and min(g["lx_nm"], g["ly_nm"], g["lz_nm"]) <= 0: + out.append(("error", "Kantenlängen > 0.")) + if g["h_obj_nm"] <= 0 or g["h_far_nm"] <= 0 or g["pml_nm"] <= 0: + out.append(("error", "Maschenweiten und PML-Dicke > 0.")) + if g["h_obj_nm"] > g["h_far_nm"]: + out.append(("warning", "Die Maschenweite am Objekt ist größer als die ferne: es gibt dann keine Verfeinerung zum Objekt.")) + ox, oy, oh = gm.object_extent({"kind": g["kind"], "r": r, "h": g["height_nm"], "lx": g["lx_nm"], "ly": g["ly_nm"], "lz": g["lz_nm"]}) + if g["hw_nm"] < 1.05 * max(ox, oy): + out.append(("error", f"Der Innenraum (halbe Breite {g['hw_nm']:g} nm) muss größer sein als das Objekt (halbe Breite {max(ox, oy):g} nm).")) + elif g["hw_nm"] < max(ox, oy) + 0.5 * g["h_far_nm"]: + out.append(("warning", f"Der Abstand zwischen Objekt ({max(ox, oy):g} nm) und PML-Beginn ({g['hw_nm']:g} nm) ist kleiner als eine halbe ferne Zelle: das Nahfeld wird vom PML gestört.")) + if g["clear_nm"] <= 0: + out.append(("error", "Abstand über dem Objekt bis zum PML > 0.")) + lam = lam_min_nm(m) + if g["h_far_nm"] > lam / 1.8: + out.append(("warning", f"Ferne Maschenweite {g['h_far_nm']:g} nm bei λ = {lam:g} nm: weniger als etwa 1,8 Zellen je Wellenlänge, das Ergebnis ist kaum aufgelöst (Vorschlag: λ/2,5).")) + nmax = index_max(m) + if g["h_obj_nm"] * nmax > lam / 1.8: + out.append(("warning", f"Maschenweite am Objekt {g['h_obj_nm']:g} nm bei n ≈ {nmax:.2f}: unter 1,8 Zellen je Wellenlänge im Material.")) + if g["pml_nm"] < 0.3 * max(lam_check(m) or [lam]): + out.append(("warning", "Das PML ist dünner als etwa 0,3 λ: die Reflexion am Rand kann das Ergebnis stören.")) + if m["task"] == "scatter" and st["enabled"]: + names = stack_regions(m) + for nm in names: + if nm not in m["materials"]: + out.append(("error", f"Material „{nm}“ des Schichtstapels fehlt.")) + if not any(e[0] == "error" for e in out): + for lam_i in lam_check(m): + if abs(fm.eps_at(m["materials"][st["incidence"]], lam_i).imag) > 1e-9: + out.append(("error", "Das Einfallsmedium muss verlustfrei sein.")) + break + if any(abs(fm.eps_at(m["materials"][nm], lam_min_nm(m)).imag) > 1e-9 for nm in names[1:2] if g["kind"] != "sphere") and st["gap_nm"] <= 0: + out.append(("warning", "Das Objekt berührt eine verlustbehaftete Schicht: die Streuquerschnitte aus dem Fluss um das Objekt sind dort nicht eindeutig.")) + if any(x["thickness_nm"] <= 0 for x in st["layers"]): + out.append(("error", "Schichtdicken > 0.")) + if st["gap_nm"] < 0 or st["depth_nm"] <= 0: + out.append(("error", "Abstand ≥ 0 und Tiefe des Substrats bis zum PML > 0.")) + if g["kind"] == "sphere" and st["gap_nm"] < 0.1 * r: + out.append(("warning", "Eine Kugel mit Abstand unter 0,1 r zur Oberfläche erzeugt sehr kleine Zellen im Spalt; ein Abstand von mindestens r/4 ist ratsam.")) + if not 0.0 <= st["angle_deg"] < 90.0: + out.append(("error", "Einfallswinkel zwischen 0° und 90°.")) + if st["angle_deg"] > 0 and g["hw_nm"] < ox + 1.0 * g["h_far_nm"]: + out.append(("warning", "Bei schrägem Einfall wirkt die Wand aus PEC (Rand der Box) nur über das PML: die Box sollte mindestens das Objekt plus ein PML breit sein.")) + out.append(("warning", "PML und Schichtstapel: das PML ist für den Index 1 ausgelegt (Substrat und Schichten haben höheren Index); Substrat und Schichten dicker als das PML-Gebiet, sonst bleibt die Reflexion am Rand.")) + return out + + +def validate_file(m): + out = [] + f = m["file"] + if not f.get("name"): + return [("error", "Bitte eine .msh-Datei hochladen (Gmsh 4.1 ASCII, Reiter 2) und lesen.")] + if not f.get("tags"): + return [("error", "Die Datei wurde noch nicht gelesen: „Datei lesen“ im Reiter 2.")] + cells = f["tags"].get("cells", {}) + if not f["object_tags"]: + out.append(("error", "Mindestens eine Zellmarke als Streukörper wählen.")) + missing = [tag for tag in cells if f["tag_material"].get(tag) not in m["materials"]] + if missing: + out.append(("error", f"Zellmarken ohne Material: {', '.join(missing)} (Tabelle im Reiter 2; Luft ist ein Material der Liste).")) + if f["pml_nm"] <= 0: + out.append(("error", "PML-Dicke > 0.")) + else: + bb = f["tags"].get("bbox") + if bb: + ext = np.array(bb[1]) - np.array(bb[0]) # metres (the worker scales the file) + if 2 * f["pml_nm"] * 1e-9 >= ext.min() * 0.9: + out.append(("error", "Die PML-Dicke ist zu groß für die Ausdehnung des Netzes (der Innenraum wäre leer).")) + out.append(("warning", "Die Seitenflächen des Netzes werden als PEC-Wand behandelt; das PML-Gebiet ist der Rand der Box (die Randflächen ohne Marke bekommen die Marken 1 bis 6).")) + return out + + def validate(m): """[(level, text)] for the model.""" out = [] t = m["task"] + if t == "ports": + return fp3.validate(m["p3"]) + if t != "bands" and m["mesh_kind"] == "file": + out += validate_file(m) + if any(x[0] == "error" for x in out): + return out + if t != "bands" and m["mesh_kind"] == "gmsh": + out += validate_gmsh(m) + if m["stack"]["enabled"] and t != "ports" and (t != "scatter" or m["mesh_kind"] != "gmsh"): + out.append(("warning", "Der Schichtstapel gilt nur für die Streuung mit einer Gmsh-Geometrie (Netz mit Ebenen an den Grenzflächen) und wird hier ignoriert.")) + if m["adaptive"]["enabled"]: + if t != "scatter": + out.append(("error", "Die hp-Adaptivität gibt es nur für die Streuung.")) + a_ = m["adaptive"] + if a_["max_steps"] < 1 or not 0.05 <= a_["theta"] <= 1.0 or a_["max_dofs"] < 100: + out.append(("error", "hp-Adaptivität: Schritte ≥ 1, θ zwischen 0,05 und 1, Obergrenze Unbekannte ≥ 100.")) + if m["order"] > 3: + out.append(("warning", "Startordnung über 3 mit hp-Adaptivität: der Speicher wächst schnell; die Obergrenze für Unbekannte greift vor dem nächsten Schritt.")) + if m["mesh_kind"] == "builtin" and m["shape"] == "cube": + out.append(("warning", "Der Würfel ist ein Gitternetz mit Zellen auf der Würfelfläche: die Verfeinerung teilt rote Tetraeder, die Würfelkante bleibt exakt.")) if t == "bands": b = m["bands"] if not 0.02 <= b["radius"] < 0.5: @@ -100,17 +342,18 @@ def validate(m): out.append(("error", "Die Kugel muss in die Zelle passen (r < 0,5 a).")) return out a = float(m["radius_nm"]) - if a <= 0: - out.append(("error", "Radius bzw. halbe Kante > 0.")) - hw, outer, n = float(m["half_width"]), float(m["outer"]), int(m["n"]) - if not (hw > 1.0 and outer > hw): - out.append(("error", "Es muss gelten: 1 < Innenraum (halbe Breite) < Außenrand; zwischen Innenraum und Außenrand liegt das PML.")) - if not (_frac_int(hw * n) and _frac_int(outer * n)): - out.append(("error", f"Innenraum und Außenrand mal Zellen je Radius (n) müssen ganzzahlig sein (hier {hw * n:g} und {outer * n:g}).")) - if hw - 1.0 < 0.5: - out.append(("warning", "Weniger als ein halber Radius Abstand zwischen Objekt und PML: das Nahfeld wird vom PML gestört.")) - if m["quarter"] and t == "resonance": - out.append(("error", "Resonanzen brauchen das ganze Modell (die Moden sind nicht alle symmetrisch).")) + if m["mesh_kind"] == "builtin": + if a <= 0: + out.append(("error", "Radius bzw. halbe Kante > 0.")) + hw, outer, n = float(m["half_width"]), float(m["outer"]), int(m["n"]) + if not (hw > 1.0 and outer > hw): + out.append(("error", "Es muss gelten: 1 < Innenraum (halbe Breite) < Außenrand; zwischen Innenraum und Außenrand liegt das PML.")) + if not (_frac_int(hw * n) and _frac_int(outer * n)): + out.append(("error", f"Innenraum und Außenrand mal Zellen je Radius (n) müssen ganzzahlig sein (hier {hw * n:g} und {outer * n:g}).")) + if hw - 1.0 < 0.5: + out.append(("warning", "Weniger als ein halber Radius Abstand zwischen Objekt und PML: das Nahfeld wird vom PML gestört.")) + if m["quarter"] and t == "resonance": + out.append(("error", "Resonanzen brauchen das ganze Modell (die Moden sind nicht alle symmetrisch).")) if m["order"] < 1: out.append(("error", "Ordnung ≥ 1.")) try: @@ -122,15 +365,19 @@ def validate(m): if t == "scatter": if not wavelengths(m): out.append(("error", "Keine Wellenlänge.")) - if m["shape"] == "cube": + if m["shape"] == "cube" and m["mesh_kind"] == "builtin": out.append(("warning", "Für den Würfel gibt es keine analytische Referenz; die Kanten sind treppenfrei, aber die Felder an den Ecken sind singulär (langsamere Konvergenz).")) - if t == "resonance" and m["shape"] == "cube": + if m["mesh_kind"] == "gmsh" and m["gmsh"]["kind"] != "sphere" or m["stack"]["enabled"]: + out.append(("warning", "Keine Mie-Referenz für diese Geometrie; Q ist auf die Grundfläche (Projektion auf die x-y-Ebene) bezogen. Prüfen Sie die Netzkonvergenz (hp-adaptive Verfeinerung zeigt sie).")) + if t == "resonance" and m["shape"] == "cube" and m["mesh_kind"] == "builtin": out.append(("warning", "Für den Würfel gibt es keine analytische Referenz.")) return out def job(m, max_gb=None): t = m["task"] + if t == "ports": + return fp3.job(m["p3"], max_gb if max_gb is not None else m["max_gb"]) j = {"task": t, "name": m["name"], "shape": m["shape"], "n": int(m["n"]), "order": int(m["order"]), "half_width": float(m["half_width"]), "outer": float(m["outer"]), "max_gb": float(max_gb if max_gb is not None else m["max_gb"]), "fields": bool(m["fields"])} if t == "bands": @@ -139,7 +386,9 @@ def job(m, max_gb=None): krylov=int(b["krylov"]), half_width=0.5, outer=0.5) return j j["radius_nm"] = float(m["radius_nm"]) - j["quarter"] = bool(m["quarter"]) and t == "scatter" + kind = m["mesh_kind"] + j["mesh_kind"] = kind + j["quarter"] = bool(m["quarter"]) and t == "scatter" and kind == "builtin" if t == "scatter": j["wavelengths_nm"] = wavelengths(m) j["eps"] = [[e.real, e.imag] for e in eps_list(m)] @@ -147,16 +396,52 @@ def job(m, max_gb=None): r = m["resonance"] e = eps_list(m)[0] j.update(lam0_nm=float(r["lam0_nm"]), num_modes=int(r["num_modes"]), krylov=int(r["krylov"]), eps=[e.real, e.imag]) + lams = lam_check(m) + if kind == "gmsh": + j["g"] = gmsh_params(m) + st = m["stack"] + if st["enabled"] and t == "scatter": + j["stack"] = dict(eps=[region_eps(m, nm, lams) for nm in stack_regions(m)], thickness_nm=[float(x["thickness_nm"]) for x in st["layers"]], pol=st["pol"], + angle_deg=float(st["angle_deg"]), azimuth_deg=float(st["azimuth_deg"])) + if kind == "file": + f = m["file"] + j["file"] = dict(path=f.get("path", ""), scale=UNIT_SCALE[f["scale"]], object_tags=[int(x) for x in f["object_tags"]], pml_nm=float(f["pml_nm"]), + tag_eps={str(tag): region_eps(m, nm, lams) for tag, nm in f["tag_material"].items() if nm in m["materials"]}) + ad = m["adaptive"] + if ad["enabled"] and t == "scatter": + j["adaptive"] = dict(enabled=True, theta=float(ad["theta"]), max_steps=int(ad["max_steps"]), max_dofs=int(ad["max_dofs"]), tol=float(ad["tol"])) return j +def worker_script(jb): + """The worker script of a job (ports: fem_ports3d_worker.py, everything else fem_threed_worker.py).""" + return fp3.SCRIPT if jb.get("task") == "ports" else "fem_threed_worker.py" + + +def run_inspect(py, repo, folder, path, unit, task="scatter", threads=0, timeout=120): + """Tags of a mesh file via the worker: dict n_cells, cells {tag: count}, facets {tag: count}, bbox [m], geometry_order; or {'error': ...}.""" + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + jb = {"task": task, "path": str(path), "scale": UNIT_SCALE[unit], "file": {"path": str(path), "scale": UNIT_SCALE[unit]}} + (folder / "job.json").write_text(json.dumps(jb), encoding="utf-8") + try: + r = subprocess.run([str(py), str(fr.HERE / worker_script(jb)), str(folder), "inspect"], cwd=fr._cwd(repo, folder), env=fr.worker_env(repo, threads), + capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return {"error": "Zeitüberschreitung beim Lesen."} + for line in r.stdout.splitlines(): + if line.startswith("INSPECT"): + return json.loads(line[len("INSPECT"):]) + return {"error": (r.stdout + r.stderr).strip().splitlines()[-1] if (r.stdout + r.stderr).strip() else "keine Ausgabe"} + + def run_estimate(py, repo, folder, jb, threads=0, timeout=300): """Memory estimate of the job from the library (meshes the model, no solve): dict cells, dofs, bytes, human, text; or {'error': ...}.""" folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) (folder / "job.json").write_text(json.dumps(jb), encoding="utf-8") try: - r = subprocess.run([str(py), str(fr.HERE / "fem_threed_worker.py"), str(folder), "estimate"], cwd=fr._cwd(repo, folder), env=fr.worker_env(repo, threads), + r = subprocess.run([str(py), str(fr.HERE / worker_script(jb)), str(folder), "estimate"], cwd=fr._cwd(repo, folder), env=fr.worker_env(repo, threads), capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: return {"error": "Zeitüberschreitung beim Vernetzen."} @@ -210,16 +495,33 @@ def section_polygons(vertices, cells, axis, coord): return polys, idx -def fig_mesh(npz, axis=1, coord=0.0, unit=1e-9, unit_label="nm", title=""): - """Cut through the mesh (straight tetrahedron edges; the curved sphere surface is drawn exact in the solver) coloured by material tag.""" +_PALETTE = ["#cfe3f5", "#d9ead3", "#e8dcf0", "#fff2cc", "#d0e0e3", "#f9cb9c", "#ead1dc", "#c9daf8"] + + +def _tag_colour(tag, obj_tags, all_tags): + if tag in obj_tags: + return "#f4b183" + others = [x for x in all_tags if x not in obj_tags] + return _PALETTE[others.index(tag) % len(_PALETTE)] if tag in others else "#cfe3f5" + + +def fig_mesh(npz, axis=1, coord=0.0, unit=1e-9, unit_label="nm", title="", obj_tags=(2,), by="tag"): + """Cut through the mesh (straight tetrahedron edges; the curved surfaces are drawn exact in the solver) coloured by material tag (orange: object) or, after an + hp-adaptive run (by = "order"), by the polynomial order of the cell.""" import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection verts, cells, tags = npz["vertices"], npz["cells"], npz["tags"] + orders = npz["orders"] if "orders" in getattr(npz, "files", npz) else None polys, idx = section_polygons(verts, cells, axis, coord) fig, ax = plt.subplots(figsize=(5.4, 5.0)) if polys: - cols = np.array(["#cfe3f5" if tags[i] == 0 else "#f4b183" for i in idx]) + if by == "order" and orders is not None: + cmap = plt.get_cmap("viridis") + lo, hi = int(orders.min()), int(orders.max()) + cols = [cmap((int(orders[i]) - lo) / max(hi - lo, 1)) for i in idx] + else: + cols = [_tag_colour(int(tags[i]), obj_tags, sorted({int(x) for x in tags})) for i in idx] ax.add_collection(PolyCollection([p / unit for p in polys], facecolors=cols, edgecolors="0.35", linewidths=0.4)) allp = np.vstack(polys) / unit ax.set_xlim(allp[:, 0].min(), allp[:, 0].max()) @@ -229,7 +531,7 @@ def fig_mesh(npz, axis=1, coord=0.0, unit=1e-9, unit_label="nm", title=""): keep = [names[i] for i in range(3) if i != axis] ax.set_xlabel(f"{keep[0]} ({unit_label})") ax.set_ylabel(f"{keep[1]} ({unit_label})") - ax.set_title(title or f"Schnitt {names[axis]} = {coord / unit:g} {unit_label} (orange: Objekt)") + ax.set_title(title or f"Schnitt {names[axis]} = {coord / unit:g} {unit_label} " + ("(Farbe: Ordnung p)" if by == "order" and orders is not None else "(orange: Objekt)")) fig.tight_layout() return fig @@ -247,7 +549,41 @@ def mirror(xs, ys, f, mirror_x=True, mirror_y=False): return X, Y, f -def fig_field(npz, key, quarter, unit=1e-9, unit_label="nm", radius=None, shape="sphere", title=""): +def object_outline(m, key): + """Outlines [nm] of the object in the cut plane key (xz: x horizontal, z vertical; xy): list of (xs, ys, style) for the field figures; for a layer stack the + interfaces of the xz cut as horizontal lines.""" + out = [] + if m["task"] == "bands" or m["mesh_kind"] == "file": + return out + th = np.linspace(0, 2 * np.pi, 200) + if m["mesh_kind"] == "builtin": + r = float(m["radius_nm"]) + if m["shape"] == "sphere": + out.append((r * np.cos(th), r * np.sin(th), "w--")) + else: + out.append((np.array([-r, r, r, -r, -r]), np.array([-r, -r, r, r, -r]), "w--")) + return out + g = gmsh_params(m) + lay = gm.layout(g) + ox, oy, oh = gm.object_extent(g) + z0, zc = lay["obj_z0"], lay["zc"] + if key == "xz": + if g["kind"] == "sphere": + out.append((g["r"] * np.cos(th), zc + g["r"] * np.sin(th), "w--")) + else: + out.append((np.array([-ox, ox, ox, -ox, -ox]), np.array([z0, z0, z0 + oh, z0 + oh, z0]), "w--")) + x1 = g["hw"] + for z in lay["interfaces"]: + out.append((np.array([-x1, x1]), np.array([z, z]), "c:")) + else: + if g["kind"] == "block": + out.append((np.array([-ox, ox, ox, -ox, -ox]), np.array([-oy, -oy, oy, oy, -oy]), "w--")) + else: + out.append((g["r"] * np.cos(th), g["r"] * np.sin(th), "w--")) + return out + + +def fig_field(npz, key, quarter, unit=1e-9, unit_label="nm", radius=None, shape="sphere", title="", outline=None): """|E|^2 / |E_0|^2 on one cut plane; xz: x horizontal, z vertical (the wave travels upwards); xy: x, y.""" import matplotlib.pyplot as plt @@ -261,7 +597,12 @@ def fig_field(npz, key, quarter, unit=1e-9, unit_label="nm", radius=None, shape= fig, ax = plt.subplots(figsize=(5.6, 5.0)) im = ax.pcolormesh(X / unit, Y / unit, F.T, shading="auto", cmap="inferno") fig.colorbar(im, ax=ax, label="|E|² / |E₀|²") - if radius is not None: + if outline is not None: + for xs_, ys_, style in outline: + ax.plot(np.asarray(xs_), np.asarray(ys_), style, lw=0.9) + ax.set_xlim(X.min() / unit, X.max() / unit) + ax.set_ylim(Y.min() / unit, Y.max() / unit) + elif radius is not None: if shape == "sphere": t = np.linspace(0, 2 * np.pi, 200) ax.plot(radius / unit * np.cos(t), radius / unit * np.sin(t), "w--", lw=0.9) @@ -288,11 +629,46 @@ def scatter_dataframe(points): if "mie_q_sca" in p: r.update({"Q_sca Mie": p["mie_q_sca"], "Q_abs Mie": p["mie_q_abs"], "ΔQ_sca (%)": 100 * (p["q_sca"] - p["mie_q_sca"]) / max(abs(p["mie_q_sca"]), 1e-30), "ΔQ_abs / Q_sca,Mie (%)": 100 * (p["q_abs"] - p["mie_q_abs"]) / max(abs(p["mie_q_sca"]), 1e-30)}) + if "stack_R" in p: + r.update({"R (Stapel)": p["stack_R"], "T (Stapel)": p["stack_T"], "A (Stapel)": p["stack_A"]}) r["Zeit (s)"] = p.get("seconds", np.nan) rows.append(r) return pd.DataFrame(rows) +def steps_dataframe(steps): + rows = [] + for s in steps: + r = {"Schritt": s["step"], "Zellen": s["cells"], "Unbekannte": s["dofs"], "Fehlerschätzer η": s["eta"], "p min": s["orders_min"], "p max": s["orders_max"], + "Q_sca": s["q_sca"], "Q_abs": s["q_abs"], "h-markiert": s.get("h_marked", np.nan), "p-markiert": s.get("p_marked", np.nan), "Zeit (s)": s["seconds"]} + if "mie_q_sca" in s: + r["Q_sca Mie"] = s["mie_q_sca"] + r["ΔQ_sca (%)"] = 100 * (s["q_sca"] - s["mie_q_sca"]) / max(abs(s["mie_q_sca"]), 1e-30) + rows.append(r) + return pd.DataFrame(rows) + + +def fig_convergence(steps): + """hp-adaptive history: estimator η and Q_sca against the number of unknowns (and the deviation from the Mie series, if there is one).""" + import matplotlib.pyplot as plt + + n = [s["dofs"] for s in steps] + fig, axs = plt.subplots(1, 2, figsize=(9.2, 3.8)) + axs[0].loglog(n, [s["eta"] for s in steps], "o-", color="C0") + axs[0].set_xlabel("Unbekannte") + axs[0].set_ylabel("Fehlerschätzer η") + axs[0].grid(alpha=0.3, which="both") + axs[1].semilogx(n, [s["q_sca"] for s in steps], "o-", color="C0", label="Q_sca") + if all("mie_q_sca" in s for s in steps): + axs[1].axhline(steps[0]["mie_q_sca"], color="k", ls="--", label="Mie-Reihe") + axs[1].set_xlabel("Unbekannte") + axs[1].set_ylabel("Q_sca") + axs[1].grid(alpha=0.3, which="both") + axs[1].legend(fontsize=8) + fig.tight_layout() + return fig + + def fig_efficiency(points): import matplotlib.pyplot as plt diff --git a/fem_gui/fem_threed_app.py b/fem_gui/fem_threed_app.py index be586b5..53c9dd9 100644 --- a/fem_gui/fem_threed_app.py +++ b/fem_gui/fem_threed_app.py @@ -14,6 +14,7 @@ import streamlit as st import fem_bands as fb +import fem_ports3d_app as pa3 import fem_run as fr import fem_threed as ft import fem_ui as ui @@ -51,12 +52,38 @@ - Die Abweichung zur Mie-Reihe ist das Maß für die Netzgüte der Streuung; für Würfel, Resonanzen und Bänder gibt es dieses Maß hier nicht. Die Resonanz- und Bandstruktur-Modi sind in der Oberfläche **nicht gegen analytische Lösungen validiert**. - Material: Streuung mit beliebigem Material der App bei jeder Wellenlänge (Dispersion wird je Wellenlänge ausgewertet); Resonanzen und Bänder mit konstantem ε. -- Nicht in dieser Oberfläche: Substrate/Schichtstapel in 3D, Ports und Wellenleiter in 3D, adaptive hp-Verfeinerung, Gmsh-Netze, 3D-Wärme und -Mechanik. +- Nicht in diesem Modus: 3D-Wärme und -Mechanik (nur 2D, Modus „Wärme und Mechanik“). + +**Substrat und Schichtstapel (Streuung, Gmsh-Geometrie).** Die Hintergrundlösung ist ein analytischer Schichtstapel (`LayerStack3D`: Einfallsmedium oben, endliche Schichten, Substrat unten; +Fresnel/Airy) mit ebener Welle unter beliebigem Einfallswinkel (s oder p, Azimut); das Objekt streut nur die Abweichung vom Stapel (Streufeld-Formulierung). Die Grenzflächen sind Ebenen im +Gmsh-Netz (jede Schicht ein eigenes Volumen), die Oberkante des Stapels liegt bei z = 0. Die Tabelle zeigt R, T, A des Stapels ohne Objekt. Der Querschnitt ist auf die **Intensität der einfallenden +Welle** bezogen, Q auf die Projektion des Objekts auf die x-y-Ebene. Grenzen: das PML ist für den Index 1 ausgelegt (Substrat und Schichten höher: nur Richtwerte, die Bibliothek meldet +ein unteraufgelöstes PML im Protokoll); der Querschnitt aus dem Fluss um das Objekt ist an lossy Schichten, die das Objekt berühren, nicht eindeutig; ein Objekt in einer Schicht (das eine Grenzfläche schneidet) gibt es nicht. +Geprüft: ein „Stapel“ aus Luft liefert dieselbe Kugel wie ohne Stapel (Q_sca 0,811 gegen 0,795, grobes Netz; Mie 0,797); R des Stapels stimmt mit der Fresnel-Formel überein. + +**Gmsh-Netze.** (1) *Gmsh-Geometrie*: Kugel, Zylinder (Achse z) oder Quader in einer Box mit PML-Rand, vernetzt von Gmsh (Python-Modul `gmsh` im hpfem-Python nötig), Elemente zweiter Ordnung (gekrümmt); +Maschenweite am Objekt und fern, Übergangslänge, Innenraum, PML-Dicke und Abstand nach oben sind einstellbar, „Maschenweiten vorschlagen“ setzt Richtwerte aus der Wellenlänge. +**Das PML braucht mindestens zwei bis drei Zellen Dicke**: an einer Kugel n = 2, ka = 1 liegt Q_sca bei PML = 2 Zellen, fern λ/4,2 und p = 2 (18 000 Unbekannte, 82 s) um 0,3 % neben der Mie-Reihe, +bei einer Zelle im PML um 25 %. (2) *Eigene Datei*: ein Gmsh-Netz (Version 4.1 ASCII) wird hochgeladen, „Datei lesen“ zeigt Zellmarken (physikalische Volumina), Flächenmarken und +Ausdehnung; Sie weisen jeder Zellmarke ein Material zu und wählen die Zellmarken des Streukörpers. Die äußeren Randflächen ohne Marke werden zu den Seiten der Box (PEC), das PML liegt in der +äußersten Schicht der Box (Dicke einstellbar). Q ist auf die Projektion des Objekts bezogen (aus der Oberfläche mit geraden Facetten berechnet, bei gekrümmten Körpern ungenau); σ ist davon unabhängig. + +**hp-adaptive Verfeinerung (Streuung).** Je Schritt: lösen, residualer Fehlerschätzer (`Scattering3D.estimate`), Dörfler-Markierung (θ), Entscheidung h oder p nach der Vorhersage, Verfeinern +(`AdaptiveMesh3D`, `hp_refine`). Die Schleife endet bei der Schrittzahl, der Obergrenze für Unbekannte, der Speichergrenze oder dem relativen Schätzer η/η₀. Ergebnis: η, Q_sca, Q_abs und Zellzahl je Schritt, +Netz mit den Ordnungen. η fällt mit den Schritten, aber Q_sca konvergiert bei grobem PML nicht monoton; die Schleife ersetzt keine Konvergenzprüfung gegen eine Referenz. + +**Wellenleiter und Ports.** Rechteckkern im Mantel (`Streifenwellenleiter`) oder zwei Kerne (`Richtkoppler`) zwischen modalen Ports (`s_parameters`): PEC-Wände an den vier Seiten, Ports auf den Stirnflächen +z = 0 und z = L; strukturiertes Tetraedernetz mit Gitterlinien auf den Kernkanten. Ergebnis: leistungsnormierte S-Matrix aller Kanäle, Reflexion, Transmission, Verlust, n_eff der Portmoden, |E|² im Längs- und +Querschnitt. Referenzen: Streifen: β der Grundmode des Querschnitts (2D-Modenlöser) und seine Phase gegen die der Transmission; Koppler: Theorie gekoppelter Moden P_cross = sin²(κL) mit κ aus den Supermoden +(gleiches Netz und ein feineres Referenznetz mit p + 2 und halber Zelle: der Unterschied zeigt den Diskretisierungsfehler). Eigene Gmsh-Datei: Flächenmarken werden als PEC-Wand oder Port (mit Modenzahl) zugewiesen, +z. B. der Ringresonator `examples/ring_resonator_3d/ring_mesh.py` der Bibliothek. **3D-Wellenleiter sind teuer**: n_eff des 450 × 220 nm Si/SiO₂-Streifens ist mit p = 1 und 150-nm-Zellen um +9 % zu klein (2,14 gegen etwa 2,36), mit p = 2 und 75-nm-Zellen konvergiert es, kostet aber Minuten und Gigabyte; die Phase der Transmission läuft mit der Länge davon. """ def _init(): if "td_model" in S: + ft.ensure(S.td_model) return S.td_model = copy.deepcopy(ft.default_model()) S.td_ver, S.td_proc, S.td_dir, S.td_msg, S.td_est = 0, None, None, None, None @@ -66,25 +93,24 @@ def _bump(): S.td_ver += 1 -def _rename(m, old, new): - m["materials"] = {(new if k == old else k): v for k, v in m["materials"].items()} - if m["object"] == old: - m["object"] = new - - def render_threed(ctx): """ctx: py, repo, work (Path), threads, lib, FEATS.""" _init() work = Path(ctx["work"]) / "threed" st.title("FEM-Modellwerkstatt: 3D-Strukturen") - st.caption("Kugel oder Würfel in Luft: Streuung mit Mie-Referenz, Resonanzen, Bandstruktur eines kubischen Kristalls. hp-FEM: Scattering3D, Resonance3D, BandStructure3D.") + st.caption("Streuung (Kugel, Würfel, Zylinder, Quader, auch über Schichtstapeln, hp-adaptiv), Resonanzen, Bandstruktur eines kubischen Kristalls, Wellenleiter und Ports. " + "hp-FEM: Scattering3D, Resonance3D, BandStructure3D, s_parameters, AdaptiveMesh3D, LayerStack3D; Netze: Bibliothek, Gmsh, eigene Datei.") if S.td_proc is not None: return _running() if not (ctx["FEATS"].get("threed") or ctx["lib"].get("error")): st.warning("Das eingestellte Python hat kein hpfem mit den 3D-Lösern. Anzeigen geht trotzdem.") + elif not (ctx["FEATS"].get("threed_ext") or ctx["lib"].get("error")): + st.warning("Dem hpfem fehlen Schichtstapel, hp-Adaptivität oder Ports in 3D (ältere Version): diese Aufgaben schlagen im Worker fehl.") + if ctx["FEATS"].get("gmsh") is False and not ctx["lib"].get("error"): + st.warning("Im hpfem-Python fehlt das Modul `gmsh` (pip install gmsh): Gmsh-Geometrien gehen nicht; Bibliotheksnetze, hochgeladene .msh-Dateien und Wellenleiter schon.") t1, t2, t3, t4 = st.tabs(["1 Modell", "2 Rechnung", "3 Ergebnisse", "4 Info"]) with t1: - _tab_model() + _tab_model(ctx, work) with t2: _tab_run(ctx, work) with t3: @@ -98,41 +124,186 @@ def _num(col, label, key, value, step=0.1, lo=0.0, hi=1e6, help=None, fmt="%.5g" # ===================================================================================================================== model -def _tab_model(): +def _rename(m, old, new): + m["materials"] = {(new if k == old else k): v for k, v in m["materials"].items()} + if m["object"] == old: + m["object"] = new + st_ = m["stack"] + for key in ("incidence", "substrate"): + if st_[key] == old: + st_[key] = new + for layer in st_["layers"]: + if layer["material"] == old: + layer["material"] = new + f = m["file"] + f["tag_material"] = {t: (new if nm == old else nm) for t, nm in f["tag_material"].items()} + + +def _head(m, ver): + presets = ft.presets() + c = st.columns([3, 1]) + pick = c[0].selectbox("Vorlage", ["– auswählen –"] + list(presets), key="td_preset") + if c[1].button("Laden", key="td_preset_load", disabled=pick.startswith("–")): + S.td_model = copy.deepcopy(presets[pick]) + S.td_est = None + _bump() + st.rerun() + m["name"] = st.text_input("Name", value=m["name"], key=f"td_name_{ver}") + m["task"] = st.radio("Aufgabe", list(ft.TASKS), index=list(ft.TASKS).index(m["task"]), format_func=ft.TASKS.get, key=f"td_task_{ver}") + + +def _tab_model(ctx, work): m, ver = S.td_model, S.td_ver + _head(m, ver) + if m["task"] == "ports": + return pa3.tab_model(m["p3"], ver, _bump, ctx, work) left, right = st.columns([6, 5]) with left: - presets = ft.presets() - c = st.columns([3, 1]) - pick = c[0].selectbox("Vorlage", ["– auswählen –"] + list(presets), key="td_preset") - if c[1].button("Laden", key="td_preset_load", disabled=pick.startswith("–")): - S.td_model = copy.deepcopy(presets[pick]) - S.td_est = None - _bump() - st.rerun() - m["name"] = st.text_input("Name", value=m["name"], key=f"td_name_{ver}") - m["task"] = st.radio("Aufgabe", list(ft.TASKS), index=list(ft.TASKS).index(m["task"]), format_func=ft.TASKS.get, key=f"td_task_{ver}") - m["shape"] = st.radio("Form", list(ft.SHAPES), index=list(ft.SHAPES).index(m["shape"]), format_func=ft.SHAPES.get, key=f"td_shape_{ver}", horizontal=True) if m["task"] == "bands": + m["shape"] = st.radio("Form", list(ft.SHAPES), index=list(ft.SHAPES).index(m["shape"]), format_func=ft.SHAPES.get, key=f"td_shape_{ver}", horizontal=True) b = m["bands"] c = st.columns(3) b["radius"] = _num(c[0], "Radius bzw. halbe Kante (a)", f"td_br_{ver}", b["radius"], 0.05, 0.02, 0.49, "Einheiten der Gitterkonstante a; die Zelle ist [−0,5, 0,5]³.") b["eps"] = _num(c[1], "ε des Objekts", f"td_be_{ver}", b["eps"], 0.5, 0.01, 400.0) b["eps_bg"] = _num(c[2], "ε des Hintergrunds", f"td_bb_{ver}", b["eps_bg"], 0.5, 0.01, 400.0) else: - m["radius_nm"] = _num(st, "Radius bzw. halbe Kante (nm)", f"td_r_{ver}", m["radius_nm"], 5.0, 1.0, 1e6) - st.subheader("Material des Objekts") + m["mesh_kind"] = st.radio("Netz", list(ft.MESH_KINDS), index=list(ft.MESH_KINDS).index(m["mesh_kind"]), format_func=ft.MESH_KINDS.get, key=f"td_mk_{ver}", + help="Bibliotheksnetz: Kugel (gekrümmt) oder Würfel in einer PML-Box, ohne Gmsh. Gmsh-Geometrie: Kugel, Zylinder oder Quader, wahlweise über einem " + "Schichtstapel. Eigene Datei: ein Gmsh-Netz mit Tabelle Zellmarke → Material.") + if m["mesh_kind"] == "builtin": + m["shape"] = st.radio("Form", list(ft.SHAPES), index=list(ft.SHAPES).index(m["shape"]), format_func=ft.SHAPES.get, key=f"td_shape_{ver}", horizontal=True) + m["radius_nm"] = _num(st, "Radius bzw. halbe Kante (nm)", f"td_r_{ver}", m["radius_nm"], 5.0, 1.0, 1e6) + elif m["mesh_kind"] == "gmsh": + _gmsh_geometry(m, ver) + else: + _file_import(m, ver, ctx, work) + st.subheader("Materialien") lam0 = ft.lam_check(m)[0] if ft.lam_check(m) else 500.0 - ui.material_editor(m, ver, lam0, {m["object"]}, _rename, _bump, prefix="td_") + used = {m["object"]} | set(ft.stack_regions(m) if m["stack"]["enabled"] else []) | set(m["file"]["tag_material"].values()) + ui.material_editor(m, ver, lam0, used, _rename, _bump, prefix="td_") names = list(m["materials"]) - m["object"] = st.selectbox("Objekt besteht aus", names, index=names.index(m["object"]) if m["object"] in names else 0, key=f"td_obj_{ver}", - help="Umgebung ist Luft (ε = 1). Die Permittivität wird bei jeder Wellenlänge des Durchlaufs ausgewertet (Resonanzen: bei der Zielwellenlänge).") + if m["mesh_kind"] != "file": + m["object"] = st.selectbox("Objekt besteht aus", names, index=names.index(m["object"]) if m["object"] in names else 0, key=f"td_obj_{ver}", + help="Umgebung ist Luft (ε = 1), beim Schichtstapel das Einfallsmedium. Die Permittivität wird bei jeder Wellenlänge des Durchlaufs ausgewertet " + "(Resonanzen: bei der Zielwellenlänge).") + if m["task"] == "scatter" and m["mesh_kind"] == "gmsh": + _stack_editor(m, ver) with right: for lvl, text in ft.validate(m): (st.error if lvl == "error" else st.warning)(text) - st.markdown("**Aufbau.** " + ("Einfach kubisches Gitter, Gitterkonstante a = 1, Zelle [−½, ½]³, ein Objekt in der Mitte; Pfad Γ–X–M–R–Γ." - if m["task"] == "bands" else - "Das Objekt sitzt im Ursprung einer Box mit PML-Rand. Ebene Welle x-polarisiert längs +z. Das Netz sehen Sie nach „Netz prüfen“ im Reiter 2.")) + st.markdown("**Aufbau.** " + _aufbau(m)) + + +def _aufbau(m): + if m["task"] == "bands": + return "Einfach kubisches Gitter, Gitterkonstante a = 1, Zelle [−½, ½]³, ein Objekt in der Mitte; Pfad Γ–X–M–R–Γ." + base = "Ebene Welle x-polarisiert längs +z. " if not m["stack"]["enabled"] else "Ebene Welle von oben auf den Schichtstapel (Einfallswinkel, s oder p wählbar). " + if m["mesh_kind"] == "gmsh": + g = m["gmsh"] + what = {"sphere": "Kugel", "cylinder": "Zylinder (Achse z)", "block": "Quader"}[g["kind"]] + pos = " über dem Stapel (Oberkante z = 0)" if m["stack"]["enabled"] and m["task"] == "scatter" else " im Ursprung" + return f"{what}{pos}, Box mit PML-Rand, Netz von Gmsh (Elemente zweiter Ordnung, gekrümmt). " + base + "Das Netz sehen Sie nach „Netz prüfen“ im Reiter 2." + if m["mesh_kind"] == "file": + return "Ihr Gmsh-Netz; die äußeren Randflächen werden zu den Seiten der Box (PEC), die PML-Schicht liegt im äußersten Bereich der Box. " + base + return "Das Objekt sitzt im Ursprung einer Box mit PML-Rand. " + base + "Das Netz sehen Sie nach „Netz prüfen“ im Reiter 2." + + +def _gmsh_geometry(m, ver): + g = m["gmsh"] + g["kind"] = st.radio("Körper", list(ft.gm.KINDS), index=list(ft.gm.KINDS).index(g["kind"]), format_func=ft.gm.KINDS.get, key=f"td_gk_{ver}", horizontal=True) + c = st.columns(3) + if g["kind"] in ("sphere", "cylinder"): + m["radius_nm"] = _num(c[0], "Radius (nm)", f"td_r_{ver}", m["radius_nm"], 5.0, 1.0, 1e6) + if g["kind"] == "cylinder": + g["height_nm"] = _num(c[1], "Höhe (nm)", f"td_gh_{ver}", g["height_nm"], 5.0, 1.0, 1e6, "Achse längs z.") + if g["kind"] == "block": + g["lx_nm"] = _num(c[0], "Länge x (nm)", f"td_glx_{ver}", g["lx_nm"], 5.0, 1.0, 1e6) + g["ly_nm"] = _num(c[1], "Länge y (nm)", f"td_gly_{ver}", g["ly_nm"], 5.0, 1.0, 1e6) + g["lz_nm"] = _num(c[2], "Höhe z (nm)", f"td_glz_{ver}", g["lz_nm"], 5.0, 1.0, 1e6) + + +def _stack_editor(m, ver): + s = m["stack"] + with st.expander("Substrat und Schichtstapel (LayerStack3D)", expanded=bool(s["enabled"])): + s["enabled"] = st.checkbox("Objekt über einem Schichtstapel", value=bool(s["enabled"]), key=f"td_st_on_{ver}", + help="Die Hintergrundlösung ist der analytische Schichtstapel (Fresnel / Airy); das Objekt streut nur die Abweichung. Die Grenzflächen sind Ebenen im " + "Gmsh-Netz. Die Oberkante des Stapels liegt bei z = 0, das Objekt darüber (Abstand), der Stapel nach unten: Schichten, dann das Substrat.") + if not s["enabled"]: + return + names = list(m["materials"]) + + def pick(label, key, cur): + return st.selectbox(label, names, index=names.index(cur) if cur in names else 0, key=key) + + s["incidence"] = pick("Einfallsmedium oben (verlustfrei)", f"td_st_inc_{ver}", s["incidence"]) + for k, layer in enumerate(s["layers"]): + c = st.columns([3, 2, 1]) + layer["material"] = pick(f"Schicht {k + 1}", f"td_st_lm_{ver}_{k}", layer["material"]) + layer["thickness_nm"] = _num(c[1], "Dicke (nm)", f"td_st_lt_{ver}_{k}", layer["thickness_nm"], 5.0, 0.1, 1e6) + if c[2].button("Entfernen", key=f"td_st_ld_{ver}_{k}"): + s["layers"].pop(k) + _bump() + st.rerun() + if st.button("Schicht hinzufügen", key=f"td_st_add_{ver}"): + s["layers"].append({"material": names[min(1, len(names) - 1)], "thickness_nm": 50.0}) + _bump() + st.rerun() + s["substrate"] = pick("Substrat unten", f"td_st_sub_{ver}", s["substrate"]) + c = st.columns(3) + s["gap_nm"] = _num(c[0], "Abstand Objekt – Oberfläche (nm)", f"td_st_gap_{ver}", s["gap_nm"], 5.0, 0.0, 1e5, "0: das Objekt sitzt auf der Oberfläche (Zylinder, Quader). Kugeln brauchen Abstand.") + s["depth_nm"] = _num(c[1], "Tiefe des Substrats bis zum PML (nm)", f"td_st_dep_{ver}", s["depth_nm"], 10.0, 1.0, 1e6) + s["angle_deg"] = _num(c[2], "Einfallswinkel (°)", f"td_st_ang_{ver}", s["angle_deg"], 5.0, 0.0, 89.0) + c = st.columns(2) + s["pol"] = c[0].radio("Polarisation", list(ft.POLS), index=list(ft.POLS).index(s["pol"]), format_func=ft.POLS.get, key=f"td_st_pol_{ver}", horizontal=True, + help="s: E senkrecht zur Einfallsebene; p: E in der Einfallsebene. Bei senkrechtem Einfall gilt der Azimut (Richtung von E gegen x).") + s["azimuth_deg"] = _num(c[1], "Azimut der Einfallsebene (°)", f"td_st_az_{ver}", s["azimuth_deg"], 15.0, -360.0, 360.0) + regs = ft.stack_regions(m) + st.caption("Aufbau von oben nach unten: " + " → ".join(f"{nm}" + (f" ({s['layers'][k - 1]['thickness_nm']:g} nm)" if 0 < k < len(regs) - 1 else "") for k, nm in enumerate(regs))) + + +def _file_import(m, ver, ctx, work): + f = m["file"] + up = st.file_uploader("Gmsh-Datei (.msh, Version 4.1 ASCII)", type=["msh"], key=f"td_fup_{ver}") + if up is not None and up.name != f.get("name"): + folder = Path(work) / "files" + folder.mkdir(parents=True, exist_ok=True) + path = folder / "mesh.msh" + path.write_bytes(up.getvalue()) + f.update(name=up.name, path=str(path), tags={}, tag_material={}, object_tags=[]) + _bump() + st.rerun() + if not f.get("name"): + st.info("Eine .msh-Datei hochladen. Zellen tragen die Marke der physikalischen Gruppe, im Netz muss die Box mit Luft und PML-Bereich enthalten sein.") + return + c = st.columns([1, 1, 2]) + f["scale"] = c[0].selectbox("Einheit der Koordinaten", ["nm", "µm", "mm", "m"], index=["nm", "µm", "mm", "m"].index(f["scale"]), key=f"td_funit_{ver}") + if c[1].button("Datei lesen", key=f"td_fread_{ver}"): + info = ft.run_inspect(ctx["py"], ctx["repo"], Path(work) / "files" / "inspect", f["path"], f["scale"], "scatter", int(ctx["threads"])) + if "error" in info: + st.error(info["error"]) + else: + f["tags"] = info + names = list(m["materials"]) + for tag in info["cells"]: + f["tag_material"].setdefault(tag, ft.AIR if ft.AIR in names else names[0]) + _bump() + st.rerun() + info = f.get("tags") + if not info: + return + ext = [(b - a) / 1e-9 for a, b in zip(info["bbox"][0], info["bbox"][1])] + st.caption(f"{info['n_cells']} Zellen, Geometrieordnung {info.get('geometry_order', '?')}, Ausdehnung {ext[0]:.0f} × {ext[1]:.0f} × {ext[2]:.0f} nm; Flächenmarken: " + + (", ".join(f"{t} ({n})" for t, n in info["facets"].items()) or "keine")) + names = list(m["materials"]) + obj = [] + for tag, count in info["cells"].items(): + c = st.columns([3, 2]) + cur = f["tag_material"].get(tag, names[0]) + f["tag_material"][tag] = c[0].selectbox(f"Zellmarke {tag} ({count} Zellen): Material", names, index=names.index(cur) if cur in names else 0, key=f"td_ftm_{ver}_{tag}") + if c[1].checkbox("Streukörper", value=int(tag) in f["object_tags"], key=f"td_fto_{ver}_{tag}", help="Um die Zellen mit dieser Marke wird die Fläche für die Wirkungsquerschnitte gelegt."): + obj.append(int(tag)) + f["object_tags"] = obj + f["pml_nm"] = _num(st, "PML-Dicke am Rand der Box (nm)", f"td_fpml_{ver}", f["pml_nm"], 10.0, 1.0, 1e6, "Das PML liegt im äußersten Bereich des Netzes; es muss mit mindestens zwei bis drei Zellen vernetzt sein.") # ===================================================================================================================== run @@ -152,10 +323,48 @@ def _estimate_box(est, m, ctx_threads): st.warning(f"Die Schätzung ({gb:.1f} GB) beansprucht mehr als 60 % des freien Hauptspeichers ({avail:.0f} GB); andere Prozesse könnten gestört werden.") +def _adaptive_params(m, ver): + a = m["adaptive"] + a["enabled"] = st.checkbox("hp-adaptive Verfeinerung (AdaptiveMesh3D)", value=bool(a["enabled"]), key=f"td_ad_on_{ver}", + help="Je Schritt: lösen, residualer Fehlerschätzer, Dörfler-Markierung, Entscheidung h oder p nach der Vorhersage, Verfeinern. Das Netz wächst, bis die Schrittzahl, " + "die Obergrenze für Unbekannte oder der Speicher erreicht ist. Querschnitte und Felder sind die des letzten Netzes.") + if a["enabled"]: + c = st.columns(4) + a["max_steps"] = int(c[0].number_input("Schritte", 1, 12, int(a["max_steps"]), key=f"td_ad_n_{ver}")) + a["theta"] = _num(c[1], "Dörfler-Anteil θ", f"td_ad_t_{ver}", a["theta"], 0.05, 0.05, 1.0, "Anteil des quadratischen Gesamtfehlers, den die markierten Zellen tragen.") + a["max_dofs"] = int(c[2].number_input("Obergrenze Unbekannte", 100, 400000, int(a["max_dofs"]), 1000, key=f"td_ad_d_{ver}", help="Ein weiterer Schritt wird nicht mehr gerechnet, wenn das nächste Netz größer wäre.")) + a["tol"] = _num(c[3], "Toleranz η/η₀ (0 = aus)", f"td_ad_tol_{ver}", a["tol"], 0.05, 0.0, 1.0, "Abbruch, wenn der Schätzer unter diesen Bruchteil seines Anfangswertes fällt.") + st.caption("Die Startordnung p ist die kleinste Ordnung; die Schritte erhöhen p dort, wo die Lösung glatt ist, und teilen Zellen dort, wo sie es nicht ist.") + + +def _gmsh_mesh_params(m, ver): + g = m["gmsh"] + c = st.columns(3) + g["hw_nm"] = _num(c[0], "Innenraum, halbe Breite (nm)", f"td_ghw_{ver}", g["hw_nm"], 10.0, 10.0, 1e6, "Bis hierher reicht die Box um das Objekt (x, y); danach beginnt das PML.") + g["pml_nm"] = _num(c[1], "PML-Dicke (nm)", f"td_gpml_{ver}", g["pml_nm"], 10.0, 10.0, 1e6, "Mindestens zwei bis drei ferne Zellen, sonst meldet die Bibliothek ein unteraufgelöstes PML und das Ergebnis ist falsch.") + g["clear_nm"] = _num(c[2], "Abstand über dem Objekt (nm)", f"td_gcl_{ver}", g["clear_nm"], 10.0, 10.0, 1e6, "Vom Objekt (bzw. der Oberkante) bis zum PML nach oben.") + c = st.columns(4) + g["h_obj_nm"] = _num(c[0], "Zelle am Objekt (nm)", f"td_gho_{ver}", g["h_obj_nm"], 5.0, 1.0, 1e5) + g["h_far_nm"] = _num(c[1], "Zelle fern (nm)", f"td_ghf_{ver}", g["h_far_nm"], 5.0, 5.0, 1e5, "In Medien mit Index n wird die Zelle durch n geteilt (Stapel).") + g["grade_nm"] = _num(c[2], "Übergangslänge (nm)", f"td_ggr_{ver}", g["grade_nm"], 10.0, 1.0, 1e6, "Abstand vom Objekt, über den die Zelle von „am Objekt“ auf „fern“ wächst.") + g["order"] = int(c[3].number_input("Geometrieordnung", 1, 2, int(g["order"]), key=f"td_gord_{ver}", help="2: gekrümmte Elemente (die Kugel wird exakt quadratisch approximiert).")) + if st.button("Maschenweiten vorschlagen", key=f"td_gsug_{ver}", help="Zelle am Objekt ≈ min(r/2,5; λ/(3n)), fern ≈ λ/2,5, PML ≈ λ/2, Innenraum ≈ 1,5 r (aus der kürzesten Wellenlänge)."): + g.update(ft.suggest_sizes(m)) + _bump() + st.rerun() + st.caption(f"PML = {g['pml_nm'] / max(g['h_far_nm'], 1e-9):.1f} ferne Zellen dick (mindestens 2 bis 3 nötig). Gemessen an einer Kugel n = 2, ka = 1: mit PML = 2 Zellen, Zelle fern λ/4 und p = 2 liegt Q_sca " + "innerhalb 1 % der Mie-Reihe; mit einer Zelle im PML 25 % daneben.") + + def _tab_run(ctx, work): m, ver = S.td_model, S.td_ver t = m["task"] - if t == "scatter": + if t == "ports": + pa3.tab_params(m["p3"], ver) + c = st.columns(1) + m["max_gb"] = _num(c[0], "Speichergrenze (GB)", f"td_mg_{ver}", m["max_gb"], 2.0, 0.5, 1000.0, "Der Worker bricht ab, wenn die Schätzung der Bibliothek darüber liegt.") + m["p3"]["max_gb"] = m["max_gb"] + elif t == "scatter": st.subheader("Wellenlängen") s = m["sweep"] c = st.columns(3) @@ -178,20 +387,26 @@ def _tab_run(ctx, work): b["bands"] = int(c[1].number_input("Zahl der Bänder", 1, 20, int(b["bands"]), key=f"td_bn_{ver}")) b["cells"] = int(c[2].number_input("Zellen je Kante (Würfel)", 2, 40, int(b["cells"]), 2, key=f"td_bc_{ver}", help="Nur für die Form Würfel.")) b["krylov"] = int(c[3].number_input("Krylov-Dimension (0 = auto)", 0, 600, int(b["krylov"]), 10, key=f"td_bk_{ver}")) - st.subheader("Netz und Ordnung") - c = st.columns(5) - if t == "bands": - m["n"] = int(c[0].number_input("Zellen je Radius (n, Kugel)", 1, 12, int(m["n"]), key=f"td_n_{ver}")) - else: - m["n"] = int(c[0].number_input("Zellen je Radius (n)", 1, 12, int(m["n"]), key=f"td_n_{ver}", help="Bei der Kugel: Zellen auf dem Radius; beim Würfel: Zellen auf der halben Kante.")) - m["half_width"] = _num(c[1], "Innenraum (halbe Breite, in r)", f"td_hw_{ver}", m["half_width"], 0.5, 1.0, 20.0, "Die Box um das Objekt bis zum PML.") - m["outer"] = _num(c[2], "Außenrand (in r)", f"td_ou_{ver}", m["outer"], 0.5, 1.5, 30.0, "Ende des PML; zwischen Innenraum und Außenrand liegt die Schicht.") - m["order"] = int(c[3].number_input("Ordnung p", 1, 6, int(m["order"]), key=f"td_p_{ver}")) - if t == "scatter": - m["quarter"] = c[4].checkbox("Viertelmodell", value=bool(m["quarter"]), key=f"td_q_{ver}", help=ft.SYM[True] + ": nur für die x-polarisierte Welle längs z; Faktor 4 weniger Speicher.") - c = st.columns(2) - m["fields"] = c[0].checkbox("Feldschnitte speichern", value=bool(m["fields"]), key=f"td_f_{ver}", disabled=t == "bands", help="|E|² auf zwei Ebenen je Wellenlänge bzw. Mode.") - m["max_gb"] = _num(c[1], "Speichergrenze (GB)", f"td_mg_{ver}", m["max_gb"], 2.0, 0.5, 1000.0, "Der Worker bricht ab, wenn die Schätzung der Bibliothek darüber liegt.") + if t != "ports": + st.subheader("Netz und Ordnung") + kind = "builtin" if t == "bands" else m["mesh_kind"] + if kind == "gmsh": + _gmsh_mesh_params(m, ver) + c = st.columns(5) + if t == "bands": + m["n"] = int(c[0].number_input("Zellen je Radius (n, Kugel)", 1, 12, int(m["n"]), key=f"td_n_{ver}")) + elif kind == "builtin": + m["n"] = int(c[0].number_input("Zellen je Radius (n)", 1, 12, int(m["n"]), key=f"td_n_{ver}", help="Bei der Kugel: Zellen auf dem Radius; beim Würfel: Zellen auf der halben Kante.")) + m["half_width"] = _num(c[1], "Innenraum (halbe Breite, in r)", f"td_hw_{ver}", m["half_width"], 0.5, 1.0, 20.0, "Die Box um das Objekt bis zum PML.") + m["outer"] = _num(c[2], "Außenrand (in r)", f"td_ou_{ver}", m["outer"], 0.5, 1.5, 30.0, "Ende des PML; zwischen Innenraum und Außenrand liegt die Schicht.") + m["order"] = int(c[3].number_input("Ordnung p", 1, 6, int(m["order"]), key=f"td_p_{ver}")) + if t == "scatter" and kind == "builtin": + m["quarter"] = c[4].checkbox("Viertelmodell", value=bool(m["quarter"]), key=f"td_q_{ver}", help=ft.SYM[True] + ": nur für die x-polarisierte Welle längs z; Faktor 4 weniger Speicher.") + if t == "scatter": + _adaptive_params(m, ver) + c = st.columns(2) + m["fields"] = c[0].checkbox("Feldschnitte speichern", value=bool(m["fields"]), key=f"td_f_{ver}", disabled=t == "bands", help="|E|² auf zwei Ebenen je Wellenlänge bzw. Mode.") + m["max_gb"] = _num(c[1], "Speichergrenze (GB)", f"td_mg_{ver}", m["max_gb"], 2.0, 0.5, 1000.0, "Der Worker bricht ab, wenn die Schätzung der Bibliothek darüber liegt.") errs = [x for lvl, x in ft.validate(m) if lvl == "error"] for e in errs: st.error(e) @@ -199,7 +414,7 @@ def _tab_run(ctx, work): c = st.columns([1, 2]) if c[0].button("Netz prüfen und Speicher schätzen", key="td_est_btn", disabled=bool(errs)): with st.spinner("Netz wird erzeugt …"): - S.td_est = ft.run_estimate(ctx["py"], ctx["repo"], folder, ft.job(m), int(ctx["threads"])) + S.td_est = ft.run_estimate(ctx["py"], ctx["repo"], folder, ft.job(m), int(ctx["threads"]), timeout=600) S.td_est_model = copy.deepcopy(m) est = S.get("td_est") _estimate_box(est, m, ctx["threads"]) @@ -210,8 +425,8 @@ def _tab_run(ctx, work): unit, lab = (1.0, "a") if t == "bands" else (1e-9, "nm") lo, hi = float(npz["vertices"][:, axis].min() / unit), float(npz["vertices"][:, axis].max() / unit) coord = st.slider("Lage der Ebene", lo, hi, min(max(0.0, lo), hi) if lo <= 0 <= hi else (lo + hi) / 2, (hi - lo) / 100 or 0.01, key=f"td_mesh_c_{axis}") - ui.show_fig(ft.fig_mesh(npz, axis, coord * unit, unit, lab), "netz.png", "td_dl_mesh") - st.caption("Gerade Tetraederkanten; bei der Kugel liegt der Rand im Löser exakt (gekrümmte Elemente). Orange: Zellen des Objekts.") + ui.show_fig(ft.fig_mesh(npz, axis, coord * unit, unit, lab, obj_tags=ft.object_cell_tags(m)), "netz.png", "td_dl_mesh") + st.caption("Gerade Tetraederkanten; gekrümmte Ränder liegen im Löser exakt. Orange: Zellen des Objekts, übrige Farben: weitere Materialien (Stapel, Marken).") st.markdown("---") stale = est is not None and S.get("td_est_model") is not None and ft.job(S.td_est_model) != ft.job(m) if stale: @@ -219,10 +434,12 @@ def _tab_run(ctx, work): if st.button("Rechnen", type="primary", key="td_run", disabled=bool(errs)): try: work.mkdir(parents=True, exist_ok=True) - (work / "job.json").write_text(json.dumps(ft.job(m), ensure_ascii=False), encoding="utf-8") - for f in work.glob("field_*.npz"): - f.unlink() - S.td_proc = fr.start_worker(ctx["py"], ctx["repo"], work, int(ctx["threads"]), script="fem_threed_worker.py") + jb = ft.job(m) + (work / "job.json").write_text(json.dumps(jb, ensure_ascii=False), encoding="utf-8") + for f in list(work.glob("field_*.npz")) + list(work.glob("mesh_*.npz")) + [work / "results.json"]: + if f.exists(): + f.unlink() + S.td_proc = fr.start_worker(ctx["py"], ctx["repo"], work, int(ctx["threads"]), script=ft.worker_script(jb)) S.td_dir, S.td_cancel, S.td_run_model = str(work), False, copy.deepcopy(m) st.rerun() except Exception as exc: @@ -231,7 +448,11 @@ def _tab_run(ctx, work): (st.success if S.td_msg[0] == "ok" else st.error)(S.td_msg[1] + (" Die Ergebnisse stehen im Reiter 3." if S.td_msg[0] == "ok" else "")) if (work / "log.txt").is_file(): with st.expander("Protokoll der letzten Rechnung"): - st.code(fr.read_log(work, tail=40)) + log = fr.read_log(work, tail=40) + st.code(log) + if "PML is under-resolved" in log or "under-resolved" in log: + st.warning("Die Bibliothek meldet ein unteraufgelöstes PML: das PML braucht mindestens zwei bis drei Zellen Dicke (bei Ordnung 1 mehr) oder ein feineres Netz im PML-Gebiet; " + "die Querschnitte sind dann nur Richtwerte.") def _running(): @@ -277,6 +498,8 @@ def _tab_results(work): _res_scatter(res, work, model, meta) elif task == "resonance": _res_resonance(res, work, model, meta) + elif task == "ports": + pa3.results(res, work, model) else: _res_bands(res, model) @@ -285,8 +508,7 @@ def _field_view(npz_path, quarter, model, key_prefix, title): npz = np.load(npz_path) c = st.columns(2) sel = c[0].radio("Ebene", ["xz", "xy"], format_func={"xz": "x–z (y = 0, Welle längs z)", "xy": "x–y (z = 0)"}.get, horizontal=True, key=f"{key_prefix}_pl") - radius = float(model["radius_nm"]) * 1e-9 - ui.show_fig(ft.fig_field(npz, sel, quarter, 1e-9, "nm", radius, model["shape"], title), f"feld_{sel}.png", f"{key_prefix}_dl") + ui.show_fig(ft.fig_field(npz, sel, quarter, 1e-9, "nm", title=title, outline=[(x, y, s) for x, y, s in ft.object_outline(model, sel)]), f"feld_{sel}.png", f"{key_prefix}_dl") def _res_scatter(res, work, model, meta): @@ -297,7 +519,8 @@ def _res_scatter(res, work, model, meta): ok = [p for p in pts if "q_sca" in p] if not ok: return - sub = st.tabs(["Wirkungsquerschnitte", "Felder", "Tabelle"]) + steps = [p for p in ok if p.get("steps")] + sub = st.tabs(["Wirkungsquerschnitte", "Felder", "hp-Verfeinerung", "Netz", "Tabelle"]) with sub[0]: if len(ok) > 1: ui.show_fig(ft.fig_efficiency(ok), "effizienz.png", "td_dl_eff") @@ -307,7 +530,10 @@ def _res_scatter(res, work, model, meta): worst = max(abs(p["q_sca"] - p["mie_q_sca"]) / max(abs(p["mie_q_sca"]), 1e-30) for p in ok) * 100 st.caption(f"Größte Abweichung Q_sca zur Mie-Reihe: {worst:.1f} %. Das ist das Maß für die Netzgüte (Q_abs bei verlustfreier Kugel: Fehler des Flussintegrals).") else: - st.caption("Würfel: keine analytische Referenz. Konvergenz prüfen, indem n und p erhöht werden.") + st.caption("Keine analytische Referenz für diese Geometrie. Konvergenz prüfen, indem Netz und p verfeinert werden (oder die hp-Verfeinerung nutzen).") + if "stack_R" in ok[0]: + st.caption("R, T, A des Schichtstapels ohne Objekt (analytisch) stehen in der Tabelle; Q ist auf die Projektion des Objekts auf die x-y-Ebene bezogen, die Querschnitte σ auf die " + "Intensität der einfallenden Welle (Poynting-Fluss von |E| = 1 V/m im Einfallsmedium).") with sub[1]: withf = [p for p in ok if p.get("field_file")] if not withf: @@ -317,6 +543,30 @@ def _res_scatter(res, work, model, meta): _field_view(work / withf[i]["field_file"], bool(meta.get("quarter")), model, "td_sc", f"|E|²/|E₀|² bei {withf[i]['lam_nm']:g} nm") st.caption("Gestrichelt: Umriss des Objekts. Im Viertelmodell wird das berechnete Viertel an den Symmetrieebenen gespiegelt; die Welle läuft in +z.") with sub[2]: + if not steps: + st.info("Die hp-adaptive Verfeinerung war nicht eingeschaltet (Reiter 2).") + else: + j = st.selectbox("Wellenlänge", range(len(steps)), format_func=lambda j: f"{steps[j]['lam_nm']:g} nm", key="td_ad_lam") if len(steps) > 1 else 0 + ps = steps[j] + ui.show_fig(ft.fig_convergence(ps["steps"]), "hp_konvergenz.png", "td_dl_conv") + ui.table_show(ft.steps_dataframe(ps["steps"]).round(5)) + st.caption(f"Abbruch: {ps.get('stop_reason', '—')}. η ist der residuale Fehlerschätzer der Bibliothek (Summe der Elementindikatoren); er fällt mit den Schritten, aber Q_sca " + "konvergiert nicht zwingend monoton: bei grobem PML dominiert dessen Diskretisierungsfehler, den der Schätzer nur teilweise sieht. Dörfler-Markierung, " + "Entscheidung h/p nach der Vorhersage (Melenk–Wohlmuth).") + with sub[3]: + npz_path = work / "mesh_scatter.npz" + if not npz_path.is_file(): + st.info("Kein Netz gespeichert.") + else: + npz = np.load(npz_path) + by = "tag" + if "orders" in npz.files and steps: + by = "order" if st.radio("Färbung", ["Material", "Ordnung p"], horizontal=True, key="td_res_mesh_by") == "Ordnung p" else "tag" + axis = {"x": 0, "y": 1, "z": 2}[st.radio("Schnittebene senkrecht zu", ["x", "y", "z"], index=1, horizontal=True, key="td_res_mesh_axis")] + lo, hi = float(npz["vertices"][:, axis].min() * 1e9), float(npz["vertices"][:, axis].max() * 1e9) + coord = st.slider("Lage der Ebene (nm)", lo, hi, min(max(0.0, lo), hi) if lo <= 0 <= hi else (lo + hi) / 2, (hi - lo) / 100 or 0.01, key=f"td_res_mesh_c_{axis}") + ui.show_fig(ft.fig_mesh(npz, axis, coord * 1e-9, 1e-9, "nm", obj_tags=ft.object_cell_tags(model), by=by), "netz_ergebnis.png", "td_dl_res_mesh") + with sub[4]: df = ft.scatter_dataframe(ok) c = st.columns(2) c[0].download_button("Tabelle (CSV)", ui.csv_bytes(df), file_name="streuung_3d.csv", mime="text/csv", key="td_dl_csv") diff --git a/fem_gui/fem_threed_gmsh.py b/fem_gui/fem_threed_gmsh.py new file mode 100644 index 0000000..dab922c --- /dev/null +++ b/fem_gui/fem_threed_gmsh.py @@ -0,0 +1,188 @@ +"""Gmsh meshes for the 3D modes of the FEM model builder (hp-FEM 0.5). Needs the Python module ``gmsh`` and NumPy, not hpfem, so it can be tested without the library +and runs inside the worker (fem_threed_worker.py, fem_ports3d_worker.py). Lengths are in nm; the worker reads the file with ``hpfem.read_gmsh(path, scale=1e-9, dim=3)``. + +``scene(g, path)``: one object (sphere, cylinder with axis z, block) in a box [-hw, hw]^2 x [z_lo - pml, z_hi + pml], optionally above a planar layer stack +(interfaces z = 0, -d1, -d1 - d2, ...; the last region is the substrate). Every region of the stack is its own volume, so the interfaces are mesh facets (a +requirement of the scattered-field formulation with a layered background). Physical groups: volumes TAG_OBJ (object) and TAG_REGION0 + k (region k from the top: +0 = incidence medium), surfaces 1..6 = the box sides X_MIN, X_MAX, Y_MIN, Y_MAX, Z_MIN, Z_MAX (the numbering of ``hpfem.box_tag``). Second-order (curved) elements by +default. The straight guide and the coupler of the task "ports" use structured meshes (fem_ports3d_worker.py), not Gmsh. +""" +from __future__ import annotations + +TAG_OBJ = 2 +TAG_REGION0 = 11 +KINDS = {"sphere": "Kugel", "cylinder": "Zylinder (Achse z)", "block": "Quader"} + + +def object_extent(g): + """(half width in x, half width in y, height) of the object [nm].""" + k = g["kind"] + if k == "sphere": + return g["r"], g["r"], 2 * g["r"] + if k == "cylinder": + return g["r"], g["r"], g["h"] + return g["lx"] / 2, g["ly"] / 2, g["lz"] + + +def layout(g): + """Vertical layout [nm]: dict with z_lo, z_hi (interior of the PML box), interfaces (top to bottom), obj_z0 (lowest z of the object), zc (centre of the object), + regions = [(zmin, zmax)] from the top (region 0 reaches z_hi).""" + ox, oy, oh = object_extent(g) + layers = [float(t) for t in g.get("layers", [])] + stack = bool(g.get("stack", False)) + if stack: + gap = float(g.get("gap", 0.0)) + z0 = gap + ifaces = [0.0] + for t in layers: + ifaces.append(ifaces[-1] - t) + z_lo = ifaces[-1] - float(g.get("depth", 0.0)) + z_hi = z0 + oh + float(g.get("clear", 0.0)) + regions = [(ifaces[0], z_hi)] + [(ifaces[i + 1], ifaces[i]) for i in range(len(ifaces) - 1)] + [(z_lo, ifaces[-1])] + zc = z0 + oh / 2 + else: + z0 = -oh / 2 + ifaces = [] + z_lo, z_hi = -oh / 2 - float(g.get("clear", 0.0)), oh / 2 + float(g.get("clear", 0.0)) + regions = [(z_lo, z_hi)] + zc = 0.0 + return dict(z_lo=z_lo, z_hi=z_hi, interfaces=ifaces, obj_z0=z0, zc=zc, regions=regions) + + +def scene(g, path): + """Writes the Gmsh 4.1 ASCII mesh to `path` and returns info: tags, interior box, number of regions.""" + import gmsh + + lay = layout(g) + hw, pml = float(g["hw"]), float(g["pml"]) + X = hw + pml + zmin, zmax = lay["z_lo"] - pml, lay["z_hi"] + pml + cuts = sorted([z for z in lay["interfaces"]] + [lay["z_lo"], lay["z_hi"]]) if lay["interfaces"] else [lay["z_lo"], lay["z_hi"]] + cuts = sorted({round(z, 9) for z in cuts}) + edges = [zmin] + cuts + [zmax] + edges = sorted(set(round(e, 9) for e in edges)) + gmsh.initialize(interruptible=False) + try: + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("scene3d") + occ = gmsh.model.occ + slabs = [occ.addBox(-X, -X, a, 2 * X, 2 * X, b - a) for a, b in zip(edges[:-1], edges[1:])] + k = g["kind"] + zc = lay["zc"] + if k == "sphere": + obj = occ.addSphere(0, 0, zc, g["r"]) + elif k == "cylinder": + obj = occ.addCylinder(0, 0, lay["obj_z0"], 0, 0, g["h"], g["r"]) + else: + obj = occ.addBox(-g["lx"] / 2, -g["ly"] / 2, lay["obj_z0"], g["lx"], g["ly"], g["lz"]) + _, parts = occ.fragment([(3, s) for s in slabs], [(3, obj)]) + occ.synchronize() + obj_vols = {t for _, t in parts[-1]} + # region of every remaining volume by its z centre (the slabs are cut at the interfaces, so every piece lies in exactly one region) + regions = lay["regions"] + by_region = {i: [] for i in range(len(regions))} + for part in parts[:-1]: + for _, t in part: + if t in obj_vols: + continue + bb = gmsh.model.getBoundingBox(3, t) + zmid = 0.5 * (bb[2] + bb[5]) + idx = _region_of(regions, zmid, edges, lay) + if t not in by_region[idx]: + by_region[idx].append(t) + for i, vols in by_region.items(): + if vols: + gmsh.model.addPhysicalGroup(3, vols, TAG_REGION0 + i, f"region{i}") + gmsh.model.addPhysicalGroup(3, sorted(obj_vols), TAG_OBJ, "object") + all_vols = sorted(obj_vols | {t for vols in by_region.values() for t in vols}) + tol = 1e-6 * max(hw, 1.0) + sides = {1: [], 2: [], 3: [], 4: [], 5: [], 6: []} + for dim, tag in gmsh.model.getBoundary([(3, t) for t in all_vols], oriented=False): + x0, y0, z0_, x1, y1, z1_ = gmsh.model.getBoundingBox(dim, tag) + if x1 < -X + tol: + sides[1].append(tag) + elif x0 > X - tol: + sides[2].append(tag) + elif y1 < -X + tol: + sides[3].append(tag) + elif y0 > X - tol: + sides[4].append(tag) + elif z1_ < zmin + tol: + sides[5].append(tag) + elif z0_ > zmax - tol: + sides[6].append(tag) + for t, faces in sides.items(): + if faces: + gmsh.model.addPhysicalGroup(2, sorted(set(faces)), t, f"side{t}") + _sizing(g, lay, regions, all_vols, obj_vols, hw, X, edges) + gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0) + gmsh.option.setNumber("Mesh.Algorithm3D", 1) + order = int(g.get("order", 2)) + gmsh.option.setNumber("Mesh.ElementOrder", order) + gmsh.option.setNumber("Mesh.SecondOrderLinear", 0) + if order > 1: + gmsh.option.setNumber("Mesh.HighOrderOptimize", 1) + gmsh.model.mesh.generate(3) + gmsh.option.setNumber("Mesh.MshFileVersion", 4.1) + gmsh.option.setNumber("Mesh.Binary", 0) + gmsh.option.setNumber("Mesh.SaveAll", 0) + gmsh.write(str(path)) + finally: + gmsh.finalize() + return dict(regions=[TAG_REGION0 + i for i, v in by_region.items() if v], object_tag=TAG_OBJ, interior=[-hw, hw, lay["z_lo"], lay["z_hi"]], layout=lay, + outer=[X, zmin, zmax]) + + +def _region_of(regions, zmid, edges, lay): + """Index of the region [zmin, zmax] containing zmid (regions are listed from the top; region 0 = above the first interface).""" + for i, (a, b) in enumerate(regions): + if a - 1e-9 <= zmid <= b + 1e-9: + return i + # PML slabs above / below the interior: the first / last region + return 0 if zmid > lay["z_hi"] else len(regions) - 1 + + +def _sizing(g, lay, regions, all_vols, obj_vols, hw, X, edges): + import gmsh + + field = gmsh.model.mesh.field + h_obj, h_far = float(g["h_obj"]), float(g["h_far"]) + grade = float(g.get("grade", 3 * h_far)) + faces = [t for _, t in gmsh.model.getBoundary([(3, t) for t in sorted(obj_vols)], oriented=False)] + dist = field.add("Distance") + field.setNumbers(dist, "SurfacesList", faces) + field.setNumber(dist, "Sampling", 40) + thr = field.add("Threshold") + field.setNumber(thr, "InField", dist) + field.setNumber(thr, "SizeMin", h_obj) + field.setNumber(thr, "SizeMax", h_far) + field.setNumber(thr, "DistMin", 0.3 * h_obj) + field.setNumber(thr, "DistMax", grade) + fields = [thr] + ns = g.get("region_n", []) + for i, (a, b) in enumerate(regions): + n = float(ns[i]) if i < len(ns) else 1.0 + size = h_far / max(n, 1.0) + if i == len(regions) - 1 or i == 0: + a_ext = a - float(g["pml"]) if i == len(regions) - 1 else a + b_ext = b + float(g["pml"]) if i == 0 else b + else: + a_ext, b_ext = a, b + if len(regions) > 2 and 0 < i < len(regions) - 1: + size = min(size, 0.5 * (b - a)) # a finite layer carries at least two cells + box = field.add("Box") + field.setNumber(box, "VIn", size) + field.setNumber(box, "VOut", 10 * h_far) + field.setNumber(box, "XMin", -X) + field.setNumber(box, "XMax", X) + field.setNumber(box, "YMin", -X) + field.setNumber(box, "YMax", X) + field.setNumber(box, "ZMin", a_ext) + field.setNumber(box, "ZMax", b_ext) + field.setNumber(box, "Thickness", 0.0) + fields.append(box) + mn = field.add("Min") + field.setNumbers(mn, "FieldsList", fields) + field.setAsBackgroundMesh(mn) diff --git a/fem_gui/fem_threed_worker.py b/fem_gui/fem_threed_worker.py index 34c18d0..d0ae47e 100644 --- a/fem_gui/fem_threed_worker.py +++ b/fem_gui/fem_threed_worker.py @@ -8,9 +8,14 @@ x > 0, y > 0 (mirror symmetry of the wave: x = 0 PEC, y = 0 natural), as in the library benchmark (validation C). resonance Resonance3D: the complex eigenfrequencies of the object (lossy or lossless) with PML; frozen permittivity at the target wavelength. bands BandStructure3D: simple-cubic photonic crystal, sphere or cube in the unit cell (a = 1), lossless, path G-X-M-R-G. +Extensions: ``mesh_kind`` gmsh (own geometry from fem_threed_gmsh.py: sphere, cylinder, block, optionally above a planar layer stack) or file (uploaded .msh with a tag +to material table); ``stack`` (scatter): LayerStack3D as layered background, oblique incidence s / p, R / T / A of the bare stack; ``adaptive`` (scatter): +AdaptiveMesh3D with the residual estimator, Doerfler marking and the hp decision by prediction, convergence per step in results.json. With ``estimate`` only the mesh is built and hpfem.estimate_memory is printed (``ESTIMATE{json}``), mesh_.npz is written. Before every run the estimate is logged; a job whose estimate exceeds ``max_gb`` stops with ERROR. +With ``inspect`` the tags of the mesh file job["file"]["path"] are printed (``INSPECT{json}``). + Writes /results.json after every step and log lines on stdout (PROGRESS i/n, ERROR ..., CANCELLED, DONE). Cancellation: the file /cancel, checked between the steps (a single solve cannot be interrupted). """ @@ -24,9 +29,12 @@ import numpy as np +sys.path.insert(0, str(Path(__file__).resolve().parent)) + C0 = 299792458.0 TAG_OBJ = 2 TAG_SYM = 7 # cut x = 0 of the quarter model (PEC) +TAG_INSIDE = 99 # cells inside the measurement surface (on a copy of the mesh) when the object has several tags GRID = 41 @@ -35,8 +43,18 @@ def say(*a): # ------------------------------------------------------------------------------------------------------------------------------------ meshes -def build_mesh(h, job): - """(mesh, info). SI units for scatter / resonance (a = radius_nm), units of the lattice constant for bands.""" +def build_mesh(h, job, folder=None): + """(mesh, info). SI units for scatter / resonance (a = radius_nm), units of the lattice constant for bands. info: a (characteristic length), hw, outer, quarter, + object_tags, interior (x_lo, x_hi, z_lo, z_hi) of the PML box, area (reference cross-section), zc (height of the object centre), sphere (radius for Mie).""" + kind = job.get("mesh_kind", "builtin") + if kind == "gmsh" and job["task"] != "bands": + return build_gmsh(h, job, folder) + if kind == "file" and job["task"] != "bands": + return build_file(h, job) + return build_builtin(h, job) + + +def build_builtin(h, job): task, shape = job["task"], job["shape"] n, hw, outer = int(job["n"]), float(job["half_width"]), float(job["outer"]) if task == "bands": @@ -65,13 +83,82 @@ def build_mesh(h, job): continue if all(abs(mesh.vertex(int(v))[0]) < 1e-9 * max(a, 1e-30) + 1e-12 * a for v in mesh.facet_vertices(int(f))): mesh.set_facet_tag(int(f), TAG_SYM) - return mesh, dict(a=a, hw=hw, outer=outer, quarter=quarter) + area = np.pi * a * a if shape == "sphere" else (2 * a) ** 2 + return mesh, dict(a=a, hw=hw, outer=outer, quarter=quarter, object_tags=[TAG_OBJ], interior=[-hw, hw, -hw, hw], area=area, zc=0.0, kind="builtin", + sphere=a if shape == "sphere" else None) + + +def build_gmsh(h, job, folder): + """Own geometry with Gmsh (fem_threed_gmsh.scene), read with hpfem.read_gmsh; the mesh file is reused when the geometry is unchanged.""" + import fem_threed_gmsh as gm + + g = dict(job["g"]) + folder = Path(folder or ".") + path = folder / "scene.msh" + key = json.dumps(g, sort_keys=True) + keyfile = folder / "scene.key" + if not (path.is_file() and keyfile.is_file() and keyfile.read_text(encoding="utf-8") == key): + gi = gm.scene(g, path) + keyfile.write_text(key, encoding="utf-8") + mesh = h.read_gmsh(str(path), 1e-9, 3) + lay = gm.layout(g) + hw = g["hw"] * 1e-9 + ox, oy, oh = gm.object_extent(g) + area = {"sphere": np.pi * g["r"] ** 2, "cylinder": np.pi * g["r"] ** 2, "block": g["lx"] * g["ly"]}[g["kind"]] * 1e-18 + return mesh, dict(a=g["r"] * 1e-9 if "r" in g else g["lx"] * 0.5e-9, hw=hw, outer=hw + g["pml"] * 1e-9, quarter=False, object_tags=[gm.TAG_OBJ], + interior=[-hw, hw, lay["z_lo"] * 1e-9, lay["z_hi"] * 1e-9], area=area, zc=lay["zc"] * 1e-9, kind="gmsh", + sphere=g["r"] * 1e-9 if (g["kind"] == "sphere" and not g.get("stack")) else None, layout=lay) + + +def build_file(h, job): + """Uploaded mesh: scale to metres, the outer boundary facets without a tag get the box tags X_MIN ... Z_MAX (the PML box is the bounding box shrunk by the PML thickness).""" + f = job["file"] + mesh = h.read_gmsh(str(f["path"]), float(f["scale"]), 3) + v = np.asarray(mesh.vertices) + lo, hi = v.min(axis=0), v.max(axis=0) + tol = 1e-6 * float(np.max(hi - lo)) + t = h.box_tag + for fc in mesh.boundary_facets: + if mesh.facet_tag(int(fc)) != h.NO_TAG: + continue + pts = np.array([mesh.vertex(int(i)) for i in mesh.facet_vertices(int(fc))]) + for axis, (tmin, tmax) in enumerate(((t.X_MIN, t.X_MAX), (t.Y_MIN, t.Y_MAX), (t.Z_MIN, t.Z_MAX))): + if np.all(np.abs(pts[:, axis] - lo[axis]) < tol): + mesh.set_facet_tag(int(fc), tmin) + break + if np.all(np.abs(pts[:, axis] - hi[axis]) < tol): + mesh.set_facet_tag(int(fc), tmax) + break + pml = float(f["pml_nm"]) * 1e-9 + tags = [int(x) for x in f["object_tags"]] + cen = np.asarray(mesh.cell_centroids) + ctags = np.asarray(mesh.cell_tags) + sel = np.isin(ctags, tags) + zc = float(cen[sel, 2].mean()) if sel.any() else 0.0 + ext = np.zeros(3) + area = 1.0 + if sel.any(): + pts = np.array([mesh.vertex(int(i)) for c in np.nonzero(sel)[0] for i in mesh.cell_vertices(int(c))]) + ext = pts.max(axis=0) - pts.min(axis=0) + area = projected_area_xy(h, mesh, tags) or float(ext[0] * ext[1]) + return mesh, dict(a=float(max(ext) / 2) if sel.any() else 1.0, hw=float(hi[0] - pml), outer=float(hi[0]), quarter=False, object_tags=tags, + interior=[float(lo[0] + pml), float(hi[0] - pml), float(lo[2] + pml), float(hi[2] - pml)], interior_y=[float(lo[1] + pml), float(hi[1] - pml)], + pml=pml, area=area, zc=zc, kind="file", sphere=None) def pml_box(h, job, info, k0): + prof = h.PmlProfile(int(job.get("pml_order", 3)), float(job.get("pml_reflection", 1e-8))) + if info["kind"] == "gmsh": + x0, x1, z0, z1 = info["interior"] + pml = float(job["g"]["pml"]) * 1e-9 + return h.PmlBox3D(np.array([x0, x0, z0]), np.array([x1, x1, z1]), [pml] * 6, k0, 1.0, prof) + if info["kind"] == "file": + x0, x1, z0, z1 = info["interior"] + y0, y1 = info["interior_y"] + pml = info["pml"] + return h.PmlBox3D(np.array([x0, y0, z0]), np.array([x1, y1, z1]), [pml] * 6, k0, 1.0, prof) hw, outer = info["hw"], info["outer"] d = outer - hw - prof = h.PmlProfile(int(job.get("pml_order", 3)), float(job.get("pml_reflection", 1e-8))) if info["quarter"]: return h.PmlBox3D(np.array([0.0, 0.0, -hw]), np.array([hw, hw, hw]), [0.0, d, 0.0, d, d, d], k0, 1.0, prof) return h.PmlBox3D.uniform(np.full(3, -hw), np.full(3, hw), d, k0, 1.0, prof) @@ -79,7 +166,48 @@ def pml_box(h, job, info, k0): def pec_tags(h, info): t = h.box_tag - return [t.X_MAX, t.Y_MAX, t.Z_MIN, t.Z_MAX, TAG_SYM] if info["quarter"] else [t.X_MIN, t.X_MAX, t.Y_MIN, t.Y_MAX, t.Z_MIN, t.Z_MAX] + if info["quarter"]: + return [t.X_MAX, t.Y_MAX, t.Z_MIN, t.Z_MAX, TAG_SYM] + return [t.X_MIN, t.X_MAX, t.Y_MIN, t.Y_MAX, t.Z_MIN, t.Z_MAX] + + +def surface_of(h, mesh, tags): + """Closed surface around the cells with one of `tags` (several tags: retagged on a copy of the mesh, the facet numbers are those of the mesh).""" + if len(tags) == 1: + return h.Surface3D.around_cells(mesh, int(tags[0])) + cp = mesh.copy() + ts = set(int(x) for x in tags) + for c in range(cp.num_cells): + if int(cp.cell_tag(c)) in ts: + cp.set_cell_tag(c, TAG_INSIDE) + return h.Surface3D.around_cells(cp, TAG_INSIDE) + + +def projected_area_xy(h, mesh, tags): + """Area of the projection of the object (cells with `tags`) onto the x-y plane: half the sum of |n_z| dA over the closed surface (straight facets).""" + surf = surface_of(h, mesh, tags) + tot = 0.0 + for f in surf.facets: + v = np.array([mesh.vertex(int(i)) for i in mesh.facet_vertices(int(f.facet))[:3]]) + tot += abs(0.5 * np.cross(v[1] - v[0], v[2] - v[0])[2]) + return 0.5 * tot + + +def set_materials(h, setup_or_map, job, info, i): + """Materials by tag for a scatter / resonance setup: the object, the regions of the layer stack (gmsh) or the tag table (file).""" + mm = setup_or_map + if info["kind"] == "file": + for tag, lst in job["file"].get("tag_eps", {}).items(): + e = lst[i] + mm.set(int(tag), h.Material(complex(e[0], e[1]))) + return + e = job["eps"][i] if job["task"] == "scatter" else job["eps"] + mm.set(TAG_OBJ, h.Material(complex(e[0], e[1]))) + st = job.get("stack") + if st and info["kind"] == "gmsh": + for r, lst in enumerate(st["eps"]): + ee = lst[i] + mm.set(11 + r, h.Material(complex(ee[0], ee[1]))) def estimate(h, job, mesh): @@ -88,70 +216,127 @@ def estimate(h, job, mesh): return dict(cells=int(mesh.num_cells), dofs=int(nd.num_dofs), bytes=int(e.total_bytes), text=e.describe(), human=h.format_bytes(int(e.total_bytes))) -def save_mesh(folder, task, mesh): - np.savez_compressed(folder / f"mesh_{task}.npz", vertices=np.asarray(mesh.vertices), cells=np.asarray(mesh.cells), tags=np.asarray(mesh.cell_tags)) +def inspect_mesh(h, path, scale): + """Tags of a mesh file: cells per tag, facets per tag, bounding box [m], geometry order.""" + mesh = h.read_gmsh(str(path), float(scale), 3) + cells = np.asarray(mesh.cell_tags) + ftags = np.asarray(mesh.facet_tags) + v = np.asarray(mesh.vertices) + return dict(n_cells=int(mesh.num_cells), cells={str(int(x)): int((cells == x).sum()) for x in np.unique(cells)}, + facets={str(int(x)): int((ftags == x).sum()) for x in np.unique(ftags) if int(x) != int(h.NO_TAG)}, + bbox=[v.min(axis=0).tolist(), v.max(axis=0).tolist()], geometry_order=int(mesh.geometry_order)) + + +def save_mesh(folder, task, mesh, orders=None): + extra = {} if orders is None else dict(orders=np.asarray(orders, dtype=int)) + np.savez_compressed(folder / f"mesh_{task}.npz", vertices=np.asarray(mesh.vertices), cells=np.asarray(mesh.cells), tags=np.asarray(mesh.cell_tags), **extra) # ------------------------------------------------------------------------------------------------------------------------------------ scatter def slice_points(info): - """Cut planes in the quarter x, y >= 0 (the fields are mirrored by the app): xz at y = 0, xy at z = 0, edges moved inwards by a tiny amount.""" + """Cut planes: xz at y = 0, xy through the centre of the object. Quarter model: x, y >= 0 (the app mirrors the fields); otherwise the whole interior of the PML box. + Returns ((xs, zs, pxz, shape), (xs, ys, pxy, shape)); edges are moved inwards by a tiny amount.""" a, hw = info["a"], info["hw"] eps = 1e-6 * a - xs, ys, zs = np.linspace(eps, hw - eps, GRID), np.linspace(eps, hw - eps, GRID), np.linspace(-hw + eps, hw - eps, 2 * GRID - 1) + if info["quarter"]: + xs, ys, zs = np.linspace(eps, hw - eps, GRID), np.linspace(eps, hw - eps, GRID), np.linspace(-hw + eps, hw - eps, 2 * GRID - 1) + y0, z0 = eps, eps + else: + x0, x1, zlo, zhi = info["interior"] + xs = np.linspace(x0 + eps, x1 - eps, GRID) + yr = info.get("interior_y", [x0, x1]) + ys = np.linspace(yr[0] + eps, yr[1] - eps, GRID) + zs = np.linspace(zlo + eps, zhi - eps, GRID if info["kind"] == "builtin" else 2 * GRID - 1) + y0, z0 = 0.5 * (yr[0] + yr[1]) + eps, info.get("zc", 0.0) + eps X, Z = np.meshgrid(xs, zs, indexing="ij") - pxz = np.stack([X.ravel(), np.full(X.size, eps), Z.ravel()], axis=1) + pxz = np.stack([X.ravel(), np.full(X.size, y0), Z.ravel()], axis=1) X2, Y2 = np.meshgrid(xs, ys, indexing="ij") - pxy = np.stack([X2.ravel(), Y2.ravel(), np.full(X2.size, eps)], axis=1) + pxy = np.stack([X2.ravel(), Y2.ravel(), np.full(X2.size, z0)], axis=1) return (xs, zs, pxz, X.shape), (xs, ys, pxy, X2.shape) +def scatter_setup(h, job, info, i): + """(setup, omega, k0, eps_obj, extra) of wavelength i. With a layer stack the background is a LayerStack3D and the incident field its plane wave (oblique, + s / p); extra then carries R, T, A of the bare stack.""" + lam = float(job["wavelengths_nm"][i]) + omega = 2 * np.pi * C0 / (lam * 1e-9) + k0 = omega / C0 + eps = complex(*(job["eps"][i] if info["kind"] != "file" else (1.0, 0.0))) + s = h.ScatteringSetup3D() + s.omega = omega + set_materials(h, s.materials, job, info, i) + s.formulation = h.Formulation.SCATTERED_FIELD + s.pml = pml_box(h, job, info, k0) + s.pec_tags = pec_tags(h, info) + extra = {} + st = job.get("stack") + if st and info["kind"] == "gmsh": + mats = [h.Material(complex(e[i][0], e[i][1])) for e in st["eps"]] + layers = [h.Layer(mats[1 + k], float(th) * 1e-9) for k, th in enumerate(st["thickness_nm"])] + stack = h.LayerStack3D(mats[0], layers, mats[-1], 0.0) + pol = h.Polarisation.S if st["pol"] == "s" else h.Polarisation.P + wave = stack.plane_wave(k0, np.deg2rad(float(st["angle_deg"])), pol, 1.0, np.deg2rad(float(st["azimuth_deg"]))) + s.background = stack + s.incident = wave.field + extra = dict(stack_R=float(wave.reflectance), stack_T=float(wave.transmittance), stack_A=float(wave.absorptance)) + else: + s.incident = h.plane_wave(np.array([1.0, 0.0, 0.0], dtype=complex), np.array([0.0, 0.0, k0])) + return s, omega, k0, eps, extra + + +def scatter_post(h, job, info, mesh, problem, sol, pt, k0, eps, locator, planes, folder, i): + """Cross sections (and Mie), field cuts of one solution into the point record pt.""" + mult = 4.0 if info["quarter"] else 1.0 + surface = surface_of(h, mesh, info["object_tags"]) + area = info["area"] + cs = h.cross_sections(problem, sol, surface, 1.0) + pt.update(sigma_sca=mult * cs.scattering, sigma_abs=mult * cs.absorption, sigma_ext=mult * cs.extinction, + q_sca=mult * cs.scattering / area, q_abs=mult * cs.absorption / area, q_ext=mult * cs.extinction / area) + if info.get("sphere"): + mie = h.mie_sphere(k0, info["sphere"], eps) + pt.update(mie_q_sca=float(mie.scattering_efficiency()), mie_q_abs=float(mie.absorption_efficiency()), mie_q_ext=float(mie.extinction_efficiency())) + if job.get("fields", True) and locator is not None: + (xs, zs, pxz, sxz), (_, ys, pxy, sxy) = planes + fields = {} + for key, pts, shp in (("xz", pxz, sxz), ("xy", pxy, sxy)): + vals, cells = problem.sample(sol, locator, pts) + e2 = np.sum(np.abs(vals) ** 2, axis=1) + e2[np.asarray(cells) < 0] = np.nan + fields[key] = e2.reshape(shp) + np.savez_compressed(folder / f"field_{i}.npz", xs=xs, ys=ys, zs=zs, xz=fields["xz"], xy=fields["xy"]) + pt["field_file"] = f"field_{i}.npz" + + +def cancelled(folder, out, flush): + if (folder / "cancel").exists(): + say("CANCELLED") + out["cancelled"] = True + flush() + return True + return False + + def run_scatter(h, job, folder, mesh, info, out, flush): a = info["a"] - sphere = job["shape"] == "sphere" lams = np.asarray(job["wavelengths_nm"], dtype=float) + ad = job.get("adaptive") or {} + if ad.get("enabled"): + return run_scatter_adaptive(h, job, folder, mesh, info, out, flush) nd = h.NedelecDofMap3D(mesh, int(job["order"])) - surface = h.Surface3D.around_cells(mesh, TAG_OBJ) - area = np.pi * a * a if sphere else (2 * a) ** 2 - mult = 4.0 if info["quarter"] else 1.0 - locator = h.PointLocator3D(mesh) - (xs, zs, pxz, sxz), (_, ys, pxy, sxy) = slice_points(info) + locator = h.PointLocator3D(mesh) if job.get("fields", True) else None + planes = slice_points(info) if locator is not None else None for i, lam in enumerate(lams): - if (folder / "cancel").exists(): - say("CANCELLED") - out["cancelled"] = True - flush() + if cancelled(folder, out, flush): return say(f"PROGRESS {i + 1}/{len(lams)} lambda = {lam:g} nm") t0 = time.time() pt = dict(index=i, lam_nm=float(lam), eps=job["eps"][i], size_parameter=float(2 * np.pi * a / (lam * 1e-9))) try: - omega = 2 * np.pi * C0 / (lam * 1e-9) - k0 = omega / C0 - eps = complex(job["eps"][i][0], job["eps"][i][1]) - s = h.ScatteringSetup3D() - s.omega = omega - s.materials.set(TAG_OBJ, h.Material(eps)) - s.incident = h.plane_wave(np.array([1.0, 0.0, 0.0], dtype=complex), np.array([0.0, 0.0, k0])) - s.formulation = h.Formulation.SCATTERED_FIELD - s.pml = pml_box(h, job, info, k0) - s.pec_tags = pec_tags(h, info) + s, omega, k0, eps, extra = scatter_setup(h, job, info, i) + pt.update(extra) problem = h.Scattering3D(nd, s) sol = problem.solve() - cs = h.cross_sections(problem, sol, surface, 1.0) - pt.update(sigma_sca=mult * cs.scattering, sigma_abs=mult * cs.absorption, sigma_ext=mult * cs.extinction, - q_sca=mult * cs.scattering / area, q_abs=mult * cs.absorption / area, q_ext=mult * cs.extinction / area) - if sphere: - mie = h.mie_sphere(k0, a, eps) - pt.update(mie_q_sca=float(mie.scattering_efficiency()), mie_q_abs=float(mie.absorption_efficiency()), mie_q_ext=float(mie.extinction_efficiency())) - if job.get("fields", True): - fields = {} - for key, pts, shp in (("xz", pxz, sxz), ("xy", pxy, sxy)): - vals, cells = problem.sample(sol, locator, pts) - e2 = np.sum(np.abs(vals) ** 2, axis=1) - e2[np.asarray(cells) < 0] = np.nan - fields[key] = e2.reshape(shp) - np.savez_compressed(folder / f"field_{i}.npz", xs=xs, ys=ys, zs=zs, xz=fields["xz"], xy=fields["xy"]) - pt["field_file"] = f"field_{i}.npz" + scatter_post(h, job, info, mesh, problem, sol, pt, k0, eps, locator, planes, folder, i) pt["seconds"] = time.time() - t0 except Exception as exc: # a failed wavelength must not stop the sweep pt["error"] = f"{type(exc).__name__}: {exc}" @@ -160,6 +345,87 @@ def run_scatter(h, job, folder, mesh, info, out, flush): flush() +def run_scatter_adaptive(h, job, folder, mesh, info, out, flush): + """hp-adaptive loop per wavelength: solve, estimate (residual), Doerfler marking, hp decision by prediction, refine; stops at max_steps, max_dofs, the memory + limit or the relative estimator tolerance. The steps are recorded in the point (pt["steps"]); cross sections and fields are those of the last mesh.""" + a = info["a"] + ad = job["adaptive"] + lams = np.asarray(job["wavelengths_nm"], dtype=float) + p0 = int(job["order"]) + max_steps, max_dofs, theta, tol = int(ad["max_steps"]), int(ad["max_dofs"]), float(ad["theta"]), float(ad.get("tol", 0.0)) + max_bytes = float(job.get("max_gb", 16.0)) * 1e9 + for i, lam in enumerate(lams): + if cancelled(folder, out, flush): + return + t0 = time.time() + pt = dict(index=i, lam_nm=float(lam), eps=job["eps"][i], size_parameter=float(2 * np.pi * a / (lam * 1e-9)), steps=[]) + out["points"].append(pt) + try: + adaptive = h.AdaptiveMesh3D(mesh) + orders = np.full(mesh.num_cells, p0, dtype=int) + predicted = [] + last = None + eta0 = None + for step in range(max_steps): + if cancelled(folder, out, flush): + return + m = adaptive.mesh + nd = h.NedelecDofMap3D(m, orders.tolist()) + mem = h.estimate_memory(nd) + if step > 0 and (nd.num_dofs > max_dofs or mem.total_bytes > max_bytes): + say(f"stop: the next mesh has {nd.num_dofs} unknowns / {h.format_bytes(int(mem.total_bytes))} (limit {max_dofs} unknowns, {max_bytes / 1e9:g} GB)") + pt["stop_reason"] = "Grenze für Unbekannte oder Speicher erreicht" + break + say(f"PROGRESS {i * max_steps + step + 1}/{len(lams) * max_steps} lambda = {lam:g} nm, step {step}: {m.num_cells} cells, {nd.num_dofs} unknowns, " + f"{h.format_bytes(int(mem.total_bytes))}") + s, omega, k0, eps, extra = scatter_setup(h, job, info, i) + pt.update(extra) + problem = h.Scattering3D(nd, s) + ts = time.time() + sol = problem.solve() + est = problem.estimate(sol) + eta = float(est.total()) + eta0 = eta if eta0 is None else eta0 + rec = dict(step=step, cells=int(m.num_cells), dofs=int(nd.num_dofs), eta=eta, orders_max=int(orders.max()), orders_min=int(orders.min()), + seconds=time.time() - ts) + surf = surface_of(h, m, info["object_tags"]) + cs = h.cross_sections(problem, sol, surf, 1.0) + mult = 4.0 if info["quarter"] else 1.0 + rec.update(q_sca=mult * cs.scattering / info["area"], q_abs=mult * cs.absorption / info["area"]) + if info.get("sphere"): + mie = h.mie_sphere(k0, info["sphere"], eps) + rec.update(mie_q_sca=float(mie.scattering_efficiency())) + pt["steps"].append(rec) + last = (m, nd, problem, sol, k0, eps, orders.copy()) + flush() + if tol > 0 and eta / eta0 < tol: + pt["stop_reason"] = "Fehlerschätzer unter der Toleranz" + break + if step == max_steps - 1: + pt["stop_reason"] = "Schrittzahl erreicht" + break + marked = h.dorfler_marking(list(est.indicators), theta) + dec = h.hp_decide_by_prediction(list(est.indicators), list(predicted), [int(c) for c in marked]) + hp = h.hp_refine(adaptive, orders.tolist(), list(dec.h_marked), list(dec.p_marked)) + predicted = list(h.predict_indicators(list(est.indicators), orders.tolist(), hp)) + rec["h_marked"], rec["p_marked"] = len(dec.h_marked), len(dec.p_marked) + orders = np.asarray(hp.orders) + if last is None: + raise RuntimeError("no step was solved") + m, nd, problem, sol, k0, eps, ords = last + locator = h.PointLocator3D(m) if job.get("fields", True) else None + planes = slice_points(info) if locator is not None else None + scatter_post(h, job, info, m, problem, sol, pt, k0, eps, locator, planes, folder, i) + save_mesh(folder, "scatter", m, ords) + pt["dofs_final"] = int(nd.num_dofs) + pt["seconds"] = time.time() - t0 + except Exception as exc: + pt["error"] = f"{type(exc).__name__}: {exc}" + say(f"ERROR wavelength {lam:g} nm: {pt['error']}") + say(traceback.format_exc()) + flush() + + # ------------------------------------------------------------------------------------------------------------------------------------ resonance def run_resonance(h, job, folder, mesh, info, out, flush): a = info["a"] @@ -172,32 +438,27 @@ def run_resonance(h, job, folder, mesh, info, out, flush): s.num_modes = int(job["num_modes"]) if int(job.get("krylov", 0)) > 0: s.krylov_dimension = int(job["krylov"]) - s.materials.set(TAG_OBJ, h.Material(complex(job["eps"][0], job["eps"][1]))) + set_materials(h, s.materials, job, info, 0) s.pml = pml_box(h, job, info, k0) s.pec_tags = pec_tags(h, info) say("PROGRESS 0/1 Arnoldi (one call, cannot be interrupted)") t0 = time.time() modes = h.Resonance3D(nd, s).solve() locator = h.PointLocator3D(mesh) - hw = info["hw"] - eps = 1e-6 * a - xs = np.linspace(-hw + eps, hw - eps, GRID) - X, Z = np.meshgrid(xs, xs, indexing="ij") - pxz = np.stack([X.ravel(), np.full(X.size, eps), Z.ravel()], axis=1) - pxy = np.stack([X.ravel(), Z.ravel(), np.full(X.size, eps)], axis=1) + (xs, zs, pxz, sxz), (_, ys, pxy, sxy) = slice_points(info) for j, m in enumerate(modes): om = complex(m.omega) rec = dict(index=j, omega=[om.real, om.imag], lam_nm=float(2 * np.pi * C0 / om.real * 1e9), Q=float(m.quality), residual=float(m.residual)) if job.get("fields", True): fields = {} - for key, pts in (("xz", pxz), ("xy", pxy)): + for key, pts, shp in (("xz", pxz, sxz), ("xy", pxy, sxy)): e2 = np.full(len(pts), np.nan) for q, x in enumerate(pts): v = h.evaluate_hcurl(nd, np.asarray(m.field), locator, x) if v is not None: e2[q] = float(np.sum(np.abs(np.asarray(v)) ** 2)) - fields[key] = e2.reshape(X.shape) - np.savez_compressed(folder / f"field_{j}.npz", xs=xs, ys=xs, zs=xs, xz=fields["xz"], xy=fields["xy"]) + fields[key] = e2.reshape(shp) + np.savez_compressed(folder / f"field_{j}.npz", xs=xs, ys=ys, zs=zs, xz=fields["xz"], xy=fields["xy"]) rec["field_file"] = f"field_{j}.npz" out["modes"].append(rec) out["seconds"] = time.time() - t0 @@ -271,8 +532,15 @@ def main(argv=None) -> int: import hpfem hpfem.set_log_level("warn") task = job["task"] + if len(argv) > 1 and argv[1] == "inspect": + try: + print("INSPECT" + json.dumps(inspect_mesh(hpfem, job["file"]["path"], job["file"]["scale"])), flush=True) + return 0 + except Exception as exc: + say(f"ERROR inspect: {type(exc).__name__}: {exc}") + return 1 try: - mesh, info = build_mesh(hpfem, job) + mesh, info = build_mesh(hpfem, job, folder) est = estimate(hpfem, job, mesh) save_mesh(folder, task, mesh) except Exception as exc: @@ -285,7 +553,7 @@ def main(argv=None) -> int: if est["bytes"] > float(job.get("max_gb", 16.0)) * 1e9: say(f"ERROR memory estimate {est['human']} exceeds the limit of {job.get('max_gb', 16.0)} GB: reduce n, p or the box (or raise the limit).") return 1 - out = dict(meta=dict(name=job.get("name", ""), task=task, shape=job["shape"], started=time.strftime("%Y-%m-%d %H:%M:%S"), + out = dict(meta=dict(name=job.get("name", ""), task=task, shape=job["shape"], mesh_kind=job.get("mesh_kind", "builtin"), started=time.strftime("%Y-%m-%d %H:%M:%S"), hpfem=str(getattr(hpfem, "__version__", "?")), quarter=info["quarter"], order=int(job["order"]), **est), points=[], modes=[]) path = folder / "results.json" diff --git a/tests/test_ports3d.py b/tests/test_ports3d.py new file mode 100644 index 0000000..ceef8aa --- /dev/null +++ b/tests/test_ports3d.py @@ -0,0 +1,226 @@ +"""3D waveguides and ports: model, job, worker on small structured meshes (straight guide, coupler) and on a Gmsh file, app results.""" +import copy +import json +import sys +from pathlib import Path + +import numpy as np +import pytest + +HERE = Path(__file__).resolve().parent.parent / "fem_gui" +sys.path.insert(0, str(HERE)) + +import fem_ports3d as fp # noqa: E402 +import fem_threed as ft # noqa: E402 + + +def errors(m): + return [t for lv, t in fp.validate(m) if lv == "error"] + + +# ------------------------------------------------------------------------------------------------------------------ model and job +def test_presets_validate_and_jobs_are_json(): + pr = fp.presets() + assert len(pr) == 3 and {m["device"] for m in pr.values()} == {"straight", "coupler"} + for name, m in pr.items(): + assert not errors(m), name + j = json.loads(json.dumps(fp.job(m))) + assert j["task"] == "ports" and j["eps_core"] == [[3.48**2, 0.0]] and j["eps_clad"] == [[1.44**2, 0.0]] + assert fp.job(pr["Richtkoppler Si/SiO2 (Halbflächen-Ports, klein)"])["num_modes"] == 1 + assert fp.job(pr["Richtkoppler Si/SiO2 (Supermoden-Ports)"])["num_modes"] == 2 + assert fp.job(next(iter(pr.values())))["num_modes"] == 1 + assert ft.worker_script(fp.job(next(iter(pr.values())))) == "fem_ports3d_worker.py" and ft.worker_script({"task": "scatter"}) == "fem_threed_worker.py" + + +def test_validation_of_ports_models(): + m = fp.default_model() + m["length_nm"] = 200.0 # fewer than two cells of 150 nm + assert any("zwei Zellen" in t for t in errors(m)) + m = fp.presets()["Richtkoppler Si/SiO2 (Supermoden-Ports)"] + m["num_modes"] = 1 + assert any("zwei Moden" in t for t in errors(m)) + m = fp.default_model() + m["materials"]["Kern"] = {"type": "index", "n": 1.3, "k": 0.0} + assert any("keine geführte Mode" in t for lv, t in fp.validate(m) if lv == "warning") + m = fp.default_model() + m["device"] = "file" + assert any("hochladen" in t for t in errors(m)) + m["file"].update(name="a.msh", path="a.msh", tags={"cells": {"1": 4}, "facets": {"11": 2}, "bbox": [[0] * 3, [1e-6] * 3]}, ports=[]) + assert any("Port" in t for t in errors(m)) + + +def test_grid_and_cell_count_and_outline(): + m = fp.default_model() + assert fp.cell_count(m) == (len(fp.grid_lines(fp.x_edges(m), 150.0)) - 1) * (len(fp.grid_lines(fp.y_edges(m), 150.0)) - 1) * 8 + lines = fp.grid_lines([0.0, 100.0, 400.0], 150.0) + assert np.allclose(lines, [0.0, 100.0, 250.0, 400.0]) # the edges are always grid lines + m["device"] = "coupler" + ol = fp.outline(m) + assert len(ol["xz"]) == 4 and len(ol["xy"]) == 2 + + +def test_dataframes_and_figures(): + pts = [{"index": 0, "lam_nm": 1550.0, "R": 0.01, "T": 0.98, "loss": 0.01, "n_eff0": 1.9, "bar": 0.9, "cross": 0.08, "cross_cmt": 0.085, "back": 0.0, "dofs": 100, "seconds": 1.0, + "channels": [{"port": 0, "mode": 0, "beta": 1.0}, {"port": 1, "mode": 0, "beta": 1.0}], "S_re": [[0.1, 0.9], [0.9, 0.1]], "S_im": [[0.0, 0.1], [0.1, 0.0]]}] + df = fp.results_dataframe(pts, "coupler", "full") + assert {"Durchgang (bar)", "Kopplung (cross)", "cross (gekoppelte Moden)"} <= set(df.columns) + s = fp.s_matrix_dataframe(pts[0]) + assert s.shape == (2, 3) and s["nach P2·M1"].iloc[0] == pytest.approx(0.82) + assert fp.fig_sparams(pts).axes + g = np.linspace(0, 1e-6, 5) + npz = {"xs": g, "ys": g, "zs": g, "xz": np.ones((5, 5)), "xy": np.ones((5, 5))} + assert fp.fig_field(npz, "xz", {"xz": [([0, 1], [0, 0])]}).axes and fp.fig_field(npz, "xy").axes + + +# ------------------------------------------------------------------------------------------------------------------ worker +def run_worker(folder, m, mode=None): + import fem_ports3d_worker as pw + folder.mkdir(parents=True, exist_ok=True) + (folder / "job.json").write_text(json.dumps(fp.job(m)), encoding="utf-8") + code = pw.main([str(folder)] + ([mode] if mode else [])) + return code, json.loads((folder / "results.json").read_text(encoding="utf-8")) if (folder / "results.json").is_file() else None + + +def test_straight_guide_transmits_with_the_2d_mode_as_reference(tmp_path): + pytest.importorskip("hpfem") + m = fp.default_model() + code, res = run_worker(tmp_path / "s", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p + assert p["T"] > 0.99 and p["R"] < 0.01 and abs(p["loss"]) < 1e-6 # power balance of the S-matrix + assert p["n_eff0"] == pytest.approx(p["n_eff_2d"], rel=1e-6) # the port mode is the 2D mode of the section on the same mesh + assert 2.0 < p["n_eff0"] < p["n_eff_ref"] < 2.5 # p = 1 on 150 nm cells underestimates n_eff (about 9 %); the fine 2D reference does not + assert 0.0 <= p["phase_error"] <= np.pi + f = np.load(tmp_path / "s" / p["field_file"]) + assert f["xz"].shape == (31, 61) and np.nanmax(f["xz"]) > 0 + est = ft.run_estimate(sys.executable, HERE.parent, tmp_path / "e", fp.job(m)) + assert est["cells"] > 1000 and (tmp_path / "e" / "mesh_ports.npz").is_file() + + +def test_grid_box_puts_the_faces_on_the_core_edges(): + hpfem = pytest.importorskip("hpfem") + import fem_ports3d_worker as pw + mesh = pw.grid_box(hpfem, np.array([0.0, 1.0, 3.0, 4.0]), np.array([0.0, 2.0, 2.5]), np.array([0.0, 1.0, 5.0])) + assert np.asarray(mesh.cell_volumes).sum() == pytest.approx(4 * 2.5 * 5) + assert {t: len(mesh.facets_with_tag(t)) for t in range(1, 7)} == {1: 8, 2: 8, 3: 12, 4: 12, 5: 12, 6: 12} + v = np.asarray(mesh.vertices) + assert set(np.round(v[:, 0], 9)) == {0.0, 1.0, 3.0, 4.0} + + +def test_coupler_with_supermode_ports_has_a_consistent_s_matrix_and_references(tmp_path): + pytest.importorskip("hpfem") + m = fp.presets()["Richtkoppler Si/SiO2 (Supermoden-Ports)"] + code, res = run_worker(tmp_path / "c", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p and p["bar"] + p["cross"] == pytest.approx(1.0) and 0.0 <= p["cross"] < 0.3 + assert p["R"] < 0.02 and abs(p["loss"]) < 1e-6 and p["back"] < 0.01 + assert p["coupling_length_nm"] > 0 and p["cross_cmt"] == pytest.approx(np.sin(p["kappa"] * 1000e-9) ** 2) + assert p["coupling_length_ref_nm"] > p["coupling_length_nm"] # p = 1 on 150 nm cells couples too strongly (about 10 µm against 25 µm) + assert 2.0 < p["n_eff_even_ref"] < 2.6 and p["n_eff_odd_ref"] < p["n_eff_even_ref"] + assert p["phase_error_even"] <= np.pi and p["phase_error_odd"] <= np.pi + + +def test_half_face_ports_have_four_channels(tmp_path): + pytest.importorskip("hpfem") + m = fp.presets()["Richtkoppler Si/SiO2 (Halbflächen-Ports, klein)"] + m["field"] = False + code, res = run_worker(tmp_path / "h", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p and len(p["channels"]) == 4 and len(p["S_re"]) == 4 + assert p["bar"] + p["cross"] + p["R"] + p["back"] == pytest.approx(1.0, abs=1e-6) # all four outgoing channels of the excited half port + + +def test_memory_limit_stops_the_ports_run(tmp_path): + pytest.importorskip("hpfem") + m = fp.default_model() + m["max_gb"] = 1e-4 + code, res = run_worker(tmp_path / "m", m) + assert code == 1 and res is None + + +def gmsh_straight_guide(path, width=450.0, height=220.0, margin_x=600.0, margin_y=450.0, length=1200.0, cell=150.0): + import gmsh + gmsh.initialize(interruptible=False) + try: + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("guide") + occ = gmsh.model.occ + X, Y = width / 2 + margin_x, height + margin_y + box = occ.addBox(-X, -margin_y, 0, 2 * X, Y + margin_y - height + height, length) + core = occ.addBox(-width / 2, 0, 0, width, height, length) + _, parts = occ.fragment([(3, box)], [(3, core)]) + occ.synchronize() + core_v = {t for _, t in parts[1]} + clad_v = {t for _, t in parts[0]} - core_v + gmsh.model.addPhysicalGroup(3, sorted(clad_v), 1) + gmsh.model.addPhysicalGroup(3, sorted(core_v), 2) + walls, left, right = [], [], [] + for dim, tag in gmsh.model.getBoundary([(3, t) for t in clad_v | core_v], oriented=False): + x0, y0, z0, x1, y1, z1 = gmsh.model.getBoundingBox(dim, tag) + if z1 < 1e-6: + left.append(tag) + elif z0 > length - 1e-6: + right.append(tag) + else: + walls.append(tag) + gmsh.model.addPhysicalGroup(2, sorted(set(walls)), 10) + gmsh.model.addPhysicalGroup(2, sorted(set(left)), 11) + gmsh.model.addPhysicalGroup(2, sorted(set(right)), 12) + gmsh.option.setNumber("Mesh.MeshSizeMax", cell) + gmsh.option.setNumber("Mesh.MeshSizeMin", cell / 2) + gmsh.model.mesh.generate(3) + gmsh.option.setNumber("Mesh.MshFileVersion", 4.1) + gmsh.option.setNumber("Mesh.Binary", 0) + gmsh.option.setNumber("Mesh.SaveAll", 0) + gmsh.write(str(path)) + finally: + gmsh.finalize() + + +def test_gmsh_file_device_matches_the_structured_guide(tmp_path): + pytest.importorskip("hpfem") + pytest.importorskip("gmsh") + path = tmp_path / "guide.msh" + gmsh_straight_guide(path) + m = fp.default_model() + m.update(device="file") + m["materials"].update({"Kern": {"type": "index", "n": 3.48, "k": 0.0}, "Mantel": {"type": "index", "n": 1.44, "k": 0.0}}) + (tmp_path / "i").mkdir() + info = ft.run_inspect(sys.executable, HERE.parent, tmp_path / "i", path, "nm", "ports") + assert set(info["cells"]) == {"1", "2"} and set(info["facets"]) == {"10", "11", "12"} + m["file"].update(name="guide.msh", path=str(path), scale="nm", tags=info, tag_material={"1": "Mantel", "2": "Kern"}, pec_tags=[10], ports=[dict(tag=11, modes=1), dict(tag=12, modes=1)]) + assert not errors(m) + j = fp.job(m) + assert j["scale"] == 1e-9 and j["pec_tags"] == [10] and len(j["ports"]) == 2 and set(j["tag_eps"]) == {"1", "2"} + code, res = run_worker(tmp_path / "f", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p and p["T"] > 0.95 and abs(p["loss"]) < 1e-6 + assert 2.1 < p["n_eff0"] < 2.45 # the port mode of the 2D section solver on an unstructured mesh (converged: about 2.36) + + +# ------------------------------------------------------------------------------------------------------------------ app +def test_app_ports_task_and_results_without_exception(tmp_path): + pytest.importorskip("hpfem") + from streamlit.testing.v1 import AppTest + + m = copy.deepcopy(ft.default_model()) + m["task"] = "ports" + run_worker(tmp_path / "threed", m["p3"]) + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=180) + at.session_state["app_mode"] = "threed" + at.session_state["work_dir"] = str(tmp_path) + at.run() + assert not at.exception, [e.value for e in at.exception] + for name in [n for n, pm in ft.presets().items() if pm["task"] == "ports"]: + at.selectbox(key="td_preset").select(name).run() + [b for b in at.button if b.key == "td_preset_load"][0].click().run() + assert not at.exception, (name, [e.value for e in at.exception]) + assert at.session_state["td_model"]["task"] == "ports" + ver = at.session_state["td_ver"] + at.radio(key=f"p3_dev_{ver}").set_value("file").run() + assert not at.exception, [e.value for e in at.exception] + assert any("hochladen" in e.value for e in at.error) diff --git a/tests/test_thermo3d.py b/tests/test_thermo3d.py new file mode 100644 index 0000000..d724155 --- /dev/null +++ b/tests/test_thermo3d.py @@ -0,0 +1,257 @@ +"""Heat and mechanics (3D): models, validation, closed-form checks of the worker (block), sphere chain optics -> heat -> stress, estimates, figures, the app.""" +import copy +import json +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest + +HERE = Path(__file__).resolve().parent.parent / "fem_gui" +sys.path.insert(0, str(HERE)) + +import fem_thermo3d as t3 # noqa: E402 + +PY = "/home/itofrenner/hpfemenv/bin/python" +pytestmark = pytest.mark.skipif(not Path(PY).exists(), reason="hpfem environment not available") + + +def run_worker(model, folder, *extra, max_gb=None): + folder.mkdir(parents=True, exist_ok=True) + (folder / "job.json").write_text(json.dumps(t3.job(t3.normalise(copy.deepcopy(model)), max_gb)), encoding="utf-8") + r = subprocess.run([PY, str(HERE / "fem_thermo3d_worker.py"), str(folder), *extra], capture_output=True, text=True, timeout=240) + res = json.loads((folder / "results.json").read_text(encoding="utf-8")) if (folder / "results.json").is_file() else None + return r, res + + +def preset(sub): + return copy.deepcopy(next(v for k, v in t3.presets().items() if sub in k)) + + +# --------------------------------------------------------------------------------------------------------------------- model +def test_presets_validate_and_are_json(): + for name, m in t3.presets().items(): + assert not [t for lv, t in t3.validate(t3.normalise(m)) if lv == "error"], name + json.dumps(m) + assert {m["case"] for m in t3.presets().values()} == {"particle", "block"} + + +def test_validation_errors(): + m = preset("Goldkugel in Glas: Erwärmung") + m["particle"]["outer_factor"] = 3 + assert any("ganzzahlig" in t for lv, t in t3.validate(m) if lv == "error") + m = preset("Goldkugel in Glas: Erwärmung") + m["materials"]["Glas"] = {"type": "index", "n": 1.5, "k": 0.1} + assert any("verlustfrei" in t for lv, t in t3.validate(m) if lv == "error") + m = preset("Quader unter Zug") + m["mech"]["bc"]["xmin"]["kind"] = m["mech"]["bc"]["ymin"]["kind"] = m["mech"]["bc"]["zmin"]["kind"] = "free" + assert any("Gleichgewicht" in t for lv, t in t3.validate(m) if lv == "error") + m = preset("Wärmequelle") + m["thermal"]["sinks"] = {s: False for s in t3.SIDE_TAGS} + assert any("Wärmesenke" in t for lv, t in t3.validate(m) if lv == "error") + m = preset("selbstkonsistent") + assert not any("ohne dε/dT" in t for lv, t in t3.validate(m)) # the preset carries a coefficient (used_materials covers the sphere) + m["props"]["Gold"].update(deps_re=0.0, deps_im=0.0) + assert any("ohne dε/dT" in t for lv, t in t3.validate(m) if lv == "warn") + m = preset("Quader unter Zug") + m["props"]["Stahl-ähnlich"]["nu"] = 0.6 + assert any("ν" in t for lv, t in t3.validate(m) if lv == "error") + + +def test_closed_forms_and_limits(): + m = preset("Quader unter Zug") + (_, ux, _), (_, uy, _), (_, uz, _) = t3.analytic_checks(m) + E, nu, s = 200e9, 0.3, 100e6 + assert ux == pytest.approx(s * 4e-6 / E) and uy == pytest.approx(-nu * s * 2e-6 / E) and uz == pytest.approx(-nu * s * 1e-6 / E) + m["mech"]["dT_b"] = 80.0 # a gradient has no textbook value here + assert t3.analytic_checks(m) == [] + assert t3.analytic_checks(preset("Goldkugel in Glas: Erwärmung")) == [] + h = preset("Wärmequelle") + (_, tm, key), = t3.heat_checks(h) + assert key == "T_mid" and tm == pytest.approx(300.0 + 1e15 * (4e-6) ** 2 / (8 * 50.0)) + h["thermal"]["sinks"]["xmax"] = False + (_, te, key), = t3.heat_checks(h) + assert key == "T_end" and te == pytest.approx(300.0 + 1e15 * (4e-6) ** 2 / (2 * 50.0)) + h["thermal"]["sinks"]["ymax"] = True + assert t3.heat_checks(h) == [] + + +def test_estimates_scale(): + a, b = t3.mech_estimate(1000), t3.mech_estimate(4000) + assert b["dofs"] == 4 * a["dofs"] and b["seconds"] > 4 * a["seconds"] and b["bytes"] > a["bytes"] + m = preset("Goldkugel in Glas: Erwärmung") + assert t3.particle_heat_estimate(m, 33e-6) == pytest.approx(33e-6 / (4 * np.pi * 1.4) * (1 / 50e-9 - 1 / (2 * 0.6606785 * 250e-9))) + assert np.isnan(t3.particle_heat_estimate(m, 0.0)) + g = t3.available_gb() + assert g is None or g > 0 + + +def test_mirror_signs_and_shapes(): + sys.path.insert(0, str(HERE)) + import fem_thermo3d_worker as w + + xs, ys, zs = np.array([0.5, 1.5]), np.array([0.5, 1.5, 2.5]), np.array([0.5]) + f = {k: np.arange(6, dtype=float).reshape(2, 3, 1) + 1.0 for k in ("T", "ux", "uy", "sxy", "uz")} + axes, out = w.mirror([xs, ys, zs], f, dict(quarter=True)) + assert [len(a) for a in axes] == [4, 6, 1] and np.allclose(axes[0], [-1.5, -0.5, 0.5, 1.5]) + assert out["T"].shape == (4, 6, 1) + assert np.allclose(out["T"], out["T"][::-1, :, :]) and np.allclose(out["T"], out["T"][:, ::-1, :]) # even + assert np.allclose(out["ux"], -out["ux"][::-1, :, :]) and np.allclose(out["ux"], out["ux"][:, ::-1, :]) # odd in x only + assert np.allclose(out["uy"], out["uy"][::-1, :, :]) and np.allclose(out["uy"], -out["uy"][:, ::-1, :]) # odd in y only + assert np.allclose(out["sxy"], -out["sxy"][::-1, :, :]) and np.allclose(out["sxy"], -out["sxy"][:, ::-1, :]) # odd in both + same = w.mirror([xs, ys, zs], f, dict(quarter=False)) + assert same[1] is f + + +# --------------------------------------------------------------------------------------------------------------------- block worker +@pytest.mark.parametrize("variant", ["tension", "heating", "shrink"]) +def test_block_matches_closed_form(tmp_path, variant): + m = preset("Quader unter Zug") + if variant == "heating": + m["mech"].update(dT_a=50.0, dT_b=50.0) + m["mech"]["bc"]["xmax"] = {"kind": "free", "value": 0.0} + if variant == "shrink": + m["mech"].update(shrink_a_pct=1.0, shrink_b_pct=1.0) + checks = t3.analytic_checks(m) + assert checks + r, res = run_worker(m, tmp_path) + assert r.returncode == 0 and res["finished"], r.stdout[-500:] + for _, exp, key in checks: + assert res["probes"][key] == pytest.approx(exp, rel=1e-8, abs=1e-18) + assert res["scalars"]["Größte Von-Mises-Spannung auf dem Raster (MPa)"] == pytest.approx(0.0 if variant == "heating" else 100.0, abs=1e-6) # the shrink case keeps the 100 MPa pull + + +def test_block_free_heating_gives_no_stress_and_clamped_does(tmp_path): + m = preset("Quader eingespannt") + r, res = run_worker(m, tmp_path / "clamped") + assert r.returncode == 0 and res["scalars"]["Größte Von-Mises-Spannung auf dem Raster (MPa)"] > 50.0 + m["mech"]["bc"] = {s: {"kind": "free", "value": 0.0} for s in t3.SIDE_TAGS} + r, res = run_worker(m, tmp_path / "free") + assert r.returncode == 0 and res["scalars"]["Größte Von-Mises-Spannung auf dem Raster (MPa)"] < 1e-3 # free body: remove_rigid_modes + + +def test_block_heat_source_matches_the_slab_solution_and_drives_stress(tmp_path): + m = preset("Wärmequelle") + (_, exp, _), = t3.heat_checks(m) + r, res = run_worker(m, tmp_path) + assert r.returncode == 0 and res["finished"], r.stdout[-500:] + assert res["probes"]["T_mid"] == pytest.approx(exp, rel=1e-8) + assert res["probes"]["T_end"] == pytest.approx(300.0, abs=1e-6) # sink face + assert res["scalars"]["Wärmeleistung im Quader (W)"] == pytest.approx(1e15 * 4e-6 * 2e-6 * 1e-6, rel=1e-9) + assert res["scalars"]["Größte Von-Mises-Spannung auf dem Raster (MPa)"] > 1.0 + f = np.load(tmp_path / "fields3d.npz") + assert f["T"].shape == (len(f["x"]), len(f["y"]), len(f["z"])) and np.nanmax(f["T"]) == pytest.approx(exp, rel=0.05) + for key in t3.FIELDS: # every map and the other figures render + if key in f.files: + for axis in "xyz": + t3.fig_slice(f, key, axis, 0.4).clear() + t3.fig_line(f, "T", "x", 0.3, 0.6).clear() + for axis in "xyz": + t3.fig_deformed(f, axis, 0.5, 1e3).clear() + t3.fig_history([3.0, 0.3, 0.03]).clear() + t3.fig_preview(m).clear() + import matplotlib.pyplot as plt + + plt.close("all") + + +def test_worker_estimate_limit_and_errors(tmp_path): + m = preset("Quader unter Zug") + r, res = run_worker(m, tmp_path / "est", "estimate") + est = json.loads(next(ln for ln in r.stdout.splitlines() if ln.startswith("ESTIMATE"))[len("ESTIMATE"):]) + assert est["cells"] == 96 and est["h1_dofs"] == 225 and est["mech_dofs"] == 675 and est["bytes"] > 0 + r, res = run_worker(m, tmp_path / "lim", max_gb=1e-6) # the memory limit stops the run before solving + assert r.returncode == 1 and "exceeds the limit" in r.stdout and res["error"] + for s in t3.SIDE_TAGS: # unbalanced load on a free body (validate would refuse it) + m["mech"]["bc"][s] = {"kind": "free", "value": 0.0} + m["mech"]["bc"]["xmax"] = {"kind": "traction", "value": 10.0} + r, res = run_worker(m, tmp_path / "err") + assert r.returncode == 1 and res.get("error") and "ERROR" in r.stdout + + +def test_particle_estimate_reports_optics_and_mechanics(tmp_path): + r, _ = run_worker(preset("Goldkugel in Glas: Erwärmung und Wärmespannung"), tmp_path, "estimate") + est = json.loads(next(ln for ln in r.stdout.splitlines() if ln.startswith("ESTIMATE"))[len("ESTIMATE"):]) + assert est["nd_dofs"] > est["h1_dofs"] > 0 and est["optics_bytes"] > 1e6 and "SparseLU" in est["optics_text"] and est["bytes"] >= est["optics_bytes"] + + +# --------------------------------------------------------------------------------------------------------------------- sphere chain +def test_sphere_chain_heat_matches_the_estimate_and_fields_are_symmetric(tmp_path): + m = preset("Goldkugel in Glas: Erwärmung und Wärmespannung") + m["grid"] = 18 + r, res = run_worker(m, tmp_path) + assert r.returncode == 0 and res["finished"], r.stdout[-800:] + sc = res["scalars"] + p, dt = sc["Absorbierte Leistung (W)"], sc["Temperaturanstieg im Kugelmittelpunkt (K)"] + assert p > 1e-6 and dt > 5 + assert dt == pytest.approx(t3.particle_heat_estimate(m, p), rel=0.10) # observed: -3.7 % on the coarse mesh + assert sc[" davon in der Kugel (W)"] == pytest.approx(p, rel=1e-6) # glass is lossless + assert sc["Größte Von-Mises-Spannung auf dem Raster (MPa)"] > 1.0 + f = np.load(tmp_path / "fields3d.npz") + assert float(f["sphere_r"]) == 50.0 and str(f["unit"]) == "nm" + assert np.allclose(f["x"], -f["x"][::-1]) and np.allclose(f["y"], -f["y"][::-1]) # the quarter is mirrored to the full box + for key in ("T", "Eabs", "umag", "svm"): + a = f[key] + assert np.allclose(a, a[::-1, :, :], equal_nan=True) and np.allclose(a, a[:, ::-1, :], equal_nan=True) + assert np.allclose(f["ux"], -f["ux"][::-1, :, :], equal_nan=True) + assert np.nanmax(f["T"]) >= 300.0 + dt * 0.9 and np.nanmin(f["T"]) >= 300.0 - 0.5 + for axis in "xyz": + t3.fig_slice(f, "T", axis, 0.5).clear() + t3.fig_slice(f, "Eabs", "y", 0.5).clear() + + +def test_sphere_selfconsistent_loop_runs_and_is_reported(tmp_path): + m = preset("selbstkonsistent") + m["order"] = 1 # quick: ~1 800 optical unknowns + m["thermal"].update(max_iter=3, tolerance=1e-2) + m["props"]["Gold"].update(deps_re=-0.05, deps_im=0.0) + r, res = run_worker(m, tmp_path) + assert r.returncode == 0 and res["finished"], r.stdout[-800:] + sc = res["scalars"] + assert sc["Iterationen"] >= 2 and len(res["history"]) == sc["Iterationen"] and res["history"][-1] < res["history"][0] + assert "Dehnungsenergie (J)" not in sc and "Schleife konvergiert" in sc + + +# --------------------------------------------------------------------------------------------------------------------- app +def _app(tmp_path): + from streamlit.testing.v1 import AppTest + + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=120) + at.session_state["app_mode"] = "thermo" + at.session_state["th_dim"] = "3D" + at.session_state["work_dir"] = str(tmp_path) + at.run() + return at + + +def test_app_all_presets_without_exception(tmp_path): + at = _app(tmp_path) + assert not at.exception, [e.value for e in at.exception] + for name in t3.presets(): + at.selectbox(key="t3_preset").select(name).run() + [b for b in at.button if b.key == "t3_preset_load"][0].click().run() + assert not at.exception, (name, [e.value for e in at.exception]) + assert at.session_state["th3_model"]["name"] == name + + +def test_app_two_d_still_default_and_dimension_switch(tmp_path): + from streamlit.testing.v1 import AppTest + + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=120) + at.session_state["app_mode"] = "thermo" + at.session_state["work_dir"] = str(tmp_path) + at.run() + assert not at.exception and at.radio(key="th_dim").value == "2D" and "th_model" in at.session_state + at.radio(key="th_dim").set_value("3D").run() + assert not at.exception and "th3_model" in at.session_state + + +def test_app_shows_results(tmp_path): + m = preset("Quader unter Zug") + run_worker(m, tmp_path / "thermo3d") + at = _app(tmp_path) + at.session_state["th3_run_model"] = m + at.run() + assert not at.exception, [e.value for e in at.exception] + assert any("geschlossene" in str(x.value) for x in at.markdown) diff --git a/tests/test_threed.py b/tests/test_threed.py index 8a6f7da..73c3f94 100644 --- a/tests/test_threed.py +++ b/tests/test_threed.py @@ -24,11 +24,11 @@ def small(task="scatter", shape="sphere", **kw): # ------------------------------------------------------------------------------------------------------------------ model and job def test_presets_validate_and_jobs_are_json(): names = ft.presets() - assert len(names) >= 5 and {m["task"] for m in names.values()} == {"scatter", "resonance", "bands"} + assert len(names) >= 5 and {m["task"] for m in names.values()} == {"scatter", "resonance", "bands", "ports"} for name, m in names.items(): assert not [t for lv, t in ft.validate(m) if lv == "error"], name j = json.loads(json.dumps(ft.job(m))) - assert j["task"] == m["task"] and j["order"] == m["order"] + assert j["task"] == m["task"] and j["order"] == (m["p3"]["order"] if m["task"] == "ports" else m["order"]) j = ft.job(ft.presets()["Dielektrische Kugel n = 2, ka = 2 (Mie-Referenz)"]) assert j["eps"] == [[4.0, 0.0]] and j["quarter"] is True and j["wavelengths_nm"] == [314.159] diff --git a/tests/test_threed_ext.py b/tests/test_threed_ext.py new file mode 100644 index 0000000..8448f35 --- /dev/null +++ b/tests/test_threed_ext.py @@ -0,0 +1,253 @@ +"""3D extensions: layer stack, Gmsh geometry and file import, hp-adaptive loop (model, job, worker on tiny meshes, app).""" +import copy +import json +import sys +from pathlib import Path + +import numpy as np +import pytest + +HERE = Path(__file__).resolve().parent.parent / "fem_gui" +sys.path.insert(0, str(HERE)) + +import fem_threed as ft # noqa: E402 +import fem_threed_gmsh as gm # noqa: E402 + + +def gmsh_model(kind="sphere", stack=False, **kw): + """A deliberately coarse Gmsh model (p = 1, a few hundred cells to a few thousand): checks the mechanics, not the accuracy.""" + m = copy.deepcopy(ft.default_model()) + m.update(task="scatter", mesh_kind="gmsh", order=1, quarter=False, radius_nm=100.0, sweep={"start": 628.3, "stop": 628.3, "count": 1}) + m["gmsh"].update(kind=kind, hw_nm=200.0, pml_nm=300.0, clear_nm=100.0, h_obj_nm=80.0, h_far_nm=250.0, grade_nm=200.0, height_nm=120.0) + if stack: + m["stack"].update(enabled=True, layers=[], substrate=ft.AIR, gap_nm=100.0, depth_nm=100.0, angle_deg=0.0, pol="p") + m.update(kw) + return m + + +def errors(m): + return [t for lv, t in ft.validate(m) if lv == "error"] + + +# ------------------------------------------------------------------------------------------------------------------ model and job +def test_layout_of_the_vertical_regions(): + g = dict(kind="sphere", r=100.0, stack=True, layers=[50.0, 30.0], depth=100.0, gap=40.0, clear=80.0) + lay = gm.layout(g) + assert lay["interfaces"] == [0.0, -50.0, -80.0] and lay["z_lo"] == -180.0 + assert lay["obj_z0"] == 40.0 and lay["zc"] == 140.0 and lay["z_hi"] == 40.0 + 200.0 + 80.0 + assert lay["regions"] == [(0.0, 320.0), (-50.0, 0.0), (-80.0, -50.0), (-180.0, -80.0)] + lay = gm.layout(dict(kind="block", lx=100.0, ly=80.0, lz=60.0, clear=50.0, stack=False)) + assert lay["zc"] == 0.0 and lay["z_lo"] == -80.0 and lay["z_hi"] == 80.0 and gm.object_extent(dict(kind="block", lx=100.0, ly=80.0, lz=60.0)) == (50.0, 40.0, 60.0) + + +def test_validation_of_gmsh_stack_adaptive_and_file(): + m = gmsh_model() + assert not errors(m) + m["gmsh"]["hw_nm"] = 100.0 # not larger than the object (half width 100 nm) + assert any("Innenraum" in t for t in errors(m)) + m = gmsh_model(stack=True) + m["stack"]["angle_deg"] = 95.0 + assert any("Einfallswinkel" in t for t in errors(m)) + m = gmsh_model(stack=True) + m["stack"]["layers"] = [{"material": "gibt es nicht", "thickness_nm": 10.0}] + assert any("fehlt" in t for t in errors(m)) + m = gmsh_model(stack=True, task="resonance") + assert any("Schichtstapel" in t for lv, t in ft.validate(m) if lv == "warning") and "stack" not in ft.job(m) and ft.job(m)["g"]["stack"] is False + m = copy.deepcopy(ft.default_model()) + m["task"] = "resonance" + m["adaptive"]["enabled"] = True + assert any("Adaptivität" in t for t in errors(m)) + m = gmsh_model(mesh_kind="file") + assert any("hochladen" in t for t in errors(m)) + m["file"].update(name="a.msh", path="a.msh", tags={"cells": {"11": 5, "2": 3}, "facets": {}, "bbox": [[-5e-7] * 3, [5e-7] * 3]}, object_tags=[2], tag_material={"11": ft.AIR}) + assert any("ohne Material" in t for t in errors(m)) + m["file"]["tag_material"]["2"] = ft.OBJ + assert not errors(m) + + +def test_jobs_carry_the_new_blocks_and_are_json(): + m = gmsh_model("cylinder", stack=True) + m["stack"].update(layers=[{"material": ft.GLASS, "thickness_nm": 40.0}], substrate=ft.GLASS, angle_deg=20.0, pol="s") + j = json.loads(json.dumps(ft.job(m))) + assert j["mesh_kind"] == "gmsh" and j["g"]["kind"] == "cylinder" and j["g"]["stack"] is True and j["g"]["layers"] == [40.0] + assert j["stack"]["pol"] == "s" and len(j["stack"]["eps"]) == 3 and j["stack"]["eps"][1][0] == [2.25, 0.0] and j["g"]["region_n"] == pytest.approx([1.0, 1.5, 1.5]) + assert j["quarter"] is False + m = copy.deepcopy(ft.default_model()) + m["adaptive"].update(enabled=True, max_steps=3) + assert ft.job(m)["adaptive"]["max_steps"] == 3 and "adaptive" not in ft.job(copy.deepcopy(ft.default_model())) + s = ft.suggest_sizes(gmsh_model()) + assert s["h_far_nm"] == pytest.approx(628.3 / 2.5, abs=0.1) and s["pml_nm"] == pytest.approx(314.2, abs=0.1) and s["h_obj_nm"] <= 40.0 + + +def test_figures_for_steps_outline_and_mesh_colours(): + steps = [dict(step=i, cells=100 + i, dofs=1000 * (i + 1), eta=1.0 / (i + 1), orders_max=2 + i, orders_min=2, seconds=1.0, q_sca=4.0 + 0.1 * i, q_abs=0.0, mie_q_sca=4.5) for i in range(3)] + df = ft.steps_dataframe(steps) + assert len(df) == 3 and "ΔQ_sca (%)" in df + assert ft.fig_convergence(steps).axes + m = gmsh_model("sphere", stack=True) + xz = ft.object_outline(m, "xz") + assert len(xz) == 2 and xz[0][1].max() == pytest.approx(300.0, abs=0.01) # circle centred at z = 100 + 100, radius 100: top at 300 nm + assert len(ft.object_outline(gmsh_model("block"), "xy")) == 1 and ft.object_outline(gmsh_model(mesh_kind="file"), "xz") == [] + fig = ft.fig_mesh({"vertices": np.array([[0.0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]), "cells": np.array([[0, 1, 2, 3]]), "tags": np.array([11])}, + 2, 0.2, 1.0, "m", obj_tags=(2,)) + assert fig.axes + + +# ------------------------------------------------------------------------------------------------------------------ worker +@pytest.fixture(scope="module") +def gmsh_available(): + pytest.importorskip("gmsh") + pytest.importorskip("hpfem") + + +def run_worker(folder, m, mode=None): + import fem_threed_worker as tw + folder.mkdir(parents=True, exist_ok=True) + (folder / "job.json").write_text(json.dumps(ft.job(m)), encoding="utf-8") + code = tw.main([str(folder)] + ([mode] if mode else [])) + return code, json.loads((folder / "results.json").read_text(encoding="utf-8")) if (folder / "results.json").is_file() else None + + +def test_gmsh_scene_tags_and_regions(tmp_path, gmsh_available): + import hpfem + g = ft.gmsh_params(gmsh_model("cylinder", stack=True)) + g.update(layers=[40.0], region_n=[1.0, 1.5, 1.5]) + info = gm.scene(g, tmp_path / "s.msh") + assert info["regions"] == [11, 12, 13] and info["object_tag"] == 2 + mesh = hpfem.read_gmsh(str(tmp_path / "s.msh"), 1e-9, 3) + tags = np.asarray(mesh.cell_tags) + assert set(np.unique(tags)) == {2, 11, 12, 13} + vol = np.asarray(mesh.cell_volumes) + assert vol[tags == 2].sum() == pytest.approx(np.pi * (100e-9) ** 2 * 120e-9, rel=0.05) # cylinder r = 100 nm, h = 120 nm (second-order geometry) + zc = np.asarray(mesh.cell_centroids)[:, 2] + assert zc[tags == 12].max() <= 1e-9 and zc[tags == 12].min() >= -40e-9 - 1e-12 # the layer lies between its interfaces z = 0 and z = -40 nm + assert all(len(mesh.facets_with_tag(t)) > 0 for t in range(1, 7)) # the six box sides carry the box tags + + +def test_gmsh_sphere_scatter_and_file_import_agree(tmp_path, gmsh_available): + m = gmsh_model("sphere") + code, res = run_worker(tmp_path / "g", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p and p["q_sca"] > 0 and p["mie_q_sca"] == pytest.approx(0.7969, rel=2e-3) + assert p["q_ext"] == pytest.approx(p["q_sca"] + p["q_abs"], rel=1e-6) + f = np.load(tmp_path / "g" / p["field_file"]) + assert f["xz"].shape == (41, 81) and np.isfinite(f["xz"]).mean() > 0.95 + # the same mesh read as a user file: the numbers are identical + mf = copy.deepcopy(m) + mf["mesh_kind"] = "file" + mf["file"].update(name="scene.msh", path=str(tmp_path / "g" / "scene.msh"), scale="nm", pml_nm=300.0, object_tags=[2], tag_material={"11": ft.AIR, "2": ft.OBJ}) + (tmp_path / "i").mkdir() + info = ft.run_inspect(sys.executable, HERE.parent, tmp_path / "i", mf["file"]["path"], "nm") + assert info["cells"].keys() == {"2", "11"} and set(info["facets"]) == {"1", "2", "3", "4", "5", "6"} and info["n_cells"] > 100 + assert info["bbox"][1][0] == pytest.approx(500e-9, rel=1e-6) + mf["file"]["tags"] = info + assert not errors(mf) + code, res2 = run_worker(tmp_path / "f", mf) + assert code == 0 + q = res2["points"][0] + assert q["sigma_sca"] == pytest.approx(p["sigma_sca"], rel=1e-6) and q["sigma_abs"] == pytest.approx(p["sigma_abs"], abs=1e-6 * p["sigma_sca"]) + assert q["q_sca"] == pytest.approx(p["q_sca"], rel=0.30) # Q of a file: cross section over the projected area of the (straight-facet) surface + + +def test_layer_stack_background_gives_fresnel_and_a_finite_particle_response(tmp_path, gmsh_available): + m = gmsh_model("cylinder", stack=True) + m["gmsh"].update(height_nm=100.0, hw_nm=250.0) + m["stack"].update(substrate=ft.GLASS, gap_nm=0.0, depth_nm=150.0, angle_deg=30.0, pol="p") + m["materials"][ft.OBJ] = {"type": "index", "n": 2.0, "k": 0.0} + code, res = run_worker(tmp_path / "s", m) + assert code == 0 + p = res["points"][0] + assert "error" not in p + rp = (1.5 * np.cos(np.deg2rad(30)) - np.sqrt(1 - (0.5 / 1.5) ** 2)) / (1.5 * np.cos(np.deg2rad(30)) + np.sqrt(1 - (0.5 / 1.5) ** 2)) + assert p["stack_R"] == pytest.approx(rp**2, rel=1e-6) and p["stack_T"] == pytest.approx(1 - rp**2, rel=1e-6) and p["stack_A"] == pytest.approx(0.0, abs=1e-9) + assert p["q_sca"] > 0.1 and abs(p["q_abs"]) < 0.25 * p["q_sca"] and p["q_ext"] == pytest.approx(p["q_sca"] + p["q_abs"], rel=1e-6) + df = ft.scatter_dataframe(res["points"]) + assert {"R (Stapel)", "T (Stapel)", "A (Stapel)"} <= set(df.columns) + + +def test_hp_adaptive_loop_records_steps_and_orders(tmp_path, gmsh_available): + m = copy.deepcopy(ft.default_model()) + m.update(task="scatter", n=1, order=1, quarter=True) + m["adaptive"].update(enabled=True, max_steps=3, max_dofs=20000, theta=0.5) + code, res = run_worker(tmp_path / "a", m) + assert code == 0 + p = res["points"][0] + steps = p["steps"] + assert len(steps) == 3 and [s["step"] for s in steps] == [0, 1, 2] and p["stop_reason"] == "Schrittzahl erreicht" + assert steps[0]["dofs"] < steps[-1]["dofs"] and steps[-1]["eta"] < steps[0]["eta"] # the estimator falls with the refinement + assert steps[0]["h_marked"] + steps[0]["p_marked"] > 0 and p["dofs_final"] == steps[-1]["dofs"] and "mie_q_sca" in p + npz = np.load(tmp_path / "a" / "mesh_scatter.npz") + assert "orders" in npz.files and len(npz["orders"]) == len(npz["cells"]) and npz["orders"].max() >= 1 + # the unknown limit stops the loop before the next solve + m["adaptive"]["max_dofs"] = steps[0]["dofs"] + 1 + code, res = run_worker(tmp_path / "b", m) + assert code == 0 and len(res["points"][0]["steps"]) == 1 and "Grenze" in res["points"][0]["stop_reason"] + + +def test_hp_adaptive_loop_on_a_curved_gmsh_mesh(tmp_path, gmsh_available): + m = gmsh_model("sphere") + m["adaptive"].update(enabled=True, max_steps=2, max_dofs=30000, theta=0.5) + code, res = run_worker(tmp_path / "ag", m) + assert code == 0 + steps = res["points"][0]["steps"] + assert len(steps) == 2 and steps[1]["dofs"] > steps[0]["dofs"] and steps[1]["eta"] < steps[0]["eta"] and "mie_q_sca" in res["points"][0] + + +# ------------------------------------------------------------------------------------------------------------------ app +def test_app_new_controls_and_results_without_exception(tmp_path, gmsh_available): + from streamlit.testing.v1 import AppTest + + m = copy.deepcopy(ft.default_model()) + m.update(task="scatter", n=1, order=1, quarter=True) + m["adaptive"].update(enabled=True, max_steps=2, max_dofs=20000) + run_worker(tmp_path / "threed", m) + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=180) + at.session_state["app_mode"] = "threed" + at.session_state["work_dir"] = str(tmp_path) + at.run() + assert not at.exception, [e.value for e in at.exception] + assert any("hp-Verfeinerung" in t.label for t in at.tabs) or at.dataframe + for name in ("Silizium-Zylinder auf Glas, schräger Einfall (p, 30°; grob, p = 1)", "Gold-Kugel auf SiO2-Schicht über Glas (Stapel, grob)"): + at.selectbox(key="td_preset").select(name).run() + [b for b in at.button if b.key == "td_preset_load"][0].click().run() + assert not at.exception, (name, [e.value for e in at.exception]) + assert at.checkbox(key=f"td_st_on_{at.session_state['td_ver']}").value is True + ver = at.session_state["td_ver"] + at.radio(key=f"td_mk_{ver}").set_value("file").run() + assert not at.exception, [e.value for e in at.exception] + assert any("hochladen" in e.value for e in at.error) + at.radio(key=f"td_task_{ver}").set_value("ports").run() + assert not at.exception, [e.value for e in at.exception] + + +def test_app_file_editors_render_with_read_tags(tmp_path): + from streamlit.testing.v1 import AppTest + + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=180) + at.session_state["app_mode"] = "threed" + at.session_state["work_dir"] = str(tmp_path) + m = copy.deepcopy(ft.default_model()) + m.update(task="scatter", mesh_kind="file") + tags = dict(n_cells=10, cells={"11": 7, "2": 3}, facets={"1": 4, "2": 4}, bbox=[[-5e-7] * 3, [5e-7] * 3], geometry_order=2) + m["file"].update(name="a.msh", path="a.msh", tags=tags, tag_material={"11": ft.AIR, "2": ft.OBJ}, object_tags=[2]) + for key, val in (("td_model", m), ("td_ver", 0), ("td_proc", None), ("td_dir", None), ("td_msg", None), ("td_est", None)): + at.session_state[key] = val + at.run() + assert not at.exception, [e.value for e in at.exception] + assert at.selectbox(key="td_ftm_0_11").value == ft.AIR and at.checkbox(key="td_fto_0_2").value is True + assert not [e for e in at.error if "hochladen" in e.value or "ohne Material" in e.value] + # the same for the ports task with a file device + p = copy.deepcopy(ft.default_model()) + p["task"] = "ports" + p["p3"].update(device="file") + p["p3"]["file"].update(name="g.msh", path="g.msh", tags=dict(n_cells=10, cells={"1": 7, "2": 3}, facets={"10": 4, "11": 2, "12": 2}, bbox=[[-5e-7] * 3, [5e-7] * 3], geometry_order=1), + tag_material={"1": "Mantel", "2": "Kern"}, pec_tags=[10], ports=[dict(tag=11, modes=1), dict(tag=12, modes=1)]) + at = AppTest.from_file(str(HERE / "fem_app.py"), default_timeout=180) # new session: the task radio of the first one keeps its widget state + at.session_state["app_mode"] = "threed" + at.session_state["work_dir"] = str(tmp_path) + for key, val in (("td_model", p), ("td_ver", 0), ("td_proc", None), ("td_dir", None), ("td_msg", None), ("td_est", None)): + at.session_state[key] = val + at.run() + assert not at.exception, [e.value for e in at.exception] + assert at.selectbox(key="p3_fr_0_11").value == "port" and at.selectbox(key="p3_fr_0_10").value == "pec"