Skip to content

Commit

Permalink
Apply suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
eliascarv committed Oct 23, 2024
1 parent fd02b34 commit dd62e96
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions src/fitting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,18 @@ function fit_impl(
# evaluate weights
w = _weights(algo.weightfun, x, n)

# objective function
function J(θ)
γ = V(ball(θ[1]), sill=θ[2], nugget=θ[3])
sum(i -> w[i] * (γ(x′[i]) - y′[i])^2, eachindex(w, x′, y′))
end

# linear constraint (sill ≥ nugget)
L(θ) = θ[2] θ[3] ? 0.0 : θ[3] - θ[2]

# penalty for linear constraint (J + λL)
λ = sum(yᵢ -> yᵢ^2, y′)

# maximum range, sill and nugget
xmax = maximum(x′)
ymax = maximum(y′)
Expand All @@ -173,7 +182,7 @@ function fit_impl(
u = [rᵤ, sᵤ, nᵤ]

# solve optimization problem
θ, ϵ = _optimize(θ -> V(ball(θ[1]), sill=θ[2], nugget=θ[3]), x′, y′, w, L, l, u, θₒ)
θ, ϵ = _optimize(J, L, λ, l, u, θₒ)

# optimal variogram (with units)
γ = V(ball(θ[1] * ux), sill=θ[2] * uy, nugget=θ[3] * uy)
Expand Down Expand Up @@ -218,11 +227,20 @@ function fit_impl(
# evaluate weights
w = _weights(algo.weightfun, x, n)

# objective function
function J(θ)
γ = V(scaling=θ[1], nugget=θ[2], exponent=θ[3])
sum(i -> w[i] * (γ(x′[i]) - y′[i])^2, eachindex(w, x′, y′))
end

# linear constraints
# 1. scaling ≥ 0
# 2. 0 ≤ exponent ≤ 2
L(θ) = θ[1] 0.0 ? 0.0 : -θ[1] + θ[3] 0.0 ? 0.0 : -θ[3] + 2.0 θ[3] ? 0.0 : θ[3] - 2.0

# penalty for linear constraint (J + λL)
λ = sum(yᵢ -> yᵢ^2, y′)

# maximum scaling, nugget and exponent
ymax = maximum(y′)
smax = isnothing(maxscaling′) ? ymax : maxscaling′
Expand All @@ -244,7 +262,7 @@ function fit_impl(
u = [sᵤ, nᵤ, eᵤ]

# solve optimization problem
θ, ϵ = _optimize(θ -> V(scaling=θ[1], nugget=θ[2], exponent=θ[3]), x′, y′, w, L, l, u, θₒ)
θ, ϵ = _optimize(J, L, λ, l, u, θₒ)

# optimal variogram (with units)
γ = V(scaling=θ[1] * uy, nugget=θ[2] * uy, exponent=θ[3])
Expand All @@ -254,16 +272,7 @@ end

_weights(f, x, n) = isnothing(f) ? n / sum(n) : map(xᵢ -> ustrip(f(xᵢ)), x)

function _optimize(gamma, x, y, w, L, l, u, θₒ)
# objective function
function J(θ)
γ = gamma(θ)
sum(i -> w[i] * (γ(x[i]) - y[i])^2, eachindex(w, x, y))
end

# penalty for linear constraint (J + λL)
λ = sum(yᵢ -> yᵢ^2, y)

function _optimize(J, L, λ, l, u, θₒ)
# solve optimization problem
sol = Optim.optimize-> J(θ) + λ * L(θ), l, u, θₒ)
ϵ = Optim.minimum(sol)
Expand Down

0 comments on commit dd62e96

Please sign in to comment.