-
Notifications
You must be signed in to change notification settings - Fork 0
/
PaRaVis.py
2074 lines (1850 loc) · 74.4 KB
/
PaRaVis.py
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
# List of libraries required by the script
needed_libraries = [
"jupyterthemes==0.20.0",
"ipywidgets==7.7.2",
"tk==0.1.0",
"xarray==2022.12.0",
"rioxarray==0.13.3",
"rasterio==1.3.4",
"numpy==1.26.2",
"spyndex==0.2.0",
"pandas==1.5.3",
"matplotlib==3.5.1",
"seaborn==0.12.2",
"ray==2.7.0",
"tqdm==4.64.1",
]
# List to store missing libraries
missing_libraries = []
# Loop through the required libraries and try importing them
for library in needed_libraries:
try:
__import__(library)
except ImportError:
# If the library is not found, add it to the list of missing libraries
missing_libraries.append(library)
# Use os.system to run 'pip install' to install the missing library
os.system(f"pip install {library}")
# Check if any libraries were missing and print the results
if missing_libraries:
print("Installed the following missing libraries:")
for library in missing_libraries:
print(library)
else:
print("All required libraries are already installed.")
# In[ ]:
# NBVAL_SKIP
# For changeing theme and notebook visualization
try:
import jupyterthemes
themes_installed = True
except ImportError:
themes_installed = False
if themes_installed:
print("Jupyter Themes is already installed.")
else:
# Install jupyterthemes package
get_ipython().system('pip install jupyterthemes')
print("Jupyter Themes is installed.")
# Change cell width and apply a theme
if themes_installed:
# Apply the 'grade3' theme with a cell width of 100%
get_ipython().system('jt -t grade3 -cellw 100% -N -T')
# -t grade3: Applies the 'grade3' theme.
# -cellw 100%: Sets the cell width to 100%.
# -T: Changes the toolbar appearance.
print("Themes have been changed. Please refresh this page (press F5).")
# In[ ]:
# Import libraries
import math
import os
import platform
import subprocess
import tkinter as tk
import warnings
from itertools import combinations
from tkinter import Tk, filedialog
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import rasterio
import ray
import rioxarray
import seaborn as sns
import spyndex
import xarray as xr
from IPython.display import clear_output, display
from ipywidgets import interactive, widgets
from mpl_toolkits.axes_grid1 import make_axes_locatable
from rasterio.io import MemoryFile
from tqdm import tqdm
# In[ ]:
# Disable all warnings
warnings.filterwarnings("ignore")
plt.rcParams[
"font.family"
] = "DejaVu Sans" # Use a font that supports Unicode characters
# Check if running in an interactive session
if "CI" not in os.environ:
root = tk.Tk() # Create the main Tkinter
root.wm_attributes("-topmost", 1) # display on top
root.eval("tk::PlaceWindow . center")
root.withdraw()
else:
root = None # Set root to None in non-interactive mode/testing
# Define a dic for datasets
indices_dict = {}
# Function to open and reproject GeoTIFF datasets
def open_gd(bt):
clear_output(wait=True) # Clear the output area
# Select GeoTIFF datasets using Tkinter
root = Tk()
root.withdraw()
file_paths = filedialog.askopenfilenames(
filetypes=(("GeoTIFF files", "*.tif;*.tiff"), ("All files", "*.*"))
)
global dataset_dict
dataset_dict = {} # For saving selected datasets
for file_path in file_paths:
global file_name
file_name = os.path.splitext(os.path.basename(file_path))[0]
dataset = xr.open_rasterio(file_path).astype("float64")
# Reprojection datasets
dst_crs = "EPSG:4326" # Define the target CRS (WGS 84, EPSG:4326)
dataset = dataset.rio.reproject(dst_crs) # Reproject the dataset to EPSG:4326
dataset = dataset.where(dataset != 0, np.nan) # Replace 0 values with NaN
bounds = dataset.rio.transform()
dataset_dict[file_name] = {"dataset": dataset, "bounds": bounds}
print("GeoTIFF datasets loaded:", dataset_dict.keys())
display(widgets_row) # Display the main container
# Normalize the bands to the range [0, 1]
def normalize(band):
band_min, band_max = (band.min(), band.max())
return (band - band_min) / ((band_max - band_min))
# For calculating desire indices
def calculate_indices(b):
# Check if user selected any VI ro not
if len(index_selection.value) == 0:
print("Error: Please select one or more indices to campute.")
return
selected_bands = [selection_widget.value for selection_widget in band_selection]
selected_indices = (
list(index_selection.value)
if len(index_selection.value) > 1
else list(index_selection.value)[0]
)
global indices_dict
indices_dict = {}
for file_name, data in dataset_dict.items():
dataset = data["dataset"]
bounds = data["bounds"]
snt = dataset / 10000
index = index_names
# Specify parameters for indices calculation
params = {
"B": snt.sel(band=selected_bands[0]),
"G": snt.sel(band=selected_bands[1]),
"R": snt.sel(band=selected_bands[2]),
"RE1": snt.sel(band=selected_bands[3]),
"N": snt.sel(band=selected_bands[4]),
"N2": snt.sel(band=selected_bands[5]),
"L": 0.5,
"g": 2.5,
"C1": 6,
"C2": 7.5,
"kNN": 0.5,
"kNR": spyndex.computeKernel(
kernel="RBF",
params={
"a": snt.sel(band=selected_bands[4]),
"b": snt.sel(band=selected_bands[2]),
"sigma": snt.sel(band=[selected_bands[4], selected_bands[2]]).mean(
"band"
),
},
),
}
# Calculate the indices and place them in the defined dictionary
idx = spyndex.computeIndex(index=selected_indices, params=params)
indices_dict[file_name] = {}
# Add bands to dictionary as seperate Gtiff
for band in snt.band:
selected_band_data = snt.sel(band=band)
bands_data = normalize(selected_band_data)
indices_dict[file_name][f"Band{band.item()}"] = bands_data
if len(index_selection.value) > 1:
for i in selected_indices:
indices_data = idx.sel(index=f"{i}")
normalized_data = normalize(indices_data)
indices_dict[file_name][i] = normalized_data
else:
indices_data = idx
normalized_data = normalize(indices_data)
indices_dict[file_name][selected_indices] = normalized_data
# Calculate and add CV values
for dataset, indices in indices_dict.items():
for index_name, index_data in indices.items():
mean_value = np.mean(index_data)
std_deviation = np.std(index_data)
cv_percentage = (std_deviation / mean_value) * 100 # CV in percentage
# Add to existing dictionary
indices[index_name]["cv_percentage"] = cv_percentage
print("Indices calculation finished!")
dataset_up_dr()
# For Ploting figures
def plot_figure(button):
clear_output(wait=True) # Clear the output for multiple attempts
# Get values from widgets
selected_dataset = dataset_dropdown.value
selected_indices = indices_dropdown.value
selected_cmap = cmap_dropdown.value
cv_value = float(indices_dict[selected_dataset][selected_indices]["cv_percentage"])
bounds = dataset_dict[selected_dataset]["bounds"]
selected_indices_data = indices_dict[selected_dataset][selected_indices]
normalized_indices_data = normalize(selected_indices_data)
# Figure options
plt.figure(figsize=(20, 5))
plt.imshow(normalized_indices_data, cmap=selected_cmap, vmin=0, vmax=1)
cbar = plt.colorbar(pad=0.01, label="Value")
cbar.ax.get_yaxis().label.set_fontsize(12) # Set font size for the colorbar label
cbar.ax.get_yaxis().label.set_fontweight(
"bold"
) # Set font weight for colorbar label
plt.title(
f"{selected_indices} - {selected_dataset} - CV: {cv_value:.2f}%\n",
size=14,
fontweight="semibold",
)
x_ticks = np.linspace(
bounds[2], (bounds[2] + selected_indices_data.shape[1] * bounds[0]), num=5
)
y_ticks = np.linspace(
bounds[5], (bounds[5] + selected_indices_data.shape[0] * bounds[4]), num=5
)
plt.xticks(
np.linspace(0, selected_indices_data.shape[1], num=5),
["{:.2f}\u00b0 {}".format(tick, "W" if tick < 0 else "E") for tick in x_ticks],
size=10,
fontweight="semibold",
ha="left",
)
plt.yticks(
np.linspace(0, selected_indices_data.shape[0], num=5),
["{:.2f}\u00b0 {}".format(tick, "S" if tick < 0 else "N") for tick in y_ticks],
size=10,
fontweight="semibold",
)
plt.gca().xaxis.get_major_ticks()[4].label1.set_visible(False)
plt.gca().xaxis.get_major_ticks()[4].tick1line.set_visible(False)
plt.gca().yaxis.get_major_ticks()[4].label1.set_visible(False)
plt.gca().yaxis.get_major_ticks()[4].tick1line.set_visible(False)
plt.xlabel("Longitude", size=12, fontweight="semibold")
plt.ylabel("Latitude", size=12, fontweight="semibold")
plt.xticks(rotation=0) # Rotate the x-axis ticks
plt.yticks(rotation=90) # Rotate the y-axis ticks
display(widgets_row)
plt.show()
# For selecting the Path
def select_path(button):
root = tk.Tk()
root.withdraw()
save_path = filedialog.askdirectory()
save_path_text.value = save_path
save_path_text_2.value = save_path
# For saving the figure
def save_figure(button):
# Get values from widgets
selected_dataset = dataset_dropdown.value
selected_indices = indices_dropdown.value
selected_cmap = cmap_dropdown.value
save_path = save_path_text.value
save_name = save_name_text.value
dpi = dpi_dropdown.value
file_format = format_dropdown.value
cv_value = float(indices_dict[selected_dataset][selected_indices]["cv_percentage"])
bounds = dataset_dict[selected_dataset]["bounds"]
selected_indices_data = indices_dict[selected_dataset][selected_indices]
normalized_indices_data = normalize(selected_indices_data)
# Figure options
plt.figure(figsize=(20, 5))
plt.imshow(normalized_indices_data, cmap=selected_cmap, vmin=0, vmax=1)
cbar = plt.colorbar(pad=0.01, label="Value")
cbar.ax.get_yaxis().label.set_fontsize(12)
cbar.ax.get_yaxis().label.set_fontweight("bold")
plt.title(
f"{selected_indices} - {selected_dataset} - CV: {cv_value:.2f}%\n",
size=14,
fontweight="semibold",
)
x_ticks = np.linspace(
bounds[2], (bounds[2] + selected_indices_data.shape[1] * bounds[0]), num=5
)
y_ticks = np.linspace(
bounds[5], (bounds[5] + selected_indices_data.shape[0] * bounds[4]), num=5
)
plt.xticks(
np.linspace(0, selected_indices_data.shape[1], num=5),
["{:.2f}\u00b0 {}".format(tick, "W" if tick < 0 else "E") for tick in x_ticks],
size=10,
fontweight="semibold",
ha="left",
)
plt.yticks(
np.linspace(0, selected_indices_data.shape[0], num=5),
["{:.2f}\u00b0 {}".format(tick, "S" if tick < 0 else "N") for tick in y_ticks],
size=10,
fontweight="semibold",
)
plt.gca().xaxis.get_major_ticks()[4].label1.set_visible(False)
plt.gca().xaxis.get_major_ticks()[4].tick1line.set_visible(False)
plt.gca().yaxis.get_major_ticks()[4].label1.set_visible(False)
plt.gca().yaxis.get_major_ticks()[4].tick1line.set_visible(False)
plt.xlabel("Longitude", size=12, fontweight="semibold")
plt.ylabel("Latitude", size=12, fontweight="semibold")
plt.yticks(rotation=90) # Rotate the y-axis ticks
save_figure_path = f"{save_path}/{save_name}.{file_format}"
plt.savefig(save_figure_path, dpi=dpi, bbox_inches="tight")
plt.close()
print(f"Figure saved as {save_figure_path}")
# For saving Gtiff of selected VI files
def save_indices(button):
# Get user-selected inputs
selected_dataset = dataset_dropdown_2.value
selected_indices_with_cv = index_tosave.value
save_path = save_path_text.value
dataset_info = dataset_dict[selected_dataset]
# Iterate over selected indices and save selected indices GeoTIFFs
for index_with_cv in selected_indices_with_cv:
index_name = index_with_cv.split(" ---------- ")[0]
index_data = indices_dict[selected_dataset][f"{index_name}"]
output_path = f"{save_path}/{selected_dataset}_{index_name}.tif"
original_dataset = dataset_info["dataset"]
index_data.rio.write_crs(original_dataset.rio.crs, inplace=True)
index_data.rio.to_raster(output_path, compress="lzw")
print(f"Index '{index_name}' saved as {output_path}")
# For updating the dataset dropdowns
def dataset_up_dr():
# First dataset dropdown
dataset_dropdown.options = list(indices_dict.keys())
dataset_dropdown.value = list(dataset_dict.keys())[0]
indices_dropdown.options = list(indices_dict[file_name].keys())
# Second dataset dropdown
dataset_dropdown_2.options = list(dataset_dict.keys())
dataset_dropdown_2.value = list(dataset_dict.keys())[0]
# For updating the index_tosave widget with indices sorted by CV value
def indices_up_dr(change):
selected_location = change.new
selected_indices = indices_dict.get(selected_location, {})
sorted_indices = sorted(
selected_indices.items(), key=lambda x: x[1]["cv_percentage"], reverse=True
) # Sort indices based on CV value
index_tosave.options = [
f"{index_name} ---------- CV value: {index_info['cv_percentage']:.2f}%"
for index_name, index_info in sorted_indices
]
# Create header widgets
header_widget1 = widgets.HTML(
"<h3 style='font-family: Arial, sans-serif; color: white; font-weight:semibold; background-color: blue; text-align: center;'>Bands Order</h3>"
)
header_widget2 = widgets.HTML(
"<h3 style='font-family: Arial, sans-serif; color: white; font-weight: semibold; background-color: blue; text-align: center;'>Indices Selection</h3>"
)
header_widget3 = widgets.HTML(
"<h3 style='font-family: Arial, sans-serif; color: white; font-weight: semibold; background-color: blue; text-align: center;'>Indices Visualization</h3>"
)
header_widget4 = widgets.HTML(
"<h3 style='font-family: Arial, sans-serif; color: white; font-weight: semibold; background-color: blue; text-align: center;'>Saving Indices</h3>"
)
# Create a button widget for loading
load_button = widgets.Button(description="Load Datasets")
# Create GUI for band selection
band_names = ["Blue", "Green", "Red", "Red Edge", "Near Infrared 1", "Near Infrared 2"]
default_band_numbers = [2, 3, 5, 6, 7, 8] # Default band numbers (for WV-2 dataset)
band_selection = []
for i in range(len(band_names)):
selection_widget = widgets.Dropdown(
options=list(range(1, 10)),
value=default_band_numbers[i], # Set default value
description=band_names[i] + ":",
)
band_selection.append(selection_widget)
# Indices list
index_names = [
"ARI",
"ARI2",
"BAI",
"BCC",
"BNDVI",
"CIG",
"CIRE",
"CVI",
"DVI",
"EVI",
"EVI2",
"ExG",
"ExGR",
"ExR",
"FCVI",
"GARI",
"GBNDVI",
"GCC",
"GLI",
"GNDVI",
"GOSAVI",
"GRNDVI",
"GRVI",
"GSAVI",
"IKAW",
"IPVI",
"MCARI",
"MCARI1",
"MCARI2",
"MCARIOSAVI",
"MGRVI",
"MNLI",
"MRBVI",
"MSAVI",
"MSR",
"MTVI1",
"MTVI2",
"NDREI",
"NDTI",
"NDVI",
"NDWI",
"NDYI",
"NGRDI",
"NIRv",
"NLI",
"NormG",
"NormNIR",
"NormR",
"OSAVI",
"RCC",
"RDVI",
"RGBVI",
"RGRI",
"RI",
"SARVI",
"SAVI",
"SI",
"SR",
"SR2",
"SR3",
"SeLI",
"TCARI",
"TCARIOSAVI",
"TCI",
"TDVI",
"TGI",
"TVI",
"TriVI",
"VARI",
"VARI700",
"VI700",
"VIG",
"kIPVI",
"kNDVI",
"kRVI",
]
# Create multiselection for selecting indices to calculate
index_selection = widgets.SelectMultiple(
options=index_names, layout=widgets.Layout(width="300px", height="190px")
)
# Create multiselection box for indices we want to save
index_tosave = widgets.SelectMultiple(
layout=widgets.Layout(width="300px", height="90px")
)
# For indices calculation button
calculate_button = widgets.Button(description="Calculate Indices")
calculate_button.layout.margin = "0px 0px 0px 140px" # Adjust the margins
calculate_button.layout.width = "150px"
# For plotting and saving the figure
plot_button = widgets.Button(description="Plot Figure")
save_button = widgets.Button(description="Save Figure")
path_button = widgets.Button(description="Output Path")
# For entering the save path and plot name
save_path_text = widgets.Text(
description="Output Path:", placeholder="Enter output path here"
)
save_name_text = widgets.Text(
description="Output Name:", placeholder="Enter plot name here", value="index_fig"
)
# For DPI, Format and Colormap
dpi_dropdown = widgets.Dropdown(
description="DPI:", options=[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
)
format_dropdown = widgets.Dropdown(
description="Format:", options=["png", "jpg", "svg", "tiff", "tif"]
)
cmap_dropdown = widgets.Dropdown(
description="Colormap:", options=plt.colormaps(), value="nipy_spectral"
)
# Dataset and Indices dropdowns
indices_dropdown = widgets.Dropdown(options=[], description="Indices:")
dataset_dropdown = widgets.Dropdown(
options=list(indices_dict.keys()), description="Dataset:"
)
# For dataset selection
dataset_dropdown_2 = widgets.Dropdown(
options=list(indices_dict.keys()), description="Dataset:"
)
# For save path
save_path_text_2 = widgets.Text(
description="Output Path:", placeholder="Enter output path here"
)
path_button_2 = widgets.Button(description="Output Path")
save_button_2 = widgets.Button(description="Save Indices")
path_button_2.layout.margin = "4px 4px 0px 155px"
save_button_2.layout.margin = "6px 6px 0px 155px"
# ordering Containers for widgets
plot_container = widgets.HBox([cmap_dropdown, plot_button])
path_container = widgets.HBox([save_path_text, path_button])
dropdowns_container = widgets.VBox([dpi_dropdown, format_dropdown])
save_container = widgets.HBox([save_name_text, save_button])
main_container = widgets.VBox(
[
dataset_dropdown,
indices_dropdown,
plot_container,
dropdowns_container,
path_container,
save_container,
]
)
widgets_container = widgets.VBox(
[dataset_dropdown_2, index_tosave, save_path_text_2, path_button_2, save_button_2]
)
index_widget = widgets.VBox([index_selection, calculate_button])
vbox_margin = "10px"
widgets_row = widgets.HBox(
[
load_button,
widgets.VBox([header_widget1] + band_selection),
widgets.VBox([header_widget2, index_widget]),
widgets.VBox([header_widget3, main_container]),
widgets.VBox([header_widget4, widgets_container]),
],
layout=widgets.Layout(justify_content="space-between", margin=f"0px {vbox_margin}"),
)
display(widgets_row)
# Attach the update function to the dropdown's value change event
dataset_dropdown_2.observe(indices_up_dr, names="value")
# Attach functions to buttons
load_button.on_click(open_gd)
calculate_button.on_click(calculate_indices)
plot_button.on_click(plot_figure)
save_button.on_click(save_figure)
path_button.on_click(select_path)
path_button_2.on_click(select_path)
save_button_2.on_click(save_indices)
# In[ ]:
# For updating widgets base on uni or multidimensional mode
def update_input(mode_value):
if mode_value == "unidimensional":
input_text.description = "Input File:"
input_button.description = "Input"
else:
input_text.description = "Input Files:"
input_button.description = "Inputs"
# For selecting the input(s)
def select_input(btn):
root = tk.Tk()
root.withdraw()
if mode.value == "unidimensional":
file_path = filedialog.askopenfilename(
filetypes=[("TIFF Files", "*.tif" or "*.ttif")]
)
if file_path:
input_text.options = [file_path]
input_text.value = os.path.basename(
file_path
) # Assign the file name without the path
global input_indice
input_indice = [rasterio.open(file_path)]
else:
file_paths = filedialog.askopenfilenames(
filetypes=[("TIFF Files", "*.tif" or "*.ttif")]
)
if file_paths:
input_text.options = list(file_paths)
input_text.value = "\n".join(
[os.path.basename(fp) for fp in file_paths]
) # Display file names only
input_indices.clear()
input_indices.extend([rasterio.open(fp) for fp in file_paths])
# For selecting output path
def select_path(button):
root = tk.Tk()
root.withdraw()
save_path = filedialog.askdirectory()
output_text.value = save_path
# for getting available Memory
def get_memory_usage():
system_platform = platform.system()
# Linux-specific memory monitoring
if system_platform == "Linux":
try:
output = subprocess.check_output(["free", "-b"])
lines = output.decode("utf-8").split("\n")
data = lines[1].split()
available_memory = int(data[6])
return available_memory / (1024**3) # Convert to GB
except Exception as e:
print("Error:", str(e))
return None
# Windows-specific memory monitoring
elif system_platform == "Windows":
try:
response = os.popen('systeminfo | find "Available Physical Memory"').read()
available_memory = int(
response.split(":")[1].strip().split(" ")[0].replace(",", "")
) / (
1024
) # Convert to GB
return available_memory
except Exception as e:
print("Error:", str(e))
return None
else:
print("Unsupported operating system:", system_platform)
return None
# Check if the platform is Linux
if platform.system() == "Linux":
# Check if running in interactive mode
if "CI" not in os.environ:
sudo_password = input("Enter your sudo password: ")
clear_output(wait=True) # Clear the output area
else:
# in case of non-interactive mode/tests
sudo_password = "sudopass"
# Call rao function when a button is clicked
def click(btn):
ray.shutdown() # for running again
p_minkowski = p_minkowskii.value # Get the degree param for minkowski
# Compute Euclidean distance between two vectors
def euclidean_dist(pair_list):
return math.sqrt(sum([(x[0] - x[1]) ** 2 for x in pair_list]))
# Compute Manhattan distance between two vectors
def manhattan_dist(pair_list):
return sum([abs(x[0] - x[1]) for x in pair_list])
# Compute Chebyshev distance between two vectors
def chebyshev_dist(pair_list):
return max([abs(x[0] - x[1]) for x in pair_list])
# Compute Jaccard distance between two vectors
def jaccard_dist(pair_list):
dists = []
for x in pair_list:
numerator = min(x[0], x[1])
denominator = max(x[0], x[1])
dists.append(1 - (numerator / denominator))
return sum(dists)
# Compute canberra distance between two vectors
def canberra_dist(pair_list):
dists = []
for x in pair_list:
numerator = abs(x[0] - x[1])
denominator = abs(x[0]) + abs(x[1])
dists.append(numerator / denominator)
return sum(dists)
# Compute Minkowski distance between two vectors with parameter p
def minkowski_dist(pair_list, p_minkowski):
return sum(
[(abs(x[0] - x[1]) ** p_minkowski) ** (1 / p_minkowski) for x in pair_list]
)
# Convert TIFF input(s) to NumPy array
def tiff_to_np(tiff_input):
matrix1 = tiff_input.read()
matrix1 = matrix1.reshape((matrix1.shape[1]), matrix1.shape[2])
minNum = -999
matrix1[matrix1 == minNum] = np.nan
return matrix1
# Write the computation output to a GeoTIFF file
def export_geotiff(naip_meta, output_rao, output_path):
naip_meta["count"] = 1
naip_meta["dtype"] = "float64"
with rasterio.open(output_path, "w", **naip_meta) as dst:
dst.write(output_rao, 1)
# Computes Rao's Q index for a specified range of rows and columns
@ray.remote
def compute_raoq_range(
row_start,
row_end,
col_start,
col_end,
trastersm_list,
window,
distance_m,
na_tolerance,
):
w = int(
(window - 1) / 2
) # Number of neighbors from the central pixel to the edge of the window
raoq_values = [] # Initialize a list to store computed Rao's Q values
# iterate through rows and columns
for rw in range(row_start, row_end):
for cl in range(col_start, col_end):
# Create a list of border condition results for all input arrays
borderCondition = [
np.sum(
np.invert(np.isnan(x[rw - w : rw + w + 1, cl - w : cl + w + 1]))
)
< np.power(window, 2) - ((np.power(window, 2)) * na_tolerance)
for x in trastersm_list
]
# Check if any array satisfies the border condition
if True in borderCondition:
raoq_values.append(np.nan)
else:
# Extract sub-windows for all input arrays
tw = [
x[rw - w : rw + w + 1, cl - w : cl + w + 1]
for x in trastersm_list
]
lv = [x.ravel() for x in tw] # Flatten the sub-windows
# Generate combinations of sub-window pairs
vcomb = combinations(range(lv[0].shape[0]), 2)
vcomb = list(vcomb)
vout = []
# Calculate selected distances for all sub-window pairs
for comb in vcomb:
lpair = [[x[comb[0]], x[comb[1]]] for x in lv]
if distance_m == "euclidean":
out = euclidean_dist(lpair)
elif distance_m == "manhattan":
out = manhattan_dist(lpair)
elif distance_m == "chebyshev":
out = chebyshev_dist(lpair)
elif distance_m == "canberra":
out = canberra_dist(lpair)
elif distance_m == "minkowski":
out = minkowski_dist(lpair, p_minkowski)
elif distance_m == "Jaccard":
out = jaccard_dist(lpair)
vout.append(out)
# Rescale the computed distances and calculate Rao's Q value
vout_rescaled = [x * 2 for x in vout]
vout_rescaled[:] = [x / window**4 for x in vout_rescaled]
raoq_value = np.nansum(vout_rescaled)
raoq_values.append(raoq_value)
# Return the results for the specified row and column range
return row_start, row_end, col_start, col_end, raoq_values
# Parallelizes the computation of Rao's Q
def parallel_raoq(
data_input,
output_path,
distance_m="euclidean",
window=9,
na_tolerance=0.0,
batch_size=100,
):
if window % 2 == 1:
w = int((window - 1) / 2)
else:
raise Exception(
"The size of the moving window must be an odd number. Exiting..."
)
# Convert input data to NumPy arrays
numpy_data = [tiff_to_np(data) for data in data_input]
# Initialize raoq array with NaN values
raoq = np.zeros(shape=numpy_data[0].shape)
raoq[:] = np.nan
# Create a list of transformed arrays for each input
trastersm_list = []
for mat in numpy_data:
trasterm = np.zeros(shape=(mat.shape[0] + 2 * w, mat.shape[1] + 2 * w))
trasterm[:] = np.nan
trasterm[w : w + mat.shape[0], w : w + mat.shape[1]] = mat
trastersm_list.append(trasterm)
# Adjust batch size to fit all pixels
max_rows = numpy_data[0].shape[0] - 2 * w + 1
max_cols = numpy_data[0].shape[1] - 2 * w + 1
batch_size = min(batch_size, max_rows, max_cols)
# Adjust row and column batches
rows = numpy_data[0].shape[0]
cols = numpy_data[0].shape[1]
row_batches = range(w, rows + w, batch_size)
col_batches = range(w, cols + w, batch_size)
# Adjust the last batch
row_batches = list(row_batches)
col_batches = list(col_batches)
if row_batches[-1] != rows + w:
row_batches.append(rows + w)
if col_batches[-1] != cols + w:
col_batches.append(cols + w)
# Use Ray to parallelize the computation
ray_results = []
for row_start, row_end in zip(row_batches[:-1], row_batches[1:]):
for col_start, col_end in zip(col_batches[:-1], col_batches[1:]):
pixel_data = (
row_start,
row_end,
col_start,
col_end,
trastersm_list,
window,
distance_m,
na_tolerance,
)
ray_results.append(compute_raoq_range.remote(*pixel_data))
# Update raoq array with the computed values
with tqdm(total=len(ray_results)) as pbar:
for result in ray_results:
row_start, row_end, col_start, col_end, raoq_values = ray.get(result)
raoq[
row_start - w : row_end - w, col_start - w : col_end - w
] = np.array(raoq_values).reshape(
row_end - row_start, col_end - col_start
)
pbar.update(1)
# Export the computed Rao's Q index as a TIFF file
info = data_input[0].profile
export_geotiff(info, raoq, output_path)
# Use the obtained password with the sudo command for linux platform
if platform.system() == "Linux":
command = f'echo "{sudo_password}" | sudo -S mount -o remount,size={memory_slider.value}G /dev/shm'
os.system(command)
# Initialize Ray
ray.init(
num_cpus=num_cpu_cores.value, object_store_memory=memory_slider.value * 10**9
)
output = parallel_raoq(
data_input=(input_indice if mode.value == "unidimensional" else input_indices),
output_path=(
r"{}/{}.tif".format(output_text.value, output_filename_text.value)
),
distance_m=distance_options.value,
window=window.value,
na_tolerance=na_tolerance.value,
batch_size=batch_size.value,
)
# Shutdown Ray
ray.shutdown()
input_indices = [] # List to store input rasterio.DatasetReader instances
# Create widgets for input parameters
mode = widgets.ToggleButtons(
options=["unidimensional", "multidimensional"],
description="Mode:",
value="unidimensional",
)
# Define the toggle buttons
distance_options = widgets.ToggleButtons(
options=["euclidean", "manhattan", "chebyshev", "Jaccard", "canberra", "minkowski"],
description="Distance:",
value="euclidean",
)
# Create the layout using GridBox
buttons_layout = widgets.GridBox(
children=[distance_options],
layout=widgets.Layout(grid_template_columns="repeat(1, 1fr)"),
)
# Create widgets for input parameters
output_text = widgets.Text(
description="Output Path:", placeholder="Enter output path here"
)
output_button = widgets.Button(description="Output Path")
output_filename_text = widgets.Text(description="Output name:", value="Rao")
p_minkowskii = widgets.BoundedIntText(description="degree:", value=2, min=2, max=5000)
window = widgets.BoundedIntText(description="Window:", min=1, max=333, step=2, value=3)
na_tolerance = widgets.BoundedFloatText(
description="NA Tolerance:", min=0, max=1, step=0.1, value=0.0
)
batch_size = widgets.BoundedIntText(
description="Batch size:", min=10, max=10000, step=10, value=100
)
input_text = widgets.Textarea(
value="", description="Input File:", placeholder="Input file(s) name"
)
# Create a Dropdown for workers
import multiprocessing
num_cpu_cores = widgets.Dropdown(
options=list(range(1, multiprocessing.cpu_count() + 1)),
description="CPU workers:",
)
# Get available memory
available_memory = get_memory_usage()