diff --git a/Project.toml b/Project.toml index f98d5d8c5..5a6ad7212 100644 --- a/Project.toml +++ b/Project.toml @@ -18,7 +18,7 @@ Artifacts = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" # gs-stalone artifact instea #Ghostscript = "d13cf601-a25a-40c9-b2bf-3622a3344160" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" -SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +#SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" LASzip_jll = "8372b9c3-1e34-5cc3-bfab-1a98e101de11" Leptonica_jll = "6a1430e4-294a-53a5-a485-ec66ef6b843c" diff --git a/src/GMT.jl b/src/GMT.jl index 578471f40..684cbe230 100644 --- a/src/GMT.jl +++ b/src/GMT.jl @@ -1,6 +1,6 @@ module GMT -using Printf, Dates, Statistics, Downloads, SparseArrays +using Printf, Dates, Statistics, Downloads using Tables: Tables using PrecompileTools using LinearAlgebra diff --git a/src/extras/whittaker.jl b/src/extras/whittaker.jl index ac5b59766..2bd9a469a 100644 --- a/src/extras/whittaker.jl +++ b/src/extras/whittaker.jl @@ -61,17 +61,7 @@ end # ------------------------------------------------------------------------------------ function whittaker(x::AbstractVecOrMat{<:Real}, y::AbstractVecOrMat{<:Real}, lambda::Real, d::Int=2; weights=nothing, checkedNaN::Bool=false) y, gotNaN, indNaN, weights = helper_whits(y, weights, checkedNaN) # Check NaNs and take measures if yes - m = length(y) - D = ddmat(x, d) - if (weights === nothing) - E = sparse(I*one(eltype(y)), m, m) - C = cholesky(E + lambda * D' * D) - z = C \ (C' \ y) - else - W = spdiagm(m, m, 0 => weights) - C = cholesky(W + lambda * D' * D) - z = C \ (C' \ (weights .*y)) - end + z = whit_solve(ddmat(x, d), y, lambda, weights) (gotNaN) && (y[indNaN] .= NaN) return z end @@ -85,18 +75,7 @@ end # plot!(D[:,1], z1, lc=:red, lt=1, plot=(data=[D[:,1] z2], lc=:blue, lt=1), title="NMR spectrum and optimal smooth", show=1) function whittaker(y::AbstractVecOrMat{<:Real}, lambda, d=2; weights=nothing, checkedNaN::Bool=false) y, gotNaN, indNaN, weights = helper_whits(y, weights, checkedNaN) # Check NaNs and take measures if yes - m = length(y); - E = sparse(I*one(eltype(y)), m, m) - D = diff(E, dims=1); - for k = 2:d D = diff(D, dims=1) end - if (weights === nothing) - C = cholesky(E + lambda * D' * D) - z = C \ (C' \ y) - else - W = spdiagm(m, m, 0 => weights) - C = cholesky(W + lambda * D' * D); - z = C \ (C' \ (weights .* y)); - end + z = whit_solve(ddmat(nothing, d, length(y)), y, lambda, weights) (gotNaN) && (y[indNaN] .= NaN) return z end @@ -114,22 +93,73 @@ function helper_whits(y, weights, checkedNaN) end # ------------------------------------------------------------------------------------ -function ddmat(x, d) +function ddmat(x, d, m=length(x)) # Compute divided differencing matrix of order d - # x: vector of sampling positions + # x: vector of sampling positions, or `nothing` for plain (unit spacing, unscaled) differences # d: order of diffferences + # m: number of points (only needed when `x === nothing`) # Output - # D: the matrix; D * Y gives divided differences of order d + # Dc: the (m-d) x (d+1) band of the (m-d) x m matrix D, Dc[i,k] = D[i,i+k-1]; + # D * Y gives divided differences of order d # - # Paul Eilers, 2003 - - m = length(x) - if (d == 0) - D = sparse(I*one(eltype(x)), m, m) - else - dx = x[(d + 1):m] - x[1:(m - d)] - V = spdiagm(m - d, m - d, 0 => 1 ./ dx) - D = V * diff(ddmat(x, d - 1), dims=1) + # Paul Eilers, 2003. Band storage instead of a sparse matrix. + + Dc = ones(Float64, m, 1) # Order 0: the identity + for k = 1:d + n = m - k + Dn = zeros(Float64, n, k + 1) + for i = 1:n, j = 1:k+1 + Dn[i,j] = (j > 1 ? Dc[i+1,j-1] : 0.0) - (j <= k ? Dc[i,j] : 0.0) # diff(D, dims=1) + end + if (x !== nothing) # V = diag(1 ./ dx) * diff(D) + for i = 1:n Dn[i,:] ./= (x[i+k] - x[i]) end + end + Dc = Dn + end + return Dc +end + +# ------------------------------------------------------------------------------------ +""" +Solve (W + lambda * D'D) z = W*y, where D is given by its band `Dc` (see `ddmat`) and W = diag(weights) +(the identity when `weights === nothing`). The system matrix is symmetric positive definite and banded +with half-bandwidth d, so a banded Cholesky does it in O(m*d^2) with no sparse-matrix machinery. +""" +function whit_solve(Dc::Matrix{Float64}, y, lambda::Real, weights) + m = length(y) + d = size(Dc, 2) - 1 + (m > d) || error("whittaker: need more than $d points for differences of order $d") + B = zeros(Float64, d + 1, m) # Lower band: B[k+1, i] = A[i+k, i] + for r = 1:size(Dc, 1), a = 0:d, b = 0:a # A = lambda * D'D + B[a-b+1, r+b] += lambda * Dc[r,a+1] * Dc[r,b+1] + end + rhs = Vector{Float64}(undef, m) + for i = 1:m + w = (weights === nothing) ? 1.0 : Float64(weights[i]) + B[1,i] += w # A += W + rhs[i] = w * y[i] + end + + for j = 1:m # In-place banded Cholesky, A = L*L'. L[i,j] = B[i-j+1, j] + s = B[1,j] + for k = max(1, j-d):j-1 s -= B[j-k+1,k]^2 end + (s > 0) || error("whittaker: system is not positive definite (too few non-zero weights?)") + B[1,j] = sqrt(s) + for i = j+1:min(m, j+d) + s = B[i-j+1,j] + for k = max(1, i-d):j-1 s -= B[i-k+1,k] * B[j-k+1,k] end + B[i-j+1,j] = s / B[1,j] + end + end + for i = 1:m # Forward: L u = rhs + s = rhs[i] + for k = max(1, i-d):i-1 s -= B[i-k+1,k] * rhs[k] end + rhs[i] = s / B[1,i] + end + for i = m:-1:1 # Backward: L' z = u + s = rhs[i] + for k = i+1:min(m, i+d) s -= B[k-i+1,i] * rhs[k] end + rhs[i] = s / B[1,i] end - return D + return rhs end diff --git a/src/t_xtide.jl b/src/t_xtide.jl index c4ea27307..60d4e7d5a 100644 --- a/src/t_xtide.jl +++ b/src/t_xtide.jl @@ -3,7 +3,7 @@ # Original: R. Pawlowicz 1/Dec/2001, Version 1.0 # Requires the xtide harmonics file - see https://flaterco.com/xtide/files.html -using Dates, SparseArrays +using Dates # ======================================================================================== """ @@ -18,8 +18,8 @@ Structure holding the per-station harmonic data read from an XTide harmonics fil - `latitude::Vector{Float64}`: Station latitudes - `timezone::Vector{Float64}`: UTC offset (hours) - `datum::Vector{Float64}`: Datum level -- `A::SparseMatrixCSC{Float64}`: Amplitudes (nsta x ncon) -- `kappa::SparseMatrixCSC{Float64}`: Phases (nsta x ncon) +- `A::Matrix{Float64}`: Amplitudes (nsta x ncon) +- `kappa::Matrix{Float64}`: Phases (nsta x ncon) """ struct XTideHarmonics station::Vector{String} @@ -28,8 +28,8 @@ struct XTideHarmonics latitude::Vector{Float64} timezone::Vector{Float64} datum::Vector{Float64} - A::SparseMatrixCSC{Float64,Int} - kappa::SparseMatrixCSC{Float64,Int} + A::Matrix{Float64} + kappa::Matrix{Float64} end # ======================================================================================== @@ -327,7 +327,7 @@ function read_xtidefile(io::IO) xtide = XTideConstituents(con_names, speed, startyear, equilibarg, nodefactor) xharm = XTideHarmonics(stations, units_vec, longitudes, latitudes, timezones, datums, - sparse(A_dense), sparse(K_dense)) + A_dense, K_dense) return xtide, xharm end @@ -337,13 +337,16 @@ _mat_charrow(row) = String(strip(String(Char.(row)))) # One MATLAB v7.3 (HDF5) sparse double matrix, stored under `HDF5:"fname"://group` as three # sibling datasets (`ir` = 0-based row indices, `jc` = CSC column pointers, `data` = nonzero -# values). MATLAB serializes sparse matrices column-sorted already, so this maps straight onto -# `SparseMatrixCSC`'s own (1-based) `colptr`/`rowval`/`nzval` layout with no re-sort needed. +# values), expanded into a dense matrix. `jc[j]+1 : jc[j+1]` are column j's entries (CSC layout). function _mat_sparse(fname::String, group::String, nrows::Int, ncols::Int) ir = vec(gdalread("HDF5:\"$fname\"://$group/ir")) jc = vec(gdalread("HDF5:\"$fname\"://$group/jc")) dat = vec(gdalread("HDF5:\"$fname\"://$group/data")) - return SparseMatrixCSC(nrows, ncols, Int.(jc) .+ 1, Int.(ir) .+ 1, Float64.(dat)) + M = zeros(Float64, nrows, ncols) + for j = 1:ncols, n = Int(jc[j])+1:Int(jc[j+1]) + M[Int(ir[n])+1, j] = dat[n] + end + return M end # ======================================================================================== @@ -456,8 +459,8 @@ function xtide_predict(xtide::XTideConstituents, xharm::XTideHarmonics, ista::In ncon = length(xtide.speed) nf = xtide.nodefactor[:, iyr] ea = xtide.equilibarg[:, iyr] - Ai = Vector(xharm.A[ista, :]) - ki = Vector(xharm.kappa[ista, :]) + Ai = xharm.A[ista, :] + ki = xharm.kappa[ista, :] pred = fill(xharm.datum[ista], lt) deg2rad = π / 180 diff --git a/test/test_whittaker.jl b/test/test_whittaker.jl index 2eb156a1e..098f40c76 100644 --- a/test/test_whittaker.jl +++ b/test/test_whittaker.jl @@ -8,4 +8,7 @@ whittaker(D, 2e4, 2); t = 2001:0.003:2007; _v = 5*cospi.((t .- 2000)/2); v = _v + (5*rand(length(t)) .- 2.5); v[2002.6 .< t .< 2003.4] .= NaN; whittaker(t, v, 0.01); + # z must solve (I + lambda*D'D) z = y once (d = 1), not twice + y = sin.(0:0.1:20) .+ 0.3*cos.(0:7.3:1460); z = whittaker(copy(y), 50.0, 1); r = diff(z); + @test maximum(abs.(z .+ 50.0 .* [-r[1]; -diff(r); r[end]] .- y)) < 1e-8 end