mpiemses3d-tools 4.7.0__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.
- mpiemses3d_tools-4.7.0/LICENSE +21 -0
- mpiemses3d_tools-4.7.0/PKG-INFO +45 -0
- mpiemses3d_tools-4.7.0/README.md +26 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/__init__.py +0 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/_fmt.py +37 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/_inp_parser.py +292 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/_serialize.py +237 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/cli/__init__.py +0 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/cli/copy_emses.py +70 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/cli/emses_unit.py +253 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/cli/toml_upgrade.py +99 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/inp2toml.py +720 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/plasma_toml.py +994 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools/unit_system.py +325 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/PKG-INFO +45 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/SOURCES.txt +20 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/dependency_links.txt +1 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/entry_points.txt +7 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/requires.txt +2 -0
- mpiemses3d_tools-4.7.0/mpiemses3d_tools.egg-info/top_level.txt +1 -0
- mpiemses3d_tools-4.7.0/pyproject.toml +35 -0
- mpiemses3d_tools-4.7.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CS12-Laboratory
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mpiemses3d-tools
|
|
3
|
+
Version: 4.7.0
|
|
4
|
+
Summary: CLI utilities for MPIEMSES3D plasma simulations
|
|
5
|
+
Author: Jin Nakazono
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/CS12-Laboratory/MPIEMSES3D
|
|
8
|
+
Keywords: plasma,PIC,EMSES,simulation,tools
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: scipy
|
|
17
|
+
Requires-Dist: typer>=0.9
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# mpiemses3d-tools
|
|
21
|
+
|
|
22
|
+
CLI utilities for [MPIEMSES3D](https://github.com/Nkzono99/mpiemses3d) plasma simulations.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install mpiemses3d-tools
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Commands
|
|
31
|
+
|
|
32
|
+
| Command | Description |
|
|
33
|
+
|---------|-------------|
|
|
34
|
+
| `inp2toml` | Convert Fortran namelist (`plasma.inp`) to TOML format |
|
|
35
|
+
| `emu` / `emses-unit` | Unit conversion and TOML inspection |
|
|
36
|
+
| `toml-upgrade` | Upgrade `plasma.toml` from format v1 to v2 |
|
|
37
|
+
| `emses-cp` / `cpem` | Copy the mpiemses3D binary to a target directory |
|
|
38
|
+
|
|
39
|
+
## Python API
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from mpiemses3d_tools.plasma_toml import PlasmaToml
|
|
43
|
+
from mpiemses3d_tools.unit_system import UnitSystem
|
|
44
|
+
from mpiemses3d_tools.inp2toml import inp2toml
|
|
45
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# mpiemses3d-tools
|
|
2
|
+
|
|
3
|
+
CLI utilities for [MPIEMSES3D](https://github.com/Nkzono99/mpiemses3d) plasma simulations.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install mpiemses3d-tools
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Commands
|
|
12
|
+
|
|
13
|
+
| Command | Description |
|
|
14
|
+
|---------|-------------|
|
|
15
|
+
| `inp2toml` | Convert Fortran namelist (`plasma.inp`) to TOML format |
|
|
16
|
+
| `emu` / `emses-unit` | Unit conversion and TOML inspection |
|
|
17
|
+
| `toml-upgrade` | Upgrade `plasma.toml` from format v1 to v2 |
|
|
18
|
+
| `emses-cp` / `cpem` | Copy the mpiemses3D binary to a target directory |
|
|
19
|
+
|
|
20
|
+
## Python API
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from mpiemses3d_tools.plasma_toml import PlasmaToml
|
|
24
|
+
from mpiemses3d_tools.unit_system import UnitSystem
|
|
25
|
+
from mpiemses3d_tools.inp2toml import inp2toml
|
|
26
|
+
```
|
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Shared TOML formatting utilities for plasma.toml serialization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def fmt(value) -> str:
|
|
7
|
+
"""Format a Python value as a TOML literal."""
|
|
8
|
+
if isinstance(value, bool):
|
|
9
|
+
return "true" if value else "false"
|
|
10
|
+
if isinstance(value, int):
|
|
11
|
+
return str(value)
|
|
12
|
+
if isinstance(value, float):
|
|
13
|
+
r = repr(value)
|
|
14
|
+
if "." not in r and "e" not in r.lower():
|
|
15
|
+
r += ".0"
|
|
16
|
+
return r
|
|
17
|
+
if isinstance(value, str):
|
|
18
|
+
return f'"{value}"'
|
|
19
|
+
if isinstance(value, list):
|
|
20
|
+
if value and isinstance(value[0], list):
|
|
21
|
+
inner = ", ".join(
|
|
22
|
+
"[" + ", ".join(fmt(v) for v in row) + "]" for row in value
|
|
23
|
+
)
|
|
24
|
+
return f"[{inner}]"
|
|
25
|
+
return "[" + ", ".join(fmt(v) for v in value) + "]"
|
|
26
|
+
return str(value)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def emit_kv(parts: list[str], params: dict, header: str | None = None):
|
|
30
|
+
"""Emit [header] + key = value lines to *parts*."""
|
|
31
|
+
if not params:
|
|
32
|
+
return
|
|
33
|
+
if header:
|
|
34
|
+
parts.append(header)
|
|
35
|
+
for k, v in params.items():
|
|
36
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
37
|
+
parts.append("")
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Fortran namelist parser for plasma.inp files.
|
|
2
|
+
|
|
3
|
+
Parses ``!!key`` headers, ``&group … /`` namelist blocks,
|
|
4
|
+
array slice syntax, 2D indexing, and Fortran literals.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections import OrderedDict
|
|
11
|
+
|
|
12
|
+
# ── LHS patterns (checked in order) ──────────────────────────────
|
|
13
|
+
_RE_2D = re.compile(r"(\w+)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)")
|
|
14
|
+
_RE_2D_COL_SLICE = re.compile(r"(\w+)\s*\(\s*(\d+)\s*,\s*(\d+)\s*:\s*(\d+)\s*\)")
|
|
15
|
+
_RE_2D_ROW_SLICE = re.compile(r"(\w+)\s*\(\s*(\d+)\s*:\s*(\d+)\s*,\s*(\d+)\s*\)")
|
|
16
|
+
_RE_2D_FULL_ROW = re.compile(r"(\w+)\s*\(\s*:\s*,\s*(\d+)\s*\)") # var(:, col)
|
|
17
|
+
_RE_2D_FULL_COL = re.compile(r"(\w+)\s*\(\s*(\d+)\s*,\s*:\s*\)") # var(row, :)
|
|
18
|
+
_RE_SLICE = re.compile(r"(\w+)\s*\(\s*(\d+)\s*:\s*(\d+)\s*\)")
|
|
19
|
+
_RE_SINGLE = re.compile(r"(\w+)\s*\(\s*(\d+)\s*\)")
|
|
20
|
+
_RE_PLAIN = re.compile(r"(\w+)")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _remove_inline_comment(line: str) -> str:
|
|
24
|
+
"""Strip trailing ``!`` comment while preserving quoted strings."""
|
|
25
|
+
in_str = False
|
|
26
|
+
qchar = ""
|
|
27
|
+
for i, ch in enumerate(line):
|
|
28
|
+
if in_str:
|
|
29
|
+
if ch == qchar:
|
|
30
|
+
in_str = False
|
|
31
|
+
else:
|
|
32
|
+
if ch in ('"', "'"):
|
|
33
|
+
in_str = True
|
|
34
|
+
qchar = ch
|
|
35
|
+
elif ch == "!":
|
|
36
|
+
return line[:i].rstrip()
|
|
37
|
+
return line.rstrip()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _parse_scalar(s: str):
|
|
41
|
+
"""Parse a single Fortran literal into a Python value."""
|
|
42
|
+
s = s.strip().rstrip(",")
|
|
43
|
+
if not s:
|
|
44
|
+
return None
|
|
45
|
+
low = s.lower()
|
|
46
|
+
if low in (".true.", "true"):
|
|
47
|
+
return True
|
|
48
|
+
if low in (".false.", "false"):
|
|
49
|
+
return False
|
|
50
|
+
if (s.startswith('"') and s.endswith('"')) or (
|
|
51
|
+
s.startswith("'") and s.endswith("'")
|
|
52
|
+
):
|
|
53
|
+
return s[1:-1]
|
|
54
|
+
# Fortran double-precision exponent d/D -> e
|
|
55
|
+
s_num = re.sub(r"[dD]", "e", s)
|
|
56
|
+
try:
|
|
57
|
+
if "." in s_num or "e" in s_num.lower():
|
|
58
|
+
return float(s_num)
|
|
59
|
+
return int(s_num)
|
|
60
|
+
except ValueError:
|
|
61
|
+
return s
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _split_values(text: str) -> list:
|
|
65
|
+
"""Split comma-separated Fortran values respecting quoted strings."""
|
|
66
|
+
values: list = []
|
|
67
|
+
current = ""
|
|
68
|
+
in_str = False
|
|
69
|
+
qchar = ""
|
|
70
|
+
for ch in text:
|
|
71
|
+
if in_str:
|
|
72
|
+
current += ch
|
|
73
|
+
if ch == qchar:
|
|
74
|
+
in_str = False
|
|
75
|
+
elif ch in ('"', "'"):
|
|
76
|
+
in_str = True
|
|
77
|
+
qchar = ch
|
|
78
|
+
current += ch
|
|
79
|
+
elif ch == ",":
|
|
80
|
+
if current.strip():
|
|
81
|
+
values.append(_parse_scalar(current))
|
|
82
|
+
current = ""
|
|
83
|
+
else:
|
|
84
|
+
current += ch
|
|
85
|
+
if current.strip():
|
|
86
|
+
values.append(_parse_scalar(current))
|
|
87
|
+
return [v for v in values if v is not None]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _parse_key_header(line: str) -> dict | None:
|
|
91
|
+
"""``!!key dx=[0.5],to_c=[10000.0]`` -> ``{'dx': 0.5, 'to_c': 10000.0}``."""
|
|
92
|
+
m = re.match(r"^!!key\s+(.*)", line.strip())
|
|
93
|
+
if not m:
|
|
94
|
+
return None
|
|
95
|
+
result: dict = {}
|
|
96
|
+
for kv in re.finditer(r"(\w+)\s*=\s*\[([^\]]*)\]", m.group(1)):
|
|
97
|
+
result[kv.group(1)] = _parse_scalar(kv.group(2))
|
|
98
|
+
return result
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _parse_group_lines(lines: list[str]) -> OrderedDict:
|
|
102
|
+
"""Parse raw lines inside ``&group ... /`` into an ordered parameter dict."""
|
|
103
|
+
|
|
104
|
+
# 1) Collect logical assignment strings (join continuation lines)
|
|
105
|
+
assignments: list[str] = []
|
|
106
|
+
current: str | None = None
|
|
107
|
+
for line in lines:
|
|
108
|
+
stripped = line.strip()
|
|
109
|
+
if not stripped or stripped.startswith("!"):
|
|
110
|
+
continue
|
|
111
|
+
stripped = _remove_inline_comment(stripped)
|
|
112
|
+
if not stripped:
|
|
113
|
+
continue
|
|
114
|
+
if re.match(r"\w+\s*(\(|=)", stripped):
|
|
115
|
+
if current is not None:
|
|
116
|
+
assignments.append(current)
|
|
117
|
+
current = stripped
|
|
118
|
+
elif current is not None:
|
|
119
|
+
current += " " + stripped
|
|
120
|
+
if current is not None:
|
|
121
|
+
assignments.append(current)
|
|
122
|
+
|
|
123
|
+
# 2) Interpret each assignment
|
|
124
|
+
storage: OrderedDict = OrderedDict()
|
|
125
|
+
|
|
126
|
+
for text in assignments:
|
|
127
|
+
eq_pos = text.index("=")
|
|
128
|
+
lhs = text[:eq_pos].strip()
|
|
129
|
+
rhs = text[eq_pos + 1 :].strip()
|
|
130
|
+
values = _split_values(rhs)
|
|
131
|
+
if not values:
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
m2d_cs = _RE_2D_COL_SLICE.match(lhs)
|
|
135
|
+
m2d_rs = _RE_2D_ROW_SLICE.match(lhs)
|
|
136
|
+
m2d_fr = _RE_2D_FULL_ROW.match(lhs)
|
|
137
|
+
m2d_fc = _RE_2D_FULL_COL.match(lhs)
|
|
138
|
+
m2d = _RE_2D.match(lhs)
|
|
139
|
+
mslice = _RE_SLICE.match(lhs)
|
|
140
|
+
msingle = _RE_SINGLE.match(lhs)
|
|
141
|
+
|
|
142
|
+
if m2d_cs:
|
|
143
|
+
var = m2d_cs.group(1)
|
|
144
|
+
ri = int(m2d_cs.group(2))
|
|
145
|
+
cs, _ce = int(m2d_cs.group(3)), int(m2d_cs.group(4))
|
|
146
|
+
entry = storage.setdefault(var, {"kind": "matrix", "data": {}})
|
|
147
|
+
if entry["kind"] != "matrix":
|
|
148
|
+
entry["kind"] = "matrix"
|
|
149
|
+
entry["data"] = {}
|
|
150
|
+
for k, v in enumerate(values):
|
|
151
|
+
entry["data"][(ri, cs + k)] = v
|
|
152
|
+
|
|
153
|
+
elif m2d_rs:
|
|
154
|
+
var = m2d_rs.group(1)
|
|
155
|
+
rs, _re = int(m2d_rs.group(2)), int(m2d_rs.group(3))
|
|
156
|
+
ci = int(m2d_rs.group(4))
|
|
157
|
+
entry = storage.setdefault(var, {"kind": "matrix", "data": {}})
|
|
158
|
+
if entry["kind"] != "matrix":
|
|
159
|
+
entry["kind"] = "matrix"
|
|
160
|
+
entry["data"] = {}
|
|
161
|
+
for k, v in enumerate(values):
|
|
162
|
+
entry["data"][(rs + k, ci)] = v
|
|
163
|
+
|
|
164
|
+
elif m2d_fr:
|
|
165
|
+
# var(:, col) — full row-slice: values fill rows 1..N at fixed column
|
|
166
|
+
var = m2d_fr.group(1)
|
|
167
|
+
ci = int(m2d_fr.group(2))
|
|
168
|
+
entry = storage.setdefault(var, {"kind": "matrix", "data": {}})
|
|
169
|
+
if entry["kind"] != "matrix":
|
|
170
|
+
entry["kind"] = "matrix"
|
|
171
|
+
entry["data"] = {}
|
|
172
|
+
for k, v in enumerate(values):
|
|
173
|
+
entry["data"][(1 + k, ci)] = v
|
|
174
|
+
|
|
175
|
+
elif m2d_fc:
|
|
176
|
+
# var(row, :) — full col-slice: values fill cols 1..N at fixed row
|
|
177
|
+
var = m2d_fc.group(1)
|
|
178
|
+
ri = int(m2d_fc.group(2))
|
|
179
|
+
entry = storage.setdefault(var, {"kind": "matrix", "data": {}})
|
|
180
|
+
if entry["kind"] != "matrix":
|
|
181
|
+
entry["kind"] = "matrix"
|
|
182
|
+
entry["data"] = {}
|
|
183
|
+
for k, v in enumerate(values):
|
|
184
|
+
entry["data"][(ri, 1 + k)] = v
|
|
185
|
+
|
|
186
|
+
elif m2d:
|
|
187
|
+
var = m2d.group(1)
|
|
188
|
+
ri, ci = int(m2d.group(2)), int(m2d.group(3))
|
|
189
|
+
entry = storage.setdefault(var, {"kind": "matrix", "data": {}})
|
|
190
|
+
if entry["kind"] != "matrix":
|
|
191
|
+
entry["kind"] = "matrix"
|
|
192
|
+
entry["data"] = {}
|
|
193
|
+
for k, v in enumerate(values):
|
|
194
|
+
entry["data"][(ri + k, ci)] = v
|
|
195
|
+
|
|
196
|
+
elif mslice:
|
|
197
|
+
var = mslice.group(1)
|
|
198
|
+
start, _end = int(mslice.group(2)), int(mslice.group(3))
|
|
199
|
+
entry = storage.setdefault(var, {"kind": "array", "data": {}})
|
|
200
|
+
if entry["kind"] == "scalar":
|
|
201
|
+
entry.update(kind="array", data={})
|
|
202
|
+
if entry["kind"] == "flat":
|
|
203
|
+
entry.update(
|
|
204
|
+
kind="array", data={i + 1: v for i, v in enumerate(entry["data"])}
|
|
205
|
+
)
|
|
206
|
+
for k, v in enumerate(values):
|
|
207
|
+
entry["data"][start + k] = v
|
|
208
|
+
|
|
209
|
+
elif msingle:
|
|
210
|
+
var = msingle.group(1)
|
|
211
|
+
idx = int(msingle.group(2))
|
|
212
|
+
entry = storage.setdefault(var, {"kind": "array", "data": {}})
|
|
213
|
+
if entry["kind"] == "scalar":
|
|
214
|
+
entry.update(kind="array", data={})
|
|
215
|
+
if entry["kind"] == "flat":
|
|
216
|
+
entry.update(
|
|
217
|
+
kind="array", data={i + 1: v for i, v in enumerate(entry["data"])}
|
|
218
|
+
)
|
|
219
|
+
for k, v in enumerate(values):
|
|
220
|
+
entry["data"][idx + k] = v
|
|
221
|
+
|
|
222
|
+
else:
|
|
223
|
+
var = _RE_PLAIN.match(lhs).group(1) # type: ignore[union-attr]
|
|
224
|
+
if len(values) == 1:
|
|
225
|
+
if var in storage and storage[var]["kind"] == "array":
|
|
226
|
+
d = storage[var]["data"]
|
|
227
|
+
d[max(d) + 1] = values[0]
|
|
228
|
+
else:
|
|
229
|
+
storage[var] = {"kind": "scalar", "data": values[0]}
|
|
230
|
+
else:
|
|
231
|
+
storage[var] = {"kind": "flat", "data": values}
|
|
232
|
+
|
|
233
|
+
# 3) Finalize into plain Python values
|
|
234
|
+
result: OrderedDict = OrderedDict()
|
|
235
|
+
for var, entry in storage.items():
|
|
236
|
+
kind = entry["kind"]
|
|
237
|
+
data = entry["data"]
|
|
238
|
+
|
|
239
|
+
if kind == "scalar":
|
|
240
|
+
result[var] = data
|
|
241
|
+
elif kind == "flat":
|
|
242
|
+
result[var] = list(data)
|
|
243
|
+
elif kind == "array":
|
|
244
|
+
hi = max(data)
|
|
245
|
+
result[var] = [data.get(i, 0) for i in range(1, hi + 1)]
|
|
246
|
+
elif kind == "matrix":
|
|
247
|
+
rhi = max(k[0] for k in data)
|
|
248
|
+
chi = max(k[1] for k in data)
|
|
249
|
+
result[var] = [
|
|
250
|
+
[data.get((r, c), 0) for c in range(1, chi + 1)]
|
|
251
|
+
for r in range(1, rhi + 1)
|
|
252
|
+
]
|
|
253
|
+
|
|
254
|
+
return result
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def parse_inp(text: str) -> tuple[dict | None, list[tuple[str, OrderedDict]]]:
|
|
258
|
+
"""Parse full ``plasma.inp`` text.
|
|
259
|
+
|
|
260
|
+
Returns ``(meta, [(group_name, params), ...])``.
|
|
261
|
+
"""
|
|
262
|
+
lines = text.splitlines()
|
|
263
|
+
|
|
264
|
+
# !!key header
|
|
265
|
+
meta = None
|
|
266
|
+
for line in lines:
|
|
267
|
+
s = line.strip()
|
|
268
|
+
if s.startswith("!!key"):
|
|
269
|
+
meta = _parse_key_header(s)
|
|
270
|
+
break
|
|
271
|
+
if s and not s.startswith("!"):
|
|
272
|
+
break
|
|
273
|
+
|
|
274
|
+
# Namelist groups
|
|
275
|
+
groups: list[tuple[str, OrderedDict]] = []
|
|
276
|
+
i = 0
|
|
277
|
+
while i < len(lines):
|
|
278
|
+
s = lines[i].strip()
|
|
279
|
+
m = re.match(r"&(\w+)", s)
|
|
280
|
+
if m:
|
|
281
|
+
gname = m.group(1)
|
|
282
|
+
glines: list[str] = []
|
|
283
|
+
i += 1
|
|
284
|
+
while i < len(lines):
|
|
285
|
+
if lines[i].strip() == "/":
|
|
286
|
+
break
|
|
287
|
+
glines.append(lines[i])
|
|
288
|
+
i += 1
|
|
289
|
+
groups.append((gname, _parse_group_lines(glines)))
|
|
290
|
+
i += 1
|
|
291
|
+
|
|
292
|
+
return meta, groups
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""TOML format_version 2 serialization for plasma.toml."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import OrderedDict
|
|
6
|
+
|
|
7
|
+
from ._fmt import emit_kv, fmt
|
|
8
|
+
|
|
9
|
+
# Canonical output order for top-level groups.
|
|
10
|
+
GROUP_ORDER = [
|
|
11
|
+
"meta",
|
|
12
|
+
"memo",
|
|
13
|
+
"real",
|
|
14
|
+
"realcv",
|
|
15
|
+
"species",
|
|
16
|
+
"esorem",
|
|
17
|
+
"jobcon",
|
|
18
|
+
"digcon",
|
|
19
|
+
"plasma",
|
|
20
|
+
"tmgrid",
|
|
21
|
+
"system",
|
|
22
|
+
"intp",
|
|
23
|
+
"others",
|
|
24
|
+
"inp",
|
|
25
|
+
"ptcond",
|
|
26
|
+
"wave",
|
|
27
|
+
"scrnt",
|
|
28
|
+
"emissn",
|
|
29
|
+
"dipole",
|
|
30
|
+
"testch",
|
|
31
|
+
"jsrc",
|
|
32
|
+
"mpi",
|
|
33
|
+
"verbose",
|
|
34
|
+
"gradema",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# AOT sub-keys inside their parent groups.
|
|
38
|
+
AOT_KEYS: dict[str, list[str]] = {
|
|
39
|
+
"ptcond": ["objects", "boundaries"],
|
|
40
|
+
"emissn": ["planes"],
|
|
41
|
+
"dipole": ["sources"],
|
|
42
|
+
"testch": ["charges"],
|
|
43
|
+
"jsrc": ["sources"],
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def serialize_v2(data: dict, schema: str | None = None) -> str:
|
|
48
|
+
"""Serialize a plasma.toml dict to format_version 2 TOML string."""
|
|
49
|
+
parts: list[str] = []
|
|
50
|
+
|
|
51
|
+
if schema:
|
|
52
|
+
parts.append(f"#:schema {schema}")
|
|
53
|
+
parts.append("")
|
|
54
|
+
|
|
55
|
+
emitted: set[str] = set()
|
|
56
|
+
|
|
57
|
+
for group in GROUP_ORDER:
|
|
58
|
+
if group not in data:
|
|
59
|
+
continue
|
|
60
|
+
emitted.add(group)
|
|
61
|
+
|
|
62
|
+
if group == "meta":
|
|
63
|
+
_emit_meta(parts, data["meta"])
|
|
64
|
+
elif group == "species":
|
|
65
|
+
_emit_species(parts, data["species"])
|
|
66
|
+
elif group in AOT_KEYS:
|
|
67
|
+
_emit_group_with_aot(parts, group, data[group])
|
|
68
|
+
else:
|
|
69
|
+
emit_kv(parts, data[group], f"[{group}]")
|
|
70
|
+
|
|
71
|
+
# Any remaining groups not in the canonical order
|
|
72
|
+
for group in data:
|
|
73
|
+
if group not in emitted:
|
|
74
|
+
val = data[group]
|
|
75
|
+
if isinstance(val, dict):
|
|
76
|
+
emit_kv(parts, val, f"[{group}]")
|
|
77
|
+
|
|
78
|
+
return "\n".join(parts)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _emit_meta(parts: list[str], meta: dict) -> None:
|
|
82
|
+
"""Emit [meta], [meta.unit_conversion], and [meta.physical]."""
|
|
83
|
+
_META_SUB = {"unit_conversion", "physical"}
|
|
84
|
+
parts.append("[meta]")
|
|
85
|
+
for k, v in meta.items():
|
|
86
|
+
if k in _META_SUB:
|
|
87
|
+
continue
|
|
88
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
89
|
+
parts.append("")
|
|
90
|
+
|
|
91
|
+
uc = meta.get("unit_conversion")
|
|
92
|
+
if uc:
|
|
93
|
+
parts.append("[meta.unit_conversion]")
|
|
94
|
+
for k, v in uc.items():
|
|
95
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
96
|
+
parts.append("")
|
|
97
|
+
|
|
98
|
+
phys = meta.get("physical")
|
|
99
|
+
if phys:
|
|
100
|
+
_PHYS_AOT = {"species", "conductors"}
|
|
101
|
+
parts.append("[meta.physical]")
|
|
102
|
+
for k, v in phys.items():
|
|
103
|
+
if k in _PHYS_AOT:
|
|
104
|
+
continue
|
|
105
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
106
|
+
parts.append("")
|
|
107
|
+
for sp in phys.get("species", []):
|
|
108
|
+
parts.append("[[meta.physical.species]]")
|
|
109
|
+
for k, v in sp.items():
|
|
110
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
111
|
+
parts.append("")
|
|
112
|
+
for cond in phys.get("conductors", []):
|
|
113
|
+
parts.append("[[meta.physical.conductors]]")
|
|
114
|
+
for k, v in cond.items():
|
|
115
|
+
parts.append(f"{k} = {fmt(v)}")
|
|
116
|
+
parts.append("")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# Canonical key order for [[species]] — groups related parameters together.
|
|
120
|
+
_SPECIES_KEY_ORDER = [
|
|
121
|
+
# Core physics
|
|
122
|
+
"wp",
|
|
123
|
+
"qm",
|
|
124
|
+
# Thermal velocity
|
|
125
|
+
"path",
|
|
126
|
+
"peth",
|
|
127
|
+
# Drift
|
|
128
|
+
"vdri",
|
|
129
|
+
"vdthz",
|
|
130
|
+
"vdthxy",
|
|
131
|
+
"vdx",
|
|
132
|
+
"vdy",
|
|
133
|
+
"vdz",
|
|
134
|
+
# Distribution
|
|
135
|
+
"spa",
|
|
136
|
+
"spe",
|
|
137
|
+
"speth",
|
|
138
|
+
"f",
|
|
139
|
+
# Particles
|
|
140
|
+
"npin",
|
|
141
|
+
"np",
|
|
142
|
+
"dnsf",
|
|
143
|
+
# Boundary
|
|
144
|
+
"npbnd",
|
|
145
|
+
# Injection
|
|
146
|
+
"inpf",
|
|
147
|
+
"inpb",
|
|
148
|
+
"injct",
|
|
149
|
+
"npr",
|
|
150
|
+
# Emission
|
|
151
|
+
"nflag_emit",
|
|
152
|
+
"curf",
|
|
153
|
+
"curb",
|
|
154
|
+
"nepl",
|
|
155
|
+
"emission_leave_anti_particle",
|
|
156
|
+
"emission_time_mode",
|
|
157
|
+
"emission_start_step",
|
|
158
|
+
"emission_end_step",
|
|
159
|
+
"emission_time_sigma",
|
|
160
|
+
"ray_zenith_angle_deg",
|
|
161
|
+
"ray_azimuth_angle_deg",
|
|
162
|
+
# Flux / charge
|
|
163
|
+
"flpf",
|
|
164
|
+
"flpb",
|
|
165
|
+
"qp",
|
|
166
|
+
"qpr",
|
|
167
|
+
"abvdem",
|
|
168
|
+
"dnsb",
|
|
169
|
+
# Diagnostics
|
|
170
|
+
"ipahdf",
|
|
171
|
+
"ipadig",
|
|
172
|
+
"ipaxyz",
|
|
173
|
+
"ildig",
|
|
174
|
+
"imdig",
|
|
175
|
+
"isort",
|
|
176
|
+
"irhsp",
|
|
177
|
+
# Velocity range
|
|
178
|
+
"vpa",
|
|
179
|
+
"vpb",
|
|
180
|
+
"vpe",
|
|
181
|
+
# Other
|
|
182
|
+
"mfpath",
|
|
183
|
+
"pemax",
|
|
184
|
+
"deltaemax",
|
|
185
|
+
"denmod",
|
|
186
|
+
"denk",
|
|
187
|
+
"omegalw",
|
|
188
|
+
"lcgamma",
|
|
189
|
+
"lcbeta",
|
|
190
|
+
"nphi",
|
|
191
|
+
"ndst",
|
|
192
|
+
"ioptd",
|
|
193
|
+
]
|
|
194
|
+
_SPECIES_KEY_SET = set(_SPECIES_KEY_ORDER)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _sorted_species_keys(sp: dict) -> list[str]:
|
|
198
|
+
"""Return species keys in canonical order, unknown keys appended at end."""
|
|
199
|
+
ordered = [k for k in _SPECIES_KEY_ORDER if k in sp]
|
|
200
|
+
ordered.extend(k for k in sp if k not in _SPECIES_KEY_SET)
|
|
201
|
+
return ordered
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _emit_species(parts: list[str], species_list: list[dict]) -> None:
|
|
205
|
+
"""Emit [[species]] entries."""
|
|
206
|
+
for sp in species_list:
|
|
207
|
+
parts.append("[[species]]")
|
|
208
|
+
for k in _sorted_species_keys(sp):
|
|
209
|
+
parts.append(f"{k} = {fmt(sp[k])}")
|
|
210
|
+
parts.append("")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _emit_group_with_aot(parts: list[str], group: str, data: dict) -> None:
|
|
214
|
+
"""Emit a group that may contain array-of-tables sub-keys."""
|
|
215
|
+
aot_keys = AOT_KEYS.get(group, [])
|
|
216
|
+
# Emit non-AOT keys first
|
|
217
|
+
simple = OrderedDict()
|
|
218
|
+
for k, v in data.items():
|
|
219
|
+
if k in aot_keys:
|
|
220
|
+
continue
|
|
221
|
+
if isinstance(v, dict):
|
|
222
|
+
# Nested table (e.g. ptcond.conductor_groups.group_1)
|
|
223
|
+
for subk, subv in v.items():
|
|
224
|
+
if isinstance(subv, dict):
|
|
225
|
+
emit_kv(parts, subv, f"[{group}.{k}.{subk}]")
|
|
226
|
+
else:
|
|
227
|
+
simple[f"{k}.{subk}"] = subv
|
|
228
|
+
else:
|
|
229
|
+
simple[k] = v
|
|
230
|
+
if simple:
|
|
231
|
+
emit_kv(parts, simple, f"[{group}]")
|
|
232
|
+
# Emit AOTs
|
|
233
|
+
for aot_key in aot_keys:
|
|
234
|
+
entries = data.get(aot_key, [])
|
|
235
|
+
if isinstance(entries, list):
|
|
236
|
+
for entry in entries:
|
|
237
|
+
emit_kv(parts, entry, f"[[{group}.{aot_key}]]")
|
|
File without changes
|