Takes an X,Y point and an array of sizes and scores the point against those ratios. For example for a finder pattern takes the ratio list of 1:1:3:1:1 and checks horizontal, vertical and diagonal ratios against that.
430090
function scorePattern(point, ratios, matrix) {
        try {
            const horizontalRun = countBlackWhiteRun(point, { x: -1, y: point.y }, matrix, ratios.length);
            const verticalRun = countBlackWhiteRun(point, { x: point.x, y: -1 }, matrix, ratios.length);
            const topLeftPoint = {
                x: Math.max(0, point.x - point.y) - 1,
                y: Math.max(0, point.y - point.x) - 1,
            };
            const topLeftBottomRightRun = countBlackWhiteRun(point, topLeftPoint, matrix, ratios.length);
            const bottomLeftPoint = {
                x: Math.min(matrix.width, point.x + point.y) + 1,
                y: Math.min(matrix.height, point.y + point.x) + 1,
            };
            const bottomLeftTopRightRun = countBlackWhiteRun(point, bottomLeftPoint, matrix, ratios.length);
            const horzError = scoreBlackWhiteRun(horizontalRun, ratios);
            const vertError = scoreBlackWhiteRun(verticalRun, ratios);
            const diagDownError = scoreBlackWhiteRun(topLeftBottomRightRun, ratios);
            const diagUpError = scoreBlackWhiteRun(bottomLeftTopRightRun, ratios);
            const ratioError = Math.sqrt(horzError.error * horzError.error +
                vertError.error * vertError.error +
                diagDownError.error * diagDownError.error +
                diagUpError.error * diagUpError.error);
            const avgSize = (horzError.averageSize + vertError.averageSize + diagDownError.averageSize + diagUpError.averageSize) / 4;
            const sizeError = (Math.pow((horzError.averageSize - avgSize), 2) +
                Math.pow((vertError.averageSize - avgSize), 2) +
                Math.pow((diagDownError.averageSize - avgSize), 2) +
                Math.pow((diagUpError.averageSize - avgSize), 2)) / avgSize;
            return ratioError + sizeError;
        }
        catch (_a) {
            return Infinity;
        }
    }
1180216
function clusterByNeighbor(points) {
    const sorted = points.slice().sort((a, b) => {
        if (a.y < b.y) {
            return -1;
        } else if (a.y > b.y) {
            return 1;
        } else {
            if (a.x < b.x) {
                return -1;
            } else if (a.x > b.x) {
                return 1;
            } else {
                return 0;
            }
        }
    });

    const cluster = sorted.reduce((sets, point) => {
        const setContainingNeighbors = sets.find(set => set.some((setPoint) => {
            return getNeighbors(setPoint).some(spn => areEqual(spn, point));
        }));

        if (setContainingNeighbors) {
            setContainingNeighbors.push(point);
        } else {
            sets.push([point]);
        }

        return sets;
    }, []);

    return cluster;
}
520886
def _points(self, x_pos):
        
        for serie in self.all_series:
            serie.points = [(x_pos[i], v) for i, v in enumerate(serie.values)]
            if serie.points and self.interpolate:
                serie.interpolated = self._interpolate(x_pos, serie.values)
            else:
                serie.interpolated = []
1043614
protected void zSort(List<? extends SpatialComparable> objs, int start, int end, double[] mms, int[] dims, int depth) {
    final int numdim = (dims != null) ? dims.length : (mms.length >> 1);
    final int edim = (dims != null) ? dims[depth] : depth;
    // Find the splitting points.
    final double min = mms[2 * edim], max = mms[2 * edim + 1];
    double spos = (min + max) / 2.;
    // Safeguard against duplicate points:
    if(max - spos < STOPVAL || spos - min < STOPVAL) {
      boolean ok = false;
      for(int d = 0; d < numdim; d++) {
        int d2 = ((dims != null) ? dims[d] : d) << 1;
        if(mms[d2 + 1] - mms[d2] >= STOPVAL) {
          ok = true;
          break;
        }
      }
      if(!ok) {
        return;
      }
    }
    int split = pivotizeList1D(objs, start, end, edim, spos, false);
    assert (start <= split && split <= end);
    int nextdim = (depth + 1) % numdim;
    if(start < split - 1) {
      mms[2 * edim] = min;
      mms[2 * edim + 1] = spos;
      zSort(objs, start, split, mms, dims, nextdim);
    }
    if(split < end - 1) {
      mms[2 * edim] = spos;
      mms[2 * edim + 1] = max;
      zSort(objs, split, end, mms, dims, nextdim);
    }
    // Restore ranges
    mms[2 * edim] = min;
    mms[2 * edim + 1] = max;
  }
978954
def _within_box(points, boxes):
    
    x_within = (points[..., 0] >= boxes[:, 0, None]) & (
        points[..., 0] <= boxes[:, 2, None]
    )
    y_within = (points[..., 1] >= boxes[:, 1, None]) & (
        points[..., 1] <= boxes[:, 3, None]
    )
    return x_within & y_within
262845
def point_on_line(ab, c):
    '''
    
    '''
    (a,b) = ab
    abc = [np.asarray(u) for u in (a,b,c)]
    if any(len(u.shape) == 2 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
    else:                                   (a,b,c) = abc
    vca = a - c
    vcb = b - c
    uba = czdivide(vba, np.sqrt(np.sum(vba**2, axis=0)))
    uca = czdivide(vca, np.sqrt(np.sum(vca**2, axis=0)))
    return (np.isclose(np.sqrt(np.sum(vca**2, axis=0)), 0) |
            np.isclose(np.sqrt(np.sum(vcb**2, axis=0)), 0) |
            np.isclose(np.abs(np.sum(uba*uca, axis=0)), 1))
22723
function (state, source, target, points, result)
	{
		var pt = (points != null && points.length > 0) ? points[0] : null;

		var vertical = false;
		var horizontal = false;
		
		if (source != null && target != null)
		{
			if (pt != null)
			{
				var left = Math.min(source.x, target.x);
				var right = Math.max(source.x + source.width,
					target.x + target.width);
	
				var top = Math.min(source.y, target.y);
				var bottom = Math.max(source.y + source.height,
					target.y + target.height);

				pt = state.view.transformControlPoint(state, pt);
					
				vertical = pt.y < top || pt.y > bottom;
				horizontal = pt.x < left || pt.x > right;
			}
			else
			{
				var left = Math.max(source.x, target.x);
				var right = Math.min(source.x + source.width,
					target.x + target.width);
					
				vertical = left == right;
				
				if (!vertical)
				{
					var top = Math.max(source.y, target.y);
					var bottom = Math.min(source.y + source.height,
						target.y + target.height);
						
					horizontal = top == bottom;
				}
			}
		}

		if (!horizontal && (vertical ||
			state.style[mxConstants.STYLE_ELBOW] == mxConstants.ELBOW_VERTICAL))
		{
			mxEdgeStyle.TopToBottom(state, source, target, points, result);
		}
		else
		{
			mxEdgeStyle.SideToSide(state, source, target, points, result);
		}
	}
158804
function pointsArray (buf, offset, numPoints) {
    var pointsData = []
    for (var i = offset; i < offset + numPoints * 12; i += 12) {
      pointsData.push([buf.readFloatLE(i + 0), buf.readFloatLE(i + 4), buf.readFloatLE(i + 8)])
    }
    return pointsData
  }
1099777
private static boolean multiPointExactlyEqualsMultiPoint_(
			MultiPoint multipoint_a, MultiPoint multipoint_b, double tolerance,
			ProgressTracker progress_tracker) {
		if (multipoint_a.getPointCount() != multipoint_b.getPointCount())
			return false;

		Point2D ptA = new Point2D(), ptB = new Point2D();
		boolean bAllPointsEqual = true;
		double tolerance_sq = tolerance * tolerance;

		for (int i = 0; i < multipoint_a.getPointCount(); i++) {
			multipoint_a.getXY(i, ptA);
			multipoint_b.getXY(i, ptB);

			if (Point2D.sqrDistance(ptA, ptB) > tolerance_sq) {
				bAllPointsEqual = false;
				break;
			}
		}

		if (!bAllPointsEqual)
			return false;

		return true;
	}
29523
def returnMatches(kw, kv, n, theta, inputScaling=1.0):
  
  # How many weight vectors and input vectors to generate at a time
  m1 = 4
  m2 = 1000

  weights = getSparseTensor(kw, n, m1, fixedRange=1.0 / kw)

  # Initialize random input vectors using given scaling and see how many match
  inputVectors = getSparseTensor(kv, n, m2,
                                 onlyPositive=True,
                                 fixedRange= 2*inputScaling / kw,
                                 )
  dot = inputVectors.matmul(weights.t())
  numMatches = ((dot >= theta).sum()).item()
  pctMatches = numMatches / float(m1*m2)

  return pctMatches, numMatches, m1*m2
489456
def match_positions(shape, list_of_coords):
    
    match_array = np.zeros(shape)
    try:
        # excpetion hit on this line if nothing in list_of_coords- i.e. no matches
        match_array[list_of_coords[:,0],list_of_coords[:,1]] = 1
        labelled = label(match_array)
        objects = find_objects(labelled[0])
        coords = [{'x':(slice_x.start, slice_x.stop),'y':(slice_y.start, slice_y.stop)} for (slice_y,slice_x) in objects]
        final_positions = [(int(np.mean(coords[i]['x'])),int(np.mean(coords[i]['y']))) for i in range(len(coords))]
        return final_positions
    except IndexError:
        print 'no matches found'
        # this error occurs if no matches are found
        return []
548767
def mae(x_values, y_values, drop_missing = True):
    ''''''
    num_points = len(x_values)
    assert(num_points == len(y_values) and num_points > 0)
    return numpy.sum(numpy.apply_along_axis(numpy.abs, 0, numpy.subtract(x_values, y_values))) / float(num_points)
404241
def _setup_xy(self, p):
        
        self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s",p.bounds, p.xdensity, p.ydensity, p.x, p.y, p.orientation)

        x_points,y_points = SheetCoordinateSystem(p.bounds, p.xdensity, p.ydensity).sheetcoordinates_of_matrixidx()

        self.pattern_x, self.pattern_y = self._create_and_rotate_coordinate_arrays(x_points-p.x, y_points-p.y, p)
1319717
def findHomography(self, img, drawMatches=False):
        '''
        
        '''
        print("\t Finding points...")
        # Find points in the next frame
        img = self._prepareImage(img)
        features, descs = self.detector.detectAndCompute(img, None)

        ######################
        # TODO: CURRENTLY BROKEN IN OPENCV3.1 - WAITNG FOR NEW RELEASE 3.2
#         matches = self.matcher.knnMatch(descs,#.astype(np.float32),
#                                         self.base_descs,
#                                         k=3)
#         print("\t Match Count: ", len(matches))
#         matches_subset = self._filterMatches(matches)

        # its working alternative (for now):
        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
        matches_subset = bf.match(descs, self.base_descs)

        ######################
#         matches = bf.knnMatch(descs,self.base_descs, k=2)
#         # Apply ratio test
#         matches_subset = []
#         medDist = np.median([m.distance for m in matches])
#         matches_subset = [m for m in matches if m.distance < medDist]
#         for m in matches:
#             print(m.distance)
#         for m,n in matches:
#             if m.distance < 0.75*n.distance:
#                 matches_subset.append([m])

        if not len(matches_subset):
            raise Exception('no matches found')
        print("\t Filtered Match Count: ", len(matches_subset))

        distance = sum([m.distance for m in matches_subset])
        print("\t Distance from Key Image: ", distance)

        averagePointDistance = distance / (len(matches_subset))
        print("\t Average Distance: ", averagePointDistance)

        kp1 = []
        kp2 = []

        for match in matches_subset:
            kp1.append(self.base_features[match.trainIdx])
            kp2.append(features[match.queryIdx])

        # /self._fH #scale with _fH, if image was resized

        p1 = np.array([k.pt for k in kp1])
        p2 = np.array([k.pt for k in kp2])  # /self._fH

        H, status = cv2.findHomography(p1, p2,
                                       cv2.RANSAC,  # method
                                       5.0  # max reprojection error (1...10)
                                       )
        if status is None:
            raise Exception('no homography found')
        else:
            inliers = np.sum(status)
            print('%d / %d  inliers/matched' % (inliers, len(status)))
            inlierRatio = inliers / len(status)
            if self.minInlierRatio > inlierRatio or inliers < self.minInliers:
                raise Exception('bad fit!')

        # scale with _fH, if image was resized
        # see
        # http://answers.opencv.org/question/26173/the-relationship-between-homography-matrix-and-scaling-images/
        s = np.eye(3, 3)
        s[0, 0] = 1 / self._fH
        s[1, 1] = 1 / self._fH
        H = s.dot(H).dot(np.linalg.inv(s))

        if drawMatches:
            #             s0,s1 = img.shape
            #             out = np.empty(shape=(s0,s1,3), dtype=np.uint8)
            img = draw_matches(self.base8bit, self.base_features, img, features,
                               matches_subset[:20],  # None,#out,
                               # flags=2
                               thickness=5
                               )

        return (H, inliers, inlierRatio, averagePointDistance,
                img, features,
                descs, len(matches_subset))
397342
def interpolate_xarray_linear(xpoints, ypoints, values, shape, chunks=CHUNK_SIZE):
    """"""
    from scipy.interpolate.interpnd import (LinearNDInterpolator,
                                            _ndim_coords_from_arrays)

    if isinstance(chunks, (list, tuple)):
        vchunks, hchunks = chunks
    else:
        vchunks, hchunks = chunks, chunks

    points = _ndim_coords_from_arrays(np.vstack((np.asarray(ypoints),
                                                 np.asarray(xpoints))).T)

    interpolator = LinearNDInterpolator(points, values)

    grid_x, grid_y = da.meshgrid(da.arange(shape[1], chunks=hchunks),
                                 da.arange(shape[0], chunks=vchunks))

    # workaround for non-thread-safe first call of the interpolator:
    interpolator((0, 0))
    res = da.map_blocks(intp, grid_x, grid_y, interpolator=interpolator)

    return DataArray(res, dims=('y', 'x'))
686006
function(points, options) {
      if (!points) {
        points = [0, 0, 0, 0];
      }

      this.callSuper('initialize', options);

      this.set('x1', points[0]);
      this.set('y1', points[1]);
      this.set('x2', points[2]);
      this.set('y2', points[3]);

      this._setWidthHeight(options);
    }
234357
def check_keypoints(keypoints, rows, cols):
    """"""
    for kp in keypoints:
        check_keypoint(kp, rows, cols)