Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as
    'anti-scoring' of far instances outside of radius of current target instance
9483
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type):
    
    scores = np.zeros(num_attributes)
    for feature_num in range(num_attributes):
        if len(NN_near) > 0:
            scores[feature_num] += compute_score(attr, mcmap, NN_near, feature_num, inst,
                                                 nan_entries, headers, class_type, X, y, labels_std, data_type)
        # Note that we are using the near scoring loop in 'compute_score' and then just subtracting it here, in line with original SURF* paper.
        if len(NN_far) > 0:
            scores[feature_num] -= compute_score(attr, mcmap, NN_far, feature_num, inst,
                                                 nan_entries, headers, class_type, X, y, labels_std, data_type)
    return scores
270230
@Override
	public ClusteringTreeNode nearestChild(double[] pointA) {
		assert (this.projections.size() > 0 &&
				this.projections.get(0).length == pointA.length);
		int minBucketProjection = -1;
		int minSize = Integer.MAX_VALUE;
		Iterator<double[]> iIterProjections = this.projections.iterator();
		Iterator<CuckooHashing<List<ClusteringTreeNode>>> iIterBuckets = this.buckets
				.iterator();
		int size = this.projections.size();
		for (int i = 0; i < size; i++) {
			long bucketNumber = calcBucketNumber(project(pointA,
					iIterProjections.next()));
			List<ClusteringTreeNode> currentBucket = iIterBuckets.next().get(
					bucketNumber);
			int bucketSize;
			if (currentBucket != null
					&& (bucketSize = currentBucket.size()) <= minSize) {
				minBucketProjection = i;
				minSize = bucketSize;
			}
		}
		if (minBucketProjection == -1) {
			return null;
		}

		long bucketNumber = calcBucketNumber(project(pointA,
				minBucketProjection));
		double minDistance = Double.POSITIVE_INFINITY;
		ClusteringTreeNode min = null;
		// for (int i = -1; i <= 1; i++) {
		List<ClusteringTreeNode> currentBucket = this.buckets.get(
				minBucketProjection).get(bucketNumber);// + i);
		if (currentBucket != null) {
			for (ClusteringTreeNode node : currentBucket) {
				double d = Metric.distance(pointA, node.getCenter());
				if (d < minDistance) {
					minDistance = d;
					min = node;
				}
			}
		}
		// }
		return min;
	}
580916
def count_neighbours(mask, radius=1):
    ''''''

    height, width = mask.shape

    f = 2.0*radius+1.0

    w = -1.0/numpy.sqrt(f)
    kernel = [w]*radius + [w] + [w]*radius

    result = mask * f

    for y in range(height):
        result[y,:]  = numpy.convolve(result[y,:], kernel, 'same')

    for x in range(width):
        result[:,x] = numpy.convolve(result[:, x], kernel, 'same')

    return result - mask
761638
def vq_nearest_neighbor(x, hparams):
  """"""
  bottleneck_size = 2**hparams.bottleneck_bits
  means = hparams.means
  x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
  means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
  scalar_prod = tf.matmul(x, means, transpose_b=True)
  dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod
  if hparams.bottleneck_kind == "em":
    x_means_idx = tf.multinomial(-dist, num_samples=hparams.num_samples)
    x_means_hot = tf.one_hot(
        x_means_idx, depth=bottleneck_size)
    x_means_hot = tf.reduce_mean(x_means_hot, axis=1)
  else:
    x_means_idx = tf.argmax(-dist, axis=-1)
    x_means_hot = tf.one_hot(x_means_idx, depth=bottleneck_size)
  x_means = tf.matmul(x_means_hot, means)
  e_loss = tf.reduce_mean(tf.squared_difference(x, tf.stop_gradient(x_means)))
  return x_means_hot, e_loss
937336
def closestNonZeroIndex(pt, arr, kSize=21):
    
    assert kSize % 2 == 1, 'need odd kernel size'

    hk = int(kSize / 2)
    ipt = np.asarray(pt, dtype=int)
    # array slice of shape kSize around ipt:
    r = [slice(max(0, p - hk),
               min(s, p + hk + 1)) for p, s in zip(ipt, arr.shape)]

    # sliced array:
    arrr = arr[tuple(r)]
    # all indices that are non zero:
    ind = np.transpose(np.nonzero(arrr))
    if not len(ind):
        # nothing found
        return None
    # pos of ipt within array slice:
    center = [p - s.start for p, s in zip(ipt, r)]
    ind -= center
    # index of minimum distance:
    m = np.argmin(norm(ind, axis=-1))
    return ipt + ind[m]
285185
private boolean backwardsValidation(int indexSrc, int bestIndex) {
		double bestScoreV = maxError;
		int bestIndexV = -1;

		D d_forward = descDst.get(bestIndex);
		setActiveSource(locationDst.get(bestIndex));

		for( int j = 0; j < locationSrc.size(); j++ ) {

			// compute distance between the two features
			double distance = computeDistanceToSource(locationSrc.get(j));
			if( distance > maxDistance )
				continue;

			D d_v = descSrc.get(j);

			double score = scoreAssociation.score(d_forward,d_v);
			if( score < bestScoreV ) {
				bestScoreV = score;
				bestIndexV = j;
			}
		}

		return bestIndexV == indexSrc;
	}
1161655
def _nn(self, side, v, k=1, radius=np.inf, eps=0.0, p=2):
        
        if self.size > 0:
            dists, idxes = Dataset._nn(self, side, v, k, radius, eps, p)
        else:
            return self.buffer._nn(side, v, k, radius, eps, p)
        if self.buffer.size > 0:
            buffer_dists, buffer_idxes = self.buffer._nn(side, v, k, radius, eps, p)
            buffer_idxes = [i + self.size for i in buffer_idxes]
            ziped = zip(dists, idxes)
            buffer_ziped = zip(buffer_dists, buffer_idxes)
            sorted_dists_idxes = sorted(ziped + buffer_ziped, key=lambda di:di[0])
            knns = sorted_dists_idxes[:k]
            return [knn[0] for knn in knns], [knn[1] for knn in knns] 
        else:
            return dists, idxes
204294
def Nstars(self):
        
        if self._Nstars is None:
            N = {}
            for n in self.get_model_nodes():
                if n.index not in N:
                    N[n.index] = 1
                else:
                    N[n.index] += 1
            self._Nstars = N
        return self._Nstars
405130
def averageSequenceAccuracy(self, minOverlap, maxOverlap,
                              firstStat=0, lastStat=None):
    
    numCorrectSparsity = 0.0
    numCorrectClassifications = 0.0
    numStats = 0.0

    # For each object or sequence we classify every point or element
    #
    # A sequence element is considered correctly classified only if the number
    # of predictedActive cells is within a reasonable range and if the KNN
    # Classifier correctly classifies the active cell representation as
    # belonging to this sequence.
    #
    # A point on an object is considered correctly classified by the TM if the
    # number of predictedActive cells is within range.
    for stats in self.statistics[firstStat:lastStat]:

      # Keep running total of how often the number of predictedActive cells are
      # in the range.  We always skip the first (unpredictable) count.
      predictedActiveStat = stats["TM PredictedActive C0"][1:]
      TMRepresentationStat = stats["TM Full Representation C0"][1:]
      # print "\n-----------"
      # print stats["object"], predictedActiveStat
      for numCells,sdr in zip(predictedActiveStat, TMRepresentationStat):
        numStats += 1.0
        # print "numCells: ", numCells
        if numCells in range(minOverlap, maxOverlap + 1):
          numCorrectSparsity += 1.0

          # Check KNN Classifier
          sdr = list(sdr)
          sdr.sort()
          dense = numpy.zeros(self.numTMCells)
          dense[sdr] = 1.0
          (winner, inferenceResult, dist, categoryDist) = \
            self.classifier.infer(dense)
          # print sdr, winner, stats['object'], winner == stats['object']
          # print categoryDist
          # print

          if winner == stats['object']:
            numCorrectClassifications += 1.0

    if numStats==0:
      return 0.0, 0.0

    return ((numCorrectSparsity / numStats),
            (numCorrectClassifications / numStats) )
735975
def _compute_nearest_weights_edge(idcs, ndist, variant):
    """"""
    # Get out-of-bounds indices from the norm_distances. Negative
    # means "too low", larger than or equal to 1 means "too high"
    lo = (ndist < 0)
    hi = (ndist > 1)

    # For "too low" nodes, the lower neighbor gets weight zero;
    # "too high" gets 1.
    if variant == 'left':
        w_lo = np.where(ndist <= 0.5, 1.0, 0.0)
    else:
        w_lo = np.where(ndist < 0.5, 1.0, 0.0)

    w_lo[lo] = 0
    w_lo[hi] = 1

    # For "too high" nodes, the upper neighbor gets weight zero;
    # "too low" gets 1.
    if variant == 'left':
        w_hi = np.where(ndist <= 0.5, 0.0, 1.0)
    else:
        w_hi = np.where(ndist < 0.5, 0.0, 1.0)

    w_hi[lo] = 1
    w_hi[hi] = 0

    # For upper/lower out-of-bounds nodes, we need to set the
    # lower/upper neighbors to the last/first grid point
    edge = [idcs, idcs + 1]
    edge[0][hi] = -1
    edge[1][lo] = 0

    return w_lo, w_hi, edge
851642
def max_sharpe(self):
        """"""
        if not self.w:
            self.solve()
        # 1) Compute the local max SR portfolio between any two neighbor turning points
        w_sr, sr = [], []
        for i in range(len(self.w) - 1):
            w0 = np.copy(self.w[i])
            w1 = np.copy(self.w[i + 1])
            kargs = {"minimum": False, "args": (w0, w1)}
            a, b = self.golden_section(self.eval_sr, 0, 1, **kargs)
            w_sr.append(a * w0 + (1 - a) * w1)
            sr.append(b)
        # return max(sr), w_sr[sr.index(max(sr))]
        self.weights = w_sr[sr.index(max(sr))].reshape((self.n_assets,))
        return dict(zip(self.tickers, self.weights))
347014
protected void computeScoreFive( int top[] , int middle[] , int bottom[] , int score[] , int width ) {

		// disparity as the outer loop to maximize common elements in inner loops, reducing redundant calculations
		for( int d = minDisparity; d < maxDisparity; d++ ) {

			// take in account the different in image border between the sub-regions and the effective region
			int indexSrc = (d-minDisparity)*width + (d-minDisparity) + radiusX;
			int indexDst = (d-minDisparity)*width + (d-minDisparity);
			int end = indexSrc + (width-d-4*radiusX);
			while( indexSrc < end ) {
				int s = 0;

				// sample four outer regions at the corners around the center region
				int val0 = top[indexSrc-radiusX];
				int val1 = top[indexSrc+radiusX];
				int val2 = bottom[indexSrc-radiusX];
				int val3 = bottom[indexSrc+radiusX];

				// select the two best scores from outer for regions
				if( val1 < val0 ) {
					int temp = val0;
					val0 = val1;
					val1 = temp;
				}

				if( val3 < val2 ) {
					int temp = val2;
					val2 = val3;
					val3 = temp;
				}

				if( val3 < val0 ) {
					s += val2;
					s += val3;
				} else if( val2 < val1 ) {
					s += val2;
					s += val0;
				} else {
					s += val0;
					s += val1;
				}

				score[indexDst++] = s + middle[indexSrc++];
			}
		}
	}
159233
public static void go_upstream_a( int[] p, RandomIter flowRandomIter, RandomIter tcaRandomIter, RandomIter lRandomIter,
            int[] param ) {
        double area = 0, lenght = 0;
        int[] point = new int[2];
        int kk = 0, count = 0;

        point[0] = p[0];
        point[1] = p[1];
        // check how many pixels are draining in the considered pixel and select
        // the pixel with maximun tca
        for( int k = 1; k <= 8; k++ ) {
            if (flowRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) == dirIn[k][2]) {
                // counts how many pixels are draining in the considere
                count++;
                if (tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) >= area) {
                    // if two pixels has the same tca select the pixel with the
                    // maximum vale of hacklength
                    if (tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) == area) {
                        if (lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0) > lenght) {
                            kk = k;
                            area = tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                            lenght = lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                            point[0] = p[0] + dirIn[k][1];
                            point[1] = p[1] + dirIn[k][0];
                        }
                    } else {
                        kk = k;
                        area = tcaRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                        lenght = lRandomIter.getSampleDouble(p[0] + dirIn[k][1], p[1] + dirIn[k][0], 0);
                        point[0] = p[0] + dirIn[k][1];
                        point[1] = p[1] + dirIn[k][0];
                    }
                }
            }

        }
        p[0] = point[0];
        p[1] = point[1];
        param[0] = kk;
        param[1] = count;
    }
163014
protected void findLocalScaleSpaceMax(PyramidFloat<T> ss, int layerID) {
		List<Point2D_I16> candidates = maximums;

		float scale0 = (float) ss.scale[layerID - 1];
		float scale1 = (float) ss.scale[layerID];
		float scale2 = (float) ss.scale[layerID + 1];

		float sigma0 = (float) ss.getSigma(layerID - 1);
		float sigma1 = (float) ss.getSigma(layerID);
		float sigma2 = (float) ss.getSigma(layerID + 1);

		// For laplacian its t^(2*gamma) where gamma = 3/4
		float ss0 = (float) (Math.pow(sigma0, 2.0 * 0.75)/scale0);// Is this divide by scale correct?
		float ss1 = (float) (Math.pow(sigma1, 2.0 * 0.75)/scale1);
		float ss2 = (float) (Math.pow(sigma2, 2.0 * 0.75)/scale2);

		for (Point2D_I16 c : candidates) {

			GrayF32 intensity = detector.getIntensity();

			float target = intensity.unsafe_get(c.x,c.y);
			float fx,fy;
			{
				float x0 = intensity.unsafe_get(c.x - 1, c.y);
				float x2 = intensity.unsafe_get(c.x + 1, c.y);
				float y0 = intensity.unsafe_get(c.x, c.y - 1);
				float y2 = intensity.unsafe_get(c.x, c.y + 1);

				fx = c.x + polyPeak(x0, target, x2);
				fy = c.y + polyPeak(y0, target, y2);
			}
//			fx=c.x;fy=c.y;

			sparseLaplace.setImage(ss.getLayer(layerID));
			float val = ss1 * (float) sparseLaplace.compute(c.x,c.y);
			// search for local maximum or local minimum
			float adj = Math.signum(val);
			val *= adj;


			// find pixel location in each image's local coordinate
			int x0 = (int) (fx * scale1 / scale0 + 0.5);
			int y0 = (int) (fy * scale1 / scale0 + 0.5);

			int x2 = (int) (fx * scale1 / scale2 + 0.5);
			int y2 = (int) (fy * scale1 / scale2 + 0.5);

			if (checkMax(ss.getLayer(layerID - 1), adj*ss0,val, x0, y0) && checkMax(ss.getLayer(layerID + 1), adj*ss2,val, x2, y2)) {
				sparseLaplace.setImage(ss.getLayer(layerID-1));
				float s0 = ss0 * (float) sparseLaplace.compute(x0,y0)*adj;
				sparseLaplace.setImage(ss.getLayer(layerID+1));
				float s2 = ss2 * (float) sparseLaplace.compute(x2,y2)*adj;

				double adjSigma;
				double sigmaInterp = polyPeak(s0, val, s2); // scaled from -1 to 1
				if( sigmaInterp < 0 ) {
					adjSigma = sigma0*(-sigmaInterp) + (1+sigmaInterp)*sigma1;
				} else {
					adjSigma = sigma2*sigmaInterp + (1-sigmaInterp)*sigma1;
				}

				// put features into the scale of the upper image
				foundPoints.add(new ScalePoint(fx * scale1, fy * scale1, adjSigma));
			}
		}
	}
1129262
def identify_vertex_neighbours(self, vertex):
        
        simplices = self.simplices
        ridx, cidx = np.where(simplices == vertex)
        neighbour_array = np.unique(np.hstack([simplices[ridx]])).tolist()
        neighbour_array.remove(vertex)
        return neighbour_array
655624
def discriminator(self, imgs):
        
        nf = 64
        with argscope(Conv2D, kernel_size=4, strides=2):
            l = (LinearWrap(imgs)
                 .Conv2D('conv0', nf, activation=tf.nn.leaky_relu)
                 .Conv2D('conv1', nf * 2)
                 .BatchNorm('bn1')
                 .tf.nn.leaky_relu()
                 .Conv2D('conv2', nf * 4)
                 .BatchNorm('bn2')
                 .tf.nn.leaky_relu()
                 .Conv2D('conv3', nf * 8)
                 .BatchNorm('bn3')
                 .tf.nn.leaky_relu()
                 .FullyConnected('fct', 1)())
        return l
975116
def hybrid_forward(self, F, x, sampled_values, label, weight, bias):
        """"""
        sampled_candidates, _, _ = sampled_values
        # (batch_size,)
        label = F.reshape(label, shape=(-1,))
        # (num_sampled+batch_size,)
        ids = F.concat(sampled_candidates, label, dim=0)
        # lookup weights and biases
        # (num_sampled+batch_size, dim)
        w_all = F.Embedding(data=ids, weight=weight,
                            input_dim=self._num_classes, output_dim=self._in_unit,
                            sparse_grad=self._sparse_grad)
        # (num_sampled+batch_size, 1)
        b_all = F.take(bias, indices=ids)
        return self._dense(x, sampled_values, label, w_all, b_all)