jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def same_mol(mol1, mol2, tol=1e-5, cmp_basis=True, ignore_chiral=False):
    '''Compare the two molecules whether they have the same structure.

    Kwargs:
        tol : float
            In Bohr
        cmp_basis : bool
            Whether to compare basis functions for the two molecules
    '''
    from pyscf import symm

    if mol1._atom.__len__() != mol2._atom.__len__():
        return False

    chg1 = mol1._atm[:,CHARGE_OF]
    chg2 = mol2._atm[:,CHARGE_OF]
    if not numpy.all(numpy.sort(chg1) == numpy.sort(chg2)):
        return False

    if cmp_basis and not same_basis_set(mol1, mol2):
        return False

    def finger(mol, chgs, coord):
        center = numpy.einsum('z,zr->r', chgs, coord) / chgs.sum()
        im = inertia_moment(mol, chgs, coord)
        # Divid im by chgs.sum(), to normalize im. Otherwise the input tol may
        # not reflect the actual deviation.
        im /= chgs.sum()

        w, v = scipy.linalg.eigh(im)
        axes = v.T
        if numpy.linalg.det(axes) < 0:
            axes *= -1
        r = numpy.dot(coord-center, axes.T)
        return w, r

    coord1 = mol1.atom_coords()
    coord2 = mol2.atom_coords()
    w1, r1 = finger(mol1, chg1, coord1)
    w2, r2 = finger(mol2, chg2, coord2)
    if not (numpy.allclose(w1, w2, atol=tol)):
        return False

    rotate_xy  = numpy.array([[-1., 0., 0.],
                              [ 0.,-1., 0.],
                              [ 0., 0., 1.]])
    rotate_yz  = numpy.array([[ 1., 0., 0.],
                              [ 0.,-1., 0.],
                              [ 0., 0.,-1.]])
    rotate_zx  = numpy.array([[-1., 0., 0.],
                              [ 0., 1., 0.],
                              [ 0., 0.,-1.]])

    def inspect(z1, r1, z2, r2):
        place = int(-numpy.log10(tol)) - 1
        idx = symm.argsort_coords(r2, place)
        z2 = z2[idx]
        r2 = r2[idx]
        for rot in (1, rotate_xy, rotate_yz, rotate_zx):
            r1new = numpy.dot(r1, rot)
            idx = symm.argsort_coords(r1new, place)
            if (numpy.all(z1[idx] == z2) and
                numpy.allclose(r1new[idx], r2, atol=tol)):
                return True
        return False

    return (inspect(chg1, r1, chg2, r2) or
            (ignore_chiral and inspect(chg1, r1, chg2, -r2)))
//  [python]
def equality_check(a, b):
    """Check equality between to instances of _HOOMDBaseObject."""

    def check_item(x, y, attr):
        if isinstance(x, hoomd.operation._HOOMDGetSetAttrBase):
            equal = equality_check(x, y)
        else:
            equal = n.all(x == y)
        if not equal:
            logger.debug(
                f"In equality check, attr '{attr}' not equal: {x} != {y}.")
            return False
        return True

    if not isinstance(a, hoomd.operation._HOOMDGetSetAttrBase):
        return a == b
    if type(a) != type(b):
        return False

    _check_obj_attr_compatibility(a, b)

    for attr in a.__dict__:
        if attr in a._skip_for_equality:
            continue

        if attr == "_param_dict":
            param_keys = a._param_dict.keys()
            b_param_keys = b._param_dict.keys()
            # Check key equality
            if param_keys != b_param_keys:
                logger.debug(
                    f"In equality check, incompatible param_dict keys: "
                    f"{param_keys}, {b_param_keys}")
                return False
            # Check item equality
            for key in param_keys:
                check_item(a._param_dict[key], b._param_dict[key], key)
            continue

        check_item(a.__dict__[attr], b.__dict__[attr], attr)
    return True
//  [python]
def equality_check(a, b):
    """Check equality between to instances of _HOOMDBaseObject."""

    def check_item(x, y, attr):
        if isinstance(x, hoomd.operation._HOOMDGetSetAttrBase):
            equal = equality_check(x, y)
        else:
            equal = numpy.all(x == y)
        if not equal:
            logger.debug(
                f"In equality check, attr '{attr}' not equal: {x} != {y}.")
            return False
        return True

    if not isinstance(a, hoomd.operation._HOOMDGetSetAttrBase):
        return a == b
    if type(a) != type(b):
        return False

    _check_obj_attr_compatibility(a, b)

    for attr in a.__dict__:
        if attr in a._skip_for_equality:
            continue

        if attr == "_param_dict":
            param_keys = a._param_dict.keys()
            b_param_keys = b._param_dict.keys()
            # Check key equality
            if param_keys != b_param_keys:
                logger.debug(
                    f"In equality check, incompatible param_dict keys: "
                    f"{param_keys}, {b_param_keys}")
                return False
            # Check item equality
            for key in param_keys:
                check_item(a._param_dict[key], b._param_dict[key], key)
            continue

        check_item(a.__dict__[attr], b.__dict__[attr], attr)
    return True
//  [python]
def test_zeros_single():
    """Test keep single object on an empty labels matrix"""
    workspace, module = make_workspace({INPUT_OBJECTS: numpy.zeros((10, 10), int)})
    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.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == 0)
//  [python]
def test_zeros_single():
    """Test keep single object on an empty labels matrix"""
    workspace, module = make_workspace({INPUT_OBJECTS: numpy.zeros((10, 10), int)})
    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.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == 0)
//  [python]
def test_zeros_per_object():
    """Test keep per object filtering on an empty labels matrix"""
    workspace, module = make_workspace(
        {
            INPUT_OBJECTS: numpy.zeros((10, 10), int),
            ENCLOSING_OBJECTS: numpy.zeros((10, 10), int),
        }
    )
    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
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == 0)
//  [python]
def test_zeros_per_object():
    """Test keep per object filtering on an empty labels matrix"""
    workspace, module = make_workspace(
        {
            INPUT_OBJECTS: numpy.zeros((10, 10), int),
            ENCLOSING_OBJECTS: numpy.zeros((10, 10), int),
        }
    )
    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
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == 0)
//  [python]
def __init__(self, data):
        # round down to the nearest power of 2
        N = 2**int(math.log(len(data)) / math.log(2))
        if N != len(data):
            warnings.warn(
                "Ignoring some data. Data array should be a power of 2.")

        block_sizes = []
        block_mean = []
        block_variance = []

        # take means of blocks and the mean/variance of all blocks, growing
        # blocks by factors of 2
        block_size = 1
        while block_size <= N // 8:
            num_blocks = N // block_size
            block_data = numpy.zeros(num_blocks)

            for i in range(0, num_blocks):
                start = i * block_size
                end = start + block_size
                block_data[i] = numpy.mean(data[start:end])

            block_mean.append(numpy.mean(block_data))
            block_variance.append(numpy.var(block_data) / (num_blocks - 1))

            block_sizes.append(block_size)
            block_size *= 2

        self._block_mean = numpy.array(block_mean)
        self._block_variance = numpy.array(block_variance)
        self._block_sizes = numpy.array(block_sizes)
        self.data = numpy.array(data)

        # check for a plateau in the relative error before the last data point
        block_relative_error = numpy.sqrt(self._block_variance) / numpy.fabs(
            self._block_mean)
        relative_error_derivative = (numpy.diff(block_relative_error)
                                     / numpy.diff(self._block_sizes))
        if numpy.alltrue(relative_error_derivative > 0):
            warnings.warn("Block averaging failed to plateau, run longer")
//  [python]
def __init__(self, data):
        # round down to the nearest power of 2
        N = 2**int(math.log(len(data)) / math.log(2))
        if N != len(data):
            warnings.warn(
                "Ignoring some data. Data array should be a power of 2.")

        block_sizes = []
        block_mean = []
        block_variance = []

        # take means of blocks and the mean/variance of all blocks, growing
        # blocks by factors of 2
        block_size = 1
        while block_size <= N // 8:
            num_blocks = N // block_size
            block_data = numpy.zeros(num_blocks)

            for i in range(0, num_blocks):
                start = i * block_size
                end = start + block_size
                block_data[i] = numpy.mean(data[start:end])

            block_mean.append(numpy.mean(block_data))
            block_variance.append(numpy.var(block_data) / (num_blocks - 1))

            block_sizes.append(block_size)
            block_size *= 2

        self._block_mean = numpy.array(block_mean)
        self._block_variance = numpy.array(block_variance)
        self._block_sizes = numpy.array(block_sizes)
        self.data = numpy.array(data)

        # check for a plateau in the relative error before the last data point
        block_relative_error = numpy.sqrt(self._block_variance) / numpy.fabs(
            self._block_mean)
        relative_error_derivative = (numpy.diff(block_relative_error)
                                     / numpy.diff(self._block_sizes))
        if numpy.all(relative_error_derivative > 0):
            warnings.warn("Block averaging failed to plateau, run longer")
//  [python]
def test_zeros_filter():
    """Test object filtering on an empty labels matrix"""
    workspace, module = make_workspace({INPUT_OBJECTS: numpy.zeros((10, 10), int)})
    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_LIMITS
    module.measurements[0].min_limit.value = 0
    module.measurements[0].max_limit.value = 1000
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == 0)
//  [python]
def test_zeros_filter():
    """Test object filtering on an empty labels matrix"""
    workspace, module = make_workspace({INPUT_OBJECTS: numpy.zeros((10, 10), int)})
    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_LIMITS
    module.measurements[0].min_limit.value = 0
    module.measurements[0].max_limit.value = 1000
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.zeros((0,)))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == 0)
//  [python]
def test_keep_single_max():
    """Keep a single object (max) from among two"""
    labels = numpy.zeros((10, 10), int)
    labels[2:4, 3:5] = 1
    labels[6:9, 5:8] = 2
    expected = labels.copy()
    expected[labels == 1] = 0
    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, 2]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_single_max():
    """Keep a single object (max) from among two"""
    labels = numpy.zeros((10, 10), int)
    labels[2:4, 3:5] = 1
    labels[6:9, 5:8] = 2
    expected = labels.copy()
    expected[labels == 1] = 0
    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, 2]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_keep_single_min():
    """Keep a single object (min) from among two"""
    labels = numpy.zeros((10, 10), int)
    labels[2:4, 3:5] = 1
    labels[6:9, 5:8] = 2
    expected = labels.copy()
    expected[labels == 1] = 0
    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_MINIMAL
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([2, 1]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
    parents = m.get_current_measurement(
        OUTPUT_OBJECTS, FF_PARENT % INPUT_OBJECTS
    )
    assert len(parents) == 1
    assert parents[0] == 2
    assert (
        m.get_current_image_measurement(
            FF_COUNT % OUTPUT_OBJECTS
        )
        == 1
    )
    feature = FF_CHILDREN_COUNT % OUTPUT_OBJECTS
    child_count = m.get_current_measurement(INPUT_OBJECTS, feature)
    assert len(child_count) == 2
    assert child_count[0] == 0
    assert child_count[1] == 1
//  [python]
def test_keep_single_min():
    """Keep a single object (min) from among two"""
    labels = numpy.zeros((10, 10), int)
    labels[2:4, 3:5] = 1
    labels[6:9, 5:8] = 2
    expected = labels.copy()
    expected[labels == 1] = 0
    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_MINIMAL
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([2, 1]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
    parents = m.get_current_measurement(
        OUTPUT_OBJECTS, FF_PARENT % INPUT_OBJECTS
    )
    assert len(parents) == 1
    assert parents[0] == 2
    assert (
        m.get_current_image_measurement(
            FF_COUNT % OUTPUT_OBJECTS
        )
        == 1
    )
    feature = FF_CHILDREN_COUNT % OUTPUT_OBJECTS
    child_count = m.get_current_measurement(INPUT_OBJECTS, feature)
    assert len(child_count) == 2
    assert child_count[0] == 0
    assert child_count[1] == 1
//  [python]
def test_keep_one_min():
    """Keep two sub-objects (min) from among four enclosed by two"""
    sub_labels = numpy.zeros((20, 20), int)
    expected = numpy.zeros((20, 20), int)
    for i, j, k, e in ((0, 0, 1, 0), (10, 0, 2, 1), (0, 10, 3, 2), (10, 10, 4, 0)):
        sub_labels[i + 2 : i + 5, j + 3 : j + 7] = k
        expected[i + 2 : i + 5, j + 3 : j + 7] = e
    labels = numpy.zeros((20, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 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
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([2, 1, 3, 4]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_one_min():
    """Keep two sub-objects (min) from among four enclosed by two"""
    sub_labels = numpy.zeros((20, 20), int)
    expected = numpy.zeros((20, 20), int)
    for i, j, k, e in ((0, 0, 1, 0), (10, 0, 2, 1), (0, 10, 3, 2), (10, 10, 4, 0)):
        sub_labels[i + 2 : i + 5, j + 3 : j + 7] = k
        expected[i + 2 : i + 5, j + 3 : j + 7] = e
    labels = numpy.zeros((20, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 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
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([2, 1, 3, 4]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_keep_one_max():
    """Keep two sub-objects (max) from among four enclosed by two"""
    sub_labels = numpy.zeros((20, 20), int)
    expected = numpy.zeros((20, 20), int)
    for i, j, k, e in ((0, 0, 1, 0), (10, 0, 2, 1), (0, 10, 3, 2), (10, 10, 4, 0)):
        sub_labels[i + 2 : i + 5, j + 3 : j + 7] = k
        expected[i + 2 : i + 5, j + 3 : j + 7] = e
    labels = numpy.zeros((20, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 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_MAXIMAL_PER_OBJECT
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 2, 4, 3]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_one_max():
    """Keep two sub-objects (max) from among four enclosed by two"""
    sub_labels = numpy.zeros((20, 20), int)
    expected = numpy.zeros((20, 20), int)
    for i, j, k, e in ((0, 0, 1, 0), (10, 0, 2, 1), (0, 10, 3, 2), (10, 10, 4, 0)):
        sub_labels[i + 2 : i + 5, j + 3 : j + 7] = k
        expected[i + 2 : i + 5, j + 3 : j + 7] = e
    labels = numpy.zeros((20, 20), int)
    labels[:, :10] = 1
    labels[:, 10:] = 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_MAXIMAL_PER_OBJECT
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([1, 2, 4, 3]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_keep_maximal_most_overlap():
    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 = sub_labels * (sub_labels != 3)
    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_PARENT_WITH_MOST_OVERLAP
    )
    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_most_overlap():
    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 = sub_labels * (sub_labels != 3)
    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_PARENT_WITH_MOST_OVERLAP
    )
    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_most_overlap():
    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 = sub_labels * (sub_labels != 3)
    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_PARENT_WITH_MOST_OVERLAP
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([4, 2, 3]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_keep_minimal_most_overlap():
    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 = sub_labels * (sub_labels != 3)
    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_PARENT_WITH_MOST_OVERLAP
    )
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, numpy.array([4, 2, 3]))
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_min = 0.3
    my_max = 0.7
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if my_min <= value <= my_max:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].wants_minimum.value = True
    module.measurements[0].min_limit.value = my_min
    module.measurements[0].wants_maximum.value = True
    module.measurements[0].max_limit.value = my_max
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_min = 0.3
    my_max = 0.7
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if my_min <= value <= my_max:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].wants_minimum.value = True
    module.measurements[0].min_limit.value = my_min
    module.measurements[0].wants_maximum.value = True
    module.measurements[0].max_limit.value = my_max
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by min limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_min = 0.3
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if value >= my_min:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].min_limit.value = my_min
    module.measurements[0].max_limit.value = 0.7
    module.measurements[0].wants_maximum.value = False
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by min limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_min = 0.3
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if value >= my_min:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].min_limit.value = my_min
    module.measurements[0].max_limit.value = 0.7
    module.measurements[0].wants_maximum.value = False
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by maximum limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_max = 0.7
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if value <= my_max:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].min_limit.value = 0.3
    module.measurements[0].wants_minimum.value = False
    module.measurements[0].max_limit.value = my_max
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_filter():
    """Filter objects by maximum limits"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.random.uniform(size=n)
    idx = 1
    my_max = 0.7
    expected = numpy.zeros(labels.shape, int)
    for i, value in zip(list(range(n)), values):
        if value <= my_max:
            expected[labels == i + 1] = idx
            idx += 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_LIMITS
    module.measurements[0].min_limit.value = 0.3
    module.measurements[0].wants_minimum.value = False
    module.measurements[0].max_limit.value = my_max
    m = workspace.measurements
    m.add_measurement(INPUT_OBJECTS, TEST_FTR, values)
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_filter_two():
    """Filter objects by two measurements"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.zeros((n, 2))
    values = numpy.random.uniform(size=(n, 2))
    idx = 1
    my_max = numpy.array([0.7, 0.5])
    expected = numpy.zeros(labels.shape, int)
    for i, v1, v2 in zip(list(range(n)), values[:, 0], values[:, 1]):
        if v1 <= my_max[0] and v2 <= my_max[1]:
            expected[labels == i + 1] = idx
            idx += 1
    workspace, module = make_workspace({INPUT_OBJECTS: labels})
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.add_measurement()
    m = workspace.measurements
    for i in range(2):
        measurement_name = "measurement%d" % (i + 1)
        module.measurements[i].measurement.value = measurement_name
        module.filter_choice.value = cellprofiler.modules.filterobjects.FI_LIMITS
        module.measurements[i].min_limit.value = 0.3
        module.measurements[i].wants_minimum.value = False
        module.measurements[i].max_limit.value = my_max[i]
        m.add_measurement(INPUT_OBJECTS, measurement_name, values[:, i])
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(labels.segmented == expected)
//  [python]
def test_filter_two():
    """Filter objects by two measurements"""
    n = 40
    labels = numpy.zeros((10, n * 10), int)
    for i in range(40):
        labels[2:5, i * 10 + 3 : i * 10 + 7] = i + 1
    numpy.random.seed(0)
    values = numpy.zeros((n, 2))
    values = numpy.random.uniform(size=(n, 2))
    idx = 1
    my_max = numpy.array([0.7, 0.5])
    expected = numpy.zeros(labels.shape, int)
    for i, v1, v2 in zip(list(range(n)), values[:, 0], values[:, 1]):
        if v1 <= my_max[0] and v2 <= my_max[1]:
            expected[labels == i + 1] = idx
            idx += 1
    workspace, module = make_workspace({INPUT_OBJECTS: labels})
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.add_measurement()
    m = workspace.measurements
    for i in range(2):
        measurement_name = "measurement%d" % (i + 1)
        module.measurements[i].measurement.value = measurement_name
        module.filter_choice.value = cellprofiler.modules.filterobjects.FI_LIMITS
        module.measurements[i].min_limit.value = 0.3
        module.measurements[i].wants_minimum.value = False
        module.measurements[i].max_limit.value = my_max[i]
        m.add_measurement(INPUT_OBJECTS, measurement_name, values[:, i])
    module.run(workspace)
    labels = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(labels.segmented == expected)
//  [python]
def test_discard_border_objects():
    """Test the mode to discard border objects"""
    labels = numpy.zeros((10, 10), int)
    labels[1:4, 0:3] = 1
    labels[4:8, 1:5] = 2
    labels[:, 9] = 3

    expected = numpy.zeros((10, 10), int)
    expected[4:8, 1:5] = 1

    workspace, module = make_workspace({INPUT_OBJECTS: labels})
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_BORDER
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(expected == output_objects.segmented)
//  [python]
def test_discard_border_objects():
    """Test the mode to discard border objects"""
    labels = numpy.zeros((10, 10), int)
    labels[1:4, 0:3] = 1
    labels[4:8, 1:5] = 2
    labels[:, 9] = 3

    expected = numpy.zeros((10, 10), int)
    expected[4:8, 1:5] = 1

    workspace, module = make_workspace({INPUT_OBJECTS: labels})
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_BORDER
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(expected == output_objects.segmented)
//  [python]
def test_filter_by_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_MyMeasurement > 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.run(workspace)
        target_objects = workspace.object_set.get_objects("MyTargetObjects")
        target_labels = target_objects.segmented
        assert n.all(target_labels[labels == 2] > 0)
        assert n.all(target_labels[labels != 2] == 0)
    finally:
        os.remove(rules_path)
//  [python]
def test_filter_by_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_MyMeasurement > 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.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)
    finally:
        os.remove(rules_path)
//  [python]
def test_discard_mask_objects():
    """Test discarding objects that touch the mask of objects parent img"""
    mask = numpy.ones((10, 10), bool)
    mask[5, 5] = False
    labels = numpy.zeros((10, 10), int)
    labels[1:4, 1:4] = 1
    labels[5:8, 5:8] = 2
    expected = labels.copy()
    expected[expected == 2] = 0

    workspace, module = make_workspace({})
    parent_image = cellprofiler_core.image.Image(numpy.zeros((10, 10)), mask=mask)
    workspace.image_set.add(INPUT_IMAGE, parent_image)

    input_objects = cellprofiler_core.object.Objects()
    input_objects.segmented = labels
    input_objects.parent_image = parent_image

    workspace.object_set.add_objects(input_objects, INPUT_OBJECTS)

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_BORDER
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert n.all(expected == output_objects.segmented)
//  [python]
def test_discard_mask_objects():
    """Test discarding objects that touch the mask of objects parent img"""
    mask = numpy.ones((10, 10), bool)
    mask[5, 5] = False
    labels = numpy.zeros((10, 10), int)
    labels[1:4, 1:4] = 1
    labels[5:8, 5:8] = 2
    expected = labels.copy()
    expected[expected == 2] = 0

    workspace, module = make_workspace({})
    parent_image = cellprofiler_core.image.Image(numpy.zeros((10, 10)), mask=mask)
    workspace.image_set.add(INPUT_IMAGE, parent_image)

    input_objects = cellprofiler_core.object.Objects()
    input_objects.segmented = labels
    input_objects.parent_image = parent_image

    workspace.object_set.add_objects(input_objects, INPUT_OBJECTS)

    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_BORDER
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    assert numpy.all(expected == output_objects.segmented)
//  [python]
def test_small_removed_segmented():
    # Test output objects' small_removed_segmented
    #
    # It should be the small_removed_segmented of the
    # source minus the filtered

    unedited = numpy.zeros((10, 10), dtype=int)
    unedited[0:4, 0:4] = 1
    unedited[6:8, 0:4] = 2
    unedited[6:8, 6:8] = 3
    segmented = numpy.zeros((10, 10), dtype=int)
    segmented[6:8, 6:8] = 1
    segmented[6:8, 0:4] = 2

    workspace, module = make_workspace({})
    input_objects = cellprofiler_core.object.Objects()
    input_objects.segmented = segmented
    input_objects.unedited_segmented = unedited
    workspace.object_set.add_objects(input_objects, INPUT_OBJECTS)
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_MEASUREMENTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MINIMAL
    m = workspace.measurements
    m[INPUT_OBJECTS, TEST_FTR] = numpy.array([2, 1])
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    small_removed = output_objects.small_removed_segmented
    mask = (unedited != 3) & (unedited != 0)
    assert n.all(small_removed[mask] != 0)
    assert n.all(small_removed[~mask] == 0)
//  [python]
def test_small_removed_segmented():
    # Test output objects' small_removed_segmented
    #
    # It should be the small_removed_segmented of the
    # source minus the filtered

    unedited = numpy.zeros((10, 10), dtype=int)
    unedited[0:4, 0:4] = 1
    unedited[6:8, 0:4] = 2
    unedited[6:8, 6:8] = 3
    segmented = numpy.zeros((10, 10), dtype=int)
    segmented[6:8, 6:8] = 1
    segmented[6:8, 0:4] = 2

    workspace, module = make_workspace({})
    input_objects = cellprofiler_core.object.Objects()
    input_objects.segmented = segmented
    input_objects.unedited_segmented = unedited
    workspace.object_set.add_objects(input_objects, INPUT_OBJECTS)
    module.x_name.value = INPUT_OBJECTS
    module.y_name.value = OUTPUT_OBJECTS
    module.mode.value = cellprofiler.modules.filterobjects.MODE_MEASUREMENTS
    module.measurements[0].measurement.value = TEST_FTR
    module.filter_choice.value = cellprofiler.modules.filterobjects.FI_MINIMAL
    m = workspace.measurements
    m[INPUT_OBJECTS, TEST_FTR] = numpy.array([2, 1])
    module.run(workspace)
    output_objects = workspace.object_set.get_objects(OUTPUT_OBJECTS)
    small_removed = output_objects.small_removed_segmented
    mask = (unedited != 3) & (unedited != 0)
    assert numpy.all(small_removed[mask] != 0)
    assert numpy.all(small_removed[~mask] == 0)
//  [python]
def test_keep_maximal_per_object_most_overlap_volume():
    labels = numpy.zeros((1, 10, 20), int)
    labels[:, :, :10] = 1
    labels[:, :, 10:] = 2

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

    expected = sub_labels * (sub_labels != 3)

    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_PARENT_WITH_MOST_OVERLAP
    )

    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_per_object_most_overlap_volume():
    labels = numpy.zeros((1, 10, 20), int)
    labels[:, :, :10] = 1
    labels[:, :, 10:] = 2

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

    expected = sub_labels * (sub_labels != 3)

    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_PARENT_WITH_MOST_OVERLAP
    )

    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_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 n.all(target_labels[labels == 2] > 0)
        assert n.all(target_labels[labels != 2] == 0)
        module.allow_fuzzy.value=False
        with pytest.raises(AssertionError):
            module.run(workspace)
    finally:
        os.remove(rules_path)