setupEM 0.18.2__tar.gz → 0.18.4__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 (63) hide show
  1. setupem-0.18.4/PKG-INFO +95 -0
  2. {setupem-0.18.2 → setupem-0.18.4}/README.md +6 -0
  3. setupem-0.18.4/README_pypi.md +66 -0
  4. {setupem-0.18.2 → setupem-0.18.4}/pyproject.toml +1 -1
  5. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/__init__.py +1 -1
  6. setupem-0.18.4/src/setupEM/script_writer.py +354 -0
  7. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/setupEM.py +8 -256
  8. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/setupThermal.py +8 -147
  9. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/setup_common.py +135 -37
  10. setupem-0.18.4/src/setupEM.egg-info/PKG-INFO +95 -0
  11. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM.egg-info/SOURCES.txt +3 -0
  12. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM.egg-info/requires.txt +1 -1
  13. {setupem-0.18.2 → setupem-0.18.4}/tests/test_cli_startup.py +2 -1
  14. {setupem-0.18.2 → setupem-0.18.4}/tests/test_config_update_gui.py +3 -0
  15. {setupem-0.18.2 → setupem-0.18.4}/tests/test_deembedded_view.py +2 -0
  16. {setupem-0.18.2 → setupem-0.18.4}/tests/test_export_no_gui.py +1 -0
  17. {setupem-0.18.2 → setupem-0.18.4}/tests/test_margin_per_side.py +1 -0
  18. {setupem-0.18.2 → setupem-0.18.4}/tests/test_piece_set.py +5 -0
  19. {setupem-0.18.2 → setupem-0.18.4}/tests/test_port_walls.py +1 -0
  20. {setupem-0.18.2 → setupem-0.18.4}/tests/test_return_applies.py +1 -0
  21. setupem-0.18.4/tests/test_save_current_file.py +119 -0
  22. setupem-0.18.4/tests/test_script_writer.py +137 -0
  23. {setupem-0.18.2 → setupem-0.18.4}/tests/test_table_rows.py +1 -0
  24. {setupem-0.18.2 → setupem-0.18.4}/tests/test_thermal_powers.py +6 -0
  25. {setupem-0.18.2 → setupem-0.18.4}/tests/test_thermal_results.py +1 -0
  26. setupem-0.18.2/PKG-INFO +0 -106
  27. setupem-0.18.2/README_pypi.md +0 -77
  28. setupem-0.18.2/src/setupEM.egg-info/PKG-INFO +0 -106
  29. {setupem-0.18.2 → setupem-0.18.4}/LICENSE +0 -0
  30. {setupem-0.18.2 → setupem-0.18.4}/setup.cfg +0 -0
  31. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/__main__.py +0 -0
  32. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/cli_common.py +0 -0
  33. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/config_update.py +0 -0
  34. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13CMOS5L_200um.xml +0 -0
  35. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13G2_100um.xml +0 -0
  36. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13G2_200um.xml +0 -0
  37. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13G2_FEM_200um.xml +0 -0
  38. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13G2_FEM_200um_passi3D.xml +0 -0
  39. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/data/SG13G2_nosub.xml +0 -0
  40. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/field_viewer.py +0 -0
  41. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/gds_hierarchy_scan.py +0 -0
  42. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/join_pieces.py +0 -0
  43. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/layout_preview.py +0 -0
  44. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/momentum_import.py +0 -0
  45. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/palace_results.py +0 -0
  46. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/piece_set.py +0 -0
  47. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/result_viewer.py +0 -0
  48. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/run_with_overrides.py +0 -0
  49. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/script_model.py +0 -0
  50. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/script_probe.py +0 -0
  51. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/simplify_gds.py +0 -0
  52. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/stackupEditor.py +0 -0
  53. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/stackup_writer.py +0 -0
  54. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM/thermal_results.py +0 -0
  55. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM.egg-info/dependency_links.txt +0 -0
  56. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM.egg-info/entry_points.txt +0 -0
  57. {setupem-0.18.2 → setupem-0.18.4}/src/setupEM.egg-info/top_level.txt +0 -0
  58. {setupem-0.18.2 → setupem-0.18.4}/tests/test_config_update.py +0 -0
  59. {setupem-0.18.2 → setupem-0.18.4}/tests/test_join_pieces.py +0 -0
  60. {setupem-0.18.2 → setupem-0.18.4}/tests/test_qt_platform_noise.py +0 -0
  61. {setupem-0.18.2 → setupem-0.18.4}/tests/test_run_with_overrides.py +0 -0
  62. {setupem-0.18.2 → setupem-0.18.4}/tests/test_script_model.py +0 -0
  63. {setupem-0.18.2 → setupem-0.18.4}/tests/test_script_probe.py +0 -0
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: setupEM
3
+ Version: 0.18.4
4
+ Summary: Python tool for configuration of gds2palace workflow with GUI.
5
+ Author-email: Volker Muehlhaus <volker@muehlhaus.com>
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/VolkerMuehlhaus/setupEM
8
+ Project-URL: Repository, https://github.com/VolkerMuehlhaus/setupEM
9
+ Project-URL: Changelog, https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc/CHANGES.md
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: gds2palace>=0.10.7
14
+ Requires-Dist: gds_prepare_for_EM>=1.6.0
15
+ Requires-Dist: PySide6
16
+ Requires-Dist: shiboken6
17
+ Requires-Dist: scipy
18
+ Requires-Dist: requests
19
+ Requires-Dist: scikit-rf
20
+ Requires-Dist: matplotlib
21
+ Requires-Dist: numpy
22
+ Requires-Dist: gdspy
23
+ Requires-Dist: meshio
24
+ Requires-Dist: pyvista
25
+ Requires-Dist: pyvistaqt
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # Python GUI for gds2palace
31
+
32
+ ![Intro](https://raw.githubusercontent.com/VolkerMuehlhaus/setupEM/main/doc/png/setupEM_banner.png)
33
+
34
+ ## Install
35
+
36
+ pip install setupEM
37
+
38
+ **Full documentation, installation guide, and usage walkthrough:**
39
+ https://github.com/VolkerMuehlhaus/setupEM
40
+
41
+ ## Recent changes
42
+
43
+ # What's New - November 16, 2026 (setupEM 0.18.4)
44
+
45
+ **File > Save (Ctrl+S) saves the settings file you opened.** Opened from a `.simcfg` (e.g. the KLayout plug-in's export, with Open in setupEM), Ctrl+S did nothing: the action existed only for a script edited in place, and changes such as a port wall extension were lost without a question when setupEM was closed. Now:
46
+ - Ctrl+S saves into the `.simcfg` / `.tsimcfg` the model was opened from (the menu names it). Its other entries, e.g. the plug-in's link to the model script, are kept. A script edited in place and a piece of a split region are saved as before; a new model asks for a file name.
47
+ - Closing setupEM, opening another file or File > New asks "Save the changes to ...?" when the settings changed since the file was opened or saved.
48
+
49
+ # What's New - November 15, 2026 (setupEM 0.18.3)
50
+
51
+ Needs gds2palace 0.10.7 or newer (`pip install` updates it).
52
+
53
+ **`combine_extend_snp.py` 1.5** (`combine_snp`, in `scripts/`), the same file as in gds2palace 0.10.7:
54
+ - 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.
55
+ - 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.
56
+
57
+ **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.
58
+
59
+ **Citation:** `CITATION.cff` and a "How to cite" section in the README; GitHub's **Cite this repository** button gives APA and BibTeX entries.
60
+
61
+ **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.
62
+
63
+ # What's New - November 13, 2026 (setupEM 0.18.2)
64
+
65
+ **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.
66
+
67
+ **Command line fixes** (from issue #52):
68
+ - 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.
69
+ - `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.
70
+
71
+ **Scripts used on two machines** (e.g. Windows and Linux):
72
+ - 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.
73
+ - 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.
74
+
75
+ Full history: [CHANGES.md](https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc/CHANGES.md)
76
+
77
+ ---
78
+
79
+ **Note:** the `setupEM` PyPI package itself requires:
80
+
81
+ - gds2palace>=0.10.7
82
+ - gds_prepare_for_EM>=1.6.0
83
+ - PySide6
84
+ - shiboken6
85
+ - scipy
86
+ - requests
87
+ - scikit-rf
88
+ - matplotlib
89
+ - numpy
90
+ - gdspy
91
+ - meshio
92
+ - pyvista
93
+ - pyvistaqt
94
+
95
+ (Other Python modules mentioned above are only needed to run standalone helper scripts in this repository, not to use the installed package.)
@@ -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,66 @@
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 16, 2026 (setupEM 0.18.4)
15
+
16
+ **File > Save (Ctrl+S) saves the settings file you opened.** Opened from a `.simcfg` (e.g. the KLayout plug-in's export, with Open in setupEM), Ctrl+S did nothing: the action existed only for a script edited in place, and changes such as a port wall extension were lost without a question when setupEM was closed. Now:
17
+ - Ctrl+S saves into the `.simcfg` / `.tsimcfg` the model was opened from (the menu names it). Its other entries, e.g. the plug-in's link to the model script, are kept. A script edited in place and a piece of a split region are saved as before; a new model asks for a file name.
18
+ - Closing setupEM, opening another file or File > New asks "Save the changes to ...?" when the settings changed since the file was opened or saved.
19
+
20
+ # What's New - November 15, 2026 (setupEM 0.18.3)
21
+
22
+ Needs gds2palace 0.10.7 or newer (`pip install` updates it).
23
+
24
+ **`combine_extend_snp.py` 1.5** (`combine_snp`, in `scripts/`), the same file as in gds2palace 0.10.7:
25
+ - 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.
26
+ - 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.
27
+
28
+ **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.
29
+
30
+ **Citation:** `CITATION.cff` and a "How to cite" section in the README; GitHub's **Cite this repository** button gives APA and BibTeX entries.
31
+
32
+ **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.
33
+
34
+ # What's New - November 13, 2026 (setupEM 0.18.2)
35
+
36
+ **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.
37
+
38
+ **Command line fixes** (from issue #52):
39
+ - 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.
40
+ - `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.
41
+
42
+ **Scripts used on two machines** (e.g. Windows and Linux):
43
+ - 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.
44
+ - 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.
45
+
46
+ Full history: [CHANGES.md](https://github.com/VolkerMuehlhaus/setupEM/blob/main/doc/CHANGES.md)
47
+
48
+ ---
49
+
50
+ **Note:** the `setupEM` PyPI package itself requires:
51
+
52
+ - gds2palace>=0.10.7
53
+ - gds_prepare_for_EM>=1.6.0
54
+ - PySide6
55
+ - shiboken6
56
+ - scipy
57
+ - requests
58
+ - scikit-rf
59
+ - matplotlib
60
+ - numpy
61
+ - gdspy
62
+ - meshio
63
+ - pyvista
64
+ - pyvistaqt
65
+
66
+ (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.4"
@@ -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)