Required for jupyter notebook to show raster as an interactive map.
968134
def _repr_html_(self):
        """"""
        TileServer.run_tileserver(self, self.footprint())
        capture = "raster: %s" % self._filename
        mp = TileServer.folium_client(self, self.footprint(), capture=capture)
        return mp._repr_html_()
630893
def interp_value(self, lat, lon, indexed=False):
        
        (px, py) = self.grid_coordinates.projection_to_raster_coords(lat, lon)
        if indexed:
            return self.raster_data[round(py), round(px)]
        else:
#             from scipy.interpolate import interp2d
#             f_interp = interp2d(self.grid_coordinates.x_axis, self.grid_coordinates.y_axis, self.raster_data, bounds_error=True)
#             return f_interp(lon, lat)[0]
            from scipy.ndimage import map_coordinates
            ret = map_coordinates(self.raster_data, [[py], [px]], order=1)  # linear interp
            return ret[0]
164014
def jupyter_notebook(script_blocks, gallery_conf):
    
    first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
    work_notebook = jupyter_notebook_skeleton()
    if first_cell is not None:
        add_code_cell(work_notebook, first_cell)
    fill_notebook(work_notebook, script_blocks)

    return work_notebook
900841
def raster_to_asc(raster_f, asc_f):
        
        raster_r = RasterUtilClass.read_raster(raster_f)
        RasterUtilClass.write_asc_file(asc_f, raster_r.data, raster_r.nCols, raster_r.nRows,
                                       raster_r.geotrans, raster_r.noDataValue)
237378
def mask_raster(in_raster, mask, out_raster):
        
        if is_string(in_raster) and is_string(out_raster):
            in_raster = [str(in_raster)]
            out_raster = [str(out_raster)]
        if len(in_raster) != len(out_raster):
            raise RuntimeError('input raster and output raster must have the same size.')

        maskr = RasterUtilClass.read_raster(mask)
        rows = maskr.nRows
        cols = maskr.nCols
        maskdata = maskr.data
        temp = maskdata == maskr.noDataValue
        for inr, outr in zip(in_raster, out_raster):
            origin = RasterUtilClass.read_raster(inr)
            if origin.nRows == rows and origin.nCols == cols:
                masked = numpy.where(temp, origin.noDataValue, origin.data)
            else:
                masked = numpy.ones((rows, cols)) * origin.noDataValue
                # TODO, the following loop should be optimized by numpy or numba
                for i in range(rows):
                    for j in range(cols):
                        if maskdata[i][j] == maskr.noDataValue:
                            continue
                        # get the center point coordinate of current cell
                        tempx, tempy = maskr.get_central_coors(i, j)
                        tempv = origin.get_value_by_xy(tempx, tempy)
                        if tempv is None:
                            continue
                        masked[i][j] = tempv
            RasterUtilClass.write_gtiff_file(outr, maskr.nRows, maskr.nCols, masked,
                                             maskr.geotrans, maskr.srs,
                                             origin.noDataValue, origin.dataType)
457498
void computeDescriptor(int row, int col) {
		// set location to top-left pixel
		locations.grow().set(col* pixelsPerCell,row* pixelsPerCell);

		TupleDesc_F64 d = descriptions.grow();

		int indexDesc = 0;
		for (int i = 0; i < cellsPerBlockY; i++) {
			for (int j = 0; j < cellsPerBlockX; j++) {
				Cell c = cells[(row+i)*cellCols + (col+j)];

				for (int k = 0; k < c.histogram.length; k++) {
					d.value[indexDesc++] = c.histogram[k];
				}
			}
		}

		// Apply SIFT style L2-Hys normalization
		DescribeSiftCommon.normalizeDescriptor(d,0.2);
	}
203399
public static void printWritableRasterData(Raster raster) {
        RandomIter iter = RandomIterFactory.create(raster, null);
        int cols = raster.getWidth();
        int rows = raster.getHeight();
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                printer.print(iter.getSampleDouble(c, r, 0));
                printer.print(separator);
            }
            printer.println();
        }
        iter.done();
    }
413669
def _parse_raster_info(self, prop=RASTER_INFO):
        

        raster_info = {}.fromkeys(_iso_definitions[prop], u'')

        # Ensure conversion of lists to newlines is in place
        raster_info['dimensions'] = get_default_for_complex_sub(
            prop=prop,
            subprop='dimensions',
            value=parse_property(self._xml_tree, None, self._data_map, '_ri_num_dims'),
            xpath=self._data_map['_ri_num_dims']
        )

        xpath_root = self._get_xroot_for(prop)
        xpath_map = self._data_structures[prop]

        for dimension in parse_complex_list(self._xml_tree, xpath_root, xpath_map, RASTER_DIMS):
            dimension_type = dimension['type'].lower()

            if dimension_type == 'vertical':
                raster_info['vertical_count'] = dimension['size']

            elif dimension_type == 'column':
                raster_info['column_count'] = dimension['size']
                raster_info['x_resolution'] = u' '.join(dimension[k] for k in ['value', 'units']).strip()

            elif dimension_type == 'row':
                raster_info['row_count'] = dimension['size']
                raster_info['y_resolution'] = u' '.join(dimension[k] for k in ['value', 'units']).strip()

        return raster_info if any(raster_info[k] for k in raster_info) else {}
713195
def select_visible_page_image(infiles, output_file, log, context):
    """"""

    options = context.get_options()
    if options.clean_final:
        image_suffix = '.pp-clean.png'
    elif options.deskew:
        image_suffix = '.pp-deskew.png'
    elif options.remove_background:
        image_suffix = '.pp-background.png'
    else:
        image_suffix = '.page.png'
    image = next(ii for ii in infiles if ii.endswith(image_suffix))

    pageinfo = get_pageinfo(image, context)
    if pageinfo.images and all(im.enc == 'jpeg' for im in pageinfo.images):
        log.debug(f'{page_number(image):4d}: JPEG input -> JPEG output')
        # If all images were JPEGs originally, produce a JPEG as output
        with Image.open(image) as im:
            # At this point the image should be a .png, but deskew, unpaper
            # might have removed the DPI information. In this case, fall back to
            # square DPI used to rasterize. When the preview image was
            # rasterized, it was also converted to square resolution, which is
            # what we want to give tesseract, so keep it square.
            fallback_dpi = get_page_square_dpi(pageinfo, options)
            dpi = im.info.get('dpi', (fallback_dpi, fallback_dpi))

            # Pillow requires integer DPI
            dpi = round(dpi[0]), round(dpi[1])
            im.save(output_file, format='JPEG', dpi=dpi)
    else:
        re_symlink(image, output_file, log)
686070
def raster_shpclip(r_fn, shp_fn, extent='raster', bbox=False, pad=None, invert=False, verbose=False):
    
    from pygeotools.lib import iolib
    from pygeotools.lib import warplib

    r_ds = iolib.fn_getds(r_fn)
    r_srs = get_ds_srs(r_ds)
    r_extent = ds_extent(r_ds)
    r_extent_geom = bbox2geom(r_extent)

    #NOTE: want to add spatial filter here to avoid reprojeting global RGI polygons, for example
    
    shp_ds = ogr.Open(shp_fn)
    lyr = shp_ds.GetLayer()
    shp_srs = lyr.GetSpatialRef()
    if not r_srs.IsSame(shp_srs):
        shp_ds = lyr_proj(lyr, r_srs)
        lyr = shp_ds.GetLayer()
    #This returns xmin, ymin, xmax, ymax
    shp_extent = lyr_extent(lyr)
    shp_extent_geom = bbox2geom(shp_extent)

    #Define the output - can set to either raster or shp
    #Could accept as cl arg
    out_srs = r_srs

    if extent == 'raster':
        out_extent = r_extent 
    elif extent == 'shp':
        out_extent = shp_extent
    elif extent == 'intersection':
        out_extent = geom_intersection([r_extent_geom, shp_extent_geom])
    elif extent == 'union':
        out_extent = geom_union([r_extent_geom, shp_extent_geom])
    else:
        print("Unexpected extent specification, reverting to input raster extent")
        out_extent = 'raster'

    #Add padding around shp_extent
    #Should implement buffer here
    if pad is not None:
        out_extent = pad_extent(out_extent, width=pad)

    print("Raster to clip: %s\nShapefile used to clip: %s" % (r_fn, shp_fn))
    if verbose:
        print(shp_extent) 
        print(r_extent)
        print(out_extent)

    r_ds = warplib.memwarp(r_ds, extent=out_extent, t_srs=out_srs, r='cubic')
    r = iolib.ds_getma(r_ds)

    #If bbox, return without clipping, otherwise, clip to polygons
    if not bbox:
        #Create binary mask from shp
        mask = shp2array(shp_fn, r_ds)
        if invert:
            mask = ~(mask)
        #Now apply the mask
        r = np.ma.array(r, mask=mask)
    #Return both the array and the dataset, needed for writing out
    #Should probably just write r to r_ds and return r_ds 
    return r, r_ds
1264671
def from_rasters(cls, rasters, relative_to_vrt=True, destination_file=None, nodata=None, mask_band=None):
        """"""
        if isinstance(rasters, list):
            doc = raster_list_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
        else:
            doc = raster_collection_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
        filename = cls._save_to_destination_file(doc, destination_file)
        return GeoRaster2.open(filename)
421707
def union(rasters):
    
    if sum([rasters[0].x_cell_size == i.x_cell_size for i in rasters]) == len(rasters) \
       and sum([rasters[0].y_cell_size == i.y_cell_size for i in rasters]) == len(rasters)\
       and sum([rasters[0].projection.ExportToProj4() == i.projection.ExportToProj4() for i in rasters]) == len(rasters):
        if sum([rasters[0].nodata_value == i.nodata_value for i in rasters]) == len(rasters):
            ndv = rasters[0].nodata_value
        else:
            ndv = np.nan
        if ndv == None:
            ndv = np.nan
        if sum([rasters[0].datatype == i.datatype for i in rasters]) == len(rasters):
            datatype = rasters[0].datatype
        else:
            datatype = None
        projection = rasters[0].projection
        lonmin = min([i.xmin for i in rasters])
        lonmax = max([i.xmax for i in rasters])
        latmin = min([i.ymin for i in rasters])
        latmax = max([i.ymax for i in rasters])
        shape = (np.abs(np.floor((latmax-latmin)/rasters[0].y_cell_size)).astype(int), np.floor((lonmax-lonmin)/rasters[0].x_cell_size).astype(int))
        out = ndv*np.ones(shape)
        outmask = np.ones(shape).astype(bool)
        for i in rasters:
            (row, col) = map_pixel(i.xmin, i.ymax, rasters[0].x_cell_size, rasters[0].y_cell_size, lonmin, latmax)
            out[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.data != i.nodata_value, i.raster.data,\
                                                         out[row:row+i.shape[0], col:col+i.shape[1]])
            outmask[row:row+i.shape[0], col:col+i.shape[1]] = np.where(i.raster.mask == False, False,\
                                                         outmask[row:row+i.shape[0], col:col+i.shape[1]])
        out = np.ma.masked_array(out, mask=outmask, fill_value=ndv)
        return GeoRaster(out, (lonmin, rasters[0].x_cell_size, 0.0, latmax, 0.0, rasters[0].y_cell_size), nodata_value=ndv, projection=projection, datatype=datatype)
    else:
        raise RasterGeoError('Rasters need to have same pixel sizes. Use the aggregate or dissolve functions to generate correct GeoRasters')
611212
def enable_notebook():
    """"""
    try:
        from IPython.core.getipython import get_ipython
    except ImportError:
        raise ImportError('This feature requires IPython 1.0+')
    ip = get_ipython()
    f = ip.display_formatter.formatters['text/html']
    f.for_type(np.ndarray, _array_to_html)
731516
def gdal2np_dtype(b):
    
    dt_dict = gdal_array.codes
    if isinstance(b, str):
        b = gdal.Open(b)
    if isinstance(b, gdal.Dataset):
        b = b.GetRasterBand(1)
    if isinstance(b, gdal.Band):
        b = b.DataType
    if isinstance(b, int):
        np_dtype = dt_dict[b]
    else:
        np_dtype = None
        print("Input must be GDAL Dataset or RasterBand object")
    return np_dtype
537602
def _showPDFpage(self, fz_srcpage, overlay=1, matrix=None, xref=0, clip=None, graftmap=None, _imgname=None):
        """"""
        return _fitz.Page__showPDFpage(self, fz_srcpage, overlay, matrix, xref, clip, graftmap, _imgname)
683997
def display(obj, raw_output=False, **kwargs):
    
    if not Store.loaded_backends() and isinstance(obj, Dimensioned):
        raise RuntimeError('To use display on a HoloViews object ensure '
                           'a backend is loaded using the holoviews '
                           'extension.')

    raw = True
    if isinstance(obj, GridSpace):
        with option_state(obj):
            output = grid_display(obj)
    elif isinstance(obj, (CompositeOverlay, ViewableElement)):
        with option_state(obj):
            output = element_display(obj)
    elif isinstance(obj, (Layout, NdLayout, AdjointLayout)):
        with option_state(obj):
            output = layout_display(obj)
    elif isinstance(obj, (HoloMap, DynamicMap)):
        with option_state(obj):
            output = map_display(obj)
    elif isinstance(obj, Plot):
        output = render(obj)
    else:
        output = obj
        raw = kwargs.pop('raw', False)

    if raw_output:
        return output
    elif isinstance(output, tuple):
        data, metadata = output
    else:
        data, metadata = output, {}
    return IPython.display.display(data, raw=raw, metadata=metadata, **kwargs)
283743
function Datamap( options ) {

    if ( typeof d3 === 'undefined' || typeof topojson === 'undefined' ) {
      throw new Error('Include d3.js (v3.0.3 or greater) and topojson on this page before creating a new map');
   }

    //set options for global use
    this.options = defaults(options, defaultOptions);
    this.options.geographyConfig = defaults(options.geographyConfig, defaultOptions.geographyConfig);
    this.options.bubblesConfig = defaults(options.bubblesConfig, defaultOptions.bubblesConfig);
    this.options.arcConfig = defaults(options.arcConfig, defaultOptions.arcConfig);

    //add the SVG container
    if ( d3.select( this.options.element ).select('svg').length > 0 ) {
      addContainer.call(this, this.options.element, this.options.height, this.options.width );
    }

    /* Add core plugins to this instance */
    this.addPlugin('bubbles', handleBubbles);
    this.addPlugin('legend', addLegend);
    this.addPlugin('arc', handleArcs);
    this.addPlugin('labels', handleLabels);

    //append style block with basic hoverover styles
    if ( ! this.options.disableDefaultStyles ) {
      addStyleBlock();
    }

    return this.draw();
  }