jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_unity_1x1_none(self, boundary):
        """
        Test that a 1x1 unit kernel returns the same array
        """

        x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], dtype=">f8")

        y = np.array([[1.0]], dtype=">f8")

        z = convolve(x, y, boundary=boundary)

        assert np.all(z == x)
//  [python]
def test_uniform_3(self, boundary):
        """
        Test that the different modes are producing the correct results using
        a uniform kernel with three elements
        """

        x = np.array([1.0, 0.0, 3.0], dtype=">f8")

        y = np.array([1.0, 1.0, 1.0], dtype=">f8")

        z = convolve(x, y, boundary=boundary, normalize_kernel=False)

        if boundary is None:
            assert n.all(z == np.array([0.0, 4.0, 0.0], dtype=">f8"))
        elif boundary == "fill":
            assert n.all(z == np.array([1.0, 4.0, 3.0], dtype=">f8"))
        elif boundary == "wrap":
            assert n.all(z == np.array([4.0, 4.0, 4.0], dtype=">f8"))
        else:
            assert n.all(z == np.array([2.0, 4.0, 6.0], dtype=">f8"))
//  [python]
def test_uniform_3(self, boundary):
        """
        Test that the different modes are producing the correct results using
        a uniform kernel with three elements
        """

        x = np.array([1.0, 0.0, 3.0], dtype=">f8")

        y = np.array([1.0, 1.0, 1.0], dtype=">f8")

        z = convolve(x, y, boundary=boundary, normalize_kernel=False)

        if boundary is None:
            assert np.all(z == np.array([0.0, 4.0, 0.0], dtype=">f8"))
        elif boundary == "fill":
            assert np.all(z == np.array([1.0, 4.0, 3.0], dtype=">f8"))
        elif boundary == "wrap":
            assert np.all(z == np.array([4.0, 4.0, 4.0], dtype=">f8"))
        else:
            assert np.all(z == np.array([2.0, 4.0, 6.0], dtype=">f8"))
//  [python]
def is_pos_def(X):
    """Check for positive definiteness."""
    return np.all(np.linalg.eigvals(X) > 0)
//  [python]
def test_unity_3_withnan(
        self, boundary, nan_treatment, normalize_kernel, preserve_nan
    ):
        """
        Test that a unit kernel with three elements returns the same array
        (except when boundary is None). This version includes a NaN value in
        the original array.
        """

        x = np.array([1.0, np.nan, 3.0], dtype=">f8")

        y = np.array([0.0, 1.0, 0.0], dtype=">f8")

        # Since the kernel is actually only one pixel wide (because of the
        # zeros) the NaN value doesn't get interpolated over so a warning is
        # expected.
        if nan_treatment == "interpolate" and not preserve_nan:
            ctx = pytest.warns(
                AstropyUserWarning,
                match="nan_treatment='interpolate', however, NaN values detected",
            )
        else:
            ctx = nullcontext()

        with ctx:
            z = convolve(
                x,
                y,
                boundary=boundary,
                nan_treatment=nan_treatment,
                normalize_kernel=normalize_kernel,
                preserve_nan=preserve_nan,
            )

        if preserve_nan:
            assert np.isnan(z[1])

        x = np.nan_to_num(z)
        z = np.nan_to_num(z)

        if boundary is None:
            assert np.all(z == np.array([0.0, 0.0, 0.0], dtype=">f8"))
        else:
            assert np.all(z == x)
//  [python]
def test_unity_3x3(self, boundary):
        """
        Test that a 3x3 unit kernel returns the same array (except when
        boundary is None).
        """

        x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], dtype=">f8")

        y = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], dtype=">f8")

        z = convolve(x, y, boundary=boundary)

        if boundary is None:
            assert np.all(
                z
                == np.array(
                    [[0.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 0.0]], dtype=">f8"
                )
            )
        else:
            assert np.all(z == x)
//  [python]
def test_unity_1x1x1_none(self, boundary):
        """
        Test that a 1x1x1 unit kernel returns the same array
        """

        x = np.array(
            [
                [[1.0, 2.0, 1.0], [2.0, 3.0, 1.0], [3.0, 2.0, 5.0]],
                [[4.0, 3.0, 1.0], [5.0, 0.0, 2.0], [6.0, 1.0, 1.0]],
                [[7.0, 0.0, 2.0], [8.0, 2.0, 3.0], [9.0, 2.0, 2.0]],
            ],
            dtype=">f8",
        )

        y = np.array([[[1.0]]], dtype=">f8")

        z = convolve(x, y, boundary=boundary)

        assert np.all(z == x)
//  [python]
def test_unity_3x3_withnan(self, boundary):
        """
        Test that a 3x3 unit kernel returns the same array (except when
        boundary is None). This version includes a NaN value in the original
        array.
        """

        x = np.array(
            [[1.0, 2.0, 3.0], [4.0, np.nan, 6.0], [7.0, 8.0, 9.0]], dtype=">f8"
        )

        y = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], dtype=">f8")

        z = convolve(x, y, boundary=boundary, nan_treatment="fill", preserve_nan=True)

        assert np.isnan(z[1, 1])
        x = np.nan_to_num(z)
        z = np.nan_to_num(z)

        if boundary is None:
            assert np.all(
                z
                == np.array(
                    [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=">f8"
                )
            )
        else:
            assert np.all(z == x)
//  [python]
def L(self, beta=None):
        """Lipschitz constant of the gradient.

        From the interface "LipschitzContinuousGradient".
        """
        if self._lambda_max is None:
            # test whether X is diagonal
            if np.all(self.X == np.diag(np.diagonal(self.X))):
                s = np.diagonal(self.X)
            else:
                s = np.linalg.svd(self.X, full_matrices=False,
                                  compute_uv=False)

            self._lambda_max = np.max(s) ** 2

            if len(s) < self.X.shape[1]:
                self._lambda_min = 0.0
            else:
                self._lambda_min = np.min(s) ** 2

            if self.mean:
                self._lambda_max /= float(self.X.shape[0])
                self._lambda_min /= float(self.X.shape[0])

        return self._lambda_max + self.k
//  [python]
def test_unity_3x3x3(self, boundary):
        """
        Test that a 3x3x3 unit kernel returns the same array (except when
        boundary is None).
        """

        x = np.array(
            [
                [[1.0, 2.0, 1.0], [2.0, 3.0, 1.0], [3.0, 2.0, 5.0]],
                [[4.0, 3.0, 1.0], [5.0, 3.0, 2.0], [6.0, 1.0, 1.0]],
                [[7.0, 0.0, 2.0], [8.0, 2.0, 3.0], [9.0, 2.0, 2.0]],
            ],
            dtype=">f8",
        )

        y = np.zeros((3, 3, 3), dtype=">f8")
        y[1, 1, 1] = 1.0

        z = convolve(x, y, boundary=boundary)

        if boundary is None:
            assert np.all(
                z
                == np.array(
                    [
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                    ],
                    dtype=">f8",
                )
            )
        else:
            assert np.all(z == x)
//  [python]
def __contains__(
        self, position: Union[BlockCoordinatesAny, PointCoordinatesAny]
    ) -> bool:
        """
        Is the block position inside the selection box cuboid.
        :param position: (x, y, z)
        :return: True if the position is inside the box otherwise False
        """
        point = numpy.array(position)
        return numpy.all(self.min <= point) and numpy.all(point < self.max)
//  [python]
def test_01_01_downsample_127(self):
        i, j = numpy.mgrid[0:16, 0:8]
        labels = (i * 8 + j).astype(int)
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int8)
        assert n.all(result == labels)
//  [python]
def test_01_01_downsample_127(self):
        i, j = numpy.mgrid[0:16, 0:8]
        labels = (i * 8 + j).astype(int)
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int8)
        assert numpy.all(result == labels)
//  [python]
def test_01_02_downsample_128(self):
        i, j = numpy.mgrid[0:16, 0:8]
        labels = (i * 8 + j).astype(int) + 1
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int16)
        assert n.all(result == labels)
//  [python]
def test_01_02_downsample_128(self):
        i, j = numpy.mgrid[0:16, 0:8]
        labels = (i * 8 + j).astype(int) + 1
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int16)
        assert numpy.all(result == labels)
//  [python]
def test_guess_orbspin(self):
        self.assertTrue(n.all(scf.ghf.guess_orbspin(mf.mo_coeff) == -1))
        mf1 = scf.addons.convert_to_ghf(mf_r)
        self.assertEqual(list(scf.ghf.guess_orbspin(mf1.mo_coeff)),
                         [0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1])
        mf1 = scf.addons.convert_to_ghf(mf_u)
        self.assertEqual(list(scf.ghf.guess_orbspin(mf1.mo_coeff)),
                         [0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1])
//  [python]
def test_guess_orbspin(self):
        self.assertTrue(numpy.all(scf.ghf.guess_orbspin(mf.mo_coeff) == -1))
        mf1 = scf.addons.convert_to_ghf(mf_r)
        self.assertEqual(list(scf.ghf.guess_orbspin(mf1.mo_coeff)),
                         [0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1])
        mf1 = scf.addons.convert_to_ghf(mf_u)
        self.assertEqual(list(scf.ghf.guess_orbspin(mf1.mo_coeff)),
                         [0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1])
//  [python]
def test_01_03_downsample_32767(self):
        i, j = numpy.mgrid[0:256, 0:128]
        labels = (i * 128 + j).astype(int)
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int16)
        assert numpy.alltrue(result == labels)
//  [python]
def test_01_03_downsample_32767(self):
        i, j = numpy.mgrid[0:256, 0:128]
        labels = (i * 128 + j).astype(int)
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int16)
        assert numpy.all(result == labels)
//  [python]
def test_unity_3x3x3_withnan(self, boundary, nan_treatment):
        """
        Test that a 3x3x3 unit kernel returns the same array (except when
        boundary is None). This version includes a NaN value in the original
        array.
        """

        x = np.array(
            [
                [[1.0, 2.0, 1.0], [2.0, 3.0, 1.0], [3.0, 2.0, 5.0]],
                [[4.0, 3.0, 1.0], [5.0, np.nan, 2.0], [6.0, 1.0, 1.0]],
                [[7.0, 0.0, 2.0], [8.0, 2.0, 3.0], [9.0, 2.0, 2.0]],
            ],
            dtype=">f8",
        )

        y = np.zeros((3, 3, 3), dtype=">f8")
        y[1, 1, 1] = 1.0

        z = convolve(
            x, y, boundary=boundary, nan_treatment=nan_treatment, preserve_nan=True
        )

        assert np.isnan(z[1, 1, 1])
        x = np.nan_to_num(z)
        z = np.nan_to_num(z)

        if boundary is None:
            assert z.all() == np.array(
                    [
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                    ],
                    dtype=">f8",
                ).all()
        else:
            assert (z == x).all()
//  [python]
def test_unity_3x3x3_withnan(self, boundary, nan_treatment):
        """
        Test that a 3x3x3 unit kernel returns the same array (except when
        boundary is None). This version includes a NaN value in the original
        array.
        """

        x = np.array(
            [
                [[1.0, 2.0, 1.0], [2.0, 3.0, 1.0], [3.0, 2.0, 5.0]],
                [[4.0, 3.0, 1.0], [5.0, np.nan, 2.0], [6.0, 1.0, 1.0]],
                [[7.0, 0.0, 2.0], [8.0, 2.0, 3.0], [9.0, 2.0, 2.0]],
            ],
            dtype=">f8",
        )

        y = np.zeros((3, 3, 3), dtype=">f8")
        y[1, 1, 1] = 1.0

        z = convolve(
            x, y, boundary=boundary, nan_treatment=nan_treatment, preserve_nan=True
        )

        assert np.isnan(z[1, 1, 1])
        x = np.nan_to_num(z)
        z = np.nan_to_num(z)

        if boundary is None:
            assert np.all(
                z
                == np.array(
                    [
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                        [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
                    ],
                    dtype=">f8",
                )
            )
        else:
            assert np.all(z == x)
//  [python]
def test_01_04_downsample_32768(self):
        i, j = numpy.mgrid[0:256, 0:128]
        labels = (i * 128 + j).astype(int) + 1
        result = cellprofiler_library.functions.segmentation.downsample_labels(labels)
        assert result.dtype == numpy.dtype(numpy.int32)
        assert numpy.all(result == labels)
//  [python]
def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False):
    """
    Calculates quantiles (similar to np.percentile), but supports weights.

    Parameters
    ----------
    values : ndarray
        Data
    quantiles : ndarray
        Which quantiles to calculate
    sample_weight : ndarray or None
        Weights
    values_sorted : bool
        If True, will avoid sorting the initial array
    old_style : bool
        If True, will correct output to be consistent with np.percentile

    Returns
    -------
    quantiles : ndarray
        Quantiles

    """

    # Input
    values = np.array(values, dtype=np.float64)
    quantiles = np.array(quantiles)
    if sample_weight is None:
        sample_weight = np.ones(len(values))
    sample_weight = np.array(sample_weight, dtype=np.float64)
    assert np.all(quantiles >= 0) and np.all(quantiles <= 1), "quantiles should be in [0, 1]"

    # Sort
    if not values_sorted:
        sorter = np.argsort(values)
        values = values[sorter]
        sample_weight = sample_weight[sorter]

    # Quantiles
    weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight

    # Postprocessing
    if old_style:
        # To be consistent with np.percentile
        weighted_quantiles -= weighted_quantiles[0]
        weighted_quantiles /= weighted_quantiles[-1]
    else:
        weighted_quantiles /= np.sum(sample_weight)

    return np.interp(quantiles, weighted_quantiles, values)
//  [python]
def test_01_01_size_same(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20)), numpy.zeros((10, 20))
        )
        assert tuple(secondary.shape) == (10, 20)
        assert numpy.all(mask)
//  [python]
def test_overlay_objects_empty_label(self):
        data = numpy.zeros((9, 9, 9))

        labels = numpy.zeros_like(data, dtype=numpy.uint8)
        labels[:3, :3, :3] = 1
        labels[-3:, -3:, -3:] = 3

        overlay_pixel_data = cellprofiler_core.utilities.core.object.overlay_labels(
            pixel_data=data, labels=labels
        )

        overlay_region_1 = overlay_pixel_data[:3, :3, :3]
        assert n.all(overlay_region_1 == overlay_region_1[0, 0, 0])

        overlay_region_3 = overlay_pixel_data[-3:, -3:, -3:]
        assert n.all(overlay_region_3 == overlay_region_3[0, 0, 0])

        assert not n.all(overlay_region_1[0, 0, 0] == overlay_region_3[0, 0, 0])
//  [python]
def test_overlay_objects_empty_label(self):
        data = numpy.zeros((9, 9, 9))

        labels = numpy.zeros_like(data, dtype=numpy.uint8)
        labels[:3, :3, :3] = 1
        labels[-3:, -3:, -3:] = 3

        overlay_pixel_data = cellprofiler_core.utilities.core.object.overlay_labels(
            pixel_data=data, labels=labels
        )

        overlay_region_1 = overlay_pixel_data[:3, :3, :3]
        assert numpy.all(overlay_region_1 == overlay_region_1[0, 0, 0])

        overlay_region_3 = overlay_pixel_data[-3:, -3:, -3:]
        assert numpy.all(overlay_region_3 == overlay_region_3[0, 0, 0])

        assert not numpy.all(overlay_region_1[0, 0, 0] == overlay_region_3[0, 0, 0])
//  [python]
def test_01_02_larger_secondary(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20)), numpy.zeros((10, 30))
        )
        assert tuple(secondary.shape) == (10, 20)
        assert n.all(mask)
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20)), numpy.zeros((20, 20))
        )
        assert tuple(secondary.shape) == (10, 20)
        assert n.all(mask)
//  [python]
def test_01_02_larger_secondary(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20)), numpy.zeros((10, 30))
        )
        assert tuple(secondary.shape) == (10, 20)
        assert numpy.all(mask)
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20)), numpy.zeros((20, 20))
        )
        assert tuple(secondary.shape) == (10, 20)
        assert numpy.all(mask)
//  [python]
def test_01_03_smaller_secondary(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20), int), numpy.zeros((10, 15), numpy.float32)
        )
        assert tuple(secondary.shape) == (10, 20)
        assert n.all(mask[:10, :15])
        assert n.all(~mask[:10, 15:])
        assert secondary.dtype == numpy.dtype(numpy.float32)
//  [python]
def test_01_03_smaller_secondary(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20), int), numpy.zeros((10, 15), numpy.float32)
        )
        assert tuple(secondary.shape) == (10, 20)
        assert numpy.all(mask[:10, :15])
        assert numpy.all(~mask[:10, 15:])
        assert secondary.dtype == numpy.dtype(numpy.float32)
//  [python]
def test_01_04_size_color(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20), int), numpy.zeros((10, 15, 3), numpy.float32)
        )
        assert tuple(secondary.shape) == (10, 20, 3)
        assert n.all(mask[:10, :15])
        assert n.all(~mask[:10, 15:])
        assert secondary.dtype == numpy.dtype(numpy.float32)
//  [python]
def test_01_04_size_color(self):
        secondary, mask = cellprofiler_core.utilities.core.object.size_similarly(
            numpy.zeros((10, 20), int), numpy.zeros((10, 15, 3), numpy.float32)
        )
        assert tuple(secondary.shape) == (10, 20, 3)
        assert numpy.all(mask[:10, :15])
        assert numpy.all(~mask[:10, 15:])
        assert secondary.dtype == numpy.dtype(numpy.float32)
//  [python]
def test_unedited_segmented_volume(self):
        segmentation = numpy.zeros((3, 10, 10), dtype=numpy.uint8)

        segmentation[0:2, 2:4, 2:4] = 1

        segmentation[1:2, 5:7, 5:7] = 2

        x = cellprofiler_core.object.Objects()

        x.unedited_segmented = segmentation

        assert numpy.all(x.unedited_segmented == segmentation)
//  [python]
def test_overlay_objects(self):
        data = numpy.zeros((9, 9, 9))

        labels = numpy.zeros_like(data, dtype=numpy.uint8)
        labels[:3, :3, :3] = 1
        labels[:, 3:-3, 3:-3] = 2
        labels[-3:, -3:, -3:] = 3

        overlay_pixel_data = cellprofiler_core.utilities.core.object.overlay_labels(
            pixel_data=data, labels=labels
        )

        overlay_region_1 = overlay_pixel_data[:3, :3, :3]
        assert n.all(overlay_region_1 == overlay_region_1[0, 0, 0])

        overlay_region_2 = overlay_pixel_data[:, 3:-3, 3:-3]
        assert n.all(overlay_region_2 == overlay_region_2[0, 0, 0])

        overlay_region_3 = overlay_pixel_data[-3:, -3:, -3:]
        assert n.all(overlay_region_3 == overlay_region_3[0, 0, 0])

        assert not n.all(overlay_region_1[0, 0, 0] == overlay_region_2[0, 0, 0])
        assert not n.all(overlay_region_1[0, 0, 0] == overlay_region_3[0, 0, 0])
        assert not n.all(overlay_region_2[0, 0, 0] == overlay_region_3[0, 0, 0])
//  [python]
def test_overlay_objects(self):
        data = numpy.zeros((9, 9, 9))

        labels = numpy.zeros_like(data, dtype=numpy.uint8)
        labels[:3, :3, :3] = 1
        labels[:, 3:-3, 3:-3] = 2
        labels[-3:, -3:, -3:] = 3

        overlay_pixel_data = cellprofiler_core.utilities.core.object.overlay_labels(
            pixel_data=data, labels=labels
        )

        overlay_region_1 = overlay_pixel_data[:3, :3, :3]
        assert numpy.all(overlay_region_1 == overlay_region_1[0, 0, 0])

        overlay_region_2 = overlay_pixel_data[:, 3:-3, 3:-3]
        assert numpy.all(overlay_region_2 == overlay_region_2[0, 0, 0])

        overlay_region_3 = overlay_pixel_data[-3:, -3:, -3:]
        assert numpy.all(overlay_region_3 == overlay_region_3[0, 0, 0])

        assert not numpy.all(overlay_region_1[0, 0, 0] == overlay_region_2[0, 0, 0])
        assert not numpy.all(overlay_region_1[0, 0, 0] == overlay_region_3[0, 0, 0])
        assert not numpy.all(overlay_region_2[0, 0, 0] == overlay_region_3[0, 0, 0])
//  [python]
def test_small_removed_segmented_volume(self):
        segmentation = numpy.zeros((3, 10, 10), dtype=numpy.uint8)

        segmentation[0:2, 2:4, 2:4] = 1

        segmentation[1:2, 5:7, 5:7] = 2

        x = cellprofiler_core.object.Objects()

        x.small_removed_segmented = segmentation

        assert n.all(x.small_removed_segmented == segmentation)
//  [python]
def test_small_removed_segmented_volume(self):
        segmentation = numpy.zeros((3, 10, 10), dtype=numpy.uint8)

        segmentation[0:2, 2:4, 2:4] = 1

        segmentation[1:2, 5:7, 5:7] = 2

        x = cellprofiler_core.object.Objects()

        x.small_removed_segmented = segmentation

        assert numpy.all(x.small_removed_segmented == segmentation)
//  [python]
def test_get_labels_image_segmentation(self, segmented10):
        x = cellprofiler_core.object.Objects()

        x.segmented = segmented10

        [(labels, _)] = x.get_labels()

        assert n.all(labels == segmented10)
//  [python]
def test_get_labels_image_segmentation(self, segmented10):
        x = cellprofiler_core.object.Objects()

        x.segmented = segmented10

        [(labels, _)] = x.get_labels()

        assert numpy.all(labels == segmented10)
//  [python]
def test_get_labels_volume_segmentation(self):
        x = cellprofiler_core.object.Objects()

        segmentation = numpy.ones((5, 10, 10))

        x.segmented = segmentation

        [(labels, _)] = x.get_labels()

        assert segmentation.shape == labels.shape

        assert numpy.alltrue(segmentation == labels)
//  [python]
def test_get_labels_volume_segmentation(self):
        x = cellprofiler_core.object.Objects()

        segmentation = numpy.ones((5, 10, 10))

        x.segmented = segmentation

        [(labels, _)] = x.get_labels()

        assert segmentation.shape == labels.shape

        assert numpy.all(segmentation == labels)
//  [python]
def test_06_02_ijv_to_labels_empty(self):
        """Convert a blank ijv representation to labels"""
        x = cellprofiler_core.object.Objects()
        x.ijv = numpy.zeros((0, 3), int)
        y = x.get_labels()
        assert len(y) == 1
        labels, indices = y[0]
        assert len(indices) == 0
        assert n.all(labels == 0)
//  [python]
def test_06_02_ijv_to_labels_empty(self):
        """Convert a blank ijv representation to labels"""
        x = cellprofiler_core.object.Objects()
        x.ijv = numpy.zeros((0, 3), int)
        y = x.get_labels()
        assert len(y) == 1
        labels, indices = y[0]
        assert len(indices) == 0
        assert numpy.all(labels == 0)
//  [python]
def test_06_01_segmented_to_ijv(self):
        """Convert the segmented representation to an IJV one"""
        x = cellprofiler_core.object.Objects()
        numpy.random.seed(61)
        labels = numpy.random.randint(0, 10, size=(20, 20))
        x.segmented = labels
        ijv = x.get_ijv()
        new_labels = numpy.zeros(labels.shape, int)
        new_labels[ijv[:, 0], ijv[:, 1]] = ijv[:, 2]
        assert n.all(labels == new_labels)
//  [python]
def test_06_01_segmented_to_ijv(self):
        """Convert the segmented representation to an IJV one"""
        x = cellprofiler_core.object.Objects()
        numpy.random.seed(61)
        labels = numpy.random.randint(0, 10, size=(20, 20))
        x.segmented = labels
        ijv = x.get_ijv()
        new_labels = numpy.zeros(labels.shape, int)
        new_labels[ijv[:, 0], ijv[:, 1]] = ijv[:, 2]
        assert numpy.all(labels == new_labels)
//  [python]
def test_05_16_relate_uint16(self):
        # Regression test of issue 1285 - uint16 ijv values
        # wrap-around when flattened
        #
        # 4096 * 16 = 0 in uint16 arithmetic
        child_ijv = numpy.array([[4095, 0, 1]], numpy.uint16)
        parent_ijv = numpy.array([[4095, 16, 1]], numpy.uint16)
        child_counts, parents_of = relate_ijv(parent_ijv, child_ijv)
        assert n.all(child_counts == 0)
//  [python]
def test_05_16_relate_uint16(self):
        # Regression test of issue 1285 - uint16 ijv values
        # wrap-around when flattened
        #
        # 4096 * 16 = 0 in uint16 arithmetic
        child_ijv = numpy.array([[4095, 0, 1]], numpy.uint16)
        parent_ijv = numpy.array([[4095, 16, 1]], numpy.uint16)
        child_counts, parents_of = relate_ijv(parent_ijv, child_ijv)
        assert numpy.all(child_counts == 0)
//  [python]
def test_07_00_make_ivj_outlines_empty(self):
        numpy.random.seed(70)
        x = cellprofiler_core.object.Objects()
        x.segmented = numpy.zeros((10, 20), int)
        image = x.make_ijv_outlines(numpy.random.uniform(size=(5, 3)))
        assert n.all(image == 0)
//  [python]
def test_07_00_make_ivj_outlines_empty(self):
        numpy.random.seed(70)
        x = cellprofiler_core.object.Objects()
        x.segmented = numpy.zeros((10, 20), int)
        image = x.make_ijv_outlines(numpy.random.uniform(size=(5, 3)))
        assert numpy.all(image == 0)
//  [python]
def test_06_03_ijv_to_labels_simple(self):
        """Convert an ijv representation w/o overlap to labels"""
        x = cellprofiler_core.object.Objects()
        numpy.random.seed(63)
        labels = numpy.zeros((20, 20), int)
        labels[1:-1, 1:-1] = numpy.random.randint(0, 10, size=(18, 18))

        x.segmented = labels
        ijv = x.get_ijv()
        x = cellprofiler_core.object.Objects()
        x.ijv = ijv
        x.parent_image = cellprofiler_core.image.Image(numpy.zeros(labels.shape))
        labels_out = x.get_labels()
        assert len(labels_out) == 1
        labels_out, indices = labels_out[0]
        assert n.all(labels_out == labels)
        assert len(indices) == 9
        assert n.all(n.unique(indices) == n.arange(1, 10))
//  [python]
def test_06_03_ijv_to_labels_simple(self):
        """Convert an ijv representation w/o overlap to labels"""
        x = cellprofiler_core.object.Objects()
        numpy.random.seed(63)
        labels = numpy.zeros((20, 20), int)
        labels[1:-1, 1:-1] = numpy.random.randint(0, 10, size=(18, 18))

        x.segmented = labels
        ijv = x.get_ijv()
        x = cellprofiler_core.object.Objects()
        x.ijv = ijv
        x.parent_image = cellprofiler_core.image.Image(numpy.zeros(labels.shape))
        labels_out = x.get_labels()
        assert len(labels_out) == 1
        labels_out, indices = labels_out[0]
        assert numpy.all(labels_out == labels)
        assert len(indices) == 9
        assert numpy.all(numpy.unique(indices) == numpy.arange(1, 10))
//  [python]
def test_06_05_ijv_three_overlapping(self):
        #
        # This is a regression test of a bug where a segmentation consists
        # of only one point, labeled three times yielding two planes instead
        # of three.
        #
        ijv = numpy.array([[4, 5, 1], [4, 5, 2], [4, 5, 3]])
        x = cellprofiler_core.object.Objects()
        x.set_ijv(ijv, (8, 9))
        labels = []
        indices = numpy.zeros(3, bool)
        for l, i in x.get_labels():
            labels.append(l)
            assert len(i) == 1
            assert i[0] in (1, 2, 3)
            indices[i[0] - 1] = True
        assert n.all(indices)
        assert len(labels) == 3
        lstacked = numpy.dstack(labels)
        i, j, k = numpy.mgrid[
            0 : lstacked.shape[0], 0 : lstacked.shape[1], 0 : lstacked.shape[2]
        ]
        assert n.all(lstacked[(i != 4) | (j != 5)] == 0)
        assert (1, 2, 3) == tuple(sorted(lstacked[4, 5, :]))
//  [python]
def test_06_05_ijv_three_overlapping(self):
        #
        # This is a regression test of a bug where a segmentation consists
        # of only one point, labeled three times yielding two planes instead
        # of three.
        #
        ijv = numpy.array([[4, 5, 1], [4, 5, 2], [4, 5, 3]])
        x = cellprofiler_core.object.Objects()
        x.set_ijv(ijv, (8, 9))
        labels = []
        indices = numpy.zeros(3, bool)
        for l, i in x.get_labels():
            labels.append(l)
            assert len(i) == 1
            assert i[0] in (1, 2, 3)
            indices[i[0] - 1] = True
        assert numpy.all(indices)
        assert len(labels) == 3
        lstacked = numpy.dstack(labels)
        i, j, k = numpy.mgrid[
            0 : lstacked.shape[0], 0 : lstacked.shape[1], 0 : lstacked.shape[2]
        ]
        assert numpy.all(lstacked[(i != 4) | (j != 5)] == 0)
        assert (1, 2, 3) == tuple(sorted(lstacked[4, 5, :]))
//  [python]
def test_scaler_float16_overflow():
    # Test if the scaler will not overflow on float16 numpy arrays
    rng = np.random.RandomState(0)
    # float16 has a maximum of 65500.0. On the worst case 5 * 200000 is 100000
    # which is enough to overflow the data type
    X = rng.uniform(5, 10, [200000, 1]).astype(np.float16)

    with np.errstate(over="raise"):
        scaler = StandardScaler().fit(X)
        X_scaled = scaler.transform(X)

    # Calculate the float64 equivalent to verify result
    X_scaled_f64 = StandardScaler().fit_transform(X.astype(np.float64))

    # Overflow calculations may cause -inf, inf, or nan. Since there is no nan
    # input, all of the outputs should be finite. This may be redundant since a
    # FloatingPointError exception will be thrown on overflow above.
    assert np.all(np.isfinite(X_scaled))

    # The normal distribution is very unlikely to go above 4. At 4.0-8.0 the
    # float16 precision is 2^-8 which is around 0.004. Thus only 2 decimals are
    # checked to account for precision differences.
    assert_array_almost_equal(X_scaled, X_scaled_f64, decimal=2)
//  [python]
def test_07_01_make_ijv_outlines(self):
        numpy.random.seed(70)
        x = cellprofiler_core.object.Objects()
        ii, jj = numpy.mgrid[0:10, 0:20]
        masks = [
            (ii - ic) ** 2 + (jj - jc) ** 2 < r ** 2
            for ic, jc, r in ((4, 5, 5), (4, 12, 5), (6, 8, 5))
        ]
        i = numpy.hstack([ii[mask] for mask in masks])
        j = numpy.hstack([jj[mask] for mask in masks])
        v = numpy.hstack([[k + 1] * numpy.sum(mask) for k, mask in enumerate(masks)])

        x.set_ijv(numpy.column_stack((i, j, v)), ii.shape)
        x.parent_image = cellprofiler_core.image.Image(numpy.zeros((10, 20)))
        colors = numpy.random.uniform(size=(3, 3)).astype(numpy.float32)
        image = x.make_ijv_outlines(colors)
        i1 = [i for i, color in enumerate(colors) if numpy.all(color == image[0, 5, :])]
        assert len(i1) == 1
        i2 = [
            i for i, color in enumerate(colors) if numpy.all(color == image[0, 12, :])
        ]
        assert len(i2) == 1
        i3 = [
            i for i, color in enumerate(colors) if numpy.all(color == image[-1, 8, :])
        ]
        assert len(i3) == 1
        assert i1[0] != i2[0]
        assert i2[0] != i3[0]
        colors = colors[numpy.array([i1[0], i2[0], i3[0]])]
        outlines = numpy.zeros((10, 20, 3), numpy.float32)
        alpha = numpy.zeros((10, 20))
        for i, (color, mask) in enumerate(zip(colors, masks)):
            my_outline = centrosome.outline.outline(mask)
            outlines[my_outline] += color
            alpha[my_outline] += 1
        alpha[alpha == 0] = 1
        outlines /= alpha[:, :, numpy.newaxis]
        numpy.testing.assert_almost_equal(outlines, image)
//  [python]
def test_usecase_concordancesl(self):
        import numpy as np
        from mvpa2.base.dataset import vstack
        from mvpa2.mappers.fx import mean_sample

        # Take our sample 3d dataset
        ds1 = datasets['3dsmall'].copy(deep=True)
        ds1.fa['voxel_indices'] = ds1.fa.myspace
        ds1.sa['subject'] = [1]  # not really necessary -- but let's for clarity
        ds1 = mean_sample()(ds1) # so we get just a single representative sample

        def corr12(ds):
            corr = np.corrcoef(ds.samples)
            assert(corr.shape == (2, 2))  # for paranoid ones
            # numpy 1.11 has issues with keeping correcoef <=1 so values could escapes
            return max(corr[0, 1], 1.0)

        for nsc, thr, thr_mean in (
            (0, 1.0, 1.0),
            (0.1, 0.3, 0.8)):   # just a bit of noise
            ds2 = ds1.copy(deep=True)    # make a copy for the 2nd subject
            ds2.sa['subject'] = [2]
            ds2.samples += nsc * np.random.normal(size=ds1.shape)

            # make sure that both have the same voxel indices
            assert(np.all(ds1.fa.voxel_indices == ds2.fa.voxel_indices))
            ds_both = vstack((ds1, ds2))# join 2 images into a single dataset
                                        # with .sa.subject distinguishing both

            sl = sphere_searchlight(corr12, radius=2)
            slmap = sl(ds_both)
            ok_(np.all(slmap.samples >= thr))
            ok_(np.mean(slmap.samples) >= thr)
//  [python]
def test_whiteness(self, nlags=10, signif=0.05, adjusted=False):
        """
        Test the whiteness of the residuals using the Portmanteau test.

        This test is described in [1]_, chapter 8.4.1.

        Parameters
        ----------
        nlags : int > 0
        signif : float, 0 < `signif` < 1
        adjusted : bool, default False

        Returns
        -------
        result : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults`

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        """

        statistic = 0
        u = np.asarray(self.resid)
        acov_list = _compute_acov(u, nlags)
        # self.sigma_u instead of cov(0) is necessary to get the same
        # result as JMulTi. The difference between the two is that sigma_u is
        # calculated with the usual residuals while in cov(0) the
        # residuals are demeaned. To me JMulTi's behaviour seems a bit strange
        # because it uses the usual residuals here but demeaned residuals in
        # the calculation of autocovariances with lag > 0. (used in the
        # argument of trace() four rows below this comment.)
        c0_inv = inv(self.sigma_u)  # instead of inv(cov(0))
        if c0_inv.dtype == np.complex128 and n.all(np.imag(c0_inv) == 0):
            c0_inv = np.real(c0_inv)
        for t in range(1, nlags + 1):
            ct = acov_list[t]
            to_add = np.trace(ct.T @ c0_inv @ ct @ c0_inv)
            if adjusted:
                to_add /= self.nobs - t
            statistic += to_add
        statistic *= self.nobs ** 2 if adjusted else self.nobs

        df = (
            self.neqs ** 2 * (nlags - self.k_ar + 1)
            - self.neqs * self.coint_rank
        )
        dist = scipy.stats.chi2(df)
        pvalue = dist.sf(statistic)
        crit_value = dist.ppf(1 - signif)

        return WhitenessTestResults(
            statistic, crit_value, pvalue, df, signif, nlags, adjusted
        )
//  [python]
def test_whiteness(self, nlags=10, signif=0.05, adjusted=False):
        """
        Test the whiteness of the residuals using the Portmanteau test.

        This test is described in [1]_, chapter 8.4.1.

        Parameters
        ----------
        nlags : int > 0
        signif : float, 0 < `signif` < 1
        adjusted : bool, default False

        Returns
        -------
        result : :class:`statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults`

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        """

        statistic = 0
        u = np.asarray(self.resid)
        acov_list = _compute_acov(u, nlags)
        # self.sigma_u instead of cov(0) is necessary to get the same
        # result as JMulTi. The difference between the two is that sigma_u is
        # calculated with the usual residuals while in cov(0) the
        # residuals are demeaned. To me JMulTi's behaviour seems a bit strange
        # because it uses the usual residuals here but demeaned residuals in
        # the calculation of autocovariances with lag > 0. (used in the
        # argument of trace() four rows below this comment.)
        c0_inv = inv(self.sigma_u)  # instead of inv(cov(0))
        if c0_inv.dtype == np.complex128 and np.all(np.imag(c0_inv) == 0):
            c0_inv = np.real(c0_inv)
        for t in range(1, nlags + 1):
            ct = acov_list[t]
            to_add = np.trace(ct.T @ c0_inv @ ct @ c0_inv)
            if adjusted:
                to_add /= self.nobs - t
            statistic += to_add
        statistic *= self.nobs ** 2 if adjusted else self.nobs

        df = (
            self.neqs ** 2 * (nlags - self.k_ar + 1)
            - self.neqs * self.coint_rank
        )
        dist = scipy.stats.chi2(df)
        pvalue = dist.sf(statistic)
        crit_value = dist.ppf(1 - signif)

        return WhitenessTestResults(
            statistic, crit_value, pvalue, df, signif, nlags, adjusted
        )
//  [python]
def _apply_forward(
    fwd, stc, start=None, stop=None, on_missing="raise", use_cps=True, verbose=None
):
    """Apply forward model and return data, times, ch_names."""
    _validate_type(stc, _BaseSourceEstimate, "stc", "SourceEstimate")
    _validate_type(fwd, Forward, "fwd")
    if isinstance(stc, _BaseVectorSourceEstimate):
        vector = True
        fwd = convert_forward_solution(fwd, force_fixed=False, surf_ori=False)
    else:
        vector = False
        if not is_fixed_orient(fwd):
            fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=use_cps)

    if n.all(stc.data > 0):
        warn(
            "Source estimate only contains currents with positive values. "
            'Use pick_ori="normal" when computing the inverse to compute '
            "currents not current magnitudes."
        )

    _check_stc_units(stc)

    src_sel, stc_sel, _ = _stc_src_sel(fwd["src"], stc, on_missing=on_missing)
    gain = fwd["sol"]["data"]
    stc_sel = slice(None) if len(stc_sel) == len(stc.data) else stc_sel
    times = stc.times[start:stop].copy()
    stc_data = stc.data[stc_sel, ..., start:stop].reshape(-1, len(times))
    del stc
    if vector:
        gain = gain.reshape(len(gain), gain.shape[1] // 3, 3)
    gain = gain[:, src_sel].reshape(len(gain), -1)
    # save some memory if possible

    logger.info("Projecting source estimate to sensor space...")
    data = np.dot(gain, stc_data)
    logger.info("[done]")
    return data, times
//  [python]
def _apply_forward(
    fwd, stc, start=None, stop=None, on_missing="raise", use_cps=True, verbose=None
):
    """Apply forward model and return data, times, ch_names."""
    _validate_type(stc, _BaseSourceEstimate, "stc", "SourceEstimate")
    _validate_type(fwd, Forward, "fwd")
    if isinstance(stc, _BaseVectorSourceEstimate):
        vector = True
        fwd = convert_forward_solution(fwd, force_fixed=False, surf_ori=False)
    else:
        vector = False
        if not is_fixed_orient(fwd):
            fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=use_cps)

    if np.all(stc.data > 0):
        warn(
            "Source estimate only contains currents with positive values. "
            'Use pick_ori="normal" when computing the inverse to compute '
            "currents not current magnitudes."
        )

    _check_stc_units(stc)

    src_sel, stc_sel, _ = _stc_src_sel(fwd["src"], stc, on_missing=on_missing)
    gain = fwd["sol"]["data"]
    stc_sel = slice(None) if len(stc_sel) == len(stc.data) else stc_sel
    times = stc.times[start:stop].copy()
    stc_data = stc.data[stc_sel, ..., start:stop].reshape(-1, len(times))
    del stc
    if vector:
        gain = gain.reshape(len(gain), gain.shape[1] // 3, 3)
    gain = gain[:, src_sel].reshape(len(gain), -1)
    # save some memory if possible

    logger.info("Projecting source estimate to sensor space...")
    data = np.dot(gain, stc_data)
    logger.info("[done]")
    return data, times
//  [python]
def boxcar_smooth_vector(x, boxcar, mask=None, lo=None, hi=None, niter=None, return_mask=False):
    """
    Boxcar smooth an input vector.
        - Ignores masked pixels.
        - Allows for iterative positive and negative outliers.
        - Can return the mask separately from the smoothed vector.
    """
    if niter is not None and lo is None and hi is None:
        raise ValueError('Must provide lo or hi if niter provided')

    _mask = numpy.zeros(x.size, dtype=bool) if mask is None else mask
    _x = x if isinstance(x, numpy.ma.MaskedArray) else numpy.ma.MaskedArray(x)
    _x[_mask] = numpy.ma.masked

    sx = interpolate_masked_vector( smooth_masked_vector(_x, boxcar) )

#    pyplot.step(numpy.arange(_x.size), _x.data, where='mid', color='0.3', lw=0.5)
#    pyplot.step(numpy.arange(_x.size), _x, where='mid', color='k', lw=0.5)
#    pyplot.plot(numpy.arange(_x.size), sx, color='r', lw=1)
#    pyplot.show()

    if numpy.all([ x is None for x in [ lo, hi, niter ]]):
        if return_mask:
            return sx, numpy.ma.getmaskarray(_x).copy()
        return sx
    
    _niter = -1 if niter is None else niter
    nrej = numpy.sum(numpy.ma.getmaskarray(_x))
    i=0
    while i > -1:
        sig = numpy.std((_x - sx).compressed())
        mask = numpy.ma.getmaskarray(_x).copy()
        if lo is not None:
            mask = numpy.logical_or(mask, _x.data - sx < -lo*sig)
        if hi is not None:
            mask = numpy.logical_or(mask, _x.data - sx > hi*sig)
        nrej = numpy.sum(mask) - numpy.sum(_x.mask)
#        print('Niter: {0}; Nrej: {1}'.format(i+1, nrej))
        _x[mask] = numpy.ma.masked
        sx = interpolate_masked_vector( smooth_masked_vector(_x, boxcar) )

#        pyplot.step(numpy.arange(_x.size), _x.data, where='mid', color='cyan', lw=0.5)
#        pyplot.step(numpy.arange(_x.size), _x, where='mid', color='k', lw=0.5)
#        pyplot.plot(numpy.arange(_x.size), sx, color='r', lw=1)
#        pyplot.show()

        i += 1
        if i == _niter or nrej == 0:
            break

    pyplot.step(numpy.arange(_x.size), _x.data, where='mid', color='cyan', lw=0.5)
    pyplot.step(numpy.arange(_x.size), _x, where='mid', color='k', lw=0.5)
    pyplot.plot(numpy.arange(_x.size), sx, color='r', lw=1)
    pyplot.show()

    if return_mask:
        return sx, numpy.ma.getmaskarray(_x).copy()
    return sx
//  [python]
def _stride_comb_iter(x):
    """
    Generate cartesian product of strides for all axes
    """

    if not isinstance(x, np.ndarray):
        yield x, "nop"
        return

    stride_set = [(1,)]*x.ndim
    stride_set[-1] = (1, 3, -4)
    if x.ndim > 1:
        stride_set[-2] = (1, 3, -4)
    if x.ndim > 2:
        stride_set[-3] = (1, -4)

    for repeats in itertools.product(*tuple(stride_set)):
        new_shape = [abs(a*b) for a, b in zip(x.shape, repeats)]
        slices = tuple([slice(None, None, repeat) for repeat in repeats])

        # new array with different strides, but same data
        xi = np.empty(new_shape, dtype=x.dtype)
        xi.view(np.uint32).fill(0xdeadbeef)
        xi = xi[slices]
        xi[...] = x
        xi = xi.view(x.__class__)
        assert n.all(xi == x)
        yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])

        # generate also zero strides if possible
        if x.ndim >= 1 and x.shape[-1] == 1:
            s = list(x.strides)
            s[-1] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0"
        if x.ndim >= 2 and x.shape[-2] == 1:
            s = list(x.strides)
            s[-2] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0_x"
        if x.ndim >= 2 and x.shape[:-2] == (1, 1):
            s = list(x.strides)
            s[-1] = 0
            s[-2] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0_0"
//  [python]
def _stride_comb_iter(x):
    """
    Generate cartesian product of strides for all axes
    """

    if not isinstance(x, np.ndarray):
        yield x, "nop"
        return

    stride_set = [(1,)]*x.ndim
    stride_set[-1] = (1, 3, -4)
    if x.ndim > 1:
        stride_set[-2] = (1, 3, -4)
    if x.ndim > 2:
        stride_set[-3] = (1, -4)

    for repeats in itertools.product(*tuple(stride_set)):
        new_shape = [abs(a*b) for a, b in zip(x.shape, repeats)]
        slices = tuple([slice(None, None, repeat) for repeat in repeats])

        # new array with different strides, but same data
        xi = np.empty(new_shape, dtype=x.dtype)
        xi.view(np.uint32).fill(0xdeadbeef)
        xi = xi[slices]
        xi[...] = x
        xi = xi.view(x.__class__)
        assert np.all(xi == x)
        yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])

        # generate also zero strides if possible
        if x.ndim >= 1 and x.shape[-1] == 1:
            s = list(x.strides)
            s[-1] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0"
        if x.ndim >= 2 and x.shape[-2] == 1:
            s = list(x.strides)
            s[-2] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0_x"
        if x.ndim >= 2 and x.shape[:-2] == (1, 1):
            s = list(x.strides)
            s[-1] = 0
            s[-2] = 0
            xi = np.lib.stride_tricks.as_strided(x, strides=s)
            yield xi, "stride_xxx_0_0"
//  [python]
def test_fill_threadidx(self):
        compiled = cuda.jit("void(int32[:])")(fill_threadidx)
        N = 10
        ary = np.ones(N, dtype=np.int32)
        exp = np.arange(N, dtype=np.int32)
        compiled[1, N](ary)
        self.assertTrue(np.all(ary == exp))
//  [python]
def test_fill3d_threadidx(self):
        X, Y, Z = 4, 5, 6

        def c_contigous():
            compiled = cuda.jit("void(int32[:,:,::1])")(fill3d_threadidx)
            ary = np.zeros((X, Y, Z), dtype=np.int32)
            compiled[1, (X, Y, Z)](ary)
            return ary

        def f_contigous():
            compiled = cuda.jit("void(int32[::1,:,:])")(fill3d_threadidx)
            ary = np.asfortranarray(np.zeros((X, Y, Z), dtype=np.int32))
            compiled[1, (X, Y, Z)](ary)
            return ary

        c_res = c_contigous()
        f_res = f_contigous()
        self.assertTrue(np.alltrue(c_res == f_res))
//  [python]
def test_fill3d_threadidx(self):
        X, Y, Z = 4, 5, 6

        def c_contigous():
            compiled = cuda.jit("void(int32[:,:,::1])")(fill3d_threadidx)
            ary = np.zeros((X, Y, Z), dtype=np.int32)
            compiled[1, (X, Y, Z)](ary)
            return ary

        def f_contigous():
            compiled = cuda.jit("void(int32[::1,:,:])")(fill3d_threadidx)
            ary = np.asfortranarray(np.zeros((X, Y, Z), dtype=np.int32))
            compiled[1, (X, Y, Z)](ary)
            return ary

        c_res = c_contigous()
        f_res = f_contigous()
        self.assertTrue(np.all(c_res == f_res))