-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathget_geo.R
executable file
·1481 lines (1283 loc) · 71 KB
/
get_geo.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
# This file contains useful functions for analyzing and visualizing geographical (spatial) data.
# Contact: Amos P. K. Tai ([email protected])
# Update history:
#
# Nov 2017 (Tai, Leung): Added the capacity to customize color schemes in plot.field() when using "custom.breaks", and added functionalities to plot legend/image only, specify the position of the legend, and new country features. Also created inv.terrain.colors() to display soil-vegetation related variables. Also modified plot.site() so that the map can be overlayed onto an existing one.
#
# Jan 2018 (Tai): Created a new function make.land.mask() that can create a land mask for any given lon-lat grid.
# Feb 2020 (Tai): Added new functionality to find grid cell sum during regridding in function sp.regrid().
###############################################################################
# Approximate the distance between two locations from the latitudes and longitudes:
dist.latlon = function(lat1, lon1, lat2, lon2) {
# This function calculates the distance (in km) between two locations on Earth, given their latitudes and longitudes.
# lat/lon is in angle
lat1 = lat1/180*pi
lat2 = lat2/180*pi
lon1 = lon1/180*pi
lon2 = lon2/180*pi
arc.angle = acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(abs(lon2-lon1)))
dist = arc.angle*6371.009
# 6371.009 km is the mean Earth radius defined by the International Union of Geodesy and Geophysics. Alternatively, you may use 6371.22 km as in the Community Earth System Model.
return(dist)
}
###############################################################################
# Approximate the area of a spatial grid square from the latitudes and longitudes of the diagonal vertices:
area.latlon = function(lat1, lon1, lat2, lon2) {
# This function calculates the area (in km^2) of a spatial grid square, given the latitudes and longitudes of the two diagonal vertices of the grid square.
# lat/lon is in angle; lat: [-90:90]; lon:[-180:180].
# lat1/lon1 and lat2/lon2 are thus the diagonal vertices of the square grid.
lat1 = lat1/180*pi
lat2 = lat2/180*pi
lon1 = lon1/180*pi
lon2 = lon2/180*pi
A = abs(6371.009^2*(sin(lat2)-sin(lat1))*(lon2-lon1))
# 6371.009 km is the mean Earth radius defined by the International Union of Geodesy and Geophysics. Alternatively, you may use 6371.22 km as in the Community Earth System Model.
return(A)
}
###############################################################################
# Finding the indices for a particular location given its longitude and latitude:
find.lon.lat = function(lonspec, latspec, lon, lat) {
# This function finds the indices for a particular location (given "lonspec" and "latspec") in the regularly spaced vectors of longitude ("lon") and latitude ("lat") frames.
lat.orig = lat
if (lat[length(lat)] > lat[1]) {
# 'lat' is in increasing order. Need to reverse it to proceed further.
lat = rev(lat)
}
dlon = abs(lon[2]-lon[1])
dlat = abs(lat[2]-lat[1])
if (lonspec < (min(lon)-dlon/2) | lonspec > (max(lon)+dlon/2) | latspec > (max(lat)+dlat/2) | latspec < (min(lat)-dlat/2)) {
return(NaN)
} else {
if (lonspec < min(lon)) lon1 = 1 else lon1 = max(which(lon <= lonspec))
if (lonspec > max(lon)) lon2 = length(lon) else lon2 = min(which(lon >= lonspec))
if (latspec < min(lat)) lat1 = length(lat) else lat1 = min(which(lat <= latspec))
if (latspec > max(lat)) lat2 = 1 else lat2 = max(which(lat >= latspec))
if (abs(lon[lon1]-lonspec) > abs(lon[lon2]-lonspec)) lon.ind = lon2 else lon.ind = lon1
if (abs(lat[lat1]-latspec) > abs(lat[lat2]-latspec)) lat.ind = lat2 else lat.ind = lat1
if (lat.orig[length(lat.orig)] > lat.orig[1]) lat.ind = length(lat.orig) - lat.ind + 1
return(c(lon.ind, lat.ind))
}
}
###############################################################################
# Interpolation method 1 - spatial averaging:
spavg = function(spdata, latlon, lat.frame, lon.frame, dlat=NULL, dlon=NULL) {
# This function performs interpolation by spatial averaging from a vector of point data into a specified lat-lon frame.
# "spdata" is a vector of spatial (point) data.
# "latlon" has two columns: 1. latitude; 2. longitude; each pair of lat/lon corresponding to each datum in "spdata".
# "lon.frame" has to be in increasing order and "lat.frame" can be in either order.
# This function utilizes another function "find.lat.lon".
lat.frame.orig = lat.frame
if (lat.frame[length(lat.frame)] > lat.frame[1]) {
# 'lat.frame' is in increasing order. Need to reverse it to proceed further.
lat.frame = rev(lat.frame)
}
if (is.null(dlat)) dlat = abs(lat.frame[2]-lat.frame[1])
if (is.null(dlon)) dlon = abs(lon.frame[2]-lon.frame[1])
interpol = matrix(0, nrow=length(lon.frame), ncol=length(lat.frame))
MAT = cbind(spdata, latlon)
MAT = na.omit(MAT)
spdata = MAT[,1]
latlon = MAT[,2:3]
if (nrow(MAT) == 0) interpol = NaN
else if (nrow(MAT) == 1) {
ind = find.lon.lat(latlon[2], latlon[1], lon.frame, lat.frame)
if (length(ind) == 1) interpol = NaN
else interpol[ind[1],ind[2]] = spdata
}
else {
for (i in 1:length(lon.frame)) {
for (j in 1:length(lat.frame)) {
ind = which(latlon[,1] >= (lat.frame[j]-dlat/2) & latlon[,1] <= (lat.frame[j]+dlat/2) & latlon[,2] >= (lon.frame[i]-dlon/2) & latlon[,2] <= (lon.frame[i]+dlon/2))
interpol[i,j] = mean(spdata[ind], na.rm=TRUE)
}
}
}
if (lat.frame.orig[length(lat.frame.orig)] > lat.frame.orig[1]) interpol = interpol[,length(lat.frame.orig):1]
return(interpol)
}
###############################################################################
# Interpolation method 2 - inverse distance weighting:
invdist = function(spdata, latlon, lat.frame, lon.frame, n=2, dlim=500) {
# This function performs interpolation by IDW from a vector of point data into a specified lat-lon frame.
# "spdata" is a vector of spatial (point) data.
# "latlon" has two columns: 1. latitude; 2. longitude; each pair of lat/lon corresponding to each datum in "spdata".
# "lon.frame" has to be in increasing order and "lat.frame" can be in either order.
# "n" is the power parameter.
# "dlim" (in km) is the maximum search distance only within which the data are counted for interpolation.
# This function utilizes another functions "dist.latlon" and "find.lon.lat".
lat.frame.orig = lat.frame
# If 'lat.frame' is in increasing order, we need to reverse it to proceed further:
if (lat.frame[length(lat.frame)] > lat.frame[1]) lat.frame = rev(lat.frame)
interpol = matrix(0, nrow=length(lon.frame), ncol=length(lat.frame))
MAT = cbind(spdata, latlon)
MAT = na.omit(MAT)
spdata = MAT[,1]
latlon = MAT[,2:3]
if (nrow(MAT) == 0) {
interpol = NaN
} else if (nrow(MAT) == 1) {
ind = find.lon.lat(latlon[2], latlon[1], lon.frame, lat.frame)
if (length(ind) == 1) interpol = NaN else interpol[ind[1],ind[2]] = spdata
} else {
for (i in 1:length(lon.frame)) {
for (j in 1:length(lat.frame)) {
dist = dist.latlon(lat.frame[j], lon.frame[i], latlon[,1], latlon[,2])
weight = 1/dist^n
ind = which(dist <= dlim)
interpol[i,j] = spdata[ind]%*%weight[ind]/sum(weight[ind], na.rm=TRUE)
}
}
}
if (lat.frame.orig[length(lat.frame.orig)] > lat.frame.orig[1]) interpol = interpol[,length(lat.frame.orig):1]
return(interpol)
}
###############################################################################
# Standard deviation of sample data in a square grid:
spsd = function(spdata, latlon, lat.frame, lon.frame) {
# This function finds the standard deviation of spatially averaged interpolated fields (using function "spavg") for each grid square.
# "spdata" is a vector of spatial (point) data.
# "latlon" has two columns: 1. latitude; 2. longitude; each pair of lat/lon corresponding to each datum in "spdata".
# "lon.frame" has to be in increasing order and "lat.frame" has to be in decreasing order.
# This function utilizes another function "find.lat.lon".
dlon = abs(lon.frame[2]-lon.frame[1])
dlat = abs(lat.frame[2]-lat.frame[1])
stdev = matrix(0, nrow=length(lon.frame), ncol=length(lat.frame))
MAT = cbind(spdata, latlon)
MAT = na.omit(MAT)
spdata = MAT[,1]
latlon = MAT[,2:3]
if (nrow(MAT) <= 2) stdev = NaN else {
for (i in 1:length(lon.frame)) {
for (j in 1:length(lat.frame)) {
ind = which(latlon[,1] >= (lat.frame[j]-dlat/2) & latlon[,1] <= (lat.frame[j]+dlat/2) & latlon[,2] >= (lon.frame[i]-dlon/2) & latlon[,2] <= (lon.frame[i]+dlon/2))
if (length(ind) < 2) stdev[i,j] = NaN else stdev[i,j] = sd(spdata[ind], na.rm=TRUE)
}
}
}
return(stdev)
}
###############################################################################
# Calculating average quantity of neighboring grid squares:
neighbor.avg <- function(spdata) {
# This function calculates, for each grid square in an interpolated field, the mean value of a variable in the neighboring grid squares.
# "spdata" is a matrix of interpolated spatial data.
navg <- matrix(0, nrow=nrow(spdata), ncol=ncol(spdata))
for (i in 1:nrow(navg)) {
for (j in 1:ncol(navg)) {
if (i == 1 & j == 1)
ndata <- spdata[i:(i+1),j:(j+1)]
else if (i == nrow(navg) & j == ncol(navg))
ndata <- spdata[(i-1):i,(j-1):j]
else if (i == 1 & j == ncol(navg))
ndata <- spdata[i:(i+1),(j-1):j]
else if (i == nrow(navg) & j == 1)
ndata <- spdata[(i-1):i,j:(j+1)]
else if (i == 1)
ndata <- spdata[i:(i+1),(j-1):(j+1)]
else if (j == 1)
ndata <- spdata[(i-1):(i+1),j:(j+1)]
else if (i == nrow(navg))
ndata <- spdata[(i-1):i,(j-1):(j+1)]
else if (j == ncol(navg))
ndata <- spdata[(i-1):(i+1),(j-1):j]
else
ndata <- spdata[(i-1):(i+1),(j-1):(j+1)]
ndata <- na.omit(as.vector(ndata))
navg[i,j] <- (mean(ndata)*length(ndata)-spdata[i,j])/(length(ndata)-1)
}
}
return(navg)
}
###############################################################################
# Regridding spatial field data into another resolution, e.g., dissolving spatial field data into lower resolution (larger pixel size):
sp.regrid = function(spdata, lon.in, lat.in, lon.out, lat.out, method="mean", full.lon=FALSE, dlon.in=NULL, dlat.in=NULL, dlon.out=NULL, dlat.out=NULL) {
# This function dissolves spatial field data (matrix or 3D array) into lower resolution with larger grid squares; it can also be used to regrid spatial field data into any other resolution.
# "spdata" is a matrix with rows corresponding to longitudes ("lon.in") and columns corresponding to latitudes ("lat.in"), or a 3D array with the first two dimensions between longitude and latitude.
# "lon.out" and "lat.out" are the lon/lat frames for the output resolution.
# "lon.in" and "lon.out" should be in increasing order; "lat.in" and "lat.out" can be in either order, but they should have the same order.
# There are three supported methods: 1. default "mean", i.e., calculating the area-weighted average; 2. "mode", take the value occupying the largest area in each output grid; 3. "sum", find the sum over all embedded grid cells, with edge grid cells discounted by areas over areas of original grid cells. For 3D array, however, only "method='mean'" is supported. ("sum" functionality added by Tai, Feb 2020)
# This function utilizes another functions "area.latlon" and "find.lon.lat".
ndim = length(dim(spdata))
if (ndim < 2 | ndim > 3) stop('Dimensions of spdata are not correct! Only 2D and 3D arrays are supported.')
lat.in.orig = lat.in
lat.out.orig = lat.out
if (lat.in[length(lat.in)] > lat.in[1] & lat.out[length(lat.out)] > lat.out[1]) {
# 'lat.in' and 'lat.out' are in increasing order. Need to reverse them to proceed further.
lat.in = rev(lat.in)
if (ndim == 2) spdata = spdata[,length(lat.in):1]
if (ndim == 3) spdata = spdata[,length(lat.in):1,]
lat.out = rev(lat.out)
}
if ( (lat.in[length(lat.in)] > lat.in[1] & lat.out[length(lat.out)] < lat.out[1]) | (lat.in[length(lat.in)] < lat.in[1] & lat.out[length(lat.out)] > lat.out[1]) ) stop('lat.in and lat.out should have the same increasing/decreasing order.')
if (is.null(dlon.in)) dlon.in = abs(lon.in[2]-lon.in[1])
if (is.null(dlat.in)) dlat.in = abs(lat.in[2]-lat.in[1])
if (is.null(dlon.out)) dlon.out = abs(lon.out[2]-lon.out[1])
if (is.null(dlat.out)) dlat.out = abs(lat.out[2]-lat.out[1])
if (full.lon) {
# If the data has full longitude range (e.g. 0:360, -180:180), we add matching lon to head and tail of lon.in.
library(abind)
lon.in.new = c(lon.in[1]-dlon.in, lon.in, lon.in[length(lon.in)]+dlon.in)
if (ndim == 2) spdata = abind(spdata[length(lon.in),], spdata, spdata[1,], along=1)
if (ndim == 3) spdata = abind(spdata[length(lon.in),,], spdata, spdata[1,,], along=1)
lon.in = lon.in.new
}
lon.in.lim = c((lon.in-dlon.in/2), (lon.in[length(lon.in)]+dlon.in/2))
lat.in.lim = c((lat.in+dlat.in/2), (lat.in[length(lat.in)]-dlat.in/2))
if (ndim == 2) {
# Add new functionality to calculate sum (Tai, Feb 2020):
if (method == 'sum') {
area.orig.grid = array(0, dim=c(length(lon.in), length(lat.in)))
for (i in 1:length(lon.in)) {
for (j in 1:length(lat.in)) {
area.orig.grid[i,j] = area.latlon(lat.in.lim[j], lon.in.lim[i], lat.in.lim[j+1], lon.in.lim[i+1])
}
}
}
# Added above a new functionality to calculate sum (Tai, Feb 2020).
sp.out = matrix(0, nrow=length(lon.out), ncol=length(lat.out))
for (i in 1:length(lon.out)) {
for (j in 1:length(lat.out)) {
lon.out1 = lon.out[i]-dlon.out/2
lon.out2 = lon.out[i]+dlon.out/2
lat.out1 = lat.out[j]+dlat.out/2
lat.out2 = lat.out[j]-dlat.out/2
lon.frame = c(lon.out1, lon.in.lim[which(lon.in.lim >= lon.out1 & lon.in.lim <= lon.out2)], lon.out2)
lat.frame = c(lat.out1, lat.in.lim[which(lat.in.lim <= lat.out1 & lat.in.lim >= lat.out2)], lat.out2)
area = matrix(0, nrow=(length(lat.frame)-1), ncol=(length(lon.frame)-1))
for (x in 1:nrow(area)) {
for (y in 1:ncol(area)) {
area[x,y] = area.latlon(lat.frame[x], lon.frame[y], lat.frame[x+1], lon.frame[y+1])
}
}
data = matrix(0, nrow=(length(lat.frame)-1), ncol=(length(lon.frame)-1))
if (method == "sum") area.orig = matrix(0, nrow=(length(lat.frame)-1), ncol=(length(lon.frame)-1))
for (x in 1:nrow(data)) {
for (y in 1:ncol(data)) {
lat.centroid = (lat.frame[x]+lat.frame[x+1])/2
lon.centroid = (lon.frame[y]+lon.frame[y+1])/2
ind = find.lon.lat(lon.centroid, lat.centroid, lon.in, lat.in)
lat.ind = ind[2]
lon.ind = ind[1]
data[x,y] = spdata[lon.ind,lat.ind]
if (method == "sum") area.orig[x,y] = area.orig.grid[lon.ind,lat.ind]
}
}
MAT = cbind(as.vector(data), as.vector(area))
if (method == "sum") MAT = cbind(as.vector(data), as.vector(area), as.vector(area.orig))
MAT = na.omit(MAT)
data = MAT[,1]
area = MAT[,2]
if (method == "sum") area.orig = MAT[,3]
if (method == "mean") {
sp.out[i,j] = sum(data*area)/sum(area)
} else if (method == "sum") {
sp.out[i,j] = sum(data*area/area.orig)
} else {
data.unique = unique(data)
area.unique = rep(0, times=length(data.unique))
for (n in 1:length(area.unique)) {
area.unique[n] = sum(area[which(data == data.unique[n])])
}
max.ind = which(area.unique == max(area.unique))
if (length(max.ind) == 1) sp.out[i,j] = data.unique[max.ind] else sp.out[i,j] = data.unique[max.ind[1]]
}
}
}
if (lat.out.orig[length(lat.out.orig)] > lat.out.orig[1]) sp.out = sp.out[,length(lat.out.orig):1]
} else {
# "spdata" are 3D.
if (method != 'mean') stop('For 3D array, only method=mean is supported.')
sp.out = array(NaN, dim=c(length(lon.out), length(lat.out), dim(spdata)[3]))
for (i in 1:length(lon.out)) {
for (j in 1:length(lat.out)) {
lon.out1 = lon.out[i]-dlon.out/2
lon.out2 = lon.out[i]+dlon.out/2
lat.out1 = lat.out[j]+dlat.out/2
lat.out2 = lat.out[j]-dlat.out/2
lon.frame = c(lon.out1, lon.in.lim[which(lon.in.lim >= lon.out1 & lon.in.lim <= lon.out2)], lon.out2)
lat.frame = c(lat.out1, lat.in.lim[which(lat.in.lim <= lat.out1 & lat.in.lim >= lat.out2)], lat.out2)
area = array(NaN, dim=c(length(lat.frame)-1, length(lon.frame)-1, dim(spdata)[3]))
for (x in 1:dim(area)[1]) {
for (y in 1:dim(area)[2]) {
for (t in 1:dim(area)[3]) {
area[x,y,t] = area.latlon(lat.frame[x], lon.frame[y], lat.frame[x+1], lon.frame[y+1])
}
}
}
data = array(NaN, dim=c(length(lat.frame)-1, length(lon.frame)-1, dim(spdata)[3]))
for (x in 1:dim(data)[1]) {
for (y in 1:dim(data)[2]) {
lat.centroid = (lat.frame[x]+lat.frame[x+1])/2
lon.centroid = (lon.frame[y]+lon.frame[y+1])/2
ind = find.lon.lat(lon.centroid, lat.centroid, lon.in, lat.in)
lat.ind = ind[2]
lon.ind = ind[1]
data[x,y,] = spdata[lon.ind,lat.ind,]
}
}
sp.out[i,j,] = apply(data*area, 3, sum, na.rm=TRUE)/apply(area*!is.na(data), 3, sum, na.rm=TRUE)
}
}
if (lat.out.orig[length(lat.out.orig)] > lat.out.orig[1]) sp.out = sp.out[,length(lat.out.orig):1,]
}
return(sp.out)
}
# "sp.regrid" and "sp.regrid.3D" used to be separate functions. Now they have been merged into one "sp.regrid".
# Also, these functions used to be called "sp.dissolve" and "sp.dissolve.3D" because the primary purpose was to dissolve higher resolution into lower resolution.
# For backward compatibility:
sp.regrid.3D = sp.regrid
sp.dissolve = sp.regrid
sp.dissolve.3D = sp.regrid.3D
###############################################################################
# Flip longitude from 0-360 to -180-180:
flip.lon = function(spdata, lon) {
# This function reorganizes a global spatial data array with longitude coordinates from 0 to 360 to the more conventional -180 to 180.
# "spdata" can be of any dimensions until eighth, but the first dimension has to be longitude.
# "lon" has to be in increasing order.
# This function requires the package "abind" to be installed and loaded.
ind.flip = which(lon >= 180)
lon.out = c((lon[ind.flip] - 360), lon[1:(ind.flip[1]-1)])
ndim = length(dim(spdata))
if (ndim == 2) spdata.out = rbind(spdata[ind.flip,], spdata[1:(ind.flip[1]-1),])
if (ndim == 3) spdata.out = abind(spdata[ind.flip,,], spdata[1:(ind.flip[1]-1),,], along=1)
if (ndim == 4) spdata.out = abind(spdata[ind.flip,,,], spdata[1:(ind.flip[1]-1),,,], along=1)
if (ndim == 5) spdata.out = abind(spdata[ind.flip,,,,], spdata[1:(ind.flip[1]-1),,,,], along=1)
if (ndim == 6) spdata.out = abind(spdata[ind.flip,,,,,], spdata[1:(ind.flip[1]-1),,,,,], along=1)
if (ndim == 7) spdata.out = abind(spdata[ind.flip,,,,,,], spdata[1:(ind.flip[1]-1),,,,,,], along=1)
if (ndim == 8) spdata.out = abind(spdata[ind.flip,,,,,,,], spdata[1:(ind.flip[1]-1),,,,,,,], along=1)
out = list(spdata=spdata.out, lon=lon.out)
return(out)
}
###############################################################################
# Turning zero or negative values into NaN, and vice versa:
# Turning zero of negative values into NaN:
zero.to.NaN = function(X) {
X[which(X <= 0)] = NaN
return(X)
}
# Turning NaN values into zero:
NaN.to.zero = function(X) {
X[which(is.na(X))] = 0
return(X)
}
###############################################################################
# Moran's I spatial autocorrelation for gridded data:
moran.I = function(spdata) {
# This function calculates the Moran's I spatial autocorrelation index for a matrix of gridded spatial data with an adjacency matrix (w_ij = 1 if i and j are adjacent; i.e., if a grid cell is one of the eight neiboring cells).
i.ind = matrix(rep(1:nrow(spdata), times=ncol(spdata)), nrow=nrow(spdata), byrow=FALSE)
j.ind = matrix(rep(1:ncol(spdata), times=nrow(spdata)), nrow=nrow(spdata), byrow=TRUE)
i.ind.vec = as.vector(i.ind)
j.ind.vec = as.vector(j.ind)
spdata.vec = as.vector(spdata)
MAT = na.omit(cbind(i.ind.vec, j.ind.vec, spdata.vec))
i.ind.vec = MAT[,1]
j.ind.vec = MAT[,2]
spdata.vec = MAT[,3]
weight.mat = matrix(0, nrow=length(spdata.vec), ncol=length(spdata.vec))
for (I in 1:length(spdata.vec)) {
for (J in 1:length(spdata.vec)) {
if (abs(diff(i.ind.vec[I], i.ind.vec[J])) <= 1 & abs(diff(j.ind.vec[I], j.ind.vec[J])) <= 1) weight.mat[I,J] = 1
}
}
diag(weight.mat) = 0
sum.cov = 0
y = spdata.vec
for (I in 1:length(y)) {
for (J in 1:length(y)) {
sum.cov = sum.cov + weight.mat[I,J]*(y[I] - mean(y))*(y[J] - mean(y))
}
}
I.value = length(y)/sum((y - mean(y))^2)*sum.cov/sum(weight.mat)
return(I.value)
}
###############################################################################
# Calculating the corresponding threshold R-value for a given p-value:
find.Rlim = function(pval, n) {
# "pval" is the desired p-value; "n" is the sample size.
t0 = qt(p=(1 - pval/2), df=(n - 1)) # The corresponding t-statistics
R = sqrt(t0^2/(n - 2 + t0^2)) # The corresponding R-value (correlation coefficient)
return(R)
}
###############################################################################
# Finding correlation coefficients between two variables for multiple locations:
find.cor = function(X, Y, plim=0.05, normalized=FALSE) {
# This function finds the correlation coefficients that are statistically significant (defined by a desired p-value "plim") for multiple locations along the third dimension of 3-dimensional arrays (usually time).
# X and Y are arrays of data with the first two dimensions defining the spatial frame (e.g. dim1 = longitude; dim2 = latitude; dim3 = time), and the correlation coefficients are found for the vectors of data contained in the third dimension.
# If "normalized" is TRUE, the inputs X and Y will be normalized to their standard deviations.
# This function utilizes another function "find.Rlim" to define the threshold R-value corresponding to the desired p-value.
cor.XY = matrix(0, nrow=nrow(X), ncol=ncol(Y))
for (i in 1:nrow(cor.XY)) {
for (j in 1:ncol(cor.XY)) {
if (length(unique(X[i,j,])) <= 2)
cor.XY[i,j] = NaN
else if (length(unique(Y[i,j,])) <= 2)
cor.XY[i,j] = NaN
else {
MAT = cbind(X[i,j,], Y[i,j,])
MAT = na.omit(MAT)
if (normalized) {
MAT[,1] = (MAT[,1] - mean(MAT[,1]))/sd(MAT[,1])
MAT[,2] = (MAT[,2] - mean(MAT[,2]))/sd(MAT[,2])
}
Rlim = find.Rlim(plim, nrow(MAT))
cor.MAT = cor(MAT[,1], MAT[,2])
if (abs(cor.MAT) < Rlim) cor.XY[i,j] = NaN
else cor.XY[i,j] = cor.MAT
}
}
}
return(cor.XY)
}
###############################################################################
# Quiver (vector arrow) plot:
quiver = function(u, v, xaxis, yaxis, xlab="x", ylab="y", scale=1, length=0.1, add=FALSE) {
# This function creates quiver (vector arrow) plots for 2-dimensional data, "u" being the x-component and "v" being the y-component.
# Source code from "http://fawn.unibw-hamburg.de/cgi-bin/Rwiki.pl?QuiverPlot".
# "u" and "v" are matrices of 2D data, and "xaxis" and "yaxis" correspond to the x- and y-axis for the data.
# "quiver" utilizes another function "par.uin" to determine scale of inches/userunits in x and y.
# First stab at MATLAB's quiver in R.
# From "http://tolstoy.newcastle.edu.au/R/help/01c/2711.html".
# Robin Hankin Tue 20 Nov 2001 - 13:10:28 EST.
xpos = matrix(rep(xaxis, times=length(yaxis)), ncol=length(yaxis))
ypos = matrix(rep(yaxis, times=length(xaxis)), nrow=length(xaxis), byrow=TRUE)
speed = sqrt(u*u+v*v)
maxspeed = max(speed)
u = u*scale/maxspeed
v = v*scale/maxspeed
matplot(xpos, ypos, type="p", cex=0, xlab=xlab, ylab=ylab, add=add)
arrows(xpos, ypos, xpos+u, ypos+v, length=length*min(par.uin()))
}
par.uin = function() {
# Determine scale of inches/userunits in x and y.
# From "http://tolstoy.newcastle.edu.au/R/help/01c/2714.html".
# Brian Ripley Tue 20 Nov 2001 - 20:13:52 EST.
u = par("usr")
p = par("pin")
c(p[1]/(u[2] - u[1]), p[2]/(u[4] - u[3]))
}
###############################################################################
# Red-white-blue color scale:
rwb.colors = function(n) {
# This function creates a vector of colors from dark blue to white to dark red, thus useful for displaying and contrasting positive versus negative values of a variable when we do a field plot.
# "n" is the number of color levels. "n" has to be an even number.
if (n/2 != round(n/2)) stop('n has to be an even number!')
red = rep(0, times=n)
green = rep(0, times=n)
blue = rep(0, times=n)
red[1:(n/2)] = seq(0, 1, length=(n/2))
red[(n/2 + 1):floor(n*3/4)] = 1
red[(floor(n*3/4) + 1):n] = seq(1, 0.5, length=ceiling(n/4))
green[1:(n/2)] = seq(0, 1, length=(n/2))
green[(n/2 + 1):n] = seq(1, 0, length=(n/2))
blue[1:ceiling(n/4)] = seq(0.5, 1, length=ceiling(n/4))
blue[(ceiling(n/4) + 1):(n/2)] = 1
blue[(n/2 + 1):n] = seq(1, 0, length=(n/2))
rwb = rgb(red, green, blue)
return(rwb)
}
###############################################################################
# Inverse terrain color scale:
inv.terrain.colors = function(n, alpha=1) {
# This function creates a vector of colors from light gray red to yellow to deep green, thus useful for displaying soil-vegetation related variables when we do a field plot.
# "n" is the number of color levels. "n" has to be an even number.
if ((n <- as.integer(n[1L])) > 0) {
k <- n%/%2
h <- c(0/12, 2/12, 4/12)
s <- c(0.1, 1, 1)
v <- c(0.85, 0.95, 0.25)
c(hsv(h = seq.int(h[1L], h[2L], length.out = k), s = seq.int(s[1L], s[2L], length.out = k), v = seq.int(v[1L], v[2L], length.out = k), alpha = alpha), hsv(h = seq.int(h[2L], h[3L], length.out = n - k + 1)[-1L], s = seq.int(s[2L], s[3L], length.out = n - k + 1)[-1L], v = seq.int(v[2L], v[3L], length.out = n - k + 1)[-1L], alpha = alpha))
}
else character()
}
###############################################################################
# Quick map plot:
# This function creates 1 to 9 map plots for spatial data using function "image.plot" from package "fields".
# Packages "fields" and "maps" must be pre-loaded.
# "spdata" is a matrix or an array of spatial data. The third dimension of "spdata" defines the number of plots.
# "type" is a vector of intended types of presentation, as explained below.
# Five types of presentation are supported:
# 1. "sign": variable that has both positive and negative values, good for comparing signs of correlations/effects/deviations.
# 2. "frac": variable that is a fraction or percentage, good for comparing proportions.
# 3. "abs": variable that has absolute values only, good for comparing magtitudes.
# 4. "def": user-defined scale and z-limits. (If chosen, must define the same same scale/limits for all plots.)
# 5. Default: no specification for display.
# If you want all plots to have the same type, simply enter a string scalar for "type".
# When "same" is set TRUE, all plots will have the same scale ("zlim").
quick.image = function(spdata, lon.map, lat.map, type=NULL, same=FALSE, zlim=NULL, col=tim.colors(32), nlevel=32, title='', width=6.5, height=4, mai=c(0.5, 0.4, 0.2, 0.2), mgp=c(1.4, 0.5, 0), tcl=-0.3, ps=12, legend.mar=3, legend.width=1.2) {
if (length(dim(spdata)) == 2) {
num.plot = 1
mfrow = c(1,1)
quartz(title=title, width=width, height=height)
par(mfrow=mfrow, mai=mai, mgp=mgp, tcl=tcl, ps=ps)
if (is.null(type)) {
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
}
else if (type == "sign") {
zlim = c(-max(abs(na.omit(as.vector(spdata)))), max(abs(na.omit(as.vector(spdata)))))
col = rwb.colors(nlevel)
}
else if (type == "frac") {
zlim = c(0,1)
}
else if (type == "abs") {
zlim = c(0, max(na.omit(as.vector(spdata))))
}
else if (type == "def") {
zlim = zlim
}
else {
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
}
image.plot(lon.map, lat.map, spdata, zlim=zlim, xlab="", ylab="", axis.args=list(mgp=c(0,0.3,0), tcl=-0.1), legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel)
map("world", add=T)
}
else {
num.plot = dim(spdata)[3]
if (num.plot == 2)
mfrow = c(2,1)
else if (num.plot == 3)
mfrow = c(3,1)
else if (num.plot == 4)
mfrow = c(2,2)
else if (num.plot == 5)
mfrow = c(3,2)
else if (num.plot == 6)
mfrow = c(3,2)
else if (num.plot == 7)
mfrow = c(4,2)
else if (num.plot == 8)
mfrow = c(4,2)
else # i.e. num.plot == 9
mfrow = c(3,3)
quartz(title=title, width=width, height=height)
par(mfrow=mfrow, mai=mai, mgp=mgp, tcl=tcl, ps=ps)
if (num.plot > 1 & length(type) == 1) # i.e. you want all the plots to have the same type.
type = rep(type, times=num.plot)
else { }
for (k in 1:num.plot) {
if (is.null(type[k])) {
if (same == TRUE)
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
else
zlim = c(min(na.omit(as.vector(spdata[,,k]))), max(na.omit(as.vector(spdata[,,k]))))
}
else if (type[k] == "sign") {
col = rwb.colors(nlevel)
if (same == TRUE)
zlim = c(-max(abs(na.omit(as.vector(spdata)))), max(abs(na.omit(as.vector(spdata)))))
else
zlim = c(-max(abs(na.omit(as.vector(spdata[,,k])))), max(abs(na.omit(as.vector(spdata[,,k])))))
}
else if (type[k] == "frac") {
zlim = c(0,1)
}
else if (type[k] == "abs") {
if (same == TRUE)
zlim = c(0, max(na.omit(as.vector(spdata))))
else
zlim = c(0, max(na.omit(as.vector(spdata[,,k]))))
}
else if (type[k] == "def") {
zlim = zlim
}
else {
if (same == TRUE)
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
else
zlim = c(min(na.omit(as.vector(spdata[,,k]))), max(na.omit(as.vector(spdata[,,k]))))
}
image.plot(lon.map, lat.map, spdata[,,k], zlim=zlim, xlab="", ylab="", axis.args=list(mgp=c(0,0.3,0), tcl=-0.1), legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel)
map("world", add=T)
}
}
}
###############################################################################
# Field map plot:
plot.field = function(spdata, lon.map, lat.map, type=NULL, same=FALSE, zlim=NULL, image.only=FALSE, legend.only=FALSE, horizontal=FALSE, col=NULL, nlevel=32, mai=c(0.2, 0.2, 0.1, 0.1), mgp=c(1.4, 0.5, 0), tcl=-0.3, ps=12, legend.mar=3, legend.width=1.2, xaxt="n", yaxt="n", Pacific.centric=FALSE, country=NULL, custom.breaks=NULL, map.xlim=NULL, map.ylim=NULL) {
# This function plots spatial field data using function "image.plot" from package "fields".
# Packages "fields" and "maps" must be pre-loaded. If Chinese/Japan provinces, Package "mapdata" is needed.
# "spdata" is a matrix or an array of spatial data.
# "type" is a vector of intended types of presentation, as explained below.
# Five types of presentation are supported:
# 1. "sign": variable that has both positive and negative values, good for comparing signs of correlations/effects/deviations.
# 2. "frac": variable that is a fraction or percentage, good for comparing proportions.
# 3. "abs": variable that has absolute values only, good for comparing magtitudes.
# 4. "def": user-defined scale and z-limits.
# 5. Default: no specification for display.
# You can specify the color scheme for the legend by specifying "col" (a function for color scheme, e.g., "tim.colors"); apart from inputting a function, you can also input a character string of hex color codes.
# You can also manually customize the numeric break points for the legend by specifying "custom.breaks" (a vector). For those who want to use custom.breaks together with hex color codes, you need to use a function colorRampPalette() from a package called "RColorBrewer".
# Last modified by Danny Leung (30 Nov 2017):
# New application: 1. plot.field() can now plot maps without legend by setting argument "image.only"; 2. plot.field() can now plot just the legend by setting argument "legend.only"; 3. the legend can be either horizontal at the bottom or vertical on the right by setting argument "horizontal=TRUE/FALSE".
# When the argument "image.only=TRUE", plot.field() plots map without legend. Further specification of arguments about legends will be ignored in the function. It will be ignored if "legend.only=TRUE".
# When the argument "legend.only=TRUE", plot.field() plots the legend without the map. "Please remember to set "image.only=FALSE"."image.only" will be ignored.
# Maps for some countries are now available. 'china', 'states' for the US, 'japan', 'france', and so on. Set "country" to customize your country map.
if (lat.map[length(lat.map)] < lat.map[1]) {
# 'lat.map' is in decreasing order. Need to reverse it to proceed further.
lat.map = rev(lat.map)
spdata = spdata[,length(lat.map):1]
}
par(mai=mai, mgp=mgp, tcl=tcl, ps=ps)
if (is.null(custom.breaks)) {
if (is.null(col)) col = tim.colors(nlevel) else if (is.function(col)) col = col(nlevel) else col = col
if (is.null(type)) {
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
} else if (type == 'sign') {
if (is.null(zlim)) zlim = c(-max(abs(na.omit(as.vector(spdata)))), max(abs(na.omit(as.vector(spdata))))) else zlim = zlim
# if (is.null(col)) col = rwb.colors(nlevel)
# If "sign" is used, the color scheme is always rwb.colors(nlevel).
col = rwb.colors(nlevel)
} else if (type == 'frac') {
zlim = c(0,1)
} else if (type == 'abs') {
zlim = c(0, max(na.omit(as.vector(spdata))))
} else if (type == 'def') {
zlim = zlim
} else {
zlim = c(min(na.omit(as.vector(spdata))), max(na.omit(as.vector(spdata))))
}
spdata[which(spdata > zlim[2])] = zlim[2]
spdata[which(spdata < zlim[1])] = zlim[1]
if (legend.only) image.only = FALSE
if (image.only) {
image(lon.map, lat.map, spdata, zlim=zlim, xlab='', ylab='', col=col, xaxt=xaxt, yaxt=yaxt)
} else {
image.plot(lon.map, lat.map, spdata, zlim=zlim, xlab='', ylab='', axis.args=list(mgp=mgp, tcl=tcl), legend.only=legend.only, horizontal=horizontal, legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel, xaxt=xaxt, yaxt=yaxt)
}
} else {
nbreaks = length(custom.breaks)
nlevel = nbreaks - 1
if (!is.null(type)) {
if (type == 'sign') col = rwb.colors(nlevel) else {
if (is.null(col)) col = tim.colors(nlevel) else if (is.function(col)) col = col(nlevel) else col = colorRampPalette(col)(nlevel)
}
} else {
if (is.null(col)) col = tim.colors(nlevel) else if (is.function(col)) col = col(nlevel) else col = colorRampPalette(col)(nlevel)
}
zval.breaks = 0:nlevel
zval.center = 0:(nlevel - 1) + 0.5
spdata.new = spdata
for (n in 1:nlevel) spdata.new[which(spdata >= custom.breaks[n] & spdata <= custom.breaks[n + 1])] = zval.center[n]
spdata.new[which(spdata < custom.breaks[1])] = zval.center[1]
spdata.new[which(spdata > tail(custom.breaks, 1))] = tail(zval.center, 1)
spdata = spdata.new
zlim = c(0, nlevel)
if (legend.only) image.only = FALSE
if (image.only) {
image(lon.map, lat.map, spdata, zlim=zlim, xlab='', ylab='', col=col, xaxt=xaxt, yaxt=yaxt, breaks=zval.breaks, lab.breaks=custom.breaks)
} else {
image.plot(lon.map, lat.map, spdata, zlim=zlim, xlab='', ylab='', axis.args=list(mgp=mgp, tcl=tcl), legend.only=legend.only, horizontal=horizontal, legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel, xaxt=xaxt, yaxt=yaxt, breaks=zval.breaks, lab.breaks=custom.breaks)
}
}
# Map:
if (Pacific.centric) map('world2', add=TRUE, xlim=map.xlim, ylim=map.ylim) else map('world', add=TRUE, xlim=map.xlim, ylim=map.ylim)
if (!is.null(country)) map(country, add=TRUE, xlim=map.xlim, ylim=map.ylim, lwd=1)
}
###############################################################################
# Site map plot:
plot.site = function(spdata, latlon, xlim=NULL, ylim=NULL, pch=19, type=NULL, zlim=NULL, col=NULL, nlevel=32, mai=c(0.5, 0.4, 0.2, 0.2), mgp=c(1.4, 0.5, 0), tcl=-0.3, ps=12, legend.mar=3, legend.width=1.2, xaxt="n", yaxt="n", Pacific.centric=FALSE, add=FALSE) {
# This function plots a map where individual site measurements are displayed as dots with colors indicating their values.
# Packages "fields" and "maps" must be pre-loaded.
# If there are more than one values for a given site, the mean will be calculated automatically.
# "spdata" is a vector of site measurements; "latlon" is a matrix with the 1st and 2nd columns being the corresponding latitude and longitude, respectively.
# "xlim" and "ylim" are the limits for the plot area; "col" is the vector of colors used to define values of "spdata"; "zlim" is the range of "spdata" values used to break down "col".
# "type" is a vector of intended types of presentation, as explained below.
# Four types of presentation are supported:
# 1. "frac": variable that is a fraction or percentage, good for comparing proportions.
# 2. "abs": variable that has absolute values only, good for comparing magtitudes.
# 3. "def": user-defined scale and z-limits.
# 4. Default: no specification for display.
MAT = na.omit(cbind(spdata, latlon))
spdata = MAT[,1]; latlon = MAT[,2:3]
if (is.null(xlim)) xlim = range(latlon[,2])
if (is.null(ylim)) ylim = range(latlon[,1])
latlon.uniq = unique(latlon)
spdata.uniq = rep(0, times=nrow(latlon.uniq))
col.uniq = rep(0, times=nrow(latlon.uniq))
for (i in 1:length(spdata.uniq)) {
spdata.uniq[i] = mean(spdata[which(latlon[,1] == latlon.uniq[i,1] & latlon[,2] == latlon.uniq[i,2])], na.rm=TRUE)
}
if (is.null(type)) {
zlim = c(min(spdata.uniq, na.rm=TRUE), max(spdata.uniq, na.rm=TRUE))
} else if (type == 'sign') {
if (is.null(zlim)) zlim = c(-max(abs(spdata.uniq)), max(abs(spdata.uniq))) else zlim = zlim
if (is.null(col)) col = rwb.colors(nlevel)
} else if (type == "frac") {
zlim = c(0, 1)
} else if (type == "abs") {
zlim = c(0, max(spdata.uniq, na.rm=TRUE))
} else if (type == "def") {
zlim = zlim
} else {
zlim = c(min(spdata.uniq, na.rm=TRUE), max(spdata.uniq, na.rm=TRUE))
}
if (is.null(col)) col = tim.colors(nlevel)
zbreak = seq(zlim[1], zlim[2], length=(length(col) + 1))
for (i in 1:length(col)) col.uniq[which(spdata.uniq >= zbreak[i] & spdata.uniq <= zbreak[i+1])] = col[i]
if (!add) {
par(mai=mai, mgp=mgp, tcl=tcl, ps=ps)
image.plot(seq(xlim[1], xlim[2], length=10), seq(ylim[1], ylim[2], length=10), matrix(zlim[1]-1, nrow=10, ncol=10), zlim=zlim, xlab="", ylab="", axis.args=list(mgp=c(0,0.5,0), tcl=-0.2), legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel, xaxt=xaxt, yaxt=yaxt)
}
points(latlon.uniq[,2], latlon.uniq[,1], col=col.uniq, pch=pch)
if (!add) {
if (Pacific.centric) map('world2', add=TRUE) else map('world', add=TRUE)
}
}
###############################################################################
# Model-observation comparison for concentrations:
plot.mod.obs.US = function(mod.data, site.data, lon.mod, lat.mod, method="spavg", n=2, dlim=500, xlab='Observed', ylab='Simulated', mai=c(0.4, 0.4, 0.2, 0.2), mgp=c(1.5, 0.5, 0), tcl=-0.25, ps=14, cex=1.4, divide.EW=TRUE) {
# This function plots model results vs. observations for the contiguous U.S.; the regression line and 1-to-1 line are also plotted.
# The plot also gives the R^2 and mean bias (b).
# "mod.data" is a matrix of gridded model results with 1st dimension = "lon.mod" and 2nd dimension = "lat.mod"; "lon.mod" and "lat.mod" are the longitudes and latitudes of model results, both in increasing order.
# "site.data" is an array of observations by site. It has 3 columns: 1st column = observed values; 2nd column = latitude of site; 3rd column = longitude of site.
# "n" and "dlim" are parameters for external function "invdist".
# The rest of parameters are for plotting.
# The package/library "lmodel2" has to be loaded.
library(lmodel2)
if (method == "spavg") {
obs.data = spavg(site.data[,1], site.data[,2:3], rev(lat.mod), lon.mod)
obs.data = obs.data[,length(lat.mod):1]
x.data = as.vector(obs.data)
y.data = as.vector(mod.data)
x.data.E = as.vector(obs.data[which(lon.mod >= -97.5),])
x.data.W = as.vector(obs.data[which(lon.mod < -97.5),])
y.data.E = as.vector(mod.data[which(lon.mod >= -97.5),])
y.data.W = as.vector(mod.data[which(lon.mod < -97.5),])
}
else if (method == "invdist") {
obs.data = invdist(site.data[,1], site.data[,2:3], rev(lat.mod), lon.mod, n=n, dlim=dlim)
obs.data = obs.data[,length(lat.mod):1]
x.data = as.vector(obs.data)
y.data = as.vector(mod.data)
x.data.E = as.vector(obs.data[which(lon.mod >= -97.5),])
x.data.W = as.vector(obs.data[which(lon.mod < -97.5),])
y.data.E = as.vector(mod.data[which(lon.mod >= -97.5),])
y.data.W = as.vector(mod.data[which(lon.mod < -97.5),])
}
else if (method == "match.site") {
mod.match = site.data
for (i in 1:nrow(site.data)) {
lon.lat.mod.ind = find.lon.lat(site.data[i,3], site.data[i,2], lon.mod, rev(lat.mod))
lon.lat.mod.ind[2] = length(lat.mod) - lon.lat.mod.ind[2] + 1
mod.match[i,1] = mod.data[lon.lat.mod.ind[1],lon.lat.mod.ind[2]]
}
x.data = site.data[,1]
y.data = mod.match[,1]
x.data.E = site.data[which(site.data[,3] >= -97.5),1]
x.data.W = site.data[which(site.data[,3] < -97.5),1]
y.data.E = mod.match[which(mod.match[,3] >= -97.5),1]
y.data.W = mod.match[which(mod.match[,3] < -97.5),1]
}
xylim = c(min(c(x.data, y.data), na.rm=TRUE), max(c(x.data, y.data), na.rm=TRUE))
par(mai=mai, mgp=mgp, tcl=tcl, ps=ps)
if (divide.EW) {
plot(x=x.data.E, y=y.data.E, pch=21, col="blue", xlim=xylim, ylim=xylim, xlab=xlab, ylab=ylab)
points(x=x.data.W, y=y.data.W, pch=25, col="red")
reg.E = lmodel2(y.data.E ~ x.data.E)
reg.W = lmodel2(y.data.W ~ x.data.W)
r.sq.E = reg.E$rsquare
r.sq.W = reg.W$rsquare
a.E = reg.E$regression.results[2,2]
a.W = reg.W$regression.results[2,2]
b.E = reg.E$regression.results[2,3]
b.W = reg.W$regression.results[2,3]
abline(a=0, b=1, col="black")
abline(a=a.E, b=b.E, col="blue", lty=2)
abline(a=a.W, b=b.W, col="red", lty=4)
#abline(h=0, lty="dashed", col="gray"); abline(v=0, lty="dashed", col="gray")
text(x=(xylim[1] + 0.000*diff(xylim)), y=(xylim[1] + 1.000*diff(xylim)), labels=expression(R^2), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.080*diff(xylim)), y=(xylim[1] + 0.970*diff(xylim)), labels=paste(' = ', as.character(round(r.sq.E, digits=2)), sep=''), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.050*diff(xylim)), y=(xylim[1] + 0.870*diff(xylim)), labels=paste('b = ', as.character(round(b.E, digits=3)), sep=''), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.560*diff(xylim)), y=(xylim[1] + 0.430*diff(xylim)), labels=expression(R^2), cex=cex, col='red', adj=c(0,1))
text(x=(xylim[1] + 0.640*diff(xylim)), y=(xylim[1] + 0.400*diff(xylim)), labels=paste(' = ', as.character(round(r.sq.W, digits=2)), sep=''), cex=cex, col='red', adj=c(0,1))
text(x=(xylim[1] + 0.610*diff(xylim)), y=(xylim[1] + 0.300*diff(xylim)), labels=paste('b = ', as.character(round(b.W, digits=3)), sep=''), cex=cex, col='red', adj=c(0,1))
LIST = list(eastern.US=reg.E, western.US=reg.W)
} else {
plot(x=x.data, y=y.data, pch=21, col="blue", xlim=xylim, ylim=xylim, xlab=xlab, ylab=ylab)
reg = lmodel2(y.data ~ x.data)
r.sq = reg$rsquare
a = reg$regression.results[2,2]
b = reg$regression.results[2,3]
NMB = sum((y.data - x.data), na.rm=TRUE)/sum(x.data, na.rm=TRUE)
abline(a=0, b=1, col="black")
abline(a=a, b=b, col="blue", lty=2)
#abline(h=0, lty="dashed", col="gray"); abline(v=0, lty="dashed", col="gray")
text(x=(xylim[1] + 0.000*diff(xylim)), y=(xylim[1] + 1.000*diff(xylim)), labels=expression(R^2), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.080*diff(xylim)), y=(xylim[1] + 0.970*diff(xylim)), labels=paste(' = ', as.character(round(r.sq, digits=2)), sep=''), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.050*diff(xylim)), y=(xylim[1] + 0.870*diff(xylim)), labels=paste('b = ', as.character(round(b, digits=3)), sep=''), cex=cex, col='blue', adj=c(0,1))
text(x=(xylim[1] + 0.050*diff(xylim)), y=(xylim[1] + 0.770*diff(xylim)), labels=paste('NMB = ', as.character(round(NMB, digits=3)), sep=''), cex=cex, col='blue', adj=c(0,1))
LIST = list(reg=reg, NMB=NMB)
}
return(LIST)
}
###############################################################################
# Plot vertical profile:
plot.vprof = function(prof, lat, lev, type=NULL, lev.type='pres', same=FALSE, zlim=NULL, xlab='Latitude', ylab=NULL, col=NULL, nlevel=32, mai=c(0.5, 0.5, 0.2, 0.2), mgp=c(1.4, 0.5, 0), tcl=-0.3, ps=12, legend.mar=3, legend.width=1.2) {
# This function plots vertical profile using function "image.plot" from package "fields".
# Packages "fields" and "maps" must be pre-loaded.
# "prof" is a matrix or an array of vertical profile data.
# "lev" can either be pressure levels "pres" or altitudes "alt", specified by value of "lev.type".
# "type" is a vector of intended types of presentation, as explained below.
# Five types of presentation are supported:
# 1. "sign": variable that has both positive and negative values, good for comparing signs of correlations/effects/deviations.
# 2. "frac": variable that is a fraction or percentage, good for comparing proportions.
# 3. "abs": variable that has absolute values only, good for comparing magtitudes.
# 4. "def": user-defined scale and z-limits. (If chosen, must define the same same scale/limits for all plots.)
# 5. Default: no specification for display.
# If you want all plots to have the same type, simply enter a string scalar for "type".
if (lat[length(lat)] < lat[1]) {
# 'lat' is in decreasing order. Need to reverse it to proceed further.
lat = rev(lat)
prof = prof[length(lat):1,]
}
if (lev.type == 'pres') {
if (lev[length(lev)] > lev[1]) {
# 'lev' is pressure levels and is now in increasing order. Need to reverse it to proceed further.
lev = rev(lev)
prof = prof[,length(lev):1]
}
} else {
if (lev[length(lev)] < lev[1]) {
# 'lev' is altitudes and is now in decreasing order. Need to reverse it to proceed further.
lev = rev(lev)
prof = prof[,length(lev):1]
}
}
par(mai=mai, mgp=mgp, tcl=tcl, ps=ps)
if (is.null(type)) {
zlim = c(min(na.omit(as.vector(prof))), max(na.omit(as.vector(prof))))
} else if (type == "sign") {
if (is.null(zlim)) zlim = c(-max(abs(na.omit(as.vector(prof)))), max(abs(na.omit(as.vector(prof))))) else zlim = zlim
if (is.null(col)) col = rwb.colors(32)
} else if (type == "frac") {
zlim = c(0,1)
} else if (type == "abs") {
zlim = c(0, max(na.omit(as.vector(prof))))
} else if (type == "def") {
zlim = zlim
} else {
zlim = c(min(na.omit(as.vector(prof))), max(na.omit(as.vector(prof))))
}
if (is.null(col)) col = tim.colors(32)
if (lev.type == 'pres') {
if (is.null(ylab)) ylab = 'Pressure (hPa)'
image.plot(lat, -lev, prof, zlim=zlim, xlab=xlab, ylab=ylab, axis.args=list(mgp=c(0,0.5,0), tcl=-0.2), legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel)
} else {
if (is.null(ylab)) ylab = 'Altitude (km)'
image.plot(lat, lev, prof, zlim=zlim, xlab=xlab, ylab=ylab, axis.args=list(mgp=c(0,0.5,0), tcl=-0.2), legend.mar=legend.mar, legend.width=legend.width, col=col, nlevel=nlevel)
}
}
###############################################################################
# Convert country-level data to longitude-latitude grid:
CountryData2LonLat = function(in.df, lon, lat, country.code='ISO3', dlon=NULL, dlat=NULL) {