-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.py
More file actions
4649 lines (3984 loc) · 161 KB
/
bootstrap.py
File metadata and controls
4649 lines (3984 loc) · 161 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) DataLab Platform Developers, BSD 3-Clause License
# See LICENSE file for details
"""
Sigima bootstrap script for DataLab-Web.
Loaded once into Pyodide at application start-up. Owns the in-memory
:class:`ObjectModel` (mirrors :mod:`datalab.objectmodel`) and exposes thin
helpers callable from JavaScript through the Pyodide bridge.
The model is hierarchical: a :class:`_Panel` (one per object kind, e.g.
``"signal"``) holds an ordered list of :class:`_Group` instances, each
holding an ordered list of objects. Identifiers are short hex strings.
Feature catalogue & processing dispatch live in :mod:`dlw_processor`,
loaded into Pyodide's filesystem by ``runtime.ts`` before this module is
executed.
The module is re-executable: the Vite Python HMR plugin re-runs this file
when it changes. We therefore preserve the live :data:`_MODEL` and
:data:`_CATALOG` so user data is not wiped when only helpers change.
"""
# bootstrap.py introspects its own ``ObjectModel`` internals (``_panels``,
# ``_objects``) when serialising/deserialising HDF5 workspaces — the ``noqa:
# SLF001`` markers already document each access for ruff. The HDF5 helpers
# also lazily import heavy optional dependencies (``os``, ``tempfile``,
# ``re``, ``guidata.io``…) inside the function body so the module loads
# fast in Pyodide. ``except Exception`` is the desktop-DataLab convention
# for "best-effort H5 read; never abort on a malformed dataset".
# pylint: disable=protected-access,import-outside-toplevel,broad-exception-caught
from __future__ import annotations
import uuid
from dataclasses import dataclass, field
from typing import Any, Iterable
import dlw_interactive_fit as _ifit
# ``dlw_processor`` / ``dlw_interactive_fit`` / ``dlw_h5browser`` are
# sibling modules pushed into Pyodide's filesystem alongside this one;
# pylint sees them as third-party because they live outside any package.
# pylint: disable=wrong-import-order,ungrouped-imports,import-error
# NOTE on locale / translations:
# ``runtime.ts`` (and ``macroWorker.ts`` for the macro Pyodide instance)
# pin ``os.environ["LANG"] = "C"`` *before* this module — and before any
# ``guidata`` import — so that all ``gettext _()``-wrapped labels coming
# from ``sigima`` / ``guidata`` (e.g. ``SignalTypes.label``,
# ``ImageTypes.label``, processing names, parameter labels…) are
# returned in English and stay consistent with the English-only React
# UI. Do NOT set ``LANG`` here: ``guidata.configtools.get_translation``
# caches the translation object at first import, so any change made
# from this module would already be too late. See the
# "Internationalisation" section of ``README.md`` for the long-term
# multi-language perspective.
import dlw_processor as _proc
# ``dlw_title_format`` installs Sigima's ``PlaceholderTitleFormatter`` as
# the default. Imported for its side-effect; the actual substitution of
# placeholders with source-object short IDs is done by
# :func:`patch_title_with_ids` below, invoked from :func:`apply_feature`.
import dlw_title_format # noqa: F401 # pylint: disable=unused-import
import numpy as np
import sigima
from sigima.objects import SignalObj
from sigima.objects.signal.creation import (
SIGNAL_TYPE_PARAM_CLASSES,
SignalTypes,
create_signal_parameters,
)
from sigima.objects.signal.roi import SignalROI
# Re-export interactive-fit helpers as module-level callables so the JS
# runtime can resolve them via ``py.globals.get(...)``.
list_interactive_fits = _ifit.list_interactive_fits
init_interactive_fit = _ifit.init_interactive_fit
evaluate_interactive_fit = _ifit.evaluate_interactive_fit
auto_fit_interactive = _ifit.auto_fit_interactive
commit_interactive_fit = _ifit.commit_interactive_fit
# ---------------------------------------------------------------------------
# Object model
# ---------------------------------------------------------------------------
def _new_id(prefix: str = "") -> str:
"""Return a short, unique identifier (optionally prefixed)."""
return f"{prefix}{uuid.uuid4().hex[:8]}"
@dataclass
class _ObjectEntry:
"""One object stored in the model."""
oid: str
kind: str # "signal" (later: "image", ...)
obj: Any # SignalObj for now
@dataclass
class _Group:
"""A group of objects (mirrors DataLab's ``ObjectGroup``)."""
gid: str
name: str
object_ids: list[str] = field(default_factory=list)
@dataclass
class _Panel:
"""A panel groups objects of a given kind into ordered groups."""
kind: str
groups: list[_Group] = field(default_factory=list)
default_group_name: str = "Group"
def ensure_default_group(self) -> _Group:
"""Return the first group, creating one when the panel is empty."""
if not self.groups:
self.groups.append(
_Group(gid=_new_id("g"), name=f"{self.default_group_name} 1")
)
return self.groups[0]
def find_group(self, gid: str) -> _Group:
"""Return the group with id *gid* (raises :class:`KeyError`)."""
for g in self.groups:
if g.gid == gid:
return g
raise KeyError(f"Unknown group: {gid!r}")
def find_group_of(self, oid: str) -> _Group:
"""Return the group containing object *oid*."""
for g in self.groups:
if oid in g.object_ids:
return g
raise KeyError(f"Object {oid!r} not in panel {self.kind!r}")
class ObjectModel:
"""Hierarchical object model.
Mirrors :class:`datalab.objectmodel.ObjectModel` in the desktop app:
each panel (signal, image, ...) owns ordered groups holding objects.
"""
def __init__(self) -> None:
self._panels: dict[str, _Panel] = {}
self._objects: dict[str, _ObjectEntry] = {}
# -- Panel access -------------------------------------------------------
def panel(self, kind: str) -> _Panel:
"""Return (creating on first access) the panel for *kind*."""
if kind not in self._panels:
self._panels[kind] = _Panel(kind=kind)
return self._panels[kind]
# -- Object access ------------------------------------------------------
def get(self, oid: str) -> Any:
"""Return the object identified by *oid*."""
return self._objects[oid].obj
def kind_of(self, oid: str) -> str:
"""Return the panel kind hosting object *oid*."""
return self._objects[oid].kind
def has(self, oid: str) -> bool:
"""Return True if *oid* is a known object id."""
return oid in self._objects
# -- Object mutation ----------------------------------------------------
def add_object(self, kind: str, obj: Any, group_id: str | None = None) -> str:
"""Insert *obj* in *kind*'s panel (in *group_id* or default group)."""
panel = self.panel(kind)
group = panel.find_group(group_id) if group_id else panel.ensure_default_group()
oid = _new_id()
self._objects[oid] = _ObjectEntry(oid=oid, kind=kind, obj=obj)
group.object_ids.append(oid)
return oid
def delete_object(self, oid: str) -> None:
"""Remove object *oid* from its panel (silent no-op if absent)."""
if oid not in self._objects:
return
kind = self._objects[oid].kind
self._objects.pop(oid)
panel = self.panel(kind)
for g in panel.groups:
if oid in g.object_ids:
g.object_ids.remove(oid)
break
def move_object(
self, oid: str, target_group_id: str, target_index: int = -1
) -> None:
"""Move object *oid* to *target_group_id* within its panel.
*target_index* is the insertion position in the destination group,
computed **after** the object has been removed from its source group.
Use ``-1`` (default) to append at the end. The index is clamped to
the valid range; same-group reorders are supported.
"""
self.move_objects([oid], target_group_id, target_index)
def move_objects(
self, oids: list[str], target_group_id: str, target_index: int = -1
) -> None:
"""Move multiple objects to *target_group_id*, preserving *oids* order.
All *oids* must belong to the same panel kind. *target_index* is
the insertion position in the destination group, computed **after**
all moved objects have been removed from their current groups
(use ``-1`` to append at the end). No-op when *oids* is empty.
"""
if not oids:
return
kind = self._objects[oids[0]].kind
panel = self.panel(kind)
target = panel.find_group(target_group_id)
moved = set(oids)
# Compute insertion index relative to the target group *after* removal
# of moved objects (so callers can pass the visible drop position).
target_remaining = [x for x in target.object_ids if x not in moved]
if target_index < 0 or target_index > len(target_remaining):
insert_at = len(target_remaining)
else:
insert_at = target_index
# Remove moved objects from every group of the panel.
for g in panel.groups:
if any(x in moved for x in g.object_ids):
g.object_ids = [x for x in g.object_ids if x not in moved]
# Insert at the computed position, preserving caller-provided order.
target.object_ids[insert_at:insert_at] = list(oids)
def move_object_in_group(self, oid: str, delta: int) -> None:
"""Reorder object *oid* within its current group by *delta*.
``delta = -1`` moves the object one slot up, ``+1`` moves it one slot
down. The operation is clamped so the object never falls outside the
group bounds (silent no-op when already at the boundary).
"""
if delta == 0:
return
kind = self._objects[oid].kind
panel = self.panel(kind)
group = panel.find_group_of(oid)
idx = group.object_ids.index(oid)
new_idx = max(0, min(len(group.object_ids) - 1, idx + delta))
if new_idx == idx:
return
group.object_ids.remove(oid)
group.object_ids.insert(new_idx, oid)
def duplicate_object(self, oid: str) -> str:
"""Insert a deep copy of object *oid* right after it in its group."""
entry = self._objects[oid]
new_obj = entry.obj.copy()
new_oid = _new_id()
self._objects[new_oid] = _ObjectEntry(oid=new_oid, kind=entry.kind, obj=new_obj)
panel = self.panel(entry.kind)
group = panel.find_group_of(oid)
idx = group.object_ids.index(oid)
group.object_ids.insert(idx + 1, new_oid)
return new_oid
def rename_object(self, oid: str, name: str) -> None:
"""Rename object *oid* in place."""
obj = self._objects[oid].obj
obj.title = name
# -- Group mutation -----------------------------------------------------
def create_group(self, kind: str, name: str | None = None) -> str:
"""Create a new group on *kind* and return its gid."""
panel = self.panel(kind)
if name is None:
name = f"{panel.default_group_name} {len(panel.groups) + 1}"
gid = _new_id("g")
panel.groups.append(_Group(gid=gid, name=name))
return gid
def rename_group(self, kind: str, gid: str, name: str) -> None:
"""Rename group *gid* of *kind* in place."""
self.panel(kind).find_group(gid).name = name
def delete_group(self, kind: str, gid: str) -> None:
"""Delete group *gid* of *kind* and all its objects."""
panel = self.panel(kind)
group = panel.find_group(gid)
for oid in list(group.object_ids):
self.delete_object(oid)
panel.groups.remove(group)
# Always keep at least one group available for fresh additions.
panel.ensure_default_group()
# -- Serialisation ------------------------------------------------------
def panel_tree(self, kind: str) -> dict[str, Any]:
"""Return the JSON-friendly tree of groups and objects for *kind*."""
panel = self.panel(kind)
panel.ensure_default_group()
return {
"kind": kind,
"groups": [
{
"gid": g.gid,
"name": g.name,
"objects": [
{"id": oid, **_object_meta(self._objects[oid])}
for oid in g.object_ids
if oid in self._objects
],
}
for g in panel.groups
],
}
def iter_all(self, kind: str) -> Iterable[tuple[str, Any]]:
"""Iterate over ``(oid, obj)`` pairs of *kind*."""
for entry in self._objects.values():
if entry.kind == kind:
yield entry.oid, entry.obj
def _object_meta(entry: _ObjectEntry) -> dict[str, Any]:
"""Return JSON-friendly metadata for *entry*."""
obj = entry.obj
if entry.kind == "signal":
return {
"kind": "signal",
"uuid": getattr(obj, "uuid", None),
"title": obj.title,
"size": int(obj.x.size),
"xlabel": obj.xlabel or "",
"ylabel": obj.ylabel or "",
"xunit": obj.xunit or "",
"yunit": obj.yunit or "",
"style": _signal_style(obj),
}
if entry.kind == "image":
h, w = obj.data.shape[:2]
return {
"kind": "image",
"uuid": getattr(obj, "uuid", None),
"title": obj.title,
"size": int(w * h),
"width": int(w),
"height": int(h),
"xlabel": obj.xlabel or "",
"ylabel": obj.ylabel or "",
"xunit": obj.xunit or "",
"yunit": obj.yunit or "",
}
return {"kind": entry.kind, "title": getattr(obj, "title", "")}
def _signal_style(obj: Any) -> dict[str, Any]:
"""Extract optional per-curve style from a SignalObj's metadata.
Sigima/PlotPy persist ``color`` / ``linestyle`` / ``linewidth`` (and
a few sibling keys) under the object's ``metadata`` dict so they
survive copy/save/restore. Missing fields are returned as ``None``
so the front-end can fall back to the cycling palette.
"""
md = getattr(obj, "metadata", None) or {}
color = md.get("color") or md.get("curvecolor")
linestyle = md.get("linestyle") or md.get("line_style")
linewidth = md.get("linewidth") or md.get("line_width")
curvestyle = md.get("curvestyle") or md.get("curve_style")
try:
linewidth = float(linewidth) if linewidth is not None else None
except (TypeError, ValueError):
linewidth = None
return {
"color": str(color) if color else None,
"linestyle": str(linestyle) if linestyle else None,
"linewidth": linewidth,
"curvestyle": str(curvestyle) if curvestyle else None,
}
def _build_full_catalog() -> dict[str, _proc.FeatureSpec]:
"""Merge signal and image curated catalogs into a single dict.
Image features are namespaced under ``"image:"`` to avoid id
collisions with same-named signal features.
"""
catalog: dict[str, _proc.FeatureSpec] = {}
for fid, spec in _proc.build_signal_catalog().items():
catalog[fid] = spec
for fid, spec in _proc.build_image_catalog().items():
new_id = f"image:{fid}"
# Reflect the prefix so the front-end uses it consistently.
catalog[new_id] = _proc.FeatureSpec(
feature_id=new_id,
label=spec.label,
menu_path=spec.menu_path,
pattern=spec.pattern,
icon=spec.icon,
operand_label=spec.operand_label,
paramclass=spec.paramclass,
func=spec.func,
object_kind=spec.object_kind,
skip_xarray_compat=spec.skip_xarray_compat,
output_kind=spec.output_kind,
)
return catalog
# Preserve the live model & catalogue across HMR re-executions of this file.
_MODEL: ObjectModel = globals().get("_MODEL", ObjectModel()) # type: ignore[assignment]
_CATALOG: dict[str, _proc.FeatureSpec] = globals().get(
"_CATALOG", _build_full_catalog()
)
_PROCESSOR: _proc.BaseProcessor = globals().get(
"_PROCESSOR", _proc.BaseProcessor("signal")
)
# ---------------------------------------------------------------------------
# Macro store (mirrors DataLab Qt's MacroPanel state)
# ---------------------------------------------------------------------------
# In-memory list of macros: ``[{"id": str, "title": str, "code": str}, ...]``.
# Order matters (mirrors Qt tab order) — preserved across HMR re-executions.
_MACROS: list[dict[str, str]] = globals().get("_MACROS", []) # type: ignore[assignment]
_MACRO_SAMPLE_TITLE = "Untitled 1"
_MACRO_SAMPLE_CODE = """# Macro simple example
import numpy as np
# `proxy` is pre-injected (DataLab-Web equivalent of RemoteProxy).
# All proxy methods are async — use `await`.
# Available methods: add_signal, add_image, calc, get_object,
# list_signals, list_images, set_current_panel, call_method, ...
x = np.linspace(-10, 10, 500)
y = np.sin(x) / (x + 1e-9)
oid = await proxy.add_signal("sinc", x, y)
print(f"Created signal {oid}")
print("All done!")
"""
def _macro_index(macro_id: str) -> int:
for idx, m in enumerate(_MACROS):
if m["id"] == macro_id:
return idx
raise KeyError(f"Unknown macro: {macro_id!r}")
def _next_untitled_title() -> str:
"""Return a unique ``"Untitled N"`` title."""
used = {m["title"] for m in _MACROS}
n = 1
while f"Untitled {n}" in used:
n += 1
return f"Untitled {n}"
def list_macros() -> list[dict[str, str]]:
"""Return a JSON-friendly snapshot of every macro (id + title only)."""
return [{"id": m["id"], "title": m["title"]} for m in _MACROS]
def get_macro(macro_id: str) -> dict[str, str]:
"""Return ``{id, title, code}`` for *macro_id*."""
return dict(_MACROS[_macro_index(macro_id)])
def create_macro(title: str | None = None, code: str | None = None) -> dict[str, str]:
"""Create a new macro and return its full record."""
new_title = title if title else _next_untitled_title()
new_code = code if code is not None else _MACRO_SAMPLE_CODE
record = {"id": _new_id("m"), "title": new_title, "code": new_code}
_MACROS.append(record)
return dict(record)
def set_macro_code(macro_id: str, code: str) -> None:
"""Update the code of *macro_id*."""
_MACROS[_macro_index(macro_id)]["code"] = code
def rename_macro(macro_id: str, title: str) -> None:
"""Rename macro *macro_id*."""
_MACROS[_macro_index(macro_id)]["title"] = title or "Untitled"
def delete_macro(macro_id: str) -> None:
"""Remove macro *macro_id* from the store."""
_MACROS.pop(_macro_index(macro_id))
def duplicate_macro(macro_id: str) -> dict[str, str]:
"""Insert a copy of *macro_id* right after it; return the new record."""
idx = _macro_index(macro_id)
src = _MACROS[idx]
record = {
"id": _new_id("m"),
"title": f"{src['title']} (copy)",
"code": src["code"],
}
_MACROS.insert(idx + 1, record)
return dict(record)
def reorder_macros(macro_ids: Any) -> None:
"""Reorder ``_MACROS`` according to *macro_ids* (must contain every id)."""
if hasattr(macro_ids, "to_py"):
macro_ids = macro_ids.to_py()
new_order: list[dict[str, str]] = []
by_id = {m["id"]: m for m in _MACROS}
for mid in macro_ids:
if mid in by_id:
new_order.append(by_id.pop(mid))
# Append any leftovers (defensive — should not happen).
new_order.extend(by_id.values())
_MACROS[:] = new_order
def replace_macros(records: Any) -> None:
"""Replace the whole macro store (used for localStorage restore)."""
if hasattr(records, "to_py"):
records = records.to_py()
cleaned: list[dict[str, str]] = []
for rec in records or []:
rid = str(rec.get("id") or _new_id("m"))
title = str(rec.get("title") or "Untitled")
code = str(rec.get("code") or "")
cleaned.append({"id": rid, "title": title, "code": code})
_MACROS[:] = cleaned
# ---------------------------------------------------------------------------
# Notebook store (mirrors :data:`_MACROS` for Jupyter-style notebooks)
# ---------------------------------------------------------------------------
#
# Notebooks are stored as opaque ``nbformat`` v4.5 JSON strings — the
# Python side does not parse them. This keeps the bootstrap layer
# symmetric with macros (``code`` ⇄ ``content``) and lets the JS
# notebook UI remain the sole owner of the nbformat schema.
_NOTEBOOKS: list[dict[str, str]] = globals().get( # type: ignore[assignment]
"_NOTEBOOKS", []
)
def _notebook_index(notebook_id: str) -> int:
for idx, n in enumerate(_NOTEBOOKS):
if n["id"] == notebook_id:
return idx
raise KeyError(f"Unknown notebook: {notebook_id!r}")
def _next_untitled_notebook_title() -> str:
"""Return a unique ``"Untitled N"`` notebook title."""
used = {n["title"] for n in _NOTEBOOKS}
n = 1
while f"Untitled {n}" in used:
n += 1
return f"Untitled {n}"
def list_notebooks() -> list[dict[str, str]]:
"""Return a JSON-friendly snapshot of every notebook (id + title only)."""
return [{"id": n["id"], "title": n["title"]} for n in _NOTEBOOKS]
def get_notebook(notebook_id: str) -> dict[str, str]:
"""Return ``{id, title, content}`` for *notebook_id*."""
return dict(_NOTEBOOKS[_notebook_index(notebook_id)])
def create_notebook(
title: str | None = None, content: str | None = None
) -> dict[str, str]:
"""Create a new notebook and return its full record.
*content* must be a serialised nbformat v4.5 JSON string. When
omitted, an empty string is stored — the JS layer is then expected
to push an initial template via :func:`set_notebook_content`.
"""
new_title = title if title else _next_untitled_notebook_title()
new_content = content if content is not None else ""
record = {"id": _new_id("n"), "title": new_title, "content": new_content}
_NOTEBOOKS.append(record)
return dict(record)
def set_notebook_content(notebook_id: str, content: str) -> None:
"""Update the nbformat JSON content of *notebook_id*."""
_NOTEBOOKS[_notebook_index(notebook_id)]["content"] = content
def rename_notebook(notebook_id: str, title: str) -> None:
"""Rename notebook *notebook_id*."""
_NOTEBOOKS[_notebook_index(notebook_id)]["title"] = title or "Untitled"
def delete_notebook(notebook_id: str) -> None:
"""Remove notebook *notebook_id* from the store."""
_NOTEBOOKS.pop(_notebook_index(notebook_id))
def duplicate_notebook(notebook_id: str) -> dict[str, str]:
"""Insert a copy of *notebook_id* right after it; return the new record."""
idx = _notebook_index(notebook_id)
src = _NOTEBOOKS[idx]
record = {
"id": _new_id("n"),
"title": f"{src['title']} (copy)",
"content": src["content"],
}
_NOTEBOOKS.insert(idx + 1, record)
return dict(record)
def reorder_notebooks(notebook_ids: Any) -> None:
"""Reorder ``_NOTEBOOKS`` according to *notebook_ids* (must contain every id)."""
if hasattr(notebook_ids, "to_py"):
notebook_ids = notebook_ids.to_py()
new_order: list[dict[str, str]] = []
by_id = {n["id"]: n for n in _NOTEBOOKS}
for nid in notebook_ids:
if nid in by_id:
new_order.append(by_id.pop(nid))
# Append any leftovers (defensive — should not happen).
new_order.extend(by_id.values())
_NOTEBOOKS[:] = new_order
def replace_notebooks(records: Any) -> None:
"""Replace the whole notebook store (used for IndexedDB restore)."""
if hasattr(records, "to_py"):
records = records.to_py()
cleaned: list[dict[str, str]] = []
for rec in records or []:
rid = str(rec.get("id") or _new_id("n"))
title = str(rec.get("title") or "Untitled")
content = str(rec.get("content") or "")
cleaned.append({"id": rid, "title": title, "content": content})
_NOTEBOOKS[:] = cleaned
# ---------------------------------------------------------------------------
# Plugin system bootstrap
# ---------------------------------------------------------------------------
def _plugin_features_for_kind(kind: str) -> dict[str, _proc.FeatureSpec]:
"""Return ``{feature_id: FeatureSpec}`` for plugin contributions."""
return _proc.merge_plugin_features({}, kind)
def _full_catalog_with_plugins() -> dict[str, _proc.FeatureSpec]:
"""Return the curated catalogue augmented with plugin features."""
cat = dict(_CATALOG)
for kind in ("signal", "image"):
cat.update(_plugin_features_for_kind(kind))
return cat
# JavaScript dialog bridge — set by ``runtime.ts`` via ``set_dialog_bridge``.
# Signature: ``async (kind: str, payload: dict) -> Any``.
_DIALOG_BRIDGE: Any = globals().get("_DIALOG_BRIDGE", None)
def set_dialog_bridge(bridge: Any) -> None:
"""Install the JS bridge used by async guidata/datalab dialogs."""
global _DIALOG_BRIDGE # pylint: disable=global-statement # singleton bridge
_DIALOG_BRIDGE = bridge
def _require_bridge(slot: str) -> Any:
if _DIALOG_BRIDGE is None:
raise RuntimeError(
f"Dialog bridge missing — cannot service {slot!r}. "
"Call sigima.setDialogHandler(...) on the JS side first."
)
return _DIALOG_BRIDGE
def _to_js_payload(payload: dict) -> Any:
"""Convert *payload* to a plain JS object before crossing the bridge.
Without this, Pyodide hands JS a ``PyProxy`` of the dict. The JS bridge
then converts + destroys the proxy explicitly, but Pyodide's
``FinalizationRegistry`` still tries to register the same proxy on the
next GC cycle — finding it destroyed and aborting the WASM runtime
("Object has already been destroyed", from ``gc_register_proxies``).
Converting on the Python side avoids any PyProxy ever existing on JS.
"""
try:
from js import Object # type: ignore[import-not-found]
from pyodide.ffi import to_js # type: ignore[import-not-found]
except Exception: # pragma: no cover - non-Pyodide environments (tests)
return payload
return to_js(payload, dict_converter=Object.fromEntries)
async def _async_edit_dataset(
instance: Any, parent: Any = None, **_kwargs: Any
) -> bool:
"""Async :meth:`DataSet.edit` handler routed through the JS bridge."""
del parent # signature compat with guidata's sync ``edit`` API
from guidata.dataset import dataset_to_schema_with_values, update_dataset
bridge = _require_bridge("edit_dataset_async")
payload = dataset_to_schema_with_values(instance)
payload["title"] = getattr(instance, "_title", None) or type(instance).__name__
result = await bridge("edit_dataset", _to_js_payload(payload))
if hasattr(result, "to_py"):
result = result.to_py()
if not result:
return False
update_dataset(instance, result)
return True
async def _async_show_message(
kind: str, message: str, title: str | None = None, **_kwargs: Any
) -> None:
bridge = _require_bridge("show_message_async")
await bridge(
"message",
_to_js_payload({"kind": kind, "message": message, "title": title or ""}),
)
async def _async_ask_question(
message: str, title: str | None = None, cancelable: bool = False, **_kwargs: Any
) -> bool | None:
bridge = _require_bridge("ask_question_async")
result = await bridge(
"confirm",
_to_js_payload(
{
"message": message,
"title": title or "",
"cancelable": bool(cancelable),
}
),
)
if hasattr(result, "to_py"):
result = result.to_py()
return result
def _install_datalab_shim() -> None:
"""Wire the portable ``datalab.*`` shim to the live bootstrap.
Idempotent — safe to call from HMR re-execution. Installs:
* the ``WebMainBridge`` into :class:`datalab.gui.main.DLMainWindow`;
* the async dialog handlers into the guidata + datalab registries;
* the bridge into :mod:`dlw_plugins` so plugin ``register()`` works.
"""
try:
import dlw_main as _dlw_main
import dlw_plugins as _dlw_plugins
from datalab import helpers as _dl_helpers
from datalab.gui.main import install_main as _install_main
from guidata.dataset import backends as _gds_backends
except Exception: # pragma: no cover - shim missing in standalone tests
print("[bootstrap] datalab.* shim unavailable; plugins disabled")
return
bridge_main = _dlw_main.WebMainBridge()
main = _install_main(bridge_main)
_dlw_plugins.install_main(main)
# Async guidata backend
_gds_backends.set_handler("edit_dataset_async", _async_edit_dataset)
# Async datalab.helpers backend
_dl_helpers.set_handler("show_message_async", _async_show_message)
_dl_helpers.set_handler("ask_question_async", _async_ask_question)
# Install once per cold-start; re-installation is idempotent (handlers
# replace the previous ones), so HMR is safe.
_install_datalab_shim()
# ---------------------------------------------------------------------------
# Signal creation helpers
# ---------------------------------------------------------------------------
def create_signal(
kind: str,
title: str,
size: int,
xmin: float,
xmax: float,
a: float = 1.0,
freq: float = 1.0,
phase: float = 0.0,
mu: float = 0.0,
sigma: float = 1.0,
group_id: str | None = None,
) -> str:
"""Create a synthetic signal and store it.
Args:
kind: One of ``"sine"``, ``"cosine"``, ``"gauss"``, ``"noise"``.
title: Display name.
size: Number of samples.
xmin: X-axis lower bound.
xmax: X-axis upper bound.
a: Amplitude (sine/cosine/gauss).
freq: Frequency in Hz (sine/cosine).
phase: Phase in radians (sine/cosine).
mu: Mean (gauss).
sigma: Standard deviation (gauss).
group_id: Optional target group id; uses the default group if absent.
Returns:
The newly assigned object id.
"""
x = np.linspace(xmin, xmax, int(size))
if kind == "sine":
y = a * np.sin(2 * np.pi * freq * x + phase)
elif kind == "cosine":
y = a * np.cos(2 * np.pi * freq * x + phase)
elif kind == "gauss":
y = a * np.exp(-0.5 * ((x - mu) / sigma) ** 2)
elif kind == "noise":
rng = np.random.default_rng()
y = a * rng.standard_normal(int(size))
else:
raise ValueError(f"Unknown signal kind: {kind!r}")
obj: SignalObj = sigima.create_signal(title=title, x=x, y=y)
return _MODEL.add_object("signal", obj, group_id=group_id)
def _coerce_array(data: Any, dtype: Any) -> np.ndarray:
"""Convert a JS-side array payload into a 1-D numpy array.
Optimised for the bridge: when the JS side hands us a typed array
(Pyodide auto-converts ``Float64Array``/``Float32Array`` to
``memoryview``, ``Uint8Array`` to ``bytes``), we wrap it through
:func:`numpy.frombuffer` for a true zero-copy view. Plain JS
arrays (``number[]``) still work via the slow ``np.asarray`` path
so existing callers using nested lists are unaffected.
Args:
data: ``bytes``/``bytearray``/``memoryview`` (zero-copy),
a JsProxy with a ``to_py`` method (e.g. unconverted
``Float64Array``), or a Python iterable / list.
dtype: target numpy dtype. Must match the binary layout of
the input when the latter is a buffer.
"""
np_dtype = np.dtype(dtype)
# Buffer-like inputs -> zero-copy view.
if isinstance(data, (bytes, bytearray, memoryview)):
return np.frombuffer(data, dtype=np_dtype)
# Pyodide JsProxy of a TypedArray -> use ``.to_py()`` which returns
# a memoryview without copying the underlying WASM heap.
if hasattr(data, "to_py"):
try:
converted = data.to_py()
except Exception: # pragma: no cover - defensive only
converted = None
if isinstance(converted, memoryview):
arr = np.frombuffer(converted, dtype=np_dtype)
return arr
if converted is not None:
return np.asarray(converted, dtype=np_dtype)
# Last resort: plain Python list / iterable.
return np.asarray(data, dtype=np_dtype)
def add_signal_from_arrays(
title: str,
xdata,
ydata,
xunit: str = "",
yunit: str = "",
xlabel: str = "",
ylabel: str = "",
group_id: str | None = None,
dtype: str = "float64",
) -> str:
"""Create a signal from raw X / Y arrays and store it.
Used by the macro proxy bridge so the JS side can pass plain
nested lists / typed arrays without building Python source code.
Typed arrays (``Float64Array`` / ``Float32Array``) and ``bytes``
are converted via :func:`_coerce_array` for zero-copy ingest.
"""
x = _coerce_array(xdata, dtype)
y = _coerce_array(ydata, dtype)
obj: SignalObj = sigima.create_signal(title=title, x=x, y=y)
if xunit:
obj.xunit = xunit
if yunit:
obj.yunit = yunit
if xlabel:
obj.xlabel = xlabel
if ylabel:
obj.ylabel = ylabel
return _MODEL.add_object("signal", obj, group_id=group_id)
def add_image_from_array(
title: str,
data,
xunit: str = "",
yunit: str = "",
zunit: str = "",
xlabel: str = "",
ylabel: str = "",
zlabel: str = "",
group_id: str | None = None,
width: int | None = None,
height: int | None = None,
dtype: str = "float64",
) -> str:
"""Create an image from a raw 2D array and store it.
``data`` may be a Python nested list (legacy slow path), a JsProxy
of a nested array, or — for large transfers — a flat 1-D buffer
(``bytes`` / typed array) accompanied by ``width`` and ``height``.
The buffer mode is zero-copy and dramatically lowers the bandwidth
cost for large remote transfers.
"""
if width is not None and height is not None:
flat = _coerce_array(data, dtype)
if flat.size != width * height:
raise ValueError(
f"flat buffer size {flat.size} does not match width*height "
f"= {width * height}"
)
arr = flat.reshape((height, width))
else:
# Legacy nested-list path: accept JsProxy via .to_py() too.
if hasattr(data, "to_py"):
data = data.to_py()
arr = np.asarray(data, dtype=float)
obj = sigima.create_image(title=title, data=arr)
if xunit:
obj.xunit = xunit
if yunit:
obj.yunit = yunit
if zunit:
obj.zunit = zunit
if xlabel:
obj.xlabel = xlabel
if ylabel:
obj.ylabel = ylabel
if zlabel:
obj.zlabel = zlabel
return _MODEL.add_object("image", obj, group_id=group_id)
def get_signal_xy(oid: str, encoding: str = "list") -> dict[str, Any]:
"""Return the X / Y arrays of *oid* in JSON-friendly form.
Args:
oid: signal identifier in the in-memory store.
encoding: ``"list"`` (default) returns ``x``/``y`` as Python
lists (slow but JSON-trivial — kept for backwards compat).
``"bytes"`` returns ``x_bytes``/``y_bytes`` as raw
little-endian ``float64`` byte strings — Pyodide hands them
to JS as a single ``Uint8Array`` memcpy, which the front-end
decodes into a typed array. Use this on the remote bridge
for large signals: a 1 M-sample signal goes from ~50 MB of
intermediate JSON allocations to a single 8 MB memcpy.
"""
obj = _MODEL.get(oid)
payload: dict[str, Any] = {
"id": oid,
**_object_meta(_ObjectEntry(oid=oid, kind="signal", obj=obj)),
}
# Complex-valued Y arrays (e.g. raw FFT output) cannot be sent as
# plain ``float64`` to the JS side without losing information AND
# without crashing JS code that assumes ``y[i]`` is a number
# (``v.toPrecision`` etc.). Mirror NumPy/Plotly defaults: take the
# real part for both the ``list`` and ``bytes`` encodings. Sigima
# exposes the imaginary part separately when the user actually
# needs it (e.g. ``fft_imag``).
y_arr = obj.y
if np.iscomplexobj(y_arr):
y_arr = y_arr.real
if encoding == "bytes":
x_arr = np.ascontiguousarray(obj.x, dtype=np.float64)
y_arr = np.ascontiguousarray(y_arr, dtype=np.float64)
payload["x_bytes"] = x_arr.tobytes()
payload["y_bytes"] = y_arr.tobytes()
payload["dtype"] = "float64"
payload["size"] = int(x_arr.size)