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 geo.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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
-
class
Feature
(geometry, properties)[source]¶ Proxy GeoJSON Feature representing a
Geometry
and aDict
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 anImage
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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
rasterize
(value=1, default_value=1)[source]¶ Rasterize this
Feature
into anImage
Parameters: - value (Int, Float, Str, default=1) – Fill pixels within the
Feature
with this value. Pixels outside theFeature
will be masked, and set to 0. If a string, it will look up that key inself.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 inself.properties
Notes
Rasterization happens according to the
GeoContext
of theJob
, 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 thisFeature
, 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
- value (Int, Float, Str, default=1) – Fill pixels within the
-
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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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
returnsTrue
.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 theGeoContext
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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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, callingmap
over anImageCollection
with a function that returns the date of theImage
will now be aList[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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
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 aFeature
. - 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 theFeature
that comes last in theFeatureCollection
.
Notes
Rasterization happens according to the
GeoContext
of theJob
, 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
- value (Int, Float, Str, default=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
- func (Python callable) – A function where the left argument is the accumulated value
(the result of the previous call to
-
sorted
(key, reverse=False)[source]¶ Copy of this
FeatureCollection
, sorted by a key function.Parameters: 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
geo.geocontext.GeoContext
containing the spatial parameters (AOI, resolution, etc.) to use when loading geospatial data. Equivalent to ageo.geocontext.AOI
, with the additional read-only propertiesarr_shape
,gdal_geotrans
, andprojected_bounds
.You don’t often need to construct a Workflows GeoContext yourself. When you call compute(), you can pass in any
geo.geocontext.GeoContext
, or usewf.map.geocontext()
for the current map viewport.Note: The
raster_params
of a GeoContext can be passed toraster.ndarray
to get an equivalent array.Examples
>>> from descarteslabs.workflows import GeoContext >>> from descarteslabs.geo import DLTile >>> dltile = 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_geo(dltile) >>> 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 ofresolution
, 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 inbounds_crs
.bounds_crs
The coordinate reference system of the bounds
, expressed as an EPSG code (likeEPSG: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 thebounds_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_geo
(ctx)Construct a Workflows GeoContext from a DL GeoContext from_scenes
(ctx)Construct a Workflows GeoContext from a DL 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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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_geo
(ctx)[source]¶ Construct a Workflows GeoContext from a DL GeoContext
Parameters: ctx (AOI, DLTile, or XYZTile) – Returns: Return type: GeoContext Example
>>> from descarteslabs.workflows import GeoContext >>> from descarteslabs import geo >>> scene = geo.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_geo(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_scenes
(ctx)¶ Construct a Workflows GeoContext from a DL GeoContext
Parameters: ctx (AOI, DLTile, or XYZTile) – Returns: Return type: GeoContext Example
>>> from descarteslabs.workflows import GeoContext >>> from descarteslabs import geo >>> scene = geo.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_geo(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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
property
align_pixels
¶ Snap the
bounds
to whole-number intervals ofresolution
, 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 thisGeoContext
will produce.This derived property (computed from
projected_bounds
,resolution
, andalign_pixels
) cannot be set in__init__
, but you can callcompute
on it (useful for uploading toCatalog
).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 inbounds_crs
.If
bounds_crs
andcrs
differ, the actual bounds will be the envelope of the rectangle defined bybounds
, when reprojected intocrs
.Type: Tuple[Float, Float, Float, Float]
-
property
bounds_crs
¶ The coordinate reference system of the
bounds
, expressed as an EPSG code (likeEPSG: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-coordinateb
: west-east pixel resolutionc
: row rotation; always 0 forGeoContext
d
: top left pixel’s y-coordinatee
: column rotation; always 0 forGeoContext
f
: north-south pixel resolution, always a negative value
This derived property (computed from
projected_bounds
,resolution
, andalign_pixels
) cannot be set in__init__
, but you can callcompute
on it (useful for uploading toCatalog
).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 tobounds
.Type: Geometry
-
property
projected_bounds
¶ The actual bounds (in units of
crs
), if thebounds_crs
convenience is used.This is the envelope of the four corners defined by
bounds
, when those corners are reprojected frombounds_crs
intocrs
.This derived property cannot be set in
__init__
, but you can callcompute
on it (useful for uploading toCatalog
).Type: Tuple[Float, Float, Float, Float]
-
-
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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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__
attributeReturns: 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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
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 theJob
, 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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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
returnsTrue
.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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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, callingmap
over anImageCollection
with a function that returns the date of theImage
will now be aList[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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
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 theJob
, 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
- func (Python callable) – A function where the left argument is the accumulated value
(the result of the previous call to
-
sorted
(key=None, reverse=False)¶ Copy of this collection, sorted by a key function.
Parameters: 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
orfunc
results in empty groups,ImageCollectionGroupby.groups
will return an empty Dict. Other operations (likemap
andcount
) will also return an empty Dict or an emptyImage
/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.geo 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
fromImageCollection.groupby
in most cases.Parameters: - imgs (ImageCollection) –
ImageCollection
to group - func (Function) – Key function which takes an
Image
and returns which group theImage
belongs to. Must return an instance ofself.key_type
.
Returns: grouped
Return type: 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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
map
(func)[source]¶ Apply a function to each group as an
ImageCollection
and combine the results.func
must take two arguments: the group, and anImageCollection
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 aDict
, where keys are groups and values are results offunc
.Note that every
Image
in everyImageCollecion
gets a"group"
field added to itsproperties
, so that field will be merged/dropped according to normal metadata broadcasting rules (i.e. will still be present on anImage
composited from a group’sImageCollection
, since it’s the same for everyImage
.)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’sImageCollection
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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
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
- imgs (ImageCollection) –
-
class
Image
[source]¶ Proxy Image; construct with
from_id
orfrom_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.geo 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
withimgs
concatenated onto thisImage
, whereimgs
is a variable number ofImage
orImageCollection
objects.concat_bands
(other_image)New Image
, with the bands inother_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 noaxis
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
objectgetmask
()Mask of this Image
, as a newImage
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 booleanImage
or vector object.max
([axis])Maximum pixel value across the provided axis
, or across all pixels in the image if noaxis
argument is provided.mean
([axis])Mean pixel value across the provided axis
, or across all pixels in the image if noaxis
argument is provided.median
([axis])Median pixel value across the provided axis
, or across all pixels in the image if noaxis
argument is provided.min
([axis])Minimum pixel value across the provided axis
, or across all pixels in the image if noaxis
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 noaxis
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 noaxis
argument is provided.sum
([axis])Sum of pixel values across the provided axis
, or across all pixels in the image if noaxis
argument is provided.tan
()Element-wise tangent of an Image
.tile_layer
([name, scales, colormap, …])A WorkflowsLayer
for thisImage
.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
towf.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’sbandinfo
.with_properties
(**properties)New Image
, with the given**properties
fields added to the Image’sproperties
.without_bandinfo
(band, *bandinfo_keys)New Image
, with each given*bandinfo_keys
field dropped from the specified band’sbandinfo
.without_properties
(*property_keys)New Image
, with each given property field name dropped from the Image’sproperties
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 emptyImage
.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 emptyImage
.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 emptyImage
.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 emptyImage
.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
ormax
, in which case they must be the same length as the number of bands. - Note (
min
andmax
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 emptyImage
.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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
concat
(*imgs)[source]¶ ImageCollection
withimgs
concatenated onto thisImage
, whereimgs
is a variable number ofImage
orImageCollection
objects.Images, properties, and bandinfo are concatenated. All imagery must have the same number of bands with identical names. Any empty
Images
orImageCollections
will not be concatenated.Parameters: *imgs (variable number of Image
orImageCollection
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 inother_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 emptyImage
.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: - row (Float) – The x coordinate, in the same CRS as the
GeoContext
- col (Float) – The y coordinate, in the same CRS as the
GeoContext
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)
- row (Float) – The x coordinate, in the same CRS as the
-
cos
()[source]¶ Element-wise cosine of an
Image
.If the
Image
is empty, returns the emptyImage
.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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the valid pixel count.
Options:
Returns: Count of valid pixels across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 emptyImage
.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 arenear
(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: ...
-
getmask
()[source]¶ Mask of this
Image
, as a newImage
with one boolean band named'mask'
.If the
Image
is empty, returns the emptyImage
.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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
log
()[source]¶ Element-wise natural log of an
Image
.If the
Image
is empty, returns the emptyImage
.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 emptyImage
.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 emptyImage
.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 emptyImage
.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:
If the function returns an
Image
,map_bands
will also return oneImage
, containing the bands from all Images returned byfunc
concatenated together.Otherwise,
map_bands
will return aDict
of the results of each call tofunc
, 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 anImage
.Returns: 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 booleanImage
or vector object.If the mask is empty, the original
Image
is returned unchanged. (If theImage
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 byimg > 2
, for example) where True means masked (invalid).Or, a vector (
Geometry
,Feature
, orFeatureCollection
), 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
- mask (
-
max
(axis=None)[source]¶ Maximum pixel value across the provided
axis
, or across all pixels in the image if noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the maximum.
Options:
Returns: Maximum pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the mean.
Options:
Returns: Mean pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the median.
Options:
Returns: Median pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the minimum.
Options:
Returns: Minimum pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 namedred red_1 red_2
).If the
Image
is empty, returns the emptyImage
.If
allow_missing
is False (default), raises an error if given band names that don’t exist in theImage
. Ifallow_missing
is True, any missing names are dropped, and if none of the names exist, returns an emptyImage
.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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
reduction
(operation, axis=None)[source]¶ Reduction along the provided
axis
, or across all pixels in the image if noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) 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:
Returns: Reduction along the provided
axis
. See the options for theaxis
argument for details.Return type: 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 theImage
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 andfill
is anImage
, the originalImage
mask will be overridden and all underlying data will be masked. Ifmask
is False andfill
is anImage
, the original mask is left as is. Iffill
is scalar, theImage
constructed will be fully masked or fully un-masked data ifmask
is True and False respectively. - bandinfo (dict, default None) – Bandinfo used in constructing new
Image
. Iffill
is anImage
, bandinfo is optional, and will be ignored if provided. Iffill
is a scalar, the bandinfo will be used to determine the number of bands on the newImage
, 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', ...
- fill (int, float,
-
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 emptyImage
.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 emptyImage
.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 emptyImage
.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 emptyImage
.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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the standard deviation.
Options:
Returns: Standard deviation along the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 noaxis
argument is provided.If the
Image
is empty, an empty (of the type determined byaxis
) will be returned.Parameters: axis ({None, "pixels", "bands"}) – A Python string indicating the axis along which to take the sum.
Options:
Returns: Sum of pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
orImage
orFloat
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 emptyImage
.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 thisImage
.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 convenienceIf 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 theImage
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 onwf.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 returnedWorkflowsLayer
.For more information, see the docstring to
ParameterSet
.
Returns: layer
Return type:
-
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 callcompute
with. For example, if yourGeoContext
uses"EPSG:4326"
, you’d givex
andy
in lon, lat degrees. If yourGeoContext
uses UTM, you’d givex
andy
in UTM coordinates.When using
visualize
to view the Image on a map,x
andy
must always be given in web-mercator ("EPSG:3857"
) coordinates (with units of meters, not degrees).If the
Image
is empty, returns an emptyDict
.Parameters: - x (Float) – The x coordinate, in the same CRS as the
GeoContext
- y (Float) – The y coordinate, in the same CRS as the
GeoContext
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}
- x (Float) – The x coordinate, in the same CRS as the
-
visualize
(name, scales=None, colormap=None, checkerboard=True, log_level=10, map=None, **parameter_overrides)[source]¶ Add this
Image
towf.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 thisImage
, scales, and colormap. This allows you to re-run cells in Jupyter callingvisualize
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 convenienceIf 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 theImage
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
orMapApp
, optional, default None) – TheMap
(or plain ipyleaflet Map) instance on which to show theImage
. If None (default), useswf.map
, the singleton WorkflowsMapApp
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 onwf.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. Runningvisualize
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 returnedWorkflowsLayer
.For more information, see the docstring to
ParameterSet
.
Returns: layer – The layer displaying this
Image
. Either a newWorkflowsLayer
if one was created, or the layer with the samename
that was already on the map.Return type: 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
- name (str) –
-
with_bandinfo
(band, **bandinfo)[source]¶ New
Image
, with the given**bandinfo
fields added to the specified band’sbandinfo
.If a given field already exists on the band’s bandinfo, it will be overwritten.
If the
Image
is empty, returns the emptyImage
.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’sproperties
.If a given field already exists on the Image’s properties, it will be overwritten.
If the
Image
is empty, returns the emptyImage
.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’sbandinfo
.If a given field doesn’t exists on the band’s
bandinfo
, it will be a no-op.Parameters: 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’sproperties
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 aDict
, where keys are band names and values are Dicts which always contain these fields:id
(Str
): the Descartes Labs ID of the bandname
(Str
): the name of the band. Equal to the key the Dict is stored under inbandinfo
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 indata_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 aDict
which always contains these fields:id
(Str
): the Descartes Labs ID of the Imageproduct
(Str
): the Descartes Labs ID of the product the Image belogs todate
(Datetime
): the UTC date the Image was acquiredcrs
(Str
): the original Coordinate Reference System of the Imagegeotrans
(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.geo 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
withimgs
concatenated onto this one, whereimgs
is a variable number ofImage
orImageCollection
objects.concat_bands
(other)New ImageCollection
, with the bands inother
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 theImageCollection
if noaxis
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 newImageCollection
with one boolean band named ‘mask’.groupby
([func, dates])Group the ImageCollection
by a key value for eachImage
.head
(n)ImageCollection
of the firstn
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 booleanImageCollection
,Image
, or vector object.max
([axis])Maximum pixel value across the provided axis
, or across all pixels in the image collection if noaxis
argument is provided.mean
([axis])Mean pixel value across the provided axis
, or across all pixels in the image collection if noaxis
argument is provided.median
([axis])Median pixel value across the provided axis
, or across all pixels in the image collection if noaxis
argument is provided.min
([axis])Minimum pixel value across the provided axis
, or across all pixels in the image collection if noaxis
argument is provided.mosaic
([reverse])Composite the ImageCollection
into a singleImage
by picking each first-unmasked pixel.partition
(i)Split this ImageCollection
into two collections at indexi
.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 providedaxis
, or across all pixels in the image collection if noaxis
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 anImageCollection
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 noaxis
argument is provided.sum
([axis])Sum of pixel values across the provided axis
, or across all pixels in the image collection if noaxis
argument is provided.tail
(n)ImageCollection
of the lastn
Images.tan
()Element-wise tangent of an ImageCollection
.tile_layer
([name, scales, colormap, …])Reduce this ImageCollection
into anImage
, and create aWorkflowsLayer
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 anImage
, and add towf.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’sbandinfo
.without_bandinfo
(band, *bandinfo_keys)New ImageCollection
, with each given*bandinfo_keys
field dropped from the specified band’sbandinfo
.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 theImageCollection
.-
arccos
()[source]¶ Element-wise inverse cosine of an
ImageCollection
.If the
ImageCollection
is empty, returns the emptyImageCollection
.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 emptyImageCollection
.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 emptyImageCollection
.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 emptyImageCollection
.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
ormax
, in which case they must be the same length as the number of bands. - Note (
min
andmax
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 emptyImageCollection
.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 aGeoContext
, 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. RaisesJobTimeoutError
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 aJob
(which has already hadexecute
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 ifblock==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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
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 moreResourceExhausted
exceptions.- geoctx (
-
concat
(*imgs)[source]¶ ImageCollection
withimgs
concatenated onto this one, whereimgs
is a variable number ofImage
orImageCollection
objects.Images, properties, and bandinfo are concatenated. All imagery must have the same number of bands with identical names. Any empty
Images
orImageCollections
will not be concatenated.Parameters: *imgs (variable number of Image
orImageCollection
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 inother
appended to this one.If band names overlap, the band name from
other
will be suffixed with “_1”.If the
ImageCollection
is empty, orother
is empty, an empty is returned (following broadcasting rules).Parameters: other ( Image
, ImageCollection) –If
other
is a singleImage
, its bands will be added to every image in thisImageCollection
.If
other
is anImageCollection
, it must be the same length asself
.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: - row (Float) – The x coordinate, in the same CRS as the
GeoContext
- col (Float) – The y coordinate, in the same CRS as the
GeoContext
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)
- row (Float) – The x coordinate, in the same CRS as the
-
cos
()[source]¶ Element-wise cosine of an
ImageCollection
.If the
ImageCollection
is empty, returns the emptyImageCollection
.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 theImageCollection
if noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the count of valid pixels across all scenes for each pixel in each band (i.e., a temporal count composite.)"bands"
: Returns a newImageCollection
with one band,"count"
, containing the count of valid pixels across all bands for each pixel and each scene."pixels"
: Returns aList[Dict[Str, Float]]
containing the count of valid pixels in each band in each scene.None
: Returns aFloat
that represents the valid pixel count for the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
containing the count of valid pixels in each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
contianing the count of valid pixels in each scene across all bands.("images", "bands")
: Returns anImage
containing the count of valid pixels across all scenes and bands.
Returns: Count of valid pixels across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 emptyImageCollection
.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
returnsTrue
.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 everyImage
in the product, everywhere. But when aGeoContext
is supplied at computation time (either by passing one intocompute
, or implicitly from the map view area when usingImage.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
andend_datetime
arguments here, and callingfilter
(likeimgs.filter(lambda img: img.properties['date'].month > 5)
). We recommend usingstart_datetime
andend_datetime
for giving a coarse date window (at the year level, for example), then usingfilter
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 arenear
(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: 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 newImageCollection
with one boolean band named ‘mask’.If the
ImageCollection
is empty, returns the emptyImageCollection
.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 eachImage
.func
must take anImage
, and return which group thatImage
belongs to. (The return type offunc
can be anything; the unique values returned byfunc
over everyImage
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 ofImage.properties
.Creates an
ImageCollectionGroupby
object, which can be used to aggregate the groups.Within the
ImageCollectionGroupby
, everyImage
in everyImageCollection
group also gets the field"group"
added to itsproperties
, which identifies which group it belongs to.If the
ImageCollection
is empty, orfunc
results in empty groups,ImageCollectionGroupby.groups
will return an emptyDict
.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 firstn
Images.If the
ImageCollection
is empty, an emptyImageCollection
is returned (all values of n are valid).Parameters: n (Int) – Can be longer than the ImageCollection
without error, in which case the wholeImageCollection
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 aJob
, which runs asynchronously, will be retried if it fails, and stores its results for later retrieval.Parameters: - geoctx (
common.geo.geocontext.GeoContext
,GeoContext
, or None) – The GeoContext parameter under which to run the computation. Almost all computations will require aGeoContext
, 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 thatobj
takes, if it’s aFunction
). 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 fromdescarteslabs.workflows.result_types
. For other formats, returns raw bytes. Consider usingfile
in that case to save the results to a file.Return type: Python object or bytes
- geoctx (
-
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 emptyImageCollection
.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 emptyImageCollection
.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 emptyImageCollection
.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 emptyImageCollection
.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 emptyImageCollection
orList
, according to the return type offunc
. Iffunc
returns some empty and some non-emptyImage
objects, the empties are dropped so only the non-empties are included in the resultingImageCollection
. Iffunc
returns all emptyImage
objects, an emptyImageCollection
is returned.Parameters: func (Python callable) – A function that takes a single Image
and returns another proxytype.Returns: mapped – ImageCollection
iffunc
returnsImage
, otherwiseList[T]
, whereT
is the return type offunc
.For example:
ic.map(lambda img: img + 1)
returns anImageCollection
ic.map(lambda img: img.properties["date"])
returns aList[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:
Str
: the band nameImageCollection
: 1-bandImageCollection
If the function returns an
ImageCollection
,map_bands
will also return oneImageCollection
, containing the bands from all ImageCollections returned byfunc
concatenated together.Otherwise,
map_bands
will return aDict
of the results of each call tofunc
, 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 emptyImageCollection
orDict
, according to the return type offunc
. Iffunc
produces an emptyImage
orImageCollection
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 anImageCollection
.Returns: ImageCollection
iffunc
returnsImageCollection
,- otherwise
Dict[Str, T]
, whereT
is the return type offunc
.
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:
back
:ImageCollection
of N prior imagescurrent
: currentImage
fwd
:ImageCollection
of N subsequent images
The window slides over the
ImageCollection
, starting at indexback
and endingfwd
images before the end.Note that the total length of the window is
back + 1 + fwd
. Specifying a window longer than theImageCollection
will cause an error.If the
ImageCollection
is empty, it will return an emptyImageCollection
orList
, according to the return type offunc
. Iffunc
returns some empty and some non-empty imagery, the empties are dropped so only the non-empties are included in the resultingImageCollection
. Iffunc
returns all empty imagery, an emptyImageCollection
is returned.Parameters: Returns: mapped – If
func
returns anImageCollection
orImage
, all of them are concatenated together and returned as oneImageCollection
.Otherwise, returns a
List
of the values returned byfunc
.Return type: 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 booleanImageCollection
,Image
, or vector object.If the mask is empty, the original
ImageCollection
is returned unchanged. (If theImageCollection
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 bycol > 2
, for example) where True means masked (invalid).Or, single-band
Image
of boolean values, (such as produced byimg > 2
, for example) where True means masked (invalid).Or, a vector (
Geometry
,Feature
, orFeatureCollection
), 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
- mask (
-
max
(axis=None)[source]¶ Maximum pixel value across the provided
axis
, or across all pixels in the image collection if noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the maximum value for each pixel in each band, across all scenes (i.e., a temporal maximum composite.)"bands"
: Returns a newImageCollection
with one band,"max"
, containing the maximum value for each pixel across all bands in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s maximum pixel value for each scene in the collection.None
: Returns aFloat
that represents the maximum pixel value of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
of the maximum pixel value for each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
of the maximum pixel value for each scene across all bands.("images", "bands")
: Returns anImage
containing the maximum value across all scenes and bands.
Returns: Maximum pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the mean value for each pixel in each band, across all scenes"bands"
: Returns a newImageCollection
with one band,"mean"
, containing the mean value for each pixel across all bands in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s mean pixel value for each scene in the collection. (i.e., a temporal mean composite.)None
: Returns aFloat
that represents the mean pixel value of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
of the mean pixel value for each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
of the mean pixel value for each scene across all bands.("images", "bands")
: Returns anImage
containing the mean value across all scenes and bands.
Returns: Mean pixel value across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the median value for each pixel in each band, across all scenes (i.e., a temporal median composite.)"bands"
: Returns a newImageCollection
with one band,"median"
, containing the median value for each pixel across all bands in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s median pixel value for each scene in the collection.None
: Returns aFloat
that represents the median pixel value of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
of the median pixel value for each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
of the median pixel value for each scene across all bands.("images", "bands")
: Returns anImage
containing the median value across all scenes and bands.
Returns: Median pixel value across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the minimum value for each pixel in each band, across all scenes (i.e., a temporal minimum composite.)"bands"
: Returns a newImageCollection
with one band,"min"
, containing the minimum value for each pixel across all bands in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s minimum pixel value for each scene in the collection.None
: Returns aFloat
that represents the minimum pixel value of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
of the minimum pixel value for each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
of the minimum pixel value for each scene across all bands.("images", "bands")
: Returns anImage
containing the minimum value across all scenes and bands.
Returns: Minimum pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 singleImage
by picking each first-unmasked pixel.The order of mosaicing is from last to first, meaning the last
Image
in theImageCollection
is on top.Parameters: reverse (Bool, default False) – The order of mosaicing. If False (default), the last Image
in theImageCollection is on top. If True, the first `Image
in theImageCollection
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 indexi
.If the
ImageCollection
is empty, a 2-tuple of emptyImageCollection
objects is returned (all indices are valid).Parameters: i (Int) – The first ImageCollection
will contain all Images up to but not including indexi
. The second will contain theImage
at indexi
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 namedred red_1 red_2
).If the
ImageCollection
is empty, returns the emptyImageCollection
.If
allow_missing
is False (default), raises an error if given band names that don’t exist in theImageCollection
. Ifallow_missing
is True, any missing names are dropped, and if none of the names exist, returns an emptyImageCollection
.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 aFunction
that takes those parameters (usingFunction.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: - id (Str) – ID for the new Workflow object. This should be of the form
-
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
- func (Python callable) – A function where the left argument is the accumulated value
(the result of the previous call to
-
reduction
(operation, axis=None)[source]¶ Reduce the
ImageCollection
along the providedaxis
, or across all pixels in the image collection if noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the reduction across all scenes, for each pixel in each band (i.e., a temporal reduction.)"bands"
: Returns a newImageCollection
with one band, named according tooperation
, containing the reduction across all bands, for each pixel in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s reduction, for each scene in the collection.None
: Returns aFloat
that represents the reduction of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
containing the reduction across all scenes, for each band, keyed by band name.("bands", "pixels")
: Returns aList[Float]
containing the reduction across all bands, for each scene.("images", "bands")
: Returns anImage
containing the reduction across all scenes and bands.
Returns: Composite along the provided
axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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)
- 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”,
-
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 (likerename_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 emptyImageCollection
.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") >>> 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 theImageCollection
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 andfill
is anImageCollection
, the originalImageCollection
mask will be overridden and all underlying data will be masked. Ifmask
is False andfill
is anImageCollection
, the original mask is left as is. Iffill
is scalar, theImageCollection
constructed will be fully masked or fully un-masked data ifmask
is True and False respectively. - bandinfo (dict, default None) – Bandinfo used in constructing new
ImageCollection
. Iffill
is anImageCollection
, bandinfo is optional, and will be ignored if provided. Iffill
is a scalar, the bandinfo will be used to determine the number of bands on the newImageCollection
, 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', ...
- fill (int, float,
-
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 emptyImageCollection
.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 emptyImageCollection
.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 anImageCollection
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 inself
to use as the sorting band. IfImageCollection
, use this single-bandImageCollection
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: 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
- band (Str or
-
sorted
(key, reverse=False)[source]¶ Copy of this
ImageCollection
, sorted by a key function.If the
ImageCollection
is empty, returns the emptyImageCollection
.Parameters: Returns: sorted
Return type: 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 emptyImageCollection
.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 emptyImageCollection
.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 noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing standard deviation across all scenes, for each pixel in each band (i.e., a temporal standard deviation composite.)"bands"
: Returns a newImageCollection
with one band,"std"
, containing the standard deviation across all bands, for each pixel in each scene."pixels"
Returns aList[Dict[Str, Float]]
containing each band’s standard deviation, for each scene in the collection.None
: Returns aFloat
that represents the standard deviation of the entireImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
containing the standard deviation across all scenes, for each band, keyed by band name.("bands", "pixels")
: Returns aList[Float]
containing the standard deviation across all bands, for each scene.("images", "bands")
: Returns anImage
containing the standard deviation across all scenes and bands.
Returns: Standard deviation along the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 noaxis
argument is provided.If the
ImageCollection
is empty, an empty (of the type determined byaxis
) 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 anImage
containing the sum across all scenes for each pixel in each band (i.e., a temporal sum composite.)"bands"
: Returns a newImageCollection
with one band,"sum"
, containing the sum across all bands for each pixel and each scene."pixels"
Returns aList[Dict[Str, Float]]
containing the sum of the pixel values for each band in each scene.None
: Returns aFloat
that represents the sum of all pixel values in theImageCollection
, across all scenes, bands, and pixels.("images", "pixels")
: Returns aDict[Str, Float]
containing the sum of the pixel values for each band across all scenes, keyed by band name.("bands", "pixels")
: Returns aList[Float]
contianing the sum of the pixel values for each scene across all bands.("images", "bands")
: Returns anImage
containing the sum across all scenes and bands.
Returns: Sum of pixel values across the provided axis
. See the options for theaxis
argument for details.Return type: Dict[Str, Float]
,List[Float]
,List[Dict[Str, Float]]
,ImageCollection
,Image
orFloat
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 lastn
Images.If the
ImageCollection
is empty, an emptyImageCollection
is returned (all values of n are valid).Parameters: n (Int) – Can be longer than the ImageCollection
without error, in which case the wholeImageCollection
is returned.Returns: imgs Return type: ImageCollection
Example
>>> from descarteslabs.workflows import ImageCollection >>> col = ImageCollection.from_id("landsat:LC08:01:RT:TOAR", ... start_datetime
-