-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathplot.R
executable file
·2539 lines (2195 loc) · 98.4 KB
/
plot.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
#
# Scripts to work with SWALS output files.
#
# It is not essential to use R to run SWALS. However, some kind of scripting
# language is useful to work with the outputs, especially if using a
# multidomain and distributed-memory parallel jobs.
#
# In general any single domain will contain "halo regions" (i.e. where the flow
# state is received from other domains), and other regions where it is the
# "priority domain". In the halo regions the values that are stored in output
# files should not be used (because some other domain is the priority domain in
# those regions). In sum, care is required to combine results from multiple domains
# while only using "priority domain" cells.
#
.library_quiet<-function(...){ suppressMessages(library(...)) }
#' Get name of folder most recently written to OUTPUTS (according to timestamp
#' in name)
get_recent_output_folder<-function(){
outputs = dir('OUTPUTS', pattern='RUN_')
output_folder = sort(outputs, decreasing=TRUE)[1]
output_folder = paste0('OUTPUTS/', output_folder)
return(output_folder)
}
#' Get times at which grid output is written
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return the times
get_time<-function(output_folder){
# Try the ascii format
model_time = try(
scan(Sys.glob(paste0(output_folder, '/', 'Time_*'))[1], quiet=TRUE),
silent=TRUE)
if(is(model_time, 'try-error')){
# Try the netcdf format
.library_quiet('ncdf4')
nc_file = Sys.glob(paste0(output_folder, '/Grid_output_*.nc'))
fid = nc_open(nc_file, readunlim=FALSE)
model_time = as.numeric(ncvar_get(fid, 'time'))
nc_close(fid)
}
return(model_time)
}
#' Get the domain dimensions
#'
#' This includes any halo regions
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return the number of cells in the x and y directions
get_model_dim<-function(output_folder){
file_metadata = readLines(Sys.glob(
paste0(output_folder, '/', 'Domain_info*'))[1])
# Get the model dimensions
model_dim_line = grep('nx :', file_metadata)
model_dim = as.numeric(scan(text=file_metadata[model_dim_line],
what='character', quiet=TRUE)[3:4])
return(model_dim)
}
#' Get the domain cell size in the x and y directions
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return the cell-size in the x and y directions
get_dx<-function(output_folder){
file_metadata = readLines(
Sys.glob(paste0(output_folder, '/', 'Domain_info*'))[1])
# Get the model cell size
model_dim_line = grep('dx :', file_metadata)
model_dx = as.numeric(scan(text=file_metadata[model_dim_line],
what='character', quiet=TRUE)[3:4])
return(model_dx)
}
#' Get the domain lower-left corner
#'
#' This includes any halo regions
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return the lower-left corner of the domain, including halo regions.
get_lower_left_corner<-function(output_folder){
file_metadata = readLines(
Sys.glob(paste0(output_folder, '/', 'Domain_info*'))[1])
# Get the model dimensions
model_dim_line = grep('lower_left_corner:', file_metadata)
model_dim = as.numeric(scan(text=file_metadata[model_dim_line],
what='character', quiet=TRUE)[2:3])
return(model_dim)
}
#' Get the domain output precision
#'
#' This is an integer that is typically '4' for single precision and '8' for double precision
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return an integer
get_model_output_precision<-function(output_folder){
file_metadata = readLines(
Sys.glob(paste0(output_folder, '/', 'Domain_info*'))[1])
model_dim_line = grep('output_precision', file_metadata)
dp = as.numeric(scan(text=file_metadata[model_dim_line], what='character',
quiet=TRUE)[2])
return(dp)
}
#' Get the domain outputs in a DEFUNCT mixed-binary format
#'
#' This has been superceeded by netcdf -- but is occasionally useful if one has
#' netcdf compilation problems and wants to test something out. However not all
#' the functionality is supported with this file format, so it isn't a general
#' solution to netcdf problems.
#'
#' @param output_folder the output folder for a domain (not a multidomain)
#' @return a list with informative names, containing the gauge data
get_gauges_mixed_binary_format<-function(output_folder){
# Read the gauge data, which is in a mixture of ascii and binary
real_precision = get_model_output_precision(output_folder)
gauge_metadata = readLines(
Sys.glob(paste0(output_folder, '/', 'Gauges_*nc_metadata')))
times = get_time(output_folder)
# If we didn't save times, guess a large number
#if(length(times) == 0) times = rep(NA, 10000)
# Get static variables (coordinates, elevation, ids, and maybe other things)
static_var_line = grep('static_var:', gauge_metadata)
nstatic_var = length(scan(text = gauge_metadata[static_var_line],
what='character', quiet=TRUE)[-1]) + 3
static_var_ids = as.numeric(scan(text = gauge_metadata[static_var_line],
what='character', quiet=TRUE)[-1])
static_var_possible_names = c('stage0', 'uh0', 'vh0', 'elevation0')
static_var_file = Sys.glob(paste0(output_folder, '/', 'Gauges*nc_static'))[1]
lt = 1e+05
static_var = readBin(static_var_file, size=real_precision, n = nstatic_var * lt,
what='numeric')
static_var = matrix(static_var, ncol=nstatic_var, byrow=TRUE)
# Get time-series
time_series_var_line = grep('time_series_var:', gauge_metadata)
ntime_series_var = length(scan(text = gauge_metadata[time_series_var_line],
what='character', quiet=TRUE)[-1])
time_series_var_ids = as.numeric(scan(
text = gauge_metadata[time_series_var_line], what='character',
quiet=TRUE)[-1])
time_series_var_possible_names = c('stage', 'uh', 'vh', 'elevation')
time_series_var_file = Sys.glob(
paste0(output_folder, '/', 'Gauges*nc_timeseries'))[1]
time_series_var = readBin(time_series_var_file, size = real_precision,
n = ntime_series_var * lt * length(static_var[,1]), what='numeric')
lt = length(time_series_var)/(ntime_series_var * length(static_var[,1]))
dim(time_series_var) = c(length(static_var[,1]), ntime_series_var, lt)
# Read static variables. First 2 columns are lon/lat, so ignore those
static_var_list=list()
counter=2
for(i in 1:length(static_var_possible_names)){
nm = static_var_possible_names[i]
if(i %in% static_var_ids){
counter=counter+1
static_var_list[[nm]] = static_var[,counter]
}else{
static_var_list[[nm]] = NA
}
}
# Read time-series variables
time_series_var_list=list()
counter=0
for(i in 1:length(time_series_var_possible_names)){
nm = time_series_var_possible_names[i]
if(i %in% time_series_var_ids){
counter=counter+1
time_series_var_list[[nm]] = time_series_var[,counter,]
}else{
time_series_var_list[[nm]] = NA
}
}
# Make sure this has the same structure as for netcdf gauge output
output = list(lon = static_var[,1], lat=static_var[,2],
gaugeID=static_var[,ncol(static_var)],
static_var=static_var_list,
time_var = time_series_var_list,
priority_gauges_only=FALSE)
return(output)
}
#' Read domain gauges from netcdf file.
#'
#' In general this is the output format we actually use -- the alternative
#' 'home-brew binary format' is not comprehensively supported.
#'
#' @param output_folder The domain's output folder
#' @return a list with informative names, containing the gauge data
get_gauges_netcdf_format<-function(output_folder){
.library_quiet('ncdf4')
gauge_fid = try(
nc_open(Sys.glob(paste0(output_folder, '/', 'Gauges_data_*.nc'))[1],
readunlim=FALSE),
silent=TRUE)
if(is(gauge_fid,'try-error')){
return(gauge_fid)
}
# Gauge coordinates
lon = ncvar_get(gauge_fid, 'lon')
lat = ncvar_get(gauge_fid, 'lat')
time = ncvar_get(gauge_fid, 'time')
gaugeID = ncvar_get(gauge_fid, 'gaugeID')
gauge_output_names = names(gauge_fid)
time_series_names = c('stage', 'uh', 'vh', 'elevation')
# The variables that are only written once [e.g. often chosen for
# elevation] have a zero appended to the name
static_names = paste0(time_series_names, '0')
# Read static variables (i.e. things that are not written every time-step
# -- sometime elevation0)
static_var = list()
for(i in 1:length(static_names)){
if(static_names[i] %in% names(gauge_fid$var)){
tmp = try(ncvar_get(gauge_fid, static_names[i]), silent=TRUE)
if(is(tmp, 'try-error')) tmp = NA
}else{
tmp = NA
}
static_var[[static_names[i]]] = tmp
}
# Read teh time-series variables (i.e. typically stage, uh, vh)
time_series_var = list()
for(i in 1:length(time_series_names)){
if(time_series_names[i] %in% names(gauge_fid$var)){
tmp = try(ncvar_get(gauge_fid, time_series_names[i]), silent=TRUE)
if(is(tmp, 'try-error')){
tmp = NA
}
# Force it to be a matrix even if there is only 1 gauge
if(length(dim(tmp)) < 2) dim(tmp) = c(1, length(tmp))
}else{
tmp = NA
}
time_series_var[[time_series_names[i]]] = tmp
}
# Check for the 'priority_gauges_only' variable -- this tells us if all the
# stored gauges are inside the priority domain. If TRUE, that's convenient,
# because we don't need to worry about throwing away non-priority-domain
# gauges.
x = ncatt_get(gauge_fid, varid=0, 'priority_gauges_only')
priority_gauges_only = FALSE
if(x$hasatt){
if(x$value == 'true') priority_gauges_only=TRUE
}
nc_close(gauge_fid)
outputs = list(lon=lon, lat=lat, time=time, gaugeID=gaugeID,
static_var=static_var, time_var=time_series_var,
priority_gauges_only=priority_gauges_only)
return(outputs)
}
#' Read EITHER the netcdf gauges OR the DEFUNCT mixed binary format
#'
#' This is a convenient interface to get the gauges -- it will try to use the
#' netcdf format, and if that doesn't work, will try the ad-hoc binary format.
#'
#' @param output_folder The domain's output folder
#' @return a list with informative names, containing the gauge data, or an
#' object of class 'try-error' if there are no gauges.
get_gauges<-function(output_folder){
outputs = try(get_gauges_netcdf_format(output_folder), silent=TRUE)
if(is(outputs, 'try-error')){
outputs = try(get_gauges_mixed_binary_format(output_folder), silent=TRUE)
}
return(outputs)
}
#' Get a global attribute from a netcdf file
#'
#' The netcdf file can be provided as a filename (in which case the function
#' opens,reads, and closes the file) or an existing file-handle (in which case
#' the function only reads the attribute)
#'
#' @param nc_file netcdf file name, or file object created by a call to
#' 'ncdf4::nc_open'
#' @param attname name of global attribute in the file
#' @return The attribute
get_nc_global_attribute<-function(nc_file, attname){
if(is(nc_file, 'character')){
fid = nc_open(nc_file, readunlim=FALSE)
bbox = ncatt_get(fid, varid=0, attname=attname)
nc_close(fid)
}else{
bbox = ncatt_get(fid, varid=0, attname=attname)
}
return(bbox)
}
#' Quickly read domain gridded outputs
#'
#' This function probably should not be called directly -- but it is called by
#' get_all_recent_results etc. FIXME: It should probably be re-written to use
#' more sensible names.
#'
#' @param var A variable name -- beware the names are archaic (derived from the
#' old home-brew binary file format). The accepted variable names are denoted
#' below [left-hand-side] along with the mapping to more sensible names
#' in the netcdf file:
#' Var_1 = 'stage'
#' Var_2 = 'uh'
#' Var_3 = 'vh'
#' Var_4 = 'elev'
#' x = 'x'
#' y = 'y'
#' Max_quantities = 'max_stage'
#' elev0 = 'elevation0'
#' is_priority_domain='is_priority_domain'
#' @param output_folder folder containing the domain output files. If NULL,
#' read the most recent one
#' @return The variable as a 3d array
#'
get_gridded_variable<-function(var = 'Var_1', output_folder = NULL){
if(is.null(output_folder)){
output_folder = get_recent_output_folder()
}
nc_file = Sys.glob(paste0(output_folder, '/Grid_output_*.nc'))
# If netcdf output does not exist, then use home-brew binary (DEFUNCT)
if(length(nc_file) != 1){
# Home-brew binary -- not really well supported, avoid this.
# FIXME: Update for parallel.
file_to_read = Sys.glob(paste0(output_folder, '/', var, '*'))[1]
model_dim = get_model_dim(output_folder)
# Read the binary file, using 'while' to get all the data
file_connection = file(file_to_read, open='rb')
real_precision = get_model_output_precision(output_folder)
output_stage_scan = c()
new_output_stage_scan = readBin(file_connection, what='numeric',
n = prod(model_dim), size=real_precision)
while(length(new_output_stage_scan)>0){
output_stage_scan = c(output_stage_scan, new_output_stage_scan)
new_output_stage_scan = readBin(file_connection, what='numeric',
n = prod(model_dim), size=real_precision)
}
close(file_connection)
num_times = length(output_stage_scan)/prod(model_dim)
dim(output_stage_scan) = c(model_dim, num_times)
}else{
# Netcdf output -- this is the usual approach. Here the naming
# convention is inherited from the hacky old binary format.
var_list = list(Var_1 = 'stage', Var_2 = 'uh', Var_3 = 'vh',
Var_4 = 'elev', x = 'x', y = 'y',
Max_quantities = 'max_stage', elev0 = 'elevation0',
is_priority_domain='is_priority_domain')
.library_quiet('ncdf4')
fid = nc_open(nc_file, readunlim=FALSE)
var_name = var_list[[var]]
if(var_name %in% c(names(fid$var), names(fid$dim))){
output_stage_scan = try(ncvar_get(fid, var_name), silent=TRUE)
}
nc_close(fid)
}
return(output_stage_scan)
}
#' Convenient function to read in pretty much all of the results in a SINGLE
#' DOMAIN.
#'
#' For multidomains, see 'get_multidomain' (or just manually loop over all
#' domains). The default options in this function can sometimes be prohibitive
#' due to memory issues, so there are options to skip reading grids and gauges
#' (i.e. to obtain minimal domain metadata, which can later be used for more
#' efficient reading of data subsets).
#'
#' @param output_folder the domain output folder
#' @param read_grids Should we read the stage/uh/vh/elev grids? These can
#' require large memory.
#' @param read_gauges Should we read the gauge outputs?
#' @param read_time_and_geometry Should we read the grid output time and
#' geometry information?
#' @param always_read_priority_domain Only matters if read_grids=FALSE. In that
#' case, setting this to TRUE ensures the priority domain information is read.
#' By default, it is always read.
#' @param always_read_xy Only matters if read_grids=FALSE. In that case,
#' setting this to TRUE ensures the x/y grid coordinates are read. Otherwise
#' they are always read.
#' @param quiet Try to minimise printed output. Note we cannot completely
#' control this due to the ncdf4 package (which reports errors in a manner that
#' we can't seem to suppress).
#' @param always_read_max_grids Only matters if read_grids=FALSE. In that case,
#' setting this to TRUE ensures the max_stage and elevation are read. Otherwise
#' they are always read.
#' @return A list with all the domain data.
get_all_recent_results<-function(
output_folder=NULL,
read_grids=TRUE,
read_gauges=TRUE,
read_time_and_geometry = TRUE,
always_read_priority_domain=FALSE,
always_read_xy = read_time_and_geometry,
quiet=FALSE,
always_read_max_grids=FALSE){
if(quiet) sink(tempfile())
if(is.null(output_folder)){
output_folder = get_recent_output_folder()
}
if(read_grids){
stage = try(get_gridded_variable(var='Var_1',
output_folder=output_folder), silent=TRUE)
ud = try(get_gridded_variable(var='Var_2',
output_folder=output_folder), silent=TRUE)
vd = try(get_gridded_variable(var='Var_3',
output_folder=output_folder), silent=TRUE)
elev = try(get_gridded_variable(var='Var_4',
output_folder=output_folder), silent=TRUE)
# maxQ might not exist if the simulation has not finished
maxQ = try(get_gridded_variable(var='Max_quantities',
output_folder=output_folder), silent=TRUE)
elev0 = try(get_gridded_variable(var='elev0',
output_folder=output_folder), silent=TRUE)
is_priority_domain = try(get_gridded_variable(var='is_priority_domain',
output_folder=output_folder), silent=TRUE)
}else{
stage = NULL
ud = NULL
vd = NULL
elev = NULL
maxQ = NULL
elev0 = NULL
is_priority_domain = NULL
if(always_read_max_grids){
maxQ = try(get_gridded_variable(var='Max_quantities',
output_folder=output_folder), silent=TRUE)
elev0 = try(get_gridded_variable(var='elev0',
output_folder=output_folder), silent=TRUE)
}
}
if(always_read_priority_domain & !read_grids){
is_priority_domain = try(get_gridded_variable(var='is_priority_domain',
output_folder=output_folder), silent=TRUE)
}
if(read_time_and_geometry){
# time is often not written until the sim is finished
time = try(get_time(output_folder), silent=TRUE)
nx = try(get_model_dim(output_folder), silent=TRUE)
dx = try(get_dx(output_folder), silent=TRUE)
lower_left_corner = try(get_lower_left_corner(output_folder),
silent=TRUE)
}else{
time = NULL
nx = NULL
dx = NULL
lower_left_corner = NULL
}
if(always_read_xy){
# x and y -- get from netcdf if we can
xs = try(get_gridded_variable(var='x', output_folder=output_folder),
silent=TRUE)
if(!is(xs, 'try_error')){
ys = try(get_gridded_variable(var='y', output_folder=output_folder),
silent=TRUE)
}else{
# Old-style, beware this does not work with decimated output
xs = lower_left_corner[1] + ((1:nx[1]) - 0.5) * dx[1]
ys = lower_left_corner[2] + ((1:nx[2]) - 0.5) * dx[2]
}
}else{
xs = NULL
ys = NULL
}
if(read_gauges){
gauges = try(get_gauges(output_folder), silent=TRUE)
}else{
gauges = NULL
}
if(quiet) sink()
return(list(stage=stage, ud=ud, vd=vd, elev=elev, maxQ=maxQ, elev0=elev0,
is_priority_domain = is_priority_domain, time=time,
output_folder = output_folder, nx=nx, gauges = gauges, xs = xs, ys=ys,
lower_left_corner=lower_left_corner, dx=dx, lw=(nx*dx)))
}
#' Read all domains in a multidomain directory into a list.
#'
#' This just applies get_all_recent_results to all domain output folders in a
#' multidomain.
#'
#' @param multidomain_dir the directory with the results
#' @param ... Further arguments to get_all_recent_results
#' @return A list with one entry per domain, containing the result of
#' get_all_recent_results
get_multidomain<-function(multidomain_dir, ...){
all_domain_files = Sys.glob(paste0(multidomain_dir, '/RUN_*'))
md = lapply(all_domain_files, function(x) get_all_recent_results(x, ...))
return(md)
}
#' Get the times at which grids or gauges are output in the multidomain
#'
#' Sometimes it is useful to know how many times there are
#'
#' @param multidomain_dir Directory containing the multidomain
#' @param output_type either 'grids' (default) or 'gauges'
#' @return a vector of times at which the 'grids' or 'gauges' are output
#'
get_multidomain_output_times<-function(multidomain_dir, output_type='grids'){
.library_quiet(ncdf4)
if(!file.exists(multidomain_dir)){
stop(paste0('Could not find multidomain_dir ', multidomain_dir))
}
# Find the netcdf grid or gauges files, depending
if(output_type =='grids'){
target_files = Sys.glob(
paste0(multidomain_dir, '/RUN_*/Grid_output_*.nc'))
}else if(output_type == 'gauges'){
target_files = Sys.glob(
paste0(multidomain_dir, '/RUN_*/Gauges_data_*.nc'))
}else{
stop(paste0('output_type should be "grids" or "gauges", but I got: ',
output_type))
}
if(length(target_files) < 1){
stop(paste0('Could not find any files holding ', output_type,
' in multidomain ', multidomain_dir))
}
fid = nc_open(target_files[1], readunlim=FALSE)
time = as.numeric(ncvar_get(fid, 'time'))
nc_close(fid)
return(time)
}
#' Convert peak stage output to raster using the domain object.
#'
#' Instead consider using 'merge_domains_nc_grids' which will combine
#' partitioned domains, and can output rasters. OR if you just want to make a
#' plot, consider 'multidomain_image', which works for the full multidomain.
#'
#' @param swals_out result of get_all_recent_results
#' @param proj4string
#' @param na_above_zero logical. If TRUE, then when elevation is > 0, set all
#' stages to NA
#' @param return_elevation logical. If TRUE, return a list with max_stage AND
#' elevation as rasters
#' @param na_outside_priority_domain If TRUE, set the raster to NA in
#' non-priority-domain regions. This is a good idea to simplify
#' interpretation.
#' @return Either the max_stage_raster (if return_elevation=FALSE), or a list
#' with both the max_stage and elevation rasters.
make_max_stage_raster<-function(swals_out, proj4string='EPSG:4326',
na_above_zero=FALSE, return_elevation=FALSE,
na_outside_priority_domain=FALSE){
.library_quiet(raster)
if(length(dim(swals_out$maxQ)) == 3){
# Using old binary format
stg = swals_out$maxQ[,,1]
elev = swals_out$maxQ[,,2]
}else{
# Using netcdf format
stg = swals_out$maxQ
elev = swals_out$elev0
}
if(na_above_zero){
stg[elev > 0] = NA
}
if(na_outside_priority_domain){
priority_region = swals_out$is_priority_domain
stg[!priority_region] = NA
elev[!priority_region] = NA
}
# Make max-stage raster
dx = swals_out$xs[2] - swals_out$xs[1]
dy = swals_out$ys[2] - swals_out$ys[1]
xs = swals_out$xs
ys = swals_out$ys
max_stage = raster(t(stg), xmn=min(xs)-dx/2,
xmx = max(xs)+dx/2, ymn=min(ys)-dy/2, ymx=max(ys)+dy/2)
max_stage = flip(max_stage, direction='y')
proj4string(max_stage) = proj4string
if(!return_elevation){
return(max_stage)
}else{
# Make elevation raster
elevation = raster(t(elev), xmn=min(xs)-dx/2,
xmx = max(xs)+dx/2, ymn=min(ys)-dy/2, ymx=max(ys)+dy/2)
elevation = flip(elevation, direction='y')
proj4string(elevation) = proj4string
output = list(max_stage = max_stage, elevation=elevation)
return(output)
}
}
#' Make an image plot for a multidomain
#'
#' This function will read the required output data from all domains in the
#' multidomain, and combine into a single plot. It generally doesn't need to
#' use much memory, and is particularly useful in cases where reading all the
#' multidomain data would be prohibitive.
#'
#' @param multidomain_dir directory where all multidomain outputs live
#' @param variable 'max_stage' or 'stage' or any other variable in the netcdf
#' file
#' @param time_index if the variable has a time dimension, the index which we
#' plot
#' @param xlim xlimit for image
#' @param ylim ylimit for image
#' @param zlim z limits for variable in image plot
#' @param col colourscheme for variable in image plot
#' @param add if TRUE, add to an existing plot
#' @param var_transform_function if not NULL, a function that is used to
#' transform the variable before plotting
#' @param NA_if_stage_not_above_elev logical. If TRUE, the set regions with
#' stage <= (elev + dry_depth) to NA
#' @param NA_if_max_flux_is_zero logical. If TRUE, then set regions with
#' max_flux == 0 to NA. This can be useful if you
#' have a model with a time-varying earthquake source, where in subsiding areas
#' that are dry the max_stage may be greater than the final elevation (=elevation0).
#' These sites are distinguished by having zero max_flux.
#' @param use_fields logical. If TRUE, use image.plot from the fields package.
#' Otherwise use graphics::image
#' @param clip_to_zlim logical. If TRUE, clip the variable limits to be within
#' zlim before plotting.
#' @param buffer_is_priority_domain. If TRUE, replace "is_priority_domain" with
#' a version that is TRUE even if the neighbouring cell is a priority domain.
#' This is an attempt to remove gaps in the image that can occur if we use a
#' spatial_stride != 1
#' @param asp plot x-y aspect ratio
#' @param fields_axis_args If use_fields=TRUE, then this list is passed to
#' image.plot(..., axis.args=fields_axis_args). It can be used to control the
#' labels on the colourbar.
#' @param dry_depth Used to determine dry regions, see documentation above for
#' NA_if_stage_not_above_elev
#' @return Nothing, but make the plot.
multidomain_image<-function(multidomain_dir, variable, time_index,
xlim, ylim, zlim, cols, add=FALSE,
var_transform_function = NULL,
NA_if_stage_not_above_elev = FALSE,
NA_if_max_flux_is_zero = FALSE,
use_fields=FALSE, clip_to_zlim=FALSE,
buffer_is_priority_domain=FALSE, asp=1, fields_axis_args=list(),
dry_depth = 1.0e-03){
.library_quiet('ncdf4')
.library_quiet(fields)
# Find all netcdf
all_nc = Sys.glob(paste0(multidomain_dir, '/*/Grid*.nc'))
# Start a new plot
if(use_fields){
if(!add) image.plot(matrix(0, ncol=2, nrow=2), asp=asp,
xlim=xlim, ylim=ylim, zlim=zlim,
col=cols, nlevel=length(cols)+1,
axis.args=fields_axis_args)
}else{
if(!add) image(matrix(0, ncol=2, nrow=2), asp=asp, col='white',
xlim=xlim, ylim=ylim, zlim=zlim)
}
# Loop over all domains, and add them to the image
for(i in 1:length(all_nc)){
# Open data
fid = nc_open(all_nc[i], readunlim=FALSE)
# Get x/y coords
xs = ncvar_get(fid, 'x')
ys = ncvar_get(fid, 'y')
# Get the variable of interest
if(fid$var[[variable]]$ndim > 2){
var = ncvar_get(fid, variable, start=c(1,1, time_index),
count=c(-1,-1,1))
}else{
var = ncvar_get(fid, variable)
}
# Find out where the priority domain is
is_priority = ncvar_get(fid, 'is_priority_domain')
if(buffer_is_priority_domain){
# In some situations this can remove 'gaps' in the image that result
# from using (stride > 1) in the output grids
nx = length(xs)
ny = length(ys)
for(inner_i in (-1):1){
for(inner_j in (-1):1){
is_priority[2:(nx-1), 2:(ny-1)] = pmax(
is_priority[2:(nx-1), 2:(ny-1)],
is_priority[(2:(nx-1)) + inner_i, (2:(ny-1)) + inner_j])
}
}
}
# Set areas outside of priority domain to NA
var[is_priority != 1] = NA
if(NA_if_stage_not_above_elev){
# Read stage and elevation, and set var to NA there
if(variable %in% c('max_stage', 'stage')){
stage = var
}else{
stage = ncvar_get(fid, 'stage', start=c(1,1, time_index),
count=c(-1,-1,1))
}
if('elev' %in% names(fid$var)){
elevation = ncvar_get(fid, 'elev', start=c(1,1, time_index),
count=c(-1,-1,1))
}else{
elevation = ncvar_get(fid, 'elevation0', start=c(1,1),
count=c(-1,-1))
}
var[stage < elevation + dry_depth] = NA
}
if(NA_if_max_flux_is_zero){
# Use NA values at sites where max_flux is zero. This can be useful if you
# have a model with a time-varying earthquake source, where in subsiding areas
# that are dry the max_stage may be greater than the final elevation (=elevation0).
# These sites are distinguished by having zero max_flux.
if('max_flux' %in% names(fid$var)){
max_flux = ncvar_get(fid, 'max_flux')
var[max_flux ==0] = NA
}else{
stop('max_flux not provided in output file, cannot use it for multidomain_image')
}
}
nc_close(fid)
if(!is.null(var_transform_function)) var = var_transform_function(var)
#image(xs2, ys2, var, zlim=zlim, col=cols, add=TRUE)
# Try giving the 'boundary' points to image
dx = (xs[length(xs)] - xs[1])/(length(xs)-1)
dy = (ys[length(ys)] - ys[1])/(length(ys)-1)
xs2 = seq(xs[1] - dx/2, xs[length(xs)] + dx/2, len=length(xs)+1)
ys2 = seq(ys[1] - dy/2, ys[length(ys)] + dy/2, len=length(ys)+1)
if(clip_to_zlim){
var = pmax(var, zlim[1])
var = pmin(var, zlim[2])
}
image(xs2, ys2, var, zlim=zlim, col=cols, add=TRUE, useRaster=TRUE)
}
}
#' Are coordinates x,y are on the priority domain of "domain"?
#'
#' The priority_domain is the region where the domain has the
#' flow solution that should be use. Other regions are halos (where
#' the domain receives from other domains) and null-regions (which
#' are isolated (by halo exchanges) from the solution that should be
#' used).
#'
#' @param x vector of x coordinates
#' @param y vector of y coordinates cooresponding to the x coordinates
#' @param domain result of get_all_recent_results( )
#' @return logical vector with TRUE where x,y is in the priority domain of
#' "domain", and FALSE otherwise
is_on_priority_domain<-function(x, y, domain){
# Get indices of xi/yi on the domain (if x/y are not on the domain, this
# may lead to indices outside the domain)
x_int = ceiling(
(x-domain$lower_left_corner[1])/(domain$lw[1] ) * length(domain$xs))
y_int = ceiling(
(y-domain$lower_left_corner[2])/(domain$lw[1] ) * length(domain$ys))
is_on = rep(FALSE, length(x_int))
# NOTE: If the netcdf output is decimated, then possibly nx != domain$nx
nx = dim(domain$is_priority_domain)
for(i in 1:length(is_on)){
xi = x_int[i]
yi = y_int[i]
if( (xi > 0) & (xi <= nx[1]) & (yi > 0) & (yi <= nx[2])){
# We are on the domain
# Check if we are in the priority region
if(domain$is_priority_domain[xi,yi] == 1) is_on[i] = TRUE
}
}
return(is_on)
}
#' Find the cell in a domain that is nearest a specified point
#'
#' Given a domain object (i.e. output from 'get_all_recent_results'), find the
#' index and distance of the point (grid-cell) nearest to 'x', 'y'
#'
#' @param x vector of x coordinates
#' @param y vector of y coordinates cooresponding to the x coordinates
#' @param domain result of get_all_recent_results( )
#' @return a list with xind/yind (2D indices of cells containing x/y), and
#' dist (the distance of x/y to the nearest cell x/y coordinates)
nearest_point_in_domain<-function(x, y, domain){
kx = which.min(abs(x-domain$xs))
ky = which.min(abs(y-domain$ys))
d_x = (domain$xs[kx]-x)
d_y = (domain$ys[ky]-y)
out = list(xind=NA, yind=NA, dist=NA)
if( (kx <= length(domain$is_priority_domain[,1])) &
(ky <= length(domain$is_priority_domain[1,]))){
if(domain$is_priority_domain[kx,ky] == 1){
out = list(xind=kx, yind=ky, dist=sqrt(d_x^2 + d_y^2))
}
}
return(out)
}
#' Find the x/y range of a coordinates in multidomain.
#'
#' @param md a list of domain objects (e.g. output of
#' "get_all_recent_results"), which collectively make the multidomain
#' @return the x-range (min_x, max_x) and y-range (min_y, max_y)
multidomain_range<-function(md){
all_ranges = lapply(md, function(x) rbind(range(x$xs), range(x$ys)))
min_x = min(unlist(lapply(all_ranges, function(x) x[1,1])))
min_y = min(unlist(lapply(all_ranges, function(x) x[2,1])))
max_x = min(unlist(lapply(all_ranges, function(x) x[1,2])))
max_y = min(unlist(lapply(all_ranges, function(x) x[2,2])))
out = rbind(c(min_x, max_x), c(min_y, max_y))
return(out)
}
#' Find the cell in a multidomain that is nearest to 'x,y'.
#'
#' It will return the xindex, yindex, distance, and index of the domain in md.
#'
#' @param x vector of x coordinates
#' @param y vector of y coordinates cooresponding to the x coordinates
#' @param md is a list of domain objects (e.g. output of
#' "get_all_recent_results"), which collectively make the multidomain
#' @return a list with xind/yind (2D indices of cells containing x/y), and
#' dist (the distance of x/y to the nearest cell x/y coordinates), and the
#' closest_domain (as in index in the list md)
nearest_point_in_multidomain<-function(x, y, md){
md_nearest = lapply(md, function(z) nearest_point_in_domain(x, y, z))
md_nearest_distances = unlist(lapply(md_nearest, function(x) x$dist))
if(all(is.na(md_nearest_distances))){
# The point is not in any domain. This can happen e.g. when we ask for
# points at model boundaries
closest_domain = -Inf
out = list(xind=NA, yind=NA, dist=NA)
}else{
closest_domain = which.min(md_nearest_distances)
out = md_nearest[[closest_domain]]
}
out$closest_domain=closest_domain
return(out)
}
#' Merge netcdf files which partition a single domain
#'
#' Given a collection of netcdf grid files which partition A SINGLE DOMAIN,
#' merge them. This can provide a method for working with
#' distributed-memory-parallel multidomains, by first combining each domain into
#' a single output.
#' There are 2 ways to select the netcdf files to merge:
#' 1) Provide 'nc_grid_files', OR
#' 2) Provide both 'multidomain_dir' and 'domain_index'
#'
#' @param nc_grid_files vector with all nc_grid files that together make up the
#' domain
#' @param multidomain_dir directory with multidomain
#' @param domain_index index of the domain of interest
#' @param desired_var name of variable in the netcdf file
#' @param desired_time_index time slice of variable in the netcdf file (or NA
#' for non-time variables)
#' @param return_raster If FALSE, return a list with xs, ys, grid. Otherwise
#' return a raster
#' @param proj4string projection info for the raster if return_raster=TRUE
#'
#' ## Example 1 -- provide vector of file names
#' all_nc = Sys.glob('RUN_ID000000000*00001_0*/Grid*.nc')
#' p1 = merge_domains_nc_grids(nc_grid_files = all_nc)
#'
#' ## Example 2 -- nicer -- provide multidomain directory, and domain index
#' p1 = merge_domains_nc_grids(multidomain_dir='.', domain_index=3)
#'
merge_domains_nc_grids<-function(nc_grid_files = NULL, multidomain_dir=NA,
domain_index = NA, desired_var = 'max_stage', desired_time_index = NA,
return_raster=FALSE, proj4string="EPSG:4326"){
.library_quiet('ncdf4')
.library_quiet('raster')
.library_quiet('sp')
# Check input makes sense
if(all(is.null(nc_grid_files)) &
(is.na(multidomain_dir) | is.na(domain_index))){
stop('Must provide EITHER nc_grid_files OR domain_index and multidomain_dir')
}
# Find the matching domain files
if(all(is.null(nc_grid_files))){
# NOTE: The number of '0' ahead of "domain_index" below protects us
# against accidently matching other domains, but will eventually fail
# if we have enough domains. For instance, if we have 10001 domains,
# then domains '1' and '10001' would both match together, which
# would be wrong. Some way off however!
nc_grid_files = Sys.glob(
paste0(multidomain_dir, '/RUN_ID0*000', domain_index,
'_*/Grid*000', domain_index, '.nc'))
}
# Get x,y,time in all the files
xs = vector(mode='list', length=length(nc_grid_files))
ys = vector(mode='list', length=length(nc_grid_files))
ts = vector(mode='list', length=length(nc_grid_files))
for(i in 1:length(nc_grid_files)){
fid = nc_open(nc_grid_files[i], readunlim=FALSE)
xs[[i]] = ncvar_get(fid, 'x')
ys[[i]] = ncvar_get(fid, 'y')
ts[[i]] = ncvar_get(fid, 'time')
nc_close(fid)
}
# Check that times are compatible in all files
if(length(ts) > 1){
# We will accept "numerically negligable" differences in times
dts = c(0, diff(ts[[1]]))
for(i in 2:length(ts)){
if(!all(abs(ts[[i]] - ts[[1]]) <= dts/1000)){
print(paste0('Times in file ', i, ': ', nc_grid_files[i],
' are incompatible with times in file 1: ',
nc_grid_files[1]))
print(cbind(ts[[i]], ts[[1]]))
stop('Times are incompatible')
}
}
}