jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_simple_grid1d(self):
        compiled = cuda.jit("void(int32[::1])")(simple_grid1d)
        ntid, nctaid = 3, 7
        nelem = ntid * nctaid
        ary = np.empty(nelem, dtype=np.int32)
        compiled[nctaid, ntid](ary)
        self.assertTrue(n.all(ary == np.arange(nelem)))
//  [python]
def test_simple_grid1d(self):
        compiled = cuda.jit("void(int32[::1])")(simple_grid1d)
        ntid, nctaid = 3, 7
        nelem = ntid * nctaid
        ary = np.empty(nelem, dtype=np.int32)
        compiled[nctaid, ntid](ary)
        self.assertTrue(np.all(ary == np.arange(nelem)))
//  [python]
def test_simple_laneid(self):
        compiled = cuda.jit("void(int32[:])")(simple_laneid)
        count = 2
        ary = np.zeros(count * 32, dtype=np.int32)
        exp = np.tile(np.arange(32, dtype=np.int32), count)
        compiled[1, count * 32](ary)
        self.assertTrue(np.all(ary == exp))
//  [python]
def __init__(
        self,
        endog,
        exog,
        exog_coint,
        k_ar,
        coint_rank,
        alpha,
        beta,
        gamma,
        sigma_u,
        deterministic="n",
        seasons=0,
        first_season=0,
        delta_y_1_T=None,
        y_lag1=None,
        delta_x=None,
        model=None,
        names=None,
        dates=None,
    ):
        self.model = model
        self.y_all = endog
        self.exog = exog
        self.exog_coint = exog_coint
        self.names = names
        self.dates = dates
        self.neqs = endog.shape[0]
        self.k_ar = k_ar
        deterministic = string_like(deterministic, "deterministic")
        self.deterministic = deterministic
        self.seasons = seasons
        self.first_season = first_season

        self.coint_rank = coint_rank
        if alpha.dtype == np.complex128 and n.all(np.imag(alpha) == 0):
            alpha = np.real_if_close(alpha)
        if beta.dtype == np.complex128 and n.all(np.imag(beta) == 0):
            beta = np.real_if_close(beta)
        if gamma.dtype == np.complex128 and n.all(np.imag(gamma) == 0):
            gamma = np.real_if_close(gamma)

        self.alpha = alpha
        self.beta, self.det_coef_coint = np.vsplit(beta, [self.neqs])
        self.gamma, self.det_coef = np.hsplit(
            gamma, [self.neqs * (self.k_ar - 1)]
        )

        if "ci" in deterministic:
            self.const_coint = self.det_coef_coint[:1, :]
        else:
            self.const_coint = np.zeros(coint_rank).reshape((1, -1))
        if "li" in deterministic:
            start = 1 if "ci" in deterministic else 0
            self.lin_trend_coint = self.det_coef_coint[start : start + 1, :]
        else:
            self.lin_trend_coint = np.zeros(coint_rank).reshape(1, -1)
        if self.exog_coint is not None:
            start = ("ci" in deterministic) + ("li" in deterministic)
            self.exog_coint_coefs = self.det_coef_coint[start:, :]
        else:
            self.exog_coint_coefs = None

        split_const_season = 1 if "co" in deterministic else 0
        split_season_lin = split_const_season + (
            (seasons - 1) if seasons else 0
        )
        if "lo" in deterministic:
            split_lin_exog = split_season_lin + 1
        else:
            split_lin_exog = split_season_lin
        self.const, self.seasonal, self.lin_trend, self.exog_coefs = np.hsplit(
            self.det_coef,
            [split_const_season, split_season_lin, split_lin_exog],
        )

        self.sigma_u = sigma_u

        if (
            y_lag1 is not None
            and delta_x is not None
            and delta_y_1_T is not None
        ):
            self._delta_y_1_T = delta_y_1_T
            self._y_lag1 = y_lag1
            self._delta_x = delta_x
        else:
            (
                _y_1_T,
                self._delta_y_1_T,
                self._y_lag1,
                self._delta_x,
            ) = _endog_matrices(endog, self.exog, k_ar, deterministic, seasons)
        self.nobs = self._y_lag1.shape[1]
//  [python]
def __init__(
        self,
        endog,
        exog,
        exog_coint,
        k_ar,
        coint_rank,
        alpha,
        beta,
        gamma,
        sigma_u,
        deterministic="n",
        seasons=0,
        first_season=0,
        delta_y_1_T=None,
        y_lag1=None,
        delta_x=None,
        model=None,
        names=None,
        dates=None,
    ):
        self.model = model
        self.y_all = endog
        self.exog = exog
        self.exog_coint = exog_coint
        self.names = names
        self.dates = dates
        self.neqs = endog.shape[0]
        self.k_ar = k_ar
        deterministic = string_like(deterministic, "deterministic")
        self.deterministic = deterministic
        self.seasons = seasons
        self.first_season = first_season

        self.coint_rank = coint_rank
        if alpha.dtype == np.complex128 and np.all(np.imag(alpha) == 0):
            alpha = np.real_if_close(alpha)
        if beta.dtype == np.complex128 and np.all(np.imag(beta) == 0):
            beta = np.real_if_close(beta)
        if gamma.dtype == np.complex128 and np.all(np.imag(gamma) == 0):
            gamma = np.real_if_close(gamma)

        self.alpha = alpha
        self.beta, self.det_coef_coint = np.vsplit(beta, [self.neqs])
        self.gamma, self.det_coef = np.hsplit(
            gamma, [self.neqs * (self.k_ar - 1)]
        )

        if "ci" in deterministic:
            self.const_coint = self.det_coef_coint[:1, :]
        else:
            self.const_coint = np.zeros(coint_rank).reshape((1, -1))
        if "li" in deterministic:
            start = 1 if "ci" in deterministic else 0
            self.lin_trend_coint = self.det_coef_coint[start : start + 1, :]
        else:
            self.lin_trend_coint = np.zeros(coint_rank).reshape(1, -1)
        if self.exog_coint is not None:
            start = ("ci" in deterministic) + ("li" in deterministic)
            self.exog_coint_coefs = self.det_coef_coint[start:, :]
        else:
            self.exog_coint_coefs = None

        split_const_season = 1 if "co" in deterministic else 0
        split_season_lin = split_const_season + (
            (seasons - 1) if seasons else 0
        )
        if "lo" in deterministic:
            split_lin_exog = split_season_lin + 1
        else:
            split_lin_exog = split_season_lin
        self.const, self.seasonal, self.lin_trend, self.exog_coefs = np.hsplit(
            self.det_coef,
            [split_const_season, split_season_lin, split_lin_exog],
        )

        self.sigma_u = sigma_u

        if (
            y_lag1 is not None
            and delta_x is not None
            and delta_y_1_T is not None
        ):
            self._delta_y_1_T = delta_y_1_T
            self._y_lag1 = y_lag1
            self._delta_x = delta_x
        else:
            (
                _y_1_T,
                self._delta_y_1_T,
                self._y_lag1,
                self._delta_x,
            ) = _endog_matrices(endog, self.exog, k_ar, deterministic, seasons)
        self.nobs = self._y_lag1.shape[1]
//  [python]
def test_simple_grid2d(self):
        compiled = cuda.jit("void(int32[:,::1])")(simple_grid2d)
        ntid = (4, 3)
        nctaid = (5, 6)
        shape = (ntid[0] * nctaid[0], ntid[1] * nctaid[1])
        ary = np.empty(shape, dtype=np.int32)
        exp = ary.copy()
        compiled[nctaid, ntid](ary)

        for i in range(ary.shape[0]):
            for j in range(ary.shape[1]):
                exp[i, j] = i + j

        self.assertTrue(np.alltrue(ary == exp))
//  [python]
def test_simple_grid2d(self):
        compiled = cuda.jit("void(int32[:,::1])")(simple_grid2d)
        ntid = (4, 3)
        nctaid = (5, 6)
        shape = (ntid[0] * nctaid[0], ntid[1] * nctaid[1])
        ary = np.empty(shape, dtype=np.int32)
        exp = ary.copy()
        compiled[nctaid, ntid](ary)

        for i in range(ary.shape[0]):
            for j in range(ary.shape[1]):
                exp[i, j] = i + j

        self.assertTrue(np.all(ary == exp))
//  [python]
def test_3dgrid_2(self):
        @cuda.jit
        def foo(out):
            x, y, z = cuda.grid(3)
            a, b, c = cuda.gridsize(3)
            grid_is_right = (
                x == cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x and
                y == cuda.threadIdx.y + cuda.blockIdx.y * cuda.blockDim.y and
                z == cuda.threadIdx.z + cuda.blockIdx.z * cuda.blockDim.z
            )
            gridsize_is_right = (a == cuda.blockDim.x * cuda.gridDim.x and
                                 b == cuda.blockDim.y * cuda.gridDim.y and
                                 c == cuda.blockDim.z * cuda.gridDim.z)
            out[x, y, z] = grid_is_right and gridsize_is_right

        x, y, z = (4 * 3, 3 * 2, 2 * 4)
        arr = np.zeros((x * y * z), dtype=np.bool_).reshape(x, y, z)
        foo[(4, 3, 2), (3, 2, 4)](arr)

        self.assertTrue(arr.all())
//  [python]
def test_3dgrid_2(self):
        @cuda.jit
        def foo(out):
            x, y, z = cuda.grid(3)
            a, b, c = cuda.gridsize(3)
            grid_is_right = (
                x == cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x and
                y == cuda.threadIdx.y + cuda.blockIdx.y * cuda.blockDim.y and
                z == cuda.threadIdx.z + cuda.blockIdx.z * cuda.blockDim.z
            )
            gridsize_is_right = (a == cuda.blockDim.x * cuda.gridDim.x and
                                 b == cuda.blockDim.y * cuda.gridDim.y and
                                 c == cuda.blockDim.z * cuda.gridDim.z)
            out[x, y, z] = grid_is_right and gridsize_is_right

        x, y, z = (4 * 3, 3 * 2, 2 * 4)
        arr = np.zeros((x * y * z), dtype=np.bool_).reshape(x, y, z)
        foo[(4, 3, 2), (3, 2, 4)](arr)

        self.assertTrue(np.all(arr))
//  [python]
def test_beam_search_smallest():
    a = numpy.array([[3, 6, 4], [1, 2, 7]])
    ind, mins = BeamSearch._smallest(a, 2)
    assert n.all(n.array(ind) == n.array([[1, 1], [0, 1]]))
    assert n.all(mins == [1, 2])
//  [python]
def test_beam_search_smallest():
    a = numpy.array([[3, 6, 4], [1, 2, 7]])
    ind, mins = BeamSearch._smallest(a, 2)
    assert numpy.all(numpy.array(ind) == numpy.array([[1, 1], [0, 1]]))
    assert numpy.all(mins == [1, 2])
//  [python]
def __eq__(self, other):
        if isinstance(other, Set):
            if not isinstance(other, STLSet):
                other = STLSet(other)
        else:
            return False

        if len(self._keys) != len(other._keys):
            return False

        keys_same = self._keys == other._keys
        if isinstance(keys_same, bool):
            return keys_same
        else:
            return numpy.all(keys_same)
//  [python]
def demo_in_val(self, demo_idx):
    return (self.split_by_demo and not self.episode_train_split[demo_idx]
            or (not self.split_by_demo
                and not n.all(self.episode_train_split[demo_idx])))
//  [python]
def demo_in_val(self, demo_idx):
    return (self.split_by_demo and not self.episode_train_split[demo_idx]
            or (not self.split_by_demo
                and not np.all(self.episode_train_split[demo_idx])))
//  [python]
def objective_function(self, fps, *args):
        """
        Function to minimize.

        Parameters
        ----------
        fps : list
            parameters returned by the fitter
        args : list
            [model, [weights], [input coordinates]]

        """
        model = args[0]
        weights = args[1]
        fitter_to_model_params(model, fps, self._use_min_max_bounds)
        meas = args[-1]

        if weights is None:
            value = np.ravel(model(*args[2:-1]) - meas)
        else:
            value = np.ravel(weights * (model(*args[2:-1]) - meas))

        if not np.alltrue(np.isfinite(value)):
            raise NonFiniteValueError(
                "Objective function has encountered a non-finite value, "
                "this will cause the fit to fail!\n"
                "Please remove non-finite values from your input data before "
                "fitting to avoid this error."
            )

        return value
//  [python]
def objective_function(self, fps, *args):
        """
        Function to minimize.

        Parameters
        ----------
        fps : list
            parameters returned by the fitter
        args : list
            [model, [weights], [input coordinates]]

        """
        model = args[0]
        weights = args[1]
        fitter_to_model_params(model, fps, self._use_min_max_bounds)
        meas = args[-1]

        if weights is None:
            value = np.ravel(model(*args[2:-1]) - meas)
        else:
            value = np.ravel(weights * (model(*args[2:-1]) - meas))

        if not np.all(np.isfinite(value)):
            raise NonFiniteValueError(
                "Objective function has encountered a non-finite value, "
                "this will cause the fit to fail!\n"
                "Please remove non-finite values from your input data before "
                "fitting to avoid this error."
            )

        return value
//  [python]
def _filter_non_finite(self, x, y, z=None, weights=None):
        """
        Filter out non-finite values in x, y, z.

        Returns
        -------
        x, y, z : ndarrays
            x, y, and z with non-finite values filtered out.
        """
        MESSAGE = "Non-Finite input data has been removed by the fitter."

        mask = np.ones_like(x, dtype=bool) if weights is None else np.isfinite(weights)
        mask &= np.isfinite(y) if z is None else np.isfinite(z)

        if not np.all(mask):
            warnings.warn(MESSAGE, AstropyUserWarning)

        return (
            x[mask],
            y[mask],
            None if z is None else z[mask],
            None if weights is None else weights[mask],
        )
//  [python]
def average_forward_solutions(fwds, weights=None, verbose=None):
    """Average forward solutions.

    Parameters
    ----------
    fwds : list of Forward
        Forward solutions to average. Each entry (dict) should be a
        forward solution.
    weights : array | None
        Weights to apply to each forward solution in averaging. If None,
        forward solutions will be equally weighted. Weights must be
        non-negative, and will be adjusted to sum to one.
    %(verbose)s

    Returns
    -------
    fwd : Forward
        The averaged forward solution.
    """
    # check for fwds being a list
    _validate_type(fwds, list, "fwds")
    if not len(fwds) > 0:
        raise ValueError("fwds must not be empty")

    # check weights
    if weights is None:
        weights = np.ones(len(fwds))
    weights = np.asanyarray(weights)  # in case it's a list, convert it
    if not np.all(weights >= 0):
        raise ValueError("weights must be non-negative")
    if not len(weights) == len(fwds):
        raise ValueError("weights must be None or the same length as fwds")
    w_sum = np.sum(weights)
    if not w_sum > 0:
        raise ValueError("weights cannot all be zero")
    weights /= w_sum

    # check our forward solutions
    for fwd in fwds:
        # check to make sure it's a forward solution
        _validate_type(fwd, dict, "each entry in fwds", "dict")
        # check to make sure the dict is actually a fwd
        check_keys = [
            "info",
            "sol_grad",
            "nchan",
            "src",
            "source_nn",
            "sol",
            "source_rr",
            "source_ori",
            "surf_ori",
            "coord_frame",
            "mri_head_t",
            "nsource",
        ]
        if not all(key in fwd for key in check_keys):
            raise KeyError(
                "forward solution dict does not have all standard "
                "entries, cannot compute average."
            )

    # check forward solution compatibility
    if any(
        fwd["sol"][k] != fwds[0]["sol"][k] for fwd in fwds[1:] for k in ["nrow", "ncol"]
    ):
        raise ValueError("Forward solutions have incompatible dimensions")
    if any(
        fwd[k] != fwds[0][k]
        for fwd in fwds[1:]
        for k in ["source_ori", "surf_ori", "coord_frame"]
    ):
        raise ValueError("Forward solutions have incompatible orientations")

    # actually average them (solutions and gradients)
    fwd_ave = deepcopy(fwds[0])
    fwd_ave["sol"]["data"] *= weights[0]
    fwd_ave["_orig_sol"] *= weights[0]
    for fwd, w in zip(fwds[1:], weights[1:]):
        fwd_ave["sol"]["data"] += w * fwd["sol"]["data"]
        fwd_ave["_orig_sol"] += w * fwd["_orig_sol"]
    if fwd_ave["sol_grad"] is not None:
        fwd_ave["sol_grad"]["data"] *= weights[0]
        fwd_ave["_orig_sol_grad"] *= weights[0]
        for fwd, w in zip(fwds[1:], weights[1:]):
            fwd_ave["sol_grad"]["data"] += w * fwd["sol_grad"]["data"]
            fwd_ave["_orig_sol_grad"] += w * fwd["_orig_sol_grad"]
    return fwd_ave
//  [python]
def test_reduce_imperative():
    for backend in collect_test_backends(symbolic=False, layers=True):
        print("Test layer for ", backend.framework_name)
        for reduction in REDUCTIONS:
            for pattern, axes_lengths, input_shape, wrong_shapes in reduction_patterns:
                print(backend, reduction, pattern, axes_lengths, input_shape, wrong_shapes)
                x = numpy.arange(1, 1 + numpy.prod(input_shape), dtype="float32").reshape(input_shape)
                x /= x.mean()
                result_numpy = reduce(x, pattern, reduction, **axes_lengths)
                layer = backend.layers().Reduce(pattern, reduction, **axes_lengths)
                for shape in wrong_shapes:
                    try:
                        layer(backend.from_numpy(numpy.zeros(shape, dtype="float32")))
                    except BaseException:
                        pass
                    else:
                        raise AssertionError("Failure expected")

                # simple pickling / unpickling
                layer2 = pickle.loads(pickle.dumps(layer))
                result1 = backend.to_numpy(layer(backend.from_numpy(x)))
                result2 = backend.to_numpy(layer2(backend.from_numpy(x)))
                assert numpy.allclose(result_numpy, result1)
                assert numpy.allclose(result1, result2)

                just_sum = backend.layers().Reduce("...->", reduction="sum")

                variable = backend.from_numpy(x)
                result = just_sum(layer(variable))

                result.backward()
                grad = backend.to_numpy(variable.grad)
                if reduction == "sum":
                    assert numpy.allclose(grad, 1)
                if reduction == "mean":
                    assert numpy.allclose(grad, grad.min())
                if reduction in ["max", "min"]:
                    assert numpy.all(numpy.in1d(grad, [0, 1]))
                    assert numpy.sum(grad) > 0.5
//  [python]
def testQintDtype(self):

    @def_function.function(autograph=False)
    def f():
      return math_ops.cast(
          array_ops.ones([2, 3], dtype=dtypes_lib.quint8), dtypes_lib.int32)

    value = self.evaluate(f())
    self.assertTrue(np.all(value))
//  [python]
def test_masked(image, measurements, module, objects, workspace):
    """Make sure we can process a completely masked image

    Regression test of IMG-971
    """
    image.pixel_data = numpy.zeros((10, 10))

    image.mask = numpy.zeros((10, 10), bool)

    objects.segmented = numpy.ones((10, 10), int)

    module.run(workspace)

    for meas_name in cellprofiler.modules.measureobjectintensity.ALL_MEASUREMENTS:
        feature_name = "%s_%s_%s" % (
            cellprofiler.modules.measureobjectintensity.INTENSITY,
            meas_name,
            "MyImage",
        )

        data = measurements.get_current_measurement("MyObjects", feature_name)

        assert numpy.product(data.shape) == 1

        assert n.all(numpy.isnan(data) | (data == 0))

    assert_features_and_columns_match(measurements, module)
//  [python]
def test_masked(image, measurements, module, objects, workspace):
    """Make sure we can process a completely masked image

    Regression test of IMG-971
    """
    image.pixel_data = numpy.zeros((10, 10))

    image.mask = numpy.zeros((10, 10), bool)

    objects.segmented = numpy.ones((10, 10), int)

    module.run(workspace)

    for meas_name in cellprofiler.modules.measureobjectintensity.ALL_MEASUREMENTS:
        feature_name = "%s_%s_%s" % (
            cellprofiler.modules.measureobjectintensity.INTENSITY,
            meas_name,
            "MyImage",
        )

        data = measurements.get_current_measurement("MyObjects", feature_name)

        assert numpy.product(data.shape) == 1

        assert numpy.all(numpy.isnan(data) | (data == 0))

    assert_features_and_columns_match(measurements, module)
//  [python]
def solve_fully_constraints(c: numpy.ndarray, A: numpy.ndarray, b: numpy.ndarray) -> Optional[SolverOutput]:
    """
    This solves a fully constrained linear system by directly solving the linear system. This is NOT complete!

    :param c: Column Vector
    :param A: Constraint LHS matrix
    :param b: Constraint RHS matrix
    :return: A SolverOutput Object
    """
    x = numpy.linalg.solve(A, b)
    dual = numpy.linalg.solve(A.T, -c)
    num_vars = A.shape[0]

    sol = SolverOutput(sol=x, obj=c.T @ x, slack=numpy.zeros(num_vars),
                       active_set=numpy.array(list(range(num_vars))), dual=dual)

    # check if the system agrees with the equality constraints

    if numpy.all(A @ sol.sol - b > -10 ** 8):
        return sol
    else:
        return None
//  [python]
def _populate_embeddings(self, initial_embeddings):
    """Modifies stored Users and Movies with learned vectors."""

    for movie_ in self.get_movies():
      movie_.movie_vec = initial_embeddings.movies[movie_.doc_id()]
      if len(movie_.movie_vec) <= len(GENRES):
        raise ValueError('The embeddings must include genre dimensions.')
      if not np.all(
          np.array_equiv(movie_.movie_vec[-len(GENRES):], movie_.genre_vec)):
        raise ValueError('Embedding dims for genre do not match genres!')
    for user_ in self.get_users():
      user_.topic_affinity = np.copy(initial_embeddings.users[user_.user_id])
      # Since users' topic affinities can change over time, store the initial
      # value as well.
      user_.initial_topic_affinity = np.copy(
          initial_embeddings.users[user_.user_id])
//  [python]
def _set_fixed(self, param, index):
        self._ensure_fixes()
        offset = self._offset_for(param)
        self._fixes_[index+offset] = FIXED
        if n.all(self._fixes_): self._fixes_ = None
//  [python]
def _set_fixed(self, param, index):
        self._ensure_fixes()
        offset = self._offset_for(param)
        self._fixes_[index+offset] = FIXED
        if np.all(self._fixes_): self._fixes_ = None
//  [python]
def is_O3(matrix, atol=None):
    """Check whether a matrix is in the length-preserving group O(3).

    Parameters
    ----------
    matrix : (..., N, N) array-like
        Must have attribute ``.shape`` and method ``.swapaxes()`` and not error
        when using `~numpy.isclose`.
    atol : float, optional
        The allowed absolute difference.
        If `None` it defaults to 1e-15 or 5 * epsilon of the matrix's dtype, if floating.

        .. versionadded:: 5.3

    Returns
    -------
    is_o3 : bool or array of bool
        If the matrix has more than two axes, the O(3) check is performed on
        slices along the last two axes -- (M, N, N) => (M, ) bool array.

    Notes
    -----
    The orthogonal group O(3) preserves lengths, but is not guaranteed to keep
    orientations. Rotations and reflections are in this group.
    For more information, see https://en.wikipedia.org/wiki/Orthogonal_group
    """
    # matrix is in O(3) (rotations, proper and improper).
    I = np.identity(matrix.shape[-1])
    if atol is None:
        if np.issubdtype(matrix.dtype, np.floating):
            atol = np.finfo(matrix.dtype).eps * 5
        else:
            atol = 1e-15

    is_o3 = n.all(
        np.isclose(matrix @ matrix.swapaxes(-2, -1), I, atol=atol), axis=(-2, -1)
    )

    return is_o3
//  [python]
def is_O3(matrix, atol=None):
    """Check whether a matrix is in the length-preserving group O(3).

    Parameters
    ----------
    matrix : (..., N, N) array-like
        Must have attribute ``.shape`` and method ``.swapaxes()`` and not error
        when using `~numpy.isclose`.
    atol : float, optional
        The allowed absolute difference.
        If `None` it defaults to 1e-15 or 5 * epsilon of the matrix's dtype, if floating.

        .. versionadded:: 5.3

    Returns
    -------
    is_o3 : bool or array of bool
        If the matrix has more than two axes, the O(3) check is performed on
        slices along the last two axes -- (M, N, N) => (M, ) bool array.

    Notes
    -----
    The orthogonal group O(3) preserves lengths, but is not guaranteed to keep
    orientations. Rotations and reflections are in this group.
    For more information, see https://en.wikipedia.org/wiki/Orthogonal_group
    """
    # matrix is in O(3) (rotations, proper and improper).
    I = np.identity(matrix.shape[-1])
    if atol is None:
        if np.issubdtype(matrix.dtype, np.floating):
            atol = np.finfo(matrix.dtype).eps * 5
        else:
            atol = 1e-15

    is_o3 = np.all(
        np.isclose(matrix @ matrix.swapaxes(-2, -1), I, atol=atol), axis=(-2, -1)
    )

    return is_o3
//  [python]
def _set_unfixed(self, param, index):
        self._ensure_fixes()
        offset = self._offset_for(param)
        self._fixes_[index+offset] = UNFIXED
        if n.all(self._fixes_): self._fixes_ = None
//  [python]
def _set_unfixed(self, param, index):
        self._ensure_fixes()
        offset = self._offset_for(param)
        self._fixes_[index+offset] = UNFIXED
        if np.all(self._fixes_): self._fixes_ = None
//  [python]
def _perform_ecf_func_fitting(self):
        num_rows = self.sicd.ImageData.NumRows
        num_cols = self.sicd.ImageData.NumCols

        row_array = numpy.linspace(0, num_rows-1, self._row_samples)
        col_array = numpy.linspace(0, num_cols-1, self._col_samples)
        hae_array = self.reference_hae + numpy.linspace(
            -self._alt_span, self._alt_span, self._alt_samples)

        row_col_grid = numpy.empty((row_array.size, col_array.size, 2), dtype='float64')
        row_col_grid[:, :, 1], row_col_grid[:, :, 0] = numpy.meshgrid(col_array, row_array)

        ECF_data = numpy.empty((row_array.size, col_array.size, hae_array.size, 3))
        for i, hae0 in enumerate(hae_array):
            ECF_data[:, :, i, :] = self.sicd.project_image_to_ground(row_col_grid, projection_type='HAE', hae0=hae0)

        if not numpy.alltrue(numpy.isfinite(ECF_data)):
            raise SarpyRatPolyError(
                'NaN values are encountered when projecting across the image area,\n\t'
                'this SICD is not a good candidate for projection using rational polynomials')
        row_func = get_rational_poly_3d(
            ECF_data[:, :, :, 0].flatten(), ECF_data[:, :, :, 1].flatten(), ECF_data[:, :, :, 2].flatten(),
            numpy.stack([row_col_grid[:, :, 0] for _ in range(self._alt_samples)], axis=2).flatten(), order=3)
        col_func = get_rational_poly_3d(
            ECF_data[:, :, :, 0].flatten(), ECF_data[:, :, :, 1].flatten(), ECF_data[:, :, :, 2].flatten(),
            numpy.stack([row_col_grid[:, :, 1] for _ in range(self._alt_samples)], axis=2).flatten(), order=3)
        self._ecf_to_pixel_func = CombinedRationalPolynomial(row_func, col_func)
//  [python]
def _perform_ecf_func_fitting(self):
        num_rows = self.sicd.ImageData.NumRows
        num_cols = self.sicd.ImageData.NumCols

        row_array = numpy.linspace(0, num_rows-1, self._row_samples)
        col_array = numpy.linspace(0, num_cols-1, self._col_samples)
        hae_array = self.reference_hae + numpy.linspace(
            -self._alt_span, self._alt_span, self._alt_samples)

        row_col_grid = numpy.empty((row_array.size, col_array.size, 2), dtype='float64')
        row_col_grid[:, :, 1], row_col_grid[:, :, 0] = numpy.meshgrid(col_array, row_array)

        ECF_data = numpy.empty((row_array.size, col_array.size, hae_array.size, 3))
        for i, hae0 in enumerate(hae_array):
            ECF_data[:, :, i, :] = self.sicd.project_image_to_ground(row_col_grid, projection_type='HAE', hae0=hae0)

        if not numpy.all(numpy.isfinite(ECF_data)):
            raise SarpyRatPolyError(
                'NaN values are encountered when projecting across the image area,\n\t'
                'this SICD is not a good candidate for projection using rational polynomials')
        row_func = get_rational_poly_3d(
            ECF_data[:, :, :, 0].flatten(), ECF_data[:, :, :, 1].flatten(), ECF_data[:, :, :, 2].flatten(),
            numpy.stack([row_col_grid[:, :, 0] for _ in range(self._alt_samples)], axis=2).flatten(), order=3)
        col_func = get_rational_poly_3d(
            ECF_data[:, :, :, 0].flatten(), ECF_data[:, :, :, 1].flatten(), ECF_data[:, :, :, 2].flatten(),
            numpy.stack([row_col_grid[:, :, 1] for _ in range(self._alt_samples)], axis=2).flatten(), order=3)
        self._ecf_to_pixel_func = CombinedRationalPolynomial(row_func, col_func)
//  [python]
def alignment(X,D):
    N_fft=D.shape[1]
    X_dft = numpy.fft.fft(X, N_fft, 0)

    X_aligned_padded = numpy.fft.ifft((1 / D.T) * X_dft,None,0)

    signal_length = X.shape[0]

    if N_fft > signal_length:
        X_aligned = X_aligned_padded[0 : signal_length, :]
    else:
        X_aligned = X_aligned_padded;


    if numpy.alltrue(numpy.isreal(X)):
        X_aligned = numpy.real(X_aligned)
    return X_aligned
//  [python]
def alignment(X,D):
    N_fft=D.shape[1]
    X_dft = numpy.fft.fft(X, N_fft, 0)

    X_aligned_padded = numpy.fft.ifft((1 / D.T) * X_dft,None,0)

    signal_length = X.shape[0]

    if N_fft > signal_length:
        X_aligned = X_aligned_padded[0 : signal_length, :]
    else:
        X_aligned = X_aligned_padded;


    if numpy.all(numpy.isreal(X)):
        X_aligned = numpy.real(X_aligned)
    return X_aligned
//  [python]
def __check_mapping(self, landmarks):
        """
        Checks whether the image, from which the supplied landmarks were extracted, can
        be transformed to the learned standard intensity space without loss of
        information.
        """
        sc_udiff = (
            numpy.asarray(self.__sc_umaxs)[1:] - numpy.asarray(self.__sc_umins)[:-1]
        )
        l_diff = numpy.asarray(landmarks)[1:] - numpy.asarray(landmarks)[:-1]
        return numpy.all(sc_udiff > numpy.asarray(l_diff))
//  [python]
def are_numbers(arg):
        """
        Checks whether all elements in a sequence are valid numbers.
        """
        return n.all([IntensityRangeStandardization.is_number(x) for x in arg])
//  [python]
def are_numbers(arg):
        """
        Checks whether all elements in a sequence are valid numbers.
        """
        return numpy.all([IntensityRangeStandardization.is_number(x) for x in arg])
//  [python]
def are_in_interval(s, l, r, border="included"):
        """
        Checks whether all number in the sequence s lie inside the interval formed by
        l and r.
        """
        return n.all(
            [IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s]
        )
//  [python]
def are_in_interval(s, l, r, border="included"):
        """
        Checks whether all number in the sequence s lie inside the interval formed by
        l and r.
        """
        return numpy.all(
            [IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s]
        )
//  [python]
def is_cartesian(self, atol: float = 0.001) -> bool:
        """
        Checks if cell vectors a,b,c are multiples of the cartesian axis vectors (x, y, z)

        Parameters
        -----------
        atol: float, optional
            the threshold above which an off diagonal term will be considered non-zero.
        """
        # Get the off diagonal terms of the cell
        off_diagonal = self.cell.ravel()[:-1].reshape(2, 4)[:, 1:]

        # Check if all are bolew the threshold tolerance
        return n.all(n.abs(off_diagonal) <= atol)
//  [python]
def is_cartesian(self, atol: float = 0.001) -> bool:
        """
        Checks if cell vectors a,b,c are multiples of the cartesian axis vectors (x, y, z)

        Parameters
        -----------
        atol: float, optional
            the threshold above which an off diagonal term will be considered non-zero.
        """
        # Get the off diagonal terms of the cell
        off_diagonal = self.cell.ravel()[:-1].reshape(2, 4)[:, 1:]

        # Check if all are bolew the threshold tolerance
        return np.all(np.abs(off_diagonal) <= atol)
//  [python]
def test_combine_series(
        self, float_frame, mixed_float_frame, mixed_int_frame, datetime_frame
    ):

        # Series
        series = float_frame.xs(float_frame.index[0])

        added = float_frame + series

        for key, s in added.items():
            tm.assert_series_equal(s, float_frame[key] + series[key])

        larger_series = series.to_dict()
        larger_series["E"] = 1
        larger_series = Series(larger_series)
        larger_added = float_frame + larger_series

        for key, s in float_frame.items():
            tm.assert_series_equal(larger_added[key], s + series[key])
        assert "E" in larger_added
        assert np.isnan(larger_added["E"]).all()

        # no upcast needed
        added = mixed_float_frame + series
        assert np.all(added.dtypes == series.dtype)

        # vs mix (upcast) as needed
        added = mixed_float_frame + series.astype("float32")
        _check_mixed_float(added, dtype={"C": None})
        added = mixed_float_frame + series.astype("float16")
        _check_mixed_float(added, dtype={"C": None})

        # FIXME: don't leave commented-out
        # these raise with numexpr.....as we are adding an int64 to an
        # uint64....weird vs int

        # added = mixed_int_frame + (100*series).astype('int64')
        # _check_mixed_int(added, dtype = {"A": 'int64', "B": 'float64', "C":
        # 'int64', "D": 'int64'})
        # added = mixed_int_frame + (100*series).astype('int32')
        # _check_mixed_int(added, dtype = {"A": 'int32', "B": 'float64', "C":
        # 'int32', "D": 'int64'})

        # TimeSeries
        ts = datetime_frame["A"]

        # 10890
        # we no longer allow auto timeseries broadcasting
        # and require explicit broadcasting
        added = datetime_frame.add(ts, axis="index")

        for key, col in datetime_frame.items():
            result = col + ts
            tm.assert_series_equal(added[key], result, check_names=False)
            assert added[key].name == key
            if col.name == ts.name:
                assert result.name == "A"
            else:
                assert result.name is None

        smaller_frame = datetime_frame[:-5]
        smaller_added = smaller_frame.add(ts, axis="index")

        tm.assert_index_equal(smaller_added.index, datetime_frame.index)

        smaller_ts = ts[:-5]
        smaller_added2 = datetime_frame.add(smaller_ts, axis="index")
        tm.assert_frame_equal(smaller_added, smaller_added2)

        # length 0, result is all-nan
        result = datetime_frame.add(ts[:0], axis="index")
        expected = DataFrame(
            np.nan, index=datetime_frame.index, columns=datetime_frame.columns
        )
        tm.assert_frame_equal(result, expected)

        # Frame is all-nan
        result = datetime_frame[:0].add(ts, axis="index")
        expected = DataFrame(
            np.nan, index=datetime_frame.index, columns=datetime_frame.columns
        )
        tm.assert_frame_equal(result, expected)

        # empty but with non-empty index
        frame = datetime_frame[:1].reindex(columns=[])
        result = frame.mul(ts, axis="index")
        assert len(result) == len(ts)
//  [python]
def test_sub_img_with_pad():
    A = np.ones((10, 10))
    A[:, 0] = 0
    A[0, :] = 0
    B = sub_img_with_pad(A, -2, -2, 2, 2)
    print(B)
    assert n.all(B[:, :2] == 0)
    assert n.all(B[:2, :] == 0)
    assert n.all(B[3:, 3:] == 1)
//  [python]
def test_sub_img_with_pad():
    A = np.ones((10, 10))
    A[:, 0] = 0
    A[0, :] = 0
    B = sub_img_with_pad(A, -2, -2, 2, 2)
    print(B)
    assert np.all(B[:, :2] == 0)
    assert np.all(B[:2, :] == 0)
    assert np.all(B[3:, 3:] == 1)
//  [python]
def checkOrtho(A):
    product = A.T.dot(A)
    #print(A)
    np.fill_diagonal(product,0)
    #print(product)
    return (n.all(n.abs(product)<1e-10))
//  [python]
def checkOrtho(A):
    product = A.T.dot(A)
    #print(A)
    np.fill_diagonal(product,0)
    #print(product)
    return (np.all(np.abs(product)<1e-10))
//  [python]
def test_sparse_nd_setitem():
    def check_sparse_nd_setitem(stype, shape, dst):
        x = mx.nd.zeros(shape=shape, stype=stype)
        x[:] = dst
        dst_nd = mx.nd.array(dst) if isinstance(dst, (np.ndarray, np.generic)) else dst
        assert n.all(x.asnumpy() == dst_nd.asnumpy() if isinstance(dst_nd, NDArray) else dst)

    shape = rand_shape_2d()
    for stype in ['row_sparse', 'csr']:
        # ndarray assignment
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, 'default'))
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, stype))
        # numpy assignment
        check_sparse_nd_setitem(stype, shape, np.ones(shape))
    # scalar assigned to row_sparse NDArray
    check_sparse_nd_setitem('row_sparse', shape, 2)
//  [python]
def test_sparse_nd_setitem():
    def check_sparse_nd_setitem(stype, shape, dst):
        x = mx.nd.zeros(shape=shape, stype=stype)
        x[:] = dst
        dst_nd = mx.nd.array(dst) if isinstance(dst, (np.ndarray, np.generic)) else dst
        assert np.all(x.asnumpy() == dst_nd.asnumpy() if isinstance(dst_nd, NDArray) else dst)

    shape = rand_shape_2d()
    for stype in ['row_sparse', 'csr']:
        # ndarray assignment
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, 'default'))
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, stype))
        # numpy assignment
        check_sparse_nd_setitem(stype, shape, np.ones(shape))
    # scalar assigned to row_sparse NDArray
    check_sparse_nd_setitem('row_sparse', shape, 2)
//  [python]
def valid(src,ll,d,piv):
    n = len(src)
    p=np.identity(n)
    for k in range(0,n):
        p = swaprow(p,k,piv[k])
    
    a = np.matmul(p,np.matmul(src,np.transpose(p)))
    t = np.matmul(ll,np.matmul(d,np.transpose(ll)))
    r = a - t
    r[abs(r)<1e-10]=0.0
    return(np.alltrue(r == 0.0))
//  [python]
def valid(src,ll,d,piv):
    n = len(src)
    p=np.identity(n)
    for k in range(0,n):
        p = swaprow(p,k,piv[k])
    
    a = np.matmul(p,np.matmul(src,np.transpose(p)))
    t = np.matmul(ll,np.matmul(d,np.transpose(ll)))
    r = a - t
    r[abs(r)<1e-10]=0.0
    return(np.all(r == 0.0))
//  [python]
def test_intersection_mask():
    r1 = (0, 0, 5, 5)
    r2 = (3, 3, 6, 6)
    mask1, mask2 = intersection_mask(r1, r2)
    assert n.all(mask1 == np.int32(
        A('0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0; 0 0 0 1 1; 0 0 0 1 1')))
    # print mask2
    # print np.int32(A('1 1 0 0 0 0; 1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0'))
    assert n.all(mask2 == np.int32(
        A('1 1 0 0 0 0; 1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0')))
//  [python]
def test_intersection_mask():
    r1 = (0, 0, 5, 5)
    r2 = (3, 3, 6, 6)
    mask1, mask2 = intersection_mask(r1, r2)
    assert np.all(mask1 == np.int32(
        A('0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0; 0 0 0 1 1; 0 0 0 1 1')))
    # print mask2
    # print np.int32(A('1 1 0 0 0 0; 1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0'))
    assert np.all(mask2 == np.int32(
        A('1 1 0 0 0 0; 1 1 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0')))
//  [python]
def test_boxslit():
    """
    Tests old vs. new bpm after adding `and_not` functionality.
    """
    bm = SlitTraceBitMask()
    v = numpy.array([10,0,2])

    desired_bpm = (v > 2) & (numpy.invert(bm.flagged(v, flag=bm.exclude_for_reducing)))

    new_bpm = bm.flagged(v, exclude='BOXSLIT', and_not=bm.exclude_for_reducing)

    assert n.all(new_bpm == desired_bpm)
//  [python]
def test_boxslit():
    """
    Tests old vs. new bpm after adding `and_not` functionality.
    """
    bm = SlitTraceBitMask()
    v = numpy.array([10,0,2])

    desired_bpm = (v > 2) & (numpy.invert(bm.flagged(v, flag=bm.exclude_for_reducing)))

    new_bpm = bm.flagged(v, exclude='BOXSLIT', and_not=bm.exclude_for_reducing)

    assert numpy.all(new_bpm == desired_bpm)
//  [python]
def test_do_not_shrink():
    """Test the option to not shrink the smaller objects"""
    primary_labels = numpy.zeros((10, 10), int)
    secondary_labels = numpy.zeros((10, 10), int)
    primary_labels[3:6, 4:7] = 1
    secondary_labels[2:7, 3:8] = 1
    expected_labels = numpy.zeros((10, 10), int)
    expected_labels[2:7, 3:8] = 1
    expected_labels[3:6, 4:7] = 0

    workspace = make_workspace(primary_labels, secondary_labels)
    module = workspace.module
    module.shrink_primary.value = False
    module.run(workspace)
    measurements = workspace.measurements

    output_objects = workspace.object_set.get_objects(TERTIARY)
    assert n.all(output_objects.segmented == expected_labels)
//  [python]
def test_do_not_shrink():
    """Test the option to not shrink the smaller objects"""
    primary_labels = numpy.zeros((10, 10), int)
    secondary_labels = numpy.zeros((10, 10), int)
    primary_labels[3:6, 4:7] = 1
    secondary_labels[2:7, 3:8] = 1
    expected_labels = numpy.zeros((10, 10), int)
    expected_labels[2:7, 3:8] = 1
    expected_labels[3:6, 4:7] = 0

    workspace = make_workspace(primary_labels, secondary_labels)
    module = workspace.module
    module.shrink_primary.value = False
    module.run(workspace)
    measurements = workspace.measurements

    output_objects = workspace.object_set.get_objects(TERTIARY)
    assert numpy.all(output_objects.segmented == expected_labels)
//  [python]
def test_opt_gpujoin_onlyajoin():
    # from a bug in normal sampling
    _a = numpy.asarray([[1, 2], [3, 4]], dtype='float32')
    _b = numpy.asarray([[5, 6, 7], [8, 9, 10]], dtype='float32')
    a = cuda.shared_constructor(_a)
    b = cuda.shared_constructor(_b)

    c = tensor.join(1, a, b)

    f = theano.function([], c, mode=mode_with_gpu)

    f()

    graph_nodes = f.maker.fgraph.toposort()

    assert isinstance(graph_nodes[-1].op, cuda.HostFromGpu)
    assert isinstance(graph_nodes[-2].op, cuda.GpuJoin)

    assert n.all(f() == numpy.concatenate([_a, _b], axis=1))

    # test mixed dtype
    _b = numpy.asarray([[5, 6, 7], [8, 9, 10]], dtype='float64')
    b = theano.tensor.constant(_b)

    c = tensor.join(1, a, b)

    f = theano.function([], c, mode=mode_with_gpu)

    f()

    graph_nodes = f.maker.fgraph.toposort()
    assert isinstance(graph_nodes[-1].op, theano.tensor.Join)

    assert n.all(f() == numpy.concatenate([_a, _b], axis=1))
//  [python]
def test_opt_gpujoin_onlyajoin():
    # from a bug in normal sampling
    _a = numpy.asarray([[1, 2], [3, 4]], dtype='float32')
    _b = numpy.asarray([[5, 6, 7], [8, 9, 10]], dtype='float32')
    a = cuda.shared_constructor(_a)
    b = cuda.shared_constructor(_b)

    c = tensor.join(1, a, b)

    f = theano.function([], c, mode=mode_with_gpu)

    f()

    graph_nodes = f.maker.fgraph.toposort()

    assert isinstance(graph_nodes[-1].op, cuda.HostFromGpu)
    assert isinstance(graph_nodes[-2].op, cuda.GpuJoin)

    assert numpy.all(f() == numpy.concatenate([_a, _b], axis=1))

    # test mixed dtype
    _b = numpy.asarray([[5, 6, 7], [8, 9, 10]], dtype='float64')
    b = theano.tensor.constant(_b)

    c = tensor.join(1, a, b)

    f = theano.function([], c, mode=mode_with_gpu)

    f()

    graph_nodes = f.maker.fgraph.toposort()
    assert isinstance(graph_nodes[-1].op, theano.tensor.Join)

    assert numpy.all(f() == numpy.concatenate([_a, _b], axis=1))
//  [python]
def test_zeros():
    """Test IdentifyTertiarySubregion on an empty image"""
    primary_labels = numpy.zeros((10, 10), int)
    secondary_labels = numpy.zeros((10, 10), int)
    workspace = make_workspace(primary_labels, secondary_labels)
    module = workspace.module
    module.run(workspace)
    measurements = workspace.measurements
    assert "Image" in measurements.get_object_names()
    count_feature = "Count_%s" % TERTIARY
    assert count_feature in measurements.get_feature_names("Image")
    value = measurements.get_current_measurement("Image", count_feature)
    assert numpy.product(value.shape) == 1
    assert value == 0
    assert TERTIARY in workspace.object_set.get_object_names()
    output_objects = workspace.object_set.get_objects(TERTIARY)
    assert n.all(output_objects.segmented == primary_labels)
    columns = module.get_measurement_columns(workspace.pipeline)
    for object_name in (
        "Image",
        PRIMARY,
        SECONDARY,
        TERTIARY,
    ):
        ocolumns = [x for x in columns if x[0] == object_name]
        features = measurements.get_feature_names(object_name)
        assert len(ocolumns) == len(features)
        assert all([column[1] in features for column in ocolumns])
//  [python]
def test_zeros():
    """Test IdentifyTertiarySubregion on an empty image"""
    primary_labels = numpy.zeros((10, 10), int)
    secondary_labels = numpy.zeros((10, 10), int)
    workspace = make_workspace(primary_labels, secondary_labels)
    module = workspace.module
    module.run(workspace)
    measurements = workspace.measurements
    assert "Image" in measurements.get_object_names()
    count_feature = "Count_%s" % TERTIARY
    assert count_feature in measurements.get_feature_names("Image")
    value = measurements.get_current_measurement("Image", count_feature)
    assert numpy.product(value.shape) == 1
    assert value == 0
    assert TERTIARY in workspace.object_set.get_object_names()
    output_objects = workspace.object_set.get_objects(TERTIARY)
    assert numpy.all(output_objects.segmented == primary_labels)
    columns = module.get_measurement_columns(workspace.pipeline)
    for object_name in (
        "Image",
        PRIMARY,
        SECONDARY,
        TERTIARY,
    ):
        ocolumns = [x for x in columns if x[0] == object_name]
        features = measurements.get_feature_names(object_name)
        assert len(ocolumns) == len(features)
        assert all([column[1] in features for column in ocolumns])
//  [python]
V1 = V + numpy.outer(u,u)
R1 = numpy.linalg.cholesky(V1).transpose()

#The following is equivalent to the above
R1_ = R.copy()
cholupdate(R1_,u.copy())
assert(n.all((R1 - R1_)**2 < 1e-16))
//  [python]
V1 = V + numpy.outer(u,u)
R1 = numpy.linalg.cholesky(V1).transpose()

#The following is equivalent to the above
R1_ = R.copy()
cholupdate(R1_,u.copy())
assert(numpy.all((R1 - R1_)**2 < 1e-16))
//  [python]
def test_pdf_logpdf(self):
        """ Checks that the probability density function (PDF) is within some
        tolerance of the natural logarithm of the PDF. This implementation is
        for one dimensional distributions.
        """

        # assign tolerance for element-wise ratio of logarithm of PDF
        tolerance = 0.01

        # step size to take in PDF evaluation
        step = 0.1

        # loop over distributions
        for dist in self.dists:
            if dist.name in EXCLUDE_DIST_NAMES:
                continue
            for param in dist.params:

                # get min and max
                hist_min = dist.bounds[param][0]
                hist_max = dist.bounds[param][1]

                # get the PDF and logarithm of the PDF from the distriubtion
                x = numpy.arange(hist_min, hist_max, step)
                pdf = numpy.array([dist.pdf(**{param : xx}) for xx in x])
                logpdf = numpy.array([dist.logpdf(**{param : xx}) for xx in x])

                # find the logarithm of the PDF
                pdf_log = numpy.log(pdf)

                # see if each element in ratio of these two logarithm of PDF
                # values are within the specified tolerance
                if not n.all(abs(1.0 - logpdf / pdf_log) < tolerance):
                    raise ValueError("The PDF and logarithm of the PDF "
                                     "functions for distribution {} "
                                     "do not agree".format(dist.name))