""" make_chips.py This script reads in HLS S30/L30 data and extracts band information around a chip_size x chip_size subset of the original raster grid. Snowy and cloudy chips beyond a threshold are discarded. Author: Besart Mujeci, Srija Chakraborty, Christopher Phillips Usage: python make_chips.py """ import rclone from pathlib import Path import shutil import pandas as pd from collections import Counter import cartopy.crs as ccrs import numpy as np import rasterio from rasterio.transform import from_gcps from rasterio.warp import transform from rasterio.windows import Window import os # --- --- --- def point_to_index(dataset, long, lat): """ Converts long/lat point to row, col position on rasterio grid. Args: dataset (Rasterio Object): rasterio object long (float): longitude float lat (float): latitude float Returns: tuple: tuple representing point mapping on grid """ from_crs = rasterio.crs.CRS.from_epsg(4326) to_crs = dataset.crs new_x,new_y = transform(from_crs,to_crs, [long], [lat]) new_x = new_x[0] new_y = new_y[0] # get row and col row, col = dataset.index(new_x,new_y) return(row, col) # --- --- --- # --- --- --- Citation for this function: Christopher Phillips def check_qc_bit(data, bit): """ Function to check QC flags Args: data (numpy array): rasterio numpy grid bit (int): 1 or 4 representing cloud or snow Returns: numpy array: numpy array with flagged indices marking cloud/snow """ qc = np.array(data//(10**bit), dtype='int') qc = qc-((qc//2)*2) return np.sum(qc)/qc.size # --- --- --- # --- --- --- rclone configuration, file collection cfg = "" result = rclone.with_config(cfg).run_cmd("ls", extra_args=[f"{idir}/"]) output_lines = result['out'].decode('utf-8').splitlines() file_list = [line.split(maxsplit=1)[1] for line in output_lines if line] # --- --- --- # --- --- --- Options hls_type = 'L30' # Switch between 'L30' and 'S30' manually. idir = "" # Raw Images Dir odir = "" # Output Chips Dir chip_size = 50 # Chip dimensions scale = 0.0001 # Scale value for HLS bandssqm cthresh = 0.05 # Cloud threshold sthresh = 0.02 # Snow/ice threshold # --- --- --- # --- --- --- Read station site data df = pd.read_csv("./TILED_filtered_flux_sites_2018_2021.csv") stations = df['SITE_ID'].tolist() tiles = [tile.split(";")[0] for tile in df['tiles'].tolist()] sYear = df['start_year'].tolist() eYear = df['end_year'].tolist() longs = df['LOCATION_LONG'].tolist() lats = df['LOCATION_LAT'].tolist() all_years = [str(sYear[i]) + "-" + str(eYear[i]) for i in range(len(df))] coords = [str(lat) + ";" + str(long) for lat, long in zip(lats, longs)] # --- --- --- for i, line in enumerate(tiles): station_data = [stations[i], coords[i].split(";")[0], coords[i].split(";")[1], all_years[i].split("-")[0], all_years[i].split("-")[1], "filler", tiles[i]] tile = station_data[-1].strip() print(f"Working on {tile}") # Determine years for this station years = range(int(station_data[3]), int(station_data[4])+1) for year in years: print(year) # Build path to this tile and locate all tifs tifs1 = sorted([filepath for filepath in file_list if tile in filepath and "B01" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs2 = sorted([filepath for filepath in file_list if tile in filepath and "B02" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs3 = sorted([filepath for filepath in file_list if tile in filepath and "B03" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs4 = sorted([filepath for filepath in file_list if tile in filepath and "B04" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs5 = sorted([filepath for filepath in file_list if tile in filepath and "B05" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs6 = sorted([filepath for filepath in file_list if tile in filepath and "B06" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs7 = sorted([filepath for filepath in file_list if tile in filepath and "B07" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs8 = sorted([filepath for filepath in file_list if tile in filepath and "B08" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs8A = sorted([filepath for filepath in file_list if tile in filepath and "B8A" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs9 = sorted([filepath for filepath in file_list if tile in filepath and "B09" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs10 = sorted([filepath for filepath in file_list if tile in filepath and "B10" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs11 = sorted([filepath for filepath in file_list if tile in filepath and "B11" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifs12 = sorted([filepath for filepath in file_list if tile in filepath and "B12" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band tifsF = sorted([filepath for filepath in file_list if tile in filepath and "Fmask" in filepath and hls_type in filepath and str(year) == filepath.split(".")[3][:4]]) # Numbered by band # Loop over each tif first = True chip_flag = False # Flag for detecting chip size errors for i in range(len(tifs2)): # Open tifs based on HLS product skip_file_iteration = False if (hls_type == 'L30'): # Ensure the sorted files are aligned correctly. # If a band is missing then things can go out of order. # Push 'filler' if layer is missing a band to maintain sorting. checkListMain = [tifs2, tifs3, tifs4, tifs5, tifs6, tifs7, tifsF] checkList = [tifs2[i], tifs3[i], tifs4[i], tifs5[i], tifs6[i], tifs7[i], tifsF[i]] checkList = ['.'.join(ele.split(".")[2:4]) for ele in checkList] counts = Counter(checkList) common_value, _ = counts.most_common(1)[0] for z, value in enumerate(checkList): if value != common_value: checkListMain[z].insert(i, "filler") # Push skip_file_iteration=True print(f"Misaligned - {checkList}") break if skip_file_iteration: continue try: if not os.path.exists(f"./{tile}"): os.makedirs(f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs2[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs3[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs4[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs5[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs6[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs7[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifsF[i]}", f"./{tile}") except: print(f"MISALIGNED FOR - {tifs2[i]} check if all bands exist") continue src2 = rasterio.open(tifs2[i]) src3 = rasterio.open(tifs3[i]) src4 = rasterio.open(tifs4[i]) src5 = rasterio.open(tifs5[i]) src6 = rasterio.open(tifs6[i]) src7 = rasterio.open(tifs7[i]) srcF = rasterio.open(tifsF[i]) elif (hls_type == 'S30'): # Ensure the sorted files are aligned correctly. # If a band is missing then order is compromised. # Push 'filler' if layer is missing a band to maintain sorting. checkListMain = [tifs2, tifs3, tifs4, tifs8A, tifs11, tifs12, tifsF] checkList = [tifs2[i], tifs3[i], tifs4[i], tifs8A[i], tifs11[i], tifs12[i], tifsF[i]] checkList = ['.'.join(ele.split(".")[2:4]) for ele in checkList] counts = Counter(checkList) common_value, _ = counts.most_common(1)[0] for z, value in enumerate(checkList): if value != common_value: checkListMain[z].insert(i, "filler") skip_file_iteration=True break if skip_file_iteration: continue try: if not os.path.exists(f"./{tile}"): os.makedirs(f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs2[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs3[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs4[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs8A[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs11[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifs12[i]}", f"./{tile}") rclone.with_config(cfg).copy(f"{idir}/{tifsF[i]}", f"./{tile}") except: print(f"MISALIGNED FOR - {tifs2[i]} check if all bands exist") continue src2 = rasterio.open(f"./{tifs2[i]}") src3 = rasterio.open(f"./{tifs3[i]}") src4 = rasterio.open(f"./{tifs4[i]}") src5 = rasterio.open(f"./{tifs8A[i]}") src6 = rasterio.open(f"./{tifs11[i]}") src7 = rasterio.open(f"./{tifs12[i]}") srcF = rasterio.open(f"./{tifsF[i]}") else: raise ValueError(f'HLS product type must be \"L30\" or \"S30\" not \"{hls_type}\".') # Station remains in the same spot/tile so only gather information once. if first: row, col = point_to_index(src2, float(station_data[2]), float(station_data[1])) y_offset = row - (chip_size // 2) x_offset = col - (chip_size // 2) window = Window(y_offset, x_offset, chip_size, chip_size) window_data = src2.read(window=window, boundless=True) window_transform = src2.window_transform(window) first = False # Subset tif bands = [] for src in (src2,src3,src4,src5,src6,src7): # Set the tuple to match desired bands # Scale and clip reflectances band = np.clip(src.read(1)[y_offset:y_offset + chip_size, x_offset:x_offset + chip_size]*scale, 0, 1) bands.append(band) bands = np.array(bands) # Check chip size and break out if wrong shape if (bands.shape[1] != chip_size) or (bands.shape[2] != chip_size): print(f'ERROR: Chip for tile {tile} is wronge size!\n Size is {band.shape[1:]} and not ({chip_size},{chip_size}).\nSkipping to next tile.') chip_flag = True break # Subset Fmask to get imperfections cbands = np.array(srcF.read(1)[y_offset:y_offset + 50, x_offset:x_offset + 50], dtype='int') cloud_frac = check_qc_bit(cbands, 1) snow_frac = check_qc_bit(cbands, 4) # Check cloud fraction if (cloud_frac > cthresh): print("CLOUDY") continue # Check snow/ice fraction if (snow_frac > sthresh): print("SNOWY") continue # Save chip with new metadata out_meta = src2.meta out_meta.update({'driver':'GTiff', 'height':bands.shape[1], 'width':bands.shape[2], 'count':bands.shape[0], 'dtype':bands.dtype, 'transform':window_transform}) save_name = f'./chips/{tifs2[i].replace("B02", f"{station_data[0]}_merged.{chip_size}x{chip_size}pixels")}' if not os.path.exists(save_name): os.makedirs(f"./chips/{tile}") with rasterio.open(save_name, 'w', **out_meta) as dest: dest.write(bands) rclone.with_config(cfg).copy(f"./chips/{tile}", f"{odir}/{tile}/") shutil.rmtree(Path(f"./chips/")) # If chip is the wrong size break to next station if chip_flag: print("Breaking to tile -- wrong size ") break shutil.rmtree(Path(f"./{tile}")) break print('Done chipping.')