dj-plotly-codecs 0.1.0__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.
@@ -0,0 +1,25 @@
1
+ """
2
+ dj-plotly-codecs: Plotly figure storage for DataJoint
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from ._version import version as __version__
8
+ from .codecs import (
9
+ EXTENSION,
10
+ PlotlyCodec,
11
+ PlotlyRef,
12
+ decode_plotly,
13
+ encode_plotly,
14
+ figure_to_dict,
15
+ )
16
+
17
+ __all__ = [
18
+ "EXTENSION",
19
+ "PlotlyCodec",
20
+ "PlotlyRef",
21
+ "__version__",
22
+ "decode_plotly",
23
+ "encode_plotly",
24
+ "figure_to_dict",
25
+ ]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,447 @@
1
+ """Plotly figure codec implementation for DataJoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import json
7
+ import math
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ from datajoint import DataJointError
13
+ from datajoint.builtin_codecs import SchemaCodec
14
+
15
+ EXTENSION = ".plotly.json"
16
+ _KEYS = frozenset({"data", "layout", "frames"})
17
+
18
+
19
+ def _plotly_io() -> Any:
20
+ """``plotly.io``, or None when plotly is not installed."""
21
+ try:
22
+ import plotly.io as pio # noqa: PLC0415
23
+ except ImportError:
24
+ return None
25
+ return pio
26
+
27
+
28
+ def _is_figure_object(value: Any) -> bool:
29
+ """True for a plotly ``Figure`` (anything with ``to_plotly_json``)."""
30
+ return callable(getattr(value, "to_plotly_json", None))
31
+
32
+
33
+ def _check_figure_dict(figure: Mapping[str, Any]) -> None:
34
+ """Raise unless ``figure`` has the structure of a Plotly figure."""
35
+ unknown = sorted(str(k) for k in set(figure) - _KEYS)
36
+ if unknown:
37
+ msg = (
38
+ "<plotly> figures have the keys 'data', 'layout' and 'frames' only, "
39
+ f"got {unknown}"
40
+ )
41
+ raise DataJointError(msg)
42
+ data = figure.get("data")
43
+ if not isinstance(data, (list, tuple)):
44
+ msg = "<plotly> requires a figure with a 'data' list of traces"
45
+ raise DataJointError(msg)
46
+ if not all(isinstance(trace, Mapping) for trace in data):
47
+ msg = "<plotly> requires every trace in 'data' to be a dict"
48
+ raise DataJointError(msg)
49
+ if not isinstance(figure.get("layout", {}), Mapping):
50
+ msg = "<plotly> requires the figure's 'layout' to be a dict"
51
+ raise DataJointError(msg)
52
+ if not isinstance(figure.get("frames", []), (list, tuple)):
53
+ msg = "<plotly> requires the figure's 'frames' to be a list"
54
+ raise DataJointError(msg)
55
+
56
+
57
+ def figure_to_dict(figure: Any) -> dict[str, Any]:
58
+ """
59
+ Return a figure as a plain dict, checking that it is one.
60
+
61
+ Parameters
62
+ ----------
63
+ figure : plotly.graph_objects.Figure or dict
64
+ A plotly ``Figure``, or a dict with a ``data`` list of traces and optional
65
+ ``layout`` and ``frames``, as ``Figure.to_plotly_json()`` returns.
66
+
67
+ Returns
68
+ -------
69
+ dict
70
+ The figure's ``data``, ``layout`` and ``frames``.
71
+
72
+ Raises
73
+ ------
74
+ DataJointError
75
+ If the value is not a figure.
76
+ """
77
+ if _is_figure_object(figure):
78
+ figure = figure.to_plotly_json()
79
+ elif not isinstance(figure, Mapping):
80
+ msg = (
81
+ "<plotly> requires a plotly Figure or a dict with 'data' and 'layout', "
82
+ f"got {type(figure).__name__}"
83
+ )
84
+ raise DataJointError(msg)
85
+ _check_figure_dict(figure)
86
+ return dict(figure)
87
+
88
+
89
+ def _jsonable(value: Any) -> Any:
90
+ """Plain JSON values, as plotly writes them: arrays as lists, NaN and inf as null."""
91
+ if value is None or isinstance(value, (str, bool, int)):
92
+ return value
93
+ if isinstance(value, float):
94
+ return value if math.isfinite(value) else None
95
+ if isinstance(value, Mapping):
96
+ return {str(k): _jsonable(v) for k, v in value.items()}
97
+ if isinstance(value, (list, tuple)):
98
+ return [_jsonable(v) for v in value]
99
+ if isinstance(value, np.ndarray):
100
+ return _jsonable(value.tolist())
101
+ if isinstance(value, np.generic):
102
+ return _jsonable(value.item())
103
+ if isinstance(value, (dt.datetime, dt.date, dt.time)):
104
+ return value.isoformat()
105
+ msg = f"<plotly> cannot store a value of type {type(value).__name__} in a figure"
106
+ raise DataJointError(msg)
107
+
108
+
109
+ def encode_plotly(figure: Any) -> bytes:
110
+ """
111
+ Encode a Plotly figure as the bytes of a JSON file.
112
+
113
+ With plotly installed, the figure is validated and serialized by
114
+ ``plotly.io.to_json``, as ``Figure.write_json`` writes it. Without plotly, a dict
115
+ figure is checked for its structure and written as plain JSON: numpy arrays as
116
+ lists, NaN and infinity as ``null``, dates and times as ISO 8601 strings.
117
+
118
+ Parameters
119
+ ----------
120
+ figure : plotly.graph_objects.Figure or dict
121
+ The figure.
122
+
123
+ Returns
124
+ -------
125
+ bytes
126
+ A UTF-8 JSON file that Plotly reads with ``plotly.io.read_json`` and renders
127
+ in a browser with ``Plotly.newPlot``.
128
+
129
+ Raises
130
+ ------
131
+ DataJointError
132
+ If the value is not a figure, or plotly finds it invalid.
133
+ """
134
+ as_dict = figure_to_dict(figure)
135
+ pio = _plotly_io()
136
+ if pio is None:
137
+ text = json.dumps(_jsonable(as_dict), separators=(",", ":"), allow_nan=False)
138
+ else:
139
+ try:
140
+ text = pio.to_json(figure if _is_figure_object(figure) else as_dict)
141
+ except ValueError as e:
142
+ msg = f"<plotly> invalid figure: {e}"
143
+ raise DataJointError(msg) from e
144
+ return text.encode()
145
+
146
+
147
+ def decode_plotly(data: bytes) -> dict[str, Any]:
148
+ """
149
+ Decode the bytes of a figure's JSON file.
150
+
151
+ Parameters
152
+ ----------
153
+ data : bytes
154
+ A JSON file written by :func:`encode_plotly` or by plotly's ``write_json``.
155
+
156
+ Returns
157
+ -------
158
+ dict
159
+ The figure's ``data``, ``layout`` and ``frames``.
160
+
161
+ Raises
162
+ ------
163
+ DataJointError
164
+ If the file is not JSON or not a figure.
165
+ """
166
+ try:
167
+ figure = json.loads(data)
168
+ except ValueError as e:
169
+ msg = f"<plotly> file is not JSON: {e}"
170
+ raise DataJointError(msg) from e
171
+ if not isinstance(figure, dict):
172
+ msg = "<plotly> file is not a figure"
173
+ raise DataJointError(msg)
174
+ _check_figure_dict(figure)
175
+ return figure
176
+
177
+
178
+ def _summary(figure: Mapping[str, Any]) -> dict[str, Any]:
179
+ """What the row records about a figure: its traces, their types, and its title."""
180
+ types = [str(trace.get("type", "scatter")) for trace in figure["data"]]
181
+ title = figure.get("layout", {}).get("title")
182
+ if isinstance(title, Mapping):
183
+ title = title.get("text")
184
+ return {
185
+ "traces": len(types),
186
+ "trace_types": list(dict.fromkeys(types)),
187
+ "title": title if isinstance(title, str) else None,
188
+ }
189
+
190
+
191
+ class PlotlyRef:
192
+ """
193
+ Lazy reference to a Plotly figure stored as a ``.plotly.json`` file.
194
+
195
+ The number of traces, their types, the title, and the file's size are known
196
+ without downloading the file. :meth:`load` downloads it and returns the figure
197
+ as a dict; :meth:`to_figure` returns a plotly ``Figure``.
198
+ """
199
+
200
+ __slots__ = ("_backend", "_cached", "_meta")
201
+
202
+ def __init__(self, metadata: dict[str, Any], backend: Any) -> None:
203
+ """
204
+ Initialize from the row's metadata and the storage backend.
205
+
206
+ Parameters
207
+ ----------
208
+ metadata : dict
209
+ JSON metadata: ``{path, store, size, traces, trace_types, title}``.
210
+ backend : StorageBackend
211
+ Storage backend for file operations.
212
+ """
213
+ self._meta = metadata
214
+ self._backend = backend
215
+ self._cached: dict[str, Any] | None = None
216
+
217
+ @property
218
+ def path(self) -> str:
219
+ """Storage path within the store."""
220
+ return str(self._meta["path"])
221
+
222
+ @property
223
+ def store(self) -> str | None:
224
+ """Store name (None for the default store)."""
225
+ store = self._meta.get("store")
226
+ return None if store is None else str(store)
227
+
228
+ @property
229
+ def size(self) -> int:
230
+ """Size of the JSON file in bytes (no I/O required)."""
231
+ return int(self._meta["size"])
232
+
233
+ @property
234
+ def traces(self) -> int:
235
+ """Number of traces (no I/O required)."""
236
+ return int(self._meta["traces"])
237
+
238
+ @property
239
+ def trace_types(self) -> list[str]:
240
+ """Trace types, each once, in order of appearance (no I/O required)."""
241
+ return list(self._meta["trace_types"])
242
+
243
+ @property
244
+ def title(self) -> str | None:
245
+ """The figure's title, if it has one (no I/O required)."""
246
+ title = self._meta.get("title")
247
+ return None if title is None else str(title)
248
+
249
+ @property
250
+ def is_loaded(self) -> bool:
251
+ """True if the figure has been downloaded and cached."""
252
+ return self._cached is not None
253
+
254
+ def load(self) -> dict[str, Any]:
255
+ """
256
+ Download, decode, and return the figure.
257
+
258
+ Returns
259
+ -------
260
+ dict
261
+ The figure's ``data``, ``layout`` and ``frames``, as JSON values. The
262
+ dict is cached: modify a copy.
263
+ """
264
+ if self._cached is None:
265
+ self._cached = decode_plotly(self._backend.get_buffer(self.path))
266
+ return self._cached
267
+
268
+ def to_figure(self) -> Any:
269
+ """
270
+ Return the figure as a plotly ``Figure``.
271
+
272
+ Returns
273
+ -------
274
+ plotly.graph_objects.Figure
275
+ A new figure built from :meth:`load`.
276
+
277
+ Raises
278
+ ------
279
+ DataJointError
280
+ If plotly is not installed.
281
+ """
282
+ try:
283
+ import plotly.graph_objects as go # noqa: PLC0415
284
+ except ImportError as e:
285
+ msg = "<plotly> to_figure() requires plotly: pip install 'dj-plotly-codecs[plotly]'"
286
+ raise DataJointError(msg) from e
287
+ return go.Figure(self.load())
288
+
289
+ def __repr__(self) -> str:
290
+ status = "loaded" if self.is_loaded else "not loaded"
291
+ return (
292
+ f"PlotlyRef(traces={self.traces}, trace_types={self.trace_types}, {status})"
293
+ )
294
+
295
+
296
+ def _require_context(context: dict[str, Any] | None, *names: str) -> dict[str, Any]:
297
+ """
298
+ Return ``context``, checked to carry ``names``.
299
+
300
+ DataJoint 2.3.4 and later pass ``context`` to every codec that declares it:
301
+ ``schema``, ``table``, ``field``, and ``config`` on insert, ``config`` on
302
+ fetch. The codec reads them there only, never from underscore keys in ``key``.
303
+ """
304
+ missing = [n for n in names if context is None or context.get(n) is None]
305
+ if context is None or missing:
306
+ msg = (
307
+ "<plotly> needs the context that DataJoint 2.3.4 and later pass to codecs "
308
+ f"(missing: {', '.join(missing)}); install datajoint>=2.3.4"
309
+ )
310
+ raise DataJointError(msg)
311
+ return context
312
+
313
+
314
+ def _primary_key(key: dict[str, Any] | None) -> dict[str, Any]:
315
+ """The primary key values in ``key``, without the underscore keys DataJoint 2.3 adds."""
316
+ return {k: v for k, v in (key or {}).items() if not k.startswith("_")}
317
+
318
+
319
+ class PlotlyCodec(SchemaCodec): # type: ignore[misc]
320
+ """
321
+ Schema-addressed storage for Plotly figures as ``.plotly.json`` files.
322
+
323
+ The ``<plotly@>`` codec stores a figure as the standard JSON file that Plotly
324
+ reads (``plotly.io.read_json``) and that ``Plotly.newPlot`` renders in a
325
+ browser, using the same schema-addressed paths as ``<npy@>``:
326
+ ``{schema_prefix}/{schema}/{table}/{pk}/{attribute}_{token}.plotly.json``.
327
+
328
+ Store only - requires ``@`` modifier. Installing ``dj-plotly-codecs``
329
+ registers ``<plotly@>`` with DataJoint through the ``datajoint.codecs``
330
+ entry point. Plotly itself is optional (``dj-plotly-codecs[plotly]``): it
331
+ validates figures on insert and builds ``Figure`` objects on fetch.
332
+
333
+ Accepted values:
334
+ - a ``plotly.graph_objects.Figure``
335
+ - a dict with a ``data`` list of traces and optional ``layout`` and
336
+ ``frames``, as ``Figure.to_plotly_json()`` returns
337
+
338
+ Anything else is refused, and so is a figure plotly finds invalid.
339
+
340
+ Example::
341
+
342
+ @schema
343
+ class TuningPlot(dj.Computed):
344
+ definition = '''
345
+ -> Tuning
346
+ ---
347
+ figure : <plotly@> # a figure any Plotly viewer renders
348
+ '''
349
+
350
+ def make(self, key):
351
+ fig = go.Figure(go.Scatter(x=angles, y=rates))
352
+ self.insert1({**key, "figure": fig})
353
+
354
+ ref = (TuningPlot & key).fetch1("figure") # PlotlyRef (lazy)
355
+ ref.traces, ref.trace_types, ref.title # no download
356
+ ref.to_figure().show() # downloads the file
357
+
358
+ Storage Details:
359
+ - File format: JSON, as ``Figure.write_json`` writes it
360
+ - Path: ``{schema_prefix}/{schema}/{table}/{pk}/{attribute}_{token}.plotly.json``
361
+ - Database column: JSON with ``{path, store, size, traces, trace_types, title}``
362
+
363
+ Deletion: Requires garbage collection via ``dj.gc.GarbageCollector``.
364
+
365
+ See Also
366
+ --------
367
+ PlotlyRef : The lazy figure reference returned on fetch.
368
+ """
369
+
370
+ name = "plotly"
371
+
372
+ def validate(self, value: Any) -> None:
373
+ """
374
+ Validate that value is a Plotly figure.
375
+
376
+ Raises
377
+ ------
378
+ DataJointError
379
+ If value is neither a plotly ``Figure`` nor a dict with the structure of
380
+ one.
381
+ """
382
+ figure_to_dict(value)
383
+
384
+ def encode(
385
+ self,
386
+ value: Any,
387
+ *,
388
+ key: dict[str, Any] | None = None,
389
+ context: dict[str, Any] | None = None,
390
+ store_name: str | None = None,
391
+ ) -> dict[str, Any]:
392
+ """
393
+ Encode the figure as JSON and upload it to storage.
394
+
395
+ Returns
396
+ -------
397
+ dict
398
+ JSON metadata: ``{path, store, size, traces, trace_types, title}``.
399
+
400
+ Raises
401
+ ------
402
+ DataJointError
403
+ If ``context`` lacks the ``schema``, ``table``, ``field``, or
404
+ ``config`` that DataJoint 2.3.4 and later pass.
405
+ """
406
+ context = _require_context(context, "schema", "table", "field", "config")
407
+ config = context["config"]
408
+ data = encode_plotly(value)
409
+ path, _ = self._build_path(
410
+ context["schema"],
411
+ context["table"],
412
+ context["field"],
413
+ _primary_key(key),
414
+ ext=EXTENSION,
415
+ store_name=store_name,
416
+ config=config,
417
+ )
418
+ backend = self._get_backend(store_name, config=config)
419
+ backend.put_buffer(data, path)
420
+ # Record the store by name; DataJoint 2.3 has no resolver and keeps None for the default store.
421
+ resolve = getattr(config, "resolve_store_name", None)
422
+ return {
423
+ "path": path,
424
+ "store": resolve(store_name) if resolve else store_name,
425
+ "size": len(data),
426
+ **_summary(decode_plotly(data)),
427
+ }
428
+
429
+ def decode(
430
+ self,
431
+ stored: dict[str, Any],
432
+ *,
433
+ key: dict[str, Any] | None = None,
434
+ context: dict[str, Any] | None = None,
435
+ ) -> PlotlyRef:
436
+ """
437
+ Create a lazy PlotlyRef from stored metadata.
438
+
439
+ Raises
440
+ ------
441
+ DataJointError
442
+ If ``context`` lacks the ``config`` that DataJoint 2.3.4 and later pass.
443
+ """
444
+ del key # the stored metadata locates the file
445
+ config = _require_context(context, "config")["config"]
446
+ backend = self._get_backend(stored.get("store"), config=config)
447
+ return PlotlyRef(stored, backend)
File without changes
@@ -0,0 +1,214 @@
1
+ Metadata-Version: 2.5
2
+ Name: dj-plotly-codecs
3
+ Version: 0.1.0
4
+ Summary: DataJoint codecs for storing Plotly figures as JSON files
5
+ Project-URL: Homepage, https://github.com/datajoint/dj-plotly-codecs
6
+ Project-URL: Repository, https://github.com/datajoint/dj-plotly-codecs
7
+ Project-URL: Documentation, https://github.com/datajoint/dj-plotly-codecs#readme
8
+ Project-URL: Bug Tracker, https://github.com/datajoint/dj-plotly-codecs/issues
9
+ Author-email: Dimitri Yatsenko <dimitri@datajoint.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: codec,datajoint,figure-storage,plotly
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Scientific/Engineering
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: datajoint>=2.3.4
28
+ Requires-Dist: numpy>=2.0
29
+ Provides-Extra: plotly
30
+ Requires-Dist: plotly>=5; extra == 'plotly'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # dj-plotly-codecs
34
+
35
+ DataJoint codecs for storing [Plotly](https://plotly.com/python/) figures as
36
+ JSON files with schema-addressed paths.
37
+
38
+ ## Overview
39
+
40
+ This package provides a DataJoint codec that stores Plotly figures as standard
41
+ Plotly JSON files in object storage, using DataJoint's schema-addressed storage
42
+ system. The stored file is the one `Figure.write_json` writes: Plotly reads it
43
+ back with `plotly.io.read_json`, and any page that loads Plotly's JavaScript
44
+ renders it with `Plotly.newPlot`. The `.plotly.json` file name and the codec
45
+ type tell tools that a column holds figures, not arbitrary JSON.
46
+
47
+ ## Features
48
+
49
+ - **Renderable files**: every stored figure is a standard Plotly JSON file
50
+ - **Validated**: with plotly installed, a figure is validated on insert
51
+ - **Lazy loading**: the number of traces, their types, the title, and the file
52
+ size are known without downloading the file
53
+ - **Plotly optional**: dict figures are stored without plotly installed; plotly
54
+ adds validation and `Figure` objects on fetch
55
+ - **Schema-addressed storage**: paths mirror the database structure
56
+ (`{schema}/{table}/{pk}/{field}_{token}.plotly.json`)
57
+ - **Automatic registration**: the codec is available after installation
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install "dj-plotly-codecs[plotly]"
63
+ ```
64
+
65
+ Requires Python 3.10 or later and `datajoint>=2.3.4`.
66
+
67
+ Without the `plotly` extra, the codec stores and loads dict figures, without
68
+ validation and without `Figure` objects.
69
+
70
+ ## Quick Start
71
+
72
+ ```python
73
+ import datajoint as dj
74
+ import plotly.graph_objects as go
75
+
76
+ schema = dj.Schema("my_schema")
77
+
78
+
79
+ @schema
80
+ class TuningPlot(dj.Manual):
81
+ definition = """
82
+ cell_id : int32
83
+ ---
84
+ figure : <plotly@> # a figure any Plotly viewer renders
85
+ """
86
+
87
+
88
+ fig = go.Figure(go.Scatter(x=[0, 45, 90, 135], y=[2.1, 5.3, 1.8, 0.9]))
89
+ fig.update_layout(title="Orientation tuning")
90
+ TuningPlot.insert1({"cell_id": 1, "figure": fig})
91
+
92
+ # Fetch returns a lazy reference
93
+ ref = (TuningPlot & {"cell_id": 1}).fetch1("figure")
94
+ print(ref.traces, ref.trace_types, ref.title) # 1 ['scatter'] Orientation tuning
95
+ ref.to_figure().show() # downloads the file; a plotly Figure
96
+ figure = ref.load() # the figure as a dict
97
+ ```
98
+
99
+ ## Configuration
100
+
101
+ Configure your object storage in DataJoint:
102
+
103
+ ```python
104
+ dj.config["stores"] = {
105
+ "mystore": {
106
+ "protocol": "s3",
107
+ "endpoint": "s3.amazonaws.com",
108
+ "bucket": "my-bucket",
109
+ "location": "datajoint",
110
+ }
111
+ }
112
+ ```
113
+
114
+ ## Codecs
115
+
116
+ ### `<plotly@>` / `<plotly@store>`
117
+
118
+ Store Plotly figures as `.plotly.json` files with schema-addressed paths.
119
+
120
+ **Accepted values:**
121
+
122
+ | value | stored as |
123
+ | ------------------------------------ | ---------------------------------------- |
124
+ | `plotly.graph_objects.Figure` | `plotly.io.to_json(figure)` |
125
+ | dict with `data`, `layout`, `frames` | validated by plotly when it is installed |
126
+
127
+ A dict figure has a `data` list of traces and optional `layout` and `frames`, as
128
+ `Figure.to_plotly_json()` returns. Anything else is refused rather than stored,
129
+ and so is a figure plotly finds invalid. With plotly installed, the file is
130
+ exactly what `Figure.write_json` writes; plotly 6 and later write numpy arrays
131
+ as base64 typed arrays, which Plotly.js 2.28 and later render. Without plotly
132
+ installed, a dict figure is written as plain JSON: numpy arrays as lists, NaN
133
+ and infinity as `null`, dates and times as ISO 8601 strings.
134
+
135
+ **On fetch**, a `PlotlyRef`:
136
+
137
+ | member | needs the file |
138
+ | ---------------------------------------- | ---------------- |
139
+ | `traces`, `trace_types`, `title`, `size` | no |
140
+ | `load()`: the figure as a dict | yes |
141
+ | `to_figure()`: a plotly `Figure` | yes (and plotly) |
142
+
143
+ **Usage:**
144
+
145
+ ```python
146
+ class MyTable(dj.Manual):
147
+ definition = """
148
+ id : int32
149
+ ---
150
+ figure : <plotly@> # Default store
151
+ summary : <plotly@s3> # Specific store
152
+ """
153
+ ```
154
+
155
+ ## Development
156
+
157
+ ### Setup
158
+
159
+ ```bash
160
+ git clone https://github.com/datajoint/dj-plotly-codecs.git
161
+ cd dj-plotly-codecs
162
+ pip install -e ".[plotly]"
163
+ ```
164
+
165
+ ### Testing
166
+
167
+ ```bash
168
+ pytest
169
+ ```
170
+
171
+ The database tests start MySQL in Docker through testcontainers and are skipped
172
+ when Docker is not available.
173
+
174
+ ### Code Style
175
+
176
+ This project uses [Ruff](https://docs.astral.sh/ruff/) for linting and
177
+ formatting:
178
+
179
+ ```bash
180
+ ruff check src tests
181
+ ruff format src tests
182
+ ```
183
+
184
+ ## Contributing
185
+
186
+ Contributions are welcome! Please:
187
+
188
+ 1. Fork the repository
189
+ 2. Create a feature branch
190
+ 3. Add tests for new functionality
191
+ 4. Ensure all tests pass
192
+ 5. Submit a pull request
193
+
194
+ ## License
195
+
196
+ Apache License 2.0. Copyright 2026 DataJoint Inc. See [LICENSE](LICENSE) for
197
+ details.
198
+
199
+ ## Related Projects
200
+
201
+ - [DataJoint](https://datajoint.com) - Framework for scientific data pipelines
202
+ - [dj-png-codecs](https://github.com/datajoint/dj-png-codecs) - DataJoint codecs
203
+ for images as PNG files
204
+ - [dj-zarr-codecs](https://github.com/datajoint/dj-zarr-codecs) - DataJoint
205
+ codecs for Zarr arrays
206
+ - [datajoint-python](https://github.com/datajoint/datajoint-python) - DataJoint
207
+ for Python
208
+
209
+ ## Documentation & Support
210
+
211
+ - [DataJoint Documentation](https://docs.datajoint.com) - Complete DataJoint
212
+ documentation
213
+ - [GitHub Issues](https://github.com/datajoint/dj-plotly-codecs/issues) - Report
214
+ bugs and request features
@@ -0,0 +1,9 @@
1
+ dj_plotly_codecs/__init__.py,sha256=rfK--3cLLo08qcahKAIbdu8JXYNrRgmGFVAGxe-kSvc,424
2
+ dj_plotly_codecs/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
3
+ dj_plotly_codecs/codecs.py,sha256=C7_yfKjjJi9QKxOEoYvAEozQ0wTnFpwBSLcI3uncsn8,14799
4
+ dj_plotly_codecs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ dj_plotly_codecs-0.1.0.dist-info/METADATA,sha256=r27ZSUNsP1j2uvg_34lXavJo97qqxmaMqA7IJssHj9M,6758
6
+ dj_plotly_codecs-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ dj_plotly_codecs-0.1.0.dist-info/entry_points.txt,sha256=zYaz3fTVUrkZLbsSZEhsYs0lpso6exs4CTHGUBf-3-A,57
8
+ dj_plotly_codecs-0.1.0.dist-info/licenses/LICENSE,sha256=oiwr9R90o13bPAXICOFr-y6YhML_005xM4adsn6qghc,10760
9
+ dj_plotly_codecs-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [datajoint.codecs]
2
+ plotly = dj_plotly_codecs:PlotlyCodec
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 DataJoint Inc.
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.