def test_fail_1_to_1(self):
        code = """import numpy as np
def ndvi_numpy(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    out_ar[:] = in_ar[0]"""

        landsat = Landsat(self.metadata_set)
        scale_params = [[0, 40000], [0, 40000], [0, 40000]]

        pixel_function_details = FunctionDetails(name="ndvi_numpy",
                                                 band_definitions=[Band.RED],
                                                 code=code,
                                                 arguments={"factor": DataType.UINT16.range_max},
                                                 data_type=DataType.UINT16)

        gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES")
        nda = landsat.fetch_imagery_array([pixel_function_details, Band.GREEN, Band.BLUE],
                                          scale_params=scale_params,
                                          polygon_boundary_wkb=self.taos_shape.wkb,
                                          output_type=DataType.BYTE)

        nda2 = landsat.fetch_imagery_array([Band.RED, Band.GREEN, Band.BLUE],
                                           scale_params=scale_params,
                                           polygon_boundary_wkb=self.taos_shape.wkb,
                                           output_type=DataType.BYTE)
        self.assertIsNotNone(nda)
        np.testing.assert_almost_equal(nda, nda2)
        np.testing.assert_equal(nda, nda2)
    def test_aws_without_google(self):
        metadata_service = MetadataService()
        # c1/L8/083/015/LC08_L1TP_083015_20171106_20171107_01_RT/
        # c1/L8/083/111/LC08_L1GT_083111_20171106_20171107_01_RT

        sqs_message = {
            "Type": "Notification",
            "MessageId": "27f57c3d-9d2e-5fa3-8f83-2e41a3aa5634",
            "TopicArn": "arn:aws:sns:us-west-2:274514004127:NewSceneHTML",
            "Subject": "Amazon S3 Notification",
            "Message": "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"us-west-2\",\"eventTime\":\"2017-11-07T23:05:40.162Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AWS:AIDAILHHXPNIKSGVUGOZK\"},\"requestParameters\":{\"sourceIPAddress\":\"35.193.238.175\"},\"responseElements\":{\"x-amz-request-id\":\"F96A6CC9816FC5EF\",\"x-amz-id-2\":\"yehs3XxTY8utc9kgKfNbMe1wdtV7F0wEMUXUQtIu7zMRtGvboxahzwncrmG046yI327j5IRh8nE=\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"C1-NewHTML\",\"bucket\":{\"name\":\"landsat-pds\",\"ownerIdentity\":{\"principalId\":\"A3LZTVCZQ87CNW\"},\"arn\":\"arn:aws:s3:::landsat-pds\"},\"object\":{\"key\":\"c1/L8/115/062/LC08_L1TP_115062_20171107_20171107_01_RT/index.html\",\"size\":5391,\"eTag\":\"0f06667fca1f707894bf579bd667e221\",\"sequencer\":\"005A023C441A8F8403\"}}}]}",
            "Timestamp": "2017-11-07T23:05:40.219Z",
            "SignatureVersion": "1",
            "Signature": "bqrW1x6CgJntCz6f0F5uncyPZR+6ZM/tZ3OrRZDiudBv5DAtMyYR9n6KQ0aT+iYP5INfpL2GuIm8Uqco8ZHzg5AqEhHtNkpzGBQpQHvlF3t0ut9K27YNwJ6ZmnS14BgsLWyXIthVRjvHf1Hhx3ZInPMJrzTcKCOhOmBcM9zOpfWrHfnynuifpN3FaldDz6VY2d9QM0Rn8Fo8XZ4F+j01eAJVlydnRbSBbLewleuvhPQh6EG5r2EeekeniOIETrodS7o43ZClFr8OSgRE7BvpecVnnUEXBUIDDtRAPnIxo3Io0AmfPRI8xRfeKNhBIhPq3W3clm7Dxkp3N96OKoVUBw==",
            "SigningCertURL": "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem",
            "UnsubscribeURL": "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:274514004127:NewSceneHTML:7997d757-d1c6-4064-8935-34111968c8cc"
        }

        d = datetime.datetime.strptime(sqs_message['Timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ")

        rows = metadata_service.search_aws('/imagery', wrs_path=115, wrs_row=62, collection_date=d)
        self.assertGreater(len(rows), 0)

        metadata = rows[0]
        self.assertIsNotNone(metadata)

        landsat = Landsat(metadata)
        nda = landsat.fetch_imagery_array([4, 3, 2], [[0, 40000], [0, 40000], [0, 40000]], spatial_resolution_m=240)
        self.assertIsNotNone(nda)
    def test_australia(self):
        # 5th Place: Lake Eyre Landsat 5 Acquired August 5, 2006
        wkt = "POLYGON((136.2469482421875 -27.57843813308233,138.6639404296875 -27.57843813308233," \
              "138.6639404296875 -29.82351878748485,136.2469482421875 -29.82351878748485,136." \
              "2469482421875 -27.57843813308233))"

        polygon = loads(wkt)

        # sql_filters = ['cloud_cover=0']
        d_start = date(2006, 8, 4)
        d_end = date(2006, 8, 7)
        bounding_box = polygon.bounds
        landsat_filters = LandsatQueryFilters()
        landsat_filters.wrs_row.set_value(79)
        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_5,
            data_filters=landsat_filters)

        rows = list(rows)

        self.assertEqual(len(rows), 1)

        metadata = rows[0]
        landsat = Landsat(metadata)

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [3, 2, 1]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        # nda = landsat.__get_ndarray(band_numbers, metadata, scale_params)
        nda = landsat.fetch_imagery_array(band_numbers, scale_params)
        self.assertEqual((3581, 4046, 3), nda.shape)
    def test_polygon_wkb_metadata(self):
        d_start = date(2017, 3, 12)  # 2017-03-12
        d_end = date(2017, 3, 19)  # 2017-03-20, epl api is inclusive

        self.metadata_service = MetadataService()

        landsat_filters = LandsatQueryFilters()
        landsat_filters.collection_number.set_value("PRE")
        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_geometry(self.taos_shape.wkb)
        # landsat_filters.geometry_bag.geometry_binaries.append(self.taos_shape.wkb)
        metadata_rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_8, limit=10, data_filters=landsat_filters)

        metadata_set = []
        for row in metadata_rows:
            metadata_set.append(row)

        landsat = Landsat(metadata_set)
        band_numbers = [Band.NIR, Band.SWIR1, Band.SWIR2]
        scaleParams = [[0.0, 40000.0], [0.0, 40000.0], [0.0, 40000.0]]
        nda = landsat.fetch_imagery_array(
            band_numbers,
            scaleParams,
            polygon_boundary_wkb=self.taos_shape.wkb)
        self.assertIsNotNone(nda)
        self.assertEqual((1804, 1295, 3), nda.shape)
    def test_rastermetadata_cache(self):
        # GDAL helper functions for generating VRT
        landsat = Landsat(self.metadata_set)

        # get a numpy.ndarray from bands for specified imagery
        # 'nir', 'swir1', 'swir2'
        band_numbers = [Band.NIR, Band.SWIR1, Band.SWIR2]
        scaleParams = [[0.0, 40000.0], [0.0, 40000.0], [0.0, 40000.0]]
        nda = landsat.fetch_imagery_array(
            band_numbers,
            scaleParams,
            polygon_boundary_wkb=self.taos_shape.wkb,
            spatial_resolution_m=120)
        self.assertIsNotNone(nda)
        self.assertEqual((902, 648, 3), nda.shape)

        band_numbers = [Band.RED, Band.BLUE, Band.GREEN]
        nda = landsat.fetch_imagery_array(
            band_numbers,
            scaleParams,
            polygon_boundary_wkb=self.taos_shape.wkb,
            spatial_resolution_m=120)
        self.assertIsNotNone(nda)
        self.assertEqual((902, 648, 3), nda.shape)

        band_numbers = [Band.RED, Band.BLUE, Band.GREEN]
        nda = landsat.fetch_imagery_array(band_numbers,
                                          scaleParams,
                                          spatial_resolution_m=120)
        self.assertIsNotNone(nda)
        self.assertNotEqual((902, 648, 3), nda.shape)
    def test_ndvi_taos(self):

        code = """import numpy as np
def ndvi_numpy(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    with np.errstate(divide = 'ignore', invalid = 'ignore'):
        factor = float(kwargs['factor'])
        output = np.divide((in_ar[1] - in_ar[0]), (in_ar[1] + in_ar[0]))
        output[np.isnan(output)] = 0.0
        # shift range from -1.0-1.0 to 0.0-2.0
        output += 1.0
        # scale up from 0.0-2.0 to 0 to 255 by multiplying by 255/2
        # https://stackoverflow.com/a/1735122/445372
        output *=  factor/2.0
        # https://stackoverflow.com/a/10622758/445372
        # in place type conversion
        out_ar[:] = output.astype(np.int16, copy=False)"""

        code2 = """import numpy as np
def ndvi_numpy2(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    with np.errstate(divide = 'ignore', invalid = 'ignore'):
        output = (in_ar[1] - in_ar[0]) / (in_ar[1] + in_ar[0])
        output[np.isnan(output)] = 0.0
        out_ar[:] = output"""

        landsat = Landsat(self.metadata_set)

        scale_params = [[0, DataType.UINT16.range_max, -1.0, 1.0]]

        pixel_function_details = FunctionDetails(name="ndvi_numpy",
                                                 band_definitions=[Band.RED, Band.NIR],
                                                 code=code,
                                                 arguments={"factor": DataType.UINT16.range_max},
                                                 data_type=DataType.UINT16)

        gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES")
        nda = landsat.fetch_imagery_array([pixel_function_details],
                                          scale_params=scale_params,
                                          polygon_boundary_wkb=self.taos_shape.wkb,
                                          output_type=DataType.FLOAT32)

        self.assertIsNotNone(nda)
        self.assertGreaterEqual(1.0, nda.max())
        self.assertLessEqual(-1.0, nda.min())

        pixel_function_details = FunctionDetails(name="ndvi_numpy2",
                                                 band_definitions=[Band.RED, Band.NIR],
                                                 code=code2,
                                                 data_type=DataType.FLOAT32)

        nda2 = landsat.fetch_imagery_array([pixel_function_details],
                                           polygon_boundary_wkb=self.taos_shape.wkb,
                                           output_type=DataType.FLOAT32)

        self.assertIsNotNone(nda2)
        self.assertGreaterEqual(1.0, nda2.max())
        self.assertLessEqual(-1.0, nda2.min())
    def test_iowa_ndarray(self):
        d_start = date(2016, 4, 4)
        d_end = date(2016, 8, 7)
        bounding_box = self.iowa_polygon.bounds
        # sql_filters = ["cloud_cover<=15"]
        landsat_filters = LandsatQueryFilters()
        landsat_filters.cloud_cover.set_range(end=15, end_inclusive=15)

        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_8,
            data_filters=landsat_filters)
        rows = list(rows)
        metadata = rows[0]
        landsat = Landsat(metadata)

        code = """import numpy as np
def ndvi_numpy(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    with np.errstate(divide = 'ignore', invalid = 'ignore'):
        out_ar[:] = np.divide((in_ar[1] - in_ar[0]), (in_ar[1] + in_ar[0]))
        out_ar[np.isnan(out_ar)] = 0.0
        out_ar """

        pixel_function_details = FunctionDetails(name="ndvi_numpy", band_definitions=[4, 5], code=code, data_type=DataType.FLOAT32)
        # pixel_function_details = {
        #     "band_numbers": [4, 5],
        #     "function_code": code,
        #     "function_type": "ndvi_numpy",
        #     "data_type": DataType.FLOAT32,
        # }

        band_definitions = [pixel_function_details, 4, 5]

        vrt = landsat.get_vrt(band_definitions)
        ds = gdal.Open(vrt)
        self.assertIsNotNone(ds)

        arr_4 = ds.GetRasterBand(2).ReadAsArray()
        arr_5 = ds.GetRasterBand(3).ReadAsArray()
        arr_ndvi = ds.GetRasterBand(1).ReadAsArray()
        del ds
        del landsat
        print(np.ndarray.max(arr_ndvi))
        print(np.ndarray.min(arr_ndvi))
        self.assertFalse(np.any(np.isinf(arr_ndvi)))
        self.assertIsNotNone(arr_ndvi)

        local_ndvi = self.ndvi_numpy(arr_5, arr_4)

        del arr_4
        del arr_5
        self.assertFalse(np.any(np.isinf(local_ndvi)))

        np.testing.assert_almost_equal(arr_ndvi, local_ndvi)
    def test_vrt_extent(self):
        # GDAL helper functions for generating VRT
        landsat = Landsat(self.metadata_set[0])

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        vrt = landsat.get_vrt(band_numbers,
                              envelope_boundary=self.taos_shape.bounds)

        self.assertIsNotNone(vrt)
 def test_one_band(self):
     # specify the bands that approximate real color
     landsat = Landsat(self.metadata_set)
     band_numbers = [Band.RED]
     scaleParams = [[0.0, 40000.0]]
     nda = landsat.fetch_imagery_array(
         band_numbers,
         scaleParams,
         polygon_boundary_wkb=self.taos_shape.wkb,
         spatial_resolution_m=120)
     self.assertIsNotNone(nda)
     self.assertEqual((902, 648), nda.shape)
    def test_native_vs_custom(self):
        landsat = Landsat(self.metadata_set)
        gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES")
        pixel_native = FunctionDetails(name="sqrt",
                                       band_definitions=[Band.RED],
                                       data_type=DataType.UINT16,
                                       transfer_type=DataType.FLOAT32)
        nda = landsat.fetch_imagery_array([pixel_native],
                                          polygon_boundary_wkb=self.taos_shape.wkb,
                                          output_type=DataType.FLOAT32)

        self.assertIsNotNone(nda)
    def test_cutline(self):
        # GDAL helper functions for generating VRT
        landsat = Landsat(self.metadata_set[0])

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        nda = landsat.fetch_imagery_array(band_numbers,
                                          scale_params,
                                          self.taos_shape.wkb,
                                          spatial_resolution_m=480)
        self.assertIsNotNone(nda)
    def test_mosaic(self):
        # GDAL helper functions for generating VRT
        landsat = Landsat(self.metadata_set)

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        nda = landsat.fetch_imagery_array(
            band_numbers,
            scale_params,
            envelope_boundary=self.taos_shape.bounds)
        self.assertIsNotNone(nda)
        self.assertEqual((1804, 1295, 3), nda.shape)
    def test_mosaic_cutline(self):
        # GDAL helper functions for generating VRT
        landsat = Landsat(self.metadata_set)

        # get a numpy.ndarray from bands for specified imagery
        # 'nir', 'swir1', 'swir2'
        band_numbers = [Band.NIR, Band.SWIR1, Band.SWIR2]
        scaleParams = [[0.0, 40000.0], [0.0, 40000.0], [0.0, 40000.0]]
        nda = landsat.fetch_imagery_array(
            band_numbers,
            scaleParams,
            polygon_boundary_wkb=self.taos_shape.wkb)
        self.assertIsNotNone(nda)
        self.assertEqual((1804, 1295, 3), nda.shape)
    def test_pixel_function_vrt_1(self):
        utah_box = (-112.66342163085938, 37.738141282210385,
                    -111.79824829101562, 38.44821130413263)
        d_start = date(2016, 7, 20)
        d_end = date(2016, 7, 28)

        landsat_filter = LandsatQueryFilters()
        landsat_filter.collection_number.set_value("PRE")
        landsat_filter.cloud_cover.set_range(
            end=5, end_inclusive=True
        )  #landsat_filter.cloud_cover.set_range_end(5, True)
        landsat_filter.acquired.set_range(d_start, True, d_end, True)
        landsat_filter.aoi.set_bounds(*utah_box)
        rows = self.metadata_service.search(SpacecraftID.LANDSAT_8,
                                            limit=10,
                                            data_filters=landsat_filter)
        rows = list(rows)
        self.assertEqual(0, len(rows))

        d_end = date(2016, 8, 28)
        landsat_filter = LandsatQueryFilters()
        landsat_filter.collection_number.set_value("PRE")
        landsat_filter.cloud_cover.set_range(
            end=5, end_inclusive=False
        )  #landsat_filter.cloud_cover.set_range_end(5, False)
        landsat_filter.acquired.set_range(
            end=d_end, end_inclusive=True
        )  #landsat_filter.acquired.set_range_end(d_end, True)
        landsat_filter.acquired.sort_by(epl_imagery_pb2.DESCENDING)
        landsat_filter.aoi.set_bounds(*utah_box)
        rows = self.metadata_service.search(SpacecraftID.LANDSAT_8,
                                            limit=10,
                                            data_filters=landsat_filter)
        rows = list(rows)
        self.assertEqual(len(rows), 10)
        #     metadata_row = ['LC80390332016208LGN00', '', 'LANDSAT_8', 'OLI_TIRS', '2016-07-26',
        # '2016-07-26T18:14:46.9465460Z', 'PRE', 'N/A', 'L1T', 39, 33, 1.69,
        # 39.96962, 37.81744, -115.27267, -112.56732, 1070517542,
        # 'gs://gcp-public-data-landsat/LC08/PRE/039/033/LC80390332016208LGN00']
        metadata = rows[0]

        # GDAL helper functions for generating VRT
        landsat = Landsat([metadata])

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [4, 3, 2]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        nda = landsat.fetch_imagery_array(band_numbers, scale_params)

        self.assertEqual(nda.shape, (3876, 3806, 3))
    def test_vrt_with_alpha(self):
        landsat = Landsat(self.metadata_set)

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE, Band.ALPHA]
        scaleParams = [[0.0, 40000], [0.0, 40000], [0.0, 40000]]

        nda = landsat.fetch_imagery_array(
            band_numbers,
            scaleParams,
            envelope_boundary=self.taos_shape.bounds,
            output_type=DataType.UINT16,
            spatial_resolution_m=120)
        self.assertIsNotNone(nda)
    def test_pixel_ndvi(self):
        """
        http://grindgis.com/blog/vegetation-indices-arcgis
        NDVI = (NIR - RED) / (NIR + RED)
        NDVI = (5 - 4) / (5 + 4)
        :return:
        """
        landsat = Landsat(self.m_metadata)  # , gsurl[2])

        code = """import numpy as np
def ndvi_numpy(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    with np.errstate(divide = 'ignore', invalid = 'ignore'):
        output = np.divide((in_ar[1] - in_ar[0]), (in_ar[1] + in_ar[0]))
        output[np.isnan(output)] = 0.0
        # shift range from -1.0-1.0 to 0.0-2.0
        output += 1.0
        # scale up from 0.0-2.0 to 0 to 255 by multiplying by 255/2
        # https://stackoverflow.com/a/1735122/445372
        output *=  65535/2.0
        # https://stackoverflow.com/a/10622758/445372
        # in place type conversion
        out_ar[:] = output.astype(np.int16, copy=False)"""

        pixel_function_details = FunctionDetails(name="ndvi_numpy", band_definitions=[4, 5],
                                                 data_type=DataType.UINT16, code=code)
        vrt = landsat.get_vrt([pixel_function_details, 3, 2])

        with open('ndvi_numpy.vrt', 'r') as myfile:
            data = myfile.read()
            expected = etree.XML(data)
            actual = etree.XML(vrt)
            result, message = xml_compare(expected, actual, {"GeoTransform": 1e-10})
            self.assertTrue(result, message)

        gdal.SetConfigOption('GDAL_VRT_ENABLE_PYTHON', "YES")

        ds = gdal.Open(vrt)
        self.assertIsNotNone(ds)
        arr_ndvi = ds.GetRasterBand(1).ReadAsArray()
        ds = None
        self.assertIsNotNone(arr_ndvi)
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        band_definitions = [pixel_function_details, 3, 2]
        nda = landsat.fetch_imagery_array(band_definitions, scale_params)
        self.assertIsNotNone(nda)
 def test_get_file(self):
     d_start = date(2015, 6, 24)
     d_end = date(2016, 6, 24)
     bounding_box = (-115.927734375, 34.52466147177172, -78.31054687499999, 44.84029065139799)
     landsat_filters = LandsatQueryFilters()
     landsat_filters.acquired.set_range(d_start, True, d_end, True)
     landsat_filters.aoi.set_bounds(*bounding_box)
     metadata_service = MetadataService()
     rows = metadata_service.search(SpacecraftID.LANDSAT_8,
                                    data_filters=landsat_filters,
                                    limit=1)
     rows = list(rows)
     metadata = rows[0]
     landsat = Landsat(metadata)
     self.assertIsNotNone(landsat)
     vrt = landsat.get_vrt([4, 3, 2])
     self.assertIsNotNone(vrt)
     dataset = landsat.get_dataset([4, 3, 2], DataType.UINT16)
     self.assertIsNotNone(dataset)
    def test_metadata_extent(self):
        r = requests.get("https://raw.githubusercontent.com/johan/world.geo.json/master/countries/USA/NM/Taos.geo.json")
        taos_geom = r.json()
        print(taos_geom)

        taos_shape = shapely.geometry.shape(taos_geom['features'][0]['geometry'])

        metadata_service = MetadataService()
        # sql_filters = ['scene_id="LC80330342017072LGN00"', 'collection_number="PRE"']
        landsat_filters = LandsatQueryFilters()
        landsat_filters.scene_id.set_value("LC80330342017072LGN00")
        landsat_filters.collection_number.set_value("PRE")
        rows = metadata_service.search(
            SpacecraftID.LANDSAT_8,
            data_filters=landsat_filters)
        rows = list(rows)
        self.assertEqual(len(rows), 1)

        metadata = rows[0]

        # GDAL helper functions for generating VRT
        landsat = Landsat(metadata)

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE]
        scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
        vrt = landsat.get_vrt(band_numbers, envelope_boundary=taos_shape.bounds)

        with open('clipped_LC80330342017072LGN00.vrt', 'r') as myfile:
            data = myfile.read()
            expected = etree.XML(data)
            actual = etree.XML(vrt)
            result, message = xml_compare(expected, actual, {"GeoTransform": 1e-10, "xOff": 1e-10, "yOff": 1e-10})
            self.assertTrue(result, message)

        dataset = gdal.Open(vrt)
        geo_transform = dataset.GetGeoTransform()

        # self.assertEqual(geo_transform, raster_metadata.get_geotransform(taos_shape.bounds))
        # self.assertNotEqual(geo_transform, raster_metadata.get_geotransform())

        """
    def test_datatypes(self):
        landsat = Landsat(self.metadata_set)

        # get a numpy.ndarray from bands for specified imagery
        band_numbers = [Band.RED, Band.GREEN, Band.BLUE]
        scaleParams = [[0.0, 40000], [0.0, 40000], [0.0, 40000]]

        for data_type in DataType:
            if data_type is DataType.UNKNOWN_GDAL:
                continue

            nda = landsat.fetch_imagery_array(
                band_numbers,
                scaleParams,
                envelope_boundary=self.taos_shape.bounds,
                output_type=data_type,
                spatial_resolution_m=240)
            self.assertIsNotNone(nda)
            self.assertGreaterEqual(data_type.range_max, nda.max())
            self.assertLessEqual(data_type.range_min, nda.min())
    def test_unmount_destructor_conflict(self):
        wkt = "POLYGON((136.2469482421875 -27.57843813308233,138.6639404296875 -27.57843813308233," \
              "138.6639404296875 -29.82351878748485,136.2469482421875 -29.82351878748485,136." \
              "2469482421875 -27.57843813308233))"

        polygon = loads(wkt)

        # sql_filters = ['cloud_cover=0']
        d_start = date(2006, 8, 4)
        d_end = date(2006, 8, 7)
        bounding_box = polygon.bounds
        # sql_filters = ['wrs_row=79']
        landsat_filters = LandsatQueryFilters()
        landsat_filters.wrs_row.set_value(79)
        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_5,
            data_filters=landsat_filters)

        rows = list(rows)

        metadata = rows[0]
        landsat = Landsat(metadata)
        vrt = landsat.get_vrt([4])
        storage = Storage("gcp-public-data-landsat")
        landsat_2 = Landsat(metadata)
        vrt = landsat_2.get_vrt([4])
        del landsat
        self.assertTrue(storage.is_mounted(metadata))
    def test_vrt_not_pre(self):
        d_start = date(2017, 6, 24)
        d_end = date(2017, 9, 24)
        bounding_box = (-115.927734375, 34.52466147177172, -78.31054687499999,
                        44.84029065139799)
        # sql_filters = ['collection_number!="PRE"']
        landsat_filter = LandsatQueryFilters()
        landsat_filter.collection_number.set_exclude_value("PRE")
        landsat_filter.acquired.set_range(d_start, True, d_end, True)
        landsat_filter.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(SpacecraftID.LANDSAT_8,
                                            limit=1,
                                            data_filters=landsat_filter)

        rows = list(rows)
        metadata = rows[0]

        landsat = Landsat(metadata)
        self.assertIsNotNone(landsat)
        vrt = landsat.get_vrt([4, 3, 2])
        self.assertIsNotNone(vrt)
        dataset = landsat.get_dataset([4, 3, 2], DataType.UINT16)
        self.assertIsNotNone(dataset)
 def test_band_enum(self):
     self.assertTrue(True)
     d_start = date(2016, 7, 20)
     d_end = date(2016, 7, 28)
     landsat_filter = LandsatQueryFilters()
     landsat_filter.scene_id.set_value("LC80390332016208LGN00")
     landsat_filter.acquired.set_range(d_start, True, d_end, True)
     rows = self.metadata_service.search(SpacecraftID.LANDSAT_8,
                                         limit=1,
                                         data_filters=landsat_filter)
     rows = list(rows)
     metadata = rows[0]
     landsat = Landsat(metadata)
     scale_params = [[0.0, 65535], [0.0, 65535], [0.0, 65535]]
     # nda = landsat.__get_ndarray(band_numbers, metadata, scale_params)
     nda = landsat.fetch_imagery_array([Band.RED, Band.GREEN, Band.BLUE],
                                       scale_params,
                                       spatial_resolution_m=240)
     self.assertIsNotNone(nda)
     nda2 = landsat.fetch_imagery_array([4, 3, 2],
                                        scale_params,
                                        spatial_resolution_m=240)
     np.testing.assert_almost_equal(nda, nda2)
    def test_pixel_1(self):
        metadata = self.m_metadata
        landsat = Landsat(metadata)  # , gsurl[2])

        code = """import numpy as np
def multiply_rounded(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize,
                   raster_ysize, buf_radius, gt, **kwargs):
    factor = float(kwargs['factor'])
    out_ar[:] = np.round_(np.clip(in_ar[0] * factor,0,255))"""

        function_arguments = {"factor": "1.5"}
        pixel_function_details = FunctionDetails(name="multiply_rounded", band_definitions=[2],
                                                 data_type=DataType.FLOAT32, code=code,
                                                 arguments=function_arguments)

        vrt = landsat.get_vrt([pixel_function_details, 3, 2])

        with open('pixel_1.vrt', 'r') as myfile:
            data = myfile.read()
            expected = etree.XML(data)
            actual = etree.XML(vrt)
            result, message = xml_compare(expected, actual, {"GeoTransform": 1e-10})
            self.assertTrue(result, message)
    def test_landsat5_vrt(self):
        # 5th Place: Lake Eyre Landsat 5 Acquired August 5, 2006
        wkt = "POLYGON((136.2469482421875 -27.57843813308233,138.6639404296875 -27.57843813308233," \
              "138.6639404296875 -29.82351878748485,136.2469482421875 -29.82351878748485,136." \
              "2469482421875 -27.57843813308233))"

        polygon = loads(wkt)

        # sql_filters = ['cloud_cover=0']
        d_start = date(2006, 8, 4)
        d_end = date(2006, 8, 5)
        bounding_box = polygon.bounds
        landsat_filters = LandsatQueryFilters()
        landsat_filters.wrs_row.set_value(79)
        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_5,
            data_filters=landsat_filters)

        rows = list(rows)

        self.assertEqual(len(rows), 1)

        # data structure that contains all fields from Google's Landsat BigQuery Database
        metadata = rows[0]

        # GDAL helper functions for generating VRT
        landsat = Landsat(metadata)
        vrt = landsat.get_vrt([3, 2, 1])

        with open('testlandsat5.vrt', 'r') as myfile:
            data = myfile.read()
            expected = etree.XML(data)
            actual = etree.XML(vrt)
            result, message = xml_compare(expected, actual, {"GeoTransform": 1e-10})
            self.assertTrue(result, message)
    def test_vrt(self):
        d_start = date(2015, 6, 24)
        d_end = date(2016, 6, 24)
        bounding_box = (-115.927734375, 34.52466147177172, -78.31054687499999, 44.84029065139799)
        # sql_filters = ['scene_id="LC80400312016103LGN00"']
        landsat_filters = LandsatQueryFilters()
        landsat_filters.scene_id.set_value("LC80400312016103LGN00")
        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(SpacecraftID.LANDSAT_8,
                                            limit=1,
                                            data_filters=landsat_filters)

        rows = list(rows)

        metadata = rows[0]
        landsat = Landsat(metadata)
        vrt = landsat.get_vrt([4, 3, 2])
        with open('test_1.vrt', 'r') as myfile:
            data = myfile.read()
            expected = etree.XML(data)
            actual = etree.XML(vrt)
            result, message = xml_compare(expected, actual)
            self.assertTrue(result, message)

        dataset = gdal.Open(vrt)
        self.assertIsNotNone(dataset)

        ds_band_1 = dataset.GetRasterBand(1)
        self.assertIsNotNone(ds_band_1)
        self.assertEqual(ds_band_1.XSize, 7631)
        ds_band_2 = dataset.GetRasterBand(2)
        self.assertIsNotNone(ds_band_2)
        self.assertEqual(ds_band_2.YSize, 7771)
        ds_band_3 = dataset.GetRasterBand(3)
        self.assertIsNotNone(ds_band_3)
        self.assertEqual(ds_band_3.YSize, 7771)
    def test_iowa_scaled(self):
        d_start = date(2016, 4, 4)
        d_end = date(2016, 8, 7)
        bounding_box = self.iowa_polygon.bounds
        # sql_filters = ["cloud_cover<=15"]
        landsat_filters = LandsatQueryFilters()
        landsat_filters.cloud_cover.set_range(end=15, end_inclusive=True)

        landsat_filters.acquired.set_range(d_start, True, d_end, True)
        landsat_filters.aoi.set_bounds(*bounding_box)
        rows = self.metadata_service.search(
            SpacecraftID.LANDSAT_8,
            data_filters=landsat_filters)
        rows = list(rows)
        metadata = rows[0]
        landsat = Landsat(metadata)

        code = """import numpy as np
def ndvi_numpy(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, raster_ysize, buf_radius, gt, **kwargs):
    with np.errstate(divide = 'ignore', invalid = 'ignore'):
        factor = float(kwargs['factor'])
        out_ar[:] = np.divide((in_ar[1] - in_ar[0]), (in_ar[1] + in_ar[0]))
        out_ar[np.isnan(out_ar)] = 0.0
        # shift range from -1.0-1.0 to 0.0-2.0
        out_ar += 1.0
        # scale up from 0.0-2.0 to 0 to 255 by multiplying by 255/2
        out_ar *= factor/2.0"""

        # pixel_function_details = {
        #     "function_arguments": {"factor": 255},
        #     "band_numbers": [4, Band.NIR],
        #     "function_code": code,
        #     "function_type": "ndvi_numpy",
        #     "data_type": DataType.FLOAT32,
        # }

        pixel_function_details = FunctionDetails(name="ndvi_numpy",
                                                 band_definitions=[4, Band.NIR],
                                                 code=code, arguments={"factor": 255},
                                                 data_type=DataType.FLOAT32)

        band_definitions = [pixel_function_details, Band.RED, 5]

        vrt = landsat.get_vrt(band_definitions)
        ds = gdal.Open(vrt)

        self.assertIsNotNone(ds)

        arr_4 = ds.GetRasterBand(2).ReadAsArray()
        arr_5 = ds.GetRasterBand(3).ReadAsArray()
        arr_ndvi = ds.GetRasterBand(1).ReadAsArray()
        del ds
        del landsat
        print(np.ndarray.max(arr_ndvi))
        # print(np.ndarray.min(arr_ndvi))
        # self.assertFalse(np.any(np.isinf(arr_ndvi)))
        self.assertIsNotNone(arr_ndvi)

        local_ndvi = self.ndvi_numpy(arr_5, arr_4)
        del arr_4
        del arr_5

        local_ndvi += 1.0
        local_ndvi *= float(pixel_function_details.arguments['factor']) / 2.0
        self.assertFalse(np.any(np.isinf(local_ndvi)))

        np.floor(arr_ndvi, out=arr_ndvi)
        np.floor(local_ndvi, out=local_ndvi)
        np.testing.assert_almost_equal(arr_ndvi, local_ndvi, decimal=0)