🔍 Code Extractor

function merge_dimensions

Maturity: 51

Merges multiple lists of Dimension objects by combining their values while preserving unique dimensions and maintaining order of first appearance.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
1213 - 1236
Complexity:
moderate

Purpose

This function is designed to consolidate dimension metadata from multiple sources (e.g., different data views or overlays) in the HoloViews library. It handles cases where the same dimension appears in multiple lists with different value sets, merging those values into a single unified dimension while removing duplicates and preserving order. This is particularly useful when combining multiple data structures that share common dimensions but may have different value ranges.

Source Code

def merge_dimensions(dimensions_list):
    """
    Merges lists of fully or partially overlapping dimensions by
    merging their values.

    >>> from holoviews import Dimension
    >>> dim_list = [[Dimension('A', values=[1, 2, 3]), Dimension('B')],
    ...             [Dimension('A', values=[2, 3, 4])]]
    >>> dimensions = merge_dimensions(dim_list)
    >>> dimensions
    [Dimension('A'), Dimension('B')]
    >>> dimensions[0].values
    [1, 2, 3, 4]
    """
    dvalues = defaultdict(list)
    dimensions = []
    for dims in dimensions_list:
        for d in dims:
            dvalues[d.name].append(d.values)
            if d not in dimensions:
                dimensions.append(d)
    dvalues = {k: list(unique_iterator(itertools.chain(*vals)))
               for k, vals in dvalues.items()}
    return [d.clone(values=dvalues.get(d.name, [])) for d in dimensions]

Parameters

Name Type Default Kind
dimensions_list - - positional_or_keyword

Parameter Details

dimensions_list: A list of lists, where each inner list contains Dimension objects. Each Dimension object has a 'name' attribute and a 'values' attribute (which can be a list or None). Dimensions with the same name across different lists will have their values merged. Expected format: [[Dimension(...), Dimension(...)], [Dimension(...), ...], ...]

Return Value

Returns a list of Dimension objects where each unique dimension (by name) appears only once. Each returned Dimension is a clone of the first occurrence with merged values from all occurrences across all input lists. Values are deduplicated while preserving order of first appearance. If a dimension has no values in any list, it will have an empty values list in the result.

Dependencies

  • itertools
  • collections.defaultdict
  • holoviews

Required Imports

import itertools
from collections import defaultdict

Usage Example

from holoviews import Dimension
from collections import defaultdict
import itertools

# Assuming unique_iterator is available in the module
# from your_module import merge_dimensions, unique_iterator

# Create dimension lists with overlapping dimensions
dim_list = [
    [Dimension('A', values=[1, 2, 3]), Dimension('B', values=['x', 'y'])],
    [Dimension('A', values=[2, 3, 4]), Dimension('C', values=[10, 20])],
    [Dimension('A', values=[5]), Dimension('B', values=['y', 'z'])]
]

# Merge the dimensions
merged_dims = merge_dimensions(dim_list)

# Result will have 3 dimensions: A, B, C
# Dimension A will have values: [1, 2, 3, 4, 5]
# Dimension B will have values: ['x', 'y', 'z']
# Dimension C will have values: [10, 20]
print(merged_dims)
for dim in merged_dims:
    print(f"{dim.name}: {dim.values}")

Best Practices

  • Ensure all Dimension objects in the input lists have the 'name', 'values', and 'clone' attributes/methods
  • The function preserves the order of first appearance for both dimensions and their values
  • Dimension equality is determined by the Dimension class's __eq__ method, not just by name
  • Empty or None values lists are handled gracefully and will result in empty lists in the output
  • The function uses 'unique_iterator' which must be available in the module scope - ensure this utility function is imported
  • This function is non-destructive - it clones dimensions rather than modifying them in place
  • Performance consideration: For very large value lists, the deduplication process may be memory-intensive

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function dimension_sort 53.0% similar

    Sorts an ordered dictionary by specified dimension keys, supporting both standard Python tuple sorting and categorical ordering for dimensions with predefined values.

    From: /tf/active/vicechatdev/patches/util.py
  • function merge_options_to_dict 52.4% similar

    Merges a collection of Option objects or partial option dictionaries into a single unified dictionary by iterating through the collection and combining their key-value pairs.

    From: /tf/active/vicechatdev/patches/util.py
  • function unbound_dimensions 51.1% similar

    Filters a list of dimensions (kdims) to return only those that have not been associated with any of the provided streams.

    From: /tf/active/vicechatdev/patches/util.py
  • function dimensioned_streams 49.7% similar

    Filters and returns streams from a DynamicMap that have parameters matching the DynamicMap's key dimensions.

    From: /tf/active/vicechatdev/patches/util.py
  • function drop_streams 48.4% similar

    Filters out dimensioned stream parameters from key dimensions (kdims) and their corresponding keys, returning cleaned dimensions and keys.

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