Geospatial

Functions:

concat(*imgs)

ImageCollection of imgs concatenated to one another, where imgs is a variable number of Image or ImageCollection objects.

conv2d(obj, filt)

2-D spatial convolution of an Image or ImageCollection.

load_geojson(geojson)

Create a Workflows Geometry, GeometryCollection, Feature, or FeatureCollection from a GeoJSON mapping.

load_geojson_file(path)

Create a Workflows Geometry, GeometryCollection, Feature, or FeatureCollection from a GeoJSON file.

where(condition, x, y)

Returns an Image or ImageCollection with values chosen from x or y depending on condition.

Classes:

Kernel(dims, data)

A Kernel is a proxy object holding the kernel when performing a 2-dimensional convolution.

Feature(geometry, properties)

Proxy GeoJSON Feature representing a Geometry and a Dict of properties.

FeatureCollection(features)

Proxy GeoJSON FeatureCollection constructed from a sequence of Features.

GeoContext([geometry, resolution, crs, …])

Proxy scenes.geocontext.GeoContext containing the spatial parameters (AOI, resolution, etc.) to use when loading geospatial data.

Geometry(type, coordinates)

Proxy GeoJSON Geometry representing a geometry’s type and coordinates.

GeometryCollection(geometries[, type])

Proxy GeoJSON GeometryCollection constructed from a sequence of Geometries.

ImageCollectionGroupby(imgs, func)

Dict-like object for a grouped ImageCollection.

Image()

Proxy Image; construct with from_id or from_scenes.

ImageCollection(images)

Proxy object representing a stack of Images; typically construct with from_id.

class Kernel(dims, data)[source]

A Kernel is a proxy object holding the kernel when performing a 2-dimensional convolution.

Examples

>>> from descarteslabs.workflows import Kernel
>>> kernel = Kernel(dims=(5,5), data=[1.0, 1.0, 1.0, 1.0, 1.0,
...                                   1.0, 2.0, 3.0, 2.0, 1.0,
...                                   1.0, 3.0, 4.0, 3.0, 1.0,
...                                   1.0, 2.0, 3.0, 2.0, 1.0,
...                                   1.0, 1.0, 1.0, 1.0, 1.0])
>>> kernel
<descarteslabs.workflows.types.geospatial.convolution.Kernel object at 0x...>

Methods:

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

Attributes:

data

List containing the kernel data in row-major format

dims

Tuple containing the dimensions of the kernel

compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") – The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") – The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

property data

List containing the kernel data in row-major format

Type

List[Float]

property dims

Tuple containing the dimensions of the kernel

Type

Tuple[Int, Int]

class Feature(geometry, properties)[source]

Proxy GeoJSON Feature representing a Geometry and a Dict of properties.

Examples

>>> from descarteslabs.workflows import Geometry, Feature
>>> geom = Geometry(type="Point", coordinates=[1, 2])
>>> feat = Feature(geometry=geom, properties={"foo": "bar"})
>>> feat
<descarteslabs.workflows.types.geospatial.feature.Feature object at 0x...>
>>> feat.compute() 
FeatureResult(geometry=GeometryResult(type=Point, coordinates=[1, 2]), properties={'foo': 'bar'})
>>> # constructing same Feature as previous example, but using from_geojson
>>> from descarteslabs.workflows import Feature
>>> geojson = {"type": "Feature",
...            "geometry": {"type": "Point", "coordinates": [1, 2]},
...            "properties": {"foo": "bar"}}
>>> feat = Feature.from_geojson(geojson)
>>> feat.compute().__geo_interface__ 
{'type': 'Feature',
 'geometry': {'type': 'Point', 'coordinates': [1, 2]},
 'properties': {'foo': 'bar'}}

Methods:

buffer(distance)

Buffer the area around self by a given distance.

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

from_geojson(geojson)

Construct a Workflows Feature from a GeoJSON mapping.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

rasterize([value, default_value])

Rasterize this Feature into an Image

Attributes:

geometry

Geometry

properties

Dict[Str, Any]

buffer(distance)

Buffer the area around self by a given distance.

Parameters

distance (Int or Float) – The distance (in decimal degrees) to buffer the area around the Geometry.

Returns

Return type

Same type as self

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> buffered = geom.buffer(2)
compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

classmethod from_geojson(geojson)[source]

Construct a Workflows Feature from a GeoJSON mapping.

Note that the GeoJSON must be relatively small (under 10MiB of serialized JSON).

Parameters

geojson (Dict) –

Returns

Return type

Feature

Example

>>> from descarteslabs.workflows import Feature
>>> geojson = {"type": "Feature",
...            "geometry": {"type": "Point", "coordinates": [1, 2]},
...            "properties": {"foo": "bar"}}
>>> feat = Feature.from_geojson(geojson)
>>> feat.compute().__geo_interface__ 
{'type': 'Feature',
 'geometry': {'type': 'Point', 'coordinates': [1, 2]},
 'properties': {'foo': 'bar'}}
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

rasterize(value=1, default_value=1)[source]

Rasterize this Feature into an Image

Parameters
  • value (Int, Float, Str, default=1) – Fill pixels within the Feature with this value. Pixels outside the Feature will be masked, and set to 0. If a string, it will look up that key in self.properties; the value there must be a number.

  • default_value (Int, Float, default=1) – Value to use if value is a string and the key does not exist in self.properties

Notes

Rasterization happens according to the GeoContext of the Job, so the geometry is projected into and rasterized at that CRS and resolution.

Returns

rasterized – An Image with 1 band named "features", the same properties as this Feature, and empty bandinfo.

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> feat = wf.Feature(geometry=geom, properties={"foo": 2})
>>> feat.rasterize(value=0.5)
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
>>> feat.rasterize(value=0.5).mean().compute(geoctx) 
0.5
>>> feat.rasterize(value="foo").mean().compute(geoctx) 
2
property geometry

Geometry

property properties

Dict[Str, Any]

class FeatureCollection(features)[source]

Proxy GeoJSON FeatureCollection constructed from a sequence of Features.

Examples

>>> from descarteslabs.workflows import Geometry, Feature, FeatureCollection
>>> geom = Geometry(type="Point", coordinates=[1, 2])
>>> feat = Feature(geometry=geom, properties={"foo": "bar"})
>>> fc = FeatureCollection(features=[feat, feat, feat])
>>> fc
<descarteslabs.workflows.types.geospatial.featurecollection.FeatureCollection object at 0x...>
>>> fc.compute() 
FeatureCollectionResult(features=(
    FeatureResult(geometry=GeometryResult(type=Point, coordinates=[1, 2]), properties={'foo': 'bar'}),
    FeatureResult(geometry=GeometryResult(type=Point, coordinates=[1, 2]), properties={'foo': 'bar'}),
    FeatureResult(geometry=GeometryResult(type=Point, coordinates=[1, 2]), properties={'foo': 'bar'})))
>>> # constructing similar FeatureCollection to previous example, but using from_geojson
>>> from descarteslabs.workflows import FeatureCollection
>>> geojson = {
...     "type": "FeatureCollection",
...     "features": [
...         {
...             "type": "Feature",
...             "geometry": {"type": "Point", "coordinates": [1, 2]},
...             "properties": {"foo": "bar"},
...         }
...     ],
... }
>>> fc = FeatureCollection.from_geojson(geojson)
>>> fc.compute().__geo_interface__ 
{'type': 'FeatureCollection',
 'features': [{'type': 'Feature',
   'geometry': {'type': 'Point', 'coordinates': [1, 2]},
   'properties': {'foo': 'bar'}}]}

Construct a FeatureCollection from a sequence of Features.

Methods:

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

contains(other)

Contains is equivalient to the Python in operator.

filter(func)

Filter elements from an iterable proxytype.

from_geojson(geojson)

Construct a Workflows FeatureCollection from a GeoJSON mapping.

from_vector_id(id)

Construct a Workflows FeatureCollection from a vector ID.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

length()

Length is equivalent to the Python len operator.

map(func)

Map a function over an iterable proxytype.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

rasterize([value, default_value, …])

Rasterize all Features into one Image

reduce(func[, initial])

Reduce a collection of elements to a single element.

sorted(key[, reverse])

Copy of this FeatureCollection, sorted by a key function.

Attributes:

features

List[Feature]

compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

contains(other)

Contains is equivalient to the Python in operator.

Parameters

other (Proxytype) – A Proxytype or type that can be promoted to a Proxytype

Returns

A Bool Proxytype

Return type

Bool

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.contains(2).compute() 
True
filter(func)

Filter elements from an iterable proxytype.

Parameters

func (Python callable) – A function that takes a single argument and returns a Bool Proxytype.

Returns

A Proxytype of the same type having only the elements where func returns True.

Return type

Proxtype

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> filtered = col.filter(lambda img: img.properties["date"].year == 2018)
classmethod from_geojson(geojson)[source]

Construct a Workflows FeatureCollection from a GeoJSON mapping.

Note that the GeoJSON must be relatively small (under 10MiB of serialized JSON).

Parameters

geojson (Dict) – A geojson FeatureCollection

Returns

Return type

FeatureCollection

Example

>>> import descarteslabs.workflows as wf
>>> geojson = {'type': 'FeatureCollection', 'features': [
... {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [1, 2]}, 'properties': {}}],
... 'properties' : {'name': 'Example'}}
>>> fc = wf.FeatureCollection.from_geojson(geojson=geojson)
>>> fc.features.compute() 
... [{'type': 'Feature',
... 'geometry': {'type': 'Point', 'coordinates': [1, 2]},
... 'properties': {}}
... ]
classmethod from_vector_id(id)[source]

Construct a Workflows FeatureCollection from a vector ID.

The FeatureCollection will contain every Feature within the GeoContext used in the computation.

Parameters

id (Str) – An ID of a product in the Descartes Labs Vector service.

Returns

Return type

FeatureCollection

Example

>>> from descarteslabs import vectors
>>> import descarteslabs.workflows as wf
>>> fc_vectors = vectors.FeatureCollection.create( 
...     product_id='my-vector-product-id',
...     title='Awesome Product',
...     description='Cool description')
>>> fc = wf.FeatureCollection.from_vector_id(fc_vectors.id) 
>>> fc.compute().__geo_interface__ 
{'type': 'FeatureCollection',
 'features': ...}
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

length()

Length is equivalent to the Python len operator.

Returns

An Int Proxytype

Return type

Int

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.length().compute() 
3
map(func)

Map a function over an iterable proxytype.

Parameters

func (Python callable) – A function that takes a single argument and returns another proxytype.

Returns

The return type is dependent on the func and the type of the element returned. For example, calling map over an ImageCollection with a function that returns the date of the Image will now be a List[Datetime].

Return type

Proxtype

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> dates = col.map(lambda img: img.properties["date"])
>>> type(dates).__name__
'List[Datetime]'
publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

rasterize(value=1, default_value=1, merge_algorithm='add')[source]

Rasterize all Features into one Image

Parameters
  • value (Int, Float, Str, default=1) –

    Fill enclosed pixels with this value. Pixels outside the FeatureCollection will be masked, and set to 0.

    If a string, it will look up that key in the properties of each Feature; the value there must be a number.

  • default_value (Int, Float, default=1) – Value to use if value is a string and the key does not exist in the properties of a Feature.

  • merge_algorithm (Str, default="add") – How to combine values where Features overlap. Options are "add", to sum the values, or "replace", to use the value from the Feature that comes last in the FeatureCollection.

Notes

Rasterization happens according to the GeoContext of the Job, so the geometry is projected into and rasterized at that CRS and resolution.

Returns

rasterized – An Image with 1 band named "features", and empty properties and bandinfo.

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> feat = wf.Feature(geometry=geom, properties={"foo": 1})
>>> fc = wf.FeatureCollection(features=[feat, feat, feat])
>>> fc.rasterize(value=0.5)
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
>>> fc.rasterize(value="foo").max().compute(geoctx) 
3
>>> fc.rasterize(value="foo", merge_algorithm="replace").max().compute(geoctx) 
1
reduce(func, initial='__NO_INITIAL_REDUCE_VALUE__')

Reduce a collection of elements to a single element.

NOTE: Optimized reducers such as sum have been implemented for some classes.

Parameters
  • func (Python callable) – A function where the left argument is the accumulated value (the result of the previous call to func) and the right argument is the next value from the iterable. The function should return a single proxtype.

  • initial (Proxytype, optional) – An optional proxtype to provide for the first iteration. If no value is provided, the first element will be used.

Returns

The return value of func for the last iteration of the collection.

Return type

Proxytype

Example

>>> from descarteslabs.workflows import List, Int
>>> def add(accumulated, current):
...     return accumulated + current
>>> my_list = List[Int]([1, 2])
>>> my_list.reduce(add, initial=Int(10)).compute()  
13
sorted(key, reverse=False)[source]

Copy of this FeatureCollection, sorted by a key function.

Parameters
  • key (Function) – Function which takes an Feature and returns a value to sort by.

  • reverse (Bool, default False) – Sorts in ascending order if False (default), descending if True.

Returns

sorted

Return type

FeatureCollection

Example

>>> import descarteslabs.workflows as wf
>>> fc = wf.FeatureCollection.from_geojson(geojson=
...     {'type': 'FeatureCollection', 'features': [
...     {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [2, 0]}, 'properties': {}},
...     {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [1, 0]}, 'properties': {}}],
...      'properties' : {'name': 'Example'}})
>>> # sort by first point coordinate in ascending order
>>> fc.sorted(key=lambda feat: feat.geometry.coordinates[0]).features.compute() 
... [{'type': 'Feature',
...   'geometry': {'type': 'Point', 'coordinates': [1, 0]},
...   'properties': {}},
...  {'type': 'Feature',
...   'geometry': {'type': 'Point', 'coordinates': [2, 0]},
...   'properties': {}}]
property features

List[Feature]

class GeoContext(geometry=None, resolution=None, crs=None, align_pixels=True, bounds=None, bounds_crs='EPSG:4326', shape=None, all_touched=False)[source]

Proxy scenes.geocontext.GeoContext containing the spatial parameters (AOI, resolution, etc.) to use when loading geospatial data. Equivalent to a scenes.geocontext.AOI, with the additional read-only properties arr_shape, gdal_geotrans, and projected_bounds.

You don’t often need to construct a Workflows GeoContext yourself. When you call compute(), you can pass in any scenes.geocontext.GeoContext, or use wf.map.geocontext() for the current map viewport.

Note: The raster_params of a GeoContext can be passed to raster.ndarray to get an equivalent array.

Examples

>>> from descarteslabs.workflows import GeoContext
>>> from descarteslabs import scenes
>>> scene = scenes.DLTile.from_latlon(10, 30, resolution=10, tilesize=512, pad=0)
>>> # the above scene could be passed to compute without being changed to a Workflows GeoContext
>>> geoctx = GeoContext.from_scenes(scene)
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'geometry': {'type': 'Polygon',
  'coordinates': (((29.964809031113013, 9.990748782946097),
    (30.011460043000678, 9.991170922969406),
    (30.011036444452188, 10.03741571582387),
    (29.964378844777645, 10.036991583007385),
    (29.964809031113013, 9.990748782946097)),)},
 'key': '512:0:10.0:36:-65:216',
 'resolution': 10.0,
 'tilesize': 512,
 'pad': 0,
 'crs': 'EPSG:32636',
 'bounds': (167200.0, 1105920.0, 172320.0, 1111040.0),
 'bounds_crs': 'EPSG:32636',
 'zone': 36,
 'ti': -65,
 'tj': 216,
 'proj4': '+proj=utm +zone=36 +datum=WGS84 +units=m +no_defs ',
 'wkt': 'PROJCS["WGS 84 / UTM zone 36N",GEOGCS["WGS 84",
         DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,
         AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],
         PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],
         UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],
         AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],
         PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",33],
         PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],
         PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],
         AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32636"]]',
 'projected_bounds': (167200.0, 1105920.0, 172320.0, 1111040.0),
 'arr_shape': (512, 512),
 'align_pixels': False,
 'geotrans': (10.0, 0.0, 167200.0, 0.0, -10.0, 1111040.0, 0.0, 0.0, 1.0),
 'gdal_geotrans': (167200.0, 10.0, 0.0, 1111040.0, 0.0, -10.0),
 'raster_params': {'dltile': '512:0:10.0:36:-65:216', 'align_pixels': False}}
>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_dltile_key('512:0:10.0:36:-65:216')
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'geometry': {'type': 'Polygon',
              'coordinates': (((29.964809031113013, 9.990748782946097),
                               (30.011460043000678, 9.991170922969406),
                               (30.011036444452188, 10.03741571582387),
                               (29.964378844777645, 10.036991583007385),
                               (29.964809031113013, 9.990748782946097)),)},
 'key': '512:0:10.0:36:-65:216',
 'resolution': 10.0,
 'tilesize': 512,
...
>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_xyz_tile(1, 2, 3)
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'x': 1,
 'y': 2,
 'z': 3,
 'geometry': {'type': 'Polygon',
 'coordinates': (((-90.0, 40.97989806962013),
                  (-90.0, 66.51326044311186),
                  (-135.0, 66.51326044311186),
                  (-135.0, 40.97989806962013),
                  (-90.0, 40.97989806962013)),)},
 'tilesize': 256,
 'crs': 'EPSG:3857',
...

Attributes:

align_pixels

Snap the bounds to whole-number intervals of resolution, ensuring non-fractional pixels.

all_touched

Bool: If True, this ensures that any source pixel which intersects the AOI GeoContext contributes to the raster result.

arr_shape

(height, width) (i.e.

bounds

Clip data to these (min_x, min_y, max_x, max_y) bounds, expressed in the coordinate reference system in bounds_crs.

bounds_crs

The coordinate reference system of the bounds, expressed as an EPSG code (like EPSG:4326) or a PROJ.4 definition.

crs

Coordinate reference system into which data will be projected, expressed as an EPSG code (like EPSG:4326) or a PROJ.4 definition.

gdal_geotrans

The 6-element GDAL geotrans this GeoContext will use.

geometry

Clip data to this Geometry (like a cutline).

projected_bounds

The actual bounds (in units of crs), if the bounds_crs convenience is used.

resolution

Distance, in units of the crs, that the edge of each pixel represents on the ground.

shape

The dimensions (rows, columns), in pixels, to fit the output array within.

Methods:

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

coords_to_index(x, y)

Convert spatial coordinates (x, y) in the GeoContext’s CRS to pixel coordinates (row, col).

from_dltile_key(key[, all_touched])

Construct a Workflows GeoContext from a DLTile key.

from_scenes(ctx)

Construct a Workflows GeoContext from a Scenes GeoContext

from_xyz_tile(x, y, z[, all_touched])

Construct a Workflows GeoContext for an XYZ tile in the OpenStreetMap tiling scheme.

index_to_coords(row, col)

Convert pixel coordinates (row, col) to spatial coordinates (x, y) in the GeoContext’s CRS.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

coords_to_index(x, y)[source]

Convert spatial coordinates (x, y) in the GeoContext’s CRS to pixel coordinates (row, col).

Parameters

Example

>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_dltile_key('512:0:10.0:36:-65:216')
>>> geoctx.coords_to_index(x=167220.0, y=1111000.0).compute() 
(4, 2)
classmethod from_dltile_key(key, all_touched=False)[source]

Construct a Workflows GeoContext from a DLTile key.

Parameters
  • key (str) –

  • all_touched (bool, default False) – If True, this ensures that any source pixel which intersects the AOI GeoContext contributes to the raster result. Normally this mode is not enabled, and its use is strongly discouraged. However, it can be useful when the AOI is smaller than a source pixel, which under many situations will return no result at all (i.e. entirely masked).

Returns

Return type

GeoContext

Example

>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_dltile_key('512:0:10.0:36:-65:216')
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'geometry': {'type': 'Polygon',
              'coordinates': (((29.964809031113013, 9.990748782946097),
                               (30.011460043000678, 9.991170922969406),
                               (30.011036444452188, 10.03741571582387),
                               (29.964378844777645, 10.036991583007385),
                               (29.964809031113013, 9.990748782946097)),)},
 'key': '512:0:10.0:36:-65:216',
 'resolution': 10.0,
 'tilesize': 512,
...
classmethod from_scenes(ctx)[source]

Construct a Workflows GeoContext from a Scenes GeoContext

Parameters

ctx (AOI, DLTile, or XYZTile) –

Returns

Return type

GeoContext

Example

>>> from descarteslabs.workflows import GeoContext
>>> from descarteslabs import scenes
>>> scene = scenes.DLTile.from_latlon(10, 30, resolution=10, tilesize=512, pad=0)
>>> # the above scene could be passed to compute without being changed to a Workflows GeoContext
>>> geoctx = GeoContext.from_scenes(scene)
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'geometry': {'type': 'Polygon',
  'coordinates': (((29.964809031113013, 9.990748782946097),
    (30.011460043000678, 9.991170922969406),
    (30.011036444452188, 10.03741571582387),
    (29.964378844777645, 10.036991583007385),
    (29.964809031113013, 9.990748782946097)),)},
 'key': '512:0:10.0:36:-65:216',
 'resolution': 10.0,
 'tilesize': 512,
 'pad': 0,
...
classmethod from_xyz_tile(x, y, z, all_touched=False)[source]

Construct a Workflows GeoContext for an XYZ tile in the OpenStreetMap tiling scheme.

Parameters
  • x (Int) –

  • y (Int) –

  • z (Int) –

  • all_touched (Bool, default False) – If True, this ensures that any source pixel which intersects the AOI GeoContext contributes to the raster result. Normally this mode is not enabled, and its use is strongly discouraged. However, it can be useful when the AOI is smaller than a source pixel, which under many situations will return no result at all (i.e. entirely masked).

Returns

Return type

GeoContext

Example

>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_xyz_tile(1, 2, 3)
>>> geoctx
<descarteslabs.workflows.types.geospatial.geocontext.GeoContext object at 0x...>
>>> geoctx.compute() 
{'x': 1,
 'y': 2,
 'z': 3,
 'geometry': {'type': 'Polygon',
 'coordinates': (((-90.0, 40.97989806962013),
                  (-90.0, 66.51326044311186),
                  (-135.0, 66.51326044311186),
                  (-135.0, 40.97989806962013),
                  (-90.0, 40.97989806962013)),)},
 'tilesize': 256,
 'crs': 'EPSG:3857',
...
index_to_coords(row, col)[source]

Convert pixel coordinates (row, col) to spatial coordinates (x, y) in the GeoContext’s CRS.

Parameters

Example

>>> from descarteslabs.workflows import GeoContext
>>> geoctx = GeoContext.from_dltile_key('512:0:10.0:36:-65:216')
>>> geoctx.index_to_coords(row=4, col=2).compute() 
(167220.0, 1111000.0)
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

property align_pixels

Snap the bounds to whole-number intervals of resolution, ensuring non-fractional pixels.

Imagine the bounds overlayed on on a grid of resolution (say, 30m) intervals. align_pixels expands the bounds outward to the next grid lines.

Type

Bool

property all_touched

Bool: If True, this ensures that any source pixel which intersects the AOI GeoContext contributes to the raster result. Normally this mode is not enabled, and its use is strongly discouraged. However, it can be useful when the AOI is smaller than a source pixel, which under many situations will return no result at all (i.e. entirely masked).

property arr_shape

(height, width) (i.e. (rows, cols)) of the array this GeoContext will produce.

This derived property (computed from projected_bounds, resolution, and align_pixels) cannot be set in __init__, but you can call compute on it (useful for uploading to Catalog).

Type

Tuple[Int, Int]

property bounds

Clip data to these (min_x, min_y, max_x, max_y) bounds, expressed in the coordinate reference system in bounds_crs.

If bounds_crs and crs differ, the actual bounds will be the envelope of the rectangle defined by bounds, when reprojected into crs.

Type

Tuple[Float, Float, Float, Float]

property bounds_crs

The coordinate reference system of the bounds, expressed as an EPSG code (like EPSG:4326) or a PROJ.4 definition.

Type

Str

property crs

Coordinate reference system into which data will be projected, expressed as an EPSG code (like EPSG:4326) or a PROJ.4 definition.

Type

Str

property gdal_geotrans

The 6-element GDAL geotrans this GeoContext will use.

This tuple is in the form (a, b, c, d, e, f), where:

  • a: top left pixel’s x-coordinate

  • b: west-east pixel resolution

  • c: row rotation; always 0 for GeoContext

  • d: top left pixel’s y-coordinate

  • e: column rotation; always 0 for GeoContext

  • f: north-south pixel resolution, always a negative value

This derived property (computed from projected_bounds, resolution, and align_pixels) cannot be set in __init__, but you can call compute on it (useful for uploading to Catalog).

Type

Tuple[Float, Float, Float, Float, Float, Float]

property geometry

Clip data to this Geometry (like a cutline).

Coordinates must be WGS84 (lat-lon). If None, data will just be clipped to bounds.

Type

Geometry

property projected_bounds

The actual bounds (in units of crs), if the bounds_crs convenience is used.

This is the envelope of the four corners defined by bounds, when those corners are reprojected from bounds_crs into crs.

This derived property cannot be set in __init__, but you can call compute on it (useful for uploading to Catalog).

Type

Tuple[Float, Float, Float, Float]

property resolution

Distance, in units of the crs, that the edge of each pixel represents on the ground.

Type

Float

property shape

The dimensions (rows, columns), in pixels, to fit the output array within.

Type

Tuple[Int, Int]

class Geometry(type, coordinates)[source]

Proxy GeoJSON Geometry representing a geometry’s type and coordinates.

Examples

>>> from descarteslabs.workflows import Geometry
>>> geom = Geometry(type="Point", coordinates=[1, 2])
>>> geom
<descarteslabs.workflows.types.geospatial.geometry.Geometry object at 0x...>
>>> geom.compute() 
GeometryResult(type=Point, coordinates=[1, 2])
>>> # constructing same Geometry as previous example, but using from_geojson
>>> from descarteslabs.workflows import Geometry
>>> geojson = {"type": "Point", "coordinates": [1, 2]}
>>> geom = Geometry.from_geojson(geojson)
>>> geom.compute().__geo_interface__ 
{'type': 'Point', 'coordinates': [1, 2]}

Methods:

buffer(distance)

Buffer the area around self by a given distance.

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

from_geo_interface(obj)

Construct a Workflows Geometry from a __geo_interface__.

from_geojson(geojson)

Construct a Workflows Geometry from a GeoJSON mapping.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

rasterize([value])

Rasterize this Geometry into an Image

Attributes:

coordinates

List[Any]

type

Str

buffer(distance)

Buffer the area around self by a given distance.

Parameters

distance (Int or Float) – The distance (in decimal degrees) to buffer the area around the Geometry.

Returns

Return type

Same type as self

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> buffered = geom.buffer(2)
compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

classmethod from_geo_interface(obj)[source]

Construct a Workflows Geometry from a __geo_interface__.

Parameters

obj (object with a __geo_interface__ attribute) – See https://gist.github.com/sgillies/2217756 for information about the __geo_interface__ attribute

Returns

Return type

Geometry

Example

>>> from descarteslabs import vectors
>>> from descarteslabs.workflows import Geometry
>>> polygon = { 'type': 'Polygon', 'coordinates': [[[-95, 42], [-93, 42], [-93, 40], [-95, 41], [-95, 42]]]}
>>> feat = vectors.Feature(geometry=polygon, properties={})
>>> feat.__geo_interface__ 
{'type': 'Polygon',
 'coordinates': (((-95.0, 42.0),
   (-93.0, 42.0),
   (-93.0, 40.0),
   (-95.0, 41.0),
   (-95.0, 42.0)),)}
>>> Geometry.from_geo_interface(feat).compute() 
GeometryResult(type=Polygon, coordinates=[[[-95.0, 42.0], [-93.0, 42.0],
... [-93.0, 40.0], [-95.0, 41.0], [-95.0, 42.0]]])
classmethod from_geojson(geojson)[source]

Construct a Workflows Geometry from a GeoJSON mapping.

Note that the GeoJSON must be relatively small (under 10MiB of serialized JSON).

Parameters

geojson (Dict) –

Returns

Return type

Geometry

Example

>>> from descarteslabs.workflows import Geometry
>>> geojson = {"type": "Point", "coordinates": [1, 2]}
>>> geom = Geometry.from_geojson(geojson)
>>> geom.compute().__geo_interface__ 
{'type': 'Point', 'coordinates': [1, 2]}
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

rasterize(value=1)

Rasterize this Geometry into an Image

Parameters

value (Int, Float, default=1) – Fill pixels within the Geometry with this value. Pixels outside the Geometry will be masked, and set to 0.

Note

Rasterization happens according to the GeoContext of the Job, so the geometry is projected into and rasterized at that CRS and resolution.

Returns

rasterized – An Image with 1 band named "features", and empty properties and bandinfo.

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> geom.rasterize(value=0.5)
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
property coordinates

List[Any]

property type

Str

class GeometryCollection(geometries, type='GeometryCollection')[source]

Proxy GeoJSON GeometryCollection constructed from a sequence of Geometries.

Examples

>>> from descarteslabs.workflows import Geometry, GeometryCollection
>>> geom = Geometry(type="Point", coordinates=[1, 2])
>>> gc = GeometryCollection(geometries=[geom, geom, geom])
>>> gc
<descarteslabs.workflows.types.geospatial.geometrycollection.GeometryCollection object at 0x...>
>>> gc.compute() 
GeometryCollectionResult(type=GeometryCollection,
        geometries=(
            GeometryResult(type=Point, coordinates=[1, 2]),
            GeometryResult(type=Point, coordinates=[1, 2]),
            GeometryResult(type=Point, coordinates=[1, 2])))
>>> # constructing similar GeometryCollection to previous example, but using from_geojson
>>> from descarteslabs.workflows import GeometryCollection
>>> geojson = {"type": "GeometryCollection", "geometries": [{"type": "Point", "coordinates": [1, 2]}]}
>>> gc = GeometryCollection.from_geojson(geojson)
>>> gc.compute().__geo_interface__ 
{'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': [1, 2]}]}

Methods:

buffer(distance)

Take the envelope of all the geometries, and buffer that by a given distance.

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

contains(other)

Contains is equivalient to the Python in operator.

filter(func)

Filter elements from an iterable proxytype.

from_geojson(geojson)

Construct a Workflows GeometryCollection from a GeoJSON mapping.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

length()

Length is equivalent to the Python len operator.

map(func)

Map a function over an iterable proxytype.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

rasterize([value])

Rasterize this Geometry into an Image

reduce(func[, initial])

Reduce a collection of elements to a single element.

sorted([key, reverse])

Copy of this collection, sorted by a key function.

Attributes:

geometries

List[Geometry]

type

Str

buffer(distance)[source]

Take the envelope of all the geometries, and buffer that by a given distance.

Parameters

distance (Int or Float) – The distance (in decimal degrees) to buffer the area around the Geometry.

Returns

Return type

Geometry

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> gc = wf.GeometryCollection(geometries=[geom, geom, geom])
>>> gc.buffer(2)
<descarteslabs.workflows.types.geospatial.geometry.Geometry object at 0x...>
compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

contains(other)

Contains is equivalient to the Python in operator.

Parameters

other (Proxytype) – A Proxytype or type that can be promoted to a Proxytype

Returns

A Bool Proxytype

Return type

Bool

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.contains(2).compute() 
True
filter(func)

Filter elements from an iterable proxytype.

Parameters

func (Python callable) – A function that takes a single argument and returns a Bool Proxytype.

Returns

A Proxytype of the same type having only the elements where func returns True.

Return type

Proxtype

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> filtered = col.filter(lambda img: img.properties["date"].year == 2018)
classmethod from_geojson(geojson)[source]

Construct a Workflows GeometryCollection from a GeoJSON mapping.

Note that the GeoJSON must be relatively small (under 10MiB of serialized JSON).

Parameters

geojson (Dict) –

Returns

Return type

GeometryCollection

Example

>>> from descarteslabs.workflows import GeometryCollection
>>> geojson = {"type": "GeometryCollection", "geometries":
... [{"type": "Point", "coordinates": [1, 2]}]}
>>> gc = GeometryCollection.from_geojson(geojson)
>>> gc.compute().__geo_interface__ 
{'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': [1, 2]}]}
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

length()[source]

Length is equivalent to the Python len operator.

Returns

An Int Proxytype

Return type

Int

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.length().compute() 
3
map(func)

Map a function over an iterable proxytype.

Parameters

func (Python callable) – A function that takes a single argument and returns another proxytype.

Returns

The return type is dependent on the func and the type of the element returned. For example, calling map over an ImageCollection with a function that returns the date of the Image will now be a List[Datetime].

Return type

Proxtype

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> dates = col.map(lambda img: img.properties["date"])
>>> type(dates).__name__
'List[Datetime]'
publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

rasterize(value=1)

Rasterize this Geometry into an Image

Parameters

value (Int, Float, default=1) – Fill pixels within the Geometry with this value. Pixels outside the Geometry will be masked, and set to 0.

Note

Rasterization happens according to the GeoContext of the Job, so the geometry is projected into and rasterized at that CRS and resolution.

Returns

rasterized – An Image with 1 band named "features", and empty properties and bandinfo.

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> geom = wf.Geometry(type="Point", coordinates=[1, 2])
>>> geom.rasterize(value=0.5)
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
reduce(func, initial='__NO_INITIAL_REDUCE_VALUE__')

Reduce a collection of elements to a single element.

NOTE: Optimized reducers such as sum have been implemented for some classes.

Parameters
  • func (Python callable) – A function where the left argument is the accumulated value (the result of the previous call to func) and the right argument is the next value from the iterable. The function should return a single proxtype.

  • initial (Proxytype, optional) – An optional proxtype to provide for the first iteration. If no value is provided, the first element will be used.

Returns

The return value of func for the last iteration of the collection.

Return type

Proxytype

Example

>>> from descarteslabs.workflows import List, Int
>>> def add(accumulated, current):
...     return accumulated + current
>>> my_list = List[Int]([1, 2])
>>> my_list.reduce(add, initial=Int(10)).compute()  
13
sorted(key=None, reverse=False)

Copy of this collection, sorted by a key function.

Parameters
  • key (Function, optional, default None) – Function which takes an element and returns a value to sort by. If not given, sorts by the elements themselves.

  • reverse (Bool, default False) – Sorts in ascending order if False (default), descending if True.

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 4, 2, 3])
>>> my_list.sorted().compute() 
[1, 2, 3, 4]
property geometries

List[Geometry]

property type

Str

class ImageCollectionGroupby(imgs, func)[source]

Dict-like object for a grouped ImageCollection.

If constructed from an empty ImageCollection or func results in empty groups, ImageCollectionGroupby.groups will return an empty Dict. Other operations (like map and count) will also return an empty Dict or an empty Image/ImageCollection.

Groups can be accessed with dict-like syntax. If indexing with a key that does not exist, an empty ImageCollection is returned.

Examples

>>> import descarteslabs.workflows as wf
>>> from descarteslabs.scenes import DLTile
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> # all Images from the same month, regardless of year
>>> col.groupby(dates="month")
<descarteslabs.workflows.types.geospatial.groupby.ImageCollectionGroupby[Int] object at 0x...>
>>>
>>> # group into 14-day bins
>>> col.groupby(lambda img: img.properties["date"] // wf.Timedelta(days=14))
<descarteslabs.workflows.types.geospatial.groupby.ImageCollectionGroupby[Datetime] object at 0x...>
>>>
>>> # group by "pass" ("ASCENDING" or "DESCENDING")
>>> col.groupby(lambda img: img.properties["pass"])
<descarteslabs.workflows.types.geospatial.groupby.ImageCollectionGroupby[Any] object at 0x...>
>>>
>>> # all Images from the same year and month
>>> month_grouped = col.groupby(dates=("year", "month"))
>>>
>>> # .mean(), etc. are applied to each group, then combined into one ImageCollection
>>> monthly = month_grouped.mean(axis="images")  # ImageCollection of monthly mean composites
>>>
>>> # a `group` field is added to each Image
>>> monthly.map(lambda img: img.properties['group']).compute(geoctx) 
[(2018, 1), (2018, 2), ... ]
>>>
>>> # use .map() to apply a function to each group, then combine into a Dict or ImageCollection
>>> monthly_l2_norm = month_grouped.map(lambda group, imgs: (imgs ** 2).sum(axis="images").sqrt())
>>> # ^ ImageCollection of each month's L2 norm
>>>
>>> monthly_medians = month_grouped.map(lambda group, imgs: imgs.median())
>>> # ^ Dict of (year, month) to median pixel value
>>>
>>> # you can select a single group with dict-like syntax
>>> feb = month_grouped[(2018, 2)]
>>> feb.compute(geoctx) 
ImageCollectionResult of length 2:
...
>>> # selecting a non-existent group returns an empty ImageCollection
>>> month_grouped[(1900, 1)].compute(geoctx) 
ImageCollectionResult of length 0:
...

You should construct ImageCollectionGroupby from ImageCollection.groupby in most cases.

Parameters
Returns

grouped

Return type

ImageCollectionGroupby

Methods:

compute(*args, **kwargs)

Compute a proxy object and wait for its result.

count([axis])

Apply ImageCollection.count to each group.

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

map(func)

Apply a function to each group as an ImageCollection and combine the results.

max([axis])

Apply ImageCollection.max to each group.

mean([axis])

Apply ImageCollection.mean to each group.

median([axis])

Apply ImageCollection.median to each group.

min([axis])

Apply ImageCollection.min to each group.

mosaic([reverse])

Apply ImageCollection.mosaic to each group.

one()

A Tuple of (group key, ImageCollection) for one random group.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

std([axis])

Apply ImageCollection.std to each group.

sum([axis])

Apply ImageCollection.sum to each group.

Attributes:

groups

Dict of group key -> ImageCollection

key_type

The type of the group keys

compute(*args, **kwargs)[source]

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

count(axis=None)[source]

Apply ImageCollection.count to each group.

Parameters

axis (Str or Tuple[Str], optional, default: None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.count(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.count(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.count(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.count(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.count(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.count(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

map(func)[source]

Apply a function to each group as an ImageCollection and combine the results.

func must take two arguments: the group, and an ImageCollection of all Images in that group.

If it returns an ImageCollection, the ImageCollections for all groups will be concatenated together.

If it returns an Image, those Images will be combined into a single ImageCollection.

If it returns any other type, map will return a Dict, where keys are groups and values are results of func.

Note that every Image in every ImageCollecion gets a "group" field added to its properties, so that field will be merged/dropped according to normal metadata broadcasting rules (i.e. will still be present on an Image composited from a group’s ImageCollection, since it’s the same for every Image.)

Parameters

func (Python function) – Function that takes an Int group number and ImageCollection

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(dates="month")
>>> groups.map(lambda group, col: col.pick_bands("red green blue"))# pick rgb bands for each group
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> # since the mapper function returns an ImageCollection, they are combined back into a single collection
>>> # each have a group key in their properties
>>> groups.map(lambda group, col: col.mean()) # equivalent to groups.mean()
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at...>
>>> # since the mapper function returns a Dict, map returns a Dict of group key to func results
max(axis=None)[source]

Apply ImageCollection.max to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.max(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.max(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.max(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.max(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.max(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.max(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
mean(axis=None)[source]

Apply ImageCollection.mean to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.mean(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.mean(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.mean(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.mean(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.mean(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.mean(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
median(axis=None)[source]

Apply ImageCollection.median to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.median(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.median(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.median(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.median(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.median(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.median(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
min(axis=None)[source]

Apply ImageCollection.min to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.min(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.min(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.min(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.min(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.min(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.min(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
mosaic(reverse=False)[source]

Apply ImageCollection.mosaic to each group.

Always returns an ImageCollection.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Returns

mosaic – The order of mosaicing is from last to first per group, meaning the last Image in the group’s ImageCollection is on top.

Return type

ImageCollection

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.mosaic()
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
one()[source]

A Tuple of (group key, ImageCollection) for one random group. Helpful for debugging.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(dates="month")
>>> groups.one().compute(geoctx) 
(5, ImageCollection...)
publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

std(axis=None)[source]

Apply ImageCollection.std to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.std(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.std(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.std(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.std(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.std(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.std(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
sum(axis=None)[source]

Apply ImageCollection.sum to each group.

Parameters

axis (Str or Tuple[Str] or None) – A string or tuple of strings of “pixels”, “images”, or “bands”

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> groups = col.groupby(lambda img: img.properties["date"].month)
>>> groups.sum(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.sum(axis="bands")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> groups.sum(axis="pixels")
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Dict[Str, Float]]] object at 0x...>
>>> groups.sum(axis=("bands", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, List[Float]] object at 0x...>
>>> groups.sum(axis=("images", "pixels"))
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Dict[Str, Float]] object at 0x...>
>>> groups.sum(axis=None)
<descarteslabs.workflows.types.containers.dict_.Dict[Int, Float] object at 0x...>
property groups

Dict of group key -> ImageCollection

property key_type

The type of the group keys

Type

Proxytype

class Image[source]

Proxy Image; construct with from_id or from_scenes.

An Image is a proxy object holding multiple (ordered) bands of raster data, plus some metadata.

Images don’t have a set spatial extent, CRS, resolution, etc: that’s determined at computation time by the GeoContext passsed in.

Supports unary operations such as negation and absolute value, as well as arithmetic and comparison operators such as >, +, and //.

Examples

>>> from descarteslabs.workflows import Image
>>> from descarteslabs.scenes import DLTile
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> img
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
>>> # create a geocontext for our computation, using DLTile
>>> geoctx = DLTile.from_latlon(35.6, -105.4, resolution=10, tilesize=512, pad=0)
>>> img.compute(geoctx) 
ImageResult:
  * ndarray: MaskedArray<shape=(27, 512, 512), dtype=float64>
  * properties: 'absolute_orbit', 'acquired', 'archived', 'area', ...
  * bandinfo: 'coastal-aerosol', 'blue', 'green', 'red', ...
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
>>>
>>> rgb = img.pick_bands("red green blue") # an Image with the red, green, and blue bands only
>>> rgb.compute(geoctx) 
ImageResult:
  * ndarray: MaskedArray<shape=(3, 512, 512), dtype=float64>
  * properties: 'absolute_orbit', 'acquired', 'archived', 'area', ...
  * bandinfo: 'red', 'green', 'blue'
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
>>> rgb.min(axis="pixels").compute(geoctx) # min along the pixels axis 
{'red': 0.0329, 'green': 0.0461, 'blue': 0.0629}

Methods:

arccos()

Element-wise inverse cosine of an Image.

arcsin()

Element-wise inverse sine of an Image.

arctan()

Element-wise inverse tangent of an Image.

clip_values([min, max])

Given an interval, band values outside the interval are clipped to the interval edge.

colormap([named_colormap, vmin, vmax])

Apply a colormap to an Image.

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

concat(*imgs)

ImageCollection with imgs concatenated onto this Image, where imgs is a variable number of Image or ImageCollection objects.

concat_bands(other_image)

New Image, with the bands in other_image appended to this one.

coords_to_index(x, y)

Convert spatial coordinates (x, y) to pixel coordinates (row, col) in the Image.

cos()

Element-wise cosine of an Image.

count([axis])

Count of valid (unmasked) pixels across the provided axis, or across all pixels in the image if no axis argument is provided.

exp()

Element-wise exponential of an Image.

from_id(image_id[, resampler, processing_level])

Create a proxy Image from an ID in the Descartes Labs catalog.

from_scene(scene)

Create a proxy image from a Scene object

getmask()

Mask of this Image, as a new Image with one boolean band named 'mask'.

index_to_coords(row, col)

Convert pixel coordinates (row, col) in the ImageCollection into spatial coordinates (x, y).

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

log()

Element-wise natural log of an Image.

log10()

Element-wise base 10 log of an Image.

log1p()

Element-wise log of 1 + an Image.

log2()

Element-wise base 2 log of an Image.

map_bands(func)

Map a function over each band in self.

mask(mask[, replace])

New Image, masked with a boolean Image or vector object.

max([axis])

Maximum pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

mean([axis])

Mean pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

median([axis])

Median pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

min([axis])

Minimum pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

pick_bands(bands[, allow_missing])

New Image, containing only the given bands.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

reduction(operation[, axis])

Reduction along the provided axis, or across all pixels in the image if no axis argument is provided.

rename_bands(*new_positional_names, **new_names)

New Image, with bands renamed by position or name.

replace_empty_with(fill[, mask, bandinfo])

Replace Image, if empty, with fill value.

scale_values(range_min, range_max[, …])

Given an interval, band values will be scaled to the interval.

sin()

Element-wise sine of an Image.

sqrt()

Element-wise square root of an Image.

square()

Element-wise square of an Image.

std([axis])

Standard deviation along the provided axis, or across all pixels in the image if no axis argument is provided.

sum([axis])

Sum of pixel values across the provided axis, or across all pixels in the image if no axis argument is provided.

tan()

Element-wise tangent of an Image.

tile_layer([name, scales, colormap, …])

A WorkflowsLayer for this Image.

unpack_bands(bands)

Convenience method for unpacking multiple bands into Python variables.

value_at(x, y)

Given coordinates x, y, returns the pixel values from an Image in a Dict by bandname.

visualize(name[, scales, colormap, …])

Add this Image to wf.map, or replace a layer with the same name.

with_bandinfo(band, **bandinfo)

New Image, with the given **bandinfo fields added to the specified band’s bandinfo.

with_properties(**properties)

New Image, with the given **properties fields added to the Image’s properties.

without_bandinfo(band, *bandinfo_keys)

New Image, with each given *bandinfo_keys field dropped from the specified band’s bandinfo.

without_properties(*property_keys)

New Image, with each given property field name dropped from the Image’s properties field.

Attributes:

bandinfo

Metadata about the bands of the Image.

nbands

The number of bands in the Image.

ndarray

MaskedArray

properties

Metadata for the Image.

arccos()[source]

Element-wise inverse cosine of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.arccos().compute(geoctx) 
ImageResult:
...
arcsin()[source]

Element-wise inverse sine of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.arcsin().compute(geoctx) 
ImageResult:
...
arctan()[source]

Element-wise inverse tangent of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.arctan().compute(geoctx) 
ImageResult:
...
clip_values(min=None, max=None)[source]

Given an interval, band values outside the interval are clipped to the interval edge.

If the Image is empty, returns the empty Image.

Parameters
  • min (float or list, default None) – Minimum value of clipping interval. If None, clipping is not performed on the lower interval edge.

  • max (float or list, default None) – Maximum value of clipping interval. If None, clipping is not performed on the upper interval edge. Different per-band clip values can by given by using lists for min or max, in which case they must be the same length as the number of bands.

  • Note (min and max cannot both be None. At least one must be specified.) –

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> img.compute(geoctx).ndarray 
masked_array(
  data=[[[0.34290000000000004, 0.34290000000000004, 0.34290000000000004,
                ..., 0.0952, 0.0952, 0.0952],
...
>>> clipped = img.clip_values(0.08, 0.3).compute(geoctx) 
>>> clipped.ndarray 
masked_array(
  data=[[[0.3, 0.3, 0.3, ..., 0.0952, 0.0952, 0.0952],
...
colormap(named_colormap='viridis', vmin=None, vmax=None)[source]

Apply a colormap to an Image. Image must have a single band.

If the Image is empty, returns the empty Image.

Parameters
  • named_colormap (Str, default "viridis") – The name of the Colormap registered with matplotlib. See https://matplotlib.org/users/colormaps.html for colormap options.

  • vmin (float, default None) – The minimum value of the range to normalize the bands within. If specified, vmax must be specified as well.

  • vmax (float, default None) – The maximum value of the range to normalize the bands within. If specified, vmin must be specified as well.

  • Note (If neither vmin nor vmax are specified, the min and max values in the Image will be used.) –

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.pick_bands("red").colormap("magma", vmin=0.1, vmax=0.8).compute(geoctx) 
ImageResult:
...
compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

concat(*imgs)[source]

ImageCollection with imgs concatenated onto this Image, where imgs is a variable number of Image or ImageCollection objects.

Images, properties, and bandinfo are concatenated. All imagery must have the same number of bands with identical names. Any empty Images or ImageCollections will not be concatenated.

Parameters

*imgs (variable number of Image or ImageCollection objects) –

Returns

concatenated

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.concat(img, img).compute(geoctx) 
ImageCollectionResult of length 3:
...
concat_bands(other_image)[source]

New Image, with the bands in other_image appended to this one.

If band names overlap, the band from the other Image will be suffixed with “_1”.

If either Image is empty, returns another empty Image.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> red = img.pick_bands("red")
>>> green = img.pick_bands("green")
>>> rg = red.concat_bands(green).compute(geoctx) 
>>> rg.bandinfo.keys() 
['red', 'green']
coords_to_index(x, y)[source]

Convert spatial coordinates (x, y) to pixel coordinates (row, col) in the Image.

Parameters

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> rgb = img.pick_bands("red green blue") # an Image with the red, green, and blue bands only
>>> rgb.index(0, 0).compute(ctx) 
(459040.0, 3942400.0)
cos()[source]

Element-wise cosine of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.cos().compute(geoctx) 
ImageResult:
...
count(axis=None)[source]

Count of valid (unmasked) pixels across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the valid pixel count.

Options:

  • "pixels": Returns a Dict[Str, Float] containing the count of valid pixels in each band.

  • "bands": Returns a new Image with one band, "count", containing the count of valid pixels across all bands, for each pixel.

  • None: Returns a Float that represents the count of valid pixels in the image.

Returns

Count of valid pixels across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> count_img = img.count(axis="bands")
>>> band_counts = img.count(axis="pixels")
>>> count = img.count(axis=None)
exp()[source]

Element-wise exponential of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.exp().compute(geoctx) 
ImageResult:
...
classmethod from_id(image_id, resampler=None, processing_level=None)[source]

Create a proxy Image from an ID in the Descartes Labs catalog.

Parameters
  • image_id (Str) – ID of the image

  • resampler (Str, optional, default None) – Algorithm used to interpolate pixel values when scaling and transforming the image to the resolution and CRS eventually defined by a GeoContext. Possible values are near (nearest-neighbor), bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1, q3.

  • processing_level (Str, optional) – Image processing level. Possible values depend on the particular product and bands. Some examples include 'toa', 'surface', 'toa_refectance', 'toa_radiance'.

Returns

img

Return type

Image

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1", processing_level="surface")
>>> img.compute(geoctx) 
ImageResult:
...
classmethod from_scene(scene)[source]

Create a proxy image from a Scene object

getmask()[source]

Mask of this Image, as a new Image with one boolean band named 'mask'.

If the Image is empty, returns the empty Image.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> mask = img.getmask().compute(geoctx) 
>>> mask.ndarray 
masked_array(
  data=[[[0, 0, 0, ..., 1, 1, 1],
...
>>> mask.bandinfo 
{'mask': {}}
index_to_coords(row, col)[source]

Convert pixel coordinates (row, col) in the ImageCollection into spatial coordinates (x, y).

Parameters
  • row (int) – The row

  • col (int) – The col

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> rgb = img.pick_bands("red green blue") # an Image with the red, green, and blue bands only
>>> rgb.index(0, 0).compute(ctx) 
(459040.0, 3942400.0)
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

log()[source]

Element-wise natural log of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.log().compute(geoctx) 
ImageResult:
...
log10()[source]

Element-wise base 10 log of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.log10().compute(geoctx) 
ImageResult:
...
log1p()[source]

Element-wise log of 1 + an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.log1p().compute(geoctx) 
ImageResult:
...
log2()[source]

Element-wise base 2 log of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.log2().compute(geoctx) 
ImageResult:
...
map_bands(func)

Map a function over each band in self.

The function must take 2 arguments:

  1. Str: the band name

  2. Image: 1-band Image

If the function returns an Image, map_bands will also return one Image, containing the bands from all Images returned by func concatenated together.

Otherwise, map_bands will return a Dict of the results of each call to func, where the keys are the band names.

Note that func can return Images with more than 1 band, but the band names must be unique across all of its results.

Parameters

func (Python function) – Function that takes a Str and an Image.

Returns

  • Image if func returns Image, otherwise Dict[Str, T],

  • where T is the return type of func.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> mapped = img.map_bands(lambda name, band: band / 2) # divide each band by 2
mask(mask, replace=False)[source]

New Image, masked with a boolean Image or vector object.

If the mask is empty, the original Image is returned unchanged. (If the Image was already empty, it is still empty even if the mask is non-empty.)

Parameters
  • mask (Image, Geometry, Feature, FeatureCollection) –

    A single-band Image of boolean values, (such as produced by img > 2, for example) where True means masked (invalid).

    Or, a vector (Geometry, Feature, or FeatureCollection), in which case pixels outside the vector are masked.

  • replace (Bool, default False) –

    Whether to add to the Image’s current mask, or replace it.

    If False (default):

    • Adds this mask to the current one, so already-masked pixels remain masked.

    • Masked-out pixels in the mask are ignored (considered False).

    If True:

    • Replaces the current mask with this new one.

    • Masked-out pixels in the mask are also masked in the result.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> red = img.pick_bands("red")
>>> masked = red.mask(red < 0.2) # mask all bands where red band is low
max(axis=None)[source]

Maximum pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the maximum.

Options:

  • "pixels": Returns a Dict[Str, Float] of each band’s maximum pixel value.

  • "bands": Returns a new Image with one band, "max", containing the maximum value for each pixel across all bands.

  • None: Returns a Float that represents the maximum pixel value of the entire image.

Returns

Maximum pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> max_img = img.max(axis="bands")
>>> band_maxs = img.max(axis="pixels")
>>> max_pixel = img.max(axis=None)
mean(axis=None)[source]

Mean pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the mean.

Options:

  • "pixels": Returns a Dict[Str, Float] of each band’s mean pixel value.

  • "bands": Returns a new Image with one band, "mean", containing the mean value for each pixel across all bands.

  • None: Returns a Float that represents the mean pixel value of the entire image.

Returns

Mean pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> mean_img = img.mean(axis="bands")
>>> band_means = img.mean(axis="pixels")
>>> mean_pixel = img.mean(axis=None)
median(axis=None)[source]

Median pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the median.

Options:

  • "pixels": Returns a Dict[Str, Float] of each band’s median pixel value.

  • "bands": Returns a new Image with one band, "median", containing the median value for each pixel across all bands.

  • None: Returns a Float that represents the median pixel value of the entire image.

Returns

Median pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> median_img = img.median(axis="bands")
>>> band_medians = img.median(axis="pixels")
>>> median_pixel = img.median(axis=None)
min(axis=None)[source]

Minimum pixel value across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the minimum.

Options:

  • "pixels": Returns a Dict[Str, Float] of each band’s minimum pixel value.

  • "bands": Returns a new Image with one band, "min", containing the minimum value for each pixel across all bands.

  • None: Returns a Float that represents the minimum pixel value of the entire image.

Returns

Minimum pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> min_img = img.min(axis="bands")
>>> band_mins = img.min(axis="pixels")
>>> min_pixel = img.min(axis=None)
pick_bands(bands, allow_missing=False)

New Image, containing only the given bands.

Bands can be given as a sequence of strings, or a single space-separated string (like "red green blue").

Bands on the new Image will be in the order given.

If names are duplicated, repeated names will be suffixed with _N, with N incrementing from 1 for each duplication (pick_bands("red red red") returns bands named red red_1 red_2).

If the Image is empty, returns the empty Image.

If allow_missing is False (default), raises an error if given band names that don’t exist in the Image. If allow_missing is True, any missing names are dropped, and if none of the names exist, returns an empty Image.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> rgb = img.pick_bands("red green blue")
>>> rgb.bandinfo.keys().inspect(ctx)  
["red", "green", "blue"]
>>> red = img.pick_bands(["red", "nonexistent_band_name"], allow_missing=True)
>>> red.bandinfo.keys().inspect(ctx)  
["red"]
>>> s1_img = Image.from_id("sentinel-1:GRD:meta_2020-06-09_049A0903_S1B")
>>> vv_vh_vv = s1_img.pick_bands("vv vh vv")
>>> vv_vh_vv.bandinfo.keys().inspect(ctx)  
["vv", "vh", "vv_1"]
publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

reduction(operation, axis=None)[source]

Reduction along the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters
  • operation ({"min", "max", "mean", "median", "sum", "std", "count"}) – A string indicating the reduction method to apply along the specified axis.

  • axis ({None, "pixels", "bands"}) –

    A Python string indicating the axis along which to perform the reduction.

    Options:

    • "pixels": Returns a Dict[Str, Float] containing the reduction across each band.

    • "bands": Returns a new Image with one band, "std", containing the reduction across all bands for each pixel.

    • None: Returns a Float that represents the reduction of the entire image.

Returns

Reduction along the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> std_img = img.reduction("std", axis="bands")
>>> band_stds = img.reduction("std", axis="pixels")
>>> std = img.reduction("std", axis=None)
rename_bands(*new_positional_names, **new_names)

New Image, with bands renamed by position or name.

New names can be given positionally (like rename_bands('new_red', 'new_green')), which renames the i-th band to the i-th argument.

Or, new names can be given by keywords (like rename_bands(red="new_red")) mapping from old band names to new ones.

To eliminate ambiguity, names cannot be given both ways.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> renamed = img.rename_bands(red="new_red", blue="new_blue", green="new_green")
replace_empty_with(fill, mask=True, bandinfo=None)[source]

Replace Image, if empty, with fill value.

Parameters
  • fill (int, float, Image) – The value to fill the Image with. If int or float, the fill value will be broadcasted to band dimensions as determined by the geocontext and provided bandinfo.

  • mask (bool, default True) – Whether to mask the band data. If mask is True and fill is an Image, the original Image mask will be overridden and all underlying data will be masked. If mask is False and fill is an Image, the original mask is left as is. If fill is scalar, the Image constructed will be fully masked or fully un-masked data if mask is True and False respectively.

  • bandinfo (dict, default None) – Bandinfo used in constructing new Image. If fill is an Image, bandinfo is optional, and will be ignored if provided. If fill is a scalar, the bandinfo will be used to determine the number of bands on the new Image, as well as become the bandinfo for it.

Example

>>> from descarteslabs.workflows import Image
>>> empty_img = Image.from_id("id_without_surface_reflectance", processing_level="surface") 
>>> empty_img.compute(geoctx) 
EmptyImage
>>> non_empty = empty_img.replace_empty_with(9999, bandinfo={"red":{}, "green":{}, "blue":{}}) 
>>> non_empty.compute(geoctx) 
ImageResult:
  * ndarray: MaskedArray<shape=(3, 512, 512), dtype=float64>
  * properties:
  * bandinfo: 'red', 'green', 'blue'
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
scale_values(range_min, range_max, domain_min=None, domain_max=None)[source]

Given an interval, band values will be scaled to the interval.

If the Image is empty, returns the empty Image.

Parameters
  • range_min (float) – Minimum value of output range.

  • range_max (float) – Maximum value of output range.

  • domain_min (float, default None) – Minimum value of the domain. If None, the band minimim is used.

  • domain_max (float, default None) – Maximum value of the domain. If None, the band maximum is used.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> img.compute(geoctx).ndarray 
masked_array(
  data=[[[0.34290000000000004, 0.34290000000000004, 0.34290000000000004, ...,
...
>>> scaled = img.scale_values(0.5, 1).compute(geoctx) 
>>> scaled.ndarray 
masked_array(
  data=[[[0.500010245513916, 0.500010245513916, 0.500010245513916, ...,
...
sin()[source]

Element-wise sine of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.sin().compute(geoctx) 
ImageResult:
...
sqrt()[source]

Element-wise square root of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.sqrt().compute(geoctx) 
ImageResult:
...
square()[source]

Element-wise square of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.square().compute(geoctx) 
ImageResult:
...
std(axis=None)[source]

Standard deviation along the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the standard deviation.

Options:

  • "pixels": Returns a Dict[Str, Float] containing the standard deviation across each band.

  • "bands": Returns a new Image with one band, "std", containing the standard deviation across all bands for each pixel.

  • None: Returns a Float that represents the standard deviation of the entire image.

Returns

Standard deviation along the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> std_img = img.std(axis="bands")
>>> band_stds = img.std(axis="pixels")
>>> std = img.std(axis=None)
sum(axis=None)[source]

Sum of pixel values across the provided axis, or across all pixels in the image if no axis argument is provided.

If the Image is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "pixels", "bands"}) –

A Python string indicating the axis along which to take the sum.

Options:

  • "pixels": Returns a Dict[Str, Float] containing the sum of the pixel values for each band.

  • "bands": Returns a new Image with one band, "sum", containing the sum across all bands for each pixel.

  • None: Returns a Float that represents the sum of all pixels in the image.

Returns

Sum of pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float] or Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_033035_20170516_20170516_01_RT_v1")
>>> sum_img = img.sum(axis="bands")
>>> band_sums = img.sum(axis="pixels")
>>> sum_pixels = img.sum(axis=None)
tan()[source]

Element-wise tangent of an Image.

If the Image is empty, returns the empty Image.

Example

>>> import descarteslabs.workflows as wf
>>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
>>> img.tan().compute(geoctx) 
ImageResult:
...
tile_layer(name=None, scales=None, colormap=None, checkerboard=True, log_level=10, **parameter_overrides)[source]

A WorkflowsLayer for this Image.

Generally, use Image.visualize for displaying on map. Only use this method if you’re managing your own ipyleaflet Map instances, and creating more custom visualizations.

An empty Image will be rendered as a checkerboard (default) or blank tile.

Parameters
  • name (str) – The name of the layer.

  • scales (list of lists, default None) –

    The scaling to apply to each band in the Image.

    If Image contains 3 bands, scales must be a list like [(0, 1), (0, 1), (-1, 1)].

    If Image contains 1 band, scales must be a list like [(0, 1)], or just (0, 1) for convenience

    If None, each 256x256 tile will be scaled independently. based on the min and max values of its data.

  • colormap (str, default None) – The name of the colormap to apply to the Image. Only valid if the Image has a single band.

  • checkerboard (bool, default True) – Whether to display a checkerboarded background for missing or masked data.

  • log_level (int, default logging.DEBUG) – Only listen for log records at or above this log level during tile computation. See https://docs.python.org/3/library/logging.html#logging-levels for valid log levels.

  • **parameter_overrides (JSON-serializable value, Proxytype, or ipywidgets.Widget) –

    Values—or ipywidgets—for any parameters that this Image depends on.

    If this Image depends on wf.widgets, you don’t have to pass anything for those—any widgets it depends on are automatically linked to the layer. However, you can override their current values (or widgets) by passing new values (or ipywidget instances) here.

    Values can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

    If an ipywidgets.Widget is given, it’s automatically linked, so updating the widget causes the argument value to change, and the layer to update.

    Once these initial argument values are set, they can be modified by assigning to parameters on the returned WorkflowsLayer.

    For more information, see the docstring to ParameterSet.

Returns

layer

Return type

WorkflowsLayer

unpack_bands(bands)

Convenience method for unpacking multiple bands into Python variables.

Returns a Python tuple of self.pick_bands called for each band name. Bands can be given as a space-separated string of band names, or a sequence.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> red, green, blue = img.unpack_bands("red green blue")
value_at(x, y)[source]

Given coordinates x, y, returns the pixel values from an Image in a Dict by bandname.

Coordinates must be given in the same coordinate reference system as the GeoContext you call compute with. For example, if your GeoContext uses "EPSG:4326", you’d give x and y in lon, lat degrees. If your GeoContext uses UTM, you’d give x and y in UTM coordinates.

When using visualize to view the Image on a map, x and y must always be given in web-mercator ("EPSG:3857") coordinates (with units of meters, not degrees).

If the Image is empty, returns an empty Dict.

Parameters

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> rgb = img.pick_bands("red green blue") # an Image with the red, green, and blue bands only
>>> rgb.value_at(459040.0, 3942400.0) 
'{red': 0.39380000000000004
'green': 0.40950000000000003,
'blue': 0.44870000000000004}
visualize(name, scales=None, colormap=None, checkerboard=True, log_level=10, map=None, **parameter_overrides)[source]

Add this Image to wf.map, or replace a layer with the same name.

An empty Image will be rendered as a checkerboard (default) or blank tile.

Parameters
  • name (str) –

    The name of the layer.

    If a layer with this name already exists on wf.map, it will be replaced with this Image, scales, and colormap. This allows you to re-run cells in Jupyter calling visualize without adding duplicate layers to the map.

  • scales (list of lists, default None) –

    The scaling to apply to each band in the Image.

    If Image contains 3 bands, scales must be a list like [(0, 1), (0, 1), (-1, 1)].

    If Image contains 1 band, scales must be a list like [(0, 1)], or just (0, 1) for convenience

    If None, each 256x256 tile will be scaled independently. based on the min and max values of its data.

  • colormap (str, default None) – The name of the colormap to apply to the Image. Only valid if the Image has a single band.

  • checkerboard (bool, default True) – Whether to display a checkerboarded background for missing or masked data.

  • log_level (int, default logging.DEBUG) – Only listen for log records at or above this log level during tile computation. See https://docs.python.org/3/library/logging.html#logging-levels for valid log levels.

  • map (Map or MapApp, optional, default None) – The Map (or plain ipyleaflet Map) instance on which to show the Image. If None (default), uses wf.map, the singleton Workflows MapApp object.

  • **parameter_overrides (JSON-serializable value, Proxytype, or ipywidgets.Widget) –

    Values—or ipywidgets—for any parameters that this Image depends on.

    If this Image depends on wf.widgets, you don’t have to pass anything for those—any widgets it depends on are automatically linked to the layer. However, you can override their current values (or widgets) by passing new values (or ipywidget instances) here.

    Values can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

    If an ipywidgets.Widget is given, it’s automatically linked, so updating the widget causes the argument value to change, and the map to update. Running visualize again and passing in a different widget instance will un-link the old one automatically.

    Once these initial argument values are set, they can be modified by assigning to parameters on the returned WorkflowsLayer.

    For more information, see the docstring to ParameterSet.

Returns

layer – The layer displaying this Image. Either a new WorkflowsLayer if one was created, or the layer with the same name that was already on the map.

Return type

WorkflowsLayer

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> nir, red = col.unpack_bands(["nir", "red"])
>>> ndvi = wf.normalized_difference(nir, red)
>>> max_ndvi = ndvi.max()
>>> highest_ndvi = max_ndvi > wf.parameter("threshold", wf.Float)
>>> lyr = highest_ndvi.visualize(
...     name="My Cool Max NDVI",
...     scales=[0, 1],
...     colormap="viridis",
...     threshold=0.4,
... )  
>>> wf.map  
>>> # `wf.map` actually displays the map; right click and open in new view in JupyterLab
>>> lyr.parameters.threshold = 0.3  
>>> # update map with a new value for the "threshold" parameter
with_bandinfo(band, **bandinfo)[source]

New Image, with the given **bandinfo fields added to the specified band’s bandinfo.

If a given field already exists on the band’s bandinfo, it will be overwritten.

If the Image is empty, returns the empty Image.

Parameters
  • band (Str) – The name of the band whose bandinfo will be added to.

  • **bandinfo (dict) – Fields that will be added to the band’s bandinfo

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> with_foo = img.with_bandinfo("red", foo="baz").compute(geoctx) 
>>> with_foo.bandinfo["red"]["foo"] 
'baz'
with_properties(**properties)[source]

New Image, with the given **properties fields added to the Image’s properties.

If a given field already exists on the Image’s properties, it will be overwritten.

If the Image is empty, returns the empty Image.

Parameters

**properties (Proxytype, or any JSON-serializable value) – Fields that will be added to the image’s properties

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> with_foo = img.with_properties(foo="baz").compute(geoctx) 
>>> with_foo.properties["foo"] 
'baz'
without_bandinfo(band, *bandinfo_keys)[source]

New Image, with each given *bandinfo_keys field dropped from the specified band’s bandinfo.

If a given field doesn’t exists on the band’s bandinfo, it will be a no-op.

Parameters
  • band (Str) – The name of the band whose bandinfo will be pruned.

  • *bandinfo_keys (Str) – Fields that will be dropped from the band’s bandinfo

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.compute(geoctx).bandinfo["red"] 
{'color': 'Red',
 'data_description': 'TOAR, 0-10000 is 0 - 100% reflective',
...
>>> without_desc = img.without_bandinfo("red", "data_description").compute(geoctx) 
>>> without_desc.bandinfo["red"] 
{'color': 'Red',
 'data_range': [0, 10000],
...
without_properties(*property_keys)[source]

New Image, with each given property field name dropped from the Image’s properties field.

If a given field doesn’t exist on the Image’s properties, it will be a no-op.

Parameters

*properties_keys (Str) – Fields that will be dropped from the image’s properties

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.compute(geoctx).properties 
{'acquired': '2016-07-06T16:59:42.753476+00:00',
 'area': 35619.4,
...
>>> without_acq = img.without_properties("acquired").compute(geoctx) 
>>> without_acq.properties 
{'area': 35619.4,
 'bits_per_pixel': [0.836, 1.767, 0.804],
...
property bandinfo

Metadata about the bands of the Image.

bandinfo is a Dict, where keys are band names and values are Dicts which always contain these fields:

  • id (Str): the Descartes Labs ID of the band

  • name (Str): the name of the band. Equal to the key the Dict is stored under in bandinfo

  • data_range (Tuple): The (min, max) values the original data had. However, data in Images is automatically rescaled to physical range, or [0, 1] if physical range is undefined, so it won’t be in data_range anymore.

Accessing other fields will return instances of Any. Accessing fields that don’t actually exist on the data is a compute-time error.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.bandinfo['red']['data_range']
<descarteslabs.workflows.types.containers.tuple_.Tuple[Float, Float] object at 0x...>
>>> img.bandinfo['red']['foobar']  # almost certainly a compute-time error
<descarteslabs.workflows.types.primitives.any_.Any object at 0x...>
>>> img.bandinfo['foobar']['id']  # also likely a compute-time error
<descarteslabs.workflows.types.primitives.string.Str object at 0x...>
Type

Dict[Str, KnownDict[dict(id=Str, name=Str, data_range=Tuple[Float, Float]), Str, Any]]

property nbands

The number of bands in the Image.

If the Image is empty, returns 0.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.nbands.compute(geoctx) 
25
property ndarray

MaskedArray

property properties

Metadata for the Image.

properties is a Dict which always contains these fields:

  • id (Str): the Descartes Labs ID of the Image

  • product (Str): the Descartes Labs ID of the product the Image belogs to

  • date (Datetime): the UTC date the Image was acquired

  • crs (Str): the original Coordinate Reference System of the Image

  • geotrans (Tuple): The original 6-tuple GDAL geotrans for the Image.

Accessing other fields will return instances of Any. Accessing fields that don’t actually exist on the data is a compute-time error.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1")
>>> img.properties['date']
<descarteslabs.workflows.types.datetimes.datetime_.Datetime object at 0x...>
>>> img.properties['date'].year
<descarteslabs.workflows.types.primitives.number.Int object at 0x...>
>>> img.properties['id']
<descarteslabs.workflows.types.primitives.string.Str object at 0x...>
>>> img.properties['foobar']  # almost certainly a compute-time error
<descarteslabs.workflows.types.primitives.any_.Any object at 0x...>
Type

KnownDict[dict(id=Str, date=Datetime, product=Str, crs=Str, geotrans=Tuple[Float, Float, Float, Float, Float, Float]), Str, Any]

class ImageCollection(images)[source]

Proxy object representing a stack of Images; typically construct with from_id.

An ImageCollection is a proxy object holding multiple images, each with the same (ordered) bands of raster data, plus metadata about each Image.

ImageCollections don’t have a set spatial extent, CRS, resolution, etc: that’s determined at computation time by the GeoContext passsed in.

Supports unary operations such as negation and absolute value, as well as arithmetic and comparison operators such as >, +, and //.

Examples

>>> from descarteslabs.workflows import ImageCollection
>>> from descarteslabs.scenes import DLTile
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...        start_datetime="2017-01-01",
...        end_datetime="2017-12-31")
>>> col
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> # create a geocontext for our computation, using DLTile
>>> geoctx = DLTile.from_latlon(10, 30, resolution=10, tilesize=512, pad=0)
>>> col.compute(geoctx) 
ImageCollectionResult of length 14:
  * ndarray: MaskedArray<shape=(14, 27, 512, 512), dtype=float64>
  * properties: 14 items
  * bandinfo: 'coastal-aerosol', 'blue', 'green', 'red', ...
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
>>>
>>> rgb = col.pick_bands("red green blue") # an ImageCollection with the red, green, and blue bands only
>>> rgb.compute(geoctx) 
ImageCollectionResult of length 14:
  * ndarray: MaskedArray<shape=(14, 3, 512, 512), dtype=float64>
  * properties: 14 items
  * bandinfo: 'red', 'green', 'blue'
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
>>> rgb.max(axis=("images", "pixels")).compute(geoctx) # max along the images then pixels axis 
{'red': 0.8074, 'green': 0.7857000000000001, 'blue': 0.8261000000000001}

Construct an ImageCollection from a sequence of Images.

Will return an empty ImageCollection if given an empty list or a list of empty images. If given a list of some non-empty and some empty images, the empties will be dropped.

Methods:

arccos()

Element-wise inverse cosine of an ImageCollection.

arcsin()

Element-wise inverse sine of an ImageCollection.

arctan()

Element-wise inverse tangent of an ImageCollection.

clip_values([min, max])

Given an interval, band values outside the interval are clipped to the interval edge.

colormap([named_colormap, vmin, vmax])

Apply a colormap to an ImageCollection.

compute([format, destination, file, …])

Compute a proxy object and wait for its result.

concat(*imgs)

ImageCollection with imgs concatenated onto this one, where imgs is a variable number of Image or ImageCollection objects.

concat_bands(other)

New ImageCollection, with the bands in other appended to this one.

contains(other)

Contains is equivalient to the Python in operator.

coords_to_index(x, y)

Convert spatial coordinates (x, y) to pixel coordinates (row, col) in the ImageCollection.

cos()

Element-wise cosine of an ImageCollection.

count([axis])

Count of valid (unmasked) pixels across the provided axis, or across all pixels in the ImageCollection if no axis argument is provided.

exp()

Element-wise exponential of an ImageCollection.

filter(func)

Filter elements from an iterable proxytype.

from_id(product_id[, start_datetime, …])

Create a proxy ImageCollection representing an entire product in the Descartes Labs catalog.

getmask()

Mask of this ImageCollection, as a new ImageCollection with one boolean band named ‘mask’.

groupby([func, dates])

Group the ImageCollection by a key value for each Image.

head(n)

ImageCollection of the first n Images.

index_to_coords(row, col)

Convert pixel coordinates (row, col) in the ImageCollection into spatial coordinates (x, y).

inspect([format, file, cache, _ruster, …])

Quickly compute a proxy object using a low-latency, lower-reliability backend.

length()

Length is equivalent to the Python len operator.

log()

Element-wise natural log of an ImageCollection.

log10()

Element-wise base 10 log of an ImageCollection.

log1p()

Element-wise log of 1 + an ImageCollection.

log2()

Element-wise base 2 log of an ImageCollection.

map(func)

Map a function over the Images in an ImageCollection.

map_bands(func)

Map a function over each band in self.

map_window(func[, back, fwd])

Map a function over a sliding window of this ImageCollection.

mask(mask[, replace])

New ImageCollection, masked with a boolean ImageCollection, Image, or vector object.

max([axis])

Maximum pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

mean([axis])

Mean pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

median([axis])

Median pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

min([axis])

Minimum pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

mosaic([reverse])

Composite the ImageCollection into a single Image by picking each first-unmasked pixel.

partition(i)

Split this ImageCollection into two collections at index i.

pick_bands(bands[, allow_missing])

New ImageCollection, containing Images with only the given bands.

publish(version[, title, description, …])

Publish a proxy object as a Workflow with the given version.

reduce(func[, initial])

Reduce a collection of elements to a single element.

reduction(operation[, axis])

Reduce the ImageCollection along the provided axis, or across all pixels in the image collection if no axis argument is provided.

rename_bands(*new_positional_names, **new_names)

New ImageCollection, with bands renamed by position or name.

replace_empty_with(fill[, mask, bandinfo])

Replace ImageCollection, if empty, with fill value.

scale_values(range_min, range_max[, …])

Given an interval, band values will be scaled to the interval.

sin()

Element-wise sine of an ImageCollection.

sortby_composite(band[, operation])

Sort-by composite of an ImageCollection Creates a composite of an ImageCollection using the argmin or argmax of a specified band as the per-pixel ordering.

sorted(key[, reverse])

Copy of this ImageCollection, sorted by a key function.

sqrt()

Element-wise square root of an ImageCollection.

square()

Element-wise square of an ImageCollection.

std([axis])

Standard deviation along the provided axis, or across all pixels in the image collection if no axis argument is provided.

sum([axis])

Sum of pixel values across the provided axis, or across all pixels in the image collection if no axis argument is provided.

tail(n)

ImageCollection of the last n Images.

tan()

Element-wise tangent of an ImageCollection.

tile_layer([name, scales, colormap, …])

Reduce this ImageCollection into an Image, and create a WorkflowsLayer for it.

unpack_bands(bands)

Convenience method for unpacking multiple bands into Python variables.

value_at(x, y)

Given coordinates x, y, returns the pixel values from an ImageCollection in a List[Dict] by bandname.

visualize(name[, scales, colormap, …])

Reduce this ImageCollection into an Image, and add to wf.map, or replace a layer with the same name.

with_bandinfo(band, **bandinfo)

New ImageCollection, with the given **bandinfo fields added to the specified band’s bandinfo.

without_bandinfo(band, *bandinfo_keys)

New ImageCollection, with each given *bandinfo_keys field dropped from the specified band’s bandinfo.

Attributes:

bandinfo

Metadata about the bands of the ImageCollection.

nbands

The number of bands in the ImageCollection.

ndarray

MaskedArray

properties

Metadata for each Image in the ImageCollection.

arccos()[source]

Element-wise inverse cosine of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.arccos().compute(geoctx) 
ImageCollectionResult of length 2:
...
arcsin()[source]

Element-wise inverse sine of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.arcsin().compute(geoctx) 
ImageCollectionResult of length 2:
...
arctan()[source]

Element-wise inverse tangent of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.arctan().compute(geoctx) 
ImageCollectionResult of length 2:
...
clip_values(min=None, max=None)[source]

Given an interval, band values outside the interval are clipped to the interval edge.

If the ImageCollection is empty, returns the empty ImageCollection.

Parameters
  • min (float or list, default None) – Minimum value of clipping interval. If None, clipping is not performed on the lower interval edge.

  • max (float or list, default None) – Maximum value of clipping interval. If None, clipping is not performed on the upper interval edge. Different per-band clip values can be given by using lists for min or max, in which case they must be the same length as the number of bands.

  • Note (min and max cannot both be None. At least one must be specified.) –

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.compute(geoctx).ndarray 
masked_array(
  data=[[[[0.1578, 0.1578, 0.1578, ..., 0.13920000000000002, 0.1376,
                 0.1376],
...
>>> clipped = col.clip_values(0.14, 0.3).compute(geoctx) 
>>> clipped.ndarray 
masked_array(
  data=[[[[0.1578, 0.1578, 0.1578, ..., 0.14, 0.14, 0.14],
...
colormap(named_colormap='viridis', vmin=None, vmax=None)[source]

Apply a colormap to an ImageCollection. Each image must have a single band.

If the ImageCollection is empty, returns the empty ImageCollection.

Parameters
  • named_colormap (Str, default "viridis") – The name of the Colormap registered with matplotlib. See https://matplotlib.org/users/colormaps.html for colormap options.

  • vmin (float, default None) – The minimum value of the range to normalize the bands within. If specified, vmax must be specified as well.

  • vmax (float, default None) – The maximum value of the range to normalize the bands within. If specified, vmin must be specified as well.

  • Note (If neither vmin nor vmax are specified, the min and max values in each Image will be used.) –

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.pick_bands("red").colormap("magma", vmin=0.1, vmax=0.8).compute(geoctx) 
ImageCollectionResult of length 2:
  * ndarray: MaskedArray<shape=(2, 3, 512, 512), dtype=float64>
  * properties: 2 items
  * bandinfo: 'red', 'green', 'blue'
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
compute(format='pyarrow', destination='download', file=None, timeout=None, block=True, progress_bar=None, cache=True, _ruster=None, _trace=False, client=None, num_retries=None, **arguments)

Compute a proxy object and wait for its result.

If the caller has too many outstanding compute jobs, this will raise a ResourceExhausted exception.

Parameters
  • geoctx (GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (Str or Dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes or None.

  • destination (str or dict, default "download") –

    The destination for the result. See the destinations documentation for more information.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • timeout (Int, optional) – The number of seconds to wait for the result, if block is True. Raises JobTimeoutError if the timeout passes.

  • block (Bool, default True) – If True (default), block until the job is completed, or timeout has passed. If False, immediately returns a Job (which has already had execute called).

  • progress_bar (Bool, default None) – Whether to draw the progress bar. If None (default), will display a progress bar in Jupyter Notebooks, but not elsewhere. Ignored if block==False.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

  • num_retries (Int, optional) – The number of retries to make in the event of a request failure. If you are making numerous long-running asynchronous requests, you can use this parameter as a way to indicate that you are comfortable waiting and retrying in response to RESOURCE EXHAUSTED errors. By default, most failures will trigger a small number of retries, but if you have reached your outstanding job limit, by default, the client will not retry. This parameter is unnecessary when making synchronous compute requests (ie. block=True, the default). See the compute section of the Workflows Guide for more information.

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file. If the destination doesn’t support retrieving results (like “email”), returns None.

Return type

Python object, bytes, or None

Raises

RetryError – Raised if there are too many failed retries. Inspect RetryError.exceptions to determine the ultimate cause of the error. If you reach your maximum number of outstanding compute jobs, there will be one or more ResourceExhausted exceptions.

concat(*imgs)[source]

ImageCollection with imgs concatenated onto this one, where imgs is a variable number of Image or ImageCollection objects.

Images, properties, and bandinfo are concatenated. All imagery must have the same number of bands with identical names. Any empty Images or ImageCollections will not be concatenated.

Parameters

*imgs (variable number of Image or ImageCollection objects) –

Returns

concatenated

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.concat(col, col).compute(geoctx) 
ImageCollectionResult of length 6:
...
concat_bands(other)[source]

New ImageCollection, with the bands in other appended to this one.

If band names overlap, the band name from other will be suffixed with “_1”.

If the ImageCollection is empty, or other is empty, an empty is returned (following broadcasting rules).

Parameters

other (Image, ImageCollection) –

If other is a single Image, its bands will be added to every image in this ImageCollection.

If other is an ImageCollection, it must be the same length as self.

Returns

concatenated

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> red = col.pick_bands("red")
>>> green = col.pick_bands("green")
>>> rg = red.concat_bands(green).compute(geoctx) 
>>> rg.bandinfo.keys() 
['red', 'green']
contains(other)

Contains is equivalient to the Python in operator.

Parameters

other (Proxytype) – A Proxytype or type that can be promoted to a Proxytype

Returns

A Bool Proxytype

Return type

Bool

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.contains(2).compute() 
True
coords_to_index(x, y)[source]

Convert spatial coordinates (x, y) to pixel coordinates (row, col) in the ImageCollection.

Parameters

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.coords_to_index(459040.0, 3942400.0).compute(ctx) 
(0, 0)
cos()[source]

Element-wise cosine of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.cos().compute(geoctx) 
ImageCollectionResult of length 2:
...
count(axis=None)[source]

Count of valid (unmasked) pixels across the provided axis, or across all pixels in the ImageCollection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the valid pixel count.

Options:

  • "images": Returns an Image containing the count of valid pixels across all scenes for each pixel in each band (i.e., a temporal count composite.)

  • "bands": Returns a new ImageCollection with one band, "count", containing the count of valid pixels across all bands for each pixel and each scene.

  • "pixels": Returns a List[Dict[Str, Float]] containing the count of valid pixels in each band in each scene.

  • None: Returns a Float that represents the valid pixel count for the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] containing the count of valid pixels in each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] contianing the count of valid pixels in each scene across all bands.

  • ("images", "bands"): Returns an Image containing the count of valid pixels across all scenes and bands.

Returns

Count of valid pixels across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> count_composite = col.count(axis="images")
>>> count_col = col.count(axis="bands")
>>> band_counts_per_scene = col.count(axis="pixels")
>>> scene_counts = col.count(axis=("bands", "pixels"))
>>> band_counts = col.count(axis=("images", "pixels"))
>>> count = col.count(axis=None)
exp()[source]

Element-wise exponential of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.exp().compute(geoctx) 
ImageCollectionResult of length 2:
...
filter(func)

Filter elements from an iterable proxytype.

Parameters

func (Python callable) – A function that takes a single argument and returns a Bool Proxytype.

Returns

A Proxytype of the same type having only the elements where func returns True.

Return type

Proxtype

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> filtered = col.filter(lambda img: img.properties["date"].year == 2018)
classmethod from_id(product_id, start_datetime=None, end_datetime=None, limit=None, resampler=None, processing_level=None)[source]

Create a proxy ImageCollection representing an entire product in the Descartes Labs catalog.

This ImageCollection represents every Image in the product, everywhere. But when a GeoContext is supplied at computation time (either by passing one into compute, or implicitly from the map view area when using Image.visualize), the actual metadata lookup and computation only happens within that area of interest.

Note there are two ways of filtering dates: using the start_datetime and end_datetime arguments here, and calling filter (like imgs.filter(lambda img: img.properties['date'].month > 5)). We recommend using start_datetime and end_datetime for giving a coarse date window (at the year level, for example), then using filter to do more sophisticated filtering within that subset if necessary.

The ImageCollection is sorted by date, in ascending order (older Images come first).

If no imagery is found to satisfy the constraints, an empty ImageCollection is returned.

Parameters
  • product_id (Str) – ID of the product

  • start_datetime (Datetime or None, optional, default None) – Restrict the ImageCollection to Images acquired after this timestamp.

  • end_datetime (Datetime or None, optional, default None) – Restrict the ImageCollection to Images before after this timestamp.

  • limit (Int or None, optional, default None) – Maximum number of Images to include. If None (default), uses the Workflows default of 10,000. Note that specifying no limit is not supported.

  • resampler (Str, optional, default None) – Algorithm used to interpolate pixel values when scaling and transforming the image to the resolution and CRS eventually defined by a GeoContext. Possible values are near (nearest-neighbor), bilinear, cubic, cubicspline, lanczos, average, mode, max, min, med, q1, q3.

  • processing_level (Str, optional) – Image processing level. Possible values depend on the particular product and bands. Some examples include 'toa', 'surface', 'toa_refectance', 'toa_radiance'.

Returns

imgs

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30", resampler="min")
>>> col.compute(geoctx) 
ImageCollectionResult of length 2:
...
getmask()[source]

Mask of this ImageCollection, as a new ImageCollection with one boolean band named ‘mask’.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> mask = col.getmask().compute(geoctx) 
>>> mask.ndarray 
masked_array(
  data=[[[[0, 0, 0, ..., 1, 1, 1],
...
>>> mask.bandinfo 
{'mask': {}}
groupby(func=None, dates=None)[source]

Group the ImageCollection by a key value for each Image.

func must take an Image, and return which group that Image belongs to. (The return type of func can be anything; the unique values returned by func over every Image become the groups.)

For convenience, dates can be given instead as a field name, or tuple of field names, to pull from the "date" field of Image.properties.

Creates an ImageCollectionGroupby object, which can be used to aggregate the groups.

Within the ImageCollectionGroupby, every Image in every ImageCollection group also gets the field "group" added to its properties, which identifies which group it belongs to.

If the ImageCollection is empty, or func results in empty groups, ImageCollectionGroupby.groups will return an empty Dict.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> # group all Images from the same year and month, then take the mean (along the 'images' axis) of each group
>>> col.groupby(dates=("year", "month")).mean(axis="images")
<descarteslabs.workflows.types.geospatial.imagecollection.ImageCollection object at 0x...>
>>> # group all Images from the same month, get Images from April, and take the median along the 'images' axis
>>> col.groupby(dates="month")[4].median(axis="images")
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
>>> # place images in 14 day bins, and take the min for each group (using a mapper function)
>>> col.groupby(lambda img: img.properties['date'] // wf.Timedelta(days=14)).map(lambda group, img: img.min())
<descarteslabs.workflows.types.containers.dict_.Dict[Datetime, Float] object at 0x...>
head(n)[source]

ImageCollection of the first n Images.

If the ImageCollection is empty, an empty ImageCollection is returned (all values of n are valid).

Parameters

n (Int) – Can be longer than the ImageCollection without error, in which case the whole ImageCollection is returned.

Returns

imgs

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.head(2).compute(geoctx) 
ImageCollectionResult of length 2:
...
index_to_coords(row, col)[source]

Convert pixel coordinates (row, col) in the ImageCollection into spatial coordinates (x, y).

Parameters
  • row (int) – The row

  • col (int) – The col

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.index_to_coords(0, 0).compute(ctx) 
(459040.0, 3942400.0)
inspect(format='pyarrow', file=None, cache=True, _ruster=None, timeout=60, client=None, **arguments)

Quickly compute a proxy object using a low-latency, lower-reliability backend.

Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It’s quicker but less resilient, won’t be retried if it fails, and has no progress updates.

If you have a larger computation (longer than ~30sec), or you want to be sure the computation will succeed, use compute instead. compute creates a Job, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.

Parameters
  • geoctx (scenes.geocontext.GeoContext, GeoContext, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require a GeoContext, but for operations that only involve non-geospatial types, this parameter is optional.

  • format (str or dict, default "pyarrow") –

    The serialization format for the result. See the formats documentation for more information. If “pyarrow” (the default), returns an appropriate Python object, otherwise returns raw bytes.

  • file (path or file-like object, optional) – If specified, writes results to the path or file instead of returning them.

  • cache (bool, default True) – Whether to use the cache for this job.

  • timeout (int, optional, default 60) – The number of seconds to wait for the result. Raises JobTimeoutError if the timeout passes.

  • client (workflows.inspect.InspectClient, optional) – Allows you to use a specific InspectClient instance with non-default auth and parameters

  • **arguments (Any) – Values for all parameters that obj depends on (or arguments that obj takes, if it’s a Function). Can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

Returns

result – When format="pyarrow" (the default), returns an appropriate Python object representing the result, either as a plain Python type, or object from descarteslabs.workflows.result_types. For other formats, returns raw bytes. Consider using file in that case to save the results to a file.

Return type

Python object or bytes

length()

Length is equivalent to the Python len operator.

Returns

An Int Proxytype

Return type

Int

Example

>>> from descarteslabs.workflows import List, Int
>>> my_list = List[Int]([1, 2, 3])
>>> my_list.length().compute() 
3
log()[source]

Element-wise natural log of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.log().compute(geoctx) 
ImageCollectionResult of length 2:
...
log10()[source]

Element-wise base 10 log of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.log10().compute(geoctx) 
ImageCollectionResult of length 2:
...
log1p()[source]

Element-wise log of 1 + an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.log1p().compute(geoctx) 
ImageCollectionResult of length 2:
...
log2()[source]

Element-wise base 2 log of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.log2().compute(geoctx) 
ImageCollectionResult of length 2:
...
map(func)[source]

Map a function over the Images in an ImageCollection.

If the ImageCollection is empty, it will return an empty ImageCollection or List, according to the return type of func. If func returns some empty and some non-empty Image objects, the empties are dropped so only the non-empties are included in the resulting ImageCollection. If func returns all empty Image objects, an empty ImageCollection is returned.

Parameters

func (Python callable) – A function that takes a single Image and returns another proxytype.

Returns

mappedImageCollection if func returns Image, otherwise List[T], where T is the return type of func.

For example:

  • ic.map(lambda img: img + 1) returns an ImageCollection

  • ic.map(lambda img: img.properties["date"]) returns a List[Datetime].

Return type

ImageCollection or List

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("sentinel-2:L1C")
>>> dates = col.map(lambda img: img.properties["date"])
>>> type(dates).__name__
'List[Datetime]'
>>> means = col.map(lambda img: img.mean(axis="pixels"))
>>> type(means).__name__
'List[Dict[Str, Float]]'
>>> mean_col = col.map(lambda img: img.mean(axis="bands"))
>>> type(mean_col).__name__
'ImageCollection'
map_bands(func)[source]

Map a function over each band in self.

The function must take 2 arguments:

  1. Str: the band name

  2. ImageCollection: 1-band ImageCollection

If the function returns an ImageCollection, map_bands will also return one ImageCollection, containing the bands from all ImageCollections returned by func concatenated together.

Otherwise, map_bands will return a Dict of the results of each call to func, where the keys are the band names.

Note that func can return ImageCollections with more than 1 band, but the band names must be unique across all of its results.

If the ImageCollection is empty, it will return an empty ImageCollection or Dict, according to the return type of func. If func produces an empty Image or ImageCollection for any band, that empty is returned. (Any band being empty propagates to all of them, because it is impossible to have some bands empty and some not.)

Parameters

func (Python function) – Function that takes a Str and an ImageCollection.

Returns

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> band_means = col.mean(axis=("images", "pixels"))
>>> deviations = col.map_bands(lambda name, imgs: imgs - band_means[name])
map_window(func, back=0, fwd=0)[source]

Map a function over a sliding window of this ImageCollection.

The function must take 3 arguments:

The window slides over the ImageCollection, starting at index back and ending fwd images before the end.

Note that the total length of the window is back + 1 + fwd. Specifying a window longer than the ImageCollection will cause an error.

If the ImageCollection is empty, it will return an empty ImageCollection or List, according to the return type of func. If func returns some empty and some non-empty imagery, the empties are dropped so only the non-empties are included in the resulting ImageCollection. If func returns all empty imagery, an empty ImageCollection is returned.

Parameters
  • back (Int, optional, default 0) – Number of previous Images to pass as back to the function.

  • fwd (Int, optional, default 0) – Number of subsequent Images to pass as fwd to the function.

Returns

mapped – If func returns an ImageCollection or Image, all of them are concatenated together and returned as one ImageCollection.

Otherwise, returns a List of the values returned by func.

Return type

ImageCollection or List

Example

>>> from descarteslabs.workflows import ImageCollection, concat
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-06-30")
>>> new_col = col.map_window(lambda back, img, fwd:
...     concat(back, img, fwd).mean(axis="images").with_properties(date=img.properties['date']), back=1, fwd=1)
>>> new_col.compute(geoctx) 
ImageCollectionResult of length 2:
...
mask(mask, replace=False)[source]

New ImageCollection, masked with a boolean ImageCollection, Image, or vector object.

If the mask is empty, the original ImageCollection is returned unchanged. (If the ImageCollection was already empty, it is still empty even if the mask is non-empty.)

Parameters
  • mask (ImageCollection, Image, Geometry, Feature, FeatureCollection) –

    A single-band ImageCollection of boolean values, (such as produced by col > 2, for example) where True means masked (invalid).

    Or, single-band Image of boolean values, (such as produced by img > 2, for example) where True means masked (invalid).

    Or, a vector (Geometry, Feature, or FeatureCollection), in which case pixels outside the vector are masked.

  • replace (Bool, default False) –

    Whether to add to the ImageCollection’s current mask, or replace it.

    If False (default):

    • Adds this mask to the current one, so already-masked pixels remain masked.

    • Masked-out pixels in the mask are ignored (considered False).

    If True:

    • Replaces the current mask with this new one.

    • Masked-out pixels in the mask are also masked in the result.

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> red = col.pick_bands("red")
>>> masked = red.mask(red < 0.2) # mask all the bands where the red band is low
max(axis=None)[source]

Maximum pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the maximum.

Options:

  • "images": Returns an Image containing the maximum value for each pixel in each band, across all scenes (i.e., a temporal maximum composite.)

  • "bands": Returns a new ImageCollection with one band, "max", containing the maximum value for each pixel across all bands in each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing each band’s maximum pixel value for each scene in the collection.

  • None: Returns a Float that represents the maximum pixel value of the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] of the maximum pixel value for each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] of the maximum pixel value for each scene across all bands.

  • ("images", "bands"): Returns an Image containing the maximum value across all scenes and bands.

Returns

Maximum pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> max_composite = col.max(axis="images")
>>> max_col = col.max(axis="bands")
>>> band_maxs_per_scene = col.max(axis="pixels")
>>> scene_maxs = col.max(axis=("bands", "pixels"))
>>> band_maxs = col.max(axis=("images", "pixels"))
>>> max_pixel = col.max(axis=None)
mean(axis=None)[source]

Mean pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the mean.

Options:

  • "images": Returns an Image containing the mean value for each pixel in each band, across all scenes

  • "bands": Returns a new ImageCollection with one band, "mean", containing the mean value for each pixel across all bands in each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing each band’s mean pixel value for each scene in the collection. (i.e., a temporal mean composite.)

  • None: Returns a Float that represents the mean pixel value of the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] of the mean pixel value for each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] of the mean pixel value for each scene across all bands.

  • ("images", "bands"): Returns an Image containing the mean value across all scenes and bands.

Returns

Mean pixel value across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> mean_composite = col.mean(axis="images")
>>> mean_col = col.mean(axis="bands")
>>> band_means_per_scene = col.mean(axis="pixels")
>>> scene_means = col.mean(axis=("bands", "pixels"))
>>> band_means = col.mean(axis=("images", "pixels"))
>>> mean_pixel = col.mean(axis=None)
median(axis=None)[source]

Median pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the median.

Options:

  • "images": Returns an Image containing the median value for each pixel in each band, across all scenes (i.e., a temporal median composite.)

  • "bands": Returns a new ImageCollection with one band, "median", containing the median value for each pixel across all bands in each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing each band’s median pixel value for each scene in the collection.

  • None: Returns a Float that represents the median pixel value of the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] of the median pixel value for each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] of the median pixel value for each scene across all bands.

  • ("images", "bands"): Returns an Image containing the median value across all scenes and bands.

Returns

Median pixel value across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> median_composite = col.median(axis="images")
>>> median_col = col.median(axis="bands")
>>> band_medians_per_scene = col.median(axis="pixels")
>>> scene_medians = col.median(axis=("bands", "pixels"))
>>> band_medians = col.median(axis=("images", "pixels"))
>>> median_pixel = col.median(axis=None)
min(axis=None)[source]

Minimum pixel value across the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the minimum.

Options:

  • "images": Returns an Image containing the minimum value for each pixel in each band, across all scenes (i.e., a temporal minimum composite.)

  • "bands": Returns a new ImageCollection with one band, "min", containing the minimum value for each pixel across all bands in each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing each band’s minimum pixel value for each scene in the collection.

  • None: Returns a Float that represents the minimum pixel value of the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] of the minimum pixel value for each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] of the minimum pixel value for each scene across all bands.

  • ("images", "bands"): Returns an Image containing the minimum value across all scenes and bands.

Returns

Minimum pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> min_composite = col.min(axis="images")
>>> min_col = col.min(axis="bands")
>>> band_mins_per_scene = col.min(axis="pixels")
>>> scene_mins = col.min(axis=("bands", "pixels"))
>>> band_mins = col.min(axis=("images", "pixels"))
>>> min_pixel = col.min(axis=None)
mosaic(reverse=False)[source]

Composite the ImageCollection into a single Image by picking each first-unmasked pixel.

The order of mosaicing is from last to first, meaning the last Image in the ImageCollection is on top.

Parameters

reverse (Bool, default False) – The order of mosaicing. If False (default), the last Image in the ImageCollection is on top. If True, the first `Image in the ImageCollection is on top.

Returns

mosaicked – The mosaicked Image

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> col.mosaic()
<descarteslabs.workflows.types.geospatial.image.Image object at 0x...>
>>> date_mosaic = col.sorted(lambda img: img.properties['date']).mosaic()
>>> cloudfree_mosaic = col.sorted(lambda img: img.properties['cloud_fraction'], reverse=True).mosaic()
partition(i)[source]

Split this ImageCollection into two collections at index i.

If the ImageCollection is empty, a 2-tuple of empty ImageCollection objects is returned (all indices are valid).

Parameters

i (Int) – The first ImageCollection will contain all Images up to but not including index i. The second will contain the Image at index i and all subsequent ones.

Returns

Return type

Tuple[ImageCollection, ImageCollection]

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> head, tail = col.partition(1)
>>> head.compute(geoctx) 
ImageCollectionResult of length 1:
...
>>> tail.compute(geoctx) 
ImageCollectionResult of length 1:
...
pick_bands(bands, allow_missing=False)[source]

New ImageCollection, containing Images with only the given bands.

Bands can be given as a sequence of strings, or a single space-separated string (like "red green blue").

Bands on the new ImageCollection will be in the order given.

If names are duplicated, repeated names will be suffixed with _N, with N incrementing from 1 for each duplication (pick_bands("red red red") returns bands named red red_1 red_2).

If the ImageCollection is empty, returns the empty ImageCollection.

If allow_missing is False (default), raises an error if given band names that don’t exist in the ImageCollection. If allow_missing is True, any missing names are dropped, and if none of the names exist, returns an empty ImageCollection.

Parameters

bands (Str or List[Str]) – A space-separated string or list of band names

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> rgb = col.pick_bands("red green blue")
>>> rgb.bandinfo.keys().inspect(ctx)  
["red", "green", "blue"]
>>> red = col.pick_bands(["red", "nonexistent_band_name"], allow_missing=True)
>>> red.bandinfo.keys().inspect(ctx)  
["red"]
>>> s1_col = ImageCollection.from_id("sentinel-1:GRD")
>>> vv_vh_vv = s1_col.pick_bands("vv vh vv")
>>> vv_vh_vv.bandinfo.keys().inspect(ctx)  
["vv", "vh", "vv_1"]
publish(version, title='', description='', labels=None, tags=None, docstring='', version_labels=None, viz_options=None, client=None)

Publish a proxy object as a Workflow with the given version.

If the proxy object depends on any parameters (obj.params is not empty), it’s first internally converted to a Function that takes those parameters (using Function.from_object).

Parameters
  • id (Str) – ID for the new Workflow object. This should be of the form email:workflow_name and should be globally unique. If this ID is not of the proper format, you will not be able to save the Workflow.

  • version (Str) – The version to be set, tied to the given obj. This should adhere to the semantic versioning schema.

  • title (Str, default "") – User-friendly title for the Workflow.

  • description (str, default "") – Long-form description of this Workflow. Markdown is supported.

  • labels (Dict, optional) – Key-value pair labels to add to the Workflow.

  • tags (list, optional) – A list of strings to add as tags to the Workflow.

  • docstring (Str, default "") – The docstring for this version.

  • version_labels (Dict, optional) – Key-value pair labels to add to the version.

  • client (workflows.client.Client, optional) – Allows you to use a specific client instance with non-default auth and parameters

Returns

workflow – The saved Workflow object. workflow.id contains the ID of the new Workflow.

Return type

Workflow or Function

reduce(func, initial='__NO_INITIAL_REDUCE_VALUE__')

Reduce a collection of elements to a single element.

NOTE: Optimized reducers such as sum have been implemented for some classes.

Parameters
  • func (Python callable) – A function where the left argument is the accumulated value (the result of the previous call to func) and the right argument is the next value from the iterable. The function should return a single proxtype.

  • initial (Proxytype, optional) – An optional proxtype to provide for the first iteration. If no value is provided, the first element will be used.

Returns

The return value of func for the last iteration of the collection.

Return type

Proxytype

Example

>>> from descarteslabs.workflows import List, Int
>>> def add(accumulated, current):
...     return accumulated + current
>>> my_list = List[Int]([1, 2])
>>> my_list.reduce(add, initial=Int(10)).compute()  
13
reduction(operation, axis=None)[source]

Reduce the ImageCollection along the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters
  • operation ({"min", "max", "mean", "median", "mosaic", "sum", "std", "count"}) – A string indicating the reduction method to apply along the specified axis. If operation is “mosaic”, axis must be “images”.

  • axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

    A Python string indicating the axis along which to perform the reduction.

    Options:

    • "images": Returns an Image containing the reduction across all scenes, for each pixel in each band (i.e., a temporal reduction.)

    • "bands": Returns a new ImageCollection with one band, named according to operation, containing the reduction across all bands, for each pixel in each scene.

    • "pixels" Returns a List[Dict[Str, Float]] containing each band’s reduction, for each scene in the collection.

    • None: Returns a Float that represents the reduction of the entire ImageCollection, across all scenes, bands, and pixels.

    • ("images", "pixels"): Returns a Dict[Str, Float] containing the reduction across all scenes, for each band, keyed by band name.

    • ("bands", "pixels"): Returns a List[Float] containing the reduction across all bands, for each scene.

    • ("images", "bands"): Returns an Image containing the reduction across all scenes and bands.

Returns

Composite along the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> std_reduction = col.reduction("std", axis="images")
>>> std_col = col.reduction("std", axis="bands")
>>> band_stds_per_scene = col.reduction("std", axis="pixels")
>>> scene_stds = col.reduction("std", axis=("bands", "pixels"))
>>> band_stds = col.reduction("std", axis=("images", "pixels"))
>>> std = col.reduction("std", axis=None)
rename_bands(*new_positional_names, **new_names)[source]

New ImageCollection, with bands renamed by position or name.

New names can be given positionally (like rename_bands('new_red', 'new_green')), which renames the i-th band to the i-th argument or new names can be given by keywords (like rename_bands(red="new_red")) mapping from old band names to new ones. To eliminate ambiguity, names cannot be given both ways.

If the ImageCollection is empty, returns the empty ImageCollection.

Parameters
  • *new_positional_names (Str) – Positional bands to rename

  • **new_names (Str) – Keyword bands to rename

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> renamed = col.rename_bands(red="new_red", blue="new_blue", green="new_green")
replace_empty_with(fill, mask=True, bandinfo=None)[source]

Replace ImageCollection, if empty, with fill value.

Parameters
  • fill (int, float, ImageCollection) – The value to fill the ImageCollection with. If int or float, the fill value will be broadcasted to a 1 image collection, with band dimensions as determined by the geocontext and provided bandinfo.

  • mask (bool, default True) – Whether to mask the band data. If mask is True and fill is an ImageCollection, the original ImageCollection mask will be overridden and all underlying data will be masked. If mask is False and fill is an ImageCollection, the original mask is left as is. If fill is scalar, the ImageCollection constructed will be fully masked or fully un-masked data if mask is True and False respectively.

  • bandinfo (dict, default None) – Bandinfo used in constructing new ImageCollection. If fill is an ImageCollection, bandinfo is optional, and will be ignored if provided. If fill is a scalar, the bandinfo will be used to determine the number of bands on the new ImageCollection, as well as become the bandinfo for it.

Example

>>> from descarteslabs.workflows import ImageCollection
>>> # no imagery exists for this product within the date range
>>> empty_col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-02-28")
>>> empty_col.compute(geoctx) 
ImageCollectionResult of length 0:
...
>>> non_empty = empty_col.replace_empty_with(9999, bandinfo={"red":{}, "green":{}, "blue":{}})
>>> non_empty.compute(geoctx) 
ImageCollectionResult of length 0:
  * ndarray: MaskedArray<shape=(1, 3, 512, 512), dtype=int64>
  * properties: 0 items
  * bandinfo: 'red', 'green', 'blue'
  * geocontext: 'geometry', 'key', 'resolution', 'tilesize', ...
scale_values(range_min, range_max, domain_min=None, domain_max=None)[source]

Given an interval, band values will be scaled to the interval.

If the ImageCollection is empty, returns the empty ImageCollection.

Parameters
  • range_min (float) – Minimum value of output range.

  • range_max (float) – Maximum value of output range.

  • domain_min (float, default None) – Minimum value of the domain. If None, the band minimum is used.

  • domain_max (float, default None) – Maximum value of the domain. If None, the band maximum is used.

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.compute(geoctx).ndarray 
masked_array(
  data=[[[[0.1578, 0.1578, 0.1578, ..., 0.13920000000000002, 0.1376,
                 0.1376],
...
>>> scaled = col.scale_values(0.1, 0.5).compute(geoctx) 
>>> scaled.ndarray 
masked_array(
  data=[[[[0.10000706665039064, 0.10000706665039064,
...
sin()[source]

Element-wise sine of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.sin().compute(geoctx) 
ImageCollectionResult of length 2:
...
sortby_composite(band, operation='argmax')[source]

Sort-by composite of an ImageCollection Creates a composite of an ImageCollection using the argmin or argmax of a specified band as the per-pixel ordering.

Parameters
  • band (Str or ImageCollection) – If Str, the name of the band in self to use as the sorting band. If ImageCollection, use this single-band ImageCollection as the sorting band.

  • operation ({"argmin", "argmax"}, default "argmax") – A string indicating whether to use the minimum or maximum from band when computing the sort-by composite.

Returns

composite

Return type

Image

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> rgb = col.pick_bands("red green blue")
>>> min_red_composite = rgb.sortby_composite("red", operation="argmin")
>>> # ^ compute a minimum sort-by composite with an existing band
>>> quality_band = col.pick_bands("swir1")
>>> max_swir_composite = rgb.sortby_composite(quality_band)
>>> # ^ compute a maximum sort-by composite with a provided band
sorted(key, reverse=False)[source]

Copy of this ImageCollection, sorted by a key function.

If the ImageCollection is empty, returns the empty ImageCollection.

Parameters
  • key (Function) – Function which takes an Image and returns a value to sort by.

  • reverse (Bool, default False) – Sorts in ascending order if False (default), descending if True.

Returns

sorted

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> month_reverse_sort = col.sorted(key=lambda img: img.properties["date"].month, reverse=True)
sqrt()[source]

Element-wise square root of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.sqrt().compute(geoctx) 
ImageCollectionResult of length 2:
...
square()[source]

Element-wise square of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.square().compute(geoctx) 
ImageCollectionResult of length 2:
...
std(axis=None)[source]

Standard deviation along the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the standard deviation.

Options:

  • "images": Returns an Image containing standard deviation across all scenes, for each pixel in each band (i.e., a temporal standard deviation composite.)

  • "bands": Returns a new ImageCollection with one band, "std", containing the standard deviation across all bands, for each pixel in each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing each band’s standard deviation, for each scene in the collection.

  • None: Returns a Float that represents the standard deviation of the entire ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] containing the standard deviation across all scenes, for each band, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] containing the standard deviation across all bands, for each scene.

  • ("images", "bands"): Returns an Image containing the standard deviation across all scenes and bands.

Returns

Standard deviation along the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> std_composite = col.std(axis="images")
>>> std_col = col.std(axis="bands")
>>> band_stds_per_scene = col.std(axis="pixels")
>>> scene_stds = col.std(axis=("bands", "pixels"))
>>> band_stds = col.std(axis=("images", "pixels"))
>>> std = col.std(axis=None)
sum(axis=None)[source]

Sum of pixel values across the provided axis, or across all pixels in the image collection if no axis argument is provided.

If the ImageCollection is empty, an empty (of the type determined by axis) will be returned.

Parameters

axis ({None, "images", "bands", "pixels", ("images", "pixels"), ("bands", "pixels"), ("images", "bands")}) –

A Python string indicating the axis along which to take the sum.

Options:

  • "images": Returns an Image containing the sum across all scenes for each pixel in each band (i.e., a temporal sum composite.)

  • "bands": Returns a new ImageCollection with one band, "sum", containing the sum across all bands for each pixel and each scene.

  • "pixels" Returns a List[Dict[Str, Float]] containing the sum of the pixel values for each band in each scene.

  • None: Returns a Float that represents the sum of all pixel values in the ImageCollection, across all scenes, bands, and pixels.

  • ("images", "pixels"): Returns a Dict[Str, Float] containing the sum of the pixel values for each band across all scenes, keyed by band name.

  • ("bands", "pixels"): Returns a List[Float] contianing the sum of the pixel values for each scene across all bands.

  • ("images", "bands"): Returns an Image containing the sum across all scenes and bands.

Returns

Sum of pixel values across the provided axis. See the options for the axis argument for details.

Return type

Dict[Str, Float], List[Float], List[Dict[Str, Float]], ImageCollection, Image or Float

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR")
>>> sum_composite = col.sum(axis="images")
>>> sum_col = col.sum(axis="bands")
>>> band_sums_per_scene = col.sum(axis="pixels")
>>> scene_sums = col.sum(axis=("bands", "pixels"))
>>> band_sums = col.sum(axis=("images", "pixels"))
>>> sum_pixel = col.sum(axis=None)
tail(n)[source]

ImageCollection of the last n Images.

If the ImageCollection is empty, an empty ImageCollection is returned (all values of n are valid).

Parameters

n (Int) – Can be longer than the ImageCollection without error, in which case the whole ImageCollection is returned.

Returns

imgs

Return type

ImageCollection

Example

>>> from descarteslabs.workflows import ImageCollection
>>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.tail(1).compute(geoctx) 
ImageCollectionResult of length 1:
...
tan()[source]

Element-wise tangent of an ImageCollection.

If the ImageCollection is empty, returns the empty ImageCollection.

Example

>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
...     start_datetime="2017-01-01", end_datetime="2017-05-30")
>>> col.tan().compute(geoctx) 
ImageCollectionResult of length 2:
...
tile_layer(name=None, scales=None, colormap=None, reduction='mosaic', checkerboard=True, log_level=10, **parameter_overrides)[source]

Reduce this ImageCollection into an Image, and create a WorkflowsLayer for it.

Generally, use ImageCollection.visualize for displaying on map. Only use this method if you’re managing your own ipyleaflet Map instances, and creating more custom visualizations.

An empty ImageCollection will be rendered as a checkerboard (default) or blank tile.

Parameters
  • name (str) – The name of the layer.

  • scales (list of lists, default None) –

    The scaling to apply to each band in the ImageCollection after being reduced into an Image.

    If ImageCollection contains 3 bands, scales must be a list like [(0, 1), (0, 1), (-1, 1)].

    If ImageCollection contains 1 band, scales must be a list like [(0, 1)], or just (0, 1) for convenience

    If None, each 256x256 tile will be scaled independently. based on the min and max values of its data.

  • colormap (str, default None) – The name of the colormap to apply to the ImageCollection after being reduced. Only valid if the ImageCollection has a single band.

  • reduction ({"mosaic", "min", "max", "mean", "median", "sum", "std", "count"}) – The method used to reduce the ImageCollection into an Image. Reduction is performed before applying a colormap or scaling.

  • checkerboard (bool, default True) – Whether to display a checkerboarded background for missing or masked data.

  • log_level (int, default logging.DEBUG) – Only listen for log records at or above this log level during tile computation. See https://docs.python.org/3/library/logging.html#logging-levels for valid log levels.

  • **parameter_overrides (JSON-serializable value, Proxytype, or ipywidgets.Widget) –

    Values—or ipywidgets—for any parameters that this ImageCollection depends on.

    If this ImageCollection depends on wf.widgets, you don’t have to pass anything for those—any widgets it depends on are automatically linked to the layer. However, you can override their current values (or widgets) by passing new values (or ipywidget instances) here.

    Values can be given as Proxytypes, or as Python objects like numbers, lists, and dicts that can be promoted to them. These arguments cannot depend on any parameters.

    If an ipywidgets.Widget is given, it’s automatically linked, so updating the widget causes the argument value to change, and the layer to update.

    Once these initial argument values are set, they can be modified by assigning to parameters on the returned WorkflowsLayer.

    For more information, see the docstring to ParameterSet.

Returns

layer

Return type

WorkflowsLayer

unpack_bands(bands)

Convenience method for unpacking multiple bands into Python variables.

Returns a Python tuple of self.pick_bands called for each band name. Bands can be given as a space-separated string of band names, or a sequence.

Example

>>> from descarteslabs.workflows import Image
>>> img = Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> red, green, blue = img.unpack_bands("red green blue")
value_at(x, y)[source]

Given coordinates x, y, returns the pixel values from an ImageCollection in a List[Dict] by bandname.

Coordinates must be given in the same coordinate reference system as the GeoContext you call compute with. For example, if your GeoContext uses "EPSG:4326", you’d give x and y in lon, lat degrees. If you