Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modifying cartesian product to allow for >2D input arrays #4482

Merged
merged 3 commits into from
Feb 26, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions pymc3/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,17 @@ def cartesian(*arrays):

Parameters
----------
arrays: 1D array-like
1D arrays where earlier arrays loop more slowly than later ones
arrays: N-D array-like
N-D arrays where earlier arrays loop more slowly than later ones
"""
N = len(arrays)
return np.stack(np.meshgrid(*arrays, indexing="ij"), -1).reshape(-1, N)
arrays_np = [np.asarray(x) for x in arrays]
arrays_2d = [x[:, None] if np.asarray(x).ndim == 1 else x for x in arrays_np]
arrays_integer = [np.arange(len(x)) for x in arrays_2d]
product_integers = np.stack(np.meshgrid(*arrays_integer, indexing="ij"), -1).reshape(-1, N)
return np.concatenate(
[array[product_integers[:, i]] for i, array in enumerate(arrays_2d)], axis=-1
)


def kron_matrix_op(krons, m, op):
Expand Down
17 changes: 17 additions & 0 deletions pymc3/tests/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ def test_cartesian():
np.testing.assert_array_almost_equal(manual_cartesian, auto_cart)


def test_cartesian_2d():
np.random.seed(1)
a = [[1, 2], [3, 4]]
b = [5, 6]
c = [0]
manual_cartesian = np.array(
[
[1, 2, 5, 0],
[1, 2, 6, 0],
[3, 4, 5, 0],
[3, 4, 6, 0],
]
)
auto_cart = cartesian(a, b, c)
np.testing.assert_array_almost_equal(manual_cartesian, auto_cart)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would think that assert_array_equal is sufficient here (no almost). I noticed the other test_cartesian does this so they should both be fixed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point - those assertions have been changed.


def test_kron_dot():
np.random.seed(1)
# Create random matrices
Expand Down