jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_pixfun_conj_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_conj_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == numpy.conj(refdata))
//  [python]
def test_pixfun_conj_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_conj_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == numpy.conj(refdata))
//  [python]
def test_pixfun_sum_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sum_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.zeros(data.shape, 'complex')
    for reffilename in ('data/uint16.tif', 'data/cint_sar.tif',
                        'data/cfloat64.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata += refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    assert numpy.alltrue(data == refdata)
//  [python]
def test_pixfun_sum_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sum_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.zeros(data.shape, 'complex')
    for reffilename in ('data/uint16.tif', 'data/cint_sar.tif',
                        'data/cfloat64.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata += refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    assert numpy.all(data == refdata)
//  [python]
def test_pixfun_sum_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sum_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.zeros(data.shape, 'float')
    for reffilename in ('data/uint16.tif', 'data/int32.tif',
                        'data/float32.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata += refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == refdata)
//  [python]
def test_pixfun_sum_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sum_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.zeros(data.shape, 'float')
    for reffilename in ('data/uint16.tif', 'data/int32.tif',
                        'data/float32.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata += refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == refdata)
//  [python]
def test_pixfun_diff_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_diff_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray(10, 10, 5, 6)

    assert numpy.alltrue(data == refdata1 - refdata2)
//  [python]
def test_pixfun_diff_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_diff_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray(10, 10, 5, 6)

    assert numpy.all(data == refdata1 - refdata2)
//  [python]
def test_pixfun_mul_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_mul_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.ones(data.shape, 'float')
    for reffilename in ('data/uint16.tif', 'data/int32.tif',
                        'data/float32.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata *= refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == refdata)
//  [python]
def test_pixfun_mul_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_mul_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    refdata = numpy.ones(data.shape, 'float')
    for reffilename in ('data/uint16.tif', 'data/int32.tif',
                        'data/float32.tif'):
        refds = gdal.Open(reffilename)
        assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
        refdata *= refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == refdata)
//  [python]
def test_pixfun_mul_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_mul_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == refdata * refdata)
//  [python]
def test_pixfun_mul_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_mul_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == refdata * refdata)
//  [python]
def test_pixfun_cmul_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_cmul_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == refdata * refdata.conj())
//  [python]
def test_pixfun_cmul_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_cmul_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == refdata * refdata.conj())
//  [python]
def test_pixfun_diff_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_diff_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cfloat64.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    assert numpy.alltrue(data == refdata1 - refdata2)
//  [python]
def test_pixfun_diff_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_diff_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cfloat64.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray(0, 0, 5, 6)

    assert numpy.all(data == refdata1 - refdata2)
//  [python]
def test_pixfun_inv_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_inv_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/uint16.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()
    refdata = refdata.astype('float64')

    assert numpy.alltrue(data == 1. / refdata)
//  [python]
def test_pixfun_inv_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_inv_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/uint16.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()
    refdata = refdata.astype('float64')

    assert numpy.all(data == 1. / refdata)
//  [python]
def test_pixfun_inv_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_inv_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()
    refdata = refdata.astype('complex')
    delta = data - 1. / refdata

    assert numpy.alltrue(abs(delta.real) < 1e-13)
    assert numpy.alltrue(abs(delta.imag) < 1e-13)
//  [python]
def test_pixfun_inv_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_inv_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()
    refdata = refdata.astype('complex')
    delta = data - 1. / refdata

    assert numpy.all(abs(delta.real) < 1e-13)
    assert numpy.all(abs(delta.imag) < 1e-13)
//  [python]
def test_pixfun_cmul_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_cmul_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/uint16.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray()
    refdata1 = refdata1.astype('float64')

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray()
    refdata2 = refdata2.astype('float64')

    assert numpy.alltrue(data == refdata1 * refdata2.conj())
//  [python]
def test_pixfun_cmul_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_cmul_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/uint16.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata1 = refds.GetRasterBand(1).ReadAsArray()
    refdata1 = refdata1.astype('float64')

    reffilename = 'data/int32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata2 = refds.GetRasterBand(1).ReadAsArray()
    refdata2 = refdata2.astype('float64')

    assert numpy.all(data == refdata1 * refdata2.conj())
//  [python]
def _is_on_simplex(v, s):
    if v.sum() < s + 1e-10 and np.alltrue(v > 0):
        return True
    return False
//  [python]
def _is_on_simplex(v, s):
    if v.sum() < s + 1e-10 and np.all(v > 0):
        return True
    return False
//  [python]
def test_pixfun_sqrt():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sqrt.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == numpy.sqrt(refdata))
//  [python]
def test_pixfun_sqrt():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_sqrt.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == numpy.sqrt(refdata))
//  [python]
def test_pixfun_intensity_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_intensity_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == (refdata * refdata.conj()).real)
//  [python]
def test_pixfun_intensity_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_intensity_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == (refdata * refdata.conj()).real)
//  [python]
def test_pixfun_intensity_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_intensity_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == (refdata * refdata.conj()).real)
//  [python]
def test_pixfun_intensity_c():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_intensity_c.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/cint_sar.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == (refdata * refdata.conj()).real)
//  [python]
def test_pixfun_log10_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_log10_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.alltrue(data == numpy.log10(refdata))
//  [python]
def test_pixfun_log10_r():

    if not numpy_available:
        pytest.skip()

    filename = 'data/pixfun_log10_r.vrt'
    ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
    assert ds is not None, ('Unable to open "%s" dataset.' % filename)
    data = ds.GetRasterBand(1).ReadAsArray()

    reffilename = 'data/float32.tif'
    refds = gdal.Open(reffilename)
    assert refds is not None, ('Unable to open "%s" dataset.' % reffilename)
    refdata = refds.GetRasterBand(1).ReadAsArray()

    assert numpy.all(data == numpy.log10(refdata))
//  [python]
def test_split_0_dim(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array([1, 3])
      a, b = xdl.split(value, num_or_size_splits, 0, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.alltrue(a == [[10, 20]]))
      self.assertTrue(np.alltrue(b == [[30, 40], [50, 60], [70, 80]]))
//  [python]
def test_split_0_dim(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array([1, 3])
      a, b = xdl.split(value, num_or_size_splits, 0, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.all(a == [[10, 20]]))
      self.assertTrue(np.all(b == [[30, 40], [50, 60], [70, 80]]))
//  [python]
def test_split_0_dim_x(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array(2)
      a, b = xdl.split(value, num_or_size_splits, 0, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.alltrue(a == [[10, 20], [30, 40]]))
      self.assertTrue(np.alltrue(b == [[50, 60], [70, 80]]))
//  [python]
def test_split_0_dim_x(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array(2)
      a, b = xdl.split(value, num_or_size_splits, 0, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.all(a == [[10, 20], [30, 40]]))
      self.assertTrue(np.all(b == [[50, 60], [70, 80]]))
//  [python]
def test_split_neg_dim(self):
      value = np.array([[10, 20, 1], [30, 40, 1], [50, 60, 1], [70, 80, 1]])
      num_or_size_splits = np.array([1, 2])
      a, b = xdl.split(value, num_or_size_splits, -1, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.alltrue(a == [[10], [30], [50], [70]]))
      self.assertTrue(np.alltrue(b == [[20, 1], [40, 1], [60, 1], [80, 1]]))
//  [python]
def test_split_neg_dim(self):
      value = np.array([[10, 20, 1], [30, 40, 1], [50, 60, 1], [70, 80, 1]])
      num_or_size_splits = np.array([1, 2])
      a, b = xdl.split(value, num_or_size_splits, -1, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.all(a == [[10], [30], [50], [70]]))
      self.assertTrue(np.all(b == [[20, 1], [40, 1], [60, 1], [80, 1]]))
//  [python]
def euclidean_proj_simplex(self, v, s=1):
        '''Compute the Euclidean projection on a positive simplex
        :param v: n-dimensional vector to project
        :param s: int, radius of the simple

        return w numpy array, Euclidean projection of v on the simplex

        Original author: John Duchi
        '''
        assert s>0, "Radius s must be positive (%d <= 0)" % s

        n, = v.shape # raise ValueError if v is not 1D
        # check if already on the simplex
        if v.sum() == s and np.alltrue( v>= 0):
            return v

        # get the array of cumulaive sums of a sorted copy of v
        u = np.sort(v)[::-1]
        cssv = np.cumsum(u)
        # get the number of >0 components of the optimal solution
        rho = np.nonzero(u * np.arange(1, n+1) > (cssv - s))[0][-1]
        # compute the Lagrange multiplier associated to the simplex constraint
        theta = (cssv[rho] - s) / (rho + 1.)
        w = (v-theta).clip(min=0)
        return w
//  [python]
def euclidean_proj_simplex(self, v, s=1):
        '''Compute the Euclidean projection on a positive simplex
        :param v: n-dimensional vector to project
        :param s: int, radius of the simple

        return w numpy array, Euclidean projection of v on the simplex

        Original author: John Duchi
        '''
        assert s>0, "Radius s must be positive (%d <= 0)" % s

        n, = v.shape # raise ValueError if v is not 1D
        # check if already on the simplex
        if v.sum() == s and np.all( v>= 0):
            return v

        # get the array of cumulaive sums of a sorted copy of v
        u = np.sort(v)[::-1]
        cssv = np.cumsum(u)
        # get the number of >0 components of the optimal solution
        rho = np.nonzero(u * np.arange(1, n+1) > (cssv - s))[0][-1]
        # compute the Lagrange multiplier associated to the simplex constraint
        theta = (cssv[rho] - s) / (rho + 1.)
        w = (v-theta).clip(min=0)
        return w
//  [python]
def test_split_neg_dim_x(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array(2)
      a, b = xdl.split(value, num_or_size_splits, -1, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.alltrue(a == [[10], [30], [50], [70]]))
      self.assertTrue(np.alltrue(b == [[20], [40], [60], [80]]))
//  [python]
def test_split_neg_dim_x(self):
      value = np.array([[10, 20], [30, 40], [50, 60], [70, 80]])
      num_or_size_splits = np.array(2)
      a, b = xdl.split(value, num_or_size_splits, -1, 2)
      a, b = xdl.execute([a, b])
      self.assertTrue(np.all(a == [[10], [30], [50], [70]]))
      self.assertTrue(np.all(b == [[20], [40], [60], [80]]))
//  [python]
def test_set_features(self):
        ds = self._random_data(num_samples=self.NUM_SAMPLES)
        self.assertEqual(self.NUM_SAMPLES, len(ds.x))
        ds_new = self._random_data(num_samples=self.NUM_SAMPLES)
        ds.x = ds_new.x

        self.assertEqual(len(ds.x), len(ds_new.x))
        tensor_pairs = zip([item for item in ds.x], [item for item in ds_new.x])
        is_equal = [torch.equal(first, second) for first, second in tensor_pairs]
        self.assertTrue(np.alltrue(is_equal))
//  [python]
def test_set_features(self):
        ds = self._random_data(num_samples=self.NUM_SAMPLES)
        self.assertEqual(self.NUM_SAMPLES, len(ds.x))
        ds_new = self._random_data(num_samples=self.NUM_SAMPLES)
        ds.x = ds_new.x

        self.assertEqual(len(ds.x), len(ds_new.x))
        tensor_pairs = zip([item for item in ds.x], [item for item in ds_new.x])
        is_equal = [torch.equal(first, second) for first, second in tensor_pairs]
        self.assertTrue(np.all(is_equal))
//  [python]
def test_graph_distances(self, make_graph, datastore):
        a = np.load(full_path("knn_distances.npy"))
        b = datastore.z[make_graph]["distances"][:]
        assert np.alltrue((a - b) < 1e-3)
//  [python]
def test_graph_distances(self, make_graph, datastore):
        a = np.load(full_path("knn_distances.npy"))
        b = datastore.z[make_graph]["distances"][:]
        assert np.all((a - b) < 1e-3)
//  [python]
def test_toy_crdir_metadata(self, toy_crdir_ds):
        assert np.alltrue(
            toy_crdir_ds.RNA.feats.fetch_all("ids") == ["g1", "g2", "g3", "g4"]
        )
        assert np.alltrue(toy_crdir_ds.ADT.feats.fetch_all("ids") == ["a1", "a2"])
        assert np.alltrue(toy_crdir_ds.HTO.feats.fetch_all("ids") == ["h1"])
        assert np.alltrue(toy_crdir_ds.cells.fetch_all("ids") == ["b1", "b2", "b3"])
//  [python]
def test_toy_crdir_metadata(self, toy_crdir_ds):
        assert np.all(
            toy_crdir_ds.RNA.feats.fetch_all("ids") == ["g1", "g2", "g3", "g4"]
        )
        assert np.all(toy_crdir_ds.ADT.feats.fetch_all("ids") == ["a1", "a2"])
        assert np.all(toy_crdir_ds.HTO.feats.fetch_all("ids") == ["h1"])
        assert np.all(toy_crdir_ds.cells.fetch_all("ids") == ["b1", "b2", "b3"])
//  [python]
def test_graph_weights(self, make_graph, datastore):
        a = np.load(full_path("knn_weights.npy"))
        b = datastore.z[make_graph]["graph__1.0__1.5"]["weights"][:]
        assert np.alltrue((a - b) < 1e-5)
//  [python]
def test_graph_weights(self, make_graph, datastore):
        a = np.load(full_path("knn_weights.npy"))
        b = datastore.z[make_graph]["graph__1.0__1.5"]["weights"][:]
        assert np.all((a - b) < 1e-5)
//  [python]
def test_toy_crdir_rawdata(self, toy_crdir_ds):
        assert np.alltrue(
            toy_crdir_ds.RNA.rawData.compute()
            == [[5, 0, 0, 2], [3, 3, 0, 7], [3, 3, 0, 7]]
        )
        assert np.alltrue(
            toy_crdir_ds.ADT.rawData.compute() == [[30, 40], [30, 50], [0, 50]]
        )
        assert np.alltrue(toy_crdir_ds.HTO.rawData.compute() == [[200], [100], [100]])
//  [python]
def test_toy_crdir_rawdata(self, toy_crdir_ds):
        assert np.all(
            toy_crdir_ds.RNA.rawData.compute()
            == [[5, 0, 0, 2], [3, 3, 0, 7], [3, 3, 0, 7]]
        )
        assert np.all(
            toy_crdir_ds.ADT.rawData.compute() == [[30, 40], [30, 50], [0, 50]]
        )
        assert np.all(toy_crdir_ds.HTO.rawData.compute() == [[200], [100], [100]])
//  [python]
def get_contour_groups(data_ranges, contours, data_files, row_ranges, name_column, x_column, y_column):
    contour_groups = []
    for data_range, data_file, row_range in zip(data_ranges, data_files, row_ranges):
        try:
            data_range[0][name_column], data_range[0][x_column], data_range[0][y_column]
        except:
            raise ValueError('Cannot find specified columns in data file "%s".'%data_file)
        contour_and_points = []
        for i, row in zip(row_range, data_range):
            if numpy.alltrue([r == None for r in row]):
                continue
            contour_name, x, y = row[name_column], row[x_column], row[y_column]
            if not contour_name:
                warn_tools.warn('Could not find contour name in otherwise non-empty row (file "%s", row %d).'%(data_file, i))
                continue
            if type(x) not in (int, float):
                warn_tools.warn('Cannot read numeric value from column %s in file "%s", row %d.'%(x_column, data_file, i))
                continue
            if type(y) not in (int, float):
                warn_tools.warn('Cannot read numeric value from column %s in file "%s", row %d.'%(y_column, data_file, i))
                continue    
            try:
                contour = contours[contour_name]
            except:
                raise ValueError('Cannot find contour file with name "%s" (referenced in file "%s", row %d).'%(contour_name, data_file, i))
            contour_and_points.append((contour, (x, y)))
        contour_groups.append(contour_and_points)
    return contour_groups
//  [python]
def get_contour_groups(data_ranges, contours, data_files, row_ranges, name_column, x_column, y_column):
    contour_groups = []
    for data_range, data_file, row_range in zip(data_ranges, data_files, row_ranges):
        try:
            data_range[0][name_column], data_range[0][x_column], data_range[0][y_column]
        except:
            raise ValueError('Cannot find specified columns in data file "%s".'%data_file)
        contour_and_points = []
        for i, row in zip(row_range, data_range):
            if numpy.all([r == None for r in row]):
                continue
            contour_name, x, y = row[name_column], row[x_column], row[y_column]
            if not contour_name:
                warn_tools.warn('Could not find contour name in otherwise non-empty row (file "%s", row %d).'%(data_file, i))
                continue
            if type(x) not in (int, float):
                warn_tools.warn('Cannot read numeric value from column %s in file "%s", row %d.'%(x_column, data_file, i))
                continue
            if type(y) not in (int, float):
                warn_tools.warn('Cannot read numeric value from column %s in file "%s", row %d.'%(y_column, data_file, i))
                continue    
            try:
                contour = contours[contour_name]
            except:
                raise ValueError('Cannot find contour file with name "%s" (referenced in file "%s", row %d).'%(contour_name, data_file, i))
            contour_and_points.append((contour, (x, y)))
        contour_groups.append(contour_and_points)
    return contour_groups
//  [python]
ort_session = onnxruntime.InferenceSession("test.onnx")
ort_inputs = {"input": numpy.ones([5], dtype=numpy.float32)}
ort_outs = ort_session.run(None, ort_inputs)
print(ort_outs)

assert numpy.alltrue(ort_outs[0] == numpy.arange(5))
//  [python]
ort_session = onnxruntime.InferenceSession("test.onnx")
ort_inputs = {"input": numpy.ones([5], dtype=numpy.float32)}
ort_outs = ort_session.run(None, ort_inputs)
print(ort_outs)

assert numpy.all(ort_outs[0] == numpy.arange(5))
//  [python]
def pca_fast(trn, tst=None, frac=0.0, centered=False):
    '''
    '''
    
    if not centered: 
        trn -= trn.mean(0)
    if trn.shape[1] <= trn.shape[0]:
        #C = numpy.cov(trn)
        #C = numpy.dot(trn.transpose(), trn)
        C = core_utility.fastdot_t1(trn, trn, None, 1.0/trn.shape[0])
    else:
        C = core_utility.fastdot_t2(trn, trn, None, 1.0/trn.shape[0])
        #C = numpy.dot(trn, trn.T)
        #numpy.multiply(C, 1.0/trn.shape[0], C)
    assert(numpy.alltrue(numpy.isfinite(C)))
    d, V = numpy.linalg.eigh(C)
    
    if trn.shape[1] > trn.shape[0]:
        #V = numpy.dot(trn.T, V)
        V = numpy.ascontiguousarray(V)
        assert(numpy.alltrue(numpy.isfinite(V)))
        V = core_utility.fastdot_t1(trn, V)
        
        err = numpy.seterr(divide='ignore', invalid='ignore')
        d = 1.0/numpy.sqrt(d)
        numpy.seterr(**err)
        d = numpy.where(numpy.isfinite(d), d, 0)
        V *= d
        assert(numpy.alltrue(numpy.isfinite(V)))
    d = numpy.where(d < 0, 0, d)
    tot = d.sum()
    if tot != 0.0: d /= tot
    idx = d.argsort()[::-1]
    d = d[idx]
    V = V[:, idx]
    
    if tst is not None:
        tst -= tst.mean(0)
        if frac >= 1:
            idx = int(frac)
        elif frac == 0.0:
            idx = d.shape[0]
        else:
            idx = numpy.sum(d.cumsum()<frac)+1
        #print V.dtype, tst.dtype
        val = core_utility.fastdot_t2(V[:, :idx].transpose().copy(), tst.astype(V.dtype)).T
        #val = numpy.dot(V[:, :idx].T, tst.T).T
        return V, d, val
    return V, d
//  [python]
def pca_fast(trn, tst=None, frac=0.0, centered=False):
    '''
    '''
    
    if not centered: 
        trn -= trn.mean(0)
    if trn.shape[1] <= trn.shape[0]:
        #C = numpy.cov(trn)
        #C = numpy.dot(trn.transpose(), trn)
        C = core_utility.fastdot_t1(trn, trn, None, 1.0/trn.shape[0])
    else:
        C = core_utility.fastdot_t2(trn, trn, None, 1.0/trn.shape[0])
        #C = numpy.dot(trn, trn.T)
        #numpy.multiply(C, 1.0/trn.shape[0], C)
    assert(numpy.all(numpy.isfinite(C)))
    d, V = numpy.linalg.eigh(C)
    
    if trn.shape[1] > trn.shape[0]:
        #V = numpy.dot(trn.T, V)
        V = numpy.ascontiguousarray(V)
        assert(numpy.all(numpy.isfinite(V)))
        V = core_utility.fastdot_t1(trn, V)
        
        err = numpy.seterr(divide='ignore', invalid='ignore')
        d = 1.0/numpy.sqrt(d)
        numpy.seterr(**err)
        d = numpy.where(numpy.isfinite(d), d, 0)
        V *= d
        assert(numpy.all(numpy.isfinite(V)))
    d = numpy.where(d < 0, 0, d)
    tot = d.sum()
    if tot != 0.0: d /= tot
    idx = d.argsort()[::-1]
    d = d[idx]
    V = V[:, idx]
    
    if tst is not None:
        tst -= tst.mean(0)
        if frac >= 1:
            idx = int(frac)
        elif frac == 0.0:
            idx = d.shape[0]
        else:
            idx = numpy.sum(d.cumsum()<frac)+1
        #print V.dtype, tst.dtype
        val = core_utility.fastdot_t2(V[:, :idx].transpose().copy(), tst.astype(V.dtype)).T
        #val = numpy.dot(V[:, :idx].T, tst.T).T
        return V, d, val
    return V, d
//  [python]
def test_run_pseudotime_marker_search(self, pseudotime_markers):
        precalc_markers = pd.read_csv(
            full_path("pseudotime_markers_r_values.csv"), index_col=0
        )
        assert np.alltrue(precalc_markers.index == pseudotime_markers.index)
        assert np.alltrue(
            precalc_markers.names.values == pseudotime_markers.names.values
        )
        assert np.allclose(
            precalc_markers.I__RNA_pseudotime__r.values,
            pseudotime_markers.I__RNA_pseudotime__r.values,
        )
//  [python]
def test_run_pseudotime_marker_search(self, pseudotime_markers):
        precalc_markers = pd.read_csv(
            full_path("pseudotime_markers_r_values.csv"), index_col=0
        )
        assert np.all(precalc_markers.index == pseudotime_markers.index)
        assert np.all(
            precalc_markers.names.values == pseudotime_markers.names.values
        )
        assert np.allclose(
            precalc_markers.I__RNA_pseudotime__r.values,
            pseudotime_markers.I__RNA_pseudotime__r.values,
        )
//  [python]
def test_set_features(self):
        ds = self._random_data(num_samples=self.NUM_SAMPLES)
        self.assertEqual(self.NUM_SAMPLES, len(ds.x))
        ds_new = self._random_data(num_samples=self.NUM_SAMPLES)
        ds.x = ds_new.x

        self.assertEqual(len(ds.x), len(ds_new.x))
        tensor_pairs = zip([item for item in ds.x], [item for item in ds_new.x])
        is_equal = [torch.equal(first, second)
                    for first, second in tensor_pairs]
        self.assertTrue(np.alltrue(is_equal))
//  [python]
def test_set_features(self):
        ds = self._random_data(num_samples=self.NUM_SAMPLES)
        self.assertEqual(self.NUM_SAMPLES, len(ds.x))
        ds_new = self._random_data(num_samples=self.NUM_SAMPLES)
        ds.x = ds_new.x

        self.assertEqual(len(ds.x), len(ds_new.x))
        tensor_pairs = zip([item for item in ds.x], [item for item in ds_new.x])
        is_equal = [torch.equal(first, second)
                    for first, second in tensor_pairs]
        self.assertTrue(np.all(is_equal))
//  [python]
def validate_outcome_length(outcomes):
    """
    Validates that all outcomes have the same length.

    """
    # Make sure each outcome is a container.
    try:
        lengths = list(map(len, outcomes))
    except TypeError:
        raise ditException('One or more outcomes is not a container.')
    else:
        outcome_length = lengths[0]

    # Make sure each outcome has the same length.
    equal_lengths = np.alltrue(np.equal(lengths, outcome_length))
    if not equal_lengths:
        raise ditException('Not all outcomes have the same length.')
    else:
        return True
//  [python]
def validate_outcome_length(outcomes):
    """
    Validates that all outcomes have the same length.

    """
    # Make sure each outcome is a container.
    try:
        lengths = list(map(len, outcomes))
    except TypeError:
        raise ditException('One or more outcomes is not a container.')
    else:
        outcome_length = lengths[0]

    # Make sure each outcome has the same length.
    equal_lengths = np.all(np.equal(lengths, outcome_length))
    if not equal_lengths:
        raise ditException('Not all outcomes have the same length.')
    else:
        return True
//  [python]
def test_dm_1__simulation_1(n_qubits, n_gates):
    from hybridq.circuit.simulation.utils import prepare_state
    from hybridq.dm.gate import KrausSuperGate
    from scipy.linalg import eigvalsh

    # Get RQC
    circuit = _get_rqc_unitary(n_qubits, n_gates)

    # Get random initial state
    initial_state = ''.join(np.random.choice(list('01+-'), size=n_qubits))

    # Get state by using state evolution
    psi_1 = simulation.simulate(circuit,
                                initial_state=initial_state,
                                verbose=True)

    # Get density matrix
    rho_1 = dm_simulation.simulate(circuit,
                                   initial_state=initial_state,
                                   verbose=True)

    # Get matrix
    _rho_1 = np.reshape(rho_1, (2**n_qubits, 2**n_qubits))

    # Density matrix should be hermitian
    assert_allclose(_rho_1, _rho_1.conj().T)

    # Density matrix should be idempotent
    assert_allclose(_rho_1, _rho_1 @ _rho_1)

    # Density matrix^2 should have trace == 1
    assert (np.isclose(np.trace(_rho_1 @ _rho_1), 1, atol=_atol))

    # Density matrix should be semi-positive definite
    assert (np.alltrue(np.round(eigvalsh(_rho_1), 5) >= 0))

    # Checks
    assert_allclose(np.kron(psi_1.ravel(), psi_1.ravel().conj()), rho_1.ravel())
//  [python]
def test_dm_1__simulation_1(n_qubits, n_gates):
    from hybridq.circuit.simulation.utils import prepare_state
    from hybridq.dm.gate import KrausSuperGate
    from scipy.linalg import eigvalsh

    # Get RQC
    circuit = _get_rqc_unitary(n_qubits, n_gates)

    # Get random initial state
    initial_state = ''.join(np.random.choice(list('01+-'), size=n_qubits))

    # Get state by using state evolution
    psi_1 = simulation.simulate(circuit,
                                initial_state=initial_state,
                                verbose=True)

    # Get density matrix
    rho_1 = dm_simulation.simulate(circuit,
                                   initial_state=initial_state,
                                   verbose=True)

    # Get matrix
    _rho_1 = np.reshape(rho_1, (2**n_qubits, 2**n_qubits))

    # Density matrix should be hermitian
    assert_allclose(_rho_1, _rho_1.conj().T)

    # Density matrix should be idempotent
    assert_allclose(_rho_1, _rho_1 @ _rho_1)

    # Density matrix^2 should have trace == 1
    assert (np.isclose(np.trace(_rho_1 @ _rho_1), 1, atol=_atol))

    # Density matrix should be semi-positive definite
    assert (np.all(np.round(eigvalsh(_rho_1), 5) >= 0))

    # Checks
    assert_allclose(np.kron(psi_1.ravel(), psi_1.ravel().conj()), rho_1.ravel())
//  [python]
def test_utils__transpose(t, n, backend):
    # Get random vector
    v = np.reshape(np.random.randint(2**32 - 1, size=2**n).astype(t), (2,) * n)
    v0 = np.array(v)
    v1 = np.array(v)
    v2 = np.array(v)

    # Get random orders
    o_1 = np.random.permutation(range(n))
    o_2 = np.concatenate(
        (np.arange(n - 6), n - 6 + np.random.permutation(range(6))))

    # Get transposition
    to_1 = transpose(v0, o_1, raise_if_hcore_fails=True,
                     backend=backend).flatten()
    to_2 = transpose(v0, o_2, raise_if_hcore_fails=True,
                     backend=backend).flatten()
    v1 = transpose(v1,
                   o_1,
                   raise_if_hcore_fails=True,
                   inplace=True,
                   backend=backend)
    v2 = transpose(v2,
                   o_2,
                   raise_if_hcore_fails=True,
                   inplace=True,
                   backend=backend)

    # Check transposition
    assert (np.alltrue(v == v0))
    assert (np.alltrue(np.transpose(v, o_1).flatten() == to_1))
    assert (np.alltrue(np.transpose(v, o_2).flatten() == to_2))
    assert (np.alltrue(to_1 == v1.flatten()))
    assert (np.alltrue(to_2 == v2.flatten()))
    assert (np.alltrue(transpose(v, o_1, force_numpy=True).flatten() == to_1))
    assert (np.alltrue(transpose(v, o_2, force_numpy=True).flatten() == to_2))
//  [python]
def test_utils__transpose(t, n, backend):
    # Get random vector
    v = np.reshape(np.random.randint(2**32 - 1, size=2**n).astype(t), (2,) * n)
    v0 = np.array(v)
    v1 = np.array(v)
    v2 = np.array(v)

    # Get random orders
    o_1 = np.random.permutation(range(n))
    o_2 = np.concatenate(
        (np.arange(n - 6), n - 6 + np.random.permutation(range(6))))

    # Get transposition
    to_1 = transpose(v0, o_1, raise_if_hcore_fails=True,
                     backend=backend).flatten()
    to_2 = transpose(v0, o_2, raise_if_hcore_fails=True,
                     backend=backend).flatten()
    v1 = transpose(v1,
                   o_1,
                   raise_if_hcore_fails=True,
                   inplace=True,
                   backend=backend)
    v2 = transpose(v2,
                   o_2,
                   raise_if_hcore_fails=True,
                   inplace=True,
                   backend=backend)

    # Check transposition
    assert (np.all(v == v0))
    assert (np.all(np.transpose(v, o_1).flatten() == to_1))
    assert (np.all(np.transpose(v, o_2).flatten() == to_2))
    assert (np.all(to_1 == v1.flatten()))
    assert (np.all(to_2 == v2.flatten()))
    assert (np.all(transpose(v, o_1, force_numpy=True).flatten() == to_1))
    assert (np.all(transpose(v, o_2, force_numpy=True).flatten() == to_2))
//  [python]
def test_utils__sort_argsort(dummy):
    _n_floats = np.random.randint(1000)
    _n_ints = np.random.randint(1000)
    _n_tuples = np.random.randint(1000)
    _n_strings = np.random.randint(1000)

    # Add floats
    _array = (10000 * np.random.random(size=_n_floats)).tolist()

    # Add integers
    _array += np.random.randint(10000, size=_n_ints).tolist()

    # Add tuples
    _array += [tuple(x) for x in np.random.random(size=(_n_tuples, 2))]

    # Add strings
    _array += [
        ''.join(map(get_symbol, np.random.randint(1000, size=30)))
        for _ in range(_n_strings)
    ]

    # Random permutation
    _array = np.random.permutation(np.array(_array, dtype='object')).tolist()

    # Sort
    _sorted_array = sort(_array)

    # Check
    for _t in [float, tuple, str]:
        # Check array is sorted properly by type
        assert (sorted(filter(lambda x: _type(x) == _t, _array)) == list(
            filter(lambda x: _type(x) == _t, _sorted_array)))

        # Check that object of the same type are consecutive
        assert (np.alltrue(
            np.unique(
                np.diff(
                    list(
                        map(
                            lambda x: x[0],
                            filter(lambda x: _type(x[1]) == _t,
                                   enumerate(_sorted_array)))))) == [1]))

    # Check that argsort works properly
    assert (sort(_array) == [_array[i] for i in argsort(_array)])
    assert (sort(_array, reverse=True) == [
        _array[i] for i in argsort(_array, reverse=True)
    ])
//  [python]
def test_utils__sort_argsort(dummy):
    _n_floats = np.random.randint(1000)
    _n_ints = np.random.randint(1000)
    _n_tuples = np.random.randint(1000)
    _n_strings = np.random.randint(1000)

    # Add floats
    _array = (10000 * np.random.random(size=_n_floats)).tolist()

    # Add integers
    _array += np.random.randint(10000, size=_n_ints).tolist()

    # Add tuples
    _array += [tuple(x) for x in np.random.random(size=(_n_tuples, 2))]

    # Add strings
    _array += [
        ''.join(map(get_symbol, np.random.randint(1000, size=30)))
        for _ in range(_n_strings)
    ]

    # Random permutation
    _array = np.random.permutation(np.array(_array, dtype='object')).tolist()

    # Sort
    _sorted_array = sort(_array)

    # Check
    for _t in [float, tuple, str]:
        # Check array is sorted properly by type
        assert (sorted(filter(lambda x: _type(x) == _t, _array)) == list(
            filter(lambda x: _type(x) == _t, _sorted_array)))

        # Check that object of the same type are consecutive
        assert (np.all(
            np.unique(
                np.diff(
                    list(
                        map(
                            lambda x: x[0],
                            filter(lambda x: _type(x[1]) == _t,
                                   enumerate(_sorted_array)))))) == [1]))

    # Check that argsort works properly
    assert (sort(_array) == [_array[i] for i in argsort(_array)])
    assert (sort(_array, reverse=True) == [
        _array[i] for i in argsort(_array, reverse=True)
    ])
//  [python]
def test_dm_3__simulation_3(n_qubits, n_gates):
    from hybridq.gate.measure import _Measure
    from scipy.linalg import eigvalsh
    from string import ascii_letters

    # Get RQC
    circuit = _get_rqc_unitary(n_qubits, n_gates)

    # Get random initial state
    initial_state = ''.join(np.random.choice(list('01+-'), size=n_qubits))

    # Get indexes for open qubits
    index_open_qubits = sorted(np.random.choice(n_qubits, size=2,
                                                replace=False))

    # Get final state, including the right projections
    final_state = ''.join('.' if i in index_open_qubits else c
                          for i, c in enumerate(ascii_letters[:n_qubits]))
    final_state += final_state

    # Get state by using state evolution
    psi_1 = simulation.simulate(circuit,
                                initial_state=initial_state,
                                verbose=True)

    # Get the expectation value using tensor contraction
    rho_1 = dm_simulation.simulate(circuit,
                                   initial_state=initial_state,
                                   final_state=final_state,
                                   optimize='tn',
                                   verbose=True)

    # Get matrix
    _rho_1 = np.reshape(rho_1, (2**len(index_open_qubits),) * 2)

    # Density matrix should be hermitian
    assert_allclose(_rho_1, _rho_1.conj().T)

    # Density matrix should be semi-positive definite
    assert (np.alltrue(np.round(eigvalsh(_rho_1), 5) >= 0))

    # Trace qubits using einsum
    _rho = np.einsum(
        ''.join(ascii_letters[i] for i in range(n_qubits)) + ',' +
        ''.join(ascii_letters[i + n_qubits if i in index_open_qubits else i]
                for i in range(n_qubits)), psi_1, psi_1.conj())

    # Check
    assert_allclose(_rho, rho_1)

    # Get probabilities of the projected states
    probs = _Measure(psi_1, axes=index_open_qubits, get_probs_only=True)

    # Check normalization
    assert (np.isclose(np.sum(probs), 1, atol=_atol))

    # Check
    assert_allclose(np.diag(_rho_1), probs)