# EESC 301, Lab 4: lake morphometry and profile workup in R
# Code from the Lab 4 deck (slides 22 and 29), assembled into one runnable file.
# Method: Wetzel and Likens (2000), Exercise 1. Density: the UNESCO-style
# freshwater equation used on slide 29 (the same form as rLakeAnalyzer::water.density).
# Base R only. Run it as is, then replace the example numbers with your own lake.

## Part 1. Depth-area table to volume, mean depth and the depth-volume curve
bel <- data.frame(z = c(0, 5, 10, 13.5),
                  A = c(1340, 725, 260, 0))     # m, m2
h  <- diff(bel$z)
A1 <- head(bel$A, -1); A2 <- tail(bel$A, -1)
Vs <- h * (A1 + A2 + sqrt(A1 * A2)) / 3         # strata, m3
bel$Vcum <- c(0, cumsum(Vs))
V    <- sum(Vs)                                 # 7753 m3
zbar <- V / bel$A[1]                            # 5.79 m
stopifnot(all(diff(bel$A) < 0), zbar < max(bel$z))
cat(sprintf("Volume %.0f m3, mean depth %.2f m\n", V, zbar))
plot(100 * bel$Vcum / V, bel$z, type = "b", ylim = rev(range(bel$z)),
     xlab = "Cumulative volume (%)", ylab = "Depth (m)")

## Part 2. A temperature profile to density, gradient and thermocline depth
# The five plateau values from the L17 cast (download L17 from the data site).
p <- data.frame(ft = c(25, 50, 75, 100, 125),
                T  = c(22.33, 15.90, 11.18, 8.44, 7.26))  # L17
p$z   <- p$ft * 0.3048                                    # m
p$rho <- 1000 * (1 - (p$T + 288.9414) * (p$T - 3.9863)^2 /
                 (508929.2 * (p$T + 68.12963)))           # kg/m3
g   <- -diff(p$T) / diff(p$z)                             # degC per m
mid <- (head(p$z, -1) + tail(p$z, -1)) / 2
cat(sprintf("Steepest gradient midpoint %.1f m\n", mid[which.max(g)]))  # 11.4 m
stopifnot(all(diff(p$rho) > 0))                           # no inversions
plot(p$T, p$z, type = "b", ylim = c(40, 0),
     xlab = "Temperature (C)", ylab = "Depth (m)")
