From b1d459e0724731b6953bef3d323043b73af42b42 Mon Sep 17 00:00:00 2001 From: beihai <3796320131@qq.com> Date: Thu, 29 Oct 2026 10:46:29 +0800 Subject: [PATCH] [MRG] Fix empty and degenerate EMD inputs without native crashes - ot.emd/ot.emd2: reject a cost matrix with an empty dimension with a ValueError before any conversion, and reject non-finite marginal masses - rescale b per histogram with a safe denominator: when both marginals have a zero total mass, return the exact zero plan with finite potentials instead of NaNs, while a batch keeps solving its non-degenerate histograms - ot.emd_1d: reject an empty support instead of crashing in the 1-D sweep - emd_c/emd_c_sparse/emd_c_lazy: validate marginals, initial potentials, edge array lengths and edge endpoints against the native buffers - EMD_wrap/EMD_wrap_sparse: return before building a graph when one side has no positive weight (OPTIMAL for an empty problem, INFEASIBLE otherwise), which also removes the &weights[0] access on empty vectors - NetworkSimplexSimple: do not read D[0] in setDenseCostMatrix when there is no arc, initialise in_arc, and return from findEnteringArc as soon as no arc has a negative reduced cost - add 11 regression tests covering the empty, zero-mass, degenerate-batch, 1-D and direct native entry points Closes #901 --- RELEASES.md | 1 + ot/lp/EMD_wrapper.cpp | 23 ++++ ot/lp/_network_simplex.py | 49 +++++++- ot/lp/emd_wrap.pyx | 59 ++++++++++ ot/lp/network_simplex_simple.h | 16 ++- ot/lp/solver_1d.py | 8 ++ test/test_ot.py | 206 +++++++++++++++++++++++++++++++++ 7 files changed, 358 insertions(+), 4 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 5d58d2128..f215a9d5f 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -40,6 +40,7 @@ - Raise errors instead of printing a message and returning `None` or dummy values in `ot.datasets.make_data_classif` (unknown dataset), `ot.stochastic.solve_semi_dual_entropic` (unknown method) and `ot.mapping.nearest_brenier_potential_*` (missing CVXPY), and emit warnings instead of prints in `ot.gaussian.bures_barycenter_fixpoint`, `ot.regpath` and `ot.partial.entropic_partial_wasserstein` (PR #888) - Fix docstring errors (wrong or duplicated parameters, typos) and fix the file patterns of the ruff hooks in `.pre-commit-config.yaml` (PR #888) - Fix `arange` in all backends silently ignoring the dtype of `type_as` (and the device in the NumPy, JAX, TensorFlow and CuPy backends), unlike `zeros`, `ones` and `full`. `roll_cols` in `ot.lp.solver_circle` no longer passes a plain Python `int` as `type_as` (PR #903, Issue #864) +- Fix interpreter crashes in the exact OT solvers on degenerate inputs: `ot.emd` and `ot.emd2` reject a cost matrix with an empty dimension with a `ValueError`, marginals with a zero total mass return the exact zero plan with finite dual potentials instead of NaNs, non-finite marginals are rejected, sparse problems without any allowed transport arc report `INFEASIBLE` instead of crashing, and `ot.emd_1d` rejects an empty support with a `ValueError`. The native entry points (`emd_c`, `emd_c_sparse`, `emd_c_lazy`) validate marginal, potential and edge buffers against the problem they solve, and the network simplex pivot rule no longer reads an uninitialised arc index when no entering arc is found (Issue #901) ## 0.9.7.post1 diff --git a/ot/lp/EMD_wrapper.cpp b/ot/lp/EMD_wrapper.cpp index b6a572015..aa06da453 100644 --- a/ot/lp/EMD_wrapper.cpp +++ b/ot/lp/EMD_wrapper.cpp @@ -236,6 +236,14 @@ int EMD_wrap(int n1, int n2, double *X, double *Y, double *D, double *G, } } + // Empty support: there is no arc to transport mass along. When both sides + // are empty the zero plan is the only feasible plan and is optimal, + // otherwise the problem is infeasible. + if (n == 0 || m == 0) { + *cost = 0.0; + return (n == 0 && m == 0) ? OPTIMAL : INFEASIBLE; + } + // Define graph and solver std::vector indI(n), indJ(m); std::vector weights1(n), weights2(m); @@ -345,6 +353,14 @@ int EMD_wrap_sparse( } } + // Empty support: see EMD_wrap. No flow can be extracted, so n_flows_out + // is reset before returning the status of the degenerate problem. + if (n == 0 || m == 0) { + *cost = 0.0; + *n_flows_out = 0; + return (n == 0 && m == 0) ? OPTIMAL : INFEASIBLE; + } + std::vector indI(n); // indI[graph_idx] = original_source_idx std::vector indJ(m); // indJ[graph_idx] = original_target_idx std::vector weights1(n); // Source masses (positive only) @@ -391,6 +407,13 @@ int EMD_wrap_sparse( for (uint64_t k = 0; k < n_edges; k++) { int64_t src_orig = edge_sources[k]; int64_t tgt_orig = edge_targets[k]; + // Reject endpoints outside the marginals: they would index + // source_to_graph / target_to_graph out of bounds. + if (src_orig < 0 || tgt_orig < 0 || + static_cast(src_orig) >= static_cast(n1) || + static_cast(tgt_orig) >= static_cast(n2)) { + return INFEASIBLE; + } int64_t src = source_to_graph[src_orig]; int64_t tgt = target_to_graph[tgt_orig]; diff --git a/ot/lp/_network_simplex.py b/ot/lp/_network_simplex.py index a3f3d548d..9b69368ae 100644 --- a/ot/lp/_network_simplex.py +++ b/ot/lp/_network_simplex.py @@ -35,6 +35,9 @@ def center_ot_dual(alpha0, beta0, a=None, b=None): since :math:`\sum_i a_i=\sum_j b_j` this can be solved by adding/removing a constant from both :math:`\alpha_0` and :math:`\beta_0`. + When both marginals have a zero total mass the constant is undefined and the + potentials are returned unchanged. + .. math:: c &= \frac{\beta_0^T \mathbf{b} - \alpha_0^T \mathbf{a}}{\mathbf{1}^T \mathbf{b} + \mathbf{1}^T \mathbf{a}} @@ -80,7 +83,9 @@ def center_ot_dual(alpha0, beta0, a=None, b=None): # compute constant that balances the weighted sums of the duals ips = nx.sum(b * beta0, axis=0) - nx.sum(a * alpha0, axis=0) denom = nx.sum(a, axis=0) + nx.sum(b, axis=0) - c = ips / denom + # A zero denominator means both marginals are empty: there is nothing to + # balance, and 0/0 would turn the potentials into NaN. + c = ips / nx.where(denom == 0, denom + 1, denom) # update duals alpha = alpha0 + c @@ -171,6 +176,32 @@ def estimate_dual_null_weights(alpha0, beta0, a, b, M): return center_ot_dual(alpha, beta, a, b) +def _check_cost_matrix_shape(n1, n2): + """Raise for a cost matrix with no row or no column.""" + if n1 == 0 or n2 == 0: + raise ValueError( + "The cost matrix must have at least one row and one column, got " + f"shape ({n1}, {n2}). An empty marginal cannot be defaulted to a " + "uniform distribution." + ) + + +def _rescale_target_mass(a, b): + """Rescale ``b`` to the total mass of ``a``, allowing empty marginals. + + A target histogram with a zero total mass cannot be rescaled: it is left + unchanged, so that the solver reports it as infeasible, while the other + histograms of a batch are still solved. When ``a`` has no mass either, the + zero plan is the only feasible plan and is optimal. + """ + mass_a = a.sum(0) + mass_b = b.sum(0, keepdims=True) + if not (np.isfinite(mass_a).all() and np.isfinite(mass_b).all()): + raise ValueError("a and b must have a finite total mass") + + return b * mass_a / np.where(mass_b != 0, mass_b, 1.0) + + def _compute_active_subset(a, b, M, row_mask, col_mask): """Return filtered inputs restricted to the rows/columns with mass.""" need_filter = np.any(~row_mask) or np.any(~col_mask) @@ -259,6 +290,10 @@ def emd( .. note:: An error will be raised if the vectors :math:`\mathbf{a}` and :math:`\mathbf{b}` do not sum to the same value. + .. note:: A cost matrix with no row or no column raises a ``ValueError``. + When both marginals have a zero total mass, the optimal plan is the + zero plan with a zero cost. + Uses the algorithm proposed in :ref:`[1] `. Parameters @@ -388,6 +423,8 @@ def emd( if n1 is None: n1, n2 = M.shape + _check_cost_matrix_shape(n1, n2) + if a is None or len(a) == 0: a = nx.ones((n1,), type_as=type_as) / n1 if b is None or len(b) == 0: @@ -414,7 +451,7 @@ def emd( err_msg="a and b vector must have the same sum", decimal=6, ) - b = b * a.sum() / b.sum() + b = _rescale_target_mass(a, b) asel = a != 0 bsel = b != 0 @@ -567,6 +604,10 @@ def emd2( .. note:: An error will be raised if the vectors :math:`\mathbf{a}` and :math:`\mathbf{b}` do not sum to the same value. + .. note:: A cost matrix with no row or no column raises a ``ValueError``. + When both marginals have a zero total mass, the optimal plan is the + zero plan with a zero cost. + Uses the algorithm proposed in :ref:`[1] `. Parameters @@ -695,6 +736,8 @@ def emd2( if n1 is None: n1, n2 = M.shape + _check_cost_matrix_shape(n1, n2) + # if empty array given then use uniform distributions if a is None or len(a) == 0: a = nx.ones((n1,), type_as=type_as) / n1 @@ -731,7 +774,7 @@ def emd2( err_msg="a and b vector must have the same sum", decimal=6, ) - b = b * a.sum(0) / b.sum(0, keepdims=True) + b = _rescale_target_mass(a, b) asel = a != 0 diff --git a/ot/lp/emd_wrap.pyx b/ot/lp/emd_wrap.pyx index 64905efe9..e1e4bb807 100644 --- a/ot/lp/emd_wrap.pyx +++ b/ot/lp/emd_wrap.pyx @@ -97,6 +97,14 @@ def emd_c(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1, mod cdef int result_code = 0 cdef int nG=0 + if (a.shape[0] != n1 and a.shape[0] != 0) or ( + b.shape[0] != n2 and b.shape[0] != 0 + ): + raise ValueError( + f"Shape mismatch: the cost matrix has shape ({n1}, {n2}) but a has " + f"{a.shape[0]} entries and b has {b.shape[0]}" + ) + cdef double cost=0 cdef np.ndarray[double, ndim=1, mode="c"] alpha=np.zeros(n1) cdef np.ndarray[double, ndim=1, mode="c"] beta=np.zeros(n2) @@ -124,6 +132,12 @@ def emd_c(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1, mod if alpha_init is not None and beta_init is not None: alpha_init_c = np.ascontiguousarray(alpha_init, dtype=np.float64) beta_init_c = np.ascontiguousarray(beta_init, dtype=np.float64) + if alpha_init_c.size != n1 or beta_init_c.size != n2: + raise ValueError( + f"Shape mismatch: the initial potentials have sizes " + f"{alpha_init_c.size} and {beta_init_c.size}, expected {n1} " + f"and {n2}" + ) alpha_init_ptr = alpha_init_c.data beta_init_ptr = beta_init_c.data @@ -175,6 +189,12 @@ def emd_1d_sorted(np.ndarray[double, ndim=1, mode="c"] u_weights, cdef Py_ssize_t n = u_weights.shape[0] cdef Py_ssize_t m = v_weights.shape[0] + if n == 0 or m == 0: + raise ValueError( + "The 1d EMD problem needs at least one source and one target point, " + f"got {n} and {m}" + ) + cdef Py_ssize_t i = 0 cdef double w_i = u_weights[0] cdef Py_ssize_t j = 0 @@ -278,10 +298,28 @@ def emd_c_sparse(np.ndarray[double, ndim=1, mode="c"] a, cdef int n1 = a.shape[0] cdef int n2 = b.shape[0] cdef uint64_t n_edges = edge_sources.shape[0] + cdef uint64_t max_source = 0 + cdef uint64_t max_target = 0 cdef uint64_t n_flows_out = 0 cdef int result_code = 0 cdef double cost = 0 + if edge_targets.shape[0] != n_edges or edge_costs.shape[0] != n_edges: + raise ValueError( + "edge_sources, edge_targets and edge_costs must have the same " + f"length, got {n_edges}, {edge_targets.shape[0]} and " + f"{edge_costs.shape[0]}" + ) + if n_edges > 0: + max_source = edge_sources.max() + max_target = edge_targets.max() + if max_source >= n1 or max_target >= n2: + raise ValueError( + f"Edge endpoints must be smaller than the marginals: got a " + f"maximal source index of {max_source} (n1={n1}) and a maximal " + f"target index of {max_target} (n2={n2})" + ) + # Allocate output arrays (max size = n_edges) cdef np.ndarray[uint64_t, ndim=1, mode="c"] flow_sources = np.zeros(n_edges, dtype=np.uint64) cdef np.ndarray[uint64_t, ndim=1, mode="c"] flow_targets = np.zeros(n_edges, dtype=np.uint64) @@ -292,6 +330,12 @@ def emd_c_sparse(np.ndarray[double, ndim=1, mode="c"] a, cdef double* alpha_init_ptr = NULL cdef double* beta_init_ptr = NULL if alpha_init is not None and beta_init is not None: + if alpha_init.shape[0] != n1 or beta_init.shape[0] != n2: + raise ValueError( + f"Shape mismatch: the initial potentials have sizes " + f"{alpha_init.shape[0]} and {beta_init.shape[0]}, expected " + f"{n1} and {n2}" + ) alpha_init_ptr = alpha_init.data beta_init_ptr = beta_init.data @@ -328,6 +372,15 @@ def emd_c_lazy(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1 cdef uint64_t n_flows_out = 0 cdef uint64_t max_flows_out = n1 + n2 + if (a.shape[0] != n1 and a.shape[0] != 0) or ( + b.shape[0] != n2 and b.shape[0] != 0 + ): + raise ValueError( + f"Shape mismatch: the coordinates have shapes ({n1}, {dim}) and " + f"({n2}, {coords_b.shape[1]}) but a has {a.shape[0]} entries and b " + f"has {b.shape[0]}" + ) + # Validate dimension consistency if coords_b.shape[1] != dim: raise ValueError(f"Coordinate dimension mismatch: coords_a has {dim} dimensions but coords_b has {coords_b.shape[1]}") @@ -356,6 +409,12 @@ def emd_c_lazy(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1 cdef double* alpha_init_ptr = NULL cdef double* beta_init_ptr = NULL if alpha_init is not None and beta_init is not None: + if alpha_init.shape[0] != n1 or beta_init.shape[0] != n2: + raise ValueError( + f"Shape mismatch: the initial potentials have sizes " + f"{alpha_init.shape[0]} and {beta_init.shape[0]}, expected " + f"{n1} and {n2}" + ) alpha_init_ptr = alpha_init.data beta_init_ptr = beta_init.data diff --git a/ot/lp/network_simplex_simple.h b/ot/lp/network_simplex_simple.h index c3b343569..3de1bac98 100644 --- a/ot/lp/network_simplex_simple.h +++ b/ot/lp/network_simplex_simple.h @@ -819,6 +819,10 @@ namespace lemon { cnt = _block_size; } } + // No arc with a negative reduced cost was scanned, so + // _in_arc was never assigned and the current flow is + // optimal. Return before dereferencing it. + if (min >= 0) return false; a=fabs(_pi[_ns.arcSource(_in_arc)])>fabs(_pi[_ns.arcTarget(_in_arc)]) ? fabs(_pi[_ns.arcSource(_in_arc)]):fabs(_pi[_ns.arcTarget(_in_arc)]); a=a>fabs(getCost(_in_arc))?a:fabs(getCost(_in_arc)); if (min >= -EPSILON*a) return false; @@ -928,9 +932,15 @@ namespace lemon { _D_ptr = D; _D_n2 = n2; // Precompute max cost once for reuse in init() + if (_arc_num == 0) { + // No arc means there is no cost to read: D[0] would be out of + // bounds and the scan below would never terminate. + _has_max_cost = false; + return *this; + } _has_max_cost = true; _max_cost = D[0]; - for (ArcsType i = 1; i != _arc_num; ++i) { + for (ArcsType i = 1; i < _arc_num; ++i) { if (D[i] > _max_cost) _max_cost = D[i]; } return *this; @@ -1931,6 +1941,10 @@ namespace lemon { _all_arc_num = f; } + // Initialize in_arc to a valid value: the pivot rule reads it to + // scale the tolerance even when no entering arc has been found. + in_arc = 0; + return true; } diff --git a/ot/lp/solver_1d.py b/ot/lp/solver_1d.py index 802621c14..1464badf3 100644 --- a/ot/lp/solver_1d.py +++ b/ot/lp/solver_1d.py @@ -319,6 +319,14 @@ def emd_1d( + "`['sqeuclidean', 'minkowski', 'cityblock', 'euclidean']`" ) + # an empty support has no transport plan: reject it before the marginal + # defaulting divides by zero + if x_a.shape[0] == 0 or x_b.shape[0] == 0: + raise ValueError( + "The 1d EMD problem needs at least one source and one target point, " + f"got {x_a.shape[0]} and {x_b.shape[0]}" + ) + # if empty array given then use uniform distributions if a is None or a.ndim == 0 or len(a) == 0: a = nx.ones((x_a.shape[0],), type_as=x_a) / x_a.shape[0] diff --git a/test/test_ot.py b/test/test_ot.py index 9b4c9545a..da3a7b0d4 100644 --- a/test/test_ot.py +++ b/test/test_ot.py @@ -266,6 +266,212 @@ def test_emd_empty(): np.testing.assert_allclose(w, 0) +def test_emd_empty_problem_raises(): + # Issue #901: an empty problem used to crash the interpreter + from scipy.sparse import coo_matrix + + for shape in [(0, 0), (0, 3), (3, 0)]: + with pytest.raises(ValueError, match="cost matrix"): + ot.emd([], [], np.zeros(shape)) + with pytest.raises(ValueError, match="cost matrix"): + ot.emd2([], [], np.zeros(shape)) + with pytest.raises(ValueError, match="cost matrix"): + ot.emd([], [], coo_matrix(shape)) + + +def test_emd_zero_mass(): + # Issue #901: no mass on either side, the zero plan is the only feasible + # plan and is optimal, with finite and dual feasible potentials + rng = np.random.RandomState(0) + for n1, n2 in [(5, 3), (3, 5)]: + for M in [rng.rand(n1, n2), rng.randn(n1, n2)]: + G, log = ot.emd(np.zeros(n1), np.zeros(n2), M, log=True) + + np.testing.assert_array_equal(G, np.zeros((n1, n2))) + assert log["cost"] == 0 + assert np.all(np.isfinite(log["u"])) + assert np.all(np.isfinite(log["v"])) + assert np.all(log["u"][:, None] + log["v"][None, :] <= M + 1e-12) + + w, log2 = ot.emd2( + np.zeros(n1), np.zeros(n2), M, log=True, return_matrix=True + ) + assert w == 0 + assert np.all(np.isfinite(log2["u"])) + assert np.all(np.isfinite(log2["v"])) + np.testing.assert_array_equal(log2["G"], np.zeros((n1, n2))) + + +def test_emd_zero_mass_sparse(): + # the sparse solver leaves the potentials of zero-weight nodes at zero, so + # only finiteness is required here (see the emd_c docstring) + from scipy.sparse import coo_matrix + + M = coo_matrix(np.arange(15, dtype=float).reshape(5, 3)) + G, log = ot.emd(np.zeros(5), np.zeros(3), M, log=True) + + assert G.shape == (5, 3) + assert G.nnz == 0 + assert log["cost"] == 0 + assert np.all(np.isfinite(log["u"])) + assert np.all(np.isfinite(log["v"])) + + +def test_emd_zero_mass_one_sided(): + # a zero-mass b cannot be rescaled onto a positive-mass a: the column is + # reported infeasible (as before) but without NaNs or a native crash + M = np.ones((3, 2)) + with pytest.warns(UserWarning, match="infeasible"): + G, log = ot.emd(np.ones(3) / 3, np.zeros(2), M, log=True, check_marginals=False) + + np.testing.assert_array_equal(G, np.zeros((3, 2))) + assert np.all(np.isfinite(log["u"])) + assert np.all(np.isfinite(log["v"])) + + # non-finite marginals cannot be rescaled either + with pytest.raises(ValueError, match="finite"): + ot.emd( + np.array([np.nan, 1.0]), + np.array([0.5, 0.5]), + np.ones((2, 2)), + check_marginals=False, + ) + + +def test_emd2_batch_with_empty_histogram(): + # an empty histogram of a batch is infeasible, the other ones are solved + M = np.array([[0.0, 1.0, 2.0], [1.0, 0.0, 3.0]]) + a = np.array([0.5, 0.5]) + b = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]]) + + with pytest.warns(UserWarning, match="infeasible"): + res = ot.emd2(a, b, M, check_marginals=False) + + np.testing.assert_allclose(res, [0.5, 0.0]) + + +def test_emd_1d_empty_support(): + # emd_1d used to segfault when one of the two supports was empty + with pytest.raises(ValueError, match="at least one source"): + ot.emd_1d(np.zeros(0), np.zeros(1), np.zeros(0), np.zeros(1)) + with pytest.raises(ValueError, match="at least one source"): + ot.emd_1d(np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0)) + + +def test_emd_sparse_no_transport_edges(): + # no stored entry means that no transport is allowed: the problem is + # infeasible and must be reported as such (it used to crash the interpreter) + from scipy.sparse import coo_matrix + + M = coo_matrix((5, 3), dtype=float) + with pytest.warns(UserWarning, match="infeasible"): + G, log = ot.emd(np.ones(5) / 5, np.ones(3) / 3, M, log=True) + + assert G.shape == (5, 3) + assert G.nnz == 0 + assert "infeasible" in log["warning"] + + +def test_emd_c_empty_support(): + # the native entry point is safe on an empty problem: it returns the + # (unique) empty plan and a zero cost instead of reading out of bounds + from ot.lp.emd_wrap import check_result, emd_c + + G, cost, u, v, result_code = emd_c( + np.zeros(0), np.zeros(0), np.zeros((0, 0)), 100000, 1 + ) + + assert G.shape == (0, 0) + assert cost == 0 + assert u.shape == (0,) and v.shape == (0,) + assert check_result(result_code) is None # OPTIMAL + + +def test_emd_c_shape_mismatch(): + # buffers shorter than the cost matrix used to be read out of bounds + from ot.lp.emd_wrap import emd_c + + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c(np.zeros(2), np.zeros(3), np.zeros((5, 3)), 100000, 1) + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c(np.ones(5) / 5, np.zeros(2), np.zeros((5, 3)), 100000, 1) + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c( + np.ones(5) / 5, + np.ones(3) / 3, + np.zeros((5, 3)), + 100000, + 1, + alpha_init=np.zeros(1), + beta_init=np.zeros(3), + ) + + +def test_emd_c_sparse_invalid_edges(): + from ot.lp.emd_wrap import emd_c_sparse + + a = np.ones(3) / 3 + b = np.ones(3) / 3 + cost = np.array([0.0, 1.0]) + # endpoints outside the marginals used to index internal maps out of bounds + with pytest.raises(ValueError, match="Edge endpoints"): + emd_c_sparse( + a, + b, + np.array([0, 7], dtype=np.uint64), + np.array([0, 1], dtype=np.uint64), + cost, + 100000, + ) + with pytest.raises(ValueError, match="Edge endpoints"): + emd_c_sparse( + a, + b, + np.array([0, 1], dtype=np.uint64), + np.array([0, 7], dtype=np.uint64), + cost, + 100000, + ) + with pytest.raises(ValueError, match="same length"): + emd_c_sparse( + a, + b, + np.array([0], dtype=np.uint64), + np.array([0, 1], dtype=np.uint64), + cost, + 100000, + ) + + +def test_emd_c_lazy_shape_mismatch(): + # the lazy entry point used to read the marginals and the coordinates out + # of bounds when their lengths did not match + from ot.lp.emd_wrap import emd_c_lazy + + coords_a = np.zeros((5, 2)) + coords_b = np.zeros((3, 2)) + + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c_lazy( + np.ones(1), np.ones(3) / 3, coords_a, coords_b, "sqeuclidean", 100000 + ) + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c_lazy( + np.ones(5) / 5, np.ones(1), coords_a, coords_b, "sqeuclidean", 100000 + ) + with pytest.raises(ValueError, match="Shape mismatch"): + emd_c_lazy( + np.ones(5) / 5, + np.ones(3) / 3, + coords_a, + coords_b, + "sqeuclidean", + 100000, + alpha_init=np.zeros(1), + beta_init=np.zeros(3), + ) + + def test_emd2_multi(): n = 500 # nb bins