Datasets:

Modalities:
Image
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 13,456 Bytes
b7a6232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""
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.')