Beispiel #1
0
def add_item(source_item: Item,
             target_catalog: Catalog,
             move_assets: bool = False) -> None:
    """Add a item into a catalog.

    Args:
        source_item (pystac.Item): The Item that will be added.
            This item is not mutated in this operation.
        target_catalog (pystac.Item): The destination catalog.
            This catalog will be mutated in this operation.
        move_assets (bool): If true, move the asset files alongside the target item.
    """

    target_item_ids = [item.id for item in target_catalog.get_all_items()]
    if source_item.id in target_item_ids:
        raise ValueError(
            f'An item with ID {source_item.id} already exists in the target catalog'
        )
    self_href = target_catalog.get_self_href()
    if self_href:
        parent_dir = os.path.dirname(self_href)
        layout_strategy = BestPracticesLayoutStrategy()
        item_copy = source_item.clone()
        item_copy.set_self_href(
            layout_strategy.get_item_href(item_copy, parent_dir))
        target_catalog.add_item(item_copy)

        if isinstance(target_catalog, Collection):
            item_copy.set_collection(target_catalog)
            target_catalog.update_extent_from_items()
        else:
            item_copy.set_collection(None)

        if move_assets:
            do_move_assets(item_copy, copy=False)
    else:
        raise ValueError(
            f"Cannot add Item {source_item.id} because {target_catalog} does not have a self href."
        )
Beispiel #2
0
def stage(input_references):
    
    STAC_IO.read_text_method = my_read_method
    
    catalogs = []

    for index, input_reference in enumerate(input_references):

        items = []

        thing = read_file(input_reference)

        if isinstance(thing, Item):

            items.append(thing)

        elif isinstance(thing, Catalog):

            for item in thing.get_items():

                items.append(item)

        # create catalog
        catalog = Catalog(id=items[0].id,
                  description='staged STAC catalog with {}'.format(items[0].id))

        catalog.add_items(items)

        catalog.normalize_and_save(root_href=items[0].id,
                                   catalog_type=CatalogType.RELATIVE_PUBLISHED)

        catalog.describe()

        catalogs.append(os.path.dirname(catalog.get_self_href()))
        
    return catalogs
Beispiel #3
0
def scombi(channel_inputs, bands, s_expressions, resolution='highest', aoi=None, color=None, profile=None, lut=None, epsg=None):

    target_dir = 'combi'
    
    if not os.path.exists(target_dir):
    
        os.mkdir(target_dir)
        
    items = []
    assets_href = []
    rescaled = []
    
    for index, input_path in enumerate(channel_inputs):
    #for index, input_path in enumerate([red_channel_input, green_channel_input, blue_channel_input]):
    
        if input_path is None:
            
            items.append(None)
            assets_href.append(None)
            continue
            
        item = get_item(input_path) 
        
        logging.info(item)
        
        items.append(item)
        assets_href.append(get_band_asset_href(item, bands[index]))

    # define AOI, if none is supplied, get the minimum bbox 
    if aoi is None:
        aoi = get_mbb([shape(item.geometry) for item in items]).wkt

    min_lon, min_lat, max_lon, max_lat = loads(aoi).bounds

    # analyze get an EPSG code if it hasn't been supplied
    # check if warp is needed
    epsg, epsg_codes = get_epsg(epsg, assets_href)

    # rescale and get the original assets (these are part of the output)
    logging.info('Rescaling and COG for input assets')
    rescaled = []
    
    # get the data
    for index, asset_href in enumerate(assets_href):

        if asset_href is None:
            
            rescaled.append(None)
            
            continue
            
        logging.info('Getting band {} from {}'.format(bands[index], asset_href))
        
        output_name = '{}/{}_{}.tif'.format(target_dir, index+1, bands[index])

        
        if epsg_codes[index] == epsg:

            ds = gdal.Translate(output_name, 
                                asset_href, 
                                outputType=gdal.GDT_Float32,
                                projWin=[min_lon, max_lat, max_lon, min_lat],
                                projWinSRS='EPSG:4326')

        else:

            logging.info('Warp')
            ds = gdal.Warp(output_name, 
                        asset_href, 
                        outputType=gdal.GDT_Float32,
                        outputBounds=[min_lon, min_lat, max_lon, max_lat],
                        outputBoundsSRS='EPSG:4326',
                        dstSRS=epsg) 
        

        ds = None

        del(ds)
        #rescaled.append(ds)
        rescaled.append(output_name)
    
    # build a VRT with the rescaled assets with the selected resolution mode
    logging.info('Build VRT')
    vrt = 'temp.vrt'
    ds = gdal.BuildVRT(vrt,
                       [ds for ds in rescaled if ds],
                       resolution=resolution, 
                       separate=True)

    ds.FlushCache()
    
    output_cell_size = ds.GetGeoTransform()[1]

    logging.info(str(output_cell_size))

    logging.info('Pimp me')

    pimp.me(vrt, 
            f'{target_dir}/combi.tif', 
            bands, 
            s_expressions,
            color, 
            lut)

    ds = None
    del(ds)
    
    # to STAC
    logging.info('STAC')
    cat = Catalog(id='scombidooo',
                  description="Combined RGB composite") 

    # TODO fix datetime
    item = Item(id='combi',
                geometry=mapping(loads(aoi)),
                bbox=list(loads(aoi).bounds),
                datetime=items[0].datetime,
                properties={'bands': bands,
                            's_expressions': s_expressions,
                            'input_items': [_item.id for _item in items],
                            'color': 'N/A' if not color else color,
                            'profile': 'N/A' if not profile else profile}) 

    item.common_metadata.set_gsd(output_cell_size)

    eo_item = extensions.eo.EOItemExt(item)

    for index, asset_href in enumerate(assets_href):
        if asset_href is None:
            continue
        _asset =  get_band_asset(items[index],
                                 bands[index]) 
      
        _asset.href = './{}_{}.tif'.format(index+1, bands[index])

        item.add_asset('{}_{}'.format(index+1, bands[index]), _asset)

        
    # add the result.tif Asset
    item.add_asset(key='rgb',
                   asset=Asset(href='./combi.tif',
                               media_type=MediaType.COG))
        
    cat.add_items([item])
    
    cat.normalize_and_save(root_href='./',
                           catalog_type=CatalogType.SELF_CONTAINED)
     
    logging.info('Done!')

    return(cat.get_self_href())
Beispiel #4
0
 def get_catalog_href(self, cat: Catalog, parent_dir: str,
                      is_root: bool) -> str:
     return str(cat.get_self_href())