Get the square boundary coordinates for a given centre and distance
775347
def get_coord_box(centre_x, centre_y, distance):
    """Todo: return coordinates inside a circle, rather than a square"""
    return {
        'top_left': (centre_x - distance, centre_y + distance),
        'top_right': (centre_x + distance, centre_y + distance),
        'bottom_left': (centre_x - distance, centre_y - distance),
        'bottom_right': (centre_x + distance, centre_y - distance),
    }
1351087
function findClosestPointIndexWithinRadius(points, x, y, radiusThreshold) {
    let closestIdx;
    let closestDist = Number.MAX_VALUE;
    points.forEach((d, idx) => {
      let distSqrd = Math.pow(d.x - x, 2) + Math.pow(d.y - y, 2); // changeto: (d.x - x)**2 + (d.y - y)**2;
      if (distSqrd < closestDist && distSqrd < radiusThreshold) {
        closestIdx = idx;
        closestDist = distSqrd;
      }
    });
    return closestIdx;
  }
797976
def coords_on_grid(self, x, y):
        

        if isinstance(x, float):
            x = int(self._round(x))
        if isinstance(y, float):
            y = int(self._round(y))
        if not self._y_coord_down:
            y = self._extents - y
        return x, y
316177
def coordinates_inside_data(
        self,
        x,
        y
        ):

        

        return (self.min_x <= x < self.max_x) and (self.min_y <= y < self.max_y)
1080466
def get_ajd_bound(mesh):
    
    print('Get elements adjacent to boundaries')
    boundary_elements = []
    str_adj_boundaries = ''
    # for boundary in mesh['elements']['1']:
    boundaries = mesh['boundaries']['12'] + mesh['boundaries']['11']
    for boundary in boundaries:
        # now find the triangle ('2') with two nodes equal to this boundary
        indices = [nr if (boundary[0] in x and boundary[1] in x) else np.nan
                   for (nr, x) in enumerate(mesh['elements']['2'])]
        indices = np.array(indices)[~np.isnan(indices)]
        if(len(indices) != 1):
            print('More than one neighbour found!')
        elif(len(indices) == 0):
            print('No neighbour found!')
        boundary_elements.append(indices[0])
        str_adj_boundaries += '{0}\n'.format(int(indices[0]) + 1)
    return str_adj_boundaries, boundary_elements
132800
def get_distance(F, x):
    """"""
    n = x.shape[0]

    square = F.sum(x ** 2.0, axis=1, keepdims=True)
    distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose()))

    # Adding identity to make sqrt work.
    return F.sqrt(distance_square + F.array(np.identity(n)))
851787
def _centered_edges(self):
        

        edges = []
        for position, bbox in zip(self.positions, self.bounding_boxes):
            xmin = bbox.ixmin - 0.5 - position[0]
            xmax = bbox.ixmax - 0.5 - position[0]
            ymin = bbox.iymin - 0.5 - position[1]
            ymax = bbox.iymax - 0.5 - position[1]
            edges.append((xmin, xmax, ymin, ymax))

        return edges
676382
def boundaries(nside, pix, step=1, nest=False):
    """"""
    pix = np.asarray(pix)
    if pix.ndim > 1:
        # For consistency with healpy we only support scalars or 1D arrays
        raise ValueError("Array has to be one dimensional")
    lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
    rep_sph = UnitSphericalRepresentation(lon, lat)
    rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1)
    if rep_car.shape[0] == 1:
        return rep_car[0]
    else:
        return rep_car
286849
def get_lons_from_cartesian(x__, y__):
    
    return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)
33527
def bounds(self):
        """"""
        google_x, google_y = self.google
        pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE
        pixel_x_east, pixel_y_south = (google_x + 1) * TILE_SIZE, (google_y + 1) * TILE_SIZE

        point_min = Point.from_pixel(pixel_x=pixel_x_west, pixel_y=pixel_y_south, zoom=self.zoom)
        point_max = Point.from_pixel(pixel_x=pixel_x_east, pixel_y=pixel_y_north, zoom=self.zoom)
        return point_min, point_max
279868
function(baseCoords, corner) {
		var result = {
			width: 0, height: 0,
			position: {
				top: 1e10, right: 0,
				bottom: 0, left: 1e10
			},
			adjustable: FALSE
		},
		i = 0, next,
		coords = [],
		compareX = 1, compareY = 1,
		realX = 0, realY = 0,
		newWidth, newHeight;

		// First pass, sanitize coords and determine outer edges
		i = baseCoords.length; 
		while(i--) {
			next = [ parseInt(baseCoords[--i], 10), parseInt(baseCoords[i+1], 10) ];

			if(next[0] > result.position.right){ result.position.right = next[0]; }
			if(next[0] < result.position.left){ result.position.left = next[0]; }
			if(next[1] > result.position.bottom){ result.position.bottom = next[1]; }
			if(next[1] < result.position.top){ result.position.top = next[1]; }

			coords.push(next);
		}

		// Calculate height and width from outer edges
		newWidth = result.width = Math.abs(result.position.right - result.position.left);
		newHeight = result.height = Math.abs(result.position.bottom - result.position.top);

		// If it's the center corner...
		if(corner.abbrev() === 'c') {
			result.position = {
				left: result.position.left + result.width / 2,
				top: result.position.top + result.height / 2
			};
		}
		else {
			// Second pass, use a binary search algorithm to locate most suitable coordinate
			while(newWidth > 0 && newHeight > 0 && compareX > 0 && compareY > 0)
			{
				newWidth = Math.floor(newWidth / 2);
				newHeight = Math.floor(newHeight / 2);

				if(corner.x === LEFT){ compareX = newWidth; }
				else if(corner.x === RIGHT){ compareX = result.width - newWidth; }
				else{ compareX += Math.floor(newWidth / 2); }

				if(corner.y === TOP){ compareY = newHeight; }
				else if(corner.y === BOTTOM){ compareY = result.height - newHeight; }
				else{ compareY += Math.floor(newHeight / 2); }

				i = coords.length;
				while(i--)
				{
					if(coords.length < 2){ break; }

					realX = coords[i][0] - result.position.left;
					realY = coords[i][1] - result.position.top;

					if(
						corner.x === LEFT && realX >= compareX ||
						corner.x === RIGHT && realX <= compareX ||
						corner.x === CENTER && (realX < compareX || realX > result.width - compareX) ||
						corner.y === TOP && realY >= compareY ||
						corner.y === BOTTOM && realY <= compareY ||
						corner.y === CENTER && (realY < compareY || realY > result.height - compareY)) {
						coords.splice(i, 1);
					}
				}
			}
			result.position = { left: coords[0][0], top: coords[0][1] };
		}

		return result;
	}
1144936
def extent(self) -> Tuple[float, float, float, float]:
        
        west, south, east, north = self.bounds
        return west, east, south, north
206979
Point determineClosestCentre(Point p, Point centreA, Point centreB){
		
		//loop counter variable
		int l;	

		//stores the distance between p and centreA
		double distanceA = 0.0;

		for(l=0;l<p.dimension;l++){
			//centroid coordinate of the point
			double centroidCoordinatePoint;
			if(p.weight != 0.0){
				centroidCoordinatePoint = p.coordinates[l] / p.weight;
			} else {
				centroidCoordinatePoint = p.coordinates[l];
			}
			//centroid coordinate of the centre
			double centroidCoordinateCentre;
			if(centreA.weight != 0.0){
				centroidCoordinateCentre = centreA.coordinates[l] / centreA.weight;
			} else {
				centroidCoordinateCentre = centreA.coordinates[l];
			}

			distanceA += (centroidCoordinatePoint-centroidCoordinateCentre) * 
					(centroidCoordinatePoint-centroidCoordinateCentre) ;
		}

		//stores the distance between p and centreB
		double distanceB = 0.0;

		for(l=0;l<p.dimension;l++){
			//centroid coordinate of the point
			double centroidCoordinatePoint;
			if(p.weight != 0.0){
				centroidCoordinatePoint = p.coordinates[l] / p.weight;
			} else {
				centroidCoordinatePoint = p.coordinates[l];
			}
			//centroid coordinate of the centre
			double centroidCoordinateCentre;
			if(centreB.weight != 0.0){
				centroidCoordinateCentre = centreB.coordinates[l] / centreB.weight;
			} else {
				centroidCoordinateCentre = centreB.coordinates[l];
			}

			distanceB += (centroidCoordinatePoint-centroidCoordinateCentre) * 
					(centroidCoordinatePoint-centroidCoordinateCentre) ;
		}

		//return the nearest centre
		if(distanceA < distanceB){
			return centreA;
		} else {
			return centreB;
		}
	}
973606
def _get_coord(self, coord):
        
        x, y = coord
        return self.ctypes.c_int(y << 16 | x)
1208303
private static double squaredDistance(FinderPattern a, FinderPattern b) {
    double x = a.getX() - b.getX();
    double y = a.getY() - b.getY();
    return x * x + y * y;
  }
282630
def bounding_box(obj):
    '''
    '''
    return np.array([np.min(obj.points[:, 0:3], axis=0),
                     np.max(obj.points[:, 0:3], axis=0)])
1186965
def _map_center(self, coord, val):
        '''  '''

        if self.ppd in [4, 16, 64, 128]:
            res = {'lat': 0, 'long': 360}
            return res[coord] / 2.0
        elif self.ppd in [256]:
            res = {'lat': 90, 'long': 180}
            c = (val // res[coord] + 1) * res[coord]
            return c - res[coord], c
        elif self.ppd in [512]:
            res = {'lat': 45, 'long': 90}
            c = (val // res[coord] + 1) * res[coord]
            return c - res[coord], c
        elif self.ppd in [1024]:
            res = {'lat': 15, 'long': 30}
            c = (val // res[coord] + 1) * res[coord]
            return c - res[coord], c