Skip to content
Merged
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
6 changes: 5 additions & 1 deletion src/Aggregators/ability_estimator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -319,12 +319,16 @@ function mean(
denom)
end

# Scalar coordinates and their estimated mean can have different precisions.
squared_deviation(mean::Real) = x -> abs2(x - mean)
squared_deviation(mean) = IntegralCoeffs.SqDev(mean)

function variance_given_mean(integrator::AbilityIntegrator,
est::DistributionAbilityEstimator,
tracked_responses::TrackedResponses,
mean,
denom = normdenom(integrator, est, tracked_responses))
expectation(IntegralCoeffs.SqDev(mean),
expectation(squared_deviation(mean),
0,
integrator,
est,
Expand Down
15 changes: 12 additions & 3 deletions src/Aggregators/ability_tracker.jl
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,11 @@ mutable struct StackedGridAbilityTracker{T <: AbilityTracker, D} <: AbilityTrack
delta_start::Int
end

StackedGridAbilityTracker(parent, density::D, delta_start) where {D} =
StackedGridAbilityTracker{typeof(parent), D}(parent, density, deepcopy(density), delta_start)
StackedGridAbilityTracker(parent, density::Vector, delta_start) =
StackedGridAbilityTracker{typeof(parent), Vector}(parent, density, copy(density), delta_start)
StackedGridAbilityTracker(parent, density::LogGridWeights, delta_start) =
StackedGridAbilityTracker{typeof(parent), LogGridWeights}(
parent, density, deepcopy(density), delta_start)

base_grid_tracker(tracker::StackedGridAbilityTracker) = base_grid_tracker(tracker.parent)
base_grid_tracker(tracker) = tracker
Expand All @@ -79,11 +82,17 @@ function track_delta!(responses::TrackedResponses, tracker::StackedGridAbilityTr
tracker.density = nothing
parent_density = tracker.parent.density
parent_density === nothing && throw(ArgumentError("Track the parent before speculating"))
tracker.density = grid_delta_density!(tracker.scratch, base_grid_tracker(tracker),
density = grid_delta_density!(tracker.scratch, base_grid_tracker(tracker),
parent_density, responses, tracker.delta_start)
tracker.scratch = updated_grid_scratch(tracker.scratch, density)
tracker.density = density
tracker
end

updated_grid_scratch(scratch, density) = density
updated_grid_scratch(scratch::LogGridWeights, density::LogGridWeights) =
scratch.log_values === density.log_values ? scratch : density

track!(responses::TrackedResponses, tracker::StackedGridAbilityTracker) =
track_delta!(responses, tracker)
track_append!(responses::TrackedResponses, tracker::StackedGridAbilityTracker) =
Expand Down
44 changes: 32 additions & 12 deletions src/Aggregators/ability_trackers/grid.jl
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const EqualWeightGridIntegrator = Union{FixedGridIntegrator,
PreallocatedFixedGridIntegrator, Integrators.IterativeFixedGridIntegrator}
const ScalarGridIntegrator = Union{FixedGridIntegrator{<:AbstractVector{Float64}},
PreallocatedFixedGridIntegrator{<:AbstractVector{Float64}},
Integrators.IterativeFixedGridIntegrator{<:AbstractVector{Float64}}}
const ScalarGrid = AbstractVector{<:Real}
const ScalarGridIntegrator = Union{FixedGridIntegrator{<:ScalarGrid},
PreallocatedFixedGridIntegrator{<:ScalarGrid},
Integrators.IterativeFixedGridIntegrator{<:ScalarGrid}}
const TabulatedDichotomousBank = Union{FittedItemBanks.DichotomousPointsItemBank,
FittedItemBanks.DichotomousPointsWithLogsItemBank}

Expand All @@ -27,6 +28,11 @@ $(TYPEDEF)

Cache an unnormalized density on an equal-weight fixed grid. The estimator
must declare `MultiplicativeResponseDelta()` through [`response_delta_style`](@ref).
Scalar grids accept real coordinates. The density uses the numeric types
produced by the prior and responses.
Use Float32 coordinates, prior parameters and a Float32 2PL transfer bank
for Float32 EAP and prepared MEPV. FittedItemBanks 0.7.7 widens Float32
guess/slip responses to Float64.
Appending responses multiplies only their probabilities into `density`;
`track!`, rollback and clearing rebuild the density, including its prior.

Expand All @@ -41,10 +47,10 @@ mutable struct GriddedAbilityTracker{
} <: AbilityTracker
ability_estimator::AbilityEstimatorT
integrator::IntegratorT
density::Union{Nothing, Vector{Float64}}
density::Union{Nothing, Vector}

function GriddedAbilityTracker(est::E, integrator::I,
density::Union{Nothing, Vector{Float64}}) where {
density::Union{Nothing, Vector}) where {
E <: DistributionAbilityEstimator, I <: EqualWeightGridIntegrator}
require_response_deltas(est)
density === nothing || length(density) == length(Integrators.get_grid(integrator)) ||
Expand All @@ -67,8 +73,8 @@ end
function track!(responses::TrackedResponses, tracker::GriddedAbilityTracker)
responses.speculation_start == 0 || return tracker
tracker.density = nothing
tracker.density = grid_linear_values(pdf(tracker.ability_estimator, responses),
Integrators.get_grid(tracker.integrator))
tracker.density = collect(grid_linear_values(pdf(tracker.ability_estimator, responses),
Integrators.get_grid(tracker.integrator)))
tracker
end

Expand All @@ -79,19 +85,33 @@ function track_append!(responses::TrackedResponses, tracker::GriddedAbilityTrack
tracker.density = nothing
delta = response_view(responses.responses, length(responses):length(responses))
likelihood = AbilityLikelihood(responses.item_bank, delta)
density .*= grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator))
tracker.density = density
factors = grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator))
tracker.density = update_grid_buffer!(density, *, density, factors)
tracker
end

function refresh_after_history_edit!(responses, tracker::GriddedAbilityTracker)
track!(responses, tracker)
end

function grid_delta_density!(scratch::Vector{Float64}, tracker::GriddedAbilityTracker,
# Widen when a response has more precision than the existing buffer. In
# particular, an empty history's density has not seen the bank's response type.
function update_grid_buffer!(buffer, op, density, factors)
values = Base.Broadcast.broadcasted(op, density, factors)
if Base.Broadcast.combine_eltypes(values.f, values.args) === eltype(buffer)
return Base.materialize!(buffer, values)
end
Base.materialize(values)
end

copy_grid_buffer!(scratch::Vector{T}, density::Vector{T}) where {T} = copyto!(scratch, density)
copy_grid_buffer!(scratch, density) = copy(density)

function grid_delta_density!(scratch::Vector, tracker::GriddedAbilityTracker,
density, responses, start)
start > length(responses) && return copyto!(scratch, density)
start > length(responses) && return copy_grid_buffer!(scratch, density)
delta = response_view(responses.responses, start:length(responses))
likelihood = AbilityLikelihood(responses.item_bank, delta)
scratch .= density .* grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator))
factors = grid_delta_values(likelihood, Integrators.get_grid(tracker.integrator))
update_grid_buffer!(scratch, *, density, factors)
end
20 changes: 12 additions & 8 deletions src/Aggregators/log_grid.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ equal-weight fixed grid. Construct with `LogGridAbilityTracker(estimator, grid)`
`tracker.density` contains `log_values`, normalized `weights`, `log_scale`
and `scaled_sum`; the unnormalized grid mass is `exp(log_scale) * scaled_sum`.
An all-zero density raises `DomainError` rather than manufacturing a posterior.
The cached log densities and weights use the floating-point type supported
by PsychometricsBazaarBase's `LogGridWeights` for the evaluated log densities.

The estimator must declare `MultiplicativeResponseDelta()` through
[`response_delta_style`](@ref). Appends add only new response log probabilities
Expand Down Expand Up @@ -89,15 +91,16 @@ initialize_grid_tracker!(responses, tracker::LogGridAbilityTracker) = track!(res
function grid_delta_density!(scratch::LogGridWeights, tracker::LogGridAbilityTracker,
density, responses, start)
if start > length(responses)
copyto!(scratch.log_values, density.log_values)
copyto!(scratch.weights, density.weights)
return LogGridWeights(scratch.log_values,
scratch.weights, density.log_scale, density.scaled_sum)
logs = copy_grid_buffer!(scratch.log_values, density.log_values)
weights = copy_grid_buffer!(scratch.weights, density.weights)
return LogGridWeights(logs, weights, density.log_scale, density.scaled_sum)
end
delta = response_view(responses.responses, start:length(responses))
scratch.log_values .= density.log_values .+ grid_delta_values(
AbilityLogLikelihood(responses.item_bank, delta), Integrators.get_grid(tracker.integrator))
normalize_grid_weights!(scratch.log_values, scratch.weights)
factors = grid_delta_values(AbilityLogLikelihood(responses.item_bank, delta),
Integrators.get_grid(tracker.integrator))
logs = update_grid_buffer!(scratch.log_values, +, density.log_values, factors)
weights = eltype(logs) === eltype(scratch.weights) ? scratch.weights : similar(logs)
normalize_grid_weights!(logs, weights)
end

"""
Expand Down Expand Up @@ -184,7 +187,8 @@ function expectation(rett::IntReturnType, f::F, ncomp, integrator::LogGridIntegr
value = weighted_grid_mean(f, Integrators.get_grid(integrator.integrator), density)
# Cancel the mass before multiplying by the moment. This also avoids loss of
# precision from adding a moment's logarithm to a huge log normalization scale.
correction = denom === nothing ? 1.0 : unlog(grid_mass(density) / denom)
denom === nothing && return rett(BareIntegrationResult(value))
correction = unlog(grid_mass(density) / denom)
rett(BareIntegrationResult(value * correction))
end

Expand Down
7 changes: 4 additions & 3 deletions src/NextItemRules/combinators/expectation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,14 @@ function compute_criterion(
tracked_responses,
item_idx)
possible_responses = responses(ItemResponse(tracked_responses.item_bank, item_idx))
res = 0.0
res = nothing
for (prob, possible_response) in zip(exp_resp, possible_responses)
replace_speculation!(speculator, SVector(item_idx), SVector(possible_response))
res += prob *
value = prob *
_generic_criterion(item_criterion.criterion, speculator.responses, item_idx, possible_response)
res = res === nothing ? value : res + value
end
res
something(res, 0.0)
end

function power_summary(io::IO, item_criterion::ExpectationBasedItemCriterion)
Expand Down
73 changes: 54 additions & 19 deletions src/NextItemRules/combinators/grid_mepv.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,55 @@ function prepare_grid_mepv(criterion, history, ::OneDimContinuousDomain,
Aggregators.TrackedLikelihoodIntegrator{<:Aggregators.ScalarGridIntegrator},
LogGridIntegrator{<:Aggregators.ScalarGridIntegrator}})
grid = prepare_mepv_grid(Integrators.get_grid(get_integrator(integrator)))
density = deepcopy(Aggregators.grid_density(criterion.criterion.dist_est, history, integrator))
bank = history.item_bank
density = Aggregators.grid_density(criterion.criterion.dist_est, history, integrator)
paired = paired_mepv_bank(density, bank)
T = candidate_weight_type(density, ItemResponse{typeof(bank)}, eltype(grid),
eltype(history.responses.values), paired)
scratch = if isconcretetype(T) && T <: Real
candidate_grid_scratch(density, T, paired)
elseif paired
return Speculator(history, 1)
else
# Let each outcome determine its own buffer type.
nothing
end
theta = criterion.response_expectation.ability_estimator(history)
PreparedGridMEPV(grid, density, theta,
candidate_grid_scratch(density, ResponseType(history.item_bank), history.item_bank))
PreparedGridMEPV(grid, deepcopy(density), theta, scratch)
end

const PairedMEPVBank = Union{TransferItemBank, SlopeInterceptTransferItemBank,
CdfMirtItemBank, SlopeInterceptMirtItemBank}
paired_mepv_bank(::AbstractItemBank) = false
paired_mepv_bank(::PairedMEPVBank) = true
paired_mepv_bank(bank::GuessAndSlipItemBank) = paired_mepv_bank(bank.inner_bank)

paired_mepv_bank(::AbstractVector, bank) = paired_mepv_bank(bank)
paired_mepv_bank(::Integrators.LogGridWeights, bank) = ResponseType(bank) isa BooleanResponse

function candidate_weight_type(::AbstractVector{W}, ::Type{IR},
::Type{X}, ::Type{C}, paired) where {W, IR, X, C}
paired ? Base.promote_op((w, ir, x, i) -> w * resp_vec(ir, x)[i], W, IR, X, Int) :
Base.promote_op((w, ir, c, x) -> w * resp(ir, c, x), W, IR, C, X)
end

candidate_grid_scratch(density, response_type) = deepcopy(density)
candidate_grid_scratch(density, response_type, bank) = candidate_grid_scratch(density, response_type)
function candidate_weight_type(::Integrators.LogGridWeights{W}, ::Type{IR},
::Type{X}, ::Type{C}, paired) where {W, IR, X, C}
paired ? Base.promote_op((w, ir, x, i) -> w + log_resp_vec(ir, x)[i], W, IR, X, Int) :
Base.promote_op((w, ir, c, x) -> w + log_resp(ir, c, x), W, IR, C, X)
end

# Native vector log responses preserve both tails for all supported banks.
candidate_grid_scratch(density::Integrators.LogGridWeights, ::BooleanResponse) =
(deepcopy(density), deepcopy(density))
function candidate_grid_scratch(density::AbstractVector, T, paired)
scratch = similar(density, T)
paired ? (scratch, similar(scratch)) : scratch
end

# Only opt into paired ordinary responses where FIB preserves both tails.
# Custom banks retain scalar evaluation: their resp_vec may still form 1-p.
candidate_grid_scratch(density::AbstractVector, ::BooleanResponse, bank) =
candidate_linear_scratch(density, bank)
candidate_linear_scratch(density, bank::AbstractItemBank) = deepcopy(density)
candidate_linear_scratch(density, bank::Union{TransferItemBank, SlopeInterceptTransferItemBank,
CdfMirtItemBank, SlopeInterceptMirtItemBank}) = (deepcopy(density), deepcopy(density))
candidate_linear_scratch(density, bank::GuessAndSlipItemBank) =
candidate_linear_scratch(density, bank.inner_bank)
function candidate_grid_scratch(density::Integrators.LogGridWeights, T, paired)
template = T === eltype(density.log_values) ? density :
Integrators.LogGridWeights(T.(density.log_values))
scratch = deepcopy(template)
paired ? (scratch, deepcopy(template)) : scratch
end

function candidate_grid_density!(scratch::AbstractVector, density::AbstractVector,
ir, category, grid)
Expand All @@ -67,6 +94,14 @@ function candidate_grid_density!(scratch::Integrators.LogGridWeights,
Integrators.normalize_grid_weights!(scratch.log_values, scratch.weights)
end

function candidate_grid_density!(::Nothing, density::AbstractVector, ir, category, grid)
density .* resp.(Ref(ir), Ref(category), grid)
end

function candidate_grid_density!(::Nothing, density::Integrators.LogGridWeights, ir, category, grid)
Integrators.LogGridWeights(density.log_values .+ log_resp.(Ref(ir), Ref(category), grid))
end

function compute_criterion(criterion::GridMEPVCriterion, state::PreparedGridMEPV,
history::TrackedResponses, item_idx)
ir = ItemResponse(history.item_bank, item_idx)
Expand All @@ -75,7 +110,7 @@ end

function candidate_expected_variance(criterion, state, ir, scratch)
probabilities = resp_vec(ir, state.theta)
value = 0.0
value = zero(state.theta)
for (probability, category) in zip(probabilities, responses(ir))
density = candidate_grid_density!(scratch, state.density, ir, category, state.grid)
value += probability * candidate_grid_variance(criterion, state.grid, density)
Expand Down Expand Up @@ -115,7 +150,7 @@ function candidate_expected_variance(criterion, state, ir,
end

function candidate_grid_variance(criterion, grid, density::AbstractVector)
criterion.skip_zero && all(iszero, density) && return Inf
criterion.skip_zero && all(iszero, density) && return oftype(float(zero(eltype(density))), Inf)
Integrators.weighted_grid_moments(grid, density).variance
end

Expand Down
4 changes: 2 additions & 2 deletions src/NextItemRules/criteria/state/ability_variance.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function AbilityVariance(bits...)
end

function compute_criterion(criterion::AbilityVariance,
tracked_responses::TrackedResponses)::Float64
tracked_responses::TrackedResponses)
# XXX: Not sure if the estimator should come from somewhere else here
denom = normdenom(criterion.integrator,
criterion.dist_est,
Expand All @@ -38,7 +38,7 @@ end
function compute_criterion(criterion::AbilityVariance,
::Union{OneDimContinuousDomain, DiscreteDomain},
tracked_responses::TrackedResponses,
denom)::Float64
denom)
return variance(
criterion.integrator,
criterion.dist_est,
Expand Down
5 changes: 4 additions & 1 deletion src/NextItemRules/prelude/criteria.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ function compute_criteria(
responses::TrackedResponseT,
items::AbstractItemBank
) where {ItemCriterionT <: ItemCriterion, TrackedResponseT <: TrackedResponses}
objective_state = init_thread(criterion, responses)
compute_criteria(criterion, init_thread(criterion, responses), responses, items)
end

function compute_criteria(criterion, objective_state, responses, items)
return [compute_criterion(criterion, objective_state, responses, item_idx)
for item_idx in eachindex(items)]
end
Expand Down
19 changes: 9 additions & 10 deletions src/NextItemRules/strategies/exhaustive.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ function exhaustive_search(
callback,
answered_items::AbstractVector{Int},
items::AbstractItemBank
)::Tuple{Int, Float64}
)
min_obj_idx::Int = -1
min_obj_val::Float64 = Inf
min_obj_val = Inf
for item_idx in eachindex(items)
# TODO: Add these back in
#@init irf_states_storage = zeros(Int, length(responses) + 1)
Expand All @@ -22,13 +22,12 @@ function exhaustive_search(
return (min_obj_idx, min_obj_val)
end

function exhaustive_search(objective::ItemCriterionT,
responses::TrackedResponseT,
items::AbstractItemBank)::Tuple{
Int,
Float64
} where {ItemCriterionT <: ItemCriterion, TrackedResponseT <: TrackedResponses}
objective_state = init_thread(objective, responses)
function exhaustive_search(objective::ItemCriterion, responses::TrackedResponses,
items::AbstractItemBank)
exhaustive_search(objective, init_thread(objective, responses), responses, items)
end

function exhaustive_search(objective, objective_state, responses, items)
return exhaustive_search(responses.responses.indices, items) do item_idx
return compute_criterion(objective, objective_state, responses, item_idx)
end
Expand All @@ -51,4 +50,4 @@ function best_item(
items
) where {ItemCriterionT <: ItemCriterion}
exhaustive_search(rule.criterion, responses, items)[1]
end
end
Loading
Loading