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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.requestOpenOrders | def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | python | def requestOpenOrders(self, all_clients=False):
"""
Request open orders - loads up orders that wasn't created using this session
"""
if all_clients:
self.ibConn.reqAllOpenOrders()
self.ibConn.reqOpenOrders() | [
"def",
"requestOpenOrders",
"(",
"self",
",",
"all_clients",
"=",
"False",
")",
":",
"if",
"all_clients",
":",
"self",
".",
"ibConn",
".",
"reqAllOpenOrders",
"(",
")",
"self",
".",
"ibConn",
".",
"reqOpenOrders",
"(",
")"
] | Request open orders - loads up orders that wasn't created using this session | [
"Request",
"open",
"orders",
"-",
"loads",
"up",
"orders",
"that",
"wasn",
"t",
"created",
"using",
"this",
"session"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1793-L1799 | train | 224,000 |
ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.cancelHistoricalData | def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId = self.tickerId(contract.m_symbol)
tickerId = self.tickerId(self.contractString(contract))
self.ibConn.cancelHistoricalData(tickerId=tickerId) | python | def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId = self.tickerId(contract.m_symbol)
tickerId = self.tickerId(self.contractString(contract))
self.ibConn.cancelHistoricalData(tickerId=tickerId) | [
"def",
"cancelHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
")",
":",
"if",
"contracts",
"==",
"None",
":",
"contracts",
"=",
"list",
"(",
"self",
".",
"contracts",
".",
"values",
"(",
")",
")",
"elif",
"not",
"isinstance",
"(",
"contracts... | cancel historical data stream | [
"cancel",
"historical",
"data",
"stream"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1931-L1941 | train | 224,001 |
ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.getConId | def getConId(self, contract_identifier):
""" Get contracts conId """
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | python | def getConId(self, contract_identifier):
""" Get contracts conId """
details = self.contractDetails(contract_identifier)
if len(details["contracts"]) > 1:
return details["m_underConId"]
return details["m_summary"]["m_conId"] | [
"def",
"getConId",
"(",
"self",
",",
"contract_identifier",
")",
":",
"details",
"=",
"self",
".",
"contractDetails",
"(",
"contract_identifier",
")",
"if",
"len",
"(",
"details",
"[",
"\"contracts\"",
"]",
")",
">",
"1",
":",
"return",
"details",
"[",
"\"... | Get contracts conId | [
"Get",
"contracts",
"conId"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1974-L1979 | train | 224,002 |
ranaroussi/ezibpy | ezibpy/ezibpy.py | ezIBpy.createComboContract | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
""" Used for ComboLegs. Expecting list of legs """
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(contract_tuple, comboLegs=legs)
return contract | python | def createComboContract(self, symbol, legs, currency="USD", exchange=None):
""" Used for ComboLegs. Expecting list of legs """
exchange = legs[0].m_exchange if exchange is None else exchange
contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
contract = self.createContract(contract_tuple, comboLegs=legs)
return contract | [
"def",
"createComboContract",
"(",
"self",
",",
"symbol",
",",
"legs",
",",
"currency",
"=",
"\"USD\"",
",",
"exchange",
"=",
"None",
")",
":",
"exchange",
"=",
"legs",
"[",
"0",
"]",
".",
"m_exchange",
"if",
"exchange",
"is",
"None",
"else",
"exchange",... | Used for ComboLegs. Expecting list of legs | [
"Used",
"for",
"ComboLegs",
".",
"Expecting",
"list",
"of",
"legs"
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L2008-L2013 | train | 224,003 |
ranaroussi/ezibpy | ezibpy/utils.py | order_to_dict | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | python | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | [
"def",
"order_to_dict",
"(",
"order",
")",
":",
"default",
"=",
"Order",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"order",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",
"default"... | Convert an IBPy Order object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Order",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L204-L207 | train | 224,004 |
ranaroussi/ezibpy | ezibpy/utils.py | contract_to_dict | def contract_to_dict(contract):
"""Convert an IBPy Contract object to a dict containing any non-default values."""
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | python | def contract_to_dict(contract):
"""Convert an IBPy Contract object to a dict containing any non-default values."""
default = Contract()
return {field: val for field, val in vars(contract).items() if val != getattr(default, field, None)} | [
"def",
"contract_to_dict",
"(",
"contract",
")",
":",
"default",
"=",
"Contract",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"contract",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",... | Convert an IBPy Contract object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Contract",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | 1a9d4bf52018abd2a01af7c991d7cf00cda53e0c | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L212-L215 | train | 224,005 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_code | def _get_utm_code(zone, direction):
""" Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str
"""
dir_dict = {_Direction.NORTH: '6', _Direction.SOUTH: '7'}
return '{}{}{}'.format('32', dir_dict[direction], str(zone).zfill(2)) | python | def _get_utm_code(zone, direction):
""" Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str
"""
dir_dict = {_Direction.NORTH: '6', _Direction.SOUTH: '7'}
return '{}{}{}'.format('32', dir_dict[direction], str(zone).zfill(2)) | [
"def",
"_get_utm_code",
"(",
"zone",
",",
"direction",
")",
":",
"dir_dict",
"=",
"{",
"_Direction",
".",
"NORTH",
":",
"'6'",
",",
"_Direction",
".",
"SOUTH",
":",
"'7'",
"}",
"return",
"'{}{}{}'",
".",
"format",
"(",
"'32'",
",",
"dir_dict",
"[",
"di... | Get UTM code given a zone and direction
Direction is encoded as NORTH=6, SOUTH=7, while zone is the UTM zone number zero-padded.
For instance, the code 32604 is returned for zone number 4, north direction.
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum
:return: UTM code
:rtype: str | [
"Get",
"UTM",
"code",
"given",
"a",
"zone",
"and",
"direction"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L225-L239 | train | 224,006 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _get_utm_name_value_pair | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
""" Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str
"""
name = 'UTM_{}{}'.format(zone, direction.value)
epsg = _get_utm_code(zone, direction)
return name, epsg | python | def _get_utm_name_value_pair(zone, direction=_Direction.NORTH):
""" Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str
"""
name = 'UTM_{}{}'.format(zone, direction.value)
epsg = _get_utm_code(zone, direction)
return name, epsg | [
"def",
"_get_utm_name_value_pair",
"(",
"zone",
",",
"direction",
"=",
"_Direction",
".",
"NORTH",
")",
":",
"name",
"=",
"'UTM_{}{}'",
".",
"format",
"(",
"zone",
",",
"direction",
".",
"value",
")",
"epsg",
"=",
"_get_utm_code",
"(",
"zone",
",",
"direct... | Get name and code for UTM coordinates
:param zone: UTM zone number
:type zone: int
:param direction: Direction enum type
:type direction: Enum, optional (default=NORTH)
:return: Name and code of UTM coordinates
:rtype: str, str | [
"Get",
"name",
"and",
"code",
"for",
"UTM",
"coordinates"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L242-L254 | train | 224,007 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _crs_parser | def _crs_parser(cls, value):
""" Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS
"""
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
parsed_value = parsed_value.strip('epsgEPSG: ')
return super(_BaseCRS, cls).__new__(cls, parsed_value) | python | def _crs_parser(cls, value):
""" Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS
"""
parsed_value = value
if isinstance(parsed_value, int):
parsed_value = str(parsed_value)
if isinstance(parsed_value, str):
parsed_value = parsed_value.strip('epsgEPSG: ')
return super(_BaseCRS, cls).__new__(cls, parsed_value) | [
"def",
"_crs_parser",
"(",
"cls",
",",
"value",
")",
":",
"parsed_value",
"=",
"value",
"if",
"isinstance",
"(",
"parsed_value",
",",
"int",
")",
":",
"parsed_value",
"=",
"str",
"(",
"parsed_value",
")",
"if",
"isinstance",
"(",
"parsed_value",
",",
"str"... | Parses user input for class CRS
:param cls: class object
:param value: user input for CRS
:type value: str, int or CRS | [
"Parses",
"user",
"input",
"for",
"class",
"CRS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L327-L339 | train | 224,008 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_wfs_typename | def get_wfs_typename(cls, data_source):
""" Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str
"""
is_eocloud = SHConfig().is_eocloud_ogc_url()
return {
cls.SENTINEL2_L1C: 'S2.TILE',
cls.SENTINEL2_L2A: 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2',
cls.SENTINEL1_IW: 'S1.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW: 'S1_EW.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW_SH: 'S1_EW_SH.TILE' if is_eocloud else 'DSS3',
cls.DEM: 'DSS4',
cls.MODIS: 'DSS5',
cls.LANDSAT8: 'L8.TILE' if is_eocloud else 'DSS6',
# eocloud sources only:
cls.LANDSAT5: 'L5.TILE',
cls.LANDSAT7: 'L7.TILE',
cls.SENTINEL3: 'S3.TILE',
cls.SENTINEL5P: 'S5p_L2.TILE',
cls.ENVISAT_MERIS: 'ENV.TILE',
cls.SENTINEL2_L3B: 'SEN4CAP_S2L3B.TILE',
cls.LANDSAT8_L2A: 'SEN4CAP_L8L2A.TILE'
}[data_source] | python | def get_wfs_typename(cls, data_source):
""" Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str
"""
is_eocloud = SHConfig().is_eocloud_ogc_url()
return {
cls.SENTINEL2_L1C: 'S2.TILE',
cls.SENTINEL2_L2A: 'SEN4CAP_S2L2A.TILE' if is_eocloud else 'DSS2',
cls.SENTINEL1_IW: 'S1.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW: 'S1_EW.TILE' if is_eocloud else 'DSS3',
cls.SENTINEL1_EW_SH: 'S1_EW_SH.TILE' if is_eocloud else 'DSS3',
cls.DEM: 'DSS4',
cls.MODIS: 'DSS5',
cls.LANDSAT8: 'L8.TILE' if is_eocloud else 'DSS6',
# eocloud sources only:
cls.LANDSAT5: 'L5.TILE',
cls.LANDSAT7: 'L7.TILE',
cls.SENTINEL3: 'S3.TILE',
cls.SENTINEL5P: 'S5p_L2.TILE',
cls.ENVISAT_MERIS: 'ENV.TILE',
cls.SENTINEL2_L3B: 'SEN4CAP_S2L3B.TILE',
cls.LANDSAT8_L2A: 'SEN4CAP_L8L2A.TILE'
}[data_source] | [
"def",
"get_wfs_typename",
"(",
"cls",
",",
"data_source",
")",
":",
"is_eocloud",
"=",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"return",
"{",
"cls",
".",
"SENTINEL2_L1C",
":",
"'S2.TILE'",
",",
"cls",
".",
"SENTINEL2_L2A",
":",
"'SEN4CAP_... | Maps data source to string identifier for WFS
:param data_source: One of the supported data sources
:type: DataSource
:return: Product identifier for WFS
:rtype: str | [
"Maps",
"data",
"source",
"to",
"string",
"identifier",
"for",
"WFS"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L140-L166 | train | 224,009 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.is_uswest_source | def is_uswest_source(self):
"""Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool
"""
return not SHConfig().is_eocloud_ogc_url() and self.value[0] in [_Source.LANDSAT8, _Source.MODIS, _Source.DEM] | python | def is_uswest_source(self):
"""Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool
"""
return not SHConfig().is_eocloud_ogc_url() and self.value[0] in [_Source.LANDSAT8, _Source.MODIS, _Source.DEM] | [
"def",
"is_uswest_source",
"(",
"self",
")",
":",
"return",
"not",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
"and",
"self",
".",
"value",
"[",
"0",
"]",
"in",
"[",
"_Source",
".",
"LANDSAT8",
",",
"_Source",
".",
"MODIS",
",",
"_Source... | Checks if data source via Sentinel Hub services is available at US West server
Example: ``DataSource.LANDSAT8.is_uswest_source()`` or ``DataSource.is_uswest_source(DataSource.LANDSAT8)``
:param self: One of the supported data sources
:type self: DataSource
:return: ``True`` if data source exists at US West server and ``False`` otherwise
:rtype: bool | [
"Checks",
"if",
"data",
"source",
"via",
"Sentinel",
"Hub",
"services",
"is",
"available",
"at",
"US",
"West",
"server"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L192-L202 | train | 224,010 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | DataSource.get_available_sources | def get_available_sources(cls):
""" Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource)
"""
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL2_L3B, cls.SENTINEL1_IW, cls.SENTINEL1_EW,
cls.SENTINEL1_EW_SH, cls.SENTINEL3, cls.SENTINEL5P, cls.LANDSAT5, cls.LANDSAT7, cls.LANDSAT8,
cls.LANDSAT8_L2A, cls.ENVISAT_MERIS]
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL1_IW, cls.SENTINEL1_EW, cls.SENTINEL1_EW_SH, cls.DEM,
cls.MODIS, cls.LANDSAT8] | python | def get_available_sources(cls):
""" Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource)
"""
if SHConfig().is_eocloud_ogc_url():
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL2_L3B, cls.SENTINEL1_IW, cls.SENTINEL1_EW,
cls.SENTINEL1_EW_SH, cls.SENTINEL3, cls.SENTINEL5P, cls.LANDSAT5, cls.LANDSAT7, cls.LANDSAT8,
cls.LANDSAT8_L2A, cls.ENVISAT_MERIS]
return [cls.SENTINEL2_L1C, cls.SENTINEL2_L2A, cls.SENTINEL1_IW, cls.SENTINEL1_EW, cls.SENTINEL1_EW_SH, cls.DEM,
cls.MODIS, cls.LANDSAT8] | [
"def",
"get_available_sources",
"(",
"cls",
")",
":",
"if",
"SHConfig",
"(",
")",
".",
"is_eocloud_ogc_url",
"(",
")",
":",
"return",
"[",
"cls",
".",
"SENTINEL2_L1C",
",",
"cls",
".",
"SENTINEL2_L2A",
",",
"cls",
".",
"SENTINEL2_L3B",
",",
"cls",
".",
"... | Returns which data sources are available for configured Sentinel Hub OGC URL
:return: List of available data sources
:rtype: list(sentinelhub.DataSource) | [
"Returns",
"which",
"data",
"sources",
"are",
"available",
"for",
"configured",
"Sentinel",
"Hub",
"OGC",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L205-L216 | train | 224,011 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | _BaseCRS.get_utm_from_wgs84 | def get_utm_from_wgs84(lng, lat):
""" Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple
"""
_, _, zone, _ = utm.from_latlon(lat, lng)
direction = 'N' if lat >= 0 else 'S'
return CRS['UTM_{}{}'.format(str(zone), direction)] | python | def get_utm_from_wgs84(lng, lat):
""" Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple
"""
_, _, zone, _ = utm.from_latlon(lat, lng)
direction = 'N' if lat >= 0 else 'S'
return CRS['UTM_{}{}'.format(str(zone), direction)] | [
"def",
"get_utm_from_wgs84",
"(",
"lng",
",",
"lat",
")",
":",
"_",
",",
"_",
",",
"zone",
",",
"_",
"=",
"utm",
".",
"from_latlon",
"(",
"lat",
",",
"lng",
")",
"direction",
"=",
"'N'",
"if",
"lat",
">=",
"0",
"else",
"'S'",
"return",
"CRS",
"["... | Convert from WGS84 to UTM coordinate system
:param lng: Longitude
:type lng: float
:param lat: Latitude
:type lat: float
:return: UTM coordinates
:rtype: tuple | [
"Convert",
"from",
"WGS84",
"to",
"UTM",
"coordinate",
"system"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L263-L275 | train | 224,012 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | CustomUrlParam.has_value | def has_value(cls, value):
""" Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool
"""
return any(value.lower() == item.value.lower() for item in cls) | python | def has_value(cls, value):
""" Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool
"""
return any(value.lower() == item.value.lower() for item in cls) | [
"def",
"has_value",
"(",
"cls",
",",
"value",
")",
":",
"return",
"any",
"(",
"value",
".",
"lower",
"(",
")",
"==",
"item",
".",
"value",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"cls",
")"
] | Tests whether CustomUrlParam contains a constant defined with a string `value`
:param value: The string representation of the enum constant
:type value: str
:return: `True` if there exists a constant with a string value `value`, `False` otherwise
:rtype: bool | [
"Tests",
"whether",
"CustomUrlParam",
"contains",
"a",
"constant",
"defined",
"with",
"a",
"string",
"value"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L367-L375 | train | 224,013 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.canonical_extension | def canonical_extension(fmt_ext):
""" Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str
"""
if MimeType.has_value(fmt_ext):
return fmt_ext
try:
return {
'tif': MimeType.TIFF.value,
'jpeg': MimeType.JPG.value,
'hdf5': MimeType.HDF.value,
'h5': MimeType.HDF.value
}[fmt_ext]
except KeyError:
raise ValueError('Data format .{} is not supported'.format(fmt_ext)) | python | def canonical_extension(fmt_ext):
""" Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str
"""
if MimeType.has_value(fmt_ext):
return fmt_ext
try:
return {
'tif': MimeType.TIFF.value,
'jpeg': MimeType.JPG.value,
'hdf5': MimeType.HDF.value,
'h5': MimeType.HDF.value
}[fmt_ext]
except KeyError:
raise ValueError('Data format .{} is not supported'.format(fmt_ext)) | [
"def",
"canonical_extension",
"(",
"fmt_ext",
")",
":",
"if",
"MimeType",
".",
"has_value",
"(",
"fmt_ext",
")",
":",
"return",
"fmt_ext",
"try",
":",
"return",
"{",
"'tif'",
":",
"MimeType",
".",
"TIFF",
".",
"value",
",",
"'jpeg'",
":",
"MimeType",
"."... | Canonical extension of file format extension
Converts the format extension fmt_ext into the canonical extension for that format. For example,
``canonical_extension('tif') == 'tiff'``. Here we agree that the canonical extension for format F is F.value
:param fmt_ext: A string representing an extension (e.g. ``'txt'``, ``'png'``, etc.)
:type fmt_ext: str
:return: The canonical form of the extension (e.g. if ``fmt_ext='tif'`` then we return ``'tiff'``)
:rtype: str | [
"Canonical",
"extension",
"of",
"file",
"format",
"extension"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L424-L445 | train | 224,014 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_image_format | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f, MimeType.PNG,
MimeType.JP2, MimeType.JPG]) | python | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f, MimeType.PNG,
MimeType.JP2, MimeType.JPG]) | [
"def",
"is_image_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
",",
"MimeType",
".",
"PNG",
",... | Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L447-L458 | train | 224,015 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.is_tiff_format | def is_tiff_format(self):
""" Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]) | python | def is_tiff_format(self):
""" Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool
"""
return self in frozenset([MimeType.TIFF, MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]) | [
"def",
"is_tiff_format",
"(",
"self",
")",
":",
"return",
"self",
"in",
"frozenset",
"(",
"[",
"MimeType",
".",
"TIFF",
",",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
")"
] | Checks whether file format is a TIFF image format
Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
:rtype: bool | [
"Checks",
"whether",
"file",
"format",
"is",
"a",
"TIFF",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L460-L470 | train | 224,016 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_string | def get_string(self):
""" Get file format as string
:return: String describing the file format
:rtype: str
"""
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
return 'image/jpeg2000'
if self in [MimeType.RAW, MimeType.REQUESTS_RESPONSE]:
return self.value
return mimetypes.types_map['.' + self.value] | python | def get_string(self):
""" Get file format as string
:return: String describing the file format
:rtype: str
"""
if self in [MimeType.TIFF_d8, MimeType.TIFF_d16, MimeType.TIFF_d32f]:
return 'image/{}'.format(self.value)
if self is MimeType.JP2:
return 'image/jpeg2000'
if self in [MimeType.RAW, MimeType.REQUESTS_RESPONSE]:
return self.value
return mimetypes.types_map['.' + self.value] | [
"def",
"get_string",
"(",
"self",
")",
":",
"if",
"self",
"in",
"[",
"MimeType",
".",
"TIFF_d8",
",",
"MimeType",
".",
"TIFF_d16",
",",
"MimeType",
".",
"TIFF_d32f",
"]",
":",
"return",
"'image/{}'",
".",
"format",
"(",
"self",
".",
"value",
")",
"if",... | Get file format as string
:return: String describing the file format
:rtype: str | [
"Get",
"file",
"format",
"as",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L483-L495 | train | 224,017 |
sentinel-hub/sentinelhub-py | sentinelhub/constants.py | MimeType.get_expected_max_value | def get_expected_max_value(self):
""" Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError
"""
try:
return {
MimeType.TIFF: 65535,
MimeType.TIFF_d8: 255,
MimeType.TIFF_d16: 65535,
MimeType.TIFF_d32f: 1.0,
MimeType.PNG: 255,
MimeType.JPG: 255,
MimeType.JP2: 10000
}[self]
except IndexError:
raise ValueError('Type {} is not supported by this method'.format(self)) | python | def get_expected_max_value(self):
""" Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError
"""
try:
return {
MimeType.TIFF: 65535,
MimeType.TIFF_d8: 255,
MimeType.TIFF_d16: 65535,
MimeType.TIFF_d32f: 1.0,
MimeType.PNG: 255,
MimeType.JPG: 255,
MimeType.JP2: 10000
}[self]
except IndexError:
raise ValueError('Type {} is not supported by this method'.format(self)) | [
"def",
"get_expected_max_value",
"(",
"self",
")",
":",
"try",
":",
"return",
"{",
"MimeType",
".",
"TIFF",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d8",
":",
"255",
",",
"MimeType",
".",
"TIFF_d16",
":",
"65535",
",",
"MimeType",
".",
"TIFF_d32f",
":",... | Returns max value of image `MimeType` format and raises an error if it is not an image format
Note: For `MimeType.TIFF_d32f` it will return ``1.0`` as that is expected maximum for an image even though it
could be higher.
:return: A maximum value of specified image format
:rtype: int or float
:raises: ValueError | [
"Returns",
"max",
"value",
"of",
"image",
"MimeType",
"format",
"and",
"raises",
"an",
"error",
"if",
"it",
"is",
"not",
"an",
"image",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/constants.py#L497-L518 | train | 224,018 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._filter_dates | def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime)
"""
LOGGER.debug("dates=%s", dates)
if len(dates) <= 1:
return dates
sorted_dates = sorted(dates)
separate_dates = [sorted_dates[0]]
for curr_date in sorted_dates[1:]:
if curr_date - separate_dates[-1] > time_difference:
separate_dates.append(curr_date)
return separate_dates | python | def _filter_dates(dates, time_difference):
"""
Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime)
"""
LOGGER.debug("dates=%s", dates)
if len(dates) <= 1:
return dates
sorted_dates = sorted(dates)
separate_dates = [sorted_dates[0]]
for curr_date in sorted_dates[1:]:
if curr_date - separate_dates[-1] > time_difference:
separate_dates.append(curr_date)
return separate_dates | [
"def",
"_filter_dates",
"(",
"dates",
",",
"time_difference",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"dates=%s\"",
",",
"dates",
")",
"if",
"len",
"(",
"dates",
")",
"<=",
"1",
":",
"return",
"dates",
"sorted_dates",
"=",
"sorted",
"(",
"dates",
")",
... | Filters out dates within time_difference, preserving only the oldest date.
:param dates: a list of datetime objects
:param time_difference: a ``datetime.timedelta`` representing the time difference threshold
:return: an ordered list of datetimes `d1<=d2<=...<=dn` such that `d[i+1]-di > time_difference`
:rtype: list(datetime.datetime) | [
"Filters",
"out",
"dates",
"within",
"time_difference",
"preserving",
"only",
"the",
"oldest",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L44-L65 | train | 224,019 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcService._sentinel1_product_check | def _sentinel1_product_check(product_id, data_source):
"""Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool
"""
props = product_id.split('_')
acquisition, resolution, polarisation = props[1], props[2][3], props[3][2:4]
if acquisition in ['IW', 'EW'] and resolution in ['M', 'H'] and polarisation in ['DV', 'DH', 'SV', 'SH']:
return acquisition == data_source.value[2].name and polarisation == data_source.value[3].name and \
resolution == data_source.value[4].name[0]
raise ValueError('Unknown Sentinel-1 tile type: {}'.format(product_id)) | python | def _sentinel1_product_check(product_id, data_source):
"""Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool
"""
props = product_id.split('_')
acquisition, resolution, polarisation = props[1], props[2][3], props[3][2:4]
if acquisition in ['IW', 'EW'] and resolution in ['M', 'H'] and polarisation in ['DV', 'DH', 'SV', 'SH']:
return acquisition == data_source.value[2].name and polarisation == data_source.value[3].name and \
resolution == data_source.value[4].name[0]
raise ValueError('Unknown Sentinel-1 tile type: {}'.format(product_id)) | [
"def",
"_sentinel1_product_check",
"(",
"product_id",
",",
"data_source",
")",
":",
"props",
"=",
"product_id",
".",
"split",
"(",
"'_'",
")",
"acquisition",
",",
"resolution",
",",
"polarisation",
"=",
"props",
"[",
"1",
"]",
",",
"props",
"[",
"2",
"]",
... | Checks if Sentinel-1 product ID matches Sentinel-1 DataSource configuration
:param product_id: Sentinel-1 product ID
:type product_id: str
:param data_source: One of the supported Sentinel-1 data sources
:type data_source: constants.DataSource
:return: True if data_source contains product_id and False otherwise
:rtype: bool | [
"Checks",
"if",
"Sentinel",
"-",
"1",
"product",
"ID",
"matches",
"Sentinel",
"-",
"1",
"DataSource",
"configuration"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L68-L83 | train | 224,020 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_url | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
""" Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.get_base_url(request)
authority = self.instance_id if hasattr(self, 'instance_id') else request.theme
params = self._get_common_url_parameters(request)
if request.service_type in (ServiceType.WMS, ServiceType.WCS):
params = {**params, **self._get_wms_wcs_url_parameters(request, date)}
if request.service_type is ServiceType.WMS:
params = {**params, **self._get_wms_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.WCS:
params = {**params, **self._get_wcs_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.FIS:
params = {**params, **self._get_fis_parameters(request, geometry)}
return '{}/{}?{}'.format(url, authority, urlencode(params)) | python | def get_url(self, request, *, date=None, size_x=None, size_y=None, geometry=None):
""" Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.get_base_url(request)
authority = self.instance_id if hasattr(self, 'instance_id') else request.theme
params = self._get_common_url_parameters(request)
if request.service_type in (ServiceType.WMS, ServiceType.WCS):
params = {**params, **self._get_wms_wcs_url_parameters(request, date)}
if request.service_type is ServiceType.WMS:
params = {**params, **self._get_wms_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.WCS:
params = {**params, **self._get_wcs_url_parameters(request, size_x, size_y)}
elif request.service_type is ServiceType.FIS:
params = {**params, **self._get_fis_parameters(request, geometry)}
return '{}/{}?{}'.format(url, authority, urlencode(params)) | [
"def",
"get_url",
"(",
"self",
",",
"request",
",",
"*",
",",
"date",
"=",
"None",
",",
"size_x",
"=",
"None",
",",
"size_y",
"=",
"None",
",",
"geometry",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"get_base_url",
"(",
"request",
")",
"author... | Returns url to Sentinel Hub's OGC service for the product specified by the OgcRequest and date.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:return: url to Sentinel Hub's OGC service for this product.
:rtype: str | [
"Returns",
"url",
"to",
"Sentinel",
"Hub",
"s",
"OGC",
"service",
"for",
"the",
"product",
"specified",
"by",
"the",
"OgcRequest",
"and",
"date",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L121-L150 | train | 224,021 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_base_url | def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.base_url + request.service_type.value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:
if hasattr(request, 'data_source') and request.data_source.is_uswest_source():
url = 'https://services-uswest2.sentinel-hub.com/ogc/{}'.format(request.service_type.value)
if hasattr(request, 'data_source') and request.data_source not in DataSource.get_available_sources():
raise ValueError("{} is not available for service at ogc_base_url={}".format(request.data_source,
SHConfig().ogc_base_url))
return url | python | def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str
"""
url = self.base_url + request.service_type.value
# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:
if hasattr(request, 'data_source') and request.data_source.is_uswest_source():
url = 'https://services-uswest2.sentinel-hub.com/ogc/{}'.format(request.service_type.value)
if hasattr(request, 'data_source') and request.data_source not in DataSource.get_available_sources():
raise ValueError("{} is not available for service at ogc_base_url={}".format(request.data_source,
SHConfig().ogc_base_url))
return url | [
"def",
"get_base_url",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
".",
"service_type",
".",
"value",
"# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:",
"if",
"hasattr",
... | Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
:rtype: str | [
"Creates",
"base",
"url",
"string",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L152-L168 | train | 224,022 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_common_url_parameters | def _get_common_url_parameters(request):
""" Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict
"""
params = {
'SERVICE': request.service_type.value
}
if hasattr(request, 'maxcc'):
params['MAXCC'] = 100.0 * request.maxcc
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
params = {**params,
**{k.value: str(v) for k, v in request.custom_url_params.items()}}
if CustomUrlParam.EVALSCRIPT.value in params:
evalscript = params[CustomUrlParam.EVALSCRIPT.value]
params[CustomUrlParam.EVALSCRIPT.value] = b64encode(evalscript.encode()).decode()
if CustomUrlParam.GEOMETRY.value in params:
geometry = params[CustomUrlParam.GEOMETRY.value]
crs = request.bbox.crs
if isinstance(geometry, Geometry):
if geometry.crs is not crs:
raise ValueError('Geometry object in custom_url_params should have the same CRS as given BBox')
else:
geometry = Geometry(geometry, crs)
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
params[CustomUrlParam.GEOMETRY.value] = geometry.wkt
return params | python | def _get_common_url_parameters(request):
""" Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict
"""
params = {
'SERVICE': request.service_type.value
}
if hasattr(request, 'maxcc'):
params['MAXCC'] = 100.0 * request.maxcc
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
params = {**params,
**{k.value: str(v) for k, v in request.custom_url_params.items()}}
if CustomUrlParam.EVALSCRIPT.value in params:
evalscript = params[CustomUrlParam.EVALSCRIPT.value]
params[CustomUrlParam.EVALSCRIPT.value] = b64encode(evalscript.encode()).decode()
if CustomUrlParam.GEOMETRY.value in params:
geometry = params[CustomUrlParam.GEOMETRY.value]
crs = request.bbox.crs
if isinstance(geometry, Geometry):
if geometry.crs is not crs:
raise ValueError('Geometry object in custom_url_params should have the same CRS as given BBox')
else:
geometry = Geometry(geometry, crs)
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
params[CustomUrlParam.GEOMETRY.value] = geometry.wkt
return params | [
"def",
"_get_common_url_parameters",
"(",
"request",
")",
":",
"params",
"=",
"{",
"'SERVICE'",
":",
"request",
".",
"service_type",
".",
"value",
"}",
"if",
"hasattr",
"(",
"request",
",",
"'maxcc'",
")",
":",
"params",
"[",
"'MAXCC'",
"]",
"=",
"100.0",
... | Returns parameters common dictionary for WMS, WCS and FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"WCS",
"and",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L171-L209 | train | 224,023 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_wms_wcs_url_parameters | def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict
"""
params = {
'BBOX': str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
'FORMAT': MimeType.get_string(request.image_format),
'CRS': CRS.ogc_string(request.bbox.crs),
}
if date is not None:
start_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date - request.time_difference
end_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date + request.time_difference
params['TIME'] = '{}/{}'.format(start_date.isoformat(), end_date.isoformat())
return params | python | def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict
"""
params = {
'BBOX': str(request.bbox.reverse()) if request.bbox.crs is CRS.WGS84 else str(request.bbox),
'FORMAT': MimeType.get_string(request.image_format),
'CRS': CRS.ogc_string(request.bbox.crs),
}
if date is not None:
start_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date - request.time_difference
end_date = date if request.time_difference < datetime.timedelta(
seconds=0) else date + request.time_difference
params['TIME'] = '{}/{}'.format(start_date.isoformat(), end_date.isoformat())
return params | [
"def",
"_get_wms_wcs_url_parameters",
"(",
"request",
",",
"date",
")",
":",
"params",
"=",
"{",
"'BBOX'",
":",
"str",
"(",
"request",
".",
"bbox",
".",
"reverse",
"(",
")",
")",
"if",
"request",
".",
"bbox",
".",
"crs",
"is",
"CRS",
".",
"WGS84",
"e... | Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"common",
"dictionary",
"for",
"WMS",
"and",
"WCS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L212-L235 | train | 224,024 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService._get_fis_parameters | def _get_fis_parameters(request, geometry):
""" Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict
"""
date_interval = parse_time_interval(request.time)
params = {
'CRS': CRS.ogc_string(geometry.crs),
'LAYER': request.layer,
'RESOLUTION': request.resolution,
'TIME': '{}/{}'.format(date_interval[0], date_interval[1])
}
if not isinstance(geometry, (BBox, Geometry)):
raise ValueError('Each geometry must be an instance of sentinelhub.{} or sentinelhub.{} but {} '
'found'.format(BBox.__name__, Geometry.__name__, geometry))
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
if isinstance(geometry, Geometry):
params['GEOMETRY'] = geometry.wkt
else:
params['BBOX'] = str(geometry)
if request.bins:
params['BINS'] = request.bins
if request.histogram_type:
params['TYPE'] = request.histogram_type.value
return params | python | def _get_fis_parameters(request, geometry):
""" Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict
"""
date_interval = parse_time_interval(request.time)
params = {
'CRS': CRS.ogc_string(geometry.crs),
'LAYER': request.layer,
'RESOLUTION': request.resolution,
'TIME': '{}/{}'.format(date_interval[0], date_interval[1])
}
if not isinstance(geometry, (BBox, Geometry)):
raise ValueError('Each geometry must be an instance of sentinelhub.{} or sentinelhub.{} but {} '
'found'.format(BBox.__name__, Geometry.__name__, geometry))
if geometry.crs is CRS.WGS84:
geometry = geometry.reverse()
if isinstance(geometry, Geometry):
params['GEOMETRY'] = geometry.wkt
else:
params['BBOX'] = str(geometry)
if request.bins:
params['BINS'] = request.bins
if request.histogram_type:
params['TYPE'] = request.histogram_type.value
return params | [
"def",
"_get_fis_parameters",
"(",
"request",
",",
"geometry",
")",
":",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"params",
"=",
"{",
"'CRS'",
":",
"CRS",
".",
"ogc_string",
"(",
"geometry",
".",
"crs",
")",
",",
"'LAY... | Returns parameters dictionary for FIS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param geometry: list of bounding boxes or geometries
:type geometry: list of BBox or Geometry
:return: dictionary with parameters
:rtype: dict | [
"Returns",
"parameters",
"dictionary",
"for",
"FIS",
"request",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L280-L315 | train | 224,025 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_filename | def get_filename(request, date, size_x, size_y):
""" Get filename location
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}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str
"""
filename = '_'.join([
str(request.service_type.value),
request.layer,
str(request.bbox.crs),
str(request.bbox).replace(',', '_'),
'' if date is None else date.strftime("%Y-%m-%dT%H-%M-%S"),
'{}X{}'.format(size_x, size_y)
])
filename = OgcImageService.filename_add_custom_url_params(filename, request)
return OgcImageService.finalize_filename(filename, request.image_format) | python | def get_filename(request, date, size_x, size_y):
""" Get filename location
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}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str
"""
filename = '_'.join([
str(request.service_type.value),
request.layer,
str(request.bbox.crs),
str(request.bbox).replace(',', '_'),
'' if date is None else date.strftime("%Y-%m-%dT%H-%M-%S"),
'{}X{}'.format(size_x, size_y)
])
filename = OgcImageService.filename_add_custom_url_params(filename, request)
return OgcImageService.finalize_filename(filename, request.image_format) | [
"def",
"get_filename",
"(",
"request",
",",
"date",
",",
"size_x",
",",
"size_y",
")",
":",
"filename",
"=",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"request",
".",
"service_type",
".",
"value",
")",
",",
"request",
".",
"layer",
",",
"str",
"(",
... | Get filename location
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}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}
In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)
to differentiate it from 16-bit float tiff.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
:param size_x: horizontal image dimension
:type size_x: int or str
:param size_y: vertical image dimension
:type size_y: int or str
:return: filename for this request and date
:rtype: str | [
"Get",
"filename",
"location"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L318-L352 | train | 224,026 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.filename_add_custom_url_params | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str
"""
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
filename = '_'.join([filename, param.value, str(value)])
return filename | python | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str
"""
if hasattr(request, 'custom_url_params') and request.custom_url_params is not None:
for param, value in sorted(request.custom_url_params.items(),
key=lambda parameter_item: parameter_item[0].value):
filename = '_'.join([filename, param.value, str(value)])
return filename | [
"def",
"filename_add_custom_url_params",
"(",
"filename",
",",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'custom_url_params'",
")",
"and",
"request",
".",
"custom_url_params",
"is",
"not",
"None",
":",
"for",
"param",
",",
"value",
"in",
"sor... | Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: Filename with custom url parameters in the name
:rtype: str | [
"Adds",
"custom",
"url",
"parameters",
"to",
"filename",
"string"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L355-L370 | train | 224,027 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.finalize_filename | def finalize_filename(filename, file_format=None):
""" Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str
"""
for char in [' ', '/', '\\', '|', ';', ':', '\n', '\t']:
filename = filename.replace(char, '')
if file_format:
suffix = str(file_format.value)
if file_format.is_tiff_format() and file_format is not MimeType.TIFF:
suffix = str(MimeType.TIFF.value)
filename = '_'.join([filename, str(file_format.value).replace(';', '_')])
filename = '.'.join([filename[:254 - len(suffix)], suffix])
LOGGER.debug("filename=%s", filename)
return filename | python | def finalize_filename(filename, file_format=None):
""" Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str
"""
for char in [' ', '/', '\\', '|', ';', ':', '\n', '\t']:
filename = filename.replace(char, '')
if file_format:
suffix = str(file_format.value)
if file_format.is_tiff_format() and file_format is not MimeType.TIFF:
suffix = str(MimeType.TIFF.value)
filename = '_'.join([filename, str(file_format.value).replace(';', '_')])
filename = '.'.join([filename[:254 - len(suffix)], suffix])
LOGGER.debug("filename=%s", filename)
return filename | [
"def",
"finalize_filename",
"(",
"filename",
",",
"file_format",
"=",
"None",
")",
":",
"for",
"char",
"in",
"[",
"' '",
",",
"'/'",
",",
"'\\\\'",
",",
"'|'",
",",
"';'",
",",
"':'",
",",
"'\\n'",
",",
"'\\t'",
"]",
":",
"filename",
"=",
"filename",... | Replaces invalid characters in filename string, adds image extension and reduces filename length
:param filename: Incomplete filename string
:type filename: str
:param file_format: Format which will be used for filename extension
:type file_format: MimeType
:return: Final filename string
:rtype: str | [
"Replaces",
"invalid",
"characters",
"in",
"filename",
"string",
"adds",
"image",
"extension",
"and",
"reduces",
"filename",
"length"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L373-L396 | train | 224,028 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_dates | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None]
"""
if DataSource.is_timeless(request.data_source):
return [None]
date_interval = parse_time_interval(request.time)
LOGGER.debug('date_interval=%s', date_interval)
if request.wfs_iterator is None:
self.wfs_iterator = WebFeatureService(request.bbox, date_interval, data_source=request.data_source,
maxcc=request.maxcc, base_url=self.base_url,
instance_id=self.instance_id)
else:
self.wfs_iterator = request.wfs_iterator
dates = sorted(set(self.wfs_iterator.get_dates()))
if request.time is OgcConstants.LATEST:
dates = dates[-1:]
return OgcService._filter_dates(dates, request.time_difference) | python | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None]
"""
if DataSource.is_timeless(request.data_source):
return [None]
date_interval = parse_time_interval(request.time)
LOGGER.debug('date_interval=%s', date_interval)
if request.wfs_iterator is None:
self.wfs_iterator = WebFeatureService(request.bbox, date_interval, data_source=request.data_source,
maxcc=request.maxcc, base_url=self.base_url,
instance_id=self.instance_id)
else:
self.wfs_iterator = request.wfs_iterator
dates = sorted(set(self.wfs_iterator.get_dates()))
if request.time is OgcConstants.LATEST:
dates = dates[-1:]
return OgcService._filter_dates(dates, request.time_difference) | [
"def",
"get_dates",
"(",
"self",
",",
"request",
")",
":",
"if",
"DataSource",
".",
"is_timeless",
"(",
"request",
".",
"data_source",
")",
":",
"return",
"[",
"None",
"]",
"date_interval",
"=",
"parse_time_interval",
"(",
"request",
".",
"time",
")",
"LOG... | Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is specified the result is a list of all scenes between the specified dates conforming to
the cloud coverage criteria. Most recent acquisition being first in the list.
When a time_difference threshold is set to a positive value, the function filters out all datetimes which
are within the time difference. The oldest datetime is preserved, all others all deleted.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: List of dates of existing acquisitions for the given request
:rtype: list(datetime.datetime) or [None] | [
"Get",
"available",
"Sentinel",
"-",
"2",
"acquisitions",
"at",
"least",
"time_difference",
"apart"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L398-L432 | train | 224,029 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | OgcImageService.get_image_dimensions | def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and
isinstance(request.size_y, int)):
return request.size_x, request.size_y
if not isinstance(request.size_x, int) and not isinstance(request.size_y, int):
raise ValueError("At least one of parameters 'width' and 'height' must have an integer value")
missing_dimension = get_image_dimension(request.bbox, width=request.size_x, height=request.size_y)
if request.size_x is None:
return missing_dimension, request.size_y
if request.size_y is None:
return request.size_x, missing_dimension
raise ValueError("Parameters 'width' and 'height' must be integers or None") | python | def get_image_dimensions(request):
"""
Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str)
"""
if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and
isinstance(request.size_y, int)):
return request.size_x, request.size_y
if not isinstance(request.size_x, int) and not isinstance(request.size_y, int):
raise ValueError("At least one of parameters 'width' and 'height' must have an integer value")
missing_dimension = get_image_dimension(request.bbox, width=request.size_x, height=request.size_y)
if request.size_x is None:
return missing_dimension, request.size_y
if request.size_y is None:
return request.size_x, missing_dimension
raise ValueError("Parameters 'width' and 'height' must be integers or None") | [
"def",
"get_image_dimensions",
"(",
"request",
")",
":",
"if",
"request",
".",
"service_type",
"is",
"ServiceType",
".",
"WCS",
"or",
"(",
"isinstance",
"(",
"request",
".",
"size_x",
",",
"int",
")",
"and",
"isinstance",
"(",
"request",
".",
"size_y",
","... | Verifies or calculates image dimensions.
:param request: OGC-type request
:type request: WmsRequest or WcsRequest
:return: horizontal and vertical dimensions of requested image
:rtype: (int or str, int or str) | [
"Verifies",
"or",
"calculates",
"image",
"dimensions",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L435-L454 | train | 224,030 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._fetch_features | def _fetch_features(self):
"""Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict
"""
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
params = {'SERVICE': ServiceType.WFS.value,
'REQUEST': 'GetFeature',
'TYPENAMES': DataSource.get_wfs_typename(self.data_source),
'BBOX': str(self.bbox.reverse()) if self.bbox.crs is CRS.WGS84 else str(self.bbox),
'OUTPUTFORMAT': MimeType.get_string(MimeType.JSON),
'SRSNAME': CRS.ogc_string(self.bbox.crs),
'TIME': '{}/{}'.format(self.time_interval[0], self.time_interval[1]),
'MAXCC': 100.0 * self.maxcc,
'MAXFEATURES': SHConfig().max_wfs_records_per_query,
'FEATURE_OFFSET': self.feature_offset}
url = main_url + urlencode(params)
LOGGER.debug("URL=%s", url)
response = get_json(url)
is_sentinel1 = self.data_source.is_sentinel1()
for tile_info in response["features"]:
if not is_sentinel1 or self._sentinel1_product_check(tile_info['properties']['id'], self.data_source):
self.tile_list.append(tile_info)
if len(response["features"]) < SHConfig().max_wfs_records_per_query:
self.feature_offset = None
else:
self.feature_offset += SHConfig().max_wfs_records_per_query | python | def _fetch_features(self):
"""Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict
"""
if self.feature_offset is None:
return
main_url = '{}{}/{}?'.format(self.base_url, ServiceType.WFS.value, self.instance_id)
params = {'SERVICE': ServiceType.WFS.value,
'REQUEST': 'GetFeature',
'TYPENAMES': DataSource.get_wfs_typename(self.data_source),
'BBOX': str(self.bbox.reverse()) if self.bbox.crs is CRS.WGS84 else str(self.bbox),
'OUTPUTFORMAT': MimeType.get_string(MimeType.JSON),
'SRSNAME': CRS.ogc_string(self.bbox.crs),
'TIME': '{}/{}'.format(self.time_interval[0], self.time_interval[1]),
'MAXCC': 100.0 * self.maxcc,
'MAXFEATURES': SHConfig().max_wfs_records_per_query,
'FEATURE_OFFSET': self.feature_offset}
url = main_url + urlencode(params)
LOGGER.debug("URL=%s", url)
response = get_json(url)
is_sentinel1 = self.data_source.is_sentinel1()
for tile_info in response["features"]:
if not is_sentinel1 or self._sentinel1_product_check(tile_info['properties']['id'], self.data_source):
self.tile_list.append(tile_info)
if len(response["features"]) < SHConfig().max_wfs_records_per_query:
self.feature_offset = None
else:
self.feature_offset += SHConfig().max_wfs_records_per_query | [
"def",
"_fetch_features",
"(",
"self",
")",
":",
"if",
"self",
".",
"feature_offset",
"is",
"None",
":",
"return",
"main_url",
"=",
"'{}{}/{}?'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"ServiceType",
".",
"WFS",
".",
"value",
",",
"self",
".",... | Collects data from WFS service
:return: dictionary containing info about product tiles
:rtype: dict | [
"Collects",
"data",
"from",
"WFS",
"service"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L524-L558 | train | 224,031 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService.get_dates | def get_dates(self):
""" Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime)
"""
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
tile_info['properties']['time'].split('.')[0]),
'%Y-%m-%dT%H:%M:%S') for tile_info in self] | python | def get_dates(self):
""" Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime)
"""
return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'],
tile_info['properties']['time'].split('.')[0]),
'%Y-%m-%dT%H:%M:%S') for tile_info in self] | [
"def",
"get_dates",
"(",
"self",
")",
":",
"return",
"[",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"'{}T{}'",
".",
"format",
"(",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'date'",
"]",
",",
"tile_info",
"[",
"'properties'",
"]",
"[",
"'time... | Returns a list of acquisition times from tile info data
:return: List of acquisition times in the order returned by WFS service.
:rtype: list(datetime.datetime) | [
"Returns",
"a",
"list",
"of",
"acquisition",
"times",
"from",
"tile",
"info",
"data"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L560-L568 | train | 224,032 |
sentinel-hub/sentinelhub-py | sentinelhub/ogc.py | WebFeatureService._parse_tile_url | def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)
return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7]) | python | def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)
return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7]) | [
"def",
"_parse_tile_url",
"(",
"tile_url",
")",
":",
"props",
"=",
"tile_url",
".",
"rsplit",
"(",
"'/'",
",",
"7",
")",
"return",
"''",
".",
"join",
"(",
"props",
"[",
"1",
":",
"4",
"]",
")",
",",
"'-'",
".",
"join",
"(",
"props",
"[",
"4",
"... | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) | [
"Extracts",
"tile",
"name",
"data",
"and",
"AWS",
"index",
"from",
"tile",
"URL"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/ogc.py#L587-L596 | train | 224,033 |
sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | get_dates_in_range | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str
"""
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] | python | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str
"""
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] | [
"def",
"get_dates_in_range",
"(",
"start_date",
",",
"end_date",
")",
":",
"start_dt",
"=",
"iso_to_datetime",
"(",
"start_date",
")",
"end_dt",
"=",
"iso_to_datetime",
"(",
"end_date",
")",
"num_days",
"=",
"int",
"(",
"(",
"end_dt",
"-",
"start_dt",
")",
"... | Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str | [
"Get",
"all",
"dates",
"within",
"input",
"start",
"and",
"end",
"date",
"in",
"ISO",
"8601",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L12-L25 | train | 224,034 |
sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | iso_to_datetime | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) | python | def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime
"""
chunks = list(map(int, date.split('T')[0].split('-')))
return datetime.datetime(chunks[0], chunks[1], chunks[2]) | [
"def",
"iso_to_datetime",
"(",
"date",
")",
":",
"chunks",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"date",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'",
")",
")",
")",
"return",
"datetime",
".",
"datetime",
"(",
"chunk... | Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
:rtype: datetime | [
"Convert",
"ISO",
"8601",
"time",
"format",
"to",
"datetime",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L56-L68 | train | 224,035 |
sentinel-hub/sentinelhub-py | sentinelhub/time_utils.py | datetime_to_iso | def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str
"""
if only_date:
return date.isoformat().split('T')[0]
return date.isoformat() | python | def datetime_to_iso(date, only_date=True):
""" Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str
"""
if only_date:
return date.isoformat().split('T')[0]
return date.isoformat() | [
"def",
"datetime_to_iso",
"(",
"date",
",",
"only_date",
"=",
"True",
")",
":",
"if",
"only_date",
":",
"return",
"date",
".",
"isoformat",
"(",
")",
".",
"split",
"(",
"'T'",
")",
"[",
"0",
"]",
"return",
"date",
".",
"isoformat",
"(",
")"
] | Convert datetime format to ISO 8601 time format
This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format,
e.g. ``2017-09-14``
:param date: datetime instance to convert
:type date: datetime
:param only_date: whether to return date only or also time information. Default is ``True``
:type only_date: bool
:return: date in ISO 8601 format
:rtype: str | [
"Convert",
"datetime",
"format",
"to",
"ISO",
"8601",
"time",
"format"
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/time_utils.py#L71-L86 | train | 224,036 |
sentinel-hub/sentinelhub-py | sentinelhub/commands.py | aws | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
"""Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a
"""
band_list = None if bands is None else bands.split(',')
data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C
if info:
if product is None:
click.echo(get_safe_format(tile=tile, entire_product=entire, data_source=data_source))
else:
click.echo(get_safe_format(product_id=product))
else:
if product is None:
download_safe_format(tile=tile, folder=folder, redownload=redownload, entire_product=entire,
bands=band_list, data_source=data_source)
else:
download_safe_format(product_id=product, folder=folder, redownload=redownload, bands=band_list) | python | def aws(product, tile, folder, redownload, info, entire, bands, l2a):
"""Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a
"""
band_list = None if bands is None else bands.split(',')
data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C
if info:
if product is None:
click.echo(get_safe_format(tile=tile, entire_product=entire, data_source=data_source))
else:
click.echo(get_safe_format(product_id=product))
else:
if product is None:
download_safe_format(tile=tile, folder=folder, redownload=redownload, entire_product=entire,
bands=band_list, data_source=data_source)
else:
download_safe_format(product_id=product, folder=folder, redownload=redownload, bands=band_list) | [
"def",
"aws",
"(",
"product",
",",
"tile",
",",
"folder",
",",
"redownload",
",",
"info",
",",
"entire",
",",
"bands",
",",
"l2a",
")",
":",
"band_list",
"=",
"None",
"if",
"bands",
"is",
"None",
"else",
"bands",
".",
"split",
"(",
"','",
")",
"dat... | Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.
\b
Examples with Sentinel-2 L1C data:
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products
sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11
sentinelhub.aws --tile T54HVH 2017-04-14
sentinelhub.aws --tile T54HVH 2017-04-14 -e
\b
Examples with Sentinel-2 L2A data:
sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222
sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a | [
"Download",
"Sentinel",
"-",
"2",
"data",
"from",
"Sentinel",
"-",
"2",
"on",
"AWS",
"to",
"ESA",
"SAFE",
"format",
".",
"Download",
"uses",
"multiple",
"threads",
"."
] | 08a83b7f1e289187159a643336995d8369860fea | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/commands.py#L38-L67 | train | 224,037 |
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):
""" 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 | [
"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 | train | 224,038 |
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):
"""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())) | [
"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 | train | 224,039 |
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):
"""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) | [
"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 | train | 224,040 |
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):
"""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() | [
"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 | train | 224,041 |
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):
""" 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]) | [
"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 | train | 224,042 |
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):
""" 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) | [
"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 | train | 224,043 |
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):
""" 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 | [
"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 | train | 224,044 |
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):
""" 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)) | [
"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 | train | 224,045 |
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):
""" 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) | [
"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 | train | 224,046 |
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):
""" 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] | [
"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 | train | 224,047 |
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):
""" 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) | [
"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 | train | 224,048 |
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):
""" 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 | [
"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 | train | 224,049 |
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):
""" 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 | [
"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 | train | 224,050 |
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):
""" 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 | [
"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 | train | 224,051 |
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):
""" 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 | [
"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 | train | 224,052 |
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):
""" 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) | [
"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 | train | 224,053 |
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):
"""
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() | [
"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 | train | 224,054 |
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):
"""
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) | [
"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 | train | 224,055 |
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):
"""
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) | [
"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 | train | 224,056 |
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):
"""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 | [
"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 | train | 224,057 |
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):
""" 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 | [
"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 | train | 224,058 |
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):
"""
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)) | [
"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 | train | 224,059 |
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):
"""
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 | [
"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 | train | 224,060 |
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):
"""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() | [
"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 | train | 224,061 |
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):
""" 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 | [
"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 | train | 224,062 |
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):
""" 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 | [
"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 | train | 224,063 |
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):
""" 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) | [
"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 | train | 224,064 |
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):
""" 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 | [
"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 | train | 224,065 |
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):
""" 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 | [
"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 | train | 224,066 |
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):
""" 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'] | [
"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 | train | 224,067 |
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='.'):
""" 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))] | [
"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 | train | 224,068 |
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):
""" 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) | [
"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 | train | 224,069 |
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):
""" 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) | [
"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 | train | 224,070 |
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):
""" 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) | [
"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 | train | 224,071 |
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):
""" 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)]) | [
"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 | train | 224,072 |
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):
""" 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 | [
"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 | train | 224,073 |
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):
""" 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) | [
"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 | train | 224,074 |
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):
""" 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) | [
"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 | train | 224,075 |
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):
""" 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 | [
"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 | train | 224,076 |
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):
""" 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)] | [
"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 | train | 224,077 |
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):
""" 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) | [
"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 | train | 224,078 |
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):
""" 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))) | [
"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 | train | 224,079 |
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):
""" 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') | [
"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 | train | 224,080 |
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):
""" 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]) | [
"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 | train | 224,081 |
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):
""" 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) | [
"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 | train | 224,082 |
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):
""" 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) | [
"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 | train | 224,083 |
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):
""" 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 | [
"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 | train | 224,084 |
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):
""" 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]) | [
"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 | train | 224,085 |
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):
""" Creates a multipolygon of bounding box polygons
"""
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 | train | 224,086 |
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):
""" 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 | [
"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 | train | 224,087 |
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):
""" 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)) | [
"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 | train | 224,088 |
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):
""" 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) | [
"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 | train | 224,089 |
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):
""" 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)) | [
"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 | train | 224,090 |
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):
""" 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)) | [
"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 | train | 224,091 |
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):
""" 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) | [
"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 | train | 224,092 |
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):
""" 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) | [
"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 | train | 224,093 |
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 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) | [
"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 | train | 224,094 |
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):
""" 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) | [
"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 | train | 224,095 |
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):
""" 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) | [
"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 | train | 224,096 |
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):
"""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 | [
"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 | train | 224,097 |
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):
"""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)) | [
"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 | train | 224,098 |
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):
""" 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] | [
"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 | train | 224,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.