Skip to content

The figure vocabulary#

A bare [float, float, float, float] cannot say whether it is [xmin, xmax, ymin, ymax] or [xmin, ymin, xmax, ymax], and this package existed because both spellings were live in one tier at once. A bare band=1 cannot say what to do when a composite needs three bands, the 3-D tier needs a vertical level and an animation needs frames. digitalearth.base.spec is the answer to both: a small set of value objects — frozen, comparable, renderer-free — that a figure is described in.

They are engine-neutral by construction. Nothing here imports matplotlib, pyvista, holoviews or maplibre, and tests/test_base_is_engine_neutral.py enforces it by reading the source, so even a lazy import inside a function fails the build. Where the vocabulary genuinely needs a renderer's arithmetic — classification lives in cleopatra — it declares a seam instead and something above base/ fills it.

Bounds — one rectangle, with its ordering named#

Two orderings were live in the static tier at once, plus a third convention that hid an EPSG:4326 assumption inside a bare tuple. Bounds carries its own CRS and makes each ordering a method, so a call site states which it wants rather than leaving it to position.

digitalearth.base.spec.bounds.Bounds dataclass #

An axis-aligned rectangle in one CRS.

Attributes:

Name Type Description
xmin float

Western edge, in crs units.

ymin float

Southern edge.

xmax float

Eastern edge.

ymax float

Northern edge.

crs Any

The CRS the four values are expressed in — an EPSG code, a WKT string, or anything pyramids resolves. Kept with the numbers so a rectangle cannot be measured against the wrong one. A CRS object is held in the spelling it is written in — "EPSG:<code>" when its definition carries one, WKT otherwise — so a rectangle and its JSON round trip are one value with one hash.

Raises:

Type Description
ValueError

if any edge is not finite, or if an edge pair is inverted (xmax < xmin). A rectangle whose corners are the wrong way round draws nothing and reports no error, which is the failure this refuses up front. Also for a CRS with no written form — a boolean, a float, a list, an object pyramids cannot read — which the message names. A string is not checked.

Examples:

  • Build one and read back the two orderings that used to be positional conventions:
    >>> from digitalearth.base.spec import Bounds
    >>> box = Bounds(0.0, 10.0, 4.0, 20.0, crs=4326)
    >>> box.as_bbox()
    [0.0, 10.0, 4.0, 20.0]
    >>> box.as_mpl()
    [0.0, 4.0, 10.0, 20.0]
    
  • The union of two rectangles is what auto-framing needs:
    >>> from digitalearth.base.spec import Bounds
    >>> west = Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)
    >>> east = Bounds(5.0, 2.0, 6.0, 3.0, crs=4326)
    >>> west.union(east)
    Bounds(xmin=0.0, ymin=0.0, xmax=6.0, ymax=3.0, crs=4326)
    
  • An inverted rectangle is refused rather than drawn empty:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(10.0, 0.0, 1.0, 1.0, crs=4326)
    Traceback (most recent call last):
        ...
    ValueError: Bounds needs xmin <= xmax; got xmin=10.0, xmax=1.0
    
Source code in src/digitalearth/base/spec/bounds.py
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
@dataclass(frozen=True)
class Bounds:
    """An axis-aligned rectangle in one CRS.

    Attributes:
        xmin: Western edge, in `crs` units.
        ymin: Southern edge.
        xmax: Eastern edge.
        ymax: Northern edge.
        crs: The CRS the four values are expressed in — an EPSG code, a WKT string, or anything pyramids
            resolves. Kept with the numbers so a rectangle cannot be measured against the wrong one. A CRS object
            is held in the spelling it is written in — ``"EPSG:<code>"`` when its definition carries one, WKT
            otherwise — so a rectangle and its JSON round trip are one value with one hash.

    Raises:
        ValueError: if any edge is not finite, or if an edge pair is inverted (``xmax < xmin``). A rectangle
            whose corners are the wrong way round draws nothing and reports no error, which is the failure
            this refuses up front. Also for a CRS with no written form — a boolean, a float, a list, an object
            pyramids cannot read — which the message names. A string is not checked.

    Examples:
        - Build one and read back the two orderings that used to be positional conventions:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> box = Bounds(0.0, 10.0, 4.0, 20.0, crs=4326)
            >>> box.as_bbox()
            [0.0, 10.0, 4.0, 20.0]
            >>> box.as_mpl()
            [0.0, 4.0, 10.0, 20.0]

            ```
        - The union of two rectangles is what auto-framing needs:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> west = Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)
            >>> east = Bounds(5.0, 2.0, 6.0, 3.0, crs=4326)
            >>> west.union(east)
            Bounds(xmin=0.0, ymin=0.0, xmax=6.0, ymax=3.0, crs=4326)

            ```
        - An inverted rectangle is refused rather than drawn empty:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(10.0, 0.0, 1.0, 1.0, crs=4326)
            Traceback (most recent call last):
                ...
            ValueError: Bounds needs xmin <= xmax; got xmin=10.0, xmax=1.0

            ```
    """

    xmin: float
    ymin: float
    xmax: float
    ymax: float
    crs: Any

    def __post_init__(self) -> None:
        """Refuse a rectangle that cannot bound anything.

        Raises:
            ValueError: for a non-finite edge, an inverted pair, or a CRS with no written form.
        """
        for name, value in (
            ("xmin", self.xmin),
            ("ymin", self.ymin),
            ("xmax", self.xmax),
            ("ymax", self.ymax),
        ):
            if not isfinite(value):
                raise ValueError(f"Bounds needs finite edges; got {name}={value!r}")
        if self.xmax < self.xmin:
            raise ValueError(
                f"Bounds needs xmin <= xmax; got xmin={self.xmin}, xmax={self.xmax}"
            )
        if self.ymax < self.ymin:
            raise ValueError(
                f"Bounds needs ymin <= ymax; got ymin={self.ymin}, ymax={self.ymax}"
            )
        try:
            written = crs_to_json(self.crs, "Bounds.crs")
        except TypeError as error:
            raise ValueError(str(error)) from error
        # Held as written. A CRS object equals its own code through pyproj's `__eq__` but hashes by its WKT, so a
        # rectangle equalled its round trip with a different hash, and could not key a cache it was rebuilt for.
        object.__setattr__(self, "crs", written)

    # ------------------------------------------------------------------ builders

    @classmethod
    def from_bbox(cls, bbox: Sequence[float], crs: Any) -> "Bounds":
        """Build from the ``[xmin, ymin, xmax, ymax]`` order cleopatra and pyramids use.

        Args:
            bbox: Four edges in bbox order.
            crs: The CRS they are expressed in.

        Returns:
            The rectangle.

        Raises:
            ValueError: if `bbox` does not hold exactly four values, or the rectangle is invalid.

        Examples:
            - The order pyramids hands back:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.from_bbox([0.0, 1.0, 2.0, 3.0], crs=4326).as_bbox()
                [0.0, 1.0, 2.0, 3.0]

                ```
        """
        xmin, ymin, xmax, ymax = cls._four(bbox, "bbox")
        return cls(xmin, ymin, xmax, ymax, crs)

    @classmethod
    def from_mpl(cls, extent: Sequence[float], crs: Any) -> "Bounds":
        """Build from the ``[xmin, xmax, ymin, ymax]`` order matplotlib's axes use.

        Args:
            extent: Four edges in matplotlib axes order.
            crs: The CRS they are expressed in.

        Returns:
            The rectangle.

        Raises:
            ValueError: if `extent` does not hold exactly four values, or the rectangle is invalid.

        Examples:
            - The order `set_xlim`/`set_ylim` read:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.from_mpl([0.0, 2.0, 1.0, 3.0], crs=4326).as_bbox()
                [0.0, 1.0, 2.0, 3.0]

                ```
        """
        xmin, xmax, ymin, ymax = cls._four(extent, "extent")
        return cls(xmin, ymin, xmax, ymax, crs)

    @classmethod
    def from_points(cls, x: Any, y: Any, crs: Any) -> "Bounds":
        """Build the rectangle enclosing coordinate arrays.

        Args:
            x: X coordinates, any sequence or array.
            y: Y coordinates.
            crs: The CRS they are expressed in.

        Returns:
            The enclosing rectangle.

        Raises:
            ValueError: if either array is empty, or the rectangle is invalid.

        Examples:
            - Enclose a scattering of points:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.from_points([3.0, 1.0, 2.0], [9.0, 7.0, 8.0], crs=4326).as_bbox()
                [1.0, 7.0, 3.0, 9.0]

                ```
        """
        # numpy's reductions rather than a Python loop: this runs per render over every coordinate of a
        # raster's axes, and materialising a Python list of them was a cost the previous np.min/np.max had
        # not. It also keeps what those accepted — a 2-D array, and NaN coordinates, which nanmin ignores
        # rather than turning into a "needs finite edges" error from the constructor.
        xs = np.asarray(x, dtype="float64")
        ys = np.asarray(y, dtype="float64")
        if xs.size == 0 or ys.size == 0:
            raise ValueError("Bounds.from_points needs at least one coordinate pair")
        with warnings.catch_warnings():
            # An all-NaN axis warns and yields NaN, which the constructor then refuses by name.
            warnings.simplefilter("ignore", RuntimeWarning)
            return cls(
                float(np.nanmin(xs)),
                float(np.nanmin(ys)),
                float(np.nanmax(xs)),
                float(np.nanmax(ys)),
                crs,
            )

    @classmethod
    def cell_edges(cls, x: Any, y: Any, crs: Any, *, step: Any = None) -> "Bounds":
        """Return the rectangle a raster's cells cover, from the axes through their centres.

        A raster is a grid of cells, and its coordinates name the middle of each one. An extent taken from the
        smallest and largest of those stops half a cell short on every side: the image is one cell narrower and
        one shorter than the data, and every pixel is drawn at `(n - 1) / n` of its size. On
        `examples/data/acc4000.tif` — 14 by 13 cells of 4,000 m — that is 2,000 m missing from each edge, and
        the picture is wrong by exactly the amount nobody notices.

        This is the rule that places one: half the outermost spacing outward on each side.

        Args:
            x: The cell-centre x coordinates, ascending or descending.
            y: The cell-centre y coordinates, ascending or descending.
            crs: What they are measured in, stored as given.
            step: `(dx, dy)`, the cell size, for an axis with one cell — which has no spacing of its own to
                read. `None` lets such an axis take the *other* axis' spacing, which is what a raster one row
                tall or one column wide means: a row of square cells. When neither axis has two cells there
                is nothing to borrow and the rectangle stays a point.

        Returns:
            The rectangle, ascending in both axes whichever way the axes run.

        Raises:
            ValueError: for an empty axis, for coordinates that are not numbers, or for a `step` that is not
                a `(dx, dy)` pair. Each is named: this is on the hot path of two tiers, and numpy's own
                `TypeError` says what it could not convert without saying which argument it came from.

        Examples:
            - Three cells of 10,000 m, centred at 5,000/15,000/25,000, cover 0 to 30,000:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> axis = [5000.0, 15000.0, 25000.0]
                >>> Bounds.cell_edges(axis, axis, crs=32618).as_bbox()
                [0.0, 0.0, 30000.0, 30000.0]

                ```
            - A descending axis — the row order a north-up raster is stored in — covers the same rectangle:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.cell_edges([5.0, 15.0, 25.0], [25.0, 15.0, 5.0], crs=4326).as_bbox()
                [0.0, 0.0, 30.0, 30.0]

                ```
            - A single cell has no spacing to read, so its width is given or it stays a line:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.cell_edges([5.0], [5.0], crs=4326, step=(10.0, 10.0)).as_bbox()
                [0.0, 0.0, 10.0, 10.0]

                ```
        """
        xs, ys = cls._axis_values(x, "x"), cls._axis_values(y, "y")
        if xs.size == 0 or ys.size == 0:
            raise ValueError(
                "Bounds.cell_edges needs coordinates on both axes; got "
                f"{xs.size} x and {ys.size} y"
            )
        steps = cls._checked_step(step)
        # A lone cell has no spacing of its own, so it borrows the other axis's: a raster one row tall is a
        # row of square cells, not a line of zero height. Without this a 1 x 25 raster was placed on a
        # rectangle with no height at all and drawn invisible (review M4). A caller who knows better says so
        # with `step=`, and an axis whose partner is also degenerate stays a point.
        # A named spacing is the caller's answer for *that* axis; the other axis' spacing is only borrowed
        # where they did not give one. Reading the derived spacings alone meant `step=(10, None)` collapsed
        # the y axis to a point although the caller had named the x cell size (review L11).
        across = steps[0] if steps[0] is not None else cls._spacing(ys) or steps[1]
        down = steps[1] if steps[1] is not None else cls._spacing(xs) or steps[0]
        west, east = cls._edges(xs, across)
        south, north = cls._edges(ys, down)
        return cls(west, south, east, north, crs)

    @staticmethod
    def _checked_step(step: Any) -> tuple[Any, Any]:
        """Return the `(dx, dy)` a caller named, refusing anything that is not one.

        Args:
            step: What the caller passed for `step`, or `None`.

        Returns:
            `(dx, dy)` as given, or `(None, None)` for `None`.

        Raises:
            ValueError: for anything that is not a pair of two numbers — including a string, which unpacks
                two characters just as happily, and a triple, whose third value was silently ignored
                (review L11).
        """
        if step is None:
            return (None, None)
        if isinstance(step, (str, bytes)) or not isinstance(step, Sequence):
            raise ValueError(
                f"Bounds.cell_edges step must be a (dx, dy) pair; got {step!r}"
            )
        if len(step) != 2:
            raise ValueError(
                f"Bounds.cell_edges step must be a (dx, dy) pair; got {len(step)} values"
            )
        for value in step:
            if value is not None and not isinstance(value, (int, float)):
                raise ValueError(
                    f"Bounds.cell_edges step must be a (dx, dy) pair of numbers; got {step!r}"
                )
        return (step[0], step[1])

    @staticmethod
    def _axis_values(axis: Any, name: str) -> Any:
        """Return one axis' coordinates as a flat float array.

        Args:
            axis: What the caller passed for that axis.
            name: `"x"` or `"y"`, for the message.

        Returns:
            The values, flattened.

        Raises:
            ValueError: when they are not numbers — naming the axis, which numpy's own `TypeError` cannot.
        """
        import numpy as np

        try:
            return np.asarray(axis, dtype="float64").ravel()
        except (TypeError, ValueError) as error:
            raise ValueError(
                f"Bounds.cell_edges needs numbers for {name}; got {type(axis).__name__} ({error})"
            ) from None

    @staticmethod
    def _spacing(axis: Any) -> float | None:
        """Return the spacing between an axis' outermost cells, or `None` when it has only one.

        Args:
            axis: The cell centres along the axis.

        Returns:
            The magnitude of the gap at the axis' near end, which is what a cell measures there.
        """
        if axis.size < 2:
            return None
        ordered = np.sort(axis)
        return abs(float(ordered[1] - ordered[0]))

    @staticmethod
    def _edges(axis: Any, step: Any) -> tuple[float, float]:
        """Return where one axis' cells start and end.

        Args:
            axis: The cell centres along the axis.
            step: The cell size, for an axis with one cell; `None` leaves such an axis unwidened.

        Returns:
            `(low, high)`, ascending.
        """
        low, high = float(np.nanmin(axis)), float(np.nanmax(axis))
        if axis.size > 1:
            ordered = np.sort(axis)
            # Half the outermost spacing at each end, so an irregular grid is placed by its own cells rather
            # than by an average that fits none of them.
            return (
                low - 0.5 * float(ordered[1] - ordered[0]),
                high + 0.5 * float(ordered[-1] - ordered[-2]),
            )
        if step is None:
            return low, high
        half = 0.5 * abs(float(step))
        return low - half, high + half

    @staticmethod
    def _four(values: Sequence[float], label: str) -> tuple[float, float, float, float]:
        """Return exactly four floats, or say which argument was the wrong length.

        Args:
            values: The candidate sequence.
            label: Argument name to blame in the error.

        Returns:
            The four values as floats.

        Raises:
            ValueError: when there are not exactly four.
        """
        seq = [float(v) for v in values]
        if len(seq) != 4:
            raise ValueError(f"{label} needs exactly 4 values; got {len(seq)}")
        return seq[0], seq[1], seq[2], seq[3]

    # ------------------------------------------------------------------ readers

    def as_bbox(self) -> list[float]:
        """Return ``[xmin, ymin, xmax, ymax]`` — the order cleopatra and pyramids take.

        Returns:
            The four edges in bbox order.

        Examples:
            - The corners come back in the order a bounding box is written in:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_bbox()
                [0.0, 10.0, 4.0, 20.0]

                ```
            - Which is what a pyramids call wants, unpacked:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> xmin, ymin, xmax, ymax = Bounds(-5.0, 40.0, 5.0, 50.0, crs=4326).as_bbox()
                >>> xmax - xmin, ymax - ymin
                (10.0, 10.0)

                ```
        """
        return [self.xmin, self.ymin, self.xmax, self.ymax]

    def as_mpl(self) -> list[float]:
        """Return ``[xmin, xmax, ymin, ymax]`` — the order matplotlib's axes take.

        Returns:
            The four edges in matplotlib axes order.

        Examples:
            - The x pair comes first here, unlike :meth:`as_bbox`:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_mpl()
                [0.0, 4.0, 10.0, 20.0]

                ```
            - The two orderings disagree for the same rectangle, which is the bug this type removes:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> box = Bounds(0.0, 10.0, 4.0, 20.0, crs=4326)
                >>> box.as_bbox() == box.as_mpl()
                False

                ```
        """
        return [self.xmin, self.xmax, self.ymin, self.ymax]

    # ------------------------------------------------------------------ operations

    def union(self, other: "Bounds") -> "Bounds":
        """Return the smallest rectangle containing both.

        Args:
            other: The rectangle to merge in. Must already be in the same CRS — reproject it first with
                :meth:`to_crs` rather than relying on a silent reinterpretation of the numbers.

        Returns:
            The enclosing rectangle, in this rectangle's CRS.

        Raises:
            ValueError: if the two carry different CRSs. Unioning across CRSs by ignoring them is how an
                extent ends up describing a region nobody asked for.

        Examples:
            - Two layers' extents, framed together:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> a = Bounds(0.0, 0.0, 2.0, 2.0, crs=3857)
                >>> b = Bounds(1.0, -5.0, 3.0, 1.0, crs=3857)
                >>> a.union(b).as_bbox()
                [0.0, -5.0, 3.0, 2.0]

                ```
        """
        if not same_crs(self.crs, other.crs):
            raise ValueError(
                f"union needs both rectangles in one CRS; got {self.crs!r} and {other.crs!r} — "
                "reproject one with to_crs() first"
            )
        return Bounds(
            min(self.xmin, other.xmin),
            min(self.ymin, other.ymin),
            max(self.xmax, other.xmax),
            max(self.ymax, other.ymax),
            self.crs,
        )

    def padded(self, fraction: float) -> "Bounds":
        """Return this rectangle grown by `fraction` of its own span on every side.

        Args:
            fraction: How much to grow, as a proportion of width and height. ``0.05`` adds a 5% margin;
                a negative value shrinks.

        Returns:
            The padded rectangle.

        Raises:
            ValueError: from :func:`check_padding`, if the fraction is not finite or would invert the
                rectangle.

        Examples:
            - A 10% margin around the data:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds(0.0, 0.0, 10.0, 10.0, crs=4326).padded(0.1).as_bbox()
                [-1.0, -1.0, 11.0, 11.0]

                ```
        """
        check_padding(fraction)
        dx = (self.xmax - self.xmin) * fraction
        dy = (self.ymax - self.ymin) * fraction
        return Bounds(
            self.xmin - dx, self.ymin - dy, self.xmax + dx, self.ymax + dy, self.crs
        )

    def to_crs(self, crs: Any) -> "Bounds":
        """Return this rectangle expressed in another CRS.

        The corner transform is pyramids' (``pyramids.base.crs.reproject_coordinates``); this package does no
        coordinate maths of its own, per `CLAUDE.md`. The result is the **enclosing** rectangle of the
        transformed corners: a warped rectangle is not a rectangle, so its axis-aligned hull is what an extent
        can hold.

        Args:
            crs: The target CRS.

        Returns:
            The enclosing rectangle in `crs`, or this rectangle unchanged when `crs` already matches. A CRS object
            given as `crs` is held in its written spelling, as the constructor holds one.

        Raises:
            ValueError: naming the rectangle and both CRSs, when a corner falls outside the area `crs` can show —
                the far side of an orthographic globe, say — so the reprojection gives no finite corner to enclose;
                or, as pyramids' `CRSError` (a `ValueError` subclass), when `crs` is not a CRS pyramids can read.

        Examples:
            - Reprojecting to the CRS it already has is a no-op:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> box = Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)
                >>> box.to_crs(4326) is box
                True

                ```
            - A rectangle on the far side of an orthographic globe has no corners to enclose:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds(100.0, -10.0, 170.0, 10.0, crs=4326).to_crs("+proj=ortho +lat_0=0 +lon_0=0")
                Traceback (most recent call last):
                    ...
                ValueError: Bounds [100.0, -10.0, 170.0, 10.0] in 4326 cannot be reprojected into ...

                ```
        """
        if same_crs(crs, self.crs):
            return self
        from pyramids.base.crs import reproject_coordinates

        # (x, y) order throughout, matching pyramids' own contract — the four corners, not the four edges.
        xs, ys = reproject_coordinates(
            [self.xmin, self.xmax, self.xmin, self.xmax],
            [self.ymin, self.ymin, self.ymax, self.ymax],
            from_crs=self.crs,
            to_crs=crs,
            # pyramids rounds to 6 decimals by default, which collapses a rectangle finer than that step
            # into a degenerate one — and set_bounds would hand matplotlib a singular limit.
            precision=None,
        )
        if not all(isfinite(value) for value in (*xs, *ys)):
            # pyramids answers a corner the target cannot show with an infinity. Handed on, the constructor would
            # report an infinite edge without saying a reprojection produced it.
            raise ValueError(
                f"Bounds {self.as_bbox()} in {self.crs!r} cannot be reprojected into {crs!r}: part of the "
                "rectangle falls outside the area that projection can show"
            )
        return Bounds(min(xs), min(ys), max(xs), max(ys), crs)

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            The four edges as Python floats, and the CRS as held: `None`, an EPSG integer or a string, which is not
            checked. The constructor has already turned a CRS object into `"EPSG:<code>"` (or WKT when its
            definition carries no EPSG code) and refused a CRS with no written form, so writing a rectangle does
            not fail on its CRS.

        Examples:
            - The edges keep their names, so the ordering cannot be misread:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds(0.0, 1.0, 2.0, 3.0, crs=4326).to_dict()
                {'xmin': 0.0, 'ymin': 1.0, 'xmax': 2.0, 'ymax': 3.0, 'crs': 4326}

                ```
            - A CRS object is written by the EPSG code it is held as:
                ```python
                >>> from pyramids.base.crs import crs_from_user_input
                >>> from digitalearth.base.spec import Bounds
                >>> box = Bounds(0.0, 1.0, 2.0, 3.0, crs=crs_from_user_input(4326))
                >>> box.crs, box.to_dict()["crs"]
                ('EPSG:4326', 'EPSG:4326')

                ```
        """
        return {
            # The constructor has already refused a non-finite edge, but not a numpy float, which json cannot write.
            "xmin": float(self.xmin),
            "ymin": float(self.ymin),
            "xmax": float(self.xmax),
            "ymax": float(self.ymax),
            "crs": crs_to_json(self.crs, "Bounds.crs"),
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Bounds":
        """Rebuild a rectangle from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`. A missing `crs` means `None`.

        Returns:
            The rectangle, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping.
            ValueError: if an edge is missing or is not a finite number — `None` and a numeric string are refused
                by name — a key is unknown, the edges do not bound a rectangle, or the CRS has no written form (a
                stored `true`, say).

        Examples:
            - A stored rectangle reads back to the same value:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> box = Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 10, "ymax": 5, "crs": 3857})
                >>> box.as_bbox(), box.crs
                ([0.0, 0.0, 10.0, 5.0], 3857)

                ```
            - A missing edge is named:
                ```python
                >>> from digitalearth.base.spec import Bounds
                >>> Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 1, "crs": 4326})
                Traceback (most recent call last):
                    ...
                ValueError: Bounds.from_dict needs 'ymax'; got keys ['crs', 'xmax', 'xmin', 'ymin']

                ```
        """
        refuse_unknown("Bounds", data, ("xmin", "ymin", "xmax", "ymax", "crs"))
        return cls(
            finite_number("Bounds", "xmin", require("Bounds", data, "xmin")),
            finite_number("Bounds", "ymin", require("Bounds", data, "ymin")),
            finite_number("Bounds", "xmax", require("Bounds", data, "xmax")),
            finite_number("Bounds", "ymax", require("Bounds", data, "ymax")),
            data.get("crs"),
        )

__post_init__() #

Refuse a rectangle that cannot bound anything.

Raises:

Type Description
ValueError

for a non-finite edge, an inverted pair, or a CRS with no written form.

Source code in src/digitalearth/base/spec/bounds.py
def __post_init__(self) -> None:
    """Refuse a rectangle that cannot bound anything.

    Raises:
        ValueError: for a non-finite edge, an inverted pair, or a CRS with no written form.
    """
    for name, value in (
        ("xmin", self.xmin),
        ("ymin", self.ymin),
        ("xmax", self.xmax),
        ("ymax", self.ymax),
    ):
        if not isfinite(value):
            raise ValueError(f"Bounds needs finite edges; got {name}={value!r}")
    if self.xmax < self.xmin:
        raise ValueError(
            f"Bounds needs xmin <= xmax; got xmin={self.xmin}, xmax={self.xmax}"
        )
    if self.ymax < self.ymin:
        raise ValueError(
            f"Bounds needs ymin <= ymax; got ymin={self.ymin}, ymax={self.ymax}"
        )
    try:
        written = crs_to_json(self.crs, "Bounds.crs")
    except TypeError as error:
        raise ValueError(str(error)) from error
    # Held as written. A CRS object equals its own code through pyproj's `__eq__` but hashes by its WKT, so a
    # rectangle equalled its round trip with a different hash, and could not key a cache it was rebuilt for.
    object.__setattr__(self, "crs", written)

as_bbox() #

Return [xmin, ymin, xmax, ymax] — the order cleopatra and pyramids take.

Returns:

Type Description
list[float]

The four edges in bbox order.

Examples:

  • The corners come back in the order a bounding box is written in:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_bbox()
    [0.0, 10.0, 4.0, 20.0]
    
  • Which is what a pyramids call wants, unpacked:
    >>> from digitalearth.base.spec import Bounds
    >>> xmin, ymin, xmax, ymax = Bounds(-5.0, 40.0, 5.0, 50.0, crs=4326).as_bbox()
    >>> xmax - xmin, ymax - ymin
    (10.0, 10.0)
    
Source code in src/digitalearth/base/spec/bounds.py
def as_bbox(self) -> list[float]:
    """Return ``[xmin, ymin, xmax, ymax]`` — the order cleopatra and pyramids take.

    Returns:
        The four edges in bbox order.

    Examples:
        - The corners come back in the order a bounding box is written in:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_bbox()
            [0.0, 10.0, 4.0, 20.0]

            ```
        - Which is what a pyramids call wants, unpacked:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> xmin, ymin, xmax, ymax = Bounds(-5.0, 40.0, 5.0, 50.0, crs=4326).as_bbox()
            >>> xmax - xmin, ymax - ymin
            (10.0, 10.0)

            ```
    """
    return [self.xmin, self.ymin, self.xmax, self.ymax]

as_mpl() #

Return [xmin, xmax, ymin, ymax] — the order matplotlib's axes take.

Returns:

Type Description
list[float]

The four edges in matplotlib axes order.

Examples:

  • The x pair comes first here, unlike :meth:as_bbox:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_mpl()
    [0.0, 4.0, 10.0, 20.0]
    
  • The two orderings disagree for the same rectangle, which is the bug this type removes:
    >>> from digitalearth.base.spec import Bounds
    >>> box = Bounds(0.0, 10.0, 4.0, 20.0, crs=4326)
    >>> box.as_bbox() == box.as_mpl()
    False
    
Source code in src/digitalearth/base/spec/bounds.py
def as_mpl(self) -> list[float]:
    """Return ``[xmin, xmax, ymin, ymax]`` — the order matplotlib's axes take.

    Returns:
        The four edges in matplotlib axes order.

    Examples:
        - The x pair comes first here, unlike :meth:`as_bbox`:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(0.0, 10.0, 4.0, 20.0, crs=4326).as_mpl()
            [0.0, 4.0, 10.0, 20.0]

            ```
        - The two orderings disagree for the same rectangle, which is the bug this type removes:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> box = Bounds(0.0, 10.0, 4.0, 20.0, crs=4326)
            >>> box.as_bbox() == box.as_mpl()
            False

            ```
    """
    return [self.xmin, self.xmax, self.ymin, self.ymax]

cell_edges(x, y, crs, *, step=None) classmethod #

Return the rectangle a raster's cells cover, from the axes through their centres.

A raster is a grid of cells, and its coordinates name the middle of each one. An extent taken from the smallest and largest of those stops half a cell short on every side: the image is one cell narrower and one shorter than the data, and every pixel is drawn at (n - 1) / n of its size. On examples/data/acc4000.tif — 14 by 13 cells of 4,000 m — that is 2,000 m missing from each edge, and the picture is wrong by exactly the amount nobody notices.

This is the rule that places one: half the outermost spacing outward on each side.

Parameters:

Name Type Description Default
x Any

The cell-centre x coordinates, ascending or descending.

required
y Any

The cell-centre y coordinates, ascending or descending.

required
crs Any

What they are measured in, stored as given.

required
step Any

(dx, dy), the cell size, for an axis with one cell — which has no spacing of its own to read. None lets such an axis take the other axis' spacing, which is what a raster one row tall or one column wide means: a row of square cells. When neither axis has two cells there is nothing to borrow and the rectangle stays a point.

None

Returns:

Type Description
Bounds

The rectangle, ascending in both axes whichever way the axes run.

Raises:

Type Description
ValueError

for an empty axis, for coordinates that are not numbers, or for a step that is not a (dx, dy) pair. Each is named: this is on the hot path of two tiers, and numpy's own TypeError says what it could not convert without saying which argument it came from.

Examples:

  • Three cells of 10,000 m, centred at 5,000/15,000/25,000, cover 0 to 30,000:
    >>> from digitalearth.base.spec import Bounds
    >>> axis = [5000.0, 15000.0, 25000.0]
    >>> Bounds.cell_edges(axis, axis, crs=32618).as_bbox()
    [0.0, 0.0, 30000.0, 30000.0]
    
  • A descending axis — the row order a north-up raster is stored in — covers the same rectangle:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.cell_edges([5.0, 15.0, 25.0], [25.0, 15.0, 5.0], crs=4326).as_bbox()
    [0.0, 0.0, 30.0, 30.0]
    
  • A single cell has no spacing to read, so its width is given or it stays a line:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.cell_edges([5.0], [5.0], crs=4326, step=(10.0, 10.0)).as_bbox()
    [0.0, 0.0, 10.0, 10.0]
    
Source code in src/digitalearth/base/spec/bounds.py
@classmethod
def cell_edges(cls, x: Any, y: Any, crs: Any, *, step: Any = None) -> "Bounds":
    """Return the rectangle a raster's cells cover, from the axes through their centres.

    A raster is a grid of cells, and its coordinates name the middle of each one. An extent taken from the
    smallest and largest of those stops half a cell short on every side: the image is one cell narrower and
    one shorter than the data, and every pixel is drawn at `(n - 1) / n` of its size. On
    `examples/data/acc4000.tif` — 14 by 13 cells of 4,000 m — that is 2,000 m missing from each edge, and
    the picture is wrong by exactly the amount nobody notices.

    This is the rule that places one: half the outermost spacing outward on each side.

    Args:
        x: The cell-centre x coordinates, ascending or descending.
        y: The cell-centre y coordinates, ascending or descending.
        crs: What they are measured in, stored as given.
        step: `(dx, dy)`, the cell size, for an axis with one cell — which has no spacing of its own to
            read. `None` lets such an axis take the *other* axis' spacing, which is what a raster one row
            tall or one column wide means: a row of square cells. When neither axis has two cells there
            is nothing to borrow and the rectangle stays a point.

    Returns:
        The rectangle, ascending in both axes whichever way the axes run.

    Raises:
        ValueError: for an empty axis, for coordinates that are not numbers, or for a `step` that is not
            a `(dx, dy)` pair. Each is named: this is on the hot path of two tiers, and numpy's own
            `TypeError` says what it could not convert without saying which argument it came from.

    Examples:
        - Three cells of 10,000 m, centred at 5,000/15,000/25,000, cover 0 to 30,000:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> axis = [5000.0, 15000.0, 25000.0]
            >>> Bounds.cell_edges(axis, axis, crs=32618).as_bbox()
            [0.0, 0.0, 30000.0, 30000.0]

            ```
        - A descending axis — the row order a north-up raster is stored in — covers the same rectangle:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.cell_edges([5.0, 15.0, 25.0], [25.0, 15.0, 5.0], crs=4326).as_bbox()
            [0.0, 0.0, 30.0, 30.0]

            ```
        - A single cell has no spacing to read, so its width is given or it stays a line:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.cell_edges([5.0], [5.0], crs=4326, step=(10.0, 10.0)).as_bbox()
            [0.0, 0.0, 10.0, 10.0]

            ```
    """
    xs, ys = cls._axis_values(x, "x"), cls._axis_values(y, "y")
    if xs.size == 0 or ys.size == 0:
        raise ValueError(
            "Bounds.cell_edges needs coordinates on both axes; got "
            f"{xs.size} x and {ys.size} y"
        )
    steps = cls._checked_step(step)
    # A lone cell has no spacing of its own, so it borrows the other axis's: a raster one row tall is a
    # row of square cells, not a line of zero height. Without this a 1 x 25 raster was placed on a
    # rectangle with no height at all and drawn invisible (review M4). A caller who knows better says so
    # with `step=`, and an axis whose partner is also degenerate stays a point.
    # A named spacing is the caller's answer for *that* axis; the other axis' spacing is only borrowed
    # where they did not give one. Reading the derived spacings alone meant `step=(10, None)` collapsed
    # the y axis to a point although the caller had named the x cell size (review L11).
    across = steps[0] if steps[0] is not None else cls._spacing(ys) or steps[1]
    down = steps[1] if steps[1] is not None else cls._spacing(xs) or steps[0]
    west, east = cls._edges(xs, across)
    south, north = cls._edges(ys, down)
    return cls(west, south, east, north, crs)

from_bbox(bbox, crs) classmethod #

Build from the [xmin, ymin, xmax, ymax] order cleopatra and pyramids use.

Parameters:

Name Type Description Default
bbox Sequence[float]

Four edges in bbox order.

required
crs Any

The CRS they are expressed in.

required

Returns:

Type Description
Bounds

The rectangle.

Raises:

Type Description
ValueError

if bbox does not hold exactly four values, or the rectangle is invalid.

Examples:

  • The order pyramids hands back:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.from_bbox([0.0, 1.0, 2.0, 3.0], crs=4326).as_bbox()
    [0.0, 1.0, 2.0, 3.0]
    
Source code in src/digitalearth/base/spec/bounds.py
@classmethod
def from_bbox(cls, bbox: Sequence[float], crs: Any) -> "Bounds":
    """Build from the ``[xmin, ymin, xmax, ymax]`` order cleopatra and pyramids use.

    Args:
        bbox: Four edges in bbox order.
        crs: The CRS they are expressed in.

    Returns:
        The rectangle.

    Raises:
        ValueError: if `bbox` does not hold exactly four values, or the rectangle is invalid.

    Examples:
        - The order pyramids hands back:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.from_bbox([0.0, 1.0, 2.0, 3.0], crs=4326).as_bbox()
            [0.0, 1.0, 2.0, 3.0]

            ```
    """
    xmin, ymin, xmax, ymax = cls._four(bbox, "bbox")
    return cls(xmin, ymin, xmax, ymax, crs)

from_dict(data) classmethod #

Rebuild a rectangle from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict. A missing crs means None.

required

Returns:

Type Description
Bounds

The rectangle, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping.

ValueError

if an edge is missing or is not a finite number — None and a numeric string are refused by name — a key is unknown, the edges do not bound a rectangle, or the CRS has no written form (a stored true, say).

Examples:

  • A stored rectangle reads back to the same value:
    >>> from digitalearth.base.spec import Bounds
    >>> box = Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 10, "ymax": 5, "crs": 3857})
    >>> box.as_bbox(), box.crs
    ([0.0, 0.0, 10.0, 5.0], 3857)
    
  • A missing edge is named:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 1, "crs": 4326})
    Traceback (most recent call last):
        ...
    ValueError: Bounds.from_dict needs 'ymax'; got keys ['crs', 'xmax', 'xmin', 'ymin']
    
Source code in src/digitalearth/base/spec/bounds.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Bounds":
    """Rebuild a rectangle from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`. A missing `crs` means `None`.

    Returns:
        The rectangle, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping.
        ValueError: if an edge is missing or is not a finite number — `None` and a numeric string are refused
            by name — a key is unknown, the edges do not bound a rectangle, or the CRS has no written form (a
            stored `true`, say).

    Examples:
        - A stored rectangle reads back to the same value:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> box = Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 10, "ymax": 5, "crs": 3857})
            >>> box.as_bbox(), box.crs
            ([0.0, 0.0, 10.0, 5.0], 3857)

            ```
        - A missing edge is named:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.from_dict({"xmin": 0, "ymin": 0, "xmax": 1, "crs": 4326})
            Traceback (most recent call last):
                ...
            ValueError: Bounds.from_dict needs 'ymax'; got keys ['crs', 'xmax', 'xmin', 'ymin']

            ```
    """
    refuse_unknown("Bounds", data, ("xmin", "ymin", "xmax", "ymax", "crs"))
    return cls(
        finite_number("Bounds", "xmin", require("Bounds", data, "xmin")),
        finite_number("Bounds", "ymin", require("Bounds", data, "ymin")),
        finite_number("Bounds", "xmax", require("Bounds", data, "xmax")),
        finite_number("Bounds", "ymax", require("Bounds", data, "ymax")),
        data.get("crs"),
    )

from_mpl(extent, crs) classmethod #

Build from the [xmin, xmax, ymin, ymax] order matplotlib's axes use.

Parameters:

Name Type Description Default
extent Sequence[float]

Four edges in matplotlib axes order.

required
crs Any

The CRS they are expressed in.

required

Returns:

Type Description
Bounds

The rectangle.

Raises:

Type Description
ValueError

if extent does not hold exactly four values, or the rectangle is invalid.

Examples:

  • The order set_xlim/set_ylim read:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.from_mpl([0.0, 2.0, 1.0, 3.0], crs=4326).as_bbox()
    [0.0, 1.0, 2.0, 3.0]
    
Source code in src/digitalearth/base/spec/bounds.py
@classmethod
def from_mpl(cls, extent: Sequence[float], crs: Any) -> "Bounds":
    """Build from the ``[xmin, xmax, ymin, ymax]`` order matplotlib's axes use.

    Args:
        extent: Four edges in matplotlib axes order.
        crs: The CRS they are expressed in.

    Returns:
        The rectangle.

    Raises:
        ValueError: if `extent` does not hold exactly four values, or the rectangle is invalid.

    Examples:
        - The order `set_xlim`/`set_ylim` read:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.from_mpl([0.0, 2.0, 1.0, 3.0], crs=4326).as_bbox()
            [0.0, 1.0, 2.0, 3.0]

            ```
    """
    xmin, xmax, ymin, ymax = cls._four(extent, "extent")
    return cls(xmin, ymin, xmax, ymax, crs)

from_points(x, y, crs) classmethod #

Build the rectangle enclosing coordinate arrays.

Parameters:

Name Type Description Default
x Any

X coordinates, any sequence or array.

required
y Any

Y coordinates.

required
crs Any

The CRS they are expressed in.

required

Returns:

Type Description
Bounds

The enclosing rectangle.

Raises:

Type Description
ValueError

if either array is empty, or the rectangle is invalid.

Examples:

  • Enclose a scattering of points:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds.from_points([3.0, 1.0, 2.0], [9.0, 7.0, 8.0], crs=4326).as_bbox()
    [1.0, 7.0, 3.0, 9.0]
    
Source code in src/digitalearth/base/spec/bounds.py
@classmethod
def from_points(cls, x: Any, y: Any, crs: Any) -> "Bounds":
    """Build the rectangle enclosing coordinate arrays.

    Args:
        x: X coordinates, any sequence or array.
        y: Y coordinates.
        crs: The CRS they are expressed in.

    Returns:
        The enclosing rectangle.

    Raises:
        ValueError: if either array is empty, or the rectangle is invalid.

    Examples:
        - Enclose a scattering of points:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds.from_points([3.0, 1.0, 2.0], [9.0, 7.0, 8.0], crs=4326).as_bbox()
            [1.0, 7.0, 3.0, 9.0]

            ```
    """
    # numpy's reductions rather than a Python loop: this runs per render over every coordinate of a
    # raster's axes, and materialising a Python list of them was a cost the previous np.min/np.max had
    # not. It also keeps what those accepted — a 2-D array, and NaN coordinates, which nanmin ignores
    # rather than turning into a "needs finite edges" error from the constructor.
    xs = np.asarray(x, dtype="float64")
    ys = np.asarray(y, dtype="float64")
    if xs.size == 0 or ys.size == 0:
        raise ValueError("Bounds.from_points needs at least one coordinate pair")
    with warnings.catch_warnings():
        # An all-NaN axis warns and yields NaN, which the constructor then refuses by name.
        warnings.simplefilter("ignore", RuntimeWarning)
        return cls(
            float(np.nanmin(xs)),
            float(np.nanmin(ys)),
            float(np.nanmax(xs)),
            float(np.nanmax(ys)),
            crs,
        )

padded(fraction) #

Return this rectangle grown by fraction of its own span on every side.

Parameters:

Name Type Description Default
fraction float

How much to grow, as a proportion of width and height. 0.05 adds a 5% margin; a negative value shrinks.

required

Returns:

Type Description
Bounds

The padded rectangle.

Raises:

Type Description
ValueError

from :func:check_padding, if the fraction is not finite or would invert the rectangle.

Examples:

  • A 10% margin around the data:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(0.0, 0.0, 10.0, 10.0, crs=4326).padded(0.1).as_bbox()
    [-1.0, -1.0, 11.0, 11.0]
    
Source code in src/digitalearth/base/spec/bounds.py
def padded(self, fraction: float) -> "Bounds":
    """Return this rectangle grown by `fraction` of its own span on every side.

    Args:
        fraction: How much to grow, as a proportion of width and height. ``0.05`` adds a 5% margin;
            a negative value shrinks.

    Returns:
        The padded rectangle.

    Raises:
        ValueError: from :func:`check_padding`, if the fraction is not finite or would invert the
            rectangle.

    Examples:
        - A 10% margin around the data:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(0.0, 0.0, 10.0, 10.0, crs=4326).padded(0.1).as_bbox()
            [-1.0, -1.0, 11.0, 11.0]

            ```
    """
    check_padding(fraction)
    dx = (self.xmax - self.xmin) * fraction
    dy = (self.ymax - self.ymin) * fraction
    return Bounds(
        self.xmin - dx, self.ymin - dy, self.xmax + dx, self.ymax + dy, self.crs
    )

to_crs(crs) #

Return this rectangle expressed in another CRS.

The corner transform is pyramids' (pyramids.base.crs.reproject_coordinates); this package does no coordinate maths of its own, per CLAUDE.md. The result is the enclosing rectangle of the transformed corners: a warped rectangle is not a rectangle, so its axis-aligned hull is what an extent can hold.

Parameters:

Name Type Description Default
crs Any

The target CRS.

required

Returns:

Type Description
Bounds

The enclosing rectangle in crs, or this rectangle unchanged when crs already matches. A CRS object

Bounds

given as crs is held in its written spelling, as the constructor holds one.

Raises:

Type Description
ValueError

naming the rectangle and both CRSs, when a corner falls outside the area crs can show — the far side of an orthographic globe, say — so the reprojection gives no finite corner to enclose; or, as pyramids' CRSError (a ValueError subclass), when crs is not a CRS pyramids can read.

Examples:

  • Reprojecting to the CRS it already has is a no-op:
    >>> from digitalearth.base.spec import Bounds
    >>> box = Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)
    >>> box.to_crs(4326) is box
    True
    
  • A rectangle on the far side of an orthographic globe has no corners to enclose:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(100.0, -10.0, 170.0, 10.0, crs=4326).to_crs("+proj=ortho +lat_0=0 +lon_0=0")
    Traceback (most recent call last):
        ...
    ValueError: Bounds [100.0, -10.0, 170.0, 10.0] in 4326 cannot be reprojected into ...
    
Source code in src/digitalearth/base/spec/bounds.py
def to_crs(self, crs: Any) -> "Bounds":
    """Return this rectangle expressed in another CRS.

    The corner transform is pyramids' (``pyramids.base.crs.reproject_coordinates``); this package does no
    coordinate maths of its own, per `CLAUDE.md`. The result is the **enclosing** rectangle of the
    transformed corners: a warped rectangle is not a rectangle, so its axis-aligned hull is what an extent
    can hold.

    Args:
        crs: The target CRS.

    Returns:
        The enclosing rectangle in `crs`, or this rectangle unchanged when `crs` already matches. A CRS object
        given as `crs` is held in its written spelling, as the constructor holds one.

    Raises:
        ValueError: naming the rectangle and both CRSs, when a corner falls outside the area `crs` can show —
            the far side of an orthographic globe, say — so the reprojection gives no finite corner to enclose;
            or, as pyramids' `CRSError` (a `ValueError` subclass), when `crs` is not a CRS pyramids can read.

    Examples:
        - Reprojecting to the CRS it already has is a no-op:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> box = Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)
            >>> box.to_crs(4326) is box
            True

            ```
        - A rectangle on the far side of an orthographic globe has no corners to enclose:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(100.0, -10.0, 170.0, 10.0, crs=4326).to_crs("+proj=ortho +lat_0=0 +lon_0=0")
            Traceback (most recent call last):
                ...
            ValueError: Bounds [100.0, -10.0, 170.0, 10.0] in 4326 cannot be reprojected into ...

            ```
    """
    if same_crs(crs, self.crs):
        return self
    from pyramids.base.crs import reproject_coordinates

    # (x, y) order throughout, matching pyramids' own contract — the four corners, not the four edges.
    xs, ys = reproject_coordinates(
        [self.xmin, self.xmax, self.xmin, self.xmax],
        [self.ymin, self.ymin, self.ymax, self.ymax],
        from_crs=self.crs,
        to_crs=crs,
        # pyramids rounds to 6 decimals by default, which collapses a rectangle finer than that step
        # into a degenerate one — and set_bounds would hand matplotlib a singular limit.
        precision=None,
    )
    if not all(isfinite(value) for value in (*xs, *ys)):
        # pyramids answers a corner the target cannot show with an infinity. Handed on, the constructor would
        # report an infinite edge without saying a reprojection produced it.
        raise ValueError(
            f"Bounds {self.as_bbox()} in {self.crs!r} cannot be reprojected into {crs!r}: part of the "
            "rectangle falls outside the area that projection can show"
        )
    return Bounds(min(xs), min(ys), max(xs), max(ys), crs)

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

The four edges as Python floats, and the CRS as held: None, an EPSG integer or a string, which is not

dict[str, Any]

checked. The constructor has already turned a CRS object into "EPSG:<code>" (or WKT when its

dict[str, Any]

definition carries no EPSG code) and refused a CRS with no written form, so writing a rectangle does

dict[str, Any]

not fail on its CRS.

Examples:

  • The edges keep their names, so the ordering cannot be misread:
    >>> from digitalearth.base.spec import Bounds
    >>> Bounds(0.0, 1.0, 2.0, 3.0, crs=4326).to_dict()
    {'xmin': 0.0, 'ymin': 1.0, 'xmax': 2.0, 'ymax': 3.0, 'crs': 4326}
    
  • A CRS object is written by the EPSG code it is held as:
    >>> from pyramids.base.crs import crs_from_user_input
    >>> from digitalearth.base.spec import Bounds
    >>> box = Bounds(0.0, 1.0, 2.0, 3.0, crs=crs_from_user_input(4326))
    >>> box.crs, box.to_dict()["crs"]
    ('EPSG:4326', 'EPSG:4326')
    
Source code in src/digitalearth/base/spec/bounds.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        The four edges as Python floats, and the CRS as held: `None`, an EPSG integer or a string, which is not
        checked. The constructor has already turned a CRS object into `"EPSG:<code>"` (or WKT when its
        definition carries no EPSG code) and refused a CRS with no written form, so writing a rectangle does
        not fail on its CRS.

    Examples:
        - The edges keep their names, so the ordering cannot be misread:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> Bounds(0.0, 1.0, 2.0, 3.0, crs=4326).to_dict()
            {'xmin': 0.0, 'ymin': 1.0, 'xmax': 2.0, 'ymax': 3.0, 'crs': 4326}

            ```
        - A CRS object is written by the EPSG code it is held as:
            ```python
            >>> from pyramids.base.crs import crs_from_user_input
            >>> from digitalearth.base.spec import Bounds
            >>> box = Bounds(0.0, 1.0, 2.0, 3.0, crs=crs_from_user_input(4326))
            >>> box.crs, box.to_dict()["crs"]
            ('EPSG:4326', 'EPSG:4326')

            ```
    """
    return {
        # The constructor has already refused a non-finite edge, but not a numpy float, which json cannot write.
        "xmin": float(self.xmin),
        "ymin": float(self.ymin),
        "xmax": float(self.xmax),
        "ymax": float(self.ymax),
        "crs": crs_to_json(self.crs, "Bounds.crs"),
    }

union(other) #

Return the smallest rectangle containing both.

Parameters:

Name Type Description Default
other Bounds

The rectangle to merge in. Must already be in the same CRS — reproject it first with :meth:to_crs rather than relying on a silent reinterpretation of the numbers.

required

Returns:

Type Description
Bounds

The enclosing rectangle, in this rectangle's CRS.

Raises:

Type Description
ValueError

if the two carry different CRSs. Unioning across CRSs by ignoring them is how an extent ends up describing a region nobody asked for.

Examples:

  • Two layers' extents, framed together:
    >>> from digitalearth.base.spec import Bounds
    >>> a = Bounds(0.0, 0.0, 2.0, 2.0, crs=3857)
    >>> b = Bounds(1.0, -5.0, 3.0, 1.0, crs=3857)
    >>> a.union(b).as_bbox()
    [0.0, -5.0, 3.0, 2.0]
    
Source code in src/digitalearth/base/spec/bounds.py
def union(self, other: "Bounds") -> "Bounds":
    """Return the smallest rectangle containing both.

    Args:
        other: The rectangle to merge in. Must already be in the same CRS — reproject it first with
            :meth:`to_crs` rather than relying on a silent reinterpretation of the numbers.

    Returns:
        The enclosing rectangle, in this rectangle's CRS.

    Raises:
        ValueError: if the two carry different CRSs. Unioning across CRSs by ignoring them is how an
            extent ends up describing a region nobody asked for.

    Examples:
        - Two layers' extents, framed together:
            ```python
            >>> from digitalearth.base.spec import Bounds
            >>> a = Bounds(0.0, 0.0, 2.0, 2.0, crs=3857)
            >>> b = Bounds(1.0, -5.0, 3.0, 1.0, crs=3857)
            >>> a.union(b).as_bbox()
            [0.0, -5.0, 3.0, 2.0]

            ```
    """
    if not same_crs(self.crs, other.crs):
        raise ValueError(
            f"union needs both rectangles in one CRS; got {self.crs!r} and {other.crs!r} — "
            "reproject one with to_crs() first"
        )
    return Bounds(
        min(self.xmin, other.xmin),
        min(self.ymin, other.ymin),
        max(self.xmax, other.xmax),
        max(self.ymax, other.ymax),
        self.crs,
    )

Scale — how a value becomes a colour#

The limits were derived in several places, the "a constant band has no range" guard was written out five times, and three tiers each called cleopatra's classifier with their own error handling. The copies agreed by luck and drifted where they did not. A Scale derived once and reused across frames is what stops an animation's colours flickering, and what lets a legend show the colours that were actually drawn.

It also states what the ramp cannot colour: missing for a value it cannot place, and over/under for one past either end of the domain. All three travel in the stored form, so a tier that reads a figure back can agree with the tier that drew it on the colour of a nodata cell and of a clipped value — see with_extremes to state them and extremes to read back only the ones that were stated. The static tier is the only one that reads them back so far; the other three do not.

straddles answers the one question a diverging ramp has to pass: does the domain run on both sides of the value the ramp would be centred on? Centred outside it, one arm is never drawn and the other carries every value — so a backend offers divergence and declines it from the same reader, with the same strict comparison cleopatra validates a diverging center with.

digitalearth.base.spec.scale.Scale dataclass #

A resolved mapping from values to colours, and the domain it covers.

Attributes:

Name Type Description
vmin float

Lower limit of the domain.

vmax float

Upper limit. Always strictly greater than vmin — see :meth:from_values for why.

scheme str | tuple[float, ...] | None

Classification scheme name ("quantiles", "equal_interval", …), or None for a continuous ramp.

breaks tuple[float, ...]

Class edges when scheme is set; empty for a continuous ramp. k classes give k + 1 edges, so a legend can label each class by the range it covers.

categories tuple[Any, ...]

The distinct values a categorical scale colours, in the order their colours were assigned.

missing str | None

Colour for a value the scale cannot place — nodata, or a category it never saw.

over str | None

Colour for a value above vmax, or None to leave the renderer's own treatment of it alone.

under str | None

Colour for a value below vmin, likewise. The pair is what tells a clipped field apart from one that really peaks at its limit: see with_extremes() for how a tier states them and extremes() for how one reads them back. Neither is validated as a colour here — the renderer that resolves it is the one that can refuse it.

Raises:

Type Description
ValueError

if vmin/vmax are not finite, if vmax is not greater than vmin, or if breaks holds a single edge — one edge bounds no class. Build through :meth:from_values rather than widening by hand.

Examples:

  • Derive a continuous scale from data, and read back the limits it settled on:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([1.0, 5.0, 9.0])
    >>> scale.vmin, scale.vmax
    (1.0, 9.0)
    >>> scale.is_classified
    False
    
  • A constant band is widened rather than dividing by zero:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([7.0, 7.0, 7.0]).as_limits()
    (7.0, 8.0)
    
  • Nothing finite falls back to the unit range, so a builder still has limits to hand a colormap:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([]).as_limits()
    (0.0, 1.0)
    
Source code in src/digitalearth/base/spec/scale.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
@dataclass(frozen=True)
class Scale:
    """A resolved mapping from values to colours, and the domain it covers.

    Attributes:
        vmin: Lower limit of the domain.
        vmax: Upper limit. Always strictly greater than `vmin` — see :meth:`from_values` for why.
        scheme: Classification scheme name (``"quantiles"``, ``"equal_interval"``, …), or ``None`` for a
            continuous ramp.
        breaks: Class edges when `scheme` is set; empty for a continuous ramp. ``k`` classes give ``k + 1``
            edges, so a legend can label each class by the range it covers.
        categories: The distinct values a categorical scale colours, in the order their colours were assigned.
        missing: Colour for a value the scale cannot place — nodata, or a category it never saw.
        over: Colour for a value above `vmax`, or `None` to leave the renderer's own treatment of it alone.
        under: Colour for a value below `vmin`, likewise. The pair is what tells a clipped field apart from
            one that really peaks at its limit: see `with_extremes()` for how a tier states them and
            `extremes()` for how one reads them back. Neither is validated as a colour here — the renderer
            that resolves it is the one that can refuse it.

    Raises:
        ValueError: if `vmin`/`vmax` are not finite, if `vmax` is not greater than `vmin`, or if `breaks`
            holds a single edge — one edge bounds no class. Build through :meth:`from_values` rather than
            widening by hand.

    Examples:
        - Derive a continuous scale from data, and read back the limits it settled on:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_values([1.0, 5.0, 9.0])
            >>> scale.vmin, scale.vmax
            (1.0, 9.0)
            >>> scale.is_classified
            False

            ```
        - A constant band is widened rather than dividing by zero:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_values([7.0, 7.0, 7.0]).as_limits()
            (7.0, 8.0)

            ```
        - Nothing finite falls back to the unit range, so a builder still has limits to hand a colormap:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_values([]).as_limits()
            (0.0, 1.0)

            ```
    """

    vmin: float
    vmax: float
    scheme: str | tuple[float, ...] | None = None
    breaks: tuple[float, ...] = ()
    categories: tuple[Any, ...] = ()
    missing: str | None = None
    over: str | None = None
    under: str | None = None
    _colors: tuple[str, ...] = field(default=(), repr=False)

    def __post_init__(self) -> None:
        """Refuse a domain nothing can be normalised against.

        Raises:
            ValueError: for a non-finite or degenerate domain, or for class edges that bound no class.
        """
        for name, value in (("vmin", self.vmin), ("vmax", self.vmax)):
            if not isfinite(value):
                raise ValueError(f"Scale needs a finite domain; got {name}={value!r}")
        if self.vmax <= self.vmin:
            raise ValueError(
                f"Scale needs vmax > vmin; got vmin={self.vmin}, vmax={self.vmax}. "
                "Build with Scale.from_values(), which widens a constant domain for you"
            )
        if self.breaks and len(self.breaks) < 2:
            raise ValueError(
                f"Scale needs at least two class edges to bound one class; got {self.breaks}. "
                "An empty breaks tuple is how a continuous ramp says it cuts no classes"
            )
        if len(tuple(self.categories)) != len(tuple(self._colors)):
            # `categorical()` checks this, but the constructor is public and color_for indexes _colors by
            # the category's position — a short list raises IndexError from a lookup, far from the cause.
            raise ValueError(
                f"a categorical Scale needs one colour per category; got {len(tuple(self.categories))} "
                f"categories and {len(tuple(self._colors))} colours"
            )
        # Coerce every sequence field to a tuple. `scheme` is a documented sequence-of-edges input on three
        # tiers, so a caller's list really does arrive here; stored as given it would leave the scale
        # unhashable and editable from outside, which is not what "frozen value object" promises.
        object.__setattr__(self, "breaks", tuple(self.breaks))
        object.__setattr__(
            self,
            "categories",
            tuple(frozen_value(category) for category in self.categories),
        )
        object.__setattr__(self, "_colors", tuple(self._colors))
        if isinstance(self.scheme, set):
            # Class edges are ordered data and a set has no order, so tuple(set) would pick one by hash.
            raise ValueError(
                f"Scale got scheme={self.scheme!r}: a set has no ordering, but class edges are ordered. "
                "Pass a list or tuple of edges, or a scheme name"
            )
        if isinstance(self.scheme, list):
            object.__setattr__(self, "scheme", tuple(self.scheme))

    # ------------------------------------------------------------------ builders

    @classmethod
    def from_values(
        cls,
        values: Any,
        *,
        vmin: float | None = None,
        vmax: float | None = None,
        scheme: str | None = None,
        k: int = DEFAULT_CLASS_COUNT,
        missing: str | None = None,
    ) -> "Scale":
        """Derive a scale from data, applying the one widening rule every tier used to write out.

        Two degenerate cases are handled here rather than at five call sites:

        * **nothing finite** — the domain falls back to ``(0.0, 1.0)``. A builder still needs limits to hand a
          colormap, and a stack whose every frame is off the view has no range to report.
        * **a constant domain** — ``vmax`` becomes ``vmin + 1``. Normalising against a zero-width range
          divides by zero; the five copies of this rule all chose ``+ 1``, so that is what is kept.

        Args:
            values: The data to measure. Non-finite values are ignored.
            vmin: Explicit lower limit, overriding the measured one.
            vmax: Explicit upper limit.
            scheme: Classification scheme to cut classes with, or ``None`` for a continuous ramp.
            k: Number of classes when `scheme` is set.
            missing: Colour for values the scale cannot place.

        Returns:
            The resolved scale.

        Raises:
            ValueError: if `scheme` is unknown to the classifier, or `k` is not a usable class count. The
                message names the scheme and the count, since a classifier error alone says neither.

        Examples:
            - An explicit limit wins over the measured one:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_values([1.0, 2.0, 3.0], vmax=10.0).as_limits()
                (1.0, 10.0)

                ```
        """
        lo, hi = cls._limits(values, vmin, vmax)
        breaks: tuple[float, ...] = ()
        if scheme is not None:
            breaks = cls._breaks(values, scheme, k)
        return cls(lo, hi, scheme=scheme, breaks=breaks, missing=missing)

    @classmethod
    def from_finite(
        cls,
        values: Any,
        *,
        vmin: float | None = None,
        vmax: float | None = None,
        missing: str | None = None,
    ) -> "Scale":
        """Derive a scale from values the caller has already filtered to finite ones.

        :meth:`from_values` filters first, which costs a full pass and a compacted copy of every finite
        value. Several callers had just done exactly that and thrown the result away — on a 2160x4320 global
        canvas that is a second ~75 MB allocation for an answer already in hand. This is the same rule
        without the second pass.

        Args:
            values: Finite values only. Passing non-finite ones here produces a NaN domain rather than an
                error, which is the price of skipping the check — use :meth:`from_values` if unsure.
            vmin: Explicit lower limit, overriding the measured one.
            vmax: Explicit upper limit.
            missing: Colour for values the scale cannot place.

        Returns:
            The resolved scale.

        Raises:
            ValueError: if both limits are given the wrong way round.

        Examples:
            - The same domain as `from_values`, without re-filtering:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_finite([1.0, 5.0, 9.0]).as_limits()
                (1.0, 9.0)

                ```
            - An empty selection still yields limits a colormap can take:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_finite([]).as_limits()
                (0.0, 1.0)

                ```
        """
        array = np.asarray(values, dtype="float64").ravel()
        lo, hi = cls._apply_limits(array, vmin, vmax)
        return cls(lo, hi, missing=missing)

    @classmethod
    def breaks_of(
        cls,
        values: Any,
        scheme: str,
        k: int = DEFAULT_CLASS_COUNT,
        *,
        clip: tuple[float | None, float | None] | None = None,
    ) -> tuple[float, ...]:
        """Cut class edges without deriving a domain, for a caller that only wants the classes.

        The three classification sites read ``.breaks`` and nothing else, so measuring the domain for them —
        a full pass over the data plus a compacted copy of every finite value — is work whose result is
        discarded. This is the same classifier, the same error, and no measurement.

        Args:
            values: The data to classify.
            scheme: Classification scheme name.
            k: Number of classes.
            clip: An optional ``(vmin, vmax)`` window the classes are pinned to (#378). When given, the
                recorded domain is the window and a cell outside it is clamped to the nearer bound, so an
                outlier lands in the first or last class instead of stretching the classes and two bands
                given the same window share one comparable scale. The interior is the scheme's own: an
                ``"equal_interval"`` window is split into equal parts of the window itself, while a
                data-driven scheme (``"quantiles"``, ``"natural_breaks"``, …) cuts its interior over the
                clamped data and only has its *outer* edges pinned to the bounds — the two synthetic bound
                points are never mixed into the statistic. Either bound may be ``None`` to leave that side at
                the data's own extent. A reversed window (``vmin > vmax``) is refused, and a zero-width one
                (``vmin == vmax``) is widened, the same as :meth:`from_values` treats explicit limits.

        Returns:
            The class edges, ``k + 1`` of them for ``k`` classes.

        Raises:
            ValueError: if the scheme is unknown to the classifier, `k` is not a usable class count, a
                `clip` window is reversed, or a data-driven scheme's window holds fewer than two distinct
                values. The message names the scheme and the count, as :meth:`from_values` does.

        Examples:
            - Three classes, four edges, and no domain derived:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> len(Scale.breaks_of(list(range(10)), "equal_interval", 3))
                4

                ```
            - An ``equal_interval`` window is split into equal parts of the window; the 999 outlier lands in
              the top class rather than stretching the edges:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.breaks_of([5, 10, 15, 20, 40, 999], "equal_interval", 2, clip=(0.0, 100.0))
                (0.0, 50.0, 100.0)

                ```
        """
        if clip is None:
            return cls._breaks(values, scheme, k)
        lo, hi = cls._clip_window(clip)
        clamped = cls._clamped_finite(values, lo, hi)
        if scheme == "equal_interval":
            # equal_interval's classes are a pure split of the domain, so cutting the window itself gives
            # equal parts of `[lo, hi]` whatever the data holds. A data-driven scheme must not take this
            # path: splitting the window would discard the distribution the scheme names. An open bound
            # falls back to the clamped data's extent, or to a unit span when no cell survived.
            left = (
                float(lo) if lo is not None else cls._open_bound(clamped, np.min, 0.0)
            )
            right = (
                float(hi) if hi is not None else cls._open_bound(clamped, np.max, 1.0)
            )
            if right <= left:
                left, right = cls._widen(left)
            return tuple(float(edge) for edge in np.linspace(left, right, k + 1))
        if np.unique(clamped).size < 2:
            # A data-driven scheme needs spread; with every cell on one side of the window (or a degenerate
            # window) the clamped sample is one value and the classifier cannot cut it. Name the window, not
            # the data, since the window is the cause.
            raise ValueError(
                f"scheme={scheme!r} cannot cut classes in the window [{lo}, {hi}]: it holds fewer than two "
                "distinct values, so every cell falls on one side of it; widen the window, or use "
                "'equal_interval', which splits the window regardless of the data"
            )
        edges = cls._breaks(clamped, scheme, k)
        return cls._pin_outer_edges(edges, lo, hi)

    @staticmethod
    def _clip_window(
        clip: tuple[float | None, float | None],
    ) -> tuple[float | None, float | None]:
        """Validate a ``(vmin, vmax)`` clip window, refusing a reversed one and widening a zero-width one.

        Args:
            clip: A ``(vmin, vmax)`` pair; ``None`` on a side leaves it open.

        Returns:
            The window, with a ``vmin == vmax`` pair widened (as :meth:`from_limits` widens a constant).

        Raises:
            ValueError: for a reversed window, with the same message :meth:`from_values` gives a reversed
                explicit pair — so the classified and continuous paths refuse a transposed pair alike.
        """
        lo, hi = clip
        if lo is not None and hi is not None:
            if hi < lo:
                raise ValueError(
                    f"Scale needs vmin <= vmax; got vmin={float(lo)}, vmax={float(hi)}. Both were given "
                    "explicitly, so this is a reversed pair rather than a constant domain to widen — check "
                    "their order"
                )
            if hi == lo:
                return Scale._widen(float(lo))
        return lo, hi

    @staticmethod
    def _clamped_finite(values: Any, lo: float | None, hi: float | None) -> Any:
        """Return the finite values clamped into the ``[lo, hi]`` window, in one pass.

        Args:
            values: The data to confine; non-finite and masked cells are dropped.
            lo: Lower bound, or ``None`` to leave the low side at the data's extent.
            hi: Upper bound, or ``None`` to leave the high side open.

        Returns:
            A 1-D float array clamped into the window. ``np.clip`` treats a ``None`` bound as no bound on
            that side (relied on since numpy 2); both ``None`` is the no-op the ``clip=(None, None)`` path
            takes.
        """
        array = np.ma.compressed(
            np.ma.masked_invalid(np.ma.asarray(values, dtype="float64"))
        )
        return np.clip(array, lo, hi)

    @staticmethod
    def _open_bound(clamped: Any, reducer: Any, default: float) -> float:
        """Return the clamped data's extent on one side, or ``default`` when no cell survived.

        Args:
            clamped: The clamped finite values.
            reducer: ``numpy.min`` or ``numpy.max`` — which extent to take.
            default: The bound to use when ``clamped`` is empty.

        Returns:
            ``float(reducer(clamped))``, or ``default`` for an empty array.
        """
        return float(reducer(clamped)) if clamped.size else default

    @staticmethod
    def _pin_outer_edges(
        edges: tuple[float, ...], lo: float | None, hi: float | None
    ) -> tuple[float, ...]:
        """Replace the outer class edges with the window bounds, keeping the scheme's interior.

        The clamped data lies inside ``[lo, hi]``, so the classifier's own outer edges are the clamped
        extent; swapping them for the window bounds pins the recorded domain to the window without touching
        the interior cuts. Any interior edge that coincides with a bound is dropped so the edges stay
        strictly increasing.

        Args:
            edges: The classifier's edges over the clamped data.
            lo: Lower bound to pin, or ``None`` to keep the classifier's own.
            hi: Upper bound to pin, or ``None`` to keep the classifier's own.

        Returns:
            The edges with their ends pinned to the given bounds.
        """
        left = float(lo) if lo is not None else edges[0]
        right = float(hi) if hi is not None else edges[-1]
        interior = [edge for edge in edges[1:-1] if left < edge < right]
        return (left, *interior, right)

    @classmethod
    def from_limits(
        cls, vmin: float, vmax: float, *, missing: str | None = None
    ) -> "Scale":
        """Build from limits that were derived elsewhere — a frozen stack range, or a caller's `clim=`.

        Args:
            vmin: Lower limit.
            vmax: Upper limit.
            missing: Colour for values the scale cannot place.

        Returns:
            The scale, with the same widening rule applied so a degenerate pair cannot get through.

        Examples:
            - The frozen range of a time stack becomes a scale every frame shares:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(2.0, 9.0).as_limits()
                (2.0, 9.0)

                ```
            - A degenerate pair is widened here too, rather than raising on the caller:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(4.0, 4.0).as_limits()
                (4.0, 5.0)

                ```
            - A constant too large for ``+ 1`` to move widens by one representable step instead:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> low, high = Scale.from_limits(1e20, 1e20).as_limits()
                >>> low == 1e20, high > low
                (True, True)

                ```
        """
        lo, hi = float(vmin), float(vmax)
        if not (isfinite(lo) and isfinite(hi)):
            raise ValueError(f"Scale needs finite limits; got ({vmin!r}, {vmax!r})")
        if hi <= lo:
            lo, hi = Scale._widen(lo)
        return cls(lo, hi, missing=missing)

    @classmethod
    def categorical(
        cls,
        categories: Sequence[Any],
        colors: Sequence[str],
        *,
        missing: str | None = None,
    ) -> "Scale":
        """Build a scale over unordered categories rather than a numeric range.

        Args:
            categories: The distinct values, in the order their colours were assigned.
            colors: One colour per category.
            missing: Colour for a value that is not one of `categories`.

        Returns:
            The categorical scale. Its numeric domain is the category *index* range, which is what a renderer
            needs to place a swatch; `vmin`/`vmax` are not meaningful as data values.

        Raises:
            ValueError: if there are no categories, or the counts do not match.

        Examples:
            - Three categories and their colours:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.categorical(["a", "b", "c"], ["#f00", "#0f0", "#00f"])
                >>> scale.is_categorical, scale.color_for("b")
                (True, '#0f0')

                ```
        """
        cats = list(categories)
        cols = list(colors)
        if not cats:
            raise ValueError("a categorical Scale needs at least one category")
        if len(cats) != len(cols):
            raise ValueError(
                f"a categorical Scale needs one colour per category; got {len(cats)} categories "
                f"and {len(cols)} colours"
            )
        return cls(
            0.0,
            float(max(len(cats) - 1, 1)),
            categories=tuple(cats),
            missing=missing,
            _colors=tuple(cols),
        )

    # ------------------------------------------------------------------ internals

    @staticmethod
    def _limits(
        values: Any, vmin: float | None, vmax: float | None
    ) -> tuple[float, float]:
        """Measure the domain, honouring explicit limits and widening a constant one.

        Args:
            values: The data to measure.
            vmin: Explicit lower limit, or ``None`` to measure.
            vmax: Explicit upper limit, or ``None`` to measure.

        Returns:
            A ``(lo, hi)`` pair with ``hi > lo`` guaranteed.
        """
        # Imported here, not at module scope: `base/arrays.py` reads this subpackage's DEFAULT_BAND, so a
        # module-level edge back to it makes `import digitalearth.base.arrays` circular. `base/spec/` holds
        # the value types and is the lower layer of the two, so the deferral belongs on this side.
        from digitalearth.base.arrays import finite

        measured = finite(values)
        return Scale._apply_limits(measured, vmin, vmax)

    @staticmethod
    def _apply_limits(
        measured: Any, vmin: float | None, vmax: float | None
    ) -> tuple[float, float]:
        """Turn an already-finite array plus any explicit limits into a usable domain.

        Args:
            measured: Finite values, as :func:`digitalearth.base.arrays.finite` returns them.
            vmin: Explicit lower limit, or ``None`` to measure.
            vmax: Explicit upper limit, or ``None`` to measure.

        Returns:
            A ``(lo, hi)`` pair with ``hi > lo`` guaranteed.

        Raises:
            ValueError: if both limits were given and they are the wrong way round.
        """
        data_lo, data_hi = (
            (float(measured.min()), float(measured.max()))
            if measured.size
            else (0.0, 1.0)
        )
        lo = data_lo if vmin is None else float(vmin)
        hi = data_hi if vmax is None else float(vmax)
        if vmin is not None and vmax is not None and hi < lo:
            # Two limits the caller wrote down, in the wrong order. An explicit *equal* pair is a caller
            # saying the range is constant, and is widened like a measured one — the web tier's raster path
            # has always done that. A reversed pair says nothing of the kind: widening it would drop the
            # caller's vmax and draw against (vmin, vmin + 1), hiding an obvious typo behind a plausible
            # range.
            raise ValueError(
                f"Scale needs vmin <= vmax; got vmin={lo}, vmax={hi}. Both were given explicitly, so this "
                "is a reversed pair rather than a constant domain to widen — check their order"
            )
        if measured.size and vmax is None and vmin is not None and lo >= data_hi:
            # One explicit limit, on the wrong side of the data. The widening below would discard it just
            # as silently as a reversed pair, and draw against a range holding none of the values.
            raise ValueError(
                f"Scale got vmin={lo}, which is at or above every value in the data (max {data_hi}); "
                "nothing would be drawn in range — check the limit or drop it"
            )
        if measured.size and vmin is None and vmax is not None and hi <= data_lo:
            raise ValueError(
                f"Scale got vmax={hi}, which is at or below every value in the data (min {data_lo}); "
                "nothing would be drawn in range — check the limit or drop it"
            )
        if hi <= lo:
            # The rule all five copies chose: a constant domain is widened by one rather than divided by.
            lo, hi = Scale._widen(lo)
        return lo, hi

    @staticmethod
    def _widen(value: float) -> tuple[float, float]:
        """Return a domain of non-zero width around a constant ``value``.

        Args:
            value: The single value the whole band holds.

        Returns:
            A ``(lo, hi)`` pair with ``hi > lo``, both finite, and `value` inside it.

        Note:
            ``+ 1.0`` is the rule the five consolidated copies chose and it stays the rule wherever it
            works, because a whole unit is a span a colour ramp can show. **Where it stops working is not
            one threshold.** ``2**53`` is where the gap between neighbouring doubles first exceeds one
            (measured: 2.0 there, against 1.0 at ``2**52``), and it is where the addition first vanishes —
            ``2**53 + 1.0 == 2**53`` — so the widened ``hi`` came back equal to ``lo`` and the constructor
            refused the scale: a constant band holding a large sentinel or an epoch-nanosecond count could
            not be scaled at all. But it is not a ceiling above which the rule never works, and it is not
            symmetric. ``(2**53 + 2.0) + 1.0`` still moves, because round-to-nearest carries that sum to
            the next representable double; and at ``-2**53`` and ``-2**53 - 2.0`` the addition still widens,
            because on the negative side it moves toward zero, where the spacing is finer. So the question
            is asked of the value rather than of its magnitude: ``widened > value`` says whether *this* one
            moved. Where it did not, the smallest span that exists is one representable step, so that is
            what is used. At the very top of the float range there is no step above — ``nextafter`` returns
            infinity, which the constructor refuses — so the floor moves down instead and `value` stays the
            upper limit.
        """
        widened = value + 1.0
        if widened > value:
            return value, widened
        stepped = nextafter(value, inf)
        if isfinite(stepped):
            return value, stepped
        return nextafter(value, -inf), value

    @staticmethod
    def _breaks(values: Any, scheme: str, k: int) -> tuple[float, ...]:
        """Cut class edges with the registered classifier, blaming the caller's arguments when it refuses.

        Args:
            values: The data to classify.
            scheme: Scheme name.
            k: Number of classes.

        Returns:
            The class edges, ``k + 1`` of them for ``k`` classes.

        Raises:
            ValueError: when the classifier refuses — an unknown scheme, a class count below one, or a
                constant column that cannot be cut. Three tiers each wrote their own version of this
                message; the classifier's own error names none of the three arguments, so they are
                named here.
            RuntimeError: if no classifier has been registered — see
                :func:`~digitalearth.base.registry.register_classifier`.
        """
        classify = get_classifier()
        numbers = np.asarray(values, dtype="float64")
        try:
            edges, _ = classify(numbers, scheme, k)
        except ValueError as err:
            raise ValueError(
                f"scheme={scheme!r} with k={k} cannot classify this data: {err}"
            ) from err
        return tuple(float(e) for e in edges)

    # ------------------------------------------------------------------ readers

    @property
    def is_classified(self) -> bool:
        """Whether this scale cuts classes rather than running a continuous ramp.

        Returns:
            ``True`` when a scheme produced class edges.

        Examples:
            - A scheme cuts classes, and the scale says so:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
                >>> scale.is_classified
                True
                >>> len(scale.class_ranges())
                2

                ```
            - Without one it runs a continuous ramp and cuts nothing:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values([0.0, 10.0])
                >>> scale.is_classified
                False
                >>> scale.breaks
                ()

                ```
        """
        return bool(self.breaks)

    @property
    def is_categorical(self) -> bool:
        """Whether this scale colours unordered categories rather than a numeric range.

        Returns:
            ``True`` when categories were supplied.

        Examples:
            - A categorical scale knows its categories by name:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.categorical(["land", "sea"], ["#8b4513", "#1e90ff"])
                >>> scale.is_categorical
                True
                >>> scale.categories
                ('land', 'sea')

                ```
            - A numeric scale is not categorical, however few values it saw:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_values([1.0, 2.0]).is_categorical
                False

                ```
        """
        return bool(self.categories)

    def straddles(self, center: float = 0.0) -> bool:
        """Whether this domain runs on **both** sides of `center` — the test a diverging ramp has to pass.

        A diverging colormap puts a neutral colour at `center` and an arm on either side of it. Centred
        outside the domain it is worse than a sequential ramp rather than better: one arm is never drawn, so
        the other carries every value and the picture loses the contrast the ramp was chosen for. Asking the
        domain first is what lets a tier offer divergence and decline it on the same call.

        The comparison is **strict**, deliberately: a centre sitting exactly on `vmin` or `vmax` leaves one
        arm holding a single value, and it is also the comparison cleopatra validates a diverging `center`
        with — `not (vmin < center < vmax)` raises
        *"diverging 'center' (0.0) must lie strictly between vmin (...) and vmax (...)"* there — so a
        centre this reader called straddled but cleopatra refuses cannot happen.

        Args:
            center: The value a diverging ramp would be centred on. Zero by default, which is the centre of
                every anomaly, difference and trend field. A non-finite centre straddles nothing — answered
                rather than compared, since `nan` fails every comparison silently.

        Returns:
            `True` when `vmin < center < vmax`.

        Examples:
            - An anomaly field with both signs straddles zero; a rainfall total does not:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_values([-2.0, -1.0, 3.0, 6.0]).straddles()
                True
                >>> Scale.from_values([12.0, 40.0, 88.0]).straddles()
                False

                ```
            - A centre need not be zero — a departure from a long-term mean sits wherever that mean does:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(283.0, 293.0).straddles(288.0)
                True
                >>> Scale.from_limits(283.0, 293.0).straddles(273.15)
                False

                ```
            - The ends are **not** straddled, which is the comparison cleopatra makes too; and a
              non-finite centre is answered rather than compared:
                ```python
                >>> from math import inf, nan
                >>> from digitalearth.base.spec import Scale
                >>> domain = Scale.from_limits(0.0, 10.0)
                >>> domain.straddles(0.0), domain.straddles(10.0)
                (False, False)
                >>> domain.straddles(nan), domain.straddles(inf)
                (False, False)

                ```
        """
        if not isfinite(center):
            return False
        return self.vmin < center < self.vmax

    def as_limits(self) -> tuple[float, float]:
        """Return the ``(vmin, vmax)`` pair a renderer's normaliser takes.

        Returns:
            The domain, with ``vmax > vmin`` guaranteed.

        Examples:
            - The pair a normaliser is built from, ready to unpack:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> vmin, vmax = Scale.from_values([3.0, 7.0, 5.0]).as_limits()
                >>> vmin, vmax
                (3.0, 7.0)
                >>> vmax - vmin
                4.0

                ```
            - A constant band still yields a usable span rather than a zero-width one:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_values([7.0, 7.0]).as_limits()
                (7.0, 8.0)

                ```
        """
        return self.vmin, self.vmax

    def with_extremes(
        self,
        *,
        missing: str | None = None,
        over: str | None = None,
        under: str | None = None,
    ) -> "Scale":
        """Return this scale with the extreme colours a caller stated, leaving the rest as they were.

        A scale is normally *derived* — `from_values()` measures the domain from the data — while the
        colours for what falls outside it are the caller's styling and arrive separately. So stating them is
        a step on an existing scale rather than three more arguments on every builder.

        `None` means "leave this one alone", which is what lets two calls compose and matches
        `matplotlib.colors.Colormap.with_extremes`, the method a renderer ends up handing these to: it copies
        the colormap and delegates to `Colormap._set_extremes`, which is where the rule really lives — three
        branches, `if bad is not None` / `if under is not None` / `if over is not None`, under a docstring
        reading *"Parameters that are None are left unchanged"* (read off matplotlib 3.11.1). The public
        `Colormap.set_extremes` is a one-line delegate to that helper and is pending-deprecated as of
        matplotlib 3.11 (`@_api.deprecated("3.11", pending=True, alternative="cmap.with_extremes(...)")`), so
        it is not what this rule is borrowed from. So `None` cannot
        **clear** a colour already stated: `with_extremes(over=None)` on a scale whose `over` is `'#ff0000'`
        answers `{'over': '#ff0000'}` again, and a call with no arguments at all is accepted and changes
        nothing. Clearing one is :meth:`without_extremes`'s job — two verbs rather than one keyword carrying a
        sentinel, which keeps all three parameters a plain `Optional[str]` and keeps `None` meaning exactly
        what it means in matplotlib. The scale itself is immutable, so the stated colours come back on a
        **new** scale: a domain derived once and shared across an animation's frames must not pick up one
        frame's styling.

        Args:
            missing: Colour for a value the scale cannot place, or `None` to keep the current `missing`.
            over: Colour for a value above `vmax`, or `None` to keep the current `over`.
            under: Colour for a value below `vmin`, or `None` to keep the current `under`.

        Returns:
            A new scale with the same domain, scheme, classes and categories, carrying the stated colours.
            Never `self`, even when nothing was stated.

        Examples:
            - State all three on a derived scale, and read them back:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values([1.0, 9.0]).with_extremes(
                ...     missing="#cccccc", over="#ff0000", under="#0000ff"
                ... )
                >>> scale.extremes()
                {'missing': '#cccccc', 'over': '#ff0000', 'under': '#0000ff'}

                ```
            - A colour stated earlier survives a later call that does not name it:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> top = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
                >>> top.with_extremes(missing="#cccccc").extremes()
                {'missing': '#cccccc', 'over': '#ff0000'}

                ```
            - The scale it was called on is unchanged, and the domain travels through:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> original = Scale.from_limits(0.0, 10.0)
                >>> original.with_extremes(under="#0000ff").as_limits()
                (0.0, 10.0)
                >>> original.under is None
                True

                ```
            - `None` keeps rather than clears, and a call that states nothing is still a new scale:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
                >>> stated.with_extremes(over=None).extremes()
                {'over': '#ff0000'}
                >>> bare = stated.with_extremes()
                >>> bare.extremes(), bare is stated
                ({'over': '#ff0000'}, False)
                >>> stated.without_extremes("over").extremes()
                {}

                ```
        """
        return replace(
            self,
            missing=self.missing if missing is None else missing,
            over=self.over if over is None else over,
            under=self.under if under is None else under,
        )

    def without_extremes(self, *names: str) -> "Scale":
        """Return this scale with the named extreme colours cleared, back to stating none of them.

        The other direction of :meth:`with_extremes`, and a separate verb because `None` there already
        means "keep this one" — the rule matplotlib's own `with_extremes` follows, through
        `Colormap._set_extremes`. Overloading `None` to mean "clear" would break the composition two
        `with_extremes` calls rely on; giving it a sentinel value instead would widen all three parameters
        from `Optional[str]` to a union every caller and every type check has to carry. So the way back is a
        call of its own, and `dataclasses.replace` stops being the only route to it.

        What it is for: a stated extreme is *styling*, and a derived scale travels — a domain measured over a
        stack is handed to each frame, and a stored figure's scale is read back and reused. Handing one on
        without the previous caller's over colour is then a call rather than a rebuild.

        Args:
            *names: The extremes to clear, from `"missing"`, `"over"` and `"under"`. Named none, it clears
                all three, which is how a scale says it states no extremes at all. Naming one twice is the
                same as naming it once.

        Returns:
            A new scale with the same domain, scheme, classes and categories, stating the extremes it was
            not asked to clear. Never `self`, even when there was nothing to clear.

        Raises:
            ValueError: for a name that is not one of the three, since a silently ignored name would read as
                a colour that had been cleared.

        Examples:
            - A colour stated earlier is cleared by name, and the rest stay stated:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
                ...     missing="#cccccc", over="#ff0000"
                ... )
                >>> stated.without_extremes("over").extremes()
                {'missing': '#cccccc'}

                ```
            - Named nothing it clears all three, and the scale it was called on is unchanged:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
                >>> stated.without_extremes().extremes()
                {}
                >>> stated.extremes()
                {'over': '#ff0000'}

                ```
            - It is the clear `with_extremes` cannot express, since `None` there keeps:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff")
                >>> stated.with_extremes(under=None).extremes()
                {'under': '#0000ff'}
                >>> stated.without_extremes("under").extremes()
                {}

                ```
            - A name that is not one of the three is refused rather than ignored:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 10.0).without_extremes("bad")
                Traceback (most recent call last):
                    ...
                ValueError: Scale.without_extremes got unknown extremes ['bad']; known: missing, over, under

                ```
            - The domain and the classes travel through it:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values([1.0, 4.0, 9.0], scheme="quantiles", k=2)
                >>> cleared = scale.with_extremes(missing="#cccccc").without_extremes()
                >>> cleared.as_limits(), cleared.is_classified
                ((1.0, 9.0), True)

                ```
        """
        unknown = sorted({name for name in names if name not in _EXTREME_NAMES})
        if unknown:
            raise ValueError(
                f"Scale.without_extremes got unknown extremes {unknown}; "
                f"known: {', '.join(_EXTREME_NAMES)}"
            )
        cleared = set(names) if names else set(_EXTREME_NAMES)
        return replace(
            self,
            missing=None if "missing" in cleared else self.missing,
            over=None if "over" in cleared else self.over,
            under=None if "under" in cleared else self.under,
        )

    def extremes(self) -> dict[str, str]:
        """Return only the extreme colours this scale states, keyed by which extreme they colour.

        The keys absent from the mapping are exactly the extremes a renderer must **not** overwrite, which is
        what makes "did the caller state any?" one test and keeps a tier from pushing a default colour onto a
        colormap the caller built themselves.

        Returns:
            A new plain `dict` over `"missing"`, `"over"` and `"under"`, holding only the ones that are set
            — empty when the scale states none. The keys come in that order, whatever order they were
            stated in, so `to_dict()` writes a stored figure the same way twice.

        Examples:
            - A scale that states nothing reports nothing, so the mapping itself is the "any?" test:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 10.0).extremes()
                {}
                >>> bool(Scale.from_limits(0.0, 10.0).extremes())
                False

                ```
            - A half-stated scale reports its half:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff").extremes()
                {'under': '#0000ff'}

                ```
            - All three come back in the fixed `missing`, `over`, `under` order, not the stated one:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
                ...     under="#0000ff", over="#ff0000", missing="#cccccc"
                ... )
                >>> list(stated.extremes())
                ['missing', 'over', 'under']

                ```
        """
        stated = {"missing": self.missing, "over": self.over, "under": self.under}
        return {name: color for name, color in stated.items() if color is not None}

    def color_for(self, category: Any) -> str | None:
        """Return the colour assigned to one category.

        Args:
            category: The category to look up. Categories are labels: a boolean — Python's, or numpy's `bool_`, which
                is what `np.unique` over a boolean column holds — matches only a boolean category, so `True` does not
                find a category `1`, nor `1` a category `True`.

        Returns:
            Its colour, or :attr:`missing` when the scale never saw it.

        Examples:
            - An unseen category gets the missing colour, not a wrong one:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
                >>> scale.color_for("zzz")
                '#ccc'

                ```
            - A numpy boolean finds the boolean category; the integer `1` does not:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.categorical([True, False], ["#f00", "#00f"], missing="#ccc")
                >>> scale.color_for(np.bool_(True)), scale.color_for(1)
                ('#f00', '#ccc')

                ```
        """
        category = frozen_value(category)
        for index, known in enumerate(self.categories):
            # `in`/`.index` compare with ==, which makes True equal to 1 and leaves a NaN category
            # unreachable. Categories are labels, so `False` and `0` are different labels even though they
            # compare equal, and an identity check is what finds a NaN that was actually stored.
            # A numpy boolean — what a boolean column's `.unique()` holds — is a boolean label too.
            if known is category or (
                isinstance(known, (bool, np.bool_))
                == isinstance(category, (bool, np.bool_))
                and known == category
            ):
                return self._colors[index]
        return self.missing

    def class_of(self, value: float) -> int | None:
        """Return the 0-based class a value falls in, for a classified scale.

        Args:
            value: The value to place.

        Returns:
            Its class index, or ``None`` when the scale is not classified or the value is not finite. A value
            outside the edges is clamped to the first or last class rather than dropped, matching what a
            renderer does with a value outside its domain.

        Examples:
            - Three classes cut from ten values, and where 5 lands:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values(list(range(10)), scheme="equal_interval", k=3)
                >>> scale.class_of(5.0) in (0, 1, 2)
                True

                ```
        """
        if not self.is_classified or not isfinite(value):
            return None
        upper = list(self.breaks)[1:]
        for index, edge in enumerate(upper):
            if value <= edge:
                return index
        return len(upper) - 1

    def class_ranges(self) -> list[tuple[float, float]]:
        """Return each class as a ``(low, high)`` pair, which is what a legend row shows.

        Returns:
            One pair per class, empty when the scale is not classified.

        Examples:
            - Two classes give two ranges:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_values([0.0, 1.0, 2.0, 3.0], scheme="equal_interval", k=2)
                >>> len(scale.class_ranges())
                2

                ```
        """
        edges = list(self.breaks)
        return [(edges[i], edges[i + 1]) for i in range(len(edges) - 1)]

    def freeze(self) -> "Scale":
        """Return a scale whose domain will not be re-derived from later data.

        `Scale` is already immutable, so this returns ``self``; it exists to say at a call site that the range
        is deliberately fixed — the thing a time sequence needs so its colours do not move between frames.

        Returns:
            This scale.

        Examples:
            - Freezing is explicit at the call site:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 1.0).freeze().as_limits()
                (0.0, 1.0)

                ```
        """
        return self

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            `vmin` and `vmax`, plus each of `scheme`, `breaks`, `categories` (with their `colors`) and the
            extreme colours (`missing`, `over`, `under`) that is set. Class edges, a scheme given as edges,
            categories and colours are written as lists. Every field goes through the JSON check, so a numpy
            number is written as a plain Python one. An unstated extreme colour is **absent** rather than
            written as ``null``, so adding the two new ones did not lengthen a single stored figure.

        Raises:
            TypeError: if any field — `scheme`, an edge, a category, a colour, or one of the extreme
                colours — has no JSON form, naming the field.

        Examples:
            - A continuous scale is its domain:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 10.0).to_dict()
                {'vmin': 0.0, 'vmax': 10.0}

                ```
            - A categorical scale carries its colours:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stored = Scale.categorical(["a", "b"], ["#f00", "#00f"]).to_dict()
                >>> stored["categories"], stored["colors"]
                (['a', 'b'], ['#f00', '#00f'])

                ```
            - A classified scale carries its scheme and its class edges:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale(0.0, 10.0, scheme="quantiles", breaks=(0.0, 4.0, 10.0)).to_dict()
                {'vmin': 0.0, 'vmax': 10.0, 'scheme': 'quantiles', 'breaks': [0.0, 4.0, 10.0]}

                ```
            - The extreme colours travel too, and only the stated ones are written:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
                {'vmin': 0.0, 'vmax': 10.0, 'over': '#ff0000'}

                ```
        """
        # Every field goes through the shared JSON rules, typed or not: the constructor checks the domain is
        # finite but not its type (np.float32 is not JSON), and checks neither the class edges nor `missing`.
        out: dict[str, Any] = {
            "vmin": to_json_value(self.vmin, "Scale.vmin"),
            "vmax": to_json_value(self.vmax, "Scale.vmax"),
        }
        if self.scheme is not None:
            out["scheme"] = to_json_value(self.scheme, "Scale.scheme")
        if self.breaks:
            out["breaks"] = to_json_value(self.breaks, "Scale.breaks")
        if self.categories:
            out["categories"] = to_json_value(self.categories, "Scale.categories")
            out["colors"] = to_json_value(self._colors, "Scale.colors")
        for name, color in self.extremes().items():
            out[name] = to_json_value(color, f"Scale.{name}")
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Scale":
        """Rebuild a scale from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The scale, validated as the constructor validates it. No classifier runs: the stored breaks are the
            breaks, which is what makes a frozen scale reproduce the colours it was drawn with. All three
            extreme colours are read back — `missing`, and the `over`/`under` pair `to_dict()` now writes —
            and a key absent from the dict comes back as `None`, which is what an unstated extreme is.

        Raises:
            TypeError: if `data` is not a mapping, or `breaks`, `categories` or `colors` is not a list, naming
                the field.
            ValueError: for a missing `vmin` or `vmax`, a limit or edge that is not a finite number, an unknown
                key, or a scale the constructor refuses — a
                non-finite or degenerate domain, a single class edge, or a colour count that does not match the
                categories. The known keys are listed in the message, so matplotlib's own spelling of the
                nodata colour is answered rather than silently dropped: `Scale.from_dict({..., "bad": ...})`
                raises *"Scale.from_dict got unknown keys ['bad']; known keys are [...]"*.

        Examples:
            - Stored class edges come back without re-classifying anything:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> scale = Scale.from_dict({"vmin": 0, "vmax": 10, "breaks": [0, 5, 10]})
                >>> scale.class_ranges()
                [(0.0, 5.0), (5.0, 10.0)]

                ```
            - A categorical scale keeps each category's colour across a round trip:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stored = Scale.categorical(["forest", "water"], ["#228b22", "#1e90ff"]).to_dict()
                >>> Scale.from_dict(stored).color_for("water")
                '#1e90ff'

                ```
            - A domain with no width is refused:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_dict({"vmin": 1, "vmax": 1})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: Scale needs vmax > vmin; got vmin=1.0, vmax=1.0. ...

                ```
            - The extreme colours survive the round trip, and the ones the dict leaves out stay unstated:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> stored = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
                >>> back = Scale.from_dict(stored)
                >>> back.extremes(), back.under is None
                ({'over': '#ff0000'}, True)

                ```
            - matplotlib's spelling of the nodata colour is not this one, and is refused by name:
                ```python
                >>> from digitalearth.base.spec import Scale
                >>> Scale.from_dict({"vmin": 0.0, "vmax": 1.0, "bad": "#ffffff"})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: Scale.from_dict got unknown keys ['bad']; known keys are [...]

                ```
        """
        refuse_unknown(
            "Scale",
            data,
            (
                "vmin",
                "vmax",
                "scheme",
                "breaks",
                "categories",
                "colors",
                "missing",
                "over",
                "under",
            ),
        )
        scheme = data.get("scheme")
        return cls(
            finite_number("Scale", "vmin", require("Scale", data, "vmin")),
            finite_number("Scale", "vmax", require("Scale", data, "vmax")),
            scheme=tuple(scheme) if isinstance(scheme, list) else scheme,
            breaks=tuple(
                finite_number("Scale", f"breaks[{index}]", edge)
                for index, edge in enumerate(
                    as_list("Scale", "breaks", data.get("breaks", ()))
                )
            ),
            categories=as_list("Scale", "categories", data.get("categories", ())),
            missing=data.get("missing"),
            over=data.get("over"),
            under=data.get("under"),
            _colors=as_list("Scale", "colors", data.get("colors", ())),
        )

is_categorical property #

Whether this scale colours unordered categories rather than a numeric range.

Returns:

Type Description
bool

True when categories were supplied.

Examples:

  • A categorical scale knows its categories by name:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.categorical(["land", "sea"], ["#8b4513", "#1e90ff"])
    >>> scale.is_categorical
    True
    >>> scale.categories
    ('land', 'sea')
    
  • A numeric scale is not categorical, however few values it saw:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([1.0, 2.0]).is_categorical
    False
    

is_classified property #

Whether this scale cuts classes rather than running a continuous ramp.

Returns:

Type Description
bool

True when a scheme produced class edges.

Examples:

  • A scheme cuts classes, and the scale says so:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
    >>> scale.is_classified
    True
    >>> len(scale.class_ranges())
    2
    
  • Without one it runs a continuous ramp and cuts nothing:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([0.0, 10.0])
    >>> scale.is_classified
    False
    >>> scale.breaks
    ()
    

__post_init__() #

Refuse a domain nothing can be normalised against.

Raises:

Type Description
ValueError

for a non-finite or degenerate domain, or for class edges that bound no class.

Source code in src/digitalearth/base/spec/scale.py
def __post_init__(self) -> None:
    """Refuse a domain nothing can be normalised against.

    Raises:
        ValueError: for a non-finite or degenerate domain, or for class edges that bound no class.
    """
    for name, value in (("vmin", self.vmin), ("vmax", self.vmax)):
        if not isfinite(value):
            raise ValueError(f"Scale needs a finite domain; got {name}={value!r}")
    if self.vmax <= self.vmin:
        raise ValueError(
            f"Scale needs vmax > vmin; got vmin={self.vmin}, vmax={self.vmax}. "
            "Build with Scale.from_values(), which widens a constant domain for you"
        )
    if self.breaks and len(self.breaks) < 2:
        raise ValueError(
            f"Scale needs at least two class edges to bound one class; got {self.breaks}. "
            "An empty breaks tuple is how a continuous ramp says it cuts no classes"
        )
    if len(tuple(self.categories)) != len(tuple(self._colors)):
        # `categorical()` checks this, but the constructor is public and color_for indexes _colors by
        # the category's position — a short list raises IndexError from a lookup, far from the cause.
        raise ValueError(
            f"a categorical Scale needs one colour per category; got {len(tuple(self.categories))} "
            f"categories and {len(tuple(self._colors))} colours"
        )
    # Coerce every sequence field to a tuple. `scheme` is a documented sequence-of-edges input on three
    # tiers, so a caller's list really does arrive here; stored as given it would leave the scale
    # unhashable and editable from outside, which is not what "frozen value object" promises.
    object.__setattr__(self, "breaks", tuple(self.breaks))
    object.__setattr__(
        self,
        "categories",
        tuple(frozen_value(category) for category in self.categories),
    )
    object.__setattr__(self, "_colors", tuple(self._colors))
    if isinstance(self.scheme, set):
        # Class edges are ordered data and a set has no order, so tuple(set) would pick one by hash.
        raise ValueError(
            f"Scale got scheme={self.scheme!r}: a set has no ordering, but class edges are ordered. "
            "Pass a list or tuple of edges, or a scheme name"
        )
    if isinstance(self.scheme, list):
        object.__setattr__(self, "scheme", tuple(self.scheme))

as_limits() #

Return the (vmin, vmax) pair a renderer's normaliser takes.

Returns:

Type Description
tuple[float, float]

The domain, with vmax > vmin guaranteed.

Examples:

  • The pair a normaliser is built from, ready to unpack:
    >>> from digitalearth.base.spec import Scale
    >>> vmin, vmax = Scale.from_values([3.0, 7.0, 5.0]).as_limits()
    >>> vmin, vmax
    (3.0, 7.0)
    >>> vmax - vmin
    4.0
    
  • A constant band still yields a usable span rather than a zero-width one:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([7.0, 7.0]).as_limits()
    (7.0, 8.0)
    
Source code in src/digitalearth/base/spec/scale.py
def as_limits(self) -> tuple[float, float]:
    """Return the ``(vmin, vmax)`` pair a renderer's normaliser takes.

    Returns:
        The domain, with ``vmax > vmin`` guaranteed.

    Examples:
        - The pair a normaliser is built from, ready to unpack:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> vmin, vmax = Scale.from_values([3.0, 7.0, 5.0]).as_limits()
            >>> vmin, vmax
            (3.0, 7.0)
            >>> vmax - vmin
            4.0

            ```
        - A constant band still yields a usable span rather than a zero-width one:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_values([7.0, 7.0]).as_limits()
            (7.0, 8.0)

            ```
    """
    return self.vmin, self.vmax

breaks_of(values, scheme, k=DEFAULT_CLASS_COUNT, *, clip=None) classmethod #

Cut class edges without deriving a domain, for a caller that only wants the classes.

The three classification sites read .breaks and nothing else, so measuring the domain for them — a full pass over the data plus a compacted copy of every finite value — is work whose result is discarded. This is the same classifier, the same error, and no measurement.

Parameters:

Name Type Description Default
values Any

The data to classify.

required
scheme str

Classification scheme name.

required
k int

Number of classes.

DEFAULT_CLASS_COUNT
clip tuple[float | None, float | None] | None

An optional (vmin, vmax) window the classes are pinned to (#378). When given, the recorded domain is the window and a cell outside it is clamped to the nearer bound, so an outlier lands in the first or last class instead of stretching the classes and two bands given the same window share one comparable scale. The interior is the scheme's own: an "equal_interval" window is split into equal parts of the window itself, while a data-driven scheme ("quantiles", "natural_breaks", …) cuts its interior over the clamped data and only has its outer edges pinned to the bounds — the two synthetic bound points are never mixed into the statistic. Either bound may be None to leave that side at the data's own extent. A reversed window (vmin > vmax) is refused, and a zero-width one (vmin == vmax) is widened, the same as :meth:from_values treats explicit limits.

None

Returns:

Type Description
tuple[float, ...]

The class edges, k + 1 of them for k classes.

Raises:

Type Description
ValueError

if the scheme is unknown to the classifier, k is not a usable class count, a clip window is reversed, or a data-driven scheme's window holds fewer than two distinct values. The message names the scheme and the count, as :meth:from_values does.

Examples:

  • Three classes, four edges, and no domain derived:
    >>> from digitalearth.base.spec import Scale
    >>> len(Scale.breaks_of(list(range(10)), "equal_interval", 3))
    4
    
  • An equal_interval window is split into equal parts of the window; the 999 outlier lands in the top class rather than stretching the edges:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.breaks_of([5, 10, 15, 20, 40, 999], "equal_interval", 2, clip=(0.0, 100.0))
    (0.0, 50.0, 100.0)
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def breaks_of(
    cls,
    values: Any,
    scheme: str,
    k: int = DEFAULT_CLASS_COUNT,
    *,
    clip: tuple[float | None, float | None] | None = None,
) -> tuple[float, ...]:
    """Cut class edges without deriving a domain, for a caller that only wants the classes.

    The three classification sites read ``.breaks`` and nothing else, so measuring the domain for them —
    a full pass over the data plus a compacted copy of every finite value — is work whose result is
    discarded. This is the same classifier, the same error, and no measurement.

    Args:
        values: The data to classify.
        scheme: Classification scheme name.
        k: Number of classes.
        clip: An optional ``(vmin, vmax)`` window the classes are pinned to (#378). When given, the
            recorded domain is the window and a cell outside it is clamped to the nearer bound, so an
            outlier lands in the first or last class instead of stretching the classes and two bands
            given the same window share one comparable scale. The interior is the scheme's own: an
            ``"equal_interval"`` window is split into equal parts of the window itself, while a
            data-driven scheme (``"quantiles"``, ``"natural_breaks"``, …) cuts its interior over the
            clamped data and only has its *outer* edges pinned to the bounds — the two synthetic bound
            points are never mixed into the statistic. Either bound may be ``None`` to leave that side at
            the data's own extent. A reversed window (``vmin > vmax``) is refused, and a zero-width one
            (``vmin == vmax``) is widened, the same as :meth:`from_values` treats explicit limits.

    Returns:
        The class edges, ``k + 1`` of them for ``k`` classes.

    Raises:
        ValueError: if the scheme is unknown to the classifier, `k` is not a usable class count, a
            `clip` window is reversed, or a data-driven scheme's window holds fewer than two distinct
            values. The message names the scheme and the count, as :meth:`from_values` does.

    Examples:
        - Three classes, four edges, and no domain derived:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> len(Scale.breaks_of(list(range(10)), "equal_interval", 3))
            4

            ```
        - An ``equal_interval`` window is split into equal parts of the window; the 999 outlier lands in
          the top class rather than stretching the edges:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.breaks_of([5, 10, 15, 20, 40, 999], "equal_interval", 2, clip=(0.0, 100.0))
            (0.0, 50.0, 100.0)

            ```
    """
    if clip is None:
        return cls._breaks(values, scheme, k)
    lo, hi = cls._clip_window(clip)
    clamped = cls._clamped_finite(values, lo, hi)
    if scheme == "equal_interval":
        # equal_interval's classes are a pure split of the domain, so cutting the window itself gives
        # equal parts of `[lo, hi]` whatever the data holds. A data-driven scheme must not take this
        # path: splitting the window would discard the distribution the scheme names. An open bound
        # falls back to the clamped data's extent, or to a unit span when no cell survived.
        left = (
            float(lo) if lo is not None else cls._open_bound(clamped, np.min, 0.0)
        )
        right = (
            float(hi) if hi is not None else cls._open_bound(clamped, np.max, 1.0)
        )
        if right <= left:
            left, right = cls._widen(left)
        return tuple(float(edge) for edge in np.linspace(left, right, k + 1))
    if np.unique(clamped).size < 2:
        # A data-driven scheme needs spread; with every cell on one side of the window (or a degenerate
        # window) the clamped sample is one value and the classifier cannot cut it. Name the window, not
        # the data, since the window is the cause.
        raise ValueError(
            f"scheme={scheme!r} cannot cut classes in the window [{lo}, {hi}]: it holds fewer than two "
            "distinct values, so every cell falls on one side of it; widen the window, or use "
            "'equal_interval', which splits the window regardless of the data"
        )
    edges = cls._breaks(clamped, scheme, k)
    return cls._pin_outer_edges(edges, lo, hi)

categorical(categories, colors, *, missing=None) classmethod #

Build a scale over unordered categories rather than a numeric range.

Parameters:

Name Type Description Default
categories Sequence[Any]

The distinct values, in the order their colours were assigned.

required
colors Sequence[str]

One colour per category.

required
missing str | None

Colour for a value that is not one of categories.

None

Returns:

Type Description
Scale

The categorical scale. Its numeric domain is the category index range, which is what a renderer

Scale

needs to place a swatch; vmin/vmax are not meaningful as data values.

Raises:

Type Description
ValueError

if there are no categories, or the counts do not match.

Examples:

  • Three categories and their colours:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.categorical(["a", "b", "c"], ["#f00", "#0f0", "#00f"])
    >>> scale.is_categorical, scale.color_for("b")
    (True, '#0f0')
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def categorical(
    cls,
    categories: Sequence[Any],
    colors: Sequence[str],
    *,
    missing: str | None = None,
) -> "Scale":
    """Build a scale over unordered categories rather than a numeric range.

    Args:
        categories: The distinct values, in the order their colours were assigned.
        colors: One colour per category.
        missing: Colour for a value that is not one of `categories`.

    Returns:
        The categorical scale. Its numeric domain is the category *index* range, which is what a renderer
        needs to place a swatch; `vmin`/`vmax` are not meaningful as data values.

    Raises:
        ValueError: if there are no categories, or the counts do not match.

    Examples:
        - Three categories and their colours:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.categorical(["a", "b", "c"], ["#f00", "#0f0", "#00f"])
            >>> scale.is_categorical, scale.color_for("b")
            (True, '#0f0')

            ```
    """
    cats = list(categories)
    cols = list(colors)
    if not cats:
        raise ValueError("a categorical Scale needs at least one category")
    if len(cats) != len(cols):
        raise ValueError(
            f"a categorical Scale needs one colour per category; got {len(cats)} categories "
            f"and {len(cols)} colours"
        )
    return cls(
        0.0,
        float(max(len(cats) - 1, 1)),
        categories=tuple(cats),
        missing=missing,
        _colors=tuple(cols),
    )

class_of(value) #

Return the 0-based class a value falls in, for a classified scale.

Parameters:

Name Type Description Default
value float

The value to place.

required

Returns:

Type Description
int | None

Its class index, or None when the scale is not classified or the value is not finite. A value

int | None

outside the edges is clamped to the first or last class rather than dropped, matching what a

int | None

renderer does with a value outside its domain.

Examples:

  • Three classes cut from ten values, and where 5 lands:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values(list(range(10)), scheme="equal_interval", k=3)
    >>> scale.class_of(5.0) in (0, 1, 2)
    True
    
Source code in src/digitalearth/base/spec/scale.py
def class_of(self, value: float) -> int | None:
    """Return the 0-based class a value falls in, for a classified scale.

    Args:
        value: The value to place.

    Returns:
        Its class index, or ``None`` when the scale is not classified or the value is not finite. A value
        outside the edges is clamped to the first or last class rather than dropped, matching what a
        renderer does with a value outside its domain.

    Examples:
        - Three classes cut from ten values, and where 5 lands:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_values(list(range(10)), scheme="equal_interval", k=3)
            >>> scale.class_of(5.0) in (0, 1, 2)
            True

            ```
    """
    if not self.is_classified or not isfinite(value):
        return None
    upper = list(self.breaks)[1:]
    for index, edge in enumerate(upper):
        if value <= edge:
            return index
    return len(upper) - 1

class_ranges() #

Return each class as a (low, high) pair, which is what a legend row shows.

Returns:

Type Description
list[tuple[float, float]]

One pair per class, empty when the scale is not classified.

Examples:

  • Two classes give two ranges:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([0.0, 1.0, 2.0, 3.0], scheme="equal_interval", k=2)
    >>> len(scale.class_ranges())
    2
    
Source code in src/digitalearth/base/spec/scale.py
def class_ranges(self) -> list[tuple[float, float]]:
    """Return each class as a ``(low, high)`` pair, which is what a legend row shows.

    Returns:
        One pair per class, empty when the scale is not classified.

    Examples:
        - Two classes give two ranges:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_values([0.0, 1.0, 2.0, 3.0], scheme="equal_interval", k=2)
            >>> len(scale.class_ranges())
            2

            ```
    """
    edges = list(self.breaks)
    return [(edges[i], edges[i + 1]) for i in range(len(edges) - 1)]

color_for(category) #

Return the colour assigned to one category.

Parameters:

Name Type Description Default
category Any

The category to look up. Categories are labels: a boolean — Python's, or numpy's bool_, which is what np.unique over a boolean column holds — matches only a boolean category, so True does not find a category 1, nor 1 a category True.

required

Returns:

Type Description
str | None

Its colour, or :attr:missing when the scale never saw it.

Examples:

  • An unseen category gets the missing colour, not a wrong one:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
    >>> scale.color_for("zzz")
    '#ccc'
    
  • A numpy boolean finds the boolean category; the integer 1 does not:
    >>> import numpy as np
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.categorical([True, False], ["#f00", "#00f"], missing="#ccc")
    >>> scale.color_for(np.bool_(True)), scale.color_for(1)
    ('#f00', '#ccc')
    
Source code in src/digitalearth/base/spec/scale.py
def color_for(self, category: Any) -> str | None:
    """Return the colour assigned to one category.

    Args:
        category: The category to look up. Categories are labels: a boolean — Python's, or numpy's `bool_`, which
            is what `np.unique` over a boolean column holds — matches only a boolean category, so `True` does not
            find a category `1`, nor `1` a category `True`.

    Returns:
        Its colour, or :attr:`missing` when the scale never saw it.

    Examples:
        - An unseen category gets the missing colour, not a wrong one:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
            >>> scale.color_for("zzz")
            '#ccc'

            ```
        - A numpy boolean finds the boolean category; the integer `1` does not:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.categorical([True, False], ["#f00", "#00f"], missing="#ccc")
            >>> scale.color_for(np.bool_(True)), scale.color_for(1)
            ('#f00', '#ccc')

            ```
    """
    category = frozen_value(category)
    for index, known in enumerate(self.categories):
        # `in`/`.index` compare with ==, which makes True equal to 1 and leaves a NaN category
        # unreachable. Categories are labels, so `False` and `0` are different labels even though they
        # compare equal, and an identity check is what finds a NaN that was actually stored.
        # A numpy boolean — what a boolean column's `.unique()` holds — is a boolean label too.
        if known is category or (
            isinstance(known, (bool, np.bool_))
            == isinstance(category, (bool, np.bool_))
            and known == category
        ):
            return self._colors[index]
    return self.missing

extremes() #

Return only the extreme colours this scale states, keyed by which extreme they colour.

The keys absent from the mapping are exactly the extremes a renderer must not overwrite, which is what makes "did the caller state any?" one test and keeps a tier from pushing a default colour onto a colormap the caller built themselves.

Returns:

Type Description
dict[str, str]

A new plain dict over "missing", "over" and "under", holding only the ones that are set

dict[str, str]

— empty when the scale states none. The keys come in that order, whatever order they were

dict[str, str]

stated in, so to_dict() writes a stored figure the same way twice.

Examples:

  • A scale that states nothing reports nothing, so the mapping itself is the "any?" test:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 10.0).extremes()
    {}
    >>> bool(Scale.from_limits(0.0, 10.0).extremes())
    False
    
  • A half-stated scale reports its half:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff").extremes()
    {'under': '#0000ff'}
    
  • All three come back in the fixed missing, over, under order, not the stated one:
    >>> from digitalearth.base.spec import Scale
    >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
    ...     under="#0000ff", over="#ff0000", missing="#cccccc"
    ... )
    >>> list(stated.extremes())
    ['missing', 'over', 'under']
    
Source code in src/digitalearth/base/spec/scale.py
def extremes(self) -> dict[str, str]:
    """Return only the extreme colours this scale states, keyed by which extreme they colour.

    The keys absent from the mapping are exactly the extremes a renderer must **not** overwrite, which is
    what makes "did the caller state any?" one test and keeps a tier from pushing a default colour onto a
    colormap the caller built themselves.

    Returns:
        A new plain `dict` over `"missing"`, `"over"` and `"under"`, holding only the ones that are set
        — empty when the scale states none. The keys come in that order, whatever order they were
        stated in, so `to_dict()` writes a stored figure the same way twice.

    Examples:
        - A scale that states nothing reports nothing, so the mapping itself is the "any?" test:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 10.0).extremes()
            {}
            >>> bool(Scale.from_limits(0.0, 10.0).extremes())
            False

            ```
        - A half-stated scale reports its half:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff").extremes()
            {'under': '#0000ff'}

            ```
        - All three come back in the fixed `missing`, `over`, `under` order, not the stated one:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
            ...     under="#0000ff", over="#ff0000", missing="#cccccc"
            ... )
            >>> list(stated.extremes())
            ['missing', 'over', 'under']

            ```
    """
    stated = {"missing": self.missing, "over": self.over, "under": self.under}
    return {name: color for name, color in stated.items() if color is not None}

freeze() #

Return a scale whose domain will not be re-derived from later data.

Scale is already immutable, so this returns self; it exists to say at a call site that the range is deliberately fixed — the thing a time sequence needs so its colours do not move between frames.

Returns:

Type Description
Scale

This scale.

Examples:

  • Freezing is explicit at the call site:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 1.0).freeze().as_limits()
    (0.0, 1.0)
    
Source code in src/digitalearth/base/spec/scale.py
def freeze(self) -> "Scale":
    """Return a scale whose domain will not be re-derived from later data.

    `Scale` is already immutable, so this returns ``self``; it exists to say at a call site that the range
    is deliberately fixed — the thing a time sequence needs so its colours do not move between frames.

    Returns:
        This scale.

    Examples:
        - Freezing is explicit at the call site:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 1.0).freeze().as_limits()
            (0.0, 1.0)

            ```
    """
    return self

from_dict(data) classmethod #

Rebuild a scale from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Scale

The scale, validated as the constructor validates it. No classifier runs: the stored breaks are the

Scale

breaks, which is what makes a frozen scale reproduce the colours it was drawn with. All three

Scale

extreme colours are read back — missing, and the over/under pair to_dict() now writes —

Scale

and a key absent from the dict comes back as None, which is what an unstated extreme is.

Raises:

Type Description
TypeError

if data is not a mapping, or breaks, categories or colors is not a list, naming the field.

ValueError

for a missing vmin or vmax, a limit or edge that is not a finite number, an unknown key, or a scale the constructor refuses — a non-finite or degenerate domain, a single class edge, or a colour count that does not match the categories. The known keys are listed in the message, so matplotlib's own spelling of the nodata colour is answered rather than silently dropped: Scale.from_dict({..., "bad": ...}) raises "Scale.from_dict got unknown keys ['bad']; known keys are [...]".

Examples:

  • Stored class edges come back without re-classifying anything:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_dict({"vmin": 0, "vmax": 10, "breaks": [0, 5, 10]})
    >>> scale.class_ranges()
    [(0.0, 5.0), (5.0, 10.0)]
    
  • A categorical scale keeps each category's colour across a round trip:
    >>> from digitalearth.base.spec import Scale
    >>> stored = Scale.categorical(["forest", "water"], ["#228b22", "#1e90ff"]).to_dict()
    >>> Scale.from_dict(stored).color_for("water")
    '#1e90ff'
    
  • A domain with no width is refused:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_dict({"vmin": 1, "vmax": 1})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Scale needs vmax > vmin; got vmin=1.0, vmax=1.0. ...
    
  • The extreme colours survive the round trip, and the ones the dict leaves out stay unstated:
    >>> from digitalearth.base.spec import Scale
    >>> stored = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
    >>> back = Scale.from_dict(stored)
    >>> back.extremes(), back.under is None
    ({'over': '#ff0000'}, True)
    
  • matplotlib's spelling of the nodata colour is not this one, and is refused by name:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_dict({"vmin": 0.0, "vmax": 1.0, "bad": "#ffffff"})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Scale.from_dict got unknown keys ['bad']; known keys are [...]
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Scale":
    """Rebuild a scale from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The scale, validated as the constructor validates it. No classifier runs: the stored breaks are the
        breaks, which is what makes a frozen scale reproduce the colours it was drawn with. All three
        extreme colours are read back — `missing`, and the `over`/`under` pair `to_dict()` now writes —
        and a key absent from the dict comes back as `None`, which is what an unstated extreme is.

    Raises:
        TypeError: if `data` is not a mapping, or `breaks`, `categories` or `colors` is not a list, naming
            the field.
        ValueError: for a missing `vmin` or `vmax`, a limit or edge that is not a finite number, an unknown
            key, or a scale the constructor refuses — a
            non-finite or degenerate domain, a single class edge, or a colour count that does not match the
            categories. The known keys are listed in the message, so matplotlib's own spelling of the
            nodata colour is answered rather than silently dropped: `Scale.from_dict({..., "bad": ...})`
            raises *"Scale.from_dict got unknown keys ['bad']; known keys are [...]"*.

    Examples:
        - Stored class edges come back without re-classifying anything:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_dict({"vmin": 0, "vmax": 10, "breaks": [0, 5, 10]})
            >>> scale.class_ranges()
            [(0.0, 5.0), (5.0, 10.0)]

            ```
        - A categorical scale keeps each category's colour across a round trip:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stored = Scale.categorical(["forest", "water"], ["#228b22", "#1e90ff"]).to_dict()
            >>> Scale.from_dict(stored).color_for("water")
            '#1e90ff'

            ```
        - A domain with no width is refused:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_dict({"vmin": 1, "vmax": 1})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Scale needs vmax > vmin; got vmin=1.0, vmax=1.0. ...

            ```
        - The extreme colours survive the round trip, and the ones the dict leaves out stay unstated:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stored = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
            >>> back = Scale.from_dict(stored)
            >>> back.extremes(), back.under is None
            ({'over': '#ff0000'}, True)

            ```
        - matplotlib's spelling of the nodata colour is not this one, and is refused by name:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_dict({"vmin": 0.0, "vmax": 1.0, "bad": "#ffffff"})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Scale.from_dict got unknown keys ['bad']; known keys are [...]

            ```
    """
    refuse_unknown(
        "Scale",
        data,
        (
            "vmin",
            "vmax",
            "scheme",
            "breaks",
            "categories",
            "colors",
            "missing",
            "over",
            "under",
        ),
    )
    scheme = data.get("scheme")
    return cls(
        finite_number("Scale", "vmin", require("Scale", data, "vmin")),
        finite_number("Scale", "vmax", require("Scale", data, "vmax")),
        scheme=tuple(scheme) if isinstance(scheme, list) else scheme,
        breaks=tuple(
            finite_number("Scale", f"breaks[{index}]", edge)
            for index, edge in enumerate(
                as_list("Scale", "breaks", data.get("breaks", ()))
            )
        ),
        categories=as_list("Scale", "categories", data.get("categories", ())),
        missing=data.get("missing"),
        over=data.get("over"),
        under=data.get("under"),
        _colors=as_list("Scale", "colors", data.get("colors", ())),
    )

from_finite(values, *, vmin=None, vmax=None, missing=None) classmethod #

Derive a scale from values the caller has already filtered to finite ones.

:meth:from_values filters first, which costs a full pass and a compacted copy of every finite value. Several callers had just done exactly that and thrown the result away — on a 2160x4320 global canvas that is a second ~75 MB allocation for an answer already in hand. This is the same rule without the second pass.

Parameters:

Name Type Description Default
values Any

Finite values only. Passing non-finite ones here produces a NaN domain rather than an error, which is the price of skipping the check — use :meth:from_values if unsure.

required
vmin float | None

Explicit lower limit, overriding the measured one.

None
vmax float | None

Explicit upper limit.

None
missing str | None

Colour for values the scale cannot place.

None

Returns:

Type Description
Scale

The resolved scale.

Raises:

Type Description
ValueError

if both limits are given the wrong way round.

Examples:

  • The same domain as from_values, without re-filtering:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_finite([1.0, 5.0, 9.0]).as_limits()
    (1.0, 9.0)
    
  • An empty selection still yields limits a colormap can take:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_finite([]).as_limits()
    (0.0, 1.0)
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def from_finite(
    cls,
    values: Any,
    *,
    vmin: float | None = None,
    vmax: float | None = None,
    missing: str | None = None,
) -> "Scale":
    """Derive a scale from values the caller has already filtered to finite ones.

    :meth:`from_values` filters first, which costs a full pass and a compacted copy of every finite
    value. Several callers had just done exactly that and thrown the result away — on a 2160x4320 global
    canvas that is a second ~75 MB allocation for an answer already in hand. This is the same rule
    without the second pass.

    Args:
        values: Finite values only. Passing non-finite ones here produces a NaN domain rather than an
            error, which is the price of skipping the check — use :meth:`from_values` if unsure.
        vmin: Explicit lower limit, overriding the measured one.
        vmax: Explicit upper limit.
        missing: Colour for values the scale cannot place.

    Returns:
        The resolved scale.

    Raises:
        ValueError: if both limits are given the wrong way round.

    Examples:
        - The same domain as `from_values`, without re-filtering:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_finite([1.0, 5.0, 9.0]).as_limits()
            (1.0, 9.0)

            ```
        - An empty selection still yields limits a colormap can take:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_finite([]).as_limits()
            (0.0, 1.0)

            ```
    """
    array = np.asarray(values, dtype="float64").ravel()
    lo, hi = cls._apply_limits(array, vmin, vmax)
    return cls(lo, hi, missing=missing)

from_limits(vmin, vmax, *, missing=None) classmethod #

Build from limits that were derived elsewhere — a frozen stack range, or a caller's clim=.

Parameters:

Name Type Description Default
vmin float

Lower limit.

required
vmax float

Upper limit.

required
missing str | None

Colour for values the scale cannot place.

None

Returns:

Type Description
Scale

The scale, with the same widening rule applied so a degenerate pair cannot get through.

Examples:

  • The frozen range of a time stack becomes a scale every frame shares:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(2.0, 9.0).as_limits()
    (2.0, 9.0)
    
  • A degenerate pair is widened here too, rather than raising on the caller:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(4.0, 4.0).as_limits()
    (4.0, 5.0)
    
  • A constant too large for + 1 to move widens by one representable step instead:
    >>> from digitalearth.base.spec import Scale
    >>> low, high = Scale.from_limits(1e20, 1e20).as_limits()
    >>> low == 1e20, high > low
    (True, True)
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def from_limits(
    cls, vmin: float, vmax: float, *, missing: str | None = None
) -> "Scale":
    """Build from limits that were derived elsewhere — a frozen stack range, or a caller's `clim=`.

    Args:
        vmin: Lower limit.
        vmax: Upper limit.
        missing: Colour for values the scale cannot place.

    Returns:
        The scale, with the same widening rule applied so a degenerate pair cannot get through.

    Examples:
        - The frozen range of a time stack becomes a scale every frame shares:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(2.0, 9.0).as_limits()
            (2.0, 9.0)

            ```
        - A degenerate pair is widened here too, rather than raising on the caller:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(4.0, 4.0).as_limits()
            (4.0, 5.0)

            ```
        - A constant too large for ``+ 1`` to move widens by one representable step instead:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> low, high = Scale.from_limits(1e20, 1e20).as_limits()
            >>> low == 1e20, high > low
            (True, True)

            ```
    """
    lo, hi = float(vmin), float(vmax)
    if not (isfinite(lo) and isfinite(hi)):
        raise ValueError(f"Scale needs finite limits; got ({vmin!r}, {vmax!r})")
    if hi <= lo:
        lo, hi = Scale._widen(lo)
    return cls(lo, hi, missing=missing)

from_values(values, *, vmin=None, vmax=None, scheme=None, k=DEFAULT_CLASS_COUNT, missing=None) classmethod #

Derive a scale from data, applying the one widening rule every tier used to write out.

Two degenerate cases are handled here rather than at five call sites:

  • nothing finite — the domain falls back to (0.0, 1.0). A builder still needs limits to hand a colormap, and a stack whose every frame is off the view has no range to report.
  • a constant domain — vmax becomes vmin + 1. Normalising against a zero-width range divides by zero; the five copies of this rule all chose + 1, so that is what is kept.

Parameters:

Name Type Description Default
values Any

The data to measure. Non-finite values are ignored.

required
vmin float | None

Explicit lower limit, overriding the measured one.

None
vmax float | None

Explicit upper limit.

None
scheme str | None

Classification scheme to cut classes with, or None for a continuous ramp.

None
k int

Number of classes when scheme is set.

DEFAULT_CLASS_COUNT
missing str | None

Colour for values the scale cannot place.

None

Returns:

Type Description
Scale

The resolved scale.

Raises:

Type Description
ValueError

if scheme is unknown to the classifier, or k is not a usable class count. The message names the scheme and the count, since a classifier error alone says neither.

Examples:

  • An explicit limit wins over the measured one:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([1.0, 2.0, 3.0], vmax=10.0).as_limits()
    (1.0, 10.0)
    
Source code in src/digitalearth/base/spec/scale.py
@classmethod
def from_values(
    cls,
    values: Any,
    *,
    vmin: float | None = None,
    vmax: float | None = None,
    scheme: str | None = None,
    k: int = DEFAULT_CLASS_COUNT,
    missing: str | None = None,
) -> "Scale":
    """Derive a scale from data, applying the one widening rule every tier used to write out.

    Two degenerate cases are handled here rather than at five call sites:

    * **nothing finite** — the domain falls back to ``(0.0, 1.0)``. A builder still needs limits to hand a
      colormap, and a stack whose every frame is off the view has no range to report.
    * **a constant domain** — ``vmax`` becomes ``vmin + 1``. Normalising against a zero-width range
      divides by zero; the five copies of this rule all chose ``+ 1``, so that is what is kept.

    Args:
        values: The data to measure. Non-finite values are ignored.
        vmin: Explicit lower limit, overriding the measured one.
        vmax: Explicit upper limit.
        scheme: Classification scheme to cut classes with, or ``None`` for a continuous ramp.
        k: Number of classes when `scheme` is set.
        missing: Colour for values the scale cannot place.

    Returns:
        The resolved scale.

    Raises:
        ValueError: if `scheme` is unknown to the classifier, or `k` is not a usable class count. The
            message names the scheme and the count, since a classifier error alone says neither.

    Examples:
        - An explicit limit wins over the measured one:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_values([1.0, 2.0, 3.0], vmax=10.0).as_limits()
            (1.0, 10.0)

            ```
    """
    lo, hi = cls._limits(values, vmin, vmax)
    breaks: tuple[float, ...] = ()
    if scheme is not None:
        breaks = cls._breaks(values, scheme, k)
    return cls(lo, hi, scheme=scheme, breaks=breaks, missing=missing)

straddles(center=0.0) #

Whether this domain runs on both sides of center — the test a diverging ramp has to pass.

A diverging colormap puts a neutral colour at center and an arm on either side of it. Centred outside the domain it is worse than a sequential ramp rather than better: one arm is never drawn, so the other carries every value and the picture loses the contrast the ramp was chosen for. Asking the domain first is what lets a tier offer divergence and decline it on the same call.

The comparison is strict, deliberately: a centre sitting exactly on vmin or vmax leaves one arm holding a single value, and it is also the comparison cleopatra validates a diverging center with — not (vmin < center < vmax) raises "diverging 'center' (0.0) must lie strictly between vmin (...) and vmax (...)" there — so a centre this reader called straddled but cleopatra refuses cannot happen.

Parameters:

Name Type Description Default
center float

The value a diverging ramp would be centred on. Zero by default, which is the centre of every anomaly, difference and trend field. A non-finite centre straddles nothing — answered rather than compared, since nan fails every comparison silently.

0.0

Returns:

Type Description
bool

True when vmin < center < vmax.

Examples:

  • An anomaly field with both signs straddles zero; a rainfall total does not:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_values([-2.0, -1.0, 3.0, 6.0]).straddles()
    True
    >>> Scale.from_values([12.0, 40.0, 88.0]).straddles()
    False
    
  • A centre need not be zero — a departure from a long-term mean sits wherever that mean does:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(283.0, 293.0).straddles(288.0)
    True
    >>> Scale.from_limits(283.0, 293.0).straddles(273.15)
    False
    
  • The ends are not straddled, which is the comparison cleopatra makes too; and a non-finite centre is answered rather than compared:
    >>> from math import inf, nan
    >>> from digitalearth.base.spec import Scale
    >>> domain = Scale.from_limits(0.0, 10.0)
    >>> domain.straddles(0.0), domain.straddles(10.0)
    (False, False)
    >>> domain.straddles(nan), domain.straddles(inf)
    (False, False)
    
Source code in src/digitalearth/base/spec/scale.py
def straddles(self, center: float = 0.0) -> bool:
    """Whether this domain runs on **both** sides of `center` — the test a diverging ramp has to pass.

    A diverging colormap puts a neutral colour at `center` and an arm on either side of it. Centred
    outside the domain it is worse than a sequential ramp rather than better: one arm is never drawn, so
    the other carries every value and the picture loses the contrast the ramp was chosen for. Asking the
    domain first is what lets a tier offer divergence and decline it on the same call.

    The comparison is **strict**, deliberately: a centre sitting exactly on `vmin` or `vmax` leaves one
    arm holding a single value, and it is also the comparison cleopatra validates a diverging `center`
    with — `not (vmin < center < vmax)` raises
    *"diverging 'center' (0.0) must lie strictly between vmin (...) and vmax (...)"* there — so a
    centre this reader called straddled but cleopatra refuses cannot happen.

    Args:
        center: The value a diverging ramp would be centred on. Zero by default, which is the centre of
            every anomaly, difference and trend field. A non-finite centre straddles nothing — answered
            rather than compared, since `nan` fails every comparison silently.

    Returns:
        `True` when `vmin < center < vmax`.

    Examples:
        - An anomaly field with both signs straddles zero; a rainfall total does not:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_values([-2.0, -1.0, 3.0, 6.0]).straddles()
            True
            >>> Scale.from_values([12.0, 40.0, 88.0]).straddles()
            False

            ```
        - A centre need not be zero — a departure from a long-term mean sits wherever that mean does:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(283.0, 293.0).straddles(288.0)
            True
            >>> Scale.from_limits(283.0, 293.0).straddles(273.15)
            False

            ```
        - The ends are **not** straddled, which is the comparison cleopatra makes too; and a
          non-finite centre is answered rather than compared:
            ```python
            >>> from math import inf, nan
            >>> from digitalearth.base.spec import Scale
            >>> domain = Scale.from_limits(0.0, 10.0)
            >>> domain.straddles(0.0), domain.straddles(10.0)
            (False, False)
            >>> domain.straddles(nan), domain.straddles(inf)
            (False, False)

            ```
    """
    if not isfinite(center):
        return False
    return self.vmin < center < self.vmax

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

vmin and vmax, plus each of scheme, breaks, categories (with their colors) and the

dict[str, Any]

extreme colours (missing, over, under) that is set. Class edges, a scheme given as edges,

dict[str, Any]

categories and colours are written as lists. Every field goes through the JSON check, so a numpy

dict[str, Any]

number is written as a plain Python one. An unstated extreme colour is absent rather than

dict[str, Any]

written as null, so adding the two new ones did not lengthen a single stored figure.

Raises:

Type Description
TypeError

if any field — scheme, an edge, a category, a colour, or one of the extreme colours — has no JSON form, naming the field.

Examples:

  • A continuous scale is its domain:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 10.0).to_dict()
    {'vmin': 0.0, 'vmax': 10.0}
    
  • A categorical scale carries its colours:
    >>> from digitalearth.base.spec import Scale
    >>> stored = Scale.categorical(["a", "b"], ["#f00", "#00f"]).to_dict()
    >>> stored["categories"], stored["colors"]
    (['a', 'b'], ['#f00', '#00f'])
    
  • A classified scale carries its scheme and its class edges:
    >>> from digitalearth.base.spec import Scale
    >>> Scale(0.0, 10.0, scheme="quantiles", breaks=(0.0, 4.0, 10.0)).to_dict()
    {'vmin': 0.0, 'vmax': 10.0, 'scheme': 'quantiles', 'breaks': [0.0, 4.0, 10.0]}
    
  • The extreme colours travel too, and only the stated ones are written:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
    {'vmin': 0.0, 'vmax': 10.0, 'over': '#ff0000'}
    
Source code in src/digitalearth/base/spec/scale.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        `vmin` and `vmax`, plus each of `scheme`, `breaks`, `categories` (with their `colors`) and the
        extreme colours (`missing`, `over`, `under`) that is set. Class edges, a scheme given as edges,
        categories and colours are written as lists. Every field goes through the JSON check, so a numpy
        number is written as a plain Python one. An unstated extreme colour is **absent** rather than
        written as ``null``, so adding the two new ones did not lengthen a single stored figure.

    Raises:
        TypeError: if any field — `scheme`, an edge, a category, a colour, or one of the extreme
            colours — has no JSON form, naming the field.

    Examples:
        - A continuous scale is its domain:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 10.0).to_dict()
            {'vmin': 0.0, 'vmax': 10.0}

            ```
        - A categorical scale carries its colours:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stored = Scale.categorical(["a", "b"], ["#f00", "#00f"]).to_dict()
            >>> stored["categories"], stored["colors"]
            (['a', 'b'], ['#f00', '#00f'])

            ```
        - A classified scale carries its scheme and its class edges:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale(0.0, 10.0, scheme="quantiles", breaks=(0.0, 4.0, 10.0)).to_dict()
            {'vmin': 0.0, 'vmax': 10.0, 'scheme': 'quantiles', 'breaks': [0.0, 4.0, 10.0]}

            ```
        - The extreme colours travel too, and only the stated ones are written:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000").to_dict()
            {'vmin': 0.0, 'vmax': 10.0, 'over': '#ff0000'}

            ```
    """
    # Every field goes through the shared JSON rules, typed or not: the constructor checks the domain is
    # finite but not its type (np.float32 is not JSON), and checks neither the class edges nor `missing`.
    out: dict[str, Any] = {
        "vmin": to_json_value(self.vmin, "Scale.vmin"),
        "vmax": to_json_value(self.vmax, "Scale.vmax"),
    }
    if self.scheme is not None:
        out["scheme"] = to_json_value(self.scheme, "Scale.scheme")
    if self.breaks:
        out["breaks"] = to_json_value(self.breaks, "Scale.breaks")
    if self.categories:
        out["categories"] = to_json_value(self.categories, "Scale.categories")
        out["colors"] = to_json_value(self._colors, "Scale.colors")
    for name, color in self.extremes().items():
        out[name] = to_json_value(color, f"Scale.{name}")
    return out

with_extremes(*, missing=None, over=None, under=None) #

Return this scale with the extreme colours a caller stated, leaving the rest as they were.

A scale is normally derived — from_values() measures the domain from the data — while the colours for what falls outside it are the caller's styling and arrive separately. So stating them is a step on an existing scale rather than three more arguments on every builder.

None means "leave this one alone", which is what lets two calls compose and matches matplotlib.colors.Colormap.with_extremes, the method a renderer ends up handing these to: it copies the colormap and delegates to Colormap._set_extremes, which is where the rule really lives — three branches, if bad is not None / if under is not None / if over is not None, under a docstring reading "Parameters that are None are left unchanged" (read off matplotlib 3.11.1). The public Colormap.set_extremes is a one-line delegate to that helper and is pending-deprecated as of matplotlib 3.11 (@_api.deprecated("3.11", pending=True, alternative="cmap.with_extremes(...)")), so it is not what this rule is borrowed from. So None cannot clear a colour already stated: with_extremes(over=None) on a scale whose over is '#ff0000' answers {'over': '#ff0000'} again, and a call with no arguments at all is accepted and changes nothing. Clearing one is :meth:without_extremes's job — two verbs rather than one keyword carrying a sentinel, which keeps all three parameters a plain Optional[str] and keeps None meaning exactly what it means in matplotlib. The scale itself is immutable, so the stated colours come back on a new scale: a domain derived once and shared across an animation's frames must not pick up one frame's styling.

Parameters:

Name Type Description Default
missing str | None

Colour for a value the scale cannot place, or None to keep the current missing.

None
over str | None

Colour for a value above vmax, or None to keep the current over.

None
under str | None

Colour for a value below vmin, or None to keep the current under.

None

Returns:

Type Description
Scale

A new scale with the same domain, scheme, classes and categories, carrying the stated colours.

Scale

Never self, even when nothing was stated.

Examples:

  • State all three on a derived scale, and read them back:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([1.0, 9.0]).with_extremes(
    ...     missing="#cccccc", over="#ff0000", under="#0000ff"
    ... )
    >>> scale.extremes()
    {'missing': '#cccccc', 'over': '#ff0000', 'under': '#0000ff'}
    
  • A colour stated earlier survives a later call that does not name it:
    >>> from digitalearth.base.spec import Scale
    >>> top = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
    >>> top.with_extremes(missing="#cccccc").extremes()
    {'missing': '#cccccc', 'over': '#ff0000'}
    
  • The scale it was called on is unchanged, and the domain travels through:
    >>> from digitalearth.base.spec import Scale
    >>> original = Scale.from_limits(0.0, 10.0)
    >>> original.with_extremes(under="#0000ff").as_limits()
    (0.0, 10.0)
    >>> original.under is None
    True
    
  • None keeps rather than clears, and a call that states nothing is still a new scale:
    >>> from digitalearth.base.spec import Scale
    >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
    >>> stated.with_extremes(over=None).extremes()
    {'over': '#ff0000'}
    >>> bare = stated.with_extremes()
    >>> bare.extremes(), bare is stated
    ({'over': '#ff0000'}, False)
    >>> stated.without_extremes("over").extremes()
    {}
    
Source code in src/digitalearth/base/spec/scale.py
def with_extremes(
    self,
    *,
    missing: str | None = None,
    over: str | None = None,
    under: str | None = None,
) -> "Scale":
    """Return this scale with the extreme colours a caller stated, leaving the rest as they were.

    A scale is normally *derived* — `from_values()` measures the domain from the data — while the
    colours for what falls outside it are the caller's styling and arrive separately. So stating them is
    a step on an existing scale rather than three more arguments on every builder.

    `None` means "leave this one alone", which is what lets two calls compose and matches
    `matplotlib.colors.Colormap.with_extremes`, the method a renderer ends up handing these to: it copies
    the colormap and delegates to `Colormap._set_extremes`, which is where the rule really lives — three
    branches, `if bad is not None` / `if under is not None` / `if over is not None`, under a docstring
    reading *"Parameters that are None are left unchanged"* (read off matplotlib 3.11.1). The public
    `Colormap.set_extremes` is a one-line delegate to that helper and is pending-deprecated as of
    matplotlib 3.11 (`@_api.deprecated("3.11", pending=True, alternative="cmap.with_extremes(...)")`), so
    it is not what this rule is borrowed from. So `None` cannot
    **clear** a colour already stated: `with_extremes(over=None)` on a scale whose `over` is `'#ff0000'`
    answers `{'over': '#ff0000'}` again, and a call with no arguments at all is accepted and changes
    nothing. Clearing one is :meth:`without_extremes`'s job — two verbs rather than one keyword carrying a
    sentinel, which keeps all three parameters a plain `Optional[str]` and keeps `None` meaning exactly
    what it means in matplotlib. The scale itself is immutable, so the stated colours come back on a
    **new** scale: a domain derived once and shared across an animation's frames must not pick up one
    frame's styling.

    Args:
        missing: Colour for a value the scale cannot place, or `None` to keep the current `missing`.
        over: Colour for a value above `vmax`, or `None` to keep the current `over`.
        under: Colour for a value below `vmin`, or `None` to keep the current `under`.

    Returns:
        A new scale with the same domain, scheme, classes and categories, carrying the stated colours.
        Never `self`, even when nothing was stated.

    Examples:
        - State all three on a derived scale, and read them back:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_values([1.0, 9.0]).with_extremes(
            ...     missing="#cccccc", over="#ff0000", under="#0000ff"
            ... )
            >>> scale.extremes()
            {'missing': '#cccccc', 'over': '#ff0000', 'under': '#0000ff'}

            ```
        - A colour stated earlier survives a later call that does not name it:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> top = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
            >>> top.with_extremes(missing="#cccccc").extremes()
            {'missing': '#cccccc', 'over': '#ff0000'}

            ```
        - The scale it was called on is unchanged, and the domain travels through:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> original = Scale.from_limits(0.0, 10.0)
            >>> original.with_extremes(under="#0000ff").as_limits()
            (0.0, 10.0)
            >>> original.under is None
            True

            ```
        - `None` keeps rather than clears, and a call that states nothing is still a new scale:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
            >>> stated.with_extremes(over=None).extremes()
            {'over': '#ff0000'}
            >>> bare = stated.with_extremes()
            >>> bare.extremes(), bare is stated
            ({'over': '#ff0000'}, False)
            >>> stated.without_extremes("over").extremes()
            {}

            ```
    """
    return replace(
        self,
        missing=self.missing if missing is None else missing,
        over=self.over if over is None else over,
        under=self.under if under is None else under,
    )

without_extremes(*names) #

Return this scale with the named extreme colours cleared, back to stating none of them.

The other direction of :meth:with_extremes, and a separate verb because None there already means "keep this one" — the rule matplotlib's own with_extremes follows, through Colormap._set_extremes. Overloading None to mean "clear" would break the composition two with_extremes calls rely on; giving it a sentinel value instead would widen all three parameters from Optional[str] to a union every caller and every type check has to carry. So the way back is a call of its own, and dataclasses.replace stops being the only route to it.

What it is for: a stated extreme is styling, and a derived scale travels — a domain measured over a stack is handed to each frame, and a stored figure's scale is read back and reused. Handing one on without the previous caller's over colour is then a call rather than a rebuild.

Parameters:

Name Type Description Default
*names str

The extremes to clear, from "missing", "over" and "under". Named none, it clears all three, which is how a scale says it states no extremes at all. Naming one twice is the same as naming it once.

()

Returns:

Type Description
Scale

A new scale with the same domain, scheme, classes and categories, stating the extremes it was

Scale

not asked to clear. Never self, even when there was nothing to clear.

Raises:

Type Description
ValueError

for a name that is not one of the three, since a silently ignored name would read as a colour that had been cleared.

Examples:

  • A colour stated earlier is cleared by name, and the rest stay stated:
    >>> from digitalearth.base.spec import Scale
    >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
    ...     missing="#cccccc", over="#ff0000"
    ... )
    >>> stated.without_extremes("over").extremes()
    {'missing': '#cccccc'}
    
  • Named nothing it clears all three, and the scale it was called on is unchanged:
    >>> from digitalearth.base.spec import Scale
    >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
    >>> stated.without_extremes().extremes()
    {}
    >>> stated.extremes()
    {'over': '#ff0000'}
    
  • It is the clear with_extremes cannot express, since None there keeps:
    >>> from digitalearth.base.spec import Scale
    >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff")
    >>> stated.with_extremes(under=None).extremes()
    {'under': '#0000ff'}
    >>> stated.without_extremes("under").extremes()
    {}
    
  • A name that is not one of the three is refused rather than ignored:
    >>> from digitalearth.base.spec import Scale
    >>> Scale.from_limits(0.0, 10.0).without_extremes("bad")
    Traceback (most recent call last):
        ...
    ValueError: Scale.without_extremes got unknown extremes ['bad']; known: missing, over, under
    
  • The domain and the classes travel through it:
    >>> from digitalearth.base.spec import Scale
    >>> scale = Scale.from_values([1.0, 4.0, 9.0], scheme="quantiles", k=2)
    >>> cleared = scale.with_extremes(missing="#cccccc").without_extremes()
    >>> cleared.as_limits(), cleared.is_classified
    ((1.0, 9.0), True)
    
Source code in src/digitalearth/base/spec/scale.py
def without_extremes(self, *names: str) -> "Scale":
    """Return this scale with the named extreme colours cleared, back to stating none of them.

    The other direction of :meth:`with_extremes`, and a separate verb because `None` there already
    means "keep this one" — the rule matplotlib's own `with_extremes` follows, through
    `Colormap._set_extremes`. Overloading `None` to mean "clear" would break the composition two
    `with_extremes` calls rely on; giving it a sentinel value instead would widen all three parameters
    from `Optional[str]` to a union every caller and every type check has to carry. So the way back is a
    call of its own, and `dataclasses.replace` stops being the only route to it.

    What it is for: a stated extreme is *styling*, and a derived scale travels — a domain measured over a
    stack is handed to each frame, and a stored figure's scale is read back and reused. Handing one on
    without the previous caller's over colour is then a call rather than a rebuild.

    Args:
        *names: The extremes to clear, from `"missing"`, `"over"` and `"under"`. Named none, it clears
            all three, which is how a scale says it states no extremes at all. Naming one twice is the
            same as naming it once.

    Returns:
        A new scale with the same domain, scheme, classes and categories, stating the extremes it was
        not asked to clear. Never `self`, even when there was nothing to clear.

    Raises:
        ValueError: for a name that is not one of the three, since a silently ignored name would read as
            a colour that had been cleared.

    Examples:
        - A colour stated earlier is cleared by name, and the rest stay stated:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(
            ...     missing="#cccccc", over="#ff0000"
            ... )
            >>> stated.without_extremes("over").extremes()
            {'missing': '#cccccc'}

            ```
        - Named nothing it clears all three, and the scale it was called on is unchanged:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(over="#ff0000")
            >>> stated.without_extremes().extremes()
            {}
            >>> stated.extremes()
            {'over': '#ff0000'}

            ```
        - It is the clear `with_extremes` cannot express, since `None` there keeps:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> stated = Scale.from_limits(0.0, 10.0).with_extremes(under="#0000ff")
            >>> stated.with_extremes(under=None).extremes()
            {'under': '#0000ff'}
            >>> stated.without_extremes("under").extremes()
            {}

            ```
        - A name that is not one of the three is refused rather than ignored:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> Scale.from_limits(0.0, 10.0).without_extremes("bad")
            Traceback (most recent call last):
                ...
            ValueError: Scale.without_extremes got unknown extremes ['bad']; known: missing, over, under

            ```
        - The domain and the classes travel through it:
            ```python
            >>> from digitalearth.base.spec import Scale
            >>> scale = Scale.from_values([1.0, 4.0, 9.0], scheme="quantiles", k=2)
            >>> cleared = scale.with_extremes(missing="#cccccc").without_extremes()
            >>> cleared.as_limits(), cleared.is_classified
            ((1.0, 9.0), True)

            ```
    """
    unknown = sorted({name for name in names if name not in _EXTREME_NAMES})
    if unknown:
        raise ValueError(
            f"Scale.without_extremes got unknown extremes {unknown}; "
            f"known: {', '.join(_EXTREME_NAMES)}"
        )
    cleared = set(names) if names else set(_EXTREME_NAMES)
    return replace(
        self,
        missing=None if "missing" in cleared else self.missing,
        over=None if "over" in cleared else self.over,
        under=None if "under" in cleared else self.under,
    )

Selection — which slice of a dataset a layer draws#

band was one integer being asked several different questions, with each tier adding a parameter beside it where it needed more. Here it is one value, and band is a tuple: a composite is not a special case of a different parameter, it is a selection of three bands.

digitalearth.base.spec.selection.Selection dataclass #

A slice of a dataset: which bands, and which position along every other axis.

Attributes:

Name Type Description
band tuple[int, ...]

1-based band indices, as a tuple. A single band is a one-tuple; a composite is three. Ordered, because an RGB composite's order is the channel order.

time Any

Time step or timestamp, or None for a dataset with no time axis.

level Any

Vertical level, for a 3-D or atmospheric dataset.

member Any

Ensemble member. A list in time, level or member, however nested, is stored as a tuple, so a selection hashes whichever spelling it was given and reads back equal from JSON.

overview int | None

Overview/LOD level to read, where the source has a pyramid. None reads full resolution.

budget int | None

Greatest number of cells or features the reader may return, for a large-data path. None means unbounded.

Raises:

Type Description
ValueError

if band is empty, a band index is not a whole number (1.0 and True are refused), or any band index is below 1. Bands are 1-based everywhere in this package's public surface — a 0 is almost always a caller who expected 0-based indexing, and silently reading band 1 instead would draw the wrong data with no error.

Examples:

  • A scalar band is normalised to a one-tuple, so one code path serves both:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(2).band
    (2,)
    
  • A composite is a selection of three bands, not a different parameter:
    >>> from digitalearth.base.spec import Selection
    >>> rgb = Selection.of((3, 2, 1))
    >>> rgb.band, rgb.is_composite
    ((3, 2, 1), True)
    
  • Narrowing to one band keeps everything else:
    >>> from digitalearth.base.spec import Selection
    >>> stack = Selection.of((1, 2, 3), level=850, member=4)
    >>> narrowed = stack.with_band(2)
    >>> narrowed.band, narrowed.level, narrowed.member
    ((2,), 850, 4)
    
  • A list and a tuple along a free-form axis make one selection:
    >>> from digitalearth.base.spec import Selection
    >>> listed = Selection.of(1, time=[1, 2])
    >>> listed.time, listed == Selection.of(1, time=(1, 2)), len({listed, Selection.of(1, time=(1, 2))})
    ((1, 2), True, 1)
    
Source code in src/digitalearth/base/spec/selection.py
@dataclass(frozen=True)
class Selection:
    """A slice of a dataset: which bands, and which position along every other axis.

    Attributes:
        band: 1-based band indices, as a tuple. A single band is a one-tuple; a composite is three. Ordered,
            because an RGB composite's order is the channel order.
        time: Time step or timestamp, or ``None`` for a dataset with no time axis.
        level: Vertical level, for a 3-D or atmospheric dataset.
        member: Ensemble member. A list in `time`, `level` or `member`, however nested, is stored as a tuple, so a
            selection hashes whichever spelling it was given and reads back equal from JSON.
        overview: Overview/LOD level to read, where the source has a pyramid. ``None`` reads full resolution.
        budget: Greatest number of cells or features the reader may return, for a large-data path. ``None``
            means unbounded.

    Raises:
        ValueError: if `band` is empty, a band index is not a whole number (`1.0` and `True` are refused), or any
            band index is below 1. Bands are 1-based everywhere in this package's public surface — a 0 is almost
            always a caller who expected 0-based indexing, and silently reading band 1 instead would draw the
            wrong data with no error.

    Examples:
        - A scalar band is normalised to a one-tuple, so one code path serves both:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection.of(2).band
            (2,)

            ```
        - A composite is a selection of three bands, not a different parameter:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> rgb = Selection.of((3, 2, 1))
            >>> rgb.band, rgb.is_composite
            ((3, 2, 1), True)

            ```
        - Narrowing to one band keeps everything else:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> stack = Selection.of((1, 2, 3), level=850, member=4)
            >>> narrowed = stack.with_band(2)
            >>> narrowed.band, narrowed.level, narrowed.member
            ((2,), 850, 4)

            ```
        - A list and a tuple along a free-form axis make one selection:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> listed = Selection.of(1, time=[1, 2])
            >>> listed.time, listed == Selection.of(1, time=(1, 2)), len({listed, Selection.of(1, time=(1, 2))})
            ((1, 2), True, 1)

            ```
    """

    band: tuple[int, ...] = (DEFAULT_BAND,)
    time: Any = None
    level: Any = None
    member: Any = None
    overview: int | None = None
    budget: int | None = None

    def __post_init__(self) -> None:
        """Refuse a selection that names no readable band.

        Raises:
            ValueError: for an empty band tuple or a non-positive index.
        """
        # A caller reaching the constructor directly can pass a list; stored as given it would leave the
        # selection unhashable, so coerce before the guards read it.
        object.__setattr__(self, "band", tuple(self.band))
        # The free-form axes are stored canonically — lists as tuples — so a selection hashes whichever spelling it
        # was given and round-trips equal through JSON, which has no tuple.
        for axis in ("time", "level", "member"):
            object.__setattr__(self, axis, frozen_value(getattr(self, axis)))
        if not self.band:
            raise ValueError("Selection needs at least one band")
        bands: list[int] = []
        for index in self.band:
            # bool is an int in Python, and True would read as band 1 — almost never what a caller meant.
            if isinstance(index, bool) or not isinstance(index, Integral):
                raise ValueError(
                    f"Selection needs whole 1-based band numbers; got {index!r}"
                )
            if index < 1:
                raise ValueError(
                    f"Selection bands are 1-based; got {index}. Band 0 is usually a caller expecting "
                    "0-based indexing, which would silently draw the wrong band"
                )
            # Accept any Integral but store a Python int: np.int64 is a whole 1-based band number by every
            # reasonable reading, and GDAL's SWIG binding rejects it outright, so coercing here is what makes
            # `bands=np.array([3, 2, 1])` work at all rather than failing deep inside the reader.
            bands.append(int(index))
        object.__setattr__(self, "band", tuple(bands))

    @classmethod
    def of(cls, band: int | Iterable[int] = DEFAULT_BAND, **rest: Any) -> "Selection":
        """Build a selection, accepting a band as either a scalar or a sequence.

        The one constructor both spellings go through, so a builder that takes ``band=2`` and one that takes
        ``bands=(3, 2, 1)`` end up with the same kind of value.

        Args:
            band: A single 1-based band, or a sequence of them.
            **rest: Any other axis — `time`, `level`, `member`, `overview`, `budget`.

        Returns:
            The selection.

        Raises:
            ValueError: if the bands are empty or not 1-based.

        Examples:
            - Both spellings produce the same shape:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of(1) == Selection.of([1])
                True

                ```
        """
        bands = _as_bands(band)
        return cls(band=bands, **rest)

    @property
    def is_composite(self) -> bool:
        """Whether this selection names more than one band.

        Returns:
            ``True`` for a multi-band selection — what a composite renderer needs to know.

        Examples:
            - Three bands are a composite; one is not:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of((3, 2, 1)).is_composite
                True
                >>> Selection.of(1).is_composite
                False

                ```
            - Which is how a builder picks its path without inspecting the tuple itself:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> sel = Selection.of((4, 3, 2))
                >>> len(sel.band) if sel.is_composite else 1
                3

                ```
        """
        return len(self.band) > 1

    @property
    def first_band(self) -> int:
        """The single band a scalar-band renderer should read.

        Returns:
            The first band in the selection. A composite narrowed to one channel goes through
            :meth:`with_band` instead; this is for the many builders that only ever draw one.

        Examples:
            - The band a single-band builder should read:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of(3).first_band
                3

                ```
            - For a composite it is the first channel, in the order the caller wrote them:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of((7, 2, 1)).first_band
                7

                ```
        """
        return self.band[0]

    def with_band(self, band: int | Iterable[int]) -> "Selection":
        """Return a copy naming different bands, keeping every other axis.

        Args:
            band: The replacement band or bands.

        Returns:
            A new selection. The original is unchanged — this is how a composite iterates its channels without
            losing the level, member or budget that were chosen once.

        Raises:
            ValueError: if the replacement is empty or not 1-based.

        Examples:
            - The other axes survive the narrowing:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of(1, time="2024-01").with_band(7).time
                '2024-01'

                ```
        """
        bands = _as_bands(band)
        return replace(self, band=bands)

    def frames(self) -> tuple["Selection", ...]:
        """Return one single-band selection per band, in order.

        Returns:
            One selection per band — for a single-band selection, one equal to this one; for a composite, the
            per-channel reads in channel order, each still carrying the shared axes. The entries are fresh
            values rather than ``self``, so a caller may hold both without either aliasing the other.

        Examples:
            - An RGB composite becomes its three channel reads, in order:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> [s.first_band for s in Selection.of((3, 2, 1)).frames()]
                [3, 2, 1]

                ```
        """
        return tuple(self.with_band(index) for index in self.band)

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``band`` as a list, plus each other axis that is set. An unset axis is omitted rather than written as
            ``None``, so the common single-band selection is one key.

        Raises:
            TypeError: if an axis other than `band` holds a value with no JSON form — a `datetime`, a set or `nan`,
                say. Store a `datetime` as its ISO string instead.

        Examples:
            - The default selection is one key:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection().to_dict()
                {'band': [1]}

                ```
            - A slice through time and level keeps both:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of(2, time="2024-01", level=850).to_dict()
                {'band': [2], 'time': '2024-01', 'level': 850}

                ```
            - A live `datetime` has no JSON form and is refused where it is written:
                ```python
                >>> from datetime import datetime
                >>> from digitalearth.base.spec import Selection
                >>> Selection.of(1, time=datetime(2024, 1, 1)).to_dict()  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                TypeError: Selection.time holds a datetime, which has no JSON form. ...

                ```
        """
        out: dict[str, Any] = {"band": list(self.band)}
        for name in ("time", "level", "member", "overview", "budget"):
            value = getattr(self, name)
            if value is not None:
                out[name] = to_json_value(value, f"Selection.{name}")
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Selection":
        """Rebuild a selection from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`. A missing ``band`` means the default band.

        Returns:
            The selection, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping, or `band` is not a list — a bare number is refused by name,
                since `to_dict` always writes a list.
            ValueError: for an unknown key, or a band the constructor refuses.

        Examples:
            - A stored composite reads back as a band tuple:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> Selection.from_dict({"band": [3, 2, 1]}).band
                (3, 2, 1)

                ```
            - Without a `band` key the default band is read, and the other axes come back as stored:
                ```python
                >>> from digitalearth.base.spec import Selection
                >>> selection = Selection.from_dict({"time": "2024-01-01", "level": 850})
                >>> selection.band, selection.time, selection.level
                ((1,), '2024-01-01', 850)

                ```
        """
        refuse_unknown(
            "Selection", data, ("band", "time", "level", "member", "overview", "budget")
        )
        return cls(
            band=as_list("Selection", "band", data.get("band", (DEFAULT_BAND,))),
            time=data.get("time"),
            level=data.get("level"),
            member=data.get("member"),
            overview=data.get("overview"),
            budget=data.get("budget"),
        )

first_band property #

The single band a scalar-band renderer should read.

Returns:

Type Description
int

The first band in the selection. A composite narrowed to one channel goes through

int

meth:with_band instead; this is for the many builders that only ever draw one.

Examples:

  • The band a single-band builder should read:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(3).first_band
    3
    
  • For a composite it is the first channel, in the order the caller wrote them:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of((7, 2, 1)).first_band
    7
    

is_composite property #

Whether this selection names more than one band.

Returns:

Type Description
bool

True for a multi-band selection — what a composite renderer needs to know.

Examples:

  • Three bands are a composite; one is not:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of((3, 2, 1)).is_composite
    True
    >>> Selection.of(1).is_composite
    False
    
  • Which is how a builder picks its path without inspecting the tuple itself:
    >>> from digitalearth.base.spec import Selection
    >>> sel = Selection.of((4, 3, 2))
    >>> len(sel.band) if sel.is_composite else 1
    3
    

__post_init__() #

Refuse a selection that names no readable band.

Raises:

Type Description
ValueError

for an empty band tuple or a non-positive index.

Source code in src/digitalearth/base/spec/selection.py
def __post_init__(self) -> None:
    """Refuse a selection that names no readable band.

    Raises:
        ValueError: for an empty band tuple or a non-positive index.
    """
    # A caller reaching the constructor directly can pass a list; stored as given it would leave the
    # selection unhashable, so coerce before the guards read it.
    object.__setattr__(self, "band", tuple(self.band))
    # The free-form axes are stored canonically — lists as tuples — so a selection hashes whichever spelling it
    # was given and round-trips equal through JSON, which has no tuple.
    for axis in ("time", "level", "member"):
        object.__setattr__(self, axis, frozen_value(getattr(self, axis)))
    if not self.band:
        raise ValueError("Selection needs at least one band")
    bands: list[int] = []
    for index in self.band:
        # bool is an int in Python, and True would read as band 1 — almost never what a caller meant.
        if isinstance(index, bool) or not isinstance(index, Integral):
            raise ValueError(
                f"Selection needs whole 1-based band numbers; got {index!r}"
            )
        if index < 1:
            raise ValueError(
                f"Selection bands are 1-based; got {index}. Band 0 is usually a caller expecting "
                "0-based indexing, which would silently draw the wrong band"
            )
        # Accept any Integral but store a Python int: np.int64 is a whole 1-based band number by every
        # reasonable reading, and GDAL's SWIG binding rejects it outright, so coercing here is what makes
        # `bands=np.array([3, 2, 1])` work at all rather than failing deep inside the reader.
        bands.append(int(index))
    object.__setattr__(self, "band", tuple(bands))

frames() #

Return one single-band selection per band, in order.

Returns:

Type Description
Selection

One selection per band — for a single-band selection, one equal to this one; for a composite, the

...

per-channel reads in channel order, each still carrying the shared axes. The entries are fresh

tuple[Selection, ...]

values rather than self, so a caller may hold both without either aliasing the other.

Examples:

  • An RGB composite becomes its three channel reads, in order:
    >>> from digitalearth.base.spec import Selection
    >>> [s.first_band for s in Selection.of((3, 2, 1)).frames()]
    [3, 2, 1]
    
Source code in src/digitalearth/base/spec/selection.py
def frames(self) -> tuple["Selection", ...]:
    """Return one single-band selection per band, in order.

    Returns:
        One selection per band — for a single-band selection, one equal to this one; for a composite, the
        per-channel reads in channel order, each still carrying the shared axes. The entries are fresh
        values rather than ``self``, so a caller may hold both without either aliasing the other.

    Examples:
        - An RGB composite becomes its three channel reads, in order:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> [s.first_band for s in Selection.of((3, 2, 1)).frames()]
            [3, 2, 1]

            ```
    """
    return tuple(self.with_band(index) for index in self.band)

from_dict(data) classmethod #

Rebuild a selection from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict. A missing band means the default band.

required

Returns:

Type Description
Selection

The selection, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping, or band is not a list — a bare number is refused by name, since to_dict always writes a list.

ValueError

for an unknown key, or a band the constructor refuses.

Examples:

  • A stored composite reads back as a band tuple:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.from_dict({"band": [3, 2, 1]}).band
    (3, 2, 1)
    
  • Without a band key the default band is read, and the other axes come back as stored:
    >>> from digitalearth.base.spec import Selection
    >>> selection = Selection.from_dict({"time": "2024-01-01", "level": 850})
    >>> selection.band, selection.time, selection.level
    ((1,), '2024-01-01', 850)
    
Source code in src/digitalearth/base/spec/selection.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Selection":
    """Rebuild a selection from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`. A missing ``band`` means the default band.

    Returns:
        The selection, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping, or `band` is not a list — a bare number is refused by name,
            since `to_dict` always writes a list.
        ValueError: for an unknown key, or a band the constructor refuses.

    Examples:
        - A stored composite reads back as a band tuple:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection.from_dict({"band": [3, 2, 1]}).band
            (3, 2, 1)

            ```
        - Without a `band` key the default band is read, and the other axes come back as stored:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> selection = Selection.from_dict({"time": "2024-01-01", "level": 850})
            >>> selection.band, selection.time, selection.level
            ((1,), '2024-01-01', 850)

            ```
    """
    refuse_unknown(
        "Selection", data, ("band", "time", "level", "member", "overview", "budget")
    )
    return cls(
        band=as_list("Selection", "band", data.get("band", (DEFAULT_BAND,))),
        time=data.get("time"),
        level=data.get("level"),
        member=data.get("member"),
        overview=data.get("overview"),
        budget=data.get("budget"),
    )

of(band=DEFAULT_BAND, **rest) classmethod #

Build a selection, accepting a band as either a scalar or a sequence.

The one constructor both spellings go through, so a builder that takes band=2 and one that takes bands=(3, 2, 1) end up with the same kind of value.

Parameters:

Name Type Description Default
band int | Iterable[int]

A single 1-based band, or a sequence of them.

DEFAULT_BAND
**rest Any

Any other axis — time, level, member, overview, budget.

{}

Returns:

Type Description
Selection

The selection.

Raises:

Type Description
ValueError

if the bands are empty or not 1-based.

Examples:

  • Both spellings produce the same shape:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(1) == Selection.of([1])
    True
    
Source code in src/digitalearth/base/spec/selection.py
@classmethod
def of(cls, band: int | Iterable[int] = DEFAULT_BAND, **rest: Any) -> "Selection":
    """Build a selection, accepting a band as either a scalar or a sequence.

    The one constructor both spellings go through, so a builder that takes ``band=2`` and one that takes
    ``bands=(3, 2, 1)`` end up with the same kind of value.

    Args:
        band: A single 1-based band, or a sequence of them.
        **rest: Any other axis — `time`, `level`, `member`, `overview`, `budget`.

    Returns:
        The selection.

    Raises:
        ValueError: if the bands are empty or not 1-based.

    Examples:
        - Both spellings produce the same shape:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection.of(1) == Selection.of([1])
            True

            ```
    """
    bands = _as_bands(band)
    return cls(band=bands, **rest)

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

band as a list, plus each other axis that is set. An unset axis is omitted rather than written as

dict[str, Any]

None, so the common single-band selection is one key.

Raises:

Type Description
TypeError

if an axis other than band holds a value with no JSON form — a datetime, a set or nan, say. Store a datetime as its ISO string instead.

Examples:

  • The default selection is one key:
    >>> from digitalearth.base.spec import Selection
    >>> Selection().to_dict()
    {'band': [1]}
    
  • A slice through time and level keeps both:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(2, time="2024-01", level=850).to_dict()
    {'band': [2], 'time': '2024-01', 'level': 850}
    
  • A live datetime has no JSON form and is refused where it is written:
    >>> from datetime import datetime
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(1, time=datetime(2024, 1, 1)).to_dict()  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    TypeError: Selection.time holds a datetime, which has no JSON form. ...
    
Source code in src/digitalearth/base/spec/selection.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``band`` as a list, plus each other axis that is set. An unset axis is omitted rather than written as
        ``None``, so the common single-band selection is one key.

    Raises:
        TypeError: if an axis other than `band` holds a value with no JSON form — a `datetime`, a set or `nan`,
            say. Store a `datetime` as its ISO string instead.

    Examples:
        - The default selection is one key:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection().to_dict()
            {'band': [1]}

            ```
        - A slice through time and level keeps both:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection.of(2, time="2024-01", level=850).to_dict()
            {'band': [2], 'time': '2024-01', 'level': 850}

            ```
        - A live `datetime` has no JSON form and is refused where it is written:
            ```python
            >>> from datetime import datetime
            >>> from digitalearth.base.spec import Selection
            >>> Selection.of(1, time=datetime(2024, 1, 1)).to_dict()  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            TypeError: Selection.time holds a datetime, which has no JSON form. ...

            ```
    """
    out: dict[str, Any] = {"band": list(self.band)}
    for name in ("time", "level", "member", "overview", "budget"):
        value = getattr(self, name)
        if value is not None:
            out[name] = to_json_value(value, f"Selection.{name}")
    return out

with_band(band) #

Return a copy naming different bands, keeping every other axis.

Parameters:

Name Type Description Default
band int | Iterable[int]

The replacement band or bands.

required

Returns:

Type Description
Selection

A new selection. The original is unchanged — this is how a composite iterates its channels without

Selection

losing the level, member or budget that were chosen once.

Raises:

Type Description
ValueError

if the replacement is empty or not 1-based.

Examples:

  • The other axes survive the narrowing:
    >>> from digitalearth.base.spec import Selection
    >>> Selection.of(1, time="2024-01").with_band(7).time
    '2024-01'
    
Source code in src/digitalearth/base/spec/selection.py
def with_band(self, band: int | Iterable[int]) -> "Selection":
    """Return a copy naming different bands, keeping every other axis.

    Args:
        band: The replacement band or bands.

    Returns:
        A new selection. The original is unchanged — this is how a composite iterates its channels without
        losing the level, member or budget that were chosen once.

    Raises:
        ValueError: if the replacement is empty or not 1-based.

    Examples:
        - The other axes survive the narrowing:
            ```python
            >>> from digitalearth.base.spec import Selection
            >>> Selection.of(1, time="2024-01").with_band(7).time
            '2024-01'

            ```
    """
    bands = _as_bands(band)
    return replace(self, band=bands)

DataRef — where the data is, rather than the data#

A layer that owns its data object cannot be tiled, cannot decimate, cannot hold a point cloud too large to read, and cannot round-trip through a dict. DataRef names the data; the registry opens it.

digitalearth.base.spec.dataref.DataRef dataclass #

Where a layer's data comes from, as a value rather than the data itself.

Attributes:

Name Type Description
uri str

What to open — a filesystem path, a URL, or an object:<id> naming something registered in this process by :meth:DataRef.to_object.

driver str | None

Optional reader hint, for a path whose extension does not settle which reader to use.

version str | None

Optional version or revision, so a figure can record which vintage of a moving dataset it described. Carried, not interpreted — a resolver that understands versioning reads it.

Examples:

  • A path, and the dict a figure would store:
    >>> from digitalearth.base.spec import DataRef
    >>> ref = DataRef("data/dem.tif")
    >>> ref.to_dict()
    {'uri': 'data/dem.tif'}
    
  • A round trip through a dict, which is what makes a figure serialisable:
    >>> from digitalearth.base.spec import DataRef
    >>> DataRef.from_dict({'uri': 's3://bucket/x.tif', 'driver': 'COG'})
    DataRef(uri='s3://bucket/x.tif', driver='COG', version=None)
    
  • An in-memory object is referenced without being written to disk:
    >>> from digitalearth.base.spec import DataRef
    >>> ref = DataRef.to_object([1, 2, 3], name="demo-doc")
    >>> ref.uri
    'object:demo-doc'
    >>> ref.open()
    [1, 2, 3]
    
Source code in src/digitalearth/base/spec/dataref.py
@dataclass(frozen=True)
class DataRef:
    """Where a layer's data comes from, as a value rather than the data itself.

    Attributes:
        uri: What to open — a filesystem path, a URL, or an ``object:<id>`` naming something registered in
            this process by :meth:`DataRef.to_object`.
        driver: Optional reader hint, for a path whose extension does not settle which reader to use.
        version: Optional version or revision, so a figure can record *which* vintage of a moving dataset it
            described. Carried, not interpreted — a resolver that understands versioning reads it.

    Examples:
        - A path, and the dict a figure would store:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> ref = DataRef("data/dem.tif")
            >>> ref.to_dict()
            {'uri': 'data/dem.tif'}

            ```
        - A round trip through a dict, which is what makes a figure serialisable:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> DataRef.from_dict({'uri': 's3://bucket/x.tif', 'driver': 'COG'})
            DataRef(uri='s3://bucket/x.tif', driver='COG', version=None)

            ```
        - An in-memory object is referenced without being written to disk:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> ref = DataRef.to_object([1, 2, 3], name="demo-doc")
            >>> ref.uri
            'object:demo-doc'
            >>> ref.open()
            [1, 2, 3]

            ```
    """

    uri: str
    driver: str | None = None
    version: str | None = None

    def __post_init__(self) -> None:
        """Refuse a reference that names nothing, or holds a hint a figure could not store.

        Raises:
            ValueError: if `uri` is not a string or is empty or blank — an empty reference resolves to whatever the
                working directory happens to be, which is a failure that only shows on someone else's machine —
                or if `driver` or `version` is neither a string nor ``None``. A `pathlib.Path` is refused as a
                `uri` too: pass ``str(path)``.
        """
        if not isinstance(self.uri, str) or not self.uri.strip():
            raise ValueError(
                f"DataRef needs uri as a non-empty string; got {self.uri!r}"
            )
        for hint in ("driver", "version"):
            value = getattr(self, hint)
            if value is not None and not isinstance(value, str):
                # Written by `to_dict` as it is, a non-string hint failed inside `json.dumps`, naming neither
                # the type nor the field — or, for a number, read back as a number.
                raise ValueError(
                    f"DataRef needs {hint} as a string or None; got {value!r}"
                )
        if self.uri != self.uri.strip() and not self.uri.startswith(
            f"{OBJECT_SCHEME}:"
        ):
            # Blank was already refused; surrounding whitespace was not, and " a.tif" is a path that does
            # not exist on any filesystem that would have opened "a.tif".
            #
            # An `object:` uri is exempt because its tail is not a path but the **key**
            # `digitalearth.base.registry.register_object` stored, verbatim, whitespace included. Stripping
            # it here rewrote the reference away from the entry it had just been handed, so
            # `Map.points(features, name="roads ")` raised a `KeyError` naming neither the layer nor the
            # name (review R2-H4). `layer_name` now keeps a padded key from ever being registered; this
            # keeps a reference honest even when something registers one anyway.
            object.__setattr__(self, "uri", self.uri.strip())

    @classmethod
    def to_object(cls, obj: Any, *, name: str = "", **rest: Any) -> "DataRef":
        """Register an in-memory object and return a reference to it.

        Args:
            obj: The object to reference — typically a pyramids ``Dataset`` or ``FeatureCollection``.
            name: An optional stable id; reusing one replaces what it points at.
            **rest: Any other field — `driver`, `version`.

        Returns:
            A reference whose `uri` resolves to `obj` **in this process**. It is deliberately not portable:
            see :func:`digitalearth.base.registry.register_object`.

        Examples:
            - The reference reaches the same object back:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> rows = [1, 2]
                >>> DataRef.to_object(rows, name="demo-rows").open() is rows
                True

                ```
        """
        return cls(register_object(obj, name=name), **rest)

    @classmethod
    def of(cls, data: Any, *, name: str = "") -> "DataRef":
        """Return the reference a builder stores for whatever it was given.

        Args:
            data: A path or URL, a `DataRef` already, or an object in memory — a pyramids dataset, a
                GeoDataFrame, an array.
            name: A stable id for an in-memory object; reusing one replaces what it points at.

        Returns:
            The reference as given for a `DataRef`; a reference to that path or URL for a string or
            `os.PathLike`, so the figure can be written and read back anywhere; and an `object:` reference
            otherwise, which resolves in this process only — a pyramids dataset does not know where it came
            from, so that is the only honest reference to one.

        Examples:
            - A path is referenced as a path, which a stored figure can carry:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> DataRef.of("data/dem.tif").uri
                'data/dem.tif'

                ```
            - An object is registered, and the reference reaches it back:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> rows = [1, 2, 3]
                >>> DataRef.of(rows, name="demo-of").open() is rows
                True

                ```
            - A reference already made is kept as it is:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> held = DataRef("s3://bucket/dem.tif")
                >>> DataRef.of(held) is held
                True

                ```
        """
        if isinstance(data, DataRef):
            return data
        if isinstance(data, (str, os.PathLike)):
            return cls(str(data))
        return cls.to_object(data, name=name)

    def open(self) -> Any:
        """Open the data this reference names.

        Returns:
            Whatever the registered resolver returns for this URI's scheme — a pyramids ``Dataset`` or
            ``FeatureCollection`` for the built-in file resolver.

        Raises:
            KeyError: if no resolver is registered for the scheme, or an ``object:`` id is not in this
                process.

        Examples:
            - An in-memory reference hands back the data it names:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> ref = DataRef.to_object({"rows": 3}, name="doc-open")
                >>> ref.open()["rows"]
                3

                ```
            - A scheme nothing is registered for says so, and lists the ones that are — a plugin that failed
              to install looks exactly like a typo otherwise:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> DataRef("weirdscheme://x").open()  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                KeyError: "no resolver registered for scheme 'weirdscheme'; known schemes are [...]..."

                ```
        """
        return resolve_uri(self.uri)

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            The fields that are set, each as a Python `str`, a field held as a `numpy.str_` included. `driver` and
            `version` are omitted when unset, so the common case is one key and a stored figure does not fill with
            nulls.

        Examples:
            - The common case is a single key:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> DataRef("data/dem.tif").to_dict()
                {'uri': 'data/dem.tif'}

                ```
            - Hints appear only when they were set:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> stored = DataRef("s3://bucket/x.tif", version="2024-01").to_dict()
                >>> sorted(stored)
                ['uri', 'version']
                >>> stored["version"]
                '2024-01'

                ```
        """
        out: dict[str, Any] = {"uri": plain_text(self.uri)}
        if self.driver is not None:
            out["driver"] = plain_text(self.driver)
        if self.version is not None:
            out["version"] = plain_text(self.version)
        return out

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "DataRef":
        """Rebuild a reference from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The reference.

        Raises:
            TypeError: if `data` is not a mapping — a bare path string included, which would otherwise be read as a
                mapping of its letters.
            ValueError: if `uri` is missing or empty, a field is not a string, or the mapping carries a key this
                type does not know — silently dropping an unknown key would lose data a newer writer meant to keep.

        Examples:
            - Rebuild a reference a figure stored, and read its fields back:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> ref = DataRef.from_dict({"uri": "s3://bucket/x.tif", "driver": "COG"})
                >>> ref.uri, ref.driver
                ('s3://bucket/x.tif', 'COG')

                ```
            - A key this version does not know is refused rather than dropped:
                ```python
                >>> from digitalearth.base.spec import DataRef
                >>> DataRef.from_dict({"uri": "a.tif", "bbox": [0, 0, 1, 1]})
                Traceback (most recent call last):
                    ...
                ValueError: DataRef.from_dict got unknown keys ['bbox']; known keys are ['driver', 'uri', 'version']

                ```
        """
        refuse_unknown("DataRef", data, ("uri", "driver", "version"))
        return cls(
            uri=require("DataRef", data, "uri"),
            driver=data.get("driver"),
            version=data.get("version"),
        )

__post_init__() #

Refuse a reference that names nothing, or holds a hint a figure could not store.

Raises:

Type Description
ValueError

if uri is not a string or is empty or blank — an empty reference resolves to whatever the working directory happens to be, which is a failure that only shows on someone else's machine — or if driver or version is neither a string nor None. A pathlib.Path is refused as a uri too: pass str(path).

Source code in src/digitalearth/base/spec/dataref.py
def __post_init__(self) -> None:
    """Refuse a reference that names nothing, or holds a hint a figure could not store.

    Raises:
        ValueError: if `uri` is not a string or is empty or blank — an empty reference resolves to whatever the
            working directory happens to be, which is a failure that only shows on someone else's machine —
            or if `driver` or `version` is neither a string nor ``None``. A `pathlib.Path` is refused as a
            `uri` too: pass ``str(path)``.
    """
    if not isinstance(self.uri, str) or not self.uri.strip():
        raise ValueError(
            f"DataRef needs uri as a non-empty string; got {self.uri!r}"
        )
    for hint in ("driver", "version"):
        value = getattr(self, hint)
        if value is not None and not isinstance(value, str):
            # Written by `to_dict` as it is, a non-string hint failed inside `json.dumps`, naming neither
            # the type nor the field — or, for a number, read back as a number.
            raise ValueError(
                f"DataRef needs {hint} as a string or None; got {value!r}"
            )
    if self.uri != self.uri.strip() and not self.uri.startswith(
        f"{OBJECT_SCHEME}:"
    ):
        # Blank was already refused; surrounding whitespace was not, and " a.tif" is a path that does
        # not exist on any filesystem that would have opened "a.tif".
        #
        # An `object:` uri is exempt because its tail is not a path but the **key**
        # `digitalearth.base.registry.register_object` stored, verbatim, whitespace included. Stripping
        # it here rewrote the reference away from the entry it had just been handed, so
        # `Map.points(features, name="roads ")` raised a `KeyError` naming neither the layer nor the
        # name (review R2-H4). `layer_name` now keeps a padded key from ever being registered; this
        # keeps a reference honest even when something registers one anyway.
        object.__setattr__(self, "uri", self.uri.strip())

from_dict(data) classmethod #

Rebuild a reference from its dict form.

Parameters:

Name Type Description Default
data dict[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
DataRef

The reference.

Raises:

Type Description
TypeError

if data is not a mapping — a bare path string included, which would otherwise be read as a mapping of its letters.

ValueError

if uri is missing or empty, a field is not a string, or the mapping carries a key this type does not know — silently dropping an unknown key would lose data a newer writer meant to keep.

Examples:

  • Rebuild a reference a figure stored, and read its fields back:
    >>> from digitalearth.base.spec import DataRef
    >>> ref = DataRef.from_dict({"uri": "s3://bucket/x.tif", "driver": "COG"})
    >>> ref.uri, ref.driver
    ('s3://bucket/x.tif', 'COG')
    
  • A key this version does not know is refused rather than dropped:
    >>> from digitalearth.base.spec import DataRef
    >>> DataRef.from_dict({"uri": "a.tif", "bbox": [0, 0, 1, 1]})
    Traceback (most recent call last):
        ...
    ValueError: DataRef.from_dict got unknown keys ['bbox']; known keys are ['driver', 'uri', 'version']
    
Source code in src/digitalearth/base/spec/dataref.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "DataRef":
    """Rebuild a reference from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The reference.

    Raises:
        TypeError: if `data` is not a mapping — a bare path string included, which would otherwise be read as a
            mapping of its letters.
        ValueError: if `uri` is missing or empty, a field is not a string, or the mapping carries a key this
            type does not know — silently dropping an unknown key would lose data a newer writer meant to keep.

    Examples:
        - Rebuild a reference a figure stored, and read its fields back:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> ref = DataRef.from_dict({"uri": "s3://bucket/x.tif", "driver": "COG"})
            >>> ref.uri, ref.driver
            ('s3://bucket/x.tif', 'COG')

            ```
        - A key this version does not know is refused rather than dropped:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> DataRef.from_dict({"uri": "a.tif", "bbox": [0, 0, 1, 1]})
            Traceback (most recent call last):
                ...
            ValueError: DataRef.from_dict got unknown keys ['bbox']; known keys are ['driver', 'uri', 'version']

            ```
    """
    refuse_unknown("DataRef", data, ("uri", "driver", "version"))
    return cls(
        uri=require("DataRef", data, "uri"),
        driver=data.get("driver"),
        version=data.get("version"),
    )

of(data, *, name='') classmethod #

Return the reference a builder stores for whatever it was given.

Parameters:

Name Type Description Default
data Any

A path or URL, a DataRef already, or an object in memory — a pyramids dataset, a GeoDataFrame, an array.

required
name str

A stable id for an in-memory object; reusing one replaces what it points at.

''

Returns:

Type Description
DataRef

The reference as given for a DataRef; a reference to that path or URL for a string or

DataRef

os.PathLike, so the figure can be written and read back anywhere; and an object: reference

DataRef

otherwise, which resolves in this process only — a pyramids dataset does not know where it came

DataRef

from, so that is the only honest reference to one.

Examples:

  • A path is referenced as a path, which a stored figure can carry:
    >>> from digitalearth.base.spec import DataRef
    >>> DataRef.of("data/dem.tif").uri
    'data/dem.tif'
    
  • An object is registered, and the reference reaches it back:
    >>> from digitalearth.base.spec import DataRef
    >>> rows = [1, 2, 3]
    >>> DataRef.of(rows, name="demo-of").open() is rows
    True
    
  • A reference already made is kept as it is:
    >>> from digitalearth.base.spec import DataRef
    >>> held = DataRef("s3://bucket/dem.tif")
    >>> DataRef.of(held) is held
    True
    
Source code in src/digitalearth/base/spec/dataref.py
@classmethod
def of(cls, data: Any, *, name: str = "") -> "DataRef":
    """Return the reference a builder stores for whatever it was given.

    Args:
        data: A path or URL, a `DataRef` already, or an object in memory — a pyramids dataset, a
            GeoDataFrame, an array.
        name: A stable id for an in-memory object; reusing one replaces what it points at.

    Returns:
        The reference as given for a `DataRef`; a reference to that path or URL for a string or
        `os.PathLike`, so the figure can be written and read back anywhere; and an `object:` reference
        otherwise, which resolves in this process only — a pyramids dataset does not know where it came
        from, so that is the only honest reference to one.

    Examples:
        - A path is referenced as a path, which a stored figure can carry:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> DataRef.of("data/dem.tif").uri
            'data/dem.tif'

            ```
        - An object is registered, and the reference reaches it back:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> rows = [1, 2, 3]
            >>> DataRef.of(rows, name="demo-of").open() is rows
            True

            ```
        - A reference already made is kept as it is:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> held = DataRef("s3://bucket/dem.tif")
            >>> DataRef.of(held) is held
            True

            ```
    """
    if isinstance(data, DataRef):
        return data
    if isinstance(data, (str, os.PathLike)):
        return cls(str(data))
    return cls.to_object(data, name=name)

open() #

Open the data this reference names.

Returns:

Type Description
Any

Whatever the registered resolver returns for this URI's scheme — a pyramids Dataset or

Any

FeatureCollection for the built-in file resolver.

Raises:

Type Description
KeyError

if no resolver is registered for the scheme, or an object: id is not in this process.

Examples:

  • An in-memory reference hands back the data it names:
    >>> from digitalearth.base.spec import DataRef
    >>> ref = DataRef.to_object({"rows": 3}, name="doc-open")
    >>> ref.open()["rows"]
    3
    
  • A scheme nothing is registered for says so, and lists the ones that are — a plugin that failed to install looks exactly like a typo otherwise:
    >>> from digitalearth.base.spec import DataRef
    >>> DataRef("weirdscheme://x").open()  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    KeyError: "no resolver registered for scheme 'weirdscheme'; known schemes are [...]..."
    
Source code in src/digitalearth/base/spec/dataref.py
def open(self) -> Any:
    """Open the data this reference names.

    Returns:
        Whatever the registered resolver returns for this URI's scheme — a pyramids ``Dataset`` or
        ``FeatureCollection`` for the built-in file resolver.

    Raises:
        KeyError: if no resolver is registered for the scheme, or an ``object:`` id is not in this
            process.

    Examples:
        - An in-memory reference hands back the data it names:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> ref = DataRef.to_object({"rows": 3}, name="doc-open")
            >>> ref.open()["rows"]
            3

            ```
        - A scheme nothing is registered for says so, and lists the ones that are — a plugin that failed
          to install looks exactly like a typo otherwise:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> DataRef("weirdscheme://x").open()  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            KeyError: "no resolver registered for scheme 'weirdscheme'; known schemes are [...]..."

            ```
    """
    return resolve_uri(self.uri)

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

The fields that are set, each as a Python str, a field held as a numpy.str_ included. driver and

dict[str, Any]

version are omitted when unset, so the common case is one key and a stored figure does not fill with

dict[str, Any]

nulls.

Examples:

  • The common case is a single key:
    >>> from digitalearth.base.spec import DataRef
    >>> DataRef("data/dem.tif").to_dict()
    {'uri': 'data/dem.tif'}
    
  • Hints appear only when they were set:
    >>> from digitalearth.base.spec import DataRef
    >>> stored = DataRef("s3://bucket/x.tif", version="2024-01").to_dict()
    >>> sorted(stored)
    ['uri', 'version']
    >>> stored["version"]
    '2024-01'
    
Source code in src/digitalearth/base/spec/dataref.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        The fields that are set, each as a Python `str`, a field held as a `numpy.str_` included. `driver` and
        `version` are omitted when unset, so the common case is one key and a stored figure does not fill with
        nulls.

    Examples:
        - The common case is a single key:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> DataRef("data/dem.tif").to_dict()
            {'uri': 'data/dem.tif'}

            ```
        - Hints appear only when they were set:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> stored = DataRef("s3://bucket/x.tif", version="2024-01").to_dict()
            >>> sorted(stored)
            ['uri', 'version']
            >>> stored["version"]
            '2024-01'

            ```
    """
    out: dict[str, Any] = {"uri": plain_text(self.uri)}
    if self.driver is not None:
        out["driver"] = plain_text(self.driver)
    if self.version is not None:
        out["version"] = plain_text(self.version)
    return out

to_object(obj, *, name='', **rest) classmethod #

Register an in-memory object and return a reference to it.

Parameters:

Name Type Description Default
obj Any

The object to reference — typically a pyramids Dataset or FeatureCollection.

required
name str

An optional stable id; reusing one replaces what it points at.

''
**rest Any

Any other field — driver, version.

{}

Returns:

Name Type Description
DataRef

A reference whose uri resolves to obj in this process. It is deliberately not portable:

see DataRef

func:digitalearth.base.registry.register_object.

Examples:

  • The reference reaches the same object back:
    >>> from digitalearth.base.spec import DataRef
    >>> rows = [1, 2]
    >>> DataRef.to_object(rows, name="demo-rows").open() is rows
    True
    
Source code in src/digitalearth/base/spec/dataref.py
@classmethod
def to_object(cls, obj: Any, *, name: str = "", **rest: Any) -> "DataRef":
    """Register an in-memory object and return a reference to it.

    Args:
        obj: The object to reference — typically a pyramids ``Dataset`` or ``FeatureCollection``.
        name: An optional stable id; reusing one replaces what it points at.
        **rest: Any other field — `driver`, `version`.

    Returns:
        A reference whose `uri` resolves to `obj` **in this process**. It is deliberately not portable:
        see :func:`digitalearth.base.registry.register_object`.

    Examples:
        - The reference reaches the same object back:
            ```python
            >>> from digitalearth.base.spec import DataRef
            >>> rows = [1, 2]
            >>> DataRef.to_object(rows, name="demo-rows").open() is rows
            True

            ```
    """
    return cls(register_object(obj, name=name), **rest)

Encoding and Symbology — how a layer looks#

Styling reached the renderers as undeclared keyword soup: 26 keys in the static tier alone, in no signature anywhere, so a caller could not ask what a builder accepts and a typo was a silently ignored keyword rather than an error. Encoding makes a visual channel a key rather than a parameter on every builder — which is what makes size, width, extrusion and text cheap to add — and Symbology is a layer's style as a declared value.

digitalearth.base.spec.encoding.Encoding dataclass #

What drives one visual channel: a constant, or a field read through a scale.

Attributes:

Name Type Description
channel str

Which channel this drives — a key of :data:CHANNELS.

value Any

The constant, when the channel does not vary with the data. A list in it, however nested, is stored as a tuple, so [1, 0, 0] and (1, 0, 0) are one constant. A mapping is a constant like any other — it is stored with its values frozen the same way, round-trips through to_dict, and hashes (review L5).

field str | None

The column or band name the channel varies with. Exactly one of value and field is set.

scale Scale | None

How a field's values map onto the channel. None passes the values through untouched, which is what a renderer wants when it holds its own mapping.

output_range tuple[float, float] | None

(low, high) the normalised position is stretched into, for a numeric channel — the marker sizes or line widths the data should span. Meaningless for a colour channel, whose positions the backend's ramp consumes.

guide Optional[Guide]

How the channel is explained to the reader — a legend or a colorbar, titled and placed. None leaves that to the renderer's own rule. The guide lives here, with what it explains, rather than on the panel: a scale shared by several layers is explained once.

Raises:

Type Description
ValueError

if the channel is not declared, if neither or both of value/field are given, if field is not a non-empty string, if a scale or an output range is attached to a constant — a constant that carries a scale is a caller who expected that scale to apply, and silently ignoring it would draw one colour — or if guide is not a :class:Guide. Note this is about the scale/output_range fields, not about a value that happens to be a mapping, which is accepted.

Examples:

  • A constant, which is what a plain color="#f00" means:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.constant("color", "#f00").resolve()
    '#f00'
    
  • Driven by a field, resolving to ramp positions the backend colours:
    >>> from digitalearth.base.spec import Encoding, Scale
    >>> enc = Encoding.by_field("color", "elevation", scale=Scale.from_limits(0.0, 10.0))
    >>> enc.resolve([0.0, 5.0, 10.0])
    [0.0, 0.5, 1.0]
    
  • The same shape drives size, in real units — the reason a new channel costs a row, not a parameter:
    >>> from digitalearth.base.spec import Encoding, Scale
    >>> enc = Encoding.by_field(
    ...     "size", "population", scale=Scale.from_limits(0.0, 100.0), output_range=(4.0, 20.0)
    ... )
    >>> enc.resolve([0.0, 50.0, 100.0])
    [4.0, 12.0, 20.0]
    
Source code in src/digitalearth/base/spec/encoding.py
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
@dataclass(frozen=True)
class Encoding:
    """What drives one visual channel: a constant, or a field read through a scale.

    Attributes:
        channel: Which channel this drives — a key of :data:`CHANNELS`.
        value: The constant, when the channel does not vary with the data. A list in it, however nested, is stored
            as a tuple, so `[1, 0, 0]` and `(1, 0, 0)` are one constant. A **mapping** is a constant like any
            other — it is stored with its values frozen the same way, round-trips through `to_dict`, and hashes
            (review L5).
        field: The column or band name the channel varies with. Exactly one of `value` and `field` is set.
        scale: How a field's values map onto the channel. ``None`` passes the values through untouched, which
            is what a renderer wants when it holds its own mapping.
        output_range: ``(low, high)`` the normalised position is stretched into, for a numeric channel — the
            marker sizes or line widths the data should span. Meaningless for a colour channel, whose
            positions the backend's ramp consumes.
        guide: How the channel is explained to the reader — a legend or a colorbar, titled and placed. `None`
            leaves that to the renderer's own rule. The guide lives here, with what it explains, rather than on
            the panel: a scale shared by several layers is explained once.

    Raises:
        ValueError: if the channel is not declared, if neither or both of `value`/`field` are given, if `field` is
            not a non-empty string, if a scale or an output range is attached to a constant — a constant that
            carries a *scale* is a caller who expected that scale to apply, and silently ignoring it would draw one
            colour — or if `guide` is not a :class:`Guide`. Note this is about the `scale`/`output_range` fields,
            not about a `value` that happens to be a mapping, which is accepted.

    Examples:
        - A constant, which is what a plain ``color="#f00"`` means:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.constant("color", "#f00").resolve()
            '#f00'

            ```
        - Driven by a field, resolving to ramp positions the backend colours:
            ```python
            >>> from digitalearth.base.spec import Encoding, Scale
            >>> enc = Encoding.by_field("color", "elevation", scale=Scale.from_limits(0.0, 10.0))
            >>> enc.resolve([0.0, 5.0, 10.0])
            [0.0, 0.5, 1.0]

            ```
        - The same shape drives size, in real units — the reason a new channel costs a row, not a parameter:
            ```python
            >>> from digitalearth.base.spec import Encoding, Scale
            >>> enc = Encoding.by_field(
            ...     "size", "population", scale=Scale.from_limits(0.0, 100.0), output_range=(4.0, 20.0)
            ... )
            >>> enc.resolve([0.0, 50.0, 100.0])
            [4.0, 12.0, 20.0]

            ```
    """

    channel: str
    value: Any = None
    field: str | None = None
    scale: Scale | None = None
    output_range: tuple[float, float] | None = None
    guide: Optional["Guide"] = None

    def __post_init__(self) -> None:
        """Refuse an encoding that names no channel, or names both a constant and a field.

        Raises:
            ValueError: for an undeclared channel, an ambiguous or empty binding, a field that is not a string, a
                mapping attached to a constant, or a `guide` that is not a :class:`Guide`.
        """
        if self.guide is not None and not isinstance(self.guide, Guide):
            raise ValueError(
                f"Encoding guide must be a Guide or None; got {type(self.guide).__name__}"
            )
        if self.channel not in CHANNELS:
            raise ValueError(
                f"{self.channel!r} is not a visual channel; declared channels are {sorted(CHANNELS)}"
            )
        # A constant is stored canonically — lists as tuples — so an encoding round-trips equal through JSON,
        # which has no tuple, and hashes whichever spelling the caller used.
        object.__setattr__(self, "value", frozen_value(self.value))
        if (self.value is None) == (self.field is None):
            raise ValueError(
                f"an Encoding for {self.channel!r} needs exactly one of value= (a constant) or field= "
                "(driven by the data); a constant of None reads as no binding at all"
            )
        if self.field is not None and (
            not isinstance(self.field, str) or not self.field.strip()
        ):
            # `by_field` refuses an empty name, but the constructor is public too — and an empty field name reports
            # is_constant == False while naming a column nobody can look up. A field that is not a string at all —
            # a datetime, NaN, a number — would be written by `to_dict` as it is, and fail inside `json.dumps`.
            raise ValueError(
                f"an Encoding for {self.channel!r} needs a field name that is a non-empty string; got {self.field!r}"
            )
        self._check_output_range()
        if self.field is None and (
            self.scale is not None or self.output_range is not None
        ):
            raise ValueError(
                f"a constant Encoding for {self.channel!r} cannot carry a scale or an output range; "
                "they only apply to a field"
            )
        if (
            self.output_range is not None
            and self.scale is not None
            and self.scale.is_categorical
        ):
            # A categorical scale resolves to its own colours, so there is no position for a range to
            # stretch. Ignoring the argument returned colours from a channel the caller asked numbers of.
            raise ValueError(
                f"the {self.channel!r} encoding cannot combine a categorical scale with an output range: "
                "a category resolves to its assigned colour, not to a position a range can stretch"
            )

    def _check_output_range(self) -> None:
        """Store `output_range` as a tuple, refusing anything that is not a `(low, high)` pair.

        Raises:
            ValueError: for a string, a non-iterable or an iterable that does not hold exactly two items, naming the
                channel.
        """
        if self.output_range is None:
            return
        if isinstance(self.output_range, (str, bytes)) or not hasattr(
            self.output_range, "__iter__"
        ):
            # tuple(5) raises TypeError about ints, which names neither the argument nor the channel.
            raise ValueError(
                f"the {self.channel!r} encoding needs output_range as a (low, high) pair; got "
                f"{self.output_range!r}"
            )
        object.__setattr__(self, "output_range", tuple(self.output_range))
        if len(self.output_range) != 2:
            raise ValueError(
                f"the {self.channel!r} encoding needs output_range as a (low, high) pair; got "
                f"{self.output_range!r}"
            )

    def __hash__(self) -> int:
        """Hash by what drives the channel, with a mapping in the constant hashed as its items.

        A frozen dataclass hashes its fields as they are, and `value` is free-form: a constant that holds a
        mapping raised `unhashable type: 'dict'`, and took every `Symbology` and `LayerSpec` holding it down
        with it. :meth:`~digitalearth.base.spec.style.Symbology.__hash__` had already answered that for its
        properties, and says a mapping is hashed as its items *wherever it sits* — the constant beside them
        is where else it sits (review L5).

        Returns:
            A hash over every field, each put through
            :func:`~digitalearth.base.spec._serial.hashable_value` first. Read from the dataclass's own
            fields rather than named here, so a channel binding that gains a field is covered by it too.

        Raises:
            TypeError: if a field holds a value that is unhashable for its own reasons. Neither a list, a
                numpy array nor a mapping is among them: the first two are stored as tuples, and the third
                is hashed as its items, however deeply it sits.

        Examples:
            - A constant bound to a mapping hashes, and two spellings of it hash alike:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> written = Encoding.constant("color", {"high": "#f00", "low": "#00f"})
                >>> rewritten = Encoding.constant("color", {"low": "#00f", "high": "#f00"})
                >>> hash(written) == hash(rewritten), len({written, rewritten})
                (True, 1)

                ```
        """
        return hash(
            tuple(hashable_value(getattr(self, field.name)) for field in fields(self))
        )

    # ------------------------------------------------------------------ builders

    @classmethod
    def constant(
        cls, channel: str, value: Any, *, guide: Optional["Guide"] = None
    ) -> "Encoding":
        """Bind a channel to one value for every feature.

        Args:
            channel: The channel to drive.
            value: The constant.
            guide: How the channel is explained to the reader. A constant rarely needs one — there is nothing to
                read off — but a chosen colour that stands for something does.

        Returns:
            The encoding.

        Raises:
            ValueError: if the channel is undeclared, or `value` is ``None`` — which would read as "no
                binding" rather than "this channel is off".

        Examples:
            - A constant colour, resolved back out:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.constant("color", "#1e90ff").resolve()
                '#1e90ff'

                ```
            - Any declared channel works the same way, and knows it does not vary:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> width = Encoding.constant("width", 2.5)
                >>> width.is_constant, width.resolve([1, 2])
                (True, [2.5, 2.5])

                ```
        """
        return cls(channel=channel, value=value, guide=guide)

    @classmethod
    def by_field(
        cls,
        channel: str,
        field: str,
        *,
        scale: Scale | None = None,
        output_range: tuple[float, float] | None = None,
        guide: Optional["Guide"] = None,
    ) -> "Encoding":
        """Bind a channel to a data field.

        Args:
            channel: The channel to drive.
            field: The column or band the channel varies with.
            scale: How its values map onto the channel; ``None`` passes them through.
            output_range: ``(low, high)`` for a numeric channel.
            guide: How the channel is explained to the reader — a legend or a colorbar, titled and placed.

        Returns:
            The encoding.

        Raises:
            ValueError: if the channel is undeclared or `field` is empty.

        Examples:
            - Name the column the channel varies with, and read it back:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> enc = Encoding.by_field("color", "landcover")
                >>> enc.field, enc.is_constant
                ('landcover', False)

                ```
            - With a scale and an output range, the values land in the channel's own units:
                ```python
                >>> from digitalearth.base.spec import Encoding, Scale
                >>> enc = Encoding.by_field(
                ...     "size", "magnitude", scale=Scale.from_limits(0.0, 8.0), output_range=(2.0, 18.0)
                ... )
                >>> enc.resolve([0.0, 4.0, 8.0])
                [2.0, 10.0, 18.0]

                ```
        """
        if not field:
            raise ValueError(
                f"an Encoding for {channel!r} needs a field name that is a non-empty string"
            )
        return cls(
            channel=channel,
            field=field,
            scale=scale,
            output_range=output_range,
            guide=guide,
        )

    # ------------------------------------------------------------------ readers

    @property
    def is_constant(self) -> bool:
        """Whether this channel holds one value rather than varying with the data.

        Returns:
            ``True`` for a constant binding — the case a renderer can set once instead of per feature.

        Examples:
            - A constant is set once; a field-driven channel is not:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.constant("opacity", 0.5).is_constant
                True
                >>> Encoding.by_field("opacity", "confidence").is_constant
                False

                ```
            - Which is what lets a renderer take the cheap path when it can:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> enc = Encoding.constant("color", "#333")
                >>> enc.resolve() if enc.is_constant else enc.resolve(["a", "b"])
                '#333'

                ```
        """
        return self.field is None

    def resolve(self, values: Any = None) -> Any:
        """Return what the channel should be, per datum.

        Args:
            values: The field's values, one per feature or cell. Required for a field-driven encoding;
                optional for a constant, where omitting it returns the constant itself rather than a list.

        Returns:
            For a constant with no `values`, the constant. Otherwise one entry per value:

            * no scale — the values unchanged, for a renderer that holds its own mapping
            * a categorical scale — each value's colour, or the scale's missing colour
            * any other scale — the normalised position in ``[0, 1]``, stretched into `output_range` when
                one is set. A classified scale steps: every value in a class resolves to that class's
                position, so the picture matches the legend's swatches.

            A value the scale cannot place — not finite — resolves to ``None``, which is the renderer's cue
            to draw it as missing rather than as some other class.

        Raises:
            ValueError: if the encoding is field-driven and no `values` were given.

        Examples:
            - A constant broadcasts when values are supplied, so one code path serves both bindings:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.constant("opacity", 0.5).resolve([1, 2, 3])
                [0.5, 0.5, 0.5]

                ```
            - A classified scale steps, so the drawn colours match the legend's classes:
                ```python
                >>> from digitalearth.base.spec import Encoding, Scale
                >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
                >>> Encoding.by_field("color", "v", scale=scale).resolve([1.0, 9.0])
                [0.0, 1.0]

                ```
        """
        if self.is_constant:
            return self.value if values is None else [self.value] * len(list(values))
        if values is None:
            raise ValueError(
                f"the {self.channel!r} encoding is driven by field {self.field!r}, so resolve() needs its "
                "values"
            )
        items = list(values)
        if self.scale is None:
            return items
        if self.scale.is_categorical:
            return [self.scale.color_for(item) for item in items]
        return [self._position(self.scale, item) for item in items]

    def _position(self, scale: Scale, value: Any) -> float | None:
        """Place one numeric value on the channel, in ``[0, 1]`` or in `output_range`.

        Args:
            scale: The scale to place against. Passed in rather than read from `self` because the caller has
                already established there is one — taking it as an argument is what makes that a fact here
                rather than a second check that can never fail.
            value: The datum to place.

        Returns:
            Its position, or ``None`` when it is not a finite number the scale can place.
        """
        try:
            number = float(value)
        except (TypeError, ValueError):
            return None
        if not isfinite(number):
            return None
        if scale.is_classified:
            classes = max(len(scale.class_ranges()) - 1, 1)
            # A finite value on a classified scale always places: `class_of` clamps rather than declining,
            # and a Scale cannot hold fewer than two edges. The fallback is for the type, not the data.
            index = scale.class_of(number)
            position = (0 if index is None else index) / classes
        else:
            lo, hi = scale.as_limits()
            position = _clamp_unit((number - lo) / (hi - lo))
        if self.output_range is None:
            return position
        low, high = self.output_range
        return low + position * (high - low)

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            `channel`, plus whichever of `value`, `field`, `scale` and `output_range` is set. The constant and
            `output_range` go through the JSON check, so a tuple is written as a list and a numpy number or string
            as a plain Python one. `channel` and `field` are written as Python strings too.

        Raises:
            TypeError: if the constant, an `output_range` end, or any field of the scale has no JSON form.

        Examples:
            - A constant is its channel and its value:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.constant("opacity", 0.5).to_dict()
                {'channel': 'opacity', 'value': 0.5}

                ```
            - A field-driven channel carries its scale:
                ```python
                >>> from digitalearth.base.spec import Encoding, Scale
                >>> stored = Encoding.by_field("size", "pop", scale=Scale.from_limits(0, 100)).to_dict()
                >>> stored["field"], stored["scale"]
                ('pop', {'vmin': 0.0, 'vmax': 100.0})

                ```
        """
        out: dict[str, Any] = {"channel": plain_text(self.channel)}
        if self.value is not None:
            out["value"] = to_json_value(
                self.value, f"Encoding[{self.channel!r}].value"
            )
        if self.field is not None:
            out["field"] = plain_text(self.field)
        if self.scale is not None:
            out["scale"] = self.scale.to_dict()
        if self.output_range is not None:
            out["output_range"] = to_json_value(
                self.output_range, f"Encoding[{self.channel!r}].output_range"
            )
        if self.guide is not None:
            out["guide"] = self.guide.to_dict()
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Encoding":
        """Rebuild an encoding from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The encoding, validated as the constructor validates it.

        Raises:
            TypeError: if `data` or its `scale` is not a mapping, or `output_range` is not a list — naming the
                field, rather than failing inside `tuple()`.
            ValueError: for a missing channel, an unknown key, a scale `Scale.from_dict` refuses, or a binding the
                constructor refuses. An error of either type from the stored scale names where it sits:
                `Encoding.from_dict scale: Scale.from_dict needs a mapping; got int`.

        Examples:
            - A stored constant reads back and resolves as before:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.from_dict({"channel": "color", "value": "#f00"}).resolve()
                '#f00'

                ```
            - A stored field-driven size reads back with its scale and output range:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> stored = {"channel": "size", "field": "pop", "scale": {"vmin": 0, "vmax": 100}}
                >>> Encoding.from_dict({**stored, "output_range": [4, 20]}).resolve([0.0, 50.0, 100.0])
                [4.0, 12.0, 20.0]

                ```
            - A binding with both a constant and a field is refused:
                ```python
                >>> from digitalearth.base.spec import Encoding
                >>> Encoding.from_dict({"channel": "color", "value": "#f00", "field": "class"})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: an Encoding for 'color' needs exactly one of value= (a constant) or field= ...

                ```
        """
        refuse_unknown(
            "Encoding",
            data,
            ("channel", "value", "field", "scale", "output_range", "guide"),
        )
        scale = data.get("scale")
        output_range = data.get("output_range")
        guide = data.get("guide")
        return cls(
            channel=require("Encoding", data, "channel"),
            value=data.get("value"),
            field=data.get("field"),
            scale=None
            if scale is None
            else read_entry("Encoding", "scale", Scale.from_dict, scale),
            output_range=None
            if output_range is None
            else as_list("Encoding", "output_range", output_range),
            guide=None
            if guide is None
            else read_entry("Encoding", "guide", Guide.from_dict, guide),
        )

is_constant property #

Whether this channel holds one value rather than varying with the data.

Returns:

Type Description
bool

True for a constant binding — the case a renderer can set once instead of per feature.

Examples:

  • A constant is set once; a field-driven channel is not:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.constant("opacity", 0.5).is_constant
    True
    >>> Encoding.by_field("opacity", "confidence").is_constant
    False
    
  • Which is what lets a renderer take the cheap path when it can:
    >>> from digitalearth.base.spec import Encoding
    >>> enc = Encoding.constant("color", "#333")
    >>> enc.resolve() if enc.is_constant else enc.resolve(["a", "b"])
    '#333'
    

__hash__() #

Hash by what drives the channel, with a mapping in the constant hashed as its items.

A frozen dataclass hashes its fields as they are, and value is free-form: a constant that holds a mapping raised unhashable type: 'dict', and took every Symbology and LayerSpec holding it down with it. :meth:~digitalearth.base.spec.style.Symbology.__hash__ had already answered that for its properties, and says a mapping is hashed as its items wherever it sits — the constant beside them is where else it sits (review L5).

Returns:

Type Description
int

A hash over every field, each put through

int

func:~digitalearth.base.spec._serial.hashable_value first. Read from the dataclass's own

int

fields rather than named here, so a channel binding that gains a field is covered by it too.

Raises:

Type Description
TypeError

if a field holds a value that is unhashable for its own reasons. Neither a list, a numpy array nor a mapping is among them: the first two are stored as tuples, and the third is hashed as its items, however deeply it sits.

Examples:

  • A constant bound to a mapping hashes, and two spellings of it hash alike:
    >>> from digitalearth.base.spec import Encoding
    >>> written = Encoding.constant("color", {"high": "#f00", "low": "#00f"})
    >>> rewritten = Encoding.constant("color", {"low": "#00f", "high": "#f00"})
    >>> hash(written) == hash(rewritten), len({written, rewritten})
    (True, 1)
    
Source code in src/digitalearth/base/spec/encoding.py
def __hash__(self) -> int:
    """Hash by what drives the channel, with a mapping in the constant hashed as its items.

    A frozen dataclass hashes its fields as they are, and `value` is free-form: a constant that holds a
    mapping raised `unhashable type: 'dict'`, and took every `Symbology` and `LayerSpec` holding it down
    with it. :meth:`~digitalearth.base.spec.style.Symbology.__hash__` had already answered that for its
    properties, and says a mapping is hashed as its items *wherever it sits* — the constant beside them
    is where else it sits (review L5).

    Returns:
        A hash over every field, each put through
        :func:`~digitalearth.base.spec._serial.hashable_value` first. Read from the dataclass's own
        fields rather than named here, so a channel binding that gains a field is covered by it too.

    Raises:
        TypeError: if a field holds a value that is unhashable for its own reasons. Neither a list, a
            numpy array nor a mapping is among them: the first two are stored as tuples, and the third
            is hashed as its items, however deeply it sits.

    Examples:
        - A constant bound to a mapping hashes, and two spellings of it hash alike:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> written = Encoding.constant("color", {"high": "#f00", "low": "#00f"})
            >>> rewritten = Encoding.constant("color", {"low": "#00f", "high": "#f00"})
            >>> hash(written) == hash(rewritten), len({written, rewritten})
            (True, 1)

            ```
    """
    return hash(
        tuple(hashable_value(getattr(self, field.name)) for field in fields(self))
    )

__post_init__() #

Refuse an encoding that names no channel, or names both a constant and a field.

Raises:

Type Description
ValueError

for an undeclared channel, an ambiguous or empty binding, a field that is not a string, a mapping attached to a constant, or a guide that is not a :class:Guide.

Source code in src/digitalearth/base/spec/encoding.py
def __post_init__(self) -> None:
    """Refuse an encoding that names no channel, or names both a constant and a field.

    Raises:
        ValueError: for an undeclared channel, an ambiguous or empty binding, a field that is not a string, a
            mapping attached to a constant, or a `guide` that is not a :class:`Guide`.
    """
    if self.guide is not None and not isinstance(self.guide, Guide):
        raise ValueError(
            f"Encoding guide must be a Guide or None; got {type(self.guide).__name__}"
        )
    if self.channel not in CHANNELS:
        raise ValueError(
            f"{self.channel!r} is not a visual channel; declared channels are {sorted(CHANNELS)}"
        )
    # A constant is stored canonically — lists as tuples — so an encoding round-trips equal through JSON,
    # which has no tuple, and hashes whichever spelling the caller used.
    object.__setattr__(self, "value", frozen_value(self.value))
    if (self.value is None) == (self.field is None):
        raise ValueError(
            f"an Encoding for {self.channel!r} needs exactly one of value= (a constant) or field= "
            "(driven by the data); a constant of None reads as no binding at all"
        )
    if self.field is not None and (
        not isinstance(self.field, str) or not self.field.strip()
    ):
        # `by_field` refuses an empty name, but the constructor is public too — and an empty field name reports
        # is_constant == False while naming a column nobody can look up. A field that is not a string at all —
        # a datetime, NaN, a number — would be written by `to_dict` as it is, and fail inside `json.dumps`.
        raise ValueError(
            f"an Encoding for {self.channel!r} needs a field name that is a non-empty string; got {self.field!r}"
        )
    self._check_output_range()
    if self.field is None and (
        self.scale is not None or self.output_range is not None
    ):
        raise ValueError(
            f"a constant Encoding for {self.channel!r} cannot carry a scale or an output range; "
            "they only apply to a field"
        )
    if (
        self.output_range is not None
        and self.scale is not None
        and self.scale.is_categorical
    ):
        # A categorical scale resolves to its own colours, so there is no position for a range to
        # stretch. Ignoring the argument returned colours from a channel the caller asked numbers of.
        raise ValueError(
            f"the {self.channel!r} encoding cannot combine a categorical scale with an output range: "
            "a category resolves to its assigned colour, not to a position a range can stretch"
        )

by_field(channel, field, *, scale=None, output_range=None, guide=None) classmethod #

Bind a channel to a data field.

Parameters:

Name Type Description Default
channel str

The channel to drive.

required
field str

The column or band the channel varies with.

required
scale Scale | None

How its values map onto the channel; None passes them through.

None
output_range tuple[float, float] | None

(low, high) for a numeric channel.

None
guide Optional[Guide]

How the channel is explained to the reader — a legend or a colorbar, titled and placed.

None

Returns:

Type Description
Encoding

The encoding.

Raises:

Type Description
ValueError

if the channel is undeclared or field is empty.

Examples:

  • Name the column the channel varies with, and read it back:
    >>> from digitalearth.base.spec import Encoding
    >>> enc = Encoding.by_field("color", "landcover")
    >>> enc.field, enc.is_constant
    ('landcover', False)
    
  • With a scale and an output range, the values land in the channel's own units:
    >>> from digitalearth.base.spec import Encoding, Scale
    >>> enc = Encoding.by_field(
    ...     "size", "magnitude", scale=Scale.from_limits(0.0, 8.0), output_range=(2.0, 18.0)
    ... )
    >>> enc.resolve([0.0, 4.0, 8.0])
    [2.0, 10.0, 18.0]
    
Source code in src/digitalearth/base/spec/encoding.py
@classmethod
def by_field(
    cls,
    channel: str,
    field: str,
    *,
    scale: Scale | None = None,
    output_range: tuple[float, float] | None = None,
    guide: Optional["Guide"] = None,
) -> "Encoding":
    """Bind a channel to a data field.

    Args:
        channel: The channel to drive.
        field: The column or band the channel varies with.
        scale: How its values map onto the channel; ``None`` passes them through.
        output_range: ``(low, high)`` for a numeric channel.
        guide: How the channel is explained to the reader — a legend or a colorbar, titled and placed.

    Returns:
        The encoding.

    Raises:
        ValueError: if the channel is undeclared or `field` is empty.

    Examples:
        - Name the column the channel varies with, and read it back:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> enc = Encoding.by_field("color", "landcover")
            >>> enc.field, enc.is_constant
            ('landcover', False)

            ```
        - With a scale and an output range, the values land in the channel's own units:
            ```python
            >>> from digitalearth.base.spec import Encoding, Scale
            >>> enc = Encoding.by_field(
            ...     "size", "magnitude", scale=Scale.from_limits(0.0, 8.0), output_range=(2.0, 18.0)
            ... )
            >>> enc.resolve([0.0, 4.0, 8.0])
            [2.0, 10.0, 18.0]

            ```
    """
    if not field:
        raise ValueError(
            f"an Encoding for {channel!r} needs a field name that is a non-empty string"
        )
    return cls(
        channel=channel,
        field=field,
        scale=scale,
        output_range=output_range,
        guide=guide,
    )

constant(channel, value, *, guide=None) classmethod #

Bind a channel to one value for every feature.

Parameters:

Name Type Description Default
channel str

The channel to drive.

required
value Any

The constant.

required
guide Optional[Guide]

How the channel is explained to the reader. A constant rarely needs one — there is nothing to read off — but a chosen colour that stands for something does.

None

Returns:

Type Description
Encoding

The encoding.

Raises:

Type Description
ValueError

if the channel is undeclared, or value is None — which would read as "no binding" rather than "this channel is off".

Examples:

  • A constant colour, resolved back out:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.constant("color", "#1e90ff").resolve()
    '#1e90ff'
    
  • Any declared channel works the same way, and knows it does not vary:
    >>> from digitalearth.base.spec import Encoding
    >>> width = Encoding.constant("width", 2.5)
    >>> width.is_constant, width.resolve([1, 2])
    (True, [2.5, 2.5])
    
Source code in src/digitalearth/base/spec/encoding.py
@classmethod
def constant(
    cls, channel: str, value: Any, *, guide: Optional["Guide"] = None
) -> "Encoding":
    """Bind a channel to one value for every feature.

    Args:
        channel: The channel to drive.
        value: The constant.
        guide: How the channel is explained to the reader. A constant rarely needs one — there is nothing to
            read off — but a chosen colour that stands for something does.

    Returns:
        The encoding.

    Raises:
        ValueError: if the channel is undeclared, or `value` is ``None`` — which would read as "no
            binding" rather than "this channel is off".

    Examples:
        - A constant colour, resolved back out:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.constant("color", "#1e90ff").resolve()
            '#1e90ff'

            ```
        - Any declared channel works the same way, and knows it does not vary:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> width = Encoding.constant("width", 2.5)
            >>> width.is_constant, width.resolve([1, 2])
            (True, [2.5, 2.5])

            ```
    """
    return cls(channel=channel, value=value, guide=guide)

from_dict(data) classmethod #

Rebuild an encoding from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Encoding

The encoding, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data or its scale is not a mapping, or output_range is not a list — naming the field, rather than failing inside tuple().

ValueError

for a missing channel, an unknown key, a scale Scale.from_dict refuses, or a binding the constructor refuses. An error of either type from the stored scale names where it sits: Encoding.from_dict scale: Scale.from_dict needs a mapping; got int.

Examples:

  • A stored constant reads back and resolves as before:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.from_dict({"channel": "color", "value": "#f00"}).resolve()
    '#f00'
    
  • A stored field-driven size reads back with its scale and output range:
    >>> from digitalearth.base.spec import Encoding
    >>> stored = {"channel": "size", "field": "pop", "scale": {"vmin": 0, "vmax": 100}}
    >>> Encoding.from_dict({**stored, "output_range": [4, 20]}).resolve([0.0, 50.0, 100.0])
    [4.0, 12.0, 20.0]
    
  • A binding with both a constant and a field is refused:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.from_dict({"channel": "color", "value": "#f00", "field": "class"})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: an Encoding for 'color' needs exactly one of value= (a constant) or field= ...
    
Source code in src/digitalearth/base/spec/encoding.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Encoding":
    """Rebuild an encoding from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The encoding, validated as the constructor validates it.

    Raises:
        TypeError: if `data` or its `scale` is not a mapping, or `output_range` is not a list — naming the
            field, rather than failing inside `tuple()`.
        ValueError: for a missing channel, an unknown key, a scale `Scale.from_dict` refuses, or a binding the
            constructor refuses. An error of either type from the stored scale names where it sits:
            `Encoding.from_dict scale: Scale.from_dict needs a mapping; got int`.

    Examples:
        - A stored constant reads back and resolves as before:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.from_dict({"channel": "color", "value": "#f00"}).resolve()
            '#f00'

            ```
        - A stored field-driven size reads back with its scale and output range:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> stored = {"channel": "size", "field": "pop", "scale": {"vmin": 0, "vmax": 100}}
            >>> Encoding.from_dict({**stored, "output_range": [4, 20]}).resolve([0.0, 50.0, 100.0])
            [4.0, 12.0, 20.0]

            ```
        - A binding with both a constant and a field is refused:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.from_dict({"channel": "color", "value": "#f00", "field": "class"})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: an Encoding for 'color' needs exactly one of value= (a constant) or field= ...

            ```
    """
    refuse_unknown(
        "Encoding",
        data,
        ("channel", "value", "field", "scale", "output_range", "guide"),
    )
    scale = data.get("scale")
    output_range = data.get("output_range")
    guide = data.get("guide")
    return cls(
        channel=require("Encoding", data, "channel"),
        value=data.get("value"),
        field=data.get("field"),
        scale=None
        if scale is None
        else read_entry("Encoding", "scale", Scale.from_dict, scale),
        output_range=None
        if output_range is None
        else as_list("Encoding", "output_range", output_range),
        guide=None
        if guide is None
        else read_entry("Encoding", "guide", Guide.from_dict, guide),
    )

resolve(values=None) #

Return what the channel should be, per datum.

Parameters:

Name Type Description Default
values Any

The field's values, one per feature or cell. Required for a field-driven encoding; optional for a constant, where omitting it returns the constant itself rather than a list.

None

Returns:

Type Description
Any

For a constant with no values, the constant. Otherwise one entry per value:

Any
  • no scale — the values unchanged, for a renderer that holds its own mapping
Any
  • a categorical scale — each value's colour, or the scale's missing colour
Any
  • any other scale — the normalised position in [0, 1], stretched into output_range when one is set. A classified scale steps: every value in a class resolves to that class's position, so the picture matches the legend's swatches.
Any

A value the scale cannot place — not finite — resolves to None, which is the renderer's cue

Any

to draw it as missing rather than as some other class.

Raises:

Type Description
ValueError

if the encoding is field-driven and no values were given.

Examples:

  • A constant broadcasts when values are supplied, so one code path serves both bindings:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.constant("opacity", 0.5).resolve([1, 2, 3])
    [0.5, 0.5, 0.5]
    
  • A classified scale steps, so the drawn colours match the legend's classes:
    >>> from digitalearth.base.spec import Encoding, Scale
    >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
    >>> Encoding.by_field("color", "v", scale=scale).resolve([1.0, 9.0])
    [0.0, 1.0]
    
Source code in src/digitalearth/base/spec/encoding.py
def resolve(self, values: Any = None) -> Any:
    """Return what the channel should be, per datum.

    Args:
        values: The field's values, one per feature or cell. Required for a field-driven encoding;
            optional for a constant, where omitting it returns the constant itself rather than a list.

    Returns:
        For a constant with no `values`, the constant. Otherwise one entry per value:

        * no scale — the values unchanged, for a renderer that holds its own mapping
        * a categorical scale — each value's colour, or the scale's missing colour
        * any other scale — the normalised position in ``[0, 1]``, stretched into `output_range` when
            one is set. A classified scale steps: every value in a class resolves to that class's
            position, so the picture matches the legend's swatches.

        A value the scale cannot place — not finite — resolves to ``None``, which is the renderer's cue
        to draw it as missing rather than as some other class.

    Raises:
        ValueError: if the encoding is field-driven and no `values` were given.

    Examples:
        - A constant broadcasts when values are supplied, so one code path serves both bindings:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.constant("opacity", 0.5).resolve([1, 2, 3])
            [0.5, 0.5, 0.5]

            ```
        - A classified scale steps, so the drawn colours match the legend's classes:
            ```python
            >>> from digitalearth.base.spec import Encoding, Scale
            >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
            >>> Encoding.by_field("color", "v", scale=scale).resolve([1.0, 9.0])
            [0.0, 1.0]

            ```
    """
    if self.is_constant:
        return self.value if values is None else [self.value] * len(list(values))
    if values is None:
        raise ValueError(
            f"the {self.channel!r} encoding is driven by field {self.field!r}, so resolve() needs its "
            "values"
        )
    items = list(values)
    if self.scale is None:
        return items
    if self.scale.is_categorical:
        return [self.scale.color_for(item) for item in items]
    return [self._position(self.scale, item) for item in items]

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

channel, plus whichever of value, field, scale and output_range is set. The constant and

dict[str, Any]

output_range go through the JSON check, so a tuple is written as a list and a numpy number or string

dict[str, Any]

as a plain Python one. channel and field are written as Python strings too.

Raises:

Type Description
TypeError

if the constant, an output_range end, or any field of the scale has no JSON form.

Examples:

  • A constant is its channel and its value:
    >>> from digitalearth.base.spec import Encoding
    >>> Encoding.constant("opacity", 0.5).to_dict()
    {'channel': 'opacity', 'value': 0.5}
    
  • A field-driven channel carries its scale:
    >>> from digitalearth.base.spec import Encoding, Scale
    >>> stored = Encoding.by_field("size", "pop", scale=Scale.from_limits(0, 100)).to_dict()
    >>> stored["field"], stored["scale"]
    ('pop', {'vmin': 0.0, 'vmax': 100.0})
    
Source code in src/digitalearth/base/spec/encoding.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        `channel`, plus whichever of `value`, `field`, `scale` and `output_range` is set. The constant and
        `output_range` go through the JSON check, so a tuple is written as a list and a numpy number or string
        as a plain Python one. `channel` and `field` are written as Python strings too.

    Raises:
        TypeError: if the constant, an `output_range` end, or any field of the scale has no JSON form.

    Examples:
        - A constant is its channel and its value:
            ```python
            >>> from digitalearth.base.spec import Encoding
            >>> Encoding.constant("opacity", 0.5).to_dict()
            {'channel': 'opacity', 'value': 0.5}

            ```
        - A field-driven channel carries its scale:
            ```python
            >>> from digitalearth.base.spec import Encoding, Scale
            >>> stored = Encoding.by_field("size", "pop", scale=Scale.from_limits(0, 100)).to_dict()
            >>> stored["field"], stored["scale"]
            ('pop', {'vmin': 0.0, 'vmax': 100.0})

            ```
    """
    out: dict[str, Any] = {"channel": plain_text(self.channel)}
    if self.value is not None:
        out["value"] = to_json_value(
            self.value, f"Encoding[{self.channel!r}].value"
        )
    if self.field is not None:
        out["field"] = plain_text(self.field)
    if self.scale is not None:
        out["scale"] = self.scale.to_dict()
    if self.output_range is not None:
        out["output_range"] = to_json_value(
            self.output_range, f"Encoding[{self.channel!r}].output_range"
        )
    if self.guide is not None:
        out["guide"] = self.guide.to_dict()
    return out

digitalearth.base.spec.encoding.Channel dataclass #

One visual variable a layer can drive.

Attributes:

Name Type Description
name str

The channel's name, and the key it is stored under.

kind str

What a resolved value is — "color" for a colour or a ramp position, "number" for a magnitude in the channel's own units, "text" for a label. A renderer reads this to know whether to hand the result to a colormap or use it directly.

doc str

One line saying what the channel controls, so the declared vocabulary is self-describing.

Examples:

  • Look a channel up and read what it controls:
    >>> from digitalearth.base.spec import CHANNELS
    >>> CHANNELS["size"].kind
    'number'
    >>> CHANNELS["size"].doc
    'Marker or glyph size, in points.'
    
  • The table is the growth axis, so the channels a feature will need are already in it:
    >>> from digitalearth.base.spec import CHANNELS
    >>> sorted(name for name in CHANNELS if CHANNELS[name].kind == "number")
    ['height', 'opacity', 'rotation', 'size', 'width']
    
Source code in src/digitalearth/base/spec/encoding.py
@dataclass(frozen=True)
class Channel:
    """One visual variable a layer can drive.

    Attributes:
        name: The channel's name, and the key it is stored under.
        kind: What a resolved value *is* — ``"color"`` for a colour or a ramp position, ``"number"`` for a
            magnitude in the channel's own units, ``"text"`` for a label. A renderer reads this to know
            whether to hand the result to a colormap or use it directly.
        doc: One line saying what the channel controls, so the declared vocabulary is self-describing.

    Examples:
        - Look a channel up and read what it controls:
            ```python
            >>> from digitalearth.base.spec import CHANNELS
            >>> CHANNELS["size"].kind
            'number'
            >>> CHANNELS["size"].doc
            'Marker or glyph size, in points.'

            ```
        - The table is the growth axis, so the channels a feature will need are already in it:
            ```python
            >>> from digitalearth.base.spec import CHANNELS
            >>> sorted(name for name in CHANNELS if CHANNELS[name].kind == "number")
            ['height', 'opacity', 'rotation', 'size', 'width']

            ```
    """

    name: str
    kind: str
    doc: str

The declared channels#

CHANNELS is the table a channel is a row in. It is the growth axis the whole type exists for: height and text are already there, ahead of the extrusion and label features that will need them, because adding a channel should cost a row plus a fold rule per backend — not a keyword on every builder on four tiers.

digitalearth.base.spec.style.Symbology dataclass #

The look of one layer: what drives each channel, plus the properties that drive nothing.

Attributes:

Name Type Description
encodings Mapping[str, Encoding]

Channel name -> :class:~digitalearth.base.spec.encoding.Encoding. Each entry is stored under the channel it drives, so a renderer asks by channel rather than searching.

props Mapping[str, Any]

Static style properties that are not visual channels — a contour level list, a hillshade flag, a legend kwargs dict. Declared, unlike the keyword soup they replace, but not resolved per datum. Every list in a value, however nested, is stored as a tuple.

Raises:

Type Description
ValueError

if an encoding is filed under a channel it does not drive. That mismatch would make :meth:encoding answer with something that styles a different channel.

Examples:

  • Constants, which is what plain styling keywords mean:
    >>> from digitalearth.base.spec import Symbology
    >>> sym = Symbology.of(color="#f00", opacity=0.5)
    >>> sym.encoding("color").resolve()
    '#f00'
    
  • Defaults fill the gaps a caller left, and never overwrite what they set:
    >>> from digitalearth.base.spec import Symbology
    >>> caller = Symbology.of(color="#f00")
    >>> theme = Symbology.of(color="#000", opacity=0.8)
    >>> merged = caller.merged_over(theme)
    >>> merged.encoding("color").resolve(), merged.encoding("opacity").resolve()
    ('#f00', 0.8)
    
Source code in src/digitalearth/base/spec/style.py
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
@dataclass(frozen=True)
class Symbology:
    """The look of one layer: what drives each channel, plus the properties that drive nothing.

    Attributes:
        encodings: Channel name -> :class:`~digitalearth.base.spec.encoding.Encoding`. Each entry is stored
            under the channel it drives, so a renderer asks by channel rather than searching.
        props: Static style properties that are not visual channels — a contour level list, a hillshade flag,
            a legend kwargs dict. Declared, unlike the keyword soup they replace, but not resolved per datum. Every
            list in a value, however nested, is stored as a tuple.

    Raises:
        ValueError: if an encoding is filed under a channel it does not drive. That mismatch would make
            :meth:`encoding` answer with something that styles a different channel.

    Examples:
        - Constants, which is what plain styling keywords mean:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> sym = Symbology.of(color="#f00", opacity=0.5)
            >>> sym.encoding("color").resolve()
            '#f00'

            ```
        - Defaults fill the gaps a caller left, and never overwrite what they set:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> caller = Symbology.of(color="#f00")
            >>> theme = Symbology.of(color="#000", opacity=0.8)
            >>> merged = caller.merged_over(theme)
            >>> merged.encoding("color").resolve(), merged.encoding("opacity").resolve()
            ('#f00', 0.8)

            ```
    """

    encodings: Mapping[str, Encoding] = field(default_factory=dict)
    props: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Check every encoding is filed under its own channel, then freeze both mappings.

        The dataclass is frozen, but a plain ``dict`` field is not — a caller holding the dict it passed in
        could still re-key the symbology afterwards. Holding both as a read-only
        :class:`~digitalearth.base.spec._serial.FrozenDict` closes that at the **top level**, and still copies,
        pickles and converts under `dataclasses.asdict`. A mapping stored *inside* a property is a plain dict,
        so a caller who kept a reference to it can still write through it — and, since a property holding a
        mapping is hashed (review L5/N1), change this symbology's hash under whoever is holding it.

        Property values are stored in their canonical form: every list and tuple in them, however nested,
        becomes a tuple (see :func:`~digitalearth.base.spec._serial.frozen_value`). That copies a caller's list —
        appending to it afterwards no longer changes the symbology — and it is what lets a symbology written with
        `to_dict`, where tuples become JSON lists, read back equal and hashable. A numpy array is stored as nested
        tuples too, and a dict is rebuilt with each of its values frozen the same way — so the mapping stored is
        never the mapping passed. Any other value, a custom object say, is held as given.

        Raises:
            ValueError: if a key does not match its encoding's channel.
        """
        for key, encoding in dict(self.encodings).items():
            if encoding.channel != key:
                raise ValueError(
                    f"encoding filed under {key!r} drives channel {encoding.channel!r}; "
                    "a Symbology stores each encoding under the channel it drives"
                )
        object.__setattr__(self, "encodings", FrozenDict(dict(self.encodings)))
        object.__setattr__(
            self,
            "props",
            FrozenDict(
                {key: frozen_value(value) for key, value in dict(self.props).items()}
            ),
        )

    def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
        """Pickle and copy by rebuilding through the constructor.

        Returns:
            ``(type(self), (dict(encodings), dict(props)))`` — the caller's subclass, not `Symbology` by name.

            Rebuilding from plain dicts goes through the same validation and freezing as any other construction.

        Examples:
            - A copy is equal to the original, and is a separate object:
                ```python
                >>> import copy
                >>> from digitalearth.base.spec import Symbology
                >>> original = Symbology.of(color="#f00").with_props(levels=(1, 2))
                >>> clone = copy.deepcopy(original)
                >>> clone == original, clone is original
                (True, False)

                ```
        """
        return type(self), (dict(self.encodings), dict(self.props))

    def __hash__(self) -> int:
        """Hash by the channels driven and the properties set, so a style can key a cache.

        Returns:
            A hash over the encodings and the properties. `Bounds`, `Scale`, `Selection` and `Encoding` all
            hash; a symbology that did not would be the odd one out the moment the data tier wants to key a set
            or a cache on a layer's style.

        Raises:
            TypeError: if any value in it is itself unhashable — and that alone. Neither a list nor a dict is
                among them: a list is stored as a tuple, so ``Symbology.of(color=[1, 0, 0])`` hashes, and a
                mapping is hashed as its items in key order wherever it sits — which is what every tier
                needs, since each records one (MapLibre's ``paint``, the resolved HoloViews style, a tile
                preset). The mapping's *keys* need not compare with each other either: ordering them by
                `repr` where they do not is what keeps the sort from raising where the values are fine
                (review L6). Nor is a numpy array unhashable here, being stored as nested tuples of its
                elements.
        """
        return hash(
            (
                tuple(sorted(self.encodings.items(), key=lambda item: item[0])),
                hashable_value(dict(self.props)),
            )
        )

    # ------------------------------------------------------------------ builders

    @classmethod
    def of(cls, **channels: Any) -> "Symbology":
        """Build a symbology from constant channel values — the common, simple case.

        Args:
            **channels: Channel name -> constant, or an already-built
                :class:`~digitalearth.base.spec.encoding.Encoding` to use as is.

        Returns:
            The symbology.

        Raises:
            ValueError: if a name is not a declared channel.

        Examples:
            - A constant and a field-driven encoding side by side:
                ```python
                >>> from digitalearth.base.spec import Encoding, Symbology
                >>> sym = Symbology.of(opacity=0.5, color=Encoding.by_field("color", "class"))
                >>> sorted(sym.encodings)
                ['color', 'opacity']

                ```
        """
        encodings = {
            name: value
            if isinstance(value, Encoding)
            else Encoding.constant(name, value)
            for name, value in channels.items()
        }
        return cls(encodings=encodings)

    # ------------------------------------------------------------------ readers

    def encoding(self, channel: str) -> Encoding | None:
        """Return what drives one channel.

        Args:
            channel: The channel to look up.

        Returns:
            Its encoding, or ``None`` when the layer does not style that channel — which is the renderer's
            cue to use its own default rather than to raise.

        Examples:
            - Ask what drives a channel, then resolve it:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology.of(color="#f00").encoding("color").resolve()
                '#f00'

                ```
            - An unstyled channel answers ``None``, so the renderer keeps its own default:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology.of(color="#f00").encoding("width") is None
                True

                ```
        """
        return self.encodings.get(channel)

    def guide(self, channel: str = "color") -> Guide | None:
        """Return what explains one channel to the reader — the legend or colorbar asked for on it.

        The read side of :meth:`with_guide`, and the reason a guide lives on the encoding rather than beside
        it: a renderer asking "does this layer want a colour key, and what is it called?" asks the layer, so
        the answer moves, hides and disappears with it (DE-48, order 24).

        Args:
            channel: The channel whose guide is wanted. Defaults to ``"color"``, which is the channel a
                colorbar and a keyed legend both explain — the other channels have guides too, and none of
                them has a default worth guessing.

        Returns:
            The :class:`~digitalearth.base.spec.encoding.Guide` on that channel's encoding, or ``None`` —
            both when nothing drives the channel and when something does and nobody asked for a guide.
            The two are one answer on purpose: a renderer's question is whether to draw a key, and there is
            nothing to draw in either case.

        Examples:
            - A guide asked for on a channel is read back from it:
                ```python
                >>> from digitalearth.base.spec import Encoding, Guide, Symbology
                >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
                >>> sym.with_guide(Guide(title="Elevation (m)")).guide().title
                'Elevation (m)'

                ```
            - A channel nobody asked a guide of, and a channel nothing drives, both answer ``None``:
                ```python
                >>> from digitalearth.base.spec import Encoding, Symbology
                >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
                >>> sym.guide() is None, sym.guide("size") is None
                (True, True)

                ```
        """
        encoding = self.encodings.get(channel)
        return None if encoding is None else encoding.guide

    def merged_over(self, defaults: "Symbology") -> "Symbology":
        """Return this symbology laid over `defaults`, channel by channel and property by property.

        Args:
            defaults: The symbology to fall back to — a theme, a layer-kind default, a figure-wide style.

        Returns:
            A new symbology where this one wins every key it sets and `defaults` supplies the rest. Merging
            per key rather than per object is the point: a caller who names one colour must not lose the
            theme's opacity.

        Examples:
            - The caller's channel wins; the default's survives where the caller was silent:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology.of(color="#f00").merged_over(Symbology.of(size=6)).encoding("size").resolve()
                6

                ```
        """
        encodings = dict(defaults.encodings)
        encodings.update(self.encodings)
        props = dict(defaults.props)
        props.update(self.props)
        return Symbology(encodings=encodings, props=props)

    def with_props(self, **props: Any) -> "Symbology":
        """Return a copy carrying extra static properties.

        Args:
            **props: The properties to add or replace.

        Returns:
            A new symbology; this one is unchanged.

        Examples:
            - Properties accumulate, and the original is untouched:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> one = Symbology().with_props(scheme="quantiles")
                >>> both = one.with_props(k=7)
                >>> sorted(both.props), sorted(one.props)
                (['k', 'scheme'], ['scheme'])

                ```
            - Naming a property again replaces it:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology().with_props(k=5).with_props(k=9).props["k"]
                9

                ```
        """
        merged = dict(self.props)
        merged.update(props)
        return Symbology(encodings=dict(self.encodings), props=merged)

    def with_guide(self, guide: Guide | None, *, channel: str = "color") -> "Symbology":
        """Return a copy whose `channel` encoding carries `guide`.

        **A guide explains an encoding**, so it is attached to one rather than held beside it. That is the
        whole of what order 24 changes: a colour key used to be figure decoration a tier drew when asked and
        then forgot — keyed by position on the static tier, a `show=` toggle on the most recent layer on the
        interactive one — so it could not move with its layer, could not go away with it, and could not be
        written into a figure and read back. Attached here it does all three for free, because the layer's
        `Symbology` is already what travels.

        Args:
            guide: What to say about the channel, or ``None`` to attach nothing — which is how a guide is
                taken off again, and why this does not raise for it: a channel nothing drives carries no
                guide, so asking for the one there to come off is already true.
            channel: The channel being explained. Defaults to ``"color"``.

        Returns:
            A new symbology; this one is unchanged, as every `Symbology` writer here is. For ``None`` on a
            channel nothing drives, an equal one — the detach is a no-op rather than a refusal.

        Raises:
            ValueError: when nothing drives `channel` **and** a guide is being attached to it. A key over a
                colour nothing varies would have no values to label and no scale to sample, so the tiers
                raise rather than draw an empty box — the message names the channels that *are* driven,
                since the usual cause is asking for a key on a layer whose colour is one flat constant.

        Examples:
            - Attached to the colour a field drives, and read back off the layer:
                ```python
                >>> from digitalearth.base.spec import Encoding, Guide, Symbology
                >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
                >>> sym.with_guide(Guide(title="People", anchor="bottom-right")).guide().anchor
                'bottom-right'

                ```
            - ``None`` takes it off again, so a caller does not have to rebuild the encoding to drop a key:
                ```python
                >>> from digitalearth.base.spec import Encoding, Guide, Symbology
                >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
                >>> sym.with_guide(Guide(title="People")).with_guide(None).guide() is None
                True

                ```
            - A channel nothing drives is refused, and the message says what the layer does drive:
                ```python
                >>> from digitalearth.base.spec import Encoding, Guide, Symbology
                >>> Symbology.of(size=6).with_guide(Guide())  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: nothing drives the 'color' channel ...; the channels it does drive are ['size']

                ```
            - Taking a guide off that same channel is not, because there is none there to refuse:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> flat = Symbology.of(size=6)
                >>> flat.with_guide(None) == flat
                True

                ```
        """
        encoding = self.encodings.get(channel)
        if encoding is None:
            if guide is None:
                # Detaching what is not there is not an error. The refusal below is about the *guide* — it
                # would have no values to label and no scale to sample — and so has nothing to say when
                # there is no guide to attach; applied to `None` as well it refused the one call that
                # cannot go wrong, and contradicted this method's own `Args` entry (review L1).
                return Symbology(encodings=dict(self.encodings), props=dict(self.props))
            raise ValueError(
                f"nothing drives the {channel!r} channel of this layer, so there is no encoding for a "
                f"guide to explain; the channels it does drive are {sorted(self.encodings)}"
            )
        encodings = dict(self.encodings)
        encodings[channel] = with_fields(encoding, guide=guide)
        return Symbology(encodings=encodings, props=dict(self.props))

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``encodings`` (channel -> encoding dict) and ``props``, each omitted when empty — so a layer with no
            styling stores an empty dict.

        Raises:
            TypeError: if a property, an encoding's constant, or the scheme or a category of an encoding's scale
                has no JSON form.

        Examples:
            - Encodings are stored under the channel they drive:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology.of(color="#f00").to_dict()
                {'encodings': {'color': {'channel': 'color', 'value': '#f00'}}}

                ```
            - No styling at all is an empty dict:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> Symbology().to_dict()
                {}

                ```
        """
        out: dict[str, Any] = {}
        if self.encodings:
            out["encodings"] = {
                plain_text(channel): encoding.to_dict()
                for channel, encoding in self.encodings.items()
            }
        if self.props:
            out["props"] = to_json_value(dict(self.props), "Symbology.props")
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Symbology":
        """Rebuild a symbology from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The symbology, with every encoding checked against the channel it is filed under.

        Raises:
            TypeError: if `data`, `encodings`, `props` or a stored encoding is not a mapping, naming the field.
            ValueError: for an unknown key, an encoding `Encoding.from_dict` refuses — an undeclared channel, say —
                or an encoding filed under a channel it does not drive. An error of either type from a stored
                encoding names where it sits:
                `Symbology.from_dict encodings['color']: Encoding.from_dict needs a mapping; got int`. The
                misfiled-channel refusal comes from the constructor, and carries no path.

        Examples:
            - A stored style reads back channel by channel:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> stored = {"encodings": {"opacity": {"channel": "opacity", "value": 0.4}}, "props": {"k": 5}}
                >>> sym = Symbology.from_dict(stored)
                >>> sym.encoding("opacity").resolve(), sym.props["k"]
                (0.4, 5)

                ```
            - An encoding filed under a channel it does not drive is refused:
                ```python
                >>> from digitalearth.base.spec import Symbology
                >>> misfiled = {"encodings": {"color": {"channel": "opacity", "value": 0.4}}}
                >>> Symbology.from_dict(misfiled)  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: encoding filed under 'color' drives channel 'opacity'; ...

                ```
        """
        refuse_unknown("Symbology", data, ("encodings", "props"))
        return cls(
            encodings={
                channel: read_entry(
                    "Symbology", f"encodings[{channel!r}]", Encoding.from_dict, encoding
                )
                for channel, encoding in as_mapping(
                    "Symbology", "encodings", data.get("encodings", {})
                ).items()
            },
            props=as_mapping("Symbology", "props", data.get("props", {})),
        )

__hash__() #

Hash by the channels driven and the properties set, so a style can key a cache.

Returns:

Type Description
int

A hash over the encodings and the properties. Bounds, Scale, Selection and Encoding all

int

hash; a symbology that did not would be the odd one out the moment the data tier wants to key a set

int

or a cache on a layer's style.

Raises:

Type Description
TypeError

if any value in it is itself unhashable — and that alone. Neither a list nor a dict is among them: a list is stored as a tuple, so Symbology.of(color=[1, 0, 0]) hashes, and a mapping is hashed as its items in key order wherever it sits — which is what every tier needs, since each records one (MapLibre's paint, the resolved HoloViews style, a tile preset). The mapping's keys need not compare with each other either: ordering them by repr where they do not is what keeps the sort from raising where the values are fine (review L6). Nor is a numpy array unhashable here, being stored as nested tuples of its elements.

Source code in src/digitalearth/base/spec/style.py
def __hash__(self) -> int:
    """Hash by the channels driven and the properties set, so a style can key a cache.

    Returns:
        A hash over the encodings and the properties. `Bounds`, `Scale`, `Selection` and `Encoding` all
        hash; a symbology that did not would be the odd one out the moment the data tier wants to key a set
        or a cache on a layer's style.

    Raises:
        TypeError: if any value in it is itself unhashable — and that alone. Neither a list nor a dict is
            among them: a list is stored as a tuple, so ``Symbology.of(color=[1, 0, 0])`` hashes, and a
            mapping is hashed as its items in key order wherever it sits — which is what every tier
            needs, since each records one (MapLibre's ``paint``, the resolved HoloViews style, a tile
            preset). The mapping's *keys* need not compare with each other either: ordering them by
            `repr` where they do not is what keeps the sort from raising where the values are fine
            (review L6). Nor is a numpy array unhashable here, being stored as nested tuples of its
            elements.
    """
    return hash(
        (
            tuple(sorted(self.encodings.items(), key=lambda item: item[0])),
            hashable_value(dict(self.props)),
        )
    )

__post_init__() #

Check every encoding is filed under its own channel, then freeze both mappings.

The dataclass is frozen, but a plain dict field is not — a caller holding the dict it passed in could still re-key the symbology afterwards. Holding both as a read-only :class:~digitalearth.base.spec._serial.FrozenDict closes that at the top level, and still copies, pickles and converts under dataclasses.asdict. A mapping stored inside a property is a plain dict, so a caller who kept a reference to it can still write through it — and, since a property holding a mapping is hashed (review L5/N1), change this symbology's hash under whoever is holding it.

Property values are stored in their canonical form: every list and tuple in them, however nested, becomes a tuple (see :func:~digitalearth.base.spec._serial.frozen_value). That copies a caller's list — appending to it afterwards no longer changes the symbology — and it is what lets a symbology written with to_dict, where tuples become JSON lists, read back equal and hashable. A numpy array is stored as nested tuples too, and a dict is rebuilt with each of its values frozen the same way — so the mapping stored is never the mapping passed. Any other value, a custom object say, is held as given.

Raises:

Type Description
ValueError

if a key does not match its encoding's channel.

Source code in src/digitalearth/base/spec/style.py
def __post_init__(self) -> None:
    """Check every encoding is filed under its own channel, then freeze both mappings.

    The dataclass is frozen, but a plain ``dict`` field is not — a caller holding the dict it passed in
    could still re-key the symbology afterwards. Holding both as a read-only
    :class:`~digitalearth.base.spec._serial.FrozenDict` closes that at the **top level**, and still copies,
    pickles and converts under `dataclasses.asdict`. A mapping stored *inside* a property is a plain dict,
    so a caller who kept a reference to it can still write through it — and, since a property holding a
    mapping is hashed (review L5/N1), change this symbology's hash under whoever is holding it.

    Property values are stored in their canonical form: every list and tuple in them, however nested,
    becomes a tuple (see :func:`~digitalearth.base.spec._serial.frozen_value`). That copies a caller's list —
    appending to it afterwards no longer changes the symbology — and it is what lets a symbology written with
    `to_dict`, where tuples become JSON lists, read back equal and hashable. A numpy array is stored as nested
    tuples too, and a dict is rebuilt with each of its values frozen the same way — so the mapping stored is
    never the mapping passed. Any other value, a custom object say, is held as given.

    Raises:
        ValueError: if a key does not match its encoding's channel.
    """
    for key, encoding in dict(self.encodings).items():
        if encoding.channel != key:
            raise ValueError(
                f"encoding filed under {key!r} drives channel {encoding.channel!r}; "
                "a Symbology stores each encoding under the channel it drives"
            )
    object.__setattr__(self, "encodings", FrozenDict(dict(self.encodings)))
    object.__setattr__(
        self,
        "props",
        FrozenDict(
            {key: frozen_value(value) for key, value in dict(self.props).items()}
        ),
    )

__reduce__() #

Pickle and copy by rebuilding through the constructor.

Returns:

Type Description
Any

(type(self), (dict(encodings), dict(props))) — the caller's subclass, not Symbology by name.

tuple[Any, ...]

Rebuilding from plain dicts goes through the same validation and freezing as any other construction.

Examples:

  • A copy is equal to the original, and is a separate object:
    >>> import copy
    >>> from digitalearth.base.spec import Symbology
    >>> original = Symbology.of(color="#f00").with_props(levels=(1, 2))
    >>> clone = copy.deepcopy(original)
    >>> clone == original, clone is original
    (True, False)
    
Source code in src/digitalearth/base/spec/style.py
def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
    """Pickle and copy by rebuilding through the constructor.

    Returns:
        ``(type(self), (dict(encodings), dict(props)))`` — the caller's subclass, not `Symbology` by name.

        Rebuilding from plain dicts goes through the same validation and freezing as any other construction.

    Examples:
        - A copy is equal to the original, and is a separate object:
            ```python
            >>> import copy
            >>> from digitalearth.base.spec import Symbology
            >>> original = Symbology.of(color="#f00").with_props(levels=(1, 2))
            >>> clone = copy.deepcopy(original)
            >>> clone == original, clone is original
            (True, False)

            ```
    """
    return type(self), (dict(self.encodings), dict(self.props))

encoding(channel) #

Return what drives one channel.

Parameters:

Name Type Description Default
channel str

The channel to look up.

required

Returns:

Type Description
Encoding | None

Its encoding, or None when the layer does not style that channel — which is the renderer's

Encoding | None

cue to use its own default rather than to raise.

Examples:

  • Ask what drives a channel, then resolve it:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology.of(color="#f00").encoding("color").resolve()
    '#f00'
    
  • An unstyled channel answers None, so the renderer keeps its own default:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology.of(color="#f00").encoding("width") is None
    True
    
Source code in src/digitalearth/base/spec/style.py
def encoding(self, channel: str) -> Encoding | None:
    """Return what drives one channel.

    Args:
        channel: The channel to look up.

    Returns:
        Its encoding, or ``None`` when the layer does not style that channel — which is the renderer's
        cue to use its own default rather than to raise.

    Examples:
        - Ask what drives a channel, then resolve it:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology.of(color="#f00").encoding("color").resolve()
            '#f00'

            ```
        - An unstyled channel answers ``None``, so the renderer keeps its own default:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology.of(color="#f00").encoding("width") is None
            True

            ```
    """
    return self.encodings.get(channel)

from_dict(data) classmethod #

Rebuild a symbology from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Symbology

The symbology, with every encoding checked against the channel it is filed under.

Raises:

Type Description
TypeError

if data, encodings, props or a stored encoding is not a mapping, naming the field.

ValueError

for an unknown key, an encoding Encoding.from_dict refuses — an undeclared channel, say — or an encoding filed under a channel it does not drive. An error of either type from a stored encoding names where it sits: Symbology.from_dict encodings['color']: Encoding.from_dict needs a mapping; got int. The misfiled-channel refusal comes from the constructor, and carries no path.

Examples:

  • A stored style reads back channel by channel:
    >>> from digitalearth.base.spec import Symbology
    >>> stored = {"encodings": {"opacity": {"channel": "opacity", "value": 0.4}}, "props": {"k": 5}}
    >>> sym = Symbology.from_dict(stored)
    >>> sym.encoding("opacity").resolve(), sym.props["k"]
    (0.4, 5)
    
  • An encoding filed under a channel it does not drive is refused:
    >>> from digitalearth.base.spec import Symbology
    >>> misfiled = {"encodings": {"color": {"channel": "opacity", "value": 0.4}}}
    >>> Symbology.from_dict(misfiled)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: encoding filed under 'color' drives channel 'opacity'; ...
    
Source code in src/digitalearth/base/spec/style.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Symbology":
    """Rebuild a symbology from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The symbology, with every encoding checked against the channel it is filed under.

    Raises:
        TypeError: if `data`, `encodings`, `props` or a stored encoding is not a mapping, naming the field.
        ValueError: for an unknown key, an encoding `Encoding.from_dict` refuses — an undeclared channel, say —
            or an encoding filed under a channel it does not drive. An error of either type from a stored
            encoding names where it sits:
            `Symbology.from_dict encodings['color']: Encoding.from_dict needs a mapping; got int`. The
            misfiled-channel refusal comes from the constructor, and carries no path.

    Examples:
        - A stored style reads back channel by channel:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> stored = {"encodings": {"opacity": {"channel": "opacity", "value": 0.4}}, "props": {"k": 5}}
            >>> sym = Symbology.from_dict(stored)
            >>> sym.encoding("opacity").resolve(), sym.props["k"]
            (0.4, 5)

            ```
        - An encoding filed under a channel it does not drive is refused:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> misfiled = {"encodings": {"color": {"channel": "opacity", "value": 0.4}}}
            >>> Symbology.from_dict(misfiled)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: encoding filed under 'color' drives channel 'opacity'; ...

            ```
    """
    refuse_unknown("Symbology", data, ("encodings", "props"))
    return cls(
        encodings={
            channel: read_entry(
                "Symbology", f"encodings[{channel!r}]", Encoding.from_dict, encoding
            )
            for channel, encoding in as_mapping(
                "Symbology", "encodings", data.get("encodings", {})
            ).items()
        },
        props=as_mapping("Symbology", "props", data.get("props", {})),
    )

guide(channel='color') #

Return what explains one channel to the reader — the legend or colorbar asked for on it.

The read side of :meth:with_guide, and the reason a guide lives on the encoding rather than beside it: a renderer asking "does this layer want a colour key, and what is it called?" asks the layer, so the answer moves, hides and disappears with it (DE-48, order 24).

Parameters:

Name Type Description Default
channel str

The channel whose guide is wanted. Defaults to "color", which is the channel a colorbar and a keyed legend both explain — the other channels have guides too, and none of them has a default worth guessing.

'color'

Returns:

Name Type Description
The Guide | None

class:~digitalearth.base.spec.encoding.Guide on that channel's encoding, or None —

Guide | None

both when nothing drives the channel and when something does and nobody asked for a guide.

Guide | None

The two are one answer on purpose: a renderer's question is whether to draw a key, and there is

Guide | None

nothing to draw in either case.

Examples:

  • A guide asked for on a channel is read back from it:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
    >>> sym.with_guide(Guide(title="Elevation (m)")).guide().title
    'Elevation (m)'
    
  • A channel nobody asked a guide of, and a channel nothing drives, both answer None:
    >>> from digitalearth.base.spec import Encoding, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
    >>> sym.guide() is None, sym.guide("size") is None
    (True, True)
    
Source code in src/digitalearth/base/spec/style.py
def guide(self, channel: str = "color") -> Guide | None:
    """Return what explains one channel to the reader — the legend or colorbar asked for on it.

    The read side of :meth:`with_guide`, and the reason a guide lives on the encoding rather than beside
    it: a renderer asking "does this layer want a colour key, and what is it called?" asks the layer, so
    the answer moves, hides and disappears with it (DE-48, order 24).

    Args:
        channel: The channel whose guide is wanted. Defaults to ``"color"``, which is the channel a
            colorbar and a keyed legend both explain — the other channels have guides too, and none of
            them has a default worth guessing.

    Returns:
        The :class:`~digitalearth.base.spec.encoding.Guide` on that channel's encoding, or ``None`` —
        both when nothing drives the channel and when something does and nobody asked for a guide.
        The two are one answer on purpose: a renderer's question is whether to draw a key, and there is
        nothing to draw in either case.

    Examples:
        - A guide asked for on a channel is read back from it:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
            >>> sym.with_guide(Guide(title="Elevation (m)")).guide().title
            'Elevation (m)'

            ```
        - A channel nobody asked a guide of, and a channel nothing drives, both answer ``None``:
            ```python
            >>> from digitalearth.base.spec import Encoding, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
            >>> sym.guide() is None, sym.guide("size") is None
            (True, True)

            ```
    """
    encoding = self.encodings.get(channel)
    return None if encoding is None else encoding.guide

merged_over(defaults) #

Return this symbology laid over defaults, channel by channel and property by property.

Parameters:

Name Type Description Default
defaults Symbology

The symbology to fall back to — a theme, a layer-kind default, a figure-wide style.

required

Returns:

Type Description
Symbology

A new symbology where this one wins every key it sets and defaults supplies the rest. Merging

Symbology

per key rather than per object is the point: a caller who names one colour must not lose the

Symbology

theme's opacity.

Examples:

  • The caller's channel wins; the default's survives where the caller was silent:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology.of(color="#f00").merged_over(Symbology.of(size=6)).encoding("size").resolve()
    6
    
Source code in src/digitalearth/base/spec/style.py
def merged_over(self, defaults: "Symbology") -> "Symbology":
    """Return this symbology laid over `defaults`, channel by channel and property by property.

    Args:
        defaults: The symbology to fall back to — a theme, a layer-kind default, a figure-wide style.

    Returns:
        A new symbology where this one wins every key it sets and `defaults` supplies the rest. Merging
        per key rather than per object is the point: a caller who names one colour must not lose the
        theme's opacity.

    Examples:
        - The caller's channel wins; the default's survives where the caller was silent:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology.of(color="#f00").merged_over(Symbology.of(size=6)).encoding("size").resolve()
            6

            ```
    """
    encodings = dict(defaults.encodings)
    encodings.update(self.encodings)
    props = dict(defaults.props)
    props.update(self.props)
    return Symbology(encodings=encodings, props=props)

of(**channels) classmethod #

Build a symbology from constant channel values — the common, simple case.

Parameters:

Name Type Description Default
**channels Any

Channel name -> constant, or an already-built :class:~digitalearth.base.spec.encoding.Encoding to use as is.

{}

Returns:

Type Description
Symbology

The symbology.

Raises:

Type Description
ValueError

if a name is not a declared channel.

Examples:

  • A constant and a field-driven encoding side by side:
    >>> from digitalearth.base.spec import Encoding, Symbology
    >>> sym = Symbology.of(opacity=0.5, color=Encoding.by_field("color", "class"))
    >>> sorted(sym.encodings)
    ['color', 'opacity']
    
Source code in src/digitalearth/base/spec/style.py
@classmethod
def of(cls, **channels: Any) -> "Symbology":
    """Build a symbology from constant channel values — the common, simple case.

    Args:
        **channels: Channel name -> constant, or an already-built
            :class:`~digitalearth.base.spec.encoding.Encoding` to use as is.

    Returns:
        The symbology.

    Raises:
        ValueError: if a name is not a declared channel.

    Examples:
        - A constant and a field-driven encoding side by side:
            ```python
            >>> from digitalearth.base.spec import Encoding, Symbology
            >>> sym = Symbology.of(opacity=0.5, color=Encoding.by_field("color", "class"))
            >>> sorted(sym.encodings)
            ['color', 'opacity']

            ```
    """
    encodings = {
        name: value
        if isinstance(value, Encoding)
        else Encoding.constant(name, value)
        for name, value in channels.items()
    }
    return cls(encodings=encodings)

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

encodings (channel -> encoding dict) and props, each omitted when empty — so a layer with no

dict[str, Any]

styling stores an empty dict.

Raises:

Type Description
TypeError

if a property, an encoding's constant, or the scheme or a category of an encoding's scale has no JSON form.

Examples:

  • Encodings are stored under the channel they drive:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology.of(color="#f00").to_dict()
    {'encodings': {'color': {'channel': 'color', 'value': '#f00'}}}
    
  • No styling at all is an empty dict:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology().to_dict()
    {}
    
Source code in src/digitalearth/base/spec/style.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``encodings`` (channel -> encoding dict) and ``props``, each omitted when empty — so a layer with no
        styling stores an empty dict.

    Raises:
        TypeError: if a property, an encoding's constant, or the scheme or a category of an encoding's scale
            has no JSON form.

    Examples:
        - Encodings are stored under the channel they drive:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology.of(color="#f00").to_dict()
            {'encodings': {'color': {'channel': 'color', 'value': '#f00'}}}

            ```
        - No styling at all is an empty dict:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology().to_dict()
            {}

            ```
    """
    out: dict[str, Any] = {}
    if self.encodings:
        out["encodings"] = {
            plain_text(channel): encoding.to_dict()
            for channel, encoding in self.encodings.items()
        }
    if self.props:
        out["props"] = to_json_value(dict(self.props), "Symbology.props")
    return out

with_guide(guide, *, channel='color') #

Return a copy whose channel encoding carries guide.

A guide explains an encoding, so it is attached to one rather than held beside it. That is the whole of what order 24 changes: a colour key used to be figure decoration a tier drew when asked and then forgot — keyed by position on the static tier, a show= toggle on the most recent layer on the interactive one — so it could not move with its layer, could not go away with it, and could not be written into a figure and read back. Attached here it does all three for free, because the layer's Symbology is already what travels.

Parameters:

Name Type Description Default
guide Guide | None

What to say about the channel, or None to attach nothing — which is how a guide is taken off again, and why this does not raise for it: a channel nothing drives carries no guide, so asking for the one there to come off is already true.

required
channel str

The channel being explained. Defaults to "color".

'color'

Returns:

Type Description
Symbology

A new symbology; this one is unchanged, as every Symbology writer here is. For None on a

Symbology

channel nothing drives, an equal one — the detach is a no-op rather than a refusal.

Raises:

Type Description
ValueError

when nothing drives channel and a guide is being attached to it. A key over a colour nothing varies would have no values to label and no scale to sample, so the tiers raise rather than draw an empty box — the message names the channels that are driven, since the usual cause is asking for a key on a layer whose colour is one flat constant.

Examples:

  • Attached to the colour a field drives, and read back off the layer:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
    >>> sym.with_guide(Guide(title="People", anchor="bottom-right")).guide().anchor
    'bottom-right'
    
  • None takes it off again, so a caller does not have to rebuild the encoding to drop a key:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
    >>> sym.with_guide(Guide(title="People")).with_guide(None).guide() is None
    True
    
  • A channel nothing drives is refused, and the message says what the layer does drive:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> Symbology.of(size=6).with_guide(Guide())  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: nothing drives the 'color' channel ...; the channels it does drive are ['size']
    
  • Taking a guide off that same channel is not, because there is none there to refuse:
    >>> from digitalearth.base.spec import Symbology
    >>> flat = Symbology.of(size=6)
    >>> flat.with_guide(None) == flat
    True
    
Source code in src/digitalearth/base/spec/style.py
def with_guide(self, guide: Guide | None, *, channel: str = "color") -> "Symbology":
    """Return a copy whose `channel` encoding carries `guide`.

    **A guide explains an encoding**, so it is attached to one rather than held beside it. That is the
    whole of what order 24 changes: a colour key used to be figure decoration a tier drew when asked and
    then forgot — keyed by position on the static tier, a `show=` toggle on the most recent layer on the
    interactive one — so it could not move with its layer, could not go away with it, and could not be
    written into a figure and read back. Attached here it does all three for free, because the layer's
    `Symbology` is already what travels.

    Args:
        guide: What to say about the channel, or ``None`` to attach nothing — which is how a guide is
            taken off again, and why this does not raise for it: a channel nothing drives carries no
            guide, so asking for the one there to come off is already true.
        channel: The channel being explained. Defaults to ``"color"``.

    Returns:
        A new symbology; this one is unchanged, as every `Symbology` writer here is. For ``None`` on a
        channel nothing drives, an equal one — the detach is a no-op rather than a refusal.

    Raises:
        ValueError: when nothing drives `channel` **and** a guide is being attached to it. A key over a
            colour nothing varies would have no values to label and no scale to sample, so the tiers
            raise rather than draw an empty box — the message names the channels that *are* driven,
            since the usual cause is asking for a key on a layer whose colour is one flat constant.

    Examples:
        - Attached to the colour a field drives, and read back off the layer:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
            >>> sym.with_guide(Guide(title="People", anchor="bottom-right")).guide().anchor
            'bottom-right'

            ```
        - ``None`` takes it off again, so a caller does not have to rebuild the encoding to drop a key:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
            >>> sym.with_guide(Guide(title="People")).with_guide(None).guide() is None
            True

            ```
        - A channel nothing drives is refused, and the message says what the layer does drive:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> Symbology.of(size=6).with_guide(Guide())  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: nothing drives the 'color' channel ...; the channels it does drive are ['size']

            ```
        - Taking a guide off that same channel is not, because there is none there to refuse:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> flat = Symbology.of(size=6)
            >>> flat.with_guide(None) == flat
            True

            ```
    """
    encoding = self.encodings.get(channel)
    if encoding is None:
        if guide is None:
            # Detaching what is not there is not an error. The refusal below is about the *guide* — it
            # would have no values to label and no scale to sample — and so has nothing to say when
            # there is no guide to attach; applied to `None` as well it refused the one call that
            # cannot go wrong, and contradicted this method's own `Args` entry (review L1).
            return Symbology(encodings=dict(self.encodings), props=dict(self.props))
        raise ValueError(
            f"nothing drives the {channel!r} channel of this layer, so there is no encoding for a "
            f"guide to explain; the channels it does drive are {sorted(self.encodings)}"
        )
    encodings = dict(self.encodings)
    encodings[channel] = with_fields(encoding, guide=guide)
    return Symbology(encodings=encodings, props=dict(self.props))

with_props(**props) #

Return a copy carrying extra static properties.

Parameters:

Name Type Description Default
**props Any

The properties to add or replace.

{}

Returns:

Type Description
Symbology

A new symbology; this one is unchanged.

Examples:

  • Properties accumulate, and the original is untouched:
    >>> from digitalearth.base.spec import Symbology
    >>> one = Symbology().with_props(scheme="quantiles")
    >>> both = one.with_props(k=7)
    >>> sorted(both.props), sorted(one.props)
    (['k', 'scheme'], ['scheme'])
    
  • Naming a property again replaces it:
    >>> from digitalearth.base.spec import Symbology
    >>> Symbology().with_props(k=5).with_props(k=9).props["k"]
    9
    
Source code in src/digitalearth/base/spec/style.py
def with_props(self, **props: Any) -> "Symbology":
    """Return a copy carrying extra static properties.

    Args:
        **props: The properties to add or replace.

    Returns:
        A new symbology; this one is unchanged.

    Examples:
        - Properties accumulate, and the original is untouched:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> one = Symbology().with_props(scheme="quantiles")
            >>> both = one.with_props(k=7)
            >>> sorted(both.props), sorted(one.props)
            (['k', 'scheme'], ['scheme'])

            ```
        - Naming a property again replaces it:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> Symbology().with_props(k=5).with_props(k=9).props["k"]
            9

            ```
    """
    merged = dict(self.props)
    merged.update(props)
    return Symbology(encodings=dict(self.encodings), props=merged)

digitalearth.base.spec.style.StyleSchema dataclass #

The declared style keywords of one builder surface, and the routing they enable.

Attributes:

Name Type Description
keys Mapping[str, StyleKey]

Keyword name -> :class:StyleKey.

Examples:

  • A declared channel keyword becomes an encoding; a declared property becomes a property; an undeclared keyword is handed back rather than swallowed:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(
    ...     StyleKey("alpha", "Opacity.", channel="opacity"),
    ...     StyleKey("hillshade", "Shade the surface."),
    ... )
    >>> sym, leftover = schema.route({"alpha": 0.5, "hillshade": True, "cmpa": "viridis"})
    >>> sym.encoding("opacity").resolve(), dict(sym.props), leftover
    (0.5, {'hillshade': True}, {'cmpa': 'viridis'})
    
  • And the nearest declared name is available for the error a caller should get:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> StyleSchema.of(StyleKey("hillshade", "Shade the surface.")).suggest("hillshde")
    'hillshade'
    
Source code in src/digitalearth/base/spec/style.py
@dataclass(frozen=True)
class StyleSchema:
    """The declared style keywords of one builder surface, and the routing they enable.

    Attributes:
        keys: Keyword name -> :class:`StyleKey`.

    Examples:
        - A declared channel keyword becomes an encoding; a declared property becomes a property; an
          undeclared keyword is handed back rather than swallowed:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(
            ...     StyleKey("alpha", "Opacity.", channel="opacity"),
            ...     StyleKey("hillshade", "Shade the surface."),
            ... )
            >>> sym, leftover = schema.route({"alpha": 0.5, "hillshade": True, "cmpa": "viridis"})
            >>> sym.encoding("opacity").resolve(), dict(sym.props), leftover
            (0.5, {'hillshade': True}, {'cmpa': 'viridis'})

            ```
        - And the nearest declared name is available for the error a caller should get:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> StyleSchema.of(StyleKey("hillshade", "Shade the surface.")).suggest("hillshde")
            'hillshade'

            ```
    """

    keys: Mapping[str, StyleKey] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Freeze the table, so a schema handed around cannot be extended behind a caller's back."""
        object.__setattr__(self, "keys", FrozenDict(dict(self.keys)))

    def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
        """Pickle and copy by rebuilding through the constructor.

        Returns:
            ``(type(self), (dict(keys),))`` — the caller's subclass, not `StyleSchema` by name. Rebuilding from a
            plain dict goes through the same freezing as any other construction.

        Examples:
            - A copy is equal to the original, and is a separate object:
                ```python
                >>> import copy
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> original = StyleSchema.of(StyleKey("cmap", "Colormap name."))
                >>> clone = copy.deepcopy(original)
                >>> clone == original, clone is original
                (True, False)

                ```
        """
        return type(self), (dict(self.keys),)

    @classmethod
    def of(cls, *keys: StyleKey) -> "StyleSchema":
        """Build a schema from its keys.

        Args:
            *keys: The declared keywords.

        Returns:
            The schema.

        Raises:
            ValueError: if a name is declared twice — two rows for one keyword means one of them is dead, and
                which one wins would depend on argument order.

        Examples:
            - Declare a surface, then ask what it accepts and what a keyword controls:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(
                ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
                ...     StyleKey("levels", "Contour levels."),
                ... )
                >>> schema.names()
                ('alpha', 'levels')
                >>> schema.keys["levels"].doc
                'Contour levels.'

                ```
            - Declaring one name twice is refused, because one of the two rows would be dead:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> StyleSchema.of(StyleKey("alpha", "One."), StyleKey("alpha", "Two."))
                Traceback (most recent call last):
                    ...
                ValueError: style key 'alpha' is declared twice

                ```
        """
        table: dict[str, StyleKey] = {}
        driving: dict[str, str] = {}
        for key in keys:
            if key.name in table:
                raise ValueError(f"style key {key.name!r} is declared twice")
            if key.channel is not None:
                if key.channel in driving:
                    # route() writes encodings[key.channel], so a second keyword on one channel would
                    # overwrite the first in whatever order the caller's kwargs happened to iterate.
                    raise ValueError(
                        f"style keys {driving[key.channel]!r} and {key.name!r} both drive the "
                        f"{key.channel!r} channel; only one may, or routing would silently drop one"
                    )
                driving[key.channel] = key.name
            table[key.name] = key
        return cls(keys=table)

    def names(self) -> tuple[str, ...]:
        """Return every declared keyword, sorted.

        Returns:
            The names a caller may pass — the answer to "what does this builder accept?" that did not exist
            before.

        Examples:
            - The declared keywords, sorted:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(StyleKey("levels", "Contour levels."), StyleKey("k", "Classes."))
                >>> schema.names()
                ('k', 'levels')

                ```
            - Which is enough to spot a keyword the surface does not accept:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
                >>> [name for name in ("hillshade", "cmpa") if name not in schema.names()]
                ['cmpa']

                ```
        """
        return tuple(sorted(self.keys))

    def channels(self) -> tuple[str, ...]:
        """Return the channels this surface can drive, sorted.

        Returns:
            The distinct channel names its keys point at.

        Examples:
            - Only the keys that drive a channel are counted:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(
                ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
                ...     StyleKey("size", "Marker size.", channel="size"),
                ...     StyleKey("hillshade", "Shade the surface."),
                ... )
                >>> schema.channels()
                ('opacity', 'size')

                ```
            - A surface of static properties alone drives nothing:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> StyleSchema.of(StyleKey("levels", "Contour levels.")).channels()
                ()

                ```
        """
        return tuple(sorted({key.channel for key in self.keys.values() if key.channel}))

    def route(self, flat: Mapping[str, Any]) -> tuple[Symbology, dict[str, Any]]:
        """Split flat keyword arguments into a declared symbology and whatever is left over.

        Args:
            flat: The caller's keyword dict. Not mutated.

        Returns:
            A ``(symbology, leftover)`` pair. A keyword declared with a channel becomes a constant
            :class:`~digitalearth.base.spec.encoding.Encoding` on it; a keyword declared without one becomes
            a static property; anything undeclared is returned in `leftover`.

            Leftovers are **returned, not raised**: this surface is not the only thing a builder's kwargs
            feed (the glyph constructor takes its own), so deciding that a key is homeless needs more
            knowledge than a schema has. :meth:`suggest` is what makes that decision answerable when a caller
            does reach it.

        Examples:
            - A ``None`` is a caller declining a key, so it routes nowhere rather than becoming a binding:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(StyleKey("alpha", "Opacity.", channel="opacity"))
                >>> sym, leftover = schema.route({"alpha": None})
                >>> dict(sym.encodings), leftover
                ({}, {})

                ```
        """
        encodings: dict[str, Encoding] = {}
        props: dict[str, Any] = {}
        leftover: dict[str, Any] = {}
        for name, value in flat.items():
            key = self.keys.get(name)
            if key is None:
                leftover[name] = value
                continue
            if value is None:
                continue  # a caller declining a key, not a binding to None
            if key.channel is None:
                props[name] = value
            else:
                encodings[key.channel] = Encoding.constant(key.channel, value)
        return Symbology(encodings=encodings, props=props), leftover

    def suggest(self, name: str) -> str | None:
        """Return the declared keyword `name` was most likely meant to be.

        Args:
            name: The keyword a caller wrote.

        Returns:
            The closest declared name, or ``None`` when nothing is close enough to be worth guessing. A wrong
            guess is worse than none — it sends the caller to a key that was never their intent.

        Examples:
            - A near miss is named, which is what turns a silently ignored typo into an answerable error:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
                >>> schema.suggest("hillshde")
                'hillshade'

                ```
            - Something unlike every declared key is not guessed at:
                ```python
                >>> from digitalearth.base.spec import StyleKey, StyleSchema
                >>> StyleSchema.of(StyleKey("hillshade", "Shade the surface.")).suggest("zzzzzz") is None
                True

                ```
        """
        matches = get_close_matches(name, self.keys, n=1, cutoff=0.7)
        return matches[0] if matches else None

__post_init__() #

Freeze the table, so a schema handed around cannot be extended behind a caller's back.

Source code in src/digitalearth/base/spec/style.py
def __post_init__(self) -> None:
    """Freeze the table, so a schema handed around cannot be extended behind a caller's back."""
    object.__setattr__(self, "keys", FrozenDict(dict(self.keys)))

__reduce__() #

Pickle and copy by rebuilding through the constructor.

Returns:

Type Description
Any

(type(self), (dict(keys),)) — the caller's subclass, not StyleSchema by name. Rebuilding from a

tuple[Any, ...]

plain dict goes through the same freezing as any other construction.

Examples:

  • A copy is equal to the original, and is a separate object:
    >>> import copy
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> original = StyleSchema.of(StyleKey("cmap", "Colormap name."))
    >>> clone = copy.deepcopy(original)
    >>> clone == original, clone is original
    (True, False)
    
Source code in src/digitalearth/base/spec/style.py
def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
    """Pickle and copy by rebuilding through the constructor.

    Returns:
        ``(type(self), (dict(keys),))`` — the caller's subclass, not `StyleSchema` by name. Rebuilding from a
        plain dict goes through the same freezing as any other construction.

    Examples:
        - A copy is equal to the original, and is a separate object:
            ```python
            >>> import copy
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> original = StyleSchema.of(StyleKey("cmap", "Colormap name."))
            >>> clone = copy.deepcopy(original)
            >>> clone == original, clone is original
            (True, False)

            ```
    """
    return type(self), (dict(self.keys),)

channels() #

Return the channels this surface can drive, sorted.

Returns:

Type Description
tuple[str, ...]

The distinct channel names its keys point at.

Examples:

  • Only the keys that drive a channel are counted:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(
    ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
    ...     StyleKey("size", "Marker size.", channel="size"),
    ...     StyleKey("hillshade", "Shade the surface."),
    ... )
    >>> schema.channels()
    ('opacity', 'size')
    
  • A surface of static properties alone drives nothing:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> StyleSchema.of(StyleKey("levels", "Contour levels.")).channels()
    ()
    
Source code in src/digitalearth/base/spec/style.py
def channels(self) -> tuple[str, ...]:
    """Return the channels this surface can drive, sorted.

    Returns:
        The distinct channel names its keys point at.

    Examples:
        - Only the keys that drive a channel are counted:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(
            ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
            ...     StyleKey("size", "Marker size.", channel="size"),
            ...     StyleKey("hillshade", "Shade the surface."),
            ... )
            >>> schema.channels()
            ('opacity', 'size')

            ```
        - A surface of static properties alone drives nothing:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> StyleSchema.of(StyleKey("levels", "Contour levels.")).channels()
            ()

            ```
    """
    return tuple(sorted({key.channel for key in self.keys.values() if key.channel}))

names() #

Return every declared keyword, sorted.

Returns:

Type Description
str

The names a caller may pass — the answer to "what does this builder accept?" that did not exist

...

before.

Examples:

  • The declared keywords, sorted:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(StyleKey("levels", "Contour levels."), StyleKey("k", "Classes."))
    >>> schema.names()
    ('k', 'levels')
    
  • Which is enough to spot a keyword the surface does not accept:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
    >>> [name for name in ("hillshade", "cmpa") if name not in schema.names()]
    ['cmpa']
    
Source code in src/digitalearth/base/spec/style.py
def names(self) -> tuple[str, ...]:
    """Return every declared keyword, sorted.

    Returns:
        The names a caller may pass — the answer to "what does this builder accept?" that did not exist
        before.

    Examples:
        - The declared keywords, sorted:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(StyleKey("levels", "Contour levels."), StyleKey("k", "Classes."))
            >>> schema.names()
            ('k', 'levels')

            ```
        - Which is enough to spot a keyword the surface does not accept:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
            >>> [name for name in ("hillshade", "cmpa") if name not in schema.names()]
            ['cmpa']

            ```
    """
    return tuple(sorted(self.keys))

of(*keys) classmethod #

Build a schema from its keys.

Parameters:

Name Type Description Default
*keys StyleKey

The declared keywords.

()

Returns:

Type Description
StyleSchema

The schema.

Raises:

Type Description
ValueError

if a name is declared twice — two rows for one keyword means one of them is dead, and which one wins would depend on argument order.

Examples:

  • Declare a surface, then ask what it accepts and what a keyword controls:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(
    ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
    ...     StyleKey("levels", "Contour levels."),
    ... )
    >>> schema.names()
    ('alpha', 'levels')
    >>> schema.keys["levels"].doc
    'Contour levels.'
    
  • Declaring one name twice is refused, because one of the two rows would be dead:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> StyleSchema.of(StyleKey("alpha", "One."), StyleKey("alpha", "Two."))
    Traceback (most recent call last):
        ...
    ValueError: style key 'alpha' is declared twice
    
Source code in src/digitalearth/base/spec/style.py
@classmethod
def of(cls, *keys: StyleKey) -> "StyleSchema":
    """Build a schema from its keys.

    Args:
        *keys: The declared keywords.

    Returns:
        The schema.

    Raises:
        ValueError: if a name is declared twice — two rows for one keyword means one of them is dead, and
            which one wins would depend on argument order.

    Examples:
        - Declare a surface, then ask what it accepts and what a keyword controls:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(
            ...     StyleKey("alpha", "Layer opacity.", channel="opacity"),
            ...     StyleKey("levels", "Contour levels."),
            ... )
            >>> schema.names()
            ('alpha', 'levels')
            >>> schema.keys["levels"].doc
            'Contour levels.'

            ```
        - Declaring one name twice is refused, because one of the two rows would be dead:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> StyleSchema.of(StyleKey("alpha", "One."), StyleKey("alpha", "Two."))
            Traceback (most recent call last):
                ...
            ValueError: style key 'alpha' is declared twice

            ```
    """
    table: dict[str, StyleKey] = {}
    driving: dict[str, str] = {}
    for key in keys:
        if key.name in table:
            raise ValueError(f"style key {key.name!r} is declared twice")
        if key.channel is not None:
            if key.channel in driving:
                # route() writes encodings[key.channel], so a second keyword on one channel would
                # overwrite the first in whatever order the caller's kwargs happened to iterate.
                raise ValueError(
                    f"style keys {driving[key.channel]!r} and {key.name!r} both drive the "
                    f"{key.channel!r} channel; only one may, or routing would silently drop one"
                )
            driving[key.channel] = key.name
        table[key.name] = key
    return cls(keys=table)

route(flat) #

Split flat keyword arguments into a declared symbology and whatever is left over.

Parameters:

Name Type Description Default
flat Mapping[str, Any]

The caller's keyword dict. Not mutated.

required

Returns:

Type Description
Symbology

A (symbology, leftover) pair. A keyword declared with a channel becomes a constant

dict[str, Any]

class:~digitalearth.base.spec.encoding.Encoding on it; a keyword declared without one becomes

tuple[Symbology, dict[str, Any]]

a static property; anything undeclared is returned in leftover.

tuple[Symbology, dict[str, Any]]

Leftovers are returned, not raised: this surface is not the only thing a builder's kwargs

tuple[Symbology, dict[str, Any]]

feed (the glyph constructor takes its own), so deciding that a key is homeless needs more

tuple[Symbology, dict[str, Any]]

knowledge than a schema has. :meth:suggest is what makes that decision answerable when a caller

tuple[Symbology, dict[str, Any]]

does reach it.

Examples:

  • A None is a caller declining a key, so it routes nowhere rather than becoming a binding:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(StyleKey("alpha", "Opacity.", channel="opacity"))
    >>> sym, leftover = schema.route({"alpha": None})
    >>> dict(sym.encodings), leftover
    ({}, {})
    
Source code in src/digitalearth/base/spec/style.py
def route(self, flat: Mapping[str, Any]) -> tuple[Symbology, dict[str, Any]]:
    """Split flat keyword arguments into a declared symbology and whatever is left over.

    Args:
        flat: The caller's keyword dict. Not mutated.

    Returns:
        A ``(symbology, leftover)`` pair. A keyword declared with a channel becomes a constant
        :class:`~digitalearth.base.spec.encoding.Encoding` on it; a keyword declared without one becomes
        a static property; anything undeclared is returned in `leftover`.

        Leftovers are **returned, not raised**: this surface is not the only thing a builder's kwargs
        feed (the glyph constructor takes its own), so deciding that a key is homeless needs more
        knowledge than a schema has. :meth:`suggest` is what makes that decision answerable when a caller
        does reach it.

    Examples:
        - A ``None`` is a caller declining a key, so it routes nowhere rather than becoming a binding:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(StyleKey("alpha", "Opacity.", channel="opacity"))
            >>> sym, leftover = schema.route({"alpha": None})
            >>> dict(sym.encodings), leftover
            ({}, {})

            ```
    """
    encodings: dict[str, Encoding] = {}
    props: dict[str, Any] = {}
    leftover: dict[str, Any] = {}
    for name, value in flat.items():
        key = self.keys.get(name)
        if key is None:
            leftover[name] = value
            continue
        if value is None:
            continue  # a caller declining a key, not a binding to None
        if key.channel is None:
            props[name] = value
        else:
            encodings[key.channel] = Encoding.constant(key.channel, value)
    return Symbology(encodings=encodings, props=props), leftover

suggest(name) #

Return the declared keyword name was most likely meant to be.

Parameters:

Name Type Description Default
name str

The keyword a caller wrote.

required

Returns:

Type Description
str | None

The closest declared name, or None when nothing is close enough to be worth guessing. A wrong

str | None

guess is worse than none — it sends the caller to a key that was never their intent.

Examples:

  • A near miss is named, which is what turns a silently ignored typo into an answerable error:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
    >>> schema.suggest("hillshde")
    'hillshade'
    
  • Something unlike every declared key is not guessed at:
    >>> from digitalearth.base.spec import StyleKey, StyleSchema
    >>> StyleSchema.of(StyleKey("hillshade", "Shade the surface.")).suggest("zzzzzz") is None
    True
    
Source code in src/digitalearth/base/spec/style.py
def suggest(self, name: str) -> str | None:
    """Return the declared keyword `name` was most likely meant to be.

    Args:
        name: The keyword a caller wrote.

    Returns:
        The closest declared name, or ``None`` when nothing is close enough to be worth guessing. A wrong
        guess is worse than none — it sends the caller to a key that was never their intent.

    Examples:
        - A near miss is named, which is what turns a silently ignored typo into an answerable error:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> schema = StyleSchema.of(StyleKey("hillshade", "Shade the surface."))
            >>> schema.suggest("hillshde")
            'hillshade'

            ```
        - Something unlike every declared key is not guessed at:
            ```python
            >>> from digitalearth.base.spec import StyleKey, StyleSchema
            >>> StyleSchema.of(StyleKey("hillshade", "Shade the surface.")).suggest("zzzzzz") is None
            True

            ```
    """
    matches = get_close_matches(name, self.keys, n=1, cutoff=0.7)
    return matches[0] if matches else None

digitalearth.base.spec.style.StyleKey dataclass #

One declared style keyword: its name, what it does, and whether it drives a channel.

Attributes:

Name Type Description
name str

The public keyword, exactly as a caller writes it.

doc str

One line saying what it controls. This is the text a discovery surface shows, so it is part of the declaration rather than a comment beside it.

channel str | None

The visual channel the keyword sets, or None when it is a static property — a flag, a threshold, a nested kwargs dict — that varies with nothing.

Raises:

Type Description
ValueError

if channel names something that is not a declared channel.

Examples:

  • A keyword that drives a channel says which one:
    >>> from digitalearth.base.spec import StyleKey
    >>> key = StyleKey("alpha", "Layer opacity, 0 transparent to 1 opaque.", channel="opacity")
    >>> key.name, key.channel
    ('alpha', 'opacity')
    
  • A static property declares no channel, and that is how routing tells the two apart:
    >>> from digitalearth.base.spec import StyleKey
    >>> StyleKey("hillshade", "Shade the surface with relief.").channel is None
    True
    
Source code in src/digitalearth/base/spec/style.py
@dataclass(frozen=True)
class StyleKey:
    """One declared style keyword: its name, what it does, and whether it drives a channel.

    Attributes:
        name: The public keyword, exactly as a caller writes it.
        doc: One line saying what it controls. This is the text a discovery surface shows, so it is part of
            the declaration rather than a comment beside it.
        channel: The visual channel the keyword sets, or ``None`` when it is a static property — a flag,
            a threshold, a nested kwargs dict — that varies with nothing.

    Raises:
        ValueError: if `channel` names something that is not a declared channel.

    Examples:
        - A keyword that drives a channel says which one:
            ```python
            >>> from digitalearth.base.spec import StyleKey
            >>> key = StyleKey("alpha", "Layer opacity, 0 transparent to 1 opaque.", channel="opacity")
            >>> key.name, key.channel
            ('alpha', 'opacity')

            ```
        - A static property declares no channel, and that is how routing tells the two apart:
            ```python
            >>> from digitalearth.base.spec import StyleKey
            >>> StyleKey("hillshade", "Shade the surface with relief.").channel is None
            True

            ```
    """

    name: str
    doc: str
    channel: str | None = None

    def __post_init__(self) -> None:
        """Refuse a key pointing at a channel that does not exist.

        Raises:
            ValueError: for an undeclared channel name.
        """
        if self.channel is not None and self.channel not in CHANNELS:
            raise ValueError(
                f"style key {self.name!r} names channel {self.channel!r}, which is not declared; "
                f"declared channels are {sorted(CHANNELS)}"
            )

__post_init__() #

Refuse a key pointing at a channel that does not exist.

Raises:

Type Description
ValueError

for an undeclared channel name.

Source code in src/digitalearth/base/spec/style.py
def __post_init__(self) -> None:
    """Refuse a key pointing at a channel that does not exist.

    Raises:
        ValueError: for an undeclared channel name.
    """
    if self.channel is not None and self.channel not in CHANNELS:
        raise ValueError(
            f"style key {self.name!r} names channel {self.channel!r}, which is not declared; "
            f"declared channels are {sorted(CHANNELS)}"
        )

The shared defaults#

Constants that exist so a second value cannot appear. DEFAULT_BAND is the band a builder reads when the caller names none; DEFAULT_CLASS_COUNT is the five classes a graduated scheme cuts by default, which every tier had written out separately.

ViewRequest — how much to read, and how finely#

A DataRef says where data is and a Selection says which slice; neither says how much of it to read or at what resolution. Three of the four backend studies invented this third question independently, which is the usual sign a type is missing rather than optional.

digitalearth.base.spec.viewrequest.ViewRequest dataclass #

A request for a region of data at a resolution, bounded by a budget.

Attributes:

Name Type Description
bounds Bounds | None

The region wanted, in its own CRS — a reader reprojects if it must. None asks for whatever the source covers.

width int | None

Target width in pixels, or None.

height int | None

Target height in pixels, or None.

pixel_ratio float

Device pixel ratio, so a HiDPI canvas can ask for the pixels it will actually draw.

budget int | None

Greatest number of cells the reader may return. This is the honest limit — width/height say what is wanted, budget says what the process can afford, and a reader that cannot serve both must respect this one.

Raises:

Type Description
ValueError

if width, height or budget is not a positive whole number (800.0 is refused), or pixel_ratio is not a positive finite number (a boolean is refused). A zero-width request reads nothing and a negative one is a computed value that went wrong upstream; both are worth catching where they are written rather than inside a reader.

Examples:

  • A request for a region at a canvas size:
    >>> from digitalearth.base.spec import Bounds, ViewRequest
    >>> req = ViewRequest(bounds=Bounds(0.0, 0.0, 10.0, 10.0, crs=4326), width=800, height=600)
    >>> req.pixels
    480000
    
  • A budget alone, with no canvas — what a decimating reader needs:
    >>> from digitalearth.base.spec import ViewRequest
    >>> ViewRequest(budget=1_000_000).side()
    1000
    
Source code in src/digitalearth/base/spec/viewrequest.py
@dataclass(frozen=True)
class ViewRequest:
    """A request for a region of data at a resolution, bounded by a budget.

    Attributes:
        bounds: The region wanted, in its own CRS — a reader reprojects if it must. ``None`` asks for
            whatever the source covers.
        width: Target width in pixels, or ``None``.
        height: Target height in pixels, or ``None``.
        pixel_ratio: Device pixel ratio, so a HiDPI canvas can ask for the pixels it will actually draw.
        budget: Greatest number of cells the reader may return. This is the honest limit — `width`/`height`
            say what is wanted, `budget` says what the process can afford, and a reader that cannot serve
            both must respect this one.

    Raises:
        ValueError: if `width`, `height` or `budget` is not a positive whole number (`800.0` is refused), or
            `pixel_ratio` is not a positive finite number (a boolean is refused). A zero-width request reads
            nothing and a negative one is a computed value that went wrong upstream; both are worth catching
            where they are written rather than inside a reader.

    Examples:
        - A request for a region at a canvas size:
            ```python
            >>> from digitalearth.base.spec import Bounds, ViewRequest
            >>> req = ViewRequest(bounds=Bounds(0.0, 0.0, 10.0, 10.0, crs=4326), width=800, height=600)
            >>> req.pixels
            480000

            ```
        - A budget alone, with no canvas — what a decimating reader needs:
            ```python
            >>> from digitalearth.base.spec import ViewRequest
            >>> ViewRequest(budget=1_000_000).side()
            1000

            ```
    """

    bounds: Bounds | None = None
    width: int | None = None
    height: int | None = None
    pixel_ratio: float = 1.0
    budget: int | None = None

    def __post_init__(self) -> None:
        """Refuse a request that asks for nothing, or for a negative amount of something.

        Raises:
            ValueError: for a dimension or budget that is not a positive whole number, or a ratio that is not a
                positive finite number.
        """
        for name in ("width", "height", "budget"):
            value = getattr(self, name)
            if value is None:
                continue
            # Integral, not int, and coerced — exactly as Selection does, and for the same reason: canvas
            # sizes and cell budgets arrive from numpy arithmetic, and these two types are meant to be used
            # in the same call. Refusing np.int64 here while Selection accepts it is one vocabulary
            # disagreeing with itself.
            if isinstance(value, bool) or not isinstance(value, Integral):
                raise ValueError(
                    f"ViewRequest {name} must be a whole number of pixels or cells; got {value!r}"
                )
            if value <= 0:
                raise ValueError(f"ViewRequest {name} must be positive; got {value}")
            object.__setattr__(self, name, int(value))
        # Stored as a Python float, as `RenderTarget` stores it: a numpy ratio was accepted and kept as numpy,
        # and a boolean was accepted as a ratio of one.
        ratio = positive_number(self.pixel_ratio)
        if ratio is None:
            raise ValueError(
                f"ViewRequest pixel_ratio must be a positive number; got {self.pixel_ratio!r}"
            )
        object.__setattr__(self, "pixel_ratio", ratio)

    @property
    def pixels(self) -> int | None:
        """How many device pixels the request covers, or ``None`` when it names no canvas.

        Returns:
            ``width * height``, scaled by :attr:`pixel_ratio` — the count a reader compares against
            :attr:`budget`.

        Examples:
            - A retina canvas asks for the pixels it will actually draw:
                ```python
                >>> from digitalearth.base.spec import ViewRequest
                >>> ViewRequest(width=800, height=600).pixels
                480000
                >>> ViewRequest(width=800, height=600, pixel_ratio=2.0).pixels
                1920000

                ```
        """
        if self.width is None or self.height is None:
            return None
        return int(self.width * self.height * self.pixel_ratio * self.pixel_ratio)

    def side(self, floor: int = 64) -> int:
        """Return the square side a decimating reader should aim for.

        Args:
            floor: Smallest side to return. A budget small enough to ask for a handful of cells produces an
                image nothing can be read from, so there is a lower bound.

        Returns:
            The larger of `floor` and the square root of the effective cell allowance — the canvas sizing
            `interactive/raster.py` does by hand as ``max(64, int(sqrt(max_pixels)))``. The allowance is the
            budget or the canvas's :attr:`pixels`, whichever is set, and the **smaller** of the two when both
            are: the canvas says what is wanted and the budget what is affordable, and a read past the canvas
            fetches cells nothing draws. With neither, `floor` is the answer.

        Examples:
            - The budget sets the side, and a tiny one still floors:
                ```python
                >>> from digitalearth.base.spec import ViewRequest
                >>> ViewRequest(budget=1_000_000).side(), ViewRequest(budget=4).side()
                (1000, 64)

                ```
            - A canvas under the budget sizes the read; one over it is held to the budget:
                ```python
                >>> from digitalearth.base.spec import ViewRequest
                >>> ViewRequest(width=640, height=480, budget=4_000_000).side()
                554
                >>> ViewRequest(width=4000, height=4000, budget=1_000_000).side()
                1000

                ```
        """
        # The windowed read in `SourceView` already reads a canvas that fits its budget; the square a decimating
        # reader aims for follows the same rule rather than reading up to the budget whatever the canvas shows.
        allowances = [
            limit for limit in (self.budget, self.pixels) if limit is not None
        ]
        if not allowances:
            return floor
        return max(floor, int(sqrt(min(allowances))))

    def within_budget(self, cells: int) -> bool:
        """Whether a read of `cells` cells is affordable.

        Args:
            cells: How many cells the read would return.

        Returns:
            ``True`` when there is no budget, or the read fits inside it.

        Examples:
            - No budget affords anything:
                ```python
                >>> from digitalearth.base.spec import ViewRequest
                >>> ViewRequest().within_budget(10 ** 9)
                True
                >>> ViewRequest(budget=100).within_budget(101)
                False

                ```
        """
        return self.budget is None or cells <= self.budget

    def as_bbox(self) -> tuple[float, float, float, float] | None:
        """Return the requested region as the bbox tuple a pyramids reader takes.

        Returns:
            ``(xmin, ymin, xmax, ymax)``, or ``None`` when the request names no region. The ordering comes
            from :meth:`~digitalearth.base.spec.bounds.Bounds.as_bbox` rather than being written out here.

        Examples:
            - A region in bbox order, and no region at all:
                ```python
                >>> from digitalearth.base.spec import Bounds, ViewRequest
                >>> ViewRequest(bounds=Bounds(0.0, 1.0, 2.0, 3.0, crs=4326)).as_bbox()
                (0.0, 1.0, 2.0, 3.0)
                >>> ViewRequest(budget=10).as_bbox() is None
                True

                ```
        """
        if self.bounds is None:
            return None
        xmin, ymin, xmax, ymax = self.bounds.as_bbox()
        return (xmin, ymin, xmax, ymax)

    @property
    def crs(self) -> Any:
        """The CRS the requested region is expressed in.

        Returns:
            The bounds' CRS, or ``None`` when the request names no region.

        Examples:
            - The CRS travels with the region:
                ```python
                >>> from digitalearth.base.spec import Bounds, ViewRequest
                >>> ViewRequest(bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=3857)).crs
                3857

                ```
        """
        return None if self.bounds is None else self.bounds.crs

crs property #

The CRS the requested region is expressed in.

Returns:

Type Description
Any

The bounds' CRS, or None when the request names no region.

Examples:

  • The CRS travels with the region:
    >>> from digitalearth.base.spec import Bounds, ViewRequest
    >>> ViewRequest(bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=3857)).crs
    3857
    

pixels property #

How many device pixels the request covers, or None when it names no canvas.

Returns:

Type Description
int | None

width * height, scaled by :attr:pixel_ratio — the count a reader compares against

int | None

attr:budget.

Examples:

  • A retina canvas asks for the pixels it will actually draw:
    >>> from digitalearth.base.spec import ViewRequest
    >>> ViewRequest(width=800, height=600).pixels
    480000
    >>> ViewRequest(width=800, height=600, pixel_ratio=2.0).pixels
    1920000
    

__post_init__() #

Refuse a request that asks for nothing, or for a negative amount of something.

Raises:

Type Description
ValueError

for a dimension or budget that is not a positive whole number, or a ratio that is not a positive finite number.

Source code in src/digitalearth/base/spec/viewrequest.py
def __post_init__(self) -> None:
    """Refuse a request that asks for nothing, or for a negative amount of something.

    Raises:
        ValueError: for a dimension or budget that is not a positive whole number, or a ratio that is not a
            positive finite number.
    """
    for name in ("width", "height", "budget"):
        value = getattr(self, name)
        if value is None:
            continue
        # Integral, not int, and coerced — exactly as Selection does, and for the same reason: canvas
        # sizes and cell budgets arrive from numpy arithmetic, and these two types are meant to be used
        # in the same call. Refusing np.int64 here while Selection accepts it is one vocabulary
        # disagreeing with itself.
        if isinstance(value, bool) or not isinstance(value, Integral):
            raise ValueError(
                f"ViewRequest {name} must be a whole number of pixels or cells; got {value!r}"
            )
        if value <= 0:
            raise ValueError(f"ViewRequest {name} must be positive; got {value}")
        object.__setattr__(self, name, int(value))
    # Stored as a Python float, as `RenderTarget` stores it: a numpy ratio was accepted and kept as numpy,
    # and a boolean was accepted as a ratio of one.
    ratio = positive_number(self.pixel_ratio)
    if ratio is None:
        raise ValueError(
            f"ViewRequest pixel_ratio must be a positive number; got {self.pixel_ratio!r}"
        )
    object.__setattr__(self, "pixel_ratio", ratio)

as_bbox() #

Return the requested region as the bbox tuple a pyramids reader takes.

Returns:

Name Type Description
tuple[float, float, float, float] | None

(xmin, ymin, xmax, ymax), or None when the request names no region. The ordering comes

from tuple[float, float, float, float] | None

meth:~digitalearth.base.spec.bounds.Bounds.as_bbox rather than being written out here.

Examples:

  • A region in bbox order, and no region at all:
    >>> from digitalearth.base.spec import Bounds, ViewRequest
    >>> ViewRequest(bounds=Bounds(0.0, 1.0, 2.0, 3.0, crs=4326)).as_bbox()
    (0.0, 1.0, 2.0, 3.0)
    >>> ViewRequest(budget=10).as_bbox() is None
    True
    
Source code in src/digitalearth/base/spec/viewrequest.py
def as_bbox(self) -> tuple[float, float, float, float] | None:
    """Return the requested region as the bbox tuple a pyramids reader takes.

    Returns:
        ``(xmin, ymin, xmax, ymax)``, or ``None`` when the request names no region. The ordering comes
        from :meth:`~digitalearth.base.spec.bounds.Bounds.as_bbox` rather than being written out here.

    Examples:
        - A region in bbox order, and no region at all:
            ```python
            >>> from digitalearth.base.spec import Bounds, ViewRequest
            >>> ViewRequest(bounds=Bounds(0.0, 1.0, 2.0, 3.0, crs=4326)).as_bbox()
            (0.0, 1.0, 2.0, 3.0)
            >>> ViewRequest(budget=10).as_bbox() is None
            True

            ```
    """
    if self.bounds is None:
        return None
    xmin, ymin, xmax, ymax = self.bounds.as_bbox()
    return (xmin, ymin, xmax, ymax)

side(floor=64) #

Return the square side a decimating reader should aim for.

Parameters:

Name Type Description Default
floor int

Smallest side to return. A budget small enough to ask for a handful of cells produces an image nothing can be read from, so there is a lower bound.

64

Returns:

Name Type Description
int

The larger of floor and the square root of the effective cell allowance — the canvas sizing

int

interactive/raster.py does by hand as max(64, int(sqrt(max_pixels))). The allowance is the

int

budget or the canvas's :attr:pixels, whichever is set, and the smaller of the two when both

are int

the canvas says what is wanted and the budget what is affordable, and a read past the canvas

int

fetches cells nothing draws. With neither, floor is the answer.

Examples:

  • The budget sets the side, and a tiny one still floors:
    >>> from digitalearth.base.spec import ViewRequest
    >>> ViewRequest(budget=1_000_000).side(), ViewRequest(budget=4).side()
    (1000, 64)
    
  • A canvas under the budget sizes the read; one over it is held to the budget:
    >>> from digitalearth.base.spec import ViewRequest
    >>> ViewRequest(width=640, height=480, budget=4_000_000).side()
    554
    >>> ViewRequest(width=4000, height=4000, budget=1_000_000).side()
    1000
    
Source code in src/digitalearth/base/spec/viewrequest.py
def side(self, floor: int = 64) -> int:
    """Return the square side a decimating reader should aim for.

    Args:
        floor: Smallest side to return. A budget small enough to ask for a handful of cells produces an
            image nothing can be read from, so there is a lower bound.

    Returns:
        The larger of `floor` and the square root of the effective cell allowance — the canvas sizing
        `interactive/raster.py` does by hand as ``max(64, int(sqrt(max_pixels)))``. The allowance is the
        budget or the canvas's :attr:`pixels`, whichever is set, and the **smaller** of the two when both
        are: the canvas says what is wanted and the budget what is affordable, and a read past the canvas
        fetches cells nothing draws. With neither, `floor` is the answer.

    Examples:
        - The budget sets the side, and a tiny one still floors:
            ```python
            >>> from digitalearth.base.spec import ViewRequest
            >>> ViewRequest(budget=1_000_000).side(), ViewRequest(budget=4).side()
            (1000, 64)

            ```
        - A canvas under the budget sizes the read; one over it is held to the budget:
            ```python
            >>> from digitalearth.base.spec import ViewRequest
            >>> ViewRequest(width=640, height=480, budget=4_000_000).side()
            554
            >>> ViewRequest(width=4000, height=4000, budget=1_000_000).side()
            1000

            ```
    """
    # The windowed read in `SourceView` already reads a canvas that fits its budget; the square a decimating
    # reader aims for follows the same rule rather than reading up to the budget whatever the canvas shows.
    allowances = [
        limit for limit in (self.budget, self.pixels) if limit is not None
    ]
    if not allowances:
        return floor
    return max(floor, int(sqrt(min(allowances))))

within_budget(cells) #

Whether a read of cells cells is affordable.

Parameters:

Name Type Description Default
cells int

How many cells the read would return.

required

Returns:

Type Description
bool

True when there is no budget, or the read fits inside it.

Examples:

  • No budget affords anything:
    >>> from digitalearth.base.spec import ViewRequest
    >>> ViewRequest().within_budget(10 ** 9)
    True
    >>> ViewRequest(budget=100).within_budget(101)
    False
    
Source code in src/digitalearth/base/spec/viewrequest.py
def within_budget(self, cells: int) -> bool:
    """Whether a read of `cells` cells is affordable.

    Args:
        cells: How many cells the read would return.

    Returns:
        ``True`` when there is no budget, or the read fits inside it.

    Examples:
        - No budget affords anything:
            ```python
            >>> from digitalearth.base.spec import ViewRequest
            >>> ViewRequest().within_budget(10 ** 9)
            True
            >>> ViewRequest(budget=100).within_budget(101)
            False

            ```
    """
    return self.budget is None or cells <= self.budget

SourceView — a view that remembers its own address#

A Source carries materialised data and forgets where it came from, so the only way to get different pixels was to start again from the caller's object. That is what blocks dynamic tiling, level of detail and point clouds too large to hold. SourceView keeps the reference and the slice, so it can be read again.

digitalearth.base.sources.view.SourceView #

Bases: Source

A materialised view of data, carrying the reference and slice it was read from.

Parameters:

Name Type Description Default
z DimensionInfo | None

The data dimension, as :class:~digitalearth.base.sources.source.Source takes it.

required
x DimensionInfo

The x / longitude axis.

required
y DimensionInfo

The y / latitude axis.

required
crs Any

The CRS the coordinates are expressed in.

None
metadata dict | None

Free-form metadata.

None
units str | None

Unit string for the values.

None
ref DataRef | None

Where the data came from. None for a view built from an object the caller held, which can still be read but not re-read.

None
selection Selection | None

Which slice was read.

None
request ViewRequest | None

The request this view answered, when it answered one. Kept so a caller can tell what it asked for from what it got — a reader may return fewer cells than the budget allowed.

None
window Bounds | None

The rectangle actually read, in the CRS its cells are measured in, for a windowed read; None for a view that read the whole source. It is what a renderer needs to place the cells, and the reader is the only one that can say: a canvas one cell wide has no spacing to derive it from, which is why a renderer must not be left to.

None

Examples:

  • A view knows its own address:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import DataRef, Selection
    >>> axis = DimensionInfo(np.array([0.0, 1.0]), "x")
    >>> view = SourceView(None, axis, axis, crs=4326,
    ...                   ref=DataRef("data/dem.tif"), selection=Selection.of(2))
    >>> view.ref.uri, view.selection.first_band
    ('data/dem.tif', 2)
    
  • And is still an ordinary Source, so every existing consumer takes it:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo, Source
    >>> from digitalearth.base.sources.view import SourceView
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> isinstance(SourceView(None, axis, axis, crs=3857), Source)
    True
    
Source code in src/digitalearth/base/sources/view.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
class SourceView(Source):
    """A materialised view of data, carrying the reference and slice it was read from.

    Args:
        z: The data dimension, as :class:`~digitalearth.base.sources.source.Source` takes it.
        x: The x / longitude axis.
        y: The y / latitude axis.
        crs: The CRS the coordinates are expressed in.
        metadata: Free-form metadata.
        units: Unit string for the values.
        ref: Where the data came from. ``None`` for a view built from an object the caller held, which can
            still be read but not re-read.
        selection: Which slice was read.
        request: The request this view answered, when it answered one. Kept so a caller can tell what it
            asked for from what it got — a reader may return fewer cells than the budget allowed.
        window: The rectangle actually read, in the CRS its cells are measured in, for a windowed read;
            `None` for a view that read the whole source. It is what a renderer needs to *place* the
            cells, and the reader is the only one that can say: a canvas one cell wide has no spacing
            to derive it from, which is why a renderer must not be left to.

    Examples:
        - A view knows its own address:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo
            >>> from digitalearth.base.sources.view import SourceView
            >>> from digitalearth.base.spec import DataRef, Selection
            >>> axis = DimensionInfo(np.array([0.0, 1.0]), "x")
            >>> view = SourceView(None, axis, axis, crs=4326,
            ...                   ref=DataRef("data/dem.tif"), selection=Selection.of(2))
            >>> view.ref.uri, view.selection.first_band
            ('data/dem.tif', 2)

            ```
        - And is still an ordinary `Source`, so every existing consumer takes it:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo, Source
            >>> from digitalearth.base.sources.view import SourceView
            >>> axis = DimensionInfo(np.array([0.0]), "x")
            >>> isinstance(SourceView(None, axis, axis, crs=3857), Source)
            True

            ```
    """

    def __init__(
        self,
        z: DimensionInfo | None,
        x: DimensionInfo,
        y: DimensionInfo,
        crs: Any = None,
        metadata: dict | None = None,
        units: str | None = None,
        *,
        ref: DataRef | None = None,
        selection: Selection | None = None,
        request: ViewRequest | None = None,
        window: Bounds | None = None,
    ):
        super().__init__(z, x, y, crs, metadata, units)
        self._ref = ref
        self._selection = selection if selection is not None else Selection()
        self._request = request
        self._window = window

    @property
    def window(self) -> Bounds | None:
        """The rectangle this view's cells cover, for a windowed read.

        Returns:
            The window read, in the CRS its cells are measured in, or `None` when the whole source was
            read and the axes describe it themselves.

        Examples:
            - A view of a whole source names no window:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> axis = DimensionInfo(np.array([0.0, 1.0]), "x")
                >>> SourceView(None, axis, axis, crs=4326).window is None
                True

                ```
        """
        return self._window

    @property
    def ref(self) -> DataRef | None:
        """Where this view's data came from, or ``None`` when it was built from a held object.

        Returns:
            The reference. ``None`` is not a defect — a caller may pass a `Dataset` they built in a notebook,
            and that view is perfectly usable; it just cannot be re-read from an address it never had.

        Examples:
            - The address a view was read from:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> from digitalearth.base.spec import DataRef
                >>> axis = DimensionInfo(np.array([0.0]), "x")
                >>> SourceView(None, axis, axis, ref=DataRef("dem.tif")).ref.uri
                'dem.tif'

                ```
        """
        return self._ref

    @property
    def selection(self) -> Selection:
        """Which slice of the source this view holds.

        Returns:
            The selection. Defaults to the default band rather than ``None``, so a caller never has to guard
            before narrowing it.

        Examples:
            - A view with no selection still answers with one:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> axis = DimensionInfo(np.array([0.0]), "x")
                >>> SourceView(None, axis, axis).selection.first_band
                1

                ```
        """
        return self._selection

    @property
    def request(self) -> ViewRequest | None:
        """The request this view answered, or ``None`` when it was not read against one.

        Returns:
            The request, kept so a caller can compare what it asked for with what it got.

        Examples:
            - A view not read against a request says so:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> axis = DimensionInfo(np.array([0.0]), "x")
                >>> SourceView(None, axis, axis).request is None
                True

                ```
        """
        return self._request

    @property
    def rereadable(self) -> bool:
        """Whether this view can be read again.

        Returns:
            ``True`` when the view carries a reference. A view built from a held object answers ``False``,
            and :meth:`reread` says so rather than failing deep inside a reader.

        Examples:
            - A view with no reference knows it cannot be re-read:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> axis = DimensionInfo(np.array([0.0]), "x")
                >>> SourceView(None, axis, axis).rereadable
                False

                ```
        """
        return self._ref is not None

    def reread(self, request: ViewRequest) -> "SourceView":
        """Read the same slice again, for a different region or resolution.

        This is what the address is for. The view re-opens its own
        :class:`~digitalearth.base.spec.dataref.DataRef`, applies its own
        :class:`~digitalearth.base.spec.selection.Selection`, and asks the reader for what `request` wants —
        the loop `interactive/raster.py` currently drives by hand at one call site.

        Args:
            request: The region, resolution and budget wanted.

        Returns:
            A new view of the same slice, carrying the same reference and selection plus the request it
            answered. Its metadata is the new read's, with each key in :data:`DESCRIBING_KEYS` the new read
            did not supply filled in from this view — see :meth:`_carried` — and its `units` are this view's
            when the new read found none.

        Raises:
            RuntimeError: if this view has no reference to read from — see :attr:`rereadable`. Raised here,
                naming the view, rather than surfacing as an `AttributeError` from inside a reader. Build the
                view from a `DataRef`, or register the object with
                :meth:`~digitalearth.base.spec.dataref.DataRef.to_object`, to make it re-readable.
            KeyError: if the reference no longer resolves — an `object:` id not registered in this process,
                or a scheme no resolver handles. Raised by
                :meth:`~digitalearth.base.spec.dataref.DataRef.open`.
            ValueError: if this view's selection is one :meth:`of` refuses, or the source is a rotated raster,
                which no window can be labelled for.

        Examples:
            - Re-reading within a budget keeps the address, and the band name the bare windowed array lacks:
                ```python
                >>> import numpy as np
                >>> from pyramids.base.georeference import GeoReference
                >>> from pyramids.dataset import Dataset
                >>> from digitalearth.base.sources.view import SourceView
                >>> from digitalearth.base.spec import DataRef, ViewRequest
                >>> dem = Dataset.from_array(
                ...     np.arange(16.0).reshape(4, 4),
                ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
                ... )
                >>> ref = DataRef.to_object(dem, name="doc-reread")
                >>> view = SourceView.of(ref.open(), ref=ref)
                >>> view.z.values.shape, view.metadata("variable"), view.metadata("band")
                ((4, 4), 'Band_1', 1)
                >>> coarse = view.reread(ViewRequest(budget=4))
                >>> coarse.z.values.shape, coarse.ref.uri, coarse.request.budget
                ((2, 2), 'object:doc-reread', 4)
                >>> coarse.x.values.tolist(), coarse.y.values.tolist()
                ([1.0, 3.0], [3.0, 1.0])

                ```
            - Only the describing keys are carried; `band` belongs to the first read, so it is not:
                ```python
                >>> import numpy as np
                >>> from pyramids.base.georeference import GeoReference
                >>> from pyramids.dataset import Dataset
                >>> from digitalearth.base.sources.view import DESCRIBING_KEYS, SourceView
                >>> from digitalearth.base.spec import DataRef, ViewRequest
                >>> dem = Dataset.from_array(
                ...     np.arange(16.0).reshape(4, 4),
                ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
                ... )
                >>> ref = DataRef.to_object(dem, name="doc-reread-keys")
                >>> coarse = SourceView.of(ref.open(), ref=ref).reread(ViewRequest(budget=4))
                >>> DESCRIBING_KEYS
                ('variable', 'kind', 'standard_name')
                >>> coarse.metadata("variable"), coarse.metadata("kind"), coarse.metadata("band")
                ('Band_1', 'raster', None)

                ```
            - A view built from a held object refuses, and says why:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources import DimensionInfo
                >>> from digitalearth.base.sources.view import SourceView
                >>> from digitalearth.base.spec import ViewRequest
                >>> axis = DimensionInfo(np.array([0.0]), "x")
                >>> SourceView(None, axis, axis).reread(ViewRequest(budget=100))
                Traceback (most recent call last):
                    ...
                RuntimeError: this SourceView has no DataRef, so it cannot be re-read

                ```
        """
        if self._ref is None:
            raise RuntimeError(
                "this SourceView has no DataRef, so it cannot be re-read"
            )
        data = self._ref.open()
        again = self.of(
            data,
            ref=self._ref,
            selection=self._selection,
            request=request,
            crs=self.crs,
        )
        # A windowed read returns a bare array, which carries no band name — so the variable, units and
        # standard_name would be lost by re-reading the very same slice at a different resolution. They
        # describe the data, not the window, so they are carried over where the new read supplied nothing.
        # The result is built as a new view from public properties rather than by writing into `again`'s
        # private state.
        return SourceView(
            again.z,
            again.x,
            again.y,
            again.crs,
            self._carried(self._meta, again._meta),
            again.units if again.units is not None else self.units,
            ref=again.ref,
            selection=again.selection,
            request=again.request,
        )

    @staticmethod
    def _carried(previous: dict, fresh: dict) -> dict:
        """Return a re-read's metadata, with what describes the data filled in from the previous read.

        Args:
            previous: The metadata of the view being re-read.
            fresh: The metadata the new read produced.

        Returns:
            A copy of `fresh` — neither argument is modified — plus each key in :data:`DESCRIBING_KEYS` that
            `previous` holds and the new read did not supply. Every other key is the new read's alone.

            Two rules replace a truthiness test that over-reached. First, only a **named** set of keys is
            carried: the ones that say what the data *is*, which a window cannot change. A key describing
            the read itself is not the old read's to supply. Second, "did not supply" means *absent*, with
            one named exception — the extractor writes ``variable=""`` for a bare array, which is a
            placeholder, not an answer. Testing ``not fresh.get(key)`` instead replaced every falsy value,
            and falsy values carry meaning: the collection extractor writes a **0-based** ``member``, so a
            re-read of member ``0`` would have reported whatever member the previous read held.
        """
        merged = dict(fresh)
        for key in DESCRIBING_KEYS:
            if key not in previous:
                continue
            placeholder = key == "variable" and merged.get(key) == ""
            if key not in merged or placeholder:
                merged[key] = previous[key]
        return merged

    @classmethod
    def of(
        cls,
        data: Any,
        *,
        ref: DataRef | None = None,
        selection: Selection | None = None,
        request: ViewRequest | None = None,
        crs: Any = None,
    ) -> "SourceView":
        """Materialise a view from an opened object, honouring the request where the reader supports it.

        Args:
            data: The opened data — a pyramids ``Dataset``, ``FeatureCollection``, or anything
                :func:`~digitalearth.base.sources.get_source` accepts.
            ref: The reference `data` was opened from, recorded so the view can be re-read.
            selection: Which slice to read. Defaults to the default band. Only its band and its `budget`
                are honoured; the axes it may not name are listed under Raises.
            request: The region/resolution/budget wanted. Applied through pyramids' windowed read when the
                object exposes one (`read_part`) and the request names a region, a budget, or a full canvas
                (both `width` and `height`) — a size with no region windows against the source's own extent.
                A request naming none of those, or one given for an object that cannot window, is recorded
                but not enforced: a reader that cannot window is not a reason to refuse the read. A `budget`
                on `selection` is folded in first, the smaller of the two winning — see :meth:`_budgeted` —
                and the view records the request as it stands after that.
            crs: The CRS to record for the coordinates, passed through to the extractor. A windowed read
                records the window's CRS instead, when the window has one.

        Returns:
            The view, carrying `ref`, the selection, and the request as recorded under `request` above.

        Raises:
            ValueError: if `selection` names a `time`, `level`, `member` or `overview`, or more than one
                band. Nothing but the band and the budget is honoured, so a view that stored the rest would
                report a slice it does not hold; a composite selection is refused for the same reason. Also
                if `request` would window a rotated raster — see :meth:`_refuse_rotated`.
            Exception: whatever the extractor raises for data it cannot read, or pyramids for a window it
                cannot read.

        Examples:
            - A plain array becomes a view with no address, which is a legitimate state:
                ```python
                >>> import numpy as np
                >>> from digitalearth.base.sources.view import SourceView
                >>> view = SourceView.of(np.arange(6.0).reshape(2, 3), crs=4326)
                >>> view.z.values.shape, view.rereadable
                ((2, 3), False)

                ```
            - A budget with no region windows the raster's own extent, labelled with real cell centres:
                ```python
                >>> import numpy as np
                >>> from pyramids.base.georeference import GeoReference
                >>> from pyramids.dataset import Dataset
                >>> from digitalearth.base.sources.view import SourceView
                >>> from digitalearth.base.spec import ViewRequest
                >>> dem = Dataset.from_array(
                ...     np.arange(16.0).reshape(4, 4),
                ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
                ... )
                >>> view = SourceView.of(dem, request=ViewRequest(budget=4))
                >>> view.z.values.shape, view.crs
                ((2, 2), 4326)
                >>> view.x.values.tolist(), view.y.values.tolist()
                ([1.0, 3.0], [3.0, 1.0])

                ```
            - A budget on the selection is applied too, and the tighter of the two budgets wins:
                ```python
                >>> import numpy as np
                >>> from pyramids.base.georeference import GeoReference
                >>> from pyramids.dataset import Dataset
                >>> from digitalearth.base.sources.view import SourceView
                >>> from digitalearth.base.spec import Selection, ViewRequest
                >>> dem = Dataset.from_array(
                ...     np.arange(16.0).reshape(4, 4),
                ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
                ... )
                >>> view = SourceView.of(
                ...     dem, selection=Selection.of(1, budget=4), request=ViewRequest(budget=100)
                ... )
                >>> view.request.budget, view.selection.budget, view.z.values.shape
                (4, 4, (2, 2))

                ```
        """
        from digitalearth.base.sources import get_source

        picked = selection if selection is not None else Selection()
        # Only the band is honoured today: the extractor takes `band=` and nothing else, and the overview is
        # chosen by read_part from the requested size. Storing a selection whose other axes were silently
        # dropped would let a caller read `.selection` back and believe the view holds a slice it does not.
        ignored = [
            name
            for name in ("time", "level", "member", "overview")
            if getattr(picked, name) is not None
        ]
        if ignored:
            raise ValueError(
                f"SourceView cannot yet honour {ignored} on a Selection — only the band is applied, and a "
                "view that stored the rest would report a slice it does not hold. Narrow the data before "
                "building the view, or track the gap in the data tier"
            )
        if picked.is_composite:
            raise ValueError(
                f"SourceView reads one band; got {len(picked.band)}. Use Selection.frames() and build a "
                "view per channel"
            )
        request = cls._budgeted(request, picked.budget)
        windowed, xs, ys, window_crs, window = cls._windowed(data, picked, request)
        source = get_source(
            windowed,
            band=picked.first_band,
            x=xs,
            y=ys,
            crs=window_crs if window_crs is not None else crs,
        )
        return cls(
            source.z,
            source.x,
            source.y,
            source.crs,
            # The extractor's metadata is passed through whole. Rebuilding it as {"variable": ...} dropped
            # `kind` and `standard_name`, and autostyle reads standard_name for the ECMWF-Magics match — so a
            # view silently lost the identity match this wave's auto_cmap consolidation exists to keep.
            dict(source._meta),
            source.units,
            ref=ref,
            selection=picked,
            request=request,
            window=window,
        )

    @staticmethod
    def _budgeted(
        request: ViewRequest | None, budget: int | None
    ) -> ViewRequest | None:
        """Fold a selection's cell budget into the request, so it is applied rather than only stored.

        Args:
            request: What was asked for, or ``None``.
            budget: The budget the selection names, or ``None``.

        Returns:
            `request` unchanged when there is no selection budget, or the request's own budget is already
            the tighter of the two. Otherwise the request with the selection's budget — a fresh
            ``ViewRequest(budget=...)`` when there was no request at all.

            Both are limits, so the smaller wins. The guard in :meth:`of` refuses `time`, `level`, `member`
            and `overview` because a view that stored them would report a slice it does not hold; `budget`
            was neither refused nor applied, so ``.selection.budget`` read back as a limit that had never
            been respected. Honouring it is possible where the others are not, because the request already
            carries the same limit.
        """
        if budget is None:
            return request
        if request is None:
            return ViewRequest(budget=budget)
        if request.budget is not None and request.budget <= budget:
            return request
        return cast(ViewRequest, replace(request, budget=budget))

    @classmethod
    def _shape(cls, request: ViewRequest) -> tuple[int, int]:
        """Return the ``(width, height)`` in cells a windowed read should produce.

        Args:
            request: What was asked for.

        Returns:
            The caller's canvas when they named both dimensions **and it fits the budget** — reading a square
            for a request that says ``800x600`` distorts the aspect ratio of the very canvas those fields
            exist to describe. A request missing either dimension gets a square, which is what a budget
            alone can say: `int(sqrt(budget))` cells on a side (at least one) when it has a budget, and
            :meth:`~digitalearth.base.spec.viewrequest.ViewRequest.side`, with its floor of 64, when it has
            none.

            The canvas is measured in **device** pixels, so a request carrying ``pixel_ratio=2.0`` reads the
            1600x1200 it will draw rather than the 800x600 it is laid out at. That is the whole purpose of
            :attr:`~digitalearth.base.spec.viewrequest.ViewRequest.pixels`, which
            :meth:`~digitalearth.base.spec.viewrequest.ViewRequest.side` already folds the ratio into; reading
            the CSS canvas instead returned a quarter of the detail on a retina display, and did it silently,
            because the result is *under* the budget the caller set.

            The count compared against the budget is the product of the two integers returned — the number of
            cells that will actually be read, which is ``pixels`` up to the rounding of a fractional device
            pixel.

            A canvas over budget is scaled down by :meth:`_fitted`. The budget is the **guarantee**: the
            product of the two numbers returned never exceeds it. The aspect ratio is best effort, held to
            the nearest whole cell, because cells do not come in fractions.
        """
        width, height = request.width, request.height
        if width is None or height is None:
            if request.budget is None:
                side = request.side()
            else:
                # The budget wins over `side()`'s readability floor. Its own docstring calls it the limit "a
                # reader that cannot serve both must respect", and a floor of 64 turned a budget of 16 into
                # 4,096 cells. A caller who sets a budget that small has asked for a thumbnail.
                side = max(1, int(request.budget**0.5))
            return side, side
        columns = max(1, int(width * request.pixel_ratio))
        rows = max(1, int(height * request.pixel_ratio))
        if request.within_budget(columns * rows):
            return columns, rows
        return cls._fitted(columns, rows, request.budget)  # type: ignore[arg-type]

    @staticmethod
    def _fitted(width: int, height: int, budget: int) -> tuple[int, int]:
        """Shrink a canvas until it fits `budget` cells, keeping its shape as nearly as whole cells allow.

        Args:
            width: The canvas width in cells.
            height: The canvas height in cells.
            budget: The greatest number of cells that may be returned.

        Returns:
            A ``(width, height)`` whose product is **always** ``<= budget``, and which is within one cell
            per axis of the exactly-scaled canvas whenever both axes survive the scaling.

            Truncating each axis can only go under the scale factor, so the product of the two truncated
            axes is under the budget by construction. What is *not* safe is lifting a truncated axis back
            to one afterwards, which is what this replaces: for an elongated canvas the short axis rounds to
            zero, and restoring it multiplies the long axis straight back through the limit. Measured on the
            old spelling, ``10000x1`` under a budget of ``100`` returned ``1000x1`` — ten times the limit the
            budget exists to impose, on exactly the shapes it matters for (a cross-section strip, a profile).

            A canvas that elongated gets its long axis capped at the budget and its short axis set to one,
            which is the most detail the limit can buy.
        """
        scale = (budget / (width * height)) ** 0.5
        columns, rows = int(width * scale), int(height * scale)
        if columns and rows:
            return columns, rows
        if width >= height:
            return max(1, min(width, budget)), 1
        return 1, max(1, min(height, budget))

    @staticmethod
    def _window_for(data: Any, request: ViewRequest) -> Bounds | None:
        """Return the rectangle to read, in the CRS the data's own cells are measured in.

        Two questions in one, kept apart from the reading: *which* rectangle, and *whose* CRS it is
        described in. `read_part` answers in the dataset's CRS, so a window given in another one is
        converted before it is read rather than after.

        Args:
            data: The opened object.
            request: What was asked for.

        Returns:
            The window, or `None` when there is no rectangle to name: the request gives no region, and
            either names no usable size (no budget, and not both of width and height) or meets an object
            with no extent of its own to window that size against.
        """
        bbox = request.as_bbox()
        if bbox is not None:
            window = Bounds.from_bbox(list(bbox), crs=request.crs)
            target = getattr(data, "epsg", None) or getattr(data, "crs", None)
            if request.crs is not None and target is not None:
                window = window.to_crs(target)
            return window
        # A size with no region still has to be honoured: the object *can* window, so skipping here
        # returned the whole raster — blowing a budget silently, or handing a caller who asked for a 4x3
        # canvas all 13x14 cells. The source's own extent is the region.
        #
        # Either spelling, and a canonical name that raises counts as absent — see `_source_extent`. A
        # missing extent returns None below and skips the window entirely.
        source_bbox = _source_extent(data)
        # A full canvas counts; half of one does not. `_shape` cannot use a lone width, so windowing on
        # one read a 64x64 floor square that honoured nothing the caller named.
        canvas = request.width is not None and request.height is not None
        if source_bbox is None or (request.budget is None and not canvas):
            return None
        return Bounds.from_bbox(list(source_bbox), crs=getattr(data, "epsg", None))

    @classmethod
    def _windowed(
        cls, data: Any, selection: Selection, request: ViewRequest | None
    ) -> tuple[Any, Any | None, Any | None, Any | None, Bounds | None]:
        """Narrow `data` to the requested window, and say where the window's cells are.

        Args:
            data: The opened object.
            selection: Which slice is wanted.
            request: What was asked for, or ``None``.

        Returns:
            A ``(data, x, y, crs, window)`` tuple. Unwindowed, that is `data` unchanged and four ``None``s:
            when there is no request, when the object has no `read_part`, or when :meth:`_window_for` can
            name no rectangle to read.

            Windowed, the window is first grown to whole source pixels by :meth:`_aligned`, and the result is
            the **array** ``read_part`` returns for it plus the coordinates of its cell centres and the CRS
            they are in. The coordinates have to be computed here because ``read_part`` is an array
            reader, not a dataset reader: pyramids' own docstring says *"Pixel values only — no transform,
            bounds, or CRS is attached"*. Without them the extractor falls back to ``np.arange`` axes and the
            view claims a projected CRS while holding pixel indices.

        Raises:
            ValueError: if the source is a rotated raster — see :meth:`_refuse_rotated`.
            Exception: whatever pyramids raises for a window it cannot read.
        """
        nothing = (data, None, None, None, None)
        if request is None or not hasattr(data, "read_part"):
            return nothing
        window = cls._window_for(data, request)
        if window is None:
            return nothing
        # Snap the window outward to whole source pixels *before* reading. read_part does this internally
        # (floor/ceil through world_to_pixel) and returns a buffer spanning the snapped window — so labelling
        # the result from the requested bbox misplaces every cell by up to one source pixel per edge, worst
        # on exactly the zoomed-out tiles this exists for. Aligning the request makes the snap a no-op, so
        # the window asked for and the window read are the same rectangle.
        cls._refuse_rotated(data)
        window = cls._aligned(window, data)
        width, height = cls._native(window, data, *cls._shape(request))
        band = selection.first_band
        try:
            array = cls._read_window(data, window, width, height, band)
        # A viewport panned off the data is a place with nothing in it, not a failed read: the canvas comes
        # back empty, as it does for a window over a hole in the raster, and the map keeps panning.
        except Exception as error:  # noqa: BLE001
            if not _off_source(error):
                raise
            array = np.full((height, width), np.nan)
        rows, columns = array.shape[-2], array.shape[-1]
        xs, ys = cls._axes(window, rows, columns, data)
        return array, xs, ys, window.crs, window

    @staticmethod
    def _missing(data: Any, band: int) -> float | None:
        """Return the value a windowed read of this band uses for "no data", in the units it returns.

        Args:
            data: The raster being read.
            band: The 1-based band.

        Returns:
            The sentinel as the read returns it — scaled and offset when the band is packed, since a windowed
            read unpacks its values — or `None` when the band declares none.

        Note:
            A native-resolution read masks through pyramids (`read_array(masked=True)`), which is the reliable
            way and the one :func:`~digitalearth.base.arrays.read_masked_band` uses. A decimated read cannot:
            pyramids refuses `masked=True` together with `out_shape=`, so until it does not
            (serapeum-org/pyramids#1156) a viewport read compares against the sentinel itself.
        """
        sentinels = getattr(data, "no_data_value", None)
        if not sentinels or band - 1 >= len(sentinels):
            return None
        sentinel = sentinels[band - 1]
        if sentinel is None:
            return None
        scales = getattr(data, "scale", None) or [1.0]
        offsets = getattr(data, "offset", None) or [0.0]
        index = band - 1 if band - 1 < len(scales) else 0
        scale = scales[index] if scales[index] is not None else 1.0
        offset = (offsets[index] if index < len(offsets) else 0.0) or 0.0
        return float(sentinel) * float(scale) + float(offset)

    @classmethod
    def _unmasked(cls, array: np.ndarray, data: Any, band: int) -> np.ndarray:
        """Return a windowed read as floats, with its nodata cells set to `NaN`.

        Args:
            array: What the windowed read returned.
            data: The raster it was read from.
            band: The 1-based band.

        Returns:
            A `float64` array. Without this a nodata cell reaches the colour range as its sentinel —
            -3.4e38 on `acc4000.tif` — which flattens every real value onto one end of the ramp.
        """
        values = np.asarray(array, dtype="float64")
        sentinel = cls._missing(data, band)
        if sentinel is not None:
            values = np.where(values == sentinel, np.nan, values)
        return values

    @classmethod
    def _read_window(
        cls, data: Any, window: Bounds, width: int, height: int, band: int
    ) -> np.ndarray:
        """Read one window of a raster as floats, with its missing cells as `NaN`.

        Args:
            data: The raster to read.
            window: The region, snapped to source pixels and in the source's CRS.
            width: Cells across the canvas.
            height: Cells down it.
            band: The 1-based band.

        Returns:
            A `float64` array of `(height, width)`.

        Note:
            **Two reads, one meaning.** At full resolution the window is read with `masked=True`, so pyramids
            decides what is missing — the only reliable answer, and the one a packed band needs, since its
            nodata cells unpack to ordinary-looking numbers. Decimated, that is not available (pyramids
            refuses `masked=True` with `out_shape=`, serapeum-org/pyramids#1156), so the read is compared
            against the sentinel instead. The difference is visible: on `acc4000.tif` the resampler carries
            values across the nodata boundary, so a decimated frame has fewer missing cells than the raster
            does. Reading at full resolution when the window allows it is what keeps a zoomed-in frame honest.
        """
        native = cls._native_cells(window, data)
        if native is not None and (width, height) == native:
            values = np.ma.asarray(
                data.read_array(band=band - 1, bbox=window.as_bbox(), masked=True)
            ).astype("float64")
            return np.ma.filled(values, np.nan)
        return cls._unmasked(
            data.read_part(
                bbox=window.as_bbox(),
                dst_width=width,
                dst_height=height,
                bbox_crs=window.crs,
                band=band - 1,  # pyramids' windowed read is 0-based
            ),
            data,
            band,
        )

    @staticmethod
    def _native(window: Bounds, data: Any, width: int, height: int) -> tuple[int, int]:
        """Return the canvas, never asking for more cells than the window holds at full resolution.

        Args:
            window: The region being read, in the source's CRS.
            data: The raster being read.
            width: The canvas width the budget allowed.
            height: The canvas height it allowed.

        Returns:
            `(width, height)`, each capped at the number of source cells the window spans. Reading 100x100
            cells from a 13x14 raster is interpolation dressed as data: it costs more, says no more, and is a
            picture of the resampler rather than of the raster.
        """
        cells = SourceView._native_cells(window, data)
        if cells is None:
            return width, height
        return min(width, cells[0]), min(height, cells[1])

    @staticmethod
    def _native_cells(window: Bounds, data: Any) -> tuple[int, int] | None:
        """Return how many source cells a window spans, across and down.

        Args:
            window: The region, in the source's CRS.
            data: The raster being read.

        Returns:
            `(across, down)`, or `None` when the source does not say what a cell measures — a reader with no
            geotransform, which is windowed exactly as it was asked.

            The two spacings are read separately. pyramids documents `Dataset.cell_size` as the *magnitude of
            the x pixel size*, so using it for both axes counted the rows of any grid whose cells are not
            square as if they were `dy/dx` times as many: a 20x10 raster of 1 x 4 m cells reported 20 x 40,
            which broke `_native`'s promise never to ask for more cells than the window holds and, with it,
            the native-resolution test that picks pyramids' reliable masking path (review M3).
        """
        across_step, down_step = SourceView._spacing(data)
        if not across_step or not down_step:
            return None
        xmin, ymin, xmax, ymax = window.as_bbox()
        across = max(1, int(round((xmax - xmin) / across_step)))
        down = max(1, int(round((ymax - ymin) / down_step)))
        return across, down

    @staticmethod
    def _spacing(data: Any) -> tuple[float | None, float | None]:
        """Return what one cell of `data` measures, across and down.

        Args:
            data: The raster being read.

        Returns:
            `(dx, dy)` as positive magnitudes, from the source's geotransform where it has one — which is the
            only place the two are stated separately — and from the square `cell_size` for both when it does
            not. `(None, None)` for a source that says neither.
        """
        # Through `_grid`, which already reads the geotransform and rejects a zero step: two readings of
        # one thing, with guards that disagreed, is how they drift apart (review N9).
        grid = SourceView._grid(data)
        if grid is not None:
            _, step_x, _, step_y = grid
            return abs(float(step_x)), abs(float(step_y))
        cell = getattr(data, "cell_size", None)
        if not cell:
            return None, None
        square = abs(float(cell))
        return square, square

    @classmethod
    def _aligned(cls, window: Bounds, data: Any) -> Bounds:
        """Grow `window` outward to the source's pixel edges, so a read of it needs no snapping.

        Args:
            window: The window wanted, in the source's CRS.
            data: The object being read, for its geotransform.

        Returns:
            The smallest pixel-aligned window containing `window`, or `window` itself when :meth:`_grid`
            finds no grid to align against (no geotransform, or a zero step).

            On an axis-aligned grid this is the same outward snap ``read_part`` performs internally — the
            floor and ceiling of the corners' pixel coordinates. Doing it here rather than reproducing its
            arithmetic afterwards is what keeps the labels honest: the caller's bbox and the rectangle
            actually read become one rectangle, so there is no second window to get wrong. A rotated grid is
            snapped as if unrotated, because :meth:`_grid` drops the rotation terms.

            The long-term answer is for the reader to report the window it actually read alongside the
            array, which is https://github.com/serapeum-org/pyramids/issues/1149.
        """
        transform = cls._grid(data)
        if transform is None:
            return window
        origin_x, pixel_w, origin_y, pixel_h = transform
        xmin, ymin, xmax, ymax = window.as_bbox()
        left, right = cls._snapped(xmin, xmax, origin_x, pixel_w)
        bottom, top = cls._snapped(ymin, ymax, origin_y, pixel_h)
        return Bounds(left, bottom, right, top, window.crs)

    @staticmethod
    def _refuse_rotated(data: Any) -> None:
        """Refuse a windowed read of a raster whose geotransform carries rotation.

        Args:
            data: The object about to be windowed.

        Raises:
            ValueError: if `geotransform[2]` or `geotransform[4]` is non-zero.

            A rotated raster's cells do not lie along one x axis and one y axis, so no pair of 1-D
            coordinate arrays can label a window of it — and the axis-aligned bbox `read_part` takes does
            not describe the rectangle of cells it returns. Windowing one anyway came back silently wrong:
            on geotransform `(0, 1, 0.5, 8, 0, -1)` a 4x4 read labelled `x = [1.5, 2.5, 3.5, 4.5]` held
            `[-9999.0, 30.0, 30.5, 31.17]` — nodata and interpolated values under clean labels. Refused
            here, like the selection axes :meth:`of` cannot honour, rather than drawn wrong.
        """
        transform = getattr(data, "geotransform", None)
        if transform and len(transform) >= 6 and (transform[2] or transform[4]):
            raise ValueError(
                f"SourceView cannot window a rotated raster (geotransform {tuple(transform)}): its cells do "
                "not lie along one x and one y axis, so a window of it has no coordinates to label. Read it "
                "without a request instead"
            )

    @staticmethod
    def _grid(data: Any) -> tuple[float, float, float, float] | None:
        """Return the source's ``(origin_x, step_x, origin_y, step_y)``, or ``None`` if it has no grid.

        Args:
            data: The object being read.

        Returns:
            The four geotransform entries that place a cell on an axis-aligned grid. The rotation terms
            (`geotransform[2]` and `geotransform[4]`) are not part of the answer: a windowed read refuses a
            rotated raster first, in :meth:`_refuse_rotated`, so by the time this is consulted they are zero.
            ``None`` when there is no geotransform, it has fewer than six entries, or a step is zero and the
            grid degenerate.
        """
        transform = getattr(data, "geotransform", None)
        if not transform or len(transform) < 6:
            return None
        origin_x, pixel_w, _, origin_y, _, pixel_h = transform[:6]
        if not pixel_w or not pixel_h:
            return None
        return float(origin_x), float(pixel_w), float(origin_y), float(pixel_h)

    @staticmethod
    def _snapped(
        low: float, high: float, origin: float, step: float
    ) -> tuple[float, float]:
        """Widen one axis of a window out to the cell edges that enclose it.

        Args:
            low: The lower world coordinate of the window on this axis.
            high: The upper world coordinate.
            origin: The geotransform's origin for this axis.
            step: The geotransform's cell step, which may be negative.

        Returns:
            The ``(low, high)`` pair of enclosing cell edges, in ascending world order.

            The floor and the ceiling are taken in **pixel** space and only then converted back, because a
            negative step reverses which end of the window each one belongs to. Flooring the low world
            coordinate directly — the obvious spelling — snaps *inward* on such an axis, which reads as a
            correct fix and silently crops.
        """
        first = (low - origin) / step
        second = (high - origin) / step
        edges = (
            origin + float(np.floor(min(first, second))) * step,
            origin + float(np.ceil(max(first, second))) * step,
        )
        return min(edges), max(edges)

    @classmethod
    def _axes(
        cls, window: Bounds, rows: int, columns: int, data: Any
    ) -> tuple[Any, Any]:
        """Return the cell-centre coordinates of a windowed read, in the order its rows and columns come.

        Args:
            window: The pixel-aligned window that was read.
            rows: How many rows came back.
            columns: How many columns.
            data: The object that was read, for its geotransform.

        Returns:
            An ``(x, y)`` pair of centre coordinates.

            Cell centres, not edges: an extractor's axes name where each cell *is*, and a half-cell offset
            is the difference between a raster drawn correctly and one drawn half a pixel adrift.

            The **direction** of each axis comes from the geotransform's step signs, because ``read_part``
            returns rows and columns in storage order. A raster stored south-up (``step_y > 0``) therefore
            hands back ascending y, and one stored east-left (``step_x < 0``) descending x; labelling
            either the usual way round renders it mirrored, silently, since a flipped raster draws
            perfectly happily. With no geotransform to consult the north-up, west-left convention is
            assumed, which is the transform pyramids builds from a `GeoReference` corner and cell size.

        Note:
            Only this windowed path derives the y direction. pyramids' own ``Dataset.y`` measures rows
            downward from ``geotransform[3]`` whatever the sign of ``geotransform[5]``, so a south-up source
            read through any other extractor is labelled outside its own extent (a raster spanning y 0..8
            reports ``y = [-0.5, -1.5, ...]``), and its ``bbox`` comes back with ``ymin > ymax``. That is
            https://github.com/serapeum-org/pyramids/issues/1148; this method only avoids adding a second,
            differently-wrong answer.
        """
        xmin, ymin, xmax, ymax = window.as_bbox()
        grid = cls._grid(data)
        east_left = grid is not None and grid[1] < 0
        south_up = grid is not None and grid[3] > 0
        x_from, x_to = (xmax, xmin) if east_left else (xmin, xmax)
        y_from, y_to = (ymin, ymax) if south_up else (ymax, ymin)
        xs = x_from + (np.arange(columns) + 0.5) * (x_to - x_from) / columns
        ys = y_from + (np.arange(rows) + 0.5) * (y_to - y_from) / rows
        return xs, ys

ref property #

Where this view's data came from, or None when it was built from a held object.

Returns:

Type Description
DataRef | None

The reference. None is not a defect — a caller may pass a Dataset they built in a notebook,

DataRef | None

and that view is perfectly usable; it just cannot be re-read from an address it never had.

Examples:

  • The address a view was read from:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import DataRef
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> SourceView(None, axis, axis, ref=DataRef("dem.tif")).ref.uri
    'dem.tif'
    

request property #

The request this view answered, or None when it was not read against one.

Returns:

Type Description
ViewRequest | None

The request, kept so a caller can compare what it asked for with what it got.

Examples:

  • A view not read against a request says so:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> SourceView(None, axis, axis).request is None
    True
    

rereadable property #

Whether this view can be read again.

Returns:

Name Type Description
bool

True when the view carries a reference. A view built from a held object answers False,

and bool

meth:reread says so rather than failing deep inside a reader.

Examples:

  • A view with no reference knows it cannot be re-read:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> SourceView(None, axis, axis).rereadable
    False
    

selection property #

Which slice of the source this view holds.

Returns:

Type Description
Selection

The selection. Defaults to the default band rather than None, so a caller never has to guard

Selection

before narrowing it.

Examples:

  • A view with no selection still answers with one:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> SourceView(None, axis, axis).selection.first_band
    1
    

window property #

The rectangle this view's cells cover, for a windowed read.

Returns:

Type Description
Bounds | None

The window read, in the CRS its cells are measured in, or None when the whole source was

Bounds | None

read and the axes describe it themselves.

Examples:

  • A view of a whole source names no window:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> axis = DimensionInfo(np.array([0.0, 1.0]), "x")
    >>> SourceView(None, axis, axis, crs=4326).window is None
    True
    

of(data, *, ref=None, selection=None, request=None, crs=None) classmethod #

Materialise a view from an opened object, honouring the request where the reader supports it.

Parameters:

Name Type Description Default
data Any

The opened data — a pyramids Dataset, FeatureCollection, or anything :func:~digitalearth.base.sources.get_source accepts.

required
ref DataRef | None

The reference data was opened from, recorded so the view can be re-read.

None
selection Selection | None

Which slice to read. Defaults to the default band. Only its band and its budget are honoured; the axes it may not name are listed under Raises.

None
request ViewRequest | None

The region/resolution/budget wanted. Applied through pyramids' windowed read when the object exposes one (read_part) and the request names a region, a budget, or a full canvas (both width and height) — a size with no region windows against the source's own extent. A request naming none of those, or one given for an object that cannot window, is recorded but not enforced: a reader that cannot window is not a reason to refuse the read. A budget on selection is folded in first, the smaller of the two winning — see :meth:_budgeted — and the view records the request as it stands after that.

None
crs Any

The CRS to record for the coordinates, passed through to the extractor. A windowed read records the window's CRS instead, when the window has one.

None

Returns:

Type Description
SourceView

The view, carrying ref, the selection, and the request as recorded under request above.

Raises:

Type Description
ValueError

if selection names a time, level, member or overview, or more than one band. Nothing but the band and the budget is honoured, so a view that stored the rest would report a slice it does not hold; a composite selection is refused for the same reason. Also if request would window a rotated raster — see :meth:_refuse_rotated.

Exception

whatever the extractor raises for data it cannot read, or pyramids for a window it cannot read.

Examples:

  • A plain array becomes a view with no address, which is a legitimate state:
    >>> import numpy as np
    >>> from digitalearth.base.sources.view import SourceView
    >>> view = SourceView.of(np.arange(6.0).reshape(2, 3), crs=4326)
    >>> view.z.values.shape, view.rereadable
    ((2, 3), False)
    
  • A budget with no region windows the raster's own extent, labelled with real cell centres:
    >>> import numpy as np
    >>> from pyramids.base.georeference import GeoReference
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import ViewRequest
    >>> dem = Dataset.from_array(
    ...     np.arange(16.0).reshape(4, 4),
    ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
    ... )
    >>> view = SourceView.of(dem, request=ViewRequest(budget=4))
    >>> view.z.values.shape, view.crs
    ((2, 2), 4326)
    >>> view.x.values.tolist(), view.y.values.tolist()
    ([1.0, 3.0], [3.0, 1.0])
    
  • A budget on the selection is applied too, and the tighter of the two budgets wins:
    >>> import numpy as np
    >>> from pyramids.base.georeference import GeoReference
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import Selection, ViewRequest
    >>> dem = Dataset.from_array(
    ...     np.arange(16.0).reshape(4, 4),
    ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
    ... )
    >>> view = SourceView.of(
    ...     dem, selection=Selection.of(1, budget=4), request=ViewRequest(budget=100)
    ... )
    >>> view.request.budget, view.selection.budget, view.z.values.shape
    (4, 4, (2, 2))
    
Source code in src/digitalearth/base/sources/view.py
@classmethod
def of(
    cls,
    data: Any,
    *,
    ref: DataRef | None = None,
    selection: Selection | None = None,
    request: ViewRequest | None = None,
    crs: Any = None,
) -> "SourceView":
    """Materialise a view from an opened object, honouring the request where the reader supports it.

    Args:
        data: The opened data — a pyramids ``Dataset``, ``FeatureCollection``, or anything
            :func:`~digitalearth.base.sources.get_source` accepts.
        ref: The reference `data` was opened from, recorded so the view can be re-read.
        selection: Which slice to read. Defaults to the default band. Only its band and its `budget`
            are honoured; the axes it may not name are listed under Raises.
        request: The region/resolution/budget wanted. Applied through pyramids' windowed read when the
            object exposes one (`read_part`) and the request names a region, a budget, or a full canvas
            (both `width` and `height`) — a size with no region windows against the source's own extent.
            A request naming none of those, or one given for an object that cannot window, is recorded
            but not enforced: a reader that cannot window is not a reason to refuse the read. A `budget`
            on `selection` is folded in first, the smaller of the two winning — see :meth:`_budgeted` —
            and the view records the request as it stands after that.
        crs: The CRS to record for the coordinates, passed through to the extractor. A windowed read
            records the window's CRS instead, when the window has one.

    Returns:
        The view, carrying `ref`, the selection, and the request as recorded under `request` above.

    Raises:
        ValueError: if `selection` names a `time`, `level`, `member` or `overview`, or more than one
            band. Nothing but the band and the budget is honoured, so a view that stored the rest would
            report a slice it does not hold; a composite selection is refused for the same reason. Also
            if `request` would window a rotated raster — see :meth:`_refuse_rotated`.
        Exception: whatever the extractor raises for data it cannot read, or pyramids for a window it
            cannot read.

    Examples:
        - A plain array becomes a view with no address, which is a legitimate state:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources.view import SourceView
            >>> view = SourceView.of(np.arange(6.0).reshape(2, 3), crs=4326)
            >>> view.z.values.shape, view.rereadable
            ((2, 3), False)

            ```
        - A budget with no region windows the raster's own extent, labelled with real cell centres:
            ```python
            >>> import numpy as np
            >>> from pyramids.base.georeference import GeoReference
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.base.sources.view import SourceView
            >>> from digitalearth.base.spec import ViewRequest
            >>> dem = Dataset.from_array(
            ...     np.arange(16.0).reshape(4, 4),
            ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
            ... )
            >>> view = SourceView.of(dem, request=ViewRequest(budget=4))
            >>> view.z.values.shape, view.crs
            ((2, 2), 4326)
            >>> view.x.values.tolist(), view.y.values.tolist()
            ([1.0, 3.0], [3.0, 1.0])

            ```
        - A budget on the selection is applied too, and the tighter of the two budgets wins:
            ```python
            >>> import numpy as np
            >>> from pyramids.base.georeference import GeoReference
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.base.sources.view import SourceView
            >>> from digitalearth.base.spec import Selection, ViewRequest
            >>> dem = Dataset.from_array(
            ...     np.arange(16.0).reshape(4, 4),
            ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
            ... )
            >>> view = SourceView.of(
            ...     dem, selection=Selection.of(1, budget=4), request=ViewRequest(budget=100)
            ... )
            >>> view.request.budget, view.selection.budget, view.z.values.shape
            (4, 4, (2, 2))

            ```
    """
    from digitalearth.base.sources import get_source

    picked = selection if selection is not None else Selection()
    # Only the band is honoured today: the extractor takes `band=` and nothing else, and the overview is
    # chosen by read_part from the requested size. Storing a selection whose other axes were silently
    # dropped would let a caller read `.selection` back and believe the view holds a slice it does not.
    ignored = [
        name
        for name in ("time", "level", "member", "overview")
        if getattr(picked, name) is not None
    ]
    if ignored:
        raise ValueError(
            f"SourceView cannot yet honour {ignored} on a Selection — only the band is applied, and a "
            "view that stored the rest would report a slice it does not hold. Narrow the data before "
            "building the view, or track the gap in the data tier"
        )
    if picked.is_composite:
        raise ValueError(
            f"SourceView reads one band; got {len(picked.band)}. Use Selection.frames() and build a "
            "view per channel"
        )
    request = cls._budgeted(request, picked.budget)
    windowed, xs, ys, window_crs, window = cls._windowed(data, picked, request)
    source = get_source(
        windowed,
        band=picked.first_band,
        x=xs,
        y=ys,
        crs=window_crs if window_crs is not None else crs,
    )
    return cls(
        source.z,
        source.x,
        source.y,
        source.crs,
        # The extractor's metadata is passed through whole. Rebuilding it as {"variable": ...} dropped
        # `kind` and `standard_name`, and autostyle reads standard_name for the ECMWF-Magics match — so a
        # view silently lost the identity match this wave's auto_cmap consolidation exists to keep.
        dict(source._meta),
        source.units,
        ref=ref,
        selection=picked,
        request=request,
        window=window,
    )

reread(request) #

Read the same slice again, for a different region or resolution.

This is what the address is for. The view re-opens its own :class:~digitalearth.base.spec.dataref.DataRef, applies its own :class:~digitalearth.base.spec.selection.Selection, and asks the reader for what request wants — the loop interactive/raster.py currently drives by hand at one call site.

Parameters:

Name Type Description Default
request ViewRequest

The region, resolution and budget wanted.

required

Returns:

Type Description
SourceView

A new view of the same slice, carrying the same reference and selection plus the request it

SourceView

answered. Its metadata is the new read's, with each key in :data:DESCRIBING_KEYS the new read

SourceView

did not supply filled in from this view — see :meth:_carried — and its units are this view's

SourceView

when the new read found none.

Raises:

Type Description
RuntimeError

if this view has no reference to read from — see :attr:rereadable. Raised here, naming the view, rather than surfacing as an AttributeError from inside a reader. Build the view from a DataRef, or register the object with :meth:~digitalearth.base.spec.dataref.DataRef.to_object, to make it re-readable.

KeyError

if the reference no longer resolves — an object: id not registered in this process, or a scheme no resolver handles. Raised by :meth:~digitalearth.base.spec.dataref.DataRef.open.

ValueError

if this view's selection is one :meth:of refuses, or the source is a rotated raster, which no window can be labelled for.

Examples:

  • Re-reading within a budget keeps the address, and the band name the bare windowed array lacks:
    >>> import numpy as np
    >>> from pyramids.base.georeference import GeoReference
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import DataRef, ViewRequest
    >>> dem = Dataset.from_array(
    ...     np.arange(16.0).reshape(4, 4),
    ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
    ... )
    >>> ref = DataRef.to_object(dem, name="doc-reread")
    >>> view = SourceView.of(ref.open(), ref=ref)
    >>> view.z.values.shape, view.metadata("variable"), view.metadata("band")
    ((4, 4), 'Band_1', 1)
    >>> coarse = view.reread(ViewRequest(budget=4))
    >>> coarse.z.values.shape, coarse.ref.uri, coarse.request.budget
    ((2, 2), 'object:doc-reread', 4)
    >>> coarse.x.values.tolist(), coarse.y.values.tolist()
    ([1.0, 3.0], [3.0, 1.0])
    
  • Only the describing keys are carried; band belongs to the first read, so it is not:
    >>> import numpy as np
    >>> from pyramids.base.georeference import GeoReference
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.base.sources.view import DESCRIBING_KEYS, SourceView
    >>> from digitalearth.base.spec import DataRef, ViewRequest
    >>> dem = Dataset.from_array(
    ...     np.arange(16.0).reshape(4, 4),
    ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
    ... )
    >>> ref = DataRef.to_object(dem, name="doc-reread-keys")
    >>> coarse = SourceView.of(ref.open(), ref=ref).reread(ViewRequest(budget=4))
    >>> DESCRIBING_KEYS
    ('variable', 'kind', 'standard_name')
    >>> coarse.metadata("variable"), coarse.metadata("kind"), coarse.metadata("band")
    ('Band_1', 'raster', None)
    
  • A view built from a held object refuses, and says why:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo
    >>> from digitalearth.base.sources.view import SourceView
    >>> from digitalearth.base.spec import ViewRequest
    >>> axis = DimensionInfo(np.array([0.0]), "x")
    >>> SourceView(None, axis, axis).reread(ViewRequest(budget=100))
    Traceback (most recent call last):
        ...
    RuntimeError: this SourceView has no DataRef, so it cannot be re-read
    
Source code in src/digitalearth/base/sources/view.py
def reread(self, request: ViewRequest) -> "SourceView":
    """Read the same slice again, for a different region or resolution.

    This is what the address is for. The view re-opens its own
    :class:`~digitalearth.base.spec.dataref.DataRef`, applies its own
    :class:`~digitalearth.base.spec.selection.Selection`, and asks the reader for what `request` wants —
    the loop `interactive/raster.py` currently drives by hand at one call site.

    Args:
        request: The region, resolution and budget wanted.

    Returns:
        A new view of the same slice, carrying the same reference and selection plus the request it
        answered. Its metadata is the new read's, with each key in :data:`DESCRIBING_KEYS` the new read
        did not supply filled in from this view — see :meth:`_carried` — and its `units` are this view's
        when the new read found none.

    Raises:
        RuntimeError: if this view has no reference to read from — see :attr:`rereadable`. Raised here,
            naming the view, rather than surfacing as an `AttributeError` from inside a reader. Build the
            view from a `DataRef`, or register the object with
            :meth:`~digitalearth.base.spec.dataref.DataRef.to_object`, to make it re-readable.
        KeyError: if the reference no longer resolves — an `object:` id not registered in this process,
            or a scheme no resolver handles. Raised by
            :meth:`~digitalearth.base.spec.dataref.DataRef.open`.
        ValueError: if this view's selection is one :meth:`of` refuses, or the source is a rotated raster,
            which no window can be labelled for.

    Examples:
        - Re-reading within a budget keeps the address, and the band name the bare windowed array lacks:
            ```python
            >>> import numpy as np
            >>> from pyramids.base.georeference import GeoReference
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.base.sources.view import SourceView
            >>> from digitalearth.base.spec import DataRef, ViewRequest
            >>> dem = Dataset.from_array(
            ...     np.arange(16.0).reshape(4, 4),
            ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
            ... )
            >>> ref = DataRef.to_object(dem, name="doc-reread")
            >>> view = SourceView.of(ref.open(), ref=ref)
            >>> view.z.values.shape, view.metadata("variable"), view.metadata("band")
            ((4, 4), 'Band_1', 1)
            >>> coarse = view.reread(ViewRequest(budget=4))
            >>> coarse.z.values.shape, coarse.ref.uri, coarse.request.budget
            ((2, 2), 'object:doc-reread', 4)
            >>> coarse.x.values.tolist(), coarse.y.values.tolist()
            ([1.0, 3.0], [3.0, 1.0])

            ```
        - Only the describing keys are carried; `band` belongs to the first read, so it is not:
            ```python
            >>> import numpy as np
            >>> from pyramids.base.georeference import GeoReference
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.base.sources.view import DESCRIBING_KEYS, SourceView
            >>> from digitalearth.base.spec import DataRef, ViewRequest
            >>> dem = Dataset.from_array(
            ...     np.arange(16.0).reshape(4, 4),
            ...     geo_ref=GeoReference(top_left_corner=(0.0, 4.0), cell_size=1.0, epsg=4326),
            ... )
            >>> ref = DataRef.to_object(dem, name="doc-reread-keys")
            >>> coarse = SourceView.of(ref.open(), ref=ref).reread(ViewRequest(budget=4))
            >>> DESCRIBING_KEYS
            ('variable', 'kind', 'standard_name')
            >>> coarse.metadata("variable"), coarse.metadata("kind"), coarse.metadata("band")
            ('Band_1', 'raster', None)

            ```
        - A view built from a held object refuses, and says why:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo
            >>> from digitalearth.base.sources.view import SourceView
            >>> from digitalearth.base.spec import ViewRequest
            >>> axis = DimensionInfo(np.array([0.0]), "x")
            >>> SourceView(None, axis, axis).reread(ViewRequest(budget=100))
            Traceback (most recent call last):
                ...
            RuntimeError: this SourceView has no DataRef, so it cannot be re-read

            ```
    """
    if self._ref is None:
        raise RuntimeError(
            "this SourceView has no DataRef, so it cannot be re-read"
        )
    data = self._ref.open()
    again = self.of(
        data,
        ref=self._ref,
        selection=self._selection,
        request=request,
        crs=self.crs,
    )
    # A windowed read returns a bare array, which carries no band name — so the variable, units and
    # standard_name would be lost by re-reading the very same slice at a different resolution. They
    # describe the data, not the window, so they are carried over where the new read supplied nothing.
    # The result is built as a new view from public properties rather than by writing into `again`'s
    # private state.
    return SourceView(
        again.z,
        again.x,
        again.y,
        again.crs,
        self._carried(self._meta, again._meta),
        again.units if again.units is not None else self.units,
        ref=again.ref,
        selection=again.selection,
        request=again.request,
    )

LegendSpec — a legend derived from what was drawn#

Every tier built one its own way, and nothing structurally tied a swatch to the colour actually drawn. Deriving the rows from the resolved Scale makes the agreement a construction rather than a maintenance task.

digitalearth.base.spec.legend.LegendSpec dataclass #

A legend as a value: what it is called, what its rows are, and how it is laid out.

Attributes:

Name Type Description
entries tuple[LegendEntry, ...]

The rows, in the order they are drawn.

kind str

"categorical", "graduated" or "continuous" — the three the tiers already distinguish, kept because a ramp is drawn as a bar and the other two as swatches.

title str | None

The legend's heading, usually the column name.

units str | None

Unit string appended to the labels, or shown once as a subtitle.

format str | None

Format spec for numeric labels, e.g. ".1f".

orientation str

"vertical" or "horizontal".

Examples:

  • A categorical legend takes its colours from the scale that drew them:
    >>> from digitalearth.base.spec import LegendSpec, Scale
    >>> scale = Scale.categorical(["land", "sea"], ["#8b4513", "#1e90ff"])
    >>> legend = LegendSpec.from_scale(scale, title="cover")
    >>> [(e.label, e.color) for e in legend.entries]
    [('land', '#8b4513'), ('sea', '#1e90ff')]
    
  • A classified scale becomes one row per class, labelled by the range it covers:
    >>> from digitalearth.base.spec import LegendSpec, Scale
    >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
    >>> legend = LegendSpec.from_scale(scale, colors=["#eee", "#111"])
    >>> len(legend.entries), legend.kind
    (2, 'graduated')
    
Source code in src/digitalearth/base/spec/legend.py
@dataclass(frozen=True)
class LegendSpec:
    """A legend as a value: what it is called, what its rows are, and how it is laid out.

    Attributes:
        entries: The rows, in the order they are drawn.
        kind: ``"categorical"``, ``"graduated"`` or ``"continuous"`` — the three the tiers already
            distinguish, kept because a ramp is drawn as a bar and the other two as swatches.
        title: The legend's heading, usually the column name.
        units: Unit string appended to the labels, or shown once as a subtitle.
        format: Format spec for numeric labels, e.g. ``".1f"``.
        orientation: ``"vertical"`` or ``"horizontal"``.

    Examples:
        - A categorical legend takes its colours from the scale that drew them:
            ```python
            >>> from digitalearth.base.spec import LegendSpec, Scale
            >>> scale = Scale.categorical(["land", "sea"], ["#8b4513", "#1e90ff"])
            >>> legend = LegendSpec.from_scale(scale, title="cover")
            >>> [(e.label, e.color) for e in legend.entries]
            [('land', '#8b4513'), ('sea', '#1e90ff')]

            ```
        - A classified scale becomes one row per class, labelled by the range it covers:
            ```python
            >>> from digitalearth.base.spec import LegendSpec, Scale
            >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=2)
            >>> legend = LegendSpec.from_scale(scale, colors=["#eee", "#111"])
            >>> len(legend.entries), legend.kind
            (2, 'graduated')

            ```
    """

    entries: tuple[LegendEntry, ...] = ()
    kind: str = "continuous"
    title: str | None = None
    units: str | None = None
    format: str | None = None
    orientation: str = "vertical"

    def __post_init__(self) -> None:
        """Refuse a kind or orientation no tier can draw.

        Raises:
            ValueError: for an unknown `kind` or `orientation`. Both select a drawing path in every tier, so
                an unrecognised one is silently ignored at render time and the legend simply does not appear.
        """
        if self.kind not in LEGEND_KINDS:
            raise ValueError(
                f"LegendSpec kind must be one of {list(LEGEND_KINDS)}; got {self.kind!r}"
            )
        if self.orientation not in ("vertical", "horizontal"):
            raise ValueError(
                f"LegendSpec orientation must be 'vertical' or 'horizontal'; got {self.orientation!r}"
            )
        object.__setattr__(self, "entries", tuple(self.entries))

    @classmethod
    def from_scale(
        cls,
        scale: Scale,
        *,
        colors: Sequence[str] | None = None,
        title: str | None = None,
        units: str | None = None,
        format: str | None = None,
        orientation: str = "vertical",
        stops: int = DEFAULT_RAMP_STOPS,
        values: Sequence[float] | None = None,
    ) -> "LegendSpec":
        """Build a legend from the scale a layer was drawn with.

        This is the load-bearing method. Deriving the rows *from the scale* is what makes a swatch equal the
        colour that was drawn, instead of a second computation that happens to agree.

        Args:
            scale: The resolved scale the layer used.
            colors: The colours drawn, one per class or stop. Required for a graduated or continuous scale,
                where the colours come from the renderer's colormap rather than from the scale. Ignored for a
                categorical scale, which carries its own — passing them there would reintroduce exactly the
                second source of truth this removes.
            title: Legend heading, usually the column name.
            units: Unit string for the values.
            format: Format spec for numeric labels.
            orientation: ``"vertical"`` or ``"horizontal"``.
            stops: How many stops describe a continuous ramp, spaced evenly between the scale's limits.
                Ignored for a categorical or graduated scale, and when `values` is given.
            values: The stop values the ramp was actually drawn with, for the continuous arm; each becomes
                one row, converted to `float`, in the order given. Ignored for a categorical or graduated
                scale. Pass them whenever the caller already holds them. Recomputing them here from the
                limits is a second computation that *usually* agrees: ``numpy.linspace`` pins its final
                element to ``stop`` exactly, and ``lo + (hi - lo) * i / (stops - 1)`` does not. For
                ``lo=-3.7, hi=12.9`` the recomputed top stop is ``12.900000000000002`` while the drawn one is
                ``12.9`` — so the top swatch carries a value the layer never draws, which is the
                disagreement this type exists to remove.

        Returns:
            The legend.

        Raises:
            ValueError: if `colors` is missing or the wrong length for a scale that needs it. A short list
                leaves classes sharing a colour and a long one leaves colours unused — either way the legend
                stops matching the picture, which is the failure this type exists to prevent. Also raised
                for a continuous scale described by fewer than two stops — `stops` below two, or fewer than
                two `values` — which cannot describe a ramp.

        Examples:
            - A categorical scale needs no colours passed, because it has them:
                ```python
                >>> from digitalearth.base.spec import LegendSpec, Scale
                >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
                >>> LegendSpec.from_scale(scale).entries[0].color
                '#f00'

                ```
            - A graduated scale given the wrong number of colours is refused:
                ```python
                >>> from digitalearth.base.spec import LegendSpec, Scale
                >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=3)
                >>> LegendSpec.from_scale(scale, colors=["#eee", "#111"])
                Traceback (most recent call last):
                    ...
                ValueError: a graduated legend needs one colour per class; got 2 colours for 3 classes

                ```
            - A ramp's rows are exactly the stops passed in `values`; without them, `DEFAULT_RAMP_STOPS`
              evenly spaced stops are computed from the limits instead:
                ```python
                >>> from digitalearth.base.spec import DEFAULT_RAMP_STOPS, LegendSpec, Scale
                >>> scale = Scale.from_limits(0.0, 10.0)
                >>> drawn = LegendSpec.from_scale(scale, colors=["#000", "#888", "#fff"], values=[0.0, 2.5, 10.0])
                >>> [entry.value for entry in drawn.entries], drawn.kind
                ([0.0, 2.5, 10.0], 'continuous')
                >>> computed = LegendSpec.from_scale(scale, colors=["#000"] * DEFAULT_RAMP_STOPS)
                >>> [entry.value for entry in computed.entries]
                [0.0, 2.5, 5.0, 7.5, 10.0]

                ```
        """
        if scale.is_categorical:
            entries = tuple(
                LegendEntry(str(category), scale.color_for(category), category)
                for category in scale.categories
            )
            return cls(entries, "categorical", title, units, format, orientation)

        if scale.is_classified:
            ranges = scale.class_ranges()
            colors = cls._checked(colors, len(ranges), "graduated", "class")
            texts = cls._texts([edge for pair in ranges for edge in pair], format)
            entries = tuple(
                LegendEntry(f"{texts[low]} – {texts[high]}", color, (low, high))
                for (low, high), color in zip(ranges, colors)
            )
            return cls(entries, "graduated", title, units, format, orientation)

        # Checked here rather than at the top of the method, because this is the only arm that reads
        # `stops`: a categorical or graduated legend has its rows from the scale and was being refused over
        # a number it goes on to ignore. Fewer than two cannot describe a ramp — one divides by zero
        # computing the spacing, none yields an empty legend — and this is the field that reaches the
        # arithmetic directly, where every other one is checked in `__post_init__`.
        described = stops if values is None else len(values)
        if described < 2:
            raise ValueError(
                f"a continuous legend needs at least two stops to describe a ramp; got {described}"
            )
        ramp = [float(value) for value in values] if values is not None else None
        if ramp is None:
            lo, hi = scale.as_limits()
            ramp = [lo + (hi - lo) * i / (stops - 1) for i in range(stops)]
        colors = cls._checked(colors, len(ramp), "continuous", "stop")
        texts = cls._texts(ramp, format)
        entries = tuple(
            LegendEntry(texts[value], color, value)
            for value, color in zip(ramp, colors)
        )
        return cls(entries, "continuous", title, units, format, orientation)

    @staticmethod
    def _checked(
        colors: Sequence[str] | None, wanted: int, kind: str, noun: str
    ) -> list[str]:
        """Return `colors` as a list, refusing a count that would misdescribe the picture.

        Args:
            colors: The colours the caller passed, or ``None``.
            wanted: How many are needed.
            kind: The legend kind, for the message.
            noun: What the colours correspond to — ``"class"`` or ``"stop"``.

        Returns:
            The colours.

        Raises:
            ValueError: if none were given, or the wrong number.
        """
        if colors is None:
            raise ValueError(
                f"a {kind} legend needs the colours the layer was drawn with, one per {noun}; "
                "they come from the renderer's colormap, not from the scale"
            )
        listed = list(colors)
        if len(listed) != wanted:
            plural = "classes" if noun == "class" else f"{noun}s"
            raise ValueError(
                f"a {kind} legend needs one colour per {noun}; got {len(listed)} colours "
                f"for {wanted} {plural}"
            )
        return listed

    @staticmethod
    def _number(value: Any, spec: str | None) -> str:
        """Format one number for a label, trimming float noise and nothing else.

        With a `spec` the number is formatted as asked. Without one it reads as `str` gives it, with one
        exception: a float whose exact text ends in floating-point noise — a run of zeros or nines and one to
        three stray digits, as ``7.600000000000023`` or ``0.30000000000000004`` — is shown rounded to twelve
        significant digits. Integers and genuinely precise floats (``123456789012345.0``) keep every digit.
        :meth:`_texts` checks that the trim never merges two distinct edges.

        Args:
            value: The number.
            spec: A format spec, applied as given, or ``None`` for the noise-trimmed `str` form.

        Returns:
            The formatted text.

        Examples:
            - Float noise is trimmed; a clean float, an integer and a precise large value are untouched:
                ```python
                >>> from digitalearth.base.spec import LegendSpec
                >>> [LegendSpec._number(v, None) for v in (7.600000000000023, 22.0, 10, 123456789012345.0)]
                ['7.6', '22.0', '10', '123456789012345.0']

                ```
            - A format spec is applied as given, with no trimming of its own:
                ```python
                >>> from digitalearth.base.spec import LegendSpec
                >>> LegendSpec._number(7.600000000000023, ".3f"), LegendSpec._number(0.25, ".0%")
                ('7.600', '25%')

                ```
        """
        if spec:
            return format(value, spec)
        if isinstance(value, numbers.Integral) or not isinstance(value, numbers.Real):
            return str(value)
        mantissa = repr(float(value)).split("e")[0]
        if _ends_in_float_noise(mantissa):
            return str(float(f"{float(value):.12g}"))
        return str(value)

    @classmethod
    def _texts(cls, values: Sequence[Any], spec: str | None) -> dict[Any, str]:
        """Return the label text of each value a legend shows, distinct values always reading distinctly.

        Args:
            values: Every number the legend labels (repeats allowed).
            spec: A format spec, or ``None`` for :meth:`_number`'s noise-trimmed form.

        Returns:
            ``value -> text``. Should trimming give two distinct values the same text — edges that differ only
            far down their digits, like ``1000000.0000001`` and ``1000000.0000002`` — every value falls back to
            its exact `str`, so no two classes are ever keyed alike.

        Examples:
            - Noise is trimmed while the edges stay apart:
                ```python
                >>> from digitalearth.base.spec import LegendSpec
                >>> LegendSpec._texts([0.0, 7.600000000000023], None)
                {0.0: '0.0', 7.600000000000023: '7.6'}

                ```
            - Edges a trim would merge are kept exact instead:
                ```python
                >>> from digitalearth.base.spec import LegendSpec
                >>> sorted(LegendSpec._texts([1000000.0000001, 1000000.0000002], None).values())
                ['1000000.0000001', '1000000.0000002']

                ```
        """
        distinct = list(dict.fromkeys(values))
        texts = {value: cls._number(value, spec) for value in distinct}
        if spec is None and len(set(texts.values())) < len(distinct):
            texts = {value: str(value) for value in distinct}
        return texts

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a tier stores or serialises.

        Every field is included, so the result is complete rather than the subset a particular tier happens
        to read. It is not paired with a `from_dict`: a legend is *derived* from a `Scale`, and rebuilding one
        from a dict would be a second way to construct it — the one thing :meth:`from_scale` exists to
        prevent. Round-tripping belongs to whatever holds the scale, not to the legend.

        Returns:
            The legend as ``kind`` / ``values`` / ``colors`` plus the labels — the shape the web tier already
            keeps in ``last_legend``, so it can derive that from this rather than assembling it three times.

        Examples:
            - The three keys a tier reads back:
                ```python
                >>> from digitalearth.base.spec import LegendSpec, Scale
                >>> payload = LegendSpec.from_scale(Scale.categorical(["a"], ["#f00"])).to_dict()
                >>> payload["kind"], payload["values"], payload["colors"]
                ('categorical', ['a'], ['#f00'])

                ```
        """
        return {
            "kind": self.kind,
            "title": self.title,
            "units": self.units,
            "format": self.format,
            "orientation": self.orientation,
            "labels": [entry.label for entry in self.entries],
            "values": [entry.value for entry in self.entries],
            "colors": [entry.color for entry in self.entries],
        }

__post_init__() #

Refuse a kind or orientation no tier can draw.

Raises:

Type Description
ValueError

for an unknown kind or orientation. Both select a drawing path in every tier, so an unrecognised one is silently ignored at render time and the legend simply does not appear.

Source code in src/digitalearth/base/spec/legend.py
def __post_init__(self) -> None:
    """Refuse a kind or orientation no tier can draw.

    Raises:
        ValueError: for an unknown `kind` or `orientation`. Both select a drawing path in every tier, so
            an unrecognised one is silently ignored at render time and the legend simply does not appear.
    """
    if self.kind not in LEGEND_KINDS:
        raise ValueError(
            f"LegendSpec kind must be one of {list(LEGEND_KINDS)}; got {self.kind!r}"
        )
    if self.orientation not in ("vertical", "horizontal"):
        raise ValueError(
            f"LegendSpec orientation must be 'vertical' or 'horizontal'; got {self.orientation!r}"
        )
    object.__setattr__(self, "entries", tuple(self.entries))

from_scale(scale, *, colors=None, title=None, units=None, format=None, orientation='vertical', stops=DEFAULT_RAMP_STOPS, values=None) classmethod #

Build a legend from the scale a layer was drawn with.

This is the load-bearing method. Deriving the rows from the scale is what makes a swatch equal the colour that was drawn, instead of a second computation that happens to agree.

Parameters:

Name Type Description Default
scale Scale

The resolved scale the layer used.

required
colors Sequence[str] | None

The colours drawn, one per class or stop. Required for a graduated or continuous scale, where the colours come from the renderer's colormap rather than from the scale. Ignored for a categorical scale, which carries its own — passing them there would reintroduce exactly the second source of truth this removes.

None
title str | None

Legend heading, usually the column name.

None
units str | None

Unit string for the values.

None
format str | None

Format spec for numeric labels.

None
orientation str

"vertical" or "horizontal".

'vertical'
stops int

How many stops describe a continuous ramp, spaced evenly between the scale's limits. Ignored for a categorical or graduated scale, and when values is given.

DEFAULT_RAMP_STOPS
values Sequence[float] | None

The stop values the ramp was actually drawn with, for the continuous arm; each becomes one row, converted to float, in the order given. Ignored for a categorical or graduated scale. Pass them whenever the caller already holds them. Recomputing them here from the limits is a second computation that usually agrees: numpy.linspace pins its final element to stop exactly, and lo + (hi - lo) * i / (stops - 1) does not. For lo=-3.7, hi=12.9 the recomputed top stop is 12.900000000000002 while the drawn one is 12.9 — so the top swatch carries a value the layer never draws, which is the disagreement this type exists to remove.

None

Returns:

Type Description
LegendSpec

The legend.

Raises:

Type Description
ValueError

if colors is missing or the wrong length for a scale that needs it. A short list leaves classes sharing a colour and a long one leaves colours unused — either way the legend stops matching the picture, which is the failure this type exists to prevent. Also raised for a continuous scale described by fewer than two stops — stops below two, or fewer than two values — which cannot describe a ramp.

Examples:

  • A categorical scale needs no colours passed, because it has them:
    >>> from digitalearth.base.spec import LegendSpec, Scale
    >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
    >>> LegendSpec.from_scale(scale).entries[0].color
    '#f00'
    
  • A graduated scale given the wrong number of colours is refused:
    >>> from digitalearth.base.spec import LegendSpec, Scale
    >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=3)
    >>> LegendSpec.from_scale(scale, colors=["#eee", "#111"])
    Traceback (most recent call last):
        ...
    ValueError: a graduated legend needs one colour per class; got 2 colours for 3 classes
    
  • A ramp's rows are exactly the stops passed in values; without them, DEFAULT_RAMP_STOPS evenly spaced stops are computed from the limits instead:
    >>> from digitalearth.base.spec import DEFAULT_RAMP_STOPS, LegendSpec, Scale
    >>> scale = Scale.from_limits(0.0, 10.0)
    >>> drawn = LegendSpec.from_scale(scale, colors=["#000", "#888", "#fff"], values=[0.0, 2.5, 10.0])
    >>> [entry.value for entry in drawn.entries], drawn.kind
    ([0.0, 2.5, 10.0], 'continuous')
    >>> computed = LegendSpec.from_scale(scale, colors=["#000"] * DEFAULT_RAMP_STOPS)
    >>> [entry.value for entry in computed.entries]
    [0.0, 2.5, 5.0, 7.5, 10.0]
    
Source code in src/digitalearth/base/spec/legend.py
@classmethod
def from_scale(
    cls,
    scale: Scale,
    *,
    colors: Sequence[str] | None = None,
    title: str | None = None,
    units: str | None = None,
    format: str | None = None,
    orientation: str = "vertical",
    stops: int = DEFAULT_RAMP_STOPS,
    values: Sequence[float] | None = None,
) -> "LegendSpec":
    """Build a legend from the scale a layer was drawn with.

    This is the load-bearing method. Deriving the rows *from the scale* is what makes a swatch equal the
    colour that was drawn, instead of a second computation that happens to agree.

    Args:
        scale: The resolved scale the layer used.
        colors: The colours drawn, one per class or stop. Required for a graduated or continuous scale,
            where the colours come from the renderer's colormap rather than from the scale. Ignored for a
            categorical scale, which carries its own — passing them there would reintroduce exactly the
            second source of truth this removes.
        title: Legend heading, usually the column name.
        units: Unit string for the values.
        format: Format spec for numeric labels.
        orientation: ``"vertical"`` or ``"horizontal"``.
        stops: How many stops describe a continuous ramp, spaced evenly between the scale's limits.
            Ignored for a categorical or graduated scale, and when `values` is given.
        values: The stop values the ramp was actually drawn with, for the continuous arm; each becomes
            one row, converted to `float`, in the order given. Ignored for a categorical or graduated
            scale. Pass them whenever the caller already holds them. Recomputing them here from the
            limits is a second computation that *usually* agrees: ``numpy.linspace`` pins its final
            element to ``stop`` exactly, and ``lo + (hi - lo) * i / (stops - 1)`` does not. For
            ``lo=-3.7, hi=12.9`` the recomputed top stop is ``12.900000000000002`` while the drawn one is
            ``12.9`` — so the top swatch carries a value the layer never draws, which is the
            disagreement this type exists to remove.

    Returns:
        The legend.

    Raises:
        ValueError: if `colors` is missing or the wrong length for a scale that needs it. A short list
            leaves classes sharing a colour and a long one leaves colours unused — either way the legend
            stops matching the picture, which is the failure this type exists to prevent. Also raised
            for a continuous scale described by fewer than two stops — `stops` below two, or fewer than
            two `values` — which cannot describe a ramp.

    Examples:
        - A categorical scale needs no colours passed, because it has them:
            ```python
            >>> from digitalearth.base.spec import LegendSpec, Scale
            >>> scale = Scale.categorical(["a"], ["#f00"], missing="#ccc")
            >>> LegendSpec.from_scale(scale).entries[0].color
            '#f00'

            ```
        - A graduated scale given the wrong number of colours is refused:
            ```python
            >>> from digitalearth.base.spec import LegendSpec, Scale
            >>> scale = Scale.from_values([0.0, 10.0], scheme="equal_interval", k=3)
            >>> LegendSpec.from_scale(scale, colors=["#eee", "#111"])
            Traceback (most recent call last):
                ...
            ValueError: a graduated legend needs one colour per class; got 2 colours for 3 classes

            ```
        - A ramp's rows are exactly the stops passed in `values`; without them, `DEFAULT_RAMP_STOPS`
          evenly spaced stops are computed from the limits instead:
            ```python
            >>> from digitalearth.base.spec import DEFAULT_RAMP_STOPS, LegendSpec, Scale
            >>> scale = Scale.from_limits(0.0, 10.0)
            >>> drawn = LegendSpec.from_scale(scale, colors=["#000", "#888", "#fff"], values=[0.0, 2.5, 10.0])
            >>> [entry.value for entry in drawn.entries], drawn.kind
            ([0.0, 2.5, 10.0], 'continuous')
            >>> computed = LegendSpec.from_scale(scale, colors=["#000"] * DEFAULT_RAMP_STOPS)
            >>> [entry.value for entry in computed.entries]
            [0.0, 2.5, 5.0, 7.5, 10.0]

            ```
    """
    if scale.is_categorical:
        entries = tuple(
            LegendEntry(str(category), scale.color_for(category), category)
            for category in scale.categories
        )
        return cls(entries, "categorical", title, units, format, orientation)

    if scale.is_classified:
        ranges = scale.class_ranges()
        colors = cls._checked(colors, len(ranges), "graduated", "class")
        texts = cls._texts([edge for pair in ranges for edge in pair], format)
        entries = tuple(
            LegendEntry(f"{texts[low]} – {texts[high]}", color, (low, high))
            for (low, high), color in zip(ranges, colors)
        )
        return cls(entries, "graduated", title, units, format, orientation)

    # Checked here rather than at the top of the method, because this is the only arm that reads
    # `stops`: a categorical or graduated legend has its rows from the scale and was being refused over
    # a number it goes on to ignore. Fewer than two cannot describe a ramp — one divides by zero
    # computing the spacing, none yields an empty legend — and this is the field that reaches the
    # arithmetic directly, where every other one is checked in `__post_init__`.
    described = stops if values is None else len(values)
    if described < 2:
        raise ValueError(
            f"a continuous legend needs at least two stops to describe a ramp; got {described}"
        )
    ramp = [float(value) for value in values] if values is not None else None
    if ramp is None:
        lo, hi = scale.as_limits()
        ramp = [lo + (hi - lo) * i / (stops - 1) for i in range(stops)]
    colors = cls._checked(colors, len(ramp), "continuous", "stop")
    texts = cls._texts(ramp, format)
    entries = tuple(
        LegendEntry(texts[value], color, value)
        for value, color in zip(ramp, colors)
    )
    return cls(entries, "continuous", title, units, format, orientation)

to_dict() #

Return the plain-dict form a tier stores or serialises.

Every field is included, so the result is complete rather than the subset a particular tier happens to read. It is not paired with a from_dict: a legend is derived from a Scale, and rebuilding one from a dict would be a second way to construct it — the one thing :meth:from_scale exists to prevent. Round-tripping belongs to whatever holds the scale, not to the legend.

Returns:

Type Description
dict[str, Any]

The legend as kind / values / colors plus the labels — the shape the web tier already

dict[str, Any]

keeps in last_legend, so it can derive that from this rather than assembling it three times.

Examples:

  • The three keys a tier reads back:
    >>> from digitalearth.base.spec import LegendSpec, Scale
    >>> payload = LegendSpec.from_scale(Scale.categorical(["a"], ["#f00"])).to_dict()
    >>> payload["kind"], payload["values"], payload["colors"]
    ('categorical', ['a'], ['#f00'])
    
Source code in src/digitalearth/base/spec/legend.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a tier stores or serialises.

    Every field is included, so the result is complete rather than the subset a particular tier happens
    to read. It is not paired with a `from_dict`: a legend is *derived* from a `Scale`, and rebuilding one
    from a dict would be a second way to construct it — the one thing :meth:`from_scale` exists to
    prevent. Round-tripping belongs to whatever holds the scale, not to the legend.

    Returns:
        The legend as ``kind`` / ``values`` / ``colors`` plus the labels — the shape the web tier already
        keeps in ``last_legend``, so it can derive that from this rather than assembling it three times.

    Examples:
        - The three keys a tier reads back:
            ```python
            >>> from digitalearth.base.spec import LegendSpec, Scale
            >>> payload = LegendSpec.from_scale(Scale.categorical(["a"], ["#f00"])).to_dict()
            >>> payload["kind"], payload["values"], payload["colors"]
            ('categorical', ['a'], ['#f00'])

            ```
    """
    return {
        "kind": self.kind,
        "title": self.title,
        "units": self.units,
        "format": self.format,
        "orientation": self.orientation,
        "labels": [entry.label for entry in self.entries],
        "values": [entry.value for entry in self.entries],
        "colors": [entry.color for entry in self.entries],
    }

digitalearth.base.spec.legend.LegendEntry dataclass #

One row of a legend: a swatch, and what it means.

Attributes:

Name Type Description
label str

The text shown beside the swatch.

color str | None

The colour drawn, as the renderer drew it.

value Any

The underlying value or range this row stands for, kept so a tier can build an interactive legend that filters or highlights. None when the row is decorative.

Examples:

  • A row carries what it stands for, not just its label:
    >>> from digitalearth.base.spec import LegendEntry
    >>> row = LegendEntry("land", "#8b4513", "land")
    >>> row.label, row.color, row.value
    ('land', '#8b4513', 'land')
    
Source code in src/digitalearth/base/spec/legend.py
@dataclass(frozen=True)
class LegendEntry:
    """One row of a legend: a swatch, and what it means.

    Attributes:
        label: The text shown beside the swatch.
        color: The colour drawn, as the renderer drew it.
        value: The underlying value or range this row stands for, kept so a tier can build an interactive
            legend that filters or highlights. ``None`` when the row is decorative.

    Examples:
        - A row carries what it stands for, not just its label:
            ```python
            >>> from digitalearth.base.spec import LegendEntry
            >>> row = LegendEntry("land", "#8b4513", "land")
            >>> row.label, row.color, row.value
            ('land', '#8b4513', 'land')

            ```
    """

    label: str
    color: str | None
    value: Any = None

Guide — the colour key, attached to the encoding it explains#

LegendSpec says what a key contains. Guide says whether to draw one at all, what to call it, and which corner it sits in — and it lives on the layer's Encoding rather than beside the figure.

That placement is the whole of it. A key used to be figure decoration each tier held its own way: drawn and then forgotten on the static tier, keyed by position (layer=-1); a show= flag on whichever layer was added last on the interactive tier; a dictionary beside the tree on the web tier, which went on describing a layer after it was removed. None of the three could move with its layer, disappear with it, or survive being written to a figure and read back.

Attached to the encoding, a guide gets all three for free, because the layer's Symbology is already what the layer tree holds, what remove_layer drops, and what a figure writes:

m = Map()
m.choropleth(regions, column="pop", scheme="quantiles", k=5, name="people")
m.colorbar("people", label="People per km²")      # records Guide(show=True, title=…) on the encoding

m.get_layer("people").symbology.guide().title     # 'People per km²'
m.remove_layer("people")                          # the key goes with the layer

A channel that nothing drives is refused rather than given an empty encoding to hang the guide on: a key over a colour that does not vary has no values to label and no scale to sample. That is why colorbar() asks for a layer whose colour is driven by a field, and why a flat-coloured layer — or one built from a caller's own artist — answers with a ValueError naming the layers that do have one.

digitalearth.base.spec.encoding.Guide dataclass #

What explains an encoding to the reader: whether to draw a legend or a colorbar for it, and where.

An encoding says what drives a channel; a guide says whether the reader is told. It lives on the encoding because that is what it explains — one scale shared by several layers is one guide, and a channel nobody needs explained (a constant colour chosen for contrast) simply carries show=False. The content stays in :class:~digitalearth.base.spec.legend.LegendSpec, which a renderer computes from the data; nothing here holds entries or colours.

Attributes:

Name Type Description
show bool

Whether to draw the guide at all. True by default: a data-driven channel that nothing explains is a map the reader cannot read.

title str | None

What to call it. None lets the renderer name it after the field the channel is driven by.

anchor str | None

Which corner of the panel it sits in — one of :data:~digitalearth.base.registry.FURNITURE_ANCHORS — or None for the tier's own default, which is the one place a colorbar's position is not worth pinning across four backends.

Raises:

Type Description
ValueError

if show is not a real boolean, title is not a non-empty string, or anchor is not one of the four corners.

Examples:

  • Title a colorbar and put it where the data is not:
    >>> from digitalearth.base.spec import Encoding, Guide, Scale
    >>> guide = Guide(title="Elevation (m)", anchor="bottom-right")
    >>> encoding = Encoding.by_field("color", "dem", scale=Scale.from_limits(0, 100), guide=guide)
    >>> encoding.guide.title, encoding.guide.anchor
    ('Elevation (m)', 'bottom-right')
    
  • Switch a guide off without losing what it would have said:
    >>> from digitalearth.base.spec import Guide
    >>> quiet = Guide(show=False, title="Elevation (m)")
    >>> quiet.show, quiet.title
    (False, 'Elevation (m)')
    
  • A corner no tier could place is refused:
    >>> from digitalearth.base.spec import Guide
    >>> Guide(anchor="middle")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Guide anchor must be one of ['top-left', ...]; got 'middle'
    
Source code in src/digitalearth/base/spec/encoding.py
@dataclass(frozen=True)
class Guide:
    """What explains an encoding to the reader: whether to draw a legend or a colorbar for it, and where.

    An encoding says what drives a channel; a guide says whether the reader is told. It lives on the encoding
    because that is what it explains — one scale shared by several layers is one guide, and a channel nobody
    needs explained (a constant colour chosen for contrast) simply carries `show=False`. The *content* stays in
    :class:`~digitalearth.base.spec.legend.LegendSpec`, which a renderer computes from the data; nothing here
    holds entries or colours.

    Attributes:
        show: Whether to draw the guide at all. `True` by default: a data-driven channel that nothing explains is
            a map the reader cannot read.
        title: What to call it. `None` lets the renderer name it after the field the channel is driven by.
        anchor: Which corner of the panel it sits in — one of
            :data:`~digitalearth.base.registry.FURNITURE_ANCHORS` — or `None` for the tier's own default, which
            is the one place a colorbar's position is not worth pinning across four backends.

    Raises:
        ValueError: if `show` is not a real boolean, `title` is not a non-empty string, or `anchor` is not one of
            the four corners.

    Examples:
        - Title a colorbar and put it where the data is not:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Scale
            >>> guide = Guide(title="Elevation (m)", anchor="bottom-right")
            >>> encoding = Encoding.by_field("color", "dem", scale=Scale.from_limits(0, 100), guide=guide)
            >>> encoding.guide.title, encoding.guide.anchor
            ('Elevation (m)', 'bottom-right')

            ```
        - Switch a guide off without losing what it would have said:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> quiet = Guide(show=False, title="Elevation (m)")
            >>> quiet.show, quiet.title
            (False, 'Elevation (m)')

            ```
        - A corner no tier could place is refused:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> Guide(anchor="middle")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Guide anchor must be one of ['top-left', ...]; got 'middle'

            ```
    """

    show: bool = True
    title: str | None = None
    anchor: str | None = None

    def __post_init__(self) -> None:
        """Refuse a guide that could not be drawn.

        Raises:
            ValueError: as described on the class.
        """
        if not isinstance(self.show, bool):
            raise ValueError(f"Guide show must be True or False; got {self.show!r}")
        if self.title is not None and (
            not isinstance(self.title, str) or not self.title.strip()
        ):
            raise ValueError(
                f"Guide title must be a non-empty string or None; got {self.title!r}"
            )
        if self.anchor is not None and self.anchor not in FURNITURE_ANCHORS:
            raise ValueError(
                f"Guide anchor must be one of {list(FURNITURE_ANCHORS)}; got {self.anchor!r}"
            )

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            Only what was asked for: a guide left at its defaults stores `{}`, so an encoding that carries one
            is no bigger in JSON than an encoding that does not.

        Examples:
            - A default guide is an empty dict, and still reads back as a guide:
                ```python
                >>> from digitalearth.base.spec import Guide
                >>> Guide().to_dict()
                {}

                ```
            - What was set is written:
                ```python
                >>> from digitalearth.base.spec import Guide
                >>> Guide(show=False, title="Rainfall", anchor="top-left").to_dict()
                {'show': False, 'title': 'Rainfall', 'anchor': 'top-left'}

                ```
        """
        out: dict[str, Any] = {}
        if not self.show:
            out["show"] = False
        if self.title is not None:
            out["title"] = plain_text(self.title)
        if self.anchor is not None:
            out["anchor"] = plain_text(self.anchor)
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Guide":
        """Rebuild a guide from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The guide, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping.
            ValueError: for an unknown key, or a guide the constructor refuses.

        Examples:
            - A stored guide reads back with what it was given:
                ```python
                >>> from digitalearth.base.spec import Guide
                >>> Guide.from_dict({"title": "Rainfall"}).title
                'Rainfall'

                ```
            - An empty dict is the default guide:
                ```python
                >>> from digitalearth.base.spec import Guide
                >>> Guide.from_dict({}).show
                True

                ```
        """
        refuse_unknown("Guide", data, ("show", "title", "anchor"))
        return cls(
            show=data.get("show", True),
            title=data.get("title"),
            anchor=data.get("anchor"),
        )

__post_init__() #

Refuse a guide that could not be drawn.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/encoding.py
def __post_init__(self) -> None:
    """Refuse a guide that could not be drawn.

    Raises:
        ValueError: as described on the class.
    """
    if not isinstance(self.show, bool):
        raise ValueError(f"Guide show must be True or False; got {self.show!r}")
    if self.title is not None and (
        not isinstance(self.title, str) or not self.title.strip()
    ):
        raise ValueError(
            f"Guide title must be a non-empty string or None; got {self.title!r}"
        )
    if self.anchor is not None and self.anchor not in FURNITURE_ANCHORS:
        raise ValueError(
            f"Guide anchor must be one of {list(FURNITURE_ANCHORS)}; got {self.anchor!r}"
        )

from_dict(data) classmethod #

Rebuild a guide from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Guide

The guide, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping.

ValueError

for an unknown key, or a guide the constructor refuses.

Examples:

  • A stored guide reads back with what it was given:
    >>> from digitalearth.base.spec import Guide
    >>> Guide.from_dict({"title": "Rainfall"}).title
    'Rainfall'
    
  • An empty dict is the default guide:
    >>> from digitalearth.base.spec import Guide
    >>> Guide.from_dict({}).show
    True
    
Source code in src/digitalearth/base/spec/encoding.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Guide":
    """Rebuild a guide from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The guide, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping.
        ValueError: for an unknown key, or a guide the constructor refuses.

    Examples:
        - A stored guide reads back with what it was given:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> Guide.from_dict({"title": "Rainfall"}).title
            'Rainfall'

            ```
        - An empty dict is the default guide:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> Guide.from_dict({}).show
            True

            ```
    """
    refuse_unknown("Guide", data, ("show", "title", "anchor"))
    return cls(
        show=data.get("show", True),
        title=data.get("title"),
        anchor=data.get("anchor"),
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

Only what was asked for: a guide left at its defaults stores {}, so an encoding that carries one

dict[str, Any]

is no bigger in JSON than an encoding that does not.

Examples:

  • A default guide is an empty dict, and still reads back as a guide:
    >>> from digitalearth.base.spec import Guide
    >>> Guide().to_dict()
    {}
    
  • What was set is written:
    >>> from digitalearth.base.spec import Guide
    >>> Guide(show=False, title="Rainfall", anchor="top-left").to_dict()
    {'show': False, 'title': 'Rainfall', 'anchor': 'top-left'}
    
Source code in src/digitalearth/base/spec/encoding.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        Only what was asked for: a guide left at its defaults stores `{}`, so an encoding that carries one
        is no bigger in JSON than an encoding that does not.

    Examples:
        - A default guide is an empty dict, and still reads back as a guide:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> Guide().to_dict()
            {}

            ```
        - What was set is written:
            ```python
            >>> from digitalearth.base.spec import Guide
            >>> Guide(show=False, title="Rainfall", anchor="top-left").to_dict()
            {'show': False, 'title': 'Rainfall', 'anchor': 'top-left'}

            ```
    """
    out: dict[str, Any] = {}
    if not self.show:
        out["show"] = False
    if self.title is not None:
        out["title"] = plain_text(self.title)
    if self.anchor is not None:
        out["anchor"] = plain_text(self.anchor)
    return out

digitalearth.base.spec.style.Symbology.with_guide(guide, *, channel='color') #

Return a copy whose channel encoding carries guide.

A guide explains an encoding, so it is attached to one rather than held beside it. That is the whole of what order 24 changes: a colour key used to be figure decoration a tier drew when asked and then forgot — keyed by position on the static tier, a show= toggle on the most recent layer on the interactive one — so it could not move with its layer, could not go away with it, and could not be written into a figure and read back. Attached here it does all three for free, because the layer's Symbology is already what travels.

Parameters:

Name Type Description Default
guide Guide | None

What to say about the channel, or None to attach nothing — which is how a guide is taken off again, and why this does not raise for it: a channel nothing drives carries no guide, so asking for the one there to come off is already true.

required
channel str

The channel being explained. Defaults to "color".

'color'

Returns:

Type Description
Symbology

A new symbology; this one is unchanged, as every Symbology writer here is. For None on a

Symbology

channel nothing drives, an equal one — the detach is a no-op rather than a refusal.

Raises:

Type Description
ValueError

when nothing drives channel and a guide is being attached to it. A key over a colour nothing varies would have no values to label and no scale to sample, so the tiers raise rather than draw an empty box — the message names the channels that are driven, since the usual cause is asking for a key on a layer whose colour is one flat constant.

Examples:

  • Attached to the colour a field drives, and read back off the layer:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
    >>> sym.with_guide(Guide(title="People", anchor="bottom-right")).guide().anchor
    'bottom-right'
    
  • None takes it off again, so a caller does not have to rebuild the encoding to drop a key:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
    >>> sym.with_guide(Guide(title="People")).with_guide(None).guide() is None
    True
    
  • A channel nothing drives is refused, and the message says what the layer does drive:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> Symbology.of(size=6).with_guide(Guide())  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: nothing drives the 'color' channel ...; the channels it does drive are ['size']
    
  • Taking a guide off that same channel is not, because there is none there to refuse:
    >>> from digitalearth.base.spec import Symbology
    >>> flat = Symbology.of(size=6)
    >>> flat.with_guide(None) == flat
    True
    
Source code in src/digitalearth/base/spec/style.py
def with_guide(self, guide: Guide | None, *, channel: str = "color") -> "Symbology":
    """Return a copy whose `channel` encoding carries `guide`.

    **A guide explains an encoding**, so it is attached to one rather than held beside it. That is the
    whole of what order 24 changes: a colour key used to be figure decoration a tier drew when asked and
    then forgot — keyed by position on the static tier, a `show=` toggle on the most recent layer on the
    interactive one — so it could not move with its layer, could not go away with it, and could not be
    written into a figure and read back. Attached here it does all three for free, because the layer's
    `Symbology` is already what travels.

    Args:
        guide: What to say about the channel, or ``None`` to attach nothing — which is how a guide is
            taken off again, and why this does not raise for it: a channel nothing drives carries no
            guide, so asking for the one there to come off is already true.
        channel: The channel being explained. Defaults to ``"color"``.

    Returns:
        A new symbology; this one is unchanged, as every `Symbology` writer here is. For ``None`` on a
        channel nothing drives, an equal one — the detach is a no-op rather than a refusal.

    Raises:
        ValueError: when nothing drives `channel` **and** a guide is being attached to it. A key over a
            colour nothing varies would have no values to label and no scale to sample, so the tiers
            raise rather than draw an empty box — the message names the channels that *are* driven,
            since the usual cause is asking for a key on a layer whose colour is one flat constant.

    Examples:
        - Attached to the colour a field drives, and read back off the layer:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
            >>> sym.with_guide(Guide(title="People", anchor="bottom-right")).guide().anchor
            'bottom-right'

            ```
        - ``None`` takes it off again, so a caller does not have to rebuild the encoding to drop a key:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "pop")})
            >>> sym.with_guide(Guide(title="People")).with_guide(None).guide() is None
            True

            ```
        - A channel nothing drives is refused, and the message says what the layer does drive:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> Symbology.of(size=6).with_guide(Guide())  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: nothing drives the 'color' channel ...; the channels it does drive are ['size']

            ```
        - Taking a guide off that same channel is not, because there is none there to refuse:
            ```python
            >>> from digitalearth.base.spec import Symbology
            >>> flat = Symbology.of(size=6)
            >>> flat.with_guide(None) == flat
            True

            ```
    """
    encoding = self.encodings.get(channel)
    if encoding is None:
        if guide is None:
            # Detaching what is not there is not an error. The refusal below is about the *guide* — it
            # would have no values to label and no scale to sample — and so has nothing to say when
            # there is no guide to attach; applied to `None` as well it refused the one call that
            # cannot go wrong, and contradicted this method's own `Args` entry (review L1).
            return Symbology(encodings=dict(self.encodings), props=dict(self.props))
        raise ValueError(
            f"nothing drives the {channel!r} channel of this layer, so there is no encoding for a "
            f"guide to explain; the channels it does drive are {sorted(self.encodings)}"
        )
    encodings = dict(self.encodings)
    encodings[channel] = with_fields(encoding, guide=guide)
    return Symbology(encodings=encodings, props=dict(self.props))

digitalearth.base.spec.style.Symbology.guide(channel='color') #

Return what explains one channel to the reader — the legend or colorbar asked for on it.

The read side of :meth:with_guide, and the reason a guide lives on the encoding rather than beside it: a renderer asking "does this layer want a colour key, and what is it called?" asks the layer, so the answer moves, hides and disappears with it (DE-48, order 24).

Parameters:

Name Type Description Default
channel str

The channel whose guide is wanted. Defaults to "color", which is the channel a colorbar and a keyed legend both explain — the other channels have guides too, and none of them has a default worth guessing.

'color'

Returns:

Name Type Description
The Guide | None

class:~digitalearth.base.spec.encoding.Guide on that channel's encoding, or None —

Guide | None

both when nothing drives the channel and when something does and nobody asked for a guide.

Guide | None

The two are one answer on purpose: a renderer's question is whether to draw a key, and there is

Guide | None

nothing to draw in either case.

Examples:

  • A guide asked for on a channel is read back from it:
    >>> from digitalearth.base.spec import Encoding, Guide, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
    >>> sym.with_guide(Guide(title="Elevation (m)")).guide().title
    'Elevation (m)'
    
  • A channel nobody asked a guide of, and a channel nothing drives, both answer None:
    >>> from digitalearth.base.spec import Encoding, Symbology
    >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
    >>> sym.guide() is None, sym.guide("size") is None
    (True, True)
    
Source code in src/digitalearth/base/spec/style.py
def guide(self, channel: str = "color") -> Guide | None:
    """Return what explains one channel to the reader — the legend or colorbar asked for on it.

    The read side of :meth:`with_guide`, and the reason a guide lives on the encoding rather than beside
    it: a renderer asking "does this layer want a colour key, and what is it called?" asks the layer, so
    the answer moves, hides and disappears with it (DE-48, order 24).

    Args:
        channel: The channel whose guide is wanted. Defaults to ``"color"``, which is the channel a
            colorbar and a keyed legend both explain — the other channels have guides too, and none of
            them has a default worth guessing.

    Returns:
        The :class:`~digitalearth.base.spec.encoding.Guide` on that channel's encoding, or ``None`` —
        both when nothing drives the channel and when something does and nobody asked for a guide.
        The two are one answer on purpose: a renderer's question is whether to draw a key, and there is
        nothing to draw in either case.

    Examples:
        - A guide asked for on a channel is read back from it:
            ```python
            >>> from digitalearth.base.spec import Encoding, Guide, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
            >>> sym.with_guide(Guide(title="Elevation (m)")).guide().title
            'Elevation (m)'

            ```
        - A channel nobody asked a guide of, and a channel nothing drives, both answer ``None``:
            ```python
            >>> from digitalearth.base.spec import Encoding, Symbology
            >>> sym = Symbology(encodings={"color": Encoding.by_field("color", "dem")})
            >>> sym.guide() is None, sym.guide("size") is None
            (True, True)

            ```
    """
    encoding = self.encodings.get(channel)
    return None if encoding is None else encoding.guide

PointArrays — geometry as coordinate arrays#

Turning a FeatureCollection into numpy arrays was written out 22 times across 9 files, in three spellings, with inconsistent handling of non-finite coordinates — the ones a globe or clipped CRS produces for the far side of the world.

digitalearth.base.points.PointArrays dataclass #

Point coordinates as parallel float arrays, with the CRS they are measured in.

Attributes:

Name Type Description
x ndarray

X coordinates, float64.

y ndarray

Y coordinates, float64.

z ndarray

Z coordinates, float64. Zeros when the source geometry is 2-D, so a consumer that needs three columns always has them — which is what the 3-D tier was filling in by hand.

crs Any

What the coordinates are measured in, or None when the source declared none. Carried, not normalised: :meth:of keeps whatever the caller passed (typically an EPSG int) and :meth:from_features keeps whatever the frame declared (typically a pyproj.CRS). Compare it with :func:pyramids.base.crs.crs_equal rather than == if the spelling could differ.

The three arrays are copies, marked read-only. Building one from a caller's buffer and then sharing memory with it would mean a "frozen" value that changes underneath whoever holds it, and x/y/z and :meth:as_xy hand the arrays straight back out.

Raises:

Type Description
ValueError

if the three arrays are not the same length. They are index-aligned with each other and with any attribute column a caller filters alongside them, so a mismatch is a defect that would otherwise surface as points drawn at another point's coordinates.

Examples:

  • Coordinates and a CRS, with z defaulting to zeros:
    >>> from digitalearth.base.points import PointArrays
    >>> pts = PointArrays.of([0.0, 1.0], [10.0, 11.0], crs=4326)
    >>> pts.x.tolist(), pts.z.tolist()
    ([0.0, 1.0], [0.0, 0.0])
    
  • Non-finite points are dropped, and anything aligned with them is dropped too:
    >>> from digitalearth.base.points import PointArrays
    >>> pts = PointArrays.of([0.0, float("inf"), 2.0], [5.0, 6.0, 7.0])
    >>> kept, (names,) = pts.finite(["a", "b", "c"])
    >>> kept.x.tolist(), [str(n) for n in names]
    ([0.0, 2.0], ['a', 'c'])
    
Source code in src/digitalearth/base/points.py
@dataclass(frozen=True, eq=False)
class PointArrays:
    """Point coordinates as parallel float arrays, with the CRS they are measured in.

    Attributes:
        x: X coordinates, ``float64``.
        y: Y coordinates, ``float64``.
        z: Z coordinates, ``float64``. Zeros when the source geometry is 2-D, so a consumer that needs three
            columns always has them — which is what the 3-D tier was filling in by hand.
        crs: What the coordinates are measured in, or ``None`` when the source declared none. Carried, not
            normalised: :meth:`of` keeps whatever the caller passed (typically an EPSG ``int``) and
            :meth:`from_features` keeps whatever the frame declared (typically a ``pyproj.CRS``). Compare it
            with :func:`pyramids.base.crs.crs_equal` rather than ``==`` if the spelling could differ.

    The three arrays are **copies**, marked read-only. Building one from a caller's buffer and then sharing
    memory with it would mean a "frozen" value that changes underneath whoever holds it, and `x`/`y`/`z` and
    :meth:`as_xy` hand the arrays straight back out.

    Raises:
        ValueError: if the three arrays are not the same length. They are index-aligned with each other and
            with any attribute column a caller filters alongside them, so a mismatch is a defect that would
            otherwise surface as points drawn at another point's coordinates.

    Examples:
        - Coordinates and a CRS, with z defaulting to zeros:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> pts = PointArrays.of([0.0, 1.0], [10.0, 11.0], crs=4326)
            >>> pts.x.tolist(), pts.z.tolist()
            ([0.0, 1.0], [0.0, 0.0])

            ```
        - Non-finite points are dropped, and anything aligned with them is dropped too:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> pts = PointArrays.of([0.0, float("inf"), 2.0], [5.0, 6.0, 7.0])
            >>> kept, (names,) = pts.finite(["a", "b", "c"])
            >>> kept.x.tolist(), [str(n) for n in names]
            ([0.0, 2.0], ['a', 'c'])

            ```
    """

    x: np.ndarray
    y: np.ndarray
    z: np.ndarray
    crs: Any = None

    def __post_init__(self) -> None:
        """Refuse arrays that are not index-aligned.

        Raises:
            ValueError: if `x`, `y` and `z` differ in length.
        """
        lengths = {len(self.x), len(self.y), len(self.z)}
        if len(lengths) != 1:
            raise ValueError(
                f"PointArrays needs x, y and z the same length; got {len(self.x)}, "
                f"{len(self.y)}, {len(self.z)}"
            )

    # ------------------------------------------------------------------ builders

    @classmethod
    def of(cls, x: Any, y: Any, z: Any = None, *, crs: Any = None) -> "PointArrays":
        """Build from coordinate sequences, forcing the dtype every call site used to choose for itself.

        Args:
            x: X coordinates.
            y: Y coordinates.
            z: Z coordinates, or ``None`` for zeros.
            crs: What the coordinates are measured in.

        Returns:
            The arrays as ``float64``, which is what every consumer wanted and only some asked for.

        Raises:
            ValueError: if the sequences are not the same length.

        Examples:
            - Integer input comes back as floats, with z filled in:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> pts = PointArrays.of([0, 1], [2, 3], crs=4326)
                >>> pts.x.tolist(), pts.z.tolist()
                ([0.0, 1.0], [0.0, 0.0])

                ```
        """
        # np.array, not np.asarray: asarray does not copy a contiguous float64 input, so the "frozen" value
        # would share memory with the caller's buffer and change underneath it. The arrays are then marked
        # read-only, because `x`/`y`/`z` and `as_xy()` hand them straight back out.
        xs = np.array(x, dtype="float64").ravel()
        ys = np.array(y, dtype="float64").ravel()
        zs = np.zeros_like(xs) if z is None else np.array(z, dtype="float64").ravel()
        for array in (xs, ys, zs):
            array.flags.writeable = False
        return cls(xs, ys, zs, crs)

    @classmethod
    def from_features(
        cls, features: Any, *, centroids: bool = True, crs: Any = None
    ) -> "PointArrays":
        """Extract coordinates from a pyramids ``FeatureCollection`` or a geopandas frame.

        Args:
            features: The collection, frame or geometry series to read. A ``FeatureCollection`` is converted
                through ``to_geodataframe()``, which is the only way this package touches vector data.
            centroids: What to do with geometry that is not a point. ``True`` (default) falls back to the
                centroid, which is what the source extractor does; ``False`` raises instead, for a caller
                whose maths is only meaningful on real points.
            crs: Override the CRS to record. Defaults to whatever the input declares.

        Returns:
            The coordinates, with `z` taken from the geometry when **every** point is 3-D, and zeros
            otherwise. A frame mixing 2-D and 3-D points therefore reads as flat: `has_z.all()` is what
            geopandas can answer cheaply, and a partly-3-D frame has no elevation for some of its points
            anyway.

            A row whose geometry is **missing** reads as `NaN`, whatever `centroids` says. A `null` geometry
            is ordinary in GeoJSON, and it is absent data rather than data of the wrong shape — so it is for
            :meth:`finite` to drop, which is what every caller does with it. Only a geometry that is
            genuinely present is subject to the `centroids` decision, and only present geometry decides
            whether the frame is 3-D: a null among 3-D points keeps the others' heights, and its own `z` is
            `NaN` like its `x` and `y`.

        Raises:
            TypeError: if `features` exposes no geometry to read.
            ValueError: if `centroids` is ``False`` and a geometry that is present is not a point.

        Examples:
            - The CRS comes from the data unless overridden:
                ```python
                >>> import geopandas as gpd
                >>> from shapely.geometry import Point
                >>> from digitalearth.base.points import PointArrays
                >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1), Point(2, 3)], crs="EPSG:4326")
                >>> pts = PointArrays.from_features(gdf)
                >>> pts.x.tolist(), pts.crs.to_epsg()
                ([0.0, 2.0], 4326)

                ```
            - A missing geometry reads as `NaN` even with `centroids=False`, keeps the other points'
              heights, and is dropped by :meth:`finite`:
                ```python
                >>> import geopandas as gpd
                >>> from shapely.geometry import Point
                >>> from digitalearth.base.points import PointArrays
                >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1, 5), None, Point(2, 3, 7)])
                >>> pts = PointArrays.from_features(gdf, centroids=False)
                >>> pts.x.tolist(), pts.z.tolist()
                ([0.0, nan, 2.0], [5.0, nan, 7.0])
                >>> pts.finite()[0].z.tolist()
                [5.0, 7.0]

                ```
            - A polygon falls back to its centroid, or is refused when `centroids=False`:
                ```python
                >>> import geopandas as gpd
                >>> from shapely.geometry import Polygon
                >>> from digitalearth.base.points import PointArrays
                >>> square = gpd.GeoDataFrame(geometry=[Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])])
                >>> centre = PointArrays.from_features(square)
                >>> centre.x.tolist(), centre.y.tolist()
                ([1.0], [1.0])
                >>> PointArrays.from_features(square, centroids=False)  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: PointArrays.from_features got geometry that is not all points, and centroids=False...

                ```
        """
        frame = (
            features.to_geodataframe()
            if hasattr(features, "to_geodataframe")
            else features
        )
        geom = getattr(frame, "geometry", frame)
        # geom_type first: geopandas raises ValueError from `.x` on a non-point series rather than
        # answering, so `hasattr(geom, "x")` raises too instead of returning False.
        if not hasattr(geom, "geom_type"):
            raise TypeError(
                f"PointArrays.from_features needs vector data with a geometry; got "
                f"{type(features).__name__}"
            )
        # Judge only the geometry that is there. A null geometry's `geom_type` is NaN, so testing the whole
        # series classified a frame with one missing row as "not all points" — which made `centroids=False`
        # refuse a frame the caller had every right to pass, and that these call sites used to draw.
        present = geom.notna()
        if not bool((geom.geom_type[present] == "Point").all()):
            if not centroids:
                raise ValueError(
                    "PointArrays.from_features got geometry that is not all points, and centroids=False. "
                    "Pass centroids=True to use each geometry's centre point"
                )
            geom = geom.centroid
        # Judged on present geometry too, for the reason the type check is: a null's `has_z` is False, so
        # one missing row made a 3-D frame read as flat and zeroed the heights of every point in it.
        has_z = bool(
            getattr(geom, "has_z", None) is not None
            and present.any()
            and geom.has_z[present].all()
        )
        return cls.of(
            geom.x.to_numpy(),
            geom.y.to_numpy(),
            geom.z.to_numpy() if has_z else None,
            crs=crs if crs is not None else getattr(geom, "crs", None),
        )

    # ------------------------------------------------------------------ readers

    def __eq__(self, other: Any) -> bool:
        """Compare by coordinates and CRS, element by element.

        Args:
            other: The value to compare with.

        Returns:
            ``True`` when both hold the same points in the same order, in the same CRS.

            The dataclass-generated ``__eq__`` compared the arrays with ``==``, which yields an array and
            then raises *"The truth value of an array with more than one element is ambiguous"* — so two
            perfectly ordinary instances could not be compared at all. Points are bulk data, so this type is
            deliberately **not** hashable: `Bounds` and `Selection` key caches, this one does not.

        Examples:
            - Two identical readings compare equal:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]) == PointArrays.of([0.0, 1.0], [2.0, 3.0])
                True

                ```
        """
        if not isinstance(other, PointArrays):
            return NotImplemented
        return (
            self.crs == other.crs
            and np.array_equal(self.x, other.x)
            and np.array_equal(self.y, other.y)
            and np.array_equal(self.z, other.z)
        )

    def __len__(self) -> int:
        """Return how many points there are.

        Returns:
            The point count.
        """
        return len(self.x)

    def finite(
        self, *aligned: Any, dims: str = "xy"
    ) -> tuple["PointArrays", tuple[np.ndarray | None, ...]]:
        """Drop points whose coordinates are not finite, taking aligned arrays with them.

        The far side of a clipped or globe display CRS reprojects to ``inf``/``nan``. Passing those on does
        not raise where they are made — it fails later, inside a tessellator, a binner or matplotlib, with a
        message about neither the points nor the projection.

        Args:
            *aligned: Optional per-point arrays to filter by the same mask — a value column, an id column.
                A ``None`` entry passes through as ``None``, so a caller with an optional column needs no
                branch of its own.
            dims: Which coordinates have to be finite. The default ``"xy"`` is deliberate: most consumers are
                2-D, and a point with a perfectly good position but an unknown *elevation* is still a point
                they can draw. Folding `z` in by default silently changed the topology of a 2-D Delaunay
                tessellation. Pass ``"xyz"`` where a missing z really does make the point unusable. Each
                axis may appear once, and at least one must.

        Returns:
            A ``(points, aligned)`` pair: the surviving points, and the filtered arrays in the order given.

        Raises:
            ValueError: if `dims` names a letter other than `x`, `y` and `z`, is empty, or names an axis twice.
            IndexError: if an array in `aligned` is not the same length as the points, raised by numpy when
                the mask is applied to it.

        Examples:
            - Points on the far side of a globe are removed:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> pts = PointArrays.of([0.0, float("nan")], [1.0, 2.0])
                >>> kept, _ = pts.finite()
                >>> len(kept)
                1

                ```
            - An unknown elevation does not remove a point a 2-D consumer can still draw:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> pts = PointArrays.of([0.0, 1.0], [2.0, 3.0], [9.0, float("nan")])
                >>> len(pts.finite()[0]), len(pts.finite(dims="xyz")[0])
                (2, 1)

                ```
            - A repeated axis is refused rather than read as the axis the caller probably meant:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> PointArrays.of([0.0], [1.0]).finite(dims="xx")
                Traceback (most recent call last):
                    ...
                ValueError: finite() needs each of 'x', 'y' and 'z' named at most once, and at least one; got 'xx'

                ```
        """
        axes = {"x": self.x, "y": self.y, "z": self.z}
        unknown = sorted(set(dims) - set(axes))
        if unknown:
            raise ValueError(
                f"finite() takes dims made of 'x', 'y' and 'z'; got {dims!r}, which names {unknown}"
            )
        # Checking only for unknown letters let two typos through: "" masks on nothing, so every point
        # survives and the call reads as working; a repeated letter is a sign the caller meant another axis.
        if not dims or len(set(dims)) != len(dims):
            raise ValueError(
                f"finite() needs each of 'x', 'y' and 'z' named at most once, and at least one; got {dims!r}"
            )
        mask = np.ones(len(self.x), dtype=bool)
        for name in dims:
            mask &= np.isfinite(axes[name])
        # Boolean indexing already copies, so these are fresh buffers; marking them read-only keeps the
        # guarantee `of` makes, since finite() is the other way an instance is built.
        kept_x, kept_y, kept_z = self.x[mask], self.y[mask], self.z[mask]
        for array in (kept_x, kept_y, kept_z):
            array.flags.writeable = False
        kept = PointArrays(kept_x, kept_y, kept_z, self.crs)
        filtered = tuple(
            None if item is None else np.asarray(item)[mask] for item in aligned
        )
        return kept, filtered

    def as_columns(self) -> np.ndarray:
        """Return the points as an ``(N, 3)`` array, the shape the 3-D tiers stack by hand.

        Returns:
            One row per point, columns ``x``, ``y``, ``z``.

        Examples:
            - The shape PyVista and deck.gl both want:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_columns().shape
                (2, 3)

                ```
        """
        return np.column_stack([self.x, self.y, self.z])

    def as_xy(self) -> list[np.ndarray]:
        """Return ``[x, y]`` for the many 2-D consumers that want exactly that.

        Returns:
            The two coordinate arrays, so a 2-D call site never has to know `z` exists.

        Examples:
            - Unpacked straight into a 2-D consumer:
                ```python
                >>> from digitalearth.base.points import PointArrays
                >>> x, y = PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_xy()
                >>> x.tolist(), y.tolist()
                ([0.0, 1.0], [2.0, 3.0])

                ```
        """
        return [self.x, self.y]

__eq__(other) #

Compare by coordinates and CRS, element by element.

Parameters:

Name Type Description Default
other Any

The value to compare with.

required

Returns:

Type Description
bool

True when both hold the same points in the same order, in the same CRS.

bool

The dataclass-generated __eq__ compared the arrays with ==, which yields an array and

bool

then raises "The truth value of an array with more than one element is ambiguous" — so two

bool

perfectly ordinary instances could not be compared at all. Points are bulk data, so this type is

bool

deliberately not hashable: Bounds and Selection key caches, this one does not.

Examples:

  • Two identical readings compare equal:
    >>> from digitalearth.base.points import PointArrays
    >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]) == PointArrays.of([0.0, 1.0], [2.0, 3.0])
    True
    
Source code in src/digitalearth/base/points.py
def __eq__(self, other: Any) -> bool:
    """Compare by coordinates and CRS, element by element.

    Args:
        other: The value to compare with.

    Returns:
        ``True`` when both hold the same points in the same order, in the same CRS.

        The dataclass-generated ``__eq__`` compared the arrays with ``==``, which yields an array and
        then raises *"The truth value of an array with more than one element is ambiguous"* — so two
        perfectly ordinary instances could not be compared at all. Points are bulk data, so this type is
        deliberately **not** hashable: `Bounds` and `Selection` key caches, this one does not.

    Examples:
        - Two identical readings compare equal:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]) == PointArrays.of([0.0, 1.0], [2.0, 3.0])
            True

            ```
    """
    if not isinstance(other, PointArrays):
        return NotImplemented
    return (
        self.crs == other.crs
        and np.array_equal(self.x, other.x)
        and np.array_equal(self.y, other.y)
        and np.array_equal(self.z, other.z)
    )

__len__() #

Return how many points there are.

Returns:

Type Description
int

The point count.

Source code in src/digitalearth/base/points.py
def __len__(self) -> int:
    """Return how many points there are.

    Returns:
        The point count.
    """
    return len(self.x)

__post_init__() #

Refuse arrays that are not index-aligned.

Raises:

Type Description
ValueError

if x, y and z differ in length.

Source code in src/digitalearth/base/points.py
def __post_init__(self) -> None:
    """Refuse arrays that are not index-aligned.

    Raises:
        ValueError: if `x`, `y` and `z` differ in length.
    """
    lengths = {len(self.x), len(self.y), len(self.z)}
    if len(lengths) != 1:
        raise ValueError(
            f"PointArrays needs x, y and z the same length; got {len(self.x)}, "
            f"{len(self.y)}, {len(self.z)}"
        )

as_columns() #

Return the points as an (N, 3) array, the shape the 3-D tiers stack by hand.

Returns:

Type Description
ndarray

One row per point, columns x, y, z.

Examples:

  • The shape PyVista and deck.gl both want:
    >>> from digitalearth.base.points import PointArrays
    >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_columns().shape
    (2, 3)
    
Source code in src/digitalearth/base/points.py
def as_columns(self) -> np.ndarray:
    """Return the points as an ``(N, 3)`` array, the shape the 3-D tiers stack by hand.

    Returns:
        One row per point, columns ``x``, ``y``, ``z``.

    Examples:
        - The shape PyVista and deck.gl both want:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_columns().shape
            (2, 3)

            ```
    """
    return np.column_stack([self.x, self.y, self.z])

as_xy() #

Return [x, y] for the many 2-D consumers that want exactly that.

Returns:

Type Description
list[ndarray]

The two coordinate arrays, so a 2-D call site never has to know z exists.

Examples:

  • Unpacked straight into a 2-D consumer:
    >>> from digitalearth.base.points import PointArrays
    >>> x, y = PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_xy()
    >>> x.tolist(), y.tolist()
    ([0.0, 1.0], [2.0, 3.0])
    
Source code in src/digitalearth/base/points.py
def as_xy(self) -> list[np.ndarray]:
    """Return ``[x, y]`` for the many 2-D consumers that want exactly that.

    Returns:
        The two coordinate arrays, so a 2-D call site never has to know `z` exists.

    Examples:
        - Unpacked straight into a 2-D consumer:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> x, y = PointArrays.of([0.0, 1.0], [2.0, 3.0]).as_xy()
            >>> x.tolist(), y.tolist()
            ([0.0, 1.0], [2.0, 3.0])

            ```
    """
    return [self.x, self.y]

finite(*aligned, dims='xy') #

Drop points whose coordinates are not finite, taking aligned arrays with them.

The far side of a clipped or globe display CRS reprojects to inf/nan. Passing those on does not raise where they are made — it fails later, inside a tessellator, a binner or matplotlib, with a message about neither the points nor the projection.

Parameters:

Name Type Description Default
*aligned Any

Optional per-point arrays to filter by the same mask — a value column, an id column. A None entry passes through as None, so a caller with an optional column needs no branch of its own.

()
dims str

Which coordinates have to be finite. The default "xy" is deliberate: most consumers are 2-D, and a point with a perfectly good position but an unknown elevation is still a point they can draw. Folding z in by default silently changed the topology of a 2-D Delaunay tessellation. Pass "xyz" where a missing z really does make the point unusable. Each axis may appear once, and at least one must.

'xy'

Returns:

Type Description
tuple[PointArrays, tuple[ndarray | None, ...]]

A (points, aligned) pair: the surviving points, and the filtered arrays in the order given.

Raises:

Type Description
ValueError

if dims names a letter other than x, y and z, is empty, or names an axis twice.

IndexError

if an array in aligned is not the same length as the points, raised by numpy when the mask is applied to it.

Examples:

  • Points on the far side of a globe are removed:
    >>> from digitalearth.base.points import PointArrays
    >>> pts = PointArrays.of([0.0, float("nan")], [1.0, 2.0])
    >>> kept, _ = pts.finite()
    >>> len(kept)
    1
    
  • An unknown elevation does not remove a point a 2-D consumer can still draw:
    >>> from digitalearth.base.points import PointArrays
    >>> pts = PointArrays.of([0.0, 1.0], [2.0, 3.0], [9.0, float("nan")])
    >>> len(pts.finite()[0]), len(pts.finite(dims="xyz")[0])
    (2, 1)
    
  • A repeated axis is refused rather than read as the axis the caller probably meant:
    >>> from digitalearth.base.points import PointArrays
    >>> PointArrays.of([0.0], [1.0]).finite(dims="xx")
    Traceback (most recent call last):
        ...
    ValueError: finite() needs each of 'x', 'y' and 'z' named at most once, and at least one; got 'xx'
    
Source code in src/digitalearth/base/points.py
def finite(
    self, *aligned: Any, dims: str = "xy"
) -> tuple["PointArrays", tuple[np.ndarray | None, ...]]:
    """Drop points whose coordinates are not finite, taking aligned arrays with them.

    The far side of a clipped or globe display CRS reprojects to ``inf``/``nan``. Passing those on does
    not raise where they are made — it fails later, inside a tessellator, a binner or matplotlib, with a
    message about neither the points nor the projection.

    Args:
        *aligned: Optional per-point arrays to filter by the same mask — a value column, an id column.
            A ``None`` entry passes through as ``None``, so a caller with an optional column needs no
            branch of its own.
        dims: Which coordinates have to be finite. The default ``"xy"`` is deliberate: most consumers are
            2-D, and a point with a perfectly good position but an unknown *elevation* is still a point
            they can draw. Folding `z` in by default silently changed the topology of a 2-D Delaunay
            tessellation. Pass ``"xyz"`` where a missing z really does make the point unusable. Each
            axis may appear once, and at least one must.

    Returns:
        A ``(points, aligned)`` pair: the surviving points, and the filtered arrays in the order given.

    Raises:
        ValueError: if `dims` names a letter other than `x`, `y` and `z`, is empty, or names an axis twice.
        IndexError: if an array in `aligned` is not the same length as the points, raised by numpy when
            the mask is applied to it.

    Examples:
        - Points on the far side of a globe are removed:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> pts = PointArrays.of([0.0, float("nan")], [1.0, 2.0])
            >>> kept, _ = pts.finite()
            >>> len(kept)
            1

            ```
        - An unknown elevation does not remove a point a 2-D consumer can still draw:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> pts = PointArrays.of([0.0, 1.0], [2.0, 3.0], [9.0, float("nan")])
            >>> len(pts.finite()[0]), len(pts.finite(dims="xyz")[0])
            (2, 1)

            ```
        - A repeated axis is refused rather than read as the axis the caller probably meant:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> PointArrays.of([0.0], [1.0]).finite(dims="xx")
            Traceback (most recent call last):
                ...
            ValueError: finite() needs each of 'x', 'y' and 'z' named at most once, and at least one; got 'xx'

            ```
    """
    axes = {"x": self.x, "y": self.y, "z": self.z}
    unknown = sorted(set(dims) - set(axes))
    if unknown:
        raise ValueError(
            f"finite() takes dims made of 'x', 'y' and 'z'; got {dims!r}, which names {unknown}"
        )
    # Checking only for unknown letters let two typos through: "" masks on nothing, so every point
    # survives and the call reads as working; a repeated letter is a sign the caller meant another axis.
    if not dims or len(set(dims)) != len(dims):
        raise ValueError(
            f"finite() needs each of 'x', 'y' and 'z' named at most once, and at least one; got {dims!r}"
        )
    mask = np.ones(len(self.x), dtype=bool)
    for name in dims:
        mask &= np.isfinite(axes[name])
    # Boolean indexing already copies, so these are fresh buffers; marking them read-only keeps the
    # guarantee `of` makes, since finite() is the other way an instance is built.
    kept_x, kept_y, kept_z = self.x[mask], self.y[mask], self.z[mask]
    for array in (kept_x, kept_y, kept_z):
        array.flags.writeable = False
    kept = PointArrays(kept_x, kept_y, kept_z, self.crs)
    filtered = tuple(
        None if item is None else np.asarray(item)[mask] for item in aligned
    )
    return kept, filtered

from_features(features, *, centroids=True, crs=None) classmethod #

Extract coordinates from a pyramids FeatureCollection or a geopandas frame.

Parameters:

Name Type Description Default
features Any

The collection, frame or geometry series to read. A FeatureCollection is converted through to_geodataframe(), which is the only way this package touches vector data.

required
centroids bool

What to do with geometry that is not a point. True (default) falls back to the centroid, which is what the source extractor does; False raises instead, for a caller whose maths is only meaningful on real points.

True
crs Any

Override the CRS to record. Defaults to whatever the input declares.

None

Returns:

Type Description
PointArrays

The coordinates, with z taken from the geometry when every point is 3-D, and zeros

PointArrays

otherwise. A frame mixing 2-D and 3-D points therefore reads as flat: has_z.all() is what

PointArrays

geopandas can answer cheaply, and a partly-3-D frame has no elevation for some of its points

PointArrays

anyway.

PointArrays

A row whose geometry is missing reads as NaN, whatever centroids says. A null geometry

PointArrays

is ordinary in GeoJSON, and it is absent data rather than data of the wrong shape — so it is for

PointArrays

meth:finite to drop, which is what every caller does with it. Only a geometry that is

PointArrays

genuinely present is subject to the centroids decision, and only present geometry decides

PointArrays

whether the frame is 3-D: a null among 3-D points keeps the others' heights, and its own z is

PointArrays

NaN like its x and y.

Raises:

Type Description
TypeError

if features exposes no geometry to read.

ValueError

if centroids is False and a geometry that is present is not a point.

Examples:

  • The CRS comes from the data unless overridden:
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from digitalearth.base.points import PointArrays
    >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1), Point(2, 3)], crs="EPSG:4326")
    >>> pts = PointArrays.from_features(gdf)
    >>> pts.x.tolist(), pts.crs.to_epsg()
    ([0.0, 2.0], 4326)
    
  • A missing geometry reads as NaN even with centroids=False, keeps the other points' heights, and is dropped by :meth:finite:
    >>> import geopandas as gpd
    >>> from shapely.geometry import Point
    >>> from digitalearth.base.points import PointArrays
    >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1, 5), None, Point(2, 3, 7)])
    >>> pts = PointArrays.from_features(gdf, centroids=False)
    >>> pts.x.tolist(), pts.z.tolist()
    ([0.0, nan, 2.0], [5.0, nan, 7.0])
    >>> pts.finite()[0].z.tolist()
    [5.0, 7.0]
    
  • A polygon falls back to its centroid, or is refused when centroids=False:
    >>> import geopandas as gpd
    >>> from shapely.geometry import Polygon
    >>> from digitalearth.base.points import PointArrays
    >>> square = gpd.GeoDataFrame(geometry=[Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])])
    >>> centre = PointArrays.from_features(square)
    >>> centre.x.tolist(), centre.y.tolist()
    ([1.0], [1.0])
    >>> PointArrays.from_features(square, centroids=False)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: PointArrays.from_features got geometry that is not all points, and centroids=False...
    
Source code in src/digitalearth/base/points.py
@classmethod
def from_features(
    cls, features: Any, *, centroids: bool = True, crs: Any = None
) -> "PointArrays":
    """Extract coordinates from a pyramids ``FeatureCollection`` or a geopandas frame.

    Args:
        features: The collection, frame or geometry series to read. A ``FeatureCollection`` is converted
            through ``to_geodataframe()``, which is the only way this package touches vector data.
        centroids: What to do with geometry that is not a point. ``True`` (default) falls back to the
            centroid, which is what the source extractor does; ``False`` raises instead, for a caller
            whose maths is only meaningful on real points.
        crs: Override the CRS to record. Defaults to whatever the input declares.

    Returns:
        The coordinates, with `z` taken from the geometry when **every** point is 3-D, and zeros
        otherwise. A frame mixing 2-D and 3-D points therefore reads as flat: `has_z.all()` is what
        geopandas can answer cheaply, and a partly-3-D frame has no elevation for some of its points
        anyway.

        A row whose geometry is **missing** reads as `NaN`, whatever `centroids` says. A `null` geometry
        is ordinary in GeoJSON, and it is absent data rather than data of the wrong shape — so it is for
        :meth:`finite` to drop, which is what every caller does with it. Only a geometry that is
        genuinely present is subject to the `centroids` decision, and only present geometry decides
        whether the frame is 3-D: a null among 3-D points keeps the others' heights, and its own `z` is
        `NaN` like its `x` and `y`.

    Raises:
        TypeError: if `features` exposes no geometry to read.
        ValueError: if `centroids` is ``False`` and a geometry that is present is not a point.

    Examples:
        - The CRS comes from the data unless overridden:
            ```python
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from digitalearth.base.points import PointArrays
            >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1), Point(2, 3)], crs="EPSG:4326")
            >>> pts = PointArrays.from_features(gdf)
            >>> pts.x.tolist(), pts.crs.to_epsg()
            ([0.0, 2.0], 4326)

            ```
        - A missing geometry reads as `NaN` even with `centroids=False`, keeps the other points'
          heights, and is dropped by :meth:`finite`:
            ```python
            >>> import geopandas as gpd
            >>> from shapely.geometry import Point
            >>> from digitalearth.base.points import PointArrays
            >>> gdf = gpd.GeoDataFrame(geometry=[Point(0, 1, 5), None, Point(2, 3, 7)])
            >>> pts = PointArrays.from_features(gdf, centroids=False)
            >>> pts.x.tolist(), pts.z.tolist()
            ([0.0, nan, 2.0], [5.0, nan, 7.0])
            >>> pts.finite()[0].z.tolist()
            [5.0, 7.0]

            ```
        - A polygon falls back to its centroid, or is refused when `centroids=False`:
            ```python
            >>> import geopandas as gpd
            >>> from shapely.geometry import Polygon
            >>> from digitalearth.base.points import PointArrays
            >>> square = gpd.GeoDataFrame(geometry=[Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])])
            >>> centre = PointArrays.from_features(square)
            >>> centre.x.tolist(), centre.y.tolist()
            ([1.0], [1.0])
            >>> PointArrays.from_features(square, centroids=False)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: PointArrays.from_features got geometry that is not all points, and centroids=False...

            ```
    """
    frame = (
        features.to_geodataframe()
        if hasattr(features, "to_geodataframe")
        else features
    )
    geom = getattr(frame, "geometry", frame)
    # geom_type first: geopandas raises ValueError from `.x` on a non-point series rather than
    # answering, so `hasattr(geom, "x")` raises too instead of returning False.
    if not hasattr(geom, "geom_type"):
        raise TypeError(
            f"PointArrays.from_features needs vector data with a geometry; got "
            f"{type(features).__name__}"
        )
    # Judge only the geometry that is there. A null geometry's `geom_type` is NaN, so testing the whole
    # series classified a frame with one missing row as "not all points" — which made `centroids=False`
    # refuse a frame the caller had every right to pass, and that these call sites used to draw.
    present = geom.notna()
    if not bool((geom.geom_type[present] == "Point").all()):
        if not centroids:
            raise ValueError(
                "PointArrays.from_features got geometry that is not all points, and centroids=False. "
                "Pass centroids=True to use each geometry's centre point"
            )
        geom = geom.centroid
    # Judged on present geometry too, for the reason the type check is: a null's `has_z` is False, so
    # one missing row made a 3-D frame read as flat and zeroed the heights of every point in it.
    has_z = bool(
        getattr(geom, "has_z", None) is not None
        and present.any()
        and geom.has_z[present].all()
    )
    return cls.of(
        geom.x.to_numpy(),
        geom.y.to_numpy(),
        geom.z.to_numpy() if has_z else None,
        crs=crs if crs is not None else getattr(geom, "crs", None),
    )

of(x, y, z=None, *, crs=None) classmethod #

Build from coordinate sequences, forcing the dtype every call site used to choose for itself.

Parameters:

Name Type Description Default
x Any

X coordinates.

required
y Any

Y coordinates.

required
z Any

Z coordinates, or None for zeros.

None
crs Any

What the coordinates are measured in.

None

Returns:

Type Description
PointArrays

The arrays as float64, which is what every consumer wanted and only some asked for.

Raises:

Type Description
ValueError

if the sequences are not the same length.

Examples:

  • Integer input comes back as floats, with z filled in:
    >>> from digitalearth.base.points import PointArrays
    >>> pts = PointArrays.of([0, 1], [2, 3], crs=4326)
    >>> pts.x.tolist(), pts.z.tolist()
    ([0.0, 1.0], [0.0, 0.0])
    
Source code in src/digitalearth/base/points.py
@classmethod
def of(cls, x: Any, y: Any, z: Any = None, *, crs: Any = None) -> "PointArrays":
    """Build from coordinate sequences, forcing the dtype every call site used to choose for itself.

    Args:
        x: X coordinates.
        y: Y coordinates.
        z: Z coordinates, or ``None`` for zeros.
        crs: What the coordinates are measured in.

    Returns:
        The arrays as ``float64``, which is what every consumer wanted and only some asked for.

    Raises:
        ValueError: if the sequences are not the same length.

    Examples:
        - Integer input comes back as floats, with z filled in:
            ```python
            >>> from digitalearth.base.points import PointArrays
            >>> pts = PointArrays.of([0, 1], [2, 3], crs=4326)
            >>> pts.x.tolist(), pts.z.tolist()
            ([0.0, 1.0], [0.0, 0.0])

            ```
    """
    # np.array, not np.asarray: asarray does not copy a contiguous float64 input, so the "frozen" value
    # would share memory with the caller's buffer and change underneath it. The arrays are then marked
    # read-only, because `x`/`y`/`z` and `as_xy()` hand them straight back out.
    xs = np.array(x, dtype="float64").ravel()
    ys = np.array(y, dtype="float64").ravel()
    zs = np.zeros_like(xs) if z is None else np.array(z, dtype="float64").ravel()
    for array in (xs, ys, zs):
        array.flags.writeable = False
    return cls(xs, ys, zs, crs)

MeshSource — an unstructured mesh, with its own connectivity#

A raster Source carries a grid and two axis vectors; a point Source carries three parallel arrays. A UGRID mesh is neither: its cells are listed rather than implied, so the geometry only exists once the connectivity travels with the coordinates — together with where on it the values sit, since a variable may be given per node or per face.

The triangles come from pyramids (Mesh2d.fan_triangles, which cuts every face — triangle, quad or larger polygon — with pure numpy), not from a triangulation computed here. Re-triangulating the nodes would invent faces the mesh does not have and paint face-located values onto them.

Which backends draw one. A MeshDataset is accepted by quickmap(backend="matplotlib"), which draws it with tripcolor — each face shaded its own colour. The interactive, web and 3-D tiers have no triangular render, so they refuse a mesh by name rather than drawing it as something else. Note this is about the mesh input: the unstructured row of the support matrix is about the triangulated verbs (tricontourf / tricontour / tripcolor), which the interactive tier does have for scattered points.

A mesh that declares a CRS is drawn in any display CRS pyproj.CRS.from_user_input accepts — an EPSG code, a "+proj=..." string, WKT or an ESRI: code — because pyramids (since pyramids-core 0.73.0, serapeum-org/pyramids-core#1404) warps a mesh to a CRS given in any form. An orthographic, Robinson or Mollweide display CRS is drawn like any other: the warp sends nodes beyond a globe's limb to non-finite coordinates, and the triangles leaning on them are then dropped, as off-view geometry is for every layer family.

digitalearth.base.sources.MeshSource #

Bases: Source

An unstructured-mesh source: node coordinates, an explicit triangulation, and values on it.

Parameters:

Name Type Description Default
z DimensionInfo | None

The values (a :class:DimensionInfo) — one per node for location="node", one per triangle for location="face".

required
x DimensionInfo

The node x / longitude coordinates (a :class:DimensionInfo), 1-D, one per node.

required
y DimensionInfo

The node y / latitude coordinates (a :class:DimensionInfo), 1-D, one per node.

required
triangles Any

The triangulation as an (n_triangles, 3) array of node indices. A mesh face with more than three nodes is already fan-triangulated by the extractor, so this is always triangles — the one shape every triangular renderer takes.

required
location str

"node" or "face" — which of the two z is aligned with.

required
crs Any

The CRS the coordinates are expressed in, as given.

None
metadata dict | None

Free-form metadata (kind, variable, n_faces, …).

None
units str | None

Unit string for the values, or None.

None

Both shapes it documents are enforced in __init__: the triangulation must be (n_triangles, 3) indices into the nodes it was given, and z must hold one value per node or per triangle. Checking them is the point of the object — an invalid one otherwise surfaced as an IndexError from inside matplotlib, several frames from the mistake.

Examples:

  • A two-triangle mesh with a value on each face:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo, MeshSource
    >>> nodes_x = DimensionInfo(np.array([0.0, 1.0, 0.0, 1.0]), "x")
    >>> nodes_y = DimensionInfo(np.array([0.0, 0.0, 1.0, 1.0]), "y")
    >>> faces = np.array([[0, 1, 2], [1, 3, 2]])
    >>> src = MeshSource(DimensionInfo(np.array([10.0, 20.0]), "z"), nodes_x, nodes_y,
    ...                  triangles=faces, location="face", crs=4326)
    >>> src.triangles.shape
    (2, 3)
    >>> src.location
    'face'
    >>> src.n_triangles
    2
    
  • The values may instead sit on the nodes, in which case there is one per coordinate:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo, MeshSource
    >>> src = MeshSource(DimensionInfo(np.arange(4.0), "z"),
    ...                  DimensionInfo(np.zeros(4), "x"), DimensionInfo(np.zeros(4), "y"),
    ...                  triangles=np.array([[0, 1, 2]]), location="node")
    >>> src.location, src.z.values.size
    ('node', 4)
    
  • Values that do not line up with what location says are refused:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo, MeshSource
    >>> try:
    ...     MeshSource(DimensionInfo(np.arange(9.0), "z"),
    ...                DimensionInfo(np.zeros(4), "x"), DimensionInfo(np.zeros(4), "y"),
    ...                triangles=np.array([[0, 1, 2]]), location="face")
    ... except ValueError as error:
    ...     print(error)
    face-located values must be one per triangle (1 expected), got 9
    
  • An unknown location is refused, because a renderer would otherwise guess which array to colour:
    >>> import numpy as np
    >>> from digitalearth.base.sources import DimensionInfo, MeshSource
    >>> try:
    ...     MeshSource(None, DimensionInfo(np.zeros(3), "x"), DimensionInfo(np.zeros(3), "y"),
    ...                triangles=np.array([[0, 1, 2]]), location="edge")
    ... except ValueError as error:
    ...     print(error)
    location='edge' is not one of ('node', 'face')
    
Source code in src/digitalearth/base/sources/mesh.py
class MeshSource(Source):
    """An unstructured-mesh source: node coordinates, an explicit triangulation, and values on it.

    Args:
        z: The values (a :class:`DimensionInfo`) — one per node for ``location="node"``, one per triangle
            for ``location="face"``.
        x: The node x / longitude coordinates (a :class:`DimensionInfo`), 1-D, one per node.
        y: The node y / latitude coordinates (a :class:`DimensionInfo`), 1-D, one per node.
        triangles: The triangulation as an ``(n_triangles, 3)`` array of node indices. A mesh face with
            more than three nodes is already fan-triangulated by the extractor, so this is always
            triangles — the one shape every triangular renderer takes.
        location: ``"node"`` or ``"face"`` — which of the two ``z`` is aligned with.
        crs: The CRS the coordinates are expressed in, **as given**.
        metadata: Free-form metadata (``kind``, ``variable``, ``n_faces``, …).
        units: Unit string for the values, or ``None``.

    Both shapes it documents are enforced in ``__init__``: the triangulation must be ``(n_triangles, 3)``
    indices into the nodes it was given, and ``z`` must hold one value per node or per triangle. Checking
    them is the point of the object — an invalid one otherwise surfaced as an ``IndexError`` from inside
    matplotlib, several frames from the mistake.

    Examples:
        - A two-triangle mesh with a value on each face:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo, MeshSource
            >>> nodes_x = DimensionInfo(np.array([0.0, 1.0, 0.0, 1.0]), "x")
            >>> nodes_y = DimensionInfo(np.array([0.0, 0.0, 1.0, 1.0]), "y")
            >>> faces = np.array([[0, 1, 2], [1, 3, 2]])
            >>> src = MeshSource(DimensionInfo(np.array([10.0, 20.0]), "z"), nodes_x, nodes_y,
            ...                  triangles=faces, location="face", crs=4326)
            >>> src.triangles.shape
            (2, 3)
            >>> src.location
            'face'
            >>> src.n_triangles
            2

            ```
        - The values may instead sit on the nodes, in which case there is one per coordinate:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo, MeshSource
            >>> src = MeshSource(DimensionInfo(np.arange(4.0), "z"),
            ...                  DimensionInfo(np.zeros(4), "x"), DimensionInfo(np.zeros(4), "y"),
            ...                  triangles=np.array([[0, 1, 2]]), location="node")
            >>> src.location, src.z.values.size
            ('node', 4)

            ```
        - Values that do not line up with what ``location`` says are refused:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo, MeshSource
            >>> try:
            ...     MeshSource(DimensionInfo(np.arange(9.0), "z"),
            ...                DimensionInfo(np.zeros(4), "x"), DimensionInfo(np.zeros(4), "y"),
            ...                triangles=np.array([[0, 1, 2]]), location="face")
            ... except ValueError as error:
            ...     print(error)
            face-located values must be one per triangle (1 expected), got 9

            ```
        - An unknown location is refused, because a renderer would otherwise guess which array to colour:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.sources import DimensionInfo, MeshSource
            >>> try:
            ...     MeshSource(None, DimensionInfo(np.zeros(3), "x"), DimensionInfo(np.zeros(3), "y"),
            ...                triangles=np.array([[0, 1, 2]]), location="edge")
            ... except ValueError as error:
            ...     print(error)
            location='edge' is not one of ('node', 'face')

            ```
    """

    def __init__(
        self,
        z: DimensionInfo | None,
        x: DimensionInfo,
        y: DimensionInfo,
        *,
        triangles: Any,
        location: str,
        crs: Any = None,
        metadata: dict | None = None,
        units: str | None = None,
    ):
        if location not in MESH_LOCATIONS:
            raise ValueError(f"location={location!r} is not one of {MESH_LOCATIONS}")
        faces = np.asarray(triangles)
        nodes = int(np.asarray(x.values).size)
        _check_triangles(faces, nodes)
        if z is not None:
            expected = int(faces.shape[0]) if location == "face" else nodes
            held = int(np.asarray(z.values).size)
            if held != expected:
                raise ValueError(
                    f"{location}-located values must be one per "
                    f"{'triangle' if location == 'face' else 'node'} "
                    f"({expected} expected), got {held}"
                )
        super().__init__(z, x, y, crs, metadata, units)
        self._triangles = faces
        self._location = location

    @property
    def triangles(self) -> np.ndarray:
        """The triangulation as an ``(n_triangles, 3)`` array of node indices."""
        return self._triangles

    @property
    def location(self) -> str:
        """Which of :data:`MESH_LOCATIONS` the values in ``z`` are aligned with."""
        return self._location

    @property
    def n_triangles(self) -> int:
        """How many triangles the mesh draws as."""
        return int(self._triangles.shape[0]) if self._triangles.ndim == 2 else 0

location property #

Which of :data:MESH_LOCATIONS the values in z are aligned with.

n_triangles property #

How many triangles the mesh draws as.

triangles property #

The triangulation as an (n_triangles, 3) array of node indices.

Getting data into the display CRS#

The three helpers each tier used to define for itself.

digitalearth.base.display.needs_reproject(data, crs) #

Whether data must be reprojected to reach the display CRS.

Parameters:

Name Type Description Default
data Any

A pyramids object — a Dataset or FeatureCollection — exposing .crs and/or .epsg.

required
crs Any

The display CRS, in any spelling pyramids reads: an EPSG int, an "EPSG:<code>" string, a proj4 or WKT string, or a pyproj CRS.

required

Returns:

Type Description
bool

False when the data's own CRS and crs name the same reference system; True otherwise,

bool

including for data that declares no CRS at all.

bool

The two are compared by meaning, through :func:~digitalearth.base.spec.bounds.same_crs, the rule

bool

Bounds and Viewport already use. Comparing Python values instead skipped a warp only for an

bool

int display CRS, so a view holding "EPSG:4326" — the spelling Viewport writes for a CRS

bool

object — warped data that was already in EPSG:4326.

bool

The data's CRS definition (.crs) is read before its EPSG code, which is only the fallback. An

bool

EPSG code says nothing about a projection with no authority code, while the definition does: an

bool

orthographic dataset still warps to EPSG:4326, and needs no warp to its own orthographic CRS.

bool

Both attributes are read with getattr, so an input declaring no CRS gets an answer rather than an

bool

AttributeError.

Examples:

  • The same system needs no warp, however the display CRS is spelled:
    >>> from types import SimpleNamespace
    >>> from digitalearth.base.display import needs_reproject
    >>> data = SimpleNamespace(epsg=4326)
    >>> needs_reproject(data, 4326), needs_reproject(data, "EPSG:4326")
    (False, False)
    
  • A different system warps, and so does data that declares no CRS:
    >>> from types import SimpleNamespace
    >>> from digitalearth.base.display import needs_reproject
    >>> needs_reproject(SimpleNamespace(epsg=4326), "+proj=ortho +lat_0=53 +lon_0=4")
    True
    >>> needs_reproject(SimpleNamespace(), 4326)
    True
    
Source code in src/digitalearth/base/display.py
def needs_reproject(data: Any, crs: Any) -> bool:
    """Whether `data` must be reprojected to reach the display CRS.

    Args:
        data: A pyramids object — a `Dataset` or `FeatureCollection` — exposing `.crs` and/or `.epsg`.
        crs: The display CRS, in any spelling pyramids reads: an EPSG `int`, an `"EPSG:<code>"` string, a
            proj4 or WKT string, or a pyproj `CRS`.

    Returns:
        `False` when the data's own CRS and `crs` name the same reference system; `True` otherwise,
        including for data that declares no CRS at all.

        The two are compared by meaning, through :func:`~digitalearth.base.spec.bounds.same_crs`, the rule
        `Bounds` and `Viewport` already use. Comparing Python values instead skipped a warp only for an
        `int` display CRS, so a view holding `"EPSG:4326"` — the spelling `Viewport` writes for a CRS
        object — warped data that was already in EPSG:4326.

        The data's CRS **definition** (`.crs`) is read before its EPSG code, which is only the fallback. An
        EPSG code says nothing about a projection with no authority code, while the definition does: an
        orthographic dataset still warps to EPSG:4326, and needs no warp to its own orthographic CRS.

        Both attributes are read with `getattr`, so an input declaring no CRS gets an answer rather than an
        `AttributeError`.

    Examples:
        - The same system needs no warp, however the display CRS is spelled:
            ```python
            >>> from types import SimpleNamespace
            >>> from digitalearth.base.display import needs_reproject
            >>> data = SimpleNamespace(epsg=4326)
            >>> needs_reproject(data, 4326), needs_reproject(data, "EPSG:4326")
            (False, False)

            ```
        - A different system warps, and so does data that declares no CRS:
            ```python
            >>> from types import SimpleNamespace
            >>> from digitalearth.base.display import needs_reproject
            >>> needs_reproject(SimpleNamespace(epsg=4326), "+proj=ortho +lat_0=53 +lon_0=4")
            True
            >>> needs_reproject(SimpleNamespace(), 4326)
            True

            ```
    """
    own = getattr(data, "crs", None)
    if own is None:
        own = getattr(data, "epsg", None)
    if own is None:
        return True
    return not same_crs(own, crs)

digitalearth.base.display.to_display_source(data, crs, *, band=DEFAULT_BAND) #

Reproject data into the display CRS through pyramids, and wrap it as a :class:Source.

The single display-CRS choke point a raster or vector builder calls. It settles the projection decision the same way on every tier: pre-reproject in pyramids, no cartopy anywhere. Data already in the display CRS passes through untouched.

Parameters:

Name Type Description Default
data Any

A pyramids Dataset / FeatureCollection, or anything :func:~digitalearth.base.sources.get_source accepts. A Source passes straight back — it has already been placed.

required
crs Any

The display CRS.

required
band int

1-based band to extract for raster inputs.

DEFAULT_BAND

Returns:

Type Description
Source

The display-CRS source.

Raises:

Type Description
Exception

whatever pyramids raises for a warp it cannot perform, or the extractor for data it cannot read.

Examples:

  • A plain array has no CRS to warp from, so it goes straight to extraction:
    >>> import numpy as np
    >>> from digitalearth.base.display import to_display_source
    >>> to_display_source(np.arange(6.0).reshape(2, 3), 4326).z.values.shape
    (2, 3)
    
Source code in src/digitalearth/base/display.py
def to_display_source(data: Any, crs: Any, *, band: int = DEFAULT_BAND) -> Source:
    """Reproject `data` into the display CRS through pyramids, and wrap it as a :class:`Source`.

    The single display-CRS choke point a raster or vector builder calls. It settles the projection decision
    the same way on every tier: **pre-reproject in pyramids**, no cartopy anywhere. Data already in the
    display CRS passes through untouched.

    Args:
        data: A pyramids ``Dataset`` / ``FeatureCollection``, or anything
            :func:`~digitalearth.base.sources.get_source` accepts. A `Source` passes straight back — it has
            already been placed.
        crs: The display CRS.
        band: 1-based band to extract for raster inputs.

    Returns:
        The display-CRS source.

    Raises:
        Exception: whatever pyramids raises for a warp it cannot perform, or the extractor for data it
            cannot read.

    Examples:
        - A plain array has no CRS to warp from, so it goes straight to extraction:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.display import to_display_source
            >>> to_display_source(np.arange(6.0).reshape(2, 3), 4326).z.values.shape
            (2, 3)

            ```
    """
    if isinstance(data, Source):
        return data
    if hasattr(data, "epsg") and hasattr(data, "to_crs") and needs_reproject(data, crs):
        data = reproject(data, crs)
    return get_source(data, band=band)

digitalearth.base.display.auto_cmap(source, cmap, fallback=DEFAULT_CMAP, *, lookup=None) #

Return the colormap to draw source with, resolving from its variable when the caller named none.

Defers to lookup, which by default is :func:digitalearth.base.autostyle.auto_style — the same variable→style table the static Map consults, ECMWF-Magics match included — so a recognised field is coloured the same way whichever tier renders it. Neither source nor the lookup is consulted when the caller named a colormap.

Parameters:

Name Type Description Default
source Any

The display-CRS source whose variable drives the lookup.

required
cmap str | None

The caller's colormap, or None to resolve one.

required
fallback str

Colormap to use when the lookup's answer has no cmap, or an empty one. The default lookup always answers one — viridis for a variable it does not recognise — so with lookup=None this is not reached.

DEFAULT_CMAP
lookup Callable[[Any], dict[str, Any]] | None

The style lookup to consult, taking source and returning the style dict. None calls :func:~digitalearth.base.autostyle.auto_style directly. A tier passes its own lookup method here — the interactive tier's _auto_style, the web tier's _style_for — because those methods are documented as the tier's single entry into the style table, and the tier's levels and units readers go through them. Calling auto_style directly instead made the colormap a separate lookup from the other two, and took away the one hook a subclass or a test had for replacing the lookup across all three.

None

Returns:

Type Description
str

The caller's cmap when they named one, else the lookup's answer, else fallback.

str

The fallback is reached with or rather than as a dict.get default. Both spellings give the

str

same answer for every input the shipped library can produce — it seeds each result from a default

str

group carrying viridis, so cmap is always present and truthy. or is chosen because it also

str

holds if a library ever answers with cmap=None or "", which .get("cmap", "viridis")

str

would hand back as the colormap.

Examples:

  • A caller's choice always wins:
    >>> from digitalearth.base.display import auto_cmap
    >>> auto_cmap(None, "magma")
    'magma'
    
  • A tier hands in its own lookup, and the colormap is whatever that lookup answers:
    >>> from digitalearth.base.display import auto_cmap
    >>> auto_cmap(None, None, lookup=lambda source: {"cmap": "RdBu_r", "units": "K"})
    'RdBu_r'
    
  • fallback is used only when the answer names no colormap; the default lookup always names one:
    >>> import numpy as np
    >>> from digitalearth.base.display import auto_cmap
    >>> from digitalearth.base.sources import get_source
    >>> auto_cmap(None, None, "gray", lookup=lambda source: {})
    'gray'
    >>> auto_cmap(get_source(np.zeros((2, 2))), None, "gray")
    'viridis'
    
Source code in src/digitalearth/base/display.py
def auto_cmap(
    source: Any,
    cmap: str | None,
    fallback: str = DEFAULT_CMAP,
    *,
    lookup: Callable[[Any], dict[str, Any]] | None = None,
) -> str:
    """Return the colormap to draw `source` with, resolving from its variable when the caller named none.

    Defers to `lookup`, which by default is :func:`digitalearth.base.autostyle.auto_style` — the same
    variable→style table the static ``Map`` consults, ECMWF-Magics match included — so a recognised field is
    coloured the same way whichever tier renders it. Neither `source` nor the lookup is consulted when the
    caller named a colormap.

    Args:
        source: The display-CRS source whose variable drives the lookup.
        cmap: The caller's colormap, or ``None`` to resolve one.
        fallback: Colormap to use when the lookup's answer has no `cmap`, or an empty one. The default
            lookup always answers one — `viridis` for a variable it does not recognise — so with
            `lookup=None` this is not reached.
        lookup: The style lookup to consult, taking `source` and returning the style dict. ``None`` calls
            :func:`~digitalearth.base.autostyle.auto_style` directly. A tier passes its own lookup method
            here — the interactive tier's ``_auto_style``, the web tier's ``_style_for`` — because those
            methods are documented as the tier's *single* entry into the style table, and the tier's
            ``levels`` and ``units`` readers go through them. Calling ``auto_style`` directly instead made
            the colormap a separate lookup from the other two, and took away the one hook a subclass or a
            test had for replacing the lookup across all three.

    Returns:
        The caller's `cmap` when they named one, else the lookup's answer, else `fallback`.

        The fallback is reached with ``or`` rather than as a ``dict.get`` default. Both spellings give the
        same answer for every input the shipped library can produce — it seeds each result from a ``default``
        group carrying ``viridis``, so ``cmap`` is always present and truthy. ``or`` is chosen because it also
        holds if a library ever answers with ``cmap=None`` or ``""``, which ``.get("cmap", "viridis")``
        would hand back as the colormap.

    Examples:
        - A caller's choice always wins:
            ```python
            >>> from digitalearth.base.display import auto_cmap
            >>> auto_cmap(None, "magma")
            'magma'

            ```
        - A tier hands in its own lookup, and the colormap is whatever that lookup answers:
            ```python
            >>> from digitalearth.base.display import auto_cmap
            >>> auto_cmap(None, None, lookup=lambda source: {"cmap": "RdBu_r", "units": "K"})
            'RdBu_r'

            ```
        - `fallback` is used only when the answer names no colormap; the default lookup always names one:
            ```python
            >>> import numpy as np
            >>> from digitalearth.base.display import auto_cmap
            >>> from digitalearth.base.sources import get_source
            >>> auto_cmap(None, None, "gray", lookup=lambda source: {})
            'gray'
            >>> auto_cmap(get_source(np.zeros((2, 2))), None, "gray")
            'viridis'

            ```
    """
    if cmap is not None:
        return cmap
    if lookup is None:
        from digitalearth.base.autostyle import auto_style

        lookup = auto_style
    style: dict[str, Any] = lookup(source)
    return style.get("cmap") or fallback

LayerSpec and LayerTree — a layer described, and addressed by id#

Every tier kept a list called layers, three of them addressed it by position, and none kept what a layer is. LayerSpec is that description — kind, source, slice, style — with no data object, viewport or engine handle, and LayerTree orders layers bottom first and addresses them by id. Every change to a tree returns a new tree.

digitalearth.base.spec.layer.LayerSpec dataclass #

What one layer draws, described without drawing it.

Where a decoration lives. Anything drawn in map coordinates is a layer, decoration included: a basemap, coastlines, a graticule, a string placed at a coordinate. Its kind's band (:data:~digitalearth.base.registry.KIND_BANDS) decides where in draw order it lands, so a graticule added last is still drawn under the data. The three other homes are for what has no place on the ground: whatever explains an encoding is a Guide on that :class:~digitalearth.base.spec.encoding.Encoding (a legend, a colorbar), whatever is fixed to the frame is :class:~digitalearth.base.spec.furniture.Furniture on the PanelSpec (a scale bar, a north arrow, a navigation control), and the panel's heading is its title.

Attributes:

Name Type Description
id str

The layer's identity within its figure, unique within a :class:LayerTree, and the only way a layer is addressed — never by position.

kind str

What sort of layer it is — "raster", "points", "graticule" — as a key into the kind registry (:func:~digitalearth.base.registry.kind_info). A lowercase identifier, optionally after one namespace and a colon ("custom:pyvista"). The spelling is checked here; whether the kind is registered is checked by the renderer that draws it, so a figure naming a plugin's kind still loads where the plugin is not installed.

source_id str | None

The key of the layer's data in the figure's sources, or None for a layer drawn from no data source (a graticule, a tile basemap).

selection Selection

Which slice of the source the layer draws.

symbology Symbology

How the layer looks.

z_source str | None

Where the layer's elevation comes from: None for a flat layer, a source id, or "layer:<id>" for another layer's surface — imagery draped over terrain (#202).

visible bool

Whether the layer is drawn. A hidden layer stays in the tree, which is what lets a viewer turn it back on.

label str | None

What a layer switcher calls it; None means the id.

group str | None

The group the layer belongs to, so a set of layers can be hidden together.

band str | None

Where this layer is drawn, overriding the band its kind declares — one of :data:~digitalearth.base.registry.KIND_BANDS, or None to take the kind's. A custom layer needs it: a caller's own object is custom:<engine> whatever it draws, so only the caller can say whether it is ground cover or a label.

filter str | None

A filter expression, carried for the renderer rather than interpreted here. A string — SQL-like, as the static and interactive tiers write one — or a JSON expression, as MapLibre and deck.gl take one (["==", ["get", "class"], "road"]). A list is stored as a tuple, like every other sequence here, and is written back as a list by to_dict.

Raises:

Type Description
ValueError

for an id that is not a non-empty string, a kind that is not a lowercase identifier, a non-boolean visible, a selection or symbology of the wrong type, a source_id, z_source, label, group or filter that is neither None nor a non-empty string, a band outside :data:~digitalearth.base.registry.KIND_BANDS, or a z_source of "layer:" that names no layer or names the layer itself.

Examples:

  • A raster layer over a source, drawn at 80% opacity:
    >>> from digitalearth.base.spec import LayerSpec, Symbology
    >>> dem = LayerSpec("dem", "raster", source_id="srtm", symbology=Symbology.of(opacity=0.8))
    >>> dem.kind, dem.source_id, dem.visible, dem.symbology.encoding("opacity").resolve()
    ('raster', 'srtm', True, 0.8)
    
  • A layer can be drawn outside the band its kind declares, which is what a caller's own object needs:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tiles = LayerSpec("tiles", "custom:maplibre", band="underlay")
    >>> LayerTree().add(LayerSpec("dem", "raster")).add(tiles).ids
    ('tiles', 'dem')
    
  • Imagery draped over that layer names it as its elevation source:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("imagery", "rgb", source_id="s2", z_source="layer:dem").z_layer
    'dem'
    
  • A layer cannot drape itself over itself:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("dem", "raster", z_source="layer:dem")
    Traceback (most recent call last):
        ...
    ValueError: layer 'dem' cannot take its elevation from itself
    
Source code in src/digitalearth/base/spec/layer.py
@dataclass(frozen=True)
class LayerSpec:
    """What one layer draws, described without drawing it.

    **Where a decoration lives.** Anything drawn in map coordinates is a layer, decoration included: a basemap,
    coastlines, a graticule, a string placed at a coordinate. Its kind's band
    (:data:`~digitalearth.base.registry.KIND_BANDS`) decides where in draw order it lands, so a graticule added
    last is still drawn under the data. The three other homes are for what has no place on the ground: whatever
    explains an encoding is a `Guide` on that :class:`~digitalearth.base.spec.encoding.Encoding` (a legend, a
    colorbar), whatever is fixed to the frame is :class:`~digitalearth.base.spec.furniture.Furniture` on the
    `PanelSpec` (a scale bar, a north arrow, a navigation control), and the panel's heading is its `title`.

    Attributes:
        id: The layer's identity within its figure, unique within a :class:`LayerTree`, and the only way
            a layer is addressed — never by position.
        kind: What sort of layer it is — `"raster"`, `"points"`, `"graticule"` — as a key into the kind
            registry (:func:`~digitalearth.base.registry.kind_info`). A lowercase identifier, optionally after one
            namespace and a colon (`"custom:pyvista"`). The spelling is checked here; whether the kind is
            registered is checked by the renderer that draws it, so a figure naming a plugin's kind still loads
            where the plugin is not installed.
        source_id: The key of the layer's data in the figure's sources, or ``None`` for a layer drawn from no data
            source (a graticule, a tile basemap).
        selection: Which slice of the source the layer draws.
        symbology: How the layer looks.
        z_source: Where the layer's elevation comes from: ``None`` for a flat layer, a source id, or
            ``"layer:<id>"`` for another layer's surface — imagery draped over terrain (#202).
        visible: Whether the layer is drawn. A hidden layer stays in the tree, which is what lets a viewer turn it
            back on.
        label: What a layer switcher calls it; ``None`` means the id.
        group: The group the layer belongs to, so a set of layers can be hidden together.
        band: Where this layer is drawn, overriding the band its kind declares — one of
            :data:`~digitalearth.base.registry.KIND_BANDS`, or `None` to take the kind's. A custom layer needs
            it: a caller's own object is `custom:<engine>` whatever it draws, so only the caller can say whether
            it is ground cover or a label.
        filter: A filter expression, carried for the renderer rather than interpreted here. A string — SQL-like,
            as the static and interactive tiers write one — or a JSON expression, as MapLibre and deck.gl take
            one (`["==", ["get", "class"], "road"]`). A list is stored as a tuple, like every other sequence
            here, and is written back as a list by `to_dict`.

    Raises:
        ValueError: for an id that is not a non-empty string, a kind that is not a
            lowercase identifier, a non-boolean `visible`, a `selection` or `symbology` of the wrong type, a
            `source_id`, `z_source`, `label`, `group` or `filter` that is neither `None` nor a non-empty string, a
            `band` outside :data:`~digitalearth.base.registry.KIND_BANDS`, or
            a `z_source` of `"layer:"` that names no layer or names the layer itself.

    Examples:
        - A raster layer over a source, drawn at 80% opacity:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, Symbology
            >>> dem = LayerSpec("dem", "raster", source_id="srtm", symbology=Symbology.of(opacity=0.8))
            >>> dem.kind, dem.source_id, dem.visible, dem.symbology.encoding("opacity").resolve()
            ('raster', 'srtm', True, 0.8)

            ```
        - A layer can be drawn outside the band its kind declares, which is what a caller's own object needs:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tiles = LayerSpec("tiles", "custom:maplibre", band="underlay")
            >>> LayerTree().add(LayerSpec("dem", "raster")).add(tiles).ids
            ('tiles', 'dem')

            ```
        - Imagery draped over that layer names it as its elevation source:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> LayerSpec("imagery", "rgb", source_id="s2", z_source="layer:dem").z_layer
            'dem'

            ```
        - A layer cannot drape itself over itself:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> LayerSpec("dem", "raster", z_source="layer:dem")
            Traceback (most recent call last):
                ...
            ValueError: layer 'dem' cannot take its elevation from itself

            ```
    """

    id: str
    kind: str
    source_id: str | None = None
    selection: Selection = field(default_factory=Selection)
    symbology: Symbology = field(default_factory=Symbology)
    z_source: str | None = None
    visible: bool = True
    label: str | None = None
    group: str | None = None
    band: str | None = None
    filter: str | None = None

    def __post_init__(self) -> None:
        """Refuse a layer that could not be addressed, looked up or drawn.

        Raises:
            ValueError: as described on the class.
        """
        # Compared exactly and kept exactly: the web tier issues a caller's layer name verbatim as its MapLibre id,
        # and refusing a padded one would refuse a figure an older version wrote. No tier mints one any more —
        # `layer_name` strips a caller's `name=` at the mint, because a padded id crashed three of the four
        # tiers on the way back out of the object registry (review R2-H4).
        if not isinstance(self.id, str) or not self.id:
            raise ValueError(
                f"LayerSpec needs an id that is a non-empty string; got {self.id!r}"
            )
        if not is_kind_name(self.kind):
            # The spelling rule lives with the kind registry, so a name a renderer can look up and a name a layer
            # can hold are one rule; whether the kind is *registered* is the renderer's question, not this one's.
            raise ValueError(
                "LayerSpec kind must be a lowercase identifier such as 'raster' or 'points', optionally after one "
                f"namespace such as 'custom:pyvista'; got {self.kind!r}"
            )
        if not isinstance(self.selection, Selection):
            raise ValueError(
                f"LayerSpec selection must be a Selection; got {type(self.selection).__name__}"
            )
        if not isinstance(self.symbology, Symbology):
            raise ValueError(
                f"LayerSpec symbology must be a Symbology; got {type(self.symbology).__name__}"
            )
        visible = true_or_false(self.visible)
        if visible is None:
            # "False" or 0 would read as a caller's intent in some places and not others; only a real boolean
            # says what it means — Python's or numpy's, which is what a comparison on an array gives back.
            raise ValueError(
                f"LayerSpec visible must be True or False; got {self.visible!r}"
            )
        object.__setattr__(self, "visible", visible)
        for name in ("source_id", "z_source", "label", "group"):
            _optional_text("LayerSpec", name, getattr(self, name))
        object.__setattr__(self, "filter", _checked_filter(self.filter))
        if self.band is not None and self.band not in KIND_BANDS:
            raise ValueError(
                f"LayerSpec band must be one of {list(KIND_BANDS)} or None; got {self.band!r}"
            )
        if self.z_source is not None and self.z_source.startswith(LAYER_REFERENCE):
            target = self.z_source[len(LAYER_REFERENCE) :]
            if not target:
                raise ValueError(
                    f"LayerSpec z_source {self.z_source!r} names no layer after {LAYER_REFERENCE!r}"
                )
            if target == self.id:
                raise ValueError(
                    f"layer {self.id!r} cannot take its elevation from itself"
                )

    @property
    def z_layer(self) -> str | None:
        """The id of the layer this one takes its elevation from, if it takes it from a layer.

        Returns:
            The layer id after ``"layer:"``, or ``None`` when `z_source` is unset or names a source.

        Examples:
            - A draped layer names the layer beneath it; a flat one names nothing:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> LayerSpec("a", "rgb", z_source="layer:dem").z_layer, LayerSpec("b", "raster").z_layer
                ('dem', None)

                ```
        """
        if self.z_source is None or not self.z_source.startswith(LAYER_REFERENCE):
            return None
        return self.z_source[len(LAYER_REFERENCE) :]

    @property
    def display_label(self) -> str:
        """What a layer switcher shows for this layer.

        Returns:
            `label`, or the id when no label was given.

        Examples:
            - The id stands in for a missing label:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> LayerSpec("roads", "lines").display_label, LayerSpec("r", "lines", label="Roads").display_label
                ('roads', 'Roads')

                ```
        """
        return self.label if self.label is not None else self.id

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``id`` and ``kind``, plus each field that differs from its default — so a plain visible layer with no
            source, slice or style stores two keys.

        Raises:
            TypeError: if the selection or the symbology holds a value with no JSON form.

        Examples:
            - Only what was set is written:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> LayerSpec("dem", "raster", source_id="srtm", visible=False).to_dict()
                {'id': 'dem', 'kind': 'raster', 'source_id': 'srtm', 'visible': False}

                ```
            - A plain visible layer with no source, slice or style stores two keys:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> LayerSpec("grid", "graticule").to_dict()
                {'id': 'grid', 'kind': 'graticule'}

                ```
        """
        out: dict[str, Any] = {"id": plain_text(self.id), "kind": plain_text(self.kind)}
        if self.source_id is not None:
            out["source_id"] = plain_text(self.source_id)
        if self.selection != Selection():
            out["selection"] = self.selection.to_dict()
        styled = self.symbology.to_dict()
        if styled:
            out["symbology"] = styled
        for name in ("z_source", "label", "group", "band"):
            value = getattr(self, name)
            if value is not None:
                out[name] = plain_text(value)
        if self.filter is not None:
            out["filter"] = to_json_value(self.filter, f"LayerSpec[{self.id!r}].filter")
        if not self.visible:
            out["visible"] = False
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "LayerSpec":
        """Rebuild a layer from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The layer, validated as the constructor validates it.

        Raises:
            TypeError: if `data`, or its `selection` or `symbology`, is not a mapping.
            ValueError: for a missing id or kind, an unknown key, a `selection` or `symbology` its own `from_dict`
                refuses, or a field the constructor refuses. An error of either type from the stored selection or
                symbology names where it sits:
                `LayerSpec.from_dict selection: Selection.from_dict needs a mapping; got int`.

        Examples:
            - A stored layer reads back with its slice:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> layer = LayerSpec.from_dict({"id": "t2m", "kind": "raster", "selection": {"band": [2]}})
                >>> layer.selection.band
                (2,)

                ```
            - Z-order lives in the tree, so an `order` key is unknown and refused rather than dropped:
                ```python
                >>> from digitalearth.base.spec import LayerSpec
                >>> LayerSpec.from_dict({"id": "dem", "kind": "raster", "order": 0})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: LayerSpec.from_dict got unknown keys ['order']; known keys are ['band', 'filter', ...]

                ```
        """
        refuse_unknown(
            "LayerSpec",
            data,
            (
                "id",
                "kind",
                "source_id",
                "selection",
                "symbology",
                "z_source",
                "visible",
                "label",
                "group",
                "band",
                "filter",
            ),
        )
        selection = data.get("selection")
        symbology = data.get("symbology")
        return cls(
            id=require("LayerSpec", data, "id"),
            kind=require("LayerSpec", data, "kind"),
            source_id=data.get("source_id"),
            selection=Selection()
            if selection is None
            else read_entry("LayerSpec", "selection", Selection.from_dict, selection),
            symbology=Symbology()
            if symbology is None
            else read_entry("LayerSpec", "symbology", Symbology.from_dict, symbology),
            z_source=data.get("z_source"),
            visible=data.get("visible", True),
            label=data.get("label"),
            group=data.get("group"),
            band=data.get("band"),
            filter=data.get("filter"),
        )

display_label property #

What a layer switcher shows for this layer.

Returns:

Type Description
str

label, or the id when no label was given.

Examples:

  • The id stands in for a missing label:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("roads", "lines").display_label, LayerSpec("r", "lines", label="Roads").display_label
    ('roads', 'Roads')
    

z_layer property #

The id of the layer this one takes its elevation from, if it takes it from a layer.

Returns:

Type Description
str | None

The layer id after "layer:", or None when z_source is unset or names a source.

Examples:

  • A draped layer names the layer beneath it; a flat one names nothing:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("a", "rgb", z_source="layer:dem").z_layer, LayerSpec("b", "raster").z_layer
    ('dem', None)
    

__post_init__() #

Refuse a layer that could not be addressed, looked up or drawn.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/layer.py
def __post_init__(self) -> None:
    """Refuse a layer that could not be addressed, looked up or drawn.

    Raises:
        ValueError: as described on the class.
    """
    # Compared exactly and kept exactly: the web tier issues a caller's layer name verbatim as its MapLibre id,
    # and refusing a padded one would refuse a figure an older version wrote. No tier mints one any more —
    # `layer_name` strips a caller's `name=` at the mint, because a padded id crashed three of the four
    # tiers on the way back out of the object registry (review R2-H4).
    if not isinstance(self.id, str) or not self.id:
        raise ValueError(
            f"LayerSpec needs an id that is a non-empty string; got {self.id!r}"
        )
    if not is_kind_name(self.kind):
        # The spelling rule lives with the kind registry, so a name a renderer can look up and a name a layer
        # can hold are one rule; whether the kind is *registered* is the renderer's question, not this one's.
        raise ValueError(
            "LayerSpec kind must be a lowercase identifier such as 'raster' or 'points', optionally after one "
            f"namespace such as 'custom:pyvista'; got {self.kind!r}"
        )
    if not isinstance(self.selection, Selection):
        raise ValueError(
            f"LayerSpec selection must be a Selection; got {type(self.selection).__name__}"
        )
    if not isinstance(self.symbology, Symbology):
        raise ValueError(
            f"LayerSpec symbology must be a Symbology; got {type(self.symbology).__name__}"
        )
    visible = true_or_false(self.visible)
    if visible is None:
        # "False" or 0 would read as a caller's intent in some places and not others; only a real boolean
        # says what it means — Python's or numpy's, which is what a comparison on an array gives back.
        raise ValueError(
            f"LayerSpec visible must be True or False; got {self.visible!r}"
        )
    object.__setattr__(self, "visible", visible)
    for name in ("source_id", "z_source", "label", "group"):
        _optional_text("LayerSpec", name, getattr(self, name))
    object.__setattr__(self, "filter", _checked_filter(self.filter))
    if self.band is not None and self.band not in KIND_BANDS:
        raise ValueError(
            f"LayerSpec band must be one of {list(KIND_BANDS)} or None; got {self.band!r}"
        )
    if self.z_source is not None and self.z_source.startswith(LAYER_REFERENCE):
        target = self.z_source[len(LAYER_REFERENCE) :]
        if not target:
            raise ValueError(
                f"LayerSpec z_source {self.z_source!r} names no layer after {LAYER_REFERENCE!r}"
            )
        if target == self.id:
            raise ValueError(
                f"layer {self.id!r} cannot take its elevation from itself"
            )

from_dict(data) classmethod #

Rebuild a layer from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
LayerSpec

The layer, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data, or its selection or symbology, is not a mapping.

ValueError

for a missing id or kind, an unknown key, a selection or symbology its own from_dict refuses, or a field the constructor refuses. An error of either type from the stored selection or symbology names where it sits: LayerSpec.from_dict selection: Selection.from_dict needs a mapping; got int.

Examples:

  • A stored layer reads back with its slice:
    >>> from digitalearth.base.spec import LayerSpec
    >>> layer = LayerSpec.from_dict({"id": "t2m", "kind": "raster", "selection": {"band": [2]}})
    >>> layer.selection.band
    (2,)
    
  • Z-order lives in the tree, so an order key is unknown and refused rather than dropped:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec.from_dict({"id": "dem", "kind": "raster", "order": 0})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: LayerSpec.from_dict got unknown keys ['order']; known keys are ['band', 'filter', ...]
    
Source code in src/digitalearth/base/spec/layer.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "LayerSpec":
    """Rebuild a layer from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The layer, validated as the constructor validates it.

    Raises:
        TypeError: if `data`, or its `selection` or `symbology`, is not a mapping.
        ValueError: for a missing id or kind, an unknown key, a `selection` or `symbology` its own `from_dict`
            refuses, or a field the constructor refuses. An error of either type from the stored selection or
            symbology names where it sits:
            `LayerSpec.from_dict selection: Selection.from_dict needs a mapping; got int`.

    Examples:
        - A stored layer reads back with its slice:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> layer = LayerSpec.from_dict({"id": "t2m", "kind": "raster", "selection": {"band": [2]}})
            >>> layer.selection.band
            (2,)

            ```
        - Z-order lives in the tree, so an `order` key is unknown and refused rather than dropped:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> LayerSpec.from_dict({"id": "dem", "kind": "raster", "order": 0})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: LayerSpec.from_dict got unknown keys ['order']; known keys are ['band', 'filter', ...]

            ```
    """
    refuse_unknown(
        "LayerSpec",
        data,
        (
            "id",
            "kind",
            "source_id",
            "selection",
            "symbology",
            "z_source",
            "visible",
            "label",
            "group",
            "band",
            "filter",
        ),
    )
    selection = data.get("selection")
    symbology = data.get("symbology")
    return cls(
        id=require("LayerSpec", data, "id"),
        kind=require("LayerSpec", data, "kind"),
        source_id=data.get("source_id"),
        selection=Selection()
        if selection is None
        else read_entry("LayerSpec", "selection", Selection.from_dict, selection),
        symbology=Symbology()
        if symbology is None
        else read_entry("LayerSpec", "symbology", Symbology.from_dict, symbology),
        z_source=data.get("z_source"),
        visible=data.get("visible", True),
        label=data.get("label"),
        group=data.get("group"),
        band=data.get("band"),
        filter=data.get("filter"),
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

id and kind, plus each field that differs from its default — so a plain visible layer with no

dict[str, Any]

source, slice or style stores two keys.

Raises:

Type Description
TypeError

if the selection or the symbology holds a value with no JSON form.

Examples:

  • Only what was set is written:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("dem", "raster", source_id="srtm", visible=False).to_dict()
    {'id': 'dem', 'kind': 'raster', 'source_id': 'srtm', 'visible': False}
    
  • A plain visible layer with no source, slice or style stores two keys:
    >>> from digitalearth.base.spec import LayerSpec
    >>> LayerSpec("grid", "graticule").to_dict()
    {'id': 'grid', 'kind': 'graticule'}
    
Source code in src/digitalearth/base/spec/layer.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``id`` and ``kind``, plus each field that differs from its default — so a plain visible layer with no
        source, slice or style stores two keys.

    Raises:
        TypeError: if the selection or the symbology holds a value with no JSON form.

    Examples:
        - Only what was set is written:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> LayerSpec("dem", "raster", source_id="srtm", visible=False).to_dict()
            {'id': 'dem', 'kind': 'raster', 'source_id': 'srtm', 'visible': False}

            ```
        - A plain visible layer with no source, slice or style stores two keys:
            ```python
            >>> from digitalearth.base.spec import LayerSpec
            >>> LayerSpec("grid", "graticule").to_dict()
            {'id': 'grid', 'kind': 'graticule'}

            ```
    """
    out: dict[str, Any] = {"id": plain_text(self.id), "kind": plain_text(self.kind)}
    if self.source_id is not None:
        out["source_id"] = plain_text(self.source_id)
    if self.selection != Selection():
        out["selection"] = self.selection.to_dict()
    styled = self.symbology.to_dict()
    if styled:
        out["symbology"] = styled
    for name in ("z_source", "label", "group", "band"):
        value = getattr(self, name)
        if value is not None:
            out[name] = plain_text(value)
    if self.filter is not None:
        out["filter"] = to_json_value(self.filter, f"LayerSpec[{self.id!r}].filter")
    if not self.visible:
        out["visible"] = False
    return out

digitalearth.base.spec.layer.LayerTree dataclass #

The layers of a figure, in draw order, addressed by id.

Every change returns a new tree of the same type — a subclass stays a subclass — and leaves this one as it was, so a renderer can compare the tree it drew with the tree it is asked to draw.

A layer is placed in the band its kind belongs to (:data:~digitalearth.base.registry.KIND_BANDS), not simply where it was added: ground cover stays under the data, a graticule over the ground but under the data, labels over everything. That is what every tier already does by hand — the web tier counts underlays onto its queue, the interactive tier inserts at position 0, the static tier sets zorder — expressed once, so the tree order is the draw order.

Attributes:

Name Type Description
layers tuple[LayerSpec, ...]

The layers, bottom first — the first is drawn first and so sits beneath the rest.

hidden_groups frozenset[str]

The groups switched off. A layer in a hidden group is not drawn whatever its own visible says, and comes back as it was when the group is switched on again.

Raises:

Type Description
ValueError

for an entry that is not a LayerSpec, two layers sharing an id, a z_source naming a layer that is not in the tree, a chain of z_source references that loops back on itself, hidden_groups given as a bare string or bytes rather than a collection of names, a hidden-group entry that is not a string (LayerTree hidden_groups must be group names (strings); got 1), or a hidden group no layer belongs to.

Examples:

  • Build a tree and address layers by id rather than by position:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("dem", "raster")).add(LayerSpec("roads", "lines"))
    >>> tree.ids
    ('dem', 'roads')
    >>> tree.move("roads", 0).ids
    ('roads', 'dem')
    
  • Hiding a group hides its layers without forgetting their own visibility:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "points"))
    >>> hidden = tree.set_group_visible("obs", False)
    >>> hidden.is_visible("a"), hidden.is_visible("b"), hidden.get("a").visible
    (False, True, True)
    
  • Draped layers that take their elevation from each other in a loop are refused:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> looped = (LayerSpec("a", "rgb", z_source="layer:b"), LayerSpec("b", "rgb", z_source="layer:a"))
    >>> LayerTree(looped)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: z_source references loop: a -> b -> a. ...
    
Source code in src/digitalearth/base/spec/layer.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
@dataclass(frozen=True)
class LayerTree:
    """The layers of a figure, in draw order, addressed by id.

    Every change returns a new tree of the same type — a subclass stays a subclass — and leaves this one as it was,
    so a renderer can compare the tree it drew with the tree it is asked to draw.

    A layer is placed in the band its kind belongs to (:data:`~digitalearth.base.registry.KIND_BANDS`), not
    simply where it was added: ground cover stays under the data, a graticule over the ground but under the data,
    labels over everything. That is what every tier already does by hand — the web tier counts underlays onto its
    queue, the interactive tier inserts at position 0, the static tier sets `zorder` — expressed once, so the tree
    order *is* the draw order.

    Attributes:
        layers: The layers, bottom first — the first is drawn first and so sits beneath the rest.
        hidden_groups: The groups switched off. A layer in a hidden group is not drawn whatever its own `visible`
            says, and comes back as it was when the group is switched on again.

    Raises:
        ValueError: for an entry that is not a `LayerSpec`, two layers sharing an id, a `z_source` naming a layer
            that is not in the tree, a chain of `z_source` references that loops back on itself, `hidden_groups`
            given as a bare string or bytes rather than a collection of names, a hidden-group entry that is not a
            string (`LayerTree hidden_groups must be group names (strings); got 1`), or a hidden group no layer
            belongs to.

    Examples:
        - Build a tree and address layers by id rather than by position:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("dem", "raster")).add(LayerSpec("roads", "lines"))
            >>> tree.ids
            ('dem', 'roads')
            >>> tree.move("roads", 0).ids
            ('roads', 'dem')

            ```
        - Hiding a group hides its layers without forgetting their own visibility:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "points"))
            >>> hidden = tree.set_group_visible("obs", False)
            >>> hidden.is_visible("a"), hidden.is_visible("b"), hidden.get("a").visible
            (False, True, True)

            ```
        - Draped layers that take their elevation from each other in a loop are refused:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> looped = (LayerSpec("a", "rgb", z_source="layer:b"), LayerSpec("b", "rgb", z_source="layer:a"))
            >>> LayerTree(looped)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: z_source references loop: a -> b -> a. ...

            ```
    """

    layers: tuple[LayerSpec, ...] = ()
    hidden_groups: frozenset[str] = frozenset()

    def __post_init__(self) -> None:
        """Refuse a tree whose ids, references or hidden groups do not hold together.

        Raises:
            ValueError: as described on the class.
        """
        object.__setattr__(self, "layers", tuple(self.layers))
        object.__setattr__(
            self, "hidden_groups", self._checked_hidden_groups(self.hidden_groups)
        )
        for layer in self.layers:
            if not isinstance(layer, LayerSpec):
                raise ValueError(
                    f"LayerTree holds LayerSpec values; got {type(layer).__name__}"
                )
        # Every check below is linear in the layer count. This runs on every add, move and replace — the web tier
        # calls it once per builder — so a quadratic check here made building a map cubic.
        ids = [layer.id for layer in self.layers]
        duplicated = sorted(
            layer_id for layer_id, count in Counter(ids).items() if count > 1
        )
        if duplicated:
            raise ValueError(
                f"LayerTree ids must be unique; {duplicated} appear more than once"
            )
        self._check_drapes(ids)
        unknown_groups = sorted(
            self.hidden_groups - {layer.group for layer in self.layers}
        )
        if unknown_groups:
            raise ValueError(
                f"LayerTree hides groups {unknown_groups} that no layer belongs to; groups are {list(self.groups)}"
            )

    @staticmethod
    def _checked_hidden_groups(hidden_groups: Any) -> frozenset[str]:
        """Return the hidden groups as a frozenset of names, refusing anything that is not one.

        Args:
            hidden_groups: What the constructor was given.

        Returns:
            The names, frozen.

        Raises:
            ValueError: for a bare string or bytes, or an entry that is not a string.
        """
        if isinstance(hidden_groups, (str, bytes)):
            # `frozenset("obs")` is the letters of the name, and a one-letter group would be hidden silently.
            raise ValueError(
                "LayerTree hidden_groups must be a collection of group names; got the string "
                f"{hidden_groups!r}"
            )
        hidden = list(hidden_groups)
        for group in hidden:
            if not isinstance(group, str):
                # Checked before the frozenset and the sorted message in the constructor, which raised bare
                # TypeErrors for an unhashable entry or for names of mixed types.
                raise ValueError(
                    f"LayerTree hidden_groups must be group names (strings); got {group!r}"
                )
        return frozenset(hidden)

    def _check_drapes(self, ids: list[str]) -> None:
        """Refuse a drape over a layer the tree does not hold, or a chain of drapes that loops.

        Args:
            ids: The layer ids, bottom first, for the message.

        Raises:
            ValueError: naming the draped layer and the missing surface, or the loop.
        """
        by_id = {layer.id: layer for layer in self.layers}
        for layer in self.layers:
            if layer.z_layer is not None and layer.z_layer not in by_id:
                raise ValueError(
                    f"layer {layer.id!r} takes its elevation from layer {layer.z_layer!r}, which is not in the tree; "
                    f"layers are {ids}"
                )
        # A layer whose chain of drapes is already known to end on a surface is not walked again.
        grounded: set[str] = set()
        for layer in self.layers:
            chain = [layer.id]
            on_chain = {layer.id}
            target = layer.z_layer
            while target is not None and target not in grounded:
                if target in on_chain:
                    raise ValueError(
                        f"z_source references loop: {' -> '.join(chain + [target])}. A draped layer must end on a "
                        "surface that takes its elevation from a source, not from another layer in the loop"
                    )
                chain.append(target)
                on_chain.add(target)
                target = by_id[target].z_layer
            grounded.update(chain)

    # ------------------------------------------------------------------ reading

    @property
    def ids(self) -> tuple[str, ...]:
        """The layer ids, bottom first.

        Returns:
            The ids in draw order.

        Examples:
            - An empty tree has no ids:
                ```python
                >>> from digitalearth.base.spec import LayerTree
                >>> LayerTree().ids
                ()

                ```
        """
        return tuple(layer.id for layer in self.layers)

    @property
    def groups(self) -> tuple[str, ...]:
        """The groups the layers belong to, in the order each first appears.

        Returns:
            The group names, without repeats.

        Examples:
            - Groups are listed once, in draw order:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree((LayerSpec("a", "points", group="obs"), LayerSpec("b", "lines", group="obs")))
                >>> tree.groups
                ('obs',)

                ```
        """
        # A dict keeps first-seen order and tests membership by hash; a list tested it by comparing against every
        # group seen so far, which made each change quadratic in the number of groups.
        return tuple(
            dict.fromkeys(
                layer.group for layer in self.layers if layer.group is not None
            )
        )

    def __len__(self) -> int:
        """Return how many layers the tree holds.

        Returns:
            The layer count.
        """
        return len(self.layers)

    def __iter__(self) -> Iterator[LayerSpec]:
        """Iterate over the layers, bottom first.

        Returns:
            An iterator over the layers in draw order.
        """
        return iter(self.layers)

    def __contains__(self, layer_id: object) -> bool:
        """Whether a layer with this id is in the tree.

        Args:
            layer_id: The id to look for.

        Returns:
            ``True`` when a layer has that id.
        """
        return layer_id in self.ids

    def get(self, layer_id: str) -> LayerSpec:
        """Return the layer with this id.

        Args:
            layer_id: The id to look up.

        Returns:
            The layer.

        Raises:
            KeyError: if no layer has that id, listing the ids that exist.

        Examples:
            - Look a layer up by id:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("dem", "raster", source_id="srtm")).get("dem").source_id
                'srtm'

                ```
            - An id the tree does not hold is named beside the ids it does:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("dem", "raster")).get("roads")
                Traceback (most recent call last):
                    ...
                KeyError: "no layer 'roads' in this tree; layers are ['dem']"

                ```
        """
        for layer in self.layers:
            if layer.id == layer_id:
                return layer
        raise KeyError(
            f"no layer {layer_id!r} in this tree; layers are {list(self.ids)}"
        )

    def is_visible(self, layer_id: str) -> bool:
        """Whether a layer is drawn: its own `visible`, and its group not hidden.

        Args:
            layer_id: The layer to ask about.

        Returns:
            ``True`` when the layer is switched on and so is its group.

        Raises:
            KeyError: if no layer has that id.

        Examples:
            - A layer switched off is not drawn:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("a", "points", visible=False)).is_visible("a")
                False

                ```
        """
        layer = self.get(layer_id)
        return layer.visible and layer.group not in self.hidden_groups

    # ------------------------------------------------------------------ changes (each returns a new tree)

    def add(self, layer: LayerSpec, *, index: int | None = None) -> "LayerTree":
        """Return a tree with `layer` added.

        Args:
            layer: The layer to add.
            index: Where it goes **within its band**. ``None`` puts it on top of the band, which is what a
                builder wants: a basemap under the data however late it is added, a label over the data however
                early. A position is counted in the whole tree, so the band's own range is what it must fall in.

        Returns:
            The new tree.

        Raises:
            ValueError: if `layer` is not a `LayerSpec`, a layer with the same id is already in the tree, or the
                layer's `z_source` names a layer that is not.
            IndexError: if `index` is outside the layer's band — `list.insert` would clamp it silently, which puts
                the layer somewhere the caller did not ask for — or is not a whole number: a boolean or a float.

        Examples:
            - A basemap is ground cover, so it goes beneath the data wherever it is added:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("roads", "lines"))
                >>> tree.add(LayerSpec("tiles", "basemap")).ids
                ('tiles', 'roads')

                ```
            - Kinds that draw over the data stay over it, and the order within a band is the order they arrived:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("place", "text")).add(LayerSpec("dem", "raster"))
                >>> tree.add(LayerSpec("grid", "graticule")).ids
                ('grid', 'dem', 'place')

                ```
            - A position that would take the layer out of its band is refused rather than clamped:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("dem", "raster")).add(LayerSpec("tiles", "basemap"), index=1)
                Traceback (most recent call last):
                    ...
                IndexError: cannot add 'tiles' at position 1; the underlay band runs from position 0 to 0

                ```
        """
        _check_layer("add", layer)
        if any(existing.id == layer.id for existing in self.layers):
            raise ValueError(
                f"a layer with id {layer.id!r} is already in the tree; layer ids must be unique"
            )
        layers = list(self.layers)
        band = _layer_band(layer)
        low, high = _band_bounds(layers, band)
        if index is None:
            layers.insert(high, layer)
        elif not _is_position(index) or not low <= index <= high:
            raise IndexError(
                f"cannot add {layer.id!r} at position {index!r}; the {band} band runs from position {low} to {high}"
            )
        else:
            layers.insert(index, layer)
        return with_fields(self, layers=tuple(layers))

    def remove(self, layer_id: str) -> "LayerTree":
        """Return a tree without the layer with this id.

        Args:
            layer_id: The layer to remove.

        Returns:
            The new tree. A hidden group left with no layers stops being hidden, since there is nothing left in it.

        Raises:
            KeyError: if no layer has that id.
            ValueError: if another layer takes its elevation from this one — removing the surface would leave the
                draped layer pointing at nothing.

        Examples:
            - Remove a layer by id:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines")).remove("a").ids
                ('b',)

                ```
            - Removing the last layer of a hidden group un-hides the group:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
                >>> hidden = tree.set_group_visible("obs", False)
                >>> hidden.hidden_groups, hidden.remove("a").hidden_groups
                (frozenset({'obs'}), frozenset())

                ```
            - A surface another layer is draped over cannot be removed first:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> draped = LayerSpec("img", "rgb", z_source="layer:dem")
                >>> tree = LayerTree().add(LayerSpec("dem", "raster")).add(draped)
                >>> tree.remove("dem")  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: layer 'dem' cannot be removed while ['img'] take their elevation from it; ...

                ```
        """
        self.get(layer_id)
        dependents = [layer.id for layer in self.layers if layer.z_layer == layer_id]
        if dependents:
            raise ValueError(
                f"layer {layer_id!r} cannot be removed while {dependents} take their elevation from it; remove or "
                "re-point those first"
            )
        layers = tuple(layer for layer in self.layers if layer.id != layer_id)
        groups = {layer.group for layer in layers}
        # `with_fields`, not `LayerTree(...)`: a caller's subclass stays a subclass, as it does through add and move.
        return with_fields(
            self,
            layers=layers,
            hidden_groups=frozenset(
                group for group in self.hidden_groups if group in groups
            ),
        )

    def move(self, layer_id: str, index: int) -> "LayerTree":
        """Return a tree with a layer moved to another position in draw order.

        Args:
            layer_id: The layer to move.
            index: Its position afterwards, counted as a list index is — ``0`` is the bottom, ``-1`` the top.
                A layer moves **within its band**: reordering the data layers is what a layer switcher does, and
                dragging the basemap over them is not something a caller means to do.

        Returns:
            The new tree. Every other layer keeps its relative order.

        Raises:
            KeyError: if no layer has that id.
            IndexError: if `index` is outside the tree or outside the layer's band, or is not a whole number — a
                boolean or a float — exactly as :meth:`add` refuses one.

        Examples:
            - Bring a layer to the top:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
                >>> tree.move("a", -1).ids
                ('b', 'a')

                ```
            - Send a layer to the bottom; the others keep their relative order:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree((LayerSpec("a", "points"), LayerSpec("b", "lines"), LayerSpec("c", "fill")))
                >>> tree.move("c", 0).ids
                ('c', 'a', 'b')

                ```
            - A layer cannot be moved out of its band; the message says where the band runs:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("tiles", "basemap")).add(LayerSpec("dem", "raster"))
                >>> tree.move("tiles", -1)
                Traceback (most recent call last):
                    ...
                IndexError: cannot move 'tiles' to position 1; the underlay band runs from position 0 to 0

                ```
        """
        layer = self.get(layer_id)
        count = len(self.layers)
        if not _is_position(index) or not -count <= index < count:
            raise IndexError(
                f"cannot move {layer_id!r} to position {index}; the tree holds {count} layers"
            )
        position = index % count
        others = [candidate for candidate in self.layers if candidate.id != layer_id]
        band = _layer_band(layer)
        low, high = _band_bounds(others, band)
        if not low <= position <= high:
            raise IndexError(
                f"cannot move {layer_id!r} to position {position}; the {band} band runs from position {low} "
                f"to {high}"
            )
        others.insert(position, layer)
        return with_fields(self, layers=tuple(others))

    def replace(self, layer: LayerSpec) -> "LayerTree":
        """Return a tree with the layer of the same id swapped for `layer`, in the same position.

        This is how a layer is restyled or re-pointed after it has been added: the id and the position stay, the
        description changes.

        A replacement that changes the layer's **band** is the exception: it takes the position `add` would
        have given it, at the top of the band it now belongs to. Keeping the old position would put a
        reference layer under the data or an overlay beneath it, which is the one thing the bands exist to
        prevent — and which `add` and `move` both refuse to do.

        Args:
            layer: The new description. Its id names the layer it replaces.

        Returns:
            The new tree. A hidden group the new description leaves with no layers stops being hidden, as
            :meth:`remove` forgets one, since there is nothing left in it.

        Raises:
            KeyError: if no layer has that id.
            ValueError: if `layer` is not a `LayerSpec`, or the new description breaks what the tree holds together:
                its `z_source` names a layer the tree does not have or closes a loop.

        Examples:
            - Restyle a layer without moving it:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree, Symbology
                >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
                >>> restyled = tree.replace(LayerSpec("a", "points", symbology=Symbology.of(color="#f00")))
                >>> restyled.ids, restyled.get("a").symbology.encoding("color").resolve()
                (('a', 'b'), '#f00')

                ```
            - Moving the last layer out of a hidden group un-hides the group, as removing it would:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
                >>> hidden = tree.set_group_visible("obs", False)
                >>> hidden.hidden_groups, hidden.replace(LayerSpec("a", "points")).hidden_groups
                (frozenset({'obs'}), frozenset())

                ```
            - Re-pointing a layer's elevation at a layer the tree lacks is refused:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("dem", "raster"))
                >>> tree.replace(LayerSpec("dem", "raster", z_source="layer:nope"))  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: layer 'dem' takes its elevation from layer 'nope', which is not in the tree; ...

                ```
        """
        _check_layer("replace", layer)
        held = self.get(layer.id)
        if _layer_band(layer) != _layer_band(held):
            # `add` inserts into the layer's band and `move` refuses a position outside it; a replacement
            # that changes the band and keeps the position walked straight through both, leaving an overlay
            # drawn beneath the data with `diff` reporting nothing (review M1). Re-band by removing and
            # adding, which puts the layer at the top of the band it now belongs to.
            return self.remove(layer.id).add(layer)
        layers = tuple(
            layer if existing.id == layer.id else existing for existing in self.layers
        )
        groups = {existing.group for existing in layers}
        return with_fields(
            self,
            layers=layers,
            hidden_groups=frozenset(
                group for group in self.hidden_groups if group in groups
            ),
        )

    def set_visible(self, layer_id: str, visible: bool) -> "LayerTree":
        """Return a tree with one layer switched on or off.

        Args:
            layer_id: The layer to change.
            visible: Whether it should be drawn.

        Returns:
            The new tree.

        Raises:
            KeyError: if no layer has that id.
            ValueError: if `visible` is not a boolean.

        Examples:
            - Switch a layer off and back on:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("a", "points"))
                >>> tree.set_visible("a", False).is_visible("a"), tree.is_visible("a")
                (False, True)

                ```
        """
        return self.replace(
            cast(LayerSpec, with_fields(self.get(layer_id), visible=visible))
        )

    def set_group_visible(self, group: str, visible: bool) -> "LayerTree":
        """Return a tree with a whole group switched on or off.

        Args:
            group: The group to change.
            visible: Whether its layers should be drawn. Each layer's own `visible` is kept, so switching the group
                back on restores exactly what was drawn before.

        Returns:
            The new tree.

        Raises:
            KeyError: if no layer belongs to that group.
            ValueError: if `visible` is not a boolean.

        Examples:
            - A group switched off hides every layer in it:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs"))
                >>> tree.set_group_visible("obs", False).hidden_groups
                frozenset({'obs'})

                ```
            - Switching the group back on restores a layer that was hidden only by its group:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> hidden = LayerTree().add(LayerSpec("a", "points", group="obs")).set_group_visible("obs", False)
                >>> hidden.is_visible("a"), hidden.set_group_visible("obs", True).is_visible("a")
                (False, True)

                ```
        """
        if group not in self.groups:
            raise KeyError(
                f"no layer belongs to group {group!r}; groups are {list(self.groups)}"
            )
        shown = true_or_false(visible)
        if shown is None:
            raise ValueError(
                f"set_group_visible needs visible as True or False; got {visible!r}"
            )
        hidden = set(self.hidden_groups)
        if shown:
            hidden.discard(group)
        else:
            hidden.add(group)
        return with_fields(self, hidden_groups=frozenset(hidden))

    # ------------------------------------------------------------------ serialisation

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``layers`` as a list in draw order, plus ``hidden_groups`` sorted, when any group is hidden.

        Raises:
            TypeError: if a layer holds a value with no JSON form.

        Examples:
            - The layers are written bottom first:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> LayerTree().add(LayerSpec("a", "points")).to_dict()
                {'layers': [{'id': 'a', 'kind': 'points'}]}

                ```
            - Hidden groups are written as a sorted list:
                ```python
                >>> from digitalearth.base.spec import LayerSpec, LayerTree
                >>> tree = LayerTree((LayerSpec("a", "points", group="obs"), LayerSpec("b", "lines", group="base")))
                >>> tree.set_group_visible("obs", False).set_group_visible("base", False).to_dict()["hidden_groups"]
                ['base', 'obs']

                ```
        """
        out: dict[str, Any] = {"layers": [layer.to_dict() for layer in self.layers]}
        if self.hidden_groups:
            out["hidden_groups"] = sorted(
                plain_text(group) for group in self.hidden_groups
            )
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "LayerTree":
        """Rebuild a tree from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The tree, validated as the constructor validates it.

        Raises:
            TypeError: if `data` or a stored layer is not a mapping, or `layers` or `hidden_groups` is not a
                list, naming the field.
            ValueError: for an unknown key, a layer `LayerSpec.from_dict` refuses, or a tree the constructor
                refuses. An error of either type from a stored layer names its position, and each nested read adds
                its own step: `LayerTree.from_dict layers[1]: LayerSpec.from_dict needs 'kind'; got keys ['id']`.

        Examples:
            - A stored tree reads back in the same order:
                ```python
                >>> from digitalearth.base.spec import LayerTree
                >>> LayerTree.from_dict({"layers": [{"id": "a", "kind": "points"}, {"id": "b", "kind": "lines"}]}).ids
                ('a', 'b')

                ```
            - A hidden group stays hidden across a round trip:
                ```python
                >>> from digitalearth.base.spec import LayerTree
                >>> stored = {"layers": [{"id": "a", "kind": "points", "group": "obs"}], "hidden_groups": ["obs"]}
                >>> LayerTree.from_dict(stored).is_visible("a")
                False

                ```
        """
        refuse_unknown("LayerTree", data, ("layers", "hidden_groups"))
        return cls(
            tuple(
                read_entry("LayerTree", f"layers[{index}]", LayerSpec.from_dict, layer)
                for index, layer in enumerate(
                    as_list("LayerTree", "layers", data.get("layers", ()))
                )
            ),
            # The constructor checks each entry is a group name and freezes them; a frozenset here would raise a bare
            # "unhashable type" for a nested list before that check could name it.
            cast(
                frozenset[str],
                as_list("LayerTree", "hidden_groups", data.get("hidden_groups", ())),
            ),
        )

groups property #

The groups the layers belong to, in the order each first appears.

Returns:

Type Description
tuple[str, ...]

The group names, without repeats.

Examples:

  • Groups are listed once, in draw order:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree((LayerSpec("a", "points", group="obs"), LayerSpec("b", "lines", group="obs")))
    >>> tree.groups
    ('obs',)
    

ids property #

The layer ids, bottom first.

Returns:

Type Description
tuple[str, ...]

The ids in draw order.

Examples:

  • An empty tree has no ids:
    >>> from digitalearth.base.spec import LayerTree
    >>> LayerTree().ids
    ()
    

__contains__(layer_id) #

Whether a layer with this id is in the tree.

Parameters:

Name Type Description Default
layer_id object

The id to look for.

required

Returns:

Type Description
bool

True when a layer has that id.

Source code in src/digitalearth/base/spec/layer.py
def __contains__(self, layer_id: object) -> bool:
    """Whether a layer with this id is in the tree.

    Args:
        layer_id: The id to look for.

    Returns:
        ``True`` when a layer has that id.
    """
    return layer_id in self.ids

__iter__() #

Iterate over the layers, bottom first.

Returns:

Type Description
Iterator[LayerSpec]

An iterator over the layers in draw order.

Source code in src/digitalearth/base/spec/layer.py
def __iter__(self) -> Iterator[LayerSpec]:
    """Iterate over the layers, bottom first.

    Returns:
        An iterator over the layers in draw order.
    """
    return iter(self.layers)

__len__() #

Return how many layers the tree holds.

Returns:

Type Description
int

The layer count.

Source code in src/digitalearth/base/spec/layer.py
def __len__(self) -> int:
    """Return how many layers the tree holds.

    Returns:
        The layer count.
    """
    return len(self.layers)

__post_init__() #

Refuse a tree whose ids, references or hidden groups do not hold together.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/layer.py
def __post_init__(self) -> None:
    """Refuse a tree whose ids, references or hidden groups do not hold together.

    Raises:
        ValueError: as described on the class.
    """
    object.__setattr__(self, "layers", tuple(self.layers))
    object.__setattr__(
        self, "hidden_groups", self._checked_hidden_groups(self.hidden_groups)
    )
    for layer in self.layers:
        if not isinstance(layer, LayerSpec):
            raise ValueError(
                f"LayerTree holds LayerSpec values; got {type(layer).__name__}"
            )
    # Every check below is linear in the layer count. This runs on every add, move and replace — the web tier
    # calls it once per builder — so a quadratic check here made building a map cubic.
    ids = [layer.id for layer in self.layers]
    duplicated = sorted(
        layer_id for layer_id, count in Counter(ids).items() if count > 1
    )
    if duplicated:
        raise ValueError(
            f"LayerTree ids must be unique; {duplicated} appear more than once"
        )
    self._check_drapes(ids)
    unknown_groups = sorted(
        self.hidden_groups - {layer.group for layer in self.layers}
    )
    if unknown_groups:
        raise ValueError(
            f"LayerTree hides groups {unknown_groups} that no layer belongs to; groups are {list(self.groups)}"
        )

add(layer, *, index=None) #

Return a tree with layer added.

Parameters:

Name Type Description Default
layer LayerSpec

The layer to add.

required
index int | None

Where it goes within its band. None puts it on top of the band, which is what a builder wants: a basemap under the data however late it is added, a label over the data however early. A position is counted in the whole tree, so the band's own range is what it must fall in.

None

Returns:

Type Description
LayerTree

The new tree.

Raises:

Type Description
ValueError

if layer is not a LayerSpec, a layer with the same id is already in the tree, or the layer's z_source names a layer that is not.

IndexError

if index is outside the layer's band — list.insert would clamp it silently, which puts the layer somewhere the caller did not ask for — or is not a whole number: a boolean or a float.

Examples:

  • A basemap is ground cover, so it goes beneath the data wherever it is added:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("roads", "lines"))
    >>> tree.add(LayerSpec("tiles", "basemap")).ids
    ('tiles', 'roads')
    
  • Kinds that draw over the data stay over it, and the order within a band is the order they arrived:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("place", "text")).add(LayerSpec("dem", "raster"))
    >>> tree.add(LayerSpec("grid", "graticule")).ids
    ('grid', 'dem', 'place')
    
  • A position that would take the layer out of its band is refused rather than clamped:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("dem", "raster")).add(LayerSpec("tiles", "basemap"), index=1)
    Traceback (most recent call last):
        ...
    IndexError: cannot add 'tiles' at position 1; the underlay band runs from position 0 to 0
    
Source code in src/digitalearth/base/spec/layer.py
def add(self, layer: LayerSpec, *, index: int | None = None) -> "LayerTree":
    """Return a tree with `layer` added.

    Args:
        layer: The layer to add.
        index: Where it goes **within its band**. ``None`` puts it on top of the band, which is what a
            builder wants: a basemap under the data however late it is added, a label over the data however
            early. A position is counted in the whole tree, so the band's own range is what it must fall in.

    Returns:
        The new tree.

    Raises:
        ValueError: if `layer` is not a `LayerSpec`, a layer with the same id is already in the tree, or the
            layer's `z_source` names a layer that is not.
        IndexError: if `index` is outside the layer's band — `list.insert` would clamp it silently, which puts
            the layer somewhere the caller did not ask for — or is not a whole number: a boolean or a float.

    Examples:
        - A basemap is ground cover, so it goes beneath the data wherever it is added:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("roads", "lines"))
            >>> tree.add(LayerSpec("tiles", "basemap")).ids
            ('tiles', 'roads')

            ```
        - Kinds that draw over the data stay over it, and the order within a band is the order they arrived:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("place", "text")).add(LayerSpec("dem", "raster"))
            >>> tree.add(LayerSpec("grid", "graticule")).ids
            ('grid', 'dem', 'place')

            ```
        - A position that would take the layer out of its band is refused rather than clamped:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("dem", "raster")).add(LayerSpec("tiles", "basemap"), index=1)
            Traceback (most recent call last):
                ...
            IndexError: cannot add 'tiles' at position 1; the underlay band runs from position 0 to 0

            ```
    """
    _check_layer("add", layer)
    if any(existing.id == layer.id for existing in self.layers):
        raise ValueError(
            f"a layer with id {layer.id!r} is already in the tree; layer ids must be unique"
        )
    layers = list(self.layers)
    band = _layer_band(layer)
    low, high = _band_bounds(layers, band)
    if index is None:
        layers.insert(high, layer)
    elif not _is_position(index) or not low <= index <= high:
        raise IndexError(
            f"cannot add {layer.id!r} at position {index!r}; the {band} band runs from position {low} to {high}"
        )
    else:
        layers.insert(index, layer)
    return with_fields(self, layers=tuple(layers))

from_dict(data) classmethod #

Rebuild a tree from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
LayerTree

The tree, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data or a stored layer is not a mapping, or layers or hidden_groups is not a list, naming the field.

ValueError

for an unknown key, a layer LayerSpec.from_dict refuses, or a tree the constructor refuses. An error of either type from a stored layer names its position, and each nested read adds its own step: LayerTree.from_dict layers[1]: LayerSpec.from_dict needs 'kind'; got keys ['id'].

Examples:

  • A stored tree reads back in the same order:
    >>> from digitalearth.base.spec import LayerTree
    >>> LayerTree.from_dict({"layers": [{"id": "a", "kind": "points"}, {"id": "b", "kind": "lines"}]}).ids
    ('a', 'b')
    
  • A hidden group stays hidden across a round trip:
    >>> from digitalearth.base.spec import LayerTree
    >>> stored = {"layers": [{"id": "a", "kind": "points", "group": "obs"}], "hidden_groups": ["obs"]}
    >>> LayerTree.from_dict(stored).is_visible("a")
    False
    
Source code in src/digitalearth/base/spec/layer.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "LayerTree":
    """Rebuild a tree from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The tree, validated as the constructor validates it.

    Raises:
        TypeError: if `data` or a stored layer is not a mapping, or `layers` or `hidden_groups` is not a
            list, naming the field.
        ValueError: for an unknown key, a layer `LayerSpec.from_dict` refuses, or a tree the constructor
            refuses. An error of either type from a stored layer names its position, and each nested read adds
            its own step: `LayerTree.from_dict layers[1]: LayerSpec.from_dict needs 'kind'; got keys ['id']`.

    Examples:
        - A stored tree reads back in the same order:
            ```python
            >>> from digitalearth.base.spec import LayerTree
            >>> LayerTree.from_dict({"layers": [{"id": "a", "kind": "points"}, {"id": "b", "kind": "lines"}]}).ids
            ('a', 'b')

            ```
        - A hidden group stays hidden across a round trip:
            ```python
            >>> from digitalearth.base.spec import LayerTree
            >>> stored = {"layers": [{"id": "a", "kind": "points", "group": "obs"}], "hidden_groups": ["obs"]}
            >>> LayerTree.from_dict(stored).is_visible("a")
            False

            ```
    """
    refuse_unknown("LayerTree", data, ("layers", "hidden_groups"))
    return cls(
        tuple(
            read_entry("LayerTree", f"layers[{index}]", LayerSpec.from_dict, layer)
            for index, layer in enumerate(
                as_list("LayerTree", "layers", data.get("layers", ()))
            )
        ),
        # The constructor checks each entry is a group name and freezes them; a frozenset here would raise a bare
        # "unhashable type" for a nested list before that check could name it.
        cast(
            frozenset[str],
            as_list("LayerTree", "hidden_groups", data.get("hidden_groups", ())),
        ),
    )

get(layer_id) #

Return the layer with this id.

Parameters:

Name Type Description Default
layer_id str

The id to look up.

required

Returns:

Type Description
LayerSpec

The layer.

Raises:

Type Description
KeyError

if no layer has that id, listing the ids that exist.

Examples:

  • Look a layer up by id:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("dem", "raster", source_id="srtm")).get("dem").source_id
    'srtm'
    
  • An id the tree does not hold is named beside the ids it does:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("dem", "raster")).get("roads")
    Traceback (most recent call last):
        ...
    KeyError: "no layer 'roads' in this tree; layers are ['dem']"
    
Source code in src/digitalearth/base/spec/layer.py
def get(self, layer_id: str) -> LayerSpec:
    """Return the layer with this id.

    Args:
        layer_id: The id to look up.

    Returns:
        The layer.

    Raises:
        KeyError: if no layer has that id, listing the ids that exist.

    Examples:
        - Look a layer up by id:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("dem", "raster", source_id="srtm")).get("dem").source_id
            'srtm'

            ```
        - An id the tree does not hold is named beside the ids it does:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("dem", "raster")).get("roads")
            Traceback (most recent call last):
                ...
            KeyError: "no layer 'roads' in this tree; layers are ['dem']"

            ```
    """
    for layer in self.layers:
        if layer.id == layer_id:
            return layer
    raise KeyError(
        f"no layer {layer_id!r} in this tree; layers are {list(self.ids)}"
    )

is_visible(layer_id) #

Whether a layer is drawn: its own visible, and its group not hidden.

Parameters:

Name Type Description Default
layer_id str

The layer to ask about.

required

Returns:

Type Description
bool

True when the layer is switched on and so is its group.

Raises:

Type Description
KeyError

if no layer has that id.

Examples:

  • A layer switched off is not drawn:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("a", "points", visible=False)).is_visible("a")
    False
    
Source code in src/digitalearth/base/spec/layer.py
def is_visible(self, layer_id: str) -> bool:
    """Whether a layer is drawn: its own `visible`, and its group not hidden.

    Args:
        layer_id: The layer to ask about.

    Returns:
        ``True`` when the layer is switched on and so is its group.

    Raises:
        KeyError: if no layer has that id.

    Examples:
        - A layer switched off is not drawn:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("a", "points", visible=False)).is_visible("a")
            False

            ```
    """
    layer = self.get(layer_id)
    return layer.visible and layer.group not in self.hidden_groups

move(layer_id, index) #

Return a tree with a layer moved to another position in draw order.

Parameters:

Name Type Description Default
layer_id str

The layer to move.

required
index int

Its position afterwards, counted as a list index is — 0 is the bottom, -1 the top. A layer moves within its band: reordering the data layers is what a layer switcher does, and dragging the basemap over them is not something a caller means to do.

required

Returns:

Type Description
LayerTree

The new tree. Every other layer keeps its relative order.

Raises:

Type Description
KeyError

if no layer has that id.

IndexError

if index is outside the tree or outside the layer's band, or is not a whole number — a boolean or a float — exactly as :meth:add refuses one.

Examples:

  • Bring a layer to the top:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
    >>> tree.move("a", -1).ids
    ('b', 'a')
    
  • Send a layer to the bottom; the others keep their relative order:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree((LayerSpec("a", "points"), LayerSpec("b", "lines"), LayerSpec("c", "fill")))
    >>> tree.move("c", 0).ids
    ('c', 'a', 'b')
    
  • A layer cannot be moved out of its band; the message says where the band runs:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("tiles", "basemap")).add(LayerSpec("dem", "raster"))
    >>> tree.move("tiles", -1)
    Traceback (most recent call last):
        ...
    IndexError: cannot move 'tiles' to position 1; the underlay band runs from position 0 to 0
    
Source code in src/digitalearth/base/spec/layer.py
def move(self, layer_id: str, index: int) -> "LayerTree":
    """Return a tree with a layer moved to another position in draw order.

    Args:
        layer_id: The layer to move.
        index: Its position afterwards, counted as a list index is — ``0`` is the bottom, ``-1`` the top.
            A layer moves **within its band**: reordering the data layers is what a layer switcher does, and
            dragging the basemap over them is not something a caller means to do.

    Returns:
        The new tree. Every other layer keeps its relative order.

    Raises:
        KeyError: if no layer has that id.
        IndexError: if `index` is outside the tree or outside the layer's band, or is not a whole number — a
            boolean or a float — exactly as :meth:`add` refuses one.

    Examples:
        - Bring a layer to the top:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
            >>> tree.move("a", -1).ids
            ('b', 'a')

            ```
        - Send a layer to the bottom; the others keep their relative order:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree((LayerSpec("a", "points"), LayerSpec("b", "lines"), LayerSpec("c", "fill")))
            >>> tree.move("c", 0).ids
            ('c', 'a', 'b')

            ```
        - A layer cannot be moved out of its band; the message says where the band runs:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("tiles", "basemap")).add(LayerSpec("dem", "raster"))
            >>> tree.move("tiles", -1)
            Traceback (most recent call last):
                ...
            IndexError: cannot move 'tiles' to position 1; the underlay band runs from position 0 to 0

            ```
    """
    layer = self.get(layer_id)
    count = len(self.layers)
    if not _is_position(index) or not -count <= index < count:
        raise IndexError(
            f"cannot move {layer_id!r} to position {index}; the tree holds {count} layers"
        )
    position = index % count
    others = [candidate for candidate in self.layers if candidate.id != layer_id]
    band = _layer_band(layer)
    low, high = _band_bounds(others, band)
    if not low <= position <= high:
        raise IndexError(
            f"cannot move {layer_id!r} to position {position}; the {band} band runs from position {low} "
            f"to {high}"
        )
    others.insert(position, layer)
    return with_fields(self, layers=tuple(others))

remove(layer_id) #

Return a tree without the layer with this id.

Parameters:

Name Type Description Default
layer_id str

The layer to remove.

required

Returns:

Type Description
LayerTree

The new tree. A hidden group left with no layers stops being hidden, since there is nothing left in it.

Raises:

Type Description
KeyError

if no layer has that id.

ValueError

if another layer takes its elevation from this one — removing the surface would leave the draped layer pointing at nothing.

Examples:

  • Remove a layer by id:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines")).remove("a").ids
    ('b',)
    
  • Removing the last layer of a hidden group un-hides the group:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
    >>> hidden = tree.set_group_visible("obs", False)
    >>> hidden.hidden_groups, hidden.remove("a").hidden_groups
    (frozenset({'obs'}), frozenset())
    
  • A surface another layer is draped over cannot be removed first:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> draped = LayerSpec("img", "rgb", z_source="layer:dem")
    >>> tree = LayerTree().add(LayerSpec("dem", "raster")).add(draped)
    >>> tree.remove("dem")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: layer 'dem' cannot be removed while ['img'] take their elevation from it; ...
    
Source code in src/digitalearth/base/spec/layer.py
def remove(self, layer_id: str) -> "LayerTree":
    """Return a tree without the layer with this id.

    Args:
        layer_id: The layer to remove.

    Returns:
        The new tree. A hidden group left with no layers stops being hidden, since there is nothing left in it.

    Raises:
        KeyError: if no layer has that id.
        ValueError: if another layer takes its elevation from this one — removing the surface would leave the
            draped layer pointing at nothing.

    Examples:
        - Remove a layer by id:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines")).remove("a").ids
            ('b',)

            ```
        - Removing the last layer of a hidden group un-hides the group:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
            >>> hidden = tree.set_group_visible("obs", False)
            >>> hidden.hidden_groups, hidden.remove("a").hidden_groups
            (frozenset({'obs'}), frozenset())

            ```
        - A surface another layer is draped over cannot be removed first:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> draped = LayerSpec("img", "rgb", z_source="layer:dem")
            >>> tree = LayerTree().add(LayerSpec("dem", "raster")).add(draped)
            >>> tree.remove("dem")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: layer 'dem' cannot be removed while ['img'] take their elevation from it; ...

            ```
    """
    self.get(layer_id)
    dependents = [layer.id for layer in self.layers if layer.z_layer == layer_id]
    if dependents:
        raise ValueError(
            f"layer {layer_id!r} cannot be removed while {dependents} take their elevation from it; remove or "
            "re-point those first"
        )
    layers = tuple(layer for layer in self.layers if layer.id != layer_id)
    groups = {layer.group for layer in layers}
    # `with_fields`, not `LayerTree(...)`: a caller's subclass stays a subclass, as it does through add and move.
    return with_fields(
        self,
        layers=layers,
        hidden_groups=frozenset(
            group for group in self.hidden_groups if group in groups
        ),
    )

replace(layer) #

Return a tree with the layer of the same id swapped for layer, in the same position.

This is how a layer is restyled or re-pointed after it has been added: the id and the position stay, the description changes.

A replacement that changes the layer's band is the exception: it takes the position add would have given it, at the top of the band it now belongs to. Keeping the old position would put a reference layer under the data or an overlay beneath it, which is the one thing the bands exist to prevent — and which add and move both refuse to do.

Parameters:

Name Type Description Default
layer LayerSpec

The new description. Its id names the layer it replaces.

required

Returns:

Type Description
LayerTree

The new tree. A hidden group the new description leaves with no layers stops being hidden, as

LayerTree

meth:remove forgets one, since there is nothing left in it.

Raises:

Type Description
KeyError

if no layer has that id.

ValueError

if layer is not a LayerSpec, or the new description breaks what the tree holds together: its z_source names a layer the tree does not have or closes a loop.

Examples:

  • Restyle a layer without moving it:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree, Symbology
    >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
    >>> restyled = tree.replace(LayerSpec("a", "points", symbology=Symbology.of(color="#f00")))
    >>> restyled.ids, restyled.get("a").symbology.encoding("color").resolve()
    (('a', 'b'), '#f00')
    
  • Moving the last layer out of a hidden group un-hides the group, as removing it would:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
    >>> hidden = tree.set_group_visible("obs", False)
    >>> hidden.hidden_groups, hidden.replace(LayerSpec("a", "points")).hidden_groups
    (frozenset({'obs'}), frozenset())
    
  • Re-pointing a layer's elevation at a layer the tree lacks is refused:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("dem", "raster"))
    >>> tree.replace(LayerSpec("dem", "raster", z_source="layer:nope"))  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: layer 'dem' takes its elevation from layer 'nope', which is not in the tree; ...
    
Source code in src/digitalearth/base/spec/layer.py
def replace(self, layer: LayerSpec) -> "LayerTree":
    """Return a tree with the layer of the same id swapped for `layer`, in the same position.

    This is how a layer is restyled or re-pointed after it has been added: the id and the position stay, the
    description changes.

    A replacement that changes the layer's **band** is the exception: it takes the position `add` would
    have given it, at the top of the band it now belongs to. Keeping the old position would put a
    reference layer under the data or an overlay beneath it, which is the one thing the bands exist to
    prevent — and which `add` and `move` both refuse to do.

    Args:
        layer: The new description. Its id names the layer it replaces.

    Returns:
        The new tree. A hidden group the new description leaves with no layers stops being hidden, as
        :meth:`remove` forgets one, since there is nothing left in it.

    Raises:
        KeyError: if no layer has that id.
        ValueError: if `layer` is not a `LayerSpec`, or the new description breaks what the tree holds together:
            its `z_source` names a layer the tree does not have or closes a loop.

    Examples:
        - Restyle a layer without moving it:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree, Symbology
            >>> tree = LayerTree().add(LayerSpec("a", "points")).add(LayerSpec("b", "lines"))
            >>> restyled = tree.replace(LayerSpec("a", "points", symbology=Symbology.of(color="#f00")))
            >>> restyled.ids, restyled.get("a").symbology.encoding("color").resolve()
            (('a', 'b'), '#f00')

            ```
        - Moving the last layer out of a hidden group un-hides the group, as removing it would:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs")).add(LayerSpec("b", "lines"))
            >>> hidden = tree.set_group_visible("obs", False)
            >>> hidden.hidden_groups, hidden.replace(LayerSpec("a", "points")).hidden_groups
            (frozenset({'obs'}), frozenset())

            ```
        - Re-pointing a layer's elevation at a layer the tree lacks is refused:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("dem", "raster"))
            >>> tree.replace(LayerSpec("dem", "raster", z_source="layer:nope"))  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: layer 'dem' takes its elevation from layer 'nope', which is not in the tree; ...

            ```
    """
    _check_layer("replace", layer)
    held = self.get(layer.id)
    if _layer_band(layer) != _layer_band(held):
        # `add` inserts into the layer's band and `move` refuses a position outside it; a replacement
        # that changes the band and keeps the position walked straight through both, leaving an overlay
        # drawn beneath the data with `diff` reporting nothing (review M1). Re-band by removing and
        # adding, which puts the layer at the top of the band it now belongs to.
        return self.remove(layer.id).add(layer)
    layers = tuple(
        layer if existing.id == layer.id else existing for existing in self.layers
    )
    groups = {existing.group for existing in layers}
    return with_fields(
        self,
        layers=layers,
        hidden_groups=frozenset(
            group for group in self.hidden_groups if group in groups
        ),
    )

set_group_visible(group, visible) #

Return a tree with a whole group switched on or off.

Parameters:

Name Type Description Default
group str

The group to change.

required
visible bool

Whether its layers should be drawn. Each layer's own visible is kept, so switching the group back on restores exactly what was drawn before.

required

Returns:

Type Description
LayerTree

The new tree.

Raises:

Type Description
KeyError

if no layer belongs to that group.

ValueError

if visible is not a boolean.

Examples:

  • A group switched off hides every layer in it:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs"))
    >>> tree.set_group_visible("obs", False).hidden_groups
    frozenset({'obs'})
    
  • Switching the group back on restores a layer that was hidden only by its group:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> hidden = LayerTree().add(LayerSpec("a", "points", group="obs")).set_group_visible("obs", False)
    >>> hidden.is_visible("a"), hidden.set_group_visible("obs", True).is_visible("a")
    (False, True)
    
Source code in src/digitalearth/base/spec/layer.py
def set_group_visible(self, group: str, visible: bool) -> "LayerTree":
    """Return a tree with a whole group switched on or off.

    Args:
        group: The group to change.
        visible: Whether its layers should be drawn. Each layer's own `visible` is kept, so switching the group
            back on restores exactly what was drawn before.

    Returns:
        The new tree.

    Raises:
        KeyError: if no layer belongs to that group.
        ValueError: if `visible` is not a boolean.

    Examples:
        - A group switched off hides every layer in it:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points", group="obs"))
            >>> tree.set_group_visible("obs", False).hidden_groups
            frozenset({'obs'})

            ```
        - Switching the group back on restores a layer that was hidden only by its group:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> hidden = LayerTree().add(LayerSpec("a", "points", group="obs")).set_group_visible("obs", False)
            >>> hidden.is_visible("a"), hidden.set_group_visible("obs", True).is_visible("a")
            (False, True)

            ```
    """
    if group not in self.groups:
        raise KeyError(
            f"no layer belongs to group {group!r}; groups are {list(self.groups)}"
        )
    shown = true_or_false(visible)
    if shown is None:
        raise ValueError(
            f"set_group_visible needs visible as True or False; got {visible!r}"
        )
    hidden = set(self.hidden_groups)
    if shown:
        hidden.discard(group)
    else:
        hidden.add(group)
    return with_fields(self, hidden_groups=frozenset(hidden))

set_visible(layer_id, visible) #

Return a tree with one layer switched on or off.

Parameters:

Name Type Description Default
layer_id str

The layer to change.

required
visible bool

Whether it should be drawn.

required

Returns:

Type Description
LayerTree

The new tree.

Raises:

Type Description
KeyError

if no layer has that id.

ValueError

if visible is not a boolean.

Examples:

  • Switch a layer off and back on:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree().add(LayerSpec("a", "points"))
    >>> tree.set_visible("a", False).is_visible("a"), tree.is_visible("a")
    (False, True)
    
Source code in src/digitalearth/base/spec/layer.py
def set_visible(self, layer_id: str, visible: bool) -> "LayerTree":
    """Return a tree with one layer switched on or off.

    Args:
        layer_id: The layer to change.
        visible: Whether it should be drawn.

    Returns:
        The new tree.

    Raises:
        KeyError: if no layer has that id.
        ValueError: if `visible` is not a boolean.

    Examples:
        - Switch a layer off and back on:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree().add(LayerSpec("a", "points"))
            >>> tree.set_visible("a", False).is_visible("a"), tree.is_visible("a")
            (False, True)

            ```
    """
    return self.replace(
        cast(LayerSpec, with_fields(self.get(layer_id), visible=visible))
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

layers as a list in draw order, plus hidden_groups sorted, when any group is hidden.

Raises:

Type Description
TypeError

if a layer holds a value with no JSON form.

Examples:

  • The layers are written bottom first:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> LayerTree().add(LayerSpec("a", "points")).to_dict()
    {'layers': [{'id': 'a', 'kind': 'points'}]}
    
  • Hidden groups are written as a sorted list:
    >>> from digitalearth.base.spec import LayerSpec, LayerTree
    >>> tree = LayerTree((LayerSpec("a", "points", group="obs"), LayerSpec("b", "lines", group="base")))
    >>> tree.set_group_visible("obs", False).set_group_visible("base", False).to_dict()["hidden_groups"]
    ['base', 'obs']
    
Source code in src/digitalearth/base/spec/layer.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``layers`` as a list in draw order, plus ``hidden_groups`` sorted, when any group is hidden.

    Raises:
        TypeError: if a layer holds a value with no JSON form.

    Examples:
        - The layers are written bottom first:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> LayerTree().add(LayerSpec("a", "points")).to_dict()
            {'layers': [{'id': 'a', 'kind': 'points'}]}

            ```
        - Hidden groups are written as a sorted list:
            ```python
            >>> from digitalearth.base.spec import LayerSpec, LayerTree
            >>> tree = LayerTree((LayerSpec("a", "points", group="obs"), LayerSpec("b", "lines", group="base")))
            >>> tree.set_group_visible("obs", False).set_group_visible("base", False).to_dict()["hidden_groups"]
            ['base', 'obs']

            ```
    """
    out: dict[str, Any] = {"layers": [layer.to_dict() for layer in self.layers]}
    if self.hidden_groups:
        out["hidden_groups"] = sorted(
            plain_text(group) for group in self.hidden_groups
        )
    return out

Viewport and Camera — the view as a value#

The view used to be loose state on each facade, mutated in place to animate. These are values: a change of view is a new view.

digitalearth.base.spec.viewport.Viewport dataclass #

What a flat map shows: the CRS it is drawn in, and optionally the region.

Attributes:

Name Type Description
crs Any

The display CRS every layer is drawn in — an EPSG integer or anything pyramids reads. Defaults to Web Mercator, as the static Map does. A CRS object is held in the spelling it is written in, as Bounds holds one, so a view and its JSON round trip are one value with one hash.

bounds Bounds | None

The region shown, in crs. None means the view is not framed yet and the renderer chooses.

domain str | tuple[float, float, float, float] | None

A named region ("europe") or a (west, south, east, north) box in degrees — the static tier's domain= — or None. A view holds one region, so bounds and domain are not set together.

globe bool

Whether the map is drawn on a globe frame rather than a flat projection.

center tuple[float, float] | None

Where a pan-and-zoom map is looking, as (x, y) in crs — what the web tier calls center=. None leaves the renderer to frame the data. A region and a centre are not the same request: a region says what to fit, a centre and a zoom say where to stand, which is why both can be set.

zoom float | None

The zoom level of a pan-and-zoom map — MapLibre's, where each step doubles the scale. None leaves it to the renderer.

Raises:

Type Description
ValueError

for a None or boolean CRS, one a figure could not store (a float, a list — anything that is not an EPSG integer, a string or a CRS object pyramids reads), or one pyramids cannot read (0, ""); bounds that is not a Bounds, carries no CRS or is in a different CRS; bounds and domain together; a domain that is neither a non-empty name nor four finite numbers, or a domain box with west past east or south past north — a box cannot cross the antimeridian; a non-boolean globe; a center that is not two finite numbers; or a zoom that is not a finite number.

Examples:

  • A map framed on a region, in the CRS it is drawn in:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> view = Viewport(4326, bounds=Bounds(-10.0, 35.0, 30.0, 60.0, crs=4326))
    >>> view.crs, view.bounds.as_bbox()
    (4326, [-10.0, 35.0, 30.0, 60.0])
    
  • A pan-and-zoom map says where it is standing rather than what to fit:
    >>> from digitalearth.base.spec import Viewport
    >>> view = Viewport(4326, center=(4.9, 52.4), zoom=7)
    >>> view.center, view.zoom
    ((4.9, 52.4), 7.0)
    
  • A named domain, as the static tier spells it:
    >>> from digitalearth.base.spec import Viewport
    >>> Viewport(domain="europe").domain
    'europe'
    
  • A region in another CRS is refused rather than drawn in the wrong place; framed reprojects it:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> Viewport(3857, bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Viewport bounds are in 4326 but the view is drawn in 3857; use Viewport.framed(bounds), ...
    
Source code in src/digitalearth/base/spec/viewport.py
@dataclass(frozen=True)
class Viewport:
    """What a flat map shows: the CRS it is drawn in, and optionally the region.

    Attributes:
        crs: The display CRS every layer is drawn in — an EPSG integer or anything pyramids reads. Defaults to Web
            Mercator, as the static `Map` does. A CRS object is held in the spelling it is written in, as `Bounds`
            holds one, so a view and its JSON round trip are one value with one hash.
        bounds: The region shown, in `crs`. ``None`` means the view is not framed yet and the renderer chooses.
        domain: A named region (``"europe"``) or a ``(west, south, east, north)`` box in degrees — the static
            tier's ``domain=`` — or ``None``. A view holds one region, so `bounds` and `domain` are not set together.
        globe: Whether the map is drawn on a globe frame rather than a flat projection.
        center: Where a pan-and-zoom map is looking, as `(x, y)` in `crs` — what the web tier calls `center=`.
            `None` leaves the renderer to frame the data. A region and a centre are not the same request: a
            region says *what to fit*, a centre and a zoom say *where to stand*, which is why both can be set.
        zoom: The zoom level of a pan-and-zoom map — MapLibre's, where each step doubles the scale. `None`
            leaves it to the renderer.

    Raises:
        ValueError: for a `None` or boolean CRS, one a figure could not store (a float, a list — anything that is
            not an EPSG integer, a string or a CRS object pyramids reads), or one pyramids cannot read (`0`, `""`);
            `bounds` that is not a `Bounds`, carries no CRS or is in a different CRS; `bounds` and `domain` together;
            a `domain` that is neither a non-empty name nor four finite numbers, or a domain box with west past east
            or south past north — a box cannot cross the antimeridian; a non-boolean `globe`; a `center`
            that is not two finite numbers; or a `zoom` that is not a finite number.

    Examples:
        - A map framed on a region, in the CRS it is drawn in:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> view = Viewport(4326, bounds=Bounds(-10.0, 35.0, 30.0, 60.0, crs=4326))
            >>> view.crs, view.bounds.as_bbox()
            (4326, [-10.0, 35.0, 30.0, 60.0])

            ```
        - A pan-and-zoom map says where it is standing rather than what to fit:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> view = Viewport(4326, center=(4.9, 52.4), zoom=7)
            >>> view.center, view.zoom
            ((4.9, 52.4), 7.0)

            ```
        - A named domain, as the static tier spells it:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> Viewport(domain="europe").domain
            'europe'

            ```
        - A region in another CRS is refused rather than drawn in the wrong place; `framed` reprojects it:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> Viewport(3857, bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Viewport bounds are in 4326 but the view is drawn in 3857; use Viewport.framed(bounds), ...

            ```
    """

    crs: Any = 3857
    bounds: Bounds | None = None
    domain: str | tuple[float, float, float, float] | None = None
    globe: bool = False
    center: tuple[float, float] | None = None
    zoom: float | None = None

    def __post_init__(self) -> None:
        """Refuse a view nothing could be drawn in.

        Raises:
            ValueError: as described on the class.
        """
        if self.crs is None or isinstance(self.crs, bool):
            raise ValueError(f"Viewport needs a display CRS; got {self.crs!r}")
        object.__setattr__(self, "crs", _written_crs("Viewport.crs", self.crs))
        self._check_bounds()
        object.__setattr__(self, "domain", self._checked_domain(self.domain))
        if self.bounds is not None and self.domain is not None:
            # Two regions with no stated precedence leave a renderer to guess which one the map shows.
            raise ValueError(
                f"Viewport takes bounds or a domain, not both; got bounds {self.bounds.as_bbox()} and domain "
                f"{self.domain!r}. Use Viewport.framed(bounds) to frame a view that has a domain"
            )
        globe = true_or_false(self.globe)
        if globe is None:
            raise ValueError(
                f"Viewport globe must be True or False; got {self.globe!r}"
            )
        object.__setattr__(self, "globe", globe)
        object.__setattr__(self, "center", self._checked_center(self.center))
        if self.zoom is not None:
            object.__setattr__(
                self, "zoom", finite_number("Viewport", "zoom", self.zoom)
            )

    @staticmethod
    def _checked_center(center: Any) -> tuple[float, float] | None:
        """Return the centre as two floats, or `None`.

        Args:
            center: What the constructor was given.

        Returns:
            `(x, y)` as floats, or `None`.

        Raises:
            ValueError: for anything that is not two finite numbers — a centre with three numbers is a caller
                who meant a bounding box, and one with a `None` in it would place the map nowhere.
        """
        if center is None:
            return None
        try:
            x, y = center
        except (TypeError, ValueError):
            raise ValueError(
                f"Viewport center must be (x, y) in the view's CRS; got {center!r}"
            ) from None
        return (
            finite_number("Viewport", "center x", x),
            finite_number("Viewport", "center y", y),
        )

    def _check_bounds(self) -> None:
        """Refuse bounds that are not a `Bounds`, or that are in a different CRS from the view.

        Raises:
            ValueError: for bounds that are not a `Bounds`; or, naming both CRSs and `framed`, which reprojects, for
                bounds in a CRS pyramids does not judge the same as the view's.
        """
        if self.bounds is None:
            return
        if not isinstance(self.bounds, Bounds):
            raise ValueError(
                f"Viewport bounds must be a Bounds; got {type(self.bounds).__name__}"
            )
        if self.bounds.crs is None:
            raise ValueError(
                f"Viewport bounds carry no CRS, so they cannot be placed in {self.crs!r}; build them in the view's "
                "CRS, or in another and pass them to Viewport.framed"
            )
        if not same_crs(self.bounds.crs, self.crs):
            # A rectangle in one CRS read as another draws the wrong place, silently. `framed` reprojects; the
            # constructor refuses, so a view never holds a region its own CRS cannot place.
            raise ValueError(
                f"Viewport bounds are in {self.bounds.crs!r} but the view is drawn in {self.crs!r}; "
                "use Viewport.framed(bounds), which reprojects"
            )

    @staticmethod
    def _checked_domain(
        domain: Any,
    ) -> str | tuple[float, float, float, float] | None:
        """Return the domain as a name or a tuple of four floats, or ``None``.

        Args:
            domain: What the constructor was given.

        Returns:
            The name unchanged, the four edges as floats, or ``None``.

        Raises:
            ValueError: for an empty or whitespace-only name, a non-iterable, the wrong number of edges, an edge
                that is not a finite number (a boolean included), or a box with west past east or south past north.
        """
        if domain is None:
            return None
        if isinstance(domain, str):
            if not domain.strip():
                raise ValueError(
                    "Viewport domain must be a region name or four numbers; got an empty name"
                )
            return domain
        edges = list(domain) if hasattr(domain, "__iter__") else []
        if len(edges) != 4:
            raise ValueError(
                f"Viewport domain must be a region name or (west, south, east, north); got {domain!r}"
            )
        west, south, east, north = (
            finite_number("Viewport", "domain", edge) for edge in edges
        )
        if west > east or south > north:
            # Refused where the view is built, as the static tier's `set_domain` refuses it: a box read as a
            # rectangle later failed inside `Bounds`, naming neither the domain nor the antimeridian.
            raise ValueError(
                f"Viewport domain {domain!r} has its corners the wrong way round: it takes (west, south, east, north) "
                "in degrees, and cannot express a region crossing the antimeridian — split it into two views, or "
                "frame the view with bounds in a CRS that is continuous across it"
            )
        return west, south, east, north

    def framed(self, bounds: Bounds) -> "Viewport":
        """Return this view framed on `bounds`, reprojected into the view's CRS if they are in another.

        Args:
            bounds: The region to show, in any CRS.

        Returns:
            A new view. This one is unchanged — a change of view is a new value, never an edit of the old one. A
            `domain` the view had is dropped: the bounds are now the region it shows.

        Raises:
            ValueError: if `bounds` is not a `Bounds`, or cannot be reprojected into the view's CRS.

        Examples:
            - Frame a view without changing the one it came from:
                ```python
                >>> from digitalearth.base.spec import Bounds, Viewport
                >>> view = Viewport(4326)
                >>> framed = view.framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
                >>> framed.bounds.as_bbox(), view.bounds
                ([0.0, 0.0, 10.0, 5.0], None)

                ```
            - A region in another CRS is reprojected into the view's:
                ```python
                >>> from digitalearth.base.spec import Bounds, Viewport
                >>> framed = Viewport(3857).framed(Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
                >>> framed.bounds.crs, [round(edge) for edge in framed.bounds.as_bbox()]
                (3857, [0, 0, 111319, 111325])

                ```
            - Framing a view that has a named domain replaces the domain with the bounds:
                ```python
                >>> from digitalearth.base.spec import Bounds, Viewport
                >>> framed = Viewport(4326, domain="europe").framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
                >>> framed.domain, framed.bounds.as_bbox()
                (None, [0.0, 0.0, 10.0, 5.0])

                ```
        """
        if not isinstance(bounds, Bounds):
            raise ValueError(
                f"Viewport.framed needs a Bounds; got {type(bounds).__name__}"
            )
        return replace(self, bounds=bounds.to_crs(self.crs), domain=None)

    def needs_reproject(self, data: Any) -> bool:
        """Whether `data` has to be reprojected to be drawn in this view.

        Args:
            data: A pyramids object exposing `.crs` and/or `.epsg`.

        Returns:
            `False` when the data's own CRS and the view's name the same reference system, however either is
            spelled — the rule every tier shares, from :func:`digitalearth.base.display.needs_reproject`.

        Examples:
            - Data already in the view's CRS needs no warp, whether the view holds a code or its string:
                ```python
                >>> from types import SimpleNamespace
                >>> from digitalearth.base.spec import Viewport
                >>> data = SimpleNamespace(epsg=4326)
                >>> Viewport(4326).needs_reproject(data), Viewport("EPSG:4326").needs_reproject(data)
                (False, False)

                ```
            - Data in another system warps:
                ```python
                >>> from types import SimpleNamespace
                >>> from digitalearth.base.spec import Viewport
                >>> Viewport(3857).needs_reproject(SimpleNamespace(epsg=4326))
                True

                ```
        """
        # Imported here: base.display reaches base.sources, which imports this package, so importing it at module
        # level would be circular.
        from digitalearth.base.display import needs_reproject

        return needs_reproject(data, self.crs)

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            `crs`, plus `bounds` and `domain` when set and `globe` only when it is `True`. The CRS is written as
            held: the constructor has already turned a CRS object into `"EPSG:<code>"` or WKT, and refused a CRS
            with no stored form or one pyramids cannot read, so writing a view does not fail on its CRS.

        Examples:
            - A default view is its CRS:
                ```python
                >>> from digitalearth.base.spec import Viewport
                >>> Viewport().to_dict()
                {'crs': 3857}

                ```
            - A framed globe view writes its region as a dict of named edges:
                ```python
                >>> from digitalearth.base.spec import Bounds, Viewport
                >>> stored = Viewport(4326, bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326), globe=True).to_dict()
                >>> sorted(stored), stored["bounds"]
                (['bounds', 'crs', 'globe'], {'xmin': 0.0, 'ymin': 0.0, 'xmax': 1.0, 'ymax': 1.0, 'crs': 4326})

                ```
        """
        out: dict[str, Any] = {"crs": crs_to_json(self.crs, "Viewport.crs")}
        if self.bounds is not None:
            out["bounds"] = self.bounds.to_dict()
        if self.domain is not None:
            out["domain"] = (
                plain_text(self.domain)
                if isinstance(self.domain, str)
                else list(self.domain)
            )
        if self.globe:
            out["globe"] = True
        if self.center is not None:
            out["center"] = [float(value) for value in self.center]
        if self.zoom is not None:
            out["zoom"] = float(self.zoom)
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Viewport":
        """Rebuild a view from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The view, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping, or its `bounds` is not one, named by where it sits:
                `Viewport.from_dict bounds: Bounds.from_dict needs a mapping; got int`.
            ValueError: for a missing CRS, an unknown key, bounds `Bounds.from_dict` refuses — named the same way —
                or a view the constructor refuses.

        Examples:
            - A stored globe view reads back:
                ```python
                >>> from digitalearth.base.spec import Viewport
                >>> view = Viewport.from_dict({"crs": "+proj=ortho +lat_0=30 +lon_0=10", "globe": True})
                >>> view.globe, view.crs
                (True, '+proj=ortho +lat_0=30 +lon_0=10')

                ```
            - A stored domain box comes back as a tuple of floats:
                ```python
                >>> from digitalearth.base.spec import Viewport
                >>> Viewport.from_dict({"crs": 4326, "domain": [-10, 35, 30, 60]}).domain
                (-10.0, 35.0, 30.0, 60.0)

                ```
            - The CRS cannot be left out:
                ```python
                >>> from digitalearth.base.spec import Viewport
                >>> Viewport.from_dict({"globe": True})
                Traceback (most recent call last):
                    ...
                ValueError: Viewport.from_dict needs 'crs'; got keys ['globe']

                ```
        """
        refuse_unknown(
            "Viewport", data, ("crs", "bounds", "domain", "globe", "center", "zoom")
        )
        bounds = data.get("bounds")
        domain = data.get("domain")
        center = data.get("center")
        return cls(
            crs=require("Viewport", data, "crs"),
            bounds=None
            if bounds is None
            else read_entry("Viewport", "bounds", Bounds.from_dict, bounds),
            domain=tuple(domain) if isinstance(domain, list) else domain,
            globe=data.get("globe", False),
            center=None if center is None else tuple(center),
            zoom=data.get("zoom"),
        )

__post_init__() #

Refuse a view nothing could be drawn in.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/viewport.py
def __post_init__(self) -> None:
    """Refuse a view nothing could be drawn in.

    Raises:
        ValueError: as described on the class.
    """
    if self.crs is None or isinstance(self.crs, bool):
        raise ValueError(f"Viewport needs a display CRS; got {self.crs!r}")
    object.__setattr__(self, "crs", _written_crs("Viewport.crs", self.crs))
    self._check_bounds()
    object.__setattr__(self, "domain", self._checked_domain(self.domain))
    if self.bounds is not None and self.domain is not None:
        # Two regions with no stated precedence leave a renderer to guess which one the map shows.
        raise ValueError(
            f"Viewport takes bounds or a domain, not both; got bounds {self.bounds.as_bbox()} and domain "
            f"{self.domain!r}. Use Viewport.framed(bounds) to frame a view that has a domain"
        )
    globe = true_or_false(self.globe)
    if globe is None:
        raise ValueError(
            f"Viewport globe must be True or False; got {self.globe!r}"
        )
    object.__setattr__(self, "globe", globe)
    object.__setattr__(self, "center", self._checked_center(self.center))
    if self.zoom is not None:
        object.__setattr__(
            self, "zoom", finite_number("Viewport", "zoom", self.zoom)
        )

framed(bounds) #

Return this view framed on bounds, reprojected into the view's CRS if they are in another.

Parameters:

Name Type Description Default
bounds Bounds

The region to show, in any CRS.

required

Returns:

Type Description
Viewport

A new view. This one is unchanged — a change of view is a new value, never an edit of the old one. A

Viewport

domain the view had is dropped: the bounds are now the region it shows.

Raises:

Type Description
ValueError

if bounds is not a Bounds, or cannot be reprojected into the view's CRS.

Examples:

  • Frame a view without changing the one it came from:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> view = Viewport(4326)
    >>> framed = view.framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
    >>> framed.bounds.as_bbox(), view.bounds
    ([0.0, 0.0, 10.0, 5.0], None)
    
  • A region in another CRS is reprojected into the view's:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> framed = Viewport(3857).framed(Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
    >>> framed.bounds.crs, [round(edge) for edge in framed.bounds.as_bbox()]
    (3857, [0, 0, 111319, 111325])
    
  • Framing a view that has a named domain replaces the domain with the bounds:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> framed = Viewport(4326, domain="europe").framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
    >>> framed.domain, framed.bounds.as_bbox()
    (None, [0.0, 0.0, 10.0, 5.0])
    
Source code in src/digitalearth/base/spec/viewport.py
def framed(self, bounds: Bounds) -> "Viewport":
    """Return this view framed on `bounds`, reprojected into the view's CRS if they are in another.

    Args:
        bounds: The region to show, in any CRS.

    Returns:
        A new view. This one is unchanged — a change of view is a new value, never an edit of the old one. A
        `domain` the view had is dropped: the bounds are now the region it shows.

    Raises:
        ValueError: if `bounds` is not a `Bounds`, or cannot be reprojected into the view's CRS.

    Examples:
        - Frame a view without changing the one it came from:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> view = Viewport(4326)
            >>> framed = view.framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
            >>> framed.bounds.as_bbox(), view.bounds
            ([0.0, 0.0, 10.0, 5.0], None)

            ```
        - A region in another CRS is reprojected into the view's:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> framed = Viewport(3857).framed(Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
            >>> framed.bounds.crs, [round(edge) for edge in framed.bounds.as_bbox()]
            (3857, [0, 0, 111319, 111325])

            ```
        - Framing a view that has a named domain replaces the domain with the bounds:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> framed = Viewport(4326, domain="europe").framed(Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
            >>> framed.domain, framed.bounds.as_bbox()
            (None, [0.0, 0.0, 10.0, 5.0])

            ```
    """
    if not isinstance(bounds, Bounds):
        raise ValueError(
            f"Viewport.framed needs a Bounds; got {type(bounds).__name__}"
        )
    return replace(self, bounds=bounds.to_crs(self.crs), domain=None)

from_dict(data) classmethod #

Rebuild a view from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Viewport

The view, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping, or its bounds is not one, named by where it sits: Viewport.from_dict bounds: Bounds.from_dict needs a mapping; got int.

ValueError

for a missing CRS, an unknown key, bounds Bounds.from_dict refuses — named the same way — or a view the constructor refuses.

Examples:

  • A stored globe view reads back:
    >>> from digitalearth.base.spec import Viewport
    >>> view = Viewport.from_dict({"crs": "+proj=ortho +lat_0=30 +lon_0=10", "globe": True})
    >>> view.globe, view.crs
    (True, '+proj=ortho +lat_0=30 +lon_0=10')
    
  • A stored domain box comes back as a tuple of floats:
    >>> from digitalearth.base.spec import Viewport
    >>> Viewport.from_dict({"crs": 4326, "domain": [-10, 35, 30, 60]}).domain
    (-10.0, 35.0, 30.0, 60.0)
    
  • The CRS cannot be left out:
    >>> from digitalearth.base.spec import Viewport
    >>> Viewport.from_dict({"globe": True})
    Traceback (most recent call last):
        ...
    ValueError: Viewport.from_dict needs 'crs'; got keys ['globe']
    
Source code in src/digitalearth/base/spec/viewport.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Viewport":
    """Rebuild a view from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The view, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping, or its `bounds` is not one, named by where it sits:
            `Viewport.from_dict bounds: Bounds.from_dict needs a mapping; got int`.
        ValueError: for a missing CRS, an unknown key, bounds `Bounds.from_dict` refuses — named the same way —
            or a view the constructor refuses.

    Examples:
        - A stored globe view reads back:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> view = Viewport.from_dict({"crs": "+proj=ortho +lat_0=30 +lon_0=10", "globe": True})
            >>> view.globe, view.crs
            (True, '+proj=ortho +lat_0=30 +lon_0=10')

            ```
        - A stored domain box comes back as a tuple of floats:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> Viewport.from_dict({"crs": 4326, "domain": [-10, 35, 30, 60]}).domain
            (-10.0, 35.0, 30.0, 60.0)

            ```
        - The CRS cannot be left out:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> Viewport.from_dict({"globe": True})
            Traceback (most recent call last):
                ...
            ValueError: Viewport.from_dict needs 'crs'; got keys ['globe']

            ```
    """
    refuse_unknown(
        "Viewport", data, ("crs", "bounds", "domain", "globe", "center", "zoom")
    )
    bounds = data.get("bounds")
    domain = data.get("domain")
    center = data.get("center")
    return cls(
        crs=require("Viewport", data, "crs"),
        bounds=None
        if bounds is None
        else read_entry("Viewport", "bounds", Bounds.from_dict, bounds),
        domain=tuple(domain) if isinstance(domain, list) else domain,
        globe=data.get("globe", False),
        center=None if center is None else tuple(center),
        zoom=data.get("zoom"),
    )

needs_reproject(data) #

Whether data has to be reprojected to be drawn in this view.

Parameters:

Name Type Description Default
data Any

A pyramids object exposing .crs and/or .epsg.

required

Returns:

Type Description
bool

False when the data's own CRS and the view's name the same reference system, however either is

bool

spelled — the rule every tier shares, from :func:digitalearth.base.display.needs_reproject.

Examples:

  • Data already in the view's CRS needs no warp, whether the view holds a code or its string:
    >>> from types import SimpleNamespace
    >>> from digitalearth.base.spec import Viewport
    >>> data = SimpleNamespace(epsg=4326)
    >>> Viewport(4326).needs_reproject(data), Viewport("EPSG:4326").needs_reproject(data)
    (False, False)
    
  • Data in another system warps:
    >>> from types import SimpleNamespace
    >>> from digitalearth.base.spec import Viewport
    >>> Viewport(3857).needs_reproject(SimpleNamespace(epsg=4326))
    True
    
Source code in src/digitalearth/base/spec/viewport.py
def needs_reproject(self, data: Any) -> bool:
    """Whether `data` has to be reprojected to be drawn in this view.

    Args:
        data: A pyramids object exposing `.crs` and/or `.epsg`.

    Returns:
        `False` when the data's own CRS and the view's name the same reference system, however either is
        spelled — the rule every tier shares, from :func:`digitalearth.base.display.needs_reproject`.

    Examples:
        - Data already in the view's CRS needs no warp, whether the view holds a code or its string:
            ```python
            >>> from types import SimpleNamespace
            >>> from digitalearth.base.spec import Viewport
            >>> data = SimpleNamespace(epsg=4326)
            >>> Viewport(4326).needs_reproject(data), Viewport("EPSG:4326").needs_reproject(data)
            (False, False)

            ```
        - Data in another system warps:
            ```python
            >>> from types import SimpleNamespace
            >>> from digitalearth.base.spec import Viewport
            >>> Viewport(3857).needs_reproject(SimpleNamespace(epsg=4326))
            True

            ```
    """
    # Imported here: base.display reaches base.sources, which imports this package, so importing it at module
    # level would be circular.
    from digitalearth.base.display import needs_reproject

    return needs_reproject(data, self.crs)

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Name Type Description
dict[str, Any]

crs, plus bounds and domain when set and globe only when it is True. The CRS is written as

held dict[str, Any]

the constructor has already turned a CRS object into "EPSG:<code>" or WKT, and refused a CRS

dict[str, Any]

with no stored form or one pyramids cannot read, so writing a view does not fail on its CRS.

Examples:

  • A default view is its CRS:
    >>> from digitalearth.base.spec import Viewport
    >>> Viewport().to_dict()
    {'crs': 3857}
    
  • A framed globe view writes its region as a dict of named edges:
    >>> from digitalearth.base.spec import Bounds, Viewport
    >>> stored = Viewport(4326, bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326), globe=True).to_dict()
    >>> sorted(stored), stored["bounds"]
    (['bounds', 'crs', 'globe'], {'xmin': 0.0, 'ymin': 0.0, 'xmax': 1.0, 'ymax': 1.0, 'crs': 4326})
    
Source code in src/digitalearth/base/spec/viewport.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        `crs`, plus `bounds` and `domain` when set and `globe` only when it is `True`. The CRS is written as
        held: the constructor has already turned a CRS object into `"EPSG:<code>"` or WKT, and refused a CRS
        with no stored form or one pyramids cannot read, so writing a view does not fail on its CRS.

    Examples:
        - A default view is its CRS:
            ```python
            >>> from digitalearth.base.spec import Viewport
            >>> Viewport().to_dict()
            {'crs': 3857}

            ```
        - A framed globe view writes its region as a dict of named edges:
            ```python
            >>> from digitalearth.base.spec import Bounds, Viewport
            >>> stored = Viewport(4326, bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326), globe=True).to_dict()
            >>> sorted(stored), stored["bounds"]
            (['bounds', 'crs', 'globe'], {'xmin': 0.0, 'ymin': 0.0, 'xmax': 1.0, 'ymax': 1.0, 'crs': 4326})

            ```
    """
    out: dict[str, Any] = {"crs": crs_to_json(self.crs, "Viewport.crs")}
    if self.bounds is not None:
        out["bounds"] = self.bounds.to_dict()
    if self.domain is not None:
        out["domain"] = (
            plain_text(self.domain)
            if isinstance(self.domain, str)
            else list(self.domain)
        )
    if self.globe:
        out["globe"] = True
    if self.center is not None:
        out["center"] = [float(value) for value in self.center]
    if self.zoom is not None:
        out["zoom"] = float(self.zoom)
    return out

digitalearth.base.spec.viewport.Camera dataclass #

Where a 3-D scene is looked at from.

Attributes:

Name Type Description
position Vector3

The camera's location, in the scene's coordinates.

focal_point Vector3

The point it looks at.

view_up Vector3

Which way is up on the screen. It may not be zero or parallel to the line of sight.

view_angle float

The vertical field of view in degrees, strictly between 0 and 180. Ignored by a parallel projection, which has no perspective.

parallel bool

Whether the projection is parallel (orthographic) rather than perspective — for a figure whose distances should be measurable.

parallel_scale float | None

How much of the scene a parallel projection shows: half the view's height, in scene units, as VTK's parallel_scale is. In a parallel projection this — not the distance or the view angle — is the zoom, so two views that differ only in it are different cameras. None, the default, leaves the renderer to fit the scene. Ignored by a perspective projection, as view_angle is by a parallel one.

vertical_exaggeration float | None

The factor applied to the z axis, strictly positive, or None for a camera that does not name one — which is not the same as naming 1.0. A viewpoint built with Camera.look_at(...) says where to stand, not how tall the relief is, so assigning one leaves a scene's exaggeration alone; a camera that does name a factor sets it. It lives on the view, as the 3-D tier already keeps it, rather than in the mesh coordinates.

crs Any

The CRS position and focal_point are measured in — the scene's display CRS — or None when the scene declares none. A CRS object is held in its written spelling, as Viewport holds one.

Raises:

Type Description
ValueError

for a vector that is not three finite numbers, a camera placed at its own focal point, a zero or parallel view_up, a view angle, exaggeration or parallel scale that is not a finite number (a boolean included), a view angle outside (0, 180), a non-positive exaggeration or parallel scale, or a non-boolean parallel.

Examples:

  • A camera south-west of a scene, 30 degrees up:
    >>> from digitalearth.base.spec import Camera
    >>> camera = Camera.look_at((0.0, 0.0, 0.0), azimuth=225.0, elevation=30.0, distance=100.0)
    >>> round(camera.azimuth, 6), round(camera.elevation, 6), round(camera.distance, 6)
    (225.0, 30.0, 100.0)
    
  • Fields left out look at the origin with +z up and VTK's 30-degree view angle; vectors become floats:
    >>> from digitalearth.base.spec import Camera
    >>> camera = Camera((0, -10, 5))
    >>> camera.position, camera.focal_point, camera.view_up, camera.view_angle
    ((0.0, -10.0, 5.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 30.0)
    
  • Looking straight down with the default vertical view_up leaves "up" undefined:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((0.0, 0.0, 10.0))  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Camera view_up (0.0, 0.0, 1.0) is parallel to the line of sight, so 'up' on the screen is ...
    
Source code in src/digitalearth/base/spec/viewport.py
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
@dataclass(frozen=True)
class Camera:
    """Where a 3-D scene is looked at from.

    Attributes:
        position: The camera's location, in the scene's coordinates.
        focal_point: The point it looks at.
        view_up: Which way is up on the screen. It may not be zero or parallel to the line of sight.
        view_angle: The vertical field of view in degrees, strictly between 0 and 180. Ignored by a parallel
            projection, which has no perspective.
        parallel: Whether the projection is parallel (orthographic) rather than perspective — for a figure whose
            distances should be measurable.
        parallel_scale: How much of the scene a parallel projection shows: half the view's height, in scene units,
            as VTK's `parallel_scale` is. In a parallel projection this — not the distance or the view angle — is
            the zoom, so two views that differ only in it are different cameras. ``None``, the default, leaves the
            renderer to fit the scene. Ignored by a perspective projection, as `view_angle` is by a parallel one.
        vertical_exaggeration: The factor applied to the z axis, strictly positive, or `None` for a camera
            that does not name one — which is not the same as naming `1.0`. A viewpoint built with
            `Camera.look_at(...)` says where to stand, not how tall the relief is, so assigning one leaves a
            scene's exaggeration alone; a camera that *does* name a factor sets it. It lives on the view, as the 3-D
            tier already keeps it, rather than in the mesh coordinates.
        crs: The CRS `position` and `focal_point` are measured in — the scene's display CRS — or `None` when the
            scene declares none. A CRS object is held in its written spelling, as `Viewport` holds one.

    Raises:
        ValueError: for a vector that is not three finite numbers, a camera placed at its own focal point, a zero or
            parallel `view_up`, a view angle, exaggeration or parallel scale that is not a finite number (a boolean
            included), a view angle outside `(0, 180)`, a non-positive exaggeration or parallel scale, or a
            non-boolean `parallel`.

    Examples:
        - A camera south-west of a scene, 30 degrees up:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> camera = Camera.look_at((0.0, 0.0, 0.0), azimuth=225.0, elevation=30.0, distance=100.0)
            >>> round(camera.azimuth, 6), round(camera.elevation, 6), round(camera.distance, 6)
            (225.0, 30.0, 100.0)

            ```
        - Fields left out look at the origin with `+z` up and VTK's 30-degree view angle; vectors become floats:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> camera = Camera((0, -10, 5))
            >>> camera.position, camera.focal_point, camera.view_up, camera.view_angle
            ((0.0, -10.0, 5.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 30.0)

            ```
        - Looking straight down with the default vertical `view_up` leaves "up" undefined:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> Camera((0.0, 0.0, 10.0))  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Camera view_up (0.0, 0.0, 1.0) is parallel to the line of sight, so 'up' on the screen is ...

            ```
    """

    position: Vector3
    focal_point: Vector3 = (0.0, 0.0, 0.0)
    view_up: Vector3 = (0.0, 0.0, 1.0)
    view_angle: float = DEFAULT_VIEW_ANGLE
    parallel: bool = False
    parallel_scale: float | None = None
    vertical_exaggeration: float | None = None
    crs: Any = None

    def __post_init__(self) -> None:
        """Refuse a camera that could not frame anything.

        Raises:
            ValueError: as described on the class.
        """
        if self.crs is not None:
            object.__setattr__(self, "crs", _written_crs("Camera.crs", self.crs))
        position = _vector("Camera", "position", self.position)
        focal = _vector("Camera", "focal_point", self.focal_point)
        up = _vector("Camera", "view_up", self.view_up)
        object.__setattr__(self, "position", position)
        object.__setattr__(self, "focal_point", focal)
        object.__setattr__(self, "view_up", up)
        sight = tuple(p - f for p, f in zip(position, focal))
        sight_length = sqrt(sum(component * component for component in sight))
        if sight_length <= 0.0:
            raise ValueError(
                f"Camera position and focal_point are the same point {position}; it looks at nothing"
            )
        up_length = sqrt(sum(component * component for component in up))
        if up_length <= 0.0:
            raise ValueError(
                "Camera view_up is the zero vector, which names no direction"
            )
        cross = (
            sight[1] * up[2] - sight[2] * up[1],
            sight[2] * up[0] - sight[0] * up[2],
            sight[0] * up[1] - sight[1] * up[0],
        )
        sine = sqrt(sum(component * component for component in cross)) / (
            sight_length * up_length
        )
        if sine < _PARALLEL_TOLERANCE:
            raise ValueError(
                f"Camera view_up {up} is parallel to the line of sight, so 'up' on the screen is undefined. "
                "Looking straight down or up, pass a horizontal view_up such as (0, 1, 0)"
            )
        angle = finite_number("Camera", "view_angle", self.view_angle)
        if not 0.0 < angle < 180.0:
            raise ValueError(
                f"Camera view_angle must be strictly between 0 and 180 degrees; got {angle}"
            )
        object.__setattr__(self, "view_angle", angle)
        if self.vertical_exaggeration is not None:
            factor = finite_number(
                "Camera", "vertical_exaggeration", self.vertical_exaggeration
            )
            if factor <= 0.0:
                raise ValueError(
                    f"Camera vertical_exaggeration must be positive; got {factor}"
                )
            object.__setattr__(self, "vertical_exaggeration", factor)
        parallel = true_or_false(self.parallel)
        if parallel is None:
            raise ValueError(
                f"Camera parallel must be True or False; got {self.parallel!r}"
            )
        object.__setattr__(self, "parallel", parallel)
        if self.parallel_scale is not None:
            scale = finite_number("Camera", "parallel_scale", self.parallel_scale)
            if scale <= 0.0:
                raise ValueError(f"Camera parallel_scale must be positive; got {scale}")
            object.__setattr__(self, "parallel_scale", scale)

    @classmethod
    def look_at(
        cls,
        focal_point: Sequence[float],
        *,
        azimuth: float,
        elevation: float,
        distance: float,
        view_up: Sequence[float] = (0.0, 0.0, 1.0),
        view_angle: float = DEFAULT_VIEW_ANGLE,
        parallel: bool = False,
        parallel_scale: float | None = None,
        vertical_exaggeration: float | None = None,
    ) -> "Camera":
        """Place a camera by the direction it looks from, in the terms a map reader uses.

        Args:
            focal_point: The point to look at.
            azimuth: The compass bearing, in degrees, **from the focal point to the camera** — clockwise from north,
                with north along ``+y`` and east along ``+x``. ``225`` puts the camera to the south-west, looking
                north-east.
            elevation: Degrees above the horizontal, from ``-90`` to ``90``. ``90`` looks straight down, which
                needs a horizontal `view_up`.
            distance: How far the camera is from the focal point; strictly positive.
            view_up: Which way is up on the screen.
            view_angle: The vertical field of view, in degrees.
            parallel: Whether the projection is parallel rather than perspective.
            parallel_scale: Half the view's height in scene units, for a parallel projection; ``None`` fits the
                scene.
            vertical_exaggeration: The z-axis factor, or `None` to leave the scene's own alone.

        Returns:
            The camera.

        Raises:
            ValueError: for a non-positive distance, an elevation outside ``[-90, 90]``, an azimuth, elevation or
                distance that is not a finite number, or any value the constructor refuses — including looking
                straight down with the default vertical `view_up`.

        Examples:
            - Looking at a point from due south, level with it:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> camera = Camera.look_at((10.0, 20.0, 0.0), azimuth=180.0, elevation=0.0, distance=5.0)
                >>> tuple(round(value, 6) for value in camera.position)
                (10.0, 15.0, 0.0)

                ```
            - Straight down needs a horizontal up vector:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> top = Camera.look_at((0, 0, 0), azimuth=0, elevation=90, distance=10, view_up=(0, 1, 0))
                >>> tuple(round(value, 6) for value in top.position)
                (0.0, 0.0, 10.0)

                ```
            - A parallel view stores how much of the scene it shows:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> plan = Camera.look_at(
                ...     (0, 0, 0), azimuth=180, elevation=30, distance=10, parallel=True, parallel_scale=50
                ... )
                >>> plan.parallel, plan.parallel_scale
                (True, 50.0)

                ```
            - An elevation past the vertical is refused rather than turning the camera round:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera.look_at((0, 0, 0), azimuth=0, elevation=120, distance=10)  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: Camera.look_at needs an elevation between -90 and 90 degrees; got 120.0. ...

                ```
        """
        span = finite_number(_LOOK_AT, "distance", distance)
        if span <= 0.0:
            raise ValueError(f"Camera.look_at needs a positive distance; got {span}")
        bearing = radians(finite_number(_LOOK_AT, "azimuth", azimuth))
        tilt_degrees = finite_number(_LOOK_AT, "elevation", elevation)
        if not -90.0 <= tilt_degrees <= 90.0:
            # Past the vertical the camera lands on the far side of the focal point, so it would read back with
            # the opposite bearing; refuse it rather than turn the camera round without a word.
            raise ValueError(
                f"Camera.look_at needs an elevation between -90 and 90 degrees; got {tilt_degrees}. To look from "
                "the other side, turn the azimuth by 180 instead"
            )
        tilt = radians(tilt_degrees)
        focal = _vector(_LOOK_AT, "focal_point", focal_point)
        offset = (
            span * sin(bearing) * cos(tilt),
            span * cos(bearing) * cos(tilt),
            span * sin(tilt),
        )
        return cls(
            position=(focal[0] + offset[0], focal[1] + offset[1], focal[2] + offset[2]),
            focal_point=focal,
            view_up=_vector(_LOOK_AT, "view_up", view_up),
            view_angle=view_angle,
            parallel=parallel,
            parallel_scale=parallel_scale,
            vertical_exaggeration=vertical_exaggeration,
        )

    @property
    def distance(self) -> float:
        """How far the camera is from its focal point.

        Returns:
            The Euclidean distance, in scene units.

        Examples:
            - A 3-4-5 triangle:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((3.0, 4.0, 0.0)).distance
                5.0

                ```
        """
        return sqrt(sum((p - f) ** 2 for p, f in zip(self.position, self.focal_point)))

    @property
    def azimuth(self) -> float:
        """The compass bearing from the focal point to the camera, in degrees.

        Returns:
            A bearing in `[0, 360)`, clockwise from north (`+y`). A camera directly above or below its focal
            point has no horizontal direction, so its bearing means nothing: it comes out as `0`, or as `180` when
            the y offset is a negative zero, because `atan2` keeps the sign of zero.

        Examples:
            - A camera due east of its focal point:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((5.0, 0.0, 0.0)).azimuth
                90.0

                ```
            - Bearings run clockwise, so due west is 270 rather than -90:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((-5.0, 0.0, 0.0)).azimuth
                270.0

                ```
            - A camera a rounding error west of due north reads as due north, not as 360:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((-1e-15, 5.0, 0.0)).azimuth
                0.0

                ```
        """
        dx = self.position[0] - self.focal_point[0]
        dy = self.position[1] - self.focal_point[1]
        bearing = degrees(atan2(dx, dy)) % 360.0
        # `%` rounds a tiny negative angle — a camera a rounding error west of due north — up to exactly 360.0,
        # outside the range this promises. That bearing is due north.
        return 0.0 if bearing >= 360.0 else bearing

    @property
    def elevation(self) -> float:
        """The angle of the camera above the horizontal, seen from the focal point.

        Returns:
            Degrees in ``[-90, 90]``: positive above, negative below.

        Examples:
            - A camera level with its focal point:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((0.0, 5.0, 0.0)).elevation
                0.0

                ```
            - A camera straight above, which needs a horizontal up vector:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera((0.0, 0.0, 5.0), view_up=(0.0, 1.0, 0.0)).elevation
                90.0

                ```
        """
        dx = self.position[0] - self.focal_point[0]
        dy = self.position[1] - self.focal_point[1]
        dz = self.position[2] - self.focal_point[2]
        return degrees(atan2(dz, hypot(dx, dy)))

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            Every field, and `crs` when one is set. A camera is small, and a stored view is only reproducible if it
            records the settings that were in force rather than relying on today's defaults.

        Examples:
            - Every setting is written, defaults included:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> stored = Camera((0.0, -10.0, 5.0), parallel=True).to_dict()
                >>> stored["position"], stored["parallel"], stored["view_angle"]
                ([0.0, -10.0, 5.0], True, 30.0)

                ```
            - A CRS is written only when the camera has one:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> "crs" in Camera((0.0, -10.0, 5.0)).to_dict()
                False
                >>> Camera((0.0, -10.0, 5.0), crs=4326).to_dict()["crs"]
                4326

                ```
            - The dict survives a JSON round trip and rebuilds an equal camera:
                ```python
                >>> import json
                >>> from digitalearth.base.spec import Camera
                >>> text = json.dumps(Camera((0.0, -10.0, 5.0), vertical_exaggeration=3.0).to_dict())
                >>> Camera.from_dict(json.loads(text)).vertical_exaggeration
                3.0

                ```
        """
        return {
            "position": list(self.position),
            "focal_point": list(self.focal_point),
            "view_up": list(self.view_up),
            "view_angle": self.view_angle,
            "parallel": self.parallel,
            "parallel_scale": self.parallel_scale,
            "vertical_exaggeration": self.vertical_exaggeration,
            # Written only when set: a camera with no CRS stores what it stored before the field existed, so a
            # reader that refuses unknown keys still reads it.
            **({} if self.crs is None else {"crs": self.crs}),
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "Camera":
        """Rebuild a camera from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The camera, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping, or `position`, `focal_point` or `view_up` is not a list,
                naming the field.
            ValueError: for a missing position, an unknown key, or a camera the constructor refuses.

        Examples:
            - A stored camera reads back with its exaggeration:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera.from_dict({"position": [0, -10, 5], "vertical_exaggeration": 3}).vertical_exaggeration
                3.0

                ```
            - Only the position is required; the rest takes the constructor's defaults:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> camera = Camera.from_dict({"position": [0, -10, 5]})
                >>> camera.focal_point, camera.parallel
                ((0.0, 0.0, 0.0), False)

                ```
            - A missing position is named:
                ```python
                >>> from digitalearth.base.spec import Camera
                >>> Camera.from_dict({"view_angle": 45})
                Traceback (most recent call last):
                    ...
                ValueError: Camera.from_dict needs 'position'; got keys ['view_angle']

                ```
        """
        refuse_unknown(
            "Camera",
            data,
            (
                "position",
                "focal_point",
                "view_up",
                "view_angle",
                "parallel",
                "parallel_scale",
                "vertical_exaggeration",
                "crs",
            ),
        )
        return cls(
            position=as_list("Camera", "position", require("Camera", data, "position")),
            focal_point=as_list(
                "Camera", "focal_point", data.get("focal_point", (0.0, 0.0, 0.0))
            ),
            view_up=as_list("Camera", "view_up", data.get("view_up", (0.0, 0.0, 1.0))),
            view_angle=data.get("view_angle", DEFAULT_VIEW_ANGLE),
            parallel=data.get("parallel", False),
            parallel_scale=data.get("parallel_scale"),
            vertical_exaggeration=data.get("vertical_exaggeration"),
            crs=data.get("crs"),
        )

azimuth property #

The compass bearing from the focal point to the camera, in degrees.

Returns:

Type Description
float

A bearing in [0, 360), clockwise from north (+y). A camera directly above or below its focal

float

point has no horizontal direction, so its bearing means nothing: it comes out as 0, or as 180 when

float

the y offset is a negative zero, because atan2 keeps the sign of zero.

Examples:

  • A camera due east of its focal point:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((5.0, 0.0, 0.0)).azimuth
    90.0
    
  • Bearings run clockwise, so due west is 270 rather than -90:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((-5.0, 0.0, 0.0)).azimuth
    270.0
    
  • A camera a rounding error west of due north reads as due north, not as 360:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((-1e-15, 5.0, 0.0)).azimuth
    0.0
    

distance property #

How far the camera is from its focal point.

Returns:

Type Description
float

The Euclidean distance, in scene units.

Examples:

  • A 3-4-5 triangle:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((3.0, 4.0, 0.0)).distance
    5.0
    

elevation property #

The angle of the camera above the horizontal, seen from the focal point.

Returns:

Type Description
float

Degrees in [-90, 90]: positive above, negative below.

Examples:

  • A camera level with its focal point:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((0.0, 5.0, 0.0)).elevation
    0.0
    
  • A camera straight above, which needs a horizontal up vector:
    >>> from digitalearth.base.spec import Camera
    >>> Camera((0.0, 0.0, 5.0), view_up=(0.0, 1.0, 0.0)).elevation
    90.0
    

__post_init__() #

Refuse a camera that could not frame anything.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/viewport.py
def __post_init__(self) -> None:
    """Refuse a camera that could not frame anything.

    Raises:
        ValueError: as described on the class.
    """
    if self.crs is not None:
        object.__setattr__(self, "crs", _written_crs("Camera.crs", self.crs))
    position = _vector("Camera", "position", self.position)
    focal = _vector("Camera", "focal_point", self.focal_point)
    up = _vector("Camera", "view_up", self.view_up)
    object.__setattr__(self, "position", position)
    object.__setattr__(self, "focal_point", focal)
    object.__setattr__(self, "view_up", up)
    sight = tuple(p - f for p, f in zip(position, focal))
    sight_length = sqrt(sum(component * component for component in sight))
    if sight_length <= 0.0:
        raise ValueError(
            f"Camera position and focal_point are the same point {position}; it looks at nothing"
        )
    up_length = sqrt(sum(component * component for component in up))
    if up_length <= 0.0:
        raise ValueError(
            "Camera view_up is the zero vector, which names no direction"
        )
    cross = (
        sight[1] * up[2] - sight[2] * up[1],
        sight[2] * up[0] - sight[0] * up[2],
        sight[0] * up[1] - sight[1] * up[0],
    )
    sine = sqrt(sum(component * component for component in cross)) / (
        sight_length * up_length
    )
    if sine < _PARALLEL_TOLERANCE:
        raise ValueError(
            f"Camera view_up {up} is parallel to the line of sight, so 'up' on the screen is undefined. "
            "Looking straight down or up, pass a horizontal view_up such as (0, 1, 0)"
        )
    angle = finite_number("Camera", "view_angle", self.view_angle)
    if not 0.0 < angle < 180.0:
        raise ValueError(
            f"Camera view_angle must be strictly between 0 and 180 degrees; got {angle}"
        )
    object.__setattr__(self, "view_angle", angle)
    if self.vertical_exaggeration is not None:
        factor = finite_number(
            "Camera", "vertical_exaggeration", self.vertical_exaggeration
        )
        if factor <= 0.0:
            raise ValueError(
                f"Camera vertical_exaggeration must be positive; got {factor}"
            )
        object.__setattr__(self, "vertical_exaggeration", factor)
    parallel = true_or_false(self.parallel)
    if parallel is None:
        raise ValueError(
            f"Camera parallel must be True or False; got {self.parallel!r}"
        )
    object.__setattr__(self, "parallel", parallel)
    if self.parallel_scale is not None:
        scale = finite_number("Camera", "parallel_scale", self.parallel_scale)
        if scale <= 0.0:
            raise ValueError(f"Camera parallel_scale must be positive; got {scale}")
        object.__setattr__(self, "parallel_scale", scale)

from_dict(data) classmethod #

Rebuild a camera from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
Camera

The camera, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping, or position, focal_point or view_up is not a list, naming the field.

ValueError

for a missing position, an unknown key, or a camera the constructor refuses.

Examples:

  • A stored camera reads back with its exaggeration:
    >>> from digitalearth.base.spec import Camera
    >>> Camera.from_dict({"position": [0, -10, 5], "vertical_exaggeration": 3}).vertical_exaggeration
    3.0
    
  • Only the position is required; the rest takes the constructor's defaults:
    >>> from digitalearth.base.spec import Camera
    >>> camera = Camera.from_dict({"position": [0, -10, 5]})
    >>> camera.focal_point, camera.parallel
    ((0.0, 0.0, 0.0), False)
    
  • A missing position is named:
    >>> from digitalearth.base.spec import Camera
    >>> Camera.from_dict({"view_angle": 45})
    Traceback (most recent call last):
        ...
    ValueError: Camera.from_dict needs 'position'; got keys ['view_angle']
    
Source code in src/digitalearth/base/spec/viewport.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "Camera":
    """Rebuild a camera from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The camera, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping, or `position`, `focal_point` or `view_up` is not a list,
            naming the field.
        ValueError: for a missing position, an unknown key, or a camera the constructor refuses.

    Examples:
        - A stored camera reads back with its exaggeration:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> Camera.from_dict({"position": [0, -10, 5], "vertical_exaggeration": 3}).vertical_exaggeration
            3.0

            ```
        - Only the position is required; the rest takes the constructor's defaults:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> camera = Camera.from_dict({"position": [0, -10, 5]})
            >>> camera.focal_point, camera.parallel
            ((0.0, 0.0, 0.0), False)

            ```
        - A missing position is named:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> Camera.from_dict({"view_angle": 45})
            Traceback (most recent call last):
                ...
            ValueError: Camera.from_dict needs 'position'; got keys ['view_angle']

            ```
    """
    refuse_unknown(
        "Camera",
        data,
        (
            "position",
            "focal_point",
            "view_up",
            "view_angle",
            "parallel",
            "parallel_scale",
            "vertical_exaggeration",
            "crs",
        ),
    )
    return cls(
        position=as_list("Camera", "position", require("Camera", data, "position")),
        focal_point=as_list(
            "Camera", "focal_point", data.get("focal_point", (0.0, 0.0, 0.0))
        ),
        view_up=as_list("Camera", "view_up", data.get("view_up", (0.0, 0.0, 1.0))),
        view_angle=data.get("view_angle", DEFAULT_VIEW_ANGLE),
        parallel=data.get("parallel", False),
        parallel_scale=data.get("parallel_scale"),
        vertical_exaggeration=data.get("vertical_exaggeration"),
        crs=data.get("crs"),
    )

look_at(focal_point, *, azimuth, elevation, distance, view_up=(0.0, 0.0, 1.0), view_angle=DEFAULT_VIEW_ANGLE, parallel=False, parallel_scale=None, vertical_exaggeration=None) classmethod #

Place a camera by the direction it looks from, in the terms a map reader uses.

Parameters:

Name Type Description Default
focal_point Sequence[float]

The point to look at.

required
azimuth float

The compass bearing, in degrees, from the focal point to the camera — clockwise from north, with north along +y and east along +x. 225 puts the camera to the south-west, looking north-east.

required
elevation float

Degrees above the horizontal, from -90 to 90. 90 looks straight down, which needs a horizontal view_up.

required
distance float

How far the camera is from the focal point; strictly positive.

required
view_up Sequence[float]

Which way is up on the screen.

(0.0, 0.0, 1.0)
view_angle float

The vertical field of view, in degrees.

DEFAULT_VIEW_ANGLE
parallel bool

Whether the projection is parallel rather than perspective.

False
parallel_scale float | None

Half the view's height in scene units, for a parallel projection; None fits the scene.

None
vertical_exaggeration float | None

The z-axis factor, or None to leave the scene's own alone.

None

Returns:

Type Description
Camera

The camera.

Raises:

Type Description
ValueError

for a non-positive distance, an elevation outside [-90, 90], an azimuth, elevation or distance that is not a finite number, or any value the constructor refuses — including looking straight down with the default vertical view_up.

Examples:

  • Looking at a point from due south, level with it:
    >>> from digitalearth.base.spec import Camera
    >>> camera = Camera.look_at((10.0, 20.0, 0.0), azimuth=180.0, elevation=0.0, distance=5.0)
    >>> tuple(round(value, 6) for value in camera.position)
    (10.0, 15.0, 0.0)
    
  • Straight down needs a horizontal up vector:
    >>> from digitalearth.base.spec import Camera
    >>> top = Camera.look_at((0, 0, 0), azimuth=0, elevation=90, distance=10, view_up=(0, 1, 0))
    >>> tuple(round(value, 6) for value in top.position)
    (0.0, 0.0, 10.0)
    
  • A parallel view stores how much of the scene it shows:
    >>> from digitalearth.base.spec import Camera
    >>> plan = Camera.look_at(
    ...     (0, 0, 0), azimuth=180, elevation=30, distance=10, parallel=True, parallel_scale=50
    ... )
    >>> plan.parallel, plan.parallel_scale
    (True, 50.0)
    
  • An elevation past the vertical is refused rather than turning the camera round:
    >>> from digitalearth.base.spec import Camera
    >>> Camera.look_at((0, 0, 0), azimuth=0, elevation=120, distance=10)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Camera.look_at needs an elevation between -90 and 90 degrees; got 120.0. ...
    
Source code in src/digitalearth/base/spec/viewport.py
@classmethod
def look_at(
    cls,
    focal_point: Sequence[float],
    *,
    azimuth: float,
    elevation: float,
    distance: float,
    view_up: Sequence[float] = (0.0, 0.0, 1.0),
    view_angle: float = DEFAULT_VIEW_ANGLE,
    parallel: bool = False,
    parallel_scale: float | None = None,
    vertical_exaggeration: float | None = None,
) -> "Camera":
    """Place a camera by the direction it looks from, in the terms a map reader uses.

    Args:
        focal_point: The point to look at.
        azimuth: The compass bearing, in degrees, **from the focal point to the camera** — clockwise from north,
            with north along ``+y`` and east along ``+x``. ``225`` puts the camera to the south-west, looking
            north-east.
        elevation: Degrees above the horizontal, from ``-90`` to ``90``. ``90`` looks straight down, which
            needs a horizontal `view_up`.
        distance: How far the camera is from the focal point; strictly positive.
        view_up: Which way is up on the screen.
        view_angle: The vertical field of view, in degrees.
        parallel: Whether the projection is parallel rather than perspective.
        parallel_scale: Half the view's height in scene units, for a parallel projection; ``None`` fits the
            scene.
        vertical_exaggeration: The z-axis factor, or `None` to leave the scene's own alone.

    Returns:
        The camera.

    Raises:
        ValueError: for a non-positive distance, an elevation outside ``[-90, 90]``, an azimuth, elevation or
            distance that is not a finite number, or any value the constructor refuses — including looking
            straight down with the default vertical `view_up`.

    Examples:
        - Looking at a point from due south, level with it:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> camera = Camera.look_at((10.0, 20.0, 0.0), azimuth=180.0, elevation=0.0, distance=5.0)
            >>> tuple(round(value, 6) for value in camera.position)
            (10.0, 15.0, 0.0)

            ```
        - Straight down needs a horizontal up vector:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> top = Camera.look_at((0, 0, 0), azimuth=0, elevation=90, distance=10, view_up=(0, 1, 0))
            >>> tuple(round(value, 6) for value in top.position)
            (0.0, 0.0, 10.0)

            ```
        - A parallel view stores how much of the scene it shows:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> plan = Camera.look_at(
            ...     (0, 0, 0), azimuth=180, elevation=30, distance=10, parallel=True, parallel_scale=50
            ... )
            >>> plan.parallel, plan.parallel_scale
            (True, 50.0)

            ```
        - An elevation past the vertical is refused rather than turning the camera round:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> Camera.look_at((0, 0, 0), azimuth=0, elevation=120, distance=10)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: Camera.look_at needs an elevation between -90 and 90 degrees; got 120.0. ...

            ```
    """
    span = finite_number(_LOOK_AT, "distance", distance)
    if span <= 0.0:
        raise ValueError(f"Camera.look_at needs a positive distance; got {span}")
    bearing = radians(finite_number(_LOOK_AT, "azimuth", azimuth))
    tilt_degrees = finite_number(_LOOK_AT, "elevation", elevation)
    if not -90.0 <= tilt_degrees <= 90.0:
        # Past the vertical the camera lands on the far side of the focal point, so it would read back with
        # the opposite bearing; refuse it rather than turn the camera round without a word.
        raise ValueError(
            f"Camera.look_at needs an elevation between -90 and 90 degrees; got {tilt_degrees}. To look from "
            "the other side, turn the azimuth by 180 instead"
        )
    tilt = radians(tilt_degrees)
    focal = _vector(_LOOK_AT, "focal_point", focal_point)
    offset = (
        span * sin(bearing) * cos(tilt),
        span * cos(bearing) * cos(tilt),
        span * sin(tilt),
    )
    return cls(
        position=(focal[0] + offset[0], focal[1] + offset[1], focal[2] + offset[2]),
        focal_point=focal,
        view_up=_vector(_LOOK_AT, "view_up", view_up),
        view_angle=view_angle,
        parallel=parallel,
        parallel_scale=parallel_scale,
        vertical_exaggeration=vertical_exaggeration,
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

Every field, and crs when one is set. A camera is small, and a stored view is only reproducible if it

dict[str, Any]

records the settings that were in force rather than relying on today's defaults.

Examples:

  • Every setting is written, defaults included:
    >>> from digitalearth.base.spec import Camera
    >>> stored = Camera((0.0, -10.0, 5.0), parallel=True).to_dict()
    >>> stored["position"], stored["parallel"], stored["view_angle"]
    ([0.0, -10.0, 5.0], True, 30.0)
    
  • A CRS is written only when the camera has one:
    >>> from digitalearth.base.spec import Camera
    >>> "crs" in Camera((0.0, -10.0, 5.0)).to_dict()
    False
    >>> Camera((0.0, -10.0, 5.0), crs=4326).to_dict()["crs"]
    4326
    
  • The dict survives a JSON round trip and rebuilds an equal camera:
    >>> import json
    >>> from digitalearth.base.spec import Camera
    >>> text = json.dumps(Camera((0.0, -10.0, 5.0), vertical_exaggeration=3.0).to_dict())
    >>> Camera.from_dict(json.loads(text)).vertical_exaggeration
    3.0
    
Source code in src/digitalearth/base/spec/viewport.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        Every field, and `crs` when one is set. A camera is small, and a stored view is only reproducible if it
        records the settings that were in force rather than relying on today's defaults.

    Examples:
        - Every setting is written, defaults included:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> stored = Camera((0.0, -10.0, 5.0), parallel=True).to_dict()
            >>> stored["position"], stored["parallel"], stored["view_angle"]
            ([0.0, -10.0, 5.0], True, 30.0)

            ```
        - A CRS is written only when the camera has one:
            ```python
            >>> from digitalearth.base.spec import Camera
            >>> "crs" in Camera((0.0, -10.0, 5.0)).to_dict()
            False
            >>> Camera((0.0, -10.0, 5.0), crs=4326).to_dict()["crs"]
            4326

            ```
        - The dict survives a JSON round trip and rebuilds an equal camera:
            ```python
            >>> import json
            >>> from digitalearth.base.spec import Camera
            >>> text = json.dumps(Camera((0.0, -10.0, 5.0), vertical_exaggeration=3.0).to_dict())
            >>> Camera.from_dict(json.loads(text)).vertical_exaggeration
            3.0

            ```
    """
    return {
        "position": list(self.position),
        "focal_point": list(self.focal_point),
        "view_up": list(self.view_up),
        "view_angle": self.view_angle,
        "parallel": self.parallel,
        "parallel_scale": self.parallel_scale,
        "vertical_exaggeration": self.vertical_exaggeration,
        # Written only when set: a camera with no CRS stores what it stored before the field existed, so a
        # reader that refuses unknown keys still reads it.
        **({} if self.crs is None else {"crs": self.crs}),
    }

RenderTarget — the output owns the read budget#

A layer never chooses how much of its source to read; the output it is rendered to does, and view_request is how a view becomes a ViewRequest.

digitalearth.base.spec.target.RenderTarget dataclass #

An output a figure is rendered to: its kind, its canvas and its read budget.

Attributes:

Name Type Description
kind str

One of :data:TARGET_KINDS.

width int | None

Canvas width in CSS pixels, or None.

height int | None

Canvas height in CSS pixels, or None.

pixel_ratio float

Device pixels per CSS pixel — 2.0 on a HiDPI display.

budget int | None

Cells the target may read per source. None takes :data:DEFAULT_BUDGETS for the kind.

Raises:

Type Description
ValueError

for an unknown kind (naming the kinds that exist), a non-positive or non-integer canvas or budget, or a pixel ratio that is a boolean, not a number, not finite or not positive.

Examples:

  • A page is lighter than a window by default:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("window").effective_budget, RenderTarget("html").effective_budget
    (4000000, 1000000)
    
  • A whole-number pixel ratio is stored as a float:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("image", width=1200, height=800, pixel_ratio=2).pixel_ratio
    2.0
    
  • An unknown kind is refused, naming the kinds that exist:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("pdf")
    Traceback (most recent call last):
        ...
    ValueError: RenderTarget kind must be one of ['window', 'html', 'image', 'batch']; got 'pdf'
    
Source code in src/digitalearth/base/spec/target.py
@dataclass(frozen=True)
class RenderTarget:
    """An output a figure is rendered to: its kind, its canvas and its read budget.

    Attributes:
        kind: One of :data:`TARGET_KINDS`.
        width: Canvas width in CSS pixels, or ``None``.
        height: Canvas height in CSS pixels, or ``None``.
        pixel_ratio: Device pixels per CSS pixel — ``2.0`` on a HiDPI display.
        budget: Cells the target may read per source. ``None`` takes :data:`DEFAULT_BUDGETS` for the kind.

    Raises:
        ValueError: for an unknown kind (naming the kinds that exist), a non-positive or non-integer canvas or
            budget, or a pixel ratio that is a boolean, not a number, not finite or not positive.

    Examples:
        - A page is lighter than a window by default:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget("window").effective_budget, RenderTarget("html").effective_budget
            (4000000, 1000000)

            ```
        - A whole-number pixel ratio is stored as a float:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget("image", width=1200, height=800, pixel_ratio=2).pixel_ratio
            2.0

            ```
        - An unknown kind is refused, naming the kinds that exist:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget("pdf")
            Traceback (most recent call last):
                ...
            ValueError: RenderTarget kind must be one of ['window', 'html', 'image', 'batch']; got 'pdf'

            ```
    """

    kind: str = "window"
    width: int | None = None
    height: int | None = None
    pixel_ratio: float = 1.0
    budget: int | None = None

    def __post_init__(self) -> None:
        """Refuse a target nothing could be rendered to.

        Raises:
            ValueError: as described on the class.
        """
        if self.kind not in TARGET_KINDS:
            raise ValueError(
                f"RenderTarget kind must be one of {list(TARGET_KINDS)}; got {self.kind!r}"
            )
        for name in ("width", "height", "budget"):
            object.__setattr__(self, name, _positive_whole(name, getattr(self, name)))
        ratio = positive_number(self.pixel_ratio)
        if ratio is None:
            raise ValueError(
                f"RenderTarget pixel_ratio must be a positive number; got {self.pixel_ratio!r}"
            )
        object.__setattr__(self, "pixel_ratio", ratio)

    @property
    def effective_budget(self) -> int:
        """The cells this target reads per source.

        Returns:
            `budget` when set, otherwise the kind's entry in :data:`DEFAULT_BUDGETS`.

        Examples:
            - An explicit budget wins over the kind's default:
                ```python
                >>> from digitalearth.base.spec import RenderTarget
                >>> RenderTarget("html", budget=250_000).effective_budget
                250000

                ```
            - With no budget of its own, each kind reads its entry in `DEFAULT_BUDGETS`:
                ```python
                >>> from digitalearth.base.spec import TARGET_KINDS, RenderTarget
                >>> {kind: RenderTarget(kind).effective_budget for kind in TARGET_KINDS}
                {'window': 4000000, 'html': 1000000, 'image': 4000000, 'batch': 4000000}

                ```
        """
        return self.budget if self.budget is not None else DEFAULT_BUDGETS[self.kind]

    def view_request(
        self,
        view: Viewport | Camera | None = None,
        *,
        bounds: Bounds | None = None,
    ) -> ViewRequest:
        """Return the request a reader answers for this view on this target.

        The region comes from the view and the canvas and budget from the target — the only way this package makes a
        :class:`~digitalearth.base.spec.viewrequest.ViewRequest` from a view, so a layer never chooses its own budget.

        Args:
            view: The view being rendered. A `Viewport` supplies its framed region; a `Camera` supplies none, since a
                3-D view has no rectangle to read.
            bounds: A region to read instead of the view's. When a `Viewport` is given, the region is reprojected into
                the view's CRS, which is the CRS the reader is asked in; with a `Camera` or no view it is used as
                given.

        Returns:
            The request: region, canvas, pixel ratio and :attr:`effective_budget`. A view framed by a
            `(west, south, east, north)` domain asks for that box, reprojected into the view's CRS. With a canvas
            named, the request's :meth:`~digitalearth.base.spec.viewrequest.ViewRequest.side` sizes a read to the
            canvas, within the budget. The region is `None` when neither the view nor `bounds` supplies one — an
            unframed `Viewport` included — and a request with no region carries no CRS either: the reader returns the
            source in its own CRS, and the renderer reprojects it into the view's.

        Raises:
            ValueError: if `view` is neither a `Viewport`, a `Camera` nor `None`, if `bounds` is not a `Bounds`, if
                `bounds` or a domain box cannot be reprojected into the viewport's CRS, or if the view is framed by a
                named domain, which `base` cannot resolve.

        Examples:
            - The view's region, the target's canvas and budget:
                ```python
                >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
                >>> view = Viewport(4326, bounds=Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
                >>> request = RenderTarget("html", width=800, height=400).view_request(view)
                >>> request.as_bbox(), request.width, request.budget
                ((0.0, 0.0, 10.0, 5.0), 800, 1000000)

                ```
            - A region given in another CRS is asked for in the view's:
                ```python
                >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
                >>> request = RenderTarget().view_request(Viewport(3857), bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
                >>> request.crs, [round(edge) for edge in request.as_bbox()]
                (3857, [0, 0, 111319, 111325])

                ```
            - A view framed by a domain box asks for that box, in the view's CRS:
                ```python
                >>> from digitalearth.base.spec import RenderTarget, Viewport
                >>> request = RenderTarget().view_request(Viewport(3857, domain=(0.0, 0.0, 1.0, 1.0)))
                >>> request.crs, [round(edge) for edge in request.as_bbox()]
                (3857, [0, 0, 111319, 111325])

                ```
            - A 3-D camera has no rectangle, so only the canvas and the budget are set:
                ```python
                >>> from digitalearth.base.spec import Camera, RenderTarget
                >>> request = RenderTarget("image", width=640, height=480).view_request(Camera((0.0, -10.0, 5.0)))
                >>> request.bounds, request.width, request.budget
                (None, 640, 4000000)

                ```
        """
        if view is not None and not isinstance(view, (Viewport, Camera)):
            raise ValueError(
                f"RenderTarget.view_request needs a Viewport, a Camera or None; got {type(view).__name__}"
            )
        if bounds is not None and not isinstance(bounds, Bounds):
            raise ValueError(
                f"RenderTarget.view_request needs bounds as a Bounds; got {type(bounds).__name__}"
            )
        region: Bounds | None = None
        if isinstance(view, Viewport) and bounds is not None:
            region = view.framed(bounds).bounds
        elif isinstance(view, Viewport):
            region = view.bounds if view.domain is None else self._domain_region(view)
        elif bounds is not None:
            region = bounds
        return ViewRequest(
            bounds=region,
            width=self.width,
            height=self.height,
            pixel_ratio=self.pixel_ratio,
            budget=self.effective_budget,
        )

    @staticmethod
    def _domain_region(view: Viewport) -> Bounds:
        """Return the region a domain-framed view shows, in the view's CRS.

        Args:
            view: A view framed by `domain` rather than `bounds`.

        Returns:
            The `(west, south, east, north)` box, read in degrees and reprojected into the view's CRS.

        Raises:
            KeyError: for a name no region is registered under, from `resolve_domain`, which names the ones
                that are.
            ValueError: from `Bounds.to_crs`, for a box part of which the view's CRS cannot show.

        Note:
            A named domain used to be refused here, because the table lived in `static/` and `base` cannot
            import a renderer — so a view framed by `domain="europe"` read its whole source instead of Europe.
            The table is `base/domains.py` now, and a name resolves to the same box on every tier.
        """
        region = resolve_domain(view.domain)
        return Bounds.from_bbox(list(region), crs=4326).to_crs(view.crs)  # type: ignore[arg-type]

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``kind`` and ``pixel_ratio``, plus the canvas and the budget when set. An unset budget is written as
            unset, not as the kind's default, so a stored target keeps following the default if the default changes.

        Examples:
            - A retina image target:
                ```python
                >>> from digitalearth.base.spec import RenderTarget
                >>> RenderTarget("image", width=1200, height=800, pixel_ratio=2.0).to_dict()
                {'kind': 'image', 'width': 1200, 'height': 800, 'pixel_ratio': 2.0}

                ```
            - The pixel ratio is written even at its default, and an unset budget stays unset:
                ```python
                >>> from digitalearth.base.spec import RenderTarget
                >>> RenderTarget("html").to_dict()
                {'kind': 'html', 'pixel_ratio': 1.0}

                ```
        """
        out: dict[str, Any] = {"kind": plain_text(self.kind)}
        for name in ("width", "height"):
            value = getattr(self, name)
            if value is not None:
                out[name] = value
        out["pixel_ratio"] = self.pixel_ratio
        if self.budget is not None:
            out["budget"] = self.budget
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "RenderTarget":
        """Rebuild a target from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`. A missing ``kind`` means ``"window"``.

        Returns:
            The target, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping.
            ValueError: for an unknown key, or a target the constructor refuses.

        Examples:
            - A stored page target reads back with its budget:
                ```python
                >>> from digitalearth.base.spec import RenderTarget
                >>> RenderTarget.from_dict({"kind": "html", "budget": 500000}).effective_budget
                500000

                ```
            - A key this version does not know is refused rather than dropped:
                ```python
                >>> from digitalearth.base.spec import RenderTarget
                >>> RenderTarget.from_dict({"kind": "html", "dpi": 2})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: RenderTarget.from_dict got unknown keys ['dpi']; known keys are ['budget', 'height', ...]

                ```
        """
        refuse_unknown(
            "RenderTarget", data, ("kind", "width", "height", "pixel_ratio", "budget")
        )
        return cls(
            kind=data.get("kind", "window"),
            width=data.get("width"),
            height=data.get("height"),
            pixel_ratio=data.get("pixel_ratio", 1.0),
            budget=data.get("budget"),
        )

effective_budget property #

The cells this target reads per source.

Returns:

Type Description
int

budget when set, otherwise the kind's entry in :data:DEFAULT_BUDGETS.

Examples:

  • An explicit budget wins over the kind's default:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("html", budget=250_000).effective_budget
    250000
    
  • With no budget of its own, each kind reads its entry in DEFAULT_BUDGETS:
    >>> from digitalearth.base.spec import TARGET_KINDS, RenderTarget
    >>> {kind: RenderTarget(kind).effective_budget for kind in TARGET_KINDS}
    {'window': 4000000, 'html': 1000000, 'image': 4000000, 'batch': 4000000}
    

__post_init__() #

Refuse a target nothing could be rendered to.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/target.py
def __post_init__(self) -> None:
    """Refuse a target nothing could be rendered to.

    Raises:
        ValueError: as described on the class.
    """
    if self.kind not in TARGET_KINDS:
        raise ValueError(
            f"RenderTarget kind must be one of {list(TARGET_KINDS)}; got {self.kind!r}"
        )
    for name in ("width", "height", "budget"):
        object.__setattr__(self, name, _positive_whole(name, getattr(self, name)))
    ratio = positive_number(self.pixel_ratio)
    if ratio is None:
        raise ValueError(
            f"RenderTarget pixel_ratio must be a positive number; got {self.pixel_ratio!r}"
        )
    object.__setattr__(self, "pixel_ratio", ratio)

from_dict(data) classmethod #

Rebuild a target from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict. A missing kind means "window".

required

Returns:

Type Description
RenderTarget

The target, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping.

ValueError

for an unknown key, or a target the constructor refuses.

Examples:

  • A stored page target reads back with its budget:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget.from_dict({"kind": "html", "budget": 500000}).effective_budget
    500000
    
  • A key this version does not know is refused rather than dropped:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget.from_dict({"kind": "html", "dpi": 2})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: RenderTarget.from_dict got unknown keys ['dpi']; known keys are ['budget', 'height', ...]
    
Source code in src/digitalearth/base/spec/target.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "RenderTarget":
    """Rebuild a target from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`. A missing ``kind`` means ``"window"``.

    Returns:
        The target, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping.
        ValueError: for an unknown key, or a target the constructor refuses.

    Examples:
        - A stored page target reads back with its budget:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget.from_dict({"kind": "html", "budget": 500000}).effective_budget
            500000

            ```
        - A key this version does not know is refused rather than dropped:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget.from_dict({"kind": "html", "dpi": 2})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: RenderTarget.from_dict got unknown keys ['dpi']; known keys are ['budget', 'height', ...]

            ```
    """
    refuse_unknown(
        "RenderTarget", data, ("kind", "width", "height", "pixel_ratio", "budget")
    )
    return cls(
        kind=data.get("kind", "window"),
        width=data.get("width"),
        height=data.get("height"),
        pixel_ratio=data.get("pixel_ratio", 1.0),
        budget=data.get("budget"),
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

kind and pixel_ratio, plus the canvas and the budget when set. An unset budget is written as

dict[str, Any]

unset, not as the kind's default, so a stored target keeps following the default if the default changes.

Examples:

  • A retina image target:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("image", width=1200, height=800, pixel_ratio=2.0).to_dict()
    {'kind': 'image', 'width': 1200, 'height': 800, 'pixel_ratio': 2.0}
    
  • The pixel ratio is written even at its default, and an unset budget stays unset:
    >>> from digitalearth.base.spec import RenderTarget
    >>> RenderTarget("html").to_dict()
    {'kind': 'html', 'pixel_ratio': 1.0}
    
Source code in src/digitalearth/base/spec/target.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``kind`` and ``pixel_ratio``, plus the canvas and the budget when set. An unset budget is written as
        unset, not as the kind's default, so a stored target keeps following the default if the default changes.

    Examples:
        - A retina image target:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget("image", width=1200, height=800, pixel_ratio=2.0).to_dict()
            {'kind': 'image', 'width': 1200, 'height': 800, 'pixel_ratio': 2.0}

            ```
        - The pixel ratio is written even at its default, and an unset budget stays unset:
            ```python
            >>> from digitalearth.base.spec import RenderTarget
            >>> RenderTarget("html").to_dict()
            {'kind': 'html', 'pixel_ratio': 1.0}

            ```
    """
    out: dict[str, Any] = {"kind": plain_text(self.kind)}
    for name in ("width", "height"):
        value = getattr(self, name)
        if value is not None:
            out[name] = value
    out["pixel_ratio"] = self.pixel_ratio
    if self.budget is not None:
        out["budget"] = self.budget
    return out

view_request(view=None, *, bounds=None) #

Return the request a reader answers for this view on this target.

The region comes from the view and the canvas and budget from the target — the only way this package makes a :class:~digitalearth.base.spec.viewrequest.ViewRequest from a view, so a layer never chooses its own budget.

Parameters:

Name Type Description Default
view Viewport | Camera | None

The view being rendered. A Viewport supplies its framed region; a Camera supplies none, since a 3-D view has no rectangle to read.

None
bounds Bounds | None

A region to read instead of the view's. When a Viewport is given, the region is reprojected into the view's CRS, which is the CRS the reader is asked in; with a Camera or no view it is used as given.

None

Returns:

Type Description
ViewRequest

The request: region, canvas, pixel ratio and :attr:effective_budget. A view framed by a

ViewRequest

(west, south, east, north) domain asks for that box, reprojected into the view's CRS. With a canvas

ViewRequest

named, the request's :meth:~digitalearth.base.spec.viewrequest.ViewRequest.side sizes a read to the

ViewRequest

canvas, within the budget. The region is None when neither the view nor bounds supplies one — an

ViewRequest

unframed Viewport included — and a request with no region carries no CRS either: the reader returns the

ViewRequest

source in its own CRS, and the renderer reprojects it into the view's.

Raises:

Type Description
ValueError

if view is neither a Viewport, a Camera nor None, if bounds is not a Bounds, if bounds or a domain box cannot be reprojected into the viewport's CRS, or if the view is framed by a named domain, which base cannot resolve.

Examples:

  • The view's region, the target's canvas and budget:
    >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
    >>> view = Viewport(4326, bounds=Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
    >>> request = RenderTarget("html", width=800, height=400).view_request(view)
    >>> request.as_bbox(), request.width, request.budget
    ((0.0, 0.0, 10.0, 5.0), 800, 1000000)
    
  • A region given in another CRS is asked for in the view's:
    >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
    >>> request = RenderTarget().view_request(Viewport(3857), bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
    >>> request.crs, [round(edge) for edge in request.as_bbox()]
    (3857, [0, 0, 111319, 111325])
    
  • A view framed by a domain box asks for that box, in the view's CRS:
    >>> from digitalearth.base.spec import RenderTarget, Viewport
    >>> request = RenderTarget().view_request(Viewport(3857, domain=(0.0, 0.0, 1.0, 1.0)))
    >>> request.crs, [round(edge) for edge in request.as_bbox()]
    (3857, [0, 0, 111319, 111325])
    
  • A 3-D camera has no rectangle, so only the canvas and the budget are set:
    >>> from digitalearth.base.spec import Camera, RenderTarget
    >>> request = RenderTarget("image", width=640, height=480).view_request(Camera((0.0, -10.0, 5.0)))
    >>> request.bounds, request.width, request.budget
    (None, 640, 4000000)
    
Source code in src/digitalearth/base/spec/target.py
def view_request(
    self,
    view: Viewport | Camera | None = None,
    *,
    bounds: Bounds | None = None,
) -> ViewRequest:
    """Return the request a reader answers for this view on this target.

    The region comes from the view and the canvas and budget from the target — the only way this package makes a
    :class:`~digitalearth.base.spec.viewrequest.ViewRequest` from a view, so a layer never chooses its own budget.

    Args:
        view: The view being rendered. A `Viewport` supplies its framed region; a `Camera` supplies none, since a
            3-D view has no rectangle to read.
        bounds: A region to read instead of the view's. When a `Viewport` is given, the region is reprojected into
            the view's CRS, which is the CRS the reader is asked in; with a `Camera` or no view it is used as
            given.

    Returns:
        The request: region, canvas, pixel ratio and :attr:`effective_budget`. A view framed by a
        `(west, south, east, north)` domain asks for that box, reprojected into the view's CRS. With a canvas
        named, the request's :meth:`~digitalearth.base.spec.viewrequest.ViewRequest.side` sizes a read to the
        canvas, within the budget. The region is `None` when neither the view nor `bounds` supplies one — an
        unframed `Viewport` included — and a request with no region carries no CRS either: the reader returns the
        source in its own CRS, and the renderer reprojects it into the view's.

    Raises:
        ValueError: if `view` is neither a `Viewport`, a `Camera` nor `None`, if `bounds` is not a `Bounds`, if
            `bounds` or a domain box cannot be reprojected into the viewport's CRS, or if the view is framed by a
            named domain, which `base` cannot resolve.

    Examples:
        - The view's region, the target's canvas and budget:
            ```python
            >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
            >>> view = Viewport(4326, bounds=Bounds(0.0, 0.0, 10.0, 5.0, crs=4326))
            >>> request = RenderTarget("html", width=800, height=400).view_request(view)
            >>> request.as_bbox(), request.width, request.budget
            ((0.0, 0.0, 10.0, 5.0), 800, 1000000)

            ```
        - A region given in another CRS is asked for in the view's:
            ```python
            >>> from digitalearth.base.spec import Bounds, RenderTarget, Viewport
            >>> request = RenderTarget().view_request(Viewport(3857), bounds=Bounds(0.0, 0.0, 1.0, 1.0, crs=4326))
            >>> request.crs, [round(edge) for edge in request.as_bbox()]
            (3857, [0, 0, 111319, 111325])

            ```
        - A view framed by a domain box asks for that box, in the view's CRS:
            ```python
            >>> from digitalearth.base.spec import RenderTarget, Viewport
            >>> request = RenderTarget().view_request(Viewport(3857, domain=(0.0, 0.0, 1.0, 1.0)))
            >>> request.crs, [round(edge) for edge in request.as_bbox()]
            (3857, [0, 0, 111319, 111325])

            ```
        - A 3-D camera has no rectangle, so only the canvas and the budget are set:
            ```python
            >>> from digitalearth.base.spec import Camera, RenderTarget
            >>> request = RenderTarget("image", width=640, height=480).view_request(Camera((0.0, -10.0, 5.0)))
            >>> request.bounds, request.width, request.budget
            (None, 640, 4000000)

            ```
    """
    if view is not None and not isinstance(view, (Viewport, Camera)):
        raise ValueError(
            f"RenderTarget.view_request needs a Viewport, a Camera or None; got {type(view).__name__}"
        )
    if bounds is not None and not isinstance(bounds, Bounds):
        raise ValueError(
            f"RenderTarget.view_request needs bounds as a Bounds; got {type(bounds).__name__}"
        )
    region: Bounds | None = None
    if isinstance(view, Viewport) and bounds is not None:
        region = view.framed(bounds).bounds
    elif isinstance(view, Viewport):
        region = view.bounds if view.domain is None else self._domain_region(view)
    elif bounds is not None:
        region = bounds
    return ViewRequest(
        bounds=region,
        width=self.width,
        height=self.height,
        pixel_ratio=self.pixel_ratio,
        budget=self.effective_budget,
    )

PanelSpec and FigureSpec — a figure that describes itself#

The whole figure — sources, one layer tree, panels with their own views — round-trips through to_dict and from_dict with no renderer imported, and records the schema version it was written in.

digitalearth.base.spec.figure.FigureSpec dataclass #

A whole figure, described with no renderer present.

Attributes:

Name Type Description
panels tuple[PanelSpec, ...]

The panels, in reading order. At least one.

sources Mapping[str, DataRef]

Source id -> :class:~digitalearth.base.spec.dataref.DataRef. Layers name their data by these ids, so several layers can draw one source without repeating its address.

layers LayerTree

Every layer in the figure, in draw order. A panel shows the ones it names.

size tuple[float, float] | None

(width, height) of the whole figure, in the renderer's units, or None.

title str | None

The figure's title, or None.

schema_version int

The description's version. Only :data:SCHEMA_VERSION, as an int, is accepted.

Raises:

Type Description
ValueError

for a schema version that is not :data:SCHEMA_VERSION as an int (1.0 is refused), no panels, a panel that is not a PanelSpec, two panels sharing an id, a source id that is not a non-empty string or maps to something other than a DataRef, a layer tree that is not a LayerTree, a layer whose source or elevation source is not among the sources, a panel naming a layer that is not in the tree, a 3-D (Camera) panel showing a draped layer without the layer it drapes over, a size that is not two positive finite numbers (a boolean counts as neither), or a title that is not a string or None (a blank title is kept as None).

Examples:

  • One source, one layer, one panel:
    >>> from digitalearth.base.spec import DataRef, FigureSpec, LayerSpec, LayerTree, PanelSpec, Viewport
    >>> fig = FigureSpec(
    ...     panels=(PanelSpec("main", Viewport(4326), layers=("dem",)),),
    ...     sources={"srtm": DataRef("data/dem.tif")},
    ...     layers=LayerTree((LayerSpec("dem", "raster", source_id="srtm"),)),
    ... )
    >>> [layer.id for layer in fig.layers_of("main")], fig.schema_version
    (['dem'], 1)
    
  • A panel may only show layers the figure holds:
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> FigureSpec(panels=(PanelSpec("main", layers=("dem",)),))
    Traceback (most recent call last):
        ...
    ValueError: panel 'main' shows layers ['dem'] that are not in the figure; layers are []
    
  • The version is the integer, not a float equal to it:
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> FigureSpec(panels=(PanelSpec("main"),), schema_version=1.0)
    Traceback (most recent call last):
        ...
    ValueError: FigureSpec schema_version 1.0 is not one this version of digitalearth reads; it reads 1
    
Source code in src/digitalearth/base/spec/figure.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
@dataclass(frozen=True, eq=True)
class FigureSpec:
    """A whole figure, described with no renderer present.

    Attributes:
        panels: The panels, in reading order. At least one.
        sources: Source id -> :class:`~digitalearth.base.spec.dataref.DataRef`. Layers name their data by these ids,
            so several layers can draw one source without repeating its address.
        layers: Every layer in the figure, in draw order. A panel shows the ones it names.
        size: ``(width, height)`` of the whole figure, in the renderer's units, or ``None``.
        title: The figure's title, or ``None``.
        schema_version: The description's version. Only :data:`SCHEMA_VERSION`, as an `int`, is accepted.

    Raises:
        ValueError: for a schema version that is not :data:`SCHEMA_VERSION` as an `int` (`1.0` is refused), no
            panels, a panel that is not a `PanelSpec`, two panels sharing an id, a source id that is not a non-empty
            string or maps to something other than a `DataRef`, a layer tree that is
            not a `LayerTree`, a layer whose source or elevation source is not among the sources, a panel naming a
            layer that is not in the tree, a 3-D (`Camera`) panel showing a draped layer without the layer it
            drapes over, a size that is not two positive finite numbers (a boolean counts as
            neither), or a title that is not a string or ``None`` (a blank title is kept as ``None``).

    Examples:
        - One source, one layer, one panel:
            ```python
            >>> from digitalearth.base.spec import DataRef, FigureSpec, LayerSpec, LayerTree, PanelSpec, Viewport
            >>> fig = FigureSpec(
            ...     panels=(PanelSpec("main", Viewport(4326), layers=("dem",)),),
            ...     sources={"srtm": DataRef("data/dem.tif")},
            ...     layers=LayerTree((LayerSpec("dem", "raster", source_id="srtm"),)),
            ... )
            >>> [layer.id for layer in fig.layers_of("main")], fig.schema_version
            (['dem'], 1)

            ```
        - A panel may only show layers the figure holds:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> FigureSpec(panels=(PanelSpec("main", layers=("dem",)),))
            Traceback (most recent call last):
                ...
            ValueError: panel 'main' shows layers ['dem'] that are not in the figure; layers are []

            ```
        - The version is the integer, not a float equal to it:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> FigureSpec(panels=(PanelSpec("main"),), schema_version=1.0)
            Traceback (most recent call last):
                ...
            ValueError: FigureSpec schema_version 1.0 is not one this version of digitalearth reads; it reads 1

            ```
    """

    panels: tuple[PanelSpec, ...]
    sources: Mapping[str, DataRef] = field(default_factory=dict)
    layers: LayerTree = field(default_factory=LayerTree)
    size: tuple[float, float] | None = None
    title: str | None = None
    schema_version: int = SCHEMA_VERSION

    def __post_init__(self) -> None:
        """Refuse a figure whose parts do not refer to each other correctly.

        Raises:
            ValueError: as described on the class.
        """
        if not _is_known_version(self.schema_version):
            raise ValueError(
                f"FigureSpec schema_version {self.schema_version!r} is not one this version of digitalearth reads; "
                f"it reads {SCHEMA_VERSION}"
            )
        object.__setattr__(self, "panels", self._checked_panels(self.panels))
        object.__setattr__(
            self, "sources", FrozenDict(self._checked_sources(self.sources))
        )
        if not isinstance(self.layers, LayerTree):
            raise ValueError(
                f"FigureSpec layers must be a LayerTree; got {type(self.layers).__name__}"
            )
        for layer in self.layers:
            self._check_sources(layer, self.sources)
        self._check_panel_layers()
        object.__setattr__(self, "size", self._checked_size(self.size))
        object.__setattr__(self, "title", _optional_title("FigureSpec", self.title))

    def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
        """Pickle and copy by rebuilding through the constructor.

        Returns:
            ``(type(self), (panels, dict(sources), layers, size, title, schema_version))`` — the caller's
            subclass, not `FigureSpec` by name. Rebuilding from a plain dict goes through the same validation and
            freezing as any other construction.

        Examples:
            - A copy is equal to the original, and is a separate object:
                ```python
                >>> import copy
                >>> from digitalearth.base.spec import FigureSpec, PanelSpec
                >>> original = FigureSpec(panels=(PanelSpec("p"),))
                >>> clone = copy.deepcopy(original)
                >>> clone == original, clone is original
                (True, False)

                ```
        """
        return type(self), (
            self.panels,
            dict(self.sources),
            self.layers,
            self.size,
            self.title,
            self.schema_version,
        )

    def __hash__(self) -> int:
        """Hash by value, like every other type in the vocabulary.

        Returns:
            A hash over every field. `sources` is held as a read-only `FrozenDict`, which has no hash of its own, so
            it is hashed as its sorted items — hashed as held, it raises `unhashable type: 'FrozenDict'`, while
            `LayerTree`, `PanelSpec` and `Viewport` all hash.

        Raises:
            TypeError: if a part holds a value that is unhashable for its own reasons. A mapping is not among
                them wherever a layer's style puts one — a property or a channel's constant, however deeply
                nested — since `Symbology` and `Encoding` each hash one as its items; nor is a list or a
                numpy array, which the vocabulary stores as tuples.

        Examples:
            - Two figures built alike hash alike, so a figure can key a cache:
                ```python
                >>> from digitalearth.base.spec import DataRef, FigureSpec, PanelSpec
                >>> one = FigureSpec(panels=(PanelSpec("p"),), sources={"a": DataRef("a.tif")})
                >>> two = FigureSpec.from_dict(one.to_dict())
                >>> hash(one) == hash(two), len({one, two})
                (True, 1)

                ```
        """
        return hash(
            (
                self.panels,
                tuple(sorted(self.sources.items())),
                self.layers,
                self.size,
                self.title,
                self.schema_version,
            )
        )

    @staticmethod
    def _checked_panels(panels: Any) -> tuple[PanelSpec, ...]:
        """Return the panels as a tuple, refusing none, a non-panel, or two panels sharing an id.

        Args:
            panels: What the constructor was given.

        Returns:
            The panels, in order.

        Raises:
            ValueError: for an empty sequence, something that is not a `PanelSpec`, or a repeated id.
        """
        checked = tuple(panels)
        if not checked:
            raise ValueError("FigureSpec needs at least one panel")
        for panel in checked:
            if not isinstance(panel, PanelSpec):
                raise ValueError(
                    f"FigureSpec panels must be PanelSpec values; got {type(panel).__name__}"
                )
        ids = [panel.id for panel in checked]
        shared = sorted({panel_id for panel_id in ids if ids.count(panel_id) > 1})
        if shared:
            raise ValueError(
                f"FigureSpec panel ids must be unique; {shared} appear more than once"
            )
        return checked

    @staticmethod
    def _checked_sources(sources: Mapping[str, Any]) -> dict[str, DataRef]:
        """Return the sources as a dict, refusing an id that addresses nothing or a value that is not a `DataRef`.

        Args:
            sources: What the constructor was given.

        Returns:
            A fresh dict of the sources.

        Raises:
            ValueError: for a source id that is not a string or is empty, or a value
                that is not a `DataRef`.
        """
        checked = dict(sources)
        for source_id, ref in checked.items():
            _identifier("FigureSpec source", source_id)
            if not isinstance(ref, DataRef):
                raise ValueError(
                    f"source {source_id!r} must be a DataRef; got {type(ref).__name__}"
                )
        return checked

    def _check_panel_layers(self) -> None:
        """Refuse a panel that names a layer the figure does not have, or a 3-D panel missing a drape's surface.

        Raises:
            ValueError: naming the panel, the missing layers and the layers that exist; or, for a `Camera` panel,
                naming the draped layer and the surface it does not show. The tree already refuses a drape over a
                layer it lacks; a 3-D panel is held to the same rule over what it shows, because a renderer has
                nothing to drape the layer onto otherwise. A flat (`Viewport`) panel draws a draped layer flat,
                so it may show one without its surface.
        """
        for panel in self.panels:
            missing = [
                layer_id for layer_id in panel.layers if layer_id not in self.layers
            ]
            if missing:
                raise ValueError(
                    f"panel {panel.id!r} shows layers {missing} that are not in the figure; layers are "
                    f"{list(self.layers.ids)}"
                )
            if not isinstance(panel.view, Camera):
                continue
            for layer_id in panel.layers:
                surface = self.layers.get(layer_id).z_layer
                if surface is not None and surface not in panel.layers:
                    raise ValueError(
                        f"panel {panel.id!r} shows {layer_id!r}, draped over {surface!r}, without {surface!r}; a 3-D "
                        "panel needs the surface a layer takes its elevation from"
                    )

    @staticmethod
    def _checked_size(size: Any) -> tuple[float, float] | None:
        """Return the figure size as two floats, or ``None``.

        Args:
            size: What the constructor was given.

        Returns:
            ``(width, height)`` as floats, or ``None`` when unset.

        Raises:
            ValueError: for anything but two positive finite numbers — a string, a non-iterable, the wrong count,
                or a boolean, which counts as no number.
        """
        if size is None:
            return None
        if isinstance(size, (str, bytes)) or not hasattr(size, "__iter__"):
            raise ValueError(f"FigureSpec size must be (width, height); got {size!r}")
        # Numpy numbers count, as they do for every other number in the vocabulary: a size is often computed.
        dimensions = [positive_number(value) for value in size]
        if len(dimensions) == 2:
            width, height = dimensions
            if width is not None and height is not None:
                return width, height
        raise ValueError(
            f"FigureSpec size must be two positive finite numbers; got {size!r}"
        )

    @staticmethod
    def _check_sources(layer: LayerSpec, sources: Mapping[str, DataRef]) -> None:
        """Refuse a layer whose data or elevation names a source the figure does not have.

        Args:
            layer: The layer to check.
            sources: The figure's sources.

        Raises:
            ValueError: naming the layer, the missing source and the sources that exist.
        """
        wanted = [layer.source_id]
        if layer.z_source is not None and layer.z_layer is None:
            wanted.append(layer.z_source)
        for source_id in wanted:
            if source_id is not None and source_id not in sources:
                raise ValueError(
                    f"layer {layer.id!r} reads source {source_id!r}, which is not in the figure; sources are "
                    f"{sorted(sources)}"
                )

    def panel(self, panel_id: str) -> PanelSpec:
        """Return the panel with this id.

        Args:
            panel_id: The id to look up.

        Returns:
            The panel.

        Raises:
            KeyError: if no panel has that id, listing the ids that exist.

        Examples:
            - Look a panel up by id:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, PanelSpec
                >>> FigureSpec(panels=(PanelSpec("a", title="Left"),)).panel("a").title
                'Left'

                ```
            - An id no panel has is named beside the ids that exist:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, PanelSpec
                >>> FigureSpec(panels=(PanelSpec("a"),)).panel("b")
                Traceback (most recent call last):
                    ...
                KeyError: "no panel 'b' in this figure; panels are ['a']"

                ```
        """
        for panel in self.panels:
            if panel.id == panel_id:
                return panel
        raise KeyError(
            f"no panel {panel_id!r} in this figure; panels are {[panel.id for panel in self.panels]}"
        )

    def layers_of(self, panel_id: str) -> tuple[LayerSpec, ...]:
        """Return the layers a panel shows, in draw order.

        Args:
            panel_id: The panel.

        Returns:
            The panel's layers, ordered as the figure's tree orders them — so reordering the tree reorders every
            panel that shows those layers.

        Raises:
            KeyError: if no panel has that id.

        Examples:
            - A panel's layers follow the tree's order, not the order the panel listed them in:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
                >>> tree = LayerTree((LayerSpec("base", "tiles"), LayerSpec("roads", "lines")))
                >>> fig = FigureSpec(panels=(PanelSpec("p", layers=("roads", "base")),), layers=tree)
                >>> [layer.id for layer in fig.layers_of("p")]
                ['base', 'roads']

                ```
        """
        shown = set(self.panel(panel_id).layers)
        return tuple(layer for layer in self.layers if layer.id in shown)

    def diff(self, other: "FigureSpec") -> FigureDiff:
        """Return what turns this figure into `other`, sorted into the updates a renderer makes.

        Layers are matched by id. A layer on both sides is **rebuilt** when what it draws changed — its kind,
        source, elevation source or selection, or the `DataRef` behind its source id — and **restyled** when only
        its symbology, filter, label or group did. A new selection is a rebuild rather than a restyle: another band
        or time step is other pixels to read. Visibility is **effective** visibility
        (:meth:`LayerTree.is_visible <digitalearth.base.spec.layer.LayerTree.is_visible>`), so hiding a group
        reports every layer it hides, and a change of a layer's own `visible` is reported only there.

        Args:
            other: The figure to compare with.

        Returns:
            The changes, as a :class:`FigureDiff`.

        Raises:
            TypeError: if `other` is not a `FigureSpec`.

        Examples:
            - Hiding a group reports the layers it hides:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
                >>> layers = (LayerSpec("s", "points", group="obs"), LayerSpec("t", "text"))
                >>> before = FigureSpec(panels=(PanelSpec("p", layers=("s", "t")),), layers=LayerTree(layers))
                >>> after = FigureSpec(
                ...     panels=(PanelSpec("p", layers=("s", "t")),),
                ...     layers=LayerTree(layers, hidden_groups=frozenset({"obs"})),
                ... )
                >>> before.diff(after).hidden
                ('s',)

                ```
            - Swapping two layers reports the whole new order:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
                >>> a, b = LayerSpec("a", "text"), LayerSpec("b", "graticule")
                >>> panels = (PanelSpec("p", layers=("a", "b")),)
                >>> before = FigureSpec(panels=panels, layers=LayerTree((a, b)))
                >>> after = FigureSpec(panels=panels, layers=LayerTree((b, a)))
                >>> before.diff(after).order
                ('b', 'a')

                ```
        """
        if not isinstance(other, FigureSpec):
            raise TypeError(
                f"FigureSpec.diff needs a FigureSpec; got {type(other).__name__}"
            )
        old_ids, new_ids = self.layers.ids, other.layers.ids
        old_set, new_set = set(old_ids), set(new_ids)
        kept = tuple(layer_id for layer_id in new_ids if layer_id in old_set)
        changed_sources = tuple(
            sorted(
                source_id
                for source_id in set(self.sources) | set(other.sources)
                if self.sources.get(source_id) != other.sources.get(source_id)
            )
        )
        rebuilt, restyled, shown, hidden = _kept_layer_changes(
            self.layers, other.layers, kept, set(changed_sources)
        )
        kept_set = set(kept)
        survivors_before = tuple(
            layer_id for layer_id in old_ids if layer_id in kept_set
        )
        return FigureDiff(
            added=tuple(layer_id for layer_id in new_ids if layer_id not in old_set),
            removed=tuple(layer_id for layer_id in old_ids if layer_id not in new_set),
            rebuilt=rebuilt,
            restyled=restyled,
            shown=shown,
            hidden=hidden,
            order=None if survivors_before == kept else new_ids,
            sources=changed_sources,
            panels=self._changed_panels(other),
            figure=(self.size, self.title) != (other.size, other.title),
        )

    def _changed_panels(self, other: "FigureSpec") -> tuple[str, ...]:
        """Return the ids of panels that differ between this figure and `other`.

        Args:
            other: The figure being compared with.

        Returns:
            Panels of `other` that are new or differ, in `other`'s order, then panels only this figure has.
        """
        old = {panel.id: panel for panel in self.panels}
        new_ids = {panel.id for panel in other.panels}
        changed = [panel.id for panel in other.panels if old.get(panel.id) != panel]
        gone = [panel.id for panel in self.panels if panel.id not in new_ids]
        return tuple(changed + gone)

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form of the whole figure.

        Returns:
            `schema_version` and `panels`, plus `sources`, `layers`, `size` and `title` when set. The free-form
            values — encoding constants, style properties, scale categories and schemes, selection axes — go
            through the JSON check as they are written, so a figure built from plain, finite Python numbers,
            strings, lists and dicts gives a dict `json.dumps` writes as is.

        Raises:
            TypeError: if a free-form value has no JSON form. A view's CRS is checked when the view is built, so
                it is not a reason this can fail.
            ValueError: if a source is an ``object:`` reference from :meth:`DataRef.to_object
                <digitalearth.base.spec.dataref.DataRef.to_object>`. It names an object in this process's memory,
                so a stored figure holding one would read back and then fail to open anywhere else. Building the
                figure in memory with one is fine; storing it is not.

        Examples:
            - The version is always written:
                ```python
                >>> from digitalearth.base.spec import FigureSpec, PanelSpec
                >>> FigureSpec(panels=(PanelSpec("main"),)).to_dict()
                {'schema_version': 1, 'panels': [{'id': 'main', 'viewport': {'crs': 3857}}]}

                ```
            - A figure survives a JSON round trip, with no renderer involved:
                ```python
                >>> import json
                >>> from digitalearth.base.spec import DataRef, FigureSpec, LayerSpec, LayerTree, PanelSpec, Viewport
                >>> fig = FigureSpec(
                ...     panels=(PanelSpec("main", Viewport(4326), layers=("dem",)),),
                ...     sources={"srtm": DataRef("data/dem.tif")},
                ...     layers=LayerTree((LayerSpec("dem", "raster", source_id="srtm"),)),
                ...     size=(8, 4),
                ... )
                >>> text = json.dumps(fig.to_dict(), allow_nan=False)
                >>> back = FigureSpec.from_dict(json.loads(text))
                >>> back == fig, back.size
                (True, (8.0, 4.0))

                ```
        """
        out: dict[str, Any] = {
            "schema_version": self.schema_version,
            "panels": [panel.to_dict() for panel in self.panels],
        }
        if self.sources:
            for source_id, ref in self.sources.items():
                if ref.uri.startswith(f"{OBJECT_SCHEME}:"):
                    raise ValueError(
                        f"source {source_id!r} is {ref.uri!r}, which only resolves in the process that registered "
                        "it, so FigureSpec.to_dict cannot store it. Save the data and reference it by path or URL"
                    )
            out["sources"] = {
                plain_text(source_id): ref.to_dict()
                for source_id, ref in self.sources.items()
            }
        if len(self.layers):
            out["layers"] = self.layers.to_dict()
        if self.size is not None:
            out["size"] = list(self.size)
        if self.title is not None:
            out["title"] = plain_text(self.title)
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "FigureSpec":
        """Rebuild a figure from its dict form.

        The version is read first: a figure written by a newer schema is refused by name before any of its fields is
        interpreted, since a field whose meaning changed would otherwise be read the old way without a word.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The figure, validated as the constructor validates it.

        Raises:
            TypeError: if `data` is not a mapping, or a part is the wrong shape — a panel, the layer tree or
                `sources` that is not a mapping, or `panels` or `size` that is not a list — naming the field.
            ValueError: for a missing or unknown schema version, a missing panel list, an unknown key, a part its own
                `from_dict` refuses, or a figure the constructor refuses. An error of either type from a stored
                panel, source or layer tree names where the part sits — `panels[0]`, `sources['a']`, `layers` — and
                each nested read adds its own step, so the message is the path from the figure down to the broken
                entry.

        Examples:
            - A figure from a newer schema is refused before it is read:
                ```python
                >>> from digitalearth.base.spec import FigureSpec
                >>> FigureSpec.from_dict({"schema_version": 2, "panels": []})
                Traceback (most recent call last):
                    ...
                ValueError: FigureSpec.from_dict got schema_version 2; this version of digitalearth reads 1

                ```
            - A broken entry deep in the figure is named by its path:
                ```python
                >>> from digitalearth.base.spec import FigureSpec
                >>> stored = {"schema_version": 1, "panels": [{"id": "p", "viewport": {"crs": True}}]}
                >>> FigureSpec.from_dict(stored)  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: FigureSpec.from_dict panels[0]: PanelSpec.from_dict viewport: Viewport needs a display ...

                ```
        """
        if not isinstance(data, Mapping):
            raise TypeError(
                f"FigureSpec.from_dict needs a mapping; got {type(data).__name__}"
            )
        version = require("FigureSpec", data, "schema_version")
        if not _is_known_version(version):
            raise ValueError(
                f"FigureSpec.from_dict got schema_version {version!r}; this version of digitalearth reads "
                f"{SCHEMA_VERSION}"
            )
        refuse_unknown(
            "FigureSpec",
            data,
            ("schema_version", "panels", "sources", "layers", "size", "title"),
        )
        size = data.get("size")
        layers = data.get("layers")
        return cls(
            panels=tuple(
                read_entry("FigureSpec", f"panels[{index}]", PanelSpec.from_dict, panel)
                for index, panel in enumerate(
                    as_list(
                        "FigureSpec", "panels", require("FigureSpec", data, "panels")
                    )
                )
            ),
            sources={
                source_id: read_entry(
                    "FigureSpec", f"sources[{source_id!r}]", DataRef.from_dict, ref
                )
                for source_id, ref in as_mapping(
                    "FigureSpec", "sources", data.get("sources", {})
                ).items()
            },
            layers=LayerTree()
            if layers is None
            else read_entry("FigureSpec", "layers", LayerTree.from_dict, layers),
            size=None if size is None else as_list("FigureSpec", "size", size),
            title=data.get("title"),
            schema_version=version,
        )

__hash__() #

Hash by value, like every other type in the vocabulary.

Returns:

Type Description
int

A hash over every field. sources is held as a read-only FrozenDict, which has no hash of its own, so

int

it is hashed as its sorted items — hashed as held, it raises unhashable type: 'FrozenDict', while

int

LayerTree, PanelSpec and Viewport all hash.

Raises:

Type Description
TypeError

if a part holds a value that is unhashable for its own reasons. A mapping is not among them wherever a layer's style puts one — a property or a channel's constant, however deeply nested — since Symbology and Encoding each hash one as its items; nor is a list or a numpy array, which the vocabulary stores as tuples.

Examples:

  • Two figures built alike hash alike, so a figure can key a cache:
    >>> from digitalearth.base.spec import DataRef, FigureSpec, PanelSpec
    >>> one = FigureSpec(panels=(PanelSpec("p"),), sources={"a": DataRef("a.tif")})
    >>> two = FigureSpec.from_dict(one.to_dict())
    >>> hash(one) == hash(two), len({one, two})
    (True, 1)
    
Source code in src/digitalearth/base/spec/figure.py
def __hash__(self) -> int:
    """Hash by value, like every other type in the vocabulary.

    Returns:
        A hash over every field. `sources` is held as a read-only `FrozenDict`, which has no hash of its own, so
        it is hashed as its sorted items — hashed as held, it raises `unhashable type: 'FrozenDict'`, while
        `LayerTree`, `PanelSpec` and `Viewport` all hash.

    Raises:
        TypeError: if a part holds a value that is unhashable for its own reasons. A mapping is not among
            them wherever a layer's style puts one — a property or a channel's constant, however deeply
            nested — since `Symbology` and `Encoding` each hash one as its items; nor is a list or a
            numpy array, which the vocabulary stores as tuples.

    Examples:
        - Two figures built alike hash alike, so a figure can key a cache:
            ```python
            >>> from digitalearth.base.spec import DataRef, FigureSpec, PanelSpec
            >>> one = FigureSpec(panels=(PanelSpec("p"),), sources={"a": DataRef("a.tif")})
            >>> two = FigureSpec.from_dict(one.to_dict())
            >>> hash(one) == hash(two), len({one, two})
            (True, 1)

            ```
    """
    return hash(
        (
            self.panels,
            tuple(sorted(self.sources.items())),
            self.layers,
            self.size,
            self.title,
            self.schema_version,
        )
    )

__post_init__() #

Refuse a figure whose parts do not refer to each other correctly.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/figure.py
def __post_init__(self) -> None:
    """Refuse a figure whose parts do not refer to each other correctly.

    Raises:
        ValueError: as described on the class.
    """
    if not _is_known_version(self.schema_version):
        raise ValueError(
            f"FigureSpec schema_version {self.schema_version!r} is not one this version of digitalearth reads; "
            f"it reads {SCHEMA_VERSION}"
        )
    object.__setattr__(self, "panels", self._checked_panels(self.panels))
    object.__setattr__(
        self, "sources", FrozenDict(self._checked_sources(self.sources))
    )
    if not isinstance(self.layers, LayerTree):
        raise ValueError(
            f"FigureSpec layers must be a LayerTree; got {type(self.layers).__name__}"
        )
    for layer in self.layers:
        self._check_sources(layer, self.sources)
    self._check_panel_layers()
    object.__setattr__(self, "size", self._checked_size(self.size))
    object.__setattr__(self, "title", _optional_title("FigureSpec", self.title))

__reduce__() #

Pickle and copy by rebuilding through the constructor.

Returns:

Type Description
Any

(type(self), (panels, dict(sources), layers, size, title, schema_version)) — the caller's

tuple[Any, ...]

subclass, not FigureSpec by name. Rebuilding from a plain dict goes through the same validation and

tuple[Any, tuple[Any, ...]]

freezing as any other construction.

Examples:

  • A copy is equal to the original, and is a separate object:
    >>> import copy
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> original = FigureSpec(panels=(PanelSpec("p"),))
    >>> clone = copy.deepcopy(original)
    >>> clone == original, clone is original
    (True, False)
    
Source code in src/digitalearth/base/spec/figure.py
def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
    """Pickle and copy by rebuilding through the constructor.

    Returns:
        ``(type(self), (panels, dict(sources), layers, size, title, schema_version))`` — the caller's
        subclass, not `FigureSpec` by name. Rebuilding from a plain dict goes through the same validation and
        freezing as any other construction.

    Examples:
        - A copy is equal to the original, and is a separate object:
            ```python
            >>> import copy
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> original = FigureSpec(panels=(PanelSpec("p"),))
            >>> clone = copy.deepcopy(original)
            >>> clone == original, clone is original
            (True, False)

            ```
    """
    return type(self), (
        self.panels,
        dict(self.sources),
        self.layers,
        self.size,
        self.title,
        self.schema_version,
    )

diff(other) #

Return what turns this figure into other, sorted into the updates a renderer makes.

Layers are matched by id. A layer on both sides is rebuilt when what it draws changed — its kind, source, elevation source or selection, or the DataRef behind its source id — and restyled when only its symbology, filter, label or group did. A new selection is a rebuild rather than a restyle: another band or time step is other pixels to read. Visibility is effective visibility (:meth:LayerTree.is_visible <digitalearth.base.spec.layer.LayerTree.is_visible>), so hiding a group reports every layer it hides, and a change of a layer's own visible is reported only there.

Parameters:

Name Type Description Default
other FigureSpec

The figure to compare with.

required

Returns:

Type Description
FigureDiff

The changes, as a :class:FigureDiff.

Raises:

Type Description
TypeError

if other is not a FigureSpec.

Examples:

  • Hiding a group reports the layers it hides:
    >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
    >>> layers = (LayerSpec("s", "points", group="obs"), LayerSpec("t", "text"))
    >>> before = FigureSpec(panels=(PanelSpec("p", layers=("s", "t")),), layers=LayerTree(layers))
    >>> after = FigureSpec(
    ...     panels=(PanelSpec("p", layers=("s", "t")),),
    ...     layers=LayerTree(layers, hidden_groups=frozenset({"obs"})),
    ... )
    >>> before.diff(after).hidden
    ('s',)
    
  • Swapping two layers reports the whole new order:
    >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
    >>> a, b = LayerSpec("a", "text"), LayerSpec("b", "graticule")
    >>> panels = (PanelSpec("p", layers=("a", "b")),)
    >>> before = FigureSpec(panels=panels, layers=LayerTree((a, b)))
    >>> after = FigureSpec(panels=panels, layers=LayerTree((b, a)))
    >>> before.diff(after).order
    ('b', 'a')
    
Source code in src/digitalearth/base/spec/figure.py
def diff(self, other: "FigureSpec") -> FigureDiff:
    """Return what turns this figure into `other`, sorted into the updates a renderer makes.

    Layers are matched by id. A layer on both sides is **rebuilt** when what it draws changed — its kind,
    source, elevation source or selection, or the `DataRef` behind its source id — and **restyled** when only
    its symbology, filter, label or group did. A new selection is a rebuild rather than a restyle: another band
    or time step is other pixels to read. Visibility is **effective** visibility
    (:meth:`LayerTree.is_visible <digitalearth.base.spec.layer.LayerTree.is_visible>`), so hiding a group
    reports every layer it hides, and a change of a layer's own `visible` is reported only there.

    Args:
        other: The figure to compare with.

    Returns:
        The changes, as a :class:`FigureDiff`.

    Raises:
        TypeError: if `other` is not a `FigureSpec`.

    Examples:
        - Hiding a group reports the layers it hides:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
            >>> layers = (LayerSpec("s", "points", group="obs"), LayerSpec("t", "text"))
            >>> before = FigureSpec(panels=(PanelSpec("p", layers=("s", "t")),), layers=LayerTree(layers))
            >>> after = FigureSpec(
            ...     panels=(PanelSpec("p", layers=("s", "t")),),
            ...     layers=LayerTree(layers, hidden_groups=frozenset({"obs"})),
            ... )
            >>> before.diff(after).hidden
            ('s',)

            ```
        - Swapping two layers reports the whole new order:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
            >>> a, b = LayerSpec("a", "text"), LayerSpec("b", "graticule")
            >>> panels = (PanelSpec("p", layers=("a", "b")),)
            >>> before = FigureSpec(panels=panels, layers=LayerTree((a, b)))
            >>> after = FigureSpec(panels=panels, layers=LayerTree((b, a)))
            >>> before.diff(after).order
            ('b', 'a')

            ```
    """
    if not isinstance(other, FigureSpec):
        raise TypeError(
            f"FigureSpec.diff needs a FigureSpec; got {type(other).__name__}"
        )
    old_ids, new_ids = self.layers.ids, other.layers.ids
    old_set, new_set = set(old_ids), set(new_ids)
    kept = tuple(layer_id for layer_id in new_ids if layer_id in old_set)
    changed_sources = tuple(
        sorted(
            source_id
            for source_id in set(self.sources) | set(other.sources)
            if self.sources.get(source_id) != other.sources.get(source_id)
        )
    )
    rebuilt, restyled, shown, hidden = _kept_layer_changes(
        self.layers, other.layers, kept, set(changed_sources)
    )
    kept_set = set(kept)
    survivors_before = tuple(
        layer_id for layer_id in old_ids if layer_id in kept_set
    )
    return FigureDiff(
        added=tuple(layer_id for layer_id in new_ids if layer_id not in old_set),
        removed=tuple(layer_id for layer_id in old_ids if layer_id not in new_set),
        rebuilt=rebuilt,
        restyled=restyled,
        shown=shown,
        hidden=hidden,
        order=None if survivors_before == kept else new_ids,
        sources=changed_sources,
        panels=self._changed_panels(other),
        figure=(self.size, self.title) != (other.size, other.title),
    )

from_dict(data) classmethod #

Rebuild a figure from its dict form.

The version is read first: a figure written by a newer schema is refused by name before any of its fields is interpreted, since a field whose meaning changed would otherwise be read the old way without a word.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
FigureSpec

The figure, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data is not a mapping, or a part is the wrong shape — a panel, the layer tree or sources that is not a mapping, or panels or size that is not a list — naming the field.

ValueError

for a missing or unknown schema version, a missing panel list, an unknown key, a part its own from_dict refuses, or a figure the constructor refuses. An error of either type from a stored panel, source or layer tree names where the part sits — panels[0], sources['a'], layers — and each nested read adds its own step, so the message is the path from the figure down to the broken entry.

Examples:

  • A figure from a newer schema is refused before it is read:
    >>> from digitalearth.base.spec import FigureSpec
    >>> FigureSpec.from_dict({"schema_version": 2, "panels": []})
    Traceback (most recent call last):
        ...
    ValueError: FigureSpec.from_dict got schema_version 2; this version of digitalearth reads 1
    
  • A broken entry deep in the figure is named by its path:
    >>> from digitalearth.base.spec import FigureSpec
    >>> stored = {"schema_version": 1, "panels": [{"id": "p", "viewport": {"crs": True}}]}
    >>> FigureSpec.from_dict(stored)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: FigureSpec.from_dict panels[0]: PanelSpec.from_dict viewport: Viewport needs a display ...
    
Source code in src/digitalearth/base/spec/figure.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "FigureSpec":
    """Rebuild a figure from its dict form.

    The version is read first: a figure written by a newer schema is refused by name before any of its fields is
    interpreted, since a field whose meaning changed would otherwise be read the old way without a word.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The figure, validated as the constructor validates it.

    Raises:
        TypeError: if `data` is not a mapping, or a part is the wrong shape — a panel, the layer tree or
            `sources` that is not a mapping, or `panels` or `size` that is not a list — naming the field.
        ValueError: for a missing or unknown schema version, a missing panel list, an unknown key, a part its own
            `from_dict` refuses, or a figure the constructor refuses. An error of either type from a stored
            panel, source or layer tree names where the part sits — `panels[0]`, `sources['a']`, `layers` — and
            each nested read adds its own step, so the message is the path from the figure down to the broken
            entry.

    Examples:
        - A figure from a newer schema is refused before it is read:
            ```python
            >>> from digitalearth.base.spec import FigureSpec
            >>> FigureSpec.from_dict({"schema_version": 2, "panels": []})
            Traceback (most recent call last):
                ...
            ValueError: FigureSpec.from_dict got schema_version 2; this version of digitalearth reads 1

            ```
        - A broken entry deep in the figure is named by its path:
            ```python
            >>> from digitalearth.base.spec import FigureSpec
            >>> stored = {"schema_version": 1, "panels": [{"id": "p", "viewport": {"crs": True}}]}
            >>> FigureSpec.from_dict(stored)  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: FigureSpec.from_dict panels[0]: PanelSpec.from_dict viewport: Viewport needs a display ...

            ```
    """
    if not isinstance(data, Mapping):
        raise TypeError(
            f"FigureSpec.from_dict needs a mapping; got {type(data).__name__}"
        )
    version = require("FigureSpec", data, "schema_version")
    if not _is_known_version(version):
        raise ValueError(
            f"FigureSpec.from_dict got schema_version {version!r}; this version of digitalearth reads "
            f"{SCHEMA_VERSION}"
        )
    refuse_unknown(
        "FigureSpec",
        data,
        ("schema_version", "panels", "sources", "layers", "size", "title"),
    )
    size = data.get("size")
    layers = data.get("layers")
    return cls(
        panels=tuple(
            read_entry("FigureSpec", f"panels[{index}]", PanelSpec.from_dict, panel)
            for index, panel in enumerate(
                as_list(
                    "FigureSpec", "panels", require("FigureSpec", data, "panels")
                )
            )
        ),
        sources={
            source_id: read_entry(
                "FigureSpec", f"sources[{source_id!r}]", DataRef.from_dict, ref
            )
            for source_id, ref in as_mapping(
                "FigureSpec", "sources", data.get("sources", {})
            ).items()
        },
        layers=LayerTree()
        if layers is None
        else read_entry("FigureSpec", "layers", LayerTree.from_dict, layers),
        size=None if size is None else as_list("FigureSpec", "size", size),
        title=data.get("title"),
        schema_version=version,
    )

layers_of(panel_id) #

Return the layers a panel shows, in draw order.

Parameters:

Name Type Description Default
panel_id str

The panel.

required

Returns:

Type Description
LayerSpec

The panel's layers, ordered as the figure's tree orders them — so reordering the tree reorders every

...

panel that shows those layers.

Raises:

Type Description
KeyError

if no panel has that id.

Examples:

  • A panel's layers follow the tree's order, not the order the panel listed them in:
    >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
    >>> tree = LayerTree((LayerSpec("base", "tiles"), LayerSpec("roads", "lines")))
    >>> fig = FigureSpec(panels=(PanelSpec("p", layers=("roads", "base")),), layers=tree)
    >>> [layer.id for layer in fig.layers_of("p")]
    ['base', 'roads']
    
Source code in src/digitalearth/base/spec/figure.py
def layers_of(self, panel_id: str) -> tuple[LayerSpec, ...]:
    """Return the layers a panel shows, in draw order.

    Args:
        panel_id: The panel.

    Returns:
        The panel's layers, ordered as the figure's tree orders them — so reordering the tree reorders every
        panel that shows those layers.

    Raises:
        KeyError: if no panel has that id.

    Examples:
        - A panel's layers follow the tree's order, not the order the panel listed them in:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, LayerSpec, LayerTree, PanelSpec
            >>> tree = LayerTree((LayerSpec("base", "tiles"), LayerSpec("roads", "lines")))
            >>> fig = FigureSpec(panels=(PanelSpec("p", layers=("roads", "base")),), layers=tree)
            >>> [layer.id for layer in fig.layers_of("p")]
            ['base', 'roads']

            ```
    """
    shown = set(self.panel(panel_id).layers)
    return tuple(layer for layer in self.layers if layer.id in shown)

panel(panel_id) #

Return the panel with this id.

Parameters:

Name Type Description Default
panel_id str

The id to look up.

required

Returns:

Type Description
PanelSpec

The panel.

Raises:

Type Description
KeyError

if no panel has that id, listing the ids that exist.

Examples:

  • Look a panel up by id:
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> FigureSpec(panels=(PanelSpec("a", title="Left"),)).panel("a").title
    'Left'
    
  • An id no panel has is named beside the ids that exist:
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> FigureSpec(panels=(PanelSpec("a"),)).panel("b")
    Traceback (most recent call last):
        ...
    KeyError: "no panel 'b' in this figure; panels are ['a']"
    
Source code in src/digitalearth/base/spec/figure.py
def panel(self, panel_id: str) -> PanelSpec:
    """Return the panel with this id.

    Args:
        panel_id: The id to look up.

    Returns:
        The panel.

    Raises:
        KeyError: if no panel has that id, listing the ids that exist.

    Examples:
        - Look a panel up by id:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> FigureSpec(panels=(PanelSpec("a", title="Left"),)).panel("a").title
            'Left'

            ```
        - An id no panel has is named beside the ids that exist:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> FigureSpec(panels=(PanelSpec("a"),)).panel("b")
            Traceback (most recent call last):
                ...
            KeyError: "no panel 'b' in this figure; panels are ['a']"

            ```
    """
    for panel in self.panels:
        if panel.id == panel_id:
            return panel
    raise KeyError(
        f"no panel {panel_id!r} in this figure; panels are {[panel.id for panel in self.panels]}"
    )

to_dict() #

Return the plain-dict form of the whole figure.

Returns:

Type Description
dict[str, Any]

schema_version and panels, plus sources, layers, size and title when set. The free-form

dict[str, Any]

values — encoding constants, style properties, scale categories and schemes, selection axes — go

dict[str, Any]

through the JSON check as they are written, so a figure built from plain, finite Python numbers,

dict[str, Any]

strings, lists and dicts gives a dict json.dumps writes as is.

Raises:

Type Description
TypeError

if a free-form value has no JSON form. A view's CRS is checked when the view is built, so it is not a reason this can fail.

ValueError

if a source is an object: reference from :meth:DataRef.to_object <digitalearth.base.spec.dataref.DataRef.to_object>. It names an object in this process's memory, so a stored figure holding one would read back and then fail to open anywhere else. Building the figure in memory with one is fine; storing it is not.

Examples:

  • The version is always written:
    >>> from digitalearth.base.spec import FigureSpec, PanelSpec
    >>> FigureSpec(panels=(PanelSpec("main"),)).to_dict()
    {'schema_version': 1, 'panels': [{'id': 'main', 'viewport': {'crs': 3857}}]}
    
  • A figure survives a JSON round trip, with no renderer involved:
    >>> import json
    >>> from digitalearth.base.spec import DataRef, FigureSpec, LayerSpec, LayerTree, PanelSpec, Viewport
    >>> fig = FigureSpec(
    ...     panels=(PanelSpec("main", Viewport(4326), layers=("dem",)),),
    ...     sources={"srtm": DataRef("data/dem.tif")},
    ...     layers=LayerTree((LayerSpec("dem", "raster", source_id="srtm"),)),
    ...     size=(8, 4),
    ... )
    >>> text = json.dumps(fig.to_dict(), allow_nan=False)
    >>> back = FigureSpec.from_dict(json.loads(text))
    >>> back == fig, back.size
    (True, (8.0, 4.0))
    
Source code in src/digitalearth/base/spec/figure.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form of the whole figure.

    Returns:
        `schema_version` and `panels`, plus `sources`, `layers`, `size` and `title` when set. The free-form
        values — encoding constants, style properties, scale categories and schemes, selection axes — go
        through the JSON check as they are written, so a figure built from plain, finite Python numbers,
        strings, lists and dicts gives a dict `json.dumps` writes as is.

    Raises:
        TypeError: if a free-form value has no JSON form. A view's CRS is checked when the view is built, so
            it is not a reason this can fail.
        ValueError: if a source is an ``object:`` reference from :meth:`DataRef.to_object
            <digitalearth.base.spec.dataref.DataRef.to_object>`. It names an object in this process's memory,
            so a stored figure holding one would read back and then fail to open anywhere else. Building the
            figure in memory with one is fine; storing it is not.

    Examples:
        - The version is always written:
            ```python
            >>> from digitalearth.base.spec import FigureSpec, PanelSpec
            >>> FigureSpec(panels=(PanelSpec("main"),)).to_dict()
            {'schema_version': 1, 'panels': [{'id': 'main', 'viewport': {'crs': 3857}}]}

            ```
        - A figure survives a JSON round trip, with no renderer involved:
            ```python
            >>> import json
            >>> from digitalearth.base.spec import DataRef, FigureSpec, LayerSpec, LayerTree, PanelSpec, Viewport
            >>> fig = FigureSpec(
            ...     panels=(PanelSpec("main", Viewport(4326), layers=("dem",)),),
            ...     sources={"srtm": DataRef("data/dem.tif")},
            ...     layers=LayerTree((LayerSpec("dem", "raster", source_id="srtm"),)),
            ...     size=(8, 4),
            ... )
            >>> text = json.dumps(fig.to_dict(), allow_nan=False)
            >>> back = FigureSpec.from_dict(json.loads(text))
            >>> back == fig, back.size
            (True, (8.0, 4.0))

            ```
    """
    out: dict[str, Any] = {
        "schema_version": self.schema_version,
        "panels": [panel.to_dict() for panel in self.panels],
    }
    if self.sources:
        for source_id, ref in self.sources.items():
            if ref.uri.startswith(f"{OBJECT_SCHEME}:"):
                raise ValueError(
                    f"source {source_id!r} is {ref.uri!r}, which only resolves in the process that registered "
                    "it, so FigureSpec.to_dict cannot store it. Save the data and reference it by path or URL"
                )
        out["sources"] = {
            plain_text(source_id): ref.to_dict()
            for source_id, ref in self.sources.items()
        }
    if len(self.layers):
        out["layers"] = self.layers.to_dict()
    if self.size is not None:
        out["size"] = list(self.size)
    if self.title is not None:
        out["title"] = plain_text(self.title)
    return out

digitalearth.base.spec.figure.PanelSpec dataclass #

One panel of a figure: a view, and the layers it shows.

Attributes:

Name Type Description
id str

The panel's identity within its figure.

view Viewport | Camera

What the panel shows the layers through — a Viewport for a flat map, a Camera for a 3-D scene. Each panel has its own, so two panels can be drawn in two CRSs.

layers tuple[str, ...]

The ids of the layers the panel shows. The draw order is the figure's tree order, not this tuple's.

title str | None

The panel's title, or None.

furniture tuple[Furniture, ...]

What is fixed to the panel's frame rather than drawn on the ground — a scale bar, a north arrow, zoom buttons, a time slider. Each item names a registered kind and the corner it sits in; a tier that cannot draw one skips it. Anything with a place on the ground is a layer instead, and anything explaining an encoding is a guide on that encoding.

Raises:

Type Description
ValueError

for an id that is not a non-empty string, a view that is neither a Viewport nor a Camera, layers given as a bare string, a layer id that is not a non-empty string, a layer listed twice, a title that is not a string or None (a blank title is kept as None), a furniture entry that is not a :class:~digitalearth.base.spec.furniture.Furniture, or one furniture kind listed twice.

Examples:

  • Two panels over the same layer, in two projections:
    >>> from digitalearth.base.spec import PanelSpec, Viewport
    >>> left = PanelSpec("mercator", Viewport(3857), layers=("t2m",))
    >>> right = PanelSpec("polar", Viewport("EPSG:3413"), layers=("t2m",))
    >>> left.view.crs, right.view.crs, left.layers == right.layers
    (3857, 'EPSG:3413', True)
    
  • A panel with no view named is a Web Mercator map, and a list of layer ids is stored as a tuple:
    >>> from digitalearth.base.spec import PanelSpec
    >>> panel = PanelSpec("main", layers=["dem", "roads"])
    >>> panel.view.crs, panel.layers
    (3857, ('dem', 'roads'))
    
  • Furniture is anchored to the frame, wherever the map is panned:
    >>> from digitalearth.base.spec import Furniture, PanelSpec
    >>> panel = PanelSpec("main", furniture=(Furniture("scale_bar"), Furniture("north_arrow")))
    >>> [(item.kind, item.anchor) for item in panel.furniture]
    [('scale_bar', 'bottom-left'), ('north_arrow', 'top-right')]
    
  • A bare string is refused rather than read as one layer id per letter:
    >>> from digitalearth.base.spec import PanelSpec
    >>> PanelSpec("main", layers="t2m")
    Traceback (most recent call last):
        ...
    ValueError: PanelSpec layers must be a sequence of layer ids; got the string 't2m'
    
Source code in src/digitalearth/base/spec/figure.py
@dataclass(frozen=True)
class PanelSpec:
    """One panel of a figure: a view, and the layers it shows.

    Attributes:
        id: The panel's identity within its figure.
        view: What the panel shows the layers through — a `Viewport` for a flat map, a `Camera` for a 3-D scene. Each
            panel has its own, so two panels can be drawn in two CRSs.
        layers: The ids of the layers the panel shows. The draw order is the figure's tree order, not this tuple's.
        title: The panel's title, or ``None``.
        furniture: What is fixed to the panel's frame rather than drawn on the ground — a scale bar, a north
            arrow, zoom buttons, a time slider. Each item names a registered kind and the corner it sits in; a
            tier that cannot draw one skips it. Anything with a place on the ground is a layer instead, and
            anything explaining an encoding is a guide on that encoding.

    Raises:
        ValueError: for an id that is not a non-empty string, a view that is neither a
            `Viewport` nor a `Camera`, `layers` given as a bare string, a layer id that is not a non-empty string, a
            layer listed twice, a title that is not a string or ``None`` (a blank title is kept as ``None``), a
            furniture entry that is not a :class:`~digitalearth.base.spec.furniture.Furniture`, or one furniture
            kind listed twice.

    Examples:
        - Two panels over the same layer, in two projections:
            ```python
            >>> from digitalearth.base.spec import PanelSpec, Viewport
            >>> left = PanelSpec("mercator", Viewport(3857), layers=("t2m",))
            >>> right = PanelSpec("polar", Viewport("EPSG:3413"), layers=("t2m",))
            >>> left.view.crs, right.view.crs, left.layers == right.layers
            (3857, 'EPSG:3413', True)

            ```
        - A panel with no view named is a Web Mercator map, and a list of layer ids is stored as a tuple:
            ```python
            >>> from digitalearth.base.spec import PanelSpec
            >>> panel = PanelSpec("main", layers=["dem", "roads"])
            >>> panel.view.crs, panel.layers
            (3857, ('dem', 'roads'))

            ```
        - Furniture is anchored to the frame, wherever the map is panned:
            ```python
            >>> from digitalearth.base.spec import Furniture, PanelSpec
            >>> panel = PanelSpec("main", furniture=(Furniture("scale_bar"), Furniture("north_arrow")))
            >>> [(item.kind, item.anchor) for item in panel.furniture]
            [('scale_bar', 'bottom-left'), ('north_arrow', 'top-right')]

            ```
        - A bare string is refused rather than read as one layer id per letter:
            ```python
            >>> from digitalearth.base.spec import PanelSpec
            >>> PanelSpec("main", layers="t2m")
            Traceback (most recent call last):
                ...
            ValueError: PanelSpec layers must be a sequence of layer ids; got the string 't2m'

            ```
    """

    id: str
    view: Viewport | Camera = field(default_factory=Viewport)
    layers: tuple[str, ...] = ()
    title: str | None = None
    furniture: tuple[Furniture, ...] = ()

    def __post_init__(self) -> None:
        """Refuse a panel that could not be drawn or addressed.

        Raises:
            ValueError: as described on the class.
        """
        _identifier("PanelSpec", self.id)
        if not isinstance(self.view, (Viewport, Camera)):
            raise ValueError(
                f"PanelSpec view must be a Viewport or a Camera; got {type(self.view).__name__}"
            )
        if isinstance(self.layers, str):
            # A bare string is iterable, and tuple("t2m") would be three one-letter layer ids.
            raise ValueError(
                f"PanelSpec layers must be a sequence of layer ids; got the string {self.layers!r}"
            )
        layers = tuple(self.layers)
        for layer_id in layers:
            if not isinstance(layer_id, str) or not layer_id:
                raise ValueError(
                    f"PanelSpec layers must be non-empty layer ids; got {layer_id!r}"
                )
        repeated = sorted(
            {layer_id for layer_id in layers if layers.count(layer_id) > 1}
        )
        if repeated:
            raise ValueError(
                f"panel {self.id!r} lists layers {repeated} more than once"
            )
        object.__setattr__(self, "layers", layers)
        object.__setattr__(self, "title", _optional_title("PanelSpec", self.title))
        furniture = tuple(self.furniture)
        for item in furniture:
            if not isinstance(item, Furniture):
                raise ValueError(
                    f"PanelSpec furniture must be Furniture items; got {type(item).__name__}"
                )
        kinds_listed = [item.kind for item in furniture]
        repeated_kinds = sorted(
            {kind for kind in kinds_listed if kinds_listed.count(kind) > 1}
        )
        if repeated_kinds:
            # Two scale bars on one panel is a caller who added the same item twice, not a design: whichever is
            # drawn second would sit on top of the first, in the same corner.
            raise ValueError(
                f"panel {self.id!r} lists furniture {repeated_kinds} more than once"
            )
        object.__setattr__(self, "furniture", furniture)

    def bounds_of(
        self,
        extents: Mapping[str, Bounds | None],
        *,
        padding: float = 0.0,
    ) -> Bounds | None:
        """Return the region this panel's own layers cover, in the CRS the panel draws in.

        What a tier needs to frame a figure on its data, composed where both halves of the question are
        already held: *which* layers count is this panel's `layers`, and *which CRS* they have to meet in is
        its `view`. Neither is the figure's — a linked-view figure frames each panel on its own subset — and
        neither is the tier's, which can measure a layer's extent but not decide those two things.

        Nothing is computed here that :class:`~digitalearth.base.spec.bounds.Bounds` did not already do:
        :meth:`~digitalearth.base.spec.bounds.Bounds.to_crs` converts,
        :meth:`~digitalearth.base.spec.bounds.Bounds.union` merges and
        :meth:`~digitalearth.base.spec.bounds.Bounds.padded` grows. This is the order they go in.

        Args:
            extents: What each layer covers, by layer id, as the tier measured it — from the artists or
                elements it actually drew, in any CRS. It is read as *what is known* rather than as one
                entry per layer: a layer with no key, and a layer whose value is ``None``, are both skipped,
                because a text label carries a point and a graticule is computed from the CRS rather than
                covering anything. Ids this panel does not show are ignored.
            padding: Breathing room around the union, as a fraction of its own span — ``0.05`` leaves a 5%
                margin. The default leaves the frame exactly the rectangle the layers cover.

        Returns:
            The padded union, in the view's CRS, or ``None`` when no layer this panel shows had an extent to
            give — which a caller has to be able to tell from a frame that came out empty.

        Raises:
            TypeError: if `extents` is not a mapping, or if one of its values is neither a `Bounds` nor
                ``None`` — named with the layer id, because a figure has many layers and only one is wrong.
            ValueError: from `Bounds`, for two extents that cannot be made to meet — a view with no CRS
                cannot convert, so rectangles in two CRSs are refused rather than reinterpreted. And from
                :func:`~digitalearth.base.spec.bounds.check_padding`, for a `padding` that is not finite or
                is below :data:`~digitalearth.base.spec.bounds.MIN_PADDING`, which would turn the frame inside
                out:
                that one is raised **before** any `Bounds` exists, which is the point of checking it here —
                behind the union it was checked only on the branch where some layer had an extent, so the same
                bad call was a hard error on a figure with data and a silent ``None`` on one without.

        Examples:
            - Two layers, framed on the rectangle that holds both:
                ```python
                >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
                >>> panel = PanelSpec("main", Viewport(3857), layers=("dem", "gauges"))
                >>> covers = {
                ...     "dem": Bounds(0.0, 0.0, 10.0, 10.0, crs=3857),
                ...     "gauges": Bounds(5.0, 20.0, 30.0, 40.0, crs=3857),
                ... }
                >>> panel.bounds_of(covers).as_bbox()
                [0.0, 0.0, 30.0, 40.0]

                ```
            - A layer measured in the data's CRS is converted into the panel's before it is merged:
                ```python
                >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
                >>> panel = PanelSpec("main", Viewport(3857), layers=("here",))
                >>> framed = panel.bounds_of({"here": Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)})
                >>> framed.crs, round(framed.xmax)
                (3857, 111319)

                ```
            - A panel whose layers measured nothing has no region to report:
                ```python
                >>> from digitalearth.base.spec import PanelSpec
                >>> PanelSpec("main", layers=("grid",)).bounds_of({}) is None
                True

                ```
        """
        if not isinstance(extents, Mapping):
            raise TypeError(
                f"bounds_of takes a mapping of layer id to Bounds; got {type(extents).__name__}"
            )
        # Before anything is measured, so the fraction is judged on its own. Behind the union it was checked
        # only by `padded`, on the branch where some layer had an extent — so the same bad call was a hard
        # error on a figure with data and a silent `None` on one without (review L2).
        check_padding(padding)
        target = self.view.crs
        total: Bounds | None = None
        for layer_id in self.layers:
            covered = extents.get(layer_id)
            if covered is None:
                continue
            if not isinstance(covered, Bounds):
                raise TypeError(
                    f"bounds_of needs a Bounds for layer {layer_id!r}; got "
                    f"{type(covered).__name__}"
                )
            # Converted before the merge, not after: `union` refuses two CRSs outright rather than
            # reinterpreting the numbers, which is the whole reason the panel is the one doing this.
            placed = covered if target is None else covered.to_crs(target)
            total = placed if total is None else total.union(placed)
        if total is None or not padding:
            return total
        return total.padded(padding)

    def to_dict(self) -> dict[str, Any]:
        """Return the plain-dict form a figure stores.

        Returns:
            ``id``, the view under ``viewport`` or ``camera`` — which names the kind of view without a separate type
            field — plus ``layers`` and ``title`` when set.

        Examples:
            - The view is stored under the key that names its kind:
                ```python
                >>> from digitalearth.base.spec import PanelSpec, Viewport
                >>> PanelSpec("main", Viewport(4326), layers=("dem",)).to_dict()
                {'id': 'main', 'viewport': {'crs': 4326}, 'layers': ['dem']}

                ```
            - A 3-D panel stores a camera, and its title:
                ```python
                >>> from digitalearth.base.spec import Camera, PanelSpec
                >>> stored = PanelSpec("3d", Camera((0.0, -10.0, 5.0)), title="Terrain").to_dict()
                >>> sorted(stored), stored["camera"]["position"]
                (['camera', 'id', 'title'], [0.0, -10.0, 5.0])

                ```
        """
        out: dict[str, Any] = {"id": plain_text(self.id)}
        if isinstance(self.view, Camera):
            out["camera"] = self.view.to_dict()
        else:
            out["viewport"] = self.view.to_dict()
        if self.layers:
            out["layers"] = [plain_text(layer_id) for layer_id in self.layers]
        if self.title is not None:
            out["title"] = plain_text(self.title)
        if self.furniture:
            out["furniture"] = [item.to_dict() for item in self.furniture]
        return out

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> "PanelSpec":
        """Rebuild a panel from its dict form.

        Args:
            data: A mapping as produced by :meth:`to_dict`.

        Returns:
            The panel, validated as the constructor validates it.

        Raises:
            TypeError: if `data` or its view is not a mapping, or `layers` is not a list, naming the field.
            ValueError: for a missing id, an unknown key, both or neither of `viewport` and `camera`, a view its own
                `from_dict` refuses, or a panel the constructor refuses. An error of either type from the stored view
                names where it sits: `PanelSpec.from_dict viewport: Viewport.from_dict needs a mapping; got int`.

        Examples:
            - A stored 3-D panel reads back with its camera:
                ```python
                >>> from digitalearth.base.spec import PanelSpec
                >>> panel = PanelSpec.from_dict({"id": "3d", "camera": {"position": [0, -10, 5]}})
                >>> panel.view.position
                (0.0, -10.0, 5.0)

                ```
            - A panel must say which kind of view it has:
                ```python
                >>> from digitalearth.base.spec import PanelSpec
                >>> PanelSpec.from_dict({"id": "main", "layers": ["dem"]})  # doctest: +ELLIPSIS
                Traceback (most recent call last):
                    ...
                ValueError: PanelSpec.from_dict needs exactly one of 'viewport' (a flat map) or 'camera' ...

                ```
        """
        refuse_unknown(
            "PanelSpec",
            data,
            ("id", "viewport", "camera", "layers", "title", "furniture"),
        )
        if ("viewport" in data) == ("camera" in data):
            raise ValueError(
                "PanelSpec.from_dict needs exactly one of 'viewport' (a flat map) or 'camera' (a 3-D scene); "
                f"got keys {sorted(data)}"
            )
        view: Viewport | Camera = (
            read_entry("PanelSpec", "camera", Camera.from_dict, data["camera"])
            if "camera" in data
            else read_entry(
                "PanelSpec", "viewport", Viewport.from_dict, data["viewport"]
            )
        )
        return cls(
            id=require("PanelSpec", data, "id"),
            view=view,
            layers=as_list("PanelSpec", "layers", data.get("layers", ())),
            title=data.get("title"),
            furniture=tuple(
                read_entry("PanelSpec", "furniture", Furniture.from_dict, item)
                for item in as_list("PanelSpec", "furniture", data.get("furniture", ()))
            ),
        )

__post_init__() #

Refuse a panel that could not be drawn or addressed.

Raises:

Type Description
ValueError

as described on the class.

Source code in src/digitalearth/base/spec/figure.py
def __post_init__(self) -> None:
    """Refuse a panel that could not be drawn or addressed.

    Raises:
        ValueError: as described on the class.
    """
    _identifier("PanelSpec", self.id)
    if not isinstance(self.view, (Viewport, Camera)):
        raise ValueError(
            f"PanelSpec view must be a Viewport or a Camera; got {type(self.view).__name__}"
        )
    if isinstance(self.layers, str):
        # A bare string is iterable, and tuple("t2m") would be three one-letter layer ids.
        raise ValueError(
            f"PanelSpec layers must be a sequence of layer ids; got the string {self.layers!r}"
        )
    layers = tuple(self.layers)
    for layer_id in layers:
        if not isinstance(layer_id, str) or not layer_id:
            raise ValueError(
                f"PanelSpec layers must be non-empty layer ids; got {layer_id!r}"
            )
    repeated = sorted(
        {layer_id for layer_id in layers if layers.count(layer_id) > 1}
    )
    if repeated:
        raise ValueError(
            f"panel {self.id!r} lists layers {repeated} more than once"
        )
    object.__setattr__(self, "layers", layers)
    object.__setattr__(self, "title", _optional_title("PanelSpec", self.title))
    furniture = tuple(self.furniture)
    for item in furniture:
        if not isinstance(item, Furniture):
            raise ValueError(
                f"PanelSpec furniture must be Furniture items; got {type(item).__name__}"
            )
    kinds_listed = [item.kind for item in furniture]
    repeated_kinds = sorted(
        {kind for kind in kinds_listed if kinds_listed.count(kind) > 1}
    )
    if repeated_kinds:
        # Two scale bars on one panel is a caller who added the same item twice, not a design: whichever is
        # drawn second would sit on top of the first, in the same corner.
        raise ValueError(
            f"panel {self.id!r} lists furniture {repeated_kinds} more than once"
        )
    object.__setattr__(self, "furniture", furniture)

bounds_of(extents, *, padding=0.0) #

Return the region this panel's own layers cover, in the CRS the panel draws in.

What a tier needs to frame a figure on its data, composed where both halves of the question are already held: which layers count is this panel's layers, and which CRS they have to meet in is its view. Neither is the figure's — a linked-view figure frames each panel on its own subset — and neither is the tier's, which can measure a layer's extent but not decide those two things.

Nothing is computed here that :class:~digitalearth.base.spec.bounds.Bounds did not already do: :meth:~digitalearth.base.spec.bounds.Bounds.to_crs converts, :meth:~digitalearth.base.spec.bounds.Bounds.union merges and :meth:~digitalearth.base.spec.bounds.Bounds.padded grows. This is the order they go in.

Parameters:

Name Type Description Default
extents Mapping[str, Bounds | None]

What each layer covers, by layer id, as the tier measured it — from the artists or elements it actually drew, in any CRS. It is read as what is known rather than as one entry per layer: a layer with no key, and a layer whose value is None, are both skipped, because a text label carries a point and a graticule is computed from the CRS rather than covering anything. Ids this panel does not show are ignored.

required
padding float

Breathing room around the union, as a fraction of its own span — 0.05 leaves a 5% margin. The default leaves the frame exactly the rectangle the layers cover.

0.0

Returns:

Type Description
Bounds | None

The padded union, in the view's CRS, or None when no layer this panel shows had an extent to

Bounds | None

give — which a caller has to be able to tell from a frame that came out empty.

Raises:

Type Description
TypeError

if extents is not a mapping, or if one of its values is neither a Bounds nor None — named with the layer id, because a figure has many layers and only one is wrong.

ValueError

from Bounds, for two extents that cannot be made to meet — a view with no CRS cannot convert, so rectangles in two CRSs are refused rather than reinterpreted. And from :func:~digitalearth.base.spec.bounds.check_padding, for a padding that is not finite or is below :data:~digitalearth.base.spec.bounds.MIN_PADDING, which would turn the frame inside out: that one is raised before any Bounds exists, which is the point of checking it here — behind the union it was checked only on the branch where some layer had an extent, so the same bad call was a hard error on a figure with data and a silent None on one without.

Examples:

  • Two layers, framed on the rectangle that holds both:
    >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
    >>> panel = PanelSpec("main", Viewport(3857), layers=("dem", "gauges"))
    >>> covers = {
    ...     "dem": Bounds(0.0, 0.0, 10.0, 10.0, crs=3857),
    ...     "gauges": Bounds(5.0, 20.0, 30.0, 40.0, crs=3857),
    ... }
    >>> panel.bounds_of(covers).as_bbox()
    [0.0, 0.0, 30.0, 40.0]
    
  • A layer measured in the data's CRS is converted into the panel's before it is merged:
    >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
    >>> panel = PanelSpec("main", Viewport(3857), layers=("here",))
    >>> framed = panel.bounds_of({"here": Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)})
    >>> framed.crs, round(framed.xmax)
    (3857, 111319)
    
  • A panel whose layers measured nothing has no region to report:
    >>> from digitalearth.base.spec import PanelSpec
    >>> PanelSpec("main", layers=("grid",)).bounds_of({}) is None
    True
    
Source code in src/digitalearth/base/spec/figure.py
def bounds_of(
    self,
    extents: Mapping[str, Bounds | None],
    *,
    padding: float = 0.0,
) -> Bounds | None:
    """Return the region this panel's own layers cover, in the CRS the panel draws in.

    What a tier needs to frame a figure on its data, composed where both halves of the question are
    already held: *which* layers count is this panel's `layers`, and *which CRS* they have to meet in is
    its `view`. Neither is the figure's — a linked-view figure frames each panel on its own subset — and
    neither is the tier's, which can measure a layer's extent but not decide those two things.

    Nothing is computed here that :class:`~digitalearth.base.spec.bounds.Bounds` did not already do:
    :meth:`~digitalearth.base.spec.bounds.Bounds.to_crs` converts,
    :meth:`~digitalearth.base.spec.bounds.Bounds.union` merges and
    :meth:`~digitalearth.base.spec.bounds.Bounds.padded` grows. This is the order they go in.

    Args:
        extents: What each layer covers, by layer id, as the tier measured it — from the artists or
            elements it actually drew, in any CRS. It is read as *what is known* rather than as one
            entry per layer: a layer with no key, and a layer whose value is ``None``, are both skipped,
            because a text label carries a point and a graticule is computed from the CRS rather than
            covering anything. Ids this panel does not show are ignored.
        padding: Breathing room around the union, as a fraction of its own span — ``0.05`` leaves a 5%
            margin. The default leaves the frame exactly the rectangle the layers cover.

    Returns:
        The padded union, in the view's CRS, or ``None`` when no layer this panel shows had an extent to
        give — which a caller has to be able to tell from a frame that came out empty.

    Raises:
        TypeError: if `extents` is not a mapping, or if one of its values is neither a `Bounds` nor
            ``None`` — named with the layer id, because a figure has many layers and only one is wrong.
        ValueError: from `Bounds`, for two extents that cannot be made to meet — a view with no CRS
            cannot convert, so rectangles in two CRSs are refused rather than reinterpreted. And from
            :func:`~digitalearth.base.spec.bounds.check_padding`, for a `padding` that is not finite or
            is below :data:`~digitalearth.base.spec.bounds.MIN_PADDING`, which would turn the frame inside
            out:
            that one is raised **before** any `Bounds` exists, which is the point of checking it here —
            behind the union it was checked only on the branch where some layer had an extent, so the same
            bad call was a hard error on a figure with data and a silent ``None`` on one without.

    Examples:
        - Two layers, framed on the rectangle that holds both:
            ```python
            >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
            >>> panel = PanelSpec("main", Viewport(3857), layers=("dem", "gauges"))
            >>> covers = {
            ...     "dem": Bounds(0.0, 0.0, 10.0, 10.0, crs=3857),
            ...     "gauges": Bounds(5.0, 20.0, 30.0, 40.0, crs=3857),
            ... }
            >>> panel.bounds_of(covers).as_bbox()
            [0.0, 0.0, 30.0, 40.0]

            ```
        - A layer measured in the data's CRS is converted into the panel's before it is merged:
            ```python
            >>> from digitalearth.base.spec import Bounds, PanelSpec, Viewport
            >>> panel = PanelSpec("main", Viewport(3857), layers=("here",))
            >>> framed = panel.bounds_of({"here": Bounds(0.0, 0.0, 1.0, 1.0, crs=4326)})
            >>> framed.crs, round(framed.xmax)
            (3857, 111319)

            ```
        - A panel whose layers measured nothing has no region to report:
            ```python
            >>> from digitalearth.base.spec import PanelSpec
            >>> PanelSpec("main", layers=("grid",)).bounds_of({}) is None
            True

            ```
    """
    if not isinstance(extents, Mapping):
        raise TypeError(
            f"bounds_of takes a mapping of layer id to Bounds; got {type(extents).__name__}"
        )
    # Before anything is measured, so the fraction is judged on its own. Behind the union it was checked
    # only by `padded`, on the branch where some layer had an extent — so the same bad call was a hard
    # error on a figure with data and a silent `None` on one without (review L2).
    check_padding(padding)
    target = self.view.crs
    total: Bounds | None = None
    for layer_id in self.layers:
        covered = extents.get(layer_id)
        if covered is None:
            continue
        if not isinstance(covered, Bounds):
            raise TypeError(
                f"bounds_of needs a Bounds for layer {layer_id!r}; got "
                f"{type(covered).__name__}"
            )
        # Converted before the merge, not after: `union` refuses two CRSs outright rather than
        # reinterpreting the numbers, which is the whole reason the panel is the one doing this.
        placed = covered if target is None else covered.to_crs(target)
        total = placed if total is None else total.union(placed)
    if total is None or not padding:
        return total
    return total.padded(padding)

from_dict(data) classmethod #

Rebuild a panel from its dict form.

Parameters:

Name Type Description Default
data Mapping[str, Any]

A mapping as produced by :meth:to_dict.

required

Returns:

Type Description
PanelSpec

The panel, validated as the constructor validates it.

Raises:

Type Description
TypeError

if data or its view is not a mapping, or layers is not a list, naming the field.

ValueError

for a missing id, an unknown key, both or neither of viewport and camera, a view its own from_dict refuses, or a panel the constructor refuses. An error of either type from the stored view names where it sits: PanelSpec.from_dict viewport: Viewport.from_dict needs a mapping; got int.

Examples:

  • A stored 3-D panel reads back with its camera:
    >>> from digitalearth.base.spec import PanelSpec
    >>> panel = PanelSpec.from_dict({"id": "3d", "camera": {"position": [0, -10, 5]}})
    >>> panel.view.position
    (0.0, -10.0, 5.0)
    
  • A panel must say which kind of view it has:
    >>> from digitalearth.base.spec import PanelSpec
    >>> PanelSpec.from_dict({"id": "main", "layers": ["dem"]})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: PanelSpec.from_dict needs exactly one of 'viewport' (a flat map) or 'camera' ...
    
Source code in src/digitalearth/base/spec/figure.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> "PanelSpec":
    """Rebuild a panel from its dict form.

    Args:
        data: A mapping as produced by :meth:`to_dict`.

    Returns:
        The panel, validated as the constructor validates it.

    Raises:
        TypeError: if `data` or its view is not a mapping, or `layers` is not a list, naming the field.
        ValueError: for a missing id, an unknown key, both or neither of `viewport` and `camera`, a view its own
            `from_dict` refuses, or a panel the constructor refuses. An error of either type from the stored view
            names where it sits: `PanelSpec.from_dict viewport: Viewport.from_dict needs a mapping; got int`.

    Examples:
        - A stored 3-D panel reads back with its camera:
            ```python
            >>> from digitalearth.base.spec import PanelSpec
            >>> panel = PanelSpec.from_dict({"id": "3d", "camera": {"position": [0, -10, 5]}})
            >>> panel.view.position
            (0.0, -10.0, 5.0)

            ```
        - A panel must say which kind of view it has:
            ```python
            >>> from digitalearth.base.spec import PanelSpec
            >>> PanelSpec.from_dict({"id": "main", "layers": ["dem"]})  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: PanelSpec.from_dict needs exactly one of 'viewport' (a flat map) or 'camera' ...

            ```
    """
    refuse_unknown(
        "PanelSpec",
        data,
        ("id", "viewport", "camera", "layers", "title", "furniture"),
    )
    if ("viewport" in data) == ("camera" in data):
        raise ValueError(
            "PanelSpec.from_dict needs exactly one of 'viewport' (a flat map) or 'camera' (a 3-D scene); "
            f"got keys {sorted(data)}"
        )
    view: Viewport | Camera = (
        read_entry("PanelSpec", "camera", Camera.from_dict, data["camera"])
        if "camera" in data
        else read_entry(
            "PanelSpec", "viewport", Viewport.from_dict, data["viewport"]
        )
    )
    return cls(
        id=require("PanelSpec", data, "id"),
        view=view,
        layers=as_list("PanelSpec", "layers", data.get("layers", ())),
        title=data.get("title"),
        furniture=tuple(
            read_entry("PanelSpec", "furniture", Furniture.from_dict, item)
            for item in as_list("PanelSpec", "furniture", data.get("furniture", ()))
        ),
    )

to_dict() #

Return the plain-dict form a figure stores.

Returns:

Type Description
dict[str, Any]

id, the view under viewport or camera — which names the kind of view without a separate type

dict[str, Any]

field — plus layers and title when set.

Examples:

  • The view is stored under the key that names its kind:
    >>> from digitalearth.base.spec import PanelSpec, Viewport
    >>> PanelSpec("main", Viewport(4326), layers=("dem",)).to_dict()
    {'id': 'main', 'viewport': {'crs': 4326}, 'layers': ['dem']}
    
  • A 3-D panel stores a camera, and its title:
    >>> from digitalearth.base.spec import Camera, PanelSpec
    >>> stored = PanelSpec("3d", Camera((0.0, -10.0, 5.0)), title="Terrain").to_dict()
    >>> sorted(stored), stored["camera"]["position"]
    (['camera', 'id', 'title'], [0.0, -10.0, 5.0])
    
Source code in src/digitalearth/base/spec/figure.py
def to_dict(self) -> dict[str, Any]:
    """Return the plain-dict form a figure stores.

    Returns:
        ``id``, the view under ``viewport`` or ``camera`` — which names the kind of view without a separate type
        field — plus ``layers`` and ``title`` when set.

    Examples:
        - The view is stored under the key that names its kind:
            ```python
            >>> from digitalearth.base.spec import PanelSpec, Viewport
            >>> PanelSpec("main", Viewport(4326), layers=("dem",)).to_dict()
            {'id': 'main', 'viewport': {'crs': 4326}, 'layers': ['dem']}

            ```
        - A 3-D panel stores a camera, and its title:
            ```python
            >>> from digitalearth.base.spec import Camera, PanelSpec
            >>> stored = PanelSpec("3d", Camera((0.0, -10.0, 5.0)), title="Terrain").to_dict()
            >>> sorted(stored), stored["camera"]["position"]
            (['camera', 'id', 'title'], [0.0, -10.0, 5.0])

            ```
    """
    out: dict[str, Any] = {"id": plain_text(self.id)}
    if isinstance(self.view, Camera):
        out["camera"] = self.view.to_dict()
    else:
        out["viewport"] = self.view.to_dict()
    if self.layers:
        out["layers"] = [plain_text(layer_id) for layer_id in self.layers]
    if self.title is not None:
        out["title"] = plain_text(self.title)
    if self.furniture:
        out["furniture"] = [item.to_dict() for item in self.furniture]
    return out

The registries#

How a reference becomes data, without base/ knowing any reader — and how Scale reaches a classifier without base/ importing the renderer it lives in.

digitalearth.base.registry.register_resolver(scheme, resolver) #

Register the callable that opens URIs of one scheme.

Parameters:

Name Type Description Default
scheme str

The URI scheme, without :// — "file", "s3", "object".

required
resolver Callable[[str], Any]

Called with the full URI, returning the opened object.

required

Raises:

Type Description
ValueError

if scheme is empty. A resolver under no scheme could never be reached, and registering one is more likely a typo than an intent.

Examples:

  • Register a resolver and reach it through the scheme it serves. A plain call is permanent — there is no unregister — so this shows it inside :func:temporary_resolver, which is what to reach for anywhere the registration should not outlive the code that made it:
    >>> from digitalearth.base.registry import resolve_uri, resolvers, temporary_resolver
    >>> with temporary_resolver("demo", lambda uri: uri.upper()):
    ...     "demo" in resolvers(), resolve_uri("demo:x")
    (True, 'DEMO:X')
    >>> "demo" in resolvers()
    False
    
Source code in src/digitalearth/base/registry.py
def register_resolver(scheme: str, resolver: Callable[[str], Any]) -> None:
    """Register the callable that opens URIs of one scheme.

    Args:
        scheme: The URI scheme, without ``://`` — ``"file"``, ``"s3"``, ``"object"``.
        resolver: Called with the full URI, returning the opened object.

    Raises:
        ValueError: if `scheme` is empty. A resolver under no scheme could never be reached, and registering
            one is more likely a typo than an intent.

    Examples:
        - Register a resolver and reach it through the scheme it serves. A plain call is **permanent** —
          there is no unregister — so this shows it inside :func:`temporary_resolver`, which is what to
          reach for anywhere the registration should not outlive the code that made it:
            ```python
            >>> from digitalearth.base.registry import resolve_uri, resolvers, temporary_resolver
            >>> with temporary_resolver("demo", lambda uri: uri.upper()):
            ...     "demo" in resolvers(), resolve_uri("demo:x")
            (True, 'DEMO:X')
            >>> "demo" in resolvers()
            False

            ```
    """
    if not scheme:
        raise ValueError("a resolver needs a non-empty scheme")
    _RESOLVERS[scheme] = resolver

digitalearth.base.registry.resolvers() #

Return the registered resolvers, keyed by scheme.

Returns:

Type Description
dict[str, Callable[[str], Any]]

A copy of the table, so a caller inspecting it cannot edit the registry by accident.

Examples:

  • Reach the resolver a scheme is served by:
    >>> from digitalearth.base.registry import resolvers
    >>> resolvers()["object"].__name__
    '_resolve_object'
    
  • Editing what comes back leaves the registry alone, because it is a copy:
    >>> from digitalearth.base.registry import resolvers
    >>> table = resolvers()
    >>> del table["file"]
    >>> "file" in resolvers()
    True
    
Source code in src/digitalearth/base/registry.py
def resolvers() -> dict[str, Callable[[str], Any]]:
    """Return the registered resolvers, keyed by scheme.

    Returns:
        A copy of the table, so a caller inspecting it cannot edit the registry by accident.

    Examples:
        - Reach the resolver a scheme is served by:
            ```python
            >>> from digitalearth.base.registry import resolvers
            >>> resolvers()["object"].__name__
            '_resolve_object'

            ```
        - Editing what comes back leaves the registry alone, because it is a copy:
            ```python
            >>> from digitalearth.base.registry import resolvers
            >>> table = resolvers()
            >>> del table["file"]
            >>> "file" in resolvers()
            True

            ```
    """
    return dict(_RESOLVERS)

digitalearth.base.registry.temporary_resolver(scheme, resolver) #

Register a resolver for the duration of a block, then put the table back as it was.

The registry is process-global and has no unregister, so a test or an example that registers a scheme changes what every later one sees. This is the scoped form, so demonstrating the registry does not leave a scheme behind in the session that ran the demonstration.

Parameters:

Name Type Description Default
scheme str

The URI scheme to register under.

required
resolver Callable[[str], Any]

The resolver to install for the block.

required

Yields:

Type Description
None

Nothing; the registration is in effect inside the block.

Examples:

  • The scheme resolves inside the block and is gone afterwards:
    >>> from digitalearth.base.registry import resolve_uri, resolvers, temporary_resolver
    >>> with temporary_resolver("scratch", lambda uri: uri.upper()):
    ...     resolve_uri("scratch:x")
    'SCRATCH:X'
    >>> "scratch" in resolvers()
    False
    
Source code in src/digitalearth/base/registry.py
@contextmanager
def temporary_resolver(scheme: str, resolver: Callable[[str], Any]) -> Iterator[None]:
    """Register a resolver for the duration of a block, then put the table back as it was.

    The registry is process-global and has no unregister, so a test or an example that registers a scheme
    changes what every later one sees. This is the scoped form, so demonstrating the registry does not leave
    a scheme behind in the session that ran the demonstration.

    Args:
        scheme: The URI scheme to register under.
        resolver: The resolver to install for the block.

    Yields:
        Nothing; the registration is in effect inside the block.

    Examples:
        - The scheme resolves inside the block and is gone afterwards:
            ```python
            >>> from digitalearth.base.registry import resolve_uri, resolvers, temporary_resolver
            >>> with temporary_resolver("scratch", lambda uri: uri.upper()):
            ...     resolve_uri("scratch:x")
            'SCRATCH:X'
            >>> "scratch" in resolvers()
            False

            ```
    """
    had = scheme in _RESOLVERS
    previous = _RESOLVERS.get(scheme)
    register_resolver(scheme, resolver)
    try:
        yield
    finally:
        if had:
            # `had`, not `previous is not None`: register_resolver validates the scheme but not the
            # resolver, so None can be registered — and testing the value would delete it instead of
            # putting it back.
            _RESOLVERS[scheme] = previous  # type: ignore[assignment]
        else:
            _RESOLVERS.pop(scheme, None)

digitalearth.base.registry.register_object(obj, *, name='') #

Hold an in-memory object in this process and return the URI that reaches it.

Parameters:

Name Type Description Default
obj Any

The object to register — typically a pyramids Dataset or FeatureCollection.

required
name str

An optional stable id. Reusing one replaces what it pointed at, which is how a caller refreshes the data behind a figure without rebuilding the figure. Omitted, a unique id is generated.

''

Returns:

Type Description
str

An object:<id> URI.

Examples:

  • An object gets a URI without touching the filesystem:
    >>> from digitalearth.base.registry import register_object, resolve_uri
    >>> uri = register_object([1, 2, 3], name="demo-rows")
    >>> uri
    'object:demo-rows'
    >>> resolve_uri(uri)
    [1, 2, 3]
    
Source code in src/digitalearth/base/registry.py
def register_object(obj: Any, *, name: str = "") -> str:
    """Hold an in-memory object in this process and return the URI that reaches it.

    Args:
        obj: The object to register — typically a pyramids ``Dataset`` or ``FeatureCollection``.
        name: An optional stable id. Reusing one replaces what it pointed at, which is how a caller refreshes
            the data behind a figure without rebuilding the figure. Omitted, a unique id is generated.

    Returns:
        An ``object:<id>`` URI.

    Examples:
        - An object gets a URI without touching the filesystem:
            ```python
            >>> from digitalearth.base.registry import register_object, resolve_uri
            >>> uri = register_object([1, 2, 3], name="demo-rows")
            >>> uri
            'object:demo-rows'
            >>> resolve_uri(uri)
            [1, 2, 3]

            ```
    """
    key = name or uuid.uuid4().hex
    _OBJECTS[key] = obj
    return f"{OBJECT_SCHEME}:{key}"

digitalearth.base.registry.clear_objects() #

Forget every registered in-memory object.

The table is process-local and holds strong references, so a long-lived session that registers many datasets keeps them all alive. This is the release valve, and what a test suite calls between cases.

Examples:

  • A cleared id no longer resolves:
    >>> from digitalearth.base.registry import clear_objects, register_object, resolve_uri
    >>> uri = register_object([1, 2], name="doc-rows")
    >>> resolve_uri(uri)
    [1, 2]
    >>> clear_objects()
    >>> resolve_uri("object:doc-rows")
    Traceback (most recent call last):
        ...
    KeyError: "no object is registered as 'doc-rows'. An object: reference only resolves in the process that registered it — save the data and reference it by path to share the figure"
    
Source code in src/digitalearth/base/registry.py
def clear_objects() -> None:
    """Forget every registered in-memory object.

    The table is process-local and holds strong references, so a long-lived session that registers many
    datasets keeps them all alive. This is the release valve, and what a test suite calls between cases.

    Examples:
        - A cleared id no longer resolves:
            ```python
            >>> from digitalearth.base.registry import clear_objects, register_object, resolve_uri
            >>> uri = register_object([1, 2], name="doc-rows")
            >>> resolve_uri(uri)
            [1, 2]
            >>> clear_objects()
            >>> resolve_uri("object:doc-rows")
            Traceback (most recent call last):
                ...
            KeyError: "no object is registered as 'doc-rows'. An object: reference only resolves in the process that registered it — save the data and reference it by path to share the figure"

            ```
    """
    _OBJECTS.clear()

digitalearth.base.registry.resolve_uri(uri) #

Open a URI with the resolver registered for its scheme.

Parameters:

Name Type Description Default
uri str

The reference to open.

required

Returns:

Type Description
Any

The opened object.

Raises:

Type Description
KeyError

if no resolver is registered for the scheme, listing the ones that are — a plugin that failed to install looks exactly like a typo otherwise.

Examples:

  • A bare path uses the default file resolver:
    >>> from digitalearth.base.registry import resolve_uri
    >>> resolve_uri("object:missing-id")
    Traceback (most recent call last):
        ...
    KeyError: "no object is registered as 'missing-id'. An object: reference only resolves in the process that registered it — save the data and reference it by path to share the figure"
    
Source code in src/digitalearth/base/registry.py
def resolve_uri(uri: str) -> Any:
    """Open a URI with the resolver registered for its scheme.

    Args:
        uri: The reference to open.

    Returns:
        The opened object.

    Raises:
        KeyError: if no resolver is registered for the scheme, listing the ones that are — a plugin that
            failed to install looks exactly like a typo otherwise.

    Examples:
        - A bare path uses the default file resolver:
            ```python
            >>> from digitalearth.base.registry import resolve_uri
            >>> resolve_uri("object:missing-id")
            Traceback (most recent call last):
                ...
            KeyError: "no object is registered as 'missing-id'. An object: reference only resolves in the process that registered it — save the data and reference it by path to share the figure"

            ```
    """
    scheme = uri.split(":", 1)[0] if ":" in uri else "file"
    # A Windows drive letter is not a scheme: "C:/data/x.tif" must read as a path, not as scheme "C".
    if len(scheme) == 1:
        scheme = "file"
    # Nor is anything holding a separator. A GDAL virtual path carries its own colon
    # ("/vsicurl/https://host/x.tif"), which split on the first colon yields "/vsicurl/https" — a scheme no
    # plugin could ever register, so the error blamed a missing plugin for what is a path.
    if "/" in scheme or "\\" in scheme:
        scheme = "file"
    if scheme not in _RESOLVERS:
        raise KeyError(
            f"no resolver registered for scheme {scheme!r}; known schemes are "
            f"{sorted(_RESOLVERS)}. A third-party resolver declares itself under the "
            f"{SOURCES_GROUP!r} entry-point group"
        )
    return _RESOLVERS[scheme](uri)

digitalearth.base.registry.register_classifier(classifier) #

Register the function that cuts class edges from values.

base/ may not import a renderer, and the classifier this package uses lives in cleopatra. So base/ declares the seam and something above it fills it — :mod:digitalearth registers a lazily-importing adapter at package import. The policy around classification (the default class count, the error that names the scheme and k, turning edges into classes) stays in :class:~digitalearth.base.spec.scale.Scale; only the arithmetic is injected.

Parameters:

Name Type Description Default
classifier Callable[[Any, str, int], Any]

Called as classifier(values, scheme, k), returning (edges, _) — cleopatra's styles.classify signature.

required

Examples:

  • Swap in a classifier of your own. :func:temporary_classifier is the form to reach for: there is one classifier for the whole process, so a replacement that is not restored silently changes every later classification:
    >>> from digitalearth.base.registry import temporary_classifier
    >>> from digitalearth.base.spec import Scale
    >>> with temporary_classifier(lambda values, scheme, k: ([0.0, 0.5, 1.0], None)):
    ...     Scale.from_values([0.0, 1.0], scheme="anything").breaks
    (0.0, 0.5, 1.0)
    
Source code in src/digitalearth/base/registry.py
def register_classifier(classifier: Callable[[Any, str, int], Any]) -> None:
    """Register the function that cuts class edges from values.

    `base/` may not import a renderer, and the classifier this package uses lives in cleopatra. So `base/`
    declares the seam and something above it fills it — :mod:`digitalearth` registers a lazily-importing
    adapter at package import. The *policy* around classification (the default class count, the error that
    names the scheme and `k`, turning edges into classes) stays in
    :class:`~digitalearth.base.spec.scale.Scale`; only the arithmetic is injected.

    Args:
        classifier: Called as ``classifier(values, scheme, k)``, returning ``(edges, _)`` — cleopatra's
            ``styles.classify`` signature.

    Examples:
        - Swap in a classifier of your own. :func:`temporary_classifier` is the form to reach for: there
          is one classifier for the whole process, so a replacement that is not restored silently changes
          every later classification:
            ```python
            >>> from digitalearth.base.registry import temporary_classifier
            >>> from digitalearth.base.spec import Scale
            >>> with temporary_classifier(lambda values, scheme, k: ([0.0, 0.5, 1.0], None)):
            ...     Scale.from_values([0.0, 1.0], scheme="anything").breaks
            (0.0, 0.5, 1.0)

            ```
    """
    global _CLASSIFIER
    _CLASSIFIER = classifier

digitalearth.base.registry.get_classifier() #

Return the registered classifier.

Returns:

Type Description
Callable[..., Any]

The function registered by :func:register_classifier.

Raises:

Type Description
RuntimeError

if none is registered. That means digitalearth was not imported, or something replaced its registration — not a caller error, so it says so rather than reading as a bad scheme.

Examples:

  • Cut class edges with whatever is registered — k classes give k + 1 edges:
    >>> import digitalearth  # registers the adapter
    >>> from digitalearth.base.registry import get_classifier
    >>> edges, _ = get_classifier()([0.0, 5.0, 10.0], "equal_interval", 2)
    >>> [float(edge) for edge in edges]
    [0.0, 5.0, 10.0]
    
Source code in src/digitalearth/base/registry.py
def get_classifier() -> Callable[..., Any]:
    """Return the registered classifier.

    Returns:
        The function registered by :func:`register_classifier`.

    Raises:
        RuntimeError: if none is registered. That means `digitalearth` was not imported, or something
            replaced its registration — not a caller error, so it says so rather than reading as a bad scheme.

    Examples:
        - Cut class edges with whatever is registered — ``k`` classes give ``k + 1`` edges:
            ```python
            >>> import digitalearth  # registers the adapter
            >>> from digitalearth.base.registry import get_classifier
            >>> edges, _ = get_classifier()([0.0, 5.0, 10.0], "equal_interval", 2)
            >>> [float(edge) for edge in edges]
            [0.0, 5.0, 10.0]

            ```
    """
    if _CLASSIFIER is None:
        raise RuntimeError(
            "no classifier is registered. digitalearth registers one at import; import the package, or "
            "call base.registry.register_classifier() with a classify(values, scheme, k) callable"
        )
    return _CLASSIFIER

digitalearth.base.registry.temporary_classifier(classifier) #

Swap the registered classifier for the duration of a block.

There is one classifier for the process, so replacing it without restoring leaves every later classification using the replacement. Where that happens inside a doctest it is worse than a wrong answer: the failure surfaces in some unrelated example further down the session.

Parameters:

Name Type Description Default
classifier Callable[..., Any]

The classify(values, scheme, k) callable to install for the block.

required

Yields:

Type Description
None

Nothing; the classifier is in effect inside the block.

Examples:

  • The swap applies inside and is undone after, even if the block raises:
    >>> import digitalearth  # registers the real adapter
    >>> from digitalearth.base.registry import get_classifier, temporary_classifier
    >>> real = get_classifier()
    >>> with temporary_classifier(lambda values, scheme, k: ([0.0, 0.5, 1.0], None)):
    ...     get_classifier()([0.0], "anything", 2)[0]
    [0.0, 0.5, 1.0]
    >>> get_classifier() is real
    True
    
Source code in src/digitalearth/base/registry.py
@contextmanager
def temporary_classifier(classifier: Callable[..., Any]) -> Iterator[None]:
    """Swap the registered classifier for the duration of a block.

    There is one classifier for the process, so replacing it without restoring leaves every later
    classification using the replacement. Where that happens inside a doctest it is worse than a wrong
    answer: the failure surfaces in some unrelated example further down the session.

    Args:
        classifier: The ``classify(values, scheme, k)`` callable to install for the block.

    Yields:
        Nothing; the classifier is in effect inside the block.

    Examples:
        - The swap applies inside and is undone after, even if the block raises:
            ```python
            >>> import digitalearth  # registers the real adapter
            >>> from digitalearth.base.registry import get_classifier, temporary_classifier
            >>> real = get_classifier()
            >>> with temporary_classifier(lambda values, scheme, k: ([0.0, 0.5, 1.0], None)):
            ...     get_classifier()([0.0], "anything", 2)[0]
            [0.0, 0.5, 1.0]
            >>> get_classifier() is real
            True

            ```
    """
    global _CLASSIFIER
    previous = _CLASSIFIER
    _CLASSIFIER = classifier
    try:
        yield
    finally:
        _CLASSIFIER = previous