Skip to content

Commit

Permalink
fix pow for negative value
Browse files Browse the repository at this point in the history
  • Loading branch information
kongdd committed Apr 8, 2024
1 parent fa28ad2 commit b6b6e81
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 15 deletions.
Binary file added data/x_ref
Binary file not shown.
2 changes: 1 addition & 1 deletion src/Dist/logLogistic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ end

function cdf_logLogistic(x::Real, params)
β, α, γ = params[1:3]
1 / (1 + ((α / (x - β))^γ))
1 / (1 + (pow/ (x - β), γ)))
end


Expand Down
9 changes: 8 additions & 1 deletion src/SPEI.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ using SpecialFunctions: gamma_inc, lgamma, loggamma


qnorm(p::Real) = quantile(Normal(), p)
pow = ^

export pow
# pow = ^
# import Base:^
pow(x, y) = x^y
function pow(x::T, y::AbstractFloat) where {T<:AbstractFloat}
x < 0 ? T(NaN) : x^y
end


include("PWM.jl")
Expand Down
4 changes: 4 additions & 0 deletions src/main_spei.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
function param_spei(x_ref::AbstractVector)
x2 = x_ref[.!isnan.(x_ref)] |> sort # have to sort
beta = pwm(x2, 0.0, 0.0, 0)
@show beta

params = _fit_logLogistic(beta)
params
end
Expand All @@ -21,6 +23,8 @@ function param_spi(x_ref::AbstractVector; fit="lmom")
params(D), q
end

export param_spei, param_spi


"""
spei(x::AbstractVector)
Expand Down
26 changes: 13 additions & 13 deletions test/test-spei.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,27 @@ using Test
using RCall
using SPEI

R"""
library(SPEI2)
"""

function nanmax(x)
x2 = x[.!isnan.(x)]
maximum(x2)
end

R"""
library(SPEI2)
"""
wb = R"wb" |> rcopy |> x -> Float32.(x)
# wb = R"wb" |> rcopy |> x -> Float32.(x)
wb = deserialize("data/wb")
x, x_ref = deserialize("data/x_ref")

@testset "spei" begin
@time r_R = R"cal_spei(wb)" |> rcopy
@time r_jl = spei(wb)
@time r_R = R"cal_spei($x, $x_ref)$z" |> rcopy
@time r_jl = spei(x, x_ref).z

z_r = r_R[:z]
z_jl = r_jl.z
e = z_r - z_jl
@test maximum(abs.(e)) <= 1e-3
# z_r = r_R[:z]
# z_jl = r_jl.z
e = r_R - r_jl
@test nanmax(e) <= 1e-3
end

@testset "spi" begin
Expand All @@ -33,11 +36,8 @@ end
end

# > 计算结果完全一致

# ## 误差还挺大的
# begin
# using Plots

# plot(z_r, label="R")
# plot!(z_jl, label="Julia")
# plot!(e, label="R - Julia")
Expand Down

0 comments on commit b6b6e81

Please sign in to comment.