Created
July 20, 2018 21:02
-
-
Save stsievert/202a07432ce82579a449ad113b33ba4a to your computer and use it in GitHub Desktop.
Sparse and opt-einsum fail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from opt_einsum import contract, helpers, contract_expression | |
import sparse | |
import pytest | |
tests = [ | |
'ab,bc->ca', | |
'abc,bcd,dea', | |
'abc,def->fedcba', | |
# test 'prefer einsum' ops | |
'ijk,ikj', | |
'i,j->ij', | |
'ijk,k->ij', | |
'ac,bc->abc', | |
'aci,bci->abci', | |
] | |
@pytest.mark.parametrize("string", tests) | |
def test_sparse(string): | |
views = helpers.build_views(string) | |
# sparsify views so they don't become dense during contraction | |
for view in views: | |
np.random.seed(42) | |
mask = np.random.choice([False, True], view.shape, True, [0.05, 0.95]) | |
view[mask] = 0 | |
# test with NumPy arrays | |
ein = contract(string, *views, optimize=False, use_blas=False) | |
numpy_ein = np.einsum(string, *views) | |
assert np.allclose(numpy_ein, ein) | |
sparse_views = [sparse.COO.from_numpy(x) for x in views] | |
# pass SparseArrays to contract | |
if string in {'ac,bc->abc', 'aci,bci->abci'}: | |
with pytest.raises(AttributeError, match=("sparse doesn't seem to provide " | |
"the function einsum")): | |
contract(string, *sparse_views, backend='sparse') | |
else: | |
sparse_opt = contract(string, *sparse_views, backend='sparse') | |
assert np.allclose(ein, sparse_opt.todense()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment