INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 | 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 func... |
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... | 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.
... |
Get requested data either by downloading it or by reading it from the disk (if it
was previously downloaded and saved).
:param save_data: flag to turn on/off saving of data to disk. Default is ``False``.
:type save_data: bool
:param redownload: if ``True``, download again the requested ... | def get_data(self, *, save_data=False, data_filter=None, redownload=False, max_threads=None,
raise_download_errors=True):
"""
Get requested data either by downloading it or by reading it from the disk (if it
was previously downloaded and saved).
:param save_data: flag t... |
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 f... | 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 a... |
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: li... | 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... |
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 do... | 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 down... |
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 | 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 ... |
Adds already saved data that was not redownloaded to the requested data list. | 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 da... |
Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter. | def _check_custom_url_parameters(self):
"""Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter.
"""
for param in self.custom_url_params:
if param not in CustomUrlParam:
raise ValueError('P... |
Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param reset_wfs_iterator: When re-running the method this flag is used to reset/keep existing ``wfs_iterator``
(i.e. instance of ``... | def create_request(self, reset_wfs_iterator=False):
"""Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param reset_wfs_iterator: When re-running the method this flag is used to reset/... |
Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage. | def create_request(self):
"""Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
"""
fis_service = FisService(instance_id=self.instance_id)
self.download_list = fis_service.... |
Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter. | def _check_custom_url_parameters(self):
"""Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter.
"""
for param in self.custom_url_params.keys():
if param is not CustomUrlParam.TRANSPARENT:
... |
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 ``Geoped... | 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 e... |
Helper function for parsing Geopedia layer name. If WMS name is required and wrong form is given it will
return a string with 'ttl' at the beginning. (WMS name can also start with something else, e.g. only 't'
instead 'ttl', therefore anything else is also allowed.) Otherwise it will parse it into a num... | def _parse_layer(layer, return_wms_name=False):
""" Helper function for parsing Geopedia layer name. If WMS name is required and wrong form is given it will
return a string with 'ttl' at the beginning. (WMS name can also start with something else, e.g. only 't'
instead 'ttl', therefore anything ... |
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
... | 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... |
Starts a new session and calculates when the new session will end. If username and password are provided
it will also make login. | 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._... |
Private method that makes 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))
... |
Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest) | def get_request(self, request):
"""Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest)
"""
request.layer = self._parse_layer(request.layer, r... |
Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest) | def get_request(self, request):
"""Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest)
"""
return [DownloadRequest(url=self._get_url(item),
... |
Collects data from Geopedia layer and returns list of features | 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,
... |
Creates a 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(GeopediaSer... |
Retrieves a new page of features from Geopedia | 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'... |
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) | 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... |
Create parent folder for input filename recursively
:param filename: input filename
:type filename: str
:raises: error if folder cannot be created | 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) |
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 | 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):
... |
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 | 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: ... |
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 | 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.p... |
Get download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param request: OGC-type request with specified bounding box, time interval, and cloud coverage for specific
product.
... | def get_request(self, request):
""" Get download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param request: OGC-type request with specified bounding box, time interval, and cloud coverage for... |
Returns filename
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{geometry}_{crs}_{st... | def get_filename(request, geometry):
""" Returns filename
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
... |
Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float) | 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 |
Returns a new BBox object where x and y coordinates are switched
:return: New BBox object with switched coordinates
:rtype: BBox | 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) |
Transforms BBox from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Bounding box in target CRS
:rtype: BBox | 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, ne... |
Changes both BBox dimensions (width and height) by a percentage of size of each dimension. If number is
negative, the size will decrease. Returns a new instance of BBox object.
:param buffer: A percentage of BBox size change
:type buffer: float
:return: A new bounding box of buffered si... | def buffer(self, buffer):
""" Changes both BBox dimensions (width and height) by a percentage of size of each dimension. If number is
negative, the size will decrease. Returns a new instance of BBox object.
:param buffer: A percentage of BBox size change
:type buffer: float
:ret... |
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))... | 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: boo... |
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) | 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 representin... |
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... | 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 n... |
Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float | 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, flo... |
Converts the input bbox representation (see the constructor docstring for a list of valid representations)
into a flat tuple
:param bbox: A bbox in one of 7 forms listed in the class description.
:return: A flat tuple of size
:raises: TypeError | def _to_tuple(bbox):
""" Converts the input bbox representation (see the constructor docstring for a list of valid representations)
into a flat tuple
:param bbox: A bbox in one of 7 forms listed in the class description.
:return: A flat tuple of size
:raises: TypeError
"... |
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 | 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 l... |
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) | 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() ... |
Returns a new Geometry object where x and y coordinates are switched
:return: New Geometry object with switched coordinates
:rtype: Geometry | 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) |
Transforms Geometry from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Geometry in target CRS
:rtype: Geometry | 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 se... |
Parses given geometry into shapely object
:param geometry:
:return: Shapely polygon or multipolygon
:rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
:raises TypeError | 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):
... |
Transforms BBoxCollection from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: BBoxCollection in target CRS
:rtype: BBoxCollection | 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.bbo... |
Creates a multipolygon of bounding box polygons | def _get_geometry(self):
""" Creates a multipolygon of bounding box polygons
"""
return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list]) |
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... | 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
... |
Helper method for parsing a list of bounding boxes | 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-emp... |
Read data from JPEG2000 file
:param filename: name of JPEG2000 file to be read
:type filename: str
:return: data stored in JPEG2000 file | 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... |
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 | 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, '... |
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: ... | 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 optio... |
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 | 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... |
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 | 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... |
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 | 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``
... |
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 | 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 ``;``
... |
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 | 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) |
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 | 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 = ... |
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
:rty... | 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_dept... |
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 ... | 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 redownlo... |
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 | 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 redownlo... |
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 | 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... |
Executes download request
:param request: A request
:type request: DownloadRequest
:return: Response of the request
:rtype: requests.Response | def _do_request(request):
""" Executes download request
:param request: A request
:type request: DownloadRequest
:return: Response of the request
:rtype: requests.Response
"""
if request.request_type is RequestType.GET:
return requests.get(request.url, headers=request.headers)
if... |
Executes download request from AWS service
:param request: A request
:type request: DownloadRequest
:return: Response of the request
:rtype: dict
:raises: AwsDownloadFailedException, ValueError | def _do_aws_request(request):
""" Executes download request from AWS service
:param request: A request
:type request: DownloadRequest
:return: Response of the request
:rtype: dict
:raises: AwsDownloadFailedException, ValueError
"""
if SHConfig().aws_access_key_id and SHConfig().aws_secre... |
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 | 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:
... |
Checks if exception was raised because of too many executed requests. (This is a temporal solution and
will be changed in later package versions.)
:param exception: Exception raised during download
:type exception: Exception
:return: True if exception is caused because too many requests were executed a... | def _request_limit_reached(exception):
""" Checks if exception was raised because of too many executed requests. (This is a temporal solution and
will be changed in later package versions.)
:param exception: Exception raised during download
:type exception: Exception
:return: True if exception is c... |
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 | 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
... |
Save data to disk, if requested by the user
:param request: Download request
:type request: DownloadRequest
:param response_content: content of the download response
:type response_content: bytes | def _save_if_needed(request, response_content):
""" Save data to disk, if requested by the user
:param request: Download request
:type request: DownloadRequest
:param response_content: content of the download response
:type response_content: bytes
"""
if request.save_response:
file_p... |
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... | 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: const... |
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
... | 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
... |
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. Def... | 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... |
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 | 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... |
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 | 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 Fals... |
Get basic information about image tile
: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
:return: dictionary with info provided by Opensearch REST service or ``None`` if such til... | def get_tile_info_id(tile_id):
""" Get basic information about image tile
: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
:return: dictionary with info provided by Opensear... |
Get basic information about image tile
:param tile: tile name (e.g. ``'T10UEV'``)
:type tile: str
:param time: A single date or a time interval, times have to be in ISO 8601 string
:type time: str or (str, str)
:param aws_index: index of tile on AWS
:type aws_index: int or None
:param all_t... | def get_tile_info(tile, time, aws_index=None, all_tiles=False):
""" Get basic information about image tile
:param tile: tile name (e.g. ``'T10UEV'``)
:type tile: str
:param time: A single date or a time interval, times have to be in ISO 8601 string
:type time: str or (str, str)
:param aws_index... |
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 coverag... | 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... |
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 cov... | 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)
:... |
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
... | 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.
... |
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
:para... | 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 bbo... |
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 | 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: bo... |
Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest) | 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... |
Describes a structure inside tile folder of ESA product .SAFE structure
:return: nested dictionaries representing .SAFE structure
:rtype: dict | 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] = {}
... |
:return: list of datastrips folder names and urls from productInfo.json file
:rtype: list((str, str)) | def get_datastrip_list(self):
"""
:return: list of datastrips folder names and urls from productInfo.json file
:rtype: list((str, str))
"""
datastrips = self.product_info['datastrips']
return [(self.get_datastrip_name(datastrip['id']), self.base_url + datastrip['path'])
... |
:param datastrip: name of datastrip
:type datastrip: str
:return: name of datastrip folder
:rtype: str | def get_datastrip_name(self, datastrip):
"""
:param datastrip: name of datastrip
:type datastrip: str
:return: name of datastrip folder
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
return datastrip
return '_'.join(datastrip.split(... |
:param datastrip_folder: name of datastrip folder
:type: str
:return: name of datastrip metadata file
:rtype: str | def get_datastrip_metadata_name(self, datastrip_folder):
"""
:param datastrip_folder: name of datastrip folder
:type: str
:return: name of datastrip metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(datastrip_fo... |
:return: name of product metadata file
:rtype: str | def get_product_metadata_name(self):
"""
:return: name of product metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.product_id, 'MTD', 'SAFL1C')
else:
name = 'MTD_{}'.format(self.product_id.split('_')[1... |
:return: name of the report file of L2A products
:rtype: str | def get_report_name(self):
"""
:return: name of the report file of L2A products
:rtype: str
"""
return '{}_{}_report.{}'.format(self.product_id, self.get_report_time(), MimeType.XML.value) |
Returns time when the L2A processing started and reports was created.
:return: String in a form YYYYMMDDTHHMMSS
:rtype: str | def get_report_time(self):
""" Returns time when the L2A processing started and reports was created.
:return: String in a form YYYYMMDDTHHMMSS
:rtype: str
"""
tree = get_xml(self.get_url(AwsConstants.REPORT))
try:
timestamp = tree.find('check/inspection').att... |
Describes a structure inside tile folder of ESA product .SAFE structure.
:return: nested dictionaries representing .SAFE structure
:rtype: dict | def get_safe_struct(self):
"""
Describes a structure inside tile folder of ESA product .SAFE structure.
:return: nested dictionaries representing .SAFE structure
:rtype: dict
"""
# pylint: disable=too-many-branches
safe = {}
main_folder = self.get_main_fo... |
Creates ESA tile ID
:return: ESA tile ID
:rtype: str | 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'
... |
:return: name of tile metadata file
:rtype: str | def get_tile_metadata_name(self):
"""
:return: name of tile metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.tile_id, 'MTD', delete_end=True)
else:
name = 'MTD_TL'
return '{}.xml'.format(name) |
:param band: band name
:type band: str
:param resolution: Specifies the resolution in case of Sentinel-2 L2A products
:type resolution: str or None
:return: name of band image file
:rtype: str | def get_img_name(self, band, resolution=None):
"""
:param band: band name
:type band: str
:param resolution: Specifies the resolution in case of Sentinel-2 L2A products
:type resolution: str or None
:return: name of band image file
:rtype: str
"""
... |
:param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:param data_format: format of the file
:type data_format: MimeType
:return: name of gml file
:rtype: str | def get_qi_name(self, qi_type, band='B00', data_format=MimeType.GML):
"""
:param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:param data_format: format of the file
:type data_format: MimeType
:return: name o... |
Returns .SAFE name of full resolution L1C preview
:return: name of preview file
:rtype: str | def get_preview_name(self):
"""Returns .SAFE name of full resolution L1C preview
:return: name of preview file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.tile_id, AwsConstants.PVI, delete_end=True)
else:
name ... |
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 | 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.P... |
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 ... | 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 splitte... |
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`
... | 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 b... |
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 | 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)
... |
Reduces sizes of bounding boxes | 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] |
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 | 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 i... |
This method makes the split | def _make_split(self):
""" This method makes the split
"""
columns, rows = self.split_shape
bbox_partition = self.area_bbox.get_partition(columns, rows)
self.bbox_list = []
self.info_list = []
for i, j in itertools.product(range(columns), range(rows)):
... |
This method makes the split | def _make_split(self, ):
"""This method makes the split
"""
self.area_bbox = self.get_area_bbox(CRS.POP_WEB)
self._check_area_bbox()
self.bbox_list = []
self.info_list = []
self._recursive_split(self.get_world_bbox(), 0, 0, 0)
for i, bbox in enumerate(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.