-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.R
2816 lines (2462 loc) · 123 KB
/
server.R
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
# Server file for Shiny App phenoRemote
server = function(input, output, session) {
observe({
shinyBS::toggleModal(session, 'curatedDataLogin')
})
#--------------------------------------------------------------------------------------------------------------------------------------
# REACTIVE VALUES
#--------------------------------------------------------------------------------------------------------------------------------------
variables = reactiveValues(
filter = 'All',
sites_df = cams_,
sites = site_names,
color_count = 1,
color = 'blue')
appeears = reactiveValues(
none = '')
highlighted = reactiveValues(
group = '')
phenocam = reactiveValues()
panel = reactiveValues(mode = '')
counter = reactiveValues(countervalue = 0)
modis = reactiveValues(data = data.frame(),
cached_ndvi = list())
data = reactiveValues(my_user = 'start',
tasks_left = 100,
site_width = 375,
site_height = 225,
tasks = NULL,
token = NULL,
NLCD = FALSE,
draw_mode = FALSE,
run = 0,
names = c(),
plot_data_table = FALSE,
df = data.frame(),
all_data = data.frame(),
veg_types = c(),
select_pixel_mode_was_on = FALSE,
pixel_sps = SpatialPolygons(list()),
pixel_sps_250m = SpatialPolygons(list()))
# Empty reactive spdf
value = reactiveValues(drawnPoly = SpatialPolygonsDataFrame(SpatialPolygons(list()),
data=data.frame()))
output$phenoTable = DT::renderDataTable(
cams_ ,
filter = 'top',
options = list(autoWidth = FALSE, scrollY = TRUE, scrollX = TRUE)
)
#--------------------------------------------------------------------------------------------------------------------------------------
# OUTPUTS
#--------------------------------------------------------------------------------------------------------------------------------------
table1 = dplyr::arrange(appeears_tasks_ndvi_tera, site_name)
table2 = dplyr::arrange(appeears_tasks_ndvi_aqua, site_name)
table3 = dplyr::arrange(appeears_tasks_evi_tera, site_name)
table4 = dplyr::arrange(appeears_tasks_evi_aqua, site_name)
table5 = dplyr::arrange(appeears_tasks_lc, site_name)
table6 = dplyr::arrange(appeears_tasks_tds, site_name)
# Appeears ndvi_tera table
output$appeearsTable1 = DT::renderDataTable({
DT::datatable(table1 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears ndvi_aqua table
output$appeearsTable2 = DT::renderDataTable({
DT::datatable(table2 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears evi_tera table
output$appeearsTable3 = DT::renderDataTable({
DT::datatable(table3 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears evi_aqua table
output$appeearsTable4 = DT::renderDataTable({
DT::datatable(table4 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears MDOIS LC table
output$appeearsTable5 = DT::renderDataTable({
DT::datatable(table5 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears MODIS Tds table
output$appeearsTable6 = DT::renderDataTable({
DT::datatable(table6 %>% dplyr::select(site_name, task_name, task_id, created))
})
# Appeears my_appeears_tasks table
output$appeearsTable7 = DT::renderDataTable({
DT::datatable(data.frame())
})
# Create the map
output$map = renderLeaflet({
leaflet('map', data = variables$sites_df, options= leafletOptions(zoomControl=TRUE, doubleClickZoom = FALSE)) %>%
addTiles(
"http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.jpg",
attribution = 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
group = "World Imagery"
) %>%
addProviderTiles(
"OpenTopoMap",
group = "Open Topo Map",
options = providerTileOptions(transparent=FALSE)
) %>%
hideGroup("MODIS Land Cover") %>%
addDrawToolbar(
targetGroup = 'drawnPoly',
polylineOptions = FALSE,
rectangleOptions = FALSE,
markerOptions = FALSE,
circleMarkerOptions = FALSE,
circleOptions = FALSE,
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()),
polygonOptions = drawPolygonOptions(
showArea = TRUE,
repeatMode = FALSE,
shapeOptions = drawShapeOptions(
clickable = TRUE,
color = 'black',
fillColor = 'blue'))) %>%
# Rendering the mouseoutput (aka lat / lon)
onRender("function(el,x){
this.on('mousemove', function(e) {
var lat = e.latlng.lat;
var lng = e.latlng.lng;
var coord = [lat, lng];
Shiny.onInputChange('hover_coordinates', coord)});
this.on('mouseout', function(e) {
Shiny.onInputChange('hover_coordinates', null)})
}") %>%
setView(lng = -93.85, lat = 37.45, zoom = 4) %>%
# addStyleEditor(openOnLeafletDraw = TRUE) %>%
addMeasure(position = "topleft",
primaryLengthUnit = "meters",
primaryAreaUnit = "sqmeters",
activeColor = "#3D535D",
completedColor = "#7D4479") %>%
# Adds the layers options to top left of Map
addLayersControl(
baseGroups = c("World Imagery", "Open Topo Map"),
position = c("topleft"),
options = layersControlOptions(collapsed = FALSE))
})
# Adds the mouse lat / lon to an output (we can change this to anything)
output$mouse = renderText({
if(is.null(input$hover_coordinates)) {
"Mouse outside of map"
} else {
paste0("Lat: ", input$hover_coordinates[1],
"\nLng: ", input$hover_coordinates[2])
}
})
# Open landing page and initialze application
observe({
if (EMAIL_MODE == FALSE){
shinyjs::hide(id = 'emailShp')
}
switch_to_explorer_panel()
data$pixel_df = setNames(data.frame(matrix(ncol = 5, nrow = 0)), c("Pixel", "Site", "lat", 'lon', 'pft'))
data$pixel_sps_250m = SpatialPolygons(list())
data$midcell_pixel_sin = SpatialPoints(data.frame(x = 0, y = 0), proj4string=CRS(sinu_crs))[-1,]
panel$mode = 'explorer'
data$paois_df = setNames(data.frame(matrix(ncol = 4, nrow = 0)), c('Name', 'Longitude', 'Latitude', 'LeafletId'))
})
#--------------------------------------------------------------------------------------------------------------------------------------
# OBSERVERS
#--------------------------------------------------------------------------------------------------------------------------------------
# Login Switch
observeEvent(input$navbar, {
if (input$navbar == 'AppEEARS' & is.null(data$token)){
if (data$my_user == 'Phenocam'){
shinyjs::show(id = 'appeearsLogin')
} else {
shinyjs::show(id = 'curatedDataLogin')
shinyBS::toggleModal(session, 'curatedDataLogin')
}
}
})
# Login to Appeears
observeEvent(input$butLogin, {
withBusyIndicatorServer("butLogin", {
print ('Loging into curated dataset')
data$my_user = input$username
my_pass = input$pwInp
data$token_response = AppEEARS4R::appeears_start_session(data$my_user,my_pass)
data$token = paste("Bearer", data$token_response$token)
if (is.null(data$token_response$token)){
message('invalid username/password combo')
data$my_user = 'start'
shinyalert("Login error", 'Invalid username/password combo, try again.' , type = "error")
}else {
message('login successful')
shinyBS::toggleModal(session, 'curatedDataLogin')
# updateTabsetPanel(session, 'navbar', selected = 'curatedPanel')
shinyjs::show(id = 'appeearsLogout')
shinyjs::show(id = 'appeearsTools')
shinyjs::hide(id = 'appeearsLogin')
shinyjs::hide(id = 'submitionsLeft')
print (length(setdiff(cams_$site, appeears_tasks_ndvi_tera$site_name)))
if (length(setdiff(cams_$site, appeears_tasks_ndvi_tera$site_name)) > 0){
shinyjs::show(id = 'siteDifference')
shinyjs::hide(id = 'submitTasks')
updateSelectInput(session, id = 'siteDifference', choices = setdiff(cams_$site, appeears_tasks_ndvi_tera$site_name))
}else {
shinyjs::hide(id = 'siteDifference')
shinyjs::hide(id = 'submitTasks')
}
}
})
})
# Login Popup
observeEvent(input$appeearsLogin,{
shinyBS::toggleModal(session, 'curatedDataLogin')
})
# Import AppEEARS tasks
observeEvent(input$pullAppeearsTasks,{
withBusyIndicatorServer("pullAppeearsTasks", {
if (is.null(data$tasks)){
token = data$token
response = GET("https://lpdaacsvc.cr.usgs.gov/appeears/api/task", add_headers(Authorization = token))
task_response = prettify(jsonlite::toJSON(content(response), auto_unbox = TRUE))
data$tasks = jsonlite::fromJSON(txt=task_response)
# Appeears ndvi_tera table
output$appeearsTable7 = DT::renderDataTable({
DT::datatable(data$tasks %>%
dplyr::select(task_name, status, task_id, created) %>%
dplyr::mutate(created = as.Date(created)))
})
data$tasks_left = get_submitions_remaining(data$tasks)
updateTextInput(session, 'submitionsLeft', value = data$tasks_left)
shinyjs::show(id = 'submitionsLeft')
shinyjs::show(id = 'myTasks')
}else{
print ('Already grabbed tasks')
}
})
})
# Submit tasks to Appeears for Diff between ROI and Cached Tasks
observeEvent(input$submitTasks, {
print ('Pretending to send tasks to AppEEARS')
})
# Just use local Phenocam data, no password or username required
observeEvent(input$byPassLogin,{
data$my_user = 'phenocam'
shinyBS::toggleModal(session, 'curatedDataLogin')
shinyjs::show(id = 'appeearsLogin')
print (message('Not logging into Appeears and only using Phenocam tasks'))
})
# Logout of AppEEARS
observeEvent(input$appeearsLogout,{
# Remove token and tasks when logging out
data$token_response = NULL
data$token = NULL
data$my_user = 'start'
# data$tasks = data.frame(task_name = '<none>', status = '<none>',
# task_id = '<none>', created = '<none>')
shinyjs::hide(id = 'appeearsLogout')
shinyjs::hide(id = 'appeearsTools')
updateTabsetPanel(session, 'navbar', selected = 'Site explorer')
})
# Turns ROI off if drawImage is off
observe({
checked = input$drawImage
if (checked == FALSE){
updateCheckboxInput(session, inputId = 'drawImageROI', value = FALSE)
}
})
# Hides frequency UI element if GCC isn't selected for data to download/get
observe({
data = input$dataTypes_plot
if ('GCC' %in% data){
shinyjs::show(id = 'phenocamFrequency')
} else{
shinyjs::hide(id = 'phenocamFrequency')}
})
# # Opacity slider for NLCD
# observeEvent(input$nlcdOpacity, {
# if (data$NLCD){
# opa = input$nlcdOpacity
# print (opa)
# }
# })
# Start of Drawing - set highlight pixel to off
observeEvent(input$map_draw_start, {
data$draw_mode = TRUE
print ('Map Draw Start')
# Turn off highlight pixel mode if it is on
if(input$highlightPixelModeNDVI == TRUE){
updateCheckboxInput(session, 'highlightPixelModeNDVI', value=FALSE)
data$select_pixel_mode_was_on = TRUE
}
})
# Clears plot
observeEvent(input$clearPlot, {
output$ndvi_pixels_plot = renderPlot({
# Only plotting the first 250m pixel
df = data.frame()
p = ggplot(df) + geom_point() + xlim(0, 10) + ylim(0, 1)
p
})
})
# Event occurs when drawing a new feature starts
observeEvent(input$map_draw_new_feature, {
# Leaflet ID to add to the shapefile dataframe
id = input$map_draw_new_feature$properties$`_leaflet_id`
# Site name combined with run # for new polygon feature
data$run = data$run + 1
if (panel$mode =='analyzer'){
name_ = paste(c(isolate(input$site),data$run), collapse='_')
}else{
name_ = paste0('no_site_',data$run)
}
data$names = c(data$names, name_)
# Grabbing lat/lon values for new leaflet polygon
coor = unlist(input$map_draw_new_feature$geometry$coordinates)
Longitude = coor[seq(1, length(coor), 2)]
Latitude = coor[seq(2, length(coor), 2)]
# Building Dataframe with points from newly created leaflet feature
c = 0
for (x in Longitude){
c = c + 1
data$paois_df = rbind(data$paois_df, data.frame(Name = name_, Longitude = x, Latitude = Latitude[c], LeafletId = id))}
# Creating a SpatialPolygon that can be added to our spatial polygons dataframe (value$drawnPoly)
poly = Polygon(cbind(Longitude, Latitude))
polys = Polygons(list(poly), ID = name_)
spPolys = SpatialPolygons(list(polys))
# Adding new polygon to a spatial polygons dataframe
value$drawnPoly = rbind(value$drawnPoly,
SpatialPolygonsDataFrame(spPolys, data = data.frame(notes = NA,
row.names = row.names(spPolys))))
# Updating the select input for the download availability of created leaflet features
updateSelectInput(session, 'shapefiles', choices = unique(data$paois_df$Name))
updateSelectInput(session, 'shapefiles2', choices = unique(data$paois_df$Name))
# Building the polygon table from the data$paois_df dataframe containing all of the leaflet polygon data
build_polygon_table(data$paois_df)
# print (data$paois_df)
# sets highlight pixel to on
data$draw_mode = FALSE
print ('Exiting Draw Mode')
print (input$map_draw_stop)
shiny::showTab('navbar', 'paoiTab')
})
# When edited feature gets saved
observeEvent(input$map_draw_edited_features, {
# Leaflet ID to edit
id = input$map_draw_edited_features$features[[1]]$properties$`_leaflet_id`
# Grabbing lat/lon values for new leaflet polygon
coor = unlist(input$map_draw_edited_features$features[[1]]$geometry$coordinates[[1]])
Longitude = coor[seq(1, length(coor), 2)]
Latitude = coor[seq(2, length(coor), 2)]
name_ = unique(subset(data$paois_df, LeafletId == id)$Name)
# Deletes all rows with id being edited
data$paois_df = subset(data$paois_df, LeafletId != id)
# Adds back the edited polygon to the dataframe (data$paois_df)
c = 0
for (x in Longitude){
c = c + 1
data$paois_df = rbind(data$paois_df, data.frame(Name = name_, Longitude = x, Latitude = Latitude[c], LeafletId = id))}
# Updating the polygon table from the data$paois_df dataframe containing all of the leaflet polygon data
build_polygon_table(data$paois_df)
print (data$paois_df)
})
# When feature is deleted
observeEvent(input$map_draw_deleted_features, {
# Leaflet ID to delete
id = input$map_draw_deleted_features$features[[1]]$properties$`_leaflet_id`
# Deletes all rows with id being edited
print (data$paois_df)
data$paois_df = subset(data$paois_df, LeafletId != id)
# Updating the select input for the download availability of created leaflet features
updateSelectInput(session, 'shapefiles', choices = unique(data$paois_df$Name))
# Updating the polygon table from the data$paois_df dataframe containing all of the leaflet polygon data
build_polygon_table(data$paois_df)
})
observeEvent(input$shapefiles, {
file = input$shapefiles
updateTextInput(session, inputId = 'savePaoiFilename', value = file)
})
# Save shapefile button
observeEvent(input$downloadShp,{
site_name = input$site
WGScoor = subset(data$paois_df, data$paois_df$Name == input$shapefiles)
xy = select(WGScoor, Longitude, Latitude)
xy_matrix = data.matrix(xy)
p = Polygon(xy_matrix)
ps = Polygons(list(p),1)
sps = SpatialPolygons(list(ps))
proj4string(sps) = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
file = input$savePaoiFilename
folder = get_download_folder()
folder = paste0(folder,site_name,'_paoi/')
filename = paste(folder, file, sep='')
dir.create(folder)
print (filename)
shapefile(sps, filename, overwrite=TRUE)
shinyBS::toggleModal(session, 'saveShpPopup', toggle = 'close')
})
# Upload shapefile or KML?
observeEvent(input$shpFileName, {
imported_shpfile = input$shpFileName
# Add filter and make sure the user selected atleast the .dbf, .prj, .shp, and .shx!
temp_dir_name = dirname(imported_shpfile$datapath[1])
# Rename files
for (i in 1:nrow(imported_shpfile)) {
file.rename(imported_shpfile$datapath[i],
paste0(temp_dir_name, "/", imported_shpfile$name[i]))
}
print (imported_shpfile)
shp_file_name = paste(temp_dir_name,
imported_shpfile$name[grep(pattern = "*.shp$", imported_shpfile$name)], sep = "/")
print (shp_file_name)
uploaded_shp = readOGR(shp_file_name)
if (as.character(crs(uploaded_shp)) != wgs_crs){
print ('Wrong crs:')
print (crs(uploaded_shp))
print ('spTransforming it to WGS84')
new_test_shape = spTransform(uploaded_shp, wgs_crs)
leafletProxy("map") %>% addPolygons(data = new_test_shape)
} else{
leafletProxy("map") %>% addPolygons(data = uploaded_shp)
}
})
# Email shapefile button
observeEvent(input$emailShpButton, {
print ('Send Email')
site_name = input$site
WGScoor = subset(data$paois_df, data$paois_df$Name == input$shapefiles2)
xy = select(WGScoor, Longitude, Latitude)
xy_matrix = data.matrix(xy)
p = Polygon(xy_matrix)
ps = Polygons(list(p),1)
sps = SpatialPolygons(list(ps))
proj4string(sps) = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
tmp_dir = paste0('./www/', site_name, '_paoi')
file = isolate(input$shapefiles2)
filename = paste0(tmp_dir,'/', file)
dir.create(tmp_dir)
shapefile(sps, filename, overwrite=TRUE)
email_body = toString(WGScoor)
sender <- EMAIL_UN
# recipients <- c("kyle.enns13@alumni.colostate.edu")
recipients <- c(EMAIL_UN)
mailR::send.mail(from = sender,
to = recipients,
subject = paste0("Phenosynth Shapefile"),
body = paste0('<site_name>',site_name , '<name>',input$paoiUser,'\n<comment>', input$paoiNotes, '\n', email_body),
smtp = list(host.name = "smtp.gmail.com", port = 465,
user.name = EMAIL_UN, # UN and PW stored in the config.R file
passwd = EMAIL_PW, ssl = TRUE),
attach.files = c(paste0(filename,'.shp'),
paste0(filename,'.dbf'),
paste0(filename,'.prj'),
paste0(filename,'.shx')),
authenticate = TRUE,
send = TRUE)
# Remove the shapefile/folder
unlink(tmp_dir, recursive = TRUE)
shinyBS::toggleModal(session, 'emailShpPopup', toggle = 'close')
#Convert the points to polygons: see spatialpolygons post in stackoverflow
# https://stackoverflow.com/questions/26620373/spatialpolygons-creating-a-set-of-polygons-in-r-from-coordinates
})
# SELECT INPUT
# Filter based on Filter Sites dropdown
observeEvent(input$filterSites, {
variables$filter = input$filterSites
print ('Running Filter Sites')
if ('All' %in% variables$filter){
variables$sites_df = cams_
}else{
if ('Active' %in% variables$filter){
sub = subset(cams_, active == 'TRUE')
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
if ('Inactive' %in% variables$filter){
sub = subset(cams_, active == 'FALSE')
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
if ('Type1' %in% variables$filter){
sub = subset(cams_, site_type == 'I')
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
if ('Type2' %in% variables$filter){
sub = subset(cams_, site_type == 'II')
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
if ('Type3' %in% variables$filter){
sub = subset(cams_, site_type == 'III')
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
if ('NEON' %in% variables$filter){
sub = subset(cams_, group == 'NEON' | group == "NEON AMERIFLUX" | group == "NEON LTAR LTER AMERIFLUX")
if (dim(sub)[1]==0){
updateSelectInput(session, 'filterSites', selected = 'All')
updateSelectInput(session, 'site', choices = cams_$site)
}else {
variables$sites_df = sub
updateSelectInput(session, 'site', choices = variables$sites_df$site)
}
}
}
variables$sites = variables$sites_df$site
updateSelectInput(session, 'site', choices = variables$sites)
show_all_sites(map_ = 'map', data_ = variables$sites_df)
})
# BUTTON
# Zooms to the selected site in the Sites dropdown option with BUTTON
observeEvent(input$siteZoom, {
print('Running BUTTON Zoom to Selected Site')
site = isolate(input$site)
site_data = get_site_info(site)
zoom_to_site(site, site_data, zoom_ = TRUE, cams_, input$drawROI)
})
# BUTTON
# Zoom to contiguous US
observe ({
input$usZoom
input$siteExplorerMode
print('Running Zoom to contiguous US')
leafletProxy("map", data = variables$sites_df) %>%
setView(lng = -93.85, lat = 37.45, zoom = 4)
showAll = isolate(input$showSites)
print('Running add All sites back to map')
show_all_sites(map_ = 'map', data_ = variables$sites_df)
count()
})
# Add All sites back to map
observeEvent(input$showSites, {
showAll = input$showSites
# variables$sites_df = cams_
print('Running add All sites back to map')
show_all_sites(map_ = 'map', data_ = variables$sites_df)
count()
})
# Observer for the azm changes from 0-360 on the slider
observeEvent(input$azm, {
azm = as.numeric(input$azm)
if (input$drawROI == TRUE){
site = input$site
site_data = get_site_info(site)
run_add_polyline(site_data, azm)
}
})
# Draws fov polyline for a site location
observeEvent(input$drawROI, {
roi_bool = input$drawROI
if (roi_bool == TRUE){
print ('Drawing fov for phenocam site')
site = input$site
site_data = get_site_info(site)
cam_orientation = as.character(site_data$camera_orientation)
degrees = as.numeric(orientation_key[cam_orientation])
run_add_polyline(site_data, degrees)
shinyjs::show(id = 'azm')
updateSliderInput(session, 'azm', value = degrees)
}
else if (roi_bool == FALSE){
shinyjs::hide(id = 'azm')
leafletProxy('map') %>% removeShape(layerId = 'azm_')
print ('Removing fov for phenocam site')
}
})
# Show Popup box for site when clicked
observeEvent(input$map_marker_click, {
event = isolate(input$map_marker_click)
updateSelectInput(session, 'site', selected = event$id )
print (event$id)
site = event$id
site_data = get_site_info(site)
if (is_not_null(event$id)){
if (isolate(input$map_zoom) < 5){
zoom_to_site(site_ = event$id, site_data_ = site_data,
zoom_ = TRUE,
data_ = cams_,
draw_ = input$drawROI)
}
}
if(is.null(event))
return()
leafletProxy("map", data = variables$sites_df) %>% clearPopups()
site = event$id
lat = site_data$lat
lon = site_data$lon
description = site_data$site_description
elevation = site_data$Elev
camera = site_data$site
site_type = site_data$site_type
cam_orientation = as.character(site_data$camera_orientation)
degrees = as.numeric(orientation_key[cam_orientation])
active = site_data$active
date_end = site_data$date_last
date_start = site_data$date_first
get_site_popup(camera, lat, lon, description, elevation,
site_type, cam_orientation, degrees,
active, date_end, date_start)
})
# Change size of phenocam Image
observeEvent(input$imagePlus,{
data$site_width = data$site_width + (50 * (5/3))
data$site_height = data$site_height + 50
})
# Change size of phenocam Image
observeEvent(input$imageMinus,{
data$site_width = data$site_width - (50 * (5/3))
data$site_height = data$site_height - 50
})
# Site Explorer Mode Images
# CheckBox to Show image for site from dropdown
observe({
print ('Doing something to Image')
draw_bool = input$drawImage
this_site = input$site
roi_bool = input$drawImageROI
removeUI(selector = '#phenocamSiteImage')
img_url = get_img_url(this_site)
if (draw_bool == TRUE){
pft_ = input$pftSelection
pft = strsplit(pft_, '_')[[1]][1]
if (is.na(pft)){
pft_abbr = subset(roi_files, roi_files$site == this_site)[1,]$roitype
}else{
pft_abbr = subset(pft_df, pft_df$pft_expanded == pft)$pft_abbreviated
}
image_width = paste0('width:', data$site_width ,'px; ')
image_height = paste0('height:', data$site_height ,'px; ')
shinyjs::show(id = 'currentImage')
insertUI(selector = '#image',
ui = tags$div(id='phenocamSiteImage',
tags$img(src=img_url, class= 'img',
style=paste0("position: absolute; z-index: 1; top:0px; left:0px;",image_width, image_height))))}
if (roi_bool == TRUE){
pft_ = input$pftSelection
pft = strsplit(pft_, '_')[[1]][1]
if (is.na(pft)){
pft_abbr = subset(roi_files, roi_files$site == this_site)[1,]$roitype
}else{
pft_abbr = (subset(pft_df, pft_df$pft_expanded == pft)$pft_abbreviated)
}
roi_url = get_roi_url(name = this_site, pft_abr = pft_abbr)
print (roi_url)
if (roi_url != 'Not Found'){
insertUI(selector = '#phenocamSiteImage',
ui = tags$img(src=roi_url,
class= 'roi', style=paste0('position: absolute; z-index: 2; top:0px; left:0px;',image_width, image_height)))}
}else if (draw_bool == FALSE){
removeUI(selector = '#phenocamSiteImage')
shinyjs::hide(id = 'currentImage')
}
})
# Button switches to Analyzer Mode
observeEvent(input$analyzerMode,{
withBusyIndicatorServer("analyzerMode", {
panel$mode = 'analyzer'
site = input$site
data$site = site
site_data = get_site_info(site)
data$all_data = data.frame()
# Reactive variables for changing and tracking color of highlighted pixel
variables$color_count = 1
variables$color_list = c()
variables$color_list_reserve = rainbow(20)
data$nlcd_breakdown_df = data.frame()
# Setting raster grid FALSE since it doesn't exist yet
data$raster_grid = FALSE
# Set up directories to store data
file_path = paste0('./www/site_data/', site, '/data_layers/')
main = './www/site_data'
npn_grid_dir = './www/npn_grid_data'
lc_filepath = paste0(file_path, 'lc/')
ndvi_filepath = paste0(file_path,'ndvi/')
ndvi_tera_filepath = paste0(ndvi_filepath, 'tera/')
if (!file.exists(main)){
dir.create(file.path(main))
}
if (!file.exists(npn_grid_dir)){
dir.create(npn_grid_dir)
}
main_site = paste0(main, '/', site)
if (!file.exists(main_site)){
dir.create(file.path(main_site))
}
if (!file.exists(file_path)){
dir.create(file.path(file_path))
}
if (!file.exists(ndvi_filepath)){
dir.create(file.path(ndvi_filepath))
}
if (!file.exists(ndvi_tera_filepath)){
dir.create(file.path(ndvi_tera_filepath))
}
if (!file.exists(lc_filepath)){
dir.create(file.path(lc_filepath))
}
# Landcover layer
# Download or Import landcover for this site
print ('Importing Landcover')
appeears$landcover = get_appeears_task(site, type = 'landcover')
if (length(list.files(lc_filepath))==0){
lc_bundle_df = download_bundle_file(appeears$landcover$task_id, lc_filepath)
lc_name = subset(lc_bundle_df, file_type == 'nc')$file_name
}else {
# lc_bundle_df = get_appeears_bundle_df(appeears$landcover$task_id)
lc_files = list.files(lc_filepath)
lc_name = lc_files[grepl('MCD12Q1.006_500m_aid0001.nc', lc_files)]
}
print (lc_filepath)
print (lc_name)
# NDVI layer
# Download or Import NDVI for this site to use to resample landcover
appeears$ndvi_tera = get_appeears_task(site, type = 'ndvi_tera')
if (length(list.files(ndvi_tera_filepath))==0){
ndvi_bundle_df_tera = download_bundle_file(appeears$ndvi_tera$task_id, ndvi_tera_filepath)
ndvi_tera_name = subset(ndvi_bundle_df_tera, file_type == 'nc')$file_name
}else {
# ndvi_bundle_df_tera = get_appeears_bundle_df(appeears$ndvi_tera$task_id)
ndvi_files = list.files(ndvi_tera_filepath)
ndvi_tera_name = ndvi_files[grepl('MOD13Q1.006_250m_aid0001.nc', ndvi_files)]
}
# Bringing in 250m sinu and re-projecting to merc
# ndvi_tera_name = subset(ndvi_bundle_df_tera, file_type == 'nc')$file_name
ndvi_tera_path = paste0(ndvi_tera_filepath, ndvi_tera_name)
ndvi_tera_brick = raster::brick(ndvi_tera_path, varname='_250m_16_days_NDVI', crs=sinu_crs)
ndvi_raster_t = raster::subset(ndvi_tera_brick, 1)
ndvi_raster_merc = projectRaster(from = ndvi_raster_t, crs = merc_crs, res = res(ndvi_raster_t))
# Bringing in 500m sinu, resampling to 250m, and then re-projecting back to 500m to merc
lc_path = paste0(lc_filepath, lc_name)
lc_brick = raster::brick(lc_path, crs=sinu_crs) #ONAQ breaks here
lc_raster = raster::subset(lc_brick, 1)
lc_raster_ = raster::resample(x = lc_raster, y = ndvi_raster_t, crs = sinu_crs, method='ngb')
lc_raster_merc = projectRaster(from = lc_raster_, crs = merc_crs, method='ngb', res = res(ndvi_raster_t))
# lc_raster_merc = projectRaster(from = lc_raster_, crs = merc_crs, method='ngb', res = res(ndvi_raster_t)*2)
veg_types = c()
print ('Switching to Analyze Mode')
zoom_to_site(site, site_data, TRUE, cams_, input$drawROI, zoom_value = 14)
highlighted$group = paste0(site, ' Highlighted Pixels')
output$analyzerTitle = renderText({paste0('Site:: ', site)})
switch_to_analyzer_panel()
veg_idx = is.element(roi_files$site, site)
veg_match = roi_files[veg_idx,]
if (nrow(veg_match) == 0){
updateSelectInput(session, 'pftSelection', choices = 'No ROI Vegetation Available')
}else{
veg_types = c()
for (i in c(1:nrow(veg_match))){
veg.idx = is.element(pft_df$pft_abbreviated, veg_match$roitype[i])
veg = pft_df$pft_expanded[veg.idx]
add_veg = as.character(veg[1])
veg_types = c(veg_types, add_veg)
}
veg_types = unique(veg_types)
data$veg_types = veg_types
# Building Landcover layer and color pallette for specific pft composition in clipped raster
lat_wgs = site_data$lat
lng_wgs = site_data$lon
# from wgs to sinusoidal
pt_sinu = from_crs1_to_crs2_lon_lat(lon_ = lng_wgs, lat_ = lat_wgs, from_crs = wgs_crs, to_crs = sinu_crs)
data$lat_sin = pt_sinu@coords[2]
data$lng_sin = pt_sinu@coords[1]
# from wgs to web mercator
pt_merc = from_crs1_to_crs2_lon_lat(lon_ = lng_wgs, lat_ = lat_wgs, from_crs = wgs_crs, to_crs = merc_crs)
data$lat_merc = pt_merc@coords[2]
data$lng_merc = pt_merc@coords[1]
data$r_landcover = crop_raster(data$lat_merc, data$lng_merc, lc_raster_merc, height = 10000, width = 10000, crs_str = merc_crs)
# Read in NLCD if site is within NLCD extent (in Mercator)
data$NLCD = FALSE
site_nlcd_file = paste0('./www/landsat_lc/', site, '_landsat_lc.tif')
# If NLCD layer exists for site, add it to map
if (file.exists(site_nlcd_file)){
site_nlcd_raster = raster::raster(site_nlcd_file)
data$r_nlcd = site_nlcd_raster
key_df = read.csv('./www/landsat_lc/nlcd_key.csv')
data$nlcd_c = build_landsat_lc_pallet(data$r_nlcd, key_df)
data$NLCD = TRUE
shinyjs::show(id = 'nlcdOpacity')
}
updateSelectInput(session, 'pftSelection', choices = veg_types)
data$veg_types = veg_types
print (veg_types)
pft = strsplit(veg_types[1], '_')[[1]][1]
print (pft)
pft_key = (subset(pft_df, pft_df$pft_expanded == pft)$pft_key)
print (as.numeric(pft_key))
data$c3 = build_pft_palette(data$r_landcover)
rc = crop_raster(lat_ = data$lat_merc, lon_ = data$lng_merc , r_ = data$r_landcover, crs_str = merc_crs, reclassify=TRUE, primary = as.numeric(pft_key), crop=FALSE)
leafletProxy('map') %>%
clearControls() %>%
clearImages() %>%
addRasterImage(data$r_landcover, opacity = .65, project=TRUE, group='MODIS Land Cover 2016', colors = data$c3$palette) %>%
addRasterImage(rc, opacity = .2, project=TRUE, group= 'Vegetation Cover Agreement', colors= c('green','gray')) %>%
addLegend(labels = data$c3$names, colors = data$c3$colors, position = "bottomleft", opacity = .95, title = 'MODIS Landcover', group = 'MODIS Landcover') %>%
addLegend(values = c(1,2), position = 'bottomright', title = 'Vegetation Cover Agreement',
colors = c('green', 'grey'), labels = c('ROI-Match', 'No-Match')) %>%
addLayersControl(baseGroups = c("World Imagery", "Open Topo Map"),
overlayGroups = c('MODIS Land Cover 2016', 'Vegetation Cover Agreement'),
position = c("topleft"),
options = layersControlOptions(collapsed = FALSE))
# If NLCD layer exists for site, add it to map
if (data$NLCD){
# modis to landsat lookup - Removing Evergreen broadleaf forest and Deciduous needleaf forest and the 2nd Shrubland
landsat_lc = Landsat_Landcover %>%
mutate(Landsat.Class = replace(Landsat.Class, MODIS.Class == 3, NA)) %>%
mutate(Landsat.Class = replace(Landsat.Class, MODIS.Class == 2, NA)) %>%
mutate(Landsat.Class = replace(Landsat.Class, MODIS.Class == 7, NA))
# create a landsat to modis lookup (so that no landsat values are left out)
landsat_lc_lookup = read.csv('./www/landsat_lc/nlcd_key.csv') %>%
dplyr::select(ID,NLCD.Land.Cover.Class) %>% left_join(landsat_lc, by = c('ID' = 'Landsat.Class')) %>%
mutate(MODIS.Class = replace(MODIS.Class, ID == 12, NA)) %>%
left_join(pft_df, by = c('MODIS.Class' = 'pft_key'))
# Build crosswalk matrix for reclassify function (rcl)
from_values = landsat_lc_lookup$ID
becomes_values = landsat_lc_lookup$MODIS.Class
# Build matrix to use in reclassify function
m = matrix(ncol = 2, nrow = length(from_values))
m[,1] = from_values
m[,2] = becomes_values
# reclassified nlcd layer to match modis values
data$rc_nlcd = reclassify(data$r_nlcd, m)
# Color palette for both nlcd and modis landcover
data$rc_nlcd_c = build_pft_palette(data$rc_nlcd)
data$nlcd_modis_c = build_pft_palette(data$r_landcover, data$rc_nlcd)
leafletProxy('map') %>% addRasterImage(data$rc_nlcd, colors = data$rc_nlcd_c$palette, opacity = .7, group = '2016 NLCD') %>%
clearControls() %>%
addLegend(labels = data$nlcd_modis_c$names, colors = data$nlcd_modis_c$colors, position = "bottomleft", opacity = .95, title = 'Landcover') %>%
addLayersControl(baseGroups = c("World Imagery", "Open Topo Map"),
overlayGroups = c('MODIS Land Cover 2016', 'Vegetation Cover Agreement', '2016 NLCD'),
position = c("topleft"),
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup("2016 NLCD")
}
}
}) # End busy indicator
}) # End analyzerMode Observer
# When ROI Vegetation type changes re-plot highlighted veg type, change roi mask to overlay, and
# the csv data to import form phenocam API
observeEvent(input$pftSelection, {
if (panel$mode == 'analyzer'){
# Change vegetation cover agreement to match selected ROI in pftSelection
print ('Running pft Selection')
site = input$site
site_data = get_site_info(site)
pft = input$pftSelection
# pft = strsplit(pft, '_')[[1]][1]
pft_key = (subset(pft_df, pft_df$pft_expanded == pft)$pft_key)
pft_abbr = as.character(subset(pft_df, pft_df$pft_expanded == pft)$pft_abbreviated)
if (pft == 'Shrubland'){pft_abbr = 'SH'}
if (pft == 'Mixed Forest'){pft_abbr = 'MF'}
data$pft_abbr = pft_abbr
print (as.numeric(pft_key))
rc = crop_raster(lat_ = data$lat_merc, lon_ = data$lng_merc ,
r_ = data$r_landcover, crs_str = merc_crs,