maxar-platform 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,323 @@
1
+ """
2
+ Provides
3
+ --------
4
+ OGC access to MGP images, footprints, and seamlines. For searching imagery, a streamlined
5
+ client that works similar to `pystac-client` is included as an alternative to using WFS
6
+ GetFeature calls.
7
+
8
+ References
9
+ ----------
10
+ https://developers.maxar.com/docs/streaming-imagery/
11
+ https://developers.maxar.com/docs/streaming-basemap/
12
+
13
+ """
14
+
15
+ from owslib import util
16
+ from owslib.etree import ParseError, etree
17
+
18
+ from maxar_platform.session import session
19
+
20
+ __all__ = [
21
+ "WebMapService",
22
+ "WebFeatureService",
23
+ "WebCoverageService",
24
+ "WfsSearchClient",
25
+ "FeatureSearch",
26
+ "flip_axis_order",
27
+ ]
28
+
29
+
30
+ def flip_axis_order(bbox):
31
+ """Flips a bbox from x,y to y,x and vice versa
32
+
33
+ Parameters
34
+ ----------
35
+ bbox: list or tuple
36
+ A bounding box
37
+
38
+ Returns
39
+ -------
40
+ list
41
+ A flipped bounding box
42
+ """
43
+ return [bbox[1], bbox[0], bbox[3], bbox[2], *bbox[4:]]
44
+
45
+
46
+ def open_MGP_URL(url_base, data=None, method="Get", **kwargs):
47
+ """An MGP URL opener using maxar_platform.session
48
+
49
+ Used to patch OWSLib's opener.
50
+
51
+ See owslib.util.OpenURL
52
+ """
53
+
54
+ rkwargs = {}
55
+ headers = {}
56
+ method = method.split("}")[-1]
57
+
58
+ if method.lower() == "post":
59
+ try:
60
+ etree.fromstring(data)
61
+ headers["Content-Type"] = "text/xml"
62
+ except (ParseError, UnicodeEncodeError):
63
+ pass
64
+
65
+ rkwargs["data"] = data
66
+
67
+ elif method.lower() == "get":
68
+ rkwargs["params"] = data
69
+
70
+ else:
71
+ raise ValueError("Unknown method ('%s'), expected 'get' or 'post'" % method)
72
+
73
+ req = session.request(method.upper(), url_base, headers=headers, **rkwargs)
74
+
75
+ if req.status_code in [400, 401]:
76
+ raise util.ServiceException(req.text)
77
+
78
+ if req.status_code in [404, 500, 502, 503, 504]: # add more if needed
79
+ req.raise_for_status()
80
+
81
+ # check for service exceptions without the http header set
82
+ if "Content-Type" in req.headers and req.headers["Content-Type"] in [
83
+ "text/xml",
84
+ "application/xml",
85
+ "application/vnd.ogc.se_xml",
86
+ ]:
87
+ # just in case 400 headers were not set, going to have to read the xml to see if it's an exception report.
88
+ se_tree = etree.fromstring(req.content)
89
+
90
+ # to handle the variety of namespaces and terms across services
91
+ # and versions, especially for "legacy" responses like WMS 1.3.0
92
+ possible_errors = [
93
+ "{http://www.opengis.net/ows}Exception",
94
+ "{http://www.opengis.net/ows/1.1}Exception",
95
+ "{http://www.opengis.net/ogc}ServiceException",
96
+ "ServiceException",
97
+ ]
98
+
99
+ for possible_error in possible_errors:
100
+ serviceException = se_tree.find(possible_error)
101
+ if serviceException is not None:
102
+ # and we need to deal with some message nesting
103
+ raise util.ServiceException(
104
+ "\n".join([t.strip() for t in serviceException.itertext() if t.strip()])
105
+ )
106
+
107
+ return util.ResponseWrapper(req)
108
+
109
+
110
+ util.openURL = open_MGP_URL
111
+
112
+ from owslib.wcs import WebCoverageService
113
+ from owslib.wfs import WebFeatureService
114
+ from owslib.wms import WebMapService
115
+
116
+
117
+ class WfsSearchClient:
118
+ """A search client for WFS
119
+
120
+ This provides a similar interface to `pystac_client` as used by the SDK for Discovery
121
+ """
122
+
123
+ def __init__(self, base_url, default_typename=None):
124
+ self.base_url = base_url
125
+ self.default_typename = default_typename
126
+
127
+ def typename_to_id(self, typename):
128
+ typename = typename.lower()
129
+ if typename.endswith("finishedfeature"):
130
+ return "legacyIdentifier"
131
+ if "seamline" in typename:
132
+ return "catid"
133
+ else:
134
+ raise NotImplementedError(
135
+ f"The layer {typename} does not contain features tied to catalog IDs"
136
+ )
137
+
138
+ def search(
139
+ self,
140
+ query,
141
+ typename=None,
142
+ bbox=None,
143
+ bbox_xy=None,
144
+ limit=200,
145
+ max_items=None,
146
+ **parameters,
147
+ ):
148
+ """Initialize a search
149
+
150
+ Parameters
151
+ ----------
152
+ query: str
153
+ CQL query
154
+ typename: str
155
+ Typename to search. This should already be defined on the class but can be changed if needed.
156
+ bbox: list or tuple
157
+ Bounding box. Since the WFS layers are in EPSG:4326, the bounding box must follow the defined coordinate
158
+ order of longitude, latitude.
159
+ bbox_xy: list or tuple
160
+ Bounding box in latitude, longitude order for convenience
161
+ max_items:
162
+ Maximum number of results to fetch
163
+
164
+ Keywords
165
+ --------
166
+ Additional keywords are passed through to the WFS GetFeature call as parameters
167
+
168
+ Notes
169
+ -----
170
+ While this functions similarly to `pystac-client`, the results are in GeoJSON. `pystac-client` returns
171
+ STAC Items either as PySTAC objects or serialized as dictionaries.
172
+
173
+ Returns
174
+ -------
175
+ FeatureSearch
176
+ The class that executes searches
177
+ """
178
+
179
+ typename = self.default_typename or typename
180
+
181
+ if typename is None:
182
+ raise ValueError(
183
+ "No typename was provided and this search client does not have a default typename to use instead"
184
+ )
185
+
186
+ parameter_keys = [key.lower() for key in parameters.keys()]
187
+ if "startindex" in parameter_keys:
188
+ raise NotImplementedError(
189
+ 'This search client does not support fetching arbitrary ranges with "startIndex"'
190
+ )
191
+
192
+ params = {
193
+ "service": "WFS",
194
+ "request": "GetFeature",
195
+ "typeName": typename,
196
+ "outputFormat": "json",
197
+ }
198
+
199
+ if bbox_xy is not None:
200
+ if type(bbox) is str:
201
+ coords = bbox_xy.split(",")
202
+ bbox_xy = [float(c) for c in coords[:4]].extend(coords[4:])
203
+ bbox = flip_axis_order(bbox_xy)
204
+
205
+ if bbox is not None:
206
+ if type(bbox) is not str:
207
+ coords = [str(c) for c in bbox]
208
+ bbox = ",".join(coords)
209
+ if query:
210
+ query = query + f"AND (bbox(featureGeometry,{bbox}))"
211
+ else:
212
+ params["bbox"] = bbox
213
+
214
+ if query:
215
+ params["cql_filter"] = query
216
+ params.update(parameters)
217
+
218
+ return FeatureSearch(self.base_url, params, limit, max_items)
219
+
220
+ def find(self, cat_id, typename=None):
221
+ """Find a feature by Catalog ID
222
+
223
+ The field name that stores the Catalog ID can vary so this function is
224
+ configured to use the correct field name.
225
+
226
+ Parameters
227
+ ----------
228
+ cat_id: str
229
+ Catalog ID of the image
230
+ typename: str
231
+ Typename to search, this will be already defined by the class but can be changed
232
+
233
+ """
234
+
235
+ typename = self.default_typename or typename
236
+ id_field = self.typename_to_id(typename)
237
+ result = self.search(f"{id_field}='{cat_id}'", typename)
238
+ return list(result.features())
239
+
240
+
241
+ class FeatureSearch:
242
+ """Executes the search and can return results in several formats
243
+
244
+ Parameters
245
+ ----------
246
+ base_url: str
247
+ WFS base URL
248
+ params: dict
249
+ WFS search parameters
250
+ page_size: int, optional
251
+ Number of records to fetch when paginating, defaults to 200
252
+ max_items: int
253
+ Total number of records to fetch
254
+ """
255
+
256
+ def __init__(self, base_url, params, limit=200, max_items=None):
257
+ self.base_url = base_url
258
+ self.params = params
259
+ self.page_size = limit
260
+ self.max_items = max_items
261
+
262
+ def features(self):
263
+ """Generator returning individual GeoJSON Features
264
+
265
+ Yields
266
+ ------
267
+ Feature"""
268
+
269
+ for page in self.pages():
270
+ for feature in page["features"]:
271
+ yield feature
272
+
273
+ def pages(self):
274
+ """Generator returning paginated fetches as GeoJSON FeatureCollections
275
+
276
+ Yields
277
+ ------
278
+ FeatureCollection
279
+ """
280
+ for page in self._fetch_pages():
281
+ yield page
282
+
283
+ def feature_collection(self):
284
+ """Return search results as single FeatureCollection
285
+
286
+ Yields
287
+ ------
288
+ FeatureCollection"""
289
+
290
+ return {"type": "FeatureCollection", "features": list(self.features)}
291
+
292
+ def _fetch_pages(self):
293
+ """Generator of pages of features as GeoJSON
294
+
295
+ Yields
296
+ ------
297
+ FeatureCollection
298
+ """
299
+ current_page = 1
300
+ total_pages = self.max_items // self.page_size if self.max_items else None
301
+ remainder = self.max_items % self.page_size if self.max_items else None
302
+ done = False
303
+ while not done:
304
+ is_last_page = total_pages == current_page
305
+ self.params.update(
306
+ {
307
+ "startindex": (current_page - 1) * self.page_size,
308
+ "count": self.page_size,
309
+ }
310
+ )
311
+ r = session.get(self.base_url, params=self.params)
312
+ fc = r.json()
313
+ if not is_last_page:
314
+ yield fc
315
+ else:
316
+ yield {
317
+ "type": "FeatureCollection",
318
+ "features": fc["features"][:remainder],
319
+ }
320
+ current_page += 1
321
+ has_more = len(fc["features"]) == self.page_size
322
+ empty_last_page = remainder == 0 and current_page + 1 == total_pages
323
+ done = is_last_page or empty_last_page or not has_more
@@ -0,0 +1,55 @@
1
+ """ WFS access to 'footprints'
2
+
3
+ Provides
4
+ --------
5
+ OGC access to image footprints as well as metadata search through WFS.
6
+
7
+ See the `ogc` parent module for more information about the classes returned here.
8
+
9
+ Notes
10
+ -----
11
+ Footprints covers both the bounds of individual strips and mosaic products.
12
+
13
+ They are served from the TypeName 'Maxar:FinishedFeature' which is not obvious.
14
+
15
+ For seamlines within a mosaic, use `maxar_platform.ogc.seamlines`
16
+
17
+ The source layer uses EPSG:4326 so beware that coordinate order should be lat,lon.
18
+
19
+ References
20
+ ----------
21
+ https://developers.maxar.com/docs/streaming-imagery/guides/wfs
22
+
23
+ """
24
+
25
+ from posixpath import join
26
+
27
+ from maxar_platform import BASE_URL
28
+ from maxar_platform.ogc import WebFeatureService as ows_wfs
29
+ from maxar_platform.ogc import WfsSearchClient
30
+
31
+ __all__ = ["WebFeatureService", "web_feature_service", "wfs_cql_client"]
32
+
33
+ STREAMING_URL = join(BASE_URL, "streaming/v1/ogc/wms")
34
+
35
+
36
+ def WebFeatureService(version="1.1.0"):
37
+ """Factory function to get an OWSLib WFS object
38
+
39
+ Parameters
40
+ ----------
41
+ version : str
42
+ WMS version, default is 1.1.0
43
+
44
+ Returns
45
+ -------
46
+ maxar_platform.ogc.WebFeatureService"""
47
+
48
+ return ows_wfs(STREAMING_URL, version=version)
49
+
50
+
51
+ wfs_cql_client = WfsSearchClient(STREAMING_URL, "Maxar:FinishedFeature")
52
+ """ A configured instance of WfsSearchClient """
53
+
54
+ web_feature_service = WebFeatureService()
55
+ """ A configured instance of OWSLib's WFS object, using WFS 1.10 """
@@ -0,0 +1,60 @@
1
+ """ OGC access to imagery
2
+
3
+ Provides
4
+ --------
5
+ OGC access to imagery - as well as metadata search.
6
+
7
+ Importing `web_feature_service` returns a configured OWSLib instance ready for use.
8
+
9
+ Similarly, `wfs_cql_client` is also a configured instance configured for searching
10
+ without having to look up TypeNames and other layer specific settings.
11
+
12
+ See the `ogc` parent module for more information about the classes returned here.
13
+
14
+ Notes
15
+ -----
16
+
17
+ This image layer contains ALL the imagery available - to access an individual image in WMS,
18
+ use a CQL filter like "legacyId=1040010096284D00". The imagery layer can evaluate filters on
19
+ the image metadata in the same manner as WFS queries on the image footprints.
20
+
21
+ The source layer uses EPSG:4326 so beware that coordinate order should be lat,lon.
22
+
23
+
24
+ References
25
+ ----------
26
+ https://developers.maxar.com/docs/streaming-imagery/guides/wms
27
+
28
+ """
29
+
30
+ from posixpath import join
31
+
32
+ from maxar_platform import BASE_URL
33
+ from maxar_platform.ogc import WebCoverageService as ows_wcs
34
+ from maxar_platform.ogc import WebFeatureService as ows_wfs
35
+ from maxar_platform.ogc import WebMapService as ows_wms
36
+ from maxar_platform.ogc import WfsSearchClient
37
+
38
+ __all__ = ["WebMapService", "WebFeatureService", "WebCoverageService", "wfs_cql_client"]
39
+
40
+
41
+ STREAMING_URL = join(BASE_URL, "streaming/v1/ogc/wms")
42
+
43
+
44
+ def WebMapService(version="1.1.1"):
45
+ return ows_wms(STREAMING_URL, version=version)
46
+
47
+
48
+ def WebFeatureService(version="1.1.0"):
49
+ return ows_wfs(STREAMING_URL, version=version)
50
+
51
+
52
+ def WebCoverageService(version="2.0.1"):
53
+ return ows_wcs(STREAMING_URL, version=version)
54
+
55
+
56
+ wfs_cql_client = WfsSearchClient(STREAMING_URL, "Maxar:FinishedFeature")
57
+
58
+ web_map_service = WebMapService()
59
+ web_feature_service = WebFeatureService()
60
+ web_coverage_service = WebCoverageService()
@@ -0,0 +1,51 @@
1
+ """ WFS access to mosaic seamlines
2
+
3
+ Provides
4
+ --------
5
+ OGC access to mosaic seamlines - as well as metadata search through WFS.
6
+
7
+ Each feature represents an individual strip as it cut to fill the mosaic product
8
+
9
+ Importing `web_feature_service` returns a configured OWSLib instance ready for use.
10
+
11
+ Similarly, `wfs_cql_client` is also a configured instance configured for searching
12
+ without having to look up TypeNames and other layer specific settings.
13
+
14
+ See the `ogc` parent module for more information about the classes returned here.
15
+
16
+ Notes
17
+ -----
18
+
19
+ The source layer uses EPSG:4326 so beware that coordinate order should be lat,lon.
20
+
21
+
22
+ References
23
+ ----------
24
+ https://developers.maxar.com/docs/streaming-basemap/guides/wfs
25
+
26
+ """
27
+
28
+ from posixpath import join
29
+
30
+ from maxar_platform import BASE_URL
31
+ from maxar_platform.ogc import WebFeatureService as ows_wfs
32
+ from maxar_platform.ogc import WebMapService as ows_wms
33
+ from maxar_platform.ogc import WfsSearchClient
34
+
35
+ __all__ = ["WebMapService", "WebFeatureService", "wfs_cql_client"]
36
+
37
+
38
+ STREAMING_URL = join(BASE_URL, "basemaps/v1/seamlines/wms")
39
+
40
+
41
+ def WebFeatureService(version="1.1.0"):
42
+ return ows_wfs(STREAMING_URL, version=version)
43
+
44
+
45
+ def WebMapService(version="1.3.0"):
46
+ return ows_wms(STREAMING_URL, version=version)
47
+
48
+
49
+ wfs_cql_client = WfsSearchClient(STREAMING_URL)
50
+ web_feature_service = WebFeatureService()
51
+ web_map_service = WebMapService()
@@ -0,0 +1,189 @@
1
+ """
2
+ Provides
3
+ --------
4
+
5
+ Functions for working with the Order API to:
6
+
7
+ - Validate, estimate cost, and place an order to a pipeline
8
+ - Get one or list multiple placed orders
9
+ - Cancel an order (if supported by the pipeline)
10
+ - Get order events to check progress
11
+
12
+ There are no formal objects for orders and order settings, an order "object" is a Python dictionary.
13
+
14
+ References
15
+ ----------
16
+ https://developers.maxar.com/docs/ordering/
17
+
18
+
19
+ """
20
+
21
+ from posixpath import join
22
+ from typing import List, Union
23
+
24
+ from maxar_platform import BASE_URL
25
+ from maxar_platform.session import paginated_request, session
26
+
27
+ __all__ = (
28
+ "submit_order",
29
+ "validate_order",
30
+ "estimate_order_usage",
31
+ "get_order",
32
+ "get_order_events",
33
+ "cancel_order",
34
+ "list_orders",
35
+ )
36
+
37
+ API_BASE = join(BASE_URL, "ordering/v1")
38
+ ORDERING_ORDERS = join(API_BASE, "orders")
39
+ ORDERING_ORDER = join(ORDERING_ORDERS, ":id")
40
+ ORDERING_ORDER_EVENTS = join(ORDERING_ORDER, "events")
41
+ ORDERING_ORDER_CANCEL = join(ORDERING_ORDER, "cancel")
42
+ ORDERING_PIPELINES = join(API_BASE, "pipelines")
43
+ ORDERING_PIPELINE_ORDER = join(ORDERING_PIPELINES, ":namespace/:name/order")
44
+ ORDERING_PIPELINE_VALIDATE = join(ORDERING_PIPELINES, ":namespace/:name/validate")
45
+ ORDERING_PIPELINE_ESTIMATE = join(ORDERING_PIPELINES, ":namespace/:name/estimate")
46
+
47
+
48
+ def list_orders(
49
+ limit=100,
50
+ sort="desc",
51
+ filter=None,
52
+ ):
53
+ """Fetch user's orders
54
+
55
+ Parameters
56
+ ----------
57
+ limit: int or None, default None
58
+ Maximum number of orders to fetch, None means unlimited, default is 100.
59
+ sort: str
60
+ Sort order for order IDs, either 'asc' (ascending) or 'desc' (descending). Default is 'desc'.
61
+ filter: str or iterable of strings
62
+ Filter results that match values contained in the given key separated by a colon.
63
+ Matches are not exact: filtering on a value of `pet:cat` will return `cat` along with `caterpillar` pets.
64
+ Multiple filters can be passed but keys must be unique since filters will be logically ANDed.
65
+ Example: 'product_id:1234' or ['pet:cat', 'color:black']
66
+
67
+ Returns
68
+ -------
69
+ list
70
+ Order objects matching parameters"""
71
+
72
+ return paginated_request("GET", ORDERING_ORDERS, "orders", sort, limit, filter=filter)
73
+
74
+
75
+ def get_order(order_id):
76
+ """Fetch raw data about an Order from an ID
77
+
78
+ Parameters
79
+ ----------
80
+ order_id : str
81
+ Order ID to fetch metadata for
82
+
83
+ Returns
84
+ -------
85
+ dict
86
+ API data for the given Order"""
87
+
88
+ url = ORDERING_ORDER.replace(":id", order_id)
89
+ r = session.oauth_session.get(url)
90
+ return r.json()["data"]
91
+
92
+
93
+ def get_order_events(order_id):
94
+ """Fetch event data from an Order from an ID
95
+
96
+ Parameters
97
+ ----------
98
+ order_id : str
99
+ Order ID to fetch metadata for
100
+
101
+ Returns
102
+ -------
103
+ list
104
+ Status events for the given Order as it completes different steps in the ordering process
105
+ """
106
+
107
+ url = ORDERING_ORDER_EVENTS.replace(":id", order_id)
108
+
109
+ return paginated_request("GET", url, "events")
110
+
111
+
112
+ def cancel_order(order_id):
113
+ """Cancel an order from an ID, if supported
114
+
115
+ Parameters
116
+ ----------
117
+ order_id : str
118
+ Order ID to cancel
119
+
120
+ Returns
121
+ -------
122
+
123
+ Note
124
+ ----
125
+
126
+ Not all pipelines support cancellation. Orders may not be cancellable after they have reached
127
+ certain points in processing. See the pipeline's documentation for more information.
128
+ """
129
+
130
+ url = ORDERING_ORDER_CANCEL.replace(":id", order_id)
131
+ r = session.get(url)
132
+
133
+
134
+ def submit_order(pipeline, order):
135
+ """Send a request to the Order API
136
+
137
+ Parameters
138
+ ----------
139
+ pipeline : str
140
+ Pipeline name, in the form `namespace/name`. Ex: "imagery/analysis-ready"
141
+ order: dict
142
+ Order object, see pipeline docs or snippets for examples.
143
+
144
+ Returns
145
+ -------
146
+ dict
147
+ API response data for the Order"""
148
+ order_url = ORDERING_PIPELINE_ORDER.replace(":namespace/:name", pipeline)
149
+ r = session.oauth_session.post(order_url, json=order)
150
+ return r.json()["data"]
151
+
152
+
153
+ def validate_order(pipeline, order):
154
+ """Validate a request to the Order API
155
+
156
+ Parameters
157
+ ----------
158
+ pipeline : str
159
+ Pipeline name, in the form `namespace/name`. Ex: "imagery/analysis-ready"
160
+ order: dict
161
+ Order object, see pipeline docs or snippets for examples.
162
+
163
+ Returns
164
+ -------
165
+ dict
166
+ API response data for the Order if it were placed"""
167
+ order_url = ORDERING_PIPELINE_VALIDATE.replace(":namespace/:name", pipeline)
168
+ print(order_url)
169
+ r = session.oauth_session.post(order_url, json=order)
170
+ return r.json()["data"]
171
+
172
+
173
+ def estimate_order_usage(pipeline, order):
174
+ """Estimate the order cost
175
+
176
+ Parameters
177
+ ----------
178
+ pipeline : str
179
+ Pipeline name, in the form `namespace/name`. Ex: "imagery/analysis-ready"
180
+ order: dict
181
+ Order object, see pipeline docs or snippets for examples.
182
+
183
+ Returns
184
+ -------
185
+ dict
186
+ Usage estimates for the given Order"""
187
+ order_url = ORDERING_PIPELINE_ESTIMATE.replace(":namespace/:name", pipeline)
188
+ r = session.oauth_session.post(order_url, json=order)
189
+ return r.json()["data"]