jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_filter_by_fuzzy_rule():
    labels = numpy.zeros((10, 20), int)
    labels[3:5, 4:9] = 1
    labels[7:9, 6:12] = 2
    labels[4:9, 14:18] = 3
    workspace, module = make_workspace({"MyObjects": labels})
    assert isinstance(
        module, cellprofiler.modules.filterobjects.FilterByObjectMeasurement
    )
    m = workspace.measurements
    m.add_measurement("MyObjects", "MyMeasurement", numpy.array([1.5, 2.3, 1.8]))
    rules_file_contents = "IF (MyObjects_MMeasurement > 2.0, [1.0,-1.0], [-1.0,1.0])\n"
    rules_path = tempfile.mktemp()
    fd = open(rules_path, "wt")
    try:
        fd.write(rules_file_contents)
        fd.close()
        rules_dir, rules_file = os.path.split(rules_path)
        module.x_name.value = "MyObjects"
        module.mode.value = cellprofiler.modules.filterobjects.MODE_RULES
        module.rules_file_name.value = rules_file
        module.rules_directory.dir_choice = (
            cellprofiler_core.preferences.ABSOLUTE_FOLDER_NAME
        )
        module.rules_directory.custom_path = rules_dir
        module.y_name.value = "MyTargetObjects"
        module.allow_fuzzy.value=True
        module.run(workspace)
        target_objects = workspace.object_set.get_objects("MyTargetObjects")
        target_labels = target_objects.segmented
        assert numpy.all(target_labels[labels == 2] > 0)
        assert numpy.all(target_labels[labels != 2] == 0)
        module.allow_fuzzy.value=False
        with pytest.raises(AssertionError):
            module.run(workspace)
    finally:
        os.remove(rules_path)
//  [python]
def valueIsDefault(self):
        """Returns True if this parameter's value is equal to the default value."""
        return n.all(self.value() == self.defaultValue())
//  [python]
def valueIsDefault(self):
        """Returns True if this parameter's value is equal to the default value."""
        return numpy.all(self.value() == self.defaultValue())
//  [python]
def test_keep_maximal_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, 2, 4] = 1
    labels[:, 4:6, 8:15] = 2
    labels[:, 8, 15] = 3

    expected = numpy.zeros_like(labels)
    expected[labels == 2] = 1

    workspace, module = make_workspace({INPUT_OBJECTS: labels})

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MAXIMAL

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_maximal_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, 2, 4] = 1
    labels[:, 4:6, 8:15] = 2
    labels[:, 8, 15] = 3

    expected = numpy.zeros_like(labels)
    expected[labels == 2] = 1

    workspace, module = make_workspace({INPUT_OBJECTS: labels})

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MAXIMAL

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert numpy.all(labels.segmented == expected)
//  [python]
def test_keep_minimal_per_object_both_parents_image():
    labels = numpy.zeros((10, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 2

    sub_labels = numpy.zeros((10, 20), int)
    sub_labels[2, 4] = 1
    sub_labels[4:6, 8:15] = 2
    sub_labels[8, 15] = 3

    expected = numpy.zeros_like(sub_labels)
    expected[2, 4] = 1
    expected[8, 15] = 2

    workspace, module = make_workspace(
        {INPUT_OBJECTS: sub_labels, ENCLOSING_OBJECTS: labels}
    )

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.enclosing_object_name.value = ENCLOSING_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = (
        cellprofiler.modules.filterobjects.FI_MINIMAL_PER_OBJECT
    )
    module.per_object_assignment.value = cellprofiler.modules.filterobjects.PO_BOTH

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_minimal_per_object_both_parents_image():
    labels = numpy.zeros((10, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 2

    sub_labels = numpy.zeros((10, 20), int)
    sub_labels[2, 4] = 1
    sub_labels[4:6, 8:15] = 2
    sub_labels[8, 15] = 3

    expected = numpy.zeros_like(sub_labels)
    expected[2, 4] = 1
    expected[8, 15] = 2

    workspace, module = make_workspace(
        {INPUT_OBJECTS: sub_labels, ENCLOSING_OBJECTS: labels}
    )

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.enclosing_object_name.value = ENCLOSING_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = (
        cellprofiler.modules.filterobjects.FI_MINIMAL_PER_OBJECT
    )
    module.per_object_assignment.value = cellprofiler.modules.filterobjects.PO_BOTH

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert numpy.all(labels.segmented == expected)
//  [python]
def setDefault(self, val):
        """Set the default value for this parameter."""
        if n.all(self.opts['default'] == val):
            return
        self.opts['default'] = val
        self.sigDefaultChanged.emit(self, val)
//  [python]
def setDefault(self, val):
        """Set the default value for this parameter."""
        if numpy.all(self.opts['default'] == val):
            return
        self.opts['default'] = val
        self.sigDefaultChanged.emit(self, val)
//  [python]
def test_keep_maximal_both_parents_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, :, :10] = 1
    labels[:, :, 10:] = 2

    sub_labels = numpy.zeros((2, 10, 20), int)
    sub_labels[:, 2, 4] = 1
    sub_labels[:, 4:6, 8:15] = 2
    sub_labels[:, 8, 15] = 3

    expected = numpy.zeros_like(sub_labels)
    expected[sub_labels == 2] = 1

    workspace, module = make_workspace(
        {INPUT_OBJECTS: sub_labels, ENCLOSING_OBJECTS: labels}
    )

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.enclosing_object_name.value = ENCLOSING_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = (
        cellprofiler.modules.filterobjects.FI_MAXIMAL_PER_OBJECT
    )
    module.per_object_assignment.value = cellprofiler.modules.filterobjects.PO_BOTH

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_maximal_both_parents_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, :, :10] = 1
    labels[:, :, 10:] = 2

    sub_labels = numpy.zeros((2, 10, 20), int)
    sub_labels[:, 2, 4] = 1
    sub_labels[:, 4:6, 8:15] = 2
    sub_labels[:, 8, 15] = 3

    expected = numpy.zeros_like(sub_labels)
    expected[sub_labels == 2] = 1

    workspace, module = make_workspace(
        {INPUT_OBJECTS: sub_labels, ENCLOSING_OBJECTS: labels}
    )

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.enclosing_object_name.value = ENCLOSING_OBJECTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = (
        cellprofiler.modules.filterobjects.FI_MAXIMAL_PER_OBJECT
    )
    module.per_object_assignment.value = cellprofiler.modules.filterobjects.PO_BOTH

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    assert numpy.all(labels.segmented == expected)
//  [python]
def setValue(self, value, blockSignal=None):
        """
        Set the value of this Parameter; return the actual value that was set.
        (this may be different from the value that was requested)
        """
        try:
            if blockSignal is not None:
                self.sigValueChanged.disconnect(blockSignal)
            if n.all(self.opts['value'] == value):
                return value
            self.opts['value'] = value
            self.sigValueChanged.emit(self, value)
        finally:
            if blockSignal is not None:
                self.sigValueChanged.connect(blockSignal)
            
        return value
//  [python]
def setValue(self, value, blockSignal=None):
        """
        Set the value of this Parameter; return the actual value that was set.
        (this may be different from the value that was requested)
        """
        try:
            if blockSignal is not None:
                self.sigValueChanged.disconnect(blockSignal)
            if numpy.all(self.opts['value'] == value):
                return value
            self.opts['value'] = value
            self.sigValueChanged.emit(self, value)
        finally:
            if blockSignal is not None:
                self.sigValueChanged.connect(blockSignal)
            
        return value
//  [python]
def test_keep_removed_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, 2, 4] = 1
    labels[:, 4:6, 8:15] = 2
    labels[:, 8, 15] = 3

    expected = numpy.zeros_like(labels)
    expected[labels == 2] = 1

    expected_removed = numpy.zeros_like(labels)
    expected_removed[labels == 1] = 1
    expected_removed[labels == 3] = 2


    workspace, module = make_workspace({INPUT_OBJECTS: labels})

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.keep_removed_objects.value = True
    module.removed_objects_name.value = "RemovedObjects"
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MAXIMAL

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    removed_labels = workspace.object_set.get_objects("RemovedObjects")

    assert n.all(labels.segmented == expected)

    assert n.all(removed_labels.segmented == expected_removed)
//  [python]
def test_keep_removed_volume():
    labels = numpy.zeros((2, 10, 20), int)
    labels[:, 2, 4] = 1
    labels[:, 4:6, 8:15] = 2
    labels[:, 8, 15] = 3

    expected = numpy.zeros_like(labels)
    expected[labels == 2] = 1

    expected_removed = numpy.zeros_like(labels)
    expected_removed[labels == 1] = 1
    expected_removed[labels == 3] = 2


    workspace, module = make_workspace({INPUT_OBJECTS: labels})

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.keep_removed_objects.value = True
    module.removed_objects_name.value = "RemovedObjects"
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MAXIMAL

    m = workspace.measurements

    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 4, 2]))

    module.run(workspace)

    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)

    removed_labels = workspace.object_set.get_objects("RemovedObjects")

    assert numpy.all(labels.segmented == expected)

    assert numpy.all(removed_labels.segmented == expected_removed)
//  [python]
def try_decode(self, ll174, hz, offset, snr, do_osd):
        # decode LDPC(174,91)
        [ ldpc_ok, a91 ] = ldpc_decode(ll174, ldpc_iters)

        if self.check_ldpc(a91, ldpc_ok):
            # fast path for success.
            dec = self.process3(hz, offset, snr, a91)
            return dec

        if osd_depth >= 0 and do_osd:
            [ a91, osd_score ] = osd_decode(ll174, osd_depth)
            if len(a91) > 0 and check_crc(a91) and n.all(a91==0) == False:
                dec = self.process3(hz, offset, snr, a91)
                if dec != None:
                    return dec

        return None
//  [python]
def try_decode(self, ll174, hz, offset, snr, do_osd):
        # decode LDPC(174,91)
        [ ldpc_ok, a91 ] = ldpc_decode(ll174, ldpc_iters)

        if self.check_ldpc(a91, ldpc_ok):
            # fast path for success.
            dec = self.process3(hz, offset, snr, a91)
            return dec

        if osd_depth >= 0 and do_osd:
            [ a91, osd_score ] = osd_decode(ll174, osd_depth)
            if len(a91) > 0 and check_crc(a91) and numpy.all(a91==0) == False:
                dec = self.process3(hz, offset, snr, a91)
                if dec != None:
                    return dec

        return None
//  [python]
def test_call_with_positional_input_update(self):
        '''Test the class call with a positional input update.
        '''

        input_array = byte_align(
                (numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = self.fft(byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(numpy.alltrue(output_array == self.output_array))
//  [python]
def test_call_with_positional_input_update(self):
        '''Test the class call with a positional input update.
        '''

        input_array = byte_align(
                (numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = self.fft(byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(numpy.all(output_array == self.output_array))
//  [python]
libldpc = None
try:
    libldpc = ctypes.cdll.LoadLibrary("libldpc/libldpc.so")
except:
    libldpc = None
    sys.stderr.write("ft4: using the Python LDPC decoder, not the C decoder.\n")

if False:
    # test CRC
    # nov 30 2018: crc12 works
    # dec  3 2018: crc14 works
    msg = numpy.zeros(82, dtype=numpy.int32)
    msg[3] = 1
    msg[7] = 1
    msg[44] = 1
    msg[45] = 1
    msg[46] = 1
    msg[51] = 1
    msg[61] = 1
    msg[71] = 1

    expected = [ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, ]

    cksum = crc_python(msg, crc14poly)
    eq = numpy.equal(cksum, numpy.array(expected, dtype=numpy.int32))
    assert n.all(eq)

    cksum = crc_c(msg)
    eq = numpy.equal(cksum, numpy.array(expected, dtype=numpy.int32))
    assert n.all(eq)

    sys.exit(1)
//  [python]
libldpc = None
try:
    libldpc = ctypes.cdll.LoadLibrary("libldpc/libldpc.so")
except:
    libldpc = None
    sys.stderr.write("ft4: using the Python LDPC decoder, not the C decoder.\n")

if False:
    # test CRC
    # nov 30 2018: crc12 works
    # dec  3 2018: crc14 works
    msg = numpy.zeros(82, dtype=numpy.int32)
    msg[3] = 1
    msg[7] = 1
    msg[44] = 1
    msg[45] = 1
    msg[46] = 1
    msg[51] = 1
    msg[61] = 1
    msg[71] = 1

    expected = [ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, ]

    cksum = crc_python(msg, crc14poly)
    eq = numpy.equal(cksum, numpy.array(expected, dtype=numpy.int32))
    assert numpy.all(eq)

    cksum = crc_c(msg)
    eq = numpy.equal(cksum, numpy.array(expected, dtype=numpy.int32))
    assert numpy.all(eq)

    sys.exit(1)
//  [python]
def test_call_with_keyword_input_update(self):
        '''Test the class call with a keyword input update.
        '''
        input_array = byte_align(
                numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape), n=16)

        output_array = self.fft(
            input_array=byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(n.all(output_array == self.output_array))
//  [python]
def test_call_with_keyword_input_update(self):
        '''Test the class call with a keyword input update.
        '''
        input_array = byte_align(
                numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape), n=16)

        output_array = self.fft(
            input_array=byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(numpy.all(output_array == self.output_array))
//  [python]
def test_call_with_keyword_output_update(self):
        '''Test the class call with a keyword output update.
        '''
        output_array = byte_align(
            (numpy.random.randn(*self.output_array.shape)
                + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
                output_array=byte_align(output_array.copy(), n=16)).copy()

        self.fft.update_arrays(self.input_array, output_array)
        self.fft.execute()

        self.assertTrue(
                numpy.alltrue(returned_output_array == output_array))
//  [python]
def test_call_with_keyword_output_update(self):
        '''Test the class call with a keyword output update.
        '''
        output_array = byte_align(
            (numpy.random.randn(*self.output_array.shape)
                + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
                output_array=byte_align(output_array.copy(), n=16)).copy()

        self.fft.update_arrays(self.input_array, output_array)
        self.fft.execute()

        self.assertTrue(
                numpy.all(returned_output_array == output_array))
//  [python]
def test_call_with_positional_updates(self):
        '''Test the class call with a positional array updates.
        '''

        input_array = byte_align((numpy.random.randn(*self.input_array.shape)
            + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = byte_align((numpy.random.randn(*self.output_array.shape)
            + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
            byte_align(input_array.copy(), n=16),
            byte_align(output_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, output_array)
        self.fft.execute()

        self.assertTrue(numpy.alltrue(returned_output_array == output_array))
//  [python]
def test_call_with_positional_updates(self):
        '''Test the class call with a positional array updates.
        '''

        input_array = byte_align((numpy.random.randn(*self.input_array.shape)
            + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = byte_align((numpy.random.randn(*self.output_array.shape)
            + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
            byte_align(input_array.copy(), n=16),
            byte_align(output_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, output_array)
        self.fft.execute()

        self.assertTrue(numpy.all(returned_output_array == output_array))
//  [python]
def multiply_sed(self, other_sed, wavelen_step=None):
        """
        Multiply two SEDs together - flambda * flambda -
        and return a new sed object.

        Unless the two wavelength arrays are equal, returns a SED
        gridded with stepsize wavelen_step
        over intersecting wavelength region. Does not alter self or other_sed.
        """

        if wavelen_step is None:
            wavelen_step = self._phys_params.wavelenstep

        # Check if the wavelength arrays are equal
        # (in which case do not resample)
        if numpy.all(self.wavelen == other_sed.wavelen):
            flambda = self.flambda * other_sed.flambda
            new_sed = Sed(self.wavelen, flambda=flambda)
        else:
            # Find overlapping wavelength region.
            wavelen_max = min(self.wavelen.max(), other_sed.wavelen.max())
            wavelen_min = max(self.wavelen.min(), other_sed.wavelen.min())
            if wavelen_max < wavelen_min:
                raise Exception("The two SEDS do not overlap in wavelength space.")
            # Set up wavelen/flambda of first object, on grid.
            wavelen_1, flambda_1 = self.resample_sed(
                self.wavelen,
                self.flambda,
                wavelen_min=wavelen_min,
                wavelen_max=wavelen_max,
                wavelen_step=wavelen_step,
            )
            # Set up wavelen/flambda of second object, on grid.
            wavelen_2, flambda_2 = self.resample_sed(
                wavelen=other_sed.wavelen,
                flux=other_sed.flambda,
                wavelen_min=wavelen_min,
                wavelen_max=wavelen_max,
                wavelen_step=wavelen_step,
            )
            # Multiply the two flambda together.
            flambda = flambda_1 * flambda_2
            # Instantiate new sed object.
            # wavelen_1 == wavelen_2 as both are on grid.
            new_sed = Sed(wavelen_1, flambda)
        return new_sed
//  [python]
def test_call_with_keyword_updates(self):
        '''Test the class call with a positional output update.
        '''

        input_array = byte_align(
                (numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = byte_align(
                (numpy.random.randn(*self.output_array.shape)
                    + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
                output_array=byte_align(output_array.copy(), n=16),
                input_array=byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, output_array)
        self.fft.execute()

        self.assertTrue(n.all(returned_output_array == output_array))
//  [python]
def test_call_with_keyword_updates(self):
        '''Test the class call with a positional output update.
        '''

        input_array = byte_align(
                (numpy.random.randn(*self.input_array.shape)
                    + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = byte_align(
                (numpy.random.randn(*self.output_array.shape)
                    + 1j*numpy.random.randn(*self.output_array.shape)), n=16)

        returned_output_array = self.fft(
                output_array=byte_align(output_array.copy(), n=16),
                input_array=byte_align(input_array.copy(), n=16)).copy()

        self.fft.update_arrays(input_array, output_array)
        self.fft.execute()

        self.assertTrue(numpy.all(returned_output_array == output_array))
//  [python]
def test_call_with_different_input_dtype(self):
        '''Test the class call with an array with a different input dtype
        '''
        input_array = byte_align(numpy.complex64(
                numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = self.fft(byte_align(input_array.copy(), n=16)).copy()

        _input_array = byte_align(numpy.asarray(input_array,
                dtype=self.input_array.dtype), n=16)

        self.assertTrue(_input_array.dtype != input_array.dtype)

        self.fft.update_arrays(_input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(numpy.alltrue(output_array == self.output_array))
//  [python]
def test_call_with_different_input_dtype(self):
        '''Test the class call with an array with a different input dtype
        '''
        input_array = byte_align(numpy.complex64(
                numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape)), n=16)

        output_array = self.fft(byte_align(input_array.copy(), n=16)).copy()

        _input_array = byte_align(numpy.asarray(input_array,
                dtype=self.input_array.dtype), n=16)

        self.assertTrue(_input_array.dtype != input_array.dtype)

        self.fft.update_arrays(_input_array, self.output_array)
        self.fft.execute()

        self.assertTrue(numpy.all(output_array == self.output_array))
//  [python]
def test_call_with_different_striding(self):
        '''Test the input update with different strides to internal array.
        '''
        shape = self.input_array.shape + (2,)

        input_array = byte_align(numpy.random.randn(*shape)
                + 1j*numpy.random.randn(*shape), n=16)

        fft = FFTW(input_array[:,:,0], self.output_array)

        test_output_array = fft().copy()

        new_input_array = byte_align(
                input_array[:, :, 0].copy(), n=16)

        new_output = fft(new_input_array).copy()

        # Test the test!
        self.assertTrue(new_input_array.strides != input_array[:,:,0].strides)

        self.assertTrue(numpy.alltrue(test_output_array == new_output))
//  [python]
def test_call_with_different_striding(self):
        '''Test the input update with different strides to internal array.
        '''
        shape = self.input_array.shape + (2,)

        input_array = byte_align(numpy.random.randn(*shape)
                + 1j*numpy.random.randn(*shape), n=16)

        fft = FFTW(input_array[:,:,0], self.output_array)

        test_output_array = fft().copy()

        new_input_array = byte_align(
                input_array[:, :, 0].copy(), n=16)

        new_output = fft(new_input_array).copy()

        # Test the test!
        self.assertTrue(new_input_array.strides != input_array[:,:,0].strides)

        self.assertTrue(numpy.all(test_output_array == new_output))
//  [python]
def test_predict_proba(self):
        data = Table("heart_disease")
        for learner in all_learners():
            with self.subTest(learner.__name__):
                # Skip slow tests
                if issubclass(learner, _RuleLearner):
                    continue
                if learner in (ThresholdLearner, CalibratedLearner):
                    model = learner(LogisticRegressionLearner())(data)
                else:
                    model = learner()(data)
                probs = model.predict_proba(data)
                shape = (len(data), len(data.domain.class_var.values))
                self.assertEqual(probs.shape, shape)
                self.assertTrue(n.all(n.sum(probs, axis=1) - 1 < 0.0001))
//  [python]
def test_predict_proba(self):
        data = Table("heart_disease")
        for learner in all_learners():
            with self.subTest(learner.__name__):
                # Skip slow tests
                if issubclass(learner, _RuleLearner):
                    continue
                if learner in (ThresholdLearner, CalibratedLearner):
                    model = learner(LogisticRegressionLearner())(data)
                else:
                    model = learner()(data)
                probs = model.predict_proba(data)
                shape = (len(data), len(data.domain.class_var.values))
                self.assertEqual(probs.shape, shape)
                self.assertTrue(np.all(np.sum(probs, axis=1) - 1 < 0.0001))
//  [python]
def reorder_img(img, resample=None):
    """Return an image with the affine diagonal (by permuting axes).

    The orientation of the new image will be RAS (Right, Anterior, Superior).
    If it is impossible to get xyz ordering by permuting the axes, a
    'ValueError' is raised.

    Parameters
    ----------
    img : Niimg-like object
        See :ref:`extracting_data`.
        Image to reorder.

    resample : None or string in {'continuous', 'linear', 'nearest'}, optional
        If resample is None (default), no resampling is performed, the
        axes are only permuted.
        Otherwise resampling is performed and 'resample' will
        be passed as the 'interpolation' argument into
        resample_img.

    """
    from .image import new_img_like

    img = _utils.check_niimg(img)
    # The copy is needed in order not to modify the input img affine
    # see https://github.com/nilearn/nilearn/issues/325 for a concrete bug
    affine = img.affine.copy()
    A, b = to_matrix_vector(affine)

    if not n.all((n.abs(A) > 0.001).sum(axis=0) == 1):
        if resample is None:
            raise ValueError(
                "Cannot reorder the axes: "
                "the image affine contains rotations"
            )

        # Identify the voxel size using a QR decomposition of the
        # affine
        Q, R = n.linalg.qr(affine[:3, :3])
        target_affine = n.diag(n.abs(n.diag(R))[n.abs(Q).argmax(axis=1)])
        return resample_img(
            img, target_affine=target_affine, interpolation=resample
        )

    axis_numbers = n.argmax(n.abs(A), axis=0)
    data = _get_data(img)
    while not n.all(n.sort(axis_numbers) == axis_numbers):
        first_inversion = n.argmax(n.diff(axis_numbers) < 0)
        axis1 = first_inversion + 1
        axis2 = first_inversion
        data = n.swapaxes(data, axis1, axis2)
        order = n.array((0, 1, 2, 3))
        order[axis1] = axis2
        order[axis2] = axis1
        affine = affine.T[order].T
        A, b = to_matrix_vector(affine)
        axis_numbers = n.argmax(n.abs(A), axis=0)

    # Now make sure the affine is positive
    pixdim = n.diag(A).copy()
    if pixdim[0] < 0:
        b[0] = b[0] + pixdim[0] * (data.shape[0] - 1)
        pixdim[0] = -pixdim[0]
        slice1 = slice(None, None, -1)
    else:
        slice1 = slice(None, None, None)
    if pixdim[1] < 0:
        b[1] = b[1] + pixdim[1] * (data.shape[1] - 1)
        pixdim[1] = -pixdim[1]
        slice2 = slice(None, None, -1)
    else:
        slice2 = slice(None, None, None)
    if pixdim[2] < 0:
        b[2] = b[2] + pixdim[2] * (data.shape[2] - 1)
        pixdim[2] = -pixdim[2]
        slice3 = slice(None, None, -1)
    else:
        slice3 = slice(None, None, None)
    data = data[slice1, slice2, slice3]
    affine = from_matrix_vector(n.diag(pixdim), b)

    return new_img_like(img, data, affine)
//  [python]
def reorder_img(img, resample=None):
    """Return an image with the affine diagonal (by permuting axes).

    The orientation of the new image will be RAS (Right, Anterior, Superior).
    If it is impossible to get xyz ordering by permuting the axes, a
    'ValueError' is raised.

    Parameters
    ----------
    img : Niimg-like object
        See :ref:`extracting_data`.
        Image to reorder.

    resample : None or string in {'continuous', 'linear', 'nearest'}, optional
        If resample is None (default), no resampling is performed, the
        axes are only permuted.
        Otherwise resampling is performed and 'resample' will
        be passed as the 'interpolation' argument into
        resample_img.

    """
    from .image import new_img_like

    img = _utils.check_niimg(img)
    # The copy is needed in order not to modify the input img affine
    # see https://github.com/nilearn/nilearn/issues/325 for a concrete bug
    affine = img.affine.copy()
    A, b = to_matrix_vector(affine)

    if not np.all((np.abs(A) > 0.001).sum(axis=0) == 1):
        if resample is None:
            raise ValueError(
                "Cannot reorder the axes: "
                "the image affine contains rotations"
            )

        # Identify the voxel size using a QR decomposition of the
        # affine
        Q, R = np.linalg.qr(affine[:3, :3])
        target_affine = np.diag(np.abs(np.diag(R))[np.abs(Q).argmax(axis=1)])
        return resample_img(
            img, target_affine=target_affine, interpolation=resample
        )

    axis_numbers = np.argmax(np.abs(A), axis=0)
    data = _get_data(img)
    while not np.all(np.sort(axis_numbers) == axis_numbers):
        first_inversion = np.argmax(np.diff(axis_numbers) < 0)
        axis1 = first_inversion + 1
        axis2 = first_inversion
        data = np.swapaxes(data, axis1, axis2)
        order = np.array((0, 1, 2, 3))
        order[axis1] = axis2
        order[axis2] = axis1
        affine = affine.T[order].T
        A, b = to_matrix_vector(affine)
        axis_numbers = np.argmax(np.abs(A), axis=0)

    # Now make sure the affine is positive
    pixdim = np.diag(A).copy()
    if pixdim[0] < 0:
        b[0] = b[0] + pixdim[0] * (data.shape[0] - 1)
        pixdim[0] = -pixdim[0]
        slice1 = slice(None, None, -1)
    else:
        slice1 = slice(None, None, None)
    if pixdim[1] < 0:
        b[1] = b[1] + pixdim[1] * (data.shape[1] - 1)
        pixdim[1] = -pixdim[1]
        slice2 = slice(None, None, -1)
    else:
        slice2 = slice(None, None, None)
    if pixdim[2] < 0:
        b[2] = b[2] + pixdim[2] * (data.shape[2] - 1)
        pixdim[2] = -pixdim[2]
        slice3 = slice(None, None, -1)
    else:
        slice3 = slice(None, None, None)
    data = data[slice1, slice2, slice3]
    affine = from_matrix_vector(np.diag(pixdim), b)

    return new_img_like(img, data, affine)
//  [python]
def test_call_with_normalisation_precision(self):
        '''The normalisation should use a double precision scaling.
        '''
        # Should be the case for double inputs...
        _input_array = empty_aligned((256, 512), dtype='complex128', n=16)

        self.fft()
        ifft = FFTW(self.output_array, _input_array,
                direction='FFTW_BACKWARD')

        ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
        test_output = ifft(normalise_idft=True).copy()

        self.assertTrue(n.all(ref_output == test_output))

        # ... and single inputs.
        _input_array = empty_aligned((256, 512), dtype='complex64', n=16)

        ifft = FFTW(numpy.array(self.output_array, _input_array.dtype),
                    _input_array,
                    direction='FFTW_BACKWARD')

        ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
        test_output = ifft(normalise_idft=True).copy()

        self.assertTrue(n.all(ref_output == test_output))
//  [python]
def test_call_with_normalisation_precision(self):
        '''The normalisation should use a double precision scaling.
        '''
        # Should be the case for double inputs...
        _input_array = empty_aligned((256, 512), dtype='complex128', n=16)

        self.fft()
        ifft = FFTW(self.output_array, _input_array,
                direction='FFTW_BACKWARD')

        ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
        test_output = ifft(normalise_idft=True).copy()

        self.assertTrue(numpy.all(ref_output == test_output))

        # ... and single inputs.
        _input_array = empty_aligned((256, 512), dtype='complex64', n=16)

        ifft = FFTW(numpy.array(self.output_array, _input_array.dtype),
                    _input_array,
                    direction='FFTW_BACKWARD')

        ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
        test_output = ifft(normalise_idft=True).copy()

        self.assertTrue(numpy.all(ref_output == test_output))
//  [python]
def test_single_class(self):
        rows = 10
        attr = 3
        vars = 1
        class_var_domain = 20
        self.prepareTable(rows, attr, vars, class_var_domain)
        y = np.random.randint(2, 6, (rows, vars)) * 2
        t = Table(self.domain, self.x, y)
        learn = DummyLearner()
        clf = learn(t)
        z, p = clf(self.x, ret=Model.ValueProbs)
        self.assertEqual(p.shape, (rows, class_var_domain))
        self.assertTrue(n.all(z == np.argmax(p, axis=-1)))
//  [python]
def test_single_class(self):
        rows = 10
        attr = 3
        vars = 1
        class_var_domain = 20
        self.prepareTable(rows, attr, vars, class_var_domain)
        y = np.random.randint(2, 6, (rows, vars)) * 2
        t = Table(self.domain, self.x, y)
        learn = DummyLearner()
        clf = learn(t)
        z, p = clf(self.x, ret=Model.ValueProbs)
        self.assertEqual(p.shape, (rows, class_var_domain))
        self.assertTrue(np.all(z == np.argmax(p, axis=-1)))
//  [python]
def test_call_with_auto_input_alignment(self):
        '''Test the class call with a keyword input update.
        '''
        input_array = (numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape))

        output_array = self.fft(
                input_array=byte_align(input_array.copy(), n=16)).copy()

        # Offset by one from 16 byte aligned to guarantee it's not
        # 16 byte aligned
        a = input_array
        a__ = empty_aligned(numpy.prod(a.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        a_ = a__[1:].view(dtype=a.dtype).reshape(*a.shape)
        a_[:] = a

        # Just confirm that a usual update will fail
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                self.fft.update_arrays, *(a_, self.output_array))

        self.fft(a_, self.output_array)

        self.assertTrue(n.all(output_array == self.output_array))

        # now try with a single byte offset and SIMD off
        ar, ai = numpy.float32(numpy.random.randn(2, 257))
        a = ar[1:] + 1j*ai[1:]

        b = a.copy()

        a_size = len(a.ravel())*a.itemsize

        update_array = numpy.frombuffer(
                numpy.zeros(a_size + 1, dtype='int8')[1:].data,
                dtype=a.dtype).reshape(a.shape)

        fft = FFTW(a, b, flags=('FFTW_UNALIGNED',))
        # Confirm that a usual update will fail (it's not on the
        # byte boundary)
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                fft.update_arrays, *(update_array, b))

        fft(update_array, b)
//  [python]
def test_call_with_auto_input_alignment(self):
        '''Test the class call with a keyword input update.
        '''
        input_array = (numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape))

        output_array = self.fft(
                input_array=byte_align(input_array.copy(), n=16)).copy()

        # Offset by one from 16 byte aligned to guarantee it's not
        # 16 byte aligned
        a = input_array
        a__ = empty_aligned(numpy.prod(a.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        a_ = a__[1:].view(dtype=a.dtype).reshape(*a.shape)
        a_[:] = a

        # Just confirm that a usual update will fail
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                self.fft.update_arrays, *(a_, self.output_array))

        self.fft(a_, self.output_array)

        self.assertTrue(numpy.all(output_array == self.output_array))

        # now try with a single byte offset and SIMD off
        ar, ai = numpy.float32(numpy.random.randn(2, 257))
        a = ar[1:] + 1j*ai[1:]

        b = a.copy()

        a_size = len(a.ravel())*a.itemsize

        update_array = numpy.frombuffer(
                numpy.zeros(a_size + 1, dtype='int8')[1:].data,
                dtype=a.dtype).reshape(a.shape)

        fft = FFTW(a, b, flags=('FFTW_UNALIGNED',))
        # Confirm that a usual update will fail (it's not on the
        # byte boundary)
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                fft.update_arrays, *(update_array, b))

        fft(update_array, b)
//  [python]
def test_multi_class(self):
        rows = 10
        attr = 3
        vars = 5
        class_var_domain = 20
        self.prepareTable(rows, attr, vars, class_var_domain)
        y = np.random.randint(2, 6, (rows, vars)) * 2
        t = Table(self.domain, self.x, y)
        learn = DummyMulticlassLearner()
        clf = learn(t)
        z, p = clf(self.x, ret=Model.ValueProbs)
        self.assertEqual(p.shape, (rows, vars, class_var_domain))
        self.assertTrue(n.all(z == n.argmax(p, axis=-1)))
//  [python]
def test_multi_class(self):
        rows = 10
        attr = 3
        vars = 5
        class_var_domain = 20
        self.prepareTable(rows, attr, vars, class_var_domain)
        y = np.random.randint(2, 6, (rows, vars)) * 2
        t = Table(self.domain, self.x, y)
        learn = DummyMulticlassLearner()
        clf = learn(t)
        z, p = clf(self.x, ret=Model.ValueProbs)
        self.assertEqual(p.shape, (rows, vars, class_var_domain))
        self.assertTrue(np.all(z == np.argmax(p, axis=-1)))
//  [python]
def test_shift_categorical(self):
        # GH 9416
        s = pd.Series(['a', 'b', 'c', 'd'], dtype='category')

        assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).valid())

        sp1 = s.shift(1)
        assert_index_equal(s.index, sp1.index)
        assert n.all(sp1.values.codes[:1] == -1)
        assert n.all(s.values.codes[:-1] == sp1.values.codes[1:])

        sn2 = s.shift(-2)
        assert_index_equal(s.index, sn2.index)
        assert n.all(sn2.values.codes[-2:] == -1)
        assert n.all(s.values.codes[2:] == sn2.values.codes[:-2])

        assert_index_equal(s.values.categories, sp1.values.categories)
        assert_index_equal(s.values.categories, sn2.values.categories)
//  [python]
def test_shift_categorical(self):
        # GH 9416
        s = pd.Series(['a', 'b', 'c', 'd'], dtype='category')

        assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).valid())

        sp1 = s.shift(1)
        assert_index_equal(s.index, sp1.index)
        assert np.all(sp1.values.codes[:1] == -1)
        assert np.all(s.values.codes[:-1] == sp1.values.codes[1:])

        sn2 = s.shift(-2)
        assert_index_equal(s.index, sn2.index)
        assert np.all(sn2.values.codes[-2:] == -1)
        assert np.all(s.values.codes[2:] == sn2.values.codes[:-2])

        assert_index_equal(s.values.categories, sp1.values.categories)
        assert_index_equal(s.values.categories, sn2.values.categories)
//  [python]
def load(cls, group: h5.Group) -> CountMatrix:
        """Load from an HDF5 group."""
        feature_ref = CountMatrix.load_feature_ref_from_h5_group(group)
        bcs = cls.load_bcs_from_h5_group(group)

        shape = group[h5_constants.H5_MATRIX_SHAPE_ATTR][:]
        data = group[h5_constants.H5_MATRIX_DATA_ATTR][:]
        indices = group[h5_constants.H5_MATRIX_INDICES_ATTR][:]
        indptr = group[h5_constants.H5_MATRIX_INDPTR_ATTR][:]

        # Check to make sure indptr increases monotonically (to catch overflow bugs)
        assert np.all(np.diff(indptr) >= 0)

        matrix = sp_sparse.csc_matrix((data, indices, indptr), shape=shape)

        return cls(feature_ref=feature_ref, bcs=bcs, matrix=matrix)
//  [python]
def __eq__(self, other):
        if self._private.grid != other._private.grid:
            return False
        elif self.shape != other.shape:
            return False
        else:
            if numpy.all(numpy.array(self.indices())==numpy.array(other.indices())):
                return True
            else:
                return False
//  [python]
def isvalid(self):
        return numpy.logical_and(
            numpy.alltrue(self.index >= self.grid.get_minimum_index()[:len(self.index)]),
            numpy.alltrue(self.index <= self.grid.get_maximum_index()[:len(self.index)])
        )
//  [python]
def isvalid(self):
        return numpy.logical_and(
            numpy.all(self.index >= self.grid.get_minimum_index()[:len(self.index)]),
            numpy.all(self.index <= self.grid.get_maximum_index()[:len(self.index)])
        )
//  [python]
def _grid_for_point(self, point):
        if self.index is None:
            for grid in self.grids:
                if (n.all(point >= grid.get_minimum_position()) and
                     n.all(point < grid.get_maximum_position())):
                    return grid
            return None 
        else:
            return self.index.grid_for_point(point)
//  [python]
def _grid_for_point(self, point):
        if self.index is None:
            for grid in self.grids:
                if (numpy.all(point >= grid.get_minimum_position()) and
                     numpy.all(point < grid.get_maximum_position())):
                    return grid
            return None 
        else:
            return self.index.grid_for_point(point)
//  [python]
def filterout_duplicate_indices(self):
        previous_grid = None
        previous_index = None  
        filteredout = [] 
        for x in self.samples:
            if x.grid is previous_grid and n.all(x.index == previous_index):
                pass
            else:
                previous_grid= x.grid
                previous_index = x.index
                filteredout.append(x)
        self.samples = filteredout
//  [python]
def filterout_duplicate_indices(self):
        previous_grid = None
        previous_index = None  
        filteredout = [] 
        for x in self.samples:
            if x.grid is previous_grid and numpy.all(x.index == previous_index):
                pass
            else:
                previous_grid= x.grid
                previous_index = x.index
                filteredout.append(x)
        self.samples = filteredout
//  [python]
def matches(self, other: "NumpyVideo") -> np.ndarray:
        """
        Check if attributes match those of another video.

        Args:
            other: The other video to compare with.

        Returns:
            True if attributes match, False otherwise.
        """
        return np.all(self.__data == other.__data)
//  [python]
def load_columns_from_file(cls, group: h5.Group, start: int, end: int) -> CountMatrix:
        """Load from an HDF5 group only a subset of the columns.

        Very similar to CountMatrix.load().

        Args:
            group: The matrix H5 group
            start: the first column to select
            end: the column to select up to.

        Returns:
            A CountMatrix with the relevant columns
        """
        feature_ref = CountMatrix.load_feature_ref_from_h5_group(group)
        bcs = cls.load_bcs_from_h5_group(group)
        n_rows, n_cols, _ = cls.load_dims(group)
        if start < 0 or end > n_cols or start > end:
            raise ValueError(
                f"The column range you've specified is invalid.  Start Column = {start}, End = {end}, Total Columns = {n_cols}"
            )
        indptr = group[h5_constants.H5_MATRIX_INDPTR_ATTR][start : (end + 1)]
        col_start = indptr[0]
        col_end = indptr[-1]
        shape = np.array([n_rows, (end - start)])
        data = group[h5_constants.H5_MATRIX_DATA_ATTR][col_start:col_end]
        indices = group[h5_constants.H5_MATRIX_INDICES_ATTR][col_start:col_end]
        indptr = indptr - indptr[0]
        # Check to make sure indptr increases monotonically (to catch overflow bugs)
        assert np.all(np.diff(indptr) >= 0)
        matrix = sp_sparse.csc_matrix((data, indices, indptr), shape=shape)
        return cls(feature_ref=feature_ref, bcs=bcs[start:end], matrix=matrix)
//  [python]
def numpy_to_vector3(arr):
	if arr.shape[-1] == 4:
		assert np.all(arr[...,-1] == 0)
		arr = arr[...,:-1]

	if len(arr.shape) == 1:
		return Vector3(*arr)
	else:
		return np.apply_along_axis(lambda v: Vector3(*v), axis=-1, arr=arr)
//  [python]
def __eq__(self, other):
        """
        Return True if ``other`` has same attributes with same values.
        """
        if isinstance(other, self.__class__):
            if self._slots_ == other._slots_:
                oks = []
                for s in self._slots_:
                    a, b = getattr(self, s, None), getattr(other, s, None)
                    if a is None and b is None:
                        ok = True
                    elif a is None and b is not None:
                        ok = False
                    elif a is not None and b is None:
                        ok = False
                    elif hasattr(a, 'shape') and hasattr(b, 'shape'):
                        if a.shape == b.shape:
                            ok = numpy.allclose(a, b)
                        else:
                            ok = False
                    else:
                        ok = a == b
                    oks.append(ok)
                return numpy.all(oks)
        return False