🔍 Code Extractor

class GridSpace

Maturity: 58

GridSpace is a container class for organizing elements in a 1D or 2D grid structure with floating-point keys, ensuring all contained elements are of the same type.

File:
/tf/active/vicechatdev/patches/spaces.py
Lines:
1732 - 1870
Complexity:
moderate

Purpose

GridSpace provides a specialized container for organizing homogeneous elements in a grid layout, typically used for parameter space sampling or multi-dimensional data visualization. Unlike Layouts which use integer keys, GridSpace uses floating-point keys corresponding to coordinates in a 1D or 2D space. It inherits from both Layoutable and UniformNdMapping, providing mapping functionality with grid-specific features like key snapping to nearest coordinates and grid shape management.

Source Code

class GridSpace(Layoutable, UniformNdMapping):
    """
    Grids are distinct from Layouts as they ensure all contained
    elements to be of the same type. Unlike Layouts, which have
    integer keys, Grids usually have floating point keys, which
    correspond to a grid sampling in some two-dimensional space. This
    two-dimensional space may have to arbitrary dimensions, e.g. for
    2D parameter spaces.
    """

    kdims = param.List(default=[Dimension("X"), Dimension("Y")], bounds=(1,2))

    def __init__(self, initial_items=None, kdims=None, **params):
        super().__init__(initial_items, kdims=kdims, **params)
        if self.ndims > 2:
            raise Exception('Grids can have no more than two dimensions.')


    def __lshift__(self, other):
        "Adjoins another object to the GridSpace"
        if isinstance(other, (ViewableElement, UniformNdMapping)):
            return AdjointLayout([self, other])
        elif isinstance(other, AdjointLayout):
            return AdjointLayout(other.data+[self])
        else:
            raise TypeError('Cannot append {0} to a AdjointLayout'.format(type(other).__name__))


    def _transform_indices(self, key):
        """Snaps indices into the GridSpace to the closest coordinate.

        Args:
            key: Tuple index into the GridSpace

        Returns:
            Transformed key snapped to closest numeric coordinates
        """
        ndims = self.ndims
        if all(not (isinstance(el, slice) or callable(el)) for el in key):
            dim_inds = []
            for dim in self.kdims:
                dim_type = self.get_dimension_type(dim)
                if isinstance(dim_type, type) and issubclass(dim_type, Number):
                    dim_inds.append(self.get_dimension_index(dim))
            str_keys = iter(key[i] for i in range(self.ndims)
                            if i not in dim_inds)
            num_keys = []
            if len(dim_inds):
                keys = list({tuple(k[i] if ndims > 1 else k for i in dim_inds)
                             for k in self.keys()})
                q = np.array([tuple(key[i] if ndims > 1 else key for i in dim_inds)])
                idx = np.argmin([np.inner(q - np.array(x), q - np.array(x))
                                 if len(dim_inds) == 2 else np.abs(q-x)
                                     for x in keys])
                num_keys = iter(keys[idx])
            key = tuple(next(num_keys) if i in dim_inds else next(str_keys)
                        for i in range(self.ndims))
        elif any(not (isinstance(el, slice) or callable(el)) for el in key):
            keys = self.keys()
            for i, k in enumerate(key):
                if isinstance(k, slice):
                    continue
                dim_keys = np.array([ke[i] for ke in keys])
                if dim_keys.dtype.kind in 'OSU':
                    continue
                snapped_val = dim_keys[np.argmin(np.abs(dim_keys-k))]
                key = list(key)
                key[i] = snapped_val
            key = tuple(key)
        return key


    def keys(self, full_grid=False):
        """Returns the keys of the GridSpace

        Args:
            full_grid (bool, optional): Return full cross-product of keys

        Returns:
            List of keys
        """
        keys = super().keys()
        if self.ndims == 1 or not full_grid:
            return keys
        dim1_keys = list(OrderedDict.fromkeys(k[0] for k in keys))
        dim2_keys = list(OrderedDict.fromkeys(k[1] for k in keys))
        return [(d1, d2) for d1 in dim1_keys for d2 in dim2_keys]


    @property
    def last(self):
        """
        The last of a GridSpace is another GridSpace
        constituted of the last of the individual elements. To access
        the elements by their X,Y position, either index the position
        directly or use the items() method.
        """
        if self.type == HoloMap:
            last_items = [(k, v.last if isinstance(v, HoloMap) else v)
                          for (k, v) in self.data.items()]
        else:
            last_items = self.data
        return self.clone(last_items)


    def __len__(self):
        """
        The maximum depth of all the elements. Matches the semantics
        of __len__ used by Maps. For the total number of elements,
        count the full set of keys.
        """
        return max([(len(v) if hasattr(v, '__len__') else 1) for v in self.values()] + [0])

    @property
    def shape(self):
        "Returns the 2D shape of the GridSpace as (rows, cols)."
        keys = self.keys()
        if self.ndims == 1:
            return (len(keys), 1)
        return len(set(k[0] for k in keys)), len(set(k[1] for k in keys))

    def decollate(self):
        """Packs GridSpace of DynamicMaps into a single DynamicMap that returns a
        GridSpace

        Decollation allows packing a GridSpace of DynamicMaps into a single DynamicMap
        that returns a GridSpace of simple (non-dynamic) elements. All nested streams
        are lifted to the resulting DynamicMap, and are available in the `streams`
        property.  The `callback` property of the resulting DynamicMap is a pure,
        stateless function of the stream values. To avoid stream parameter name
        conflicts, the resulting DynamicMap is configured with
        positional_stream_args=True, and the callback function accepts stream values
        as positional dict arguments.

        Returns:
            DynamicMap that returns a GridSpace
        """
        from .decollate import decollate
        return decollate(self)

Parameters

Name Type Default Kind
bases Layoutable, UniformNdMapping -

Parameter Details

initial_items: Optional initial collection of items to populate the GridSpace. Can be a list of tuples (key, value) or a dictionary-like structure. Keys should be numeric (float) coordinates.

kdims: List of Dimension objects defining the key dimensions of the grid. Defaults to [Dimension('X'), Dimension('Y')]. Must have 1 or 2 dimensions. These define the coordinate system for the grid.

params: Additional keyword arguments passed to parent class constructors (Layoutable and UniformNdMapping). Can include metadata, labels, and other configuration options.

Return Value

Instantiation returns a GridSpace object that acts as a mapping container. Methods return various types: keys() returns a list of coordinate tuples, shape returns a tuple (rows, cols), last returns a new GridSpace with last elements, decollate() returns a DynamicMap, and __lshift__ returns an AdjointLayout.

Class Interface

Methods

__init__(self, initial_items=None, kdims=None, **params)

Purpose: Initialize a GridSpace with optional initial items and key dimensions

Parameters:

  • initial_items: Optional collection of (key, value) pairs to populate the grid
  • kdims: List of 1-2 Dimension objects defining the coordinate system
  • params: Additional keyword arguments for parent class configuration

Returns: None (constructor)

__lshift__(self, other) -> AdjointLayout

Purpose: Adjoin another object to the GridSpace using the << operator

Parameters:

  • other: ViewableElement, UniformNdMapping, or AdjointLayout to adjoin

Returns: AdjointLayout containing this GridSpace and the adjoined object

_transform_indices(self, key) -> tuple

Purpose: Snap index keys to the closest available coordinates in the grid

Parameters:

  • key: Tuple of indices to transform, may contain numeric values or slices

Returns: Transformed key tuple with numeric values snapped to nearest grid coordinates

keys(self, full_grid=False) -> list

Purpose: Return the keys (coordinates) of elements in the GridSpace

Parameters:

  • full_grid: If True, return full cross-product of all dimension values; if False, return only existing keys

Returns: List of coordinate tuples representing grid positions

last property

Purpose: Get a GridSpace containing the last elements of any HoloMap contents

Returns: New GridSpace with last elements extracted from HoloMaps

__len__(self) -> int

Purpose: Return the maximum depth of all elements in the grid

Returns: Integer representing the maximum length of any element (for HoloMaps) or 1 for simple elements

shape property

Purpose: Get the 2D shape of the GridSpace as (rows, columns)

Returns: Tuple (rows, cols) representing the number of unique values in each dimension

decollate(self) -> DynamicMap

Purpose: Pack a GridSpace of DynamicMaps into a single DynamicMap that returns a GridSpace

Returns: DynamicMap with lifted streams and a pure callback function that returns a GridSpace

Attributes

Name Type Description Scope
kdims param.List List of 1-2 Dimension objects defining the key dimensions. Defaults to [Dimension('X'), Dimension('Y')]. Bounds enforced to (1, 2) dimensions. class
ndims int Number of key dimensions (inherited from parent). Must be 1 or 2 for GridSpace. instance
data OrderedDict Internal storage for grid elements, mapping coordinate tuples to elements (inherited from UniformNdMapping). instance
type type The type of elements stored in the GridSpace (inherited from UniformNdMapping). instance

Dependencies

  • numpy
  • param
  • numbers

Required Imports

import numpy as np
import param
from numbers import Number
from collections import OrderedDict

Conditional/Optional Imports

These imports are only needed under specific conditions:

from .dimension import Dimension, ViewableElement

Condition: Required for dimension and element type definitions

Required (conditional)
from .layout import AdjointLayout, Layoutable

Condition: Required for layout operations and inheritance

Required (conditional)
from .ndmapping import UniformNdMapping

Condition: Required for base mapping functionality

Required (conditional)
from .decollate import decollate

Condition: Only needed when calling the decollate() method

Optional

Usage Example

from holoviews import GridSpace, Dimension
import numpy as np

# Create a 2D GridSpace with custom dimensions
grid = GridSpace(kdims=[Dimension('x'), Dimension('y')])

# Add elements at specific coordinates
for x in [0.0, 0.5, 1.0]:
    for y in [0.0, 0.5, 1.0]:
        grid[(x, y)] = some_element  # e.g., Image, Curve, etc.

# Access elements by coordinate (snaps to nearest)
element = grid[(0.48, 0.52)]  # Will snap to (0.5, 0.5)

# Get grid shape
rows, cols = grid.shape  # Returns (3, 3)

# Get all keys
keys = grid.keys()  # Returns list of (x, y) tuples

# Get full cross-product of keys
full_keys = grid.keys(full_grid=True)

# Adjoin another element
adjoined = grid << other_element

# Get last elements (for HoloMap contents)
last_grid = grid.last

Best Practices

  • GridSpace is limited to 1 or 2 dimensions - attempting to create a GridSpace with more than 2 dimensions will raise an Exception
  • All elements in a GridSpace must be of the same type (enforced by UniformNdMapping parent class)
  • Keys are typically floating-point coordinates, and indexing automatically snaps to the nearest available coordinate
  • Use keys(full_grid=True) to get the full cross-product of dimension values when working with sparse grids
  • The shape property returns (rows, cols) based on unique values in each dimension
  • The __len__ method returns the maximum depth of elements, not the total number of grid cells
  • Use the << operator to adjoin elements and create AdjointLayout compositions
  • The last property is useful for extracting the final frame from HoloMap elements within the grid
  • The decollate() method is used to pack a GridSpace of DynamicMaps into a single DynamicMap for stream handling
  • When indexing with numeric keys, the _transform_indices method automatically finds the closest matching coordinate

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class GridMatrix 71.1% similar

    GridMatrix is a container class for heterogeneous Element types arranged in a grid layout where axes don't represent coordinate space but are used to plot various dimensions against each other.

    From: /tf/active/vicechatdev/patches/spaces.py
  • class HoloMap 59.4% similar

    HoloMap is an n-dimensional mapping container that stores viewable elements or overlays indexed by tuple keys along declared key dimensions, enabling interactive exploration through widgets.

    From: /tf/active/vicechatdev/patches/spaces.py
  • function expand_grid_coords 55.0% similar

    Expands coordinates along a specified dimension of a gridded dataset into an N-dimensional array that matches the full dimensionality of the dataset.

    From: /tf/active/vicechatdev/patches/util.py
  • class Config_v4 41.7% similar

    A configuration class that manages global HoloViews behavior settings, including deprecation warnings, default colormaps, and rendering parameters.

    From: /tf/active/vicechatdev/patches/util.py
  • class DynamicMap 41.5% similar

    A DynamicMap is a type of HoloMap where the elements are dynamically generated by a callable. The callable is invoked with values associated with the key dimensions or with values supplied by stream parameters.

    From: /tf/active/vicechatdev/patches/spaces.py
← Back to Browse