jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def set_weight(self, weight):
        """Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy 1-D array, pandas Series or None
            Weight to be set for each data point.

        Returns
        -------
        self : Dataset
            Dataset with set weight.
        """
        if weight is not None and np.all(weight == 1):
            weight = None
        self.weight = weight
        if self.handle is not None and weight is not None:
            weight = list_to_1d_numpy(weight, name='weight')
            self.set_field('weight', weight)
            self.weight = self.get_field('weight')  # original values can be modified at cpp side
        return self
//  [python]
def test_orders(size=40):
    effs1 = losses._compute_positions(numpy.arange(size), numpy.ones(size))
    p = numpy.random.permutation(size)
    effs2 = losses._compute_positions(numpy.arange(size)[p], numpy.ones(size))
    assert n.all(effs1[p] == effs2), 'Efficiencies are wrong'
    assert n.all(effs1 == numpy.sort(effs1)), 'sortings are wrong'
//  [python]
def test_orders(size=40):
    effs1 = losses._compute_positions(numpy.arange(size), numpy.ones(size))
    p = numpy.random.permutation(size)
    effs2 = losses._compute_positions(numpy.arange(size)[p], numpy.ones(size))
    assert numpy.all(effs1[p] == effs2), 'Efficiencies are wrong'
    assert numpy.all(effs1 == numpy.sort(effs1)), 'sortings are wrong'
//  [python]
def all(a, axis: Optional[int] = None):
    """Test whether all array elements along a given axis evaluate to True.

    This function has the same behavior as
    ``np.all(array,axis=axis)``.
    """
    if isinstance(a, TorchTensor):
        # torch.all has two implementation, and picks one depending if more than one
        # parameter is given. The second one does not supports setting dim to `None`
        if axis is None:
            return torch.all(a)
        else:
            return torch.all(a, dim=axis)
    elif isinstance(a, np.ndarray):
        return np.all(a, axis=axis)
    else:
        raise TypeError(UNKNOWN_ARRAY_TYPE)
//  [python]
def test_instance_made_correctly(self):
        """Test that instance of channel class is initialized correctly"""

        class DummyOp(qml.operation.Channel):
            r"""Dummy custom channel"""

            num_wires = 1
            grad_method = "F"

            @staticmethod
            def compute_kraus_matrices(p):  # pylint:disable=arguments-differ
                K1 = np.sqrt(p) * X
                K2 = np.sqrt(1 - p) * I
                return [K1, K2]

        expected = np.array([[0, np.sqrt(0.1)], [np.sqrt(0.1), 0]])
        op = DummyOp(0.1, wires=0)
        assert np.all(op.kraus_matrices()[0] == expected)
//  [python]
def __repr__(self):
        """
        Literal string representation.

        """
        if self._baseclass is np.ndarray:
            name = 'array'
        else:
            name = self._baseclass.__name__


        # 2016-11-19: Demoted to legacy format
        if np.get_printoptions()['legacy'] == '1.13':
            is_long = self.ndim > 1
            parameters = dict(
                name=name,
                nlen=" " * len(name),
                data=str(self),
                mask=str(self._mask),
                fill=str(self.fill_value),
                dtype=str(self.dtype)
            )
            is_structured = bool(self.dtype.names)
            key = '{}_{}'.format(
                'long' if is_long else 'short',
                'flx' if is_structured else 'std'
            )
            return _legacy_print_templates[key] % parameters

        prefix = f"masked_{name}("

        dtype_needed = (
            not np.core.arrayprint.dtype_is_implied(self.dtype) or
            n.all(self.mask) or
            self.size == 0
        )

        # determine which keyword args need to be shown
        keys = ['data', 'mask', 'fill_value']
        if dtype_needed:
            keys.append('dtype')

        # array has only one row (non-column)
        is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1])

        # choose what to indent each keyword with
        min_indent = 2
        if is_one_row:
            # first key on the same line as the type, remaining keys
            # aligned by equals
            indents = {}
            indents[keys[0]] = prefix
            for k in keys[1:]:
                n = builtins.max(min_indent, len(prefix + keys[0]) - len(k))
                indents[k] = ' ' * n
            prefix = ''  # absorbed into the first indent
        else:
            # each key on its own line, indented by two spaces
            indents = {k: ' ' * min_indent for k in keys}
            prefix = prefix + '\n'  # first key on the next line

        # format the field values
        reprs = {}
        reprs['data'] = np.array2string(
            self._insert_masked_print(),
            separator=", ",
            prefix=indents['data'] + 'data=',
            suffix=',')
        reprs['mask'] = np.array2string(
            self._mask,
            separator=", ",
            prefix=indents['mask'] + 'mask=',
            suffix=',')
        reprs['fill_value'] = repr(self.fill_value)
        if dtype_needed:
            reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype)

        # join keys with values and indentations
        result = ',\n'.join(
            '{}{}={}'.format(indents[k], k, reprs[k])
            for k in keys
        )
        return prefix + result + ')'
//  [python]
def __repr__(self):
        """
        Literal string representation.

        """
        if self._baseclass is np.ndarray:
            name = 'array'
        else:
            name = self._baseclass.__name__


        # 2016-11-19: Demoted to legacy format
        if np.get_printoptions()['legacy'] == '1.13':
            is_long = self.ndim > 1
            parameters = dict(
                name=name,
                nlen=" " * len(name),
                data=str(self),
                mask=str(self._mask),
                fill=str(self.fill_value),
                dtype=str(self.dtype)
            )
            is_structured = bool(self.dtype.names)
            key = '{}_{}'.format(
                'long' if is_long else 'short',
                'flx' if is_structured else 'std'
            )
            return _legacy_print_templates[key] % parameters

        prefix = f"masked_{name}("

        dtype_needed = (
            not np.core.arrayprint.dtype_is_implied(self.dtype) or
            np.all(self.mask) or
            self.size == 0
        )

        # determine which keyword args need to be shown
        keys = ['data', 'mask', 'fill_value']
        if dtype_needed:
            keys.append('dtype')

        # array has only one row (non-column)
        is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1])

        # choose what to indent each keyword with
        min_indent = 2
        if is_one_row:
            # first key on the same line as the type, remaining keys
            # aligned by equals
            indents = {}
            indents[keys[0]] = prefix
            for k in keys[1:]:
                n = builtins.max(min_indent, len(prefix + keys[0]) - len(k))
                indents[k] = ' ' * n
            prefix = ''  # absorbed into the first indent
        else:
            # each key on its own line, indented by two spaces
            indents = {k: ' ' * min_indent for k in keys}
            prefix = prefix + '\n'  # first key on the next line

        # format the field values
        reprs = {}
        reprs['data'] = np.array2string(
            self._insert_masked_print(),
            separator=", ",
            prefix=indents['data'] + 'data=',
            suffix=',')
        reprs['mask'] = np.array2string(
            self._mask,
            separator=", ",
            prefix=indents['mask'] + 'mask=',
            suffix=',')
        reprs['fill_value'] = repr(self.fill_value)
        if dtype_needed:
            reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype)

        # join keys with values and indentations
        result = ',\n'.join(
            '{}{}={}'.format(indents[k], k, reprs[k])
            for k in keys
        )
        return prefix + result + ')'
//  [python]
def update(self, t):
        self._T[:] = np.roll(self._T, -1)
        self._T_isfinite[:] = np.roll(self._T_isfinite, -1)
        if np.isfinite(t):
            self._T_isfinite[-1] = True
            self._T[-1] = t
        else:
            self._T_isfinite[-1] = False
            self._T[-1] = 0
        self._n_appended += 1

        self._P = np.roll(self._P, -1, axis=0)
        self._I = np.roll(self._I, -1, axis=0)
        self._left_P[:] = np.roll(self._left_P, -1)
        self._left_I[:] = np.roll(self._left_I, -1)

        D = cdist(
            core.rolling_window(self._T[-self._m :], self._m),
            core.rolling_window(self._T, self._m),
            metric="minkowski",
            p=self._p,
        )[0]
        T_subseq_isfinite = np.all(
            core.rolling_window(self._T_isfinite, self._m), axis=1
        )
        D[~T_subseq_isfinite] = np.inf
        if np.any(~self._T_isfinite[-self._m :]):
            D[:] = np.inf

        apply_exclusion_zone(D, D.shape[0] - 1, self._excl_zone, np.inf)
        for j in range(D.shape[0]):
            if D[j] < self._P[j, -1]:
                pos = np.searchsorted(self._P[j], D[j], side="right")
                self._P[j] = np.insert(self._P[j], pos, D[j])[:-1]
                self._I[j] = np.insert(
                    self._I[j], pos, D.shape[0] - 1 + self._n_appended
                )[:-1]

        # update top-k for the last, newly-updated index
        I_last_topk = np.argsort(D, kind="mergesort")[: self._k]
        self._P[-1] = D[I_last_topk]
        self._I[-1] = I_last_topk + self._n_appended
        self._I[-1][self._P[-1] == np.inf] = -1

        # for the last index, the left matrix profile value is self.P_[-1, 0]
        # and the same goes for the left matrix profile index
        self._left_P[-1] = self._P[-1, 0]
        self._left_I[-1] = self._I[-1, 0]
//  [python]
def clean_poly(points):
    if not n.all(points[0, :] == points[-1, :]):
        points = n.vstack((points, points[0:1, :]))

    dupl = n.concatenate(
        (n.all(points[1:, :] == points[:-1, :], axis=1), [False]))
    points = points[n.logical_not(dupl)]
    return points
//  [python]
def clean_poly(points):
    if not num.all(points[0, :] == points[-1, :]):
        points = num.vstack((points, points[0:1, :]))

    dupl = num.concatenate(
        (num.all(points[1:, :] == points[:-1, :], axis=1), [False]))
    points = points[num.logical_not(dupl)]
    return points
//  [python]
def close_poly(points):
    if not n.all(points[0, :] == points[-1, :]):
        points = n.vstack((points, points[0:1, :]))

    return points
//  [python]
def close_poly(points):
    if not num.all(points[0, :] == points[-1, :]):
        points = num.vstack((points, points[0:1, :]))

    return points
//  [python]
def update(self, t):
        self._T[:] = np.roll(self._T, -1)
        self._T_isfinite[:] = np.roll(self._T_isfinite, -1)
        if np.isfinite(t):
            self._T_isfinite[-1] = True
            self._T[-1] = t
        else:
            self._T_isfinite[-1] = False
            self._T[-1] = 0

        self._T_subseq_isconstant[:] = np.roll(self._T_subseq_isconstant, -1)
        self._T_subseq_isconstant[-1] = rolling_isconstant(
            self._T[-self._m :], self._m, self._T_subseq_isconstant_func
        ) & n.all(self._T_isfinite[-self._m :])

        self._n_appended += 1

        self._P = np.roll(self._P, -1, axis=0)
        self._I = np.roll(self._I, -1, axis=0)
        self._left_P[:] = np.roll(self._left_P, -1)
        self._left_I[:] = np.roll(self._left_I, -1)

        D = core.mass(
            self._T[-self._m :],
            self._T,
            T_subseq_isconstant=self._T_subseq_isconstant,
            Q_subseq_isconstant=self._T_subseq_isconstant[[-1]],
        )
        T_subseq_isfinite = n.all(
            core.rolling_window(self._T_isfinite, self._m), axis=1
        )
        D[~T_subseq_isfinite] = np.inf
        if np.any(~self._T_isfinite[-self._m :]):
            D[:] = np.inf

        apply_exclusion_zone(D, D.shape[0] - 1, self._excl_zone, np.inf)
        # update top-k matrix profile using newly calculated distance profile `D`
        for j in range(D.shape[0]):
            if D[j] < self._P[j, -1]:
                pos = np.searchsorted(self._P[j], D[j], side="right")
                self._P[j] = np.insert(self._P[j], pos, D[j])[:-1]
                self._I[j] = np.insert(
                    self._I[j], pos, D.shape[0] - 1 + self._n_appended
                )[:-1]

        # update top-k for the last, newly-updated index
        I_last_topk = np.argsort(D, kind="mergesort")[: self._k]
        self._P[-1] = D[I_last_topk]
        self._I[-1] = I_last_topk + self._n_appended
        self._I[-1][self._P[-1] == np.inf] = -1

        # for the last index, the left matrix profile value is self.P_[-1, 0]
        # and the same goes for the left matrix profile index
        self._left_P[-1] = self._P[-1, 0]
        self._left_I[-1] = self._I[-1, 0]
//  [python]
def update(self, t):
        self._T[:] = np.roll(self._T, -1)
        self._T_isfinite[:] = np.roll(self._T_isfinite, -1)
        if np.isfinite(t):
            self._T_isfinite[-1] = True
            self._T[-1] = t
        else:
            self._T_isfinite[-1] = False
            self._T[-1] = 0

        self._T_subseq_isconstant[:] = np.roll(self._T_subseq_isconstant, -1)
        self._T_subseq_isconstant[-1] = rolling_isconstant(
            self._T[-self._m :], self._m, self._T_subseq_isconstant_func
        ) & np.all(self._T_isfinite[-self._m :])

        self._n_appended += 1

        self._P = np.roll(self._P, -1, axis=0)
        self._I = np.roll(self._I, -1, axis=0)
        self._left_P[:] = np.roll(self._left_P, -1)
        self._left_I[:] = np.roll(self._left_I, -1)

        D = core.mass(
            self._T[-self._m :],
            self._T,
            T_subseq_isconstant=self._T_subseq_isconstant,
            Q_subseq_isconstant=self._T_subseq_isconstant[[-1]],
        )
        T_subseq_isfinite = np.all(
            core.rolling_window(self._T_isfinite, self._m), axis=1
        )
        D[~T_subseq_isfinite] = np.inf
        if np.any(~self._T_isfinite[-self._m :]):
            D[:] = np.inf

        apply_exclusion_zone(D, D.shape[0] - 1, self._excl_zone, np.inf)
        # update top-k matrix profile using newly calculated distance profile `D`
        for j in range(D.shape[0]):
            if D[j] < self._P[j, -1]:
                pos = np.searchsorted(self._P[j], D[j], side="right")
                self._P[j] = np.insert(self._P[j], pos, D[j])[:-1]
                self._I[j] = np.insert(
                    self._I[j], pos, D.shape[0] - 1 + self._n_appended
                )[:-1]

        # update top-k for the last, newly-updated index
        I_last_topk = np.argsort(D, kind="mergesort")[: self._k]
        self._P[-1] = D[I_last_topk]
        self._I[-1] = I_last_topk + self._n_appended
        self._I[-1][self._P[-1] == np.inf] = -1

        # for the last index, the left matrix profile value is self.P_[-1, 0]
        # and the same goes for the left matrix profile index
        self._left_P[-1] = self._P[-1, 0]
        self._left_I[-1] = self._I[-1, 0]
//  [python]
def test_convert_to_H():
    operator = (
        2 * qml.X(0)
        + 3 * qml.X(0)
        + qml.Y(1) @ qml.Z(2) @ (2 * qml.X(3))
        + 2 * (qml.Hadamard(3) + 3 * qml.Z(2))
    )
    with qml.operation.disable_new_opmath_cm():
        legacy_H = qml.operation.convert_to_H(operator)
    linear_combination = qml.operation.convert_to_H(operator)

    assert isinstance(legacy_H, qml.ops.Hamiltonian)
    assert isinstance(linear_combination, qml.ops.LinearCombination)

    # coeffs match
    legacy_coeffs, legacy_ops = legacy_H.terms()
    coeffs, ops = linear_combination.terms()
    assert n.all(legacy_coeffs == coeffs)

    # legacy version has Tensors and not Prods, new version opposite
    assert Tensor in [type(o) for o in legacy_ops]
    assert Tensor not in [type(o) for o in ops]
    assert qml.ops.op_math.Prod not in [type(o) for o in legacy_ops]
    assert qml.ops.op_math.Prod in [type(o) for o in ops]

    # ops match
    for legacy_op, op in zip(legacy_ops, ops):
        assert n.all(legacy_op.matrix() == op.matrix())

    # the converted op is the same as the original op
    assert qml.equal(operator.simplify(), linear_combination.simplify())
//  [python]
def test_convert_to_H():
    operator = (
        2 * qml.X(0)
        + 3 * qml.X(0)
        + qml.Y(1) @ qml.Z(2) @ (2 * qml.X(3))
        + 2 * (qml.Hadamard(3) + 3 * qml.Z(2))
    )
    with qml.operation.disable_new_opmath_cm():
        legacy_H = qml.operation.convert_to_H(operator)
    linear_combination = qml.operation.convert_to_H(operator)

    assert isinstance(legacy_H, qml.ops.Hamiltonian)
    assert isinstance(linear_combination, qml.ops.LinearCombination)

    # coeffs match
    legacy_coeffs, legacy_ops = legacy_H.terms()
    coeffs, ops = linear_combination.terms()
    assert np.all(legacy_coeffs == coeffs)

    # legacy version has Tensors and not Prods, new version opposite
    assert Tensor in [type(o) for o in legacy_ops]
    assert Tensor not in [type(o) for o in ops]
    assert qml.ops.op_math.Prod not in [type(o) for o in legacy_ops]
    assert qml.ops.op_math.Prod in [type(o) for o in ops]

    # ops match
    for legacy_op, op in zip(legacy_ops, ops):
        assert np.all(legacy_op.matrix() == op.matrix())

    # the converted op is the same as the original op
    assert qml.equal(operator.simplify(), linear_combination.simplify())
//  [python]
def test_check_cv():
    X = np.ones(9)
    cv = check_cv(3, classifier=False)
    # Use numpy.testing.assert_equal which recursively compares
    # lists of lists
    np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X)))

    y_binary = np.array([0, 1, 0, 1, 0, 0, 1, 1, 1])
    cv = check_cv(3, y_binary, classifier=True)
    np.testing.assert_equal(
        list(StratifiedKFold(3).split(X, y_binary)), list(cv.split(X, y_binary))
    )

    y_multiclass = np.array([0, 1, 0, 1, 2, 1, 2, 0, 2])
    cv = check_cv(3, y_multiclass, classifier=True)
    np.testing.assert_equal(
        list(StratifiedKFold(3).split(X, y_multiclass)), list(cv.split(X, y_multiclass))
    )
    # also works with 2d multiclass
    y_multiclass_2d = y_multiclass.reshape(-1, 1)
    cv = check_cv(3, y_multiclass_2d, classifier=True)
    np.testing.assert_equal(
        list(StratifiedKFold(3).split(X, y_multiclass_2d)),
        list(cv.split(X, y_multiclass_2d)),
    )

    assert not np.all(
        next(StratifiedKFold(3).split(X, y_multiclass_2d))[0]
        == next(KFold(3).split(X, y_multiclass_2d))[0]
    )

    X = np.ones(5)
    y_multilabel = np.array(
        [[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 1], [0, 0, 1, 0]]
    )
    cv = check_cv(3, y_multilabel, classifier=True)
    np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X)))

    y_multioutput = np.array([[1, 2], [0, 3], [0, 0], [3, 1], [2, 0]])
    cv = check_cv(3, y_multioutput, classifier=True)
    np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X)))

    with pytest.raises(ValueError):
        check_cv(cv="lolo")
//  [python]
def __eq__(self, other):
        if type(self) != type(other):
            return False
        try:
            (t0, d0), (t1, d1) = self, other
        except Exception:
            return False

        # N.B. compare shape to ensure no broadcasting in ==
        if t0 != t1 or d0.shape != d1.shape:
            return False

        self.no_nan  # Ensure has_nan is computed.
        # Note that in the comparisons below, the elementwise comparisons
        # come last because they are the most expensive checks.
        if self.has_nan:
            other.no_nan  # Ensure has_nan is computed.
            return (other.has_nan and
                    self.sum == other.sum and
                    (self.no_nan.mask == other.no_nan.mask).all() and
                    # Note that the second test below (==) may crash e.g. for
                    # a single scalar NaN value, so we do not run it when all
                    # values are missing.
                    (self.no_nan.mask.all() or
                     (self.no_nan == other.no_nan).all()))
        else:
            # Simple case where we do not need to worry about NaN values.
            # (note that if there are NaN values in d1, this will return
            # False, which is why we do not bother with testing `other.has_nan`
            # here).
            return (self.sum == other.sum) and n.all(d0 == d1)
//  [python]
def __eq__(self, other):
        if type(self) != type(other):
            return False
        try:
            (t0, d0), (t1, d1) = self, other
        except Exception:
            return False

        # N.B. compare shape to ensure no broadcasting in ==
        if t0 != t1 or d0.shape != d1.shape:
            return False

        self.no_nan  # Ensure has_nan is computed.
        # Note that in the comparisons below, the elementwise comparisons
        # come last because they are the most expensive checks.
        if self.has_nan:
            other.no_nan  # Ensure has_nan is computed.
            return (other.has_nan and
                    self.sum == other.sum and
                    (self.no_nan.mask == other.no_nan.mask).all() and
                    # Note that the second test below (==) may crash e.g. for
                    # a single scalar NaN value, so we do not run it when all
                    # values are missing.
                    (self.no_nan.mask.all() or
                     (self.no_nan == other.no_nan).all()))
        else:
            # Simple case where we do not need to worry about NaN values.
            # (note that if there are NaN values in d1, this will return
            # False, which is why we do not bother with testing `other.has_nan`
            # here).
            return (self.sum == other.sum) and np.all(d0 == d1)
//  [python]
def _read_time_0_no_grid(self, do_slice, t_start, t_stop, nodes):
        if do_slice:
            is_sorted = numpy.all(numpy.diff(nodes) > 0)
            if not is_sorted:
                mapping = numpy.argsort(nodes)
                sorted_nodes = numpy.sort(nodes)
            if not is_sorted:
                local_chunk = self.data[t_start:t_stop, sorted_nodes]
                local_chunk = local_chunk[:, mapping]
            else:
                local_chunk = self.data[t_start:t_stop, nodes]
        else:
            local_chunk = self.data[t_start:t_stop, :]
        return local_chunk
//  [python]
def read_chunk(self, idx, chunk_size, padding=(0, 0), nodes=None):

        t_start, t_stop = self._get_t_start_t_stop(idx, chunk_size, padding)
        do_slice = nodes is not None and not numpy.all(nodes == numpy.arange(self.nb_channels))
        local_chunk = self._read_chunk(do_slice, t_start, t_stop, nodes)

        return self._scale_data_to_float32(local_chunk)
//  [python]
def _read_time_1_no_grid(self, do_slice, t_start, t_stop, nodes):
        if do_slice:
            is_sorted = numpy.all(numpy.diff(nodes) > 0)
            if not is_sorted:
                mapping = numpy.argsort(nodes)
            sorted_nodes = numpy.sort(nodes)
            if not is_sorted:
                local_chunk = self.data[sorted_nodes, t_start:t_stop].T
                local_chunk = local_chunk[:, mapping]
            else:
                local_chunk = self.data[nodes, t_start:t_stop].T
        else:
            local_chunk = self.data[:, t_start:t_stop].T
        return local_chunk
//  [python]
def test_object_with_array(self):
        mx1 = masked_array([1.], mask=[True])
        mx2 = masked_array([1., 2.])
        mx = masked_array([mx1, mx2], mask=[False, True])
        assert mx[0] is mx1
        assert mx[1] is not mx2
        assert n.all(mx[1].data == mx2.data)
        assert n.all(mx[1].mask)
        # check that we return a view.
        mx[1].data[0] = 0.
        assert mx2[0] == 0.
//  [python]
def test_object_with_array(self):
        mx1 = masked_array([1.], mask=[True])
        mx2 = masked_array([1., 2.])
        mx = masked_array([mx1, mx2], mask=[False, True])
        assert mx[0] is mx1
        assert mx[1] is not mx2
        assert np.all(mx[1].data == mx2.data)
        assert np.all(mx[1].mask)
        # check that we return a view.
        mx[1].data[0] = 0.
        assert mx2[0] == 0.
//  [python]
def is_closed_polygon(X):
    """
    Tests whether first and last object in a sequence are the same.  These are
    presumably coordinates on a polygonal curve, in which case this function
    tests if that curve is closed.
    """
    return n.all(X[0] == X[-1])
//  [python]
def is_closed_polygon(X):
    """
    Tests whether first and last object in a sequence are the same.  These are
    presumably coordinates on a polygonal curve, in which case this function
    tests if that curve is closed.
    """
    return np.all(X[0] == X[-1])
//  [python]
def check_sigma(A):
    """
        checks if the sigma matrix is symmetric
        positive definite before inverting via
        cholesky decomposition

        Lekan Molux. Circa, Summer 2018.
    """
    eigval = np.linalg.eigh(A)[0]
    if np.array_equal(A, A.T) and n.all(eigval>0):
        # logger.debug("sigma is pos. def. Computing cholesky factorization")
        return A
    else:
        # find lowest eigen value
        eta = 1e-6  # regularizer for matrix multiplier
        low = np.amin(np.sort(eigval))
        Anew = low * A + eta * np.eye(A.shape[0])
        return Anew
//  [python]
def check_sigma(A):
    """
        checks if the sigma matrix is symmetric
        positive definite before inverting via
        cholesky decomposition

        Lekan Molux. Circa, Summer 2018.
    """
    eigval = np.linalg.eigh(A)[0]
    if np.array_equal(A, A.T) and np.all(eigval>0):
        # logger.debug("sigma is pos. def. Computing cholesky factorization")
        return A
    else:
        # find lowest eigen value
        eta = 1e-6  # regularizer for matrix multiplier
        low = np.amin(np.sort(eigval))
        Anew = low * A + eta * np.eye(A.shape[0])
        return Anew
//  [python]
def _value_to_value_table_with_interpolation_conversion(vector, cc_val):
    """ apply value to value table with interpolation conversion to data

    Parameters
    ----------------
    vector : numpy 1D array
        raw data to be converted to physical value
    cc_val : mdfinfo4.info4 conversion block ('CCBlock') dict

    Returns
    -----------
    converted data to physical value
    """
    val_count = 2 * int(len(cc_val) / 2)
    int_val = [cc_val[i] for i in range(0, val_count, 2)]
    phys_val = [cc_val[i] for i in range(1, val_count, 2)]
    if n.all(n.diff(int_val) > 0):
        return interp(vector, int_val, phys_val)  # with interpolation
    else:
        warn('X values for interpolation of channel are not increasing')
//  [python]
def _value_to_value_table_with_interpolation_conversion(vector, cc_val):
    """ apply value to value table with interpolation conversion to data

    Parameters
    ----------------
    vector : numpy 1D array
        raw data to be converted to physical value
    cc_val : mdfinfo4.info4 conversion block ('CCBlock') dict

    Returns
    -----------
    converted data to physical value
    """
    val_count = 2 * int(len(cc_val) / 2)
    int_val = [cc_val[i] for i in range(0, val_count, 2)]
    phys_val = [cc_val[i] for i in range(1, val_count, 2)]
    if all(diff(int_val) > 0):
        return interp(vector, int_val, phys_val)  # with interpolation
    else:
        warn('X values for interpolation of channel are not increasing')
//  [python]
def _value_to_value_table_without_interpolation_conversion(vector, cc_val):
    """ apply value to value table without interpolation conversion to data

    Parameters
    ----------------
    vector : numpy 1D array
        raw data to be converted to physical value
    cc_val : mdfinfo4.info4 conversion block ('CCBlock') dict

    Returns
    -----------
    converted data to physical value
    """
    val_count = 2 * int(len(cc_val) / 2)
    int_val = [cc_val[i] for i in range(0, val_count, 2)]
    phys_val = [cc_val[i] for i in range(1, val_count, 2)]
    if n.all(n.diff(int_val) > 0):
        try:
            from scipy import interpolate
            f = interpolate.interp1d(int_val, phys_val, kind='nearest', bounds_error=False)  # nearest
            return f(vector)  # fill with Nan out of bounds while should be bounds
        except ImportError:
            warn('Please install scipy to convert channel')
    else:
        warn('X values for interpolation of channel are not increasing')
//  [python]
def _value_to_value_table_without_interpolation_conversion(vector, cc_val):
    """ apply value to value table without interpolation conversion to data

    Parameters
    ----------------
    vector : numpy 1D array
        raw data to be converted to physical value
    cc_val : mdfinfo4.info4 conversion block ('CCBlock') dict

    Returns
    -----------
    converted data to physical value
    """
    val_count = 2 * int(len(cc_val) / 2)
    int_val = [cc_val[i] for i in range(0, val_count, 2)]
    phys_val = [cc_val[i] for i in range(1, val_count, 2)]
    if all(diff(int_val) > 0):
        try:
            from scipy import interpolate
            f = interpolate.interp1d(int_val, phys_val, kind='nearest', bounds_error=False)  # nearest
            return f(vector)  # fill with Nan out of bounds while should be bounds
        except ImportError:
            warn('Please install scipy to convert channel')
    else:
        warn('X values for interpolation of channel are not increasing')
//  [python]
def test_straighten_nothing():
    workspace, module = make_workspace(
        numpy.zeros((5, 2, 0)), numpy.zeros(0), numpy.zeros(5), numpy.zeros((20, 10))
    )
    module.run(workspace)

    image = workspace.image_set.get_image(STRAIGHTENED_IMAGE_NAME)
    # TODO: This test is failing due to a chance in ndimage.map_coordinates as of scipy v1.1
    # TODO: Previously the map_coordinates call on line 542 of straightenworms would return
    # TODO: an all False array - as of v1.1 it is returning an all True array. I don't know
    # TODO: enough about map_coordinates to know what it should be doing here or why, so I'll
    # TODO: need to come back to this and see what needs to be changed for this to be resolved
    # assertFalse(np.any(image.mask))
    objectset = workspace.object_set
    assert isinstance(objectset, cellprofiler_core.object.ObjectSet)
    labels = objectset.get_objects(STRAIGHTENED_OBJECTS_NAME).segmented
    assert numpy.all(labels == 0)
    m = workspace.measurements
    assert isinstance(m,cellprofiler_core.measurement.Measurements)
    assert (
        m.get_current_image_measurement(
            "_".join((C_COUNT, STRAIGHTENED_OBJECTS_NAME))
        )
        == 0
    )
    assert (
        len(
            m.get_current_measurement(
                STRAIGHTENED_OBJECTS_NAME,
                M_LOCATION_CENTER_X,
            )
        )
        == 0
    )
    assert (
        len(
            m.get_current_measurement(
                STRAIGHTENED_OBJECTS_NAME,
                M_LOCATION_CENTER_Y,
            )
        )
        == 0
    )
//  [python]
def all(self, *args, **kwargs):
        """
        Return whether all elements are Truthy.

        Parameters
        ----------
        *args
            Required for compatibility with numpy.
        **kwargs
            Required for compatibility with numpy.

        Returns
        -------
        bool or array-like (if axis is specified)
            A single element array-like may be converted to bool.

        See Also
        --------
        Index.any : Return whether any element in an Index is True.
        Series.any : Return whether any element in a Series is True.
        Series.all : Return whether all elements in a Series are True.

        Notes
        -----
        Not a Number (NaN), positive infinity and negative infinity
        evaluate to True because these are not equal to zero.

        Examples
        --------
        True, because nonzero integers are considered True.

        >>> pd.Index([1, 2, 3]).all()
        True

        False, because ``0`` is considered False.

        >>> pd.Index([0, 1, 2]).all()
        False
        """
        nv.validate_all(args, kwargs)
        self._maybe_disable_logical_methods("all")
        return n.all(self.values)
//  [python]
def all(self, *args, **kwargs):
        """
        Return whether all elements are Truthy.

        Parameters
        ----------
        *args
            Required for compatibility with numpy.
        **kwargs
            Required for compatibility with numpy.

        Returns
        -------
        bool or array-like (if axis is specified)
            A single element array-like may be converted to bool.

        See Also
        --------
        Index.any : Return whether any element in an Index is True.
        Series.any : Return whether any element in a Series is True.
        Series.all : Return whether all elements in a Series are True.

        Notes
        -----
        Not a Number (NaN), positive infinity and negative infinity
        evaluate to True because these are not equal to zero.

        Examples
        --------
        True, because nonzero integers are considered True.

        >>> pd.Index([1, 2, 3]).all()
        True

        False, because ``0`` is considered False.

        >>> pd.Index([0, 1, 2]).all()
        False
        """
        nv.validate_all(args, kwargs)
        self._maybe_disable_logical_methods("all")
        # error: Argument 1 to "all" has incompatible type "ArrayLike"; expected
        # "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int,
        # float, complex, str, bytes, generic]], Sequence[Sequence[Any]],
        # _SupportsArray]"
        return np.all(self.values)
//  [python]
def test_average():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.zeros((10, 10), numpy.float32)
    for image, mask in images_and_masks:
        expected += image
    expected = expected / len(images_and_masks)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_AVERAGE, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def circularize(x, bottom=0, top=2 * np.pi, deg=False):
    """Maps the input into the continuous interval (bottom, top) where
    bottom defaults to 0 and top defaults to 2*pi

    Parameters
    ----------

    x : ndarray - the input array

    bottom : float, optional (defaults to 0).
        If you want to set the bottom of the interval into which you
        modulo to something else than 0.

    top : float, optional (defaults to 2*pi).
        If you want to set the top of the interval into which you
        modulo to something else than 2*pi

    Returns
    -------
    The input array, mapped into the interval (bottom,top)

    """
    x = np.asarray([x])

    if  (np.alltrue(x[np.isfinite(x)] >= bottom) and
         np.alltrue(x[np.isfinite(x)] <= top)):
        return np.squeeze(x)
    else:
        x[np.where(x < 0)] += top
        x[np.where(x > top)] -= top

    return np.squeeze(circularize(x, bottom=bottom, top=top))
//  [python]
def circularize(x, bottom=0, top=2 * np.pi, deg=False):
    """Maps the input into the continuous interval (bottom, top) where
    bottom defaults to 0 and top defaults to 2*pi

    Parameters
    ----------

    x : ndarray - the input array

    bottom : float, optional (defaults to 0).
        If you want to set the bottom of the interval into which you
        modulo to something else than 0.

    top : float, optional (defaults to 2*pi).
        If you want to set the top of the interval into which you
        modulo to something else than 2*pi

    Returns
    -------
    The input array, mapped into the interval (bottom,top)

    """
    x = np.asarray([x])

    if  (np.all(x[np.isfinite(x)] >= bottom) and
         np.all(x[np.isfinite(x)] <= top)):
        return np.squeeze(x)
    else:
        x[np.where(x < 0)] += top
        x[np.where(x > top)] -= top

    return np.squeeze(circularize(x, bottom=bottom, top=top))
//  [python]
def test_average_color():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10, 3)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.zeros((10, 10, 3), numpy.float32)
    for image, mask in images_and_masks:
        expected += image
    expected = expected / len(images_and_masks)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_AVERAGE, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_maximum():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.zeros((10, 10), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.maximum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MAXIMUM, images_and_masks
    )
    assert not image.has_mask
    assert n.all(n.abs(image.pixel_data - expected) < n.finfo(float).eps)
//  [python]
def test_maximum():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.zeros((10, 10), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.maximum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MAXIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_average_mask():
    numpy.random.seed(0)
    images_and_masks = [
        (
            numpy.random.uniform(size=(100, 100)).astype(numpy.float32),
            numpy.random.uniform(size=(100, 100)) > 0.3,
        )
        for i in range(3)
    ]
    expected = numpy.zeros((100, 100), numpy.float32)
    expected_count = numpy.zeros((100, 100), numpy.float32)
    expected_mask = numpy.zeros((100, 100), bool)
    for image, mask in images_and_masks:
        expected[mask] += image[mask]
        expected_count[mask] += 1
        expected_mask = mask | expected_mask
    expected = expected / expected_count
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_AVERAGE, images_and_masks
    )
    assert image.has_mask
    assert numpy.alltrue(expected_mask == image.mask)
    numpy.testing.assert_almost_equal(
        image.pixel_data[image.mask], expected[expected_mask]
    )
//  [python]
def test_average_mask():
    numpy.random.seed(0)
    images_and_masks = [
        (
            numpy.random.uniform(size=(100, 100)).astype(numpy.float32),
            numpy.random.uniform(size=(100, 100)) > 0.3,
        )
        for i in range(3)
    ]
    expected = numpy.zeros((100, 100), numpy.float32)
    expected_count = numpy.zeros((100, 100), numpy.float32)
    expected_mask = numpy.zeros((100, 100), bool)
    for image, mask in images_and_masks:
        expected[mask] += image[mask]
        expected_count[mask] += 1
        expected_mask = mask | expected_mask
    expected = expected / expected_count
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_AVERAGE, images_and_masks
    )
    assert image.has_mask
    assert numpy.all(expected_mask == image.mask)
    numpy.testing.assert_almost_equal(
        image.pixel_data[image.mask], expected[expected_mask]
    )
//  [python]
def test_maximum_color():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10, 3)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.zeros((10, 10, 3), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.maximum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MAXIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_maximum_mask():
    numpy.random.seed(0)
    images_and_masks = [
        (
            numpy.random.uniform(size=(100, 100)).astype(numpy.float32),
            numpy.random.uniform(size=(100, 100)) > 0.3,
        )
        for i in range(3)
    ]
    expected = numpy.zeros((100, 100), numpy.float32)
    expected_mask = numpy.zeros((100, 100), bool)
    for image, mask in images_and_masks:
        expected[mask] = numpy.maximum(expected[mask], image[mask])
        expected_mask = mask | expected_mask
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MAXIMUM, images_and_masks
    )
    assert image.has_mask
    assert n.all(expected_mask == image.mask)
    assert n.all(
        numpy.abs(image.pixel_data[image.mask] - expected[expected_mask])
        < numpy.finfo(float).eps
    )
//  [python]
def test_maximum_mask():
    numpy.random.seed(0)
    images_and_masks = [
        (
            numpy.random.uniform(size=(100, 100)).astype(numpy.float32),
            numpy.random.uniform(size=(100, 100)) > 0.3,
        )
        for i in range(3)
    ]
    expected = numpy.zeros((100, 100), numpy.float32)
    expected_mask = numpy.zeros((100, 100), bool)
    for image, mask in images_and_masks:
        expected[mask] = numpy.maximum(expected[mask], image[mask])
        expected_mask = mask | expected_mask
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MAXIMUM, images_and_masks
    )
    assert image.has_mask
    assert numpy.all(expected_mask == image.mask)
    assert numpy.all(
        numpy.abs(image.pixel_data[image.mask] - expected[expected_mask])
        < numpy.finfo(float).eps
    )
//  [python]
def test_minimum():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.minimum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MINIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.alltrue(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_minimum():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.minimum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MINIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_mask_unmasked():
    numpy.random.seed(81)
    images_and_masks = [(numpy.random.uniform(size=(10, 10)), None) for i in range(3)]
    image = run_image_set(cellprofiler.modules.makeprojection.P_MASK, images_and_masks)
    assert tuple(image.pixel_data.shape) == (10, 10)
    assert numpy.alltrue(image.pixel_data == True)
    assert not image.has_mask
//  [python]
def test_mask_unmasked():
    numpy.random.seed(81)
    images_and_masks = [(numpy.random.uniform(size=(10, 10)), None) for i in range(3)]
    image = run_image_set(cellprofiler.modules.makeprojection.P_MASK, images_and_masks)
    assert tuple(image.pixel_data.shape) == (10, 10)
    assert numpy.all(image.pixel_data == True)
    assert not image.has_mask
//  [python]
def test_minimum_color():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10, 3)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10, 3), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.minimum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MINIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.alltrue(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_minimum_color():
    numpy.random.seed(0)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10, 3)).astype(numpy.float32), None)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10, 3), numpy.float32)
    for image, mask in images_and_masks:
        expected = numpy.minimum(expected, image)
    image = run_image_set(
        cellprofiler.modules.makeprojection.P_MINIMUM, images_and_masks
    )
    assert not image.has_mask
    assert numpy.all(numpy.abs(image.pixel_data - expected) < numpy.finfo(float).eps)
//  [python]
def test_mask():
    numpy.random.seed(81)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)), numpy.random.uniform(size=(10, 10)) > 0.3)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10), bool)
    for _, mask in images_and_masks:
        expected = expected & mask
    image = run_image_set(cellprofiler.modules.makeprojection.P_MASK, images_and_masks)
    assert n.all(image.pixel_data == expected)
//  [python]
def test_mask():
    numpy.random.seed(81)
    images_and_masks = [
        (numpy.random.uniform(size=(10, 10)), numpy.random.uniform(size=(10, 10)) > 0.3)
        for i in range(3)
    ]
    expected = numpy.ones((10, 10), bool)
    for _, mask in images_and_masks:
        expected = expected & mask
    image = run_image_set(cellprofiler.modules.makeprojection.P_MASK, images_and_masks)
    assert numpy.all(image.pixel_data == expected)
//  [python]
def test_to_copies(self):
        q = u.Quantity(np.arange(1.0, 100.0), "km/s")
        q2 = q.to(u.m / u.s)
        assert n.all(q.value != q2.value)
        q3 = q.to(u.km / u.s)
        assert n.all(q.value == q3.value)
        q[0] = -1.0 * u.km / u.s
        assert q[0].value != q3[0].value
//  [python]
def test_to_copies(self):
        q = u.Quantity(np.arange(1.0, 100.0), "km/s")
        q2 = q.to(u.m / u.s)
        assert np.all(q.value != q2.value)
        q3 = q.to(u.km / u.s)
        assert np.all(q.value == q3.value)
        q[0] = -1.0 * u.km / u.s
        assert q[0].value != q3[0].value