API Reference

Catalog

class Catalog(**kwargs)
get(catID, includeRelationships=False)

Retrieves the strip footprint WKT string given a cat ID.

Parameters:
  • catID (str) – The source catalog ID from the platform catalog.
  • includeRelationships (bool) – whether to include graph links to related objects. Default False.
Returns:

A dict object identical to the json representation of the catalog record

Return type:

record (dict)

get_address_coords(address)

Use the google geocoder to get latitude and longitude for an address string

Parameters:address – any address string
Returns:A tuple of (lat,lng)
get_data_location(catalog_id)

Find and return the S3 data location given a catalog_id.

Parameters:catalog_id – The catalog ID
Returns:A string containing the s3 location of the data associated with a catalog ID. Returns None if the catalog ID is not found, or if there is no data yet associated with it.
get_most_recent_images(results, types=[], sensors=[], N=1)

Return the most recent image

Parameters:
  • results – a catalog resultset, as returned from a search
  • types – array of types you want. optional.
  • sensors – array of sensornames. optional.
  • N – number of recent images to return. defaults to 1.
Returns:

single catalog item, or none if not found

get_strip_footprint_wkt(catID)

Retrieves the strip footprint WKT string given a cat ID.

Parameters:catID (str) – The source catalog ID from the platform catalog.
Returns:A POLYGON of coordinates.
Return type:footprint (str)
get_strip_metadata(catID)

Retrieves the strip catalog metadata given a cat ID.

Parameters:catID (str) – The source catalog ID from the platform catalog.
Returns:A metadata dictionary .

TODO: have this return a class object with interesting information exposed.

Return type:metadata (dict)
search(searchAreaWkt=None, filters=None, startDate=None, endDate=None, types=None)

Perform a catalog search

Parameters:
  • searchAreaWkt – WKT Polygon of area to search. Optional.
  • filters – Array of filters. Optional. Example:
  • [ – “(sensorPlatformName = ‘WORLDVIEW01’ OR sensorPlatformName =’QUICKBIRD02’)”, “cloudCover < 10”, “offNadirAngle < 10”
  • ]
  • startDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • endDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • types – Array of types to search for. Defaults to [“Acquisition”] if not provided.
Returns:

catalog search resultset

search_address(address, filters=None, startDate=None, endDate=None, types=None)

Perform a catalog search over an address string

Parameters:
  • address – any address string
  • filters – Array of filters. Optional. Example:
  • [ – “(sensorPlatformName = ‘WORLDVIEW01’ OR sensorPlatformName =’QUICKBIRD02’)”, “cloudCover < 10”, “offNadirAngle < 10”
  • ]
  • startDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • endDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • types – Array of types to search for. Optional. Example (and default): [“Acquisition”]
Returns:

catalog search resultset

search_point(lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None)

Perform a catalog search over a specific point, specified by lat,lng

Parameters:
  • lat – latitude
  • lng – longitude
  • filters – Array of filters. Optional. Example:
  • [ – “(sensorPlatformName = ‘WORLDVIEW01’ OR sensorPlatformName =’QUICKBIRD02’)”, “cloudCover < 10”, “offNadirAngle < 10”
  • ]
  • startDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • endDate – string. Optional. Example: “2004-01-01T00:00:00.000Z”
  • types – Array of types to search for. Optional. Example (and default): [“Acquisition”]
Returns:

catalog search resultset

CatalogImage

CatalogImage is a wrapper class that returns the appropriate image class for the catalog ID. This description applies to all of the other RDA-based classes.

CatalogImages are also Dask arrays and support all of their properties and methods. The most commonly used ones are listed here. Some methods are overridden to preserve geospatial information but other work identically.

class CatalogImage

Creates an image instance matching the type of the Catalog ID.

Parameters:
  • catalogID (str) – The source catalog ID from the platform catalog.
  • bbox (list of xmin, ymin, xmax, ymax) – Bounding box of image to crop to in EPSG:4326 units unless specified by from_proj
  • proj (str) – Optional EPSG projection string for the image, default is “EPSG:4326”
  • from_proj (str) – Optional projection string to define the coordinate system of bbox, default is “EPSG:4327”
  • dtype (str) – The dtype for the returned image (only valid for Worldview). One of: “int8”, “int16”, “uint16”, “int32”, “float32”, “float64”
  • band_type (str) – The product spec / band type for the image returned (band_type=’MS’|’Pan’)
  • bands (list of int) – bands to include in the image. Bands are zero-indexed.
  • pansharpen (bool) – Whether or not to return a pansharpened image (defaults to False)
  • acomp (bool) – Perform atmospheric compensation on the image (defaults to False, i.e. Top of Atmosphere value)
  • gsd (float) – The Ground Sample Distance (GSD) of the image. Must be defined in the same projected units as the image projection.
  • dra (bool) – Perform Dynamic Range Adjustment (DRA) on the image. DRA will override the dtype and return int8 data.
affine

The image affine transformation

Type:list
bounds

Spatial bounds of the image

Type:list
metadata

image metadata

Type:dict
ntiles

the number of tiles composing the image

Type:int
nbytes

size of the image in bytes

Type:int
proj

The image projection as EPSG string

Type:str
Returns:An image instance - one of IdahoImage, WV02, WV03_VNIR, LandsatImage, IkonosImage
Return type:image (ndarray)
aoi(**kwargs)

Subsets the Image by the given bounds

Parameters:
  • bbox (list) – optional. A bounding box array [minx, miny, maxx, maxy]
  • wkt (str) – optional. A WKT geometry string
  • geojson (str) – optional. A GeoJSON geometry dictionary
Returns:

an image instance of the same type

Return type:

image

geotiff(**kwargs)

Creates a geotiff on the filesystem

Parameters:
  • path (str) – optional, path to write the geotiff file to, default is ./output.tif
  • proj (str) – optional, EPSG string of projection to reproject to
  • spec (str) – optional, if set to ‘rgb’, write out color-balanced 8-bit RGB tif
  • bands (list) – optional, list of bands to export. If spec=’rgb’ will default to RGB bands, otherwise will export all bands
Returns:

path the geotiff was written to

Return type:

str

iterwindows(count=64, window_shape=(256, 256))

Iterate over random windows of an image

Parameters:
  • count (int) – the number of the windows to generate. Defaults to 64, if None will continue to iterate over random windows until stopped.
  • window_shape (tuple) – The desired shape of each image as (height, width) in pixels.
Yields:

image – an image of the given shape and same type.

map_blocks(*args, **kwargs)

Queue a deferred function to run on each block of image

This is identical to Dask’s map_block functinos, but returns a GeoDaskImage to preserve the geospatial information.

Args: see dask.Array.map_blocks

Returns:a dask array with the function queued up to run when the image is read
Return type:GeoDaskImage
ndvi(**kwargs)

Calculates Normalized Difference Vegetation Index using NIR and Red of an image.

Returns: numpy array with ndvi values

ndwi()

Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03. For Landsat8 and sentinel2 calculated by using Green and NIR bands.

Returns: numpy array of ndwi values

plot(spec='rgb', **kwargs)

Plot the image with MatplotLib

Plot sizing includes default borders and spacing. If the image is shown in Jupyter the outside whitespace will be automatically cropped to save size, resulting in a smaller sized image than expected.

Histogram options:
  • ‘equalize’: performs histogram equalization on the image.
  • ‘minmax’: stretch the pixel range to the minimum and maximum input pixel values. Equivalent to stretch=[0,100].
  • ‘match’: match the histogram to the Maps API imagery. Pass the additional keyword blm_source=’browse’ to match to the Browse Service (image thumbnail) instead.
  • ‘ignore’: Skip dynamic range adjustment, in the event the image is already correctly balanced and the values are in the correct range.

Gamma values greater than 1 will brighten the image midtones, values less than 1 will darken the midtones.

Plots generated with the histogram options of ‘match’ and ‘equalize’ can be combined with the stretch and gamma options. The stretch and gamma adjustments will be applied after the histogram adjustments.

Parameters:
  • w (float or int) – width of plot in inches at 72 dpi, default is 10
  • h (float or int) – height of plot in inches at 72 dpi, default is 10
  • title (str) – Title to use on the plot
  • fontsize (int) – Size of title font, default is 22. Size is measured in points.
  • bands (list) – bands to use for plotting, such as bands=[4,2,1]. Defaults to the image’s natural RGB bands. This option is useful for generating pseudocolor images when passed a list of three bands. If only a single band is provided, a colormapped plot will be generated instead.
  • cmap (str) – MatPlotLib colormap name to use for single band images. Default is colormap=’Grey_R’.
  • histogram (str) – either ‘equalize’, ‘minmax’, ‘match’, or ignore
  • stretch (list) – stretch the histogram between two percentile values, default is [2,98]
  • gamma (float) – adjust image gamma, default is 1.0
preview(**kwargs)

Show a slippy map preview of the image. Requires iPython.

Parameters:
  • image (image) – image object to display
  • zoom (int) – zoom level to intialize the map, default is 16
  • center (list) – center coordinates to initialize the map, defaults to center of image
  • bands (list) – bands of image to display, defaults to the image’s default RGB bands
pxbounds(geom, clip=False)

Returns the bounds of a geometry object in pixel coordinates

Parameters:
  • geom – Shapely geometry object or GeoJSON as Python dictionary or WKT string
  • clip (bool) – Clip the bounds to the min/max extent of the image
Returns:

bounds in pixels [min x, min y, max x, max y] clipped to image bounds

Return type:

list

randwindow(window_shape)

Get a random window of a given shape from within an image

Parameters:window_shape (tuple) – The desired shape of the returned image as (height, width) in pixels.
Returns:a new image object of the specified shape and same type
Return type:image
read(bands=None, **kwargs)

Reads data from a dask array and returns the computed ndarray matching the given bands

Parameters:bands (list) – band indices to read from the image. Returns bands in the order specified in the list of bands.
Returns:a numpy array of image data
Return type:ndarray
rgb(**kwargs)

Convert the image to a 3 band RGB for plotting

This method shares the same arguments as plot(). It will perform visual adjustment on the image and prepare the data for plotting in MatplotLib. Values are converted to an appropriate precision and the axis order is changed to put the band axis last.

warp(dem=None, proj='EPSG:4326', **kwargs)

Delayed warp across an entire AOI or Image

Creates a new dask image by deferring calls to the warp_geometry on chunks

Parameters:
  • dem (ndarray) – optional. A DEM for warping to specific elevation planes
  • proj (str) – optional. An EPSG proj string to project the image data into (“EPSG:32612”)
Returns:

a warped image as deferred image array

Return type:

daskarray

window_at(geom, window_shape)

Return a subsetted window of a given size, centered on a geometry object

Useful for generating training sets from vector training data Will throw a ValueError if the window is not within the image bounds

Parameters:
  • geom (shapely,geometry) – Geometry to center the image on
  • window_shape (tuple) – The desired shape of the image as (height, width) in pixels.
Returns:

image object of same type

Return type:

image

window_cover(window_shape, pad=True)

Iterate over a grid of windows of a specified shape covering an image.

The image is divided into a grid of tiles of size window_shape. Each iteration returns the next window.

Parameters:
  • window_shape (tuple) – The desired shape of each image as (height, width) in pixels.
  • pad – (bool): Whether or not to pad edge cells. If False, cells that do not have the desired shape will not be returned. Defaults to True.
Yields:

image – image object of same type.

RDAImage.materialize(node=None, bounds=None, callback=None, out_format='TILE_STREAM', **kwargs)

Materializes images into gbdx user buckets in s3. Note: This method is only available to RDA based image classes.

Parameters:
  • node (str) – the node in the graph to materialize
  • bounds (list) – optional bbox for cropping what gets materialized in s3
  • out_format (str) – VECTOR_TILE, VECTOR, TIF, TILE_STREAM
  • callback (str) – a callback url like an sns://
Returns:

the job_id of the materialization

Return type:

job_id (str)

RDAImage.materialize_status(job_id)

Checks the status of an materialize job.

Parameters:job_id (str) – the node in the graph to materialize
Returns:the status of the job
Return type:status (dict)
classmethod acomp_available(cat_id)

Checks to see if a CatalogID can be atmos. compensated or not.

Parameters:catalogID (str) – The catalog ID from the platform catalog.
Returns:Whether or not the image can be acomp’d
Return type:available (bool)
classmethod is_ordered(cat_id)

Checks to see if a CatalogID has been ordered or not.

Parameters:catalogID (str) – The catalog ID from the platform catalog.
Returns:Whether or not the image has been ordered
Return type:ordered (bool)

Base Image classes

IdahoImage

class IdahoImage

Image based on IDAHO virtual tiles

Like a CatalogImage, but takes an IDAHO ID when initialized. Band_type and pansharpen arguments are not supported because IDAHO multispectral and panchromatic images are stored separately.

Parameters:(str) – IDAHO ID

Example

>>> img = IdahoImage('87a5b5a7-5438-44bf-926a-c8c7bc153713')

LandsatImage

class LandsatImage

Dask based access to landsat image backed by rda Graphs.

TmsImage

class TmsImage

An image built from TMS tiles

Originally designed to access DigitalGlobe Maps API TMS service, now deprecated.

Instead of an ID the zoom level to use can be specified (default is 22). Changing the zoom level will change the resolution of the image. Note that different image sources are used at different zoom levels.

Supports the basic methods shared by Catalog Images such as plot() and geotiff().

Parameters:
  • url (str) – url of server with {x}, {y}, {z} templating
  • access_token – access token to use, this query string is automatically appended to the url
  • zoom (int) – (optional) Zoom level to use as the source if the image, default is 22
  • bbox (list) – (optional) Bounding box of AOI, if aoi() method is not used.

Example

>>> img = TmsImage(zoom=12, access_token='', url='https://a.tile.openstreetmap.org/{z}/{x}/{y}.png')

DemImage

class DemImage

Image class for Digital Elevation Model (DEM) data from the NED/SRTM dataset.

This class has no Catalog IDs and is created by passing an AOI. It shares most of the same methods as CatalogImage objects.

Parameters:
  • aoi (list) – list of coordinate in BBOX format
  • proj (str) – (optional) EPSG string of projection reproject to. Native projection is “EPSG:4326” (WGS84)

Example

>>> dem = DemImage(aoi=[5.279, 60.358, 5.402, 60.419])

S3Image

class S3Image

Dask based access to geotiffs on S3.

Parameters:
  • path (string) – path to the geotiff file in S3.
  • proj (string) – destination EPSG string, e.g. ‘EPSG:4326’ Perform optional reprojection if needed.
  • src_proj (string) – source EPSG string Define the source projection if it can’t be automatically determined.

Example

>>> img = S3Image('landsat-pds/c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B3.TIF')

RDATemplateImage

class RDATemplateImage

Creates an image instance matching the template ID with the given params.

Parameters:
  • template_id (str) – The RDA template ID
  • node_id (str) – the node ID to render as the image (defaults to None)
  • kwargs – Parameters needed to fill the template params
Returns:

An image instance

Return type:

image (ndarray)

Idaho

class Idaho(**kwargs)
create_leaflet_viewer(idaho_image_results, filename)

Create a leaflet viewer html file for viewing idaho images.

Parameters:
  • idaho_image_results (dict) – IDAHO image result set as returned from the catalog.
  • filename (str) – Where to save output html file.
describe_images(idaho_image_results)

Describe the result set of a catalog search for IDAHO images.

Parameters:idaho_image_results (dict) – Result set of catalog search.
Returns:
The full catalog-search response for IDAHO images
corresponding to the given catID.
Return type:results (json)
get_chip(coordinates, catid, chip_type='PAN', chip_format='TIF', filename='chip.tif')

Downloads a native resolution, orthorectified chip in tif format from a user-specified catalog id.

Parameters:
  • coordinates (list) – Rectangle coordinates in order West, South, East, North. West and East are longitudes, North and South are latitudes. The maximum chip size is (2048 pix)x(2048 pix)
  • catid (str) – The image catalog id.
  • chip_type (str) – ‘PAN’ (panchromatic), ‘MS’ (multispectral), ‘PS’ (pansharpened). ‘MS’ is 4 or 8 bands depending on sensor.
  • chip_format (str) – ‘TIF’ or ‘PNG’
  • filename (str) – Where to save chip.
Returns:

True if chip is successfully downloaded; else False.

get_images_by_catid(catid)

Retrieves the IDAHO image records associated with a given catid. :param catid: The source catalog ID from the platform catalog. :type catid: str

Returns:
The full catalog-search response for IDAHO images
within the catID.
Return type:results (json)
get_images_by_catid_and_aoi(catid, aoi_wkt)

Retrieves the IDAHO image records associated with a given catid. :param catid: The source catalog ID from the platform catalog. :type catid: str :param aoi_wkt: The well known text of the area of interest. :type aoi_wkt: str

Returns:
The full catalog-search response for IDAHO images
within the catID.
Return type:results (json)
get_tms_layers(catid, bands='4, 2, 1', gamma=1.3, highcutoff=0.98, lowcutoff=0.02, brightness=1.0, contrast=1.0)

Get list of urls and bounding boxes corrsponding to idaho images for a given catalog id.

Parameters:
  • catid (str) – Catalog id
  • bands (str) – Bands to display, separated by commas (0-7).
  • gamma (float) – gamma coefficient. This is for on-the-fly pansharpening.
  • highcutoff (float) – High cut off coefficient (0.0 to 1.0). This is for on-the-fly pansharpening.
  • lowcutoff (float) – Low cut off coefficient (0.0 to 1.0). This is for on-the-fly pansharpening.
  • brightness (float) – Brightness coefficient (0.0 to 1.0). This is for on-the-fly pansharpening.
  • contrast (float) – Contrast coefficient (0.0 to 1.0). This is for on-the-fly pansharpening.
Returns:

TMS urls. bboxes (list of tuples): Each tuple is (W, S, E, N) where (W,S,E,N) are the bounds of the corresponding idaho part.

Return type:

urls (list)

Ordering

class Ordering(**kwargs)
heartbeat()

Check the heartbeat of the ordering API

Args: None

Returns: True or False

order(image_catalog_ids, batch_size=100, callback=None)

Orders images from GBDX.

Parameters:
  • image_catalog_ids (str or list) – A single catalog id or a list of catalog ids.
  • batch_size (int) – The image_catalog_ids will be split into batches of batch_size. The ordering API max batch size is 100, if batch_size is greater than 100 it will be truncated.
  • callback (str) – A url to call when ordering is completed.
Returns:

If one batch, returns a string. If more

than one batch, returns a list of order ids, one for each batch.

Return type:

order_ids (str or list)

status(order_id)

Checks imagery order status. There can be more than one image per order and this function returns the status of all images within the order.

Parameters:order_id (str) – The id of the order placed.
Returns:List of dictionaries, one per image. Each dictionary consists of the keys ‘acquisition_id’, ‘location’ and ‘state’.

S3

class S3(**kwargs)
delete(location)

Delete content in bucket/prefix/location. Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif) Location is a wildcard match - ‘image’ will delete anything that matches “image*” including “image/foo/*” This treats objects purely as a key/value store and does not respect directories. Limited to deleting 1000 objects at a time.

Parameters:location (str) – S3 location within prefix
download(location, local_dir='.')

Download content from bucket/prefix/location. Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif) If location is a directory, all files in the directory are downloaded. If it is a file, then that file is downloaded.

Parameters:
  • location (str) – S3 location within prefix.
  • local_dir (str) – Local directory where file(s) will be stored. Default is here.
upload(local_file, s3_path=None)

Upload files to your DG S3 bucket/prefix.

Parameters:
  • local_file (str) – a path to a local file to upload, directory structures are not mirrored
  • s3_path – a key (location) on s3 to upload the file to
Returns:

s3 path file was saved to

Return type:

str

Examples

>>> upload('path/to/image.tif')
'mybucket/myprefix/image.tif'
>>> upload('./images/image.tif')
'mybucket/myprefix/image.tif'
>>> upload('./images/image.tif', s3_path='images/image.tif')
'mybucket/myprefix/images/image.tif'

Task

class Task(_Task__task_type, **kwargs)
set(**kwargs)

Set input values on task

Parameters:arbitrary_keys – values for the keys
Returns:None

Task Registry

class TaskRegistry(**kwargs)
delete(task_name)

Deletes a GBDX task.

Parameters:task_name (str) – Task name.
Returns:Response (str).
get_definition(task_name)

Gets definition of a registered GBDX task.

Parameters:task_name (str) – Task name.
Returns:Dictionary representing the task definition.
list()

Lists available and visible GBDX tasks.

Returns:List of tasks
register(task_json=None, json_filename=None)

Registers a new GBDX task.

Parameters:
  • task_json (dict) – Dictionary representing task definition.
  • json_filename (str) – A full path of a file with json representing the task definition.
  • one out of task_json and json_filename should be provided. (Only) –
Returns:

Response (str).

update(task_name, task_json)

Updates a GBDX task.

Parameters:
  • task_name (str) – Task name.
  • task_json (dict) – Dictionary representing updated task definition.
Returns:

Dictionary representing the updated task definition.

Vectors

class Vectors(**kwargs)
aggregate_query(searchAreaWkt, agg_def, query=None, start_date=None, end_date=None, count=10, index='vector-gbdx-alpha-catalog-v2-*')

Aggregates results of a query into buckets defined by the ‘agg_def’ parameter. The aggregations are represented by dicts containing a ‘name’ key and a ‘terms’ key holding a list of the aggregation buckets. Each bucket element is a dict containing a ‘term’ key containing the term used for this bucket, a ‘count’ key containing the count of items that match this bucket, and an ‘aggregations’ key containing any child aggregations.

Parameters:
  • searchAreaWkt (str) – wkt representation of the geometry
  • agg_def (str or AggregationDef) – the aggregation definitions
  • query (str) – a valid Elasticsearch query string to constrain the items going into the aggregation
  • start_date (str) – either an ISO-8601 date string or a ‘now’ expression (e.g. “now-6d” or just “now”)
  • end_date (str) – either an ISO-8601 date string or a ‘now’ expression (e.g. “now-6d” or just “now”)
  • count (int) – the number of buckets to include in the aggregations (the top N will be returned)
  • index (str) – the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes
Returns:

A (usually single-element) list of dict objects containing the aggregation results.

Return type:

results (list)

create(vectors)

Create a vectors in the vector service.

Parameters:vectors – A single geojson vector or a list of geojson vectors. Item_type and ingest_source are required.
Returns:IDs of the vectors created
Return type:(list)

Example

>>> vectors.create(
...     {
...         "type": "Feature",
...         "geometry": {
...             "type": "Point",
...             "coordinates": [1.0,1.0]
...         },
...         "properties": {
...             "text" : "item text",
...             "name" : "item name",
...             "item_type" : "type",
...             "ingest_source" : "source",
...             "attributes" : {
...                 "latitude" : 1,
...                 "institute_founded" : "2015-07-17",
...                 "mascot" : "moth"
...             }
...         }
...     }
... )
create_from_wkt(wkt, item_type, ingest_source, **attributes)

Create a single vector in the vector service

Parameters:
  • wkt (str) – wkt representation of the geometry
  • item_type (str) – item_type of the vector
  • ingest_source (str) – source of the vector
  • attributes – a set of key-value pairs of attributes
Returns:

string identifier of the vector created

Return type:

id (str)

get(ID, index='vector-web-s')

Retrieves a vector. Not usually necessary because searching is the best way to find & get stuff.

Parameters:
  • ID (str) – ID of the vector object
  • index (str) – Optional. Index the object lives in. defaults to ‘vector-web-s’
Returns:

A dict object identical to the json representation of the catalog record

Return type:

record (dict)

map(features=None, query=None, styles=None, bbox=[-180, -90, 180, 90], zoom=10, center=None, image=None, image_bounds=None, cmap='viridis', api_key=None, **kwargs)

Renders a mapbox gl map from a vector service query or a list of geojson features

Parameters:
  • features (list) – a list of geojson features
  • query (str) – a VectorServices query
  • styles (list) – a list of VectorStyles to apply to the features
  • bbox (list) – a bounding box to query for features ([minx, miny, maxx, maxy])
  • zoom (int) – the initial zoom level of the map
  • center (list) – a list of [lat, lon] used to center the map
  • api_key (str) – a valid Mapbox API key
  • image (dict) – a CatalogImage or a ndarray
  • image_bounds (list) – a list of bounds for image positioning
  • outside of GBDX Notebooks requires a MapBox API key, sign up for free at https (Use) – //www.mapbox.com/pricing/
  • the key using the api_key keyword or set an environmental variable called MAPBOX API KEY (Pass) –
  • cmap (str) – MatPlotLib colormap to use for rendering single band images (default: viridis)
query(searchAreaWkt, query, count=100, ttl='5m', index='vector-gbdx-alpha-catalog-v2-*')

Perform a vector services query using the QUERY API (https://gbdxdocs.digitalglobe.com/docs/vs-query-list-vector-items-returns-default-fields)

Parameters:
  • searchAreaWkt – WKT Polygon of area to search
  • query – Elastic Search query
  • count – Maximum number of results to return
  • ttl – Amount of time for each temporary vector page to exist
Returns:

List of vector results

query_iteratively(searchAreaWkt, query, count=100, ttl='5m', index='vector-gbdx-alpha-catalog-v2-*')

Perform a vector services query using the QUERY API (https://gbdxdocs.digitalglobe.com/docs/vs-query-list-vector-items-returns-default-fields)

Parameters:
  • searchAreaWkt – WKT Polygon of area to search
  • query – Elastic Search query
  • count – Maximum number of results to return
  • ttl – Amount of time for each temporary vector page to exist
Returns:

generator of vector results

tilemap(query, styles={}, bbox=[-180, -90, 180, 90], zoom=16, api_key=None, image=None, image_bounds=None, index='vector-user-provided', name='GBDX_Task_Output', **kwargs)

Renders a mapbox gl map from a vector service query

Vector Layers

class ImageLayer

A layer for rendering images and image arrays to slippy maps

Parameters:
  • image (str) – a vector tile url template
  • coordinates – the coordinate bounds (list of polygon corners) for placing the image
Returns:

An string of the layer definition

class VectorGeojsonLayer(geojson, **kwargs)

Represents a vector layer created from a geojson source

Parameters:
  • geojson (dict) – a list of geojson features to render
  • styles (list) – A list of style objects to be applied to the layer
class VectorLayer(styles=None, **kwargs)

Abstract constructor for a vector layer knowing how to render itself as javascript.

Parameters:styles (list) – list of styles for which to create layers
datasource

Renders the datasource to add to the map, referenced by the layers created by this layer instance.

Returns:a datasource json dict used for adding data to maps
Return type:datasource (dict)
layers

Renders the list of layers to add to the map.

Returns:list of layer entries suitable for use in mapbox-gl ‘map.addLayer()’ call
Return type:layers (list)
class VectorTileLayer(url=None, source_layer_name='GBDX_Task_Output', **kwargs)

Represents a vector tile layer in a tile map

Parameters:
  • url (str) – a vector tile url template
  • source_name (str) – the name of the source layer in the vector tiles
  • styles (list) – A list of style objects to be applied to the layer

Vector Styles

class CircleStyle(radius=1.0, **kwargs)

Creates a style entry for a circle layer.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#layers-circle

Parameters:
  • radius (float/StyleExpression/list) – the radius of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the circles (will accept either an an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
Returns:

A circle style which can be applied to a circle layer

paint()

Renders a javascript snippet suitable for use as a mapbox-gl circle paint entry

Returns:A dict that can be converted to a mapbox-gl javascript paint snippet
class FillExtrusionStyle(base=0, height=0, **kwargs)

Creates a style entry for extruded polygons (fills)

See https://www.mapbox.com/mapbox-gl-js/style-spec/#layers-fill-extrusion

Parameters:
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the circles (will accept either an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • base (int/StyleExpression) – the height at which to extrude the base of the features. must be less than or equal to the height.
  • height (int/StyleExpression) – the height with which to extrude features.
Returns:

A fill-extrusion style which can be applied to a fill-extrusion layer

paint()

Renders a javascript snippet suitable for use as a mapbox-gl fill-extrusion paint entry

Returns:A dict that can be converted to a mapbox-gl javascript paint snippet
class FillStyle(color='rgb(255, 0, 0)', opacity=0.5, outline_color=None, **kwargs)

Creates a style entry for a fill layer.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#layers-fill

Parameters:
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the fill (will accept either an an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • outline_color (str/StyleExpression/list) – the color of the outline (will accept either an an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
Returns:

A fill style which can be applied to a fill layer

paint()

Renders a javascript snippet suitable for use as a mapbox-gl fill paint entry

Returns:A dict that can be converted to a mapbox-gl javascript paint snippet
class HeatmapStyle(intensity=1, weight=1, color=None, radius=1, **kwargs)

Creates a style entry for heatmap layers.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#layers-heatmap

Parameters:
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • radius (int) – the radius of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the circles (will accept either an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • intensity (int/StyleExpression) – controls the intensity of the heatmap
  • weight (int/StyleExpression) – how much an individual point contributes to the heatmap
Returns:

A heatmap style which can be applied to a heatmap layer

paint()

Renders a javascript snippet suitable for use as a mapbox-gl heatmap paint entry

Returns:A dict that can be converted to a mapbox-gl javascript paint snippet
class LineStyle(cap='butt', join='miter', width=1.0, gap_width=0, blur=0, dasharray=None, **kwargs)

Creates a style entry for a line layer

See https://www.mapbox.com/mapbox-gl-js/style-spec/#layers-line

Parameters:
  • cap (str) – the line-ending style (‘butt’ (default), ‘round’, or ‘square’)
  • join (str) – the line-joining style (‘miter’ (default), ‘bevel’, or ‘round’)
  • width (float/StyleExpression/list) – the width of the line in pixels
  • gap_width (float/StyleExpression/list) – the width of the gap between the line and its casing in pixels
  • blur (float) – blur value in pixels
  • dasharray (list) – list of numbers indicating line widths for a dashed line
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the circles (will accept either an an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
Returns:

A line style which can be applied to a line layer

paint()

Renders a javascript snippet suitable for use as a mapbox-gl line paint entry

Returns:A dict that can be converted to a mapbox-gl javascript paint snippet
class VectorStyle(opacity=1.0, color='rgb(255, 0, 0)', translate=None, **kwargs)

Allows setting parameters common to all layer styles

Parameters:
  • opacity (float/StyleExpression/list) – the opacity of the circles (will accept either a float value, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • color (str/StyleExpression/list) – the color of the circles (will accept either an an rgb/hex/html-color-name string, a StyleExpression, or a list representing a mapbox-gl conditional expression)
  • translate – (float): the offset from the original vector location at which the vector will be rendered
static get_style_value(style_value)

Decides which value will be added to a style’s ‘paint’ configuration

Parameters:style_value – the value set on the style instance
Returns:a value suitable for inclusion in a ‘paint’ configuration
paint()

Renders a javascript snippet suitable for use as a mapbox-gl style entry

Returns:A dict that can be converted to a mapbox-gl javascript ‘paint’ snippet

Vector Style Expressions

class HeatmapExpression(stops=None, type=['linear'])

Creates an interpolation expression using heatmap-density for pixels in a heatmap layer. Values indicating range boundaries and the styling to apply to features in those ranges are supplied in the ‘stops’ dict.

Parameters:
  • stops (dict) – key/value pairs for range values and the style value to apply to values in that range
  • type (list) – interpolation type params
class InterpolateExpression(property_name=None, stops=None, type=['linear'])

Creates an interpolate expression, based on values in the supplied property of a feature. Values indicating range boundaries and the styling to apply to features in those ranges are supplied in the ‘stops’ dict.

The ‘type’ params must be a list whose values depend on the interpolation type (taken from the mapbox-gl documentation):

[“linear”]: interpolates linearly between the pair of stops just less than and just greater
than the input.
[“exponential”, base]: interpolates exponentially between the stops just less than and just greater than
the input. base controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.

[“cubic-bezier”, x1, y1, x2, y2]: interpolates using the cubic bezier curve defined by the given control points.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate

Parameters:
  • property_name (str) – the name of the feature property to match values against
  • stops (dict) – key/value pairs for range values and the style value to apply to values in that range
  • type (list) – interpolation type params
class MatchExpression(property_name=None, values=None, default_value=None)

Represents a mapbox-gl “match” conditional expression, where a set of values is matched against a property and styling applied based on the match. name in a feature. Values to match against and the styling to apply for those matches are supplied in the ‘values’ dict. If the feature property does not match any of the values provided, it will be styled with the provided default.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-match

Parameters:
  • property_name (str) – the name of the feature property to match values against
  • values (dict) – key/value pairs for property values and the style value to apply
  • default_value (str/float) – default value to apply when no value matches
class StepExpression(property_name=None, stops=None)

Represents a mapbox-gl “step” expression, creating discrete stepped results between provided stops for a given feature property. Values indicating range boundaries and the styling to apply to features in those ranges are supplied in the ‘stops’ dict.

See https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step

Parameters:
  • property_name (str) – the name of the feature property to match values against
  • stops (dict) – key/value pairs for range values and the style value to apply to values in that range
class StyleExpression

Represents a mapbox-gl conditional for styling, knowing how to turn itself into the appropriate javascript for use in styling a layer.

Returns:list of values for mapbox-gl conditional
class ZoomExpression(stops=None, type=['linear'])

Creates an interpolate expression, based on the map’s current zoom level. Values indicating range boundaries and the styling to apply to features in those ranges are supplied in the ‘stops’ dict.

Parameters:
  • stops (list) – zoom -> value list of zooms and values at specific zooms
  • type (list) – interpolation type params

Workflows

class Workflow(tasks, **kwargs)
cancel()

Cancel a running workflow.

Parameters:None
Returns:None
execute()

Execute the workflow.

Parameters:None
Returns:Workflow_id
generate_workflow_description()

Generate workflow json for launching the workflow against the gbdx api

Parameters:None
Returns:json string
list_workflow_outputs()

Get a list of outputs from the workflow that are saved to S3. To get resolved locations call workflow status. :param None:

Returns:list
savedata(output, location=None)

Save output data from any task in this workflow to S3

Parameters:
  • output – Reference task output (e.g. task.outputs.output1).
  • location (optional) – Subfolder under which the output will be saved. It will be placed under the account directory in gbd-customer-data bucket: s3://gbd-customer-data/{account_id}/{location} Leave blank to save to: workflow_output/{workflow_id}/{task_name}/{port_name}
Returns:

None

stderr

Get stderr from all the tasks of a workflow.

Returns:tasks with their stderr
Return type:(list)

Example

>>> workflow.stderr
[
    {
        "id": "4488895771403082552",
        "taskType": "AOP_Strip_Processor",
        "name": "Task1",
        "stderr": "............"
    }
]
stdout

Get stdout from all the tasks of a workflow.

Returns:tasks with their stdout
Return type:(list)

Example

>>> workflow.stdout
[
    {
        "id": "4488895771403082552",
        "taskType": "AOP_Strip_Processor",
        "name": "Task1",
        "stdout": "............"
    }
]
task_ids

Get the task IDs of a running workflow

Parameters:None
Returns:List of task IDs

Workflow API

class Workflow(**kwargs)
batch_workflow_cancel(batch_workflow_id)

Cancels GBDX batch workflow.

Parameters:workflow_id (batch) – Batch workflow id.
Returns:Batch Workflow status (str).
batch_workflow_status(batch_workflow_id)

Checks GBDX batch workflow status.

Parameters:workflow_id (batch) – Batch workflow id.
Returns:Batch Workflow status (str).
cancel(workflow_id)

Cancels a running workflow.

Parameters:workflow_id (str) – Workflow id.
Returns:Nothing
events(workflow_id)

Get workflow events.

Parameters:workflow_id (str) – Workflow id.
Returns:List of workflow events.
get(workflow_id)

Get existing workflow state and task information.

Parameters:workflow_id (str) – Workflow id.
Returns:Workflow object (dict).
get_stderr(workflow_id, task_id)

Get stderr for a particular task.

Parameters:
  • workflow_id (str) – Workflow id.
  • task_id (str) – Task id.
Returns:

Stderr of the task (string).

get_stdout(workflow_id, task_id)

Get stdout for a particular task.

Parameters:
  • workflow_id (str) – Workflow id.
  • task_id (str) – Task id.
Returns:

Stdout of the task (string).

launch(workflow)

Launches GBDX workflow.

Parameters:workflow (dict) – Dictionary specifying workflow tasks.
Returns:Workflow id (str).
launch_batch_workflow(batch_workflow)

Launches GBDX batch workflow.

Parameters:batch_workflow (dict) – Dictionary specifying batch workflow tasks.
Returns:Batch Workflow id (str).
search(lookback_h=12, owner=None, state='all')

Cancels GBDX batch workflow.

Params:

lookback_h (int): Look back time in hours. owner (str): Workflow owner to search by state (str): State to filter by, eg:

“submitted”, “scheduled”, “started”, “canceled”, “cancelling”, “failed”, “succeeded”, “timedout”, “pending”, “running”, “complete”, “waiting”, “all”
Returns:Batch Workflow status (str).
status(workflow_id)

Checks workflow status.

Parameters:workflow_id (str) – Workflow id.
Returns:Workflow status (str).