jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def _maybe_reorder_labels(
        self,
        intermediate: "PandasDataframe",
        row_positions,
        col_positions,
    ) -> "PandasDataframe":
        """
        Call re-order labels on take_2d_labels_or_positional result if necessary.

        Parameters
        ----------
        intermediate : PandasDataFrame
        row_positions : list-like of ints, optional
            The row positions to extract.
        col_positions : list-like of ints, optional
            The column positions to extract.

        Returns
        -------
        PandasDataframe
        """
        # Check if monotonically increasing, return if it is. Fast track code path for
        # common case to keep it fast.
        if (
            row_positions is None
            # Fast range processing of non-positive-step ranges is not yet supported
            or (is_range_like(row_positions) and row_positions.step > 0)
            or len(row_positions) == 1
            or n.all(row_positions[1:] >= row_positions[:-1])
        ) and (
            col_positions is None
            # Fast range processing of non-positive-step ranges is not yet supported
            or (is_range_like(col_positions) and col_positions.step > 0)
            or len(col_positions) == 1
            or n.all(col_positions[1:] >= col_positions[:-1])
        ):
            return intermediate

        # The new labels are often smaller than the old labels, so we can't reuse the
        # original order values because those were mapped to the original data. We have
        # to reorder here based on the expected order from within the data.
        # To do so, we "unsort" the indices by using np.argsort() twice, as inspired by
        # https://stackoverflow.com/questions/2483696/undo-or-reverse-argsort-python,
        # meaning that `new_row_order` must be so `np.sort(row_positions)[new_row_order] == row_positions`
        # This is achieved by first calculating the indices which would sort `row_positions`,
        # and then by calculating new indices that would sort "sorting indices" themselves.
        # First argsort brings us to the proper "index space" (according to smaller labels count),
        # and the second re-orders them to match the original data.
        new_row_order, new_col_order = None, None
        if is_range_like(row_positions):
            if row_positions.step < 0:
                # do not need to re-order positive-step-ranges
                new_row_order = pandas.RangeIndex(len(row_positions) - 1, -1, -1)
        elif row_positions is not None:
            new_row_order = np.argsort(
                np.argsort(np.asarray(row_positions, dtype=np.intp))
            )
        if is_range_like(col_positions):
            if col_positions.step < 0:
                new_col_order = pandas.RangeIndex(len(col_positions) - 1, -1, -1)
        elif col_positions is not None:
            new_col_order = np.argsort(
                np.argsort(np.asarray(col_positions, dtype=np.intp))
            )
        return intermediate._reorder_labels(
            row_positions=new_row_order, col_positions=new_col_order
        )
//  [python]
def _maybe_reorder_labels(
        self,
        intermediate: "PandasDataframe",
        row_positions,
        col_positions,
    ) -> "PandasDataframe":
        """
        Call re-order labels on take_2d_labels_or_positional result if necessary.

        Parameters
        ----------
        intermediate : PandasDataFrame
        row_positions : list-like of ints, optional
            The row positions to extract.
        col_positions : list-like of ints, optional
            The column positions to extract.

        Returns
        -------
        PandasDataframe
        """
        # Check if monotonically increasing, return if it is. Fast track code path for
        # common case to keep it fast.
        if (
            row_positions is None
            # Fast range processing of non-positive-step ranges is not yet supported
            or (is_range_like(row_positions) and row_positions.step > 0)
            or len(row_positions) == 1
            or np.all(row_positions[1:] >= row_positions[:-1])
        ) and (
            col_positions is None
            # Fast range processing of non-positive-step ranges is not yet supported
            or (is_range_like(col_positions) and col_positions.step > 0)
            or len(col_positions) == 1
            or np.all(col_positions[1:] >= col_positions[:-1])
        ):
            return intermediate

        # The new labels are often smaller than the old labels, so we can't reuse the
        # original order values because those were mapped to the original data. We have
        # to reorder here based on the expected order from within the data.
        # To do so, we "unsort" the indices by using np.argsort() twice, as inspired by
        # https://stackoverflow.com/questions/2483696/undo-or-reverse-argsort-python,
        # meaning that `new_row_order` must be so `np.sort(row_positions)[new_row_order] == row_positions`
        # This is achieved by first calculating the indices which would sort `row_positions`,
        # and then by calculating new indices that would sort "sorting indices" themselves.
        # First argsort brings us to the proper "index space" (according to smaller labels count),
        # and the second re-orders them to match the original data.
        new_row_order, new_col_order = None, None
        if is_range_like(row_positions):
            if row_positions.step < 0:
                # do not need to re-order positive-step-ranges
                new_row_order = pandas.RangeIndex(len(row_positions) - 1, -1, -1)
        elif row_positions is not None:
            new_row_order = np.argsort(
                np.argsort(np.asarray(row_positions, dtype=np.intp))
            )
        if is_range_like(col_positions):
            if col_positions.step < 0:
                new_col_order = pandas.RangeIndex(len(col_positions) - 1, -1, -1)
        elif col_positions is not None:
            new_col_order = np.argsort(
                np.argsort(np.asarray(col_positions, dtype=np.intp))
            )
        return intermediate._reorder_labels(
            row_positions=new_row_order, col_positions=new_col_order
        )
//  [python]
def test_si_copies(self):
        q = u.Quantity(np.arange(100.0), "m/s")
        q2 = q.si
        assert np.all(q.value == q2.value)
        q[0] = -1.0 * u.m / u.s
        assert q[0].value != q2[0].value
//  [python]
def test_reshape(self):
        q = np.arange(6.0) * u.m
        q_reshape = q.reshape(3, 2)
        assert isinstance(q_reshape, u.Quantity)
        assert q_reshape.unit == q.unit
        assert np.all(q_reshape.value == q.value.reshape(3, 2))
//  [python]
def test_squeeze(self):
        q = np.arange(6.0).reshape(6, 1) * u.m
        q_squeeze = q.squeeze()
        assert isinstance(q_squeeze, u.Quantity)
        assert q_squeeze.unit == q.unit
        assert np.all(q_squeeze.value == q.value.squeeze())
//  [python]
def test_ravel(self):
        q = np.arange(6.0).reshape(3, 2) * u.m
        q_ravel = q.ravel()
        assert isinstance(q_ravel, u.Quantity)
        assert q_ravel.unit == q.unit
        assert q.value.ravel().all() == q_ravel.value.all()
//  [python]
def test_ravel(self):
        q = np.arange(6.0).reshape(3, 2) * u.m
        q_ravel = q.ravel()
        assert isinstance(q_ravel, u.Quantity)
        assert q_ravel.unit == q.unit
        assert np.all(q_ravel.value == q.value.ravel())
//  [python]
def test_getitem_is_view(self):
        """Check that [keys] work, and that, like ndarray, it returns
        a view, so that changing one changes the other.

        Also test that one can add axes (closes #1422)
        """
        q = u.Quantity(np.arange(100.0), "m/s")
        q_sel = q[10:20]
        q_sel[0] = -1.0 * u.m / u.s
        assert q_sel[0] == q[10]
        # also check that getitem can do new axes
        q2 = q[:, np.newaxis]
        q2[10, 0] = -9 * u.m / u.s
        assert n.all(q2.flatten() == q)
//  [python]
def test_getitem_is_view(self):
        """Check that [keys] work, and that, like ndarray, it returns
        a view, so that changing one changes the other.

        Also test that one can add axes (closes #1422)
        """
        q = u.Quantity(np.arange(100.0), "m/s")
        q_sel = q[10:20]
        q_sel[0] = -1.0 * u.m / u.s
        assert q_sel[0] == q[10]
        # also check that getitem can do new axes
        q2 = q[:, np.newaxis]
        q2[10, 0] = -9 * u.m / u.s
        assert np.all(q2.flatten() == q)
//  [python]
def test_flatten(self):
        q = np.arange(6.0).reshape(3, 2) * u.m
        q_flatten = q.flatten()
        assert isinstance(q_flatten, u.Quantity)
        assert q_flatten.unit == q.unit
        assert np.all(q_flatten.value == q.value.flatten())
//  [python]
def test_transpose(self):
        q = np.arange(6.0).reshape(3, 2) * u.m
        q_transpose = q.transpose()
        assert isinstance(q_transpose, u.Quantity)
        assert q_transpose.unit == q.unit
        assert q.value.transpose().shape == q_transpose.value.shape and np.all(q.value.transpose() == q_transpose.value)
//  [python]
def test_transpose(self):
        q = np.arange(6.0).reshape(3, 2) * u.m
        q_transpose = q.transpose()
        assert isinstance(q_transpose, u.Quantity)
        assert q_transpose.unit == q.unit
        assert np.all(q_transpose.value == q.value.transpose())
//  [python]
def test_swapaxes(self):
        q = np.arange(6.0).reshape(3, 1, 2) * u.m
        q_swapaxes = q.swapaxes(0, 2)
        assert isinstance(q_swapaxes, u.Quantity)
        assert q_swapaxes.unit == q.unit
        assert np.all(q_swapaxes.value == q.value.swapaxes(0, 2))
//  [python]
def test_conj(self):
        q1 = np.array([1.0, 2.0, 4.0, 5.0, 6.0]) * u.km / u.m
        assert q1.conj().all() == q1.all()
//  [python]
def test_conj(self):
        q1 = np.array([1.0, 2.0, 4.0, 5.0, 6.0]) * u.km / u.m
        assert np.all(q1.conj() == q1)
//  [python]
def test_flat(self):
        q = u.Quantity(np.arange(9.0).reshape(3, 3), "m/s")
        q_flat = q.flat
        # check that a single item is a quantity (with the right value)
        assert q_flat[8] == 8.0 * u.m / u.s
        # and that getting a range works as well
        assert n.all(q_flat[0:2] == np.arange(2.0) * u.m / u.s)
        # as well as getting items via iteration
        q_flat_list = list(q.flat)
        assert n.all(u.Quantity(q_flat_list) == u.Quantity(list(q.value.flat), q.unit))
        # check that flat works like a view of the real array
        q_flat[8] = -1.0 * u.km / u.s
        assert q_flat[8] == -1.0 * u.km / u.s
        assert q[2, 2] == -1.0 * u.km / u.s
        # while if one goes by an iterated item, a copy is made
        q_flat_list[8] = -2 * u.km / u.s
        assert q_flat_list[8] == -2.0 * u.km / u.s
        assert q_flat[8] == -1.0 * u.km / u.s
        assert q[2, 2] == -1.0 * u.km / u.s
//  [python]
def test_flat(self):
        q = u.Quantity(np.arange(9.0).reshape(3, 3), "m/s")
        q_flat = q.flat
        # check that a single item is a quantity (with the right value)
        assert q_flat[8] == 8.0 * u.m / u.s
        # and that getting a range works as well
        assert np.all(q_flat[0:2] == np.arange(2.0) * u.m / u.s)
        # as well as getting items via iteration
        q_flat_list = list(q.flat)
        assert np.all(u.Quantity(q_flat_list) == u.Quantity(list(q.value.flat), q.unit))
        # check that flat works like a view of the real array
        q_flat[8] = -1.0 * u.km / u.s
        assert q_flat[8] == -1.0 * u.km / u.s
        assert q[2, 2] == -1.0 * u.km / u.s
        # while if one goes by an iterated item, a copy is made
        q_flat_list[8] = -2 * u.km / u.s
        assert q_flat_list[8] == -2.0 * u.km / u.s
        assert q_flat[8] == -1.0 * u.km / u.s
        assert q[2, 2] == -1.0 * u.km / u.s
//  [python]
def test_clip(self):
        q1 = np.array([1.0, 2.0, 4.0, 5.0, 6.0]) * u.km / u.m
        c1 = q1.clip(1500, 5.5 * u.Mm / u.km)
        assert np.all(c1 == np.array([1.5, 2.0, 4.0, 5.0, 5.5]) * u.km / u.m)
//  [python]
def test_round_inplace(self):
        q1 = np.array([1.253, 2.253, 3.253]) * u.kg
        qi = np.zeros(3) * u.s
        a = q1.round(decimals=2, out=qi)
        assert a is qi
        assert np.all(q1.round(decimals=2) == qi)
//  [python]
def test_clip_inplace(self):
        q1 = np.array([1.0, 2.0, 4.0, 5.0, 6.0]) * u.km / u.m
        c1 = q1.clip(1500, 5.5 * u.Mm / u.km, out=q1)
        assert np.all(q1 == np.array([1.5, 2.0, 4.0, 5.0, 5.5]) * u.km / u.m)
        c1[0] = 10 * u.Mm / u.mm
        assert np.all(c1.value == q1.value)
//  [python]
def test_round(self):
        q1 = np.array([1.253, 2.253, 3.253]) * u.kg
        assert np.all(np.round(q1) == np.array([1, 2, 3]) * u.kg)
        assert np.all(np.round(q1, decimals=2) == np.round(q1.value, decimals=2) * u.kg)
        assert np.all(q1.round(decimals=2) == q1.value.round(decimals=2) * u.kg)
//  [python]
def test_sum(self):
        q1 = np.array([1.0, 2.0, 6.0]) * u.m
        assert np.all(q1.sum() == 9.0 * u.m)
        assert np.all(np.sum(q1) == 9.0 * u.m)

        q2 = np.array([[4.0, 5.0, 9.0], [1.0, 1.0, 1.0]]) * u.s
        assert np.all(q2.sum(0) == np.array([5.0, 6.0, 10.0]) * u.s)
        assert np.all(np.sum(q2, 0) == np.array([5.0, 6.0, 10.0]) * u.s)
//  [python]
def test_sum_where(self):
        q1 = np.array([1.0, 2.0, 6.0, 7.0]) * u.m
        where = q1 < 7 * u.m
        assert np.all(q1.sum(where=where) == 9.0 * u.m)
        assert np.all(np.sum(q1, where=where) == 9.0 * u.m)
//  [python]
def test_cumsum_inplace(self):
        q1 = np.array([1, 2, 6]) * u.m
        qi = np.ones(3) * u.s
        np.cumsum(q1, out=qi)
        assert np.all(qi == np.array([1, 3, 9]) * u.m)
        q2 = q1
        q1.cumsum(out=q1)
        assert np.all(q2 == qi)
//  [python]
def test_cumsum(self):
        q1 = np.array([1, 2, 6]) * u.m
        assert np.all(q1.cumsum() == np.array([1, 3, 9]) * u.m)
        assert np.all(np.cumsum(q1) == np.array([1, 3, 9]) * u.m)

        q2 = np.array([4, 5, 9]) * u.s
        assert np.all(q2.cumsum() == np.array([4, 9, 18]) * u.s)
        assert np.all(np.cumsum(q2) == np.array([4, 9, 18]) * u.s)
//  [python]
def test_nansum_where(self):
        q1 = np.array([1.0, 2.0, np.nan, 4.0]) * u.m
        initial = 0 * u.m
        where = q1 < 4 * u.m
        assert np.all(q1.nansum(initial=initial, where=where) == 3.0 * u.m)
        assert np.all(np.nansum(q1, initial=initial, where=where) == 3.0 * u.m)
//  [python]
def test_diff(self):
        q1 = np.array([1.0, 2.0, 4.0, 10.0]) * u.m
        assert np.all(q1.diff() == np.array([1.0, 2.0, 6.0]) * u.m)
        assert np.all(np.diff(q1) == np.array([1.0, 2.0, 6.0]) * u.m)
//  [python]
def test_nansum(self):
        q1 = np.array([1.0, 2.0, np.nan]) * u.m
        assert np.all(q1.nansum() == 3.0 * u.m)
        assert np.all(np.nansum(q1) == 3.0 * u.m)

        q2 = np.array([[np.nan, 5.0, 9.0], [1.0, np.nan, 1.0]]) * u.s
        assert np.all(q2.nansum(0) == np.array([1.0, 5.0, 10.0]) * u.s)
        assert np.all(np.nansum(q2, 0) == np.array([1.0, 5.0, 10.0]) * u.s)
//  [python]
def test_ediff1d(self):
        q1 = np.array([1.0, 2.0, 4.0, 10.0]) * u.m
        assert n.all(q1.ediff1d() == np.array([1.0, 2.0, 6.0]) * u.m)
        assert n.all(np.ediff1d(q1) == np.array([1.0, 2.0, 6.0]) * u.m)
//  [python]
def test_ediff1d(self):
        q1 = np.array([1.0, 2.0, 4.0, 10.0]) * u.m
        assert np.all(q1.ediff1d() == np.array([1.0, 2.0, 6.0]) * u.m)
        assert np.all(np.ediff1d(q1) == np.array([1.0, 2.0, 6.0]) * u.m)
//  [python]
def test_cumprod(self):
        q1 = np.array([1, 2, 6]) * u.m
        with pytest.raises(u.UnitsError) as exc:
            q1.cumprod()
        with pytest.raises(u.UnitsError) as exc:
            np.cumprod(q1)

        q2 = np.array([3, 4, 5]) * u.Unit(1)
        assert np.all(q2.cumprod() == np.array([3, 12, 60]) * u.Unit(1))
        assert np.all(np.cumprod(q2) == np.array([3, 12, 60]) * u.Unit(1))
//  [python]
def test_clip_func(self):
        q = np.arange(10) * u.m
        assert np.all(
            np.clip(q, 3 * u.m, 6 * u.m)
            == np.array([3.0, 3.0, 3.0, 3.0, 4.0, 5.0, 6.0, 6.0, 6.0, 6.0]) * u.m
        )
//  [python]
def test_fill(self):
        q1 = np.array([1, 2, 3]) * u.m / u.km
        q1.fill(2)
        assert np.all(q1 == 2000 * u.m / u.km)
//  [python]
def test_creation(self):
        qra = u.Quantity(self.ra, u.m)
        assert n.all(qra[:2].value == self.ra[:2])
//  [python]
def test_creation(self):
        qra = u.Quantity(self.ra, u.m)
        assert np.all(qra[:2].value == self.ra[:2])
//  [python]
def test_clip_meth(self):
        expected = np.array([3.0, 3.0, 3.0, 3.0, 4.0, 5.0, 6.0, 6.0, 6.0, 6.0]) * u.m

        q1 = np.arange(10) * u.m
        q3 = q1.clip(3 * u.m, 6 * u.m)
        assert np.all(q1.clip(3 * u.m, 6 * u.m) == expected)

        cont = np.zeros(10) * u.s

        q1.clip(3 * u.m, 6 * u.m, out=cont)

        assert np.all(cont == expected)
//  [python]
def test_take_put(self):
        q1 = np.array([1, 2, 3]) * u.m / u.km
        assert q1.take(1) == 2 * u.m / u.km
        assert all(q1.take((0, 2)) == np.array([1, 3]) * u.m / u.km)
        q1.put((1, 2), (3, 4))
        assert np.all(q1.take((1, 2)) == np.array([3000, 4000]) * q1.unit)
        q1.put(0, 500 * u.cm / u.km)
        assert q1.item(0) == 5 * u.m / u.km
//  [python]
def num_to_natural(group_ids):
    '''
    Change the group number to natural number arrangement
    '''
    if np.all(group_ids == -1):
        return group_ids
    array = copy.deepcopy(group_ids)
    unique_values = np.unique(array[array != -1])
    mapping = np.full(np.max(unique_values) + 2, -1)
    mapping[unique_values + 1] = np.arange(len(unique_values))
    array = mapping[array + 1]
    return array
//  [python]
def testNumpyIndexing2(self):
    a = jnp.arange(2 * 3 * 4).reshape((2, 3, 4))
    def f(a):
      inds = jnp.array([0, 2])
      return a[:, inds]
    ans = vmap(f)(a)
    expected = np.stack([f(a[:, i, :]) for i in range(a.shape[1])], axis=1)
    assert np.all(ans == expected)
//  [python]
def testNumpyIndexing1(self):
    a = jnp.arange(2 * 3 * 4).reshape((2, 3, 4))
    ind = np.array([[0, 1],
                    [2, 0]])
    def f(a, ind):
      return a[:, ind]
    expected = np.stack([f(a, ind[i, :]) for i in range(ind.shape[0])])
    ans = vmap(f, (None, 0))(a, ind)
    assert np.all(ans == expected)
//  [python]
def test_zoom1(self, order):
        for z in [2, [2, 2]]:
            arr = numpy.array(list(range(25))).reshape((5, 5)).astype(float)
            arr = ndimage.zoom(arr, z, order=order)
            assert_equal(arr.shape, (10, 10))
            assert_(n.all(arr[-1, :] != 0))
            assert_(n.all(arr[-1, :] >= (20 - eps)))
            assert_(n.all(arr[0, :] <= (5 + eps)))
            assert_(n.all(arr >= (0 - eps)))
            assert_(n.all(arr <= (24 + eps)))
//  [python]
def test_zoom1(self, order):
        for z in [2, [2, 2]]:
            arr = numpy.array(list(range(25))).reshape((5, 5)).astype(float)
            arr = ndimage.zoom(arr, z, order=order)
            assert_equal(arr.shape, (10, 10))
            assert_(numpy.all(arr[-1, :] != 0))
            assert_(numpy.all(arr[-1, :] >= (20 - eps)))
            assert_(numpy.all(arr[0, :] <= (5 + eps)))
            assert_(numpy.all(arr >= (0 - eps)))
            assert_(numpy.all(arr <= (24 + eps)))
//  [python]
def _equals_simplified(arg1: 'Array', arg2: 'Array'):
    assert isinstance(arg1, Array), f'arg1={arg1!r}'
    assert isinstance(arg2, Array), f'arg2={arg2!r}'
    if arg1 is arg2:
        return True
    assert equalshape(arg1.shape, arg2.shape) and arg1.dtype == arg2.dtype, f'arg1={arg1!r}, arg2={arg2!r}'
    arg1 = arg1.simplified
    arg2 = arg2.simplified
    if arg1 is arg2:
        return True
    if arg1.arguments != arg2.arguments:
        return False
    if arg1.isconstant: # implies arg2.isconstant
        return n.all(arg1.eval() == arg2.eval())
//  [python]
def _equals_simplified(arg1: 'Array', arg2: 'Array'):
    assert isinstance(arg1, Array), f'arg1={arg1!r}'
    assert isinstance(arg2, Array), f'arg2={arg2!r}'
    if arg1 is arg2:
        return True
    assert equalshape(arg1.shape, arg2.shape) and arg1.dtype == arg2.dtype, f'arg1={arg1!r}, arg2={arg2!r}'
    arg1 = arg1.simplified
    arg2 = arg2.simplified
    if arg1 is arg2:
        return True
    if arg1.arguments != arg2.arguments:
        return False
    if arg1.isconstant: # implies arg2.isconstant
        return numpy.all(arg1.eval() == arg2.eval())
//  [python]
def _simplified(self):
        if not self.value.any():
            return zeros_like(self)
        if self.ndim == 1 and self.dtype == int and n.all(self.value == n.arange(self.value.shape[0])):
            return Range(self.shape[0])
        for i, sh in enumerate(self.shape):
            # Find and replace invariant axes with InsertAxis. Since `self.value.any()`
            # is False for arrays with a zero-length axis, we can arrive here only if all
            # axes have at least length one, hence the following statement should work.
            first, *others = n.rollaxis(self.value, i)
            if all(n.equal(first, other).all() for other in others):
                return insertaxis(constant(first), i, sh)
//  [python]
def _simplified(self):
        if not self.value.any():
            return zeros_like(self)
        if self.ndim == 1 and self.dtype == int and numpy.all(self.value == numpy.arange(self.value.shape[0])):
            return Range(self.shape[0])
        for i, sh in enumerate(self.shape):
            # Find and replace invariant axes with InsertAxis. Since `self.value.any()`
            # is False for arrays with a zero-length axis, we can arrive here only if all
            # axes have at least length one, hence the following statement should work.
            first, *others = numpy.rollaxis(self.value, i)
            if all(numpy.equal(first, other).all() for other in others):
                return insertaxis(constant(first), i, sh)
//  [python]
def test_simple(self):
        [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
        assert_(n.all(X == np.array([[1, 2, 3],
                               [1, 2, 3],
                               [1, 2, 3],
                               [1, 2, 3]])))
        assert_(n.all(Y == np.array([[4, 4, 4],
                               [5, 5, 5],
                               [6, 6, 6],
                               [7, 7, 7]])))
//  [python]
def test_simple(self):
        [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
        assert_(np.all(X == np.array([[1, 2, 3],
                               [1, 2, 3],
                               [1, 2, 3],
                               [1, 2, 3]])))
        assert_(np.all(Y == np.array([[4, 4, 4],
                               [5, 5, 5],
                               [6, 6, 6],
                               [7, 7, 7]])))
//  [python]
def test_sparse(self):
        [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
        assert_(n.all(X == n.array([[1, 2, 3]])))
        assert_(n.all(Y == n.array([[4], [5], [6], [7]])))
//  [python]
def test_sparse(self):
        [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
        assert_(np.all(X == np.array([[1, 2, 3]])))
        assert_(np.all(Y == np.array([[4], [5], [6], [7]])))
//  [python]
def loadFile(filename, ndims, dimlens):
    """Convenience function which loads data from a file, and checks
    that it has the correct number of dimensions/dimension sizes.

    :arg filename: File to load
    
    :arg ndims:    Expected number of dimensions (1 or 2)
    
    :arg dimlens:  Sequence of expected lengths, one per dimension. Pass
                   in -1 for a dimension to accept any size for that
                   dimension. 
    """

    data = np.loadtxt(filename, dtype=np.float64)

    # Expected 2 dimensions, but only got 1 - file
    # with a single line or a single column
    if ndims == 2 and len(data.shape) == 1:
        try:
            # Caller wants 2D, but doesn't care 
            # about the length of each dimension.
            if n.all(np.array(dimlens) == -1):
                dimlens = [data.shape[0], -1]
                
            data = data.reshape(dimlens)
        except:
            raise ValueError('Unexpected size: {0} (expected: {1}, is: '
                             '{2})'.format(filename, dimlens, data.shape))
            
    if len(data.shape) != ndims:
        raise ValueError('Wrong number of dimensions: {0}'.format(filename))

    for dim, dimlen in enumerate(dimlens):

        # Pass in a dimlen == -1 to skip
        # the size check for a dimension
        if dimlen == -1:
            continue

        if data.shape[dim] != dimlen:
            raise ValueError('Wrong shape: {0}'.format(filename))

    return data
//  [python]
def loadFile(filename, ndims, dimlens):
    """Convenience function which loads data from a file, and checks
    that it has the correct number of dimensions/dimension sizes.

    :arg filename: File to load
    
    :arg ndims:    Expected number of dimensions (1 or 2)
    
    :arg dimlens:  Sequence of expected lengths, one per dimension. Pass
                   in -1 for a dimension to accept any size for that
                   dimension. 
    """

    data = np.loadtxt(filename, dtype=np.float64)

    # Expected 2 dimensions, but only got 1 - file
    # with a single line or a single column
    if ndims == 2 and len(data.shape) == 1:
        try:
            # Caller wants 2D, but doesn't care 
            # about the length of each dimension.
            if np.all(np.array(dimlens) == -1):
                dimlens = [data.shape[0], -1]
                
            data = data.reshape(dimlens)
        except:
            raise ValueError('Unexpected size: {0} (expected: {1}, is: '
                             '{2})'.format(filename, dimlens, data.shape))
            
    if len(data.shape) != ndims:
        raise ValueError('Wrong number of dimensions: {0}'.format(filename))

    for dim, dimlen in enumerate(dimlens):

        # Pass in a dimlen == -1 to skip
        # the size check for a dimension
        if dimlen == -1:
            continue

        if data.shape[dim] != dimlen:
            raise ValueError('Wrong shape: {0}'.format(filename))

    return data
//  [python]
def test_indexing(self):
        x = [1, 2, 3]
        y = [4, 5, 6, 7]
        [X, Y] = meshgrid(x, y, indexing='ij')
        assert_(n.all(X == n.array([[1, 1, 1, 1],
                                      [2, 2, 2, 2],
                                      [3, 3, 3, 3]])))
        assert_(n.all(Y == n.array([[4, 5, 6, 7],
                                      [4, 5, 6, 7],
                                      [4, 5, 6, 7]])))

        # Test expected shapes:
        z = [8, 9]
        assert_(meshgrid(x, y)[0].shape == (4, 3))
        assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
        assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
        assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))

        assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
//  [python]
def test_indexing(self):
        x = [1, 2, 3]
        y = [4, 5, 6, 7]
        [X, Y] = meshgrid(x, y, indexing='ij')
        assert_(np.all(X == np.array([[1, 1, 1, 1],
                                      [2, 2, 2, 2],
                                      [3, 3, 3, 3]])))
        assert_(np.all(Y == np.array([[4, 5, 6, 7],
                                      [4, 5, 6, 7],
                                      [4, 5, 6, 7]])))

        # Test expected shapes:
        z = [8, 9]
        assert_(meshgrid(x, y)[0].shape == (4, 3))
        assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
        assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
        assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))

        assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
//  [python]
def test_numpy_randint(self):
        cfunc = self._compile_array_dist("randint", 3)
        low, high = 1000, 10000
        size = (30, 30)
        res = cfunc(low, high, size)
        self.assertIsInstance(res, np.ndarray)
        self.assertEqual(res.shape, size)
        self.assertIn(res.dtype, (np.dtype('int32'), np.dtype('int64')))
        self.assertTrue(n.all(res >= low))
        self.assertTrue(n.all(res < high))
        # Crude statistical tests
        mean = (low + high) / 2
        tol = (high - low) / 20
        self.assertGreaterEqual(res.mean(), mean - tol)
        self.assertLessEqual(res.mean(), mean + tol)
//  [python]
def test_numpy_randint(self):
        cfunc = self._compile_array_dist("randint", 3)
        low, high = 1000, 10000
        size = (30, 30)
        res = cfunc(low, high, size)
        self.assertIsInstance(res, np.ndarray)
        self.assertEqual(res.shape, size)
        self.assertIn(res.dtype, (np.dtype('int32'), np.dtype('int64')))
        self.assertTrue(np.all(res >= low))
        self.assertTrue(np.all(res < high))
        # Crude statistical tests
        mean = (low + high) / 2
        tol = (high - low) / 20
        self.assertGreaterEqual(res.mean(), mean - tol)
        self.assertLessEqual(res.mean(), mean + tol)
//  [python]
def test_numpy_random_random(self):
        cfunc = self._compile_array_dist("random", 1)
        size = (30, 30)
        res = cfunc(size)
        self.assertIsInstance(res, np.ndarray)
        self.assertEqual(res.shape, size)
        self.assertEqual(res.dtype, np.dtype('float64'))
        # Results are within expected bounds
        self.assertTrue(np.all(res >= 0.0))
        self.assertTrue(np.all(res < 1.0))
        # Crude statistical tests
        self.assertTrue(np.any(res <= 0.1))
        self.assertTrue(np.any(res >= 0.9))
        mean = res.mean()
        self.assertGreaterEqual(mean, 0.45)
        self.assertLessEqual(mean, 0.55)
//  [python]
def Elemwise(data: typing.Tuple[types.arraydata, ...], index: Array, dtype: Dtype):
    assert isinstance(data, tuple) and all(isinstance(d, types.arraydata) and d.dtype == dtype for d in data), f'data={data!r}'
    assert isinstance(index, Array) and index.ndim == 0 and index.dtype == int, f'index={index!r}'
    unique, indices = util.unique(data)
    if len(unique) == 1:
        return Constant(unique[0])
    # Create shape from data and index, rather than unique and the modified
    # index, in order to avoid potential shape inconsistencies later on.
    shapes = numpy.array([d.shape for d in data])
    shape = [Take(constant(s), index) for s in shapes.T]
    if len(unique) < len(data):
        index = Take(constant(indices), index)
    # Move all axes with constant shape to the left and ravel the remainder.
    is_constant = n.all(shapes[1:] == shapes[0], axis=0)
    const_axes = tuple(is_constant.nonzero()[0])
    var_axes = tuple((~is_constant).nonzero()[0])
    raveled = [numpy.transpose(d, const_axes + var_axes).reshape(*shapes[0, const_axes], -1) for d in unique]
    # Concatenate the raveled axis, take slices, unravel and reorder the axes to
    # the original position.
    concat = constant(numpy.concatenate(raveled, axis=-1))
    if not var_axes:
        return Take(concat, index)
    cumprod = [shape[i] for i in var_axes]
    for i in reversed(range(len(cumprod)-1)):
        cumprod[i] *= cumprod[i+1]  # work backwards so that the shape check matches in Unravel
    offsets = _SizesToOffsets(asarray([d.shape[-1] for d in raveled]))
    elemwise = Take(concat, Range(cumprod[0]) + Take(offsets, index))
    for i in range(len(var_axes)-1):
        elemwise = Unravel(elemwise, shape[var_axes[i]], cumprod[i+1])
    return Transpose.from_end(elemwise, *var_axes)
//  [python]
def Elemwise(data: typing.Tuple[types.arraydata, ...], index: Array, dtype: Dtype):
    assert isinstance(data, tuple) and all(isinstance(d, types.arraydata) and d.dtype == dtype for d in data), f'data={data!r}'
    assert isinstance(index, Array) and index.ndim == 0 and index.dtype == int, f'index={index!r}'
    unique, indices = util.unique(data)
    if len(unique) == 1:
        return Constant(unique[0])
    # Create shape from data and index, rather than unique and the modified
    # index, in order to avoid potential shape inconsistencies later on.
    shapes = numpy.array([d.shape for d in data])
    shape = [Take(constant(s), index) for s in shapes.T]
    if len(unique) < len(data):
        index = Take(constant(indices), index)
    # Move all axes with constant shape to the left and ravel the remainder.
    is_constant = numpy.all(shapes[1:] == shapes[0], axis=0)
    const_axes = tuple(is_constant.nonzero()[0])
    var_axes = tuple((~is_constant).nonzero()[0])
    raveled = [numpy.transpose(d, const_axes + var_axes).reshape(*shapes[0, const_axes], -1) for d in unique]
    # Concatenate the raveled axis, take slices, unravel and reorder the axes to
    # the original position.
    concat = constant(numpy.concatenate(raveled, axis=-1))
    if not var_axes:
        return Take(concat, index)
    cumprod = [shape[i] for i in var_axes]
    for i in reversed(range(len(cumprod)-1)):
        cumprod[i] *= cumprod[i+1]  # work backwards so that the shape check matches in Unravel
    offsets = _SizesToOffsets(asarray([d.shape[-1] for d in raveled]))
    elemwise = Take(concat, Range(cumprod[0]) + Take(offsets, index))
    for i in range(len(var_axes)-1):
        elemwise = Unravel(elemwise, shape[var_axes[i]], cumprod[i+1])
    return Transpose.from_end(elemwise, *var_axes)
//  [python]
def test_multiple_axes(self):
        data = np.arange(24).reshape(3, 2, 4)
        x = as_tensor_variable(data)
        v, i = eval_outputs(max_and_argmax(x, [1, -1]))
        assert n.all(v == np.array([7, 15, 23]))
        assert n.all(i == np.array([7, 7, 7]))

        v = eval_outputs(max_and_argmax(x, [1, -1])[0].shape)
        assert tuple(v) == np.max(data, (1, -1)).shape
//  [python]
def test_multiple_axes(self):
        data = np.arange(24).reshape(3, 2, 4)
        x = as_tensor_variable(data)
        v, i = eval_outputs(max_and_argmax(x, [1, -1]))
        assert np.all(v == np.array([7, 15, 23]))
        assert np.all(i == np.array([7, 7, 7]))

        v = eval_outputs(max_and_argmax(x, [1, -1])[0].shape)
        assert tuple(v) == np.max(data, (1, -1)).shape
//  [python]
def test2_float16(self):
        # Test negative values and bigger range to make sure numpy don't do the argmax as on uint16
        data = (rand(20, 30).astype("float16") - 0.5) * 20
        n = shared(data)
        for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                ([0, 1], None), ([1, 0], None),
                                (NoneConst.clone(), None),
                                (constant(0), 0)]:
            v, i = eval_outputs(max_and_argmax(n, axis), (MaxAndArgmax,))
            assert i.dtype == 'int64'
            self.assertTrue(n.all(v == np.max(data, np_axis)))
            self.assertTrue(n.all(i == np.argmax(data, np_axis)))
            v_shape = eval_outputs(max_and_argmax(n, axis)[0].shape)
            assert tuple(v_shape) == np.max(data, np_axis).shape
//  [python]
def test2_float16(self):
        # Test negative values and bigger range to make sure numpy don't do the argmax as on uint16
        data = (rand(20, 30).astype("float16") - 0.5) * 20
        n = shared(data)
        for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                ([0, 1], None), ([1, 0], None),
                                (NoneConst.clone(), None),
                                (constant(0), 0)]:
            v, i = eval_outputs(max_and_argmax(n, axis), (MaxAndArgmax,))
            assert i.dtype == 'int64'
            self.assertTrue(np.all(v == np.max(data, np_axis)))
            self.assertTrue(np.all(i == np.argmax(data, np_axis)))
            v_shape = eval_outputs(max_and_argmax(n, axis)[0].shape)
            assert tuple(v_shape) == np.max(data, np_axis).shape
//  [python]
def test_simple(self):
        x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \
        [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]])
        H, edges = histogramdd(x, (2, 3, 3), range=[[-1, 1], [0, 3], [0, 3]])
        answer = np.array([[[0, 1, 0], [0, 0, 1], [1, 0, 0]], [[0, 1, 0], [0, 0, 1],
            [0, 0, 1]]])
        assert_array_equal(H, answer)
        # Check normalization
        ed = [[-2, 0, 2], [0, 1, 2, 3], [0, 1, 2, 3]]
        H, edges = histogramdd(x, bins=ed, normed=True)
        assert_(np.all(H == answer / 12.))
        # Check that H has the correct shape.
        H, edges = histogramdd(x, (2, 3, 4), range=[[-1, 1], [0, 3], [0, 4]],
            normed=True)
        answer = np.array([[[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]], [[0, 1, 0, 0],
            [0, 0, 1, 0], [0, 0, 1, 0]]])
        assert_array_almost_equal(H, answer / 6., 4)
        # Check that a sequence of arrays is accepted and H has the correct
        # shape.
        z = [np.squeeze(y) for y in split(x, 3, axis=1)]
        H, edges = histogramdd(z, bins=(4, 3, 2), range=[[-2, 2], [0, 3], [0, 2]])
        answer = np.array([[[0, 0], [0, 0], [0, 0]],
                          [[0, 1], [0, 0], [1, 0]],
                          [[0, 1], [0, 0], [0, 0]],
                          [[0, 0], [0, 0], [0, 0]]])
        assert_array_equal(H, answer)

        Z = np.zeros((5, 5, 5))
        Z[range(5), range(5), range(5)] = 1.
        H, edges = histogramdd([np.arange(5), np.arange(5), np.arange(5)], 5)
        assert_array_equal(H, Z)
//  [python]
def makeBroadcastTester(op, expected, checks=None, name=None, **kwargs):
    if checks is None:
        checks = {}
    if name is None:
        name = str(op)
    # Here we ensure the test name matches the name of the variable defined in
    # this script. This is needed to properly identify the test e.g. with the
    # --with-id option of nosetests, or simply to rerun a specific test that
    # failed.
    capitalize = False
    if name.startswith('Elemwise{') and name.endswith(',no_inplace}'):
        # For instance: Elemwise{add,no_inplace} -> Add
        name = name[9:-12]
        capitalize = True
    elif name.endswith('_inplace'):
        # For instance: sub_inplace -> SubInplace
        capitalize = True
    if capitalize:
        name = ''.join([x.capitalize() for x in name.split('_')])
    # Some tests specify a name that already ends with 'Tester', while in other
    # cases we need to add it manually.
    if not name.endswith('Tester'):
        name += "Tester"
    if 'inplace' in kwargs:
        if kwargs['inplace']:
            _expected = expected
            if not isinstance(_expected, dict):
                def expected(*inputs):
                    return np.array(_expected(*inputs), dtype=inputs[0].dtype)

            def inplace_check(inputs, outputs):
                # this used to be inputs[0] is output[0]
                # I changed it so that it was easier to satisfy by the
                # DebugMode
                return n.all(inputs[0] == outputs[0])

            checks = dict(checks, inplace_check=inplace_check)
        del kwargs['inplace']
    return makeTester(name, op, expected, checks, **kwargs)
//  [python]
def makeBroadcastTester(op, expected, checks=None, name=None, **kwargs):
    if checks is None:
        checks = {}
    if name is None:
        name = str(op)
    # Here we ensure the test name matches the name of the variable defined in
    # this script. This is needed to properly identify the test e.g. with the
    # --with-id option of nosetests, or simply to rerun a specific test that
    # failed.
    capitalize = False
    if name.startswith('Elemwise{') and name.endswith(',no_inplace}'):
        # For instance: Elemwise{add,no_inplace} -> Add
        name = name[9:-12]
        capitalize = True
    elif name.endswith('_inplace'):
        # For instance: sub_inplace -> SubInplace
        capitalize = True
    if capitalize:
        name = ''.join([x.capitalize() for x in name.split('_')])
    # Some tests specify a name that already ends with 'Tester', while in other
    # cases we need to add it manually.
    if not name.endswith('Tester'):
        name += "Tester"
    if 'inplace' in kwargs:
        if kwargs['inplace']:
            _expected = expected
            if not isinstance(_expected, dict):
                def expected(*inputs):
                    return np.array(_expected(*inputs), dtype=inputs[0].dtype)

            def inplace_check(inputs, outputs):
                # this used to be inputs[0] is output[0]
                # I changed it so that it was easier to satisfy by the
                # DebugMode
                return np.all(inputs[0] == outputs[0])

            checks = dict(checks, inplace_check=inplace_check)
        del kwargs['inplace']
    return makeTester(name, op, expected, checks, **kwargs)
//  [python]
def test_clip_repeat_grad(self):
        # This is testing for the issue #633
        x, y = tensor.vectors('xy')
        a = clip(x, y, x)
        g = theano.gradient.grad(a.sum(), x)
        fn = theano.function([x, y], [g])

        # Test the other way around as well
        a2 = clip(x, x, y)
        g2 = theano.gradient.grad(a2.sum(), x)
        fn2 = theano.function([x, y], [g2])

        # Test for the equal case too
        a3 = theano.tensor.clip(x, x, x)
        g3 = theano.gradient.grad(a3.sum(), x)
        fn3 = theano.function([x], [g3])

        rng = np.random.RandomState(utt.fetch_seed())

        nvals = 50
        xval = rng.rand(nvals).astype(config.floatX)
        # To ensure that the min < x
        yval_mn = rng.rand(nvals).astype(config.floatX) - 1.0

        # To ensure that the max > x
        yval_mx = rng.rand(nvals).astype(config.floatX) + 1.0

        aval, = fn(xval, yval_mn)
        aval2, = fn2(xval, yval_mx)
        aval3, = fn3(xval)
        self.assertTrue(n.all(aval == 1.))
        self.assertTrue(n.all(aval2 == 1.))
        self.assertTrue(n.all(aval3 == 1.))
//  [python]
def test_clip_repeat_grad(self):
        # This is testing for the issue #633
        x, y = tensor.vectors('xy')
        a = clip(x, y, x)
        g = theano.gradient.grad(a.sum(), x)
        fn = theano.function([x, y], [g])

        # Test the other way around as well
        a2 = clip(x, x, y)
        g2 = theano.gradient.grad(a2.sum(), x)
        fn2 = theano.function([x, y], [g2])

        # Test for the equal case too
        a3 = theano.tensor.clip(x, x, x)
        g3 = theano.gradient.grad(a3.sum(), x)
        fn3 = theano.function([x], [g3])

        rng = np.random.RandomState(utt.fetch_seed())

        nvals = 50
        xval = rng.rand(nvals).astype(config.floatX)
        # To ensure that the min < x
        yval_mn = rng.rand(nvals).astype(config.floatX) - 1.0

        # To ensure that the max > x
        yval_mx = rng.rand(nvals).astype(config.floatX) + 1.0

        aval, = fn(xval, yval_mn)
        aval2, = fn2(xval, yval_mx)
        aval3, = fn3(xval)
        self.assertTrue(np.all(aval == 1.))
        self.assertTrue(np.all(aval2 == 1.))
        self.assertTrue(np.all(aval3 == 1.))
//  [python]
def test2(self):
        data = rand(2, 3)
        n = as_tensor_variable(data)
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                    ([0, 1], None), ([1, 0], None)]:
                v = eval_outputs(fct(n, axis))
                self.assertTrue(n.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test2(self):
        data = rand(2, 3)
        n = as_tensor_variable(data)
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                    ([0, 1], None), ([1, 0], None)]:
                v = eval_outputs(fct(n, axis))
                self.assertTrue(np.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test2_valid_neg(self):
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            n = as_tensor_variable(rand(2, 3))
            i = eval_outputs(fct(n, -1))
            self.assertTrue(i.shape == (2,))
            self.assertTrue(n.all(i == nfct(n.value, -1)))
            i = eval_outputs(fct(n, -2))
            self.assertTrue(i.shape == (3,))
            self.assertTrue(n.all(i == nfct(n.value, -2)))

            v = eval_outputs(fct(n, -1).shape)
            assert v == (2)
            v = eval_outputs(fct(n, -2).shape)
            assert v == (3)
//  [python]
def test2_valid_neg(self):
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            n = as_tensor_variable(rand(2, 3))
            i = eval_outputs(fct(n, -1))
            self.assertTrue(i.shape == (2,))
            self.assertTrue(np.all(i == nfct(n.value, -1)))
            i = eval_outputs(fct(n, -2))
            self.assertTrue(i.shape == (3,))
            self.assertTrue(np.all(i == nfct(n.value, -2)))

            v = eval_outputs(fct(n, -1).shape)
            assert v == (2)
            v = eval_outputs(fct(n, -2).shape)
            assert v == (3)
//  [python]
def test2_float16(self):
        # Test negative values and bigger range to make sure numpy don't do the argmax as on uint16
        data = (rand(20, 30).astype("float16") - 0.5) * 20
        n = shared(data)
        mode = get_default_mode().including("local_max_and_argmax", "uncanonicalize")
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                    ([0, 1], None), ([1, 0], None)]:
                v = eval_outputs(fct(n, axis), (Argmax,), mode=mode)
                self.assertTrue(n.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape, mode=mode)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test2_float16(self):
        # Test negative values and bigger range to make sure numpy don't do the argmax as on uint16
        data = (rand(20, 30).astype("float16") - 0.5) * 20
        n = shared(data)
        mode = get_default_mode().including("local_max_and_argmax", "uncanonicalize")
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                    ([0, 1], None), ([1, 0], None)]:
                v = eval_outputs(fct(n, axis), (Argmax,), mode=mode)
                self.assertTrue(np.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape, mode=mode)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test3(self):
        data = rand(2, 3, 4)
        n = as_tensor_variable(data)
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (2, 2),
                                    (None, None), ([0, 1, 2], None),
                                    ([1, 0, 2], None)]:
                v = eval_outputs(fct(n, axis))
                self.assertTrue(n.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test3(self):
        data = rand(2, 3, 4)
        n = as_tensor_variable(data)
        for fct, nfct in [(argmax, np.argmax), (argmin, np.argmin)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (2, 2),
                                    (None, None), ([0, 1, 2], None),
                                    ([1, 0, 2], None)]:
                v = eval_outputs(fct(n, axis))
                self.assertTrue(np.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape)
                assert tuple(v_shape) == nfct(data, np_axis).shape
//  [python]
def test2(self):
        data = rand(2, 3)
        n = as_tensor_variable(data)
        for fct, nfct in [(max, np.max), (min, np.min)]:
            for (axis, np_axis) in [(-1, -1), (0, 0), (1, 1), (None, None),
                                    ([0, 1], None), ([1, 0], None)]:
                v = eval_outputs(fct(n, axis))
                self.assertTrue(n.all(v == nfct(data, np_axis)))
                v_shape = eval_outputs(fct(n, axis).shape)
                assert tuple(v_shape) == nfct(data, np_axis).shape