jcmsuite 7.4.2__py3-none-any.whl
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.
Potentially problematic release.
This version of jcmsuite might be problematic. Click here for more details.
- jcmsuite/__init__.py +22 -0
- jcmsuite/_build_info.py +4 -0
- jcmsuite/context/__init__.py +44 -0
- jcmsuite/context/interface_metadata.py +158 -0
- jcmsuite/context/models.py +213 -0
- jcmsuite/context/scope.py +210 -0
- jcmsuite/context/solver_context.py +569 -0
- jcmsuite/context/subprocess_tools.py +172 -0
- jcmsuite/contract.py +47 -0
- jcmsuite/daemon/__init__.py +19 -0
- jcmsuite/daemon/handler.py +925 -0
- jcmsuite/daemon/internal/__init__.py +4 -0
- jcmsuite/daemon/internal/bundle_protocol.py +64 -0
- jcmsuite/daemon/internal/handler_helpers.py +368 -0
- jcmsuite/daemon/internal/handler_resource_jobs.py +227 -0
- jcmsuite/daemon/internal/handler_wait.py +564 -0
- jcmsuite/daemon/models.py +349 -0
- jcmsuite/daemon/namespaces.py +250 -0
- jcmsuite/daemon/protocol.py +801 -0
- jcmsuite/daemon/resources.py +407 -0
- jcmsuite/daemon/scope.py +53 -0
- jcmsuite/daemon/transport.py +223 -0
- jcmsuite/editing/__init__.py +10 -0
- jcmsuite/editing/editor.py +274 -0
- jcmsuite/exceptions/__init__.py +32 -0
- jcmsuite/exceptions/errors.py +173 -0
- jcmsuite/geo/__init__.py +10 -0
- jcmsuite/geo/mesh.py +302 -0
- jcmsuite/info/__init__.py +10 -0
- jcmsuite/info/runtime_info.py +45 -0
- jcmsuite/internal/__init__.py +2 -0
- jcmsuite/internal/diagnostics.py +74 -0
- jcmsuite/internal/progress.py +80 -0
- jcmsuite/loaders/__init__.py +18 -0
- jcmsuite/loaders/blob_header.py +315 -0
- jcmsuite/loaders/cartesian_field_reader.py +249 -0
- jcmsuite/loaders/cartesian_fields.py +324 -0
- jcmsuite/loaders/nested_mapping.py +69 -0
- jcmsuite/loaders/powerflux.py +136 -0
- jcmsuite/loaders/table.py +637 -0
- jcmsuite/logging/__init__.py +22 -0
- jcmsuite/logging/runtime.py +210 -0
- jcmsuite/results/__init__.py +126 -0
- jcmsuite/results/artifacts.py +806 -0
- jcmsuite/results/discovery.py +82 -0
- jcmsuite/results/field_exports.py +1062 -0
- jcmsuite/results/field_payloads.py +453 -0
- jcmsuite/results/internal/__init__.py +4 -0
- jcmsuite/results/internal/export/__init__.py +4 -0
- jcmsuite/results/internal/export/common.py +56 -0
- jcmsuite/results/internal/export/pandas/__init__.py +4 -0
- jcmsuite/results/internal/export/pandas/common.py +165 -0
- jcmsuite/results/internal/export/pandas/payload.py +480 -0
- jcmsuite/results/internal/export/pandas/rows.py +484 -0
- jcmsuite/results/internal/export/preview.py +178 -0
- jcmsuite/results/internal/export/xarray/__init__.py +4 -0
- jcmsuite/results/internal/export/xarray/export.py +688 -0
- jcmsuite/results/internal/export/xarray/grouped.py +608 -0
- jcmsuite/results/internal/export/xarray/headers.py +290 -0
- jcmsuite/results/internal/export/xarray/runtime.py +99 -0
- jcmsuite/results/internal/export/xarray/shared.py +246 -0
- jcmsuite/results/internal/export/xarray/tabular.py +304 -0
- jcmsuite/results/internal/export/xarray/types.py +28 -0
- jcmsuite/results/internal/models/__init__.py +4 -0
- jcmsuite/results/internal/models/batch.py +1081 -0
- jcmsuite/results/internal/models/batch_postprocess.py +1728 -0
- jcmsuite/results/internal/models/bundle.py +343 -0
- jcmsuite/results/internal/models/core.py +556 -0
- jcmsuite/results/internal/models/submission.py +1157 -0
- jcmsuite/results/internal/resultbag/__init__.py +4 -0
- jcmsuite/results/internal/resultbag/access.py +489 -0
- jcmsuite/results/internal/resultbag/iteration.py +199 -0
- jcmsuite/results/internal/resultbag/query.py +226 -0
- jcmsuite/results/internal/resultbag/raw.py +407 -0
- jcmsuite/results/internal/resultbag/source_files.py +142 -0
- jcmsuite/results/internal/resultbag/store.py +881 -0
- jcmsuite/results/internal/resultbag/utils.py +258 -0
- jcmsuite/results/models.py +76 -0
- jcmsuite/results/opening.py +55 -0
- jcmsuite/results/pandas_export.py +325 -0
- jcmsuite/results/payloads.py +478 -0
- jcmsuite/results/postprocess.py +97 -0
- jcmsuite/results/postprocess_payloads.py +757 -0
- jcmsuite/results/postprocess_record.py +418 -0
- jcmsuite/results/resultbag.py +279 -0
- jcmsuite/results/resultbag_management.py +433 -0
- jcmsuite/results/structured_derivatives.py +387 -0
- jcmsuite/solve/__init__.py +10 -0
- jcmsuite/solve/daemon_bundle_staging.py +100 -0
- jcmsuite/solve/daemon_bundle_wait.py +89 -0
- jcmsuite/solve/orchestration.py +1576 -0
- jcmsuite/solve/orchestration_execution.py +180 -0
- jcmsuite/solve/orchestration_routing.py +128 -0
- jcmsuite/solve/orchestration_support.py +323 -0
- jcmsuite/solve/path_resolution.py +98 -0
- jcmsuite/solve/progress.py +20 -0
- jcmsuite/solve/solver.py +709 -0
- jcmsuite/solve/staging.py +264 -0
- jcmsuite/solve/types.py +25 -0
- jcmsuite/solve/working_dirs.py +227 -0
- jcmsuite/templates/__init__.py +11 -0
- jcmsuite/templates/converter.py +71 -0
- jcmsuite/templates/formatting.py +335 -0
- jcmsuite/templates/formatting_cli.py +47 -0
- jcmsuite/templates/rendering.py +666 -0
- jcmsuite/torch/__init__.py +25 -0
- jcmsuite/torch/autograd.py +488 -0
- jcmsuite/torch/coordinate_policy.py +82 -0
- jcmsuite/torch/core.py +312 -0
- jcmsuite/torch/results/__init__.py +51 -0
- jcmsuite/torch/types.py +84 -0
- jcmsuite/torch/validation.py +208 -0
- jcmsuite/torch/wrappers.py +4332 -0
- jcmsuite/view/__init__.py +10 -0
- jcmsuite/view/viewer.py +122 -0
- jcmsuite-7.4.2.dist-info/METADATA +180 -0
- jcmsuite-7.4.2.dist-info/RECORD +119 -0
- jcmsuite-7.4.2.dist-info/WHEEL +4 -0
- jcmsuite-7.4.2.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2001-2026 JCMwave GmbH
|
|
3
|
+
|
|
4
|
+
"""Template rendering engine for ``.jcmt`` and ``.jcmpt`` files.
|
|
5
|
+
|
|
6
|
+
This module implements the template execution model:
|
|
7
|
+
|
|
8
|
+
1. Python script blocks are delimited by ``<? ... ?>`` (or ``<?Python ... ?>``).
|
|
9
|
+
2. Non-script text supports printf-like substitutions such as ``%(name)e``.
|
|
10
|
+
3. Source line tracking is preserved via generated ``# __LINE`` markers so
|
|
11
|
+
failures can be mapped back to template locations.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import re
|
|
18
|
+
import sys
|
|
19
|
+
from collections.abc import Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from traceback import TracebackException
|
|
23
|
+
from types import CodeType
|
|
24
|
+
from typing import Any, Final, cast
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
from numpy.typing import NDArray
|
|
28
|
+
|
|
29
|
+
from ..exceptions import TemplateMappingError
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(slots=True)
|
|
33
|
+
class _SubstitutionFailure(Exception):
|
|
34
|
+
"""Internal marker for substitution failures with precise position data."""
|
|
35
|
+
|
|
36
|
+
message: str
|
|
37
|
+
position_in_fragment: int
|
|
38
|
+
line: int | None = None
|
|
39
|
+
column: int | None = None
|
|
40
|
+
|
|
41
|
+
def __str__(self) -> str:
|
|
42
|
+
|
|
43
|
+
return self.message
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(slots=True)
|
|
47
|
+
class _GeneratedScriptError(Exception):
|
|
48
|
+
"""Internal marker for generated-script errors mapped to source lines."""
|
|
49
|
+
|
|
50
|
+
message: str
|
|
51
|
+
line: int | None = None
|
|
52
|
+
column: int | None = None
|
|
53
|
+
|
|
54
|
+
def __str__(self) -> str:
|
|
55
|
+
|
|
56
|
+
return self.message
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# Substitution pattern groups:
|
|
60
|
+
# - `([?]?)` optional "don't fail on missing key" flag (`%?`).
|
|
61
|
+
# - `\(([^)]*)\)` key path inside parentheses.
|
|
62
|
+
# - `([\d]{0,2})` optional precision width (legacy keeps this to max 2 digits).
|
|
63
|
+
# - `([sdiefg])` printf-like format code family.
|
|
64
|
+
_SUBSTITUTION_PATTERN: Final[re.Pattern[str]] = re.compile(
|
|
65
|
+
r"[%]([?]?)\(([^)]*)\)([\d]{0,2})([sdiefg])"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# Script tag matcher groups:
|
|
70
|
+
# - `(<[?](Python)?|[?]>)` matches opening or closing script delimiters.
|
|
71
|
+
# - Optional `(Python)?` preserves legacy support for `<?Python`.
|
|
72
|
+
_SCRIPT_TOKEN_PATTERN: Final[re.Pattern[str]] = re.compile(r"(<[?](Python)?|[?]>)")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Source marker matcher:
|
|
76
|
+
# - This marker is injected at generation time and later used to map
|
|
77
|
+
# generated-code failures back to original template line numbers.
|
|
78
|
+
_SOURCE_MARKER_PATTERN: Final[re.Pattern[str]] = re.compile(r"# __LINE (\d+)")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def render_template(
|
|
82
|
+
template_text: str,
|
|
83
|
+
*,
|
|
84
|
+
keys: Mapping[str, object],
|
|
85
|
+
source: str | Path,
|
|
86
|
+
) -> tuple[str, list[int]]:
|
|
87
|
+
"""Render template text into JCM output while preserving source mapping.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
template_text : str
|
|
92
|
+
Raw input template content.
|
|
93
|
+
keys : Mapping[str, object]
|
|
94
|
+
Mapping used by substitutions and script blocks.
|
|
95
|
+
source : str | Path
|
|
96
|
+
Source identifier used for diagnostic mapping.
|
|
97
|
+
|
|
98
|
+
Returns
|
|
99
|
+
-------
|
|
100
|
+
rendered_text : str
|
|
101
|
+
Final rendered JCM text.
|
|
102
|
+
rendered_line_map : list[int]
|
|
103
|
+
Mapping list from rendered lines to source template lines.
|
|
104
|
+
"""
|
|
105
|
+
source_path: Path = Path(source)
|
|
106
|
+
original_template_text: str = template_text
|
|
107
|
+
|
|
108
|
+
# Legacy behavior replaces CRLF with " <LF>" (space + newline) instead of
|
|
109
|
+
# a plain newline replacement. We keep this exact normalization to avoid
|
|
110
|
+
# subtle column-shift behavior changes in downstream diagnostics.
|
|
111
|
+
normalized_template_text: str = re.sub(r"\r\n", " \n", template_text)
|
|
112
|
+
escaped_template_text: str = _escape_comment_embedded_tags(normalized_template_text)
|
|
113
|
+
_validate_script_start_tags(
|
|
114
|
+
escaped_template_text, source_path, original_template_text
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
generated_script: str = _compile_template_to_python(escaped_template_text)
|
|
119
|
+
except _GeneratedScriptError as generated_error:
|
|
120
|
+
# Surface a single user-facing template mapping error without nested
|
|
121
|
+
# internal exception chains (`_GeneratedScriptError`, `KeyError`, ...).
|
|
122
|
+
raise _raise_template_mapping_error(
|
|
123
|
+
source=source_path,
|
|
124
|
+
template_text=original_template_text,
|
|
125
|
+
message=str(generated_error),
|
|
126
|
+
line=generated_error.line,
|
|
127
|
+
column=generated_error.column,
|
|
128
|
+
) from None
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
compiled_script: CodeType = compile(
|
|
132
|
+
generated_script,
|
|
133
|
+
"<jcmsuite-jcmpy>",
|
|
134
|
+
"exec",
|
|
135
|
+
)
|
|
136
|
+
except SyntaxError as error:
|
|
137
|
+
generated_line_number: int | None = getattr(error, "lineno", None)
|
|
138
|
+
source_line: int | None = _source_line_from_generated_script(
|
|
139
|
+
generated_script, generated_line_number
|
|
140
|
+
)
|
|
141
|
+
message: str = error.msg if isinstance(error.msg, str) else str(error)
|
|
142
|
+
raise _raise_template_mapping_error(
|
|
143
|
+
source=source_path,
|
|
144
|
+
template_text=original_template_text,
|
|
145
|
+
message=message,
|
|
146
|
+
line=source_line,
|
|
147
|
+
column=None,
|
|
148
|
+
) from None
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
rendered_text: str
|
|
152
|
+
rendered_line_map: list[int]
|
|
153
|
+
rendered_text, rendered_line_map = _exec_generated_script(
|
|
154
|
+
compiled_script=compiled_script,
|
|
155
|
+
generated_script=generated_script,
|
|
156
|
+
keys=keys,
|
|
157
|
+
)
|
|
158
|
+
except _SubstitutionFailure as substitution_error:
|
|
159
|
+
raise _raise_template_mapping_error(
|
|
160
|
+
source=source_path,
|
|
161
|
+
template_text=original_template_text,
|
|
162
|
+
message=str(substitution_error),
|
|
163
|
+
line=substitution_error.line,
|
|
164
|
+
column=substitution_error.column,
|
|
165
|
+
) from None
|
|
166
|
+
except _GeneratedScriptError as generated_error:
|
|
167
|
+
raise _raise_template_mapping_error(
|
|
168
|
+
source=source_path,
|
|
169
|
+
template_text=original_template_text,
|
|
170
|
+
message=str(generated_error),
|
|
171
|
+
line=generated_error.line,
|
|
172
|
+
column=generated_error.column,
|
|
173
|
+
) from None
|
|
174
|
+
|
|
175
|
+
return rendered_text, rendered_line_map
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _escape_comment_embedded_tags(template_text: str) -> str:
|
|
179
|
+
"""Escape script/substitution tags that appear inside comment lines."""
|
|
180
|
+
|
|
181
|
+
escaped_text: str = template_text
|
|
182
|
+
|
|
183
|
+
# Escape opening tags in comments:
|
|
184
|
+
# - `( #.* )` captures the full comment prefix.
|
|
185
|
+
# - `(<[?])` matches the script opener.
|
|
186
|
+
# - `(Python)?` preserves optional language token.
|
|
187
|
+
# We rewrite opener tokens to inert placeholders inside comments.
|
|
188
|
+
escaped_text = re.sub(
|
|
189
|
+
r"(#.*)(<[?])(Python)?(.*)",
|
|
190
|
+
lambda match: f"{match.group(1)}?<{match.group(3) or ''}{match.group(4)}",
|
|
191
|
+
escaped_text,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# Escape closing tags in comments by replacing `?>` with `>?`.
|
|
195
|
+
escaped_text = re.sub(
|
|
196
|
+
r"(#.*)([?]>)(.*)",
|
|
197
|
+
lambda match: f"{match.group(1)}>?{match.group(3)}",
|
|
198
|
+
escaped_text,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
# Escape substitution markers in comments by rewriting `%` to `%?`,
|
|
202
|
+
# preserving legacy "optional substitution" semantics for commented text.
|
|
203
|
+
escaped_text = re.sub(
|
|
204
|
+
r"(#.*)([%])([^?]?)(\(.*\))(.*)",
|
|
205
|
+
lambda match: (
|
|
206
|
+
f"{match.group(1)}{match.group(2)}?{match.group(3)}"
|
|
207
|
+
f"{match.group(4)}{match.group(5)}"
|
|
208
|
+
),
|
|
209
|
+
escaped_text,
|
|
210
|
+
)
|
|
211
|
+
return escaped_text
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _validate_script_start_tags(
|
|
215
|
+
template_text: str,
|
|
216
|
+
source: Path,
|
|
217
|
+
original_template_text: str,
|
|
218
|
+
) -> None:
|
|
219
|
+
"""Reject malformed script opening tags early with source mapping."""
|
|
220
|
+
|
|
221
|
+
# This regex matches `<?token` and captures `token`.
|
|
222
|
+
# Only empty token (`<?`) and `Python` (`<?Python`) are accepted.
|
|
223
|
+
for match in re.finditer(r"<[?]([^ \n]*)", template_text):
|
|
224
|
+
start_token: str = match.group(1)
|
|
225
|
+
if start_token in ("", "Python"):
|
|
226
|
+
continue
|
|
227
|
+
line, column = _line_col_from_offset(template_text, match.start() + 2)
|
|
228
|
+
raise _raise_template_mapping_error(
|
|
229
|
+
source=source,
|
|
230
|
+
template_text=original_template_text,
|
|
231
|
+
message=f"Wrong script start tag `{start_token}`.",
|
|
232
|
+
line=line,
|
|
233
|
+
column=column,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _compile_template_to_python(template_text: str) -> str:
|
|
238
|
+
"""Transform template text into executable Python script text."""
|
|
239
|
+
|
|
240
|
+
lines: list[str] = template_text.split("\n")
|
|
241
|
+
lines_with_markers: list[str] = [
|
|
242
|
+
f"{line}# __LINE {line_number}"
|
|
243
|
+
for line_number, line in enumerate(lines, start=1)
|
|
244
|
+
]
|
|
245
|
+
marked_template: str = "\n".join(lines_with_markers) + "<?"
|
|
246
|
+
|
|
247
|
+
generated_script_parts: list[str] = []
|
|
248
|
+
in_script_block: bool = False
|
|
249
|
+
previous_position: int = 0
|
|
250
|
+
|
|
251
|
+
for token_match in _SCRIPT_TOKEN_PATTERN.finditer(marked_template):
|
|
252
|
+
token_text: str = token_match.group(1)
|
|
253
|
+
is_start_tag: bool = token_text in ("<?", "<?Python")
|
|
254
|
+
token_position: int = token_match.start()
|
|
255
|
+
|
|
256
|
+
if is_start_tag and in_script_block:
|
|
257
|
+
if token_position < len(marked_template) - 3:
|
|
258
|
+
line, column = _line_col_from_offset(marked_template, token_position)
|
|
259
|
+
raise _GeneratedScriptError(
|
|
260
|
+
"Double script block opening tag.",
|
|
261
|
+
line=line,
|
|
262
|
+
column=column,
|
|
263
|
+
)
|
|
264
|
+
line, column = _line_col_from_offset(marked_template, token_position)
|
|
265
|
+
raise _GeneratedScriptError(
|
|
266
|
+
"Script block not closed.",
|
|
267
|
+
line=line,
|
|
268
|
+
column=column,
|
|
269
|
+
)
|
|
270
|
+
if (not is_start_tag) and (not in_script_block):
|
|
271
|
+
line, column = _line_col_from_offset(marked_template, token_position)
|
|
272
|
+
raise _GeneratedScriptError(
|
|
273
|
+
"Non matching script block ending.",
|
|
274
|
+
line=line,
|
|
275
|
+
column=column,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
snippet: str = marked_template[previous_position:token_position]
|
|
279
|
+
if in_script_block:
|
|
280
|
+
generated_script_parts.append(snippet)
|
|
281
|
+
else:
|
|
282
|
+
generated_script_prefix: str = "".join(generated_script_parts)
|
|
283
|
+
indentation: str = _current_indentation(generated_script_prefix)
|
|
284
|
+
first_line_info: re.Match[str] | None = _SOURCE_MARKER_PATTERN.search(
|
|
285
|
+
snippet
|
|
286
|
+
)
|
|
287
|
+
if first_line_info is not None:
|
|
288
|
+
generated_script_parts.append(
|
|
289
|
+
f"{indentation}# __LINE {first_line_info.group(1)}\n"
|
|
290
|
+
)
|
|
291
|
+
snippet_literal: str = repr(snippet)
|
|
292
|
+
generated_script_parts.append(
|
|
293
|
+
f"{indentation}(jcm_, jcm_lines_) = _jcm_echo({snippet_literal}, keys); "
|
|
294
|
+
f"jcm += jcm_; jcm_lines.extend(jcm_lines_)\n"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
in_script_block = is_start_tag
|
|
298
|
+
previous_position = token_match.end()
|
|
299
|
+
|
|
300
|
+
return "".join(generated_script_parts)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _current_indentation(generated_script_prefix: str) -> str:
|
|
304
|
+
"""Compute indentation from trailing spaces/tabs in generated script."""
|
|
305
|
+
|
|
306
|
+
position: int = len(generated_script_prefix)
|
|
307
|
+
while position > 0:
|
|
308
|
+
previous_char: str = generated_script_prefix[position - 1]
|
|
309
|
+
if previous_char not in (" ", "\t"):
|
|
310
|
+
break
|
|
311
|
+
position -= 1
|
|
312
|
+
return generated_script_prefix[position:]
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _source_line_from_generated_script(
|
|
316
|
+
generated_script: str,
|
|
317
|
+
generated_line_number: int | None,
|
|
318
|
+
) -> int | None:
|
|
319
|
+
"""Map generated script line to original source line via markers."""
|
|
320
|
+
|
|
321
|
+
if generated_line_number is None:
|
|
322
|
+
return None
|
|
323
|
+
generated_lines: list[str] = generated_script.splitlines()
|
|
324
|
+
if generated_line_number <= 0 or generated_line_number > len(generated_lines):
|
|
325
|
+
return None
|
|
326
|
+
index: int = generated_line_number - 1
|
|
327
|
+
while index >= 0:
|
|
328
|
+
marker_match: re.Match[str] | None = _SOURCE_MARKER_PATTERN.search(
|
|
329
|
+
generated_lines[index]
|
|
330
|
+
)
|
|
331
|
+
if marker_match is not None:
|
|
332
|
+
return int(marker_match.group(1))
|
|
333
|
+
index -= 1
|
|
334
|
+
return None
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _exec_generated_script(
|
|
338
|
+
*,
|
|
339
|
+
compiled_script: CodeType,
|
|
340
|
+
generated_script: str,
|
|
341
|
+
keys: Mapping[str, object],
|
|
342
|
+
) -> tuple[str, list[int]]:
|
|
343
|
+
"""Execute generated script and return rendered text plus line mapping."""
|
|
344
|
+
|
|
345
|
+
jcm_text: str = ""
|
|
346
|
+
jcm_lines: list[int] = []
|
|
347
|
+
# We deep-copy keys for parity: script blocks may mutate `keys`, and we do
|
|
348
|
+
# not want caller-owned mappings modified as a side effect of rendering.
|
|
349
|
+
execution_locals: dict[str, object] = {
|
|
350
|
+
"keys": copy.deepcopy(dict(keys)),
|
|
351
|
+
"jcm": jcm_text,
|
|
352
|
+
"jcm_lines": jcm_lines,
|
|
353
|
+
}
|
|
354
|
+
execution_globals: dict[str, object] = {
|
|
355
|
+
"__builtins__": __builtins__,
|
|
356
|
+
"_jcm_echo": _jcm_echo,
|
|
357
|
+
# Legacy template scripts sometimes call `jcm_echo(...)` directly from
|
|
358
|
+
# inside Python blocks; keep this compatibility alias.
|
|
359
|
+
"jcm_echo": _jcm_echo,
|
|
360
|
+
"np": np,
|
|
361
|
+
"numpy": np,
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
try:
|
|
365
|
+
exec(compiled_script, execution_globals, execution_locals)
|
|
366
|
+
except _SubstitutionFailure:
|
|
367
|
+
raise
|
|
368
|
+
except Exception as error:
|
|
369
|
+
traceback_info: TracebackException = TracebackException.from_exception(error)
|
|
370
|
+
generated_line: int | None = None
|
|
371
|
+
for frame in traceback_info.stack:
|
|
372
|
+
if frame.filename == "<jcmsuite-jcmpy>":
|
|
373
|
+
generated_line = frame.lineno
|
|
374
|
+
break
|
|
375
|
+
source_line: int | None = None
|
|
376
|
+
if generated_line is not None:
|
|
377
|
+
source_line = _source_line_from_generated_script(
|
|
378
|
+
generated_script, generated_line
|
|
379
|
+
)
|
|
380
|
+
raise _GeneratedScriptError(
|
|
381
|
+
str(error), line=source_line, column=None
|
|
382
|
+
) from error
|
|
383
|
+
|
|
384
|
+
return cast(str, execution_locals["jcm"]), cast(
|
|
385
|
+
list[int], execution_locals["jcm_lines"]
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _jcm_echo(fragment: str, keys: Mapping[str, object]) -> tuple[str, list[int]]:
|
|
390
|
+
"""Render a non-script fragment using substitution rules."""
|
|
391
|
+
|
|
392
|
+
if fragment == "":
|
|
393
|
+
return "", []
|
|
394
|
+
|
|
395
|
+
try:
|
|
396
|
+
rendered_fragment: str = _SUBSTITUTION_PATTERN.sub(
|
|
397
|
+
lambda match: _jcm_substitute(match, keys),
|
|
398
|
+
fragment,
|
|
399
|
+
)
|
|
400
|
+
except _SubstitutionFailure as error:
|
|
401
|
+
source_line, source_column = _source_position_from_fragment(
|
|
402
|
+
fragment=fragment,
|
|
403
|
+
error_position=error.position_in_fragment,
|
|
404
|
+
)
|
|
405
|
+
error.line = source_line
|
|
406
|
+
error.column = source_column
|
|
407
|
+
raise
|
|
408
|
+
|
|
409
|
+
line_markers: list[str] = re.findall(r"# __LINE \d*", rendered_fragment)
|
|
410
|
+
rendered_line_map: list[int]
|
|
411
|
+
if line_markers:
|
|
412
|
+
first_line_match: re.Match[str] | None = _SOURCE_MARKER_PATTERN.search(
|
|
413
|
+
rendered_fragment
|
|
414
|
+
)
|
|
415
|
+
first_line: int = int(first_line_match.group(1)) if first_line_match else 1
|
|
416
|
+
rendered_line_map = list(range(first_line, first_line + len(line_markers)))
|
|
417
|
+
else:
|
|
418
|
+
rendered_line_map = []
|
|
419
|
+
|
|
420
|
+
rendered_fragment = re.sub(r"# __LINE \d*", "", rendered_fragment)
|
|
421
|
+
return rendered_fragment, rendered_line_map
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _source_position_from_fragment(
|
|
425
|
+
*,
|
|
426
|
+
fragment: str,
|
|
427
|
+
error_position: int,
|
|
428
|
+
) -> tuple[int | None, int | None]:
|
|
429
|
+
"""Map substitution failure position in fragment to source line/column."""
|
|
430
|
+
|
|
431
|
+
line_match: re.Match[str] | None = re.search(
|
|
432
|
+
r"(.*)# __LINE (\d*)", fragment[error_position:]
|
|
433
|
+
)
|
|
434
|
+
if line_match is None:
|
|
435
|
+
return None, None
|
|
436
|
+
|
|
437
|
+
column: int = 1
|
|
438
|
+
cursor: int = error_position - 1
|
|
439
|
+
while cursor >= 0 and fragment[cursor] != "\n":
|
|
440
|
+
column += 1
|
|
441
|
+
cursor -= 1
|
|
442
|
+
return int(line_match.group(2)), column
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _coerce_to_matrix(value: object) -> NDArray[Any] | None:
|
|
446
|
+
"""Coerce matrix-like values for JCM matrix substitution."""
|
|
447
|
+
|
|
448
|
+
if isinstance(value, (np.matrix, np.ndarray)):
|
|
449
|
+
matrix_value: NDArray[Any] = np.asarray(value)
|
|
450
|
+
if matrix_value.ndim == 2:
|
|
451
|
+
return matrix_value
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
if not isinstance(value, (list, tuple)):
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
rows: list[object] = list(value)
|
|
458
|
+
if not rows:
|
|
459
|
+
return None
|
|
460
|
+
if not all(isinstance(row, (list, tuple, np.ndarray)) for row in rows):
|
|
461
|
+
return None
|
|
462
|
+
|
|
463
|
+
matrix_value = np.asarray(value)
|
|
464
|
+
if matrix_value.ndim != 2:
|
|
465
|
+
return None
|
|
466
|
+
if np.issubdtype(matrix_value.dtype, np.number):
|
|
467
|
+
return matrix_value
|
|
468
|
+
|
|
469
|
+
row: object
|
|
470
|
+
for row in rows:
|
|
471
|
+
if isinstance(row, np.ndarray):
|
|
472
|
+
row_items: list[object] = cast(list[object], row.ravel().tolist())
|
|
473
|
+
else:
|
|
474
|
+
row_items = list(cast(list[object], row))
|
|
475
|
+
item: object
|
|
476
|
+
for item in row_items:
|
|
477
|
+
if not isinstance(
|
|
478
|
+
item,
|
|
479
|
+
(int, float, complex, np.integer, np.floating, np.complexfloating),
|
|
480
|
+
):
|
|
481
|
+
return None
|
|
482
|
+
return np.asarray(value, dtype=complex)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _jcm_substitute(match: re.Match[str], keys: Mapping[str, object]) -> str:
|
|
486
|
+
"""Substitute one printf-like placeholder against template keys."""
|
|
487
|
+
|
|
488
|
+
optional_flag: str = match.group(1)
|
|
489
|
+
key_path: str = match.group(2)
|
|
490
|
+
precision_text: str = match.group(3)
|
|
491
|
+
format_code: str = match.group(4)
|
|
492
|
+
|
|
493
|
+
try:
|
|
494
|
+
value: object = _nested_dict_get(keys, key_path)
|
|
495
|
+
except KeyError as error:
|
|
496
|
+
if optional_flag == "?":
|
|
497
|
+
return match.group(0)
|
|
498
|
+
raise _SubstitutionFailure(
|
|
499
|
+
f"No value provided for key `{key_path}`.",
|
|
500
|
+
position_in_fragment=match.start(),
|
|
501
|
+
) from error
|
|
502
|
+
|
|
503
|
+
if format_code == "s":
|
|
504
|
+
if not isinstance(value, str):
|
|
505
|
+
raise _SubstitutionFailure(
|
|
506
|
+
f"Value for key `{key_path}` not a string.",
|
|
507
|
+
position_in_fragment=match.start(),
|
|
508
|
+
)
|
|
509
|
+
return value
|
|
510
|
+
|
|
511
|
+
matrix_value: NDArray[Any] | None = _coerce_to_matrix(value)
|
|
512
|
+
if matrix_value is not None:
|
|
513
|
+
matrix_precision: int = int(precision_text) if precision_text else 15
|
|
514
|
+
row_count: int = int(matrix_value.shape[0])
|
|
515
|
+
rows: list[str] = [
|
|
516
|
+
_array_row_to_string(matrix_value[row], matrix_precision)
|
|
517
|
+
for row in range(row_count)
|
|
518
|
+
]
|
|
519
|
+
matrix_row_separator: str = ";\n"
|
|
520
|
+
return f"[{matrix_row_separator.join(rows)}]"
|
|
521
|
+
|
|
522
|
+
if format_code in ("d", "i") and isinstance(value, (int, np.integer)):
|
|
523
|
+
return str(value)
|
|
524
|
+
|
|
525
|
+
numeric_values: list[complex] | None = _coerce_to_numeric_list(
|
|
526
|
+
value=value,
|
|
527
|
+
integer_only=format_code in ("d", "i"),
|
|
528
|
+
)
|
|
529
|
+
if numeric_values is None:
|
|
530
|
+
type_description: str = "an integer" if format_code in ("d", "i") else "a float"
|
|
531
|
+
raise _SubstitutionFailure(
|
|
532
|
+
f"Value for key `{key_path}` not {type_description}.",
|
|
533
|
+
position_in_fragment=match.start(),
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
if format_code in ("d", "i"):
|
|
537
|
+
value_text: str = " ".join(str(int(number.real)) for number in numeric_values)
|
|
538
|
+
else:
|
|
539
|
+
scalar_precision_text: str = precision_text if precision_text else "15"
|
|
540
|
+
normalized_code: str = format_code if precision_text else "g"
|
|
541
|
+
scalar_formatter: str = f"%.{scalar_precision_text}{normalized_code}"
|
|
542
|
+
complex_formatter: str = f"({scalar_formatter}, {scalar_formatter})"
|
|
543
|
+
pieces: list[str] = []
|
|
544
|
+
for number in numeric_values:
|
|
545
|
+
if number.imag != 0:
|
|
546
|
+
pieces.append(complex_formatter % (number.real, number.imag))
|
|
547
|
+
else:
|
|
548
|
+
pieces.append(scalar_formatter % number.real)
|
|
549
|
+
value_text = " ".join(pieces)
|
|
550
|
+
|
|
551
|
+
if len(numeric_values) > 1 or len(numeric_values) == 0:
|
|
552
|
+
return f"[{value_text}]"
|
|
553
|
+
return value_text
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _coerce_to_numeric_list(
|
|
557
|
+
*,
|
|
558
|
+
value: object,
|
|
559
|
+
integer_only: bool,
|
|
560
|
+
) -> list[complex] | None:
|
|
561
|
+
"""Coerce scalars/arrays/iterables to numeric list compatible with formatter."""
|
|
562
|
+
|
|
563
|
+
if isinstance(value, tuple):
|
|
564
|
+
values: list[object] = list(value)
|
|
565
|
+
elif isinstance(value, list):
|
|
566
|
+
values = value
|
|
567
|
+
elif isinstance(
|
|
568
|
+
value, (int, float, complex, np.integer, np.floating, np.complexfloating)
|
|
569
|
+
):
|
|
570
|
+
values = [value]
|
|
571
|
+
elif isinstance(value, np.matrix):
|
|
572
|
+
values = cast(list[object], value.ravel().tolist()[0])
|
|
573
|
+
elif isinstance(value, np.ndarray):
|
|
574
|
+
values = cast(list[object], value.ravel().tolist())
|
|
575
|
+
else:
|
|
576
|
+
return None
|
|
577
|
+
|
|
578
|
+
normalized: list[complex] = []
|
|
579
|
+
for item in values:
|
|
580
|
+
if integer_only:
|
|
581
|
+
if not isinstance(item, (int, np.integer)):
|
|
582
|
+
return None
|
|
583
|
+
normalized.append(complex(int(item), 0.0))
|
|
584
|
+
else:
|
|
585
|
+
if not isinstance(
|
|
586
|
+
item,
|
|
587
|
+
(int, float, complex, np.integer, np.floating, np.complexfloating),
|
|
588
|
+
):
|
|
589
|
+
return None
|
|
590
|
+
normalized.append(complex(item))
|
|
591
|
+
return normalized
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _array_row_to_string(array_value: object, precision: int) -> str:
|
|
595
|
+
"""Format one 1D matrix/array row as JCM text."""
|
|
596
|
+
|
|
597
|
+
normalized_array: NDArray[Any] = np.asarray(array_value)
|
|
598
|
+
if np.iscomplexobj(normalized_array):
|
|
599
|
+
flat_values: list[complex] = [
|
|
600
|
+
complex(value) for value in normalized_array.ravel().tolist()
|
|
601
|
+
]
|
|
602
|
+
format_specifier: str = f".{precision}g"
|
|
603
|
+
pieces: list[str] = [
|
|
604
|
+
f"({format(value.real, format_specifier)}, "
|
|
605
|
+
f"{format(value.imag, format_specifier)})"
|
|
606
|
+
for value in flat_values
|
|
607
|
+
]
|
|
608
|
+
return ", ".join(pieces)
|
|
609
|
+
|
|
610
|
+
array_text: str = np.array2string(
|
|
611
|
+
normalized_array,
|
|
612
|
+
separator=", ",
|
|
613
|
+
threshold=sys.maxsize,
|
|
614
|
+
max_line_width=sys.maxsize,
|
|
615
|
+
precision=precision,
|
|
616
|
+
).strip("[]")
|
|
617
|
+
return array_text.replace("\n", "")
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _nested_dict_get(mapping: Mapping[str, object], path: str) -> object:
|
|
621
|
+
"""Resolve colon-separated nested dictionary key paths."""
|
|
622
|
+
|
|
623
|
+
current: object = mapping
|
|
624
|
+
path_components: list[str] = [
|
|
625
|
+
component for component in path.split(":") if component
|
|
626
|
+
]
|
|
627
|
+
for path_component in path_components:
|
|
628
|
+
if not isinstance(current, Mapping):
|
|
629
|
+
raise KeyError(path_component)
|
|
630
|
+
current = current[path_component]
|
|
631
|
+
return current
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _line_col_from_offset(text: str, offset: int) -> tuple[int, int]:
|
|
635
|
+
"""Compute 1-based line/column pair for character offset in text."""
|
|
636
|
+
|
|
637
|
+
prefix: str = text[:offset]
|
|
638
|
+
line: int = prefix.count("\n") + 1
|
|
639
|
+
last_newline_index: int = prefix.rfind("\n")
|
|
640
|
+
if last_newline_index < 0:
|
|
641
|
+
column: int = len(prefix) + 1
|
|
642
|
+
else:
|
|
643
|
+
column = len(prefix) - last_newline_index
|
|
644
|
+
return line, column
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _raise_template_mapping_error(
|
|
648
|
+
*,
|
|
649
|
+
source: Path,
|
|
650
|
+
template_text: str,
|
|
651
|
+
message: str,
|
|
652
|
+
line: int | None,
|
|
653
|
+
column: int | None,
|
|
654
|
+
) -> TemplateMappingError:
|
|
655
|
+
"""Create diagnostic-rich `TemplateMappingError` with source context."""
|
|
656
|
+
|
|
657
|
+
detail_message: str = message
|
|
658
|
+
if line is not None and 1 <= line <= len(template_text.splitlines()):
|
|
659
|
+
source_line_text: str = template_text.splitlines()[line - 1]
|
|
660
|
+
detail_message = f"{message}\n {source_line_text}"
|
|
661
|
+
return TemplateMappingError(
|
|
662
|
+
detail_message,
|
|
663
|
+
source=source,
|
|
664
|
+
line=line,
|
|
665
|
+
column=column,
|
|
666
|
+
)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Optional PyTorch integration for solver-driven result data.
|
|
2
|
+
|
|
3
|
+
The public names are re-exported from the implementation module so ordinary
|
|
4
|
+
``jcmsuite`` imports do not load PyTorch.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from . import results
|
|
8
|
+
from .core import solve
|
|
9
|
+
from .types import (
|
|
10
|
+
ComplexDerivative,
|
|
11
|
+
DerivativeBinding,
|
|
12
|
+
RealDerivative,
|
|
13
|
+
SolverDerivative,
|
|
14
|
+
)
|
|
15
|
+
from .validation import validate_inputs
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"ComplexDerivative",
|
|
19
|
+
"DerivativeBinding",
|
|
20
|
+
"RealDerivative",
|
|
21
|
+
"SolverDerivative",
|
|
22
|
+
"results",
|
|
23
|
+
"solve",
|
|
24
|
+
"validate_inputs",
|
|
25
|
+
]
|