forked from dankelley/oce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.R
4168 lines (4015 loc) · 167 KB
/
misc.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
## vim:textwidth=80:expandtab:shiftwidth=4:softtabstop=4
shortenTimeString <- function(t, debug=getOption("oceDebug"))
{
tc <- as.character(t)
oceDebug(debug, "shortenTimeString() {\n", sep="", unindent=1)
oceDebug(debug, "A: '", paste(t, collapse="' '"), "'\n")
tc <- gsub(" [A-Z]{3}$", "", tc) # remove timezone
if (all(grepl("^[0-9]{4}", tc))) { # leading years
years <- substr(tc, 1, 4)
if (1 == length(unique(years))) {
tc <- gsub("^[0-9]{4}", "", tc)
tc <- gsub("^-", "", tc) # works for ISO dates
oceDebug(debug, "B: '", paste(tc, collapse="' '"), "'\n", sep='')
}
} else if (any(grepl("[a-zA-Z]", tc))) {
## Change e.g. 'Jul 01' to 'Jul' if all labels end in 01
if (all(grepl("01\\s*$", tc))) {
tc <- gsub(" 01\\s*$", "", tc)
oceDebug(debug, "B: '", paste(tc, collapse="' '"), "'\n", sep='')
}
}
oceDebug(debug, "C: '", paste(tc, collapse="' '"), "'\n", sep='')
tc <- gsub("^\\s*", "", tc)
tc <- gsub("\\s*$", "", tc)
oceDebug(debug, "D: '", paste(tc, collapse="' '"), "'\n", sep='')
oceDebug(debug, "}\n", unindent=1)
tc
}
#' Get first finite value in a vector or array, or NULL if none
#' @param v A numerical vector or array.
firstFinite <- function(v)
{
if (!is.vector(v))
v <- as.vector(v)
first <- which(is.finite(v))
if (length(first) > 0) v[first[1]] else NULL
}
#' Decode units, from strings
#'
#' @param s A string.
#' @return A \code{\link{list}} of two items: \code{unit} which is an
#' \code{\link{expression}}, and \code{scale}, which is a string.
#' @examples
#' unitFromString("DB") # dbar
#' @family functions that interpret variable names and units from headers
unitFromString <- function(s)
{
## 1. Strings that have been encountered in WOCE secton (.csv) files
## ",,,,,,,,,,,,DBAR,IPTS-68,PSS-78,,PSS-78,,UMOL/KG,,UMOL/KG,,UMOL/KG,,UMOL/KG,,UMOL/KG,"
##> message("unitFromString(", s, ")")
if (s == "DB" || s == "DBAR")
return(list(unit=expression(db), scale=""))
if (s == "ITS-90 DEGC" || s == "ITS-90")
return(list(unit=expression(degree*C), scale="ITS-90"))
if (s == "IPTS-68 DEGC" || s == "IPTS-68")
return(list(unit=expression(degree*C), scale="IPTS-68"))
if (s == "PSS-78")
return(list(unit=expression(), scale="PSS-78"))
if (s == "PSU")
return(list(unit=expression(), scale="PSS-78"))
if (s == "ML/L")
return(list(unit=expression(ml/l), scale=""))
if (s == "UG/L")
return(list(unit=expression(mu*g/l), scale=""))
if (s == "UMOL/KG")
return(list(unit=expression(mu*mol/kg), scale=""))
if (s == "%")
return(list(unit=expression(percent), scale=""))
return(list(unit=as.expression(s), scale=""))
}
## #' Rename a duplicated item (used in reading CTD files)
## #'
## #' Determine a new name for an item that is already in a list of names. This is
## #' done by e.g. appending a \code{2} to the second occurrence of a name, etc.
## #' The purpose is to create distinct variable names for
## #' \code{\link{read.ctd.sbe}}.
## #'
## #' @param existingNames Vector of strings with names already processed.
## #' @param name String with a candidate name.
## #' @return names String with an unduplicated name.
## #' @seealso \code{\link{unduplicateNames}} is similar, but considers
## #' a vector of names.
## #'
## #' @examples
## #' unduplicateName("a", c("a", "b", "a")) # returns "a3"
## unduplicateName <- function(name, existingNames)
## {
## counter <- 0
## for (i in seq_along(existingNames)) {
## if (name == existingNames[i])
## counter <- counter + 1
## }
## res <- if (counter > 0) paste(name, counter+1, sep="") else name
## ## message("unduplicateName() name: '", name, "'")
## ## message(" existingNames '", paste(existingNames, collapse="' '"))
## ## message(" returning '", res, "'")
## res
## }
#' Rename duplicated items (used in reading CTD files)
#'
#' Rename items to avoid name collision, by appending a \code{2} to
#' the second occurrence of a name, etc.
#'
#' @param names Vector of strings with variable names.
#' @return names Vector of strings with numbered variable names.
#' @seealso used by \code{\link{read.ctd.sbe}}.
#'
#' @examples
#' unduplicateNames(c("a", "b", "a", "c", "b"))
unduplicateNames <- function(names)
{
## Handle duplicated names
for (i in seq_along(names)) {
w <- which(names == names[i])
if (1 < length(w)) {
##print(w)
w <- w[-1]
##message("duplicated: ", names[i])
##message("w: ", paste(w, collapse=" "))
##message(paste(names, collapse=" "))
names[w] <- paste(names[i], 1+seq.int(1,length(w)), sep="")
##message(paste(names, collapse=" "))
}
}
names
}
#' Rename items in the data slot of an oce object
#'
#' This function may be used to rename elements within the
#' \code{data} slot of \code{oce} objects. It also updates
#' the processing log of the returned object, indicating
#' the changes.
#'
#' @param x An \code{oce} object, i.e. one inheriting from
#' \code{\link{oce-class}}.
#' @param old Vector of strings, containing old names.
#' @param new Vector of strings, containing old names.
#'
#' @examples
#' data(ctd)
#' new <- renameData(ctd, "temperature", "temperature68")
#' new <- oceSetData(new, name="temperature",
#' value=T90fromT68(new[["temperature68"]]),
#' unit=list(unit=expression(degree*C),scale="ITS=90"))
renameData <- function(x, old=NULL, new=NULL)
{
if (is.null(old)) stop("need to supply old")
if (is.null(new)) stop("need to supply new")
n <- length(old)
if (n != length(new)) stop("lengths of old and new must match")
Old <- names(x@data)
New <- Old
for (i in 1:n) {
w <- which(Old == old[i])
if (length(w) == 0) stop("'", old[i], "' is not in the data slot of x")
if (length(w) > 1) stop("multiple matches are not permitted")
## message("i: ", i, ", old[i]: ", old[i], ", w:", w)
New[w] <- new[i]
}
## ensure unique ... this is a common user error
if (length(New) != length(unique(New))) stop("cannot have two columns of same name")
names(x@data) <- New
x@processingLog <- processingLogAppend(x@processingLog, paste(deparse(match.call()), sep="", collapse=""))
x
}
#' Calculate a rounded bound, rounded up to matissa 1, 2, or 5
#'
#' @param x a single positive number
#' @return for positive x, a value exceeding x that has mantissa 1, 2, or 5; otherwise, x
bound125 <- function(x)
{
x <- x[1] # ignore all but first element
if (x <= 0) {
res <- x
} else {
exp10 <- 10^floor(log10(x))
xx <- x / exp10
m <- if (xx <= 1) 1 else if (xx <=2) 2 else if (xx <= 5) 5 else 10
res <- m * exp10
##> r <- 10^rnorm(1e4)
##> R <- unlist(lapply(1:1e4, function(i) bound125(r[i]))
##> range(r/R)
##> message("x: ", x, ", exp10: ", exp10, ", m: ", m, ", xx: ", xx, ", res: ", res)
}
res
}
#' Put longitude in the range from -180 to 180
#'
#' @param longitude in degrees East, possibly exceeding 180
#' @return longitude in signed degrees East
#' @seealso
#' \code{\link{matrixShiftLongitude}} and \code{\link{shiftLongitude}} are more
#' powerful relatives to \code{standardizeLongitude}.
standardizeLongitude <- function(longitude) ifelse(longitude > 180, longitude-360, longitude)
#' Show an argument to a function, e.g. for debugging
#'
#' @param x the argument
#' @param nshow number of values to show at first (if length(x)> 1)
#' @param last indicates whether this is the final argument to the function
#' @param sep the separator between name and value
argShow <- function(x, nshow=2, last=FALSE, sep="=")
{
if (missing(x))
return("")
name <- paste(substitute(x))
res <- ""
if (missing(x)) {
res <- "(missing)"
} else {
if (is.null(x)) {
res <- NULL
} else {
nx <- length(x)
if (nx > 1)
name <- paste(name, "[", nx, "]", sep="")
if (is.function(x)) {
res <- "(provided)"
} else if (is.character(x) && nx==1) {
res <- paste('"', x[1], '"', sep="")
} else {
look <- 1:min(nshow, nx)
res <- paste(format(x[look], digits=4), collapse=" ")
if (nx > nshow)
res <- paste(res, "...", x[nx])
}
}
}
if (!last)
res <- paste(res, ", ", sep="")
paste(name, res, sep="=")
}
#' Try to associate data names with units, for use by summary()
#'
#' Note that the whole object is not being given as an argument;
#' possibly this will reduce copying and thus storage impact.
#'
#' @param names the names of data within an object
#' @param units the units from metadata
#' @return a vector of strings, with blank entries for data with unknown units
#' @examples
#' library(oce)
#' data(ctd)
#' dataLabel(names(ctd@@data), ctd@@metadata$units)
dataLabel <- function(names, units)
{
res <- names
## message("in dataLabel()")
if (!missing(units)) {
## message(" dataLabel(); next line is names")
## print(names)
## message(" dataLabel(); next line is units")
## print(units)
unitsNames <- names(units)
##message(" dataLabel(); next line is unitsNames")
##print(unitsNames)
for (i in seq_along(names)) {
##message(" i: ", i, ", name: ", names[i])
w <- which(unitsNames == names[i])
if (length(w)) {
##message(" we match a unit at index w=", paste(w, collapse=" "))
u <- units[w]
if (!is.null(u)) {
if (is.character(u)) {
res[i] <- paste(res[i], " [", u, "]", sep="")
} else if (is.list(u)) {
res[i] <- paste(res[i], " [", u$unit[[1]], u$scale, "]", sep="")
}
}
}
}
}
##> message("names:", paste(names, collapse=" | "))
##> message("units:", paste(units, collapse=" | "))
##> message("res:", paste(res, collapse=" | "))
res <- gsub(" *\\[\\]", "", res)
##message("dataLabel() returning:")
##print(res)
res
}
#' Capitalize first letter of each of a vector of words
#'
#' This is used in making labels for data names in some ctd functions
#' @param w vector of character strings
#' @return vector of strings patterned on \code{w} but with first letter
#' in upper case and others in lower case
titleCase <- function(w)
{
unlist(lapply(seq_along(w),
function(i) paste(toupper(substr(w[i], 1, 1)),
tolower(substr(w[i], 2, nchar(w[i]))), sep="")))
}
#' Curl of 2D vector field
#'
#' Calculate the z component of the curl of an x-y vector field.
#'
#' The computed component of the curl is defined by \eqn{\partial }{dv/dx -
#' du/dy}\eqn{ v/\partial x - \partial u/\partial y}{dv/dx - du/dy} and the
#' estimate is made using first-difference approximations to the derivatives.
#' Two methods are provided, selected by the value of \code{method}.
#'
#' \itemize{
#'
#' \item For \code{method=1}, a centred-difference, 5-point stencil is used in
#' the interior of the domain. For example, \eqn{\partial v/\partial x}{dv/dx}
#' is given by the ratio of \eqn{v_{i+1,j}-v_{i-1,j}}{v[i+1,j]-v[i-1,j]} to the
#' x extent of the grid cell at index \eqn{j}{j}. (The cell extents depend on
#' the value of \code{geographical}.) Then, the edges are filled in with
#' nearest-neighbour values. Finally, the corners are filled in with the
#' adjacent value along a diagonal. If \code{geographical=TRUE}, then \code{x}
#' and \code{y} are taken to be longitude and latitude in degrees, and the
#' earth shape is approximated as a sphere with radius 6371km. The resultant
#' \code{x} and \code{y} are identical to the provided values, and the
#' resultant \code{curl} is a matrix with dimension identical to that of
#' \code{u}.
#'
#' \item For \code{method=2}, each interior cell in the grid is considered
#' individually, with derivatives calculated at the cell center. For example,
#' \eqn{\partial v/\partial x}{dv/dx} is given by the ratio of
#' \eqn{0.5*(v_{i+1,j}+v_{i+1,j+1}) -
#' 0.5*(v_{i,j}+v_{i,j+1})}{0.5*(v[i+1,j]+v[i+1,j+1]) - 0.5*(v[i,j]+v[i,j+1])}
#' to the average of the x extent of the grid cell at indices \eqn{j}{j} and
#' \eqn{j+1}{j+1}. (The cell extents depend on the value of
#' \code{geographical}.) The returned \code{x} and \code{y} values are the
#' mid-points of the supplied values. Thus, the returned \code{x} and \code{y}
#' are shorter than the supplied values by 1 item, and the returned \code{curl}
#' matrix dimensions are similarly reduced compared with the dimensions of
#' \code{u} and \code{v}.
#' }
#'
#' @param u matrix containing the 'x' component of a vector field
#' @param v matrix containing the 'y' component of a vector field
#' @param x the x values for the matrices, a vector of length equal to the
#' number of rows in \code{u} and \code{v}.
#' @param y the y values for the matrices, a vector of length equal to the
#' number of cols in \code{u} and \code{v}.
#' @param geographical logical value indicating whether \code{x} and \code{y}
#' are longitude and latitude, in which case spherical trigonometry is used.
#' @param method A number indicating the method to be used to calculate the
#' first-difference approximations to the derivatives. See \dQuote{Details}.
#' @return A list containing vectors \code{x} and \code{y}, along with matrix
#' \code{curl}. See \dQuote{Details} for the lengths and dimensions, for
#' various values of \code{method}.
#' @section Development status.: This function is under active development as
#' of December 2014 and is unlikely to be stabilized until February 2015.
#' @author Dan Kelley and Chantelle Layton
#' @examples
#' library(oce)
#' ## 1. Shear flow with uniform curl.
#' x <- 1:4
#' y <- 1:10
#' u <- outer(x, y, function(x,y) y/2)
#' v <- outer(x, y, function(x,y) -x/2)
#' C <- curl(u, v, x, y, FALSE)
#'
#' ## 2. Rankine vortex: constant curl inside circle, zero outside
#' rankine <- function(x, y)
#' {
#' r <- sqrt(x^2 + y^2)
#' theta <- atan2(y, x)
#' speed <- ifelse(r < 1, 0.5*r, 0.5/r)
#' list(u=-speed*sin(theta), v=speed*cos(theta))
#' }
#' x <- seq(-2, 2, length.out=100)
#' y <- seq(-2, 2, length.out=50)
#' u <- outer(x, y, function(x,y) rankine(x,y)$u)
#' v <- outer(x, y, function(x,y) rankine(x,y)$v)
#' C <- curl(u, v, x, y, FALSE)
#' ## plot results
#' par(mfrow=c(2,2))
#' imagep(x, y, u, zlab="u", asp=1)
#' imagep(x, y, v, zlab="v", asp=1)
#' imagep(x, y, C$curl, zlab="curl", asp=1)
#' hist(C$curl, breaks=100)
#' @family functions relating to vector calculus
curl <- function(u, v, x, y, geographical=FALSE, method=1)
{
if (missing(u)) stop("must supply u")
if (missing(v)) stop("must supply v")
if (missing(x)) stop("must supply x")
if (missing(y)) stop("must supply y")
if (length(x) <= 1) stop("length(x) must exceed 1 but it is ", length(x))
if (length(y) <= 1) stop("length(y) must exceed 1 but it is ", length(y))
if (length(x) != nrow(u)) stop("length(x) must equal nrow(u)")
if (length(y) != ncol(u)) stop("length(x) must equal ncol(u)")
if (nrow(u) != nrow(v)) stop("nrow(u) and nrow(v) must match")
if (ncol(u) != ncol(v)) stop("ncol(u) and ncol(v) must match")
if (!is.logical(geographical)) stop("geographical must be a logical quantity")
method <- as.integer(round(method))
if (1 == method)
res <- .Call("curl1", u, v, x, y, geographical)
else if (2 == method)
res <- .Call("curl2", u, v, x, y, geographical)
else
stop("method must be 1 or 2")
res
}
#' Calculate Range, Extended a Little, as is Done for Axes
#'
#' This is analogous to what is done as part of the R axis range calculation,
#' in the case where \code{xaxs="r"}.
#'
#' @param x a numeric vector.
#' @param extend fraction to extend on either end
#' @return A two-element vector with the extended range of \code{x}.
#' @author Dan Kelley
rangeExtended <- function(x, extend=0.04) # extend by 4% on each end, like axes
{
if (length(x) == 1) {
x * c(1 - extend, 1 + extend)
} else {
r <- range(x, na.rm=TRUE)
d <- diff(r)
c(r[1] - d * extend, r[2] + d * extend)
}
}
#' Apply a function to vector data
#'
#' The function \code{FUN} is applied to \code{f} in bins specified by
#' \code{xbreaks}. (If \code{FUN} is \code{\link{mean}},
#' consider using \code{\link{binMean2D}} instead, since it should be faster.)
#'
#' @param x a vector of numerical values.
#' @param f a vector of data to which the elements of \code{FUN} may be
#' supplied
#' @param xbreaks values of x at the boundaries between bins; calculated using
#' \code{\link{pretty}} if not supplied.
#' @param FUN function to apply to the data
#' @param \dots arguments to pass to the function \code{FUN}
#' @return A list with the following elements: the breaks in x and y
#' (\code{xbreaks} and \code{ybreaks}), the break mid-points (\code{xmids} and
#' \code{ymids}), and a matrix containing the result of applying function
#' \code{FUN} to \code{f} subsetted by these breaks.
#' @author Dan Kelley
#' @examples
#' library(oce)
#' ## salinity profile with median and quartile 1 and 3
#' data(ctd)
#' p <- ctd[["pressure"]]
#' S <- ctd[["salinity"]]
#' q1 <- binApply1D(p, S, pretty(p, 30), function(x) quantile(x, 1/4))
#' q3 <- binApply1D(p, S, pretty(p, 30), function(x) quantile(x, 3/4))
#' plotProfile(ctd, "salinity", col='gray', type='n')
#' polygon(c(q1$result, rev(q3$result)),
#' c(q1$xmids, rev(q1$xmids)), col='gray')
#' points(S, p, pch=20)
#' @family bin-related functions
binApply1D <- function(x, f, xbreaks, FUN, ...)
{
if (missing(x)) stop("must supply 'x'")
if (missing(f)) stop("must supply 'f'")
if (missing(xbreaks)) xbreaks <- pretty(x, 20)
if (missing(FUN)) stop("must supply 'FUN'")
if (!is.function(FUN)) stop("'FUN' must be a function")
## FIXME: maybe employ the code below to get data from oce objects
##if ("data" %in% slotNames(x)) # oce objects have this
## x <- x@data
##t <- try(x <- data.frame(x), silent=TRUE)
##if (class(t) == "try-error")
## stop("cannot coerce 'data' into a data.frame")
fSplit <- split(f, cut(x, xbreaks))
res <- sapply(fSplit, FUN, ...)
names(res) <- NULL
list(xbreaks=xbreaks, xmids=xbreaks[-1]-0.5*diff(xbreaks), result=res)
}
#' Apply a function to matrix data
#'
#' The function \code{FUN} is applied to \code{f} in bins specified by
#' \code{xbreaks} and \code{ybreaks}. (If \code{FUN} is \code{\link{mean}},
#' consider using \code{\link{binMean2D}} instead, since it should be faster.)
#'
#' @param x a vector of numerical values.
#' @param y a vector of numerical values.
#' @param f a vector of data to which the elements of \code{FUN} may be
#' supplied
#' @param xbreaks values of x at the boundaries between bins; calculated using
#' \code{\link{pretty}} if not supplied.
#' @param ybreaks values of y at the boundaries between bins; calculated using
#' \code{\link{pretty}} if not supplied.
#' @param FUN function to apply to the data
#' @param \dots arguments to pass to the function \code{FUN}
#' @return A list with the following elements: the breaks in x and y
#' (\code{xbreaks} and \code{ybreaks}), the break mid-points (\code{xmids} and
#' \code{ymids}), and a matrix containing the result of applying function
#' \code{FUN} to \code{f} subsetted by these breaks.
#' @author Dan Kelley
#' @examples
#' library(oce)
#' \dontrun{
#' ## secchi depths in lat and lon bins
#' if (require(ocedata)) {
#' data(secchi, package="ocedata")
#' col <- rev(oce.colorsJet(100))[rescale(secchi$depth,
#' xlow=0, xhigh=20,
#' rlow=1, rhigh=100)]
#' zlim <- c(0, 20)
#' breaksPalette <- seq(min(zlim), max(zlim), 1)
#' colPalette <- rev(oce.colorsJet(length(breaksPalette)-1))
#' drawPalette(zlim, "Secchi Depth", breaksPalette, colPalette)
#' data(coastlineWorld)
#' mapPlot(coastlineWorld, longitudelim=c(-5,20), latitudelim=c(50,66),
#' grid=5, fill='gray', projection="+proj=lcc +lat_1=50 +lat_2=65")
#' bc <- binApply2D(secchi$longitude, secchi$latitude,
#' pretty(secchi$longitude, 80),
#' pretty(secchi$latitude, 40),
#' f=secchi$depth, FUN=mean)
#' mapImage(bc$xmids, bc$ymids, bc$result, zlim=zlim, col=colPalette)
#' mapPolygon(coastlineWorld, col='gray')
#' }
#' }
#' @family bin-related functions
binApply2D <- function(x, y, f, xbreaks, ybreaks, FUN, ...)
{
if (missing(x)) stop("must supply 'x'")
if (missing(y)) stop("must supply 'y'")
if (missing(f)) stop("must supply 'f'")
nx <- length(x)
if (nx != length(y)) stop("lengths of x and y must agree")
if (missing(xbreaks)) xbreaks <- pretty(x, 20)
if (missing(ybreaks)) ybreaks <- pretty(y, 20)
if (missing(FUN)) stop("must supply 'FUN'")
if (!is.function(FUN)) stop("'FUN' must be a function")
nxbreaks <- length(xbreaks)
if (nxbreaks < 2) stop("must have more than 1 xbreak")
nybreaks <- length(ybreaks)
if (nybreaks < 2) stop("must have more than 1 ybreak")
res <- matrix(nrow=nxbreaks-1, ncol=nybreaks-1)
A <- split(f, cut(y, ybreaks))
B <- split(x, cut(y, ybreaks))
for (i in 1:length(A)) {
fSplit <- split(A[[i]], cut(B[[i]], xbreaks))
##res[,i] <- binApply1D(B[[i]], A[[i]], xbreaks, FUN)$result
res[,i] <- sapply(fSplit, FUN, ...)
}
list(xbreaks=xbreaks, xmids=xbreaks[-1]-0.5*diff(xbreaks),
ybreaks=ybreaks, ymids=ybreaks[-1]-0.5*diff(ybreaks),
result=res)
}
#' Bin-count vector data
#'
#' Count the number of elements of a given vector that fall within
#' successive pairs of values within a second vector.
#'
#' @param x Vector of numerical values.
#' @param xbreaks Vector of values of x at the boundaries between bins, calculated using
#' \code{\link{pretty}} if not supplied.
#' @return A list with the following elements: the breaks (\code{xbreaks},
#' midpoints (\code{xmids}) between those breaks, and
#' the count (\code{number}) of \code{x} values between successive breaks.
#' @author Dan Kelley
#' @family bin-related functions
binCount1D <- function(x, xbreaks)
{
if (missing(x)) stop("must supply 'x'")
##nx <- length(x)
if (missing(xbreaks))
xbreaks <- pretty(x)
nxbreaks <- length(xbreaks)
if (nxbreaks < 2)
stop("must have more than 1 break")
res <- .C("bin_count_1d", length(x), as.double(x),
length(xbreaks), as.double(xbreaks),
number=integer(nxbreaks-1),
result=double(nxbreaks-1),
NAOK=TRUE, PACKAGE="oce")
list(xbreaks=xbreaks,
xmids=xbreaks[-1]-0.5*diff(xbreaks),
number=res$number)
}
#' Bin-average f=f(x)
#'
#' Average the values of a vector \code{f} in bins defined on another
#' vector \code{x}. A common example might be averaging CTD profile
#' data into pressure bins (see \dQuote{Examples}).
#'
#' @param x Vector of numerical values.
#' @param f Vector of numerical values.
#' @param xbreaks Vector of values of x at the boundaries between bins, calculated using
#' \code{\link{pretty}} if not supplied.
#' @return A list with the following elements: the breaks (\code{xbreaks},
#' midpoints (\code{xmids}) between those breaks,
#' the count (\code{number}) of \code{x} values between successive breaks,
#' and the resultant average (\code{result}) of \code{f}, classified by the
#' \code{x} breaks.
#'
#' @examples
#' library(oce)
#' data(ctd)
#' z <- ctd[["z"]]
#' T <- ctd[["temperature"]]
#' plot(T, z)
#' TT <- binMean1D(z, T, seq(-100, 0, 1))
#' lines(TT$result, TT$xmids, col='red')
#'
#' @author Dan Kelley
#' @family bin-related functions
binMean1D <- function(x, f, xbreaks)
{
if (missing(x)) stop("must supply 'x'")
fGiven <- !missing(f)
if (!fGiven)
f <- rep(1, length(x))
nx <- length(x)
if (nx != length(f))
stop("lengths of x and f must agree")
if (missing(xbreaks))
xbreaks <- pretty(x)
nxbreaks <- length(xbreaks)
if (nxbreaks < 2)
stop("must have more than 1 break")
res <- .C("bin_mean_1d", length(x), as.double(x), as.double(f),
length(xbreaks), as.double(xbreaks),
number=integer(nxbreaks-1),
result=double(nxbreaks-1),
NAOK=TRUE, PACKAGE="oce")
list(xbreaks=xbreaks,
xmids=xbreaks[-1]-0.5*diff(xbreaks),
number=res$number,
result=if (fGiven) res$result else rep(NA, length=nx))
}
#' Bin-count matrix data
#'
#' Count the number of elements of a given matrix z=z(x,y) that fall within
#' successive pairs of breaks in x and y.
#'
#' @param x Vector of numerical values.
#' @param y Vector of numerical values.
#' @param xbreaks Vector of values of \code{x} at the boundaries between bins, calculated using
#' \code{\link{pretty}(x)} if not supplied.
#' @param ybreaks Vector of values of \code{y} at the boundaries between bins, calculated using
#' \code{\link{pretty}(y)} if not supplied.
#' @param flatten A logical value indicating whether
#' the return value also contains equilength
#' vectors \code{x}, \code{y}, \code{z} and \code{n}, a flattened
#' representation of \code{xmids}, \code{ymids}, \code{result} and
#' \code{number}.
#' @return A list with the following elements: the breaks (\code{xbreaks}
#' and \code{ybreaks}), the midpoints (\code{xmids} and \code{ymids})
#' between those breaks, and
#' the count (\code{number}) of \code{f} values in the boxes defined
#' between successive breaks.
#' @author Dan Kelley
#' @family bin-related functions
binCount2D <- function(x, y, xbreaks, ybreaks, flatten=FALSE)
{
if (missing(x)) stop("must supply 'x'")
if (missing(y)) stop("must supply 'y'")
if (length(x) != length(y)) stop("lengths of x and y must agree")
if (missing(xbreaks)) xbreaks <- pretty(x)
if (missing(ybreaks)) ybreaks <- pretty(y)
nxbreaks <- length(xbreaks)
if (nxbreaks < 2) stop("must have more than 1 xbreak")
nybreaks <- length(ybreaks)
if (nybreaks < 2) stop("must have more than 1 ybreak")
M <- .C("bin_count_2d", length(x), as.double(x), as.double(y),
length(xbreaks), as.double(xbreaks),
length(ybreaks), as.double(ybreaks),
number=integer((nxbreaks-1)*(nybreaks-1)),
mean=double((nxbreaks-1)*(nybreaks-1)),
NAOK=TRUE, PACKAGE="oce")
res <- list(xbreaks=xbreaks,
ybreaks=ybreaks,
xmids=xbreaks[-1]-0.5*diff(xbreaks),
ymids=ybreaks[-1]-0.5*diff(ybreaks),
number=matrix(M$number, nrow=nxbreaks-1))
if (flatten) {
res2 <- list()
res2$x <- rep(res$xmids, times=nybreaks-1)
res2$y <- rep(res$ymids, each=nxbreaks-1)
res2$n <- as.vector(res$number)
res <- res2
}
res
}
#' Bin-average f=f(x,y)
#'
#' Average the values of a vector \code{f(x,y)} in bins defined on
#' vectors \code{x} and \code{y}. A common example might be averaging
#' spatial data into location bins.
#'
#' @param x Vector of numerical values.
#' @param y Vector of numerical values.
#' @param f Matrix of numerical values, a matrix f=f(x,y).
#' @param xbreaks Vector of values of \code{x} at the boundaries between bins, calculated using
#' \code{\link{pretty}(x)} if not supplied.
#' @param ybreaks Vector of values of \code{y} at the boundaries between bins, calculated using
#' \code{\link{pretty}(y)} if not supplied.
#' @param flatten A logical value indicating whether
#' the return value also contains equilength
#' vectors \code{x}, \code{y}, \code{z} and \code{n}, a flattened
#' representation of \code{xmids}, \code{ymids}, \code{result} and
#' \code{number}.
#' @param fill Logical value indicating whether to fill \code{NA}-value gaps in
#' the matrix. Gaps will be filled as the average of linear interpolations
#' across rows and columns. See \code{fillgap}, which works together with this.
#' @param fillgap Integer controlling the size of gap that can be filled
#' across. If this is negative (as in the default), gaps will be filled
#' regardless of their size. If it is positive, then gaps exceeding this
#' number of indices will not be filled.
#'
#' @return A list with the following elements: the midpoints (renamed as
#' \code{x} and \code{y}), the count (\code{number}) of \code{f(x,y)} values
#' for \code{x} and \code{y} values that lie between corresponding breaks,
#' and the resultant average (\code{f}) of \code{f(x,y)}, classified by the
#' \code{x} and \code{y} breaks.
#'
#' @examples
#' library(oce)
#' x <- runif(500)
#' y <- runif(500)
#' f <- x + y
#' xb <- seq(0, 1, 0.1)
#' yb <- seq(0, 1, 0.2)
#' m <- binMean2D(x, y, f, xb, yb)
#' plot(x, y)
#' contour(m$xmids, m$ymids, m$result, add=TRUE, levels=seq(0, 2, 0.5), labcex=1)
#'
#' @author Dan Kelley
#' @family bin-related functions
binMean2D <- function(x, y, f, xbreaks, ybreaks, flatten=FALSE, fill=FALSE, fillgap=-1)
{
if (missing(x)) stop("must supply 'x'")
if (missing(y)) stop("must supply 'y'")
if (fillgap == 0) stop("cannot have a negative 'fillgap' value")
fGiven <- !missing(f)
if (!fGiven)
f <- rep(1, length(x))
if (length(x) != length(y)) stop("lengths of x and y must agree")
if (length(x) != length(f)) stop("lengths of x and f must agree")
if (missing(xbreaks)) xbreaks <- pretty(x)
if (missing(ybreaks)) ybreaks <- pretty(y)
nxbreaks <- length(xbreaks)
if (nxbreaks < 2) stop("must have more than 1 xbreak")
nybreaks <- length(ybreaks)
if (nybreaks < 2) stop("must have more than 1 ybreak")
M <- .C("bin_mean_2d", length(x), as.double(x), as.double(y), as.double(f),
length(xbreaks), as.double(xbreaks),
length(ybreaks), as.double(ybreaks),
as.integer(fill), as.integer(fillgap),
number=integer((nxbreaks-1)*(nybreaks-1)),
mean=double((nxbreaks-1)*(nybreaks-1)),
NAOK=TRUE, PACKAGE="oce")
res <- list(xbreaks=xbreaks,
ybreaks=ybreaks,
xmids=xbreaks[-1]-0.5*diff(xbreaks),
ymids=ybreaks[-1]-0.5*diff(ybreaks),
number=matrix(M$number, nrow=nxbreaks-1),
result=if (fGiven) matrix(M$mean, nrow=nxbreaks-1) else matrix(NA, ncol=nybreaks-1, nrow=nxbreaks-1))
if (flatten) {
res2 <- list()
res2$x <- rep(res$xmids, times=nybreaks-1)
res2$y <- rep(res$ymids, each=nxbreaks-1)
res2$f <- as.vector(res$result)
res2$n <- as.vector(res$number)
res <- res2
}
res
}
#' Bin-average a vector y, based on x values
#'
#' The \code{y} vector is averaged in bins defined for \code{x}. Missing
#' values in \code{y} are ignored.
#'
#' @param x a vector of numerical values.
#' @param y a vector of numerical values.
#' @param xmin x value at the lower limit of first bin; the minimum \code{x}
#' will be used if this is not provided.
#' @param xmax x value at the upper limit of last bin; the maximum \code{x}
#' will be used if this is not provided.
#' @param xinc width of bins, in terms of x value; 1/10th of \code{xmax-xmin}
#' will be used if this is not provided.
#' @return A list with two elements: \code{x}, the mid-points of the bins, and
#' \code{y}, the average \code{y} value in the bins.
#' @author Dan Kelley
#'
#' @examples
#' library(oce)
#' ## A. fake linear data
#' x <- seq(0, 100, 1)
#' y <- 1 + 2 * x
#' plot(x, y, pch=1)
#' ba <- binAverage(x, y)
#' points(ba$x, ba$y, pch=3, col='red', cex=3)
#'
#' ## B. fake quadratic data
#' y <- 1 + x ^2
#' plot(x, y, pch=1)
#' ba <- binAverage(x, y)
#' points(ba$x, ba$y, pch=3, col='red', cex=3)
#'
#' ## C. natural data
#' data(co2)
#' plot(co2)
#' avg <- binAverage(time(co2), co2, 1950, 2000, 2)
#' points(avg$x, avg$y, col='red')
#' @family bin-related functions
binAverage <- function(x, y, xmin, xmax, xinc)
{
if (missing(y))
stop("must supply 'y'")
if (missing(xmin))
xmin <- min(as.numeric(x), na.rm=TRUE)
if (missing(xmax))
xmax <- max(as.numeric(x), na.rm=TRUE)
if (missing(xinc))
xinc <- (xmax - xmin) / 10
if (xmax <= xmin)
stop("must have xmax > xmin")
if (xinc <= 0)
stop("must have xinc > 0")
xx <- head(seq(xmin, xmax, xinc), -1) + xinc / 2
#cat("xx:", xx, "\n")
nb <- length(xx)
##dyn.load("bin_average.so") # include this whilst debugging
yy <- .C("bin_average", length(x), as.double(x), as.double(y),
as.double(xmin), as.double(xmax), as.double(xinc),
##means=double(nb), NAOK=TRUE)$means
means=double(nb), NAOK=TRUE, PACKAGE="oce")$means # include this whilst debugging
list(x=xx, y=yy)
}
#' Extract (x, y, z) from (x, y, grid)
#'
#' Extract the grid points from a grid, returning columns.
#' This is useful for e.g. gridding large datasets, in which the first step
#' might be to use \code{\link{binMean2D}}, followed by
#' \code{\link{interpBarnes}}.
#'
#' @param x a vector holding the x coordinates of grid.
#' @param y a vector holding the y coordinates of grid.
#' @param grid a matrix holding the grid.
#' @return A list containing three vectors: \code{x}, the grid x values,
#' \code{y}, the grid y values, and \code{grid}, the grid values.
#' @author Dan Kelley
#' @examples
#'
#' library(oce)
#' data(wind)
#' u <- interpBarnes(wind$x, wind$y, wind$z)
#' contour(u$xg, u$yg, u$zg)
#' U <- ungrid(u$xg, u$yg, u$zg)
#' points(U$x, U$y, col=oce.colorsJet(100)[rescale(U$grid, rlow=1, rhigh=100)], pch=20)
ungrid <- function(x, y, grid)
{
nrow <- nrow(grid)
ncol <- ncol(grid)
grid <- as.vector(grid) # by columns
x <- rep(x, times=ncol)
y <- rep(y, each=nrow)
ok <- !is.na(grid)
list(x=x[ok], y=y[ok], grid=grid[ok])
}
#' Trilinear interpolation in a 3D array
#'
#' Interpolate within a 3D array, using the trilinear approximation.
#'
#' Trilinear interpolation is used to interpolate within the \code{f} array,
#' for those (\code{xout}, \code{yout} and \code{zout}) triplets that are
#' inside the region specified by \code{x}, \code{y} and \code{z}. Triplets
#' that lie outside the range of \code{x}, \code{y} or \code{z} result in
#' \code{NA} values.
#'
#' @param x vector of x values for grid (must be equi-spaced)
#' @param y vector of y values for grid (must be equi-spaced)
#' @param z vector of z values for grid (must be equi-spaced)
#' @param f matrix of rank 3, with the gridd values mapping to the \code{x}
#' values (first index of \code{f}), etc.
#' @param xout vector of x values for output.
#' @param yout vector of y values for output (length must match that of
#' \code{xout}).
#' @param zout vector of z values for output (length must match that of
#' \code{xout}).
#' @return A vector of interpolated values (or \code{NA} values), with length
#' matching that of \code{xout}.
#' @author Dan Kelley and Clark Richards
#'
#' @examples
#' ## set up a grid
#' library(oce)
#' n <- 5
#' x <- seq(0, 1, length.out=n)
#' y <- seq(0, 1, length.out=n)
#' z <- seq(0, 1, length.out=n)
#' f <- array(1:n^3, dim=c(length(x), length(y), length(z)))
#' ## interpolate along a diagonal line
#' m <- 100
#' xout <- seq(0, 1, length.out=m)
#' yout <- seq(0, 1, length.out=m)
#' zout <- seq(0, 1, length.out=m)
#' approx <- approx3d(x, y, z, f, xout, yout, zout)
#' ## graph the results
#' plot(xout, approx, type='l')
#' points(xout[1], f[1,1,1])
#' points(xout[m], f[n,n,n])
approx3d <- function(x, y, z, f, xout, yout, zout)
{
equispaced <- function(x) sd(diff(x)) / mean(diff(x)) < 1e-5
if (missing(x)) stop("must provide x")
if (missing(y)) stop("must provide y")
if (missing(z)) stop("must provide z")
if (missing(f)) stop("must provide f")
if (missing(xout)) stop("must provide xout")
if (missing(yout)) stop("must provide yout")
if (missing(zout)) stop("must provide zout")
if (!equispaced(x)) stop("x values must be equi-spaced")
if (!equispaced(y)) stop("y values must be equi-spaced")
if (!equispaced(z)) stop("z values must be equi-spaced")
.Call("approx3d", x, y, z, f, xout, yout, zout)
}
#' Draw error bars on an existing xy diagram
#'
#' @param x x coordinates of points on the existing plot.
#' @param y y coordinates of points on the existing plot.
#' @param xe error on x coordinates of points on the existing plot, either a
#' single number or a vector of length identical to that of \code{y}.
#' @param ye as \code{xe} but for y coordinate.
#' @param percent boolean flag indicating whether \code{xe} and \code{ye} are
#' in terms of percent of the corresponding \code{x} and \code{y} values.
#' @param style indication of the style of error bar. Using \code{style=0}
#' yields simple line segments (drawn with \code{\link{segments}}) and
#' \code{style=1} yields line segments with short perpendicular endcaps.
#' @param length length of endcaps, for \code{style=1} only; it is passed to
#' \code{\link{arrows}}, which is used to draw that style of error bars.
#' @param \dots graphical parameters passed to the code that produces the error
#' bars, e.g. to \code{\link{segments}} for \code{style=0}.
#' @author Dan Kelley
#' @examples
#'
#' library(oce)
#' data(ctd)
#' S <- ctd[["salinity"]]
#' T <- ctd[["temperature"]]
#' plot(S, T)
#' errorbars(S, T, 0.05, 0.5)
errorbars <- function(x, y, xe, ye, percent=FALSE, style=0, length=0.025, ...)
{
if (missing(x))
stop("must supply x")
if (missing(y))
stop("must supply y")
n <- length(x)
if (n != length(y))
stop("x and y must be of same length\n")
if (missing(xe) && missing(ye))
stop("must give either xe or ye")
if (1 == length(xe))
xe <- rep(xe, n) # FIXME probably gives wrong length
if (1 == length(ye))
ye <- rep(ye, n)
if (!missing(xe)) {
if (n != length(xe))
stop("x and xe must be of same length\n")
if (percent)
xe <- xe * x / 100
look <- xe != 0
if (style == 0) {
segments(x[look], y[look], x[look]+xe[look], y[look], ...)
segments(x[look], y[look], x[look]-xe[look], y[look], ...)
} else if (style == 1) {
arrows(x[look], y[look], x[look] + xe[look], y[look], angle=90, length=length, ...)
arrows(x[look], y[look], x[look] - xe[look], y[look], angle=90, length=length, ...)
} else {
stop("unknown value ", style, " of style; must be 0 or 1\n")
}
}