ultrafast-engine 1.0.0a1__py3-none-win_amd64.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.
Files changed (80) hide show
  1. ultrafast/__init__.py +47 -0
  2. ultrafast/_native.py +222 -0
  3. ultrafast/agents/__init__.py +131 -0
  4. ultrafast/agents/__main__.py +3 -0
  5. ultrafast/agents/pack/debug-setup/SKILL.md +23 -0
  6. ultrafast/agents/pack/design-system/SKILL.md +36 -0
  7. ultrafast/agents/pack/mirror-lab-setup/SKILL.md +22 -0
  8. ultrafast/agents/pack/optimise-setup/SKILL.md +25 -0
  9. ultrafast/agents/pack/replicate-paper/SKILL.md +25 -0
  10. ultrafast/agents/pack/run-simulations/SKILL.md +47 -0
  11. ultrafast/algorithms/__init__.py +5 -0
  12. ultrafast/algorithms/control.py +172 -0
  13. ultrafast/algorithms/holography.py +198 -0
  14. ultrafast/algorithms/optimisation.py +5 -0
  15. ultrafast/algorithms/retrieval.py +4 -0
  16. ultrafast/algorithms/sensorless.py +147 -0
  17. ultrafast/algorithms/zernike.py +117 -0
  18. ultrafast/bin/native/ultrafast.dll +0 -0
  19. ultrafast/build.py +791 -0
  20. ultrafast/calc/__init__.py +19 -0
  21. ultrafast/calc/_compat.py +40 -0
  22. ultrafast/calc/beam.py +299 -0
  23. ultrafast/calc/cell.py +47 -0
  24. ultrafast/calc/crystal.py +67 -0
  25. ultrafast/calc/nonlinear.py +111 -0
  26. ultrafast/calc/pulse.py +126 -0
  27. ultrafast/cells.py +3 -0
  28. ultrafast/components/__init__.py +17 -0
  29. ultrafast/components/amplifiers.py +16 -0
  30. ultrafast/components/crystals.py +10 -0
  31. ultrafast/components/fibres.py +10 -0
  32. ultrafast/components/media.py +11 -0
  33. ultrafast/components/optics.py +29 -0
  34. ultrafast/components/polarisation.py +13 -0
  35. ultrafast/components/splitters.py +14 -0
  36. ultrafast/core.py +721 -0
  37. ultrafast/crystal.py +3 -0
  38. ultrafast/diagram.py +10 -0
  39. ultrafast/instruments/__init__.py +109 -0
  40. ultrafast/laser.py +137 -0
  41. ultrafast/materials.py +44 -0
  42. ultrafast/mcp/__init__.py +6 -0
  43. ultrafast/mcp/__main__.py +4 -0
  44. ultrafast/mcp/_worker_main.py +38 -0
  45. ultrafast/mcp/explain.py +53 -0
  46. ultrafast/mcp/ops.py +372 -0
  47. ultrafast/mcp/policy.py +244 -0
  48. ultrafast/mcp/prompts.py +54 -0
  49. ultrafast/mcp/resources.py +95 -0
  50. ultrafast/mcp/server.py +236 -0
  51. ultrafast/mcp/tools.py +273 -0
  52. ultrafast/mcp/worker.py +146 -0
  53. ultrafast/measured.py +151 -0
  54. ultrafast/plot.py +86 -0
  55. ultrafast/plotting/__init__.py +116 -0
  56. ultrafast/plotting/animate.py +96 -0
  57. ultrafast/plotting/data.py +82 -0
  58. ultrafast/plotting/diagrams.py +570 -0
  59. ultrafast/plotting/graph_layout.py +348 -0
  60. ultrafast/plotting/instrument_panels.py +461 -0
  61. ultrafast/plotting/run_figures.py +419 -0
  62. ultrafast/plotting/spatial.py +23 -0
  63. ultrafast/plotting/spectral.py +83 -0
  64. ultrafast/plotting/spectrogram.py +215 -0
  65. ultrafast/plotting/style.py +293 -0
  66. ultrafast/plotting/time_domain.py +88 -0
  67. ultrafast/plotting/zernike.py +177 -0
  68. ultrafast/plugins.py +140 -0
  69. ultrafast/py.typed +0 -0
  70. ultrafast/results/__init__.py +46 -0
  71. ultrafast/schemas/run.schema.json +5345 -0
  72. ultrafast/schemas/ufs.schema.json +13469 -0
  73. ultrafast/sources.py +26 -0
  74. ultrafast/system/__init__.py +26 -0
  75. ultrafast/types.py +5066 -0
  76. ultrafast_engine-1.0.0a1.dist-info/METADATA +54 -0
  77. ultrafast_engine-1.0.0a1.dist-info/RECORD +80 -0
  78. ultrafast_engine-1.0.0a1.dist-info/WHEEL +4 -0
  79. ultrafast_engine-1.0.0a1.dist-info/entry_points.txt +4 -0
  80. ultrafast_engine-1.0.0a1.dist-info/top_level.txt +1 -0
ultrafast/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """UltrafastEngine -- nonlinear ultrafast pulse propagation through complete optical systems.
2
+
3
+ Quick start::
4
+
5
+ import ultrafast as uf
6
+ from ultrafast import build as b
7
+
8
+ system = uf.System.load(b.system("plate", [
9
+ b.bulk("plate", "FusedSilica", 5e-3, beam=b.gaussian_beam(w0_m=100e-6, z_waist_m=2.5e-3)),
10
+ ]))
11
+ result = uf.run(system, b.run_spec(b.pulse(1.03e-6, 200e-15, energy=20e-6)))
12
+ print(result.summary["output"]["fwhmS"], result["output_spectrum"].shape)
13
+
14
+ Docs: docs/reference/python.md. The engine itself is the C# UltrafastEngine.Core, reached through its C API
15
+ (``include/ultrafast.h``) -- see :mod:`ultrafast._native` for how the library is found.
16
+ """
17
+ from .core import (ElementContext, Result, ResponseContext, Run, System, UltrafastError, UnverifiedInput, benchmark, capabilities, coherence, command, devices,
18
+ retrieve, retrieve_multi, run, scan, Scan, set_default_backend, study, version,
19
+ estimate_memory, MemoryWarning)
20
+ from . import build
21
+ from . import crystal
22
+ from . import calc
23
+ from . import cells
24
+ from . import laser
25
+ from . import plugins
26
+ from . import materials
27
+ from . import measured
28
+ from . import types
29
+ from . import algorithms, components, instruments, results, sources, system
30
+
31
+ __version__ = "1.0.0a1"
32
+ __all__ = ["System", "Run", "Result", "ResponseContext", "ElementContext", "UltrafastError", "UnverifiedInput", "run", "version", "capabilities",
33
+ "command", "study", "scan", "Scan", "estimate_memory", "MemoryWarning", "coherence", "retrieve", "retrieve_multi", "devices", "benchmark", "set_default_backend", "build", "crystal", "calc", "cells", "laser", "plugins", "materials", "measured", "types", "plot", "load",
34
+ "algorithms", "components", "instruments", "results", "sources", "system"]
35
+
36
+
37
+ def plot(result, what: str = "overview", ax=None):
38
+ """Quick matplotlib plots of a :class:`Result` or a CLI results folder ("overview", "measurements", "spectrum",
39
+ "temporal", "phase", "losses", "elements"). Full reports: :func:`ultrafast.plotting.report`."""
40
+ from .plotting import plot as _plot
41
+ return _plot(result, what, ax)
42
+
43
+
44
+ def load(directory):
45
+ """Open a results folder written by the CLI (``summary.json`` + ``result.npz``) -- no engine needed."""
46
+ from .plotting import load as _load
47
+ return _load(directory)
ultrafast/_native.py ADDED
@@ -0,0 +1,222 @@
1
+ """Locating and loading the engine library.
2
+
3
+ Two back-ends expose the same C API (see ``include/ultrafast.h``):
4
+
5
+ * **native** -- the NativeAOT library ``ultrafast.dll`` / ``libultrafast.so`` / ``libultrafast.dylib``
6
+ (``dotnet publish src/UltrafastEngine.Native -c Release -r <rid>``), loaded with :mod:`ctypes`.
7
+ No .NET runtime is needed. This is what wheels ship.
8
+ * **hosted** -- the managed ``UltrafastEngine.Native.dll`` (plain ``dotnet build``), loaded through the
9
+ .NET host with ``clr_loader``; the ``[UnmanagedCallersOnly]`` exports are fetched as function pointers.
10
+ Needs the .NET 10 runtime. Convenient during development (no AOT toolchain required).
11
+
12
+ Search order: ``$ULTRAFAST_LIBRARY`` (a native library or a ``UltrafastEngine.Native.dll``), then
13
+ ``ultrafast/bin/native``, then ``ultrafast/bin/hosted``, then a repository build
14
+ (``src/UltrafastEngine.Native/bin/{Release,Debug}/net10.0``).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import ctypes
19
+ import os
20
+ import sys
21
+ from pathlib import Path
22
+ from typing import Callable, Dict, Optional
23
+
24
+ _HERE = Path(__file__).resolve().parent
25
+
26
+ # C entry point -> C# method in UltrafastEngine.Native.Exports (hosted back-end)
27
+ EXPORTS: Dict[str, str] = {
28
+ "uf_version": "Version", "uf_last_error": "LastError", "uf_free": "Free", "uf_release": "Release",
29
+ "uf_capabilities": "Capabilities", "uf_crystal_phase_match": "CrystalPhaseMatch", "uf_pulse_calc": "PulseCalc", "uf_command": "Command",
30
+ "uf_devices_json": "DevicesJson", "uf_set_default_backend": "SetDefaultBackend",
31
+ "uf_system_load_file": "SystemLoadFile", "uf_system_load_json": "SystemLoadJson",
32
+ "uf_system_to_json": "SystemToJson", "uf_system_validate": "SystemValidate",
33
+ "uf_run_create": "RunCreate", "uf_run_create_file": "RunCreateFile",
34
+ "uf_run_set_time_response_callback": "SetTimeResponse", "uf_run_set_index_callback": "SetIndex",
35
+ "uf_run_set_filter_callback": "SetFilter", "uf_run_set_beam_callback": "SetBeam",
36
+ "uf_run_set_array_callback": "SetArray", "uf_run_set_progress_callback": "SetProgress",
37
+ "uf_run_set_element_callback": "SetElement", "uf_run_set_field_callback": "SetField",
38
+ "uf_run_execute": "RunExecute",
39
+ "uf_result_summary_json": "ResultSummary", "uf_result_provenance_json": "ResultProvenance",
40
+ "uf_result_array_names": "ResultArrayNames", "uf_result_array_info": "ResultArrayInfo",
41
+ "uf_result_array_copy": "ResultArrayCopy", "uf_result_write": "ResultWrite",
42
+ }
43
+
44
+ c_double_p = ctypes.POINTER(ctypes.c_double)
45
+ c_char_pp = ctypes.POINTER(ctypes.c_char_p)
46
+ vp = ctypes.c_void_p
47
+ vpp = ctypes.POINTER(ctypes.c_void_p)
48
+
49
+
50
+ class ResponseCtx(ctypes.Structure):
51
+ """Mirror of ``uf_response_ctx``."""
52
+ _fields_ = [
53
+ ("n", ctypes.c_int32),
54
+ ("t", c_double_p), ("t_lab", c_double_p),
55
+ ("t_arrival", ctypes.c_double), ("z", ctypes.c_double), ("length", ctypes.c_double),
56
+ ("intensity", c_double_p), ("intensity_x", c_double_p), ("intensity_y", c_double_p),
57
+ ("instant_intensity", c_double_p), ("field", c_double_p),
58
+ ("omega0", ctypes.c_double), ("area", ctypes.c_double),
59
+ ("carrier_resolved", ctypes.c_int32),
60
+ ("element_id", ctypes.c_char_p),
61
+ ("x", ctypes.c_double), ("y", ctypes.c_double),
62
+ ("spatial", ctypes.c_int32),
63
+ ]
64
+
65
+
66
+ class ElementCtx(ctypes.Structure):
67
+ """Mirror of ``uf_element_ctx``."""
68
+ _fields_ = [
69
+ ("n", ctypes.c_int32),
70
+ ("omega", c_double_p), ("t", c_double_p),
71
+ ("omega0", ctypes.c_double), ("dt", ctypes.c_double),
72
+ ("ax_re", c_double_p), ("ax_im", c_double_p), ("ay_re", c_double_p), ("ay_im", c_double_p),
73
+ ("arrival", ctypes.c_double),
74
+ ("element_id", ctypes.c_char_p), ("params_json", ctypes.c_char_p),
75
+ ]
76
+
77
+
78
+ ELEMENT_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.POINTER(ElementCtx))
79
+ TIME_RESPONSE_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.POINTER(ResponseCtx), c_double_p, c_double_p)
80
+ INDEX_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_int32, c_double_p, c_double_p)
81
+ FILTER_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_int32, c_double_p, c_double_p, c_double_p)
82
+ BEAM_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_int32, c_double_p, c_double_p, c_double_p)
83
+ ARRAY_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_int32, c_double_p, c_double_p)
84
+ FIELD_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_int32, c_double_p, c_double_p, c_double_p, c_double_p)
85
+ PROGRESS_FN = ctypes.CFUNCTYPE(ctypes.c_int, vp, ctypes.c_char_p, ctypes.c_int32, ctypes.c_int32, ctypes.c_double)
86
+
87
+ # restype, argtypes for each entry point
88
+ SIGNATURES = {
89
+ "uf_version": (ctypes.c_void_p, []),
90
+ "uf_last_error": (ctypes.c_void_p, []),
91
+ "uf_free": (None, [vp]),
92
+ "uf_release": (None, [vp]),
93
+ "uf_capabilities": (ctypes.c_int, [vpp]),
94
+ "uf_command": (ctypes.c_int, [ctypes.c_char_p, vpp]),
95
+ "uf_devices_json": (ctypes.c_int, [ctypes.c_char_p, vpp]),
96
+ "uf_set_default_backend": (ctypes.c_int, [ctypes.c_char_p]),
97
+ "uf_crystal_phase_match": (ctypes.c_int, [ctypes.c_char_p, vpp]),
98
+ "uf_pulse_calc": (ctypes.c_int, [ctypes.c_char_p, vpp]),
99
+ "uf_system_load_file": (ctypes.c_int, [ctypes.c_char_p, vpp]),
100
+ "uf_system_load_json": (ctypes.c_int, [ctypes.c_char_p, vpp]),
101
+ "uf_system_to_json": (ctypes.c_int, [vp, vpp]),
102
+ "uf_system_validate": (ctypes.c_int, [vp, vpp]),
103
+ "uf_run_create": (ctypes.c_int, [vp, ctypes.c_char_p, vpp]),
104
+ "uf_run_create_file": (ctypes.c_int, [vp, ctypes.c_char_p, vpp]),
105
+ "uf_run_set_time_response_callback": (ctypes.c_int, [vp, ctypes.c_char_p, TIME_RESPONSE_FN, vp, ctypes.c_int32]),
106
+ "uf_run_set_index_callback": (ctypes.c_int, [vp, ctypes.c_char_p, INDEX_FN, vp]),
107
+ "uf_run_set_filter_callback": (ctypes.c_int, [vp, ctypes.c_char_p, FILTER_FN, vp]),
108
+ "uf_run_set_beam_callback": (ctypes.c_int, [vp, ctypes.c_char_p, BEAM_FN, vp]),
109
+ "uf_run_set_array_callback": (ctypes.c_int, [vp, ctypes.c_char_p, ARRAY_FN, vp]),
110
+ "uf_run_set_progress_callback": (ctypes.c_int, [vp, PROGRESS_FN, vp]),
111
+ "uf_run_set_element_callback": (ctypes.c_int, [vp, ctypes.c_char_p, ELEMENT_FN, vp]),
112
+ "uf_run_set_field_callback": (ctypes.c_int, [vp, ctypes.c_char_p, FIELD_FN, vp]),
113
+ "uf_run_execute": (ctypes.c_int, [vp, vpp]),
114
+ "uf_result_summary_json": (ctypes.c_int, [vp, vpp]),
115
+ "uf_result_provenance_json": (ctypes.c_int, [vp, vpp]),
116
+ "uf_result_array_names": (ctypes.c_int, [vp, vpp]),
117
+ "uf_result_array_info": (ctypes.c_int, [vp, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int32), ctypes.POINTER(ctypes.c_int64), ctypes.POINTER(ctypes.c_int64)]),
118
+ "uf_result_array_copy": (ctypes.c_int, [vp, ctypes.c_char_p, c_double_p, ctypes.c_int64]),
119
+ "uf_result_write": (ctypes.c_int, [vp, ctypes.c_char_p]),
120
+ }
121
+
122
+
123
+ # Functions added after the first release. An older engine library may lack them: the library still loads, and calling one
124
+ # raises an error that says how to update (Library.fn). Every other function is required.
125
+ OPTIONAL = {"uf_pulse_calc"}
126
+
127
+
128
+ def _native_name() -> str:
129
+ if sys.platform.startswith("win"):
130
+ return "ultrafast.dll"
131
+ if sys.platform == "darwin":
132
+ return "libultrafast.dylib"
133
+ return "libultrafast.so"
134
+
135
+
136
+ def _candidates():
137
+ env = os.environ.get("ULTRAFAST_LIBRARY")
138
+ if env:
139
+ yield Path(env)
140
+ yield _HERE / "bin" / "native" / _native_name()
141
+ if not sys.platform.startswith("win"): # older builds named it ultrafast.so / ultrafast.dylib
142
+ yield _HERE / "bin" / "native" / _native_name()[3:]
143
+ yield _HERE / "bin" / "hosted" / "UltrafastEngine.Native.dll"
144
+ repo = _HERE.parents[2] if len(_HERE.parents) > 2 else _HERE
145
+ for cfg in ("Release", "Debug"):
146
+ yield repo / "src" / "UltrafastEngine.Native" / "bin" / cfg / "net10.0" / "UltrafastEngine.Native.dll"
147
+
148
+
149
+ class Library:
150
+ """The loaded engine: ``lib.fn('uf_version')()`` etc."""
151
+
152
+ def __init__(self, path: Path):
153
+ self.path = path
154
+ self.mode = "hosted" if path.name.lower() == "ultrafastengine.native.dll" else "native"
155
+ self._fns: Dict[str, Callable] = {}
156
+ if self.mode == "native":
157
+ self._cdll = ctypes.CDLL(str(path))
158
+ for name, (res, args) in SIGNATURES.items():
159
+ try:
160
+ f = getattr(self._cdll, name)
161
+ except AttributeError:
162
+ if name in OPTIONAL:
163
+ continue
164
+ raise
165
+ f.restype, f.argtypes = res, args
166
+ self._fns[name] = f
167
+ else:
168
+ self._load_hosted(path)
169
+
170
+ def _load_hosted(self, path: Path):
171
+ try:
172
+ import clr_loader # type: ignore
173
+ from clr_loader.ffi import ffi # type: ignore
174
+ import clr_loader.hostfxr as hostfxr # type: ignore
175
+ except ImportError as e: # pragma: no cover
176
+ raise ImportError("The hosted engine needs clr_loader (pip install clr_loader) and the .NET 10 runtime; "
177
+ "or build the NativeAOT library with tools/build_engine.py --aot.") from e
178
+ cfg = path.with_name("UltrafastEngine.Native.runtimeconfig.json")
179
+ self._runtime = clr_loader.get_coreclr(runtime_config=str(cfg))
180
+ load = self._runtime._get_load_func()
181
+ import atexit
182
+ atexit.register(self._runtime.shutdown) # close the host handle while cffi is still alive
183
+ asm = hostfxr.encode(str(path))
184
+ type_name = hostfxr.encode("UltrafastEngine.Native.Exports, UltrafastEngine.Native")
185
+ for name, method in EXPORTS.items():
186
+ p = ffi.new("void**")
187
+ # delegate type (void*)-1 == UNMANAGEDCALLERSONLY_METHOD
188
+ rc = load(asm, type_name, hostfxr.encode(method), ffi.cast("void*", -1), ffi.NULL, p)
189
+ if rc != 0 and name in OPTIONAL:
190
+ continue
191
+ if rc != 0:
192
+ raise OSError("could not bind %s (hostfxr error 0x%08x)" % (name, rc & 0xFFFFFFFF))
193
+ res, args = SIGNATURES[name]
194
+ proto = ctypes.CFUNCTYPE(res, *args)
195
+ self._fns[name] = proto(int(ffi.cast("uintptr_t", p[0])))
196
+
197
+ def fn(self, name: str) -> Callable:
198
+ try:
199
+ return self._fns[name]
200
+ except KeyError:
201
+ raise RuntimeError("%s is not in the engine library %s, which is older than this Python package. Rebuild it "
202
+ "(python build/setup.py --python --clean-native) or delete python/src/ultrafast/bin/native "
203
+ "if a hosted build is newer; ULTRAFAST_LIBRARY selects a library." % (name, self.path)) from None
204
+
205
+
206
+ _lib: Optional[Library] = None
207
+
208
+
209
+ def library() -> Library:
210
+ """Load (once) and return the engine library."""
211
+ global _lib
212
+ if _lib is None:
213
+ tried = []
214
+ for c in _candidates():
215
+ tried.append(str(c))
216
+ if c.exists():
217
+ _lib = Library(c)
218
+ break
219
+ if _lib is None:
220
+ raise OSError("UltrafastEngine library not found. Build it with `python tools/build_engine.py` "
221
+ "(or set ULTRAFAST_LIBRARY). Looked in:\n " + "\n ".join(tried))
222
+ return _lib
@@ -0,0 +1,131 @@
1
+ """The agent pack: skills that teach a coding agent to drive UltrafastEngine, and the command that installs them.
2
+
3
+ ``pack/<name>/SKILL.md`` holds the skills shipped in the wheel: ``run-simulations``, ``debug-setup``, ``mirror-lab-setup``,
4
+ ``optimise-setup``, ``replicate-paper`` and ``design-system`` (the same text as ``.claude/skills/`` in the repository; a test keeps the two equal).
5
+ ``install(target, dest)`` writes them where an agent looks for them:
6
+
7
+ * ``claude``: ``<dest>/.claude/skills/<name>/SKILL.md`` (Claude Code skills);
8
+ * ``codex``: one block between ``<!-- ultrafast-agent-pack -->`` markers in ``<dest>/AGENTS.md`` (replaced on re-install, the rest of the file kept);
9
+ * ``cursor``: ``<dest>/.cursor/rules/ultrafast-<name>.mdc`` (rules that apply when the agent decides they are relevant).
10
+
11
+ Command line: ``ultrafast-agent list`` and ``ultrafast-agent install --target claude|codex|cursor [--dest DIR] [--force]``; ``ultrafast-agent mcp-config``
12
+ prints the MCP server configuration. Nothing outside ``dest`` is touched, and an existing skill file is overwritten only with ``--force``.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import re
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Dict, List, Optional
22
+
23
+ __all__ = ["skills", "install", "mcp_config", "main", "TARGETS"]
24
+
25
+ TARGETS = ("claude", "codex", "cursor")
26
+ PACK = Path(__file__).with_name("pack")
27
+ FOOTER = ("\n\n---\nThe paths `docs/...` in this skill are pages of the documentation site (https://josephcodemard.github.io/UltrafastEngine/) and, in a source checkout, "
28
+ "files of the repository. The MCP server (`ultrafast-mcp`, `ultrafast-agent mcp-config`) gives the same workflow as tools.\n")
29
+ BEGIN, END = "<!-- ultrafast-agent-pack -->", "<!-- /ultrafast-agent-pack -->"
30
+
31
+
32
+ def skills() -> Dict[str, str]:
33
+ """``{name: SKILL.md text}`` of the shipped skills."""
34
+ return {d.name: (d / "SKILL.md").read_text(encoding="utf-8") for d in sorted(PACK.iterdir()) if (d / "SKILL.md").is_file()}
35
+
36
+
37
+ def _split(text: str):
38
+ m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S)
39
+ if not m:
40
+ raise ValueError("skill without front matter")
41
+ meta = dict(re.findall(r"^(\w+):\s*(.*)$", m.group(1), re.M))
42
+ return meta, m.group(2).lstrip("\n")
43
+
44
+
45
+ def _write(p: Path, text: str) -> None:
46
+ """Write UTF-8 with LF line ends on every OS (write_text gives CRLF on Windows; ``ultrafast agent install`` writes LF)."""
47
+ p.write_bytes(text.encode("utf-8"))
48
+
49
+
50
+ def install(target: str, dest: Path, force: bool = False) -> List[Path]:
51
+ """Write the pack for ``target`` under ``dest``; returns the files written. Raises ``FileExistsError`` for an existing skill file unless ``force``."""
52
+ if target not in TARGETS:
53
+ raise ValueError("target must be one of %s" % ", ".join(TARGETS))
54
+ dest = Path(dest)
55
+ written: List[Path] = []
56
+ sk = skills()
57
+ if target == "claude":
58
+ for name, text in sk.items():
59
+ p = dest / ".claude" / "skills" / name / "SKILL.md"
60
+ if p.exists() and not force:
61
+ raise FileExistsError("%s exists (use --force to overwrite)" % p)
62
+ p.parent.mkdir(parents=True, exist_ok=True)
63
+ _write(p, text.rstrip("\n") + FOOTER)
64
+ written.append(p)
65
+ elif target == "cursor":
66
+ for name, text in sk.items():
67
+ meta, body = _split(text)
68
+ p = dest / ".cursor" / "rules" / ("ultrafast-%s.mdc" % name)
69
+ if p.exists() and not force:
70
+ raise FileExistsError("%s exists (use --force to overwrite)" % p)
71
+ p.parent.mkdir(parents=True, exist_ok=True)
72
+ _write(p, "---\ndescription: %s\nalwaysApply: false\n---\n%s" % (meta.get("description", name), body.rstrip("\n") + FOOTER))
73
+ written.append(p)
74
+ else:
75
+ block = [BEGIN, "# UltrafastEngine skills (installed by `ultrafast-agent install --target codex`)", ""]
76
+ for name, text in sk.items():
77
+ meta, body = _split(text)
78
+ block += ["## Skill: %s" % name, "", "_When: %s_" % meta.get("description", ""), "", body.rstrip("\n"), ""]
79
+ block += [FOOTER.strip(), END, ""]
80
+ p = dest / "AGENTS.md"
81
+ old = p.read_text(encoding="utf-8") if p.exists() else ""
82
+ if BEGIN in old and END in old:
83
+ i, j = old.index(BEGIN), old.index(END) + len(END)
84
+ new = old[:i] + "\n".join(block).rstrip("\n") + old[j:]
85
+ else:
86
+ new = (old.rstrip("\n") + "\n\n" if old.strip() else "") + "\n".join(block)
87
+ p.parent.mkdir(parents=True, exist_ok=True)
88
+ _write(p, new)
89
+ written.append(p)
90
+ return written
91
+
92
+
93
+ def mcp_config(workspace: str = ".", client: str = "claude") -> str:
94
+ """The server entry for an MCP client's configuration (JSON text)."""
95
+ entry = {"command": "ultrafast-mcp", "args": ["--workspace", str(workspace)]}
96
+ if client == "codex":
97
+ return '[mcp_servers.ultrafast]\ncommand = "ultrafast-mcp"\nargs = ["--workspace", %s]\n' % json.dumps(str(workspace))
98
+ return json.dumps({"mcpServers": {"ultrafast": entry}}, indent=2) + "\n"
99
+
100
+
101
+ def main(argv: Optional[List[str]] = None) -> int:
102
+ ap = argparse.ArgumentParser(prog="ultrafast-agent", description="Install the UltrafastEngine skills for a coding agent (docs/agents.md).")
103
+ sub = ap.add_subparsers(dest="cmd", required=True)
104
+ sub.add_parser("list", help="list the skills of the pack")
105
+ ins = sub.add_parser("install", help="write the skills where the agent looks for them")
106
+ ins.add_argument("--target", required=True, choices=TARGETS)
107
+ ins.add_argument("--dest", default=".", help="project folder (default: the current folder)")
108
+ ins.add_argument("--force", action="store_true", help="overwrite existing skill files")
109
+ mc = sub.add_parser("mcp-config", help="print the MCP server configuration")
110
+ mc.add_argument("--workspace", default=".")
111
+ mc.add_argument("--client", choices=("claude", "codex"), default="claude")
112
+ a = ap.parse_args(argv)
113
+ if a.cmd == "list":
114
+ for n, t in skills().items():
115
+ print("%-18s %s" % (n, _split(t)[0].get("description", "")[:100]))
116
+ return 0
117
+ if a.cmd == "mcp-config":
118
+ sys.stdout.write(mcp_config(a.workspace, a.client))
119
+ return 0
120
+ try:
121
+ files = install(a.target, Path(a.dest), a.force)
122
+ except (FileExistsError, ValueError) as e:
123
+ print("ultrafast-agent: %s" % e, file=sys.stderr)
124
+ return 2
125
+ for f in files:
126
+ print(f)
127
+ return 0
128
+
129
+
130
+ if __name__ == "__main__":
131
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: debug-setup
3
+ description: Find problems in a user's UltrafastEngine system file or results - wrong units, unresolved grids, missing physics switches, energy that does not close, polarisation or carrier mistakes, results that disagree with a measurement. Use when a simulation looks wrong, a run warns, or a model does not match the lab.
4
+ ---
5
+ # Debugging a setup
6
+
7
+ Checks in this order (cheap first):
8
+
9
+ 1. `ultrafast validate system.ufs run.json` (add `--graph` for branched) and read every warning; `ultrafast describe`
10
+ shows what each element became. `ULTRAFAST_STRICT_OPTIONS=1` turns unknown keys into errors (typos).
11
+ 2. **Units and names**: SI with the unit in the key (`lengthM`, `energyJ`, `durationFwhmS`). FWHM of intensity, not T0.
12
+ 3. **Grid**: `summary["output"]["edgeEnergyFraction"]` < 1e-6 (else the window or band is too small); the spectrum must
13
+ not touch the band edge; at least ~20 points across the shortest feature. Let the planner size it before a manual grid.
14
+ 4. **Energy and budget**: input − output = booked losses (`summary["elements"]`, `graph.energyClosureJ` at rounding level).
15
+ 5. **Physics switches**: Raman, self-steepening, plasma, ionisation and the spatial model only if the regime needs them
16
+ (B-integral, peak intensity vs the ionisation threshold, beam collapse P/P_cr). Compare with the analytic estimate
17
+ in `docs/reference/nonlinear.md`.
18
+ 6. **Polarisation and carrier**: circular and linear light differ by 2/3 in the electronic Kerr effect; waveplate
19
+ angles and which port a measurement sits on; a beam of another colour needs its own carrier.
20
+ 7. **Vs the lab**: measurement point and instrument response (`measured` with the resolution), background, calibration;
21
+ one stage at a time (`mirror-lab-setup`). Vary the suspect parameter in a study to see whether it can explain the gap.
22
+ 8. If a minimal case still contradicts an analytic or published value, it is an engine bug: `/bug-report`.
23
+ Report: the cause, the evidence (numbers), the fix to the file, and what you could not check.
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: design-system
3
+ description: Design a new laser, amplifier, compressor, beamline or nonlinear stage in UltrafastEngine from a stated goal - choose the architecture, size it with the calculators, build the system file, check it in the cheapest faithful model, then confirm it in full. Use when asked to design, size or propose a system (not to model an existing lab setup, and not to tune an existing one).
4
+ ---
5
+ # Designing a system from a goal
6
+
7
+ Tools: the calculators (`docs/reference/calculators.md`, `docs/reference/pulse-calculator.md`: pulse limits, beam and cavity
8
+ matching, B-integral and critical power, phase matching), the element list (`docs/reference/components.md`, `fibers.md`,
9
+ `crystals.md`, `gain.md`), studies (`docs/reference/studies.md`), fidelity (`docs/reference/fidelity.md`) and the plotting
10
+ backend (`docs/reference/plotting.md`).
11
+
12
+ 1. **Write the goal as numbers**: output energy, duration, wavelength, repetition rate, beam size, and the limits that must hold
13
+ (B-integral, fluence against the damage threshold `lidt`, intensity in the medium, efficiency). Ask for what is missing; do not guess.
14
+ 2. **Size on paper first**, with the calculators: the Fourier limit of the bandwidth, the beam waist and lens or mirror spacing
15
+ (`calc.beam`), the crystal angle and acceptance (`calc.crystal`), the B-integral and critical power (`calc.nonlinear`).
16
+ Write the numbers down: they are the check for the simulation later.
17
+ 3. **Build the smallest system that has the physics** (one stage, 1-D, no spatial model) as a `.ufs` file with the builders
18
+ (`ultrafast.build`) or JSON. Name every element; SI units with the unit in the key. Add the instruments that read the goal
19
+ (pulse width, spectrum, energy, B-integral).
20
+ 4. **Run it in `fidelity: quick`**, compare with the paper numbers of step 2, and say where they differ and why. A disagreement
21
+ is a finding: do not tune a parameter to hide it.
22
+ 5. **Add one effect at a time** (Raman, self-steepening, gain, the spatial model, higher orders), each time checking that the
23
+ result changes by the amount the effect should change it. Stop when the next effect changes the goal numbers by less than the tolerance.
24
+ 6. **Scan the free parameters** (`docs/reference/studies.md`): length, angle, chirp, energy. Report the sensitivity, and the
25
+ margin to every limit of step 1. Use `uf.validate` and read every warning (`explain_warning` on the MCP server).
26
+ 7. **Confirm in full** (`fidelity: full`) at the chosen point and at the edges of the tolerance range.
27
+ 8. **Deliver**: the `.ufs` and `run.json`, a schematic (`up.system(result, params=True)`), the figure of merit against the
28
+ goal, the margins, the assumptions (every value that is a guess, with its source), and what was not modelled.
29
+
30
+ Do not present a design whose limits were not checked, or one found at the boundary of a scan without saying so.
31
+
32
+ ## Fidelity: explore in `quick`, confirm in `full` (a rule, not a tip)
33
+
34
+ The tools' default fidelity is `full`, which is slow. Every exploratory scan, study, run, comparison or fit passes `"fidelity": "quick"` (Raman, self-steepening and
35
+ polarisation dropped; seconds instead of minutes). Run only the point or points you will report again with `"fidelity": "full"`, and say in the answer which numbers came from
36
+ `quick` and which from `full`. Never quote a `quick` number as a result; never explore in `full`. A failed point in `quick` is a reason to look, not to switch to `full` for the whole scan.
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: mirror-lab-setup
3
+ description: Build a model of a user's real laser / beamline in UltrafastEngine from what they know about it (layout, components, measured spectra and traces), calibrate it against their data and say where the model and the lab disagree. Use when asked to model, simulate or digitally twin a lab setup.
4
+ ---
5
+ # Mirroring a lab setup
6
+
7
+ Tools: `run-simulations` skill, `docs/reference/measured-data.md`, the fitting plugin (`docs/plugins/fitting.md`),
8
+ branched systems for interferometers and pump arms (`docs/reference/branches.md`).
9
+
10
+ 1. **Interview first.** Ask for, in this order: the layout as a list of components in beam order with distances; the
11
+ source (energy, duration, spectrum, polarisation, contrast, beam size); every medium (material, length, pressure,
12
+ temperature); coatings and their dispersion; the diagnostics and where they sit. Ask which numbers were measured
13
+ and which are nominal. Do not guess a number the user can look up.
14
+ 2. **Use their data as given**: input spectrum and traces as `measured` (units from column names, background removed,
15
+ resolution stated). Keep data files with the model; never edit them.
16
+ 3. **Build in stages and validate each**: source alone against its measured spectrum and duration; then one component
17
+ at a time against the measurement just after it, so a disagreement points at a component.
18
+ 4. **Calibrate few unknowns with the fitting plugin** (energy reaching a stage, input chirp, one transform per
19
+ unknown). One unknown per measurement; report uncertainties and correlations; do not fit what the data cannot constrain.
20
+ 5. **Report the comparison honestly**: what matches, what does not, the most likely cause in the physics or the
21
+ data (polarisation setting, measurement point, wavelength calibration), and what extra measurement would settle it.
22
+ 6. Save `system.ufs`, `run.json`, the data and a README with the assumptions so the model can be re-run.
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: optimise-setup
3
+ description: Find better settings for a simulated setup (compressor, waveplate angles, lengths, pressures, input chirp, energy) with parameter studies and the fitting plugin's estimators, against a stated goal. Use when asked to optimise, tune, scan or find the best operating point of a system.
4
+ ---
5
+ # Optimising a setup
6
+
7
+ Tools: studies (`docs/reference/studies.md`: scans and grids, the study restarts after unchanged elements, so scanning a
8
+ late parameter is cheap), instruments (`docs/reference/instruments.md`), the fitting plugin (LM, CMA-ES, ensemble MCMC).
9
+
10
+ 1. **State the goal as a number**: peak power, duration, contrast at +2 ps, efficiency, bandwidth. Name the
11
+ constraints (damage threshold `lidt`, minimum throughput, maximum B-integral, no wavefront distortion).
12
+ 2. **Start with a coarse scan** of the one or two parameters that matter; plot it. A scan shows whether the optimum is
13
+ interior, whether the landscape has several maxima, and which parameters do nothing.
14
+ 3. **Refine with an estimator** (`fit` with the goal as a target, or CMA-ES for multimodal landscapes); keep the
15
+ evaluation count small by running the cheapest faithful model (1-D before spatial, fewer points before the final run).
16
+ 4. **Check the answer in the full model** and at the edges: tolerance to ±1 step of each parameter (alignment, angle
17
+ resolution of a waveplate mount). A sharp optimum is a warning, not a result.
18
+ 5. **Report**: the setting, the figure of merit, the sensitivity, what limits it, and the runner-up settings.
19
+ Do not report an optimum found at the boundary of the scanned range without saying so.
20
+
21
+ ## Fidelity: explore in `quick`, confirm in `full` (a rule, not a tip)
22
+
23
+ The tools' default fidelity is `full`, which is slow. Every exploratory scan, study, run, comparison or fit passes `"fidelity": "quick"` (Raman, self-steepening and
24
+ polarisation dropped; seconds instead of minutes). Run only the point or points you will report again with `"fidelity": "full"`, and say in the answer which numbers came from
25
+ `quick` and which from `full`. Never quote a `quick` number as a result; never explore in `full`. A failed point in `quick` is a reason to look, not to switch to `full` for the whole scan.
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: replicate-paper
3
+ description: Reproduce the headline results of a published ultrafast-optics paper with UltrafastEngine - extract parameters, build the system, run it, compare with the paper's numbers and explain any disagreement. Use when asked to replicate, check or reproduce a paper, figure or published number.
4
+ ---
5
+ # Replicating a paper
6
+
7
+ Examples to copy: `docs/papers/*/` (each has `paper.json`, `run.py`, `checks.json`, README). Harness: `python3 build/paper_check.py`.
8
+ Conventions and what the engine can simulate: `docs/capabilities.md`, `docs/concepts.md`.
9
+
10
+ 1. **Read the paper, list the inputs.** Wavelength, duration and shape, energy or power, beam size, every length and
11
+ material, dispersion, pressure, mirror GDD. Write each with its location (section / figure / table) in `paper.json`.
12
+ What is missing gets a stated, reasonable assumption; say so in the README. Never copy the paper's text, figures or PDF.
13
+ 2. **List the headline results**: the numbers the paper claims (compression factor, efficiency, shift, contrast ...).
14
+ A number you only recalled, or could not read in the full text, is UNVERIFIED and is never a hard check.
15
+ 3. **Build the smallest system that contains the physics** (`run-simulations` skill). Start 1-D; add the spatial model
16
+ only if the paper's result depends on it. Check units and the pulse-duration convention (FWHM of intensity vs T0).
17
+ 4. **Check the model before comparing**: energy budget closes, B-integral as expected, grid resolves the pulse and
18
+ the broadened spectrum (`ultrafast validate`, `summary.json` warnings).
19
+ 5. **Compare**: an analytic reference computed in `run.py` is better than a number read off a figure. Put checks in
20
+ `checks.json` (`number`, `ordering`, `location`) with tolerances that reflect the source.
21
+ 6. **If it disagrees**: first make sure the setup matches the paper; then try the debug-setup skill (grid, switches,
22
+ polarisation, units); only then suspect the engine and reduce it to a minimal case (`/bug-report`). Record in the
23
+ README what agrees, what does not and the most likely reason.
24
+ 7. Plots: our result with the paper's formula or numbers on the same axes, labelled with units; commentary in the
25
+ README for a reader who has not seen the paper.
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: run-simulations
3
+ description: How to drive UltrafastEngine - write .ufs system files and run.json specs, run them from the CLI or Python, pick grids and physics switches, use measured data and studies, and read summary.json / result.npz. Use when asked to simulate a system, reproduce a measurement, or build an example.
4
+ ---
5
+ # Running UltrafastEngine
6
+
7
+ Full guide: `docs/agents.md`; every key with unit and default: `docs/reference/options.md` (large -- grep it for a
8
+ key instead of reading it); examples to copy: `docs/examples/*/` (README + .ufs + run.json).
9
+
10
+ ## Workflow
11
+
12
+ 1. Start from the closest example. `ultrafast describe system.ufs` shows what each element becomes.
13
+ 2. Write with `ULTRAFAST_STRICT_OPTIONS=1` so typos fail. `ultrafast validate system.ufs run.json`.
14
+ 3. `ultrafast run system.ufs run.json -o results` (CLI: `dotnet src/UltrafastEngine.Cli/bin/Release/net10.0/ultrafast.dll`
15
+ in the repo). Read the notes and warnings it prints -- they explain grids, satellites, cleaning, B estimates.
16
+ 4. Python: `import ultrafast as uf; from ultrafast import build as b` -- builders return typed dicts;
17
+ `res = uf.run(b.system(...), b.run_spec(...))`; `res.summary`, `res["inst_array"]`, `res.instrument(name)`,
18
+ `res.comparisons`. Figures: `ultrafast-plot results` or `uf.plot(res, "overview" | "measurements")`.
19
+
20
+ ## Essentials
21
+
22
+ * SI everywhere (wavelengths 1.03e-6 m); keys carry units; `gddFs2` etc. are explicit fs-unit variants.
23
+ * Nonlinear elements need a beam (`beam` on the element or `inputBeam` in the run): constant (radiusM/areaM2),
24
+ gaussian (w0M, zWaistM, m2), or a `transverse` model for real spatial effects.
25
+ * Polarisation: `"x"`, `"rcp"`, `{ "angleDeg": 0, "ellipticity": tan χ }` (+1 right circular) or a Jones vector.
26
+ Elliptical light uses the vector Kerr + Raman model (NER).
27
+ * Measured input: `"pulse": {"spectrum": {"csv": "s.csv", "background": "auto", "resolutionM": 0.5e-9,
28
+ "extrapolate": "gaussian"}, "energyJ": ...}`. Instrument recordings: `"measured": {"file": "osa.csv",
29
+ "background": "auto", "resolutionM": 0.5e-9}` -> `summary.comparisons`.
30
+ * Grid: leave `grid.auto` on; for many ghosted plates the window follows `grid.satelliteLevel`; fix the grid
31
+ (`"auto": false, "n", "windowS"`) only for studies or to match another code.
32
+ * Many runs: `ultrafast study study.json` (frozen grid, prefix cache, parallel) instead of loops. Fits / backward
33
+ propagation: fitting plugin (`docs/plugins/fitting.md`).
34
+
35
+ ## Reading results
36
+
37
+ `summary.json`: `output` (energyJ, fwhmS, transformLimitFwhmS, peakPowerW, spectralFwhmM, pulseGddS2,
38
+ edgeEnergyFraction), `elements[]` (bIntegralRad, energyOutJ, criticalPowerRatio, lidtMargin, notes), `instruments[]`
39
+ (values, settings, arrays in result.npz as `<name>_<array>`), `comparisons[]`, `lossBudget`, `totals`, `warnings`.
40
+ Sanity: energy balance (`totals.energyTransmission`), `edgeEnergyFraction` < 1e-6, B-integral vs your estimate
41
+ k0·n2·I·L, TL vs the input spectrum width.
42
+
43
+ ## Fidelity: explore in `quick`, confirm in `full` (a rule, not a tip)
44
+
45
+ The tools' default fidelity is `full`, which is slow. Every exploratory scan, study, run, comparison or fit passes `"fidelity": "quick"` (Raman, self-steepening and
46
+ polarisation dropped; seconds instead of minutes). Run only the point or points you will report again with `"fidelity": "full"`, and say in the answer which numbers came from
47
+ `quick` and which from `full`. Never quote a `quick` number as a result; never explore in `full`. A failed point in `quick` is a reason to look, not to switch to `full` for the whole scan.
@@ -0,0 +1,5 @@
1
+ """Algorithms usable on their own: Zernike polynomials (NumPy only), retrieval and optimisation wrappers around the engine.
2
+ Holography, wavefront sensing and control, and sensorless optimisers (the ao plugin's algorithms, usable without it)."""
3
+ from . import control, holography, optimisation, retrieval, sensorless, zernike
4
+
5
+ __all__ = ["zernike", "retrieval", "optimisation", "holography", "control", "sensorless"]