jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_crop_color_with_rectangle():
    """Regression test: make sure cropping works with a color image"""
    i, j, k = numpy.mgrid[0:10, 0:10, 0:3]
    input_image = (i / 1000.0 + j / 100.0 + k).astype(numpy.float32)
    expected_image = input_image[2:8, 1:9, :]
    workspace, module = make_workspace(input_image)
    module.shape.value = cellprofiler.modules.crop.SH_RECTANGLE
    module.horizontal_limits.set_value((1, 9))
    module.vertical_limits.set_value((2, 8))
    module.remove_rows_and_columns.value = cellprofiler.modules.crop.RM_EDGES
    module.run(workspace)
    output_image = workspace.image_set.get_image(OUTPUT_IMAGE)
    assert numpy.all(output_image.pixel_data == expected_image)
//  [python]
def test_mask_with_objects():
    numpy.random.seed()
    input_image = numpy.random.uniform(size=(20, 10))
    input_objects = numpy.zeros((20, 10), dtype=int)
    input_objects[2:7, 3:8] = 1
    input_objects[12:17, 3:8] = 2
    workspace, module = make_workspace(input_image, crop_objects=input_objects)
    module.shape.value = cellprofiler.modules.crop.SH_OBJECTS
    module.objects_source.value = CROP_OBJECTS
    module.remove_rows_and_columns.value = cellprofiler.modules.crop.RM_NO
    module.run(workspace)
    output_image = workspace.image_set.get_image(OUTPUT_IMAGE)
    assert output_image.has_masking_objects
    assert n.all(input_objects == output_image.labels)
    assert n.all(output_image.mask == (input_objects > 0))
//  [python]
def test_mask_with_objects():
    numpy.random.seed()
    input_image = numpy.random.uniform(size=(20, 10))
    input_objects = numpy.zeros((20, 10), dtype=int)
    input_objects[2:7, 3:8] = 1
    input_objects[12:17, 3:8] = 2
    workspace, module = make_workspace(input_image, crop_objects=input_objects)
    module.shape.value = cellprofiler.modules.crop.SH_OBJECTS
    module.objects_source.value = CROP_OBJECTS
    module.remove_rows_and_columns.value = cellprofiler.modules.crop.RM_NO
    module.run(workspace)
    output_image = workspace.image_set.get_image(OUTPUT_IMAGE)
    assert output_image.has_masking_objects
    assert numpy.all(input_objects == output_image.labels)
    assert numpy.all(output_image.mask == (input_objects > 0))
//  [python]
def test_crop_with_objects():
    numpy.random.seed()
    input_image = numpy.random.uniform(size=(20, 10))
    input_objects = numpy.zeros((20, 10), dtype=int)
    input_objects[2:7, 3:8] = 1
    input_objects[12:17, 3:8] = 2
    workspace, module = make_workspace(input_image, crop_objects=input_objects)
    module.shape.value = cellprofiler.modules.crop.SH_OBJECTS
    module.objects_source.value = CROP_OBJECTS
    module.remove_rows_and_columns.value = cellprofiler.modules.crop.RM_EDGES
    module.run(workspace)
    output_image = workspace.image_set.get_image(OUTPUT_IMAGE)
    assert output_image.has_masking_objects
    assert n.all(input_objects[2:17, 3:8] == output_image.labels)
    assert n.all(output_image.mask == (input_objects[2:17, 3:8] > 0))
    assert n.all(output_image.crop_mask == (input_objects > 0))
//  [python]
def test_crop_with_objects():
    numpy.random.seed()
    input_image = numpy.random.uniform(size=(20, 10))
    input_objects = numpy.zeros((20, 10), dtype=int)
    input_objects[2:7, 3:8] = 1
    input_objects[12:17, 3:8] = 2
    workspace, module = make_workspace(input_image, crop_objects=input_objects)
    module.shape.value = cellprofiler.modules.crop.SH_OBJECTS
    module.objects_source.value = CROP_OBJECTS
    module.remove_rows_and_columns.value = cellprofiler.modules.crop.RM_EDGES
    module.run(workspace)
    output_image = workspace.image_set.get_image(OUTPUT_IMAGE)
    assert output_image.has_masking_objects
    assert numpy.all(input_objects[2:17, 3:8] == output_image.labels)
    assert numpy.all(output_image.mask == (input_objects[2:17, 3:8] > 0))
    assert numpy.all(output_image.crop_mask == (input_objects > 0))
//  [python]
def equal_actions(a1, a2):
  """Test whether the dicts a1 and a2 are equal in each action component."""
  # Assumes a1 and a2 are drawn from the same action space.
  return all([all(a1[k] == a2[k]) for k in a1.keys()])
//  [python]
def equal_actions(a1, a2):
  """Test whether the dicts a1 and a2 are equal in each action component."""
  # Assumes a1 and a2 are drawn from the same action space.
  return np.all([np.all(np.equal(a1[k], a2[k])) for k in a1.keys()])
//  [python]
def __init__(self, diagonal: NDArray):
        if not np.alltrue(diagonal > 0):
            msg = "Diagonal values must all be positive."
            raise ValueError(msg)
        super().__init__(diagonal)
//  [python]
def __init__(self, diagonal: NDArray):
        if not np.all(diagonal > 0):
            msg = "Diagonal values must all be positive."
            raise ValueError(msg)
        super().__init__(diagonal)
//  [python]
def _dilate_shape(shape, dilation):
  """Utility function for computing the shape resulting from a dilation."""
  if not n.all(n.greater(dilation, 0)):
    msg = "All dilations must be positive, got {}."
    raise TypeError(msg.format(dilation))
  dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)
  return tuple(map(core.dilate_dim, shape, dilation))
//  [python]
def _dilate_shape(shape, dilation):
  """Utility function for computing the shape resulting from a dilation."""
  if not np.all(np.greater(dilation, 0)):
    msg = "All dilations must be positive, got {}."
    raise TypeError(msg.format(dilation))
  dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)
  return tuple(map(core.dilate_dim, shape, dilation))
//  [python]
def _export_to_saved_model_graph(self, tensor_map, **unused_kwargs):
    capture_constant_value = tensor_util.constant_value(self.capture)
    if capture_constant_value is None:
      raise ValueError(
          f"Unable to save function {self.function.name} because it "
          f"captures graph tensor {self.capture} from a parent function which "
          "cannot be converted to a constant with `tf.get_static_value`.")

    if numpy.prod(self.capture.shape.as_list()) > 1 and numpy.all(
        capture_constant_value == capture_constant_value.flat[0]):
      # For the common case of a constant array filled with the same
      # value, rebuild the constant op specifically with the shape arg,
      # since otherwise the whole array is written into the node def,
      # causing performance and graph proto size issues (protos cannot be
      # bigger than 2GB).
      copied_tensor = constant_op.constant(
          capture_constant_value.flat[0],
          dtype=self.capture.dtype,
          shape=self.capture.shape)
    else:
      copied_tensor = constant_op.constant(capture_constant_value)

    tensor_map[self.capture] = copied_tensor
    self._exported_tensor = copied_tensor
    return [self.capture]
//  [python]
def __init__(self, eigvec: Union[NDArray, OrthogonalMatrix], eigval: NDArray):
        if not np.all(eigval > 0):
            msg = "Eigenvalues must all be positive."
            raise ValueError(msg)
        super().__init__(eigvec, eigval)
//  [python]
def test_in1d():
    a = [1, 2, 3] * cm
    b = [1, 2] * cm
    assert n.all(n.in1d(b, a))
//  [python]
def test_in1d():
    a = [1, 2, 3] * cm
    b = [1, 2] * cm
    assert np.all(np.in1d(b, a))
//  [python]
def test_isreal_like():
    a = [1, 2, 3] * cm
    assert n.all(n.isreal(a))
    assert n.isrealobj(a)
    assert not n.any(n.iscomplex(a))
    assert not n.iscomplexobj(a)

    b = [1j, 2j, 3j] * cm
    assert not n.any(n.isreal(b))
    assert not n.isrealobj(b)
    assert n.all(n.iscomplex(b))
    assert n.iscomplexobj(b)
//  [python]
def test_isreal_like():
    a = [1, 2, 3] * cm
    assert np.all(np.isreal(a))
    assert np.isrealobj(a)
    assert not np.any(np.iscomplex(a))
    assert not np.iscomplexobj(a)

    b = [1j, 2j, 3j] * cm
    assert not np.any(np.isreal(b))
    assert not np.isrealobj(b)
    assert np.all(np.iscomplex(b))
    assert np.iscomplexobj(b)
//  [python]
def test_match_global_no_float_error_when_axis_aligned():
    a = np.array([[1, 1.1], [-1.3, np.pi]])
    a2, _ = cirq.match_global_phase(a, a)
    a3, _ = cirq.match_global_phase(a * 1j, a * 1j)
    a4, _ = cirq.match_global_phase(-a, -a)
    a5, _ = cirq.match_global_phase(a * -1j, a * -1j)

    assert n.all(a2 == a)
    assert n.all(a3 == a)
    assert n.all(a4 == a)
    assert n.all(a5 == a)
//  [python]
def test_match_global_no_float_error_when_axis_aligned():
    a = np.array([[1, 1.1], [-1.3, np.pi]])
    a2, _ = cirq.match_global_phase(a, a)
    a3, _ = cirq.match_global_phase(a * 1j, a * 1j)
    a4, _ = cirq.match_global_phase(-a, -a)
    a5, _ = cirq.match_global_phase(a * -1j, a * -1j)

    assert np.all(a2 == a)
    assert np.all(a3 == a)
    assert np.all(a4 == a)
    assert np.all(a5 == a)
//  [python]
def _sample_shapes_to_shape(self, sample_shapes, squeeze_dims, sample_ndim):
        is_same = n.all(sample_shapes == sample_shapes[0, :], axis=0)
        shape = [  # type: ignore
            (
                int(sample_shapes[0, i])
                if sample_shapes[0, i] != -1 and is_same[i]
                else None
            )
            for i in range(sample_ndim)
        ]

        return tuple(shape[i] for i in range(len(shape)) if i not in squeeze_dims)
//  [python]
def _sample_shapes_to_shape(self, sample_shapes, squeeze_dims, sample_ndim):
        is_same = np.all(sample_shapes == sample_shapes[0, :], axis=0)
        shape = [  # type: ignore
            (
                int(sample_shapes[0, i])
                if sample_shapes[0, i] != -1 and is_same[i]
                else None
            )
            for i in range(sample_ndim)
        ]

        return tuple(shape[i] for i in range(len(shape)) if i not in squeeze_dims)
//  [python]
def test_variable_set(comm):

    dataset = BinnedStatistic.from_json(os.path.join(data_dir, 'dataset_2d.json'))
    modes = numpy.ones(dataset.shape)

    # add new variable
    dataset['TEST'] = modes
    assert 'TEST' in dataset

    # override existing variable
    dataset['modes'] = modes
    assert numpy.all(dataset['modes'] == 1.0)

    # needs right shape
    with pytest.raises(ValueError):
        dataset['TEST'] = 10.
//  [python]
def _merge_seq_shape(self, shape, sample_index):
        """Merges shapes of sequence items into one shape"""
        if sample_index and not sample_index[0].subscriptable():
            shape = (1, *tuple(shape[sample_index[0].value].tolist()))  # type: ignore
        else:
            is_same = np.all(shape == shape[0, :], axis=0)  # type: ignore
            shape = (len(shape),) + (
                tuple(
                    (
                        int(shape[0, i])  # type: ignore
                        if is_same[i]  # type: ignore
                        else -1
                    )
                    for i in range(shape.shape[1])  # type: ignore
                )
                or (1,)
            )
        return shape
//  [python]
def test_coords_strictly_in_central_image_ortho(self, backend):
        box = np.array([10.1, 10.1, 10.1, 90.0, 90.0, 90.0], dtype=np.float32)
        # coordinates just below lower or exactly at the upper box boundaries:
        coords = np.array([[-1.0e-7, -1.0e-7, -1.0e-7],
                           [-1.0e-7, -1.0e-7,  box[2]],
                           [-1.0e-7,  box[1], -1.0e-7],
                           [ box[0], -1.0e-7, -1.0e-7],
                           [ box[0],  box[1], -1.0e-7],
                           [ box[0], -1.0e-7,  box[2]],
                           [-1.0e-7,  box[1],  box[2]],
                           [ box[0],  box[1],  box[2]]], dtype=np.float32)
        # Check that all test coordinates actually lie below the lower or
        # exactly at the upper box boundary:
        assert n.all((coords < 0.0) | (coords == box[:3]))
        res = distances.apply_PBC(coords, box, backend=backend)
        # Assert all result coordinates lie strictly within the primary image:
        assert n.all(res >= 0.0)
        assert n.all(res < box[:3])
//  [python]
def test_coords_strictly_in_central_image_ortho(self, backend):
        box = np.array([10.1, 10.1, 10.1, 90.0, 90.0, 90.0], dtype=np.float32)
        # coordinates just below lower or exactly at the upper box boundaries:
        coords = np.array([[-1.0e-7, -1.0e-7, -1.0e-7],
                           [-1.0e-7, -1.0e-7,  box[2]],
                           [-1.0e-7,  box[1], -1.0e-7],
                           [ box[0], -1.0e-7, -1.0e-7],
                           [ box[0],  box[1], -1.0e-7],
                           [ box[0], -1.0e-7,  box[2]],
                           [-1.0e-7,  box[1],  box[2]],
                           [ box[0],  box[1],  box[2]]], dtype=np.float32)
        # Check that all test coordinates actually lie below the lower or
        # exactly at the upper box boundary:
        assert np.all((coords < 0.0) | (coords == box[:3]))
        res = distances.apply_PBC(coords, box, backend=backend)
        # Assert all result coordinates lie strictly within the primary image:
        assert np.all(res >= 0.0)
        assert np.all(res < box[:3])
//  [python]
def check_real_and_finite(A):
    """Checks that all elements in a matrix are read and finite"""
    return numpy.alltrue(numpy.isreal(A)) and numpy.alltrue(numpy.isfinite(A))
//  [python]
def check_real_and_finite(A):
    """Checks that all elements in a matrix are read and finite"""
    return numpy.all(numpy.isreal(A)) and numpy.all(numpy.isfinite(A))
//  [python]
def _sanitize_levels(levels, minsize=2):
    """
    Ensure the levels are monotonic. If they are descending, reverse them.
    """
    # NOTE: Matplotlib does not support datetime colormap levels as of 3.5
    levels = inputs._to_numpy_array(levels)
    if levels.ndim != 1 or levels.size < minsize:
        raise ValueError(f'Levels {levels} must be a 1D array with size >= {minsize}.')
    if isinstance(levels, ma.core.MaskedArray):
        levels = levels.filled(np.nan)
    if not inputs._is_numeric(levels) or not np.all(np.isfinite(levels)):
        raise ValueError(f'Levels {levels} does not support non-numeric cmap levels.')
    diffs = np.sign(np.diff(levels))
    if np.all(diffs == 1):
        descending = False
    elif np.all(diffs == -1):
        descending = True
        levels = levels[::-1]
    else:
        raise ValueError(f'Levels {levels} must be monotonic.')
    return levels, descending
//  [python]
def test_get_unique_invidx_low_high_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques_low, idxes_low, srcids_low, dstids_low = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=True,
    )
    uniques_high, idxes_high, srcids_high, dstids_high = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=False,
    )
    assert n.all(
        uniques_low == uniques_high
    ), f"unique is not expected. {uniques_low} != {uniques_high}"
    assert not n.all(
        idxes_low == idxes_high
    ), f"indices is not expected. {idxes_low} == {idxes_high}"
    assert n.all(
        srcids_low == srcids_high
    ), f"srcids is not expected. {srcids_low} != {srcids_high}"
    assert n.all(
        dstids_low == dstids_high
    ), f"dstdis is not expected. {dstids_low} != {dstids_high}"
//  [python]
def test_get_unique_invidx_low_high_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques_low, idxes_low, srcids_low, dstids_low = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=True,
    )
    uniques_high, idxes_high, srcids_high, dstids_high = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=False,
    )
    assert np.all(
        uniques_low == uniques_high
    ), f"unique is not expected. {uniques_low} != {uniques_high}"
    assert not np.all(
        idxes_low == idxes_high
    ), f"indices is not expected. {idxes_low} == {idxes_high}"
    assert np.all(
        srcids_low == srcids_high
    ), f"srcids is not expected. {srcids_low} != {srcids_high}"
    assert np.all(
        dstids_low == dstids_high
    ), f"dstdis is not expected. {dstids_low} != {dstids_high}"
//  [python]
def test_get_unique_invidx_with_numpy(num_nodes, num_edges, nid_begin, nid_end):
    # prepare data for the function
    # generate synthetic edges
    if num_edges > 0:
        srcids = np.random.randint(0, num_nodes, (num_edges,))  # exclusive
        dstids = np.random.randint(
            nid_begin, nid_end, (num_edges,)
        )  # exclusive
    else:
        srcids = np.array([])
        dstids = np.array([])

    assert nid_begin <= nid_end

    # generate unique node-ids for any
    # partition. This list should be sorted.
    # This is equivilant to shuffle_nids in a partition
    unique_nids = np.arange(nid_begin, nid_end)  # exclusive

    # test with numpy unique here
    orig_srcids = srcids.copy()
    orig_dstids = dstids.copy()
    input_arr = np.concatenate([srcids, dstids, unique_nids])

    # test
    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids, dstids, unique_nids
    )

    assert len(uniques) == len(idxes)
    assert n.all(srcids < len(uniques))
    assert n.all(dstids < len(uniques))
    assert n.all(uniques[srcids].sort() == orig_srcids.sort())
    assert n.all(uniques[dstids] == orig_dstids)

    assert n.all(uniques == input_arr[idxes])

    # numpy
    np_uniques, np_idxes, np_inv_idxes = np.unique(
        np.concatenate([orig_srcids, orig_dstids, unique_nids]),
        return_index=True,
        return_inverse=True,
    )

    # test uniques
    assert n.all(np_uniques == uniques)

    # test idxes array
    assert n.all(input_arr[idxes].sort() == input_arr[np_idxes].sort())

    # test srcids, inv_indices
    assert n.all(
        uniques[srcids].sort()
        == np_uniques[np_inv_idxes[0 : len(srcids)]].sort()
    )

    # test dstids, inv_indices
    assert n.all(
        uniques[dstids].sort() == np_uniques[np_inv_idxes[len(srcids) :]].sort()
    )
//  [python]
def test_get_unique_invidx_with_numpy(num_nodes, num_edges, nid_begin, nid_end):
    # prepare data for the function
    # generate synthetic edges
    if num_edges > 0:
        srcids = np.random.randint(0, num_nodes, (num_edges,))  # exclusive
        dstids = np.random.randint(
            nid_begin, nid_end, (num_edges,)
        )  # exclusive
    else:
        srcids = np.array([])
        dstids = np.array([])

    assert nid_begin <= nid_end

    # generate unique node-ids for any
    # partition. This list should be sorted.
    # This is equivilant to shuffle_nids in a partition
    unique_nids = np.arange(nid_begin, nid_end)  # exclusive

    # test with numpy unique here
    orig_srcids = srcids.copy()
    orig_dstids = dstids.copy()
    input_arr = np.concatenate([srcids, dstids, unique_nids])

    # test
    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids, dstids, unique_nids
    )

    assert len(uniques) == len(idxes)
    assert np.all(srcids < len(uniques))
    assert np.all(dstids < len(uniques))
    assert np.all(uniques[srcids].sort() == orig_srcids.sort())
    assert np.all(uniques[dstids] == orig_dstids)

    assert np.all(uniques == input_arr[idxes])

    # numpy
    np_uniques, np_idxes, np_inv_idxes = np.unique(
        np.concatenate([orig_srcids, orig_dstids, unique_nids]),
        return_index=True,
        return_inverse=True,
    )

    # test uniques
    assert np.all(np_uniques == uniques)

    # test idxes array
    assert np.all(input_arr[idxes].sort() == input_arr[np_idxes].sort())

    # test srcids, inv_indices
    assert np.all(
        uniques[srcids].sort()
        == np_uniques[np_inv_idxes[0 : len(srcids)]].sort()
    )

    # test dstids, inv_indices
    assert np.all(
        uniques[dstids].sort() == np_uniques[np_inv_idxes[len(srcids) :]].sort()
    )
//  [python]
def test_get_unique_invidx(num_nodes, num_edges, nid_begin, nid_end):
    # prepare data for the function
    # generate synthetic edges
    if num_edges > 0:
        srcids = np.random.randint(0, num_nodes, (num_edges,))
        dstids = np.random.randint(nid_begin, nid_end, (num_edges,))
    else:
        srcids = np.array([])
        dstids = np.array([])

    assert nid_begin <= nid_end

    # generate unique node-ids for any
    # partition. This list should be sorted.
    # This is equivilant to shuffle_nids in a partition
    unique_nids = np.arange(nid_begin, nid_end)

    # invoke the test target
    uniques, idxes, src_ids, dst_ids = _get_unique_invidx(
        srcids, dstids, unique_nids
    )

    # validate the outputs of this function
    # array uniques should be sorted list of integers.
    assert n.all(
        np.diff(uniques) >= 0
    ), f"Output parameter uniques assert failing."

    # idxes are list of integers
    # these are indices in the concatenated list (srcids, dstids, unique_nids)
    max_idx = len(src_ids) + len(dst_ids) + len(unique_nids)
    assert n.all(idxes >= 0), f"Output parameter idxes has negative values."
    assert n.all(
        idxes < max_idx
    ), f"Output parameter idxes has invalid maximum value."

    # srcids and dstids will be inverse indices in the uniques list
    min_src = np.amin(src_ids)
    max_src = np.amax(src_ids)

    min_dst = np.amin(dst_ids)
    max_dst = np.amax(dst_ids)

    assert (
        len(uniques) > max_src
    ), f"Inverse idx, src_ids, has invalid max value."
    assert min_src >= 0, f"Inverse idx, src_ids has negative values."

    assert len(uniques) > max_dst, f"Inverse idx, dst_ids, invalid max value."
    assert max_dst >= 0, f"Inverse idx, dst_ids has negative values."
//  [python]
def test_get_unique_invidx(num_nodes, num_edges, nid_begin, nid_end):
    # prepare data for the function
    # generate synthetic edges
    if num_edges > 0:
        srcids = np.random.randint(0, num_nodes, (num_edges,))
        dstids = np.random.randint(nid_begin, nid_end, (num_edges,))
    else:
        srcids = np.array([])
        dstids = np.array([])

    assert nid_begin <= nid_end

    # generate unique node-ids for any
    # partition. This list should be sorted.
    # This is equivilant to shuffle_nids in a partition
    unique_nids = np.arange(nid_begin, nid_end)

    # invoke the test target
    uniques, idxes, src_ids, dst_ids = _get_unique_invidx(
        srcids, dstids, unique_nids
    )

    # validate the outputs of this function
    # array uniques should be sorted list of integers.
    assert np.all(
        np.diff(uniques) >= 0
    ), f"Output parameter uniques assert failing."

    # idxes are list of integers
    # these are indices in the concatenated list (srcids, dstids, unique_nids)
    max_idx = len(src_ids) + len(dst_ids) + len(unique_nids)
    assert np.all(idxes >= 0), f"Output parameter idxes has negative values."
    assert np.all(
        idxes < max_idx
    ), f"Output parameter idxes has invalid maximum value."

    # srcids and dstids will be inverse indices in the uniques list
    min_src = np.amin(src_ids)
    max_src = np.amax(src_ids)

    min_dst = np.amin(dst_ids)
    max_dst = np.amax(dst_ids)

    assert (
        len(uniques) > max_src
    ), f"Inverse idx, src_ids, has invalid max value."
    assert min_src >= 0, f"Inverse idx, src_ids has negative values."

    assert len(uniques) > max_dst, f"Inverse idx, dst_ids, invalid max value."
    assert max_dst >= 0, f"Inverse idx, dst_ids has negative values."
//  [python]
def test_get_unique_invidx_low_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=True,
    )
    expected_unqiues = np.array(
        [0, 3, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    )
    expected_idxes = np.array(
        [1, 2, 7, 6, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
    )
    expected_srcids = np.array([8, 0, 1, 1, 0, 1, 3, 2, 8, 6])
    expected_dstids = np.array([4, 10, 6, 7, 4, 11, 10, 7, 8, 10])
    assert n.all(
        uniques == expected_unqiues
    ), f"unique is not expected. {uniques} != {expected_unqiues}"
    assert n.all(
        idxes == expected_idxes
    ), f"indices is not expected. {idxes} != {expected_idxes}"
    assert n.all(
        srcids == expected_srcids
    ), f"srcids is not expected. {srcids} != {expected_srcids}"
    assert n.all(
        dstids == expected_dstids
    ), f"dstdis is not expected. {dstids} != {expected_dstids}"
//  [python]
def test_get_unique_invidx_low_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=True,
    )
    expected_unqiues = np.array(
        [0, 3, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    )
    expected_idxes = np.array(
        [1, 2, 7, 6, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
    )
    expected_srcids = np.array([8, 0, 1, 1, 0, 1, 3, 2, 8, 6])
    expected_dstids = np.array([4, 10, 6, 7, 4, 11, 10, 7, 8, 10])
    assert np.all(
        uniques == expected_unqiues
    ), f"unique is not expected. {uniques} != {expected_unqiues}"
    assert np.all(
        idxes == expected_idxes
    ), f"indices is not expected. {idxes} != {expected_idxes}"
    assert np.all(
        srcids == expected_srcids
    ), f"srcids is not expected. {srcids} != {expected_srcids}"
    assert np.all(
        dstids == expected_dstids
    ), f"dstdis is not expected. {dstids} != {expected_dstids}"
//  [python]
def test_get_unique_invidx_high_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=False,
    )
    expected_unqiues = np.array(
        [0, 3, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    )
    expected_idxes = np.array(
        [1, 2, 7, 6, 10, 21, 9, 13, 0, 25, 11, 15, 28, 29]
    )
    expected_srcids = np.array([8, 0, 1, 1, 0, 1, 3, 2, 8, 6])
    expected_dstids = np.array([4, 10, 6, 7, 4, 11, 10, 7, 8, 10])
    assert n.all(
        uniques == expected_unqiues
    ), f"unique is not expected. {uniques} != {expected_unqiues}"
    assert n.all(
        idxes == expected_idxes
    ), f"indices is not expected. {idxes} != {expected_idxes}"
    assert n.all(
        srcids == expected_srcids
    ), f"srcids is not expected. {srcids} != {expected_srcids}"
    assert n.all(
        dstids == expected_dstids
    ), f"dstdis is not expected. {dstids} != {expected_dstids}"
//  [python]
def test_get_unique_invidx_high_mem():
    srcids = np.array([14, 0, 3, 3, 0, 3, 9, 5, 14, 12])
    dstids = np.array([10, 16, 12, 13, 10, 17, 16, 13, 14, 16])
    unique_nids = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

    uniques, idxes, srcids, dstids = _get_unique_invidx(
        srcids,
        dstids,
        unique_nids,
        low_mem=False,
    )
    expected_unqiues = np.array(
        [0, 3, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    )
    expected_idxes = np.array(
        [1, 2, 7, 6, 10, 21, 9, 13, 0, 25, 11, 15, 28, 29]
    )
    expected_srcids = np.array([8, 0, 1, 1, 0, 1, 3, 2, 8, 6])
    expected_dstids = np.array([4, 10, 6, 7, 4, 11, 10, 7, 8, 10])
    assert np.all(
        uniques == expected_unqiues
    ), f"unique is not expected. {uniques} != {expected_unqiues}"
    assert np.all(
        idxes == expected_idxes
    ), f"indices is not expected. {idxes} != {expected_idxes}"
    assert np.all(
        srcids == expected_srcids
    ), f"srcids is not expected. {srcids} != {expected_srcids}"
    assert np.all(
        dstids == expected_dstids
    ), f"dstdis is not expected. {dstids} != {expected_dstids}"
//  [python]
def get_mmax(self, catalogue, config):
        """
        Calculates maximum magnitude

        :param catalogue:
            Instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue

        :param dict config:
            Configuration parameters - including:
            * 'number_earthquakes': Number of largest magnitudes to consider
            * 'number_samples' [optional]: Number of samples for integral {default=51}
            * 'maximum_iterations' [optional]: Maximum number of iterations {default=100}
            * 'tolerance' [optional]: Magnitude difference threshold for iterstor stability {default=0.05}

        :returns:
            Maximum magnitude and its uncertainty
        """
        config = check_config(config)

        # Unlike the exponential distributions, if the input mmax is
        # greater than the observed mmax the integral expands rapidly.
        # Therefore, only observed mmax is considered
        max_loc = np.argmax(catalogue.data["magnitude"])
        obsmax = catalogue.data["magnitude"][max_loc]
        if (
            not (isinstance(catalogue.data["sigmaMagnitude"], np.ndarray))
            or (len(catalogue.data["sigmaMagnitude"]) == 0)
            or n.all(n.isnan(catalogue.data["sigmaMagnitude"]))
        ):
            obsmaxsig = 0.0
        else:
            obsmaxsig = catalogue.data["sigmaMagnitude"][max_loc]

        # Find number_eqs largest events
        n_evts = np.shape(catalogue.data["magnitude"])[0]
        if n_evts <= config["number_earthquakes"]:
            # Catalogue smaller than number of required events
            mag = np.copy(catalogue.data["magnitude"])
            neq = float(np.shape(mag)[0])
        else:
            # Select number_eqs largest events
            mag = np.sort(catalogue.data["magnitude"], kind="quicksort")
            mag = mag[-config["number_earthquakes"] :]
            neq = float(config["number_earthquakes"])

        mmin = np.min(mag)
        # Get smoothing factor
        hfact = self.h_smooth(mag)
        mmax = np.copy(obsmax)
        d_t = mmax.item() - 0.0
        iterator = 0
        while d_t > config["tolerance"]:
            # Generate exponentially spaced samples
            magval = _get_exponential_spaced_values(
                mmin, mmax.item(), config["number_samples"]
            )

            # Evaluate integral function using Simpson's method
            delta = self._kijko_npg_intfunc_simps(
                magval, mag, mmax.item(), hfact, neq
            )
            tmmax = obsmax + delta
            d_t = np.abs(tmmax - mmax.item())
            mmax = np.copy(tmmax)
            iterator += 1
            if iterator > config["maximum_iterations"]:
                print(
                    "Kijko-Non-Parametric Gaussian estimator reached"
                    "maximum # of iterations"
                )
                d_t = -np.inf
        return mmax.item(), np.sqrt(
            obsmaxsig**2.0 + (mmax.item() - obsmax) ** 2.0
        )
//  [python]
def get_mmax(self, catalogue, config):
        """
        Calculates maximum magnitude

        :param catalogue:
            Instance of :class: openquake.hmtk.seismicity.catalogue.Catalogue

        :param dict config:
            Configuration parameters - including:
            * 'number_earthquakes': Number of largest magnitudes to consider
            * 'number_samples' [optional]: Number of samples for integral {default=51}
            * 'maximum_iterations' [optional]: Maximum number of iterations {default=100}
            * 'tolerance' [optional]: Magnitude difference threshold for iterstor stability {default=0.05}

        :returns:
            Maximum magnitude and its uncertainty
        """
        config = check_config(config)

        # Unlike the exponential distributions, if the input mmax is
        # greater than the observed mmax the integral expands rapidly.
        # Therefore, only observed mmax is considered
        max_loc = np.argmax(catalogue.data["magnitude"])
        obsmax = catalogue.data["magnitude"][max_loc]
        if (
            not (isinstance(catalogue.data["sigmaMagnitude"], np.ndarray))
            or (len(catalogue.data["sigmaMagnitude"]) == 0)
            or np.all(np.isnan(catalogue.data["sigmaMagnitude"]))
        ):
            obsmaxsig = 0.0
        else:
            obsmaxsig = catalogue.data["sigmaMagnitude"][max_loc]

        # Find number_eqs largest events
        n_evts = np.shape(catalogue.data["magnitude"])[0]
        if n_evts <= config["number_earthquakes"]:
            # Catalogue smaller than number of required events
            mag = np.copy(catalogue.data["magnitude"])
            neq = float(np.shape(mag)[0])
        else:
            # Select number_eqs largest events
            mag = np.sort(catalogue.data["magnitude"], kind="quicksort")
            mag = mag[-config["number_earthquakes"] :]
            neq = float(config["number_earthquakes"])

        mmin = np.min(mag)
        # Get smoothing factor
        hfact = self.h_smooth(mag)
        mmax = np.copy(obsmax)
        d_t = mmax.item() - 0.0
        iterator = 0
        while d_t > config["tolerance"]:
            # Generate exponentially spaced samples
            magval = _get_exponential_spaced_values(
                mmin, mmax.item(), config["number_samples"]
            )

            # Evaluate integral function using Simpson's method
            delta = self._kijko_npg_intfunc_simps(
                magval, mag, mmax.item(), hfact, neq
            )
            tmmax = obsmax + delta
            d_t = np.abs(tmmax - mmax.item())
            mmax = np.copy(tmmax)
            iterator += 1
            if iterator > config["maximum_iterations"]:
                print(
                    "Kijko-Non-Parametric Gaussian estimator reached"
                    "maximum # of iterations"
                )
                d_t = -np.inf
        return mmax.item(), np.sqrt(
            obsmaxsig**2.0 + (mmax.item() - obsmax) ** 2.0
        )
//  [python]
def is_positive_semidefinite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
    """
    Tests mat for positive semidefiniteness.

    Checking whether all eigenvalues of mat are nonnegative within a certain tolerance

    Parameters
    ----------
    mat : np.ndarray
        Matrix to test for positive semidefiniteness
    tol : float, optional
        Absolute tolerance in determining nonnegativity due to loss of precision
        when computing the eigenvalues of mat. Defaults to :data:`ALMOST_ZERO`

    Returns
    -------
    res : bool or array of bool

    See Also
    --------
    is_Hermitian
    is_positive_definite
    """
    if not is_Hermitian(mat):
        return False
    try:
        v = np.linalg.eigvalsh(mat)
    except np.linalg.LinAlgError:
        return False
    return n.all(v > -tol)
//  [python]
def is_positive_semidefinite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
    """
    Tests mat for positive semidefiniteness.

    Checking whether all eigenvalues of mat are nonnegative within a certain tolerance

    Parameters
    ----------
    mat : np.ndarray
        Matrix to test for positive semidefiniteness
    tol : float, optional
        Absolute tolerance in determining nonnegativity due to loss of precision
        when computing the eigenvalues of mat. Defaults to :data:`ALMOST_ZERO`

    Returns
    -------
    res : bool or array of bool

    See Also
    --------
    is_Hermitian
    is_positive_definite
    """
    if not is_Hermitian(mat):
        return False
    try:
        v = np.linalg.eigvalsh(mat)
    except np.linalg.LinAlgError:
        return False
    return np.all(v > -tol)
//  [python]
def test_coplanar(self):
        # Check that the coplanar point output option indeed works
        points = np.random.rand(10, 2)
        points = np.r_[points, points]  # duplicate input data

        tri = qhull.Delaunay(points)

        assert_(len(np.unique(tri.simplices.ravel())) == len(points)//2)
        assert_(len(tri.coplanar) == len(points)//2)

        assert_(len(np.unique(tri.coplanar[:,2])) == len(points)//2)

        assert_(np.alltrue(tri.vertex_to_simplex >= 0))
//  [python]
def test_coplanar(self):
        # Check that the coplanar point output option indeed works
        points = np.random.rand(10, 2)
        points = np.r_[points, points]  # duplicate input data

        tri = qhull.Delaunay(points)

        assert_(len(np.unique(tri.simplices.ravel())) == len(points)//2)
        assert_(len(tri.coplanar) == len(points)//2)

        assert_(len(np.unique(tri.coplanar[:,2])) == len(points)//2)

        assert_(np.all(tri.vertex_to_simplex >= 0))
//  [python]
def test_ridges(self, name):
        # Check that the ridges computed by Voronoi indeed separate
        # the regions of nearest neighborhood, by comparing the result
        # to KDTree.

        points = DATASETS[name]

        tree = KDTree(points)
        vor = qhull.Voronoi(points)

        for p, v in vor.ridge_dict.items():
            # consider only finite ridges
            if not np.alltrue(np.asarray(v) >= 0):
                continue

            ridge_midpoint = vor.vertices[v].mean(axis=0)
            d = 1e-6 * (points[p[0]] - ridge_midpoint)

            dist, k = tree.query(ridge_midpoint + d, k=1)
            assert_equal(k, p[0])

            dist, k = tree.query(ridge_midpoint - d, k=1)
            assert_equal(k, p[1])
//  [python]
def test_ridges(self, name):
        # Check that the ridges computed by Voronoi indeed separate
        # the regions of nearest neighborhood, by comparing the result
        # to KDTree.

        points = DATASETS[name]

        tree = KDTree(points)
        vor = qhull.Voronoi(points)

        for p, v in vor.ridge_dict.items():
            # consider only finite ridges
            if not np.all(np.asarray(v) >= 0):
                continue

            ridge_midpoint = vor.vertices[v].mean(axis=0)
            d = 1e-6 * (points[p[0]] - ridge_midpoint)

            dist, k = tree.query(ridge_midpoint + d, k=1)
            assert_equal(k, p[0])

            dist, k = tree.query(ridge_midpoint - d, k=1)
            assert_equal(k, p[1])
//  [python]
def test_input_unmodified(
        self, boundary, nan_treatment, normalize_kernel, preserve_nan, dtype
    ):
        """
        Test that convolve works correctly when inputs are lists
        """

        array = [1.0, 4.0, 5.0, 6.0, 5.0, 7.0, 8.0]
        kernel = [0.2, 0.6, 0.2]
        x = np.array(array, dtype=dtype)
        y = np.array(kernel, dtype=dtype)

        # Make pseudoimmutable
        x.flags.writeable = False
        y.flags.writeable = False

        convolve(
            x,
            y,
            boundary=boundary,
            nan_treatment=nan_treatment,
            normalize_kernel=normalize_kernel,
            preserve_nan=preserve_nan,
        )

        assert np.all(np.array(array, dtype=dtype) == x)
        assert np.all(np.array(kernel, dtype=dtype) == y)
//  [python]
def test_lecun_init_torch():
    nseed = args.seed
    random.seed(nseed)
    torch.manual_seed(nseed)
    numpy.random.seed(nseed)
    os.environ["CHAINER_SEED"] = str(nseed)
    import espnet.nets.pytorch_backend.e2e_asr as m

    model = m.E2E(40, 5, args)
    b = model.ctc.ctc_lo.bias.data.numpy()
    assert numpy.all(b == 0.0)
    w = model.ctc.ctc_lo.weight.data.numpy()
    numpy.testing.assert_allclose(w.mean(), 0.0, 1e-2, 1e-2)
    numpy.testing.assert_allclose(w.var(), 1.0 / w.shape[1], 1e-2, 1e-2)

    for name, p in model.named_parameters():
        print(name)
        data = p.data.numpy()
        if "embed" in name:
            numpy.testing.assert_allclose(data.mean(), 0.0, 5e-2, 5e-2)
            numpy.testing.assert_allclose(data.var(), 1.0, 5e-2, 5e-2)
        elif "dec.decoder.0.bias_ih" in name:
            assert data.sum() == data.size // 4
        elif "dec.decoder.1.bias_ih" in name:
            assert data.sum() == data.size // 4
        elif data.ndim == 1:
            assert numpy.all(data == 0.0)
        else:
            numpy.testing.assert_allclose(data.mean(), 0.0, 5e-2, 5e-2)
            numpy.testing.assert_allclose(
                data.var(), 1.0 / numpy.prod(data.shape[1:]), 5e-2, 5e-2
            )
//  [python]
def test_unity_3(self, boundary):
        """
        Test that a unit kernel with three elements returns the same array
        (except when boundary is None).
        """

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

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

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

        if boundary is None:
            assert np.all(z == np.array([0.0, 2.0, 0.0], dtype=">f8"))
        else:
            assert np.all(z == x)
//  [python]
def test_track_split():
    """Track an object that splits"""
    labels1 = numpy.zeros((11, 9), int)
    labels1[1:10, 1:8] = 1
    labels2 = numpy.zeros((10, 10), int)
    labels2[1:6, 1:8] = 1
    labels2[6:10, 1:8] = 2

    def fn(module, workspace, idx):
        if idx == 0:
            module.pixel_radius.value = 5
            module.tracking_method.value = "Distance"

    measurements = runTrackObjects((labels1, labels2, labels2), fn)

    def m(feature, idx):
        name = "_".join((cellprofiler.modules.trackobjects.F_PREFIX, feature, "5"))
        values = measurements.get_measurement(OBJECT_NAME, name, idx + 1)
        assert len(values) == 2
        return values

    labels = m(cellprofiler.modules.trackobjects.F_LABEL, 2)
    assert len(labels) == 2
    assert n.all(labels == 1)
    parents = m(cellprofiler.modules.trackobjects.F_PARENT_OBJECT_NUMBER, 1)
    assert n.all(parents == 1)
    assert n.all(m(cellprofiler.modules.trackobjects.F_PARENT_IMAGE_NUMBER, 1) == 1)
    parents = m(cellprofiler.modules.trackobjects.F_PARENT_OBJECT_NUMBER, 2)
    assert n.all(parents == numpy.array([1, 2]))
    assert n.all(m(cellprofiler.modules.trackobjects.F_PARENT_IMAGE_NUMBER, 2) == 2)

    def m(feature):
        name = "_".join(
            (cellprofiler.modules.trackobjects.F_PREFIX, feature, OBJECT_NAME, "5")
        )
        return measurements.get_measurement("Image", name, measurements.get_image_numbers())[1]

    assert m(cellprofiler.modules.trackobjects.F_NEW_OBJECT_COUNT) == 0
    assert m(cellprofiler.modules.trackobjects.F_LOST_OBJECT_COUNT) == 0
    assert m(cellprofiler.modules.trackobjects.F_SPLIT_COUNT) == 1
    assert m(cellprofiler.modules.trackobjects.F_MERGE_COUNT) == 0
    check_relationships(
        measurements, [1, 1, 2, 2], [1, 1, 1, 2], [2, 2, 3, 3], [1, 2, 1, 2]
    )
//  [python]
def test_track_split():
    """Track an object that splits"""
    labels1 = numpy.zeros((11, 9), int)
    labels1[1:10, 1:8] = 1
    labels2 = numpy.zeros((10, 10), int)
    labels2[1:6, 1:8] = 1
    labels2[6:10, 1:8] = 2

    def fn(module, workspace, idx):
        if idx == 0:
            module.pixel_radius.value = 5
            module.tracking_method.value = "Distance"

    measurements = runTrackObjects((labels1, labels2, labels2), fn)

    def m(feature, idx):
        name = "_".join((cellprofiler.modules.trackobjects.F_PREFIX, feature, "5"))
        values = measurements.get_measurement(OBJECT_NAME, name, idx + 1)
        assert len(values) == 2
        return values

    labels = m(cellprofiler.modules.trackobjects.F_LABEL, 2)
    assert len(labels) == 2
    assert numpy.all(labels == 1)
    parents = m(cellprofiler.modules.trackobjects.F_PARENT_OBJECT_NUMBER, 1)
    assert numpy.all(parents == 1)
    assert numpy.all(m(cellprofiler.modules.trackobjects.F_PARENT_IMAGE_NUMBER, 1) == 1)
    parents = m(cellprofiler.modules.trackobjects.F_PARENT_OBJECT_NUMBER, 2)
    assert numpy.all(parents == numpy.array([1, 2]))
    assert numpy.all(m(cellprofiler.modules.trackobjects.F_PARENT_IMAGE_NUMBER, 2) == 2)

    def m(feature):
        name = "_".join(
            (cellprofiler.modules.trackobjects.F_PREFIX, feature, OBJECT_NAME, "5")
        )
        return measurements.get_measurement("Image", name, measurements.get_image_numbers())[1]

    assert m(cellprofiler.modules.trackobjects.F_NEW_OBJECT_COUNT) == 0
    assert m(cellprofiler.modules.trackobjects.F_LOST_OBJECT_COUNT) == 0
    assert m(cellprofiler.modules.trackobjects.F_SPLIT_COUNT) == 1
    assert m(cellprofiler.modules.trackobjects.F_MERGE_COUNT) == 0
    check_relationships(
        measurements, [1, 1, 2, 2], [1, 1, 1, 2], [2, 2, 3, 3], [1, 2, 1, 2]
    )
//  [python]
def test_lecun_init_chainer():
    nseed = args.seed
    random.seed(nseed)
    numpy.random.seed(nseed)
    os.environ["CHAINER_SEED"] = str(nseed)
    import espnet.nets.chainer_backend.e2e_asr as m

    model = m.E2E(40, 5, args)
    b = model.ctc.ctc_lo.b.data
    assert numpy.all(b == 0.0)
    w = model.ctc.ctc_lo.W.data
    numpy.testing.assert_allclose(w.mean(), 0.0, 1e-2, 1e-2)
    numpy.testing.assert_allclose(w.var(), 1.0 / w.shape[1], 1e-2, 1e-2)

    for name, p in model.namedparams():
        print(name)
        data = p.data
        if "rnn0/upward/b" in name:
            assert data.sum() == data.size // 4
        elif "rnn1/upward/b" in name:
            assert data.sum() == data.size // 4
        elif "embed" in name:
            numpy.testing.assert_allclose(data.mean(), 0.0, 5e-2, 5e-2)
            numpy.testing.assert_allclose(data.var(), 1.0, 5e-2, 5e-2)
        elif data.ndim == 1:
            assert numpy.all(data == 0.0)
        else:
            numpy.testing.assert_allclose(data.mean(), 0.0, 5e-2, 5e-2)
            numpy.testing.assert_allclose(
                data.var(), 1.0 / numpy.prod(data.shape[1:]), 5e-2, 5e-2
            )
//  [python]
def test_input_unmodified_with_nan(
        self, boundary, nan_treatment, normalize_kernel, preserve_nan, dtype
    ):
        """
        Test that convolve doesn't modify the input data
        """

        array = [1.0, 4.0, 5.0, np.nan, 5.0, 7.0, 8.0]
        kernel = [0.2, 0.6, 0.2]
        x = np.array(array, dtype=dtype)
        y = np.array(kernel, dtype=dtype)

        # Make pseudoimmutable
        x.flags.writeable = False
        y.flags.writeable = False

        # make copies for post call comparison
        x_copy = x.copy()
        y_copy = y.copy()

        convolve(
            x,
            y,
            boundary=boundary,
            nan_treatment=nan_treatment,
            normalize_kernel=normalize_kernel,
            preserve_nan=preserve_nan,
        )

        # ( NaN == NaN ) = False
        # Only compare non NaN values for canonical equivalence
        # and then check NaN explicitly with np.isnan()
        array_is_nan = np.isnan(array)
        kernel_is_nan = np.isnan(kernel)
        array_not_nan = ~array_is_nan
        kernel_not_nan = ~kernel_is_nan
        assert n.all(x_copy[array_not_nan] == x[array_not_nan])
        assert n.all(y_copy[kernel_not_nan] == y[kernel_not_nan])
        assert n.all(np.isnan(x[array_is_nan]))
        assert n.all(np.isnan(y[kernel_is_nan]))
//  [python]
def test_input_unmodified_with_nan(
        self, boundary, nan_treatment, normalize_kernel, preserve_nan, dtype
    ):
        """
        Test that convolve doesn't modify the input data
        """

        array = [1.0, 4.0, 5.0, np.nan, 5.0, 7.0, 8.0]
        kernel = [0.2, 0.6, 0.2]
        x = np.array(array, dtype=dtype)
        y = np.array(kernel, dtype=dtype)

        # Make pseudoimmutable
        x.flags.writeable = False
        y.flags.writeable = False

        # make copies for post call comparison
        x_copy = x.copy()
        y_copy = y.copy()

        convolve(
            x,
            y,
            boundary=boundary,
            nan_treatment=nan_treatment,
            normalize_kernel=normalize_kernel,
            preserve_nan=preserve_nan,
        )

        # ( NaN == NaN ) = False
        # Only compare non NaN values for canonical equivalence
        # and then check NaN explicitly with np.isnan()
        array_is_nan = np.isnan(array)
        kernel_is_nan = np.isnan(kernel)
        array_not_nan = ~array_is_nan
        kernel_not_nan = ~kernel_is_nan
        assert np.all(x_copy[array_not_nan] == x[array_not_nan])
        assert np.all(y_copy[kernel_not_nan] == y[kernel_not_nan])
        assert np.all(np.isnan(x[array_is_nan]))
        assert np.all(np.isnan(y[kernel_is_nan]))