jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def inherit_parameter(self, A, B, C, D):
        from sklearn.cluster import KMeans
        assert numpy.shape(A) == self.output_shape and \
                numpy.shape(B) == self.output_shape and \
                numpy.shape(C) == self.output_shape and \
                numpy.shape(D) == self.output_shape, "shapes of the inherited parameters do not match"
        params_ABCD = numpy.reshape(numpy.asarray([A,B,C,D], dtype="float32"), (4, numpy.product(self.output_shape)))
        params_ABCD = numpy.transpose(params_ABCD)
        self.kmeans = KMeans(n_clusters=self.n_clusters, random_state=10)
        self.kmeans.fit(params_ABCD)
        hash_map = numpy.reshape(numpy.copy(self.kmeans.labels_), self.output_shape)
        self.set_parameter("Cluster", self.kmeans.cluster_centers_)
        self.set_parameter("hash_map", hash_map, is_static=True)
//  [python]
def inherit_parameter(self, A, B, C, D):
        from sklearn.cluster import KMeans
        assert numpy.shape(A) == self.output_shape and \
                numpy.shape(B) == self.output_shape and \
                numpy.shape(C) == self.output_shape and \
                numpy.shape(D) == self.output_shape, "shapes of the inherited parameters do not match"
        params_ABCD = numpy.reshape(numpy.asarray([A,B,C,D], dtype="float32"), (4, numpy.prod(self.output_shape)))
        params_ABCD = numpy.transpose(params_ABCD)
        self.kmeans = KMeans(n_clusters=self.n_clusters, random_state=10)
        self.kmeans.fit(params_ABCD)
        hash_map = numpy.reshape(numpy.copy(self.kmeans.labels_), self.output_shape)
        self.set_parameter("Cluster", self.kmeans.cluster_centers_)
        self.set_parameter("hash_map", hash_map, is_static=True)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args or self.static):
            return numpy.copy(self.memory)

        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        whts = self.evo_path()
        eta = self.parameter("\eta") + 10.0
        eta = 0.50 * eta / (numpy.abs(eta) + 1) + 0.50
        alpha = 0.001
        n_whts = eta * numpy.outer(post_syn, pre_syn) + (1 - eta) * whts

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += alpha * numpy.outer(mod, pre_unit) * n_whts
            elif(numpy.product(mod.shape)==1):
                self.memory += alpha * kw_args["modulator"] * n_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += alpha * n_whts 
        self.memory = numpy.clip(self.memory, -5.0, 5.0)
        self.evo_path(n_whts)

        return numpy.copy(self.memory)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args or self.static):
            return numpy.copy(self.memory)

        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        whts = self.evo_path()
        eta = self.parameter("\eta") + 10.0
        eta = 0.50 * eta / (numpy.abs(eta) + 1) + 0.50
        alpha = 0.001
        n_whts = eta * numpy.outer(post_syn, pre_syn) + (1 - eta) * whts

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += alpha * numpy.outer(mod, pre_unit) * n_whts
            elif(numpy.prod(mod.shape)==1):
                self.memory += alpha * kw_args["modulator"] * n_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += alpha * n_whts 
        self.memory = numpy.clip(self.memory, -5.0, 5.0)
        self.evo_path(n_whts)

        return numpy.copy(self.memory)
//  [python]
def test_imread_masked():
    filename = _locate_test_image('test_box_shadow.png')

    gray = qimage2ndarray.imread(filename, masked = True)

    assert 200 < gray.max() <= 255

    assert numpy.ndim(gray) == 2

    assert gray.shape == (50, 111)

    assert numpy.ma.is_masked(gray)

    masked_count = gray.mask.sum()
    assert 0 < masked_count < numpy.product(gray.shape)
    assert masked_count == 1464
//  [python]
def test_imread_masked():
    filename = _locate_test_image('test_box_shadow.png')

    gray = qimage2ndarray.imread(filename, masked = True)

    assert 200 < gray.max() <= 255

    assert numpy.ndim(gray) == 2

    assert gray.shape == (50, 111)

    assert numpy.ma.is_masked(gray)

    masked_count = gray.mask.sum()
    assert 0 < masked_count < numpy.prod(gray.shape)
    assert masked_count == 1464
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        n_whts = (numpy.outer(post_syn, pre_syn) * self.p_a
                + numpy.outer(post_syn, pre_unit) * self.p_b
                + numpy.outer(post_unit, pre_syn) * self.p_c
                + numpy.outer(post_unit, pre_unit) * self.p_d)

        #whts = self.evo_path()
        #eta = self.parameter("\eta")
        #n_whts = eta * deta + (1 - eta) * whts

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                f_mod = numpy.repeat(numpy.expand(mod, axis=1), repeats=self.d_x, axis=1)
                self.memory += 0.20 * f_mod * n_whts
            elif(numpy.product(mod.shape)==1):
                self.memory += 0.20 * mod * n_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += n_whts 
        #self.decay_over_boundary(0.05, [-5.0, 5.0])

        return numpy.copy(self.memory)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        n_whts = (numpy.outer(post_syn, pre_syn) * self.p_a
                + numpy.outer(post_syn, pre_unit) * self.p_b
                + numpy.outer(post_unit, pre_syn) * self.p_c
                + numpy.outer(post_unit, pre_unit) * self.p_d)

        #whts = self.evo_path()
        #eta = self.parameter("\eta")
        #n_whts = eta * deta + (1 - eta) * whts

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                f_mod = numpy.repeat(numpy.expand(mod, axis=1), repeats=self.d_x, axis=1)
                self.memory += 0.20 * f_mod * n_whts
            elif(numpy.prod(mod.shape)==1):
                self.memory += 0.20 * mod * n_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += n_whts 
        #self.decay_over_boundary(0.05, [-5.0, 5.0])

        return numpy.copy(self.memory)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        deta_whts = 0.05 * (numpy.outer(post_syn, pre_syn) * self._para_A
                + numpy.outer(post_syn, pre_unit) * self._para_B
                + numpy.outer(post_unit, pre_syn) * self._para_C
                + numpy.outer(post_unit, pre_unit) * self._para_D)

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += numpy.outer(mod, pre_unit) * deta_whts
            elif(numpy.product(mod.shape)==1):
                self.memory += mod * deta_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += deta_whts 

        return numpy.copy(self.memory)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        deta_whts = 0.05 * (numpy.outer(post_syn, pre_syn) * self._para_A
                + numpy.outer(post_syn, pre_unit) * self._para_B
                + numpy.outer(post_unit, pre_syn) * self._para_C
                + numpy.outer(post_unit, pre_unit) * self._para_D)

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += numpy.outer(mod, pre_unit) * deta_whts
            elif(numpy.prod(mod.shape)==1):
                self.memory += mod * deta_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += deta_whts 

        return numpy.copy(self.memory)
//  [python]
def get_surface(self, dest_surf=None):
        camera = self.camera
        im = highgui.cvQueryFrame(camera)
        #convert Ipl image to PIL image
        if not im:
            return None
        xx = opencv.adaptors.Ipl2NumPy(im)
        xxx = numpy.reshape(xx, (numpy.product(xx.shape),))
        if xx.shape[2] != 3:
            raise ValueError("not sure what to do about this size")
        pg_img = pygame.image.frombuffer(xxx, (xx.shape[1], xx.shape[0]), "RGB")
        # if there is a destination surface given, we blit onto that.
        if dest_surf:
            dest_surf.blit(pg_img, (0, 0))
        return dest_surf
//  [python]
def get_surface(self, dest_surf=None):
        camera = self.camera
        im = highgui.cvQueryFrame(camera)
        #convert Ipl image to PIL image
        if not im:
            return None
        xx = opencv.adaptors.Ipl2NumPy(im)
        xxx = numpy.reshape(xx, (numpy.prod(xx.shape),))
        if xx.shape[2] != 3:
            raise ValueError("not sure what to do about this size")
        pg_img = pygame.image.frombuffer(xxx, (xx.shape[1], xx.shape[0]), "RGB")
        # if there is a destination surface given, we blit onto that.
        if dest_surf:
            dest_surf.blit(pg_img, (0, 0))
        return dest_surf
//  [python]
def lhsFromDensity(kde,siz=100):
    """
    LHS sampling from a variable's Kernel density estimate.

    :Parameters:
        - `kde`: scipy.stats.kde.gaussian_kde object
        - `siz`: Number or shape tuple for the output sample
    """
    if not isinstance(kde,scipy.stats.kde.gaussian_kde):
        raise TypeError("kde is not a density object")
    if isinstance(siz,(tuple,list)):
        n=numpy.product(siz)
    s = kde.resample(n)
    v = lhsFromSample(s,n)
    if isinstance(siz,(tuple,list)):
        v.shape = siz
    return v
//  [python]
def lhsFromDensity(kde,siz=100):
    """
    LHS sampling from a variable's Kernel density estimate.

    :Parameters:
        - `kde`: scipy.stats.kde.gaussian_kde object
        - `siz`: Number or shape tuple for the output sample
    """
    if not isinstance(kde,scipy.stats.kde.gaussian_kde):
        raise TypeError("kde is not a density object")
    if isinstance(siz,(tuple,list)):
        n=numpy.prod(siz)
    s = kde.resample(n)
    v = lhsFromSample(s,n)
    if isinstance(siz,(tuple,list)):
        v.shape = siz
    return v
//  [python]
def lhsFromSample(sample,siz=100):
    """
    Latin Hypercube Sample from a set of values.
    For univariate distributions only

    :Parameters:
        - `sample`: list, tuple of array
        - `siz`: Number or shape tuple for the output sample
    """
    #TODO: add support to correlation restricted multivariate samples
    if not isinstance(sample, (list,tuple,numpy.ndarray)):
        raise TypeError('sample is not a list, tuple or numpy vector')
    n = siz
    if isinstance(siz,(tuple,list)):
        n=numpy.product(siz)
    perc = numpy.arange(0,100.,100./n)
    shuffle(perc)
    smp = [stats.uniform(i,100./n).rvs() for i in perc]
    v = numpy.array([stats.scoreatpercentile(sample,p) for p in smp])
    if isinstance(siz,(tuple,list)):
        v.shape = siz
    return v
//  [python]
def lhsFromSample(sample,siz=100):
    """
    Latin Hypercube Sample from a set of values.
    For univariate distributions only

    :Parameters:
        - `sample`: list, tuple of array
        - `siz`: Number or shape tuple for the output sample
    """
    #TODO: add support to correlation restricted multivariate samples
    if not isinstance(sample, (list,tuple,numpy.ndarray)):
        raise TypeError('sample is not a list, tuple or numpy vector')
    n = siz
    if isinstance(siz,(tuple,list)):
        n=numpy.prod(siz)
    perc = numpy.arange(0,100.,100./n)
    shuffle(perc)
    smp = [stats.uniform(i,100./n).rvs() for i in perc]
    v = numpy.array([stats.scoreatpercentile(sample,p) for p in smp])
    if isinstance(siz,(tuple,list)):
        v.shape = siz
    return v
//  [python]
def test_testAddSumProd (self):
        "Test add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue (eq(numpy.add.reduce(x), add.reduce(x)))
        self.assertTrue (eq(numpy.add.accumulate(x), add.accumulate(x)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(numpy.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue (eq(numpy.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue (eq(numpy.sum(x, 0), sum(x, 0)))
        self.assertTrue (eq(numpy.product(x, axis=0), product(x, axis=0)))
        self.assertTrue (eq(numpy.product(x, 0), product(x, 0)))
        self.assertTrue (eq(numpy.product(filled(xm, 1), axis=0),
                            product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue (eq(numpy.concatenate((x, y), 1),
                                concatenate((xm, ym), 1)))
            self.assertTrue (eq(numpy.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue (eq(numpy.sum(x, 1), sum(x, 1)))
            self.assertTrue (eq(numpy.product(x, 1), product(x, 1)))
//  [python]
def test_testAddSumProd (self):
        "Test add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue (eq(numpy.add.reduce(x), add.reduce(x)))
        self.assertTrue (eq(numpy.add.accumulate(x), add.accumulate(x)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(numpy.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue (eq(numpy.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue (eq(numpy.sum(x, 0), sum(x, 0)))
        self.assertTrue (eq(numpy.prod(x, axis=0), product(x, axis=0)))
        self.assertTrue (eq(numpy.prod(x, 0), product(x, 0)))
        self.assertTrue (eq(numpy.prod(filled(xm, 1), axis=0),
                            product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue (eq(numpy.concatenate((x, y), 1),
                                concatenate((xm, ym), 1)))
            self.assertTrue (eq(numpy.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue (eq(numpy.sum(x, 1), sum(x, 1)))
            self.assertTrue (eq(numpy.prod(x, 1), product(x, 1)))
//  [python]
def assign_conv2d_from_checkpoint_fn(variable_name, checkpoint_name, checkpoint_tensor_name):
    '''
    Like slim.assign_from_checkpoint_fn, this returns a function that needs to be run in your session (ie f(sess)). This assignment will allow the conv2d kernel shapes to be different. Only the parts that overlap will be copied and non-overlapping parts will be set to zero. The spatial dimensions will be centered so that a bigger/smaller kernel will crop/expand from the center. The feature dimensions will be packed in the lower indices.
    '''
    # variable_name='xception_65/entry_flow/conv1_1/weights:0'
    # checkpoint_name='deeplabv3_pascal_train_aug/model.ckpt'
    # checkpoint_tensor_name='xception_65/entry_flow/conv1_1/weights'
    model_vars = slim.get_model_variables()
    dest = next(x for x in model_vars if x.name ==
                variable_name)  # tf.Variable
    src = tf.contrib.framework.load_variable(
        checkpoint_name, checkpoint_tensor_name)  # numpy.ndarray

    if FLAGS.input_kernel_filler == 'gaussian':
        # Gaussian init
        n = numpy.array(dest.get_shape().as_list())
        #print(n)
        init_data = numpy.random.randn(numpy.product(n)) * numpy.sqrt(2.0 / numpy.product(n))
        init_data = init_data.reshape(n).astype(dest.dtype.as_numpy_dtype)
        #print (init_data.shape)
    elif FLAGS.input_kernel_filler == 'zeros':
        # Zero init
        init_data = None
    else:
        raise Exception("Unknown filler type: {}".format(FLAGS.input_kernel_filler))

    op = partial_assign_variable_op(dest=dest,
                                    src=src,
                                    gravity=(0, 0, -1, -1),
                                    data=init_data)

    def f(sess):
        sess.run(op)
    return f
//  [python]
def assign_conv2d_from_checkpoint_fn(variable_name, checkpoint_name, checkpoint_tensor_name):
    '''
    Like slim.assign_from_checkpoint_fn, this returns a function that needs to be run in your session (ie f(sess)). This assignment will allow the conv2d kernel shapes to be different. Only the parts that overlap will be copied and non-overlapping parts will be set to zero. The spatial dimensions will be centered so that a bigger/smaller kernel will crop/expand from the center. The feature dimensions will be packed in the lower indices.
    '''
    # variable_name='xception_65/entry_flow/conv1_1/weights:0'
    # checkpoint_name='deeplabv3_pascal_train_aug/model.ckpt'
    # checkpoint_tensor_name='xception_65/entry_flow/conv1_1/weights'
    model_vars = slim.get_model_variables()
    dest = next(x for x in model_vars if x.name ==
                variable_name)  # tf.Variable
    src = tf.contrib.framework.load_variable(
        checkpoint_name, checkpoint_tensor_name)  # numpy.ndarray

    if FLAGS.input_kernel_filler == 'gaussian':
        # Gaussian init
        n = numpy.array(dest.get_shape().as_list())
        #print(n)
        init_data = numpy.random.randn(numpy.prod(n)) * numpy.sqrt(2.0 / numpy.prod(n))
        init_data = init_data.reshape(n).astype(dest.dtype.as_numpy_dtype)
        #print (init_data.shape)
    elif FLAGS.input_kernel_filler == 'zeros':
        # Zero init
        init_data = None
    else:
        raise Exception("Unknown filler type: {}".format(FLAGS.input_kernel_filler))

    op = partial_assign_variable_op(dest=dest,
                                    src=src,
                                    gravity=(0, 0, -1, -1),
                                    data=init_data)

    def f(sess):
        sess.run(op)
    return f
//  [python]
def _logsum(matrix):
    if len(matrix.shape) > 1:
        vec = numpy.reshape(matrix, (numpy.product(matrix.shape),))
    else:
        vec = matrix
    sum = LOG0
    for num in vec:
        sum = logaddexp(sum, num)
    return sum
//  [python]
def _logsum(matrix):
    if len(matrix.shape) > 1:
        vec = numpy.reshape(matrix, (numpy.prod(matrix.shape),))
    else:
        vec = matrix
    sum = LOG0
    for num in vec:
        sum = logaddexp(sum, num)
    return sum
//  [python]
def rank_restr(nvars=4, smp=100, noCorrRestr=False, Corrmat=None):
    """
    Returns the indices for sampling variables with  
    the desired correlation structure.
    
    :Parameters:
        - `nvars`: number of variables
        - `smp`: number of samples
        - `noCorrRestr`: No correlation restriction if True
        - `Corrmat`: Correlation matrix. If None, assure uncorrelated samples.
    """
    if isinstance(smp,(tuple,list)):
            smp=numpy.product(smp)
    def shuf(s):
        """
        Shuffle a vector, making shure to make a copy of the original
        :param s: A vector of values
        :return: a list of arrays
        """
        s1=[]
        for i in range(nvars):
            shuffle(s)
            s1.append(s.copy())
        return s1
    if noCorrRestr or nvars ==1:
        inds = numpy.arange(smp)
        x = shuf(inds)
    else:
        if Corrmat == None:
            C=numpy.core.numeric.identity(nvars)
        else:
            if Corrmat.shape[0] != nvars:
                raise TypeError('Correlation matrix must be of rank %s'%nvars)
            C=numpy.matrix(Corrmat)
        s0=numpy.arange(1.,smp+1)/(smp+1.)
        s=stats.norm().ppf(s0)
        s1 = shuf(s)
        S=numpy.matrix(s1)
        P=cholesky(C)
        Q=cholesky(numpy.corrcoef(S))

        Final=S.transpose()*inv(Q).transpose()*P.transpose()
        x = [stats.stats.rankdata(Final.transpose()[i,]) for i in range(nvars)]
    return x
//  [python]
def rank_restr(nvars=4, smp=100, noCorrRestr=False, Corrmat=None):
    """
    Returns the indices for sampling variables with  
    the desired correlation structure.
    
    :Parameters:
        - `nvars`: number of variables
        - `smp`: number of samples
        - `noCorrRestr`: No correlation restriction if True
        - `Corrmat`: Correlation matrix. If None, assure uncorrelated samples.
    """
    if isinstance(smp,(tuple,list)):
            smp=numpy.prod(smp)
    def shuf(s):
        """
        Shuffle a vector, making shure to make a copy of the original
        :param s: A vector of values
        :return: a list of arrays
        """
        s1=[]
        for i in range(nvars):
            shuffle(s)
            s1.append(s.copy())
        return s1
    if noCorrRestr or nvars ==1:
        inds = numpy.arange(smp)
        x = shuf(inds)
    else:
        if Corrmat == None:
            C=numpy.core.numeric.identity(nvars)
        else:
            if Corrmat.shape[0] != nvars:
                raise TypeError('Correlation matrix must be of rank %s'%nvars)
            C=numpy.matrix(Corrmat)
        s0=numpy.arange(1.,smp+1)/(smp+1.)
        s=stats.norm().ppf(s0)
        s1 = shuf(s)
        S=numpy.matrix(s1)
        P=cholesky(C)
        Q=cholesky(numpy.corrcoef(S))

        Final=S.transpose()*inv(Q).transpose()*P.transpose()
        x = [stats.stats.rankdata(Final.transpose()[i,]) for i in range(nvars)]
    return x
//  [python]
def make_array(start, shape, dtype):
    size = numpy.product(shape, dtype='i')
    a = numpy.arange(start, start + size)
    a = a.reshape(shape)
    a = a.astype(dtype, copy=False)
    return a
//  [python]
def make_array(start, shape, dtype):
    size = numpy.prod(shape, dtype='i')
    a = numpy.arange(start, start + size)
    a = a.reshape(shape)
    a = a.astype(dtype, copy=False)
    return a
//  [python]
def lhs(dist, parms, siz=100, noCorrRestr=False, corrmat=None, seed=None):
    '''
    Latin Hypercube sampling of any distribution.
    dist is is a scipy.stats random number generator 
    such as stats.norm, stats.beta, etc
    parms is a tuple with the parameters needed for 
    the specified distribution.

    :Parameters:
        - `dist`: random number generator from scipy.stats module or a list of them.
        - `parms`: tuple of parameters as required for dist, or a list of them.
        - `siz` :number or shape tuple for the output sample
        - `noCorrRestr`: if true, does not enforce correlation structure on the sample.
        - `corrmat`: Correlation matrix
    '''
    if seed:
        numpy.random.seed( seed )
    if not isinstance(dist,(list,tuple)):
        dists = [dist]
        parms = [parms]
    else:
        assert len(dist) == len(parms)
        dists = dist
    indices=rank_restr(nvars=len(dists), smp=siz, noCorrRestr=noCorrRestr, Corrmat=corrmat)
    smplist = []
    for j,d in enumerate(dists):
        if not isinstance(d, (stats.rv_discrete,stats.rv_continuous)):
            raise TypeError('dist is not a scipy.stats distribution object')
        n=siz
        if isinstance(siz,(tuple,list)):
            n=numpy.product(siz)
        #force type to float for sage compatibility
        pars = tuple([float(k) for k in parms[j]])
        #perc = numpy.arange(1.,n+1)/(n+1)
        step = 1./(n)
        perc = numpy.arange(0, 1, step) #class boundaries
        s_pos = [uniform(i, i+ step) for i in perc[:]]#[i+ step/2. for i in perc[:]]
        v = d(*pars).ppf(s_pos)
        #print len(v), step, perc
        index=list(map(int,indices[j]-1))
        v = v[index]
        if isinstance(siz,(tuple,list)):
            v.shape = siz
        smplist.append(v)
    if len(dists) == 1:
        return smplist[0]
    return numpy.array(smplist).transpose()
//  [python]
def lhs(dist, parms, siz=100, noCorrRestr=False, corrmat=None, seed=None):
    '''
    Latin Hypercube sampling of any distribution.
    dist is is a scipy.stats random number generator 
    such as stats.norm, stats.beta, etc
    parms is a tuple with the parameters needed for 
    the specified distribution.

    :Parameters:
        - `dist`: random number generator from scipy.stats module or a list of them.
        - `parms`: tuple of parameters as required for dist, or a list of them.
        - `siz` :number or shape tuple for the output sample
        - `noCorrRestr`: if true, does not enforce correlation structure on the sample.
        - `corrmat`: Correlation matrix
    '''
    if seed:
        numpy.random.seed( seed )
    if not isinstance(dist,(list,tuple)):
        dists = [dist]
        parms = [parms]
    else:
        assert len(dist) == len(parms)
        dists = dist
    indices=rank_restr(nvars=len(dists), smp=siz, noCorrRestr=noCorrRestr, Corrmat=corrmat)
    smplist = []
    for j,d in enumerate(dists):
        if not isinstance(d, (stats.rv_discrete,stats.rv_continuous)):
            raise TypeError('dist is not a scipy.stats distribution object')
        n=siz
        if isinstance(siz,(tuple,list)):
            n=numpy.prod(siz)
        #force type to float for sage compatibility
        pars = tuple([float(k) for k in parms[j]])
        #perc = numpy.arange(1.,n+1)/(n+1)
        step = 1./(n)
        perc = numpy.arange(0, 1, step) #class boundaries
        s_pos = [uniform(i, i+ step) for i in perc[:]]#[i+ step/2. for i in perc[:]]
        v = d(*pars).ppf(s_pos)
        #print len(v), step, perc
        index=list(map(int,indices[j]-1))
        v = v[index]
        if isinstance(siz,(tuple,list)):
            v.shape = siz
        smplist.append(v)
    if len(dists) == 1:
        return smplist[0]
    return numpy.array(smplist).transpose()
//  [python]
def __array__(self, dtype=None):
        """ Create a Numpy array containing the whole dataset.  DON'T THINK
        THIS MEANS DATASETS ARE INTERCHANGEABLE WITH ARRAYS.  For one thing,
        you have to read the whole dataset every time this method is called.
        """
        arr = numpy.zeros(self.shape, dtype=self.dtype if dtype is None else dtype)

        # Special case for (0,)*-shape datasets
        if numpy.product(self.shape, dtype=numpy.ulonglong) == 0:
            return arr

        self.read_direct(arr)
        return arr
//  [python]
def __array__(self, dtype=None):
        """ Create a Numpy array containing the whole dataset.  DON'T THINK
        THIS MEANS DATASETS ARE INTERCHANGEABLE WITH ARRAYS.  For one thing,
        you have to read the whole dataset every time this method is called.
        """
        arr = numpy.zeros(self.shape, dtype=self.dtype if dtype is None else dtype)

        # Special case for (0,)*-shape datasets
        if numpy.prod(self.shape, dtype=numpy.ulonglong) == 0:
            return arr

        self.read_direct(arr)
        return arr
//  [python]
def collect_values(fp, N, dtp):
    """Collect N values from stream

    Must be contained in exact number of lines.
    This will advance the stream forward by the number of lines found to
    contain N numeric values, and return an ndarray of type tp containing
    those.

    :param file fp: Stream
    :param int N: Total no. expected values
    :param dtype tp: dtype for values
    :returns: ndarray of type dtype with values found in file
    """ 
    L = []
    while len(L) < N:
        line = fp.readline()
        if line == "":
            raise EOFError("File ended prematurely")
        L.extend(ast.literal_eval(f) for f in line.strip().split())
    if len(L) != N:
        raise ValueError("Unexpected number of values.  Expected:"
            "{N:d}.  Got: {L}".format(N=N, L=len(L)))
    if numpy.dtype(dtp).isbuiltin == 0:
        flat_dtp = numpy.dtype(list(zip(
            (''.join(s) for s in itertools.product(string.ascii_letters, repeat=2)),
            (item for sublist in 
            [[x[1]]*(numpy.product(x[2]) if len(x)>2 else 1) for x in numpy.dtype(dtp).descr]
                    for item in sublist))))
        return numpy.array(tuple(L), dtype=flat_dtp).view(dtp)
    else:
        return numpy.array(L, dtype=dtp)
//  [python]
def collect_values(fp, N, dtp):
    """Collect N values from stream

    Must be contained in exact number of lines.
    This will advance the stream forward by the number of lines found to
    contain N numeric values, and return an ndarray of type tp containing
    those.

    :param file fp: Stream
    :param int N: Total no. expected values
    :param dtype tp: dtype for values
    :returns: ndarray of type dtype with values found in file
    """ 
    L = []
    while len(L) < N:
        line = fp.readline()
        if line == "":
            raise EOFError("File ended prematurely")
        L.extend(ast.literal_eval(f) for f in line.strip().split())
    if len(L) != N:
        raise ValueError("Unexpected number of values.  Expected:"
            "{N:d}.  Got: {L}".format(N=N, L=len(L)))
    if numpy.dtype(dtp).isbuiltin == 0:
        flat_dtp = numpy.dtype(list(zip(
            (''.join(s) for s in itertools.product(string.ascii_letters, repeat=2)),
            (item for sublist in 
            [[x[1]]*(numpy.prod(x[2]) if len(x)>2 else 1) for x in numpy.dtype(dtp).descr]
                    for item in sublist))))
        return numpy.array(tuple(L), dtype=flat_dtp).view(dtp)
    else:
        return numpy.array(L, dtype=dtp)
//  [python]
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	try:
		W = layer.output
	except:
		W = layer
	wp = W.eval(feed_dict=feed_dict);
	if len(numpy.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = numpy.zeros(numpy.product(fieldShape)); temp[0:numpy.shape(wp.ravel())[0]] = wp.ravel()
		fields = numpy.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = numpy.rollaxis(wp,3,0)
		features, channels, iy,ix = numpy.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = numpy.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = numpy.vstack([fields,numpy.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(numpy.hstack(fields2[i:i+perColumn]))

	tiled = numpy.vstack(tiled)
	if figOffset is not None:
		pylab.figure(figOffset); pylab.clf(); 

	pylab.imshow(tiled,cmap=cmap); pylab.title('%s Output' % layer.name); pylab.colorbar();
//  [python]
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
	# Output summary
	try:
		W = layer.output
	except:
		W = layer
	wp = W.eval(feed_dict=feed_dict);
	if len(numpy.shape(wp)) < 4:		# Fully connected layer, has no shape
		temp = numpy.zeros(numpy.prod(fieldShape)); temp[0:numpy.shape(wp.ravel())[0]] = wp.ravel()
		fields = numpy.reshape(temp,[1]+fieldShape)
	else:			# Convolutional layer already has shape
		wp = numpy.rollaxis(wp,3,0)
		features, channels, iy,ix = numpy.shape(wp)
		if channel is not None:
			fields = wp[:,channel,:,:]
		else:
			fields = numpy.reshape(wp,[features*channels,iy,ix])

	perRow = int(math.floor(math.sqrt(fields.shape[0])))
	perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
	fields2 = numpy.vstack([fields,numpy.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
	tiled = []
	for i in range(0,perColumn*perRow,perColumn):
		tiled.append(numpy.hstack(fields2[i:i+perColumn]))

	tiled = numpy.vstack(tiled)
	if figOffset is not None:
		pylab.figure(figOffset); pylab.clf(); 

	pylab.imshow(tiled,cmap=cmap); pylab.title('%s Output' % layer.name); pylab.colorbar();
//  [python]
def __init__(self, img_shape, dtype=np.float64):
        self.img_shape = img_shape
        n = np.product(self.img_shape)
        shape = (n, n)
        super(ImageLinearOperator, self).__init__(dtype, shape)
//  [python]
def __init__(self, img_shape, dtype=np.float64):
        self.img_shape = img_shape
        n = np.prod(self.img_shape)
        shape = (n, n)
        super(ImageLinearOperator, self).__init__(dtype, shape)
//  [python]
def test_addsumprod (self):
        "Tests add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.add.reduce(x), add.reduce(x))
        assert_equal(np.add.accumulate(x), add.accumulate(x))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(np.sum(x, axis=0), sum(x, axis=0))
        assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))
        assert_equal(np.sum(x, 0), sum(x, 0))
        assert_equal(np.product(x, axis=0), product(x, axis=0))
        assert_equal(np.product(x, 0), product(x, 0))
        assert_equal(np.product(filled(xm, 1), axis=0), product(xm, axis=0))
        s = (3, 4)
        x.shape = y.shape = xm.shape = ym.shape = s
        if len(s) > 1:
            assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
            assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
            assert_equal(np.sum(x, 1), sum(x, 1))
            assert_equal(np.product(x, 1), product(x, 1))
//  [python]
def test_addsumprod (self):
        "Tests add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.add.reduce(x), add.reduce(x))
        assert_equal(np.add.accumulate(x), add.accumulate(x))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(np.sum(x, axis=0), sum(x, axis=0))
        assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))
        assert_equal(np.sum(x, 0), sum(x, 0))
        assert_equal(np.prod(x, axis=0), product(x, axis=0))
        assert_equal(np.prod(x, 0), product(x, 0))
        assert_equal(np.prod(filled(xm, 1), axis=0), product(xm, axis=0))
        s = (3, 4)
        x.shape = y.shape = xm.shape = ym.shape = s
        if len(s) > 1:
            assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
            assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
            assert_equal(np.sum(x, 1), sum(x, 1))
            assert_equal(np.prod(x, 1), product(x, 1))
//  [python]
def _setup(self, image, acwe_mask, inside_bias):
        self.image = image
        assert self.image.shape == self.mask.shape
        self.acwe_mask = acwe_mask
        if acwe_mask is not None:
            assert self.image.shape == self.acwe_mask.shape
        self.inside_bias = inside_bias
        # note: self.mask is clipped to self.max_region_mask so the below works.
        self.inside_count = self.mask.sum()
        self.outside_count = numpy.product(self.mask[self.max_region_mask].shape) - self.inside_count
        self.inside_sum = self.image[self.mask].sum()
        self.outside_sum = self.image[self.max_region_mask].sum() - self.inside_sum
//  [python]
def _setup(self, image, acwe_mask, inside_bias):
        self.image = image
        assert self.image.shape == self.mask.shape
        self.acwe_mask = acwe_mask
        if acwe_mask is not None:
            assert self.image.shape == self.acwe_mask.shape
        self.inside_bias = inside_bias
        # note: self.mask is clipped to self.max_region_mask so the below works.
        self.inside_count = self.mask.sum()
        self.outside_count = numpy.prod(self.mask[self.max_region_mask].shape) - self.inside_count
        self.inside_sum = self.image[self.mask].sum()
        self.outside_sum = self.image[self.max_region_mask].sum() - self.inside_sum
//  [python]
def test_testAddSumProd (self):
        "Test add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue (eq(np.add.reduce(x), add.reduce(x)))
        self.assertTrue (eq(np.add.accumulate(x), add.accumulate(x)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(np.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue (eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue (eq(np.sum(x, 0), sum(x, 0)))
        self.assertTrue (eq(np.product(x, axis=0), product(x, axis=0)))
        self.assertTrue (eq(np.product(x, 0), product(x, 0)))
        self.assertTrue (eq(np.product(filled(xm, 1), axis=0),
                            product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue (eq(np.concatenate((x, y), 1),
                                concatenate((xm, ym), 1)))
            self.assertTrue (eq(np.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue (eq(np.sum(x, 1), sum(x, 1)))
            self.assertTrue (eq(np.product(x, 1), product(x, 1)))
//  [python]
def test_testAddSumProd (self):
        "Test add, sum, product."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue (eq(np.add.reduce(x), add.reduce(x)))
        self.assertTrue (eq(np.add.accumulate(x), add.accumulate(x)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(4, sum(array(4), axis=0)))
        self.assertTrue (eq(np.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue (eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue (eq(np.sum(x, 0), sum(x, 0)))
        self.assertTrue (eq(np.prod(x, axis=0), product(x, axis=0)))
        self.assertTrue (eq(np.prod(x, 0), product(x, 0)))
        self.assertTrue (eq(np.prod(filled(xm, 1), axis=0),
                            product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue (eq(np.concatenate((x, y), 1),
                                concatenate((xm, ym), 1)))
            self.assertTrue (eq(np.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue (eq(np.sum(x, 1), sum(x, 1)))
            self.assertTrue (eq(np.prod(x, 1), product(x, 1)))
//  [python]
def _assert_invariants(self):
        super()._assert_invariants()
        assert self.inside_count == self.mask.sum()
        assert self.outside_count == numpy.product(self.mask[self.max_region_mask].shape) - self.inside_count
        assert self.inside_sum == self.image[self.mask].sum()
        assert self.outside_sum == self.image[self.max_region_mask].sum() - self.inside_sum
        assert numpy.allclose(self.inside_sum/self.inside_count, self.image[self.mask].mean())
        if self.max_region_mask is None:
            assert numpy.allclose(self.outside_sum/self.outside_count, self.image[~self.mask].mean())
        else:
            assert numpy.allclose(self.outside_sum/self.outside_count, self.image[self.max_region_mask & ~self.mask].mean())
//  [python]
def _assert_invariants(self):
        super()._assert_invariants()
        assert self.inside_count == self.mask.sum()
        assert self.outside_count == numpy.prod(self.mask[self.max_region_mask].shape) - self.inside_count
        assert self.inside_sum == self.image[self.mask].sum()
        assert self.outside_sum == self.image[self.max_region_mask].sum() - self.inside_sum
        assert numpy.allclose(self.inside_sum/self.inside_count, self.image[self.mask].mean())
        if self.max_region_mask is None:
            assert numpy.allclose(self.outside_sum/self.outside_count, self.image[~self.mask].mean())
        else:
            assert numpy.allclose(self.outside_sum/self.outside_count, self.image[self.max_region_mask & ~self.mask].mean())
//  [python]
def 乘法(*args,  **kwargs):
		return cn_array(numpy.product(*args,  **kwargs))
//  [python]
def 乘法(*args,  **kwargs):
		return cn_array(numpy.prod(*args,  **kwargs))
//  [python]
def _setup(self, image, acwe_mask, inside_bias):
        if image.dtype == bool:
            image = image.astype(numpy.uint8)
        self.image = image
        assert self.image.shape == self.mask.shape
        self.acwe_mask = acwe_mask
        if acwe_mask is not None:
            assert self.image.shape == self.acwe_mask.shape
        # note: self.mask is clipped to self.max_region_mask so the below works.
        self.inside_count = self.mask.sum()
        self.inside_bias = inside_bias
        self.outside_count = numpy.product(self.mask[self.max_region_mask].shape) - self.inside_count
        bincounts = numpy.bincount(self.image[self.max_region_mask].flat)
        self.bins = len(bincounts)
        self.inside_bincounts = self._bincount(self.mask)
        self.outside_bincounts = bincounts - self.inside_bincounts
//  [python]
def _setup(self, image, acwe_mask, inside_bias):
        if image.dtype == bool:
            image = image.astype(numpy.uint8)
        self.image = image
        assert self.image.shape == self.mask.shape
        self.acwe_mask = acwe_mask
        if acwe_mask is not None:
            assert self.image.shape == self.acwe_mask.shape
        # note: self.mask is clipped to self.max_region_mask so the below works.
        self.inside_count = self.mask.sum()
        self.inside_bias = inside_bias
        self.outside_count = numpy.prod(self.mask[self.max_region_mask].shape) - self.inside_count
        bincounts = numpy.bincount(self.image[self.max_region_mask].flat)
        self.bins = len(bincounts)
        self.inside_bincounts = self._bincount(self.mask)
        self.outside_bincounts = bincounts - self.inside_bincounts
//  [python]
def makeSampleGeneratorFromLushDataset(filePath):
    # Set paths
    samplePath = makeSampleLabelPaths(filePath)[0]
    # Initialize
    sampleFile = open(samplePath)
    header = sampleFile.next()
    sampleShape = [int(x) for x in header.split()[3:]]
    sampleSize = numpy.product(sampleShape)
    terms = []
    # For each line,
    for line in sampleFile:
        # Extend terms
        terms.extend(float(x) for x in line.split())
        # If we have enough terms,
        while len(terms) >= sampleSize:
            # Yield sample
            yield numpy.array(terms[:sampleSize]).reshape(sampleShape)
            # Set terms
            terms = terms[sampleSize:]
//  [python]
def makeSampleGeneratorFromLushDataset(filePath):
    # Set paths
    samplePath = makeSampleLabelPaths(filePath)[0]
    # Initialize
    sampleFile = open(samplePath)
    header = sampleFile.next()
    sampleShape = [int(x) for x in header.split()[3:]]
    sampleSize = numpy.prod(sampleShape)
    terms = []
    # For each line,
    for line in sampleFile:
        # Extend terms
        terms.extend(float(x) for x in line.split())
        # If we have enough terms,
        while len(terms) >= sampleSize:
            # Yield sample
            yield numpy.array(terms[:sampleSize]).reshape(sampleShape)
            # Set terms
            terms = terms[sampleSize:]
//  [python]
def update_captured(self):
        idx_mask = self.edge_mask[tuple(self.inside_border_indices.T)]
        captured_indices = self.inside_border_indices[idx_mask]
        captured_idx = tuple(captured_indices.T)
        self.captured_idx = captured_idx
        self.outside_free[:] = True
        self.outside_free[captured_idx] = False
        neighbor_indices = self.index_neighborhood[captured_idx] # shape = (m, 3, 3, 2)
        all_neighbors = neighbor_indices.reshape((numpy.product(neighbor_indices.shape[:-1]), 2)) # shape = (m*3*3, 2)
        all_idx = tuple(all_neighbors.T)
        # now erode to get pixels non-adjacent to captured edges
        self.outside_free[all_idx] = self.outside_free_neighborhood[all_idx].all()
        # Technically, we should set outside_free[captured_idx] to True,
        # but it doesn't matter because we will never look up those locations.
        # the outside_free array is only used to look at the outside_border_indices
        # positions, which are non-overlapping with inside_border_indices.
        # Now free outside pixels atop an edge:
        self.outside_free[tuple(self.edge_indices.T)] = True
        self.noncaptured_indices = _diff_indices(self.edge_indices, captured_indices)
        self.noncaptured[:] = False
        self.noncaptured[tuple(self.noncaptured_indices.T)] = True
//  [python]
def update_captured(self):
        idx_mask = self.edge_mask[tuple(self.inside_border_indices.T)]
        captured_indices = self.inside_border_indices[idx_mask]
        captured_idx = tuple(captured_indices.T)
        self.captured_idx = captured_idx
        self.outside_free[:] = True
        self.outside_free[captured_idx] = False
        neighbor_indices = self.index_neighborhood[captured_idx] # shape = (m, 3, 3, 2)
        all_neighbors = neighbor_indices.reshape((numpy.prod(neighbor_indices.shape[:-1]), 2)) # shape = (m*3*3, 2)
        all_idx = tuple(all_neighbors.T)
        # now erode to get pixels non-adjacent to captured edges
        self.outside_free[all_idx] = self.outside_free_neighborhood[all_idx].all()
        # Technically, we should set outside_free[captured_idx] to True,
        # but it doesn't matter because we will never look up those locations.
        # the outside_free array is only used to look at the outside_border_indices
        # positions, which are non-overlapping with inside_border_indices.
        # Now free outside pixels atop an edge:
        self.outside_free[tuple(self.edge_indices.T)] = True
        self.noncaptured_indices = _diff_indices(self.edge_indices, captured_indices)
        self.noncaptured[:] = False
        self.noncaptured[tuple(self.noncaptured_indices.T)] = True