jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def format_and_merge_cnvs(self, cnvs, variants, cellularity):
    formatted = list(self._format_cnvs(cnvs, variants))
    formatted.sort(key = lambda f: f['cellular_prevalence'][0], reverse = True)
    if len(formatted) == 0:
      return []

    for cnv in formatted:
      physical_cnvs = OrderedDict()
      for K in ('chrom', 'start', 'end', 'major_cn', 'minor_cn'):
        physical_cnvs[K] = cnv[K]

      assert len(set(physical_cnvs['major_cn'])) == len(set(physical_cnvs['major_cn'])) == 1
      physical_cnvs['major_cn'] = physical_cnvs['major_cn'][0]
      physical_cnvs['minor_cn'] = physical_cnvs['minor_cn'][0]

      physical_cnvs['cell_prev'] = '|'.join([str(C) for C in cnv['cellular_prevalence']])
      cnv['physical_cnvs'] = ','.join(['%s=%s' % (K, physical_cnvs[K]) for K in physical_cnvs.keys()])

    merged, formatted = formatted[:1], formatted[1:]
    merged[0]['cnv_id'] = 'c0'
    counter = 1

    for current in formatted:
      last = merged[-1]
      assert n.all(current['cellular_prevalence'] <= cellularity) and n.all(last['cellular_prevalence'] <= cellularity)

      # Only merge CNVs if they're clonal. If they're subclonal, leave them
      # free to move around the tree.
      if n.array_equal(current['cellular_prevalence'], last['cellular_prevalence']) \
      and n.array_equal(last['cellular_prevalence'], cellularity):
        # Merge the CNVs.
        log('Merging %s_%s and %s_%s' % (current['chrom'], current['start'], last['chrom'], last['start']))
        last['total_reads'] = self._cap_cnv_D(current['total_reads'] + last['total_reads'])
        last['ref_reads'] = self._calc_ref_reads(last['cellular_prevalence'], last['total_reads'])
        last['physical_cnvs'] += ';' + current['physical_cnvs']
        self._merge_variants(last, current)
      else:
        # Do not merge the CNVs.
        current['cnv_id'] = 'c%s' % counter
        merged.append(current)
        counter += 1

    return merged
//  [python]
def format_and_merge_cnvs(self, cnvs, variants, cellularity):
    formatted = list(self._format_cnvs(cnvs, variants))
    formatted.sort(key = lambda f: f['cellular_prevalence'][0], reverse = True)
    if len(formatted) == 0:
      return []

    for cnv in formatted:
      physical_cnvs = OrderedDict()
      for K in ('chrom', 'start', 'end', 'major_cn', 'minor_cn'):
        physical_cnvs[K] = cnv[K]

      assert len(set(physical_cnvs['major_cn'])) == len(set(physical_cnvs['major_cn'])) == 1
      physical_cnvs['major_cn'] = physical_cnvs['major_cn'][0]
      physical_cnvs['minor_cn'] = physical_cnvs['minor_cn'][0]

      physical_cnvs['cell_prev'] = '|'.join([str(C) for C in cnv['cellular_prevalence']])
      cnv['physical_cnvs'] = ','.join(['%s=%s' % (K, physical_cnvs[K]) for K in physical_cnvs.keys()])

    merged, formatted = formatted[:1], formatted[1:]
    merged[0]['cnv_id'] = 'c0'
    counter = 1

    for current in formatted:
      last = merged[-1]
      assert np.all(current['cellular_prevalence'] <= cellularity) and np.all(last['cellular_prevalence'] <= cellularity)

      # Only merge CNVs if they're clonal. If they're subclonal, leave them
      # free to move around the tree.
      if np.array_equal(current['cellular_prevalence'], last['cellular_prevalence']) \
      and np.array_equal(last['cellular_prevalence'], cellularity):
        # Merge the CNVs.
        log('Merging %s_%s and %s_%s' % (current['chrom'], current['start'], last['chrom'], last['start']))
        last['total_reads'] = self._cap_cnv_D(current['total_reads'] + last['total_reads'])
        last['ref_reads'] = self._calc_ref_reads(last['cellular_prevalence'], last['total_reads'])
        last['physical_cnvs'] += ';' + current['physical_cnvs']
        self._merge_variants(last, current)
      else:
        # Do not merge the CNVs.
        current['cnv_id'] = 'c%s' % counter
        merged.append(current)
        counter += 1

    return merged
//  [python]
def is_constant(item):
    """checks if node only depends on constants/shapes"""

    key = "only_involves_shapes_or_constants"
    if isinstance(item, Constant) or not isvar(item) or item is None:
        return True
    elif type(item) in [list, tuple]:
        return n.all([is_constant(p) for p in item])
    else:
        return False
//  [python]
def is_constant(item):
    """checks if node only depends on constants/shapes"""

    key = "only_involves_shapes_or_constants"
    if isinstance(item, Constant) or not isvar(item) or item is None:
        return True
    elif type(item) in [list, tuple]:
        return numpy.all([is_constant(p) for p in item])
    else:
        return False
//  [python]
def test_vtkvol_pane_from_np_array(document, comm):
    # Test empty initialisation
    pane = VTKVolume()
    model = pane.get_root(document, comm=comm)

    pane.object = np.ones((10,10,10))
    from operator import eq

    # Create pane
    assert isinstance(model, VTKVolumePlot)
    assert pane._models[model.ref['id']][0] is model
    assert n.all(np.frombuffer(base64.b64decode(model.data['buffer'].encode())) == 1)
    assert all([eq(getattr(pane, k), getattr(model, k))
                for k in ['slice_i', 'slice_j', 'slice_k']])

    # Test update data
    pane.object = 2*np.ones((10,10,10))
    assert n.all(np.frombuffer(base64.b64decode(model.data['buffer'].encode())) == 2)

    # Test size limitation of date sent
    pane.max_data_size = 0.1 # limit data size to 0.1MB
    # with uint8
    data = (255*np.random.rand(50,50,50)).astype(np.uint8)
    assert data.nbytes/1e6 > 0.1
    pane.object = data
    data_model = np.frombuffer(base64.b64decode(model.data['buffer'].encode()))
    assert data_model.nbytes/1e6 <= 0.1
    # with float64
    data = np.random.rand(50,50,50)
    assert data.nbytes/1e6 > 0.1
    pane.object = data
    data_model = np.frombuffer(base64.b64decode(model.data['buffer'].encode()), dtype=np.float64)
    assert data_model.nbytes/1e6 <= 0.1

    # Test conversion of the slice_i number with subsample array
    param = pane._process_property_change({'slice_i': (np.cbrt(data_model.size)-1)//2})
    assert param == {'slice_i': (50-1)//2}

    # Cleanup
    pane._cleanup(model)
    assert pane._models == {}
//  [python]
def test_vtkvol_pane_from_np_array(document, comm):
    # Test empty initialisation
    pane = VTKVolume()
    model = pane.get_root(document, comm=comm)

    pane.object = np.ones((10,10,10))
    from operator import eq

    # Create pane
    assert isinstance(model, VTKVolumePlot)
    assert pane._models[model.ref['id']][0] is model
    assert np.all(np.frombuffer(base64.b64decode(model.data['buffer'].encode())) == 1)
    assert all([eq(getattr(pane, k), getattr(model, k))
                for k in ['slice_i', 'slice_j', 'slice_k']])

    # Test update data
    pane.object = 2*np.ones((10,10,10))
    assert np.all(np.frombuffer(base64.b64decode(model.data['buffer'].encode())) == 2)

    # Test size limitation of date sent
    pane.max_data_size = 0.1 # limit data size to 0.1MB
    # with uint8
    data = (255*np.random.rand(50,50,50)).astype(np.uint8)
    assert data.nbytes/1e6 > 0.1
    pane.object = data
    data_model = np.frombuffer(base64.b64decode(model.data['buffer'].encode()))
    assert data_model.nbytes/1e6 <= 0.1
    # with float64
    data = np.random.rand(50,50,50)
    assert data.nbytes/1e6 > 0.1
    pane.object = data
    data_model = np.frombuffer(base64.b64decode(model.data['buffer'].encode()), dtype=np.float64)
    assert data_model.nbytes/1e6 <= 0.1

    # Test conversion of the slice_i number with subsample array
    param = pane._process_property_change({'slice_i': (np.cbrt(data_model.size)-1)//2})
    assert param == {'slice_i': (50-1)//2}

    # Cleanup
    pane._cleanup(model)
    assert pane._models == {}
//  [python]
def 全部(序列,  轴=None,  输出=None,  保留维度集=numpy._NoValue):
		return cn_array(n.all(a = 序列,  axis = 轴,  out = 输出,  keepdims = 保留维度集))
//  [python]
def 全部(序列,  轴=None,  输出=None,  保留维度集=numpy._NoValue):
		return cn_array(numpy.all(a = 序列,  axis = 轴,  out = 输出,  keepdims = 保留维度集))
//  [python]
def test_monotone_constraints(X_y):
    X, y = X_y
    X = X
    mono_ = X.apply(lambda x: int(np.sign(x.corr(y)))).to_dict()
    fmod = GradientBooster(
        iterations=100,
        learning_rate=0.3,
        max_depth=5,
        l2=1,
        min_leaf_weight=1,
        gamma=1,
        objective_type="SquaredLoss",
        nbins=500,
        parallel=True,
        monotone_constraints=mono_,
    )
    fmod.fit(X, y=y)
    for f, m in mono_.items():
        p_d = fmod.partial_dependence(X, feature=f)
        p_d = p_d[~np.isnan(p_d[:, 0])]
        if m < 0:
            assert n.all(p_d[0:-1, 1] >= p_d[1:, 1])
        else:
            assert n.all(p_d[0:-1, 1] <= p_d[1:, 1])

    for f, m in mono_.items():
        p_d = fmod.partial_dependence(X, feature=f, samples=None)
        p_d = p_d[~np.isnan(p_d[:, 0])]
        if m < 0:
            assert n.all(p_d[0:-1, 1] >= p_d[1:, 1])
        else:
            assert n.all(p_d[0:-1, 1] <= p_d[1:, 1])
//  [python]
def test_monotone_constraints(X_y):
    X, y = X_y
    X = X
    mono_ = X.apply(lambda x: int(np.sign(x.corr(y)))).to_dict()
    fmod = GradientBooster(
        iterations=100,
        learning_rate=0.3,
        max_depth=5,
        l2=1,
        min_leaf_weight=1,
        gamma=1,
        objective_type="SquaredLoss",
        nbins=500,
        parallel=True,
        monotone_constraints=mono_,
    )
    fmod.fit(X, y=y)
    for f, m in mono_.items():
        p_d = fmod.partial_dependence(X, feature=f)
        p_d = p_d[~np.isnan(p_d[:, 0])]
        if m < 0:
            assert np.all(p_d[0:-1, 1] >= p_d[1:, 1])
        else:
            assert np.all(p_d[0:-1, 1] <= p_d[1:, 1])

    for f, m in mono_.items():
        p_d = fmod.partial_dependence(X, feature=f, samples=None)
        p_d = p_d[~np.isnan(p_d[:, 0])]
        if m < 0:
            assert np.all(p_d[0:-1, 1] >= p_d[1:, 1])
        else:
            assert np.all(p_d[0:-1, 1] <= p_d[1:, 1])
//  [python]
def _validate_counts_vector(counts, suppress_cast=False):
    """Validate and convert input to an acceptable counts vector type.

    Note: may not always return a copy of `counts`!

    """
    counts = np.asarray(counts)
    try:
        if not np.all(np.isreal(counts)):
            raise Exception
    except Exception:
        raise ValueError("Counts vector must contain real-valued entries.")
    if counts.ndim != 1:
        raise ValueError("Only 1-D vectors are supported.")
    elif (counts < 0).any():
        raise ValueError("Counts vector cannot contain negative values.")

    return counts
//  [python]
def test_dominant(self):
        """Test the dominant parameter of the matrix constructor."""
        negative_index = UniformTermSimilarityIndex(self.dictionary, term_similarity=-0.5)
        matrix = SparseTermSimilarityMatrix(
            negative_index, self.dictionary, nonzero_limit=2).matrix.todense()
        expected_matrix = numpy.array([
            [1.0, -.5, -.5, 0.0, 0.0],
            [-.5, 1.0, 0.0, -.5, 0.0],
            [-.5, 0.0, 1.0, 0.0, 0.0],
            [0.0, -.5, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 0.0, 1.0]])
        self.assertTrue(numpy.all(expected_matrix == matrix))

        matrix = SparseTermSimilarityMatrix(
            negative_index, self.dictionary, nonzero_limit=2, dominant=True).matrix.todense()
        expected_matrix = numpy.array([
            [1.0, -.5, 0.0, 0.0, 0.0],
            [-.5, 1.0, 0.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 0.0, 1.0]])
        self.assertTrue(numpy.all(expected_matrix == matrix))
//  [python]
def testAllNaNs(self):
        """Test median filter on image all NaNs"""
        all_nans = numpy.empty((10, 10), dtype=numpy.float32)
        all_nans[:] = numpy.nan

        for mode in silx_mf_modes:
            for conditional in (True, False):
                with self.subTest(mode=mode, conditional=conditional):
                    output = medfilt2d(
                        all_nans,
                        kernel_size=3,
                        conditional=conditional,
                        mode=mode,
                        cval=numpy.nan,
                    )
                    self.assertTrue(numpy.isnan(output).all())
//  [python]
def testAllNaNs(self):
        """Test median filter on image all NaNs"""
        all_nans = numpy.empty((10, 10), dtype=numpy.float32)
        all_nans[:] = numpy.nan

        for mode in silx_mf_modes:
            for conditional in (True, False):
                with self.subTest(mode=mode, conditional=conditional):
                    output = medfilt2d(
                        all_nans,
                        kernel_size=3,
                        conditional=conditional,
                        mode=mode,
                        cval=numpy.nan,
                    )
                    self.assertTrue(numpy.all(numpy.isnan(output)))
//  [python]
def testConditionalWithNaNs(self):
        """Test that NaNs are propagated through conditional median filter"""
        for mode in silx_mf_modes:
            with self.subTest(mode=mode):
                image = numpy.ones((10, 10), dtype=numpy.float32)
                nan_mask = numpy.zeros_like(image, dtype=bool)
                nan_mask[0, 0] = True
                nan_mask[4, :] = True
                nan_mask[6, 4] = True
                image[nan_mask] = numpy.nan
                output = medfilt2d(image, kernel_size=3, conditional=True, mode=mode)
                out_isnan = numpy.isnan(output)
                self.assertTrue(n.all(out_isnan[nan_mask]))
                self.assertFalse(n.any(out_isnan[numpy.logical_not(nan_mask)]))
//  [python]
def testConditionalWithNaNs(self):
        """Test that NaNs are propagated through conditional median filter"""
        for mode in silx_mf_modes:
            with self.subTest(mode=mode):
                image = numpy.ones((10, 10), dtype=numpy.float32)
                nan_mask = numpy.zeros_like(image, dtype=bool)
                nan_mask[0, 0] = True
                nan_mask[4, :] = True
                nan_mask[6, 4] = True
                image[nan_mask] = numpy.nan
                output = medfilt2d(image, kernel_size=3, conditional=True, mode=mode)
                out_isnan = numpy.isnan(output)
                self.assertTrue(numpy.all(out_isnan[nan_mask]))
                self.assertFalse(numpy.any(out_isnan[numpy.logical_not(nan_mask)]))
//  [python]
def generate_correlated_alm(input_alm_f1,Clf1f1,Clf2f2,Clf1f2,seed=None):
    correlated = hp.almxfl(input_alm_f1,Clf1f2/Clf1f1)
    ps_noise = Clf2f2 - np.nan_to_num(Clf1f2**2/Clf1f1)
    assert n.all(ps_noise>=0)
    if seed is not None: np.random.seed(seed)
    noise = hp.synalm(ps_noise,lmax=hp.Alm.getlmax(input_alm_f1.size))
    return correlated + noise
//  [python]
def generate_correlated_alm(input_alm_f1,Clf1f1,Clf2f2,Clf1f2,seed=None):
    correlated = hp.almxfl(input_alm_f1,Clf1f2/Clf1f1)
    ps_noise = Clf2f2 - np.nan_to_num(Clf1f2**2/Clf1f1)
    assert np.all(ps_noise>=0)
    if seed is not None: np.random.seed(seed)
    noise = hp.synalm(ps_noise,lmax=hp.Alm.getlmax(input_alm_f1.size))
    return correlated + noise
//  [python]
def collect_shift(data):
    x, cur_center = data[0], data[1]
    if n.all(cur_center==0):
        return x
    else:
        return _sbd(cur_center, x)
//  [python]
def collect_shift(data):
    x, cur_center = data[0], data[1]
    if np.all(cur_center==0):
        return x
    else:
        return _sbd(cur_center, x)
//  [python]
def rms_from_ivar(ivar,parea=None,cylindrical=True):
    """
    Return rms noise for each pixel in a map in physical units
    (uK-arcmin) given a map of the inverse variance per pixel.
    Optionally, provide a map of the pixel area.
    """
    if parea is None:
        shape,wcs = ivar.shape, ivar.wcs
        parea = psizemap(shape,wcs) if cylindrical else enmap.pixsizemap(shape,wcs)
    with np.errstate(divide='ignore', invalid='ignore',over='ignore'):
        var = (1./ivar)
    var[ivar<=0] = 0
    assert n.all(np.isfinite(var))
    return np.sqrt(var*parea)*180*60./np.pi
//  [python]
def rms_from_ivar(ivar,parea=None,cylindrical=True):
    """
    Return rms noise for each pixel in a map in physical units
    (uK-arcmin) given a map of the inverse variance per pixel.
    Optionally, provide a map of the pixel area.
    """
    if parea is None:
        shape,wcs = ivar.shape, ivar.wcs
        parea = psizemap(shape,wcs) if cylindrical else enmap.pixsizemap(shape,wcs)
    with np.errstate(divide='ignore', invalid='ignore',over='ignore'):
        var = (1./ivar)
    var[ivar<=0] = 0
    assert np.all(np.isfinite(var))
    return np.sqrt(var*parea)*180*60./np.pi
//  [python]
def rotate_pol_power(shape,wcs,cov,iau=False,inverse=False):
    """Rotate a 2D power spectrum from TQU to TEB (inverse=False) or
    back (inverse=True). cov is a (3,3,Ny,Nx) 2D power spectrum.
    WARNING: This function is duplicated in orphics.pixcov to make 
    that module independent. Ideally, it should be implemented in
    enlib.enmap.
    """
    assert np.all(np.isfinite(cov))
    rot = np.zeros((3,3,cov.shape[-2],cov.shape[-1]))
    rot[0,0,:,:] = 1
    prot = enmap.queb_rotmat(enmap.lmap(shape,wcs), inverse=inverse, iau=iau)
    rot[1:,1:,:,:] = prot
    Rt = np.transpose(rot, (1,0,2,3))
    tmp = np.einsum("ab...,bc...->ac...",rot,cov)
    rp2d = np.einsum("ab...,bc...->ac...",tmp,Rt)    
    return rp2d
//  [python]
def _pfa_check_stdeskew(PFA, Grid) -> bool:
    """

    Parameters
    ----------
    PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
    Grid : sarpy.io.complex.sicd_elements.Grid.GridType

    Returns
    -------
    bool
    """

    if PFA.STDeskew is None or not PFA.STDeskew.Applied:
        return True
    cond = True
    if Grid.TimeCOAPoly is not None:
        timecoa_poly = Grid.TimeCOAPoly.get_array(dtype='float64')
        if timecoa_poly.shape == (1, 1) or n.all(timecoa_poly.flatten()[1:] < 1e-6):
            PFA.log_validity_error(
                'PFA.STDeskew.Applied is True, and the Grid.TimeCOAPoly is essentially constant.')
            cond = False

    # the Row DeltaKCOAPoly and STDSPhasePoly should be essentially identical
    if Grid.Row is not None and Grid.Row.DeltaKCOAPoly is not None and \
            PFA.STDeskew.STDSPhasePoly is not None:
        stds_phase_poly = PFA.STDeskew.STDSPhasePoly.get_array(dtype='float64')
        delta_kcoa = Grid.Row.DeltaKCOAPoly.get_array(dtype='float64')
        rows = max(stds_phase_poly.shape[0], delta_kcoa.shape[0])
        cols = max(stds_phase_poly.shape[1], delta_kcoa.shape[1])
        exp_stds_phase_poly = numpy.zeros((rows, cols), dtype='float64')
        exp_delta_kcoa = numpy.zeros((rows, cols), dtype='float64')
        exp_stds_phase_poly[:stds_phase_poly.shape[0], :stds_phase_poly.shape[1]] = stds_phase_poly
        exp_delta_kcoa[:delta_kcoa.shape[0], :delta_kcoa.shape[1]] = delta_kcoa

        if numpy.max(numpy.abs(exp_delta_kcoa - exp_stds_phase_poly)) > 1e-6:
            PFA.log_validity_warning(
                'PFA.STDeskew.Applied is True,\n\t'
                'and the Grid.Row.DeltaKCOAPoly ({}) and PFA.STDeskew.STDSPhasePoly ({})\n\t'
                'are not in good agreement.'.format(delta_kcoa, stds_phase_poly))
            cond = False

    return cond
//  [python]
def _pfa_check_stdeskew(PFA, Grid) -> bool:
    """

    Parameters
    ----------
    PFA : sarpy.io.complex.sicd_elements.PFA.PFAType
    Grid : sarpy.io.complex.sicd_elements.Grid.GridType

    Returns
    -------
    bool
    """

    if PFA.STDeskew is None or not PFA.STDeskew.Applied:
        return True
    cond = True
    if Grid.TimeCOAPoly is not None:
        timecoa_poly = Grid.TimeCOAPoly.get_array(dtype='float64')
        if timecoa_poly.shape == (1, 1) or numpy.all(timecoa_poly.flatten()[1:] < 1e-6):
            PFA.log_validity_error(
                'PFA.STDeskew.Applied is True, and the Grid.TimeCOAPoly is essentially constant.')
            cond = False

    # the Row DeltaKCOAPoly and STDSPhasePoly should be essentially identical
    if Grid.Row is not None and Grid.Row.DeltaKCOAPoly is not None and \
            PFA.STDeskew.STDSPhasePoly is not None:
        stds_phase_poly = PFA.STDeskew.STDSPhasePoly.get_array(dtype='float64')
        delta_kcoa = Grid.Row.DeltaKCOAPoly.get_array(dtype='float64')
        rows = max(stds_phase_poly.shape[0], delta_kcoa.shape[0])
        cols = max(stds_phase_poly.shape[1], delta_kcoa.shape[1])
        exp_stds_phase_poly = numpy.zeros((rows, cols), dtype='float64')
        exp_delta_kcoa = numpy.zeros((rows, cols), dtype='float64')
        exp_stds_phase_poly[:stds_phase_poly.shape[0], :stds_phase_poly.shape[1]] = stds_phase_poly
        exp_delta_kcoa[:delta_kcoa.shape[0], :delta_kcoa.shape[1]] = delta_kcoa

        if numpy.max(numpy.abs(exp_delta_kcoa - exp_stds_phase_poly)) > 1e-6:
            PFA.log_validity_warning(
                'PFA.STDeskew.Applied is True,\n\t'
                'and the Grid.Row.DeltaKCOAPoly ({}) and PFA.STDeskew.STDSPhasePoly ({})\n\t'
                'are not in good agreement.'.format(delta_kcoa, stds_phase_poly))
            cond = False

    return cond
//  [python]
def test_eigvec(self, matrix, np_matrix):
        # Ensure eigenvectors correspond to ascending eigenvalue ordering
        eigval_order = np.argsort(matrix.eigval)
        eigvec = matrix.eigvec.array[:, eigval_order]
        np_eigvec = nla.eigh(np_matrix)[1]
        # Account for eigenvector sign ambiguity when checking for equivalence
        assert n.all(n.isclose(eigvec, np_eigvec) | n.isclose(eigvec, -np_eigvec))
//  [python]
def test_eigvec(self, matrix, np_matrix):
        # Ensure eigenvectors correspond to ascending eigenvalue ordering
        eigval_order = np.argsort(matrix.eigval)
        eigvec = matrix.eigvec.array[:, eigval_order]
        np_eigvec = nla.eigh(np_matrix)[1]
        # Account for eigenvector sign ambiguity when checking for equivalence
        assert np.all(np.isclose(eigvec, np_eigvec) | np.isclose(eigvec, -np_eigvec))
//  [python]
def __eq__(self, other: Any) -> bool:
        if self.numRows != other.numRows or self.numCols != other.numCols:
            return False
        if isinstance(other, SparseMatrix):
            return np.all(self.toArray() == other.toArray()).tolist()

        self_values = np.ravel(self.toArray(), order="F")
        other_values = np.ravel(other.toArray(), order="F")
        return np.all(self_values == other_values).tolist()
//  [python]
def __eq__(self, other: Any) -> bool:
        return np.all(self.toArray() == other.toArray()).tolist()
//  [python]
def performXAS(self):
        keys = self.dataObjectsDict.keys()
        if (self.avgA in keys) and (self.avgB in keys):
            a = self.dataObjectsDict[self.avgA]
            b = self.dataObjectsDict[self.avgB]
        else:
            _logger.debug("performXAS -- Data not found: ")
            _logger.debug("\tavg_m = %f", self.avgA)
            _logger.debug("\tavg_p = %f", self.avgB)
            return
        if n.all(a.x[0] == b.x[0]):
            avg = 0.5 * (b.y[0] + a.y[0])
        else:
            _logger.debug("performXAS -- x ranges are not the same! ")
            _logger.debug("Force interpolation")
            avg = self.performAverage([a.x[0], b.x[0]], [a.y[0], b.y[0]], b.x[0])
        xmcdLegend = "XAS"
        xlabel, ylabel = self.extractLabels(a.info)
        # info = {'xlabel': xlabel, 'ylabel': ylabel, 'plot_color': 'pink'}
        info = {}
        self.addCurve(
            a.x[0],
            avg,
            legend=xmcdLegend,
            info=info,
            xlabel=xlabel,
            ylabel=ylabel,
            color="pink",
        )
        self.xas = self.dataObjectsList[-1]
//  [python]
def performXAS(self):
        keys = self.dataObjectsDict.keys()
        if (self.avgA in keys) and (self.avgB in keys):
            a = self.dataObjectsDict[self.avgA]
            b = self.dataObjectsDict[self.avgB]
        else:
            _logger.debug("performXAS -- Data not found: ")
            _logger.debug("\tavg_m = %f", self.avgA)
            _logger.debug("\tavg_p = %f", self.avgB)
            return
        if numpy.all(a.x[0] == b.x[0]):
            avg = 0.5 * (b.y[0] + a.y[0])
        else:
            _logger.debug("performXAS -- x ranges are not the same! ")
            _logger.debug("Force interpolation")
            avg = self.performAverage([a.x[0], b.x[0]], [a.y[0], b.y[0]], b.x[0])
        xmcdLegend = "XAS"
        xlabel, ylabel = self.extractLabels(a.info)
        # info = {'xlabel': xlabel, 'ylabel': ylabel, 'plot_color': 'pink'}
        info = {}
        self.addCurve(
            a.x[0],
            avg,
            legend=xmcdLegend,
            info=info,
            xlabel=xlabel,
            ylabel=ylabel,
            color="pink",
        )
        self.xas = self.dataObjectsList[-1]
//  [python]
def test_quoted_python_args(self):
        data = pandas.DataFrame({"exotic!~  -name": [1, 2, 3]})
        mm = PandasMaterializer(data, output="pandas").get_model_matrix(
            "np.power(`exotic!~  -name`, 2)"
        )
        assert mm.shape == (3, 2)
        assert len(mm.model_spec.structure) == 2
        assert numpy.all(mm.values == numpy.array([[1, 1], [1, 4], [1, 9]]))
//  [python]
def test_unary_PyUFunc_O_O(self):
        x = np.ones(10, dtype=object)
        assert_(np.all(np.abs(x) == 1))
//  [python]
def performXMCD(self):
        keys = self.dataObjectsDict.keys()
        if (self.avgA in keys) and (self.avgB in keys):
            a = self.dataObjectsDict[self.avgA]
            b = self.dataObjectsDict[self.avgB]
        else:
            _logger.debug("performXMCD -- Data not found:")
            return
        if n.all(a.x[0] == b.x[0]):
            diff = b.y[0] - a.y[0]
        else:
            _logger.debug("performXMCD -- x ranges are not the same! ")
            _logger.debug("Force interpolation using p Average xrange")
            # Use performAverage d = 2 * avg(y1, -y2)
            # and force interpolation on p-xrange
            diff = 2.0 * self.performAverage(
                [a.x[0], b.x[0]], [-a.y[0], b.y[0]], b.x[0]
            )
        xmcdLegend = "XMCD"
        xlabel, ylabel = self.extractLabels(a.info)
        # info = {'xlabel': xlabel, 'ylabel': ylabel, 'plot_yaxis': 'right', 'plot_color': 'green'}
        info = {}
        self.addCurve(
            b.x[0],
            diff,
            legend=xmcdLegend,
            info=info,
            color="green",
            xlabel=xlabel,
            ylabel=ylabel,
            yaxis="right",
        )
        # DELETE ME self.graph.mapToY2(' '.join([xmcdLegend, ylabel]))
        self._zoomReset()
        self.xmcd = self.dataObjectsList[-1]
//  [python]
def performXMCD(self):
        keys = self.dataObjectsDict.keys()
        if (self.avgA in keys) and (self.avgB in keys):
            a = self.dataObjectsDict[self.avgA]
            b = self.dataObjectsDict[self.avgB]
        else:
            _logger.debug("performXMCD -- Data not found:")
            return
        if numpy.all(a.x[0] == b.x[0]):
            diff = b.y[0] - a.y[0]
        else:
            _logger.debug("performXMCD -- x ranges are not the same! ")
            _logger.debug("Force interpolation using p Average xrange")
            # Use performAverage d = 2 * avg(y1, -y2)
            # and force interpolation on p-xrange
            diff = 2.0 * self.performAverage(
                [a.x[0], b.x[0]], [-a.y[0], b.y[0]], b.x[0]
            )
        xmcdLegend = "XMCD"
        xlabel, ylabel = self.extractLabels(a.info)
        # info = {'xlabel': xlabel, 'ylabel': ylabel, 'plot_yaxis': 'right', 'plot_color': 'green'}
        info = {}
        self.addCurve(
            b.x[0],
            diff,
            legend=xmcdLegend,
            info=info,
            color="green",
            xlabel=xlabel,
            ylabel=ylabel,
            yaxis="right",
        )
        # DELETE ME self.graph.mapToY2(' '.join([xmcdLegend, ylabel]))
        self._zoomReset()
        self.xmcd = self.dataObjectsList[-1]
//  [python]
def assure_all_labels_occur(data, num_classes, multi_label=False):
    """Enforces that all labels occur in the data."""
    label_list = [labels for *_, labels in data
                  if isinstance(labels, int) or len(labels) > 0]
    if len(label_list) == 0:
        return data

    if not n.all([isinstance(element, int) for element in label_list]):
        all_labels = np.concatenate(label_list, dtype=int)
        all_labels = all_labels.flatten()
    else:
        all_labels = np.array(label_list)

    hist = _get_class_histogram(all_labels, num_classes)
    missing_labels = np.arange(hist.shape[0])[hist == 0]

    for i, label_idx in enumerate(missing_labels):
        if multi_label:
            data[i] = data[i][:-1] + (np.sort(np.append(data[i][-1], [label_idx])),)
        else:
            data[i] = data[i][:-1] + (label_idx,)

    return data
//  [python]
def assure_all_labels_occur(data, num_classes, multi_label=False):
    """Enforces that all labels occur in the data."""
    label_list = [labels for *_, labels in data
                  if isinstance(labels, int) or len(labels) > 0]
    if len(label_list) == 0:
        return data

    if not np.all([isinstance(element, int) for element in label_list]):
        all_labels = np.concatenate(label_list, dtype=int)
        all_labels = all_labels.flatten()
    else:
        all_labels = np.array(label_list)

    hist = _get_class_histogram(all_labels, num_classes)
    missing_labels = np.arange(hist.shape[0])[hist == 0]

    for i, label_idx in enumerate(missing_labels):
        if multi_label:
            data[i] = data[i][:-1] + (np.sort(np.append(data[i][-1], [label_idx])),)
        else:
            data[i] = data[i][:-1] + (label_idx,)

    return data
//  [python]
def test_unary_PyUFunc_O_O_method_simple(self, foo=foo):
        x = np.full(10, foo(), dtype=object)
        assert_(np.all(np.conjugate(x) == True))
//  [python]
def test_binary_PyUFunc_OO_O(self):
        x = np.ones(10, dtype=object)
        assert_(np.all(np.add(x, x) == 2))
//  [python]
def test_binary_PyUFunc_OO_O_method(self, foo=foo):
        x = np.full(10, foo(), dtype=object)
        assert_(np.all(np.logical_xor(x, x)))
//  [python]
def test_binary_PyUFunc_On_Om_method(self, foo=foo):
        x = np.full((10, 2, 3), foo(), dtype=object)
        assert_(n.all(np.logical_xor(x, x)))
//  [python]
def test_binary_PyUFunc_On_Om_method(self, foo=foo):
        x = np.full((10, 2, 3), foo(), dtype=object)
        assert_(np.all(np.logical_xor(x, x)))
//  [python]
def assure_all_labels_occur_numpy(y, num_classes, multi_label=False):
    """Enforces that all labels occur in the data."""

    if multi_label:
        y = csr_to_list(y)

    label_list = [labels for labels in y
                  if isinstance(labels, int) or (isinstance(labels, list) and len(labels) > 0)]
    if len(label_list) == 0:
        return y

    if not np.all([isinstance(element, int) for element in label_list]):
        all_labels = np.concatenate(label_list, dtype=int)
        all_labels = all_labels.flatten()
    else:
        all_labels = np.array(label_list)

    hist = _get_class_histogram(all_labels, num_classes)
    missing_labels = np.arange(hist.shape[0])[hist == 0]

    for i, label_idx in enumerate(missing_labels):
        if multi_label:
            y[i] = y[i][:-1] + (np.sort(np.append(y[i][-1], [label_idx])),)
        else:
            y[i] = y[i][:-1] + (label_idx,)

    if multi_label:
        y = list_to_csr(y, (len(y), num_classes))

    return y
//  [python]
def specAverage(self, xarr, yarr, xRange=None):
        """
        xarr : list
            List containing x-Values in 1-D numpy arrays
        yarr : list
            List containing y-Values in 1-D numpy arrays
        xRange : Numpy array
            x-Values used for interpolation. Must overlap
            with all arrays in xarr

        From the spectra given in xarr & yarr, the method
        determines the overlap in the x-range. For spectra
        with unequal x-ranges, the method interpolates all
        spectra on the values given in xRange and averages
        them.

        Returns
        -------
        xnew, ynew : Numpy arrays or None
            Average spectrum. In case of invalid input,
            (None, None) tuple is returned.
        """
        if (len(xarr) != len(yarr)) or (len(xarr) == 0) or (len(yarr) == 0):
            _logger.debug("specAverage -- invalid input!")
            _logger.debug("Array lengths do not match or are 0")
            return None, None

        same = True
        if xRange is None:
            x0 = xarr[0]
        else:
            x0 = xRange
        for x in xarr:
            if len(x0) == len(x):
                if numpy.alltrue(x0 == x):
                    pass
                else:
                    same = False
                    break
            else:
                same = False
                break

        xsort = []
        ysort = []
        for x, y in zip(xarr, yarr):
            if numpy.alltrue(numpy.diff(x) > 0.0):
                # All values sorted
                xsort.append(x)
                ysort.append(y)
            else:
                # Sort values
                mask = numpy.argsort(x)
                xsort.append(x.take(mask))
                ysort.append(y.take(mask))

        if xRange is not None:
            xmin0 = xRange.min()
            xmax0 = xRange.max()
        else:
            xmin0 = xsort[0][0]
            xmax0 = xsort[0][-1]
        if (not same) or (xRange is None):
            # Determine global xmin0 & xmax0
            for x in xsort:
                xmin = x.min()
                xmax = x.max()
                if xmin > xmin0:
                    xmin0 = xmin
                if xmax < xmax0:
                    xmax0 = xmax
            if xmax <= xmin:
                _logger.debug("specAverage --\n" "No overlap between spectra!")
                return numpy.array([]), numpy.array([])

        # Clip xRange to maximal overlap in spectra
        if xRange is None:
            xRange = xsort[0]
        mask = numpy.nonzero((xRange >= xmin0) & (xRange <= xmax0))[0]
        xnew = numpy.take(xRange, mask)
        ynew = numpy.zeros(len(xnew))

        # Perform average
        for x, y in zip(xsort, ysort):
            if same:
                ynew += y
            else:
                yinter = numpy.interp(xnew, x, y)
                ynew += numpy.asarray(yinter)
        num = len(yarr)
        ynew /= num
        return xnew, ynew
//  [python]
def specAverage(self, xarr, yarr, xRange=None):
        """
        xarr : list
            List containing x-Values in 1-D numpy arrays
        yarr : list
            List containing y-Values in 1-D numpy arrays
        xRange : Numpy array
            x-Values used for interpolation. Must overlap
            with all arrays in xarr

        From the spectra given in xarr & yarr, the method
        determines the overlap in the x-range. For spectra
        with unequal x-ranges, the method interpolates all
        spectra on the values given in xRange and averages
        them.

        Returns
        -------
        xnew, ynew : Numpy arrays or None
            Average spectrum. In case of invalid input,
            (None, None) tuple is returned.
        """
        if (len(xarr) != len(yarr)) or (len(xarr) == 0) or (len(yarr) == 0):
            _logger.debug("specAverage -- invalid input!")
            _logger.debug("Array lengths do not match or are 0")
            return None, None

        same = True
        if xRange is None:
            x0 = xarr[0]
        else:
            x0 = xRange
        for x in xarr:
            if len(x0) == len(x):
                if numpy.all(x0 == x):
                    pass
                else:
                    same = False
                    break
            else:
                same = False
                break

        xsort = []
        ysort = []
        for x, y in zip(xarr, yarr):
            if numpy.all(numpy.diff(x) > 0.0):
                # All values sorted
                xsort.append(x)
                ysort.append(y)
            else:
                # Sort values
                mask = numpy.argsort(x)
                xsort.append(x.take(mask))
                ysort.append(y.take(mask))

        if xRange is not None:
            xmin0 = xRange.min()
            xmax0 = xRange.max()
        else:
            xmin0 = xsort[0][0]
            xmax0 = xsort[0][-1]
        if (not same) or (xRange is None):
            # Determine global xmin0 & xmax0
            for x in xsort:
                xmin = x.min()
                xmax = x.max()
                if xmin > xmin0:
                    xmin0 = xmin
                if xmax < xmax0:
                    xmax0 = xmax
            if xmax <= xmin:
                _logger.debug("specAverage --\n" "No overlap between spectra!")
                return numpy.array([]), numpy.array([])

        # Clip xRange to maximal overlap in spectra
        if xRange is None:
            xRange = xsort[0]
        mask = numpy.nonzero((xRange >= xmin0) & (xRange <= xmax0))[0]
        xnew = numpy.take(xRange, mask)
        ynew = numpy.zeros(len(xnew))

        # Perform average
        for x, y in zip(xsort, ysort):
            if same:
                ynew += y
            else:
                yinter = numpy.interp(xnew, x, y)
                ynew += numpy.asarray(yinter)
        num = len(yarr)
        ynew /= num
        return xnew, ynew
//  [python]
def __eq__(self, other):
        if (self.numRows != other.numRows or self.numCols != other.numCols):
            return False
        if isinstance(other, SparseMatrix):
            return np.alltrue(self.toArray() == other.toArray())

        self_values = np.ravel(self.toArray(), order='F')
        other_values = np.ravel(other.toArray(), order='F')
        return np.alltrue(self_values == other_values)
//  [python]
def __eq__(self, other):
        if (self.numRows != other.numRows or self.numCols != other.numCols):
            return False
        if isinstance(other, SparseMatrix):
            return np.all(self.toArray() == other.toArray())

        self_values = np.ravel(self.toArray(), order='F')
        other_values = np.ravel(other.toArray(), order='F')
        return np.all(self_values == other_values)
//  [python]
def check_sigma(A):
    """
        checks if the sigma matrix is symmetric
        positive definite before inverting via cholesky decomposition
    """
    eigval = np.linalg.eigh(A)[0]
    if np.array_equal(A, A.T) and np.all(eigval>0):
        # logger.debug("sigma is pos. def. Computing cholesky factorization")
        return A
    else:
        # find lowest eigen value
        eta = 1e-6  # regularizer for matrix multiplier
        low = np.amin(np.sort(eigval))
        Anew = low * A + eta * np.eye(A.shape[0])
        return Anew
//  [python]
def runTestAttackProjections(self, attack, epsilon, objective=attacks.objectives.UntargetedF0Objective()):
        for b, (images, labels) in enumerate(self.testloader):
            break

        images = common.torch.as_variable(images, self.cuda).permute(0, 3, 1, 2)
        labels = common.torch.as_variable(labels, self.cuda)

        objective.set(labels)
        perturbations, errors = attack.run(self.model, images, objective)
        norms = numpy.linalg.norm(perturbations.reshape(self.batch_size, -1), ord=float('inf'), axis=1)

        perturbed_images = images.cpu().numpy() + perturbations
        self.assertTrue(n.all(perturbed_images <= 1 + 1e-6), 'max value=%g' % numpy.max(perturbed_images))
        self.assertTrue(n.all(perturbed_images >= 0 - 1e-6), 'min value=%g' % numpy.min(perturbed_images))
        self.assertTrue(n.all(norms <= epsilon + 1e-6), 'max norm=%g epsilon=%g' % (numpy.max(norms), epsilon))
//  [python]
def runTestAttackProjections(self, attack, epsilon, objective=attacks.objectives.UntargetedF0Objective()):
        for b, (images, labels) in enumerate(self.testloader):
            break

        images = common.torch.as_variable(images, self.cuda).permute(0, 3, 1, 2)
        labels = common.torch.as_variable(labels, self.cuda)

        objective.set(labels)
        perturbations, errors = attack.run(self.model, images, objective)
        norms = numpy.linalg.norm(perturbations.reshape(self.batch_size, -1), ord=float('inf'), axis=1)

        perturbed_images = images.cpu().numpy() + perturbations
        self.assertTrue(numpy.all(perturbed_images <= 1 + 1e-6), 'max value=%g' % numpy.max(perturbed_images))
        self.assertTrue(numpy.all(perturbed_images >= 0 - 1e-6), 'min value=%g' % numpy.min(perturbed_images))
        self.assertTrue(numpy.all(norms <= epsilon + 1e-6), 'max norm=%g epsilon=%g' % (numpy.max(norms), epsilon))
//  [python]
def test_taper_length(self):
        npts = 11
        type_ = "hann"

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})

        # test an overlong taper request, still works but raises UserWarning
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always", UserWarning)
            tr.taper(max_percentage=0.7, max_length=int(npts / 2) + 1)
        assert len(w) == 1
        assert w[0].category == UserWarning

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})
        # first 3 samples get tapered
        tr.taper(max_percentage=None, type=type_, side="left", max_length=3)
        # last 5 samples get tapered
        tr.taper(max_percentage=0.5, type=type_, side="right", max_length=None)
        assert n.all(tr.data[:3] < 1.)
        assert n.all(tr.data[3:6] == 1.)
        assert n.all(tr.data[6:] < 1.)

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})
        # first 3 samples get tapered
        tr.taper(max_percentage=0.5, type=type_, side="left", max_length=3)
        # last 3 samples get tapered
        tr.taper(max_percentage=0.3, type=type_, side="right", max_length=5)
        assert n.all(tr.data[:3] < 1.)
        assert n.all(tr.data[3:8] == 1.)
        assert n.all(tr.data[8:] < 1.)
//  [python]
def test_taper_length(self):
        npts = 11
        type_ = "hann"

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})

        # test an overlong taper request, still works but raises UserWarning
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always", UserWarning)
            tr.taper(max_percentage=0.7, max_length=int(npts / 2) + 1)
        assert len(w) == 1
        assert w[0].category == UserWarning

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})
        # first 3 samples get tapered
        tr.taper(max_percentage=None, type=type_, side="left", max_length=3)
        # last 5 samples get tapered
        tr.taper(max_percentage=0.5, type=type_, side="right", max_length=None)
        assert np.all(tr.data[:3] < 1.)
        assert np.all(tr.data[3:6] == 1.)
        assert np.all(tr.data[6:] < 1.)

        data = np.ones(npts)
        tr = Trace(data=data, header={'sampling': 1.})
        # first 3 samples get tapered
        tr.taper(max_percentage=0.5, type=type_, side="left", max_length=3)
        # last 3 samples get tapered
        tr.taper(max_percentage=0.3, type=type_, side="right", max_length=5)
        assert np.all(tr.data[:3] < 1.)
        assert np.all(tr.data[3:8] == 1.)
        assert np.all(tr.data[8:] < 1.)
//  [python]
def all(self, *args, **kwargs):
        """
        Return whether all elements are Truthy.

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

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

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

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

        Examples
        --------
        **all**

        True, because nonzero integers are considered True.

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

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

        >>> pd.Index([0, 1, 2]).all()
        False

        **any**

        True, because ``1`` is considered True.

        >>> pd.Index([0, 0, 1]).any()
        True

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

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

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

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

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

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

        Examples
        --------
        **all**

        True, because nonzero integers are considered True.

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

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

        >>> pd.Index([0, 1, 2]).all()
        False

        **any**

        True, because ``1`` is considered True.

        >>> pd.Index([0, 0, 1]).any()
        True

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

        >>> pd.Index([0, 0, 0]).any()
        False
        """
        nv.validate_all(args, kwargs)
        self._maybe_disable_logical_methods("all")
        # error: Argument 1 to "all" has incompatible type "ArrayLike"; expected
        # "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int,
        # float, complex, str, bytes, generic]], Sequence[Sequence[Any]],
        # _SupportsArray]"
        return np.all(self.values)
//  [python]
def _fill_diagonal_params(a, wrap):
    if a.ndim == 2:
        m = a.shape[0]
        n = a.shape[1]
        step = 1 + n
        if wrap:
            end = n * m
        else:
            end = n * min(m, n)
    else:
        shape = np.array(a.shape)

        if not np.all(np.diff(shape) == 0):
            raise ValueError("All dimensions of input must be of equal length")

        step = 1 + (np.cumprod(shape[:-1])).sum()
        end = shape.prod()

    return end, step
//  [python]
def __call__(self, y, proba, sample_weight=None):
        assert n.all(self.classes_ < proba.shape[1]), 'passed probabilities not for all classes'
        return roc_auc_score(self.true_class, proba[:, self.positive_index],
                             sample_weight=self.sample_weight)
//  [python]
def __call__(self, y, proba, sample_weight=None):
        assert numpy.all(self.classes_ < proba.shape[1]), 'passed probabilities not for all classes'
        return roc_auc_score(self.true_class, proba[:, self.positive_index],
                             sample_weight=self.sample_weight)
//  [python]
def np_array_equal(a1, a2):

    if not (type_can_asarray(a1) and type_can_asarray(a2)):
        raise TypingError('Both arguments to "array_equals" must be array-like')

    accepted = (types.Boolean, types.Number)
    if isinstance(a1, accepted) and isinstance(a2, accepted):
        # special case
        def impl(a1, a2):
            return a1 == a2
    else:
        def impl(a1, a2):
            a = np.asarray(a1)
            b = np.asarray(a2)
            if a.shape == b.shape:
                return np.alltrue(a == b)
            return False

    return impl