id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
243,000 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | _config_options | def _config_options(func):
""" A helper function which joins click.option functions of each parameter from config.json
"""
for param in SHConfig().get_params()[-1::-1]:
func = click.option('--{}'.format(param), param,
help='Set new values to configuration parameter "{}"'.format(param))(func)
return func | python | def _config_options(func):
for param in SHConfig().get_params()[-1::-1]:
func = click.option('--{}'.format(param), param,
help='Set new values to configuration parameter "{}"'.format(param))(func)
return func | [
"def",
"_config_options",
"(",
"func",
")",
":",
"for",
"param",
"in",
"SHConfig",
"(",
")",
".",
"get_params",
"(",
")",
"[",
"-",
"1",
":",
":",
"-",
"1",
"]",
":",
"func",
"=",
"click",
".",
"option",
"(",
"'--{}'",
".",
"format",
"(",
"param"... | A helper function which joins click.option functions of each parameter from config.json | [
"A",
"helper",
"function",
"which",
"joins",
"click",
".",
"option",
"functions",
"of",
"each",
"parameter",
"from",
"config",
".",
"json"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L70-L76 |
243,001 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | config | def config(show, reset, **params):
"""Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120
"""
sh_config = SHConfig()
if reset:
sh_config.reset()
for param, value in params.items():
if value is not None:
try:
value = int(value)
except ValueError:
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
if getattr(sh_config, param) != value:
setattr(sh_config, param, value)
old_config = SHConfig()
sh_config.save()
for param in sh_config.get_params():
if sh_config[param] != old_config[param]:
value = sh_config[param]
if isinstance(value, str):
value = "'{}'".format(value)
click.echo("The value of parameter '{}' was updated to {}".format(param, value))
if show:
click.echo(str(sh_config))
click.echo('Configuration file location: {}'.format(sh_config.get_config_location())) | python | def config(show, reset, **params):
sh_config = SHConfig()
if reset:
sh_config.reset()
for param, value in params.items():
if value is not None:
try:
value = int(value)
except ValueError:
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
if getattr(sh_config, param) != value:
setattr(sh_config, param, value)
old_config = SHConfig()
sh_config.save()
for param in sh_config.get_params():
if sh_config[param] != old_config[param]:
value = sh_config[param]
if isinstance(value, str):
value = "'{}'".format(value)
click.echo("The value of parameter '{}' was updated to {}".format(param, value))
if show:
click.echo(str(sh_config))
click.echo('Configuration file location: {}'.format(sh_config.get_config_location())) | [
"def",
"config",
"(",
"show",
",",
"reset",
",",
"*",
"*",
"params",
")",
":",
"sh_config",
"=",
"SHConfig",
"(",
")",
"if",
"reset",
":",
"sh_config",
".",
"reset",
"(",
")",
"for",
"param",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
... | Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_timeout_seconds 120 | [
"Inspect",
"and",
"configure",
"parameters",
"in",
"your",
"local",
"sentinelhub",
"configuration",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L83-L121 |
243,002 | sentinel-hub/sentinelhub-py | sentinelhub/commands.py | download | def download(url, filename, redownload):
"""Download from custom created URL into custom created file path
\b
Example:
sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml
"""
data_folder, filename = filename.rsplit('/', 1)
download_list = [DownloadRequest(url=url, data_folder=data_folder, filename=filename, save_response=True,
return_data=False)]
download_data(download_list, redownload=redownload) | python | def download(url, filename, redownload):
data_folder, filename = filename.rsplit('/', 1)
download_list = [DownloadRequest(url=url, data_folder=data_folder, filename=filename, save_response=True,
return_data=False)]
download_data(download_list, redownload=redownload) | [
"def",
"download",
"(",
"url",
",",
"filename",
",",
"redownload",
")",
":",
"data_folder",
",",
"filename",
"=",
"filename",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"download_list",
"=",
"[",
"DownloadRequest",
"(",
"url",
"=",
"url",
",",
"data_folde... | Download from custom created URL into custom created file path
\b
Example:
sentinelhub.download http://sentinel-s2-l1c.s3.amazonaws.com/tiles/54/H/VH/2017/4/14/0/metadata.xml home/example.xml | [
"Download",
"from",
"custom",
"created",
"URL",
"into",
"custom",
"created",
"file",
"path"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L128-L138 |
243,003 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig.save | def save(self):
"""Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()``
"""
is_changed = False
for prop in self._instance.CONFIG_PARAMS:
if getattr(self, prop) != getattr(self._instance, prop):
is_changed = True
setattr(self._instance, prop, getattr(self, prop))
if is_changed:
self._instance.save_configuration() | python | def save(self):
is_changed = False
for prop in self._instance.CONFIG_PARAMS:
if getattr(self, prop) != getattr(self._instance, prop):
is_changed = True
setattr(self._instance, prop, getattr(self, prop))
if is_changed:
self._instance.save_configuration() | [
"def",
"save",
"(",
"self",
")",
":",
"is_changed",
"=",
"False",
"for",
"prop",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
":",
"if",
"getattr",
"(",
"self",
",",
"prop",
")",
"!=",
"getattr",
"(",
"self",
".",
"_instance",
",",
"prop",
"... | Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()`` | [
"Method",
"that",
"saves",
"configuration",
"parameter",
"changes",
"from",
"instance",
"of",
"SHConfig",
"class",
"to",
"global",
"config",
"class",
"and",
"to",
"config",
".",
"json",
"file",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L158-L173 |
243,004 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig._reset_param | def _reset_param(self, param):
""" Resets a single parameter
:param param: A configuration parameter
:type param: str
"""
if param not in self._instance.CONFIG_PARAMS:
raise ValueError("Cannot reset unknown parameter '{}'".format(param))
setattr(self, param, self._instance.CONFIG_PARAMS[param]) | python | def _reset_param(self, param):
if param not in self._instance.CONFIG_PARAMS:
raise ValueError("Cannot reset unknown parameter '{}'".format(param))
setattr(self, param, self._instance.CONFIG_PARAMS[param]) | [
"def",
"_reset_param",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"not",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
":",
"raise",
"ValueError",
"(",
"\"Cannot reset unknown parameter '{}'\"",
".",
"format",
"(",
"param",
")",
")",
"setattr"... | Resets a single parameter
:param param: A configuration parameter
:type param: str | [
"Resets",
"a",
"single",
"parameter"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L195-L203 |
243,005 | sentinel-hub/sentinelhub-py | sentinelhub/config.py | SHConfig.get_config_dict | def get_config_dict(self):
""" Get a dictionary representation of `SHConfig` class
:return: A dictionary with configuration parameters
:rtype: OrderedDict
"""
return OrderedDict((prop, getattr(self, prop)) for prop in self._instance.CONFIG_PARAMS) | python | def get_config_dict(self):
return OrderedDict((prop, getattr(self, prop)) for prop in self._instance.CONFIG_PARAMS) | [
"def",
"get_config_dict",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"prop",
",",
"getattr",
"(",
"self",
",",
"prop",
")",
")",
"for",
"prop",
"in",
"self",
".",
"_instance",
".",
"CONFIG_PARAMS",
")"
] | Get a dictionary representation of `SHConfig` class
:return: A dictionary with configuration parameters
:rtype: OrderedDict | [
"Get",
"a",
"dictionary",
"representation",
"of",
"SHConfig",
"class"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/config.py#L213-L219 |
243,006 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | bbox_to_resolution | def bbox_to_resolution(bbox, width, height):
""" Calculates pixel resolution in meters for a given bbox of a given width and height.
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: width of bounding box in pixels
:type width: int
:param height: height of bounding box in pixels
:type height: int
:return: resolution east-west at north and south, and resolution north-south in meters for given CRS
:rtype: float, float
:raises: ValueError if CRS is not supported
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
return abs(east2 - east1) / width, abs(north2 - north1) / height | python | def bbox_to_resolution(bbox, width, height):
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
return abs(east2 - east1) / width, abs(north2 - north1) / height | [
"def",
"bbox_to_resolution",
"(",
"bbox",
",",
"width",
",",
"height",
")",
":",
"utm_bbox",
"=",
"to_utm_bbox",
"(",
"bbox",
")",
"east1",
",",
"north1",
"=",
"utm_bbox",
".",
"lower_left",
"east2",
",",
"north2",
"=",
"utm_bbox",
".",
"upper_right",
"ret... | Calculates pixel resolution in meters for a given bbox of a given width and height.
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: width of bounding box in pixels
:type width: int
:param height: height of bounding box in pixels
:type height: int
:return: resolution east-west at north and south, and resolution north-south in meters for given CRS
:rtype: float, float
:raises: ValueError if CRS is not supported | [
"Calculates",
"pixel",
"resolution",
"in",
"meters",
"for",
"a",
"given",
"bbox",
"of",
"a",
"given",
"width",
"and",
"height",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L38-L54 |
243,007 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | get_image_dimension | def get_image_dimension(bbox, width=None, height=None):
""" Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image height or None if height is unknown
:type height: int or None
:return: width or height rounded to integer
:rtype: int
"""
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
if isinstance(width, int):
return round(width * abs(north2 - north1) / abs(east2 - east1))
return round(height * abs(east2 - east1) / abs(north2 - north1)) | python | def get_image_dimension(bbox, width=None, height=None):
utm_bbox = to_utm_bbox(bbox)
east1, north1 = utm_bbox.lower_left
east2, north2 = utm_bbox.upper_right
if isinstance(width, int):
return round(width * abs(north2 - north1) / abs(east2 - east1))
return round(height * abs(east2 - east1) / abs(north2 - north1)) | [
"def",
"get_image_dimension",
"(",
"bbox",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"utm_bbox",
"=",
"to_utm_bbox",
"(",
"bbox",
")",
"east1",
",",
"north1",
"=",
"utm_bbox",
".",
"lower_left",
"east2",
",",
"north2",
"=",
"utm_bb... | Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image height or None if height is unknown
:type height: int or None
:return: width or height rounded to integer
:rtype: int | [
"Given",
"bounding",
"box",
"and",
"one",
"of",
"the",
"parameters",
"width",
"or",
"height",
"it",
"will",
"return",
"the",
"other",
"parameter",
"that",
"will",
"best",
"fit",
"the",
"bounding",
"box",
"dimensions"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L57-L75 |
243,008 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | to_utm_bbox | def to_utm_bbox(bbox):
""" Transform bbox into UTM CRS
:param bbox: bounding box
:type bbox: geometry.BBox
:return: bounding box in UTM CRS
:rtype: geometry.BBox
"""
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | python | def to_utm_bbox(bbox):
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | [
"def",
"to_utm_bbox",
"(",
"bbox",
")",
":",
"if",
"CRS",
".",
"is_utm",
"(",
"bbox",
".",
"crs",
")",
":",
"return",
"bbox",
"lng",
",",
"lat",
"=",
"bbox",
".",
"middle",
"utm_crs",
"=",
"get_utm_crs",
"(",
"lng",
",",
"lat",
",",
"source_crs",
"... | Transform bbox into UTM CRS
:param bbox: bounding box
:type bbox: geometry.BBox
:return: bounding box in UTM CRS
:rtype: geometry.BBox | [
"Transform",
"bbox",
"into",
"UTM",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L78-L90 |
243,009 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | get_utm_bbox | def get_utm_bbox(img_bbox, transform):
""" Get UTM coordinates given a bounding box in pixels and a transform
:param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]`
:type img_bbox: list
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: UTM coordinates as [east1, north1, east2, north2]
:rtype: list
"""
east1, north1 = pixel_to_utm(img_bbox[0], img_bbox[1], transform)
east2, north2 = pixel_to_utm(img_bbox[2], img_bbox[3], transform)
return [east1, north1, east2, north2] | python | def get_utm_bbox(img_bbox, transform):
east1, north1 = pixel_to_utm(img_bbox[0], img_bbox[1], transform)
east2, north2 = pixel_to_utm(img_bbox[2], img_bbox[3], transform)
return [east1, north1, east2, north2] | [
"def",
"get_utm_bbox",
"(",
"img_bbox",
",",
"transform",
")",
":",
"east1",
",",
"north1",
"=",
"pixel_to_utm",
"(",
"img_bbox",
"[",
"0",
"]",
",",
"img_bbox",
"[",
"1",
"]",
",",
"transform",
")",
"east2",
",",
"north2",
"=",
"pixel_to_utm",
"(",
"i... | Get UTM coordinates given a bounding box in pixels and a transform
:param img_bbox: boundaries of bounding box in pixels as `[row1, col1, row2, col2]`
:type img_bbox: list
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: UTM coordinates as [east1, north1, east2, north2]
:rtype: list | [
"Get",
"UTM",
"coordinates",
"given",
"a",
"bounding",
"box",
"in",
"pixels",
"and",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L93-L105 |
243,010 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | wgs84_to_utm | def wgs84_to_utm(lng, lat, utm_crs=None):
""" Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS or None
:return: east, north coordinates in UTM system
:rtype: float, float
"""
if utm_crs is None:
utm_crs = get_utm_crs(lng, lat)
return transform_point((lng, lat), CRS.WGS84, utm_crs) | python | def wgs84_to_utm(lng, lat, utm_crs=None):
if utm_crs is None:
utm_crs = get_utm_crs(lng, lat)
return transform_point((lng, lat), CRS.WGS84, utm_crs) | [
"def",
"wgs84_to_utm",
"(",
"lng",
",",
"lat",
",",
"utm_crs",
"=",
"None",
")",
":",
"if",
"utm_crs",
"is",
"None",
":",
"utm_crs",
"=",
"get_utm_crs",
"(",
"lng",
",",
"lat",
")",
"return",
"transform_point",
"(",
"(",
"lng",
",",
"lat",
")",
",",
... | Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically.
:param lng: longitude in WGS84 system
:type lng: float
:param lat: latitude in WGS84 system
:type lat: float
:param utm_crs: UTM coordinate reference system enum constants
:type utm_crs: constants.CRS or None
:return: east, north coordinates in UTM system
:rtype: float, float | [
"Convert",
"WGS84",
"coordinates",
"to",
"UTM",
".",
"If",
"UTM",
"CRS",
"is",
"not",
"set",
"it",
"will",
"be",
"calculated",
"automatically",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L108-L122 |
243,011 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | utm_to_pixel | def utm_to_pixel(east, north, transform, truncate=True):
""" Convert UTM coordinate to image coordinate given a transform
:param east: east coordinate of point
:type east: float
:param north: north coordinate of point
:type north: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
column = (east - transform[0]) / transform[1]
row = (north - transform[3]) / transform[5]
if truncate:
return int(row + ERR), int(column + ERR)
return row, column | python | def utm_to_pixel(east, north, transform, truncate=True):
column = (east - transform[0]) / transform[1]
row = (north - transform[3]) / transform[5]
if truncate:
return int(row + ERR), int(column + ERR)
return row, column | [
"def",
"utm_to_pixel",
"(",
"east",
",",
"north",
",",
"transform",
",",
"truncate",
"=",
"True",
")",
":",
"column",
"=",
"(",
"east",
"-",
"transform",
"[",
"0",
"]",
")",
"/",
"transform",
"[",
"1",
"]",
"row",
"=",
"(",
"north",
"-",
"transform... | Convert UTM coordinate to image coordinate given a transform
:param east: east coordinate of point
:type east: float
:param north: north coordinate of point
:type north: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int | [
"Convert",
"UTM",
"coordinate",
"to",
"image",
"coordinate",
"given",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L140-L158 |
243,012 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | pixel_to_utm | def pixel_to_utm(row, column, transform):
""" Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: east, north UTM coordinates
:rtype: float, float
"""
east = transform[0] + column * transform[1]
north = transform[3] + row * transform[5]
return east, north | python | def pixel_to_utm(row, column, transform):
east = transform[0] + column * transform[1]
north = transform[3] + row * transform[5]
return east, north | [
"def",
"pixel_to_utm",
"(",
"row",
",",
"column",
",",
"transform",
")",
":",
"east",
"=",
"transform",
"[",
"0",
"]",
"+",
"column",
"*",
"transform",
"[",
"1",
"]",
"north",
"=",
"transform",
"[",
"3",
"]",
"+",
"row",
"*",
"transform",
"[",
"5",... | Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:return: east, north UTM coordinates
:rtype: float, float | [
"Convert",
"pixel",
"coordinate",
"to",
"UTM",
"coordinate",
"given",
"a",
"transform"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L161-L175 |
243,013 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | wgs84_to_pixel | def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True):
""" Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be
calculated it automatically.
:param lng: longitude of point
:type lng: float
:param lat: latitude of point
:type lat: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param utm_epsg: UTM coordinate reference system enum constants
:type utm_epsg: constants.CRS or None
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int
"""
east, north = wgs84_to_utm(lng, lat, utm_epsg)
row, column = utm_to_pixel(east, north, transform, truncate=truncate)
return row, column | python | def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True):
east, north = wgs84_to_utm(lng, lat, utm_epsg)
row, column = utm_to_pixel(east, north, transform, truncate=truncate)
return row, column | [
"def",
"wgs84_to_pixel",
"(",
"lng",
",",
"lat",
",",
"transform",
",",
"utm_epsg",
"=",
"None",
",",
"truncate",
"=",
"True",
")",
":",
"east",
",",
"north",
"=",
"wgs84_to_utm",
"(",
"lng",
",",
"lat",
",",
"utm_epsg",
")",
"row",
",",
"column",
"=... | Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be
calculated it automatically.
:param lng: longitude of point
:type lng: float
:param lat: latitude of point
:type lat: float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
:type transform: tuple or list
:param utm_epsg: UTM coordinate reference system enum constants
:type utm_epsg: constants.CRS or None
:param truncate: Whether to truncate pixel coordinates. Default is ``True``
:type truncate: bool
:return: row and column pixel image coordinates
:rtype: float, float or int, int | [
"Convert",
"WGS84",
"coordinates",
"to",
"pixel",
"image",
"coordinates",
"given",
"transform",
"and",
"UTM",
"CRS",
".",
"If",
"no",
"CRS",
"is",
"given",
"it",
"will",
"be",
"calculated",
"it",
"automatically",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L178-L197 |
243,014 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | transform_point | def transform_point(point, source_crs, target_crs):
""" Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: point in target CRS
:rtype: (float, float)
"""
if source_crs == target_crs:
return point
old_x, old_y = point
new_x, new_y = pyproj.transform(CRS.projection(source_crs), CRS.projection(target_crs), old_x, old_y)
return new_x, new_y | python | def transform_point(point, source_crs, target_crs):
if source_crs == target_crs:
return point
old_x, old_y = point
new_x, new_y = pyproj.transform(CRS.projection(source_crs), CRS.projection(target_crs), old_x, old_y)
return new_x, new_y | [
"def",
"transform_point",
"(",
"point",
",",
"source_crs",
",",
"target_crs",
")",
":",
"if",
"source_crs",
"==",
"target_crs",
":",
"return",
"point",
"old_x",
",",
"old_y",
"=",
"point",
"new_x",
",",
"new_y",
"=",
"pyproj",
".",
"transform",
"(",
"CRS",... | Maps point form src_crs to tgt_crs
:param point: a tuple `(x, y)`
:type point: (float, float)
:param source_crs: source CRS
:type source_crs: constants.CRS
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: point in target CRS
:rtype: (float, float) | [
"Maps",
"point",
"form",
"src_crs",
"to",
"tgt_crs"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L217-L233 |
243,015 | sentinel-hub/sentinelhub-py | sentinelhub/geo_utils.py | transform_bbox | def transform_bbox(bbox, target_crs):
""" Maps bbox from current crs to target_crs
:param bbox: bounding box
:type bbox: geometry.BBox
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: bounding box in target CRS
:rtype: geometry.BBox
"""
warnings.warn("This function is deprecated, use BBox.transform method instead", DeprecationWarning, stacklevel=2)
return bbox.transform(target_crs) | python | def transform_bbox(bbox, target_crs):
warnings.warn("This function is deprecated, use BBox.transform method instead", DeprecationWarning, stacklevel=2)
return bbox.transform(target_crs) | [
"def",
"transform_bbox",
"(",
"bbox",
",",
"target_crs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is deprecated, use BBox.transform method instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"bbox",
".",
"transform",
"(",... | Maps bbox from current crs to target_crs
:param bbox: bounding box
:type bbox: geometry.BBox
:param target_crs: target CRS
:type target_crs: constants.CRS
:return: bounding box in target CRS
:rtype: geometry.BBox | [
"Maps",
"bbox",
"from",
"current",
"crs",
"to",
"target_crs"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geo_utils.py#L236-L248 |
243,016 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | get_safe_format | def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C):
"""
Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified.
:param product_id: original ESA product identification string. Default is ``None``
:type product_id: str
:param tile: tuple containing tile name and sensing time/date. Default is ``None``
:type tile: (str, str)
:param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure
of the product. Default is ``False``
:type entire_product: bool
:param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None``
:type bands: list(str) or None
:param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2
L1C data.
:type data_source: constants.DataSource
:return: Nested dictionaries representing .SAFE structure.
:rtype: dict
"""
entire_product = entire_product and product_id is None
if tile is not None:
safe_tile = SafeTile(tile_name=tile[0], time=tile[1], bands=bands, data_source=data_source)
if not entire_product:
return safe_tile.get_safe_struct()
product_id = safe_tile.get_product_id()
if product_id is None:
raise ValueError('Either product_id or tile must be specified')
safe_product = SafeProduct(product_id, tile_list=[tile[0]], bands=bands) if entire_product else \
SafeProduct(product_id, bands=bands)
return safe_product.get_safe_struct() | python | def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C):
entire_product = entire_product and product_id is None
if tile is not None:
safe_tile = SafeTile(tile_name=tile[0], time=tile[1], bands=bands, data_source=data_source)
if not entire_product:
return safe_tile.get_safe_struct()
product_id = safe_tile.get_product_id()
if product_id is None:
raise ValueError('Either product_id or tile must be specified')
safe_product = SafeProduct(product_id, tile_list=[tile[0]], bands=bands) if entire_product else \
SafeProduct(product_id, bands=bands)
return safe_product.get_safe_struct() | [
"def",
"get_safe_format",
"(",
"product_id",
"=",
"None",
",",
"tile",
"=",
"None",
",",
"entire_product",
"=",
"False",
",",
"bands",
"=",
"None",
",",
"data_source",
"=",
"DataSource",
".",
"SENTINEL2_L1C",
")",
":",
"entire_product",
"=",
"entire_product",
... | Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified.
:param product_id: original ESA product identification string. Default is ``None``
:type product_id: str
:param tile: tuple containing tile name and sensing time/date. Default is ``None``
:type tile: (str, str)
:param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure
of the product. Default is ``False``
:type entire_product: bool
:param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None``
:type bands: list(str) or None
:param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2
L1C data.
:type data_source: constants.DataSource
:return: Nested dictionaries representing .SAFE structure.
:rtype: dict | [
"Returns",
".",
"SAFE",
"format",
"structure",
"in",
"form",
"of",
"nested",
"dictionaries",
".",
"Either",
"product_id",
"or",
"tile",
"must",
"be",
"specified",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L862-L891 |
243,017 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | download_safe_format | def download_safe_format(product_id=None, tile=None, folder='.', redownload=False, entire_product=False, bands=None,
data_source=DataSource.SENTINEL2_L1C):
"""
Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must
be specified.
:param product_id: original ESA product identification string. Default is ``None``
:type product_id: str
:param tile: tuple containing tile name and sensing time/date. Default is ``None``
:type tile: (str, str)
:param folder: location of the directory where the fetched data will be saved. Default is ``'.'``
:type folder: str
:param redownload: if ``True``, download again the requested data even though it's already saved to disk. If
``False``, do not download if data is already available on disk. Default is ``False``
:type redownload: bool
:param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure
of the product. Default is ``False``
:type entire_product: bool
:param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None``
:type bands: list(str) or None
:param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2
L1C data.
:type data_source: constants.DataSource
:return: Nested dictionaries representing .SAFE structure.
:rtype: dict
"""
entire_product = entire_product and product_id is None
if tile is not None:
safe_request = AwsTileRequest(tile=tile[0], time=tile[1], data_folder=folder, bands=bands,
safe_format=True, data_source=data_source)
if entire_product:
safe_tile = safe_request.get_aws_service()
product_id = safe_tile.get_product_id()
if product_id is not None:
safe_request = AwsProductRequest(product_id, tile_list=[tile[0]], data_folder=folder, bands=bands,
safe_format=True) if entire_product else \
AwsProductRequest(product_id, data_folder=folder, bands=bands, safe_format=True)
safe_request.save_data(redownload=redownload) | python | def download_safe_format(product_id=None, tile=None, folder='.', redownload=False, entire_product=False, bands=None,
data_source=DataSource.SENTINEL2_L1C):
entire_product = entire_product and product_id is None
if tile is not None:
safe_request = AwsTileRequest(tile=tile[0], time=tile[1], data_folder=folder, bands=bands,
safe_format=True, data_source=data_source)
if entire_product:
safe_tile = safe_request.get_aws_service()
product_id = safe_tile.get_product_id()
if product_id is not None:
safe_request = AwsProductRequest(product_id, tile_list=[tile[0]], data_folder=folder, bands=bands,
safe_format=True) if entire_product else \
AwsProductRequest(product_id, data_folder=folder, bands=bands, safe_format=True)
safe_request.save_data(redownload=redownload) | [
"def",
"download_safe_format",
"(",
"product_id",
"=",
"None",
",",
"tile",
"=",
"None",
",",
"folder",
"=",
"'.'",
",",
"redownload",
"=",
"False",
",",
"entire_product",
"=",
"False",
",",
"bands",
"=",
"None",
",",
"data_source",
"=",
"DataSource",
".",... | Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must
be specified.
:param product_id: original ESA product identification string. Default is ``None``
:type product_id: str
:param tile: tuple containing tile name and sensing time/date. Default is ``None``
:type tile: (str, str)
:param folder: location of the directory where the fetched data will be saved. Default is ``'.'``
:type folder: str
:param redownload: if ``True``, download again the requested data even though it's already saved to disk. If
``False``, do not download if data is already available on disk. Default is ``False``
:type redownload: bool
:param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure
of the product. Default is ``False``
:type entire_product: bool
:param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None``
:type bands: list(str) or None
:param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2
L1C data.
:type data_source: constants.DataSource
:return: Nested dictionaries representing .SAFE structure.
:rtype: dict | [
"Downloads",
".",
"SAFE",
"format",
"structure",
"in",
"form",
"of",
"nested",
"dictionaries",
".",
"Either",
"product_id",
"or",
"tile",
"must",
"be",
"specified",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L894-L932 |
243,018 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | DataRequest.save_data | def save_data(self, *, data_filter=None, redownload=False, max_threads=None, raise_download_errors=False):
"""
Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers.
:param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with
`data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``.
:type data_filter: list(int) or None
:param redownload: data is redownloaded if ``redownload=True``. Default is ``False``
:type redownload: bool
:param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which
by default uses the number of processors on the system
:type max_threads: int
:param raise_download_errors: If ``True`` any error in download process should be raised as
``DownloadFailedException``. If ``False`` failed downloads will only raise warnings.
:type raise_download_errors: bool
"""
self._preprocess_request(True, False)
self._execute_data_download(data_filter, redownload, max_threads, raise_download_errors) | python | def save_data(self, *, data_filter=None, redownload=False, max_threads=None, raise_download_errors=False):
self._preprocess_request(True, False)
self._execute_data_download(data_filter, redownload, max_threads, raise_download_errors) | [
"def",
"save_data",
"(",
"self",
",",
"*",
",",
"data_filter",
"=",
"None",
",",
"redownload",
"=",
"False",
",",
"max_threads",
"=",
"None",
",",
"raise_download_errors",
"=",
"False",
")",
":",
"self",
".",
"_preprocess_request",
"(",
"True",
",",
"False... | Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers.
:param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with
`data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``.
:type data_filter: list(int) or None
:param redownload: data is redownloaded if ``redownload=True``. Default is ``False``
:type redownload: bool
:param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which
by default uses the number of processors on the system
:type max_threads: int
:param raise_download_errors: If ``True`` any error in download process should be raised as
``DownloadFailedException``. If ``False`` failed downloads will only raise warnings.
:type raise_download_errors: bool | [
"Saves",
"data",
"to",
"disk",
".",
"If",
"redownload",
"=",
"True",
"then",
"the",
"data",
"is",
"redownloaded",
"using",
"max_threads",
"workers",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L113-L130 |
243,019 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | DataRequest._execute_data_download | def _execute_data_download(self, data_filter, redownload, max_threads, raise_download_errors):
"""Calls download module and executes the download process
:param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with
`data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``.
:type data_filter: list(int) or None
:param redownload: data is redownloaded if ``redownload=True``. Default is ``False``
:type redownload: bool
:param max_threads: the number of workers to use when downloading, default ``max_threads=None``
:type max_threads: int
:param raise_download_errors: If ``True`` any error in download process should be raised as
``DownloadFailedException``. If ``False`` failed downloads will only raise warnings.
:type raise_download_errors: bool
:return: List of data obtained from download
:rtype: list
"""
is_repeating_filter = False
if data_filter is None:
filtered_download_list = self.download_list
elif isinstance(data_filter, (list, tuple)):
try:
filtered_download_list = [self.download_list[index] for index in data_filter]
except IndexError:
raise IndexError('Indices of data_filter are out of range')
filtered_download_list, mapping_list = self._filter_repeating_items(filtered_download_list)
is_repeating_filter = len(filtered_download_list) < len(mapping_list)
else:
raise ValueError('data_filter parameter must be a list of indices')
data_list = []
for future in download_data(filtered_download_list, redownload=redownload, max_threads=max_threads):
try:
data_list.append(future.result(timeout=SHConfig().download_timeout_seconds))
except ImageDecodingError as err:
data_list.append(None)
LOGGER.debug('%s while downloading data; will try to load it from disk if it was saved', err)
except DownloadFailedException as download_exception:
if raise_download_errors:
raise download_exception
warnings.warn(str(download_exception))
data_list.append(None)
if is_repeating_filter:
data_list = [copy.deepcopy(data_list[index]) for index in mapping_list]
return data_list | python | def _execute_data_download(self, data_filter, redownload, max_threads, raise_download_errors):
is_repeating_filter = False
if data_filter is None:
filtered_download_list = self.download_list
elif isinstance(data_filter, (list, tuple)):
try:
filtered_download_list = [self.download_list[index] for index in data_filter]
except IndexError:
raise IndexError('Indices of data_filter are out of range')
filtered_download_list, mapping_list = self._filter_repeating_items(filtered_download_list)
is_repeating_filter = len(filtered_download_list) < len(mapping_list)
else:
raise ValueError('data_filter parameter must be a list of indices')
data_list = []
for future in download_data(filtered_download_list, redownload=redownload, max_threads=max_threads):
try:
data_list.append(future.result(timeout=SHConfig().download_timeout_seconds))
except ImageDecodingError as err:
data_list.append(None)
LOGGER.debug('%s while downloading data; will try to load it from disk if it was saved', err)
except DownloadFailedException as download_exception:
if raise_download_errors:
raise download_exception
warnings.warn(str(download_exception))
data_list.append(None)
if is_repeating_filter:
data_list = [copy.deepcopy(data_list[index]) for index in mapping_list]
return data_list | [
"def",
"_execute_data_download",
"(",
"self",
",",
"data_filter",
",",
"redownload",
",",
"max_threads",
",",
"raise_download_errors",
")",
":",
"is_repeating_filter",
"=",
"False",
"if",
"data_filter",
"is",
"None",
":",
"filtered_download_list",
"=",
"self",
".",
... | Calls download module and executes the download process
:param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with
`data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``.
:type data_filter: list(int) or None
:param redownload: data is redownloaded if ``redownload=True``. Default is ``False``
:type redownload: bool
:param max_threads: the number of workers to use when downloading, default ``max_threads=None``
:type max_threads: int
:param raise_download_errors: If ``True`` any error in download process should be raised as
``DownloadFailedException``. If ``False`` failed downloads will only raise warnings.
:type raise_download_errors: bool
:return: List of data obtained from download
:rtype: list | [
"Calls",
"download",
"module",
"and",
"executes",
"the",
"download",
"process"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L132-L178 |
243,020 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | DataRequest._filter_repeating_items | def _filter_repeating_items(download_list):
""" Because of data_filter some requests in download list might be the same. In order not to download them again
this method will reduce the list of requests. It will also return a mapping list which can be used to
reconstruct the previous list of download requests.
:param download_list: List of download requests
:type download_list: list(sentinelhub.DownloadRequest)
:return: reduced download list with unique requests and mapping list
:rtype: (list(sentinelhub.DownloadRequest), list(int))
"""
unique_requests_map = {}
mapping_list = []
unique_download_list = []
for download_request in download_list:
if download_request not in unique_requests_map:
unique_requests_map[download_request] = len(unique_download_list)
unique_download_list.append(download_request)
mapping_list.append(unique_requests_map[download_request])
return unique_download_list, mapping_list | python | def _filter_repeating_items(download_list):
unique_requests_map = {}
mapping_list = []
unique_download_list = []
for download_request in download_list:
if download_request not in unique_requests_map:
unique_requests_map[download_request] = len(unique_download_list)
unique_download_list.append(download_request)
mapping_list.append(unique_requests_map[download_request])
return unique_download_list, mapping_list | [
"def",
"_filter_repeating_items",
"(",
"download_list",
")",
":",
"unique_requests_map",
"=",
"{",
"}",
"mapping_list",
"=",
"[",
"]",
"unique_download_list",
"=",
"[",
"]",
"for",
"download_request",
"in",
"download_list",
":",
"if",
"download_request",
"not",
"i... | Because of data_filter some requests in download list might be the same. In order not to download them again
this method will reduce the list of requests. It will also return a mapping list which can be used to
reconstruct the previous list of download requests.
:param download_list: List of download requests
:type download_list: list(sentinelhub.DownloadRequest)
:return: reduced download list with unique requests and mapping list
:rtype: (list(sentinelhub.DownloadRequest), list(int)) | [
"Because",
"of",
"data_filter",
"some",
"requests",
"in",
"download",
"list",
"might",
"be",
"the",
"same",
".",
"In",
"order",
"not",
"to",
"download",
"them",
"again",
"this",
"method",
"will",
"reduce",
"the",
"list",
"of",
"requests",
".",
"It",
"will"... | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L181-L199 |
243,021 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | DataRequest._preprocess_request | def _preprocess_request(self, save_data, return_data):
"""
Prepares requests for download and creates empty folders
:param save_data: Tells whether to save data or not
:type: bool
:param return_data: Tells whether to return data or not
:type: bool
"""
if not self.is_valid_request():
raise ValueError('Cannot obtain data because request is invalid')
if save_data and self.data_folder is None:
raise ValueError('Request parameter `data_folder` is not specified. '
'In order to save data please set `data_folder` to location on your disk.')
for download_request in self.download_list:
download_request.set_save_response(save_data)
download_request.set_return_data(return_data)
download_request.set_data_folder(self.data_folder)
if save_data:
for folder in self.folder_list:
make_folder(os.path.join(self.data_folder, folder)) | python | def _preprocess_request(self, save_data, return_data):
if not self.is_valid_request():
raise ValueError('Cannot obtain data because request is invalid')
if save_data and self.data_folder is None:
raise ValueError('Request parameter `data_folder` is not specified. '
'In order to save data please set `data_folder` to location on your disk.')
for download_request in self.download_list:
download_request.set_save_response(save_data)
download_request.set_return_data(return_data)
download_request.set_data_folder(self.data_folder)
if save_data:
for folder in self.folder_list:
make_folder(os.path.join(self.data_folder, folder)) | [
"def",
"_preprocess_request",
"(",
"self",
",",
"save_data",
",",
"return_data",
")",
":",
"if",
"not",
"self",
".",
"is_valid_request",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot obtain data because request is invalid'",
")",
"if",
"save_data",
"and",
"s... | Prepares requests for download and creates empty folders
:param save_data: Tells whether to save data or not
:type: bool
:param return_data: Tells whether to return data or not
:type: bool | [
"Prepares",
"requests",
"for",
"download",
"and",
"creates",
"empty",
"folders"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L201-L224 |
243,022 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | DataRequest._add_saved_data | def _add_saved_data(self, data_list, data_filter, raise_download_errors):
"""
Adds already saved data that was not redownloaded to the requested data list.
"""
filtered_download_list = self.download_list if data_filter is None else \
[self.download_list[index] for index in data_filter]
for i, request in enumerate(filtered_download_list):
if request.return_data and data_list[i] is None:
if os.path.exists(request.get_file_path()):
data_list[i] = read_data(request.get_file_path())
elif raise_download_errors:
raise DownloadFailedException('Failed to download data from {}.\n No previously downloaded data '
'exists in file {}.'.format(request.url, request.get_file_path()))
return data_list | python | def _add_saved_data(self, data_list, data_filter, raise_download_errors):
filtered_download_list = self.download_list if data_filter is None else \
[self.download_list[index] for index in data_filter]
for i, request in enumerate(filtered_download_list):
if request.return_data and data_list[i] is None:
if os.path.exists(request.get_file_path()):
data_list[i] = read_data(request.get_file_path())
elif raise_download_errors:
raise DownloadFailedException('Failed to download data from {}.\n No previously downloaded data '
'exists in file {}.'.format(request.url, request.get_file_path()))
return data_list | [
"def",
"_add_saved_data",
"(",
"self",
",",
"data_list",
",",
"data_filter",
",",
"raise_download_errors",
")",
":",
"filtered_download_list",
"=",
"self",
".",
"download_list",
"if",
"data_filter",
"is",
"None",
"else",
"[",
"self",
".",
"download_list",
"[",
"... | Adds already saved data that was not redownloaded to the requested data list. | [
"Adds",
"already",
"saved",
"data",
"that",
"was",
"not",
"redownloaded",
"to",
"the",
"requested",
"data",
"list",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L226-L239 |
243,023 | sentinel-hub/sentinelhub-py | sentinelhub/data_request.py | GeopediaImageRequest.create_request | def create_request(self, reset_gpd_iterator=False):
"""Set a list of download requests
Set a list of DownloadRequests for all images that are under the
given property of the Geopedia's Vector layer.
:param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator``
(i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to
repeat a service call but tiles and dates will stay the same.
:type reset_gpd_iterator: bool
"""
if reset_gpd_iterator:
self.gpd_iterator = None
gpd_service = GeopediaImageService()
self.download_list = gpd_service.get_request(self)
self.gpd_iterator = gpd_service.get_gpd_iterator() | python | def create_request(self, reset_gpd_iterator=False):
if reset_gpd_iterator:
self.gpd_iterator = None
gpd_service = GeopediaImageService()
self.download_list = gpd_service.get_request(self)
self.gpd_iterator = gpd_service.get_gpd_iterator() | [
"def",
"create_request",
"(",
"self",
",",
"reset_gpd_iterator",
"=",
"False",
")",
":",
"if",
"reset_gpd_iterator",
":",
"self",
".",
"gpd_iterator",
"=",
"None",
"gpd_service",
"=",
"GeopediaImageService",
"(",
")",
"self",
".",
"download_list",
"=",
"gpd_serv... | Set a list of download requests
Set a list of DownloadRequests for all images that are under the
given property of the Geopedia's Vector layer.
:param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator``
(i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to
repeat a service call but tiles and dates will stay the same.
:type reset_gpd_iterator: bool | [
"Set",
"a",
"list",
"of",
"download",
"requests"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L707-L723 |
243,024 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaSession.provide_session | def provide_session(self, start_new=False):
""" Makes sure that session is still valid and provides session info
:param start_new: If `True` it will always create a new session. Otherwise it will create a new
session only if no session exists or the previous session timed out.
:type start_new: bool
:return: Current session info
:rtype: dict
"""
if self.is_global:
self._session_info = self._global_session_info
self._session_start = self._global_session_start
if self._session_info is None or start_new or \
datetime.datetime.now() > self._session_start + self.SESSION_DURATION:
self._start_new_session()
return self._session_info | python | def provide_session(self, start_new=False):
if self.is_global:
self._session_info = self._global_session_info
self._session_start = self._global_session_start
if self._session_info is None or start_new or \
datetime.datetime.now() > self._session_start + self.SESSION_DURATION:
self._start_new_session()
return self._session_info | [
"def",
"provide_session",
"(",
"self",
",",
"start_new",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_global",
":",
"self",
".",
"_session_info",
"=",
"self",
".",
"_global_session_info",
"self",
".",
"_session_start",
"=",
"self",
".",
"_global_session_star... | Makes sure that session is still valid and provides session info
:param start_new: If `True` it will always create a new session. Otherwise it will create a new
session only if no session exists or the previous session timed out.
:type start_new: bool
:return: Current session info
:rtype: dict | [
"Makes",
"sure",
"that",
"session",
"is",
"still",
"valid",
"and",
"provides",
"session",
"info"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L153-L170 |
243,025 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaSession._start_new_session | def _start_new_session(self):
""" Starts a new session and calculates when the new session will end. If username and password are provided
it will also make login.
"""
self._session_start = datetime.datetime.now()
session_id = self._parse_session_id(self._session_info) if self._session_info else ''
session_url = '{}data/v1/session/create?locale=en&sid={}'.format(self.base_url, session_id)
self._session_info = get_json(session_url)
if self.username and self.password and self._parse_user_id(self._session_info) == self.UNAUTHENTICATED_USER_ID:
self._make_login()
if self.is_global:
GeopediaSession._global_session_info = self._session_info
GeopediaSession._global_session_start = self._session_start | python | def _start_new_session(self):
self._session_start = datetime.datetime.now()
session_id = self._parse_session_id(self._session_info) if self._session_info else ''
session_url = '{}data/v1/session/create?locale=en&sid={}'.format(self.base_url, session_id)
self._session_info = get_json(session_url)
if self.username and self.password and self._parse_user_id(self._session_info) == self.UNAUTHENTICATED_USER_ID:
self._make_login()
if self.is_global:
GeopediaSession._global_session_info = self._session_info
GeopediaSession._global_session_start = self._session_start | [
"def",
"_start_new_session",
"(",
"self",
")",
":",
"self",
".",
"_session_start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"session_id",
"=",
"self",
".",
"_parse_session_id",
"(",
"self",
".",
"_session_info",
")",
"if",
"self",
".",
"_ses... | Starts a new session and calculates when the new session will end. If username and password are provided
it will also make login. | [
"Starts",
"a",
"new",
"session",
"and",
"calculates",
"when",
"the",
"new",
"session",
"will",
"end",
".",
"If",
"username",
"and",
"password",
"are",
"provided",
"it",
"will",
"also",
"make",
"login",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L172-L187 |
243,026 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaSession._make_login | def _make_login(self):
""" Private method that makes login
"""
login_url = '{}data/v1/session/login?user={}&pass={}&sid={}'.format(self.base_url, self.username, self.password,
self._parse_session_id(self._session_info))
self._session_info = get_json(login_url) | python | def _make_login(self):
login_url = '{}data/v1/session/login?user={}&pass={}&sid={}'.format(self.base_url, self.username, self.password,
self._parse_session_id(self._session_info))
self._session_info = get_json(login_url) | [
"def",
"_make_login",
"(",
"self",
")",
":",
"login_url",
"=",
"'{}data/v1/session/login?user={}&pass={}&sid={}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
",",
"self",
".",
"_parse_session_id",
"("... | Private method that makes login | [
"Private",
"method",
"that",
"makes",
"login"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L189-L194 |
243,027 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaImageService._get_items | def _get_items(self, request):
""" Collects data from Geopedia layer and returns list of features
"""
if request.gpd_iterator is None:
self.gpd_iterator = GeopediaFeatureIterator(request.layer, bbox=request.bbox, base_url=self.base_url,
gpd_session=request.gpd_session)
else:
self.gpd_iterator = request.gpd_iterator
field_iter = self.gpd_iterator.get_field_iterator(request.image_field_name)
items = []
for field_items in field_iter: # an image field can have multiple images
for item in field_items:
if not item['mimeType'].startswith('image/'):
continue
mime_type = MimeType.from_string(item['mimeType'][6:])
if mime_type is request.image_format:
items.append(item)
return items | python | def _get_items(self, request):
if request.gpd_iterator is None:
self.gpd_iterator = GeopediaFeatureIterator(request.layer, bbox=request.bbox, base_url=self.base_url,
gpd_session=request.gpd_session)
else:
self.gpd_iterator = request.gpd_iterator
field_iter = self.gpd_iterator.get_field_iterator(request.image_field_name)
items = []
for field_items in field_iter: # an image field can have multiple images
for item in field_items:
if not item['mimeType'].startswith('image/'):
continue
mime_type = MimeType.from_string(item['mimeType'][6:])
if mime_type is request.image_format:
items.append(item)
return items | [
"def",
"_get_items",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"gpd_iterator",
"is",
"None",
":",
"self",
".",
"gpd_iterator",
"=",
"GeopediaFeatureIterator",
"(",
"request",
".",
"layer",
",",
"bbox",
"=",
"request",
".",
"bbox",
",",
... | Collects data from Geopedia layer and returns list of features | [
"Collects",
"data",
"from",
"Geopedia",
"layer",
"and",
"returns",
"list",
"of",
"features"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L269-L292 |
243,028 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaImageService._get_filename | def _get_filename(request, item):
""" Creates a filename
"""
if request.keep_image_names:
filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))
else:
filename = OgcImageService.finalize_filename(
'_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]),
request.image_format
)
LOGGER.debug("filename=%s", filename)
return filename | python | def _get_filename(request, item):
if request.keep_image_names:
filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))
else:
filename = OgcImageService.finalize_filename(
'_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]),
request.image_format
)
LOGGER.debug("filename=%s", filename)
return filename | [
"def",
"_get_filename",
"(",
"request",
",",
"item",
")",
":",
"if",
"request",
".",
"keep_image_names",
":",
"filename",
"=",
"OgcImageService",
".",
"finalize_filename",
"(",
"item",
"[",
"'niceName'",
"]",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
")... | Creates a filename | [
"Creates",
"a",
"filename"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L299-L311 |
243,029 | sentinel-hub/sentinelhub-py | sentinelhub/geopedia.py | GeopediaFeatureIterator._fetch_features | def _fetch_features(self):
""" Retrieves a new page of features from Geopedia
"""
if self.next_page_url is None:
return
response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers)
self.features.extend(response['features'])
self.next_page_url = response['pagination']['next']
self.layer_size = response['pagination']['total'] | python | def _fetch_features(self):
if self.next_page_url is None:
return
response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers)
self.features.extend(response['features'])
self.next_page_url = response['pagination']['next']
self.layer_size = response['pagination']['total'] | [
"def",
"_fetch_features",
"(",
"self",
")",
":",
"if",
"self",
".",
"next_page_url",
"is",
"None",
":",
"return",
"response",
"=",
"get_json",
"(",
"self",
".",
"next_page_url",
",",
"post_values",
"=",
"self",
".",
"query",
",",
"headers",
"=",
"self",
... | Retrieves a new page of features from Geopedia | [
"Retrieves",
"a",
"new",
"page",
"of",
"features",
"from",
"Geopedia"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L388-L398 |
243,030 | sentinel-hub/sentinelhub-py | sentinelhub/os_utils.py | get_folder_list | def get_folder_list(folder='.'):
""" Get list of sub-folders contained in input folder
:param folder: input folder to list sub-folders. Default is ``'.'``
:type folder: str
:return: list of sub-folders
:rtype: list(str)
"""
dir_list = get_content_list(folder)
return [f for f in dir_list if not os.path.isfile(os.path.join(folder, f))] | python | def get_folder_list(folder='.'):
dir_list = get_content_list(folder)
return [f for f in dir_list if not os.path.isfile(os.path.join(folder, f))] | [
"def",
"get_folder_list",
"(",
"folder",
"=",
"'.'",
")",
":",
"dir_list",
"=",
"get_content_list",
"(",
"folder",
")",
"return",
"[",
"f",
"for",
"f",
"in",
"dir_list",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"joi... | Get list of sub-folders contained in input folder
:param folder: input folder to list sub-folders. Default is ``'.'``
:type folder: str
:return: list of sub-folders
:rtype: list(str) | [
"Get",
"list",
"of",
"sub",
"-",
"folders",
"contained",
"in",
"input",
"folder"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L21-L30 |
243,031 | sentinel-hub/sentinelhub-py | sentinelhub/os_utils.py | create_parent_folder | def create_parent_folder(filename):
""" Create parent folder for input filename recursively
:param filename: input filename
:type filename: str
:raises: error if folder cannot be created
"""
path = os.path.dirname(filename)
if path != '':
make_folder(path) | python | def create_parent_folder(filename):
path = os.path.dirname(filename)
if path != '':
make_folder(path) | [
"def",
"create_parent_folder",
"(",
"filename",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"path",
"!=",
"''",
":",
"make_folder",
"(",
"path",
")"
] | Create parent folder for input filename recursively
:param filename: input filename
:type filename: str
:raises: error if folder cannot be created | [
"Create",
"parent",
"folder",
"for",
"input",
"filename",
"recursively"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L45-L54 |
243,032 | sentinel-hub/sentinelhub-py | sentinelhub/os_utils.py | make_folder | def make_folder(path):
""" Create folder at input path recursively
Create a folder specified by input path if one
does not exist already
:param path: input path to folder to be created
:type path: str
:raises: os.error if folder cannot be created
"""
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise ValueError('Specified folder is not writable: %s'
'\nPlease check permissions or set a new valid folder.' % path) | python | def make_folder(path):
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise ValueError('Specified folder is not writable: %s'
'\nPlease check permissions or set a new valid folder.' % path) | [
"def",
"make_folder",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"exception",
":",
"if",
"exception",
".",
"errno",
"!... | Create folder at input path recursively
Create a folder specified by input path if one
does not exist already
:param path: input path to folder to be created
:type path: str
:raises: os.error if folder cannot be created | [
"Create",
"folder",
"at",
"input",
"path",
"recursively"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L57-L73 |
243,033 | sentinel-hub/sentinelhub-py | sentinelhub/os_utils.py | rename | def rename(old_path, new_path, edit_folders=True):
""" Rename files or folders
:param old_path: name of file or folder to rename
:param new_path: name of new file or folder
:param edit_folders: flag to allow recursive renaming of folders. Default is ``True``
:type old_path: str
:type new_path: str
:type edit_folders: bool
"""
if edit_folders:
os.renames(old_path, new_path)
else:
os.rename(old_path, new_path) | python | def rename(old_path, new_path, edit_folders=True):
if edit_folders:
os.renames(old_path, new_path)
else:
os.rename(old_path, new_path) | [
"def",
"rename",
"(",
"old_path",
",",
"new_path",
",",
"edit_folders",
"=",
"True",
")",
":",
"if",
"edit_folders",
":",
"os",
".",
"renames",
"(",
"old_path",
",",
"new_path",
")",
"else",
":",
"os",
".",
"rename",
"(",
"old_path",
",",
"new_path",
"... | Rename files or folders
:param old_path: name of file or folder to rename
:param new_path: name of new file or folder
:param edit_folders: flag to allow recursive renaming of folders. Default is ``True``
:type old_path: str
:type new_path: str
:type edit_folders: bool | [
"Rename",
"files",
"or",
"folders"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L76-L89 |
243,034 | sentinel-hub/sentinelhub-py | sentinelhub/os_utils.py | size | def size(pathname):
""" Returns size of a file or folder in Bytes
:param pathname: path to file or folder to be sized
:type pathname: str
:return: size of file or folder in Bytes
:rtype: int
:raises: os.error if file is not accessible
"""
if os.path.isfile(pathname):
return os.path.getsize(pathname)
return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)]) | python | def size(pathname):
if os.path.isfile(pathname):
return os.path.getsize(pathname)
return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)]) | [
"def",
"size",
"(",
"pathname",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pathname",
")",
":",
"return",
"os",
".",
"path",
".",
"getsize",
"(",
"pathname",
")",
"return",
"sum",
"(",
"[",
"size",
"(",
"'{}/{}'",
".",
"format",
"(",
... | Returns size of a file or folder in Bytes
:param pathname: path to file or folder to be sized
:type pathname: str
:return: size of file or folder in Bytes
:rtype: int
:raises: os.error if file is not accessible | [
"Returns",
"size",
"of",
"a",
"file",
"or",
"folder",
"in",
"Bytes"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L92-L103 |
243,035 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.middle | def middle(self):
""" Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float)
"""
return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2 | python | def middle(self):
return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2 | [
"def",
"middle",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
"+",
"self",
".",
"max_x",
")",
"/",
"2",
",",
"(",
"self",
".",
"min_y",
"+",
"self",
".",
"max_y",
")",
"/",
"2"
] | Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float) | [
"Returns",
"the",
"middle",
"point",
"of",
"the",
"bounding",
"box"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L206-L212 |
243,036 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.reverse | def reverse(self):
""" Returns a new BBox object where x and y coordinates are switched
:return: New BBox object with switched coordinates
:rtype: BBox
"""
return BBox((self.min_y, self.min_x, self.max_y, self.max_x), crs=self.crs) | python | def reverse(self):
return BBox((self.min_y, self.min_x, self.max_y, self.max_x), crs=self.crs) | [
"def",
"reverse",
"(",
"self",
")",
":",
"return",
"BBox",
"(",
"(",
"self",
".",
"min_y",
",",
"self",
".",
"min_x",
",",
"self",
".",
"max_y",
",",
"self",
".",
"max_x",
")",
",",
"crs",
"=",
"self",
".",
"crs",
")"
] | Returns a new BBox object where x and y coordinates are switched
:return: New BBox object with switched coordinates
:rtype: BBox | [
"Returns",
"a",
"new",
"BBox",
"object",
"where",
"x",
"and",
"y",
"coordinates",
"are",
"switched"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L222-L228 |
243,037 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.transform | def transform(self, crs):
""" Transforms BBox from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Bounding box in target CRS
:rtype: BBox
"""
new_crs = CRS(crs)
return BBox((transform_point(self.lower_left, self.crs, new_crs),
transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs) | python | def transform(self, crs):
new_crs = CRS(crs)
return BBox((transform_point(self.lower_left, self.crs, new_crs),
transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs) | [
"def",
"transform",
"(",
"self",
",",
"crs",
")",
":",
"new_crs",
"=",
"CRS",
"(",
"crs",
")",
"return",
"BBox",
"(",
"(",
"transform_point",
"(",
"self",
".",
"lower_left",
",",
"self",
".",
"crs",
",",
"new_crs",
")",
",",
"transform_point",
"(",
"... | Transforms BBox from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Bounding box in target CRS
:rtype: BBox | [
"Transforms",
"BBox",
"from",
"current",
"CRS",
"to",
"target",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L230-L240 |
243,038 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.get_polygon | def get_polygon(self, reverse=False):
""" Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first
point is the same as the last.
:param reverse: `True` if x and y coordinates should be switched and `False` otherwise
:type reverse: bool
:return: `((x_1, y_1), ... , (x_5, y_5))`
:rtype: tuple(tuple(float))
"""
bbox = self.reverse() if reverse else self
polygon = ((bbox.min_x, bbox.min_y),
(bbox.min_x, bbox.max_y),
(bbox.max_x, bbox.max_y),
(bbox.max_x, bbox.min_y),
(bbox.min_x, bbox.min_y))
return polygon | python | def get_polygon(self, reverse=False):
bbox = self.reverse() if reverse else self
polygon = ((bbox.min_x, bbox.min_y),
(bbox.min_x, bbox.max_y),
(bbox.max_x, bbox.max_y),
(bbox.max_x, bbox.min_y),
(bbox.min_x, bbox.min_y))
return polygon | [
"def",
"get_polygon",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"bbox",
"=",
"self",
".",
"reverse",
"(",
")",
"if",
"reverse",
"else",
"self",
"polygon",
"=",
"(",
"(",
"bbox",
".",
"min_x",
",",
"bbox",
".",
"min_y",
")",
",",
"(",
"... | Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first
point is the same as the last.
:param reverse: `True` if x and y coordinates should be switched and `False` otherwise
:type reverse: bool
:return: `((x_1, y_1), ... , (x_5, y_5))`
:rtype: tuple(tuple(float)) | [
"Returns",
"a",
"tuple",
"of",
"coordinates",
"of",
"5",
"points",
"describing",
"a",
"polygon",
".",
"Points",
"are",
"listed",
"in",
"clockwise",
"order",
"first",
"point",
"is",
"the",
"same",
"as",
"the",
"last",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L258-L273 |
243,039 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.get_partition | def get_partition(self, num_x=1, num_y=1):
""" Partitions bounding box into smaller bounding boxes of the same size.
:param num_x: Number of parts BBox will be horizontally divided into.
:type num_x: int
:param num_y: Number of parts BBox will be vertically divided into.
:type num_y: int or None
:return: Two-dimensional list of smaller bounding boxes. Their location is
:rtype: list(list(BBox))
"""
size_x, size_y = (self.max_x - self.min_x) / num_x, (self.max_y - self.min_y) / num_y
return [[BBox([self.min_x + i * size_x, self.min_y + j * size_y,
self.min_x + (i + 1) * size_x, self.min_y + (j + 1) * size_y],
crs=self.crs) for j in range(num_y)] for i in range(num_x)] | python | def get_partition(self, num_x=1, num_y=1):
size_x, size_y = (self.max_x - self.min_x) / num_x, (self.max_y - self.min_y) / num_y
return [[BBox([self.min_x + i * size_x, self.min_y + j * size_y,
self.min_x + (i + 1) * size_x, self.min_y + (j + 1) * size_y],
crs=self.crs) for j in range(num_y)] for i in range(num_x)] | [
"def",
"get_partition",
"(",
"self",
",",
"num_x",
"=",
"1",
",",
"num_y",
"=",
"1",
")",
":",
"size_x",
",",
"size_y",
"=",
"(",
"self",
".",
"max_x",
"-",
"self",
".",
"min_x",
")",
"/",
"num_x",
",",
"(",
"self",
".",
"max_y",
"-",
"self",
"... | Partitions bounding box into smaller bounding boxes of the same size.
:param num_x: Number of parts BBox will be horizontally divided into.
:type num_x: int
:param num_y: Number of parts BBox will be vertically divided into.
:type num_y: int or None
:return: Two-dimensional list of smaller bounding boxes. Their location is
:rtype: list(list(BBox)) | [
"Partitions",
"bounding",
"box",
"into",
"smaller",
"bounding",
"boxes",
"of",
"the",
"same",
"size",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L284-L297 |
243,040 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox.get_transform_vector | def get_transform_vector(self, resx, resy):
""" Given resolution it returns a transformation vector
:param resx: Resolution in x direction
:type resx: float or int
:param resy: Resolution in y direction
:type resy: float or int
:return: A tuple with 6 numbers representing transformation vector
:rtype: tuple(float)
"""
return self.x_min, self._parse_resolution(resx), 0, self.y_max, 0, -self._parse_resolution(resy) | python | def get_transform_vector(self, resx, resy):
return self.x_min, self._parse_resolution(resx), 0, self.y_max, 0, -self._parse_resolution(resy) | [
"def",
"get_transform_vector",
"(",
"self",
",",
"resx",
",",
"resy",
")",
":",
"return",
"self",
".",
"x_min",
",",
"self",
".",
"_parse_resolution",
"(",
"resx",
")",
",",
"0",
",",
"self",
".",
"y_max",
",",
"0",
",",
"-",
"self",
".",
"_parse_res... | Given resolution it returns a transformation vector
:param resx: Resolution in x direction
:type resx: float or int
:param resy: Resolution in y direction
:type resy: float or int
:return: A tuple with 6 numbers representing transformation vector
:rtype: tuple(float) | [
"Given",
"resolution",
"it",
"returns",
"a",
"transformation",
"vector"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L299-L309 |
243,041 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox._parse_resolution | def _parse_resolution(res):
""" Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float
"""
if isinstance(res, str):
return float(res.strip('m'))
if isinstance(res, (int, float)):
return float(res)
raise TypeError('Resolution should be a float, got resolution of type {}'.format(type(res))) | python | def _parse_resolution(res):
if isinstance(res, str):
return float(res.strip('m'))
if isinstance(res, (int, float)):
return float(res)
raise TypeError('Resolution should be a float, got resolution of type {}'.format(type(res))) | [
"def",
"_parse_resolution",
"(",
"res",
")",
":",
"if",
"isinstance",
"(",
"res",
",",
"str",
")",
":",
"return",
"float",
"(",
"res",
".",
"strip",
"(",
"'m'",
")",
")",
"if",
"isinstance",
"(",
"res",
",",
"(",
"int",
",",
"float",
")",
")",
":... | Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float | [
"Helper",
"method",
"for",
"parsing",
"given",
"resolution",
".",
"It",
"will",
"also",
"try",
"to",
"parse",
"a",
"string",
"into",
"float"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L312-L323 |
243,042 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox._tuple_from_list_or_tuple | def _tuple_from_list_or_tuple(bbox):
""" Converts a list or tuple representation of a bbox into a flat tuple representation.
:param bbox: a list or tuple with 4 coordinates that is either flat or nested
:return: tuple (min_x,min_y,max_x,max_y)
:raises: TypeError
"""
if len(bbox) == 4:
return tuple(map(float, bbox))
if len(bbox) == 2 and all([isinstance(point, (list, tuple)) for point in bbox]):
return BBox._tuple_from_list_or_tuple(bbox[0] + bbox[1])
raise TypeError('Expected a valid list or tuple representation of a bbox') | python | def _tuple_from_list_or_tuple(bbox):
if len(bbox) == 4:
return tuple(map(float, bbox))
if len(bbox) == 2 and all([isinstance(point, (list, tuple)) for point in bbox]):
return BBox._tuple_from_list_or_tuple(bbox[0] + bbox[1])
raise TypeError('Expected a valid list or tuple representation of a bbox') | [
"def",
"_tuple_from_list_or_tuple",
"(",
"bbox",
")",
":",
"if",
"len",
"(",
"bbox",
")",
"==",
"4",
":",
"return",
"tuple",
"(",
"map",
"(",
"float",
",",
"bbox",
")",
")",
"if",
"len",
"(",
"bbox",
")",
"==",
"2",
"and",
"all",
"(",
"[",
"isins... | Converts a list or tuple representation of a bbox into a flat tuple representation.
:param bbox: a list or tuple with 4 coordinates that is either flat or nested
:return: tuple (min_x,min_y,max_x,max_y)
:raises: TypeError | [
"Converts",
"a",
"list",
"or",
"tuple",
"representation",
"of",
"a",
"bbox",
"into",
"a",
"flat",
"tuple",
"representation",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L347-L358 |
243,043 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBox._tuple_from_str | def _tuple_from_str(bbox):
""" Parses a string of numbers separated by any combination of commas and spaces
:param bbox: e.g. str of the form `min_x ,min_y max_x, max_y`
:return: tuple (min_x,min_y,max_x,max_y)
"""
return tuple([float(s) for s in bbox.replace(',', ' ').split() if s]) | python | def _tuple_from_str(bbox):
return tuple([float(s) for s in bbox.replace(',', ' ').split() if s]) | [
"def",
"_tuple_from_str",
"(",
"bbox",
")",
":",
"return",
"tuple",
"(",
"[",
"float",
"(",
"s",
")",
"for",
"s",
"in",
"bbox",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"if",
"s",
"]",
")"
] | Parses a string of numbers separated by any combination of commas and spaces
:param bbox: e.g. str of the form `min_x ,min_y max_x, max_y`
:return: tuple (min_x,min_y,max_x,max_y) | [
"Parses",
"a",
"string",
"of",
"numbers",
"separated",
"by",
"any",
"combination",
"of",
"commas",
"and",
"spaces"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L361-L367 |
243,044 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | Geometry.reverse | def reverse(self):
""" Returns a new Geometry object where x and y coordinates are switched
:return: New Geometry object with switched coordinates
:rtype: Geometry
"""
return Geometry(shapely.ops.transform(lambda x, y: (y, x), self.geometry), crs=self.crs) | python | def reverse(self):
return Geometry(shapely.ops.transform(lambda x, y: (y, x), self.geometry), crs=self.crs) | [
"def",
"reverse",
"(",
"self",
")",
":",
"return",
"Geometry",
"(",
"shapely",
".",
"ops",
".",
"transform",
"(",
"lambda",
"x",
",",
"y",
":",
"(",
"y",
",",
"x",
")",
",",
"self",
".",
"geometry",
")",
",",
"crs",
"=",
"self",
".",
"crs",
")"... | Returns a new Geometry object where x and y coordinates are switched
:return: New Geometry object with switched coordinates
:rtype: Geometry | [
"Returns",
"a",
"new",
"Geometry",
"object",
"where",
"x",
"and",
"y",
"coordinates",
"are",
"switched"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L423-L429 |
243,045 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | Geometry.transform | def transform(self, crs):
""" Transforms Geometry from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Geometry in target CRS
:rtype: Geometry
"""
new_crs = CRS(crs)
geometry = self.geometry
if new_crs is not self.crs:
project = functools.partial(pyproj.transform, self.crs.projection(), new_crs.projection())
geometry = shapely.ops.transform(project, geometry)
return Geometry(geometry, crs=new_crs) | python | def transform(self, crs):
new_crs = CRS(crs)
geometry = self.geometry
if new_crs is not self.crs:
project = functools.partial(pyproj.transform, self.crs.projection(), new_crs.projection())
geometry = shapely.ops.transform(project, geometry)
return Geometry(geometry, crs=new_crs) | [
"def",
"transform",
"(",
"self",
",",
"crs",
")",
":",
"new_crs",
"=",
"CRS",
"(",
"crs",
")",
"geometry",
"=",
"self",
".",
"geometry",
"if",
"new_crs",
"is",
"not",
"self",
".",
"crs",
":",
"project",
"=",
"functools",
".",
"partial",
"(",
"pyproj"... | Transforms Geometry from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Geometry in target CRS
:rtype: Geometry | [
"Transforms",
"Geometry",
"from",
"current",
"CRS",
"to",
"target",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L431-L446 |
243,046 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | Geometry._parse_geometry | def _parse_geometry(geometry):
""" Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError
"""
if isinstance(geometry, str):
geometry = shapely.wkt.loads(geometry)
elif isinstance(geometry, dict):
geometry = shapely.geometry.shape(geometry)
elif not isinstance(geometry, shapely.geometry.base.BaseGeometry):
raise TypeError('Unsupported geometry representation')
if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)):
raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry)))
return geometry | python | def _parse_geometry(geometry):
if isinstance(geometry, str):
geometry = shapely.wkt.loads(geometry)
elif isinstance(geometry, dict):
geometry = shapely.geometry.shape(geometry)
elif not isinstance(geometry, shapely.geometry.base.BaseGeometry):
raise TypeError('Unsupported geometry representation')
if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)):
raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry)))
return geometry | [
"def",
"_parse_geometry",
"(",
"geometry",
")",
":",
"if",
"isinstance",
"(",
"geometry",
",",
"str",
")",
":",
"geometry",
"=",
"shapely",
".",
"wkt",
".",
"loads",
"(",
"geometry",
")",
"elif",
"isinstance",
"(",
"geometry",
",",
"dict",
")",
":",
"g... | Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError | [
"Parses",
"given",
"geometry",
"into",
"shapely",
"object"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L467-L485 |
243,047 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBoxCollection.transform | def transform(self, crs):
""" Transforms BBoxCollection from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: BBoxCollection in target CRS
:rtype: BBoxCollection
"""
return BBoxCollection([bbox.transform(crs) for bbox in self.bbox_list]) | python | def transform(self, crs):
return BBoxCollection([bbox.transform(crs) for bbox in self.bbox_list]) | [
"def",
"transform",
"(",
"self",
",",
"crs",
")",
":",
"return",
"BBoxCollection",
"(",
"[",
"bbox",
".",
"transform",
"(",
"crs",
")",
"for",
"bbox",
"in",
"self",
".",
"bbox_list",
"]",
")"
] | Transforms BBoxCollection from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: BBoxCollection in target CRS
:rtype: BBoxCollection | [
"Transforms",
"BBoxCollection",
"from",
"current",
"CRS",
"to",
"target",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L551-L559 |
243,048 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBoxCollection._get_geometry | def _get_geometry(self):
""" Creates a multipolygon of bounding box polygons
"""
return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list]) | python | def _get_geometry(self):
return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list]) | [
"def",
"_get_geometry",
"(",
"self",
")",
":",
"return",
"shapely",
".",
"geometry",
".",
"MultiPolygon",
"(",
"[",
"bbox",
".",
"geometry",
"for",
"bbox",
"in",
"self",
".",
"bbox_list",
"]",
")"
] | Creates a multipolygon of bounding box polygons | [
"Creates",
"a",
"multipolygon",
"of",
"bounding",
"box",
"polygons"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L561-L564 |
243,049 | sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | BBoxCollection._parse_bbox_list | def _parse_bbox_list(bbox_list):
""" Helper method for parsing a list of bounding boxes
"""
if isinstance(bbox_list, BBoxCollection):
return bbox_list.bbox_list, bbox_list.crs
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-empty list of BBox objects')
for bbox in bbox_list:
if not isinstance(bbox, BBox):
raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox)))
crs = bbox_list[0].crs
for bbox in bbox_list:
if bbox.crs is not crs:
raise ValueError('All bounding boxes should have the same CRS')
return bbox_list, crs | python | def _parse_bbox_list(bbox_list):
if isinstance(bbox_list, BBoxCollection):
return bbox_list.bbox_list, bbox_list.crs
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-empty list of BBox objects')
for bbox in bbox_list:
if not isinstance(bbox, BBox):
raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox)))
crs = bbox_list[0].crs
for bbox in bbox_list:
if bbox.crs is not crs:
raise ValueError('All bounding boxes should have the same CRS')
return bbox_list, crs | [
"def",
"_parse_bbox_list",
"(",
"bbox_list",
")",
":",
"if",
"isinstance",
"(",
"bbox_list",
",",
"BBoxCollection",
")",
":",
"return",
"bbox_list",
".",
"bbox_list",
",",
"bbox_list",
".",
"crs",
"if",
"not",
"isinstance",
"(",
"bbox_list",
",",
"list",
")"... | Helper method for parsing a list of bounding boxes | [
"Helper",
"method",
"for",
"parsing",
"a",
"list",
"of",
"bounding",
"boxes"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L567-L585 |
243,050 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | read_data | def read_data(filename, data_format=None):
""" Read image data from file
This function reads input data from file. The format of the file
can be specified in ``data_format``. If not specified, the format is
guessed from the extension of the filename.
:param filename: filename to read data from
:type filename: str
:param data_format: format of filename. Default is ``None``
:type data_format: MimeType
:return: data read from filename
:raises: exception if filename does not exist
"""
if not os.path.exists(filename):
raise ValueError('Filename {} does not exist'.format(filename))
if not isinstance(data_format, MimeType):
data_format = get_data_format(filename)
if data_format.is_tiff_format():
return read_tiff_image(filename)
if data_format is MimeType.JP2:
return read_jp2_image(filename)
if data_format.is_image_format():
return read_image(filename)
try:
return {
MimeType.TXT: read_text,
MimeType.CSV: read_csv,
MimeType.JSON: read_json,
MimeType.XML: read_xml,
MimeType.GML: read_xml,
MimeType.SAFE: read_xml
}[data_format](filename)
except KeyError:
raise ValueError('Reading data format .{} is not supported'.format(data_format.value)) | python | def read_data(filename, data_format=None):
if not os.path.exists(filename):
raise ValueError('Filename {} does not exist'.format(filename))
if not isinstance(data_format, MimeType):
data_format = get_data_format(filename)
if data_format.is_tiff_format():
return read_tiff_image(filename)
if data_format is MimeType.JP2:
return read_jp2_image(filename)
if data_format.is_image_format():
return read_image(filename)
try:
return {
MimeType.TXT: read_text,
MimeType.CSV: read_csv,
MimeType.JSON: read_json,
MimeType.XML: read_xml,
MimeType.GML: read_xml,
MimeType.SAFE: read_xml
}[data_format](filename)
except KeyError:
raise ValueError('Reading data format .{} is not supported'.format(data_format.value)) | [
"def",
"read_data",
"(",
"filename",
",",
"data_format",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"'Filename {} does not exist'",
".",
"format",
"(",
"filename",
")",
")",
... | Read image data from file
This function reads input data from file. The format of the file
can be specified in ``data_format``. If not specified, the format is
guessed from the extension of the filename.
:param filename: filename to read data from
:type filename: str
:param data_format: format of filename. Default is ``None``
:type data_format: MimeType
:return: data read from filename
:raises: exception if filename does not exist | [
"Read",
"image",
"data",
"from",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L26-L62 |
243,051 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | read_jp2_image | def read_jp2_image(filename):
""" Read data from JPEG2000 file
:param filename: name of JPEG2000 file to be read
:type filename: str
:return: data stored in JPEG2000 file
"""
# Other option:
# return glymur.Jp2k(filename)[:]
image = read_image(filename)
with open(filename, 'rb') as file:
bit_depth = get_jp2_bit_depth(file)
return fix_jp2_image(image, bit_depth) | python | def read_jp2_image(filename):
# Other option:
# return glymur.Jp2k(filename)[:]
image = read_image(filename)
with open(filename, 'rb') as file:
bit_depth = get_jp2_bit_depth(file)
return fix_jp2_image(image, bit_depth) | [
"def",
"read_jp2_image",
"(",
"filename",
")",
":",
"# Other option:",
"# return glymur.Jp2k(filename)[:]",
"image",
"=",
"read_image",
"(",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"file",
":",
"bit_depth",
"=",
"get_jp2_bit_depth... | Read data from JPEG2000 file
:param filename: name of JPEG2000 file to be read
:type filename: str
:return: data stored in JPEG2000 file | [
"Read",
"data",
"from",
"JPEG2000",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L75-L89 |
243,052 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | read_csv | def read_csv(filename, delimiter=CSV_DELIMITER):
""" Read data from CSV file
:param filename: name of CSV file to be read
:type filename: str
:param delimiter: type of CSV delimiter. Default is ``;``
:type delimiter: str
:return: data stored in CSV file as list
"""
with open(filename, 'r') as file:
return list(csv.reader(file, delimiter=delimiter)) | python | def read_csv(filename, delimiter=CSV_DELIMITER):
with open(filename, 'r') as file:
return list(csv.reader(file, delimiter=delimiter)) | [
"def",
"read_csv",
"(",
"filename",
",",
"delimiter",
"=",
"CSV_DELIMITER",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"list",
"(",
"csv",
".",
"reader",
"(",
"file",
",",
"delimiter",
"=",
"delimiter",
")"... | Read data from CSV file
:param filename: name of CSV file to be read
:type filename: str
:param delimiter: type of CSV delimiter. Default is ``;``
:type delimiter: str
:return: data stored in CSV file as list | [
"Read",
"data",
"from",
"CSV",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L113-L123 |
243,053 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_data | def write_data(filename, data, data_format=None, compress=False, add=False):
""" Write image data to file
Function to write image data to specified file. If file format is not provided
explicitly, it is guessed from the filename extension. If format is TIFF, geo
information and compression can be optionally added.
:param filename: name of file to write data to
:type filename: str
:param data: image data to write to file
:type data: numpy array
:param data_format: format of output file. Default is ``None``
:type data_format: MimeType
:param compress: whether to compress data or not. Default is ``False``
:type compress: bool
:param add: whether to append to existing text file or not. Default is ``False``
:type add: bool
:raises: exception if numpy format is not supported or file cannot be written
"""
create_parent_folder(filename)
if not isinstance(data_format, MimeType):
data_format = get_data_format(filename)
if data_format.is_tiff_format():
return write_tiff_image(filename, data, compress)
if data_format.is_image_format():
return write_image(filename, data)
if data_format is MimeType.TXT:
return write_text(filename, data, add=add)
try:
return {
MimeType.CSV: write_csv,
MimeType.JSON: write_json,
MimeType.XML: write_xml,
MimeType.GML: write_xml
}[data_format](filename, data)
except KeyError:
raise ValueError('Writing data format .{} is not supported'.format(data_format.value)) | python | def write_data(filename, data, data_format=None, compress=False, add=False):
create_parent_folder(filename)
if not isinstance(data_format, MimeType):
data_format = get_data_format(filename)
if data_format.is_tiff_format():
return write_tiff_image(filename, data, compress)
if data_format.is_image_format():
return write_image(filename, data)
if data_format is MimeType.TXT:
return write_text(filename, data, add=add)
try:
return {
MimeType.CSV: write_csv,
MimeType.JSON: write_json,
MimeType.XML: write_xml,
MimeType.GML: write_xml
}[data_format](filename, data)
except KeyError:
raise ValueError('Writing data format .{} is not supported'.format(data_format.value)) | [
"def",
"write_data",
"(",
"filename",
",",
"data",
",",
"data_format",
"=",
"None",
",",
"compress",
"=",
"False",
",",
"add",
"=",
"False",
")",
":",
"create_parent_folder",
"(",
"filename",
")",
"if",
"not",
"isinstance",
"(",
"data_format",
",",
"MimeTy... | Write image data to file
Function to write image data to specified file. If file format is not provided
explicitly, it is guessed from the filename extension. If format is TIFF, geo
information and compression can be optionally added.
:param filename: name of file to write data to
:type filename: str
:param data: image data to write to file
:type data: numpy array
:param data_format: format of output file. Default is ``None``
:type data_format: MimeType
:param compress: whether to compress data or not. Default is ``False``
:type compress: bool
:param add: whether to append to existing text file or not. Default is ``False``
:type add: bool
:raises: exception if numpy format is not supported or file cannot be written | [
"Write",
"image",
"data",
"to",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L157-L196 |
243,054 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_tiff_image | def write_tiff_image(filename, image, compress=False):
""" Write image data to TIFF file
:param filename: name of file to write data to
:type filename: str
:param image: image data to write to file
:type image: numpy array
:param compress: whether to compress data. If ``True``, lzma compression is used. Default is ``False``
:type compress: bool
"""
if compress:
return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks
return tiff.imsave(filename, image) | python | def write_tiff_image(filename, image, compress=False):
if compress:
return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks
return tiff.imsave(filename, image) | [
"def",
"write_tiff_image",
"(",
"filename",
",",
"image",
",",
"compress",
"=",
"False",
")",
":",
"if",
"compress",
":",
"return",
"tiff",
".",
"imsave",
"(",
"filename",
",",
"image",
",",
"compress",
"=",
"'lzma'",
")",
"# loseless compression, works very w... | Write image data to TIFF file
:param filename: name of file to write data to
:type filename: str
:param image: image data to write to file
:type image: numpy array
:param compress: whether to compress data. If ``True``, lzma compression is used. Default is ``False``
:type compress: bool | [
"Write",
"image",
"data",
"to",
"TIFF",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L199-L211 |
243,055 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_image | def write_image(filename, image):
""" Write image data to PNG, JPG file
:param filename: name of PNG or JPG file to write data to
:type filename: str
:param image: image data to write to file
:type image: numpy array
"""
data_format = get_data_format(filename)
if data_format is MimeType.JPG:
LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')
return Image.fromarray(image).save(filename) | python | def write_image(filename, image):
data_format = get_data_format(filename)
if data_format is MimeType.JPG:
LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')
return Image.fromarray(image).save(filename) | [
"def",
"write_image",
"(",
"filename",
",",
"image",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"filename",
")",
"if",
"data_format",
"is",
"MimeType",
".",
"JPG",
":",
"LOGGER",
".",
"warning",
"(",
"'Warning: jpeg is a lossy format therefore saved data ... | Write image data to PNG, JPG file
:param filename: name of PNG or JPG file to write data to
:type filename: str
:param image: image data to write to file
:type image: numpy array | [
"Write",
"image",
"data",
"to",
"PNG",
"JPG",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L229-L240 |
243,056 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_text | def write_text(filename, data, add=False):
""" Write image data to text file
:param filename: name of text file to write data to
:type filename: str
:param data: image data to write to text file
:type data: numpy array
:param add: whether to append to existing file or not. Default is ``False``
:type add: bool
"""
write_type = 'a' if add else 'w'
with open(filename, write_type) as file:
print(data, end='', file=file) | python | def write_text(filename, data, add=False):
write_type = 'a' if add else 'w'
with open(filename, write_type) as file:
print(data, end='', file=file) | [
"def",
"write_text",
"(",
"filename",
",",
"data",
",",
"add",
"=",
"False",
")",
":",
"write_type",
"=",
"'a'",
"if",
"add",
"else",
"'w'",
"with",
"open",
"(",
"filename",
",",
"write_type",
")",
"as",
"file",
":",
"print",
"(",
"data",
",",
"end",... | Write image data to text file
:param filename: name of text file to write data to
:type filename: str
:param data: image data to write to text file
:type data: numpy array
:param add: whether to append to existing file or not. Default is ``False``
:type add: bool | [
"Write",
"image",
"data",
"to",
"text",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L243-L255 |
243,057 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_csv | def write_csv(filename, data, delimiter=CSV_DELIMITER):
""" Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
:type delimiter: str
"""
with open(filename, 'w') as file:
csv_writer = csv.writer(file, delimiter=delimiter)
for line in data:
csv_writer.writerow(line) | python | def write_csv(filename, data, delimiter=CSV_DELIMITER):
with open(filename, 'w') as file:
csv_writer = csv.writer(file, delimiter=delimiter)
for line in data:
csv_writer.writerow(line) | [
"def",
"write_csv",
"(",
"filename",
",",
"data",
",",
"delimiter",
"=",
"CSV_DELIMITER",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"file",
":",
"csv_writer",
"=",
"csv",
".",
"writer",
"(",
"file",
",",
"delimiter",
"=",
"delim... | Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
:type delimiter: str | [
"Write",
"image",
"data",
"to",
"CSV",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L258-L271 |
243,058 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | write_json | def write_json(filename, data):
""" Write data to JSON file
:param filename: name of JSON file to write data to
:type filename: str
:param data: data to write to JSON file
:type data: list, tuple
"""
with open(filename, 'w') as file:
json.dump(data, file, indent=4, sort_keys=True) | python | def write_json(filename, data):
with open(filename, 'w') as file:
json.dump(data, file, indent=4, sort_keys=True) | [
"def",
"write_json",
"(",
"filename",
",",
"data",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"file",
":",
"json",
".",
"dump",
"(",
"data",
",",
"file",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
] | Write data to JSON file
:param filename: name of JSON file to write data to
:type filename: str
:param data: data to write to JSON file
:type data: list, tuple | [
"Write",
"data",
"to",
"JSON",
"file"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L274-L283 |
243,059 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | get_jp2_bit_depth | def get_jp2_bit_depth(stream):
"""Reads bit encoding depth of jpeg2000 file in binary stream format
:param stream: binary stream format
:type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...)
:return: bit depth
:rtype: int
"""
stream.seek(0)
while True:
read_buffer = stream.read(8)
if len(read_buffer) < 8:
raise ValueError('Image Header Box not found in Jpeg2000 file')
_, box_id = struct.unpack('>I4s', read_buffer)
if box_id == b'ihdr':
read_buffer = stream.read(14)
params = struct.unpack('>IIHBBBB', read_buffer)
return (params[3] & 0x7f) + 1 | python | def get_jp2_bit_depth(stream):
stream.seek(0)
while True:
read_buffer = stream.read(8)
if len(read_buffer) < 8:
raise ValueError('Image Header Box not found in Jpeg2000 file')
_, box_id = struct.unpack('>I4s', read_buffer)
if box_id == b'ihdr':
read_buffer = stream.read(14)
params = struct.unpack('>IIHBBBB', read_buffer)
return (params[3] & 0x7f) + 1 | [
"def",
"get_jp2_bit_depth",
"(",
"stream",
")",
":",
"stream",
".",
"seek",
"(",
"0",
")",
"while",
"True",
":",
"read_buffer",
"=",
"stream",
".",
"read",
"(",
"8",
")",
"if",
"len",
"(",
"read_buffer",
")",
"<",
"8",
":",
"raise",
"ValueError",
"("... | Reads bit encoding depth of jpeg2000 file in binary stream format
:param stream: binary stream format
:type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...)
:return: bit depth
:rtype: int | [
"Reads",
"bit",
"encoding",
"depth",
"of",
"jpeg2000",
"file",
"in",
"binary",
"stream",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L322-L341 |
243,060 | sentinel-hub/sentinelhub-py | sentinelhub/io_utils.py | fix_jp2_image | def fix_jp2_image(image, bit_depth):
"""Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the
values in image.
:param image: image read by opencv library
:type image: numpy array
:param bit_depth: bit depth of jp2 image encoding
:type bit_depth: int
:return: corrected image
:rtype: numpy array
"""
if bit_depth in [8, 16]:
return image
if bit_depth == 15:
try:
return image >> 1
except TypeError:
raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not '
'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel')
raise ValueError('Bit depth {} of jp2 image is currently not supported. '
'Please raise an issue on package Github page'.format(bit_depth)) | python | def fix_jp2_image(image, bit_depth):
if bit_depth in [8, 16]:
return image
if bit_depth == 15:
try:
return image >> 1
except TypeError:
raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not '
'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel')
raise ValueError('Bit depth {} of jp2 image is currently not supported. '
'Please raise an issue on package Github page'.format(bit_depth)) | [
"def",
"fix_jp2_image",
"(",
"image",
",",
"bit_depth",
")",
":",
"if",
"bit_depth",
"in",
"[",
"8",
",",
"16",
"]",
":",
"return",
"image",
"if",
"bit_depth",
"==",
"15",
":",
"try",
":",
"return",
"image",
">>",
"1",
"except",
"TypeError",
":",
"ra... | Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the
values in image.
:param image: image read by opencv library
:type image: numpy array
:param bit_depth: bit depth of jp2 image encoding
:type bit_depth: int
:return: corrected image
:rtype: numpy array | [
"Because",
"Pillow",
"library",
"incorrectly",
"reads",
"JPEG",
"2000",
"images",
"with",
"15",
"-",
"bit",
"encoding",
"this",
"function",
"corrects",
"the",
"values",
"in",
"image",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L344-L365 |
243,061 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | download_data | def download_data(request_list, redownload=False, max_threads=None):
""" Download all requested data or read data from disk, if already downloaded and available and redownload is
not required.
:param request_list: list of DownloadRequests
:type request_list: list of DownloadRequests
:param redownload: if ``True``, download again the data, although it was already downloaded and is available
on the disk. Default is ``False``.
:type redownload: bool
:param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which
by default uses the number of processors on the system
:type max_threads: int
:return: list of Futures holding downloaded data, where each element in the list corresponds to an element
in the download request list.
:rtype: list[concurrent.futures.Future]
"""
_check_if_must_download(request_list, redownload)
LOGGER.debug("Using max_threads=%s for %s requests", max_threads, len(request_list))
with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
return [executor.submit(execute_download_request, request) for request in request_list] | python | def download_data(request_list, redownload=False, max_threads=None):
_check_if_must_download(request_list, redownload)
LOGGER.debug("Using max_threads=%s for %s requests", max_threads, len(request_list))
with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
return [executor.submit(execute_download_request, request) for request in request_list] | [
"def",
"download_data",
"(",
"request_list",
",",
"redownload",
"=",
"False",
",",
"max_threads",
"=",
"None",
")",
":",
"_check_if_must_download",
"(",
"request_list",
",",
"redownload",
")",
"LOGGER",
".",
"debug",
"(",
"\"Using max_threads=%s for %s requests\"",
... | Download all requested data or read data from disk, if already downloaded and available and redownload is
not required.
:param request_list: list of DownloadRequests
:type request_list: list of DownloadRequests
:param redownload: if ``True``, download again the data, although it was already downloaded and is available
on the disk. Default is ``False``.
:type redownload: bool
:param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which
by default uses the number of processors on the system
:type max_threads: int
:return: list of Futures holding downloaded data, where each element in the list corresponds to an element
in the download request list.
:rtype: list[concurrent.futures.Future] | [
"Download",
"all",
"requested",
"data",
"or",
"read",
"data",
"from",
"disk",
"if",
"already",
"downloaded",
"and",
"available",
"and",
"redownload",
"is",
"not",
"required",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L178-L199 |
243,062 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | _check_if_must_download | def _check_if_must_download(request_list, redownload):
"""
Updates request.will_download attribute of each request in request_list.
**Note:** the function mutates the elements of the list!
:param request_list: a list of ``DownloadRequest`` instances
:type: list[DownloadRequest]
:param redownload: tells whether to download the data again or not
:type: bool
"""
for request in request_list:
request.will_download = (request.save_response or request.return_data) \
and (not request.is_downloaded() or redownload) | python | def _check_if_must_download(request_list, redownload):
for request in request_list:
request.will_download = (request.save_response or request.return_data) \
and (not request.is_downloaded() or redownload) | [
"def",
"_check_if_must_download",
"(",
"request_list",
",",
"redownload",
")",
":",
"for",
"request",
"in",
"request_list",
":",
"request",
".",
"will_download",
"=",
"(",
"request",
".",
"save_response",
"or",
"request",
".",
"return_data",
")",
"and",
"(",
"... | Updates request.will_download attribute of each request in request_list.
**Note:** the function mutates the elements of the list!
:param request_list: a list of ``DownloadRequest`` instances
:type: list[DownloadRequest]
:param redownload: tells whether to download the data again or not
:type: bool | [
"Updates",
"request",
".",
"will_download",
"attribute",
"of",
"each",
"request",
"in",
"request_list",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L202-L215 |
243,063 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | execute_download_request | def execute_download_request(request):
""" Executes download request.
:param request: DownloadRequest to be executed
:type request: DownloadRequest
:return: downloaded data or None
:rtype: numpy array, other possible data type or None
:raises: DownloadFailedException
"""
if request.save_response and request.data_folder is None:
raise ValueError('Data folder is not specified. '
'Please give a data folder name in the initialization of your request.')
if not request.will_download:
return None
try_num = SHConfig().max_download_attempts
response = None
while try_num > 0:
try:
if request.is_aws_s3():
response = _do_aws_request(request)
response_content = response['Body'].read()
else:
response = _do_request(request)
response.raise_for_status()
response_content = response.content
LOGGER.debug('Successful download from %s', request.url)
break
except requests.RequestException as exception:
try_num -= 1
if try_num > 0 and (_is_temporal_problem(exception) or
(isinstance(exception, requests.HTTPError) and
exception.response.status_code >= requests.status_codes.codes.INTERNAL_SERVER_ERROR) or
_request_limit_reached(exception)):
LOGGER.debug('Download attempt failed: %s\n%d attempts left, will retry in %ds', exception,
try_num, SHConfig().download_sleep_time)
sleep_time = SHConfig().download_sleep_time
if _request_limit_reached(exception):
sleep_time = max(sleep_time, 60)
time.sleep(sleep_time)
else:
if request.url.startswith(SHConfig().aws_metadata_url) and \
isinstance(exception, requests.HTTPError) and \
exception.response.status_code == requests.status_codes.codes.NOT_FOUND:
raise AwsDownloadFailedException('File in location %s is missing' % request.url)
raise DownloadFailedException(_create_download_failed_message(exception, request.url))
_save_if_needed(request, response_content)
if request.return_data:
return decode_data(response_content, request.data_type, entire_response=response)
return None | python | def execute_download_request(request):
if request.save_response and request.data_folder is None:
raise ValueError('Data folder is not specified. '
'Please give a data folder name in the initialization of your request.')
if not request.will_download:
return None
try_num = SHConfig().max_download_attempts
response = None
while try_num > 0:
try:
if request.is_aws_s3():
response = _do_aws_request(request)
response_content = response['Body'].read()
else:
response = _do_request(request)
response.raise_for_status()
response_content = response.content
LOGGER.debug('Successful download from %s', request.url)
break
except requests.RequestException as exception:
try_num -= 1
if try_num > 0 and (_is_temporal_problem(exception) or
(isinstance(exception, requests.HTTPError) and
exception.response.status_code >= requests.status_codes.codes.INTERNAL_SERVER_ERROR) or
_request_limit_reached(exception)):
LOGGER.debug('Download attempt failed: %s\n%d attempts left, will retry in %ds', exception,
try_num, SHConfig().download_sleep_time)
sleep_time = SHConfig().download_sleep_time
if _request_limit_reached(exception):
sleep_time = max(sleep_time, 60)
time.sleep(sleep_time)
else:
if request.url.startswith(SHConfig().aws_metadata_url) and \
isinstance(exception, requests.HTTPError) and \
exception.response.status_code == requests.status_codes.codes.NOT_FOUND:
raise AwsDownloadFailedException('File in location %s is missing' % request.url)
raise DownloadFailedException(_create_download_failed_message(exception, request.url))
_save_if_needed(request, response_content)
if request.return_data:
return decode_data(response_content, request.data_type, entire_response=response)
return None | [
"def",
"execute_download_request",
"(",
"request",
")",
":",
"if",
"request",
".",
"save_response",
"and",
"request",
".",
"data_folder",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Data folder is not specified. '",
"'Please give a data folder name in the initializatio... | Executes download request.
:param request: DownloadRequest to be executed
:type request: DownloadRequest
:return: downloaded data or None
:rtype: numpy array, other possible data type or None
:raises: DownloadFailedException | [
"Executes",
"download",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L218-L270 |
243,064 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | _is_temporal_problem | def _is_temporal_problem(exception):
""" Checks if the obtained exception is temporal and if download attempt should be repeated
:param exception: Exception raised during download
:type exception: Exception
:return: True if exception is temporal and False otherwise
:rtype: bool
"""
try:
return isinstance(exception, (requests.ConnectionError, requests.Timeout))
except AttributeError: # Earlier requests versions might not have requests.Timeout
return isinstance(exception, requests.ConnectionError) | python | def _is_temporal_problem(exception):
try:
return isinstance(exception, (requests.ConnectionError, requests.Timeout))
except AttributeError: # Earlier requests versions might not have requests.Timeout
return isinstance(exception, requests.ConnectionError) | [
"def",
"_is_temporal_problem",
"(",
"exception",
")",
":",
"try",
":",
"return",
"isinstance",
"(",
"exception",
",",
"(",
"requests",
".",
"ConnectionError",
",",
"requests",
".",
"Timeout",
")",
")",
"except",
"AttributeError",
":",
"# Earlier requests versions ... | Checks if the obtained exception is temporal and if download attempt should be repeated
:param exception: Exception raised during download
:type exception: Exception
:return: True if exception is temporal and False otherwise
:rtype: bool | [
"Checks",
"if",
"the",
"obtained",
"exception",
"is",
"temporal",
"and",
"if",
"download",
"attempt",
"should",
"be",
"repeated"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L325-L336 |
243,065 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | _create_download_failed_message | def _create_download_failed_message(exception, url):
""" Creates message describing why download has failed
:param exception: Exception raised during download
:type exception: Exception
:param url: An URL from where download was attempted
:type url: str
:return: Error message
:rtype: str
"""
message = 'Failed to download from:\n{}\nwith {}:\n{}'.format(url, exception.__class__.__name__, exception)
if _is_temporal_problem(exception):
if isinstance(exception, requests.ConnectionError):
message += '\nPlease check your internet connection and try again.'
else:
message += '\nThere might be a problem in connection or the server failed to process ' \
'your request. Please try again.'
elif isinstance(exception, requests.HTTPError):
try:
server_message = ''
for elem in decode_data(exception.response.content, MimeType.XML):
if 'ServiceException' in elem.tag or 'Message' in elem.tag:
server_message += elem.text.strip('\n\t ')
except ElementTree.ParseError:
server_message = exception.response.text
message += '\nServer response: "{}"'.format(server_message)
return message | python | def _create_download_failed_message(exception, url):
message = 'Failed to download from:\n{}\nwith {}:\n{}'.format(url, exception.__class__.__name__, exception)
if _is_temporal_problem(exception):
if isinstance(exception, requests.ConnectionError):
message += '\nPlease check your internet connection and try again.'
else:
message += '\nThere might be a problem in connection or the server failed to process ' \
'your request. Please try again.'
elif isinstance(exception, requests.HTTPError):
try:
server_message = ''
for elem in decode_data(exception.response.content, MimeType.XML):
if 'ServiceException' in elem.tag or 'Message' in elem.tag:
server_message += elem.text.strip('\n\t ')
except ElementTree.ParseError:
server_message = exception.response.text
message += '\nServer response: "{}"'.format(server_message)
return message | [
"def",
"_create_download_failed_message",
"(",
"exception",
",",
"url",
")",
":",
"message",
"=",
"'Failed to download from:\\n{}\\nwith {}:\\n{}'",
".",
"format",
"(",
"url",
",",
"exception",
".",
"__class__",
".",
"__name__",
",",
"exception",
")",
"if",
"_is_tem... | Creates message describing why download has failed
:param exception: Exception raised during download
:type exception: Exception
:param url: An URL from where download was attempted
:type url: str
:return: Error message
:rtype: str | [
"Creates",
"message",
"describing",
"why",
"download",
"has",
"failed"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L352-L380 |
243,066 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | decode_data | def decode_data(response_content, data_type, entire_response=None):
""" Interprets downloaded data and returns it.
:param response_content: downloaded data (i.e. json, png, tiff, xml, zip, ... file)
:type response_content: bytes
:param data_type: expected downloaded data type
:type data_type: constants.MimeType
:param entire_response: A response obtained from execution of download request
:type entire_response: requests.Response or dict or None
:return: downloaded data
:rtype: numpy array in case of image data type, or other possible data type
:raises: ValueError
"""
LOGGER.debug('data_type=%s', data_type)
if data_type is MimeType.JSON:
if isinstance(entire_response, requests.Response):
return entire_response.json()
return json.loads(response_content.decode('utf-8'))
if MimeType.is_image_format(data_type):
return decode_image(response_content, data_type)
if data_type is MimeType.XML or data_type is MimeType.GML or data_type is MimeType.SAFE:
return ElementTree.fromstring(response_content)
try:
return {
MimeType.RAW: response_content,
MimeType.TXT: response_content,
MimeType.REQUESTS_RESPONSE: entire_response,
MimeType.ZIP: BytesIO(response_content)
}[data_type]
except KeyError:
raise ValueError('Unknown response data type {}'.format(data_type)) | python | def decode_data(response_content, data_type, entire_response=None):
LOGGER.debug('data_type=%s', data_type)
if data_type is MimeType.JSON:
if isinstance(entire_response, requests.Response):
return entire_response.json()
return json.loads(response_content.decode('utf-8'))
if MimeType.is_image_format(data_type):
return decode_image(response_content, data_type)
if data_type is MimeType.XML or data_type is MimeType.GML or data_type is MimeType.SAFE:
return ElementTree.fromstring(response_content)
try:
return {
MimeType.RAW: response_content,
MimeType.TXT: response_content,
MimeType.REQUESTS_RESPONSE: entire_response,
MimeType.ZIP: BytesIO(response_content)
}[data_type]
except KeyError:
raise ValueError('Unknown response data type {}'.format(data_type)) | [
"def",
"decode_data",
"(",
"response_content",
",",
"data_type",
",",
"entire_response",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'data_type=%s'",
",",
"data_type",
")",
"if",
"data_type",
"is",
"MimeType",
".",
"JSON",
":",
"if",
"isinstance",
"... | Interprets downloaded data and returns it.
:param response_content: downloaded data (i.e. json, png, tiff, xml, zip, ... file)
:type response_content: bytes
:param data_type: expected downloaded data type
:type data_type: constants.MimeType
:param entire_response: A response obtained from execution of download request
:type entire_response: requests.Response or dict or None
:return: downloaded data
:rtype: numpy array in case of image data type, or other possible data type
:raises: ValueError | [
"Interprets",
"downloaded",
"data",
"and",
"returns",
"it",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L398-L430 |
243,067 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | decode_image | def decode_image(data, image_type):
""" Decodes the image provided in various formats, i.e. png, 16-bit float tiff, 32-bit float tiff, jp2
and returns it as an numpy array
:param data: image in its original format
:type data: any of possible image types
:param image_type: expected image format
:type image_type: constants.MimeType
:return: image as numpy array
:rtype: numpy array
:raises: ImageDecodingError
"""
bytes_data = BytesIO(data)
if image_type.is_tiff_format():
image = tiff.imread(bytes_data)
else:
image = np.array(Image.open(bytes_data))
if image_type is MimeType.JP2:
try:
bit_depth = get_jp2_bit_depth(bytes_data)
image = fix_jp2_image(image, bit_depth)
except ValueError:
pass
if image is None:
raise ImageDecodingError('Unable to decode image')
return image | python | def decode_image(data, image_type):
bytes_data = BytesIO(data)
if image_type.is_tiff_format():
image = tiff.imread(bytes_data)
else:
image = np.array(Image.open(bytes_data))
if image_type is MimeType.JP2:
try:
bit_depth = get_jp2_bit_depth(bytes_data)
image = fix_jp2_image(image, bit_depth)
except ValueError:
pass
if image is None:
raise ImageDecodingError('Unable to decode image')
return image | [
"def",
"decode_image",
"(",
"data",
",",
"image_type",
")",
":",
"bytes_data",
"=",
"BytesIO",
"(",
"data",
")",
"if",
"image_type",
".",
"is_tiff_format",
"(",
")",
":",
"image",
"=",
"tiff",
".",
"imread",
"(",
"bytes_data",
")",
"else",
":",
"image",
... | Decodes the image provided in various formats, i.e. png, 16-bit float tiff, 32-bit float tiff, jp2
and returns it as an numpy array
:param data: image in its original format
:type data: any of possible image types
:param image_type: expected image format
:type image_type: constants.MimeType
:return: image as numpy array
:rtype: numpy array
:raises: ImageDecodingError | [
"Decodes",
"the",
"image",
"provided",
"in",
"various",
"formats",
"i",
".",
"e",
".",
"png",
"16",
"-",
"bit",
"float",
"tiff",
"32",
"-",
"bit",
"float",
"tiff",
"jp2",
"and",
"returns",
"it",
"as",
"an",
"numpy",
"array"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L433-L460 |
243,068 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | get_json | def get_json(url, post_values=None, headers=None):
""" Download request as JSON data type
:param url: url to Sentinel Hub's services or other sources from where the data is downloaded
:type url: str
:param post_values: form encoded data to send in POST request. Default is ``None``
:type post_values: dict
:param headers: add HTTP headers to request. Default is ``None``
:type headers: dict
:return: request response as JSON instance
:rtype: JSON instance or None
:raises: RunTimeError
"""
json_headers = {} if headers is None else headers.copy()
if post_values is None:
request_type = RequestType.GET
else:
request_type = RequestType.POST
json_headers = {**json_headers, **{'Content-Type': MimeType.get_string(MimeType.JSON)}}
request = DownloadRequest(url=url, headers=json_headers, request_type=request_type, post_values=post_values,
save_response=False, return_data=True, data_type=MimeType.JSON)
return execute_download_request(request) | python | def get_json(url, post_values=None, headers=None):
json_headers = {} if headers is None else headers.copy()
if post_values is None:
request_type = RequestType.GET
else:
request_type = RequestType.POST
json_headers = {**json_headers, **{'Content-Type': MimeType.get_string(MimeType.JSON)}}
request = DownloadRequest(url=url, headers=json_headers, request_type=request_type, post_values=post_values,
save_response=False, return_data=True, data_type=MimeType.JSON)
return execute_download_request(request) | [
"def",
"get_json",
"(",
"url",
",",
"post_values",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"json_headers",
"=",
"{",
"}",
"if",
"headers",
"is",
"None",
"else",
"headers",
".",
"copy",
"(",
")",
"if",
"post_values",
"is",
"None",
":",
"re... | Download request as JSON data type
:param url: url to Sentinel Hub's services or other sources from where the data is downloaded
:type url: str
:param post_values: form encoded data to send in POST request. Default is ``None``
:type post_values: dict
:param headers: add HTTP headers to request. Default is ``None``
:type headers: dict
:return: request response as JSON instance
:rtype: JSON instance or None
:raises: RunTimeError | [
"Download",
"request",
"as",
"JSON",
"data",
"type"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L463-L488 |
243,069 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | get_xml | def get_xml(url):
""" Download request as XML data type
:param url: url to Sentinel Hub's services or other sources from where the data is downloaded
:type url: str
:return: request response as XML instance
:rtype: XML instance or None
:raises: RunTimeError
"""
request = DownloadRequest(url=url, request_type=RequestType.GET, save_response=False, return_data=True,
data_type=MimeType.XML)
return execute_download_request(request) | python | def get_xml(url):
request = DownloadRequest(url=url, request_type=RequestType.GET, save_response=False, return_data=True,
data_type=MimeType.XML)
return execute_download_request(request) | [
"def",
"get_xml",
"(",
"url",
")",
":",
"request",
"=",
"DownloadRequest",
"(",
"url",
"=",
"url",
",",
"request_type",
"=",
"RequestType",
".",
"GET",
",",
"save_response",
"=",
"False",
",",
"return_data",
"=",
"True",
",",
"data_type",
"=",
"MimeType",
... | Download request as XML data type
:param url: url to Sentinel Hub's services or other sources from where the data is downloaded
:type url: str
:return: request response as XML instance
:rtype: XML instance or None
:raises: RunTimeError | [
"Download",
"request",
"as",
"XML",
"data",
"type"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L491-L503 |
243,070 | sentinel-hub/sentinelhub-py | sentinelhub/download.py | DownloadRequest.is_downloaded | def is_downloaded(self):
""" Checks if data for this request has already been downloaded and is saved to disk.
:return: returns ``True`` if data for this request has already been downloaded and is saved to disk.
:rtype: bool
"""
if self.file_path is None:
return False
return os.path.exists(self.file_path) | python | def is_downloaded(self):
if self.file_path is None:
return False
return os.path.exists(self.file_path) | [
"def",
"is_downloaded",
"(",
"self",
")",
":",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"return",
"False",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file_path",
")"
] | Checks if data for this request has already been downloaded and is saved to disk.
:return: returns ``True`` if data for this request has already been downloaded and is saved to disk.
:rtype: bool | [
"Checks",
"if",
"data",
"for",
"this",
"request",
"has",
"already",
"been",
"downloaded",
"and",
"is",
"saved",
"to",
"disk",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L159-L167 |
243,071 | sentinel-hub/sentinelhub-py | sentinelhub/opensearch.py | get_area_info | def get_area_info(bbox, date_interval, maxcc=None):
""" Get information about all images from specified area and time range
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param date_interval: a pair of time strings in ISO8601 format
:type date_interval: tuple(str)
:param maxcc: filter images by maximum percentage of cloud coverage
:type maxcc: float in range [0, 1] or None
:return: list of dictionaries containing info provided by Opensearch REST service
:rtype: list(dict)
"""
result_list = search_iter(bbox=bbox, start_date=date_interval[0], end_date=date_interval[1])
if maxcc:
return reduce_by_maxcc(result_list, maxcc)
return result_list | python | def get_area_info(bbox, date_interval, maxcc=None):
result_list = search_iter(bbox=bbox, start_date=date_interval[0], end_date=date_interval[1])
if maxcc:
return reduce_by_maxcc(result_list, maxcc)
return result_list | [
"def",
"get_area_info",
"(",
"bbox",
",",
"date_interval",
",",
"maxcc",
"=",
"None",
")",
":",
"result_list",
"=",
"search_iter",
"(",
"bbox",
"=",
"bbox",
",",
"start_date",
"=",
"date_interval",
"[",
"0",
"]",
",",
"end_date",
"=",
"date_interval",
"[",... | Get information about all images from specified area and time range
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param date_interval: a pair of time strings in ISO8601 format
:type date_interval: tuple(str)
:param maxcc: filter images by maximum percentage of cloud coverage
:type maxcc: float in range [0, 1] or None
:return: list of dictionaries containing info provided by Opensearch REST service
:rtype: list(dict) | [
"Get",
"information",
"about",
"all",
"images",
"from",
"specified",
"area",
"and",
"time",
"range"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L79-L94 |
243,072 | sentinel-hub/sentinelhub-py | sentinelhub/opensearch.py | get_area_dates | def get_area_dates(bbox, date_interval, maxcc=None):
""" Get list of times of existing images from specified area and time range
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param date_interval: a pair of time strings in ISO8601 format
:type date_interval: tuple(str)
:param maxcc: filter images by maximum percentage of cloud coverage
:type maxcc: float in range [0, 1] or None
:return: list of time strings in ISO8601 format
:rtype: list[datetime.datetime]
"""
area_info = get_area_info(bbox, date_interval, maxcc=maxcc)
return sorted({datetime.datetime.strptime(tile_info['properties']['startDate'].strip('Z'),
'%Y-%m-%dT%H:%M:%S')
for tile_info in area_info}) | python | def get_area_dates(bbox, date_interval, maxcc=None):
area_info = get_area_info(bbox, date_interval, maxcc=maxcc)
return sorted({datetime.datetime.strptime(tile_info['properties']['startDate'].strip('Z'),
'%Y-%m-%dT%H:%M:%S')
for tile_info in area_info}) | [
"def",
"get_area_dates",
"(",
"bbox",
",",
"date_interval",
",",
"maxcc",
"=",
"None",
")",
":",
"area_info",
"=",
"get_area_info",
"(",
"bbox",
",",
"date_interval",
",",
"maxcc",
"=",
"maxcc",
")",
"return",
"sorted",
"(",
"{",
"datetime",
".",
"datetime... | Get list of times of existing images from specified area and time range
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param date_interval: a pair of time strings in ISO8601 format
:type date_interval: tuple(str)
:param maxcc: filter images by maximum percentage of cloud coverage
:type maxcc: float in range [0, 1] or None
:return: list of time strings in ISO8601 format
:rtype: list[datetime.datetime] | [
"Get",
"list",
"of",
"times",
"of",
"existing",
"images",
"from",
"specified",
"area",
"and",
"time",
"range"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L97-L113 |
243,073 | sentinel-hub/sentinelhub-py | sentinelhub/opensearch.py | search_iter | def search_iter(tile_id=None, bbox=None, start_date=None, end_date=None, absolute_orbit=None):
""" A generator function that implements OpenSearch search queries and returns results
All parameters for search are optional.
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param start_date: beginning of time range in ISO8601 format
:type start_date: str
:param end_date: end of time range in ISO8601 format
:type end_date: str
:param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA
:type absolute_orbit: int
:return: An iterator returning dictionaries with info provided by Sentinel Hub OpenSearch REST service
:rtype: Iterator[dict]
"""
if bbox and bbox.crs is not CRS.WGS84:
bbox = bbox.transform(CRS.WGS84)
url_params = _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit)
url_params['maxRecords'] = SHConfig().max_opensearch_records_per_query
start_index = 1
while True:
url_params['index'] = start_index
url = '{}search.json?{}'.format(SHConfig().opensearch_url, urlencode(url_params))
LOGGER.debug("URL=%s", url)
response = get_json(url)
for tile_info in response["features"]:
yield tile_info
if len(response["features"]) < SHConfig().max_opensearch_records_per_query:
break
start_index += SHConfig().max_opensearch_records_per_query | python | def search_iter(tile_id=None, bbox=None, start_date=None, end_date=None, absolute_orbit=None):
if bbox and bbox.crs is not CRS.WGS84:
bbox = bbox.transform(CRS.WGS84)
url_params = _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit)
url_params['maxRecords'] = SHConfig().max_opensearch_records_per_query
start_index = 1
while True:
url_params['index'] = start_index
url = '{}search.json?{}'.format(SHConfig().opensearch_url, urlencode(url_params))
LOGGER.debug("URL=%s", url)
response = get_json(url)
for tile_info in response["features"]:
yield tile_info
if len(response["features"]) < SHConfig().max_opensearch_records_per_query:
break
start_index += SHConfig().max_opensearch_records_per_query | [
"def",
"search_iter",
"(",
"tile_id",
"=",
"None",
",",
"bbox",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"absolute_orbit",
"=",
"None",
")",
":",
"if",
"bbox",
"and",
"bbox",
".",
"crs",
"is",
"not",
"CRS",
".",... | A generator function that implements OpenSearch search queries and returns results
All parameters for search are optional.
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbox: bounding box of requested area
:type bbox: geometry.BBox
:param start_date: beginning of time range in ISO8601 format
:type start_date: str
:param end_date: end of time range in ISO8601 format
:type end_date: str
:param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA
:type absolute_orbit: int
:return: An iterator returning dictionaries with info provided by Sentinel Hub OpenSearch REST service
:rtype: Iterator[dict] | [
"A",
"generator",
"function",
"that",
"implements",
"OpenSearch",
"search",
"queries",
"and",
"returns",
"results"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L129-L168 |
243,074 | sentinel-hub/sentinelhub-py | sentinelhub/opensearch.py | _prepare_url_params | def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit):
""" Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbox: bounding box of requested area in WGS84 CRS
:type bbox: geometry.BBox
:param start_date: beginning of time range in ISO8601 format
:type start_date: str
:param end_date: end of time range in ISO8601 format
:type end_date: str
:param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA
:type absolute_orbit: int
:return: dictionary with parameters as properties when arguments not None
:rtype: dict
"""
url_params = {
'identifier': tile_id,
'startDate': start_date,
'completionDate': end_date,
'orbitNumber': absolute_orbit,
'box': bbox
}
return {key: str(value) for key, value in url_params.items() if value} | python | def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit):
url_params = {
'identifier': tile_id,
'startDate': start_date,
'completionDate': end_date,
'orbitNumber': absolute_orbit,
'box': bbox
}
return {key: str(value) for key, value in url_params.items() if value} | [
"def",
"_prepare_url_params",
"(",
"tile_id",
",",
"bbox",
",",
"end_date",
",",
"start_date",
",",
"absolute_orbit",
")",
":",
"url_params",
"=",
"{",
"'identifier'",
":",
"tile_id",
",",
"'startDate'",
":",
"start_date",
",",
"'completionDate'",
":",
"end_date... | Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbox: bounding box of requested area in WGS84 CRS
:type bbox: geometry.BBox
:param start_date: beginning of time range in ISO8601 format
:type start_date: str
:param end_date: end of time range in ISO8601 format
:type end_date: str
:param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA
:type absolute_orbit: int
:return: dictionary with parameters as properties when arguments not None
:rtype: dict | [
"Constructs",
"dict",
"with",
"URL",
"params"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L171-L195 |
243,075 | sentinel-hub/sentinelhub-py | sentinelhub/aws_safe.py | _edit_name | def _edit_name(name, code, add_code=None, delete_end=False):
"""
Helping function for creating file names in .SAFE format
:param name: initial string
:type name: str
:param code:
:type code: str
:param add_code:
:type add_code: str or None
:param delete_end:
:type delete_end: bool
:return: edited string
:rtype: str
"""
info = name.split('_')
info[2] = code
if add_code is not None:
info[3] = add_code
if delete_end:
info.pop()
return '_'.join(info) | python | def _edit_name(name, code, add_code=None, delete_end=False):
info = name.split('_')
info[2] = code
if add_code is not None:
info[3] = add_code
if delete_end:
info.pop()
return '_'.join(info) | [
"def",
"_edit_name",
"(",
"name",
",",
"code",
",",
"add_code",
"=",
"None",
",",
"delete_end",
"=",
"False",
")",
":",
"info",
"=",
"name",
".",
"split",
"(",
"'_'",
")",
"info",
"[",
"2",
"]",
"=",
"code",
"if",
"add_code",
"is",
"not",
"None",
... | Helping function for creating file names in .SAFE format
:param name: initial string
:type name: str
:param code:
:type code: str
:param add_code:
:type add_code: str or None
:param delete_end:
:type delete_end: bool
:return: edited string
:rtype: str | [
"Helping",
"function",
"for",
"creating",
"file",
"names",
"in",
".",
"SAFE",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L362-L383 |
243,076 | sentinel-hub/sentinelhub-py | sentinelhub/aws_safe.py | SafeProduct.get_requests | def get_requests(self):
"""
Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest)
"""
safe = self.get_safe_struct()
self.download_list = []
self.structure_recursion(safe, self.parent_folder)
self.sort_download_list()
return self.download_list, self.folder_list | python | def get_requests(self):
safe = self.get_safe_struct()
self.download_list = []
self.structure_recursion(safe, self.parent_folder)
self.sort_download_list()
return self.download_list, self.folder_list | [
"def",
"get_requests",
"(",
"self",
")",
":",
"safe",
"=",
"self",
".",
"get_safe_struct",
"(",
")",
"self",
".",
"download_list",
"=",
"[",
"]",
"self",
".",
"structure_recursion",
"(",
"safe",
",",
"self",
".",
"parent_folder",
")",
"self",
".",
"sort_... | Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest) | [
"Creates",
"product",
"structure",
"and",
"returns",
"list",
"of",
"files",
"for",
"download"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L14-L26 |
243,077 | sentinel-hub/sentinelhub-py | sentinelhub/aws_safe.py | SafeProduct.get_safe_struct | def get_safe_struct(self):
"""
Describes a structure inside tile folder of ESA product .SAFE structure
:return: nested dictionaries representing .SAFE structure
:rtype: dict
"""
safe = {}
main_folder = self.get_main_folder()
safe[main_folder] = {}
safe[main_folder][AwsConstants.AUX_DATA] = {}
safe[main_folder][AwsConstants.DATASTRIP] = {}
datastrip_list = self.get_datastrip_list()
for datastrip_folder, datastrip_url in datastrip_list:
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder] = {}
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA] = {}
# S-2 L1C reports are on AWS only stored with tiles and without RADIOMETRIC_QUALITY
if self.has_reports() and self.data_source is DataSource.SENTINEL2_L2A:
for metafile in AwsConstants.QUALITY_REPORTS:
metafile_name = self.add_file_extension(metafile)
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA][
metafile_name] = '{}/qi/{}'.format(datastrip_url, metafile_name)
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][
self.get_datastrip_metadata_name(datastrip_folder)] = '{}/{}'.format(
datastrip_url, self.add_file_extension(AwsConstants.METADATA))
safe[main_folder][AwsConstants.GRANULE] = {}
for tile_info in self.product_info['tiles']:
tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info))
if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list:
tile_struct = SafeTile(tile_name, date, aws_index, parent_folder=None, bands=self.bands,
metafiles=self.metafiles, data_source=self.data_source).get_safe_struct()
for tile_name, safe_struct in tile_struct.items():
safe[main_folder][AwsConstants.GRANULE][tile_name] = safe_struct
safe[main_folder][AwsConstants.HTML] = {} # AWS doesn't have this data
safe[main_folder][AwsConstants.INFO] = {} # AWS doesn't have this data
safe[main_folder][self.get_product_metadata_name()] = self.get_url(AwsConstants.METADATA)
safe[main_folder]['INSPIRE.xml'] = self.get_url(AwsConstants.INSPIRE)
safe[main_folder][self.add_file_extension(AwsConstants.MANIFEST)] = self.get_url(AwsConstants.MANIFEST)
if self.is_early_compact_l2a():
safe[main_folder]['L2A_Manifest.xml'] = self.get_url(AwsConstants.L2A_MANIFEST)
safe[main_folder][self.get_report_name()] = self.get_url(AwsConstants.REPORT)
if self.safe_type == EsaSafeType.OLD_TYPE and self.baseline != '02.02':
safe[main_folder][_edit_name(self.product_id, 'BWI') + '.png'] = self.get_url(AwsConstants.PREVIEW,
MimeType.PNG)
return safe | python | def get_safe_struct(self):
safe = {}
main_folder = self.get_main_folder()
safe[main_folder] = {}
safe[main_folder][AwsConstants.AUX_DATA] = {}
safe[main_folder][AwsConstants.DATASTRIP] = {}
datastrip_list = self.get_datastrip_list()
for datastrip_folder, datastrip_url in datastrip_list:
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder] = {}
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA] = {}
# S-2 L1C reports are on AWS only stored with tiles and without RADIOMETRIC_QUALITY
if self.has_reports() and self.data_source is DataSource.SENTINEL2_L2A:
for metafile in AwsConstants.QUALITY_REPORTS:
metafile_name = self.add_file_extension(metafile)
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA][
metafile_name] = '{}/qi/{}'.format(datastrip_url, metafile_name)
safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][
self.get_datastrip_metadata_name(datastrip_folder)] = '{}/{}'.format(
datastrip_url, self.add_file_extension(AwsConstants.METADATA))
safe[main_folder][AwsConstants.GRANULE] = {}
for tile_info in self.product_info['tiles']:
tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info))
if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list:
tile_struct = SafeTile(tile_name, date, aws_index, parent_folder=None, bands=self.bands,
metafiles=self.metafiles, data_source=self.data_source).get_safe_struct()
for tile_name, safe_struct in tile_struct.items():
safe[main_folder][AwsConstants.GRANULE][tile_name] = safe_struct
safe[main_folder][AwsConstants.HTML] = {} # AWS doesn't have this data
safe[main_folder][AwsConstants.INFO] = {} # AWS doesn't have this data
safe[main_folder][self.get_product_metadata_name()] = self.get_url(AwsConstants.METADATA)
safe[main_folder]['INSPIRE.xml'] = self.get_url(AwsConstants.INSPIRE)
safe[main_folder][self.add_file_extension(AwsConstants.MANIFEST)] = self.get_url(AwsConstants.MANIFEST)
if self.is_early_compact_l2a():
safe[main_folder]['L2A_Manifest.xml'] = self.get_url(AwsConstants.L2A_MANIFEST)
safe[main_folder][self.get_report_name()] = self.get_url(AwsConstants.REPORT)
if self.safe_type == EsaSafeType.OLD_TYPE and self.baseline != '02.02':
safe[main_folder][_edit_name(self.product_id, 'BWI') + '.png'] = self.get_url(AwsConstants.PREVIEW,
MimeType.PNG)
return safe | [
"def",
"get_safe_struct",
"(",
"self",
")",
":",
"safe",
"=",
"{",
"}",
"main_folder",
"=",
"self",
".",
"get_main_folder",
"(",
")",
"safe",
"[",
"main_folder",
"]",
"=",
"{",
"}",
"safe",
"[",
"main_folder",
"]",
"[",
"AwsConstants",
".",
"AUX_DATA",
... | Describes a structure inside tile folder of ESA product .SAFE structure
:return: nested dictionaries representing .SAFE structure
:rtype: dict | [
"Describes",
"a",
"structure",
"inside",
"tile",
"folder",
"of",
"ESA",
"product",
".",
"SAFE",
"structure"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L28-L81 |
243,078 | sentinel-hub/sentinelhub-py | sentinelhub/aws_safe.py | SafeTile.get_tile_id | def get_tile_id(self):
"""Creates ESA tile ID
:return: ESA tile ID
:rtype: str
"""
tree = get_xml(self.get_url(AwsConstants.METADATA))
tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\
'TILE_ID'
tile_id = tree[0].find(tile_id_tag).text
if self.safe_type is not EsaSafeType.OLD_TYPE:
info = tile_id.split('_')
tile_id = '_'.join([info[3], info[-2], info[-3], self.get_sensing_time()])
return tile_id | python | def get_tile_id(self):
tree = get_xml(self.get_url(AwsConstants.METADATA))
tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\
'TILE_ID'
tile_id = tree[0].find(tile_id_tag).text
if self.safe_type is not EsaSafeType.OLD_TYPE:
info = tile_id.split('_')
tile_id = '_'.join([info[3], info[-2], info[-3], self.get_sensing_time()])
return tile_id | [
"def",
"get_tile_id",
"(",
"self",
")",
":",
"tree",
"=",
"get_xml",
"(",
"self",
".",
"get_url",
"(",
"AwsConstants",
".",
"METADATA",
")",
")",
"tile_id_tag",
"=",
"'TILE_ID_2A'",
"if",
"self",
".",
"data_source",
"is",
"DataSource",
".",
"SENTINEL2_L2A",
... | Creates ESA tile ID
:return: ESA tile ID
:rtype: str | [
"Creates",
"ESA",
"tile",
"ID"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L250-L264 |
243,079 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | AreaSplitter._parse_shape_list | def _parse_shape_list(shape_list, crs):
""" Checks if the given list of shapes is in correct format and parses geometry objects
:param shape_list: The parameter `shape_list` from class initialization
:type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon)
:raises: ValueError
"""
if not isinstance(shape_list, list):
raise ValueError('Splitter must be initialized with a list of shapes')
return [AreaSplitter._parse_shape(shape, crs) for shape in shape_list] | python | def _parse_shape_list(shape_list, crs):
if not isinstance(shape_list, list):
raise ValueError('Splitter must be initialized with a list of shapes')
return [AreaSplitter._parse_shape(shape, crs) for shape in shape_list] | [
"def",
"_parse_shape_list",
"(",
"shape_list",
",",
"crs",
")",
":",
"if",
"not",
"isinstance",
"(",
"shape_list",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'Splitter must be initialized with a list of shapes'",
")",
"return",
"[",
"AreaSplitter",
".",
"... | Checks if the given list of shapes is in correct format and parses geometry objects
:param shape_list: The parameter `shape_list` from class initialization
:type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon)
:raises: ValueError | [
"Checks",
"if",
"the",
"given",
"list",
"of",
"shapes",
"is",
"in",
"correct",
"format",
"and",
"parses",
"geometry",
"objects"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L40-L50 |
243,080 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | AreaSplitter.get_bbox_list | def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None):
"""Returns a list of bounding boxes that are the result of the split
:param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will
be the default CRS of the splitter.
:type crs: CRS or None
:param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap.
:type buffer: float or None
:param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly
fit the given geometry in `shape_list`. This overrides the same parameter from constructor
:type reduce_bbox_sizes: bool
:return: List of bounding boxes
:rtype: list(BBox)
"""
bbox_list = self.bbox_list
if buffer:
bbox_list = [bbox.buffer(buffer) for bbox in bbox_list]
if reduce_bbox_sizes is None:
reduce_bbox_sizes = self.reduce_bbox_sizes
if reduce_bbox_sizes:
bbox_list = self._reduce_sizes(bbox_list)
if crs:
return [bbox.transform(crs) for bbox in bbox_list]
return bbox_list | python | def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None):
bbox_list = self.bbox_list
if buffer:
bbox_list = [bbox.buffer(buffer) for bbox in bbox_list]
if reduce_bbox_sizes is None:
reduce_bbox_sizes = self.reduce_bbox_sizes
if reduce_bbox_sizes:
bbox_list = self._reduce_sizes(bbox_list)
if crs:
return [bbox.transform(crs) for bbox in bbox_list]
return bbox_list | [
"def",
"get_bbox_list",
"(",
"self",
",",
"crs",
"=",
"None",
",",
"buffer",
"=",
"None",
",",
"reduce_bbox_sizes",
"=",
"None",
")",
":",
"bbox_list",
"=",
"self",
".",
"bbox_list",
"if",
"buffer",
":",
"bbox_list",
"=",
"[",
"bbox",
".",
"buffer",
"(... | Returns a list of bounding boxes that are the result of the split
:param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will
be the default CRS of the splitter.
:type crs: CRS or None
:param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap.
:type buffer: float or None
:param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly
fit the given geometry in `shape_list`. This overrides the same parameter from constructor
:type reduce_bbox_sizes: bool
:return: List of bounding boxes
:rtype: list(BBox) | [
"Returns",
"a",
"list",
"of",
"bounding",
"boxes",
"that",
"are",
"the",
"result",
"of",
"the",
"split"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L78-L103 |
243,081 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | AreaSplitter.get_area_bbox | def get_area_bbox(self, crs=None):
"""Returns a bounding box of the entire area
:param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will
be the default CRS of the splitter.
:type crs: CRS or None
:return: A bounding box of the area defined by the `shape_list`
:rtype: BBox
"""
bbox_list = [BBox(shape.bounds, crs=self.crs) for shape in self.shape_list]
area_minx = min([bbox.lower_left[0] for bbox in bbox_list])
area_miny = min([bbox.lower_left[1] for bbox in bbox_list])
area_maxx = max([bbox.upper_right[0] for bbox in bbox_list])
area_maxy = max([bbox.upper_right[1] for bbox in bbox_list])
bbox = BBox([area_minx, area_miny, area_maxx, area_maxy], crs=self.crs)
if crs is None:
return bbox
return bbox.transform(crs) | python | def get_area_bbox(self, crs=None):
bbox_list = [BBox(shape.bounds, crs=self.crs) for shape in self.shape_list]
area_minx = min([bbox.lower_left[0] for bbox in bbox_list])
area_miny = min([bbox.lower_left[1] for bbox in bbox_list])
area_maxx = max([bbox.upper_right[0] for bbox in bbox_list])
area_maxy = max([bbox.upper_right[1] for bbox in bbox_list])
bbox = BBox([area_minx, area_miny, area_maxx, area_maxy], crs=self.crs)
if crs is None:
return bbox
return bbox.transform(crs) | [
"def",
"get_area_bbox",
"(",
"self",
",",
"crs",
"=",
"None",
")",
":",
"bbox_list",
"=",
"[",
"BBox",
"(",
"shape",
".",
"bounds",
",",
"crs",
"=",
"self",
".",
"crs",
")",
"for",
"shape",
"in",
"self",
".",
"shape_list",
"]",
"area_minx",
"=",
"m... | Returns a bounding box of the entire area
:param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will
be the default CRS of the splitter.
:type crs: CRS or None
:return: A bounding box of the area defined by the `shape_list`
:rtype: BBox | [
"Returns",
"a",
"bounding",
"box",
"of",
"the",
"entire",
"area"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L131-L148 |
243,082 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | AreaSplitter._bbox_to_area_polygon | def _bbox_to_area_polygon(self, bbox):
"""Transforms bounding box into a polygon object in the area CRS.
:param bbox: A bounding box
:type bbox: BBox
:return: A polygon
:rtype: shapely.geometry.polygon.Polygon
"""
projected_bbox = bbox.transform(self.crs)
return projected_bbox.geometry | python | def _bbox_to_area_polygon(self, bbox):
projected_bbox = bbox.transform(self.crs)
return projected_bbox.geometry | [
"def",
"_bbox_to_area_polygon",
"(",
"self",
",",
"bbox",
")",
":",
"projected_bbox",
"=",
"bbox",
".",
"transform",
"(",
"self",
".",
"crs",
")",
"return",
"projected_bbox",
".",
"geometry"
] | Transforms bounding box into a polygon object in the area CRS.
:param bbox: A bounding box
:type bbox: BBox
:return: A polygon
:rtype: shapely.geometry.polygon.Polygon | [
"Transforms",
"bounding",
"box",
"into",
"a",
"polygon",
"object",
"in",
"the",
"area",
"CRS",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L170-L179 |
243,083 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | AreaSplitter._reduce_sizes | def _reduce_sizes(self, bbox_list):
"""Reduces sizes of bounding boxes
"""
return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list] | python | def _reduce_sizes(self, bbox_list):
return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list] | [
"def",
"_reduce_sizes",
"(",
"self",
",",
"bbox_list",
")",
":",
"return",
"[",
"BBox",
"(",
"self",
".",
"_intersection_area",
"(",
"bbox",
")",
".",
"bounds",
",",
"self",
".",
"crs",
")",
".",
"transform",
"(",
"bbox",
".",
"crs",
")",
"for",
"bbo... | Reduces sizes of bounding boxes | [
"Reduces",
"sizes",
"of",
"bounding",
"boxes"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L181-L184 |
243,084 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | BBoxSplitter._parse_split_shape | def _parse_split_shape(split_shape):
"""Parses the parameter `split_shape`
:param split_shape: The parameter `split_shape` from class initialization
:type split_shape: int or (int, int)
:return: A tuple of n
:rtype: (int, int)
:raises: ValueError
"""
if isinstance(split_shape, int):
return split_shape, split_shape
if isinstance(split_shape, (tuple, list)):
if len(split_shape) == 2 and isinstance(split_shape[0], int) and isinstance(split_shape[1], int):
return split_shape[0], split_shape[1]
raise ValueError("Content of split_shape {} must be 2 integers.".format(split_shape))
raise ValueError("Split shape must be an int or a tuple of 2 integers.") | python | def _parse_split_shape(split_shape):
if isinstance(split_shape, int):
return split_shape, split_shape
if isinstance(split_shape, (tuple, list)):
if len(split_shape) == 2 and isinstance(split_shape[0], int) and isinstance(split_shape[1], int):
return split_shape[0], split_shape[1]
raise ValueError("Content of split_shape {} must be 2 integers.".format(split_shape))
raise ValueError("Split shape must be an int or a tuple of 2 integers.") | [
"def",
"_parse_split_shape",
"(",
"split_shape",
")",
":",
"if",
"isinstance",
"(",
"split_shape",
",",
"int",
")",
":",
"return",
"split_shape",
",",
"split_shape",
"if",
"isinstance",
"(",
"split_shape",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if... | Parses the parameter `split_shape`
:param split_shape: The parameter `split_shape` from class initialization
:type split_shape: int or (int, int)
:return: A tuple of n
:rtype: (int, int)
:raises: ValueError | [
"Parses",
"the",
"parameter",
"split_shape"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L212-L227 |
243,085 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | OsmSplitter._recursive_split | def _recursive_split(self, bbox, zoom_level, column, row):
"""Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in the OSM grid
:type column: int
:param row: Row in the OSM grid
:type row: int
"""
if zoom_level == self.zoom_level:
self.bbox_list.append(bbox)
self.info_list.append({'zoom_level': zoom_level,
'index_x': column,
'index_y': row})
return
bbox_partition = bbox.get_partition(2, 2)
for i, j in itertools.product(range(2), range(2)):
if self._intersects_area(bbox_partition[i][j]):
self._recursive_split(bbox_partition[i][j], zoom_level + 1, 2 * column + i, 2 * row + 1 - j) | python | def _recursive_split(self, bbox, zoom_level, column, row):
if zoom_level == self.zoom_level:
self.bbox_list.append(bbox)
self.info_list.append({'zoom_level': zoom_level,
'index_x': column,
'index_y': row})
return
bbox_partition = bbox.get_partition(2, 2)
for i, j in itertools.product(range(2), range(2)):
if self._intersects_area(bbox_partition[i][j]):
self._recursive_split(bbox_partition[i][j], zoom_level + 1, 2 * column + i, 2 * row + 1 - j) | [
"def",
"_recursive_split",
"(",
"self",
",",
"bbox",
",",
"zoom_level",
",",
"column",
",",
"row",
")",
":",
"if",
"zoom_level",
"==",
"self",
".",
"zoom_level",
":",
"self",
".",
"bbox_list",
".",
"append",
"(",
"bbox",
")",
"self",
".",
"info_list",
... | Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in the OSM grid
:type column: int
:param row: Row in the OSM grid
:type row: int | [
"Method",
"that",
"recursively",
"creates",
"bounding",
"boxes",
"of",
"OSM",
"grid",
"that",
"intersect",
"the",
"area",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L303-L325 |
243,086 | sentinel-hub/sentinelhub-py | sentinelhub/areas.py | CustomGridSplitter._parse_bbox_grid | def _parse_bbox_grid(bbox_grid):
""" Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection`
"""
if isinstance(bbox_grid, BBoxCollection):
return bbox_grid
if isinstance(bbox_grid, list):
return BBoxCollection(bbox_grid)
raise ValueError("Parameter 'bbox_grid' should be an instance of {}".format(BBoxCollection.__name__)) | python | def _parse_bbox_grid(bbox_grid):
if isinstance(bbox_grid, BBoxCollection):
return bbox_grid
if isinstance(bbox_grid, list):
return BBoxCollection(bbox_grid)
raise ValueError("Parameter 'bbox_grid' should be an instance of {}".format(BBoxCollection.__name__)) | [
"def",
"_parse_bbox_grid",
"(",
"bbox_grid",
")",
":",
"if",
"isinstance",
"(",
"bbox_grid",
",",
"BBoxCollection",
")",
":",
"return",
"bbox_grid",
"if",
"isinstance",
"(",
"bbox_grid",
",",
"list",
")",
":",
"return",
"BBoxCollection",
"(",
"bbox_grid",
")",... | Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection` | [
"Helper",
"method",
"for",
"parsing",
"bounding",
"box",
"grid",
".",
"It",
"will",
"try",
"to",
"parse",
"it",
"into",
"BBoxCollection"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L446-L455 |
243,087 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService._parse_metafiles | def _parse_metafiles(self, metafile_input):
"""
Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str)
"""
all_metafiles = AwsConstants.S2_L1C_METAFILES if self.data_source is DataSource.SENTINEL2_L1C else \
AwsConstants.S2_L2A_METAFILES
if metafile_input is None:
if self.__class__.__name__ == 'SafeProduct':
return all_metafiles
if self.__class__.__name__ == 'SafeTile':
return [metafile for metafile in all_metafiles if metafile in AwsConstants.TILE_FILES]
return []
if isinstance(metafile_input, str):
metafile_list = metafile_input.split(',')
elif isinstance(metafile_input, list):
metafile_list = metafile_input.copy()
else:
raise ValueError('metafiles parameter must be a list or a string')
metafile_list = [metafile.strip().split('.')[0] for metafile in metafile_list]
metafile_list = [metafile for metafile in metafile_list if metafile != '']
if not set(metafile_list) <= set(all_metafiles):
raise ValueError('metadata files {} must be a subset of {}'.format(metafile_list, all_metafiles))
return metafile_list | python | def _parse_metafiles(self, metafile_input):
all_metafiles = AwsConstants.S2_L1C_METAFILES if self.data_source is DataSource.SENTINEL2_L1C else \
AwsConstants.S2_L2A_METAFILES
if metafile_input is None:
if self.__class__.__name__ == 'SafeProduct':
return all_metafiles
if self.__class__.__name__ == 'SafeTile':
return [metafile for metafile in all_metafiles if metafile in AwsConstants.TILE_FILES]
return []
if isinstance(metafile_input, str):
metafile_list = metafile_input.split(',')
elif isinstance(metafile_input, list):
metafile_list = metafile_input.copy()
else:
raise ValueError('metafiles parameter must be a list or a string')
metafile_list = [metafile.strip().split('.')[0] for metafile in metafile_list]
metafile_list = [metafile for metafile in metafile_list if metafile != '']
if not set(metafile_list) <= set(all_metafiles):
raise ValueError('metadata files {} must be a subset of {}'.format(metafile_list, all_metafiles))
return metafile_list | [
"def",
"_parse_metafiles",
"(",
"self",
",",
"metafile_input",
")",
":",
"all_metafiles",
"=",
"AwsConstants",
".",
"S2_L1C_METAFILES",
"if",
"self",
".",
"data_source",
"is",
"DataSource",
".",
"SENTINEL2_L1C",
"else",
"AwsConstants",
".",
"S2_L2A_METAFILES",
"if",... | Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str) | [
"Parses",
"class",
"input",
"and",
"verifies",
"metadata",
"file",
"names",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L74-L102 |
243,088 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.get_base_url | def get_base_url(self, force_http=False):
""" Creates base URL path
:param force_http: `True` if HTTP base URL should be used and `False` otherwise
:type force_http: str
:return: base url string
:rtype: str
"""
base_url = SHConfig().aws_metadata_url.rstrip('/') if force_http else 's3:/'
aws_bucket = SHConfig().aws_s3_l1c_bucket if self.data_source is DataSource.SENTINEL2_L1C else \
SHConfig().aws_s3_l2a_bucket
return '{}/{}/'.format(base_url, aws_bucket) | python | def get_base_url(self, force_http=False):
base_url = SHConfig().aws_metadata_url.rstrip('/') if force_http else 's3:/'
aws_bucket = SHConfig().aws_s3_l1c_bucket if self.data_source is DataSource.SENTINEL2_L1C else \
SHConfig().aws_s3_l2a_bucket
return '{}/{}/'.format(base_url, aws_bucket) | [
"def",
"get_base_url",
"(",
"self",
",",
"force_http",
"=",
"False",
")",
":",
"base_url",
"=",
"SHConfig",
"(",
")",
".",
"aws_metadata_url",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"force_http",
"else",
"'s3:/'",
"aws_bucket",
"=",
"SHConfig",
"(",
")",
... | Creates base URL path
:param force_http: `True` if HTTP base URL should be used and `False` otherwise
:type force_http: str
:return: base url string
:rtype: str | [
"Creates",
"base",
"URL",
"path"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L104-L116 |
243,089 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.get_safe_type | def get_safe_type(self):
"""Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: constants.EsaSafeType
:raises: ValueError
"""
product_type = self.product_id.split('_')[1]
if product_type.startswith('MSI'):
return EsaSafeType.COMPACT_TYPE
if product_type in ['OPER', 'USER']:
return EsaSafeType.OLD_TYPE
raise ValueError('Unrecognized product type of product id {}'.format(self.product_id)) | python | def get_safe_type(self):
product_type = self.product_id.split('_')[1]
if product_type.startswith('MSI'):
return EsaSafeType.COMPACT_TYPE
if product_type in ['OPER', 'USER']:
return EsaSafeType.OLD_TYPE
raise ValueError('Unrecognized product type of product id {}'.format(self.product_id)) | [
"def",
"get_safe_type",
"(",
"self",
")",
":",
"product_type",
"=",
"self",
".",
"product_id",
".",
"split",
"(",
"'_'",
")",
"[",
"1",
"]",
"if",
"product_type",
".",
"startswith",
"(",
"'MSI'",
")",
":",
"return",
"EsaSafeType",
".",
"COMPACT_TYPE",
"i... | Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: constants.EsaSafeType
:raises: ValueError | [
"Determines",
"the",
"type",
"of",
"ESA",
"product",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L118-L133 |
243,090 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService._read_baseline_from_info | def _read_baseline_from_info(self):
"""Tries to find and return baseline number from either tileInfo or productInfo file.
:return: Baseline ID
:rtype: str
:raises: ValueError
"""
if hasattr(self, 'tile_info'):
return self.tile_info['datastrip']['id'][-5:]
if hasattr(self, 'product_info'):
return self.product_info['datastrips'][0]['id'][-5:]
raise ValueError('No info file has been obtained yet.') | python | def _read_baseline_from_info(self):
if hasattr(self, 'tile_info'):
return self.tile_info['datastrip']['id'][-5:]
if hasattr(self, 'product_info'):
return self.product_info['datastrips'][0]['id'][-5:]
raise ValueError('No info file has been obtained yet.') | [
"def",
"_read_baseline_from_info",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'tile_info'",
")",
":",
"return",
"self",
".",
"tile_info",
"[",
"'datastrip'",
"]",
"[",
"'id'",
"]",
"[",
"-",
"5",
":",
"]",
"if",
"hasattr",
"(",
"self",
... | Tries to find and return baseline number from either tileInfo or productInfo file.
:return: Baseline ID
:rtype: str
:raises: ValueError | [
"Tries",
"to",
"find",
"and",
"return",
"baseline",
"number",
"from",
"either",
"tileInfo",
"or",
"productInfo",
"file",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L149-L160 |
243,091 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.url_to_tile | def url_to_tile(url):
"""
Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, str, int)
"""
info = url.strip('/').split('/')
name = ''.join(info[-7: -4])
date = '-'.join(info[-4: -1])
return name, date, int(info[-1]) | python | def url_to_tile(url):
info = url.strip('/').split('/')
name = ''.join(info[-7: -4])
date = '-'.join(info[-4: -1])
return name, date, int(info[-1]) | [
"def",
"url_to_tile",
"(",
"url",
")",
":",
"info",
"=",
"url",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"name",
"=",
"''",
".",
"join",
"(",
"info",
"[",
"-",
"7",
":",
"-",
"4",
"]",
")",
"date",
"=",
"'-'",
".",
"joi... | Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, str, int) | [
"Extracts",
"tile",
"name",
"date",
"and",
"AWS",
"index",
"from",
"tile",
"url",
"on",
"AWS",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L163-L175 |
243,092 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.structure_recursion | def structure_recursion(self, struct, folder):
"""
From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be
downloaded and stores them into class attribute `download_list`.
:param struct: nested dictionaries representing a part of .SAFE structure
:type struct: dict
:param folder: name of folder where this structure will be saved
:type folder: str
"""
has_subfolder = False
for name, substruct in struct.items():
subfolder = os.path.join(folder, name)
if not isinstance(substruct, dict):
product_name, data_name = self._url_to_props(substruct)
if '.' in data_name:
data_type = MimeType(data_name.split('.')[-1])
data_name = data_name.rsplit('.', 1)[0]
else:
data_type = MimeType.RAW
if data_name in self.bands + self.metafiles:
self.download_list.append(DownloadRequest(url=substruct, filename=subfolder, data_type=data_type,
data_name=data_name, product_name=product_name))
else:
has_subfolder = True
self.structure_recursion(substruct, subfolder)
if not has_subfolder:
self.folder_list.append(folder) | python | def structure_recursion(self, struct, folder):
has_subfolder = False
for name, substruct in struct.items():
subfolder = os.path.join(folder, name)
if not isinstance(substruct, dict):
product_name, data_name = self._url_to_props(substruct)
if '.' in data_name:
data_type = MimeType(data_name.split('.')[-1])
data_name = data_name.rsplit('.', 1)[0]
else:
data_type = MimeType.RAW
if data_name in self.bands + self.metafiles:
self.download_list.append(DownloadRequest(url=substruct, filename=subfolder, data_type=data_type,
data_name=data_name, product_name=product_name))
else:
has_subfolder = True
self.structure_recursion(substruct, subfolder)
if not has_subfolder:
self.folder_list.append(folder) | [
"def",
"structure_recursion",
"(",
"self",
",",
"struct",
",",
"folder",
")",
":",
"has_subfolder",
"=",
"False",
"for",
"name",
",",
"substruct",
"in",
"struct",
".",
"items",
"(",
")",
":",
"subfolder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"fold... | From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be
downloaded and stores them into class attribute `download_list`.
:param struct: nested dictionaries representing a part of .SAFE structure
:type struct: dict
:param folder: name of folder where this structure will be saved
:type folder: str | [
"From",
"nested",
"dictionaries",
"representing",
".",
"SAFE",
"structure",
"it",
"recursively",
"extracts",
"all",
"the",
"files",
"that",
"need",
"to",
"be",
"downloaded",
"and",
"stores",
"them",
"into",
"class",
"attribute",
"download_list",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L194-L221 |
243,093 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.add_file_extension | def add_file_extension(filename, data_format=None, remove_path=False):
"""Joins filename and corresponding file extension if it has one.
:param filename: Name of the file without extension
:type filename: str
:param data_format: format of file, if None it will be set automatically
:type data_format: constants.MimeType or None
:param remove_path: True if the path in filename string should be removed
:type remove_path: bool
:return: Name of the file with extension
:rtype: str
"""
if data_format is None:
data_format = AwsConstants.AWS_FILES[filename]
if remove_path:
filename = filename.split('/')[-1]
if filename.startswith('datastrip'):
filename = filename.replace('*', '0')
if data_format is MimeType.RAW:
return filename
return '{}.{}'.format(filename.replace('*', ''), data_format.value) | python | def add_file_extension(filename, data_format=None, remove_path=False):
if data_format is None:
data_format = AwsConstants.AWS_FILES[filename]
if remove_path:
filename = filename.split('/')[-1]
if filename.startswith('datastrip'):
filename = filename.replace('*', '0')
if data_format is MimeType.RAW:
return filename
return '{}.{}'.format(filename.replace('*', ''), data_format.value) | [
"def",
"add_file_extension",
"(",
"filename",
",",
"data_format",
"=",
"None",
",",
"remove_path",
"=",
"False",
")",
":",
"if",
"data_format",
"is",
"None",
":",
"data_format",
"=",
"AwsConstants",
".",
"AWS_FILES",
"[",
"filename",
"]",
"if",
"remove_path",
... | Joins filename and corresponding file extension if it has one.
:param filename: Name of the file without extension
:type filename: str
:param data_format: format of file, if None it will be set automatically
:type data_format: constants.MimeType or None
:param remove_path: True if the path in filename string should be removed
:type remove_path: bool
:return: Name of the file with extension
:rtype: str | [
"Joins",
"filename",
"and",
"corresponding",
"file",
"extension",
"if",
"it",
"has",
"one",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L244-L264 |
243,094 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsService.is_early_compact_l2a | def is_early_compact_l2a(self):
"""Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool
"""
return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \
self.baseline <= '02.06' | python | def is_early_compact_l2a(self):
return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \
self.baseline <= '02.06' | [
"def",
"is_early_compact_l2a",
"(",
"self",
")",
":",
"return",
"self",
".",
"data_source",
"is",
"DataSource",
".",
"SENTINEL2_L2A",
"and",
"self",
".",
"safe_type",
"is",
"EsaSafeType",
".",
"COMPACT_TYPE",
"and",
"self",
".",
"baseline",
"<=",
"'02.06'"
] | Check if product is early version of compact L2A product
:return: True if product is early version of compact L2A product and False otherwise
:rtype: bool | [
"Check",
"if",
"product",
"is",
"early",
"version",
"of",
"compact",
"L2A",
"product"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L275-L282 |
243,095 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsProduct.get_requests | def get_requests(self):
"""
Creates product structure and returns list of files for download.
:return: List of download requests and list of empty folders that need to be created
:rtype: (list(download.DownloadRequest), list(str))
"""
self.download_list = [DownloadRequest(url=self.get_url(metafile), filename=self.get_filepath(metafile),
data_type=AwsConstants.AWS_FILES[metafile], data_name=metafile) for
metafile in self.metafiles if metafile in AwsConstants.PRODUCT_FILES]
tile_parent_folder = os.path.join(self.parent_folder, self.product_id)
for tile_info in self.product_info['tiles']:
tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info))
if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list:
tile_downloads, tile_folders = AwsTile(tile_name, date, aws_index, parent_folder=tile_parent_folder,
bands=self.bands, metafiles=self.metafiles,
data_source=self.data_source).get_requests()
self.download_list.extend(tile_downloads)
self.folder_list.extend(tile_folders)
self.sort_download_list()
return self.download_list, self.folder_list | python | def get_requests(self):
self.download_list = [DownloadRequest(url=self.get_url(metafile), filename=self.get_filepath(metafile),
data_type=AwsConstants.AWS_FILES[metafile], data_name=metafile) for
metafile in self.metafiles if metafile in AwsConstants.PRODUCT_FILES]
tile_parent_folder = os.path.join(self.parent_folder, self.product_id)
for tile_info in self.product_info['tiles']:
tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info))
if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list:
tile_downloads, tile_folders = AwsTile(tile_name, date, aws_index, parent_folder=tile_parent_folder,
bands=self.bands, metafiles=self.metafiles,
data_source=self.data_source).get_requests()
self.download_list.extend(tile_downloads)
self.folder_list.extend(tile_folders)
self.sort_download_list()
return self.download_list, self.folder_list | [
"def",
"get_requests",
"(",
"self",
")",
":",
"self",
".",
"download_list",
"=",
"[",
"DownloadRequest",
"(",
"url",
"=",
"self",
".",
"get_url",
"(",
"metafile",
")",
",",
"filename",
"=",
"self",
".",
"get_filepath",
"(",
"metafile",
")",
",",
"data_ty... | Creates product structure and returns list of files for download.
:return: List of download requests and list of empty folders that need to be created
:rtype: (list(download.DownloadRequest), list(str)) | [
"Creates",
"product",
"structure",
"and",
"returns",
"list",
"of",
"files",
"for",
"download",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L337-L358 |
243,096 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsProduct.get_data_source | def get_data_source(self):
"""The method determines data source from product ID.
:return: Data source of the product
:rtype: DataSource
:raises: ValueError
"""
product_type = self.product_id.split('_')[1]
if product_type.endswith('L1C') or product_type == 'OPER':
return DataSource.SENTINEL2_L1C
if product_type.endswith('L2A') or product_type == 'USER':
return DataSource.SENTINEL2_L2A
raise ValueError('Unknown data source of product {}'.format(self.product_id)) | python | def get_data_source(self):
product_type = self.product_id.split('_')[1]
if product_type.endswith('L1C') or product_type == 'OPER':
return DataSource.SENTINEL2_L1C
if product_type.endswith('L2A') or product_type == 'USER':
return DataSource.SENTINEL2_L2A
raise ValueError('Unknown data source of product {}'.format(self.product_id)) | [
"def",
"get_data_source",
"(",
"self",
")",
":",
"product_type",
"=",
"self",
".",
"product_id",
".",
"split",
"(",
"'_'",
")",
"[",
"1",
"]",
"if",
"product_type",
".",
"endswith",
"(",
"'L1C'",
")",
"or",
"product_type",
"==",
"'OPER'",
":",
"return",
... | The method determines data source from product ID.
:return: Data source of the product
:rtype: DataSource
:raises: ValueError | [
"The",
"method",
"determines",
"data",
"source",
"from",
"product",
"ID",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L360-L372 |
243,097 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsProduct.get_date | def get_date(self):
""" Collects sensing date of the product.
:return: Sensing date
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = self.product_id.split('_')[-2]
date = [name[1:5], name[5:7], name[7:9]]
else:
name = self.product_id.split('_')[2]
date = [name[:4], name[4:6], name[6:8]]
return '-'.join(date_part.lstrip('0') for date_part in date) | python | def get_date(self):
if self.safe_type == EsaSafeType.OLD_TYPE:
name = self.product_id.split('_')[-2]
date = [name[1:5], name[5:7], name[7:9]]
else:
name = self.product_id.split('_')[2]
date = [name[:4], name[4:6], name[6:8]]
return '-'.join(date_part.lstrip('0') for date_part in date) | [
"def",
"get_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"safe_type",
"==",
"EsaSafeType",
".",
"OLD_TYPE",
":",
"name",
"=",
"self",
".",
"product_id",
".",
"split",
"(",
"'_'",
")",
"[",
"-",
"2",
"]",
"date",
"=",
"[",
"name",
"[",
"1",
":... | Collects sensing date of the product.
:return: Sensing date
:rtype: str | [
"Collects",
"sensing",
"date",
"of",
"the",
"product",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L374-L386 |
243,098 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsProduct.get_product_url | def get_product_url(self, force_http=False):
"""
Creates base url of product location on AWS.
:param force_http: True if HTTP base URL should be used and False otherwise
:type force_http: str
:return: url of product location
:rtype: str
"""
base_url = self.base_http_url if force_http else self.base_url
return '{}products/{}/{}'.format(base_url, self.date.replace('-', '/'), self.product_id) | python | def get_product_url(self, force_http=False):
base_url = self.base_http_url if force_http else self.base_url
return '{}products/{}/{}'.format(base_url, self.date.replace('-', '/'), self.product_id) | [
"def",
"get_product_url",
"(",
"self",
",",
"force_http",
"=",
"False",
")",
":",
"base_url",
"=",
"self",
".",
"base_http_url",
"if",
"force_http",
"else",
"self",
".",
"base_url",
"return",
"'{}products/{}/{}'",
".",
"format",
"(",
"base_url",
",",
"self",
... | Creates base url of product location on AWS.
:param force_http: True if HTTP base URL should be used and False otherwise
:type force_http: str
:return: url of product location
:rtype: str | [
"Creates",
"base",
"url",
"of",
"product",
"location",
"on",
"AWS",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L405-L415 |
243,099 | sentinel-hub/sentinelhub-py | sentinelhub/aws.py | AwsTile.parse_tile_name | def parse_tile_name(name):
"""
Parses and verifies tile name.
:param name: class input parameter `tile_name`
:type name: str
:return: parsed tile name
:rtype: str
"""
tile_name = name.lstrip('T0')
if len(tile_name) == 4:
tile_name = '0' + tile_name
if len(tile_name) != 5:
raise ValueError('Invalid tile name {}'.format(name))
return tile_name | python | def parse_tile_name(name):
tile_name = name.lstrip('T0')
if len(tile_name) == 4:
tile_name = '0' + tile_name
if len(tile_name) != 5:
raise ValueError('Invalid tile name {}'.format(name))
return tile_name | [
"def",
"parse_tile_name",
"(",
"name",
")",
":",
"tile_name",
"=",
"name",
".",
"lstrip",
"(",
"'T0'",
")",
"if",
"len",
"(",
"tile_name",
")",
"==",
"4",
":",
"tile_name",
"=",
"'0'",
"+",
"tile_name",
"if",
"len",
"(",
"tile_name",
")",
"!=",
"5",
... | Parses and verifies tile name.
:param name: class input parameter `tile_name`
:type name: str
:return: parsed tile name
:rtype: str | [
"Parses",
"and",
"verifies",
"tile",
"name",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L485-L499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.