Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/MortalityTable.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""
UltimateMortality(vector; start_age=0)

Given a vector of rates, returns an `OffsetArray` that is indexed by attained age.
Given a vector of rates, returns an `OffsetArray` that is indexed by attained age.

Any `AbstractVector` is accepted (a `Vector`, a range, a `view`, or a vector containing `missing`); the input is wrapped without copying.

Give the optional keyword argument to start the indexing at an age other than zero.

Expand All @@ -19,8 +21,10 @@ julia> m[18]

```
"""
function UltimateMortality(v::Array{<:Real,1}; start_age = 0)
return OffsetArray(v, start_age - 1)
function UltimateMortality(v::AbstractVector; start_age = 0)
# the offset is relative to `v`'s own axes, which need not start at 1 (a view, or a vector
# that is already indexed by age)
return OffsetArray(v, start_age - firstindex(v))
end

"""
Expand Down Expand Up @@ -327,5 +331,7 @@ Equivalent to doing:
using OffsetArrays
OffsetArray(vec,start_age-1)
```

This is an alias for [`UltimateMortality`](@ref).
"""
mortality_vector(vec; start_age = 0) = return OffsetArray(vec, start_age - 1)
mortality_vector(vec; start_age = 0) = UltimateMortality(vec; start_age)
35 changes: 35 additions & 0 deletions test/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,41 @@
q = mortality_vector(collect(0:5))
@test q[0] == 0
@test q[5] == 5

# mortality_vector is an alias of UltimateMortality
@test mortality_vector(v, start_age = 3) == UltimateMortality(v, start_age = 3)
end

@testset "UltimateMortality accepts any AbstractVector" begin
# a range
r = UltimateMortality(0:0.1:1)
@test r[0] == 0.0
@test r[10] == 1.0

# a view
base = [0.1, 0.2, 0.3, 0.4]
vw = UltimateMortality(view(base, 2:4), start_age = 1)
@test vw[1] == 0.2
@test vw[3] == 0.4

# a vector containing missing (as the XTbML and CSV loaders produce)
mv = UltimateMortality([0.1, missing])
@test mv[0] == 0.1
@test mv[1] === missing

# no copy is made
q = UltimateMortality(base)
base[1] = 0.5
@test q[0] == 0.5

# start_age sets the first age whatever the input's own axes: a vector already indexed
# by age is re-anchored, not shifted relative to its old first age
for v in ([0.1, 0.2], view([0.0, 0.1, 0.2], 2:3), UltimateMortality([0.1, 0.2]; start_age = 40),
UltimateMortality([0.1, 0.2]; start_age = -5))
m = UltimateMortality(v; start_age = 7)
@test axes(m, 1) == 7:8
@test m[7] == 0.1 && m[8] == 0.2
end
end

@testset "utility functions" begin
Expand Down
Loading