jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_adjacent(lhs, rhs, mask, delta, lhs_idx_expected, rhs_idx_expected):
    if mask is None:
        mask = np.uint64(0xFFFFFFFFFFFFFFFF)
    if delta == -1:
        rhs_idx, lhs_idx = adjacent(rhs, lhs, mask)
    else:
        lhs_idx, rhs_idx = adjacent(lhs, rhs, mask)
    assert np.all(lhs_idx == lhs_idx_expected)
    assert np.all(rhs_idx == rhs_idx_expected)
//  [python]
def __D_matrix_eigen_values_check(D):
        try:
            eigen_values = np.linalg.eigvals(D)
        except LinAlgError:
            return False
        return np.all(np.abs(eigen_values) < 1.01)
//  [python]
def __AR_is_stationary(ar_coefs):
        # cut out trailing and non-significant AR components
        significant_indices = np.where(np.abs(ar_coefs) > 1e-08)[0]
        if len(significant_indices) == 0:
            return True
        p = np.max(significant_indices) + 1
        significant_ar_coefs = ar_coefs[0:p]

        roots = np.polynomial.polynomial.polyroots(np.concatenate([[1], -significant_ar_coefs]))
        # Note that np.abs also works with complex numbers. It provides length of complex number
        # There should be no roots in the unit circle
        return n.all(np.abs(roots) > 1.0)
//  [python]
def __AR_is_stationary(ar_coefs):
        # cut out trailing and non-significant AR components
        significant_indices = np.where(np.abs(ar_coefs) > 1e-08)[0]
        if len(significant_indices) == 0:
            return True
        p = np.max(significant_indices) + 1
        significant_ar_coefs = ar_coefs[0:p]

        roots = np.polynomial.polynomial.polyroots(np.concatenate([[1], -significant_ar_coefs]))
        # Note that np.abs also works with complex numbers. It provides length of complex number
        # There should be no roots in the unit circle
        return np.all(np.abs(roots) > 1.0)
//  [python]
def __MA_is_invertible(ma_coefs):
        # cut out trailing and non-significant AR components
        significant_indices = np.where(np.abs(ma_coefs) > 1e-08)[0]
        if len(significant_indices) == 0:
            return True
        q = np.max(significant_indices) + 1
        significant_ma_coefs = ma_coefs[0:q]

        roots = np.polynomial.polynomial.polyroots(np.concatenate([[1], significant_ma_coefs]))
        # Note that np.abs also works with complex numbers. It provides length of complex number
        # There should be no roots in the unit circle
        return n.all(np.abs(roots) > 1.0)
//  [python]
def __MA_is_invertible(ma_coefs):
        # cut out trailing and non-significant AR components
        significant_indices = np.where(np.abs(ma_coefs) > 1e-08)[0]
        if len(significant_indices) == 0:
            return True
        q = np.max(significant_indices) + 1
        significant_ma_coefs = ma_coefs[0:q]

        roots = np.polynomial.polynomial.polyroots(np.concatenate([[1], significant_ma_coefs]))
        # Note that np.abs also works with complex numbers. It provides length of complex number
        # There should be no roots in the unit circle
        return np.all(np.abs(roots) > 1.0)
//  [python]
def make_global_use_all_patterns() -> Callable[[NDArray[np.bool_]], bool]:
    def global_use_all_patterns(wave: NDArray[np.bool_]) -> bool:
        """Returns true if at least one instance of each pattern is still possible."""
        return n.all(n.any(wave, axis=(1, 2))).item()

    return global_use_all_patterns
//  [python]
def make_global_use_all_patterns() -> Callable[[NDArray[np.bool_]], bool]:
    def global_use_all_patterns(wave: NDArray[np.bool_]) -> bool:
        """Returns true if at least one instance of each pattern is still possible."""
        return numpy.all(numpy.any(wave, axis=(1, 2))).item()

    return global_use_all_patterns
//  [python]
def PseudomorphicMaterial(sub, layer, relaxation=0, trans=None):
    """
    This function returns a material whos lattice is pseudomorphic on a
    particular substrate material. The two materials must have similar unit
    cell definitions for the algorithm to work correctly, i.e. it does not work
    for combiniations of materials with different lattice symmetry. It is also
    crucial that the layer object includes values for the elastic tensor.

    Parameters
    ----------
    sub :       Crystal
        substrate material
    layer :     Crystal
        bulk material of the layer, including its elasticity tensor
    relaxation : float, optional
        degree of relaxation 0: pseudomorphic, 1: relaxed (default: 0)
    trans :     Tranform
        Transformation which transforms lattice directions into a surface
        orientated coordinate frame (x, y inplane, z out of plane). If None a
        (001) surface geometry of a cubic material is assumed.

    Returns
    -------
    An instance of Crystal holding the new pseudomorphically
    strained material.

    Raises
    ------
    InputError
        If the layer material has no elastic parameters
    """
    def get_inplane(lat):
        """determine inplane lattice parameter"""
        return (math.VecNorm(lat.GetPoint(trans.inverse((1, 0, 0)))) +
                math.VecNorm(lat.GetPoint(trans.inverse((0, 1, 0))))) / 2.

    if not trans:
        trans = math.Transform(numpy.identity(3))

    if n.all(layer.cijkl == 0):
        raise InputError("'layer' argument needs elastic parameters")

    # calculate the strain
    asub = get_inplane(sub.lattice)
    abulk = get_inplane(layer.lattice)
    apar = asub + (abulk - asub) * relaxation
    epar = (apar - abulk) / abulk
    cT = trans(layer.cijkl, rank=4)

    eperp = -epar * (cT[1, 1, 2, 2] + cT[2, 2, 0, 0]) / (cT[2, 2, 2, 2])
    eps = trans.inverse(numpy.diag((epar, epar, eperp)), rank=2)
    if config.VERBOSITY >= config.INFO_ALL:
        print("XU.materials.PseudomorphicMaterial: applying strain (inplane, "
              f"perpendicular): {epar:.4g} {eperp:.4g}")

    # create the pseudomorphic material
    pmlatt = copy.deepcopy(layer.lattice)
    pmat = Crystal(layer.name, pmlatt, layer.cij)
    pmat.ApplyStrain(eps)
    return pmat
//  [python]
def PseudomorphicMaterial(sub, layer, relaxation=0, trans=None):
    """
    This function returns a material whos lattice is pseudomorphic on a
    particular substrate material. The two materials must have similar unit
    cell definitions for the algorithm to work correctly, i.e. it does not work
    for combiniations of materials with different lattice symmetry. It is also
    crucial that the layer object includes values for the elastic tensor.

    Parameters
    ----------
    sub :       Crystal
        substrate material
    layer :     Crystal
        bulk material of the layer, including its elasticity tensor
    relaxation : float, optional
        degree of relaxation 0: pseudomorphic, 1: relaxed (default: 0)
    trans :     Tranform
        Transformation which transforms lattice directions into a surface
        orientated coordinate frame (x, y inplane, z out of plane). If None a
        (001) surface geometry of a cubic material is assumed.

    Returns
    -------
    An instance of Crystal holding the new pseudomorphically
    strained material.

    Raises
    ------
    InputError
        If the layer material has no elastic parameters
    """
    def get_inplane(lat):
        """determine inplane lattice parameter"""
        return (math.VecNorm(lat.GetPoint(trans.inverse((1, 0, 0)))) +
                math.VecNorm(lat.GetPoint(trans.inverse((0, 1, 0))))) / 2.

    if not trans:
        trans = math.Transform(numpy.identity(3))

    if numpy.all(layer.cijkl == 0):
        raise InputError("'layer' argument needs elastic parameters")

    # calculate the strain
    asub = get_inplane(sub.lattice)
    abulk = get_inplane(layer.lattice)
    apar = asub + (abulk - asub) * relaxation
    epar = (apar - abulk) / abulk
    cT = trans(layer.cijkl, rank=4)

    eperp = -epar * (cT[1, 1, 2, 2] + cT[2, 2, 0, 0]) / (cT[2, 2, 2, 2])
    eps = trans.inverse(numpy.diag((epar, epar, eperp)), rank=2)
    if config.VERBOSITY >= config.INFO_ALL:
        print("XU.materials.PseudomorphicMaterial: applying strain (inplane, "
              f"perpendicular): {epar:.4g} {eperp:.4g}")

    # create the pseudomorphic material
    pmlatt = copy.deepcopy(layer.lattice)
    pmat = Crystal(layer.name, pmlatt, layer.cij)
    pmat.ApplyStrain(eps)
    return pmat
//  [python]
def test_two_objects_propagation_image():
    img = numpy.zeros((10, 20))
    img[2:7, 2:7] = 0.3
    img[2:7, 7:17] = 0.5
    labels = numpy.zeros((10, 20), int)
    labels[3:6, 3:6] = 1
    labels[3:6, 13:16] = 2
    workspace, module = make_workspace(img, labels)
    module.method.value = cellprofiler.modules.identifysecondaryobjects.M_PROPAGATION
    module.regularization_factor.value = 0  # propagate by image
    module.threshold.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.threshold.global_operation.value = cellprofiler.modules.threshold.TM_MANUAL
    module.threshold.manual_threshold.value = 0.2
    module.run(workspace)
    m = workspace.measurements
    assert OUTPUT_OBJECTS_NAME in m.get_object_names()
    assert "Image" in m.get_object_names()
    assert "Count_%s" % OUTPUT_OBJECTS_NAME in m.get_feature_names("Image")
    counts = m.get_current_measurement("Image", "Count_%s" % OUTPUT_OBJECTS_NAME)
    assert numpy.product(counts.shape) == 1
    assert counts == 2
    objects_out = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME)
    expected = numpy.zeros((10, 10), int)
    expected[2:7, 2:7] = 1
    expected[2:7, 7:17] = 2
    mask = numpy.ones((10, 10), bool)
    mask[:, 7:9] = False
    assert numpy.alltrue(objects_out.segmented[:10, :10][mask] == expected[mask])
//  [python]
def test_two_objects_propagation_image():
    img = numpy.zeros((10, 20))
    img[2:7, 2:7] = 0.3
    img[2:7, 7:17] = 0.5
    labels = numpy.zeros((10, 20), int)
    labels[3:6, 3:6] = 1
    labels[3:6, 13:16] = 2
    workspace, module = make_workspace(img, labels)
    module.method.value = cellprofiler.modules.identifysecondaryobjects.M_PROPAGATION
    module.regularization_factor.value = 0  # propagate by image
    module.threshold.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.threshold.global_operation.value = cellprofiler.modules.threshold.TM_MANUAL
    module.threshold.manual_threshold.value = 0.2
    module.run(workspace)
    m = workspace.measurements
    assert OUTPUT_OBJECTS_NAME in m.get_object_names()
    assert "Image" in m.get_object_names()
    assert "Count_%s" % OUTPUT_OBJECTS_NAME in m.get_feature_names("Image")
    counts = m.get_current_measurement("Image", "Count_%s" % OUTPUT_OBJECTS_NAME)
    assert numpy.product(counts.shape) == 1
    assert counts == 2
    objects_out = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME)
    expected = numpy.zeros((10, 10), int)
    expected[2:7, 2:7] = 1
    expected[2:7, 7:17] = 2
    mask = numpy.ones((10, 10), bool)
    mask[:, 7:9] = False
    assert numpy.all(objects_out.segmented[:10, :10][mask] == expected[mask])
//  [python]
def test_pickling(A):

    lat = kwant.lattice.square(norbs=2)
    syst = kwant.Builder()
    syst[(lat(i, j) for i in range(5) for j in range(5))] = random_onsite
    syst[lat.neighbors()] = random_hopping
    fsyst = syst.finalized()

    wf = np.random.rand(2 * len(fsyst.sites))

    def all_equal(it):
        it = iter(it)
        first = next(it)
        return all(n.all(first == rest) for rest in it)

    ops = [
        A(fsyst),
        A(fsyst, onsite=f_sigmay),
        A(fsyst, onsite=sigmaz),
        A(fsyst, sum=True),
        A(fsyst, onsite=sigmaz, sum=True),
        A(fsyst, onsite=f_sigmay, sum=True),
    ]
    ops += [op.bind() for op in ops]

    for op in ops:
        loaded_op = pickle.loads(pickle.dumps(op))
        assert n.all(op(wf) == loaded_op(wf))
//  [python]
def test_pickling(A):

    lat = kwant.lattice.square(norbs=2)
    syst = kwant.Builder()
    syst[(lat(i, j) for i in range(5) for j in range(5))] = random_onsite
    syst[lat.neighbors()] = random_hopping
    fsyst = syst.finalized()

    wf = np.random.rand(2 * len(fsyst.sites))

    def all_equal(it):
        it = iter(it)
        first = next(it)
        return all(np.all(first == rest) for rest in it)

    ops = [
        A(fsyst),
        A(fsyst, onsite=f_sigmay),
        A(fsyst, onsite=sigmaz),
        A(fsyst, sum=True),
        A(fsyst, onsite=sigmaz, sum=True),
        A(fsyst, onsite=f_sigmay, sum=True),
    ]
    ops += [op.bind() for op in ops]

    for op in ops:
        loaded_op = pickle.loads(pickle.dumps(op))
        assert np.all(op(wf) == loaded_op(wf))
//  [python]
def test_one_object_propagation():
    img = numpy.zeros((10, 10))
    img[2:7, 2:7] = 0.5
    labels = numpy.zeros((10, 10), int)
    labels[3:6, 3:6] = 1
    workspace, module = make_workspace(img, labels)
    module.method.value = cellprofiler.modules.identifysecondaryobjects.M_PROPAGATION
    module.threshold.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.threshold.global_operation.value = cellprofiler.modules.threshold.TM_MANUAL
    module.threshold.manual_threshold.value = 0.25
    module.run(workspace)
    m = workspace.measurements
    assert OUTPUT_OBJECTS_NAME in m.get_object_names()
    assert "Image" in m.get_object_names()
    assert "Count_%s" % OUTPUT_OBJECTS_NAME in m.get_feature_names("Image")
    objects_out = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME)
    counts = m.get_current_measurement("Image", "Count_%s" % OUTPUT_OBJECTS_NAME)
    assert numpy.product(counts.shape) == 1
    assert counts == 1
    expected = numpy.zeros((10, 10), int)
    expected[2:7, 2:7] = 1
    assert n.all(objects_out.segmented == expected)
    child_counts = m.get_current_measurement(
        INPUT_OBJECTS_NAME, "Children_%s_Count" % OUTPUT_OBJECTS_NAME
    )
    assert len(child_counts) == 1
    assert child_counts[0] == 1
    parents = m.get_current_measurement(
        OUTPUT_OBJECTS_NAME, "Parent_%s" % INPUT_OBJECTS_NAME
    )
    assert len(parents) == 1
    assert parents[0] == 1
//  [python]
def test_one_object_propagation():
    img = numpy.zeros((10, 10))
    img[2:7, 2:7] = 0.5
    labels = numpy.zeros((10, 10), int)
    labels[3:6, 3:6] = 1
    workspace, module = make_workspace(img, labels)
    module.method.value = cellprofiler.modules.identifysecondaryobjects.M_PROPAGATION
    module.threshold.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.threshold.global_operation.value = cellprofiler.modules.threshold.TM_MANUAL
    module.threshold.manual_threshold.value = 0.25
    module.run(workspace)
    m = workspace.measurements
    assert OUTPUT_OBJECTS_NAME in m.get_object_names()
    assert "Image" in m.get_object_names()
    assert "Count_%s" % OUTPUT_OBJECTS_NAME in m.get_feature_names("Image")
    objects_out = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME)
    counts = m.get_current_measurement("Image", "Count_%s" % OUTPUT_OBJECTS_NAME)
    assert numpy.product(counts.shape) == 1
    assert counts == 1
    expected = numpy.zeros((10, 10), int)
    expected[2:7, 2:7] = 1
    assert numpy.all(objects_out.segmented == expected)
    child_counts = m.get_current_measurement(
        INPUT_OBJECTS_NAME, "Children_%s_Count" % OUTPUT_OBJECTS_NAME
    )
    assert len(child_counts) == 1
    assert child_counts[0] == 1
    parents = m.get_current_measurement(
        OUTPUT_OBJECTS_NAME, "Parent_%s" % INPUT_OBJECTS_NAME
    )
    assert len(parents) == 1
    assert parents[0] == 1
//  [python]
def test_tocoo():
    syst = kwant.Builder()
    lat1 = kwant.lattice.chain(norbs=1)
    syst[lat1(0)] = syst[lat1(1)] = 0
    syst = syst.finalized()

    op = ops.Density(syst)
    assert isinstance(op.tocoo(), coo_matrix)

    # Constant and non-constant values.
    assert n.all(op.tocoo().toarray() == np.eye(2))
    op = ops.Density(syst, lambda site: 1)
    assert n.all(op.tocoo().toarray() == np.eye(2))

    # Correct treatment of where
    op = ops.Density(syst, where=[lat1(0)])
    assert n.all(op.tocoo().toarray() == [[1, 0], [0, 0]])

    # No accidental transpose.
    syst = kwant.Builder()
    lat2 = kwant.lattice.chain(norbs=2)
    syst[lat2(0)] = lambda site, p: np.eye(2)
    syst = syst.finalized()
    op = ops.Density(syst, [[1, 1], [0, 1]], check_hermiticity=False)
    assert n.all(op.tocoo().toarray() == [[1, 1], [0, 1]])

    op = ops.Density(syst, lambda site, p: [[1, 1], [0, 1]],
                     check_hermiticity=False)
    op = op.bind(params=dict(p=1))
    raises(ValueError, op.tocoo, [1])
//  [python]
def test_tocoo():
    syst = kwant.Builder()
    lat1 = kwant.lattice.chain(norbs=1)
    syst[lat1(0)] = syst[lat1(1)] = 0
    syst = syst.finalized()

    op = ops.Density(syst)
    assert isinstance(op.tocoo(), coo_matrix)

    # Constant and non-constant values.
    assert np.all(op.tocoo().toarray() == np.eye(2))
    op = ops.Density(syst, lambda site: 1)
    assert np.all(op.tocoo().toarray() == np.eye(2))

    # Correct treatment of where
    op = ops.Density(syst, where=[lat1(0)])
    assert np.all(op.tocoo().toarray() == [[1, 0], [0, 0]])

    # No accidental transpose.
    syst = kwant.Builder()
    lat2 = kwant.lattice.chain(norbs=2)
    syst[lat2(0)] = lambda site, p: np.eye(2)
    syst = syst.finalized()
    op = ops.Density(syst, [[1, 1], [0, 1]], check_hermiticity=False)
    assert np.all(op.tocoo().toarray() == [[1, 1], [0, 1]])

    op = ops.Density(syst, lambda site, p: [[1, 1], [0, 1]],
                     check_hermiticity=False)
    op = op.bind(params=dict(p=1))
    raises(ValueError, op.tocoo, [1])
//  [python]
def depthcut_90prime_alternative(ccds, annotated, n=6):
    s = numpy.lexsort([ccds.image_hdu, ccds.image_filename])
    ccds = ccds[s]
    sa = numpy.lexsort([annotated.image_hdu, annotated.image_filename])
    annotated = annotated[sa]
    if not numpy.alltrue((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    keep = numpy.zeros(len(ccds), dtype='bool')

    def int_noexception(x, sentinel=-1):
        try:
            y = int(x)
        except:
            return sentinel
        return y

    tileid = numpy.array([int_noexception(o, -1) for o in ccds.object],
                         dtype='i4')

    m = (ccds.ccd_cuts == 0) & (tileid >= 0)
    keep[s[m]] = keep_deepest_ccds(
        ccds.image_filename[m], tileid[m], ccds.filter[m],
        annotated.psfdepth[m], n=n)
    return keep
//  [python]
def depthcut_90prime_alternative(ccds, annotated, n=6):
    s = numpy.lexsort([ccds.image_hdu, ccds.image_filename])
    ccds = ccds[s]
    sa = numpy.lexsort([annotated.image_hdu, annotated.image_filename])
    annotated = annotated[sa]
    if not numpy.all((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    keep = numpy.zeros(len(ccds), dtype='bool')

    def int_noexception(x, sentinel=-1):
        try:
            y = int(x)
        except:
            return sentinel
        return y

    tileid = numpy.array([int_noexception(o, -1) for o in ccds.object],
                         dtype='i4')

    m = (ccds.ccd_cuts == 0) & (tileid >= 0)
    keep[s[m]] = keep_deepest_ccds(
        ccds.image_filename[m], tileid[m], ccds.filter[m],
        annotated.psfdepth[m], n=n)
    return keep
//  [python]
def plot_ellipsoid_3D(p, q, ax, n_points=100):
    """ Plot an ellipsoid in 3D

    Based on
    https://stackoverflow.com/questions/7819498/plotting-ellipsoid-with-matplotlib

    TODO: Untested!

    Parameters
    ----------
    p: 3x1 array[float]
        Center of the ellipsoid
    q: 3x3 array[float]
        Shape matrix of the ellipsoid
    ax: matplotlib.Axes object
        Ax on which to plot the ellipsoid

    Returns
    -------
    ax: matplotlib.Axes object
        The Ax containing the ellipsoid

    """

    assert np.shape(p) == (3, 1), "p needs to be a 3x1 vector"
    assert np.shape(q) == (3, 3), "q needs to be a spd 3x3 matrix"
    assert np.allclose(q, 0.5 * (q + q.T), "q needs to be spd")
    # transform to radius/center parametrization
    U, s, rotation = linalg.svd(q)
    assert np.all(s > 0), "q needs to be positive definite"
    radii = 1.0 / np.sqrt(s)

    # get x,y,z of sphere and transform
    u = np.linspace(0.0, 2.0 * np.pi, n_points)
    v = np.linspace(0.0, np.pi, n_points)
    x = radii[0] * np.outer(np.cos(u), np.sin(v))
    y = radii[1] * np.outer(np.sin(u), np.sin(v))
    z = radii[2] * np.outer(np.ones_like(u), np.cos(v))
    for i in range(len(x)):
        for j in range(len(x)):
            [x[i, j], y[i, j], z[i, j]] = np.dot([x[i, j], y[i, j], z[i, j]],
                                                 rotation) + center

    # plot the result
    ax.plot_wireframe(x, y, z, rstride=4, cstride=4, color='b', alpha=0.2)
    return ax
//  [python]
def repair_object_names(ccds, imlist, prefix='90prime/'):
    ccds = ccds.copy()
    imfilename = numpy.array([prefix+f for f in imlist.filename])
    s = numpy.argsort(imfilename)
    imlist = imlist[s]
    imfilename = imfilename[s]
    cobjectname = numpy.array([o.strip() for o in ccds.object])
    iobjectname = numpy.array([o.replace("'",'').strip()
                               for o in imlist.object])
    m = (cobjectname == '')
    cfilename = numpy.array([f.strip() for f in ccds.image_filename])
    ind = numpy.searchsorted(imfilename, cfilename)
    if not numpy.alltrue(imfilename[ind] == cfilename):
        raise AssertionError('some image file names not found in image list?')
    ccds.object[m] = iobjectname[ind[m]]
    return ccds
//  [python]
def repair_object_names(ccds, imlist, prefix='90prime/'):
    ccds = ccds.copy()
    imfilename = numpy.array([prefix+f for f in imlist.filename])
    s = numpy.argsort(imfilename)
    imlist = imlist[s]
    imfilename = imfilename[s]
    cobjectname = numpy.array([o.strip() for o in ccds.object])
    iobjectname = numpy.array([o.replace("'",'').strip()
                               for o in imlist.object])
    m = (cobjectname == '')
    cfilename = numpy.array([f.strip() for f in ccds.image_filename])
    ind = numpy.searchsorted(imfilename, cfilename)
    if not numpy.all(imfilename[ind] == cfilename):
        raise AssertionError('some image file names not found in image list?')
    ccds.object[m] = iobjectname[ind[m]]
    return ccds
//  [python]
def all(self, axis=None, keepdims=False):
        """Wrapper of `numpy.all`

        Parameters
        ----------
        axis : None or int or tuple of ints , optional
            Axis or axes to operate on, by default None
        keepdims : bool, optional
            If true, the axes along which the operation performed are left
            to size one, by default False

        Returns
        -------
        DTensor or bool
            Result of `all` operation as a DTensor or a boolean value.
        """
        return n.all(self._data, axis=axis, keepdims=keepdims)
//  [python]
def all(self, axis=None, keepdims=False):
        """Wrapper of `numpy.all`

        Parameters
        ----------
        axis : None or int or tuple of ints , optional
            Axis or axes to operate on, by default None
        keepdims : bool, optional
            If true, the axes along which the operation performed are left
            to size one, by default False

        Returns
        -------
        DTensor or bool
            Result of `all` operation as a DTensor or a boolean value.
        """
        return np.all(self._data, axis=axis, keepdims=keepdims)
//  [python]
def depthcut_mosaic(ccds, annotated, tilefile, n=2):
    if len(tilefile) == 0:
        raise ValueError('Mosaic depth cut requires a tile file.')
    # original proposal was something like take only 'MzLS'.
    # 2677 OBJECT Observation(s) in tile file.
    # 361 MOSAIC_XYZ_z observations in file list.  None in tile file.
    # 2015B-2001
    s = numpy.lexsort([ccds.image_hdu, ccds.image_filename])
    ccds = ccds[s]
    sa = numpy.lexsort([annotated.image_hdu, annotated.image_filename])
    annotated = annotated[sa]
    if not numpy.alltrue((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    keep = numpy.zeros(len(ccds), dtype='bool')
    m = ccds.ccd_cuts == 0
    keep[s[m]] = keep_deepest_tiles(ccds[m], annotated[m], tilefile, n=n)
    return keep
//  [python]
def depthcut_mosaic(ccds, annotated, tilefile, n=2):
    if len(tilefile) == 0:
        raise ValueError('Mosaic depth cut requires a tile file.')
    # original proposal was something like take only 'MzLS'.
    # 2677 OBJECT Observation(s) in tile file.
    # 361 MOSAIC_XYZ_z observations in file list.  None in tile file.
    # 2015B-2001
    s = numpy.lexsort([ccds.image_hdu, ccds.image_filename])
    ccds = ccds[s]
    sa = numpy.lexsort([annotated.image_hdu, annotated.image_filename])
    annotated = annotated[sa]
    if not numpy.all((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    keep = numpy.zeros(len(ccds), dtype='bool')
    m = ccds.ccd_cuts == 0
    keep[s[m]] = keep_deepest_tiles(ccds[m], annotated[m], tilefile, n=n)
    return keep
//  [python]
def long_lat_dist_decomposition(
    gt_vector: npt.NDArray[np.float64], est_vector: npt.NDArray[np.float64]
) -> Tuple[float, float]:
    """
    Longitudinal and lateral decomposition of est_vector - gt_vector.
    We define longitudinal direction as the direction of gt_vector. Lateral direction is defined as direction of
    cross product between longitudinal vector and vertical vector (longitudinal x vertical).
    :param gt_vector: <np.float: 2>. 2-dimensional ground truth vector.
    :param est_vector: <np.float: 2>. 2-dimensional ground estimated vector.
    :return: Longitudinal distance and lateral distance.
    """
    assert gt_vector.size == est_vector.size == 2, "Input vector should be 2-dimensional"
    # We specify this condition to handle when gt vector is zero.
    # We consider the error is solely longitudinal in this case.
    if n.all(gt_vector == 0):
        return np.linalg.norm(est_vector), 0  # type: ignore
    unit_long_vector = gt_vector / np.linalg.norm(gt_vector)
    dist_vector: npt.NDArray[np.float64] = est_vector - gt_vector
    long_dist = float(np.dot(unit_long_vector, dist_vector))
    lat_dist = np.linalg.norm(dist_vector - (long_dist * unit_long_vector))

    return long_dist, lat_dist
//  [python]
def long_lat_dist_decomposition(
    gt_vector: npt.NDArray[np.float64], est_vector: npt.NDArray[np.float64]
) -> Tuple[float, float]:
    """
    Longitudinal and lateral decomposition of est_vector - gt_vector.
    We define longitudinal direction as the direction of gt_vector. Lateral direction is defined as direction of
    cross product between longitudinal vector and vertical vector (longitudinal x vertical).
    :param gt_vector: <np.float: 2>. 2-dimensional ground truth vector.
    :param est_vector: <np.float: 2>. 2-dimensional ground estimated vector.
    :return: Longitudinal distance and lateral distance.
    """
    assert gt_vector.size == est_vector.size == 2, "Input vector should be 2-dimensional"
    # We specify this condition to handle when gt vector is zero.
    # We consider the error is solely longitudinal in this case.
    if np.all(gt_vector == 0):
        return np.linalg.norm(est_vector), 0  # type: ignore
    unit_long_vector = gt_vector / np.linalg.norm(gt_vector)
    dist_vector: npt.NDArray[np.float64] = est_vector - gt_vector
    long_dist = float(np.dot(unit_long_vector, dist_vector))
    lat_dist = np.linalg.norm(dist_vector - (long_dist * unit_long_vector))

    return long_dist, lat_dist
//  [python]
def all(self, axis=None, keepdims=False):
        """Wrapper of `numpy.all`

        Parameters
        ----------
        axis : None or int or tuple of ints, optional
            Axis or axes to operate on, by default None
        keepdims : bool, optional
            If true, the axes along which the operation performed are left
            to size one, by default False

        Returns
        -------
        STensor or bool
            Result of `all` operation as a STensor or a boolean value.
        """
        return n.all(self._data, axis=axis, keepdims=keepdims)
//  [python]
def all(self, axis=None, keepdims=False):
        """Wrapper of `numpy.all`

        Parameters
        ----------
        axis : None or int or tuple of ints, optional
            Axis or axes to operate on, by default None
        keepdims : bool, optional
            If true, the axes along which the operation performed are left
            to size one, by default False

        Returns
        -------
        STensor or bool
            Result of `all` operation as a STensor or a boolean value.
        """
        return np.all(self._data, axis=axis, keepdims=keepdims)
//  [python]
def depthcut_decam(ccds, annotated, tilefile):
    if len(tilefile) == 0:
        raise ValueError('DECam depth cut requires a tile file.')
    # need ccds & annotated ccds: former has ccd_cuts, latter has psfdepth
    if not n.all((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    # we will only keep exposures that:
    # - have no ccd_cuts
    # - are from a set of chosen propids, with good object names within those
    # propids
    # - match a tile
    # - are among the top two deepest exposures satisfying the above.
    keep = depthcut_propid_decam(ccds) & (ccds.ccd_cuts == 0)
    mdelve = numpy.array([(('DELVE' in s) or ('PALS' in s))
                          for s in ccds.object])
    mbyobject = numpy.ones(len(ccds), dtype='bool')

    for pp in pidlist_byobject:
        mbyobject |= (ccds.propid == pp) & ~mdelve
    m = ~(mdelve | mbyobject)
    # for LS-like surveys
    keep[m & keep] = keep_deepest_tiles(
        ccds[m & keep], annotated[m & keep], tilefile, n=2)
    # for surveys where we just do object name selection
    keep[mbyobject & keep] = keep_deepest_des(
        ccds[mbyobject & keep], annotated[mbyobject & keep])
    # for delve-like surveys with too many passes
    keep[mdelve & keep] = keep_deepest_delve(ccds[mdelve & keep],
                                             annotated[mdelve & keep])
    return keep
//  [python]
def depthcut_decam(ccds, annotated, tilefile):
    if len(tilefile) == 0:
        raise ValueError('DECam depth cut requires a tile file.')
    # need ccds & annotated ccds: former has ccd_cuts, latter has psfdepth
    if not numpy.all((ccds.image_hdu == annotated.image_hdu) &
                     (ccds.image_filename == annotated.image_filename)):
        raise ValueError('Inconsistent ccds & annotated ccds file?')
    # we will only keep exposures that:
    # - have no ccd_cuts
    # - are from a set of chosen propids, with good object names within those
    # propids
    # - match a tile
    # - are among the top two deepest exposures satisfying the above.
    keep = depthcut_propid_decam(ccds) & (ccds.ccd_cuts == 0)
    mdelve = numpy.array([(('DELVE' in s) or ('PALS' in s))
                          for s in ccds.object])
    mbyobject = numpy.ones(len(ccds), dtype='bool')

    for pp in pidlist_byobject:
        mbyobject |= (ccds.propid == pp) & ~mdelve
    m = ~(mdelve | mbyobject)
    # for LS-like surveys
    keep[m & keep] = keep_deepest_tiles(
        ccds[m & keep], annotated[m & keep], tilefile, n=2)
    # for surveys where we just do object name selection
    keep[mbyobject & keep] = keep_deepest_des(
        ccds[mbyobject & keep], annotated[mbyobject & keep])
    # for delve-like surveys with too many passes
    keep[mdelve & keep] = keep_deepest_delve(ccds[mdelve & keep],
                                             annotated[mdelve & keep])
    return keep
//  [python]
def is_binary_feature(trait_tbl):
    n_features = trait_tbl.shape[-1]
    b = np.zeros(n_features, dtype = int)
    freq_state = np.zeros(n_features, dtype = int)
    for i in range(n_features):
        if len(trait_tbl.shape) == 3:
            values, counts = np.unique(trait_tbl[:, :, i], return_counts=True)
        else:
            values, counts = np.unique(trait_tbl[:, i], return_counts=True)
        values_range = np.arange(np.min(values), np.max(values) + 1)
        b[i] = np.all(np.isin(values, values_range))
        freq_state[i] = values[np.argmax(counts)]
    b = b.astype(bool)
    return b, freq_state
//  [python]
def get_idx_maineffect(m, p, k, old_idx):
    out = old_idx
    if len(m) == len(p):
        if n.all(m == p):
            out = k
    return out
//  [python]
def get_idx_maineffect(m, p, k, old_idx):
    out = old_idx
    if len(m) == len(p):
        if np.all(m == p):
            out = k
    return out
//  [python]
def get_rates_summary(cond_rates):
    nrows_cond_rates = cond_rates.shape[0]
    rate_sum = np.zeros((nrows_cond_rates, 3))
    rate_sum[:] = np.nan
    rate_sum[:, 0] = np.mean(cond_rates, axis = 1)
    for i in range(nrows_cond_rates):
        rate_isnan = np.isnan(cond_rates[i, :])
        all_nan = rate_isnan.all()
        n_rates = len(cond_rates[i, ~rate_isnan])
        if not all_nan and n_rates > 1:
            rate_sum[i, 1:] = util.calcHPD(cond_rates[i, :], .95)
    needs_median = rate_sum[:, 0] > rate_sum[:, 2]
    rate_sum[needs_median, 0] = np.median(cond_rates[needs_median, :], axis = 1)
    return rate_sum
//  [python]
def get_rates_summary(cond_rates):
    nrows_cond_rates = cond_rates.shape[0]
    rate_sum = np.zeros((nrows_cond_rates, 3))
    rate_sum[:] = np.nan
    rate_sum[:, 0] = np.mean(cond_rates, axis = 1)
    for i in range(nrows_cond_rates):
        rate_isnan = np.isnan(cond_rates[i, :])
        all_nan = np.all(rate_isnan)
        n_rates = len(cond_rates[i, ~rate_isnan])
        if not all_nan and n_rates > 1:
            rate_sum[i, 1:] = util.calcHPD(cond_rates[i, :], .95)
    needs_median = rate_sum[:, 0] > rate_sum[:, 2]
    rate_sum[needs_median, 0] = np.median(cond_rates[needs_median, :], axis = 1)
    return rate_sum
//  [python]
def get_feat_to_keep_for_netdiv(cond_trait_tbl_sp, cond_trait_tbl_ex):
    feat_sp = np.unique(cond_trait_tbl_sp[ :, -6])
    feat_ex = np.unique(cond_trait_tbl_ex[:, -6])
    feat_in_any = np.intersect1d(feat_sp, feat_ex).astype(int)
    l = len(feat_in_any)
    all_values_equal = np.zeros(l, dtype = bool)
    if l > 0:
        for i in range(l):
            ii = feat_in_any[i]
            # Check if values for feature i are the same in both cond_trait_tbls
            idx_feat_i_sp = np.logical_and(cond_trait_tbl_sp[ :, -6] == ii, np.isnan(cond_trait_tbl_sp[ :, -5]))
            idx_feat_i_ex = np.logical_and(cond_trait_tbl_ex[:, -6] == ii, np.isnan(cond_trait_tbl_ex[:, -5]))
            if np.sum(idx_feat_i_sp) == np.sum(idx_feat_i_ex):
                all_values_equal[i] = np.alltrue(cond_trait_tbl_sp[idx_feat_i_sp, ii] == cond_trait_tbl_ex[idx_feat_i_ex, ii])
    feat_to_keep = feat_in_any[all_values_equal]
    return feat_to_keep
//  [python]
def get_feat_to_keep_for_netdiv(cond_trait_tbl_sp, cond_trait_tbl_ex):
    feat_sp = np.unique(cond_trait_tbl_sp[ :, -6])
    feat_ex = np.unique(cond_trait_tbl_ex[:, -6])
    feat_in_any = np.intersect1d(feat_sp, feat_ex).astype(int)
    l = len(feat_in_any)
    all_values_equal = np.zeros(l, dtype = bool)
    if l > 0:
        for i in range(l):
            ii = feat_in_any[i]
            # Check if values for feature i are the same in both cond_trait_tbls
            idx_feat_i_sp = np.logical_and(cond_trait_tbl_sp[ :, -6] == ii, np.isnan(cond_trait_tbl_sp[ :, -5]))
            idx_feat_i_ex = np.logical_and(cond_trait_tbl_ex[:, -6] == ii, np.isnan(cond_trait_tbl_ex[:, -5]))
            if np.sum(idx_feat_i_sp) == np.sum(idx_feat_i_ex):
                all_values_equal[i] = np.all(cond_trait_tbl_sp[idx_feat_i_sp, ii] == cond_trait_tbl_ex[idx_feat_i_ex, ii])
    feat_to_keep = feat_in_any[all_values_equal]
    return feat_to_keep
//  [python]
def __init__(self, data=None, vertices=None, mode=None):
    """
    Creates the segment vertices.

    Parameters
    ----------
    data: dictionary, optional
      YAML data;
      default: None.
    vertices: 1D array of floats, optional
      vertices along the segment;
      default: None.
    mode: string, optional
      Mode to use to create the segment;
      choices: ['cuibm'];
      default: None.
    """
    if data:
      self.create_from_yaml_data(data, mode=mode)
    elif n.all(vertices):
      self.create_from_vertices(vertices)
    self.nb_divisions = self.vertices.size - 1
//  [python]
def __init__(self, data=None, vertices=None, mode=None):
    """
    Creates the segment vertices.

    Parameters
    ----------
    data: dictionary, optional
      YAML data;
      default: None.
    vertices: 1D array of floats, optional
      vertices along the segment;
      default: None.
    mode: string, optional
      Mode to use to create the segment;
      choices: ['cuibm'];
      default: None.
    """
    if data:
      self.create_from_yaml_data(data, mode=mode)
    elif numpy.all(vertices):
      self.create_from_vertices(vertices)
    self.nb_divisions = self.vertices.size - 1
//  [python]
def __init__(self, data=None, vertices=None, label=None, mode=None):
    """
    Creates a gridline from provided YAML data or vertices.

    Parameters
    ----------
    data: dictionary, optional
      YAML data about the gridline;
      default: None.
    vertices: 1D array of floats, optional
      Vertices along the gridline;
      default: None.
    label: string, optional
      Label of the direction;
      default: None.
    mode: string, optional
      Mode to use to create the gridline;
      choices: ['cuibm'];
      default: None.
    """
    self.label = label
    self.segments = []
    if data:
      self.create_from_yaml_data(data, mode=mode)
    elif n.all(vertices):
      self.create_from_vertices(vertices)
    self.nb_divisions = sum(segment.nb_divisions for segment in self.segments)
//  [python]
def __init__(self, data=None, vertices=None, label=None, mode=None):
    """
    Creates a gridline from provided YAML data or vertices.

    Parameters
    ----------
    data: dictionary, optional
      YAML data about the gridline;
      default: None.
    vertices: 1D array of floats, optional
      Vertices along the gridline;
      default: None.
    label: string, optional
      Label of the direction;
      default: None.
    mode: string, optional
      Mode to use to create the gridline;
      choices: ['cuibm'];
      default: None.
    """
    self.label = label
    self.segments = []
    if data:
      self.create_from_yaml_data(data, mode=mode)
    elif numpy.all(vertices):
      self.create_from_vertices(vertices)
    self.nb_divisions = sum(segment.nb_divisions for segment in self.segments)
//  [python]
def patch_zeropoints(zps, ccds, ccdsa, decboundary=-29.25):
    if not n.all((ccds.image_hdu == ccdsa.image_hdu) &
                     (ccdsa.image_filename == ccdsa.image_filename)):
        raise ValueError('ccds and ccdsa must be row matched!')

    # UGH, dr10-v2 CCDs table contains some ccdname='' entries!
    ok = numpy.array([len(name.strip())>0 for name in ccds.ccdname])
    if not n.all(ok):
        print('Cutting to', numpy.sum(ok), 'of', len(ccds), 'CCDs with valid CCDNAME')
        ccds.cut(ok)
        ccdsa.cut(ok)

    mreplace = ccds.dec < decboundary
    oldccdzpt = ccds.ccdzpt.copy()
    ccds.zpt[mreplace] = 0
    ccds.ccdzpt[mreplace] = 0
    ccds.ccdphrms[mreplace] = 0
    olderr = numpy.seterr(invalid='ignore')
    mokim = ((zps.scatter > 0) & (zps.scatter < 0.02) &
             (numpy.abs(zps.resid) < 0.2))
    numpy.seterr(**olderr)
    zps = zps[mokim]
    mz, mc = match(zps.mjd_obs, ccds.mjd_obs)
    ccdnum = numpy.array([ccdnamenumdict[name.strip()]
                          for name in ccds.ccdname])
    newzpt = zps.zp[mz] - zps.resid[mz]
    newccdzpt = zps.zp[mz] - zps.resid[mz] - zps.mnchip[mz, ccdnum[mc]]
    newccdphrms = zps.sdchip[mz, ccdnum[mc]]
    newccdnphotom = zps.nstarchip[mz, ccdnum[mc]]
    m = (ccds.dec[mc] < decboundary)
    # S7 == ccdnum 31; removes worst-performing 5% of S7 CCDs.
    ms7 = (ccdnum[mc] != 31) | ((newccdnphotom > 3) & (newccdphrms < 0.02))
    m = m & ms7
    mz = mz[m]
    mc = mc[m]
    ccds.zpt[mc] = newzpt[m]
    ccds.ccdzpt[mc] = newccdzpt[m]
    ccds.ccdphrms[mc] = newccdphrms[m]
    ccds.phrms[mc] = zps.scatter[mz]
    ccdsa.zpt[mc] = newzpt[m]
    ccdsa.ccdzpt[mc] = newccdzpt[m]
    ccdsa.ccdphrms[mc] = newccdphrms[m]
    ccdsa.phrms[mc] = zps.scatter[mz]
    oldzp = numpy.where(oldccdzpt != 0, oldccdzpt, 22.5)
    newzp = numpy.where(ccds.ccdzpt != 0, ccds.ccdzpt, 22.5)
    oldzpscale = 10.**((oldzp-22.5)/2.5)
    newzpscale = 10.**((newzp-22.5)/2.5)
    rescale1 = oldzpscale/newzpscale
    ccds.sig1 = ccds.sig1*rescale1
    ccdsa.sig1 = ccdsa.sig1*rescale1
    rescale2 = 10.**((oldccdzpt-ccds.ccdzpt)/2.5)
    ccdsa.meansky = ccdsa.meansky*rescale2
    ccdsa.stdsky = ccdsa.stdsky*rescale2
    ccdsa.minsky = ccdsa.minsky*rescale2
    ccdsa.maxsky = ccdsa.maxsky*rescale2
    dzp = newzp-oldzp
    ccdsa.psfdepth += dzp
    ccdsa.gausspsfdepth += dzp
    ccdsa.galdepth += dzp
    ccdsa.gaussgaldepth += dzp
//  [python]
def patch_zeropoints(zps, ccds, ccdsa, decboundary=-29.25):
    if not numpy.all((ccds.image_hdu == ccdsa.image_hdu) &
                     (ccdsa.image_filename == ccdsa.image_filename)):
        raise ValueError('ccds and ccdsa must be row matched!')

    # UGH, dr10-v2 CCDs table contains some ccdname='' entries!
    ok = numpy.array([len(name.strip())>0 for name in ccds.ccdname])
    if not numpy.all(ok):
        print('Cutting to', numpy.sum(ok), 'of', len(ccds), 'CCDs with valid CCDNAME')
        ccds.cut(ok)
        ccdsa.cut(ok)

    mreplace = ccds.dec < decboundary
    oldccdzpt = ccds.ccdzpt.copy()
    ccds.zpt[mreplace] = 0
    ccds.ccdzpt[mreplace] = 0
    ccds.ccdphrms[mreplace] = 0
    olderr = numpy.seterr(invalid='ignore')
    mokim = ((zps.scatter > 0) & (zps.scatter < 0.02) &
             (numpy.abs(zps.resid) < 0.2))
    numpy.seterr(**olderr)
    zps = zps[mokim]
    mz, mc = match(zps.mjd_obs, ccds.mjd_obs)
    ccdnum = numpy.array([ccdnamenumdict[name.strip()]
                          for name in ccds.ccdname])
    newzpt = zps.zp[mz] - zps.resid[mz]
    newccdzpt = zps.zp[mz] - zps.resid[mz] - zps.mnchip[mz, ccdnum[mc]]
    newccdphrms = zps.sdchip[mz, ccdnum[mc]]
    newccdnphotom = zps.nstarchip[mz, ccdnum[mc]]
    m = (ccds.dec[mc] < decboundary)
    # S7 == ccdnum 31; removes worst-performing 5% of S7 CCDs.
    ms7 = (ccdnum[mc] != 31) | ((newccdnphotom > 3) & (newccdphrms < 0.02))
    m = m & ms7
    mz = mz[m]
    mc = mc[m]
    ccds.zpt[mc] = newzpt[m]
    ccds.ccdzpt[mc] = newccdzpt[m]
    ccds.ccdphrms[mc] = newccdphrms[m]
    ccds.phrms[mc] = zps.scatter[mz]
    ccdsa.zpt[mc] = newzpt[m]
    ccdsa.ccdzpt[mc] = newccdzpt[m]
    ccdsa.ccdphrms[mc] = newccdphrms[m]
    ccdsa.phrms[mc] = zps.scatter[mz]
    oldzp = numpy.where(oldccdzpt != 0, oldccdzpt, 22.5)
    newzp = numpy.where(ccds.ccdzpt != 0, ccds.ccdzpt, 22.5)
    oldzpscale = 10.**((oldzp-22.5)/2.5)
    newzpscale = 10.**((newzp-22.5)/2.5)
    rescale1 = oldzpscale/newzpscale
    ccds.sig1 = ccds.sig1*rescale1
    ccdsa.sig1 = ccdsa.sig1*rescale1
    rescale2 = 10.**((oldccdzpt-ccds.ccdzpt)/2.5)
    ccdsa.meansky = ccdsa.meansky*rescale2
    ccdsa.stdsky = ccdsa.stdsky*rescale2
    ccdsa.minsky = ccdsa.minsky*rescale2
    ccdsa.maxsky = ccdsa.maxsky*rescale2
    dzp = newzp-oldzp
    ccdsa.psfdepth += dzp
    ccdsa.gausspsfdepth += dzp
    ccdsa.galdepth += dzp
    ccdsa.gaussgaldepth += dzp
//  [python]
def _construct_xhat(self) -> None:
        k = len(self._x)
        self._xhat = []
        self._wxhat = []
        for i in range(k):
            x, z = self._x[i], self._z[i]
            if z.shape == x.shape and n.all(z == x):
                # OLS, no instruments
                self._xhat.append(x)
                self._wxhat.append(self._wx[i])
            else:
                delta = lstsq(z, x, rcond=None)[0]
                xhat = z @ delta
                self._xhat.append(xhat)
                w = self._w[i]
                self._wxhat.append(xhat * np.sqrt(w))
//  [python]
def _construct_xhat(self) -> None:
        k = len(self._x)
        self._xhat = []
        self._wxhat = []
        for i in range(k):
            x, z = self._x[i], self._z[i]
            if z.shape == x.shape and np.all(z == x):
                # OLS, no instruments
                self._xhat.append(x)
                self._wxhat.append(self._wx[i])
            else:
                delta = lstsq(z, x, rcond=None)[0]
                xhat = z @ delta
                self._xhat.append(xhat)
                w = self._w[i]
                self._wxhat.append(xhat * np.sqrt(w))
//  [python]
def plot_wigner_seitz(lattice, figure=None, **kwargs):  # pragma: no cover
    """
    Adds the skeleton of the Wigner-Seitz cell of the lattice to a mayavi_ figure

    Args:
        lattice: Reciprocal-space |Lattice| object
        figure: mayavi figure, None to plot on the curretn figure
        kwargs: kwargs passed to the mayavi function ``plot3d``. Color defaults to black
            and line_width to 1.

    Returns: mayavi figure
    """
    figure, mlab = get_fig_mlab(figure=figure)

    if "color" not in kwargs:
        kwargs["color"] = (0, 0, 0)
    if "line_width" not in kwargs:
        kwargs["line_width"] = 1
    if "tube_radius" not in kwargs:
        kwargs["tube_radius"] = None

    bz = lattice.get_wigner_seitz_cell()
    for iface in range(len(bz)):
        for line in itertools.combinations(bz[iface], 2):
            for jface in range(len(bz)):
                if iface < jface and any(np.all(line[0] == x) for x in bz[jface])\
                        and any(np.all(line[1] == x) for x in bz[jface]):
                    #do_plot = True
                    #if in_unit_cell:
                    #    kred0 = lattice.get_fractional_coords(line[0])
                    #    kred1 = lattice.get_fractional_coords(line[1])
                    #    do_plot = np.alltrue((kred0 >= 0) & (kred0 <= 0.5) &
                    #                         (kred1 >= 0) & (kred1 <= 0.5))
                    #    print(kred0, kred1, do_plot)
                    #if not do_plot: continue
                    mlab.plot3d(*zip(line[0], line[1]), figure=figure, **kwargs)

    return figure
//  [python]
def test_randomize(self):
        ps = self.test1.param.view(np.ndarray).copy()
        self.test1.param[2:5].fix()
        self.test1.param.randomize()
        self.assertFalse(np.all(ps==self.test1.param),str(ps)+str(self.test1.param))