-
Notifications
You must be signed in to change notification settings - Fork 0
/
STELLA_brief_Nick_May31_ver6.py
2913 lines (2184 loc) · 111 KB
/
STELLA_brief_Nick_May31_ver6.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
# ![image.png](attachment:d1a6ee73-3085-450f-ae5a-dfa6a5f2c70a.png)
#
#
# # **Science-and-Technology-Society-Use-of-NASA-STELLA-Q2-Spectrometer**
#
# The **Science and Technology Society (STS) of Sarasota-Manatee Counties, Florida** is working with the NASA STELLA (Science and Technology Education for Land/Life Assessment) outreach program as a part of our STEM initiative. According to their site,
#
# - "NASA STELLA instruments are portable low-cost do-it-yourself (DIY) instruments that support science education, and outreach through scientific engagement, inquiry, and discovery while helping you understand Landsat better".
#
# **STELLA instruments are developed under the influence and inspiration of Landsat.** This alignment not only fulfills our project needs but also serves as a compelling addition to our STEAM initiatives:
#
# 1) To train the minds young Floridians to be more aware of our wetlands, to care for them and about them. Our program will bring more community publicity to the issue of wetlands change, as well.
#
# 2) To expose our middle- and high- school aged students to real science, using real data. That means how to use instrumentation and understand how the data is collected, and how the data can be used in the real world. It means not only to create beautiful charts and images that form the good results, but also to understand that data must be collected in a proper and reproducible way, that there physics reasons for lack of accuracy and lack of precision that one must understand and minimize in order to achieve meaningful results.
#
#
# The NASA STELLA-Q2 is capable of making 18 different spectral measurements from the violet/blue portions of the electromagnetic spectrum out to near infrared regions (beyond our range of vision).The following figure **(1)** shows the visible spectrum by wavelength, and the yellow box indicates the STELLA-Q2 frequency range.
#
# >![image](wavelengths.png)
#
#
# More can be found on the STELLA DIY instruments at the following link.
#
# >https://landsat.gsfc.nasa.gov/stella/
#
#
# The **Science and Technology Society (STS)** of Sarasota-Manatee Counties, FL have created a Jupyter Notebook to load raw **NASA STELLA-Q2** spectrometer data, white-card correct the wavelength data and then use **Decision Tree** and **Knn** to differentiate plant species based on the **mean End-Members** reference data where the **Normalized Difference Vegetative Index (NDVI)** is key to this analysis. NDVI is calculated:
#
# NDVI = (Near IR irradiance – Red irradiance)/( Near IR irradiance + Red irradiance)
#
#
# The STELLA-Q2 is a NASA configured hand-held spectrometer designed by Paul Mirel at NASA. The unit is relatively inexpensive and is used to collect End-Member data that can then be used to calibrate Landsat interpretations. Mike Taylor of NASA heads up the STELLA team, and he and his entire team have been so immensely helpful as we delve into calibrated Landsat interpretations.
#
# In our notebooks we employ a few novel python methods using Altair and Panel to display the actual plant species images along the time-series NDVI data for each of the spectrometer readings. This helps us better understand the subtle differences in the STELLA data and calculated values.
#
# >
# >![animated](STELLA_with_Photos.gif)
# >
# >
#
#
# ## **These are all of the wavelength plots colored by vegetative species after the white-card corrections:**
#
# >
# >![non-animated](wavelengths.png)
# >
#
# ## **The Decision Tree method allows us to better understand the logic used to differente one species from the other:**
#
# >
# >![non-animated](DecisionTree.png)
# >
#
# ## **The following table shows the various mean End-Members for each species used with our transparent Knn method:**
#
# >
# >![non-animated](EndMember.png)
# >
#
# ## **The STELLA data clusters naturally for each vegetative target species in red, near IR and NDVI space:**
#
# >
# >![non-animated](3D.png)
# >
#
#
#
# ### Load Python requirements:
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
import ipywidgets as widgets
from IPython.display import display
#import altair as alt
####import panel as pn
#pn.extension('vega')
#pn.extension('tabulator')
#####pn.extension(sizing_mode = 'stretch_width')
#######alt.data_transformers.disable_max_rows()
# # **1) Read in Excel data file in xlsx format collected on the STELLA-Q2 micro SD card:**
# ---
# In[2]:
#read the file
file = r'data_Nick_HomeDepot.xlsx'
df = pd.read_excel(file,index_col=False)
# Remove leading/trailing whitespaces in column names
df.columns = df.columns.str.strip()
df.head()
# # **2) Read in the average White-Card data for full-sun normailzation:**
# ---
#
# **The following is a single white-card full sun reading, but was taken from the average of all of the full sun white-card readings taken in this test found in the first row of data.**
# In[3]:
#read the file
file = r'data_Nick_HomeDepot_white.xlsx'
white = pd.read_excel(file,index_col=False, nrows=1)
# Remove leading/trailing whitespaces in column names
white.columns = white.columns.str.strip()
white.head()
# ## Explore the data:
# In[4]:
df.info()
# ## We did alter the original code.py file on the STELLA-Q2 to use actual color names for the following column data vs. *near IR* as in the original STELLA-Q2 code.py code file.
#
# 49 irradiance_680nm_black_wavelength_nm 60 non-null int64
# 50 irradiance_680nm_black_wavelength_uncertainty_nm 60 non-null int64
# 51 irradiance_680nm_black_irradiance_uW_per_cm_squared 60 non-null float64
# 52 irradiance_680nm_black_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 53 irradiance_705nm_brown_wavelength_nm 60 non-null int64
# 54 irradiance_705nm_brown_wavelength_uncertainty_nm 60 non-null int64
# 55 irradiance_705nm_brown_irradiance_uW_per_cm_squared 60 non-null float64
# 56 irradiance_705nm_brown_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 57 irradiance_730nm_gray_wavelength_nm 60 non-null int64
# 58 irradiance_730nm_gray_wavelength_uncertainty_nm 60 non-null int64
# 59 irradiance_730nm_gray_irradiance_uW_per_cm_squared 60 non-null float64
# 60 irradiance_730nm_gray_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 61 irradiance_760nm_silver_wavelength_nm 60 non-null int64
# 62 irradiance_760nm_silver_wavelength_uncertainty_nm 60 non-null int64
# 63 irradiance_760nm_silver_irradiance_uW_per_cm_squared 60 non-null float64
# 64 irradiance_760nm_silver_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 65 irradiance_810nm_lightgray_wavelength_nm 60 non-null int64
# 66 irradiance_810nm_lightgray_wavelength_uncertainty_nm 60 non-null int64
# 67 irradiance_810nm_lightgray_irradiance_uW_per_cm_squared 60 non-null float64
# 68 irradiance_810nm_lightgray_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 69 irradiance_860nm_linen_wavelength_nm 60 non-null int64
# 70 irradiance_860nm_linen_wavelength_uncertainty_nm 60 non-null int64
# 71 irradiance_860nm_linen_irradiance_uW_per_cm_squared 60 non-null float64
# 72 irradiance_860nm_linen_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 73 irradiance_900nm_wheat_wavelength_nm 60 non-null int64
# 74 irradiance_900nm_wheat_wavelength_uncertainty_nm 60 non-null int64
# 75 irradiance_900nm_wheat_irradiance_uW_per_cm_squared 60 non-null float64
# 76 irradiance_900nm_wheat_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
# 77 irradiance_940nm_gold_wavelength_nm 60 non-null int64
# 78 irradiance_940nm_gold_wavelength_uncertainty_nm 60 non-null int64
# 79 irradiance_940nm_gold_irradiance_uW_per_cm_squared 60 non-null float64
# 80 irradiance_940nm_gold_irradiance_uncertainty_uW_per_cm_squared 60 non-null float64
#
# In[5]:
df.describe()
# In[6]:
df.head()
# ## Plot Battery Voltage Level:
# In[7]:
plt.figure(figsize=(12, 6))
plt.plot(df['timestamp_iso8601'], df['battery_percent'], linewidth=4, color='red')
plt.ylim(0,100)
plt.xlabel('Timestamp (ISO8601)', color='blue')
plt.ylabel('Battery Percent', color='blue')
plt.title('Battery Percent Over Time', color='blue')
#plt.grid()
plt.show()
# In[8]:
# List of wavelengths for plotting
#wavelengths_to_plot = [410, 435, 450, 485, 510, 535, 560, 585, 610, 645, 680]
wavelengths_to_plot= [410, 435, 460, 485, 510, 535, 560, 585, 610, 645, 680, 705, 730, 760, 810, 860, 900, 940]
# Create subplots
fig, axs = plt.subplots(len(wavelengths_to_plot), 1, figsize=(10, 1 * len(wavelengths_to_plot)), sharex=True)
# Loop through each wavelength and plot the data
for i, wavelength in enumerate(wavelengths_to_plot):
# Use regex to match column names containing the wavelength
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
# Plot the data for each matched column
for column in wavelength_columns:
color = re.search(wavelength_pattern, column).group(1)
axs[i].plot(df['timestamp_iso8601'], df[column], label=f'{wavelength}nm - {color}',color=color,linewidth=3)
axs[i].set_ylabel('Irradiance (uW/cm^2)', color='blue')
#axs[i].set_ylim(0,1)
axs[i].legend()
# Set common xlabel and title
plt.xlabel('Timestamp (ISO8601)', color='blue')
plt.suptitle('Irradiance Over Time for Selected Wavelengths', y=0.89, color='blue')
#plt.grid()
# Show the plot
plt.show()
# In[9]:
from ipywidgets import interact, FloatRangeSlider, Layout
# Extract all unique wavelengths
wavelengths = sorted(set(re.findall(r'(\d+)nm_', ' '.join(df.columns))))
def update_plot(timestamp_index):
plt.figure(figsize=(12, 6))
timestamp = df['timestamp_iso8601'][timestamp_index]
test = df['Test'][timestamp_index]
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Define specific colors for certain wavelengths
if wavelength == '410':
color = 'purple'
elif wavelength == '435':
color = 'blue'
elif wavelength == '460':
color = 'dodgerblue'
elif wavelength == '485':
color = 'cyan'
elif wavelength == '510':
color = 'green'
elif wavelength == '535':
color = 'aquamarine'
elif wavelength == '560':
color = 'limegreen'
elif wavelength == '585':
color = 'yellow'
elif wavelength == '610':
color = 'orange'
elif wavelength == '645':
color = 'red'
elif wavelength == '680':
color = 'black'
elif wavelength == '705':
color = 'brown'
elif wavelength == '730':
color = 'gray'
elif wavelength == '760':
color = 'silver'
elif wavelength == '810':
color = 'lightgray'
elif wavelength == '860':
color = 'linen'
elif wavelength == '900':
color = 'wheat'
elif wavelength == '940':
color = 'gold'
# Map custom colors to standard recognized color names
# color = map_color(color)
# Check if the column exists before using it
if f'irradiance_{wavelength}nm_{color}_wavelength_nm' in df.columns and f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared' in df.columns:
wavelength_data = df[f'irradiance_{wavelength}nm_{color}_wavelength_nm'][timestamp_index]
irradiance_data = df[f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared'][timestamp_index]
wavelength_uncertainty = df[f'irradiance_{wavelength}nm_{color}_wavelength_uncertainty_nm'][timestamp_index]
irradiance_uncertainty = df[f'irradiance_{wavelength}nm_{color}_irradiance_uncertainty_uW_per_cm_squared'][timestamp_index]
# Create a Gaussian distribution
x_values = np.linspace(wavelength_data - 3 * wavelength_uncertainty,
wavelength_data + 3 * wavelength_uncertainty, 100)
y_values = irradiance_data * np.exp(-0.5 * ((x_values - wavelength_data) / wavelength_uncertainty) ** 2)
# Plot Gaussian distribution
plt.plot(x_values, y_values, label=f'{wavelength}nm - {color}', linestyle='--', linewidth=2, color=color)
# Plot data point with error bars
plt.errorbar(wavelength_data, irradiance_data, xerr=wavelength_uncertainty, yerr=irradiance_uncertainty,
linestyle='', marker='o', markersize=5, capsize=5, color=color)
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Irradiance (uW/cm^2)')
plt.xlim(350,1000)
#plt.ylim(0,30000)
#plt.ylim(0,30)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.grid()
#plt.title(f'Irradiance Over Wavelength by Timestamp {timestamp_index} and Batch {batch_index} for Backyard')
#plt.title(f"Irradiance Over Wavelength by Timestamp Index {timestamp_index}: \n \n Test Pattern {grass['Test']} for Backyard")
#plt.title(f"Raw Irradiance Over Wavelength by Pattern Type: {test} \n \n Test Pattern {grass['Test']} for Backyard")
plt.title(f"Raw Readings Irradiance Over Wavelength by Pattern Type: {test} ")
plt.show()
timestamp_slider = widgets.IntSlider(value=0, min=0, max=len(df) - 1, step=1, description='Timestamp Index',layout=Layout(width='90%'))
batch_slider = widgets.IntSlider(value=0, min=0, max=20, step=1, description='Batch Index')
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_index=timestamp_slider, batch_index=batch_slider)
# Display the interactive plot
display(interactive_plot)
# ## Line-Plot of raw Spectral Data:
# In[10]:
def update_plot(timestamp_index):
plt.figure(figsize=(12, 6))
timestamp = timestamp_index
test = df['Test'][timestamp_index]
wavelength_data_list = []
irradiance_data_list = []
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Check if the column exists before using it
if column in df.columns:
# Extract wavelength data
wavelength_data_str = wavelength
try:
wavelength_data = int(wavelength_data_str) # Convert string to integer
except ValueError:
try:
wavelength_data = float(wavelength_data_str) # Convert string to float
except ValueError:
continue # Skip if wavelength cannot be converted to int or float
# Append data to lists
wavelength_data_list.append(wavelength_data)
irradiance_data_list.append(df[column][timestamp_index])
# Plot data points
plt.plot(wavelength_data_list, irradiance_data_list, linestyle='dotted', marker = 'o',markersize = 5, markeredgecolor = 'blue', mfc = 'blue', linewidth = 3,color='red')
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Irradiance (uW/cm^2)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.xlim(350,1000)
#plt.ylim(0,14000)
plt.grid()
plt.title(f"Raw Readings Irradiance Over Wavelength by Test Pattern {test}")
plt.show()
# Create a slider widget
timestamp_slider = widgets.IntSlider(value=0, min=0, max=len(df) - 1, step=1, description='Timestamp Index',layout=Layout(width='99%'))
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_index=timestamp_slider)
# Display the interactive plot
display(interactive_plot)
# ## Plot bewtween a Sample Range:
# In[11]:
def update_plot(timestamp_range):
plt.figure(figsize=(12, 6))
start_timestamp_index, end_timestamp_index = timestamp_range
test = df['Test'][start_timestamp_index]
testb = df['Test'][start_timestamp_index]
teste = df['Test'][end_timestamp_index]
# Loop over the range of timestamp indices
for timestamp_index in range(start_timestamp_index, end_timestamp_index + 1):
wavelength_data_list = []
irradiance_data_list = []
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Check if the column exists before using it
if column in df.columns:
# Extract wavelength data
wavelength_data_str = wavelength
try:
wavelength_data = int(wavelength_data_str) # Convert string to integer
except ValueError:
try:
wavelength_data = float(wavelength_data_str) # Convert string to float
except ValueError:
continue # Skip if wavelength cannot be converted to int or float
# Append data to lists
wavelength_data_list.append(wavelength_data)
irradiance_data_list.append(df[column][timestamp_index])
# Plot data points
plt.plot(wavelength_data_list, irradiance_data_list, linestyle='dotted', marker='o', markersize=5, markeredgecolor='blue', mfc='blue', linewidth=2, color='red')
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Irradiance (uW/cm^2)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.xlim(350,1000)
plt.ylim(0,30000)
plt.grid()
#plt.title(f"Raw Readings Irradiance Over Wavelength by Pattern Type: {test} \n \n Test Pattern {df['Test']}")
plt.title(f"Raw Readings Irradiance Over Wavelength by Pattern Type: {testb} - to -{teste}")
plt.show()
# Create a range slider widget for timestamp indices
timestamp_range_slider = widgets.IntRangeSlider(value=(0, len(df) - 1), min=0, max=len(df) - 1, step=1, description='Timestamp Range', layout=Layout(width='90%'))
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_range=timestamp_range_slider)
# Display the interactive plot
display(interactive_plot)
# ---
# ---
# # **Now we will apply White Card Normalization to our data per recommendations from Paul Mirel.**
# ---
#
# ## Load White Standard data taken in same lighting conditions:
#
# ### Email from Paul Mirel of NASA, February 5, 2024:
# It’s general practice to measure a white reference in the same illumination as the sample, and then to measure the sample. The unitless reflectance from the sample is then the sample signal divided by the white reference signal, in each wavelength. Landsat uses a stretch of desert sand, or a huge white tarp!, as a reference. Spectralon is the material of choice for white references, but it’s expensive. We get quite good results with ordinary white Styrofoam (without cover sheets), and are considering using white playground sand, or a plain white felt acrylic blanket. The goal is a material that scatters light equally in all directions, and does not have much, or any, specular shiny reflectance.
#
#
# ## White and Gray Card Readings within Range:
# In[12]:
def update_plot(timestamp_range):
plt.figure(figsize=(12, 6))
start_timestamp_index, end_timestamp_index = timestamp_range
testb = white['Test'][start_timestamp_index]
teste = white['Test'][end_timestamp_index]
# Loop over the range of timestamp indices
for timestamp_index in range(start_timestamp_index, end_timestamp_index + 1):
wavelength_data_list = []
irradiance_data_list = []
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in white.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Check if the column exists before using it
if column in white.columns:
# Extract wavelength data
wavelength_data_str = wavelength
try:
wavelength_data = int(wavelength_data_str) # Convert string to integer
except ValueError:
try:
wavelength_data = float(wavelength_data_str) # Convert string to float
except ValueError:
continue # Skip if wavelength cannot be converted to int or float
# Append data to lists
wavelength_data_list.append(wavelength_data)
irradiance_data_list.append(white[column][timestamp_index])
# Plot data points
plt.plot(wavelength_data_list, irradiance_data_list, linestyle='dotted', marker='o', markersize=5, markeredgecolor='blue', mfc='blue', linewidth=2, color='red')
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Irradiance (uW/cm^2)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.xlim(350,1000)
plt.ylim(0,30000)
plt.grid()
#plt.title(f"Raw Readings Irradiance Over Wavelength by Pattern Type: {test} \n \n Test Pattern {df['Test']}")
plt.title(f"White and Gray Card Readings Irradiance Over Wavelength by Pattern Type: {testb} - to -{teste}")
plt.show()
# Create a range slider widget for timestamp indices
timestamp_range_slider = widgets.IntRangeSlider(value=(0, len(white) - 1), min=0, max=len(white) - 1, step=1, description='Timestamp Range', layout=Layout(width='90%'))
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_range=timestamp_range_slider)
# Display the interactive plot
display(interactive_plot)
# **In the above plot for our white standard, there is quite a range of magnitudes across what should be a uniform specrtum. This could be instrument bias.**
#
# ---
# ---
# # **White Card Correct all STELLA-Q2 Readings to the average of the White Card Readings.**
#
# ## Calculate Scaling Factor per Wavelength:
# In[13]:
# Extract the white standard readings from the DataFrame
# Initialize white_standard_readings as an empty dictionary
white_standard_readings = {}
# Extract all unique wavelengths
wavelengths = sorted(set(re.findall(r'(\d+)nm_', ' '.join(white.columns))))
timestamp = white['timestamp_iso8601'][0]
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in white.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Define specific colors for certain wavelengths
if wavelength == '410':
color = 'purple'
elif wavelength == '435':
color = 'blue'
elif wavelength == '460':
color = 'dodgerblue'
elif wavelength == '485':
color = 'cyan'
elif wavelength == '510':
color = 'green'
elif wavelength == '535':
color = 'aquamarine'
elif wavelength == '560':
color = 'limegreen'
elif wavelength == '585':
color = 'yellow'
elif wavelength == '610':
color = 'orange'
elif wavelength == '645':
color = 'red'
elif wavelength == '680':
color = 'black'
elif wavelength == '705':
color = 'brown'
elif wavelength == '730':
color = 'gray'
elif wavelength == '760':
color = 'silver'
elif wavelength == '810':
color = 'lightgray'
elif wavelength == '860':
color = 'linen'
elif wavelength == '900':
color = 'wheat'
elif wavelength == '940':
color = 'gold'
# Map custom colors to standard recognized color names
# color = map_color(color)
# Check if the column exists before using it
if f'irradiance_{wavelength}nm_{color}_wavelength_nm' in white.columns and f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared' in white.columns:
#wavelength_data = white[f'irradiance_{wavelength}nm_{color}_wavelength_nm'][0]
#irradiance_data = white[f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared'][0]
white_reading = white[f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared'][0]
white_standard_readings[wavelength] = white_reading
#print()
#print('1) This is the raw white card readings from our white card calibration:',white_reading, 'at', wavelength,'nm.')
#print()
#print('2) These are our white card standard wavelengths and readings from our spectrometer:',white_standard_readings,'used with wavelength', wavelength,'nm.')
scaling_factor_save = []
# Calculate scaling factors using only white standard readings
scaling_factors = {}
for wavelength, white_reading in white_standard_readings.items():
# Assuming the minimum possible reading is zero
scaling_factor = 1.0 / white_reading
scaling_factors[wavelength] = scaling_factor
scaling_factor_save.append(scaling_factor)
print('scaling_factor_save:',scaling_factor_save)
#print()
#print('3) These are our wavelengths and white scaling factors:',scaling_factors)
# Print scaling factors
k=0
print()
print("Scaling Factors:")
for wavelength, factor in scaling_factors.items():
print(f"4) These are our final wavelength and scaling factors per wavelength {wavelength}nm: {factor} \tline {k}")
k=k+1
#print([scaling_factors[factor] for wavelength in wavelengths])
# ## White Card Corrected Spectral Data Displayed as Gaussian points with Error for Individual Readings:
# In[14]:
# Extract all unique wavelengths
wavelengths = sorted(set(re.findall(r'(\d+)nm_', ' '.join(df.columns))))
def update_plot(timestamp_index):
plt.figure(figsize=(12, 6))
timestamp = df['timestamp_iso8601'][timestamp_index]
test = df['Test'][timestamp_index]
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Define specific colors for certain wavelengths
if wavelength == '410':
color = 'purple'
elif wavelength == '435':
color = 'blue'
elif wavelength == '460':
color = 'dodgerblue'
elif wavelength == '485':
color = 'cyan'
elif wavelength == '510':
color = 'green'
elif wavelength == '535':
color = 'aquamarine'
elif wavelength == '560':
color = 'limegreen'
elif wavelength == '585':
color = 'yellow'
elif wavelength == '610':
color = 'orange'
elif wavelength == '645':
color = 'red'
elif wavelength == '680':
color = 'black'
elif wavelength == '705':
color = 'brown'
elif wavelength == '730':
color = 'gray'
elif wavelength == '760':
color = 'silver'
elif wavelength == '810':
color = 'lightgray'
elif wavelength == '860':
color = 'linen'
elif wavelength == '900':
color = 'wheat'
elif wavelength == '940':
color = 'gold'
# Check if the column exists before using it
if f'irradiance_{wavelength}nm_{color}_wavelength_nm' in df.columns and f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared' in df.columns:
wavelength_data = df[f'irradiance_{wavelength}nm_{color}_wavelength_nm'][timestamp_index]
irradiance_data = df[f'irradiance_{wavelength}nm_{color}_irradiance_uW_per_cm_squared'][timestamp_index]
wavelength_uncertainty = df[f'irradiance_{wavelength}nm_{color}_wavelength_uncertainty_nm'][timestamp_index]
irradiance_uncertainty = df[f'irradiance_{wavelength}nm_{color}_irradiance_uncertainty_uW_per_cm_squared'][timestamp_index]
# Apply scaling factor to correct irradiance data
scaling_factor = scaling_factors[wavelength]
#print(scaling_factor)
corrected_irradiance_data = irradiance_data * scaling_factor
# Create a Gaussian distribution
x_values = np.linspace(wavelength_data - 3 * wavelength_uncertainty,
wavelength_data + 3 * wavelength_uncertainty, 100)
y_values = corrected_irradiance_data * np.exp(-0.5 * ((x_values - wavelength_data) / wavelength_uncertainty) ** 2)
# Plot Gaussian distribution
plt.plot(x_values, y_values, label=f'{wavelength}nm - {color}', linestyle='--', linewidth=2, color=color)
# Plot data point with error bars
#plt.errorbar(wavelength_data, corrected_irradiance_data, xerr=wavelength_uncertainty, yerr=irradiance_uncertainty,
# linestyle='', marker='o', markersize=5, capsize=5, color=color)
plt.errorbar(wavelength_data, corrected_irradiance_data, xerr=wavelength_uncertainty, yerr=irradiance_uncertainty*scaling_factor,
linestyle='', marker='o', markersize=5, capsize=5, color=color)
# Plot data point with error bars (same as before)
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
# Display the plot
plt.xlabel('Wavelength (nm)')
plt.ylabel('Corrected Irradiance (uW/cm^2)') # Updated ylabel to reflect correction
plt.xlim(350,1000)
plt.ylim(0,1)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.grid()
#plt.title(f'Corrected Irradiance Over Wavelength by Timestamp {timestamp} and Batch {batch_index} for Backyard')
plt.title(f"Corrected Irradiance Over Wavelength by Pattern Type: {test}")
plt.show()
timestamp_slider = widgets.IntSlider(value=0, min=0, max=len(df) - 1, step=1, description='Timestamp Index', layout=Layout(width='90%'))
batch_slider = widgets.IntSlider(value=0, min=0, max=20, step=1, description='Batch Index')
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_index=timestamp_slider, batch_index=batch_slider)
# Display the interactive plot
display(interactive_plot)
# ## White Card Corrected Spectral Data Over a Range of Readings:
# In[15]:
def update_plot(timestamp_range):
plt.figure(figsize=(12, 6))
start_timestamp_index, end_timestamp_index = timestamp_range
test = df['Test'][start_timestamp_index]
testb = df['Test'][start_timestamp_index]
teste = df['Test'][end_timestamp_index]
# Loop over the range of timestamp indices
for timestamp_index in range(start_timestamp_index, end_timestamp_index + 1):
wavelength_data_list = []
irradiance_data_list = []
for wavelength in wavelengths:
wavelength_pattern = f'{wavelength}nm_(.*?)_irradiance_uW_per_cm_squared'
wavelength_columns = [col for col in df.columns if re.search(wavelength_pattern, col)]
# Apply scaling factor to correct irradiance data
scaling_factor = scaling_factors[wavelength]
#print(scaling_factor)
#corrected_irradiance_data = irradiance_data * scaling_factor
for column in wavelength_columns:
color = 'black' # Default color for wavelengths not explicitly defined
# Check if the column exists before using it
if column in df.columns:
# Extract wavelength data
wavelength_data_str = wavelength
try:
wavelength_data = int(wavelength_data_str) # Convert string to integer
except ValueError:
try:
wavelength_data = float(wavelength_data_str) # Convert string to float
except ValueError:
continue # Skip if wavelength cannot be converted to int or float
# Append data to lists
wavelength_data_list.append(wavelength_data)
irradiance_data_list.append(df[column][timestamp_index]* scaling_factor)
# Plot data points
plt.plot(wavelength_data_list, irradiance_data_list, linestyle='dotted', marker='o', markersize=5, markeredgecolor='blue', mfc='blue', linewidth=2, color='red')
# Add background colors with low alpha
plt.axvspan(300, 450, alpha=0.5, color='violet',label='Near UV from 380-450m')
plt.axvspan(450, 495, alpha=0.2, color='blue',label='Blue from 450-495nm')
plt.axvspan(495, 570, alpha=0.2, color='green',label='Green from 495-570nm')
plt.axvspan(570, 590, alpha=0.2, color='yellow',label='Yellow from 570-590nm')
plt.axvspan(590, 620, alpha=0.2, color='orange',label='Orange from 590-620nm')
plt.axvspan(620, 750, alpha=0.2, color='red',label='Red from 620-750nm')
plt.axvspan(750, 1000, alpha=1, color='lavender',label='Near IR from 700-1,000nm')
plt.xlabel('Wavelength (nm)')
plt.ylabel('Irradiance (uW/cm^2)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.xlim(350,1000)
plt.ylim(0,1.2)
plt.grid()
#plt.title(f"Raw Readings Irradiance Over Wavelength by Pattern Type: {test} \n \n Test Pattern {df['Test']}")
plt.title(f"Corrected Readings Irradiance Over Wavelength by Pattern Type: {testb} - to -{teste}")
plt.show()
# Create a range slider widget for timestamp indices
timestamp_range_slider = widgets.IntRangeSlider(value=(0, len(df) - 1), min=0, max=len(df) - 1, step=1, description='Timestamp Range', layout=Layout(width='90%'))
# Create an interactive plot using widgets.interactive
interactive_plot = widgets.interactive(update_plot, timestamp_range=timestamp_range_slider)
# Display the interactive plot
display(interactive_plot)
# ---
# # **Can We use the average data for each Vegetative Species to Predict Each Species from STELLA Spectrometer data?**
# ---
#
#
#
# # **Define this example Test Patterns by Color and Names in the cell below:**
# ---
# **This is Test Case specific for your data.**
# In[16]:
# These are all of the Test Pattern Names
ndvi_names = [ 'Palm',
'Broad Leaf',
'Piney' ,
'Big Leaf',
'Coral' ,
'Piny Green',
'More Green Plant',
'Green Plant',
'Yellow Shrub',
'Red Broad Leaf',
'Vgreen',
'Red Plant',
'Leafy',
'Pink Flower',
'White Card']
# Define Name and Colors for each unique value in the 'Test' column
test_colors = {
'Palm':'limegreen',
'Broad Leaf':'aquamarine',
'Piney':'lawngreen',
'Big Leaf':'darkgreen',
'Coral':'magenta',
'Piny Green':'olive',
'More Green Plant':'green',
'Green Plant':'seagreen',
'Yellow Shrub':'yellow',
'Red Broad Leaf':'red',
'Vgreen':'lime',
'Red Plant':'deeppink',
'Leafy':'yellowgreen',
'Pink Flower':'pink',
'White Card':'silver'
}
# This is for Knn most frequent choice
# Get the test pattern names right from your STELLA data
def which_is_most_frequent(List):
#print(most_frequent(List))
if most_frequent(List) == 1:
test_pattern_knn.append('Palm')
elif most_frequent(List) == 2:
test_pattern_knn.append('Broad Leaf')
elif most_frequent(List) == 3:
test_pattern_knn.append('Piney')
elif most_frequent(List) == 4:
test_pattern_knn.append('Big Leaf')
elif most_frequent(List) == 5:
test_pattern_knn.append('Coral')
elif most_frequent(List) == 6:
test_pattern_knn.append('Piny Green')
elif most_frequent(List) == 7:
test_pattern_knn.append('More Green Plant')
elif most_frequent(List) == 8:
test_pattern_knn.append('Green Plant')
elif most_frequent(List) == 9:
test_pattern_knn.append('Yellow Shrub')
elif most_frequent(List) == 10:
test_pattern_knn.append('Red Broad Leaf')
elif most_frequent(List) == 11:
test_pattern_knn.append('Vgreen')
elif most_frequent(List) == 12:
test_pattern_knn.append('Red Plant')
elif most_frequent(List) == 13:
test_pattern_knn.append('Leafy')
elif most_frequent(List) == 14:
test_pattern_knn.append('Pink Flower')
elif most_frequent(List) == 15:
test_pattern_knn.append('White Card')
# In[17]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ipywidgets import widgets, Layout
def update_plot(timestamp_range):
plt.figure(figsize=(12, 6))