return the coordinates (in RAI) of the corners of a box enclosing the data in ``dset``
499596
def bounding_box(dset):
    ''''''
    o = nl.run(["3dAutobox","-input",dset])
    ijk_coords = re.findall(r'[xyz]=(\d+)\.\.(\d+)',o.output)
    from_rai = ijk_to_xyz(dset,[float(x[0]) for x in ijk_coords])
    to_rai = ijk_to_xyz(dset,[float(x[1]) for x in ijk_coords])
    return (from_rai,to_rai)
1259465
def rd2xy(input,ra=None,dec=None,coordfile=None,colnames=None,
            precision=6,output=None,verbose=True):
    
    single_coord = False
    if coordfile is not None:
        if colnames in blank_list:
            colnames = ['c1','c2']
        elif isinstance(colnames,type('a')):
            colnames = colnames.split(',')
        # convert input file coordinates to lists of decimal degrees values
        xlist,ylist = tweakutils.readcols(coordfile,cols=colnames)
    else:
        if isinstance(ra,np.ndarray):
            ralist = ra.tolist()
            declist = dec.tolist()
        elif not isinstance(ra, list):
            ralist = [ra]
            declist = [dec]
        else:
            ralist = ra
            declist = dec
        xlist  = [0]*len(ralist)
        ylist = [0]*len(ralist)
        if len(xlist) == 1:
            single_coord = True
        for i,(r,d) in enumerate(zip(ralist,declist)):
            # convert input value into decimal degrees value
            xval,yval = tweakutils.parse_skypos(r,d)
            xlist[i] = xval
            ylist[i] = yval

    # start by reading in WCS+distortion info for input image
    inwcs = wcsutil.HSTWCS(input)
    if inwcs.wcs.is_unity():
        print("####\nNo valid WCS found in {}.\n  Results may be invalid.\n####\n".format(input))

    # Now, convert pixel coordinates into sky coordinates
    try:
        outx,outy = inwcs.all_world2pix(xlist,ylist,1)
    except RuntimeError:
        outx,outy = inwcs.wcs_world2pix(xlist,ylist,1)

    # add formatting based on precision here...
    xstr = []
    ystr = []
    fmt = "%."+repr(precision)+"f"
    for x,y in zip(outx,outy):
        xstr.append(fmt%x)
        ystr.append(fmt%y)

    if verbose or (not verbose and util.is_blank(output)):
        print ('# Coordinate transformations for ',input)
        print('# X      Y         RA             Dec\n')
        for x,y,r,d in zip(xstr,ystr,xlist,ylist):
            print("%s  %s    %s  %s"%(x,y,r,d))

    # Create output file, if specified
    if output:
        f = open(output,mode='w')
        f.write("# Coordinates converted from %s\n"%input)
        for x,y in zip(xstr,ystr):
            f.write('%s    %s\n'%(x,y))
        f.close()
        print('Wrote out results to: ',output)

    if single_coord:
        outx = outx[0]
        outy = outy[0]

    return outx, outy
1233230
def bounding_box(positions):
    '''
    '''
    (x0, y0, z0) = (x1, y1, z1) = positions[0]
    for x, y, z in positions:
        x0 = min(x0, x)
        y0 = min(y0, y)
        z0 = min(z0, z)
        x1 = max(x1, x)
        y1 = max(y1, y)
        z1 = max(z1, z)
    return (x0, y0, z0), (x1, y1, z1)
427481
def bounding_boxes(self):
        

        cos_theta = np.cos(self.theta)
        sin_theta = np.sin(self.theta)
        ax = self.a_out * cos_theta
        ay = self.a_out * sin_theta
        bx = self.b_out * -sin_theta
        by = self.b_out * cos_theta
        dx = np.sqrt(ax*ax + bx*bx)
        dy = np.sqrt(ay*ay + by*by)

        xmin = self.positions[:, 0] - dx
        xmax = self.positions[:, 0] + dx
        ymin = self.positions[:, 1] - dy
        ymax = self.positions[:, 1] + dy

        return [BoundingBox._from_float(x0, x1, y0, y1)
                for x0, x1, y0, y1 in zip(xmin, xmax, ymin, ymax)]
205060
def get_wcs(self, data_x, data_y):
        
        img = self.fitsimage.get_image()
        ra, dec = img.pixtoradec(data_x, data_y)
        return ra, dec
360772
def get_bounding_box(self, maxdist):
        
        return utils.get_bounding_box([ps.location for ps in self], maxdist)
1078557
function bounds(boxes) {
	var width = 0
	var height = 0
	for (var i = 0; i < boxes.length; i++) {
		var box = boxes[i]
		var right = box.position[0] + box.size[0]
		var bottom = box.position[1] + box.size[1]
		if (right > width) {
			width = right
		}
		if (bottom > height) {
			height = bottom
		}
	}
	return [ width, height ]
}
1372937
def _get_corners(self, image):
        """"""
        temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        ret, corners = cv2.findChessboardCorners(temp,
                                                 (self.rows, self.columns))
        if not ret:
            raise ChessboardNotFoundError("No chessboard could be found.")
        cv2.cornerSubPix(temp, corners, (11, 11), (-1, -1),
                         (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS,
                          30, 0.01))
        return corners
422459
def get_bounding_box(self):
        
        pointlist = self.get_pointlist()

        # Initialize bounding box parameters to save values
        minx, maxx = pointlist[0][0]["x"], pointlist[0][0]["x"]
        miny, maxy = pointlist[0][0]["y"], pointlist[0][0]["y"]
        mint, maxt = pointlist[0][0]["time"], pointlist[0][0]["time"]

        # Adjust parameters
        for stroke in pointlist:
            for p in stroke:
                minx, maxx = min(minx, p["x"]), max(maxx, p["x"])
                miny, maxy = min(miny, p["y"]), max(maxy, p["y"])
                mint, maxt = min(mint, p["time"]), max(maxt, p["time"])
        return {"minx": minx, "maxx": maxx, "miny": miny, "maxy": maxy,
                "mint": mint, "maxt": maxt}
109629
def element_coordinates(cls, element):
        
        out = (0, 0, 0, 0)
        if 'title' in element.attrib:
            matches = cls.box_pattern.search(element.attrib['title'])
            if matches:
                coords = matches.group(1).split()
                out = Rect._make(int(coords[n]) for n in range(4))
        return out
568522
def t_coords(self, t_coords):
        """"""
        if not isinstance(t_coords, np.ndarray):
            raise TypeError('Texture coordinates must be a numpy array')
        if t_coords.ndim != 2:
            raise AssertionError('Texture coordinates must be a 2-dimensional array')
        if t_coords.shape[0] != self.n_points:
            raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points))
        if t_coords.shape[1] != 2:
            raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1]))
        if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0:
            raise AssertionError('Texture coordinates must be within (0, 1) range.')
        # convert the array
        vtkarr = numpy_to_vtk(t_coords)
        vtkarr.SetName('Texture Coordinates')
        self.GetPointData().SetTCoords(vtkarr)
        self.GetPointData().Modified()
        return
863302
def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1,
              window_size=None, float_descriptors=False,
              verbose=False, matlab_style=True):
    '''
    
    '''
    if not matlab_style:
        import warnings
        warnings.warn("matlab_style=False gets different results than matlab, "
                      "not sure why or how incorrect they are.")

    order = 'F' if matlab_style else 'C'
    data = as_float_image(data, dtype=np.float32, order=order)
    if data.ndim != 2:
        raise TypeError("data should be a 2d array")

    if window_size is not None:
        assert np.isscalar(window_size) and window_size >= 0

    # construct the dsift object
    M, N = data.shape
    dsift_p = vl_dsift_new_basic(M, N, step, size)

    try:
        dsift = dsift_p.contents

        # set parameters
        if bounds is not None:
            if matlab_style:
                y0, x0, y1, x1 = bounds  # transposed
            else:
                x0, y0, x1, y1 = bounds
            dsift.boundMinX = int(max(x0, 0))
            dsift.boundMinY = int(max(y0, 0))
            dsift.boundMaxX = int(min(x1, M - 1))
            dsift.boundMaxY = int(min(y1, N - 1))
            _vl_dsift_update_buffers(dsift_p)

        dsift.useFlatWindow = fast

        if window_size is not None:
            dsift.windowSize = window_size

        # get calculated parameters
        descr_size = dsift.descrSize
        num_frames = dsift.numFrames
        geom = dsift.geom

        if verbose:
            pr = lambda *a, **k: print('vl_dsift:', *a, **k)
            pr("image size         [W, H] = [{}, {}]".format(N, M))
            x0 = dsift.boundMinX + 1
            y0 = dsift.boundMinY + 1
            x1 = dsift.boundMaxX + 1
            y1 = dsift.boundMaxY + 1
            bound_args = [y0, x0, y1, x1] if matlab_style else [x0, y0, x1, y1]
            pr("bounds:            [minX,minY,maxX,maxY] = [{}, {}, {}, {}]"
                .format(*bound_args))
            pr("subsampling steps: stepX={}, stepY={}".format(
                    dsift.stepX, dsift.stepY))
            pr("num bins:          [numBinT, numBinX, numBinY] = [{}, {}, {}]"
                .format(geom.numBinT, geom.numBinX, geom.numBinY))
            pr("descriptor size:   {}".format(descr_size))
            pr("bin sizes:         [binSizeX, binSizeY] = [{}, {}]".format(
                    geom.binSizeX, geom.binSizeY))
            pr("flat window:       {}".format(bool(fast)))
            pr("window size:       {}".format(dsift.windowSize))
            pr("num of features:   {}".format(num_frames))

        # do the actual processing
        vl_dsift_process(dsift_p, data)

        # copy frames' locations, norms out
        # the frames are a structure of just 4 doubles (VLDsiftKeypoint),
        # which luckily looks exactly like an array of doubles. :)
        # NOTE: this might be platform/compiler-dependent...but it works with
        #       the provided binaries on os x, at least
        frames_p = cast(dsift.frames, c_double_p)
        frames_p_a = npc.as_array(frames_p, shape=(num_frames, 4))
        cols = [1, 0] if matlab_style else [0, 1]
        if norm:
            cols.append(3)
        frames = np.require(frames_p_a[:, cols], requirements=['C', 'O'])

        # copy descriptors into a new array
        descrs_p = npc.as_array(dsift.descrs, shape=(num_frames, descr_size))
        descrs = descrs_p * 512
        assert descrs.flags.owndata
        np.minimum(descrs, 255, out=descrs)
        if not float_descriptors:
            descrs = descrs.astype(np.uint8)  # TODO: smarter about copying?
        if matlab_style:
            new_order = np.empty(descr_size, dtype=int)
            vl_dsift_transpose_descriptor(new_order, np.arange(descr_size),
                geom.numBinT, geom.numBinX, geom.numBinY)
            descrs = descrs[:, new_order]
        # the old, super-slow way:
        ## # gross pointer arithmetic to get the relevant descriptor
        ## descrs_addr = addressof(descrs.contents)
        ## descrs_step = descr_size * sizeof(c_float)
        ##
        ## for k in range(num_frames):
        ##     out_frames[:2, k] = [frames[k].y + 1, frames[k].x + 1]
        ##     if norm:  # there's an implied / 2 in norm, because of clipping
        ##         out_frames[2, k] = frames[k].norm
        ##
        ##     # gross pointer arithmetic to get the relevant descriptor
        ##     the_descr = cast(descrs_addr + k * descrs_step, c_float_p)
        ##     transposed = vl_dsift_transpose_descriptor(
        ##         the_descr,
        ##         geom.numBinT, geom.numBinX, geom.numBinY)
        ##     out_descrs[:, k] = np.minimum(512. * transposed, 255.)

        return frames, descrs

    finally:
        vl_dsift_delete(dsift_p)
417765
def extract_bbox(layers):
    
    if not hasattr(layers, '__iter__'):
        layers = [layers]
    bboxes = [
        layer.bbox for layer in layers
        if layer.is_visible() and not layer.bbox == (0, 0, 0, 0)
    ]
    if len(bboxes) == 0:  # Empty bounding box.
        return (0, 0, 0, 0)
    lefts, tops, rights, bottoms = zip(*bboxes)
    return (min(lefts), min(tops), max(rights), max(bottoms))
1265052
def _get_data_bounds(data_bounds, pos=None, length=None):
    """""""
    if data_bounds is None or (isinstance(data_bounds, string_types) and
                               data_bounds == 'auto'):
        if pos is not None and len(pos):
            m, M = pos.min(axis=0), pos.max(axis=0)
            data_bounds = [m[0], m[1], M[0], M[1]]
        else:
            data_bounds = NDC
    data_bounds = np.atleast_2d(data_bounds)

    ind_x = data_bounds[:, 0] == data_bounds[:, 2]
    ind_y = data_bounds[:, 1] == data_bounds[:, 3]
    if np.sum(ind_x):
        data_bounds[ind_x, 0] -= 1
        data_bounds[ind_x, 2] += 1
    if np.sum(ind_y):
        data_bounds[ind_y, 1] -= 1
        data_bounds[ind_y, 3] += 1

    # Extend the data_bounds if needed.
    if length is None:
        length = pos.shape[0] if pos is not None else 1
    if data_bounds.shape[0] == 1:
        data_bounds = np.tile(data_bounds, (length, 1))

    # Check the shape of data_bounds.
    assert data_bounds.shape == (length, 4)

    _check_data_bounds(data_bounds)
    return data_bounds
275978
def get_bounding_box(df_points):
    '''
    
    '''
    xy_min = df_points[['x', 'y']].min()
    xy_max = df_points[['x', 'y']].max()

    wh = xy_max - xy_min
    wh.index = 'width', 'height'
    bbox = pd.concat([xy_min, wh])
    bbox.name = 'bounding_box'
    return bbox
884412
def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None):
    """"""

    from matplotlib.patches import Ellipse

    if logger is None:
        logger = logging.getLogger(__name__)

    region = bounding_box.slice
    ref_x = region[1].start
    ref_y = region[0].start
    logger.debug('region ofset is %s, %s', ref_x, ref_y)
    subimage = data[region].copy()
    bkg = sep.Background(subimage)
    data_sub = subimage - bkg
    objects = sep.extract(data_sub, 1.5, err=bkg.globalrms)
    # Select brightest object
    logger.debug('%d object found', len(objects))

    if len(objects) == 0:
        # print('No objects')
        return None

    iadx = objects['flux'].argmax()
    # plot background-subtracted image
    maxflux = objects[iadx]

    if debug_plot:
        fig, ax = plt.subplots()
        m, s = np.mean(data_sub), np.std(data_sub)
        ax.imshow(data_sub, interpolation='nearest', cmap='gray',
                  vmin=m - s, vmax=m + s, origin='lower',
                  extent=bounding_box.extent)
        if plot_reference:
            e = Ellipse(xy=(plot_reference[0], plot_reference[1]),
                        width=6,
                        height=6,
                        angle=0)
            e.set_facecolor('none')
            e.set_edgecolor('green')
            ax.add_artist(e)

        # plot an ellipse for each object
        for idx, obj in enumerate(objects):
            e = Ellipse(xy=(obj['x'] + ref_x, obj['y'] + ref_y),
                        width=6 * obj['a'],
                        height=6 * obj['b'],
                        angle=obj['theta'] * 180. / np.pi)
            e.set_facecolor('none')
            if idx == iadx:
                e.set_edgecolor('blue')
            else:
                e.set_edgecolor('red')
            ax.add_artist(e)
        return maxflux['x'], maxflux['y'], ax
    else:
        return maxflux['x'], maxflux['y']
1275022
def extent(self):

        

        return [min(self.x), max(self.x), min(self.y), max(self.y)]