-
Notifications
You must be signed in to change notification settings - Fork 0
/
Functions_RasterExtraction.R
768 lines (587 loc) · 31.4 KB
/
Functions_RasterExtraction.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
##---- Check SLURM partitions
get.partitions<- function(partition){
## Check if supplied partition name is in the list of available partitions
if(partition %in% trimws(system("sinfo -O PartitionName",intern=TRUE)[-1])){
return(TRUE)
}else{
return(FALSE)
}
}
##---- Load Required Packages
load.packages<- function(){
listOfPackages <- c("batchtools","terra","tools","reshape2","ids","lubridate")
for (i in listOfPackages){
if(! i %in% installed.packages()){
install.packages(i, dependencies = TRUE)
}
require(i,character.only=TRUE)
}
}
##---- Create a temporary registry item
set.parallel.registry = function(PROJECT_NAME){
if(file.exists(paste(PROJECT_NAME,"Registry",sep="_"))){
reg = loadRegistry(paste(PROJECT_NAME,"Registry",sep="_"),writeable = TRUE)
}else{
reg = makeRegistry(file.dir = paste(PROJECT_NAME,"Registry",sep="_"), seed = 42)
}
return(reg)
}
##---- Select and Set Cluster Function Settings
select.Cluster = function(projectdirectory=getwd(),projectname,scheduler="socket"){
#setwd(projectdirectory)
load.packages()
reg = set.parallel.registry(projectname)
if (scheduler=="SLURM"){
if(!file.exists("slurm.tmpl")){
download.file("https://raw.githubusercontent.com/WillhKessler/GCMC_RScripts/main/slurm.tmpl","slurm.tmpl")
}else{
print("template exists")
}
if(!file.exists("batchtools.conf.R")){
download.file("https://raw.githubusercontent.com/WillhKessler/GCMC_RScripts/main/batchtools.conf.R", "batchtools.conf.R")
}else{
print("conf file exists")
}
}
else if (scheduler == "socket"){
reg$cluster.functions=makeClusterFunctionsSocket()
}
else if (scheduler == "interactive"){
reg$cluster.functions=makeClusterFunctionsInteractive()
}
return(reg)
}
##---- Create batchgrid
create.jobgrid = function(rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays,period,weightslayers){
require("tools")
##---- Set up the batch processing jobs
pvars = list.dirs(path = rasterdir,full.names = FALSE,recursive = FALSE)
if(file_ext(extractionlayer)=="csv"){
feature<-read.csv(extractionlayer,stringsAsFactors = FALSE)
feature$OID<-1:nrow(feature)
write.csv(x = feature,file = paste0(file_path_sans_ext(extractionlayer),"_tmp",".csv"),row.names = FALSE)
feature<-feature$OID
layername = NA
weightslayers = NA
extractionlayer<-paste0(file_path_sans_ext(extractionlayer),"_tmp",".csv")
IDfield="OID"
}else if(file_ext(extractionlayer) %in% c("shp","gdb")){
require('terra')
vectorfile<- vect(x=extractionlayer,layer=layername)
vectorfile$OID<-1:nrow(vectorfile)
writeVector(x = vectorfile,filename = paste0(file_path_sans_ext(extractionlayer),"_tmp.",file_ext(extractionlayer)),layer=layername,overwrite=TRUE)
feature<- unlist(unique(values(vectorfile[,"OID"])))
Xfield = NA
Yfield = NA
extractionlayer<-paste0(file_path_sans_ext(extractionlayer),"_tmp.",file_ext(extractionlayer))
IDfield="OID"
if (file_ext(extractionlayer)=="shp"){
layername<-paste0(extractionlayer,"_tmp")
}
}
output<- expand.grid(vars = pvars,
period=period,
piece = feature,
rasterdir = rasterdir,
extractionlayer = extractionlayer,
layername = layername,
IDfield = IDfield,
Xfield = Xfield,
Yfield = Yfield,
startdatefield = startdatefield,
enddatefield = enddatefield,
predays = predays,
weightslayers = weightslayers,
stringsAsFactors = FALSE)
return(output)
}
##---- Initialize submission of jobs to cluster
init.jobs = function(func = extract.rast, rasterdir, extractionlayer, layername, IDfield, Xfield, Yfield,
startdatefield, enddatefield, period, predays,weightslayers, chunk.size = 1000,
memory = 2048,partition="linux01", projectdirectory, projectname, scheduler = "socket", email, reg){
# init.jobs = function(func = extract.rast,rasterdir = rasterdir,extractionlayer = extractionlayer,layername = layername,IDfield = IDfield,Xfield = Xfield,
# Yfield = Yfield,startdatefield = startdatefield,enddatefield = enddatefield,predays = predays,weightslayers = weights,chunk.size = 1000,
# memory = 2048,partition="linux01", projectdirectory = projectdirectory,projectname=PROJECT_NAME, scheduler = "interactive",email=email,reg=reg){
##---- Clear the R registry
clearRegistry(reg)
##---- Create jobs
##---- create jobs from variable grid
jobs<- batchMap(fun = func,
create.jobgrid(rasterdir = rasterdir,
extractionlayer = extractionlayer,
layername = layername,
IDfield = IDfield,
Xfield = Xfield,
Yfield = Yfield,
startdatefield = startdatefield,
enddatefield = enddatefield,
predays = predays,
weightslayers = weights),
reg = reg)
setJobNames(jobs,paste(abbreviate(PROJECT_NAME),jobs$job.id,sep=""),reg=reg)
jobs$chunk <- chunk(jobs$job.id, chunk.size = chunk.size)
getJobTable()
getStatus()
##---- Submit Jobs
if(toupper(scheduler) == "SLURM"){
if(partition == "linux12h"){walltime<- 43200}else{walltime=36000000}
done <- batchtools::submitJobs(jobs,
reg=reg,
resources=list(partition=partition, walltime=walltime, ntasks=1, ncpus=1, memory=memory,email=email))
}else if(toupper(scheduler)=="SOCKET"){
done<- batchtools::submitJobs(jobs,resources = list(memory=memory),reg = reg)
}else{
done<- batchtools::submitJobs(resources = c(walltime=3600000000, memory=memory),reg = reg)
}
waitForJobs()
# If any of the jobs failed, they will be displayed here as 'Errors"
getStatus()
# Look at the Error Messages to see what the errors are:
getErrorMessages()
}
##---- Helper function for adjusting extraction periods when averaging time periods
set.period<- function(polygons,period,startdatefield,enddatefield,predays){
if(period=="monthly"){
polygons$extract_start<- as.character(floor_date(as.Date(unlist(as.data.frame(polygons[,startdatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d"))-predays,"month"))
polygons$extract_stop<-as.character(ceiling_date(as.Date(unlist(as.data.frame(polygons[,enddatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d")),"month")-1)
}else if(period=="yearly"){
polygons$extract_start<- as.character(floor_date(as.Date(unlist(as.data.frame(polygons[,startdatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d"))-predays,"year"))
polygons$extract_stop<-as.character(ceiling_date(as.Date(unlist(as.data.frame(polygons[,enddatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d")),"year")-1)
}else{
polygons$extract_start<- as.character(as.Date(unlist(as.data.frame(polygons[,startdatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d"))-predays)
polygons$extract_stop<-as.character(as.Date(unlist(as.data.frame(polygons[,enddatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d")))
}
return(polygons)
}
##---- Helper function for setting calculating spatial weights
calc.spatialweights<- function(weightslayers,rasters,polygons){
rweights<-list.files(weightslayers,full.names = TRUE)
print(rweights)
## Rasterize the Weights data
print('the weights rasters')
weightrast<- rast(rweights)
print(weightrast)
## Reproject everything to the same resolution and CRS
print('reprojecting clim vars')
polygons<-project(polygons,crs(rasters))
#crs(weightrast)<-crs(rasters)
weightrast<-project(weightrast,rasters)
print('cropping weightrasters')
weightrast<-crop(weightrast,polygons,snap="out")
## Create a composite population raster at the same crs and extent of the climate variables
weightrast2<-sum(weightrast)
print(weightrast2)
# Crop and resample climate rasters to weights
print("croppings rasters with weightrast2")
rasters2<-crop(rasters, weightrast2,snap='out')
print("resampling rasters2")
print("the tempdir(): ")
print(tempdir())
print("the current working directory")
print(getwd())
print("starting resample")
rasters2<-resample(rasters2,weightrast2,method='bilinear',wopt=list(gdal = c("BIGTIFF=YES")))
output<-data.frame()
print('cropping the weightrast2 to polygon')
weightzone = crop(x= weightrast2,y= polygons, touches=FALSE,mask=TRUE)
#Scale the population weights to sum to 1
print('scaling the population weights')
weights = weightzone*(1/sum(values(weightzone,na.rm=TRUE)))
weights<-extend(weights,rasters2,fill=NA)
weightedavg<-zonal(x=rasters2,z=polygons,w=weights, fun = mean,na.rm=TRUE,as.polygons=TRUE)
print(str(weightedavg))
print("the weights average: ")
#print(weightedavg)
output<-cbind(polygons,weightedavg)
print(str(output))
#output<-weightedavg
return(output)
}
##---- Function to extract Raster Data to points or polygons weighted/unweighted based on other rasters
extract.rast= function(vars,period,piece,rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays=0,weightslayers = NA){
##---- Load required packages, needs to be inside function for batch jobs
require(terra)
require(reshape2)
require(tools)
require(ids)
require(lubridate)
source("https://raw.githubusercontent.com/WillhKessler/GCMC_RScripts/refs/heads/main/Functions_RasterExtraction.R")
print(system("hostname",intern=TRUE))
print(paste('Current working directory:',getwd()))
print(paste('Current temp directory:',tempdir()))
##---- Climate Rasters
rastfiles<-rasterdir
climvars<-list.files(file.path(rastfiles,vars),pattern = paste(".*",vars,".*[1-2][0-9][0-9][0-9]-?[0-1][0-9]-?[0-3][0-9]\\.(tif|bil)$",sep=""),recursive=TRUE,full.names=TRUE)
# Determine unique raster dates
rdates<-unique(sapply(X = strsplit(file_path_sans_ext(basename(climvars)),"_"),FUN = function(x){x[length(x)]}))
rdates<-rdates[order(rdates)]
#print(rdates)
##---- Extraction Features Layer
if(file_ext(extractionlayer)=='csv'){
extlayer<-read.csv(extractionlayer,stringsAsFactors = FALSE)
extlayer<-extlayer[extlayer[IDfield]==piece,]
polygons<- vect(x = extlayer,geom = c(Xfield,Yfield),crs="EPSG:4326",keepgeom=TRUE)
rm(extlayer)
}else if (file_ext(extractionlayer) %in% c("gdb")){
polygons<-vect(x=extractionlayer,layer = layername,query = paste("SELECT * FROM ",layername," WHERE ",IDfield," = ",piece))
}else if (file_ext(extractionlayer) %in% c("shp")){
polygons<-vect(x=extractionlayer, query = paste0("SELECT * FROM ",layername," WHERE ",IDfield," = ","'",as.character(piece),"'"))
}
##---- Set summary period for extractions (monthly, yearly)
polygons<-set.period(polygons,period,startdatefield,enddatefield,predays)
##---- Create extraction date ranges for points
polygonstartSeasonIndex<- sapply(polygons$extract_start, function(i) which((as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0)[which.min(abs(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i))[(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0])])
polygonsendSeasonIndex<- sapply(polygons$extract_stop, function(i) which((as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0)[which.min(abs(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i))[(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0])])
##---- Handle cases where extraction dates are outside available data
if(length(unlist(polygonstartSeasonIndex))==0 & length(unlist(polygonsendSeasonIndex))==0){
output<- polygons
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
return(list(exposure=vars,piece=piece,result=wrap(output),longresult=longoutput,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[7:8],collapse=".") ))
} else if (length(unlist(polygonstartSeasonIndex))==0 & length(unlist(polygonsendSeasonIndex))>0){
polygonstartSeasonIndex<- sapply(polygons$extract_start, function(i) which.min(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))))
}else{
}
polygons$first_extract<-as.Date(rdates[polygonstartSeasonIndex],tryFormats=c("%Y-%m-%d","%Y%m%d"))
polygons$last_extract<-as.Date(rdates[polygonsendSeasonIndex],tryFormats=c("%Y-%m-%d","%Y%m%d"))
##---- Perform Extractions
##---- Determine which raster dates fall within the data range
rasterDateRange<-rdates[as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))>=min(polygons$first_extract) & as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))<=max(polygons$last_extract)]
# Load Climate Rasters
print("loading the climvars to rast()")
climvars2<-sapply(rasterDateRange, function(x){climvars[grep(x,climvars)]})
rasters<- rast(climvars2)
names(rasters)<-rasterDateRange
if(is.polygons(polygons)){
if(is.na(weightslayers)){
polygons<-project(polygons,crs(rasters))
rasters2<- crop(x = rasters, y = polygons,snap = 'out')
tempoutput<-zonal(x=rasters2,z=polygons,fun=mean,na.rm=TRUE,as.polygons=TRUE)
tempnames<-names(tempoutput)
output<-cbind(polygons,tempoutput)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
}else{
output<-calc.spatialweights(weightslayers= weightslayers,rasters= rasters,polygons= polygons)
}
}else if(is.points(polygons)){
polygons<-project(polygons,crs(rasters))
output<-terra::extract(x = rasters,y = polygons,ID=FALSE)
names(output)<-names(rasters)
}
row_average_function <- function(row_data,timeperiod) {
tapply(as.numeric(row_data), timeperiod, mean)
}
# Calculate period averages
if(period == "monthly"){
timeperiod<-substr(colnames(output),1,6)
monthlyaverages<-t(apply(output,1,row_average_function))
output<-cbind(polygons,as.data.frame(monthlyaverages))
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
}else if(period == "yearly"){
timeperiod<-substr(colnames(output),1,4)
yearaverages<-t(apply(output,1,row_average_function))
output<-cbind(polygons,as.data.frame(yearaverage))
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
}else{
output<-cbind(polygons,output)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
}
#return(list(exposure=vars,piece=piece,result=output,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[6:7],collapse=".") ))
return(list(exposure=vars,piece=piece,result=wrap(output),longresult=longoutput,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[7:8],collapse=".") ))
}
##---- Function to perform time invariant raster data extraction to points or polygons with or without raster weighting
simple.extract.rast= function(vars,piece,rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays=0,weightslayers = NA){
##---- Load required packages, needs to be inside function for batch jobs
require(terra)
require(reshape2)
require(tools)
require(ids)
print(system("hostname",intern=TRUE))
print(paste('Current working directory:',getwd()))
print(paste('Current temp directory:',tempdir()))
##---- Climate Rasters
rastfiles<-rasterdir
climvars<-list.files(file.path(rastfiles,vars),pattern = paste(".*",vars,".*.(tif|bil)$",sep=""),recursive=TRUE,full.names=TRUE)
##---- Extraction Features Layer
if(file_ext(extractionlayer)=='csv'){
extlayer<-read.csv(extractionlayer,stringsAsFactors = FALSE)
extlayer<-extlayer[extlayer[IDfield]==piece,]
polygons<- vect(x = extlayer,geom = c(Xfield,Yfield), keepgeom=TRUE)
}else if (file_ext(extractionlayer) %in% c("gdb")){
polygons<-vect(x=extractionlayer,layer = layername,query = paste("SELECT * FROM ",layername," WHERE ",IDfield," = ",piece))
}else if (file_ext(extractionlayer) %in% c("shp")){
polygons<-vect(x=extractionlayer, query = paste0("SELECT * FROM ",layername," WHERE ",IDfield," = ","'",as.character(piece),"'"))
}
rasters<- rast(climvars)
names(rasters)<-basename(file_path_sans_ext(climvars))
#################################################################
#################################################################
##---- Weights Rasters for spatial weights
calc.spatialweights<- function(weightslayers,rasters,polygons){
rweights<-list.files(weightslayers,full.names = TRUE)
print(rweights)
## Rasterize the Weights data
print('the weights rasters')
weightrast<- rast(rweights)
print(weightrast)
## Reproject everything to the same resolution and CRS
print('reprojecting clim vars')
polygons<-project(polygons,crs(rasters))
#crs(weightrast)<-crs(rasters)
weightrast<-project(weightrast,rasters)
print('cropping weightrasters')
weightrast<-crop(weightrast,polygons,snap="out")
## Create a composite population raster at the same crs and extent of the climate variables
weightrast2<-sum(weightrast)
print(weightrast2)
# Crop and resample climate rasters to weights
print("croppings rasters with weightrast2")
rasters2<-crop(rasters, weightrast2,snap='out')
print("resampling rasters2")
print("the tempdir(): ")
print(tempdir())
print("the current working directory")
print(getwd())
print("starting resample")
rasters2<-resample(rasters2,weightrast2,method='bilinear',wopt=list(gdal = c("BIGTIFF=YES")))
output<-data.frame()
print('cropping the weightrast2 to polygon')
weightzone = crop(x= weightrast2,y= polygons, touches=FALSE,mask=TRUE)
#Scale the population weights to sum to 1
print('scaling the population weights')
weights = weightzone*(1/sum(values(weightzone,na.rm=TRUE)))
weights<-extend(weights,rasters2,fill=NA)
weightedavg<-zonal(x=rasters2,z=polygons,w=weights, fun = mean,na.rm=TRUE,as.polygons=TRUE)
print(str(weightedavg))
print("the weights average: ")
#print(weightedavg)
output<-cbind(polygons,weightedavg)
print(str(output))
#output<-weightedavg
return(output)
}
#################################################################
#################################################################
##---- Perform Extractions
if(is.polygons(polygons)){
if(is.na(weightslayers)){
polygons<-project(polygons,crs(rasters))
rasters2<- crop(x = rasters, y = polygons,snap = 'out')
tempoutput<-zonal(x=rasters2,z=polygons,fun=mean,na.rm=TRUE,as.polygons=TRUE)
tempnames<-names(tempoutput)
output<-cbind(polygons,tempoutput)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="variable",value.name=vars,na.rm=FALSE)
}else{output<-calc.spatialweights(weightslayers= weightslayers,rasters= rasters,polygons= polygons)}
}else if(is.points(polygons)){
polygons<-project(polygons,crs(rasters))
output<-extract(x = rasters,y = polygons,ID=FALSE)
names(output)<-names(rasters)
output<-cbind(polygons,output)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="variable",value.name=vars,na.rm=FALSE)
}
#return(list(exposure=vars,piece=piece,result=output,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[6:7],collapse=".") ))
return(list(exposure=vars,piece=piece,result=wrap(output),longresult=longoutput,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[7:8],collapse=".") ))
}
##---- An example inner Parallel Function
p.extract.rast <- function(pieces,vars,rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays=0,weightslayers = NA){
multicore.extract.rast<-function(pieces2,vars,rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays=0,weightslayers = NA){
##---- Load required packages, needs to be inside function for batch jobs
require(terra)
require(reshape2)
require(tools)
require(ids)
require(lubridate)
source("https://raw.githubusercontent.com/WillhKessler/GCMC_RScripts/refs/heads/main/Functions_RasterExtraction.R")
print(system("hostname",intern=TRUE))
print(paste('Current working directory:',getwd()))
print(paste('Current temp directory:',tempdir()))
print(pieces2)
print(vars)
print(rasterdir)
print(extractionlayer)
print(IDfield)
print(Xfield)
print(Yfield)
print(startdatefield)
print(enddatefield)
print(predays)
##---- Climate Rasters
rastfiles<-rasterdir
climvars<-list.files(file.path(rastfiles,vars),pattern = paste(".*",vars,".*[1-2][0-9][0-9][0-9]-?[0-1][0-9]-?[0-3][0-9]\\.(tif|bil)$",sep=""),recursive=TRUE,full.names=TRUE)
# Determine unique raster dates
rdates<-unique(sapply(X = strsplit(file_path_sans_ext(basename(climvars)),"_"),FUN = function(x){x[length(x)]}))
rdates<-rdates[order(rdates)]
##---- Extraction Features Layer
if(file_ext(extractionlayer)=='csv'){
extlayer<-read.csv(extractionlayer,stringsAsFactors = FALSE)
#extlayer<-extlayer[extlayer[IDfield]==piece,]
extlayer<-extlayer[extlayer[IDfield] == pieces2,]
polygons<- vect(x = extlayer,geom = c(Xfield,Yfield), crs="EPSG:4326" ,keepgeom=TRUE)
}else if (file_ext(extractionlayer) %in% c("gdb")){
polygons<-vect(x=extractionlayer,layer = layername,query = paste("SELECT * FROM ",layername," WHERE ",IDfield," = ",piece))
}else if (file_ext(extractionlayer) %in% c("shp")){
polygons<-vect(x=extractionlayer, query = paste0("SELECT * FROM ",layername," WHERE ",IDfield," = ","'",as.character(piece),"'"))
}
polygons$extract_start<- as.character(as.Date(unlist(as.data.frame(polygons[,startdatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d"))-predays)
polygons$extract_stop<-as.character(as.Date(unlist(as.data.frame(polygons[,enddatefield])),tryFormats=c("%Y-%m-%d","%m/%d/%Y","%Y%m%d","%Y/%m/%d")))
##---- Create extraction date ranges for points
polygonstartSeasonIndex<- sapply(polygons$extract_start, function(i) which((as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0)[which.min(abs(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i))[(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0])])
polygonsendSeasonIndex<- sapply(polygons$extract_stop, function(i) which((as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0)[which.min(abs(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i))[(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d"))-as.Date(i)) <= 0])])
polygons$first_extract<-as.Date(rdates[polygonstartSeasonIndex],tryFormats=c("%Y-%m-%d","%Y%m%d"))
polygons$last_extract<-as.Date(rdates[polygonsendSeasonIndex],tryFormats=c("%Y-%m-%d","%Y%m%d"))
##---- Determine which raster dates fall within the data range
##---- Determine required rasters
minrdate<-min(polygons$first_extract)
maxrdate<-max(polygons$last_extract)
rdaterange<-rdates[which(as.Date(rdates,tryFormats = c("%Y-%m-%d","%Y%m%d")) %in% as.Date(minrdate:maxrdate))]
##---- Filter Raster List
climvars2<-sapply(rdaterange, function(x){climvars[grep(x,climvars)]})
rm(climvars)
rdates2<-unique(sapply(X = strsplit(file_path_sans_ext(basename(climvars2)),"_"),FUN = function(x){x[length(x)]}))
rdates2<-rdates2[order(rdates2)]
rasterDateRange<-mapply(function(first_extract,last_extract) which(as.Date(rdates2,tryFormats = c("%Y-%m-%d","%Y%m%d")) >=first_extract & as.Date(rdates2,tryFormats = c("%Y-%m-%d","%Y%m%d")) <= last_extract),polygons$first_extract,polygons$last_extract,SIMPLIFY=F)
##---- Load Climate Rasters
print("loading the climvars to rast()")
rasters<- rast(climvars2)
names(rasters)<-rdaterange
##---- Reformat polygons
polygons<-lapply(1:length(polygons),FUN = function(x) polygons[x])
#################################################################
#################################################################
##---- Weights Rasters for spatial weights
calc.spatialweights<- function(weightslayers,rasters,polygons){
rweights<-list.files(weightslayers,full.names = TRUE)
print(rweights)
## Rasterize the Weights data
print('the weights rasters')
weightrast<- rast(rweights)
print(weightrast)
## Reproject everything to the same resolution and CRS
print('reprojecting clim vars')
polygons<-project(polygons,crs(rasters))
crs(weightrast)<-crs(rasters)
print('cropping weightrasters')
weightrast<-crop(weightrast,polygons,snap="out")
## Create a composite population raster at the same crs and extent of the climate variables
weightrast2<-sum(weightrast)
print(weightrast2)
# Crop and resample climate rasters to weights
print("croppings rasters with weightrast2")
rasters2<-crop(rasters, weightrast2,snap='out')
print("resampling rasters2")
print("the tempdir(): ")
print(tempdir())
print("the current working directory")
print(getwd())
print("starting resample")
rasters2<-resample(rasters2,weightrast2,method='bilinear',wopt=list(gdal = c("BIGTIFF=YES")))
output<-data.frame()
print('cropping the weightrast2 to polygon')
weightzone = crop(x= weightrast2,y= polygons, touches=FALSE,mask=TRUE)
#Scale the population weights to sum to 1
print('scaling the population weights')
weights = weightzone*(1/sum(values(weightzone,na.rm=TRUE)))
weights<-extend(weights,rasters2,fill=NA)
weightedavg<-zonal(x=rasters2,z=polygons,w=weights, fun = mean,na.rm=TRUE,as.polygons=TRUE)
print(str(weightedavg))
print("the weights average: ")
#print(weightedavg)
output<-cbind(polygons,weightedavg)
print(str(output))
#output<-weightedavg
return(output)
}
#################################################################
#################################################################
##---- Perform Extractions
if(is.polygons(polygons[[1]])){
if(is.na(weightslayers)){
rasters2<- crop(x = rasters, y = polygons,snap = 'out')
tempoutput<-zonal(x=rasters2,z=polygons,fun=mean,na.rm=TRUE,as.polygons=TRUE)
tempnames<-names(tempoutput)
output<-cbind(polygons,tempoutput)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons),variable.names="date",value.name=vars,na.rm=FALSE)
}else{output<-calc.spatialweights(weightslayers= weightslayers,rasters= rasters,polygons= polygons)}
}else if(is.points(polygons[[1]])){
print("performing extraction")
output<-mapply(function(x,y){extract(rasters[[x]],y,ID=FALSE)},rasterDateRange,polygons)
output<-mapply(cbind,polygons,output)
output<-lapply(X = output,as.data.frame)
output<-Reduce(function(dtf1,dtf2){merge(dtf1,dtf2,all=TRUE)},output)
#output<-extract(x = rasters,y = polygons,ID=FALSE)
#print("assigning names")
#names(output)<-names(rasters)
#output<-cbind(polygons,output)
longoutput<-reshape2::melt(as.data.frame(output),id.vars=names(polygons[[1]]),variable.names="date",value.name=vars,na.rm=FALSE)
}
jobout<-output
longout<-longoutput
return(list(exposure=vars,result=jobout,longresult=longout,node = system("hostname",intern=TRUE), Rversion = paste(R.Version()[6:7],collapse=".") ))
}
parallelMap::parallelMap(
fun=multicore.extract.rast,
pieces,
more.args = list(vars,rasterdir,extractionlayer,layername,IDfield,Xfield,Yfield,startdatefield,enddatefield,predays,weightslayers))
}
##---- Function to append all Recombine Outputs from Parallelization
combine.results= function(projectname=PROJECT_NAME){
require('batchtools')
require('tidyr')
require('terra')
##---- Load Registry
reg<- loadRegistry(paste(PROJECT_NAME,"Registry",sep="_"))
##---- Create Jobs Table
jobs<-getJobPars(reg=reg)
#jobpars<-as.data.frame(lapply(data.frame(do.call(rbind,jobs$job.pars)),unlist))
#jobpars2<-jobpars
#jobpars2[]<-lapply(jobpars2[],as.character)
##---- Combine all the outputs into a dataframe
results<- do.call("rbind",lapply(1:nrow(jobs),loadResult))
#results<- do.call("rbind",lapply(1:20,loadResult))
for(v in as.character(unique(unlist(results[,1])))){
out<- lapply(results[as.character(unlist(results[,1]))==v,3],terra::unwrap)
out2<- lapply(out,terra::as.data.frame)
rm(out)
out3<-Reduce(function(dtf1,dtf2){merge(dtf1,dtf2,all=TRUE)},out2)
#longout<-lapply(out2,function(x){reshape2::melt(melt(x,id.vars=colnames(x)[!grepl("^\\d{4}\\-?\\d{2}\\-?\\d{2}\\b",colnames(x))],
# variable.names="date",value.name=v,na.rm=FALSE))})
longout<- lapply(out2,function(x){as.data.frame(x%>% pivot_longer(cols= colnames(x)[grepl("^\\d{4}\\-?\\d{2}\\-?\\d{2}\\b",colnames(x))],names_to = "date",values_to = v))})
rm(out2)
longout<-do.call("rbind",longout)
write.csv(longout,paste(projectname,"_LONG_",v,".csv",sep=""))
write.csv(out3,paste(projectname,"_",v,".csv",sep=""))
saveRDS(out3,file=paste(projectname,"_",v,".rds",sep=""))
}
}
#################################################################################
##---- An example Function
get_random_mean <- function(mu, sigma, ...){
stim<-Sys.time()
Sys.sleep(runif(1)*22)
x <- rnorm(100, mean = mu, sd = sigma)
out<- c(sample_mean = mean(x), sample_sd = sd(x), Node=system("hostname", intern=TRUE),
Rversion=paste(R.Version()[6:7], collapse="."),starttime=stim,endtime=Sys.time())
}
##---- An example Function
myFct <- function(cpucore) {
Sys.sleep(10) # to see job in queue, pause for 10 sec
result <- cbind(iris[cpucore, 1:4],
Node=system("hostname", intern=TRUE),
Rversion=paste(R.Version()[6:7], collapse="."))
return(result)
}
##---- An example inner Parallel Function
innerParallel <- function(cpu){
#Must supply inner function inside the outer function
myFct <- function(cpucore) {
stim<-Sys.time() # logging clock time shows that the inner function is called at the same time across all cores, not sequentially
Sys.sleep(10) # to see job in queue, pause for 10 sec
etim<-Sys.time()
result <- cbind(iris[cpucore, 1:4,],
Node=system("hostname", intern=TRUE),
Rversion=paste(R.Version()[6:7], collapse="."),
start = stim,
end = etim)
return(result)
}
parallelMap::parallelMap(myFct,1:cpu)
}