setupEM 0.18.2__tar.gz → 0.18.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {setupem-0.18.2/src/setupEM.egg-info → setupem-0.18.3}/PKG-INFO +17 -19
  2. {setupem-0.18.2 → setupem-0.18.3}/README.md +6 -0
  3. setupem-0.18.3/README_pypi.md +75 -0
  4. {setupem-0.18.2 → setupem-0.18.3}/pyproject.toml +1 -1
  5. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/__init__.py +1 -1
  6. setupem-0.18.3/src/setupEM/script_writer.py +354 -0
  7. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/setupEM.py +8 -256
  8. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/setupThermal.py +8 -147
  9. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/setup_common.py +4 -17
  10. {setupem-0.18.2 → setupem-0.18.3/src/setupEM.egg-info}/PKG-INFO +17 -19
  11. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM.egg-info/SOURCES.txt +2 -0
  12. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM.egg-info/requires.txt +1 -1
  13. {setupem-0.18.2 → setupem-0.18.3}/tests/test_cli_startup.py +1 -1
  14. setupem-0.18.3/tests/test_script_writer.py +136 -0
  15. setupem-0.18.2/README_pypi.md +0 -77
  16. {setupem-0.18.2 → setupem-0.18.3}/LICENSE +0 -0
  17. {setupem-0.18.2 → setupem-0.18.3}/setup.cfg +0 -0
  18. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/__main__.py +0 -0
  19. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/cli_common.py +0 -0
  20. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/config_update.py +0 -0
  21. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13CMOS5L_200um.xml +0 -0
  22. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13G2_100um.xml +0 -0
  23. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13G2_200um.xml +0 -0
  24. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13G2_FEM_200um.xml +0 -0
  25. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13G2_FEM_200um_passi3D.xml +0 -0
  26. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/data/SG13G2_nosub.xml +0 -0
  27. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/field_viewer.py +0 -0
  28. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/gds_hierarchy_scan.py +0 -0
  29. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/join_pieces.py +0 -0
  30. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/layout_preview.py +0 -0
  31. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/momentum_import.py +0 -0
  32. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/palace_results.py +0 -0
  33. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/piece_set.py +0 -0
  34. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/result_viewer.py +0 -0
  35. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/run_with_overrides.py +0 -0
  36. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/script_model.py +0 -0
  37. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/script_probe.py +0 -0
  38. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/simplify_gds.py +0 -0
  39. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/stackupEditor.py +0 -0
  40. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/stackup_writer.py +0 -0
  41. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM/thermal_results.py +0 -0
  42. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM.egg-info/dependency_links.txt +0 -0
  43. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM.egg-info/entry_points.txt +0 -0
  44. {setupem-0.18.2 → setupem-0.18.3}/src/setupEM.egg-info/top_level.txt +0 -0
  45. {setupem-0.18.2 → setupem-0.18.3}/tests/test_config_update.py +0 -0
  46. {setupem-0.18.2 → setupem-0.18.3}/tests/test_config_update_gui.py +0 -0
  47. {setupem-0.18.2 → setupem-0.18.3}/tests/test_deembedded_view.py +0 -0
  48. {setupem-0.18.2 → setupem-0.18.3}/tests/test_export_no_gui.py +0 -0
  49. {setupem-0.18.2 → setupem-0.18.3}/tests/test_join_pieces.py +0 -0
  50. {setupem-0.18.2 → setupem-0.18.3}/tests/test_margin_per_side.py +0 -0
  51. {setupem-0.18.2 → setupem-0.18.3}/tests/test_piece_set.py +0 -0
  52. {setupem-0.18.2 → setupem-0.18.3}/tests/test_port_walls.py +0 -0
  53. {setupem-0.18.2 → setupem-0.18.3}/tests/test_qt_platform_noise.py +0 -0
  54. {setupem-0.18.2 → setupem-0.18.3}/tests/test_return_applies.py +0 -0
  55. {setupem-0.18.2 → setupem-0.18.3}/tests/test_run_with_overrides.py +0 -0
  56. {setupem-0.18.2 → setupem-0.18.3}/tests/test_script_model.py +0 -0
  57. {setupem-0.18.2 → setupem-0.18.3}/tests/test_script_probe.py +0 -0
  58. {setupem-0.18.2 → setupem-0.18.3}/tests/test_table_rows.py +0 -0
  59. {setupem-0.18.2 → setupem-0.18.3}/tests/test_thermal_powers.py +0 -0
  60. {setupem-0.18.2 → setupem-0.18.3}/tests/test_thermal_results.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: setupEM
3
- Version: 0.18.2
3
+ Version: 0.18.3
4
4
  Summary: Python tool for configuration of gds2palace workflow with GUI.
5
5
  Author-email: Volker Muehlhaus <volker@muehlhaus.com>
6
6
  License-Expression: GPL-3.0-or-later
@@ -10,7 +10,7 @@ Project-URL: Changelog, https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc
10
10
  Requires-Python: >=3.9
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
- Requires-Dist: gds2palace>=0.10.1
13
+ Requires-Dist: gds2palace>=0.10.7
14
14
  Requires-Dist: gds_prepare_for_EM>=1.6.0
15
15
  Requires-Dist: PySide6
16
16
  Requires-Dist: shiboken6
@@ -40,6 +40,20 @@ https://github.com/VolkerMuehlhaus/setupEM
40
40
 
41
41
  ## Recent changes
42
42
 
43
+ # What's New - November 15, 2026 (setupEM 0.18.3)
44
+
45
+ Needs gds2palace 0.10.7 or newer (`pip install` updates it).
46
+
47
+ **`combine_extend_snp.py` 1.5** (`combine_snp`, in `scripts/`), the same file as in gds2palace 0.10.7:
48
+ - The `_dc` Touchstone file keeps all simulated frequency points and adds only the 0 Hz point in front. Before, a result with the two low frequency points of a sweep from 0 Hz was resampled to a uniform frequency grid, so the simulated points, among them the two low ones, were replaced by interpolated values. The 0 Hz value itself is unchanged.
49
+ - Port walls (from gds2palace 0.10.6): the line resistance of the standards is taken from the model's lowest frequency, so R and Q of models with port walls are right also below fstop/20.
50
+
51
+ **Sweep from 0 Hz, the frequencies that replace DC** (a gds2palace 0.10.7 change, nothing to set in setupEM): with start frequency 0, gds2palace simulates two low frequency points instead of 0 Hz. These were always 10 MHz and 20 MHz. With a mesh finer than 0.5 µm (refined cellsize or a per-layer override), gds2palace 0.10.7 moves them up, to 5 MHz·µm divided by the smallest cell size and twice that (e.g. 25 and 50 MHz at 0.2 µm), because on such a fine mesh Palace could stop with "SuperLUSolver: Found a singular matrix" at 10 MHz. Models with cell sizes of 0.5 µm and more keep 10 and 20 MHz. The user's guide section on DC handling says this now.
52
+
53
+ **Citation:** `CITATION.cff` and a "How to cite" section in the README; GitHub's **Cite this repository** button gives APA and BibTeX entries.
54
+
55
+ **Internal:** the model script writer of setupEM and setupThermal is now a module without Qt (`script_writer.py`, issue #52). The written scripts are unchanged; `tests/test_script_writer.py` checks 8 recorded scripts against both the GUI and the writer.
56
+
43
57
  # What's New - November 13, 2026 (setupEM 0.18.2)
44
58
 
45
59
  **Ports and thermal objects:** Return in a text field of the form (source layer, Z0, voltage; in setupThermal layer, power, temperature) applies the settings to the selected row, like the Apply button. With no row selected, the status bar says so.
@@ -67,29 +81,13 @@ https://github.com/VolkerMuehlhaus/setupEM
67
81
 
68
82
  **Split regions, fix:**a side of the region made a port wall in setupEM after the export (e.g. with via ports of the layout on the region's edge) was a plain PEC wall in every piece and in the full check model: the wall shorted those ports, and the joined result and the full model were both wrong, in the same way. The pieces' port walls on the region's edge are now found from the ports on the edge of each piece's layout; the full model has all of the region's port walls. Where the region has a port wall but a piece none of its ports, that stretch stays PEC and now moves outward with the region's port wall extension (a length; written as `settings['wall_extension']`, needs gds2palace 0.10.1), so that all pieces and the full model have the same box.
69
83
 
70
- # What's New - November 10, 2026 (setupEM 0.18.0)
71
-
72
- **De-embedded results shown**: View S-Parameters lists the `_deembedded` files from the start and opens with the raw result and its `_deembedded` result together. Model Fit fits the calibrated result (`_dc_deembedded`, else `_deembedded`) of a model with port walls or a moved reference plane; the raw result still holds the uncalibrated gap ports.
73
-
74
- **Port wall fixes:** a model script edited in place now gives back its port wall extension, reference plane shift and de-embedding length (they were written but not read, so the next session started with 0). Two port walls no longer make 0 the default oversize and air (the other sides became overrides and the default fields changed nothing); a default field that sets no side any more is greyed out. The status line under the log names the solve of a port wall run (calibration standard k/n, reused, or the model). The Port walls status says OK or the warnings only; the layout preview draws an extended feed and its length, a symbol per box side, and labels without the side names.
75
-
76
- **Split regions**: a `.simcfg` from the KLayout plug-in's Export All of a split region (several EM region boxes) opens as a set of pieces. The Models list shows the pieces (and an unticked full check model). The settings (frequencies, mesh, solver, boundaries) are those of the whole region, shared by all pieces; a piece's box sides follow from the region's (a cut is a port wall, a stretch of a port wall without the piece's ports is PEC at the layout edge) and are locked; a piece can have its own mesh settings (Mesh tab, "Own mesh settings for p2"). Start Simulation runs the pieces without a gmsh window and does not mesh a piece again whose mesh is current; View S-Parameters shows the joined result first, and Model Fit fits it. The port wall extension and reference plane shift are the region's, on its outer sides only (none on a cut). An export written on another machine opens with its model folders, layouts and stackup found here. Start Simulation creates and runs the ticked pieces one after another and joins their results at the cuts (`join_pieces.py`, also `python -m setupEM.join_pieces <name>.simcfg`) into `<name>_deembedded.sNp` of the whole region. A piece whose layout fingerprint, settings and gds2palace version are unchanged since its last run is reused (`piece.key` in its model folder); **Run unchanged pieces too** overrides. Create Model keeps a settings file's own keys of the layout tool (piece name, fingerprint) when it rewrites the file.
77
-
78
- The calibration standards of a port wall are no longer listed as models of their own in **Models** on the Create Model tab (they share the model's `_data` folder and its `run_sim` solves them before the model); Start Simulation ran `run_sim` once per listed row, and **Preview** stopped after the first standard with the model itself unbuilt. For a script that creates several models, the question about results of a previous simulation is now asked once before the first model starts, not between two models.
79
-
80
- **Port walls**: calibrated ports at the layout edge (needs gds2palace 0.10.0). **Mesh and Boundaries > Advanced...** offers **Port wall** for xmin, xmax, ymin and ymax: PEC at the layout edge, oversize and air 0 and locked, written as `'PORTWALL'` in `settings['boundary']`. The Ports tab gets a **De-embedding** column (calibrated at a port wall, or the estimated port inductance), locks the direction of ports on a port wall, and a **Port walls** group with **Check port walls** (reads the layout, no meshing): per port wall its ports, ground at the cut, D, the standards' lengths, the valid frequency range, warnings or the error, and the **Reference plane shift** (`settings['reference_plane_shift']`). A port on an edge that is not a port wall gets the question whether to make that side one. Create Model runs the check when a port wall is set and stops on an error. An **Extension (µm)** per port wall (`auto` or a length, `settings['port_wall_extension']`) moves the port wall outward. The Ports tab runs the check by itself when a port wall has no result yet; the panel splits with the port list by a divider; warnings show with an icon and the start of their text. The layout preview shows the reference plane, where the uniform feed ends, and an extension, and fits the view to the layout and its box. setupEM and setupThermal keep the window's size and position (and the Ports tab's divider) from one session to the next. A via port on a port wall is listed as "via port used as a gap port on <line metal>" (gds2palace converts it when writing the model). The layout preview draws the simulation box: one frame, not to scale, with a label per side (a click opens the box sides dialog), a port wall as a white line. `combine_extend_snp.py` in `src/scripts` is synced with gds2palace.
81
-
82
- The dielectric oversize can be set per side (xmin, xmax, ymin, ymax): in setupEM with **Advanced...** next to **Boundary conditions**, in setupThermal with **Advanced...** next to the oversize. It is written to the model script as a list `settings['margin'] = [xmin, xmax, ymin, ymax]`, and read from there and from settings files. Needs gds2palace 0.10.0. A negative oversize is no longer accepted.
83
-
84
- Bundled IHP stackups (from gds2palace 0.10.0): heat source target layers `HEAT_TRANSISTOR` and `HEAT_RESISTOR`, for thermal models. Nothing is drawn on them, so EM models are unchanged.
85
-
86
84
  Full history: [CHANGES.md](https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc/CHANGES.md)
87
85
 
88
86
  ---
89
87
 
90
88
  **Note:** the `setupEM` PyPI package itself requires:
91
89
 
92
- - gds2palace>=0.10.1
90
+ - gds2palace>=0.10.7
93
91
  - gds_prepare_for_EM>=1.6.0
94
92
  - PySide6
95
93
  - shiboken6
@@ -339,6 +339,12 @@ If you then start KLayout using this script, a new menu item is available: Tools
339
339
 
340
340
  3. Name it e.g. **setupEM via KLayout**
341
341
 
342
+ # How to cite
343
+
344
+ If you use setupEM in a publication, please cite it. The **Cite this repository** button on the GitHub repository page gives APA and BibTeX entries, generated from [CITATION.cff](./CITATION.cff).
345
+
346
+ Please also cite [gds2palace](https://github.com/VolkerMuehlhaus/gds2palace_ihp_sg13g2), which builds the model, and the [Palace](https://github.com/awslabs/palace) solver that computed your results.
347
+
342
348
  # License
343
349
 
344
350
  This project is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later) - see [LICENSE](./LICENSE) for the full text.
@@ -0,0 +1,75 @@
1
+ # Python GUI for gds2palace
2
+
3
+ ![Intro](https://raw.githubusercontent.com/VolkerMuehlhaus/setupEM/main/doc/png/setupEM_banner.png)
4
+
5
+ ## Install
6
+
7
+ pip install setupEM
8
+
9
+ **Full documentation, installation guide, and usage walkthrough:**
10
+ https://github.com/VolkerMuehlhaus/setupEM
11
+
12
+ ## Recent changes
13
+
14
+ # What's New - November 15, 2026 (setupEM 0.18.3)
15
+
16
+ Needs gds2palace 0.10.7 or newer (`pip install` updates it).
17
+
18
+ **`combine_extend_snp.py` 1.5** (`combine_snp`, in `scripts/`), the same file as in gds2palace 0.10.7:
19
+ - The `_dc` Touchstone file keeps all simulated frequency points and adds only the 0 Hz point in front. Before, a result with the two low frequency points of a sweep from 0 Hz was resampled to a uniform frequency grid, so the simulated points, among them the two low ones, were replaced by interpolated values. The 0 Hz value itself is unchanged.
20
+ - Port walls (from gds2palace 0.10.6): the line resistance of the standards is taken from the model's lowest frequency, so R and Q of models with port walls are right also below fstop/20.
21
+
22
+ **Sweep from 0 Hz, the frequencies that replace DC** (a gds2palace 0.10.7 change, nothing to set in setupEM): with start frequency 0, gds2palace simulates two low frequency points instead of 0 Hz. These were always 10 MHz and 20 MHz. With a mesh finer than 0.5 µm (refined cellsize or a per-layer override), gds2palace 0.10.7 moves them up, to 5 MHz·µm divided by the smallest cell size and twice that (e.g. 25 and 50 MHz at 0.2 µm), because on such a fine mesh Palace could stop with "SuperLUSolver: Found a singular matrix" at 10 MHz. Models with cell sizes of 0.5 µm and more keep 10 and 20 MHz. The user's guide section on DC handling says this now.
23
+
24
+ **Citation:** `CITATION.cff` and a "How to cite" section in the README; GitHub's **Cite this repository** button gives APA and BibTeX entries.
25
+
26
+ **Internal:** the model script writer of setupEM and setupThermal is now a module without Qt (`script_writer.py`, issue #52). The written scripts are unchanged; `tests/test_script_writer.py` checks 8 recorded scripts against both the GUI and the writer.
27
+
28
+ # What's New - November 13, 2026 (setupEM 0.18.2)
29
+
30
+ **Ports and thermal objects:** Return in a text field of the form (source layer, Z0, voltage; in setupThermal layer, power, temperature) applies the settings to the selected row, like the Apply button. With no row selected, the status bar says so.
31
+
32
+ **Command line fixes** (from issue #52):
33
+ - A script from File > Export runs without a display: gds2palace 0.10.4 and newer builds the model without the gmsh window on Linux with no display (ssh, container, batch job). Before, the script stopped with "Can't open display". The exported script also has the switch as a comment, `# settings['no_gui'] = True`, for unattended runs where a display exists.
34
+ - `combine_extend_snp.py` (`combine_snp`, in `scripts/`) has `--help` and `--version`, and takes the folder to search as an optional argument. Before, any option was ignored and the conversion ran. Same file as in gds2palace 0.10.4.
35
+
36
+ **Scripts used on two machines** (e.g. Windows and Linux):
37
+ - A model script edited in place whose GDS file was taken from its folder on opening (the script had the other machine's path, e.g. `/mnt/pub/...` for `P:/...`) now gets that path when it is saved or the model is created; the Code tab shows it. Before, the GUI showed the new path and the script kept the old one, and the model was made from the old one.
38
+ - On Linux, a path with a drive letter from Windows (`D:/...`) in a script or settings file is no longer taken as relative to the script's folder (`/mnt/.../D:/...`, "Load a GDSII file and XML stackup first"). A stackup that is not found, also not next to the script, is taken from the stackups that ship with gds2palace if one has that name; the log says so.
39
+
40
+ # What's New - November 11, 2026 (setupEM 0.18.1)
41
+
42
+ **Command line fixes** (from issue #52, use without a display):
43
+ - `--help`, `--version` and a wrong argument of `setupEM`, `setupThermal`, `stackupEditor`, `resultViewer` and `fieldViewer` no longer need a display: the arguments are read before Qt starts. All five have `--version` now.
44
+ - `setupEM -simcfg <file>` opens a settings file of an Elmer model in Elmer mode. It opened in Palace mode unless `--elmer` was given, also when started from the KLayout plug-in.
45
+ - A `-simcfg`, `-gdsfile` or `-xmlfile` that does not exist, or a settings file of the other application, ends `setupEM` / `setupThermal` with a message on stderr and exit code 2 instead of an empty window. In the GUI, a settings file that is gone is reported as "File not found", not as "Unknown data format".
46
+ - Loading a settings file no longer shows a "Loaded" box: the log says "Config loaded from ...", with a GDS or stackup file that was not found at its saved path and was taken from the settings file's folder instead.
47
+ - Opening a `.simcfg` continues with the model script only when the file is linked to it, and asks only when the two have other settings (the question lists them). Create Model links: besides `<model>.simcfg` it writes the script's name (`"model_script"`) into the `.simcfg` the model was opened from, e.g. the KLayout plug-in's export, which keeps it on the next export. A script that only reads the same GDSII file is no longer taken for the model; the log names it. New options `--continue-with-script` and `--start-from-config` answer the question on the command line.
48
+ - `fieldViewer --screenshot` needs no display and no `QT_QPA_PLATFORM=offscreen`.
49
+ - `python -m setupEM.join_pieces` and `python -m setupEM.thermal_results` have `--help` and `--version`, write their errors to stderr, and a missing file is a message, not a traceback.
50
+ - The modules without a GUI (`join_pieces`, `thermal_results`, `script_model`, ...) can be imported without loading Qt.
51
+ - User guide: Model Fit starts snp2le with the result file loaded (the text said it has to be loaded by hand).
52
+
53
+ **Split regions, fix:**a side of the region made a port wall in setupEM after the export (e.g. with via ports of the layout on the region's edge) was a plain PEC wall in every piece and in the full check model: the wall shorted those ports, and the joined result and the full model were both wrong, in the same way. The pieces' port walls on the region's edge are now found from the ports on the edge of each piece's layout; the full model has all of the region's port walls. Where the region has a port wall but a piece none of its ports, that stretch stays PEC and now moves outward with the region's port wall extension (a length; written as `settings['wall_extension']`, needs gds2palace 0.10.1), so that all pieces and the full model have the same box.
54
+
55
+ Full history: [CHANGES.md](https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc/CHANGES.md)
56
+
57
+ ---
58
+
59
+ **Note:** the `setupEM` PyPI package itself requires:
60
+
61
+ - gds2palace>=0.10.7
62
+ - gds_prepare_for_EM>=1.6.0
63
+ - PySide6
64
+ - shiboken6
65
+ - scipy
66
+ - requests
67
+ - scikit-rf
68
+ - matplotlib
69
+ - numpy
70
+ - gdspy
71
+ - meshio
72
+ - pyvista
73
+ - pyvistaqt
74
+
75
+ (Other Python modules mentioned above are only needed to run standalone helper scripts in this repository, not to use the installed package.)
@@ -12,7 +12,7 @@ authors = [
12
12
  { name = "Volker Muehlhaus", email = "volker@muehlhaus.com" }
13
13
  ]
14
14
  dependencies = [
15
- "gds2palace>=0.10.1",
15
+ "gds2palace>=0.10.7",
16
16
  "gds_prepare_for_EM>=1.6.0",
17
17
  "PySide6",
18
18
  "shiboken6",
@@ -31,4 +31,4 @@ def main():
31
31
 
32
32
 
33
33
  __all__ = ["main"]
34
- __version__ = "0.18.2"
34
+ __version__ = "0.18.3"
@@ -0,0 +1,354 @@
1
+ ########################################################################
2
+ #
3
+ # Copyright 2025-2026 Volker Muehlhaus and IHP PDK Authors
4
+ #
5
+ # Licensed under the GNU General Public License, Version 3.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # https://www.gnu.org/licenses/gpl-3.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ ########################################################################
18
+
19
+ """The gds2palace model script that setupEM and setupThermal write (Code tab, File > Export, Create Model), made
20
+ from the settings, the ports or thermal objects, and the solver mode. No Qt: the GUIs call it after collecting the
21
+ tabs' values, and a command can call it with the contents of a settings file.
22
+
23
+ em_script_text(saved_values, simulation_ports, elmer_mode, for_export) setupEM, Palace or Elmer EM
24
+ thermal_script_text(saved_values, thermal_objects, for_export) setupThermal, Elmer thermal
25
+
26
+ saved_values holds frequencies in GHz, as the settings file does; the script gets them in Hz.
27
+ """
28
+
29
+ import ast
30
+
31
+ from gds2palace import gds_reader, simulation_setup
32
+
33
+ # Solvers ("palace", "elmer", "elmer_thermal") for which the installed gds2palace applies
34
+ # settings['fill_factor_correction']; an older gds2palace silently ignores the setting, so
35
+ # only offer it where it has an effect. gds2palace declares this list itself since Elmer
36
+ # support was added; before that, the feature existed for Palace only.
37
+ FILL_FACTOR_CORRECTION_SOLVERS = getattr(
38
+ simulation_setup, "FILL_FACTOR_CORRECTION_SOLVERS",
39
+ ("palace",) if hasattr(gds_reader.all_polygons_list, "compute_via_fill_factors") else ())
40
+ # Palace linear solver settings (settings['complex_coarse_solve'/'solver_maxits'/'solver_tol'])
41
+ # the installed gds2palace understands - empty for an older gds2palace, which hardcodes them
42
+ # and would silently ignore these keys, so the Mesh tab hides its linear solver rows then.
43
+ PALACE_LINEAR_SOLVER_SETTINGS = tuple(getattr(simulation_setup, "PALACE_LINEAR_SOLVER_SETTINGS", ()))
44
+
45
+ # File > Export: the switch for running the exported script with no gmsh window, commented out (an import
46
+ # reads no settings from comments). gds2palace 0.10.4 and newer turns it on by itself without a display.
47
+ NO_GUI_EXPORT_LINE = ("# settings['no_gui'] = True # no gmsh window, for unattended runs "
48
+ "(on Linux without a display, gds2palace 0.10.4 and newer skips it by itself)")
49
+
50
+ # keys written in Hz in the script, held in GHz in the settings
51
+ _GHZ_VALUES = ('fstart', 'fstop', 'fstep')
52
+ _GHZ_LISTS = ('fdump', 'fpoint')
53
+
54
+
55
+ def ports_from_struct(ports):
56
+ """gds2palace's all_simulation_ports from the "ports" list of a settings file, as the Ports tab builds it from its
57
+ table: numbers as float (Z0, voltage) and int (layer), ports in the order of their numbers. Raises ValueError for
58
+ a port the Ports tab would refuse."""
59
+ simulation_ports = simulation_setup.all_simulation_ports()
60
+ for port in sorted(ports, key=lambda p: int(p["portnumber"])):
61
+ number = int(port["portnumber"])
62
+ try:
63
+ z0, voltage = float(port.get("port_Z0", 50)), float(port.get("voltage", 1))
64
+ layer = int(port["source_layernum"])
65
+ except (KeyError, TypeError, ValueError):
66
+ raise ValueError(f"Invalid input for port {number}") from None
67
+ direction = str(port.get("direction") or "")
68
+ via = "Z" in direction.upper()
69
+ target, from_name, to_name = (port.get(k) or "" for k in ("target_layername", "from_layername",
70
+ "to_layername"))
71
+ # gds2palace's simulation_port() exits the whole program on a direction that does not match its layers
72
+ if direction.strip().upper() not in ("X", "Y", "Z", "-X", "-Y", "-Z") or \
73
+ not ((from_name and to_name) if via else target):
74
+ raise ValueError(f"Port {number} is incomplete: direction X, Y, -X or -Y needs a target layer (in-plane "
75
+ "port), Z or -Z needs a from and a to layer (via port).")
76
+ if via:
77
+ simulation_ports.add_port(simulation_setup.simulation_port(
78
+ portnumber=number, voltage=voltage, port_Z0=z0, source_layernum=layer,
79
+ from_layername=from_name, to_layername=to_name, direction=direction))
80
+ else:
81
+ simulation_ports.add_port(simulation_setup.simulation_port(
82
+ portnumber=number, voltage=voltage, port_Z0=z0, source_layernum=layer,
83
+ target_layername=target, direction=direction))
84
+ return simulation_ports
85
+
86
+
87
+ def thermal_objects_from_struct(objects):
88
+ """gds2palace's all_thermal_objects from the "thermal" list of a settings file, as the thermal tab builds it.
89
+ Raises ValueError for an entry the tab would refuse."""
90
+ thermal_objects = simulation_setup.all_thermal_objects()
91
+ for row, entry in enumerate(objects, start=1):
92
+ is_source = "SOURCE" in str(entry.get("type", "")).upper()
93
+ try:
94
+ layer = int(entry["source_layernum"])
95
+ value = float(entry["power"] if is_source else entry["temp"])
96
+ except (KeyError, TypeError, ValueError):
97
+ raise ValueError(f"Invalid input in row {row}") from None
98
+ target = entry.get("target_layername") or ""
99
+ if is_source:
100
+ thermal_objects.add_heatsource(simulation_setup.heatsource(
101
+ power=value, source_layernum=layer, target_layername=target))
102
+ else:
103
+ thermal_objects.add_consttemp(simulation_setup.constanttemp(
104
+ temp=value, source_layernum=layer, target_layername=target))
105
+ return thermal_objects
106
+
107
+
108
+ def _setting_line(saved_values, key):
109
+ """settings['key'] = value, as a line of Python."""
110
+ value = str(saved_values[key])
111
+ if '\\' in value:
112
+ # make sure we don't run into escape character issue with Windows paths
113
+ value = value.replace('\\', '/')
114
+ if key in _GHZ_VALUES:
115
+ value = str(value) + 'e9'
116
+ if key in _GHZ_LISTS:
117
+ # value is the string representation of a list
118
+ value = "[" + ",".join(str(f) + "e9" for f in ast.literal_eval(value)) + "]"
119
+ if isinstance(saved_values[key], str):
120
+ # value is a string, enclose in quotes (backslashes of Windows paths replaced above)
121
+ return "settings['" + key + "'] = '" + value + "'"
122
+ return "settings['" + key + "'] = " + str(value)
123
+
124
+
125
+ def _header(lines, app_name, title, dirname):
126
+ lines.append(f"# {title} created using " + app_name)
127
+ lines.append("import os, sys, subprocess")
128
+ lines.append("\nfrom gds2palace import *")
129
+ lines.append("\n# get path for this simulation file")
130
+ lines.append("script_path = utilities.get_script_path(__file__)")
131
+ lines.append("# use script filename as model basename")
132
+ lines.append("model_basename = utilities.get_basename(__file__)")
133
+ lines.append("# set and create directory for simulation output")
134
+ if dirname:
135
+ lines.append(f"sim_path = utilities.create_sim_path (script_path,model_basename,dirname='{dirname}')")
136
+ else:
137
+ lines.append("sim_path = utilities.create_sim_path (script_path,model_basename)")
138
+
139
+
140
+ def _start_simulation(lines, solver, run_script):
141
+ """The part of an exported script that starts the solver when start_simulation is set."""
142
+ lines.append(f"\n# run after creating mesh and {solver} ")
143
+ lines.append("if start_simulation:")
144
+ lines.append(" try:")
145
+ lines.append(" os.chdir(sim_path)")
146
+ if run_script:
147
+ lines.append(" if sys.platform.startswith('linux'):")
148
+ lines.append(f" os.chmod('{run_script}', 0o755)")
149
+ lines.append(" subprocess.run(run_command, shell=True)")
150
+ lines.append(" except:")
151
+ lines.append(f" print(f'Unable to run {solver.split()[0]} using command ',run_command)\n")
152
+
153
+
154
+ def _read_geometry(lines, layers_from, em):
155
+ lines.append("\n# ================= read stackup and geometries =================")
156
+ lines.append("materials_list, dielectrics_list, metals_list = stackup_reader.read_substrate "
157
+ "(settings['SubstrateFile'], variable_overrides=settings['variable_overrides'])")
158
+ lines.append("layernumbers = metals_list.getlayernumbers()")
159
+ lines.append(f"layernumbers.extend({layers_from})")
160
+ lines.append("\n# read geometries from GDSII")
161
+ text = ("allpolygons = gds_reader.read_gds(settings['GdsFile'], "
162
+ "\n\tlayernumbers,"
163
+ "\n\tcellname=settings['cellname'], "
164
+ "\n\tpurposelist=settings['purpose'], "
165
+ "\n\tmetals_list=metals_list, \n\tpreprocess=settings['preprocess_gds'], "
166
+ "\n\tmerge_polygon_size=settings['merge_polygon_size'],")
167
+ if em:
168
+ text += ("\n\tgds_boundary_layers=dielectrics_list.get_boundary_layers(),"
169
+ "\n\tmirror=False, "
170
+ "\n\toffset_x=0, offset_y=0,"
171
+ "\n\tlayernumber_offset=0)")
172
+ else:
173
+ text += "\n\tgds_boundary_layers=dielectrics_list.get_boundary_layers())"
174
+ lines.append(text)
175
+ lines.append("\n")
176
+
177
+
178
+ def em_script_text(saved_values, simulation_ports, elmer_mode, for_export=False, app_name="setupEM",
179
+ fill_factor_solvers=None, palace_linear_solver_settings=None):
180
+ """setupEM's model script, Palace (elmer_mode False) or Elmer EM. for_export: the File > Export form, which also
181
+ starts the solver; without it, the form setupEM runs itself (Create Model). simulation_ports: gds2palace's
182
+ all_simulation_ports. The two capability arguments default to what the installed gds2palace supports."""
183
+ if fill_factor_solvers is None:
184
+ fill_factor_solvers = FILL_FACTOR_CORRECTION_SOLVERS
185
+ if palace_linear_solver_settings is None:
186
+ palace_linear_solver_settings = PALACE_LINEAR_SOLVER_SETTINGS
187
+ palace_mode = not elmer_mode
188
+ lines = []
189
+ _header(lines, app_name, "Model for IHP OpenPDK EM workflow", "elmer_model" if elmer_mode else None)
190
+
191
+ lines.append("\n# ========================= workflow settings ==========================")
192
+ if for_export:
193
+ lines.append("# preview model/mesh only, without running solver?")
194
+ lines.append("start_simulation = False")
195
+ lines.append("\n# Command to start simulation")
196
+ if palace_mode:
197
+ lines.append("# run_command = ['start', 'wsl.exe'] # Windows Subsystem for Linux")
198
+ lines.append("run_command = ['./run_sim'] # Linux")
199
+ else:
200
+ lines.append("run_command = ['./run_elmer'] # Linux")
201
+
202
+ lines.append("\n# ===================== input files and settings =======================")
203
+ lines.append("settings={}")
204
+ if for_export:
205
+ lines.append(NO_GUI_EXPORT_LINE)
206
+
207
+ # keys that must be set AFTER reading stackup and GDSII, not before
208
+ special_keylist = ['simulation_ports', 'materials_list', 'dielectrics_list', 'metals_list',
209
+ 'layernumbers', 'allpolygons']
210
+ # keys not written to the script; fdump_enabled is a GUI-only toggle (Elmer mode), never a gds2palace setting
211
+ ignore_list = ['model_basename', 'sim_path', 'fdump_enabled']
212
+ if palace_mode:
213
+ ignore_list.append('iterative')
214
+ else:
215
+ # Elmer mode shows a plain on/off checkbox (fdump_enabled) instead of Palace's per-frequency fdump list, so a
216
+ # stale Palace-mode list from earlier in the same session must not leak into an Elmer script; the
217
+ # synthesized settings['fdump'] line below is written instead when the checkbox is on.
218
+ ignore_list.append('fdump')
219
+ # conductor_model (filled_metals with an older gds2palace) is Palace-only in the GUI: gds2palace's volume
220
+ # conductors also cover Elmer EM, but that path is untested from setupEM so far
221
+ ignore_list.extend(['conductor_model', 'filled_metals'])
222
+ # an older gds2palace supports the via fill factor correction for Palace only
223
+ if 'elmer' not in fill_factor_solvers:
224
+ ignore_list.append('fill_factor_correction')
225
+ if for_export:
226
+ # these only control gmsh within the GUI
227
+ ignore_list.extend(['preview_only', 'no_preview'])
228
+ # Palace linear solver settings: Palace-only, and only for a gds2palace that applies them (an older one
229
+ # hardcodes them and would silently ignore the keys)
230
+ if elmer_mode or not palace_linear_solver_settings:
231
+ ignore_list.extend(['complex_coarse_solve', 'solver_maxits', 'solver_tol'])
232
+ # AMR settings only matter for Palace with at least one AMR iteration
233
+ if elmer_mode:
234
+ ignore_list.extend(['adaptive_mesh_iterations', 'amr_tol', 'amr_max_dof', 'adaptive_mesh_conformal'])
235
+ elif int(saved_values.get('adaptive_mesh_iterations', 0)) == 0:
236
+ ignore_list.extend(['amr_tol', 'amr_max_dof', 'adaptive_mesh_conformal'])
237
+
238
+ # settings grouped by topic; keys not listed here end up in "Other", so a new setting is never silently dropped
239
+ setting_groups = [
240
+ ("Input files", ['GdsFile', 'SubstrateFile', 'variable_overrides', 'cellname', 'purpose',
241
+ 'preprocess_gds', 'merge_polygon_size', 'fill_factor_correction']),
242
+ ("Frequencies", ['fstart', 'fstop', 'fstep', 'fpoint', 'fdump']),
243
+ ("Mesh", ['unit', 'refined_cellsize', 'refined_cellsize_override', 'cells_per_wavelength',
244
+ 'meshsize_max', 'order', 'conductor_model', 'filled_metals']),
245
+ ("Adaptive mesh refinement", ['adaptive_mesh_iterations', 'amr_tol', 'amr_max_dof',
246
+ 'adaptive_mesh_conformal']),
247
+ ("Simulation boundary", ['boundary', 'margin', 'air_around', 'reference_plane_shift', 'port_wall_extension',
248
+ 'wall_extension']),
249
+ ("Solver", ['complex_coarse_solve', 'solver_maxits', 'solver_tol', 'iterative', 'ELMER_MPI_THREADS']),
250
+ ("Script control", ['preview_only', 'no_preview']),
251
+ ]
252
+ grouped_keys = {key for _, keys in setting_groups for key in keys}
253
+ setting_groups.append(("Other", [key for key in saved_values if key not in grouped_keys]))
254
+ for group_name, keys in setting_groups:
255
+ keys = [key for key in keys if key in saved_values and key not in special_keylist and key not in ignore_list]
256
+ if keys:
257
+ lines.append(f"\n# ---- {group_name} ----")
258
+ lines.extend(_setting_line(saved_values, key) for key in keys)
259
+
260
+ if elmer_mode and bool(saved_values.get('fdump_enabled')):
261
+ # Elmer has no per-frequency SaveStep like Palace: it dumps fields at every solved frequency once any fdump
262
+ # value is set, so reuse an already-solved frequency (no extra solve: util_elmer.write_elmer_frequencies()
263
+ # dedupes the frequency list). Known limitation: this line's right-hand side references "settings", so
264
+ # parse_assignments() skips it on Import, and a re-imported Elmer+fdump script loads unchecked.
265
+ lines.append("\n# 'Enable field dump' checkbox: Elmer dumps fields at every solved")
266
+ lines.append("# frequency once fdump is non-empty, so reuse an already-solved one")
267
+ if 'fstop' in saved_values:
268
+ lines.append("settings['fdump'] = [settings['fstop']]")
269
+ elif saved_values.get('fpoint'):
270
+ lines.append("settings['fdump'] = [settings['fpoint'][0]]")
271
+
272
+ lines.append("\n# ===================== port definitions =======================")
273
+ lines.append("simulation_ports = simulation_setup.all_simulation_ports()")
274
+ for port in simulation_ports.ports:
275
+ if "Z" in port.direction.upper():
276
+ layers = f"from_layername='{port.from_layername}', to_layername='{port.to_layername}', "
277
+ else:
278
+ layers = f"target_layername='{port.target_layername}', "
279
+ lines.append(f"simulation_ports.add_port(simulation_setup.simulation_port("
280
+ f"portnumber={port.portnumber}, voltage={port.voltage}, port_Z0={port.port_Z0}, "
281
+ f"source_layernum={port.source_layernum}, {layers}direction='{port.direction}'))")
282
+
283
+ _read_geometry(lines, "simulation_ports.portlayers", em=True)
284
+ for key in special_keylist:
285
+ lines.append("settings['" + key + "'] = " + key)
286
+ lines.append("settings['sim_path'] = sim_path")
287
+ lines.append("settings['model_basename'] = model_basename")
288
+
289
+ lines.append("\n# list of ports that are excited (set voltage to zero in port excitation to skip an excitation!)")
290
+ lines.append("excite_ports = simulation_ports.all_active_excitations()")
291
+ if elmer_mode:
292
+ lines.append("config_name, data_dir = simulation_setup.create_elmer (excite_ports, settings)")
293
+ lines.append("\n# for convenience, write run script to model directory")
294
+ lines.append("utilities.create_elmer_run_script(settings['sim_path'],settings)")
295
+ if for_export:
296
+ _start_simulation(lines, "Elmer model files", "run_elmer")
297
+ else:
298
+ lines.append("config_name, data_dir = simulation_setup.create_palace (excite_ports, settings)")
299
+ lines.append("\n# for convenience, write run script to model directory")
300
+ lines.append("utilities.create_run_script(settings['sim_path'])")
301
+ if for_export:
302
+ _start_simulation(lines, "Palace config.json", "run_sim")
303
+ return "\n".join(lines)
304
+
305
+
306
+ def thermal_script_text(saved_values, thermal_objects, for_export=False, app_name="setupThermal"):
307
+ """setupThermal's model script (Elmer thermal). for_export: the File > Export form, which also starts the solver.
308
+ thermal_objects: gds2palace's all_thermal_objects."""
309
+ lines = []
310
+ _header(lines, app_name, "Thermal model for IHP OpenPDK workflow", "elmer_model")
311
+
312
+ lines.append("\n# ========================= workflow settings ==========================")
313
+ if for_export:
314
+ lines.append("# preview model/mesh only, without running solver?")
315
+ lines.append("start_simulation = False")
316
+ lines.append("\n# Command to start simulation")
317
+ lines.append("run_command = ['ElmerSolver']")
318
+
319
+ lines.append("\n# ===================== input files and settings =======================")
320
+ lines.append("settings={}")
321
+ if for_export:
322
+ lines.append(NO_GUI_EXPORT_LINE)
323
+
324
+ special_keylist = ['thermal_objects', 'materials_list', 'dielectrics_list', 'metals_list',
325
+ 'layernumbers', 'allpolygons']
326
+ ignore_list = ['model_basename', 'sim_path']
327
+ if for_export:
328
+ ignore_list.extend(['preview_only', 'no_preview'])
329
+ lines.extend(_setting_line(saved_values, key) for key in saved_values
330
+ if key not in special_keylist and key not in ignore_list)
331
+ lines.append("settings['elmer_thermal'] = True # create all metals as volumes, enable Elmer thermal output")
332
+
333
+ lines.append("\n# ===================== port definitions =======================")
334
+ lines.append("thermal_objects = simulation_setup.all_thermal_objects()")
335
+ for thermal_object in thermal_objects.objects:
336
+ if isinstance(thermal_object, simulation_setup.heatsource):
337
+ lines.append(f"thermal_objects.add_heatsource(simulation_setup.heatsource("
338
+ f"power={thermal_object.power}, source_layernum={thermal_object.source_layernum}, "
339
+ f"target_layername='{thermal_object.target_layername}'))")
340
+ if isinstance(thermal_object, simulation_setup.constanttemp):
341
+ lines.append(f"thermal_objects.add_consttemp(simulation_setup.constanttemp("
342
+ f"temp={thermal_object.temp}, source_layernum={thermal_object.source_layernum}, "
343
+ f"target_layername='{thermal_object.target_layername}'))")
344
+
345
+ _read_geometry(lines, "thermal_objects.layers", em=False)
346
+ for key in special_keylist:
347
+ lines.append("settings['" + key + "'] = " + key)
348
+ lines.append("settings['sim_path'] = sim_path")
349
+ lines.append("settings['model_basename'] = model_basename")
350
+ lines.append("\n")
351
+ lines.append("config_name, data_dir = simulation_setup.create_elmer_thermal (settings)")
352
+ if for_export:
353
+ _start_simulation(lines, "Elmer model files", None)
354
+ return "\n".join(lines)