forked from dankelley/oce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.R
2314 lines (2249 loc) · 103 KB
/
sw.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
#' @title Convert from ITS-90 to IPTS-68 temperature
#'
#' @template temperatureConversionTemplate
#' @param temperature Vector of temperatures expressed in the ITS-90 scale.
#' @return Temperature expressed in the IPTS-68 scale.
T68fromT90 <- function(temperature) temperature * 1.00024
#' @title Convert from IPTS-68 to ITS-90 temperature
#'
#' @template temperatureConversionTemplate
#' @param temperature Vector of temperatures expressed in the IPTS-68 scale.
#' @return temperature Temperature expressed in the ITS-90 scale.
T90fromT68 <- function(temperature) temperature / 1.00024
#' @title Convert from ITS-48 to ITS-90 temperature
#'
#' @template temperatureConversionTemplate
#' @param temperature Vector of temperatures expressed in the ITS-48 scale.
#' @return Temperature expressed in the ITS-90 scale.
T90fromT48 <- function(temperature) (temperature-4.4e-6*temperature * (100-temperature))/1.00024
#' Look Within the First Element of a List for Replacement Values
#'
#' @details
#' This is a helper function used by various seawater functions. It is used for a
#' call like \code{\link{swRho}(ctd)}, in which the first argument, which is
#' normally \code{salinity} may be an object that contains salinity plus
#' the other items that \code{\link{swRho}} expects to see as arguments. This
#' shorthand is very helpful in calls to the suite of \code{sw} functions. If
#' this first argument is an object of this sort, then the other arguments
#' are ignored \emph{except} for two special cases:
#' \itemize{
#' \item an item named \code{eos} is copied directly from \code{list}
#' \item if the object stores \code{temperature} defined with the IPTS-68
#' scale, then \code{\link{T90fromT68}} is used to convert to the ITS-90 scale,
#' because this is what is expected in most seawater functions. (For example,
#' the RMS difference between these temperature variants is 0.002C for the
#' \code{\link{ctd}} dataset.)
#' }
#'
#' @param list A list of elements, typically arguments that will be used in sw functions.
#' @return A list with elements of the same names but possibly filled in from the first element.
lookWithin <- function(list)
{
n <- length(list)
names <- names(list)
## str(list)
list1 <- list[[1]]
if (inherits(list[[1]], "oce")) {
for (i in 1:n) {
##message("names[", i, "]: ", names[i])
if ("eos" != names[i]) {
## Note: the accessor [[]] will return temperature
## in ITS-90 regardless of how it is stored, and similarly pressure
## in dbar and salinity in FIXME: what unit to use??
try({
list[[i]] <- list1[[names[i], "nowarn"]]
}, silent=TRUE)
}
}
if (inherits(list1, "ctd")) {
nrows <- length(list[[names[1]]])
if (length(list[["longitude"]]))
list[["longitude"]] <- rep(mean(list[["longitude"]], na.rm=TRUE), nrows)
if (length(list[["latitude"]]))
list[["latitude"]] <- rep(mean(list[["latitude"]], na.rm=TRUE), nrows)
}
## FIXME: should special-case some other object types
}
if ("eos" %in% names)
list[["eos"]] <- match.arg(list[["eos"]], c("unesco", "gsw"))
list
}
#' Density ratio
#'
#' Compute density ratio
#'
#' This computes Rrho (density ratio) from a \code{ctd} object.
#'
#' If \code{eos="unesco"}, this is done by calculating salinity and
#' potential-temperature derivatives from smoothing splines whose properties
#' are governed by \code{smoothingLength} or \code{df}. If
#' \code{sense="diffusive"} the definition is
#' \eqn{(beta*dS/dz)/(alpha*d(theta)/dz)}{(beta*dS/dz)/(alpha*d(theta)/dz)} and
#' the reciprocal for \code{"finger"}.
#'
#' If \code{eos="gsw"}, this is done by extracting absolute salinity and
#' conservative temperature, smoothing with a smoothing spline as in the
#' \code{"unesco"} case, and then calling \code{\link[gsw]{gsw_Turner_Rsubrho}}
#' on these smoothed fields. Since the gsw function works on mid-point
#' pressures, \code{\link{approx}} is used to interpolate back to the original
#' pressures.
#'
#' If the default arguments are acceptable, \code{ctd[["Rrho"]]} may be used
#' instead of \code{swRrho(ctd)}.
#'
#' @param ctd an object of class \code{ctd}
#' @param sense an indication of the sense of double diffusion under study and
#' therefore of the definition of Rrho; see \sQuote{Details}
#' @param smoothingLength ignored if \code{df} supplied, but otherwise the
#' latter is calculated as the number of data points, divided by the number
#' within a depth interval of \code{smoothingLength} metres.
#' @param df if given, this is provided to \code{\link{smooth.spline}}.
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Density ratio defined in either the \code{"diffusive"} or
#' \code{"finger"} sense.
#' @author Dan Kelley and Chantelle Layton
#' @examples
#' library(oce)
#' data(ctd)
#' u <- swRrho(ctd, eos="unesco")
#' g <- swRrho(ctd, eos="gsw")
#' p <- ctd[["p"]]
#' plot(u, p, ylim=rev(range(p)), type='l', xlab=expression(R[rho]))
#' lines(g, p, lty=2, col='red')
#' legend("topright", lty=1:2, legend=c("unesco", "gsw"), col=c("black", "red"))
#'
#' @family functions that calculate seawater properties
swRrho <- function(ctd, sense=c("diffusive", "finger"), smoothingLength=10, df,
eos=getOption("oceEOS", default="gsw"))
{
if (!inherits(ctd, "ctd"))
stop("first argument must be of class \"ctd\"")
sense <- match.arg(sense)
eos <- match.arg(eos, c("unesco", "gsw"))
p <- ctd[['pressure']]
n <- length(p)
if (n < 4)
return(rep(NA, length.out=n))
A <- smoothingLength / mean(diff(p), na.rm=TRUE)
if (missing(df))
df <- n / A
if (eos == "unesco") {
salinity <- ctd[['salinity']]
temperature <- ctd[['temperature']]
theta <- ctd[['theta']]
ok <- !is.na(p) & !is.na(salinity) & !is.na(temperature)
## infer d(theta)/dp and d(salinity)/dp from smoothing splines
temperatureSpline <- smooth.spline(p[ok], temperature[ok], df=df)
salinitySpline <- smooth.spline(p[ok], salinity[ok], df=df)
## Smooth temperature and salinity to get smoothed alpha and beta
CTD <- as.ctd(predict(salinitySpline, p)$y, predict(temperatureSpline, p)$y, p)
alpha <- swAlpha(CTD, eos="unesco")
beta <- swBeta(CTD, eos="unesco")
## Using alpha ... is that right, since we have theta?
thetaSpline <- smooth.spline(p[ok], theta[ok], df=df)
dthetadp <- predict(thetaSpline, p, deriv=1)$y
dsalinitydp <- predict(salinitySpline, p, deriv=1)$y
Rrho <- if (sense == "diffusive") (beta * dsalinitydp)/ (alpha * dthetadp) else
(alpha * dthetadp) / (beta * dsalinitydp)
} else if (eos == "gsw") {
SA <- ctd[["SA"]]
CT <- ctd[["CT"]]
ok <- !is.na(p) & !is.na(SA) & !is.na(CT)
SA <- predict(smooth.spline(p[ok], SA[ok], df=df), p)$y
CT <- predict(smooth.spline(p[ok], CT[ok], df=df), p)$y
a <- gsw::gsw_Turner_Rsubrho(SA, CT, p)
Rrho <- a$Rsubrho
Rrho[Rrho==9e15] <- NA
Rrho <- approx(a$p_mid, Rrho, p, rule=2)$y
if (sense == "diffusive")
Rrho <- 1 / Rrho
}
Rrho
}
#' Squared buoyancy frequency for seawater
#'
#' Compute \eqn{N^2}{N^2}, the square of the buoyancy frequency for a seawater
#' profile.
#'
#' Smoothing is often useful prior to computing buoyancy frequency, and so this
#' may optionally be done with \code{\link{smooth.spline}}, unless
#' \code{df=NA}, in which case raw data are used. If \code{df} is not
#' provided, a possibly reasonable value computed from an analysis of the
#' profile, based on the number of pressure levels.
#'
#' If \code{eos="gsw"}, then the first argument must be a \code{ctd} object,
#' and processing is done with \code{\link[gsw]{gsw_Nsquared}}, based on
#' extracted values of Absolute Salinity and Conservative Temperature (possibly
#' smoothed, depending on \code{df}).
#'
#' If \code{eos="unesco"}, then the processing is as follows. The core of the
#' method involves differentiating potential density (referenced to median
#' pressure) with respect to pressure, and the \code{derivs} argument is used
#' to control how this is done, as follows.
#'
#' \itemize{
#'
#' \item if \code{derivs} is not supplied, the action is as though it were
#' given as the string \code{"smoothing"}
#'
#' \item if \code{derivs} equals \code{"simple"}, then the derivative of
#' density with respect to pressure is calculated as the ratio of first-order
#' derivatives of density and pressure, each calculated using
#' \code{\link{diff}}. (A zero is appended at the top level.)
#'
#' \item if \code{derivs} equals \code{"smoothing"}, then the processing
#' depends on the number of data in the profile, and on whether \code{df} is
#' given as an optional argument. When the number of points exceeds 4, and
#' when \code{df} exceeds 1, \code{\link{smooth.spline}} is used to calculate
#' smoothing spline representation the variation of density as a function of
#' pressure, and derivatives are extracted from the spline using
#' \code{predict}. Otherwise, density is smoothed using \code{\link{smooth}},
#' and derivatives are calculated as with the \code{"simple"} method.
#'
#' \item if \code{derivs} is a function taking two arguments (first pressure,
#' then density) then that function is called directly to calculate the
#' derivative, and no smoothing is done before or after that call. }
#'
#' For deep-sea work, the \code{eos="gsw"} option is the best scheme, because
#' it uses derivatives of density computed with \emph{local} reference
#' pressure.
#'
#' For precise work, it makes sense to skip \code{swN2} entirely, choosing
#' whether, what, and how to smooth based on an understanding of fundamental
#' principles as well as data practicalities.
#'
#' @param pressure either pressure [dbar] (in which case \code{sigmaTheta} must
#' be provided) \strong{or} an object of class \code{ctd} object (in which case
#' \code{sigmaTheta} is inferred from the object.
#' @param sigmaTheta Surface-referenced potential density minus 1000
#' [kg/m\eqn{^3}{^3}]
#' @param derivs optional argument to control how the derivative
#' \eqn{d\sigma_\theta/dp}{d(sigmaTheta)/d(pressure)} is calculated. This may
#' be a character string or a function of two arguments. See \dQuote{Details}.
#' @param df argument passed to \code{\link{smooth.spline}} if this function is
#' used for smoothing; set to \code{NA} to prevent smoothing.
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @param \dots additional argument, passed to \code{\link{smooth.spline}}, in
#' the case that \code{derivs="smoothing"}. See \dQuote{Details}.
#' @return Square of buoyancy frequency [\eqn{radian^2/s^2}{radian^2/s^2}].
#' @author Dan Kelley
#' @examples
#'
#' library(oce)
#' data(ctd)
#' # Illustrate difference between UNESCO and GSW
#' p <- ctd[["pressure"]]
#' ylim <- rev(range(p))
#' par(mfrow=c(1,3), mar=c(3, 3, 1, 1), mgp=c(2, 0.7, 0))
#' plot(ctd[["sigmaTheta"]], p, ylim=ylim, type='l', xlab=expression(sigma[theta]))
#' N2u <- swN2(ctd, eos="unesco")
#' N2g <- swN2(ctd, eos="gsw")
#' plot(N2u, p, ylim=ylim, xlab="N2 Unesco", ylab="p", type="l")
#' d <- 100 * (N2u - N2g) / N2g
#' plot(d, p, ylim=ylim, xlab="N2 UNESCO-GSW diff. [%]", ylab="p", type="l")
#' abline(v=0)
#' @family functions that calculate seawater properties
swN2 <- function(pressure, sigmaTheta=NULL, derivs, df,
eos=getOption("oceEOS", default="gsw"), ...)
{
##cat("swN2(..., df=", df, ")\n",sep="")
eos <- match.arg(eos, c("unesco", "gsw"))
##useSmoothing <- !missing(df) && is.finite(df)
if (eos == "unesco") {
if (inherits(pressure, "ctd")) {
pref <- median(pressure[["pressure"]], na.rm=TRUE)
sigmaTheta <- swSigmaTheta(pressure, referencePressure=pref)
pressure <- pressure[['pressure']] # over-writes pressure
}
if (missing(derivs))
derivs <- "smoothing"
ok <- !is.na(pressure) & !is.na(sigmaTheta)
if (is.character(derivs)) {
if (derivs == "simple") {
sigmaThetaDeriv <- c(0, diff(sigmaTheta) / diff(pressure))
} else if (derivs == "smoothing") {
depths <- sum(!is.na(pressure))
if (missing(df)) {
df <- if (depths > 100) f <- floor(depths / 10) # at least 10
else if (depths > 20) f <- floor(depths / 3) # at least 7
else if (depths > 10) f <- floor(depths / 2) # at least 5
else depths
oceDebug(getOption("oceDebug"), "df not supplied, so set to ", df, "(note: #depths=", depths, ")\n")
}
if (depths > 4 && df > 5) {
sigmaThetaSmooth <- smooth.spline(pressure[ok], sigmaTheta[ok], df=df)
sigmaThetaDeriv <- rep(NA, length(pressure))
sigmaThetaDeriv[ok] <- predict(sigmaThetaSmooth, pressure[ok], deriv = 1)$y
} else {
sigmaThetaSmooth <- as.numeric(smooth(sigmaTheta[ok]))
sigmaThetaDeriv <- rep(NA, length(pressure))
sigmaThetaDeriv[ok] <- c(0, diff(sigmaThetaSmooth) / diff(pressure[ok]))
}
} else {
stop("derivs must be 'simple', 'smoothing', or a function")
}
} else {
if (!is.function(derivs))
stop("derivs must be 'smoothing', 'simple', or a function")
sigmaThetaDeriv <- derivs(pressure, sigmaTheta)
}
## FIXME (DK 2016-05-04) I am not sure I like the following since it
## uses a standardized rho_0. But it's from some official source I think.
## Must check this. (UNESCO book?)
res <- ifelse(ok, 9.8 * 9.8 * 1e-4 * sigmaThetaDeriv, NA)
} else if (eos == "gsw") {
if (!inherits(pressure, "ctd"))
stop("first argument must be a CTD object if eos=\"gsw\"")
ctd <- pressure
SA <- ctd[["SA"]]
CT <- ctd[["CT"]]
p <- ctd[["pressure"]]
##np <- length(p)
ok <- !is.na(p) & !is.na(SA) & !is.na(CT)
if (missing(df))
df <- round(sum(ok) / 10)
df <- max(df, 2) # smooth.spline won't work if df<2
df <- min(df, sum(ok))
if (sum(ok) > 4 && is.finite(df)) {
SA <- predict(smooth.spline(p[ok], SA[ok], df=df), p[ok])$y
CT <- predict(smooth.spline(p[ok], CT[ok], df=df), p[ok])$y
}
latitude <- ctd[["latitude"]]
if (is.na(latitude[1]))
latitude <- 0
l <- gsw::gsw_Nsquared(SA=SA, CT=CT, p=p, latitude=latitude[1])
## approx back to the given pressures
ok <- is.finite(l$p_mid) & is.finite(l$N2)
x <- l$p_mid[ok]
y <- l$N2[ok]
res <- approx(x, y, p, rule=2)$y
}
res
}
#' Water pressure
#'
#' Compute seawater pressure from depth by inverting \code{\link{swDepth}}
#' using \code{\link{uniroot}}.
#'
#' If \code{eos="unesco"} this is done by numerical inversion of
#' \code{\link{swDepth}} is done using \code{\link{uniroot}}. If
#' \code{eos="gsw"}, it is done using \code{\link[gsw]{gsw_p_from_z}} in the
#' \code{gsw} package.
#'
#' @param depth distance below the surface in metres.
#' @param latitude Latitude in \eqn{^\circ}{deg}N or radians north of the
#' equator.
#' @param eos indication of formulation to be used, either \code{"unesco"} or
#' \code{"gsw"}.
#' @return Pressure in dbar.
#' @author Dan Kelley
#' @references Unesco 1983. Algorithms for computation of fundamental
#' properties of seawater, 1983. \emph{Unesco Tech. Pap. in Mar. Sci.}, No. 44,
#' 53 pp.
#' @examples
#' swPressure(9712.653, 30, eos="unesco") # 10000
#' swPressure(9712.653, 30, eos="gsw") # 9998.863
#'
#' @family functions that calculate seawater properties
swPressure <- function(depth, latitude=45, eos=getOption("oceEOS", default="gsw"))
{
if (missing(depth))
stop("must supply depth")
## FIXME-gsw add gsw version
ndepth <- length(depth)
if (length(latitude) < ndepth)
latitude <- rep(latitude, ndepth)
res <- vector("numeric", ndepth)
eos <- match.arg(eos, c("unesco", "gsw"))
## Takes 3.55s for 15225 points
if (eos == "unesco") {
for (i in 1:ndepth) {
## FIXME: this loop is slow and should be done in C, like swCStp()
res[i] <- if (depth[i] == 0) 0 else
uniroot(function(p) depth[i] - swDepth(p, latitude[i], eos), interval=depth[i]*c(0.9, 1.1))$root
}
} else if (eos == "gsw") {
res <- gsw::gsw_p_from_z(-depth, latitude)
} else {
stop("eos must be 'unesco' or 'gsw'")
}
res
}
#' Electrical conductivity ratio from salinity, temperature and pressure
#'
#' Compute electrical conductivity ratio based on salinity, temperature, and
#' pressure (relative to the conductivity of seawater with salinity=35,
#' temperature68=15, and pressure=0).
#'
#' If \code{eos="unesco"}, the calculation is done by a bisection root search
#' on the UNESCO formula relating salinity to conductivity, temperature, and
#' pressure (see \code{\link{swSCTp}}). If it is \code{"gsw"} then the
#' Gibbs-SeaWater formulation is used, via \code{\link{gsw_C_from_SP}}.
#'
#' @param salinity practical salinity, or a CTD object (in which case its
#' temperature and pressure are used, and the next two arguments are ignored)
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
#' on the ITS-90 scale; see the examples, as well as the
#' \dQuote{Temperature units} section in the documentation for \code{\link{swRho}}.
#' @param pressure pressure [dbar]
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Conductivity ratio [unitless], i.e. the ratio of conductivity to the
#' conductivity at salinity=35, temperature=15 (IPTS-68 scale) and pressure=0,
#' which has numerical value 42.9140 mS/cm = 4.29140 S/m (see
#' Culkin and Smith, 1980, in the regression result cited at the bottom of
#' the left-hand column on page 23).
#' @author Dan Kelley
#' @seealso For thermal (as opposed to electrical) conductivity, see
#' \code{\link{swThermalConductivity}}. For computation of salinity from
#' electrical conductivity, see \code{\link{swSCTp}}.
#' @references
#' 1. Fofonoff, P. and R. C. Millard Jr, 1983. Algorithms for
#' computation of fundamental properties of seawater. \emph{Unesco Technical
#' Papers in Marine Science}, \bold{44}, 53 pp.
#'
#' 2. Culkin, F., and Norman D. Smith, 1980. Determination of the concentration of
#' potassium chloride solution having the same electrical conductivity, at 15 C
#' and infinite frequency, as standard seawater of salinity 35.0000 ppt
#' (Chlorinity 19.37394 ppt). \emph{IEEE Journal of Oceanic Engineering},
#' \bold{5}, pp 22-23.
#' @examples
#' expect_equal(1, swCSTp(35, T90fromT68(15), 0, eos="unesco")) # by definition of cond. ratio
#' expect_equal(1, swCSTp(34.25045, T90fromT68(15), 2000, eos="unesco"), tolerance=1e-7)
#' expect_equal(1, swCSTp(34.25045, T90fromT68(15), 2000, eos="gsw"), tolerance=1e-7)
#'
#' @family functions that calculate seawater properties
swCSTp <- function(salinity, temperature=15, pressure=0,
eos=getOption("oceEOS", default="gsw"))
{
if (missing(salinity))
stop("must provide salinity")
if (inherits(salinity, "oce")) {
ctd <- salinity
salinity <- ctd[["salinity"]]
temperature <- ctd[["temperature"]]
pressure <- ctd[["pressure"]]
}
dim <- dim(salinity)
salinity <- as.vector(salinity)
temperature <- as.vector(temperature)
pressure <- as.vector(pressure)
n <- length(salinity)
if (length(temperature) != n)
temperature <- rep(temperature, length.out=n)
if (length(pressure) != n)
pressure <- rep(pressure, length.out=n)
eos <- match.arg(eos, c("unesco", "gsw"))
if (eos == "unesco") {
## cat("S= ", paste(salinity, collapse=" "), "\n")
## cat("T= ", paste(temperature, collapse=" "), "\n")
## cat("p= ", paste(pressure, collapse=" "), "\n")
res <- .C("sw_CSTp",
as.integer(n), as.double(salinity), as.double(T68fromT90(temperature)), as.double(pressure),
C=double(n), NAOK=TRUE, PACKAGE="oce")$C
} else {
## for the use of a constant, as opposed to a function call with (35,15,0), see
## https://github.com/dankelley/oce/issues/746
res <- gsw::gsw_C_from_SP(SP=salinity, t=temperature, p=pressure) / 42.9140
}
dim(res) <- dim
res
}
#' Salinity from electrical conductivity, temperature and pressure
#'
#' Compute salinity based on electrical conductivity, temperature, and
#' pressure.
#'
#' Calculate salinity from what is actually measured by a CTD, \emph{i.e.}
#' conductivity, \emph{in-situ} temperature and pressure. Often this is done
#' by the CTD processing software, but sometimes it is helpful to do this
#' directly, \emph{e.g.} when there is a concern about mismatches in sensor
#' response times. If \code{eos="unesco"} then salinity is calculated using
#' the UNESCO algorithm described by Fofonoff and Millard (1983); if it is
#' \code{"gsw"} then the Gibbs-SeaWater formulation is used, via
#' \code{\link{gsw_SP_from_C}}.
#'
#' @param conductivity a measure of conductivity (see also \code{conductivityUnit})
#' or an \code{oce} object holding hydrographic information. In the second case,
#' all the other arguments to \code{swSCTp} are ignored.
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
#' on the ITS-90 scale; see \dQuote{Temperature units} in the documentation for
#' \code{\link{swRho}}.
#' @param pressure pressure [dbar]
#' @param conductivityUnit string indicating the unit used for conductivity.
#' This may be \code{"ratio"} or \code{""} (meaning conductivity ratio),
#' \code{"mS/cm"} or \code{"S/m"}. Note that the ratio mode assumes that
#' measured conductivity has been divided by the standard conductivity
#' of 4.2914 S/m.
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Practical salinity.
#' @author Dan Kelley
#' @seealso For thermal (as opposed to electrical) conductivity, see
#' \code{\link{swThermalConductivity}}. For computation of electrical
#' conductivity from salinity, see \code{\link{swCSTp}}.
#' @references Fofonoff, P. and R. C. Millard Jr, 1983. Algorithms for
#' computation of fundamental properties of seawater. \emph{Unesco Technical
#' Papers in Marine Science}, \bold{44}, 53 pp
#' @examples
#' swSCTp(1, T90fromT68(15), 0, eos="unesco") # 35
#' swSCTp(1, T90fromT68(15), 0, eos="gsw") # 35
#'
#' @family functions that calculate seawater properties
swSCTp <- function(conductivity, temperature=NULL, pressure=NULL,
conductivityUnit, eos=getOption("oceEOS", default="gsw"))
{
C0 <- 42.9140 # Culkin and Smith (1980)
## FIXME-gsw add gsw version
if (missing(conductivity))
stop("must supply conductivity (which may be S or a CTD object)")
if (missing(conductivityUnit)) {
conductivityUnit <- ""
} else {
if (is.list(conductivityUnit) && "unit" %in% names(conductivityUnit))
conductivityUnit <- conductivityUnit$unit
if (is.expression(conductivityUnit))
conductivityUnit <- as.character(conductivityUnit)
if (conductivityUnit == "ratio")
conductivityUnit <- ""
}
if (conductivityUnit != "" && conductivityUnit != "mS/cm" && conductivityUnit != "S/m")
stop("conductivity unit must be \"\", \"mS/cm\", or \"S/m\"")
if (inherits(conductivity, "oce")) {
if (inherits(conductivity, "rsk")) {
ctd <- as.ctd(conductivity)
} else {
ctd <- conductivity
}
## cat("< ", paste(names(ctd@data), collapse=" "), " >\n", sep="")
conductivity <- ctd[["conductivity"]]
if (is.null(conductivity))
stop("this CTD object has no conductivity")
## Use unit from within the object, but may be overridden after this block.
tmp <- ctd[["conductivityUnit"]]
if (is.list(tmp) && "unit" %in% names(tmp))
conductivityUnit <- as.character(tmp$unit)
temperature <- ctd[["temperature"]]
pressure <- ctd[["pressure"]]
}
if (is.list(conductivityUnit)) {
conductivityUnit <- as.character(conductivityUnit$unit)
}
if (!length(conductivityUnit))
conductivityUnit <- ""
if (conductivityUnit == "mS/cm")
conductivity <- conductivity / C0
else if (conductivityUnit == "S/m")
conductivity <- conductivity / (C0 / 10)
else
conductivity <- conductivity
## Now, "conductivity" is in ratio form
dim <- dim(conductivity)
nC <- length(conductivity)
nT <- length(temperature)
if (nC != nT)
stop("lengths of conductivity and temperature must agree, but they are ", nC, " and ", nT)
if (is.null(pressure))
pressure <- rep(0, nC)
np <- length(pressure)
if (nC != np)
stop("lengths of conductivity and pressure must agree, but they are ", nC, " and ", np)
if (eos == "unesco") {
##> message("swSCTp() unesco; conductivity[1]=", conductivity[1], ", temperature[1]=", temperature[1], ", pressure[1]=", pressure[1])
res <- .C("sw_salinity",
as.integer(nC),
as.double(conductivity),
as.double(T68fromT90(temperature)), # original formula is in IPTS-68 but we now use ITS-90
as.double(pressure),
value = double(nC),
NAOK=TRUE, PACKAGE = "oce")$value
} else if (eos == "gsw") {
## we don't need to convert to IPTS-68 for the gsw formulation, because it is already formulated
## to work with ITS-90
##> message("swSCTp() gsw; conductivity[1]=", conductivity[1], ", temperature[1]=", temperature[1], ", pressure[1]=", pressure[1])
res <- gsw::gsw_SP_from_C(C0 * conductivity, temperature, pressure)
}
dim(res) <- dim
res
}
#' Seawater salinity from temperature and density
#'
#' Compute Practical or Absolute Salinity, given in-situ or Conservative
#' Temperature, density, and pressure. This is mainly used to draw isopycnal
#' lines on TS diagrams, hence the dual meanings for salinity and temperature,
#' depending on the value of \code{eos}.
#'
#' For \code{eos="unesco"}, finds the practical salinity that yields the given
#' density, with the given in-situ temperature and pressure. The method is a
#' bisection search with a salinity tolerance of 0.001. For \code{eos="gsw"},
#' the function \code{\link[gsw]{gsw_SA_from_rho}} in the \code{gsw}
#' package is used
#' to infer Absolute Salinity from Conservative Temperature.
#'
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
#' on the ITS-90 scale; see \dQuote{Temperature units} in the documentation for
#' \code{\link{swRho}}.
#' @param density \emph{in-situ} density or sigma value [\eqn{kg/m^3}{kg/m^3}]
#' @param pressure \emph{in-situ} pressure [dbar]
#' @param eos equation of state, either \code{"unesco"} [1,2] or \code{"gsw"}
#' [3,4].
#' @return Practical Salinity, if \code{eos="unesco"}, or Absolute Salinity, if
#' \code{eos="gsw"}.
#' @author Dan Kelley
#' @seealso \code{\link{swTSrho}}
#' @references
#'
#' 1. Fofonoff, P. and R. C. Millard Jr, 1983. Algorithms for computation of
#' fundamental properties of seawater. \emph{Unesco Technical Papers in Marine
#' Science}, \bold{44}, 53 pp
#'
#' 2. Gill, A.E., 1982. \emph{Atmosphere-ocean Dynamics}, Academic Press, New
#' York, 662 pp.
#'
#' 3. IOC, SCOR, and IAPSO (2010). The international thermodynamic equation of
#' seawater-2010: Calculation and use of thermodynamic properties. Technical
#' Report 56, Intergovernmental Oceanographic Commission, Manuals and Guide.
#'
#' 4. McDougall, T.J. and P.M. Barker, 2011: Getting started with TEOS-10 and
#' the Gibbs Seawater (GSW) Oceanographic Toolbox, 28pp., SCOR/IAPSO WG127,
#' ISBN 978-0-646-55621-5.
#' @examples
#' swSTrho(10, 22, 0, eos="gsw") # 28.76285
#' swSTrho(10, 22, 0, eos="unesco") # 28.651625
#'
#' @family functions that calculate seawater properties
swSTrho <- function(temperature, density, pressure, eos=getOption("oceEOS", default="gsw"))
{
## FIXME-gsw add gsw version
eos <- match.arg(eos, c("unesco", "gsw"))
teos <- eos == "gsw" # FIXME still the best way?
dim <- dim(temperature)
nt <- length(temperature)
nrho <- length(density)
np <- length(pressure)
if (nrho == 1) density <- rep(density, nt)
if (np == 1) pressure <- rep(pressure, nt)
if (nt == 1) temperature <- rep(temperature, nt)
sigma <- ifelse(density > 500, density - 1000, density)
if (eos == "unesco") {
res <- .C("sw_strho",
as.integer(nt),
as.double(T68fromT90(temperature)),
as.double(sigma),
as.double(pressure),
as.integer(teos),
S=double(nt),
NAOK=TRUE, PACKAGE="oce")$S
##NAOK=TRUE)$S # permits dyn.load() on changing .so
} else if (eos == "gsw") {
density <- ifelse(density < 900, density + 1000, density)
res <- gsw::gsw_SA_from_rho(density, temperature, pressure) ## assumes temperature=CT
}
dim(res) <- dim
res
}
#' Seawater temperature from salinity and density
#'
#' Compute \emph{in-situ} temperature, given salinity, density, and pressure.
#'
#' Finds the temperature that yields the given density, with the given salinity
#' and pressure. The method is a bisection search with temperature tolerance
#' 0.001 \eqn{^\circ C}{degC}.
#'
#' @param salinity \emph{in-situ} salinity [PSU]
#' @param density \emph{in-situ} density or sigma value [kg/m\eqn{^3}{^3}]
#' @param pressure \emph{in-situ} pressure [dbar]
#' @param eos equation of state to be used, either \code{"unesco"} or
#' \code{"gsw"} (ignored at present).
#' @return \emph{In-situ} temperature [\eqn{^\circ C}{degC}] in the ITS-90
#' scale.
#' @author Dan Kelley
#' @seealso \code{\link{swSTrho}}
#' @references Fofonoff, P. and R. C. Millard Jr, 1983. Algorithms for
#' computation of fundamental properties of seawater. \emph{Unesco Technical
#' Papers in Marine Science}, \bold{44}, 53 pp
#'
#' Gill, A.E., 1982. \emph{Atmosphere-ocean Dynamics}, Academic Press, New
#' York, 662 pp.
#' @examples
#' swTSrho(35, 23, 0, eos="unesco") # 26.11301
#'
#' @family functions that calculate seawater properties
swTSrho <- function(salinity, density, pressure=NULL, eos=getOption("oceEOS", default="gsw"))
{
## FIXME-gsw add gsw version
if (missing(salinity))
stop("must provide salinity")
eos <- match.arg(eos, c("unesco", "gsw"))
teos <- eos == "gsw"
dim <- dim(salinity)
nS <- length(salinity)
nrho <- length(density)
if (is.null(pressure))
pressure <- rep(0, nS)
if (length(pressure) == 1)
pressure <- rep(pressure[1], length.out=nS)
np <- length(pressure)
if (nS != nrho)
stop("lengths of salinity and rho must agree, but they are ", nS, " and ", nrho, ", respectively")
if (nS != np)
stop("lengths of salinity and pressure must agree, but they are ", nS, " and ", np, ", respectively")
for (i in 1:nS) {
## FIXME: avoid loops
sig <- density[i]
if (sig > 500) {
sig <- sig - 1000
}
## FIXME: is this right for all equations of state? I doubt it
this.T <- .C("sw_tsrho",
as.double(salinity[i]),
as.double(sig),
as.double(pressure[i]),
as.integer(teos),
temperature = double(1),
NAOK=TRUE, PACKAGE = "oce")$t
this.T <- T90fromT68(this.T)
if (i == 1) res <- this.T else res <- c(res, this.T)
}
dim(res) <- dim
res
}
#' Seawater freezing temperature
#'
#' Compute freezing temperature of seawater.
#'
#' In the first form, the argument is a \code{ctd} object, from which the
#' salinity and pressure values are extracted and used to for the calculation.
#'
#' @param salinity either salinity [PSU] or a \code{ctd} object from which
#' salinity will be inferred.
#' @param pressure seawater pressure [dbar]
#' @param longitude longitude of observation (only used if \code{eos="gsw"};
#' see \sQuote{Details}).
#' @param latitude latitude of observation (only used if \code{eos="gsw"}; see
#' \sQuote{Details}).
#' @param saturation_fraction saturation fraction of dissolved air in seawater
#' (used only if \code{eos="gsw"}).
#' @param eos equation of state, either \code{"unesco"} [1,2] or \code{"gsw"}
#' [3,4].
#' @return Temperature [\eqn{^\circ}{deg}C], defined on the ITS-90 scale.
#' @author Dan Kelley
#' @references [1] Fofonoff, P. and R. C. Millard Jr, 1983. Algorithms for
#' computation of fundamental properties of seawater. \emph{Unesco Technical
#' Papers in Marine Science}, \bold{44}, 53 pp
#'
#' [2] Gill, A.E., 1982. \emph{Atmosphere-ocean Dynamics}, Academic Press, New
#' York, 662 pp.
#'
#' [3] IOC, SCOR, and IAPSO (2010). The international thermodynamic equation of
#' seawater-2010: Calculation and use of thermodynamic properties. Technical
#' Report 56, Intergovernmental Oceanographic Commission, Manuals and Guide.
#'
#' [4] McDougall, T.J. and P.M. Barker, 2011: Getting started with TEOS-10 and
#' the Gibbs Seawater (GSW) Oceanographic Toolbox, 28pp., SCOR/IAPSO WG127,
#' ISBN 978-0-646-55621-5.
#' @examples
#' swTFreeze(salinity=40, pressure=500, eos="unesco") # -2.588567 degC
#'
#' @family functions that calculate seawater properties
swTFreeze <- function(salinity, pressure=0,
longitude=NULL, latitude=NULL, saturation_fraction=1,
eos=getOption("oceEOS", default="gsw"))
{
if (missing(salinity))
stop("must supply salinity (which may be S or a CTD object)")
if (eos == "gsw") {
if (inherits(salinity, "oce")) {
if (is.null(longitude))
longitude <- salinity[["longitude"]]
if (is.null(latitude))
latitude <- salinity[["latitude"]]
}
if (is.null(longitude))
stop("must supply longitude")
if (is.null(latitude))
stop("must supply latitude")
l <- lookWithin(list(salinity=salinity, pressure=pressure, longitude=longitude, latitude=latitude))
} else {
l <- lookWithin(list(salinity=salinity, pressure=pressure))
}
Smatrix <- is.matrix(l$salinity)
dim <- dim(l$salinity)
if (eos == "unesco") {
res <- (-.0575+1.710523e-3*sqrt(abs(l$salinity))-2.154996e-4*l$salinity)*l$salinity-7.53e-4*l$pressure
res <- T90fromT68(res)
} else if (eos == "gsw") {
SA <- gsw::gsw_SA_from_SP(SP=l$salinity, p=l$pressure, longitude=l$longitude, latitude=l$latitude)
res <- gsw::gsw_t_freezing(SA=SA, p=0, saturation_fraction=saturation_fraction)
}
if (Smatrix) dim(res) <- dim
res
}
#' Seawater thermal expansion coefficient
#'
#' Compute \eqn{\alpha}{alpha}, the thermal expansion coefficient for seawater.
#'
#' @param salinity either practical salinity (in which case \code{temperature}
#' and \code{pressure} must be provided) \strong{or} an \code{oce} object (in
#' which case \code{salinity}, etc. are inferred from the object).
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
#' on the ITS-90 scale; see \dQuote{Temperature units} in the documentation for
#' \code{\link{swRho}}.
#' @param pressure pressure [dbar]
#' @param longitude longitude of observation (only used if \code{eos="gsw"};
#' see \sQuote{Details}).
#' @param latitude latitude of observation (only used if \code{eos="gsw"}; see
#' \sQuote{Details}).
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Value in 1/degC.
#' @author Dan Kelley
#' @references The \code{eos="unesco"} formulae are based on the UNESCO
#' equation of state, but are formulated empirically by Trevor J. McDougall,
#' 1987, Neutral Surfaces, Journal of Physical Oceanography, volume 17, pages
#' 1950-1964. The \code{eos="gsw"} formulae come from GSW; see references in
#' the \code{\link{swRho}} documentation.
#' @family functions that calculate seawater properties
swAlpha <- function(salinity, temperature=NULL, pressure=0,
longitude=NULL, latitude=NULL, eos=getOption("oceEOS", default="gsw"))
{
if (missing(salinity))
stop("must provide salinity")
if (eos == "gsw") {
if (inherits(salinity, "oce")) {
if (is.null(longitude))
longitude <- salinity[["longitude"]]
if (is.null(latitude))
latitude <- salinity[["latitude"]]
}
if (is.null(longitude))
stop("must supply longitude")
if (is.null(latitude))
stop("must supply latitude")
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure,
longitude=longitude, latitude=latitude, eos=eos))
} else {
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure, eos=eos))
}
nS <- length(l$salinity)
nt <- length(l$temperature)
if (nS != nt) stop("lengths of salinity and temperature must agree, but they are ", nS, " and ", nt, ", respectively")
if (length(l$pressure) == 1) l$pressure <- rep(l$pressure, length.out=nS)
np <- length(l$pressure)
if (nS != np) stop("lengths of salinity and pressure must agree, but they are ", nS, " and ", np, ", respectively")
if (l$eos == "unesco") {
res <- swAlphaOverBeta(l$salinity, l$temperature, l$pressure, eos="unesco") * swBeta(l$salinity, l$temperature, l$pressure, eos="unesco")
} else if (l$eos == "gsw") {
SA <- gsw::gsw_SA_from_SP(SP=l$salinity, p=l$pressure, longitude=l$longitude, latitude=l$latitude)
CT <- gsw::gsw_CT_from_t(SA=SA, t=l$temperature, p=l$pressure)
res <- gsw::gsw_alpha(SA=SA, CT=CT, p=l$pressure)
}
res
}
#' Ratio of seawater thermal expansion coefficient to haline contraction
#' coefficient
#'
#' Compute \eqn{\alpha/\beta}{alpha/beta} using McDougall's (1987) algorithm.
#'
#' @param salinity either practical salinity (in which case \code{temperature}
#' and \code{pressure} must be provided) \strong{or} an \code{oce} object (in
#' which case \code{salinity}, etc. are inferred from the object).
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C]
#' @param pressure pressure [dbar]
#' @param longitude longitude of observation (only used if \code{eos="gsw"};
#' see \sQuote{Details}).
#' @param latitude latitude of observation (only used if \code{eos="gsw"}; see
#' \sQuote{Details}).
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Value in psu/\eqn{^\circ}{deg}C.
#' @author Dan Kelley
#' @references The \code{eos="unesco"} formulae are based on the UNESCO
#' equation of state, but are formulated empirically by Trevor J. McDougall,
#' 1987, Neutral Surfaces, Journal of Physical Oceanography, volume 17, pages
#' 1950-1964. The \code{eos="gsw"} formulae come from GSW; see references in
#' the \code{\link{swRho}} documentation.
#' @examples
#' swAlphaOverBeta(40, 10, 4000, eos="unesco") # 0.3476
#'
#' @family functions that calculate seawater properties
swAlphaOverBeta <- function(salinity, temperature=NULL, pressure=NULL,
longitude=NULL, latitude=NULL, eos=getOption("oceEOS", default="gsw"))
{
if (missing(salinity))
stop("must provide salinity")
if (eos == "gsw") {
if (inherits(salinity, "oce")) {
temperature <- salinity[["temperature"]]
pressure <- salinity[["temperature"]]
if (is.null(longitude))
longitude <- salinity[["longitude"]]
if (is.null(latitude))
latitude <- salinity[["latitude"]]
}
if (is.null(longitude))
stop("must supply longitude")
if (is.null(latitude))
stop("must supply latitude")
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure,
longitude=longitude, latitude=latitude, eos=eos))
} else {
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure, eos=eos))
}
Smatrix <- is.matrix(l$salinity)
dim <- dim(l$salinity)
if (is.null(l$temperature))
stop("must provide temperature")
nS <- length(l$salinity)
nt <- length(l$temperature)
if (nS != nt) stop("lengths of salinity and temperature must agree, but they are ", nS, " and ", nt, ", respectively")
if (is.null(l$pressure)) pressure <- 0
if (length(l$pressure) != nS) l$pressure <- rep(l$pressure, length.out=nS)
if (l$eos == "gsw") {
## not likely to be called since gsw has a direct function for alpha, but put this here anyway
SA <- gsw::gsw_SA_from_SP(SP=l$salinity, p=l$pressure, longitude=l$longitude, latitude=l$latitude)
CT <- gsw::gsw_CT_from_t(SA=SA, t=l$temperature, p=l$pressure)
res <- gsw::gsw_alpha_on_beta(SA=SA, CT=CT, p=l$pressure)
} else if (l$eos == "unesco") {
theta <- swTheta(l$salinity, l$temperature, l$pressure, eos="unesco")
res <- .C("sw_alpha_over_beta", as.integer(nS),
as.double(l$salinity), as.double(theta), as.double(l$pressure),
value = double(nS), NAOK=TRUE, PACKAGE = "oce")$value
}
if (Smatrix) dim(res) <- dim
res
}
#' Seawater haline contraction coefficient
#'
#' Compute \eqn{\beta}{beta}, the haline contraction coefficient for seawater.
#'
#' @param salinity either practical salinity (in which case \code{temperature}
#' and \code{pressure} must be provided) \strong{or} an \code{oce} object (in
#' which case \code{salinity}, etc. are inferred from the object).
#' @param temperature \emph{in-situ} temperature [\eqn{^\circ}{deg}C], defined
#' on the ITS-90 scale; see \dQuote{Temperature units} in the documentation for
#' \code{\link{swRho}}.
#' @param pressure seawater pressure [dbar]
#' @param longitude longitude of observation (only used if \code{eos="gsw"};
#' see \sQuote{Details}).
#' @param latitude latitude of observation (only used if \code{eos="gsw"}; see
#' \sQuote{Details}).
#' @param eos equation of state, either \code{"unesco"} or \code{"gsw"}.
#' @return Value in 1/psu.
#' @author Dan Kelley
#' @references The \code{eos="unesco"} formulae are based on the UNESCO
#' equation of state, but are formulaed empirically by Trevor J. McDougall,
#' 1987, Neutral Surfaces, Journal of Physical Oceanography, volume 17, pages
#' 1950-1964. The \code{eos="gsw"} formulae come from GSW; see references in
#' the \code{\link{swRho}} documentation.
#' @family functions that calculate seawater properties
swBeta <- function(salinity, temperature=NULL, pressure=0,
longitude=NULL, latitude=NULL, eos=getOption("oceEOS", default="gsw"))
{
if (missing(salinity))
stop("must provide salinity")
if (inherits(salinity, "oce")) {
temperature <- salinity[["temperature"]]
pressure <- salinity[["temperature"]]
if (is.null(longitude))
longitude <- salinity[["longitude"]]
if (is.null(latitude))
latitude <- salinity[["latitude"]]
}
if (eos == "gsw") {
if (is.null(longitude))
stop("must supply longitude")
if (is.null(latitude))
stop("must supply latitude")
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure,
longitude=longitude, latitude=latitude, eos=eos))
} else {
l <- lookWithin(list(salinity=salinity, temperature=temperature, pressure=pressure, eos=eos))
}
Smatrix <- is.matrix(l$salinity)
dim <- dim(l$salinity)
nS <- length(l$salinity)
nt <- length(l$temperature)
if (nS != nt) stop("lengths of salinity and temperature must agree, but they are ", nS, " and ", nt, ", respectively")
if (length(l$pressure) == 1) l$pressure <- rep(l$pressure, length.out=nS)
np <- length(l$pressure)
if (nS != np) stop("lengths of salinity and pressure must agree, but they are ", nS, " and ", np, ", respectively")
if (eos == "gsw") {
SA <- gsw::gsw_SA_from_SP(SP=l$salinity, p=l$pressure, longitude=l$longitude, latitude=l$latitude)
CT <- gsw::gsw_CT_from_t(SA=SA, t=l$temperature, p=l$pressure)
res <- gsw::gsw_beta(SA=SA, CT=CT, p=l$pressure)
} else if (eos == "unesco") {
theta <- swTheta(l$salinity, l$temperature, l$pressure, eos="unesco") # the formula is i.t.o. theta
res <- .C("sw_beta", as.integer(nS),
as.double(l$salinity), as.double(theta), as.double(l$pressure),
value = double(nS), NAOK=TRUE, PACKAGE = "oce")$value