Ejemplo n.º 1
0
def search(
    username, password, dataset, location, bbox, clouds, start, end, output, limit
):
    """Search for scenes."""
    api = API(username, password)

    where = {"dataset": dataset}
    if location:
        latitude, longitude = location
        where.update(latitude=latitude, longitude=longitude)
    if bbox:
        where.update(bbox=bbox)
    if clouds:
        where.update(max_cloud_cover=clouds)
    if start:
        where.update(start_date=start)
    if end:
        where.update(end_date=end)
    if limit:
        where.update(max_results=limit)

    results = api.search(**where)
    api.logout()

    if not results:
        return

    if output == "entity_id":
        for scene in results:
            click.echo(scene["entity_id"])

    if output == "display_id":
        for scene in results:
            click.echo(scene["display_id"])

    if output == "json":
        dump = json.dumps(results, indent=True)
        click.echo(dump)

    if output == "csv":
        with StringIO("tmp.csv") as f:
            w = csv.DictWriter(f, results[0].keys())
            w.writeheader()
            w.writerows(results)
            click.echo(f.getvalue())
Ejemplo n.º 2
0
def downloader(sat_choice=None,
               block=2027,
               dates=None,
               indice_requested=[False, False, False, True, False],
               test=False,
               root=str):
    api = API(username, password)
    if test == True:
        sat_choice = satellite_selector()
        dates = get_dates(sat_choice=sat_choice, test=False)
        indice_requested = indices_requested()
    request = str(random.randint(5, 101))
    try:
        try:
            os.rmdir(f'./Images/Request.{request}')
        except:
            os.mkdir(f'./Images/Request.{request}')
            os.mkdir(f"./Images/Request.{request}/Start_date")
            os.mkdir(f"./Images/Request.{request}/End_date")
    except:
        pass
    co_ord = csv_crawler(block=block, clipper=True, root=root)
    # print(co_ord)
    for (id, date) in enumerate(dates):
        scenes = scene_finder(api, sat_choice, date, coordinates=co_ord)
        print(scenes)
        # scene_list, scene_data = download_selector(scenes, test=True, sat_choice=sat_choice)
        scene_list, scene_data = download_selector(scenes,
                                                   sat_choice=sat_choice)
        scene_downloader(scene_list,
                         id=id,
                         request=request,
                         sat_choice=sat_choice)

    api.logout()

    return sat_choice, indice_requested
Ejemplo n.º 3
0
class QCConnectLandsat:
    def __init__(self, username, password, archive, backup_archive):
        """Connect API.

        Raise ProcessorFailedError on failure

        :param str username: username
        :param str password: password
        :param str archive: not used by Landsat implementation
        :param str backup_archive: not used by Landsat implementation
        """
        from landsatxplore.api import API as LandsatAPI
        from landsatxplore.exceptions import EarthExplorerError

        try:
            self.api = LandsatAPI(
                username, password
            )
        except EarthExplorerError as e:
            raise ProcessorFailedError(
                self,
                "Unable to connect API: {}".format(e),
                set_status=False
            )
        except json.JSONDecodeError as e:
            raise ProcessorFailedError(
                self,
                "Landsat server is down. It raised a JSON exception: "
                "{}".format(e),
                set_status=False
            )

    def __del__(self):
        if not hasattr(self, "api"):
            return

        from landsatxplore.exceptions import EarthExplorerError
        try:
            self.api.logout()
        except EarthExplorerError as e:
            Logger.error("Landsat server is down. {}".format(e))

    def query(self, footprint, kwargs):
        """Query API.

        :return: result
        """
        from landsatxplore.exceptions import EarthExplorerError

        kwargs['bbox'] = wkt2bbox(footprint, switch_axis=True)
        kwargs['max_results'] = 500
        del kwargs['producttype'] # used only for testing
        try:
            items = self.api.search(**kwargs)
        except EarthExplorerError as e:
            raise ProcessorFailedError(
                self,
                "Landsat server is down. "
                "{}".format(e),
                set_status=False
            )

        dict_items = {}
        for item in items:
            selected = False
            if self.filter_by_tiles:
                for tile in self.filter_by_tiles:
                    if str(tile) in item['entityId']:
                        selected = True
                        break
            else:
                selected = True
            if selected:
                dict_items[item['entityId']] = item
                # used tests only
                dict_items[item['entityId']]['producttype'] = item['displayId'].split('_')[1]
                dict_items[item['entityId']]['beginposition'] = \
                    datetime.strptime(item['startTime'], '%Y-%m-%d')
            else:
                Logger.info("IP {} skipped by tile filter".format(item['entityId']))

        return dict_items
Ejemplo n.º 4
0
                b5 = landsat_array[4][y][x].astype('int32')
                nvdi_array[i][y][x] = (b5 - b4) / (b5 + b4) * 10000.
                # print(min(max(nvdi_array[i][y][x],-10000),10000))
            except:
                # pass
                print("x = " + str(x) + "; y = " + str(y))
                print("b4 = " + str(b4) + "; b5 = " + str(b5))
    print(nvdi_array[i])

    # Convert NVDI matrix to tif file
    print("Converting NVDI matrix to GeoTiff file...")
    wkt = dataset.GetProjection()
    driver = gdal.GetDriverByName("GTiff")
    band = dataset.GetRasterBand(1)
    gt = dataset.GetGeoTransform()
    output_file = os.path.join(landsat_dir, landsat_product_id + "_NVDI.TIF")
    dst_ds = driver.Create(output_file, XSize, YSize, 1, gdal.GDT_Int16)
    dst_ds.GetRasterBand(1).WriteArray(nvdi_array[i])  # write output raster
    dst_ds.GetRasterBand(1).SetNoDataValue(0)  # set nodata value
    dst_ds.SetGeoTransform(gt)  # set geotransform from dataset
    srs = osr.SpatialReference()  # set spatial reference of output raster
    srs.ImportFromWkt(wkt)
    dst_ds.SetProjection(srs.ExportToWkt())
    ds = None  # close output raster dataset
    dst_ds = None  # close output raster dataset
    print("GeoTiff file created at" + output_file)

# Log out of api
print("Logging out of API...")
api.logout()