function cartesian_product
Computes the Cartesian product of multiple 1D arrays, returning expanded array views for each dimension with optional flattening and copying.
/tf/active/vicechatdev/patches/util.py
1921 - 1931
moderate
Purpose
This function efficiently generates the Cartesian product of multiple 1D arrays using NumPy's broadcasting capabilities. It's useful for creating all possible combinations of elements from multiple arrays, commonly needed in grid generation, parameter sweeps, combinatorial operations, and multi-dimensional coordinate systems. The function leverages array views for memory efficiency and provides options to flatten results or create independent copies.
Source Code
def cartesian_product(arrays, flat=True, copy=False):
"""
Efficient cartesian product of a list of 1D arrays returning the
expanded array views for each dimensions. By default arrays are
flattened, which may be controlled with the flat flag. The array
views can be turned into regular arrays with the copy flag.
"""
arrays = np.broadcast_arrays(*np.ix_(*arrays))
if flat:
return tuple(arr.flatten() if copy else arr.flat for arr in arrays)
return tuple(arr.copy() if copy else arr for arr in arrays)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
arrays |
- | - | positional_or_keyword |
flat |
- | True | positional_or_keyword |
copy |
- | False | positional_or_keyword |
Parameter Details
arrays: A list or iterable of 1D NumPy arrays for which to compute the Cartesian product. Each array represents one dimension, and the function will generate all possible combinations of elements across these arrays.
flat: Boolean flag (default: True) that controls whether the output arrays are flattened to 1D. When True, returns flattened views/arrays. When False, returns multi-dimensional arrays with the full broadcast shape.
copy: Boolean flag (default: False) that controls whether to return independent copies of the arrays or memory-efficient views. When True, creates actual array copies. When False, returns array views (flat views if flat=True, or broadcast views if flat=False).
Return Value
Returns a tuple of NumPy arrays, one for each input array dimension. The length of the tuple equals the number of input arrays. Each returned array contains the expanded values for that dimension across the Cartesian product. If flat=True (default), each array is 1D with length equal to the product of all input array lengths. If flat=False, arrays have the full broadcast shape. If copy=True, returns independent array copies; if copy=False (default), returns memory-efficient views.
Dependencies
numpy
Required Imports
import numpy as np
Usage Example
import numpy as np
def cartesian_product(arrays, flat=True, copy=False):
arrays = np.broadcast_arrays(*np.ix_(*arrays))
if flat:
return tuple(arr.flatten() if copy else arr.flat for arr in arrays)
return tuple(arr.copy() if copy else arr for arr in arrays)
# Example 1: Basic usage with two arrays
x = np.array([1, 2, 3])
y = np.array([10, 20])
result = cartesian_product([x, y])
print("X coordinates:", result[0]) # [1, 1, 2, 2, 3, 3]
print("Y coordinates:", result[1]) # [10, 20, 10, 20, 10, 20]
# Example 2: Three dimensions
a = np.array([1, 2])
b = np.array([10, 20])
c = np.array([100, 200])
result = cartesian_product([a, b, c])
print("Total combinations:", len(result[0])) # 8 (2*2*2)
# Example 3: Non-flattened output
result_unflat = cartesian_product([x, y], flat=False)
print("Shape:", result_unflat[0].shape) # (3, 2)
# Example 4: With copy for independent arrays
result_copy = cartesian_product([x, y], copy=True)
print("Type:", type(result_copy[0])) # numpy.ndarray (actual array, not view)
Best Practices
- Input arrays should be 1D NumPy arrays for correct behavior; multi-dimensional inputs may produce unexpected results
- Use flat=True (default) when you need simple 1D arrays of all combinations, which is most common for iteration or data processing
- Use flat=False when you need to preserve the multi-dimensional structure, useful for grid-based operations or visualization
- Keep copy=False (default) for memory efficiency when working with large arrays, as views don't duplicate data
- Set copy=True only when you need independent arrays that won't be affected by changes to the original data or when the views will outlive the source arrays
- Be aware that the output size grows multiplicatively: for arrays of lengths n1, n2, ..., nk, the output will have n1*n2*...*nk elements per dimension
- For very large Cartesian products, consider memory constraints as the result size can grow exponentially with the number of input arrays
- This function is more memory-efficient than using nested loops or itertools.product when working with NumPy arrays
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function cross_index 66.0% similar
-
function expand_grid_coords 60.6% similar
-
function max_extents 39.2% similar
-
class GridMatrix 38.7% similar
-
function asarray 38.6% similar