-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
LMM cluster permutation #6
Draft
behinger
wants to merge
9
commits into
main
Choose a base branch
from
lmm_perm
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d5f2636
inital lmm_perm
behinger 152b1f6
Moved UnfoldMixedModels also to new extension
behinger 638ba0b
well, it does something now
behinger 67fe653
added lmm clusterperm
behinger eaa207d
forgot to save this file
behinger 247623a
forgot to save
behinger 409f647
Update UnfoldStatsMixedModelsPermutationsExt.jl
behinger 767e5b1
added an 'abs'
behinger 482a8f7
Merge branch 'lmm_perm' of http://github.com/unfoldtoolbox/UnfoldStat…
behinger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,3 +6,4 @@ | |
/docs/Manifest.toml | ||
/docs/build/ | ||
/docs/src/generated | ||
/docs/dev |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
|
||
# get some data | ||
using UnfoldSim | ||
using Unfold | ||
using MixedModelsPermutations, ClusterDepth # both necessary to activate correct extension! | ||
using UnfoldStats | ||
using StatsModels | ||
using Random | ||
|
||
srate = 25 | ||
design = MultiSubjectDesign(; | ||
n_subjects = 30, | ||
n_items = 40, | ||
items_between = Dict(:stimtype => ["car", "face"]), | ||
) | ||
#both_within = Dict(:condition=>["scrambled","intact"])) | ||
contrasts = Dict(:stimtype => DummyCoding()) | ||
p1 = MixedModelComponent(; | ||
basis = UnfoldSim.p100(; sfreq = srate), | ||
formula = @formula(dv ~ 1 + (1 | subject) + (1 | item)), | ||
β = [5.0], | ||
σs = Dict(:subject => [0.0], :item => [0.0]), | ||
contrasts = contrasts, | ||
); | ||
|
||
n1 = MixedModelComponent(; | ||
basis = UnfoldSim.n170(; sfreq = srate), | ||
formula = @formula(dv ~ 1 + stimtype + (1 + stimtype | subject) + (1 | item)), | ||
β = [1.0, 4], # n170-basis is negative | ||
σs = Dict(:subject => [2.0, 0.25], :item => [0.25]), | ||
contrasts = contrasts, | ||
); | ||
|
||
p3 = MixedModelComponent(; | ||
basis = UnfoldSim.p300(; sfreq = srate), | ||
formula = @formula(dv ~ 1 + (1 | subject) + (1 + stimtype | item)), | ||
β = [4.0], | ||
σs = Dict(:subject => [1.0], :item => [0.5, 2]), | ||
contrasts = contrasts, | ||
); | ||
|
||
|
||
|
||
data_e, events = UnfoldSim.simulate( | ||
design, | ||
[p1, n1, p3], | ||
UniformOnset(srate * 2, 10), | ||
PinkNoise(; noiselevel = 1); | ||
return_epoched = true, | ||
) # 18 | ||
times = range(-0.1, 0.5, length = size(data_e, 1)) | ||
data_e = reshape(data_e, size(data_e, 1), :) | ||
#events.latency .+= repeat(range(0,length=size(data,2),step=size(data,1)),inner=size(events[events.subject.=="S01",:],1)) | ||
|
||
|
||
|
||
# # Fit LMM | ||
m = fit( | ||
UnfoldModel, | ||
[ | ||
Any => ( | ||
@formula(0 ~ 1 + stimtype + (1 + stimtype | item) + (1 + stimtype | subject)), | ||
times, | ||
), | ||
], | ||
events, | ||
data_e, | ||
); | ||
|
||
|
||
# # Cluster Permute :) | ||
coefficient = 2 | ||
pvalues( | ||
MersenneTwister(1), | ||
m, | ||
data_e, | ||
coefficient; | ||
n_permutations = 10, | ||
clusterforming_threshold = 1.8, | ||
) | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,23 @@ | ||||||
module UnfoldStatsMixedModelsExt | ||||||
using Unfold | ||||||
using UnfoldStats | ||||||
using MixedModels | ||||||
import StatsAPI: pvalue | ||||||
|
||||||
lmm_ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) | ||||||
|
||||||
if isnothing(lmm_ext) | ||||||
error("Something went wrong with getting the Unfold UnfoldMixedModelsExt extension") | ||||||
end | ||||||
# Currently, `extract_coefs` is not implemented for mixed-effects models | ||||||
UnfoldStats.extract_coefs( | ||||||
model::Union{ | ||||||
lmm_ext.UnfoldLinearMixedModel, | ||||||
lmm_ext.UnfoldLinearMixedModelContinuousTime, | ||||||
}, | ||||||
predictor, | ||||||
basisname, | ||||||
) = throw( | ||||||
"The `extract_coefs` function is currently not implemented for mixed-effects models.", | ||||||
) | ||||||
end | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [JuliaFormatter] reported by reviewdog 🐶
Suggested change
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,174 @@ | ||||||
module UnfoldStatsMixedModelsPermutationsExt | ||||||
using Unfold | ||||||
import Unfold: pvalues | ||||||
using UnfoldStats | ||||||
#using MixedModels | ||||||
using MixedModelsPermutations | ||||||
using ClusterDepth | ||||||
using Logging | ||||||
using Random | ||||||
const MixedModels = MixedModelsPermutations.MixedModels | ||||||
LMMext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) | ||||||
|
||||||
|
||||||
function Unfold.pvalues( | ||||||
rng, | ||||||
model::LMMext.UnfoldLinearMixedModel, | ||||||
data, | ||||||
coefficient; | ||||||
type = "clusterdepth", | ||||||
clusterforming_threshold, | ||||||
kwargs..., | ||||||
) | ||||||
if type != "clusterdepth" | ||||||
error("other types (e.g. FDR currently not implemented") | ||||||
elseif type == "clusterdepth" | ||||||
return lmm_clusterdepth( | ||||||
rng, | ||||||
model, | ||||||
data, | ||||||
coefficient; | ||||||
clusterforming_threshold, | ||||||
kwargs..., | ||||||
) | ||||||
end | ||||||
end | ||||||
|
||||||
|
||||||
|
||||||
|
||||||
function lmm_clusterdepth( | ||||||
rng, | ||||||
model, | ||||||
data, | ||||||
coefficient; | ||||||
lmm_statistic = :z, | ||||||
clusterforming_threshold, | ||||||
kwargs..., | ||||||
) | ||||||
permuted = lmm_permutations(rng, model, data, coefficient; kwargs...) | ||||||
observed = get_lmm_statistic(model, coefficient, lmm_statistic) | ||||||
return lmm_clusterdepth_pvalues( | ||||||
rng, | ||||||
observed, | ||||||
permuted; | ||||||
clusterforming_threshold, | ||||||
kwargs..., | ||||||
) | ||||||
end | ||||||
function lmm_clusterdepth_pvalues( | ||||||
rng, | ||||||
observed, | ||||||
permuted; | ||||||
clusterforming_threshold, | ||||||
kwargs..., | ||||||
) | ||||||
|
||||||
# we need global variables here (yes, sorry...), because instead of actually | ||||||
# letting ClusterDepth do the permutation, we just have to index the already | ||||||
# permuted data given in the function (`permuted`) | ||||||
global n_permutation_count | ||||||
n_permutation_count = 0 | ||||||
function _fake_permutation_fun(r, data) | ||||||
global n_permutation_count | ||||||
n_permutation_count = n_permutation_count + 1 | ||||||
return permuted[:, n_permutation_count] | ||||||
end | ||||||
J_tuple = ClusterDepth.perm_clusterdepths_both( | ||||||
rng, | ||||||
abs.(permuted), | ||||||
_fake_permutation_fun, | ||||||
clusterforming_threshold; | ||||||
statfun = x -> abs.(x), | ||||||
nₚ = size(permuted, 2), | ||||||
) | ||||||
|
||||||
pvals = ClusterDepth.pvals(observed, J_tuple, clusterforming_threshold) | ||||||
|
||||||
end | ||||||
|
||||||
function lmm_permutations( | ||||||
rng::AbstractRNG, | ||||||
model, | ||||||
data::AbstractArray{<:Real,3}, | ||||||
coefficient::Int; | ||||||
n_permutations = 500, | ||||||
lmm_statistic = :z, | ||||||
time_selection = 1:size(data, 2), | ||||||
) | ||||||
permdata = Matrix{Float64}(undef, length(time_selection), n_permutations) | ||||||
|
||||||
|
||||||
Xs = LMMext.prepare_modelmatrix(model) | ||||||
|
||||||
mm_outer = LMMext.LinearMixedModel_wrapper(Unfold.formulas(model), data[1, 1, :], Xs) | ||||||
mm_outer.optsum.maxtime = 0.1 # | ||||||
|
||||||
chIx = 1 # for now we only support 1 channel anyway | ||||||
# | ||||||
#p = Progress(length(time_selection)) | ||||||
#Threads.@threads for tIx =1:length(time_selection) | ||||||
#@showprogress "Processing Timepoints" for | ||||||
Threads.@threads for tIx = 1:length(time_selection) | ||||||
|
||||||
# splice in the correct dataa for residual calculation | ||||||
mm = deepcopy(mm_outer) | ||||||
mm.y .= data[chIx, time_selection[tIx], :] | ||||||
|
||||||
# set the previous calculated model-fit | ||||||
θ = Vector(modelfit(model).θ[time_selection[tIx]]) | ||||||
@debug size(θ) | ||||||
MixedModels.updateL!(MixedModels.setθ!(mm, θ)) | ||||||
|
||||||
# get the coefficient | ||||||
H0 = coef(mm) | ||||||
# set the one of interest to 0 | ||||||
H0[coefficient] = 0 | ||||||
# run the permutation | ||||||
|
||||||
permutations = undef | ||||||
Logging.with_logger(NullLogger()) do # remove NLopt warnings | ||||||
permutations = permutation( | ||||||
deepcopy(rng), # important here is to set the same seed to keep flip all time-points the same | ||||||
n_permutations, | ||||||
mm; | ||||||
β = H0, | ||||||
hide_progress = true, | ||||||
#blup_method = MixedModelsPermutations.olsranef, | ||||||
) # constant rng to keep autocorr & olsranef for singular models | ||||||
end | ||||||
|
||||||
# extract the test-statistic | ||||||
|
||||||
permdata[tIx, :] = | ||||||
get_lmm_statistic(model, permutations, coefficient, lmm_statistic) | ||||||
|
||||||
#next!(p) | ||||||
end # end for | ||||||
return permdata | ||||||
end | ||||||
|
||||||
function get_lmm_statistic( | ||||||
model, | ||||||
permutations::MixedModelsPermutations.MixedModels.MixedModelFitCollection, | ||||||
coefficient::Int, | ||||||
lmm_statistic, | ||||||
) | ||||||
[ | ||||||
getproperty(m, lmm_statistic) for m in permutations.coefpvalues if | ||||||
String(m.coefname) == Unfold.coefnames(Unfold.formulas(model))[1][coefficient] | ||||||
] | ||||||
|
||||||
end | ||||||
function get_lmm_statistic( | ||||||
model::LMMext.UnfoldLinearMixedModel, | ||||||
coefficient::Int, | ||||||
lmm_statistic, | ||||||
) | ||||||
return get_lmm_statistic(model, modelfit(model), coefficient, lmm_statistic) | ||||||
# r = coeftable(m) | ||||||
# r = subset(r, :group => (x -> isnothing.(x)), :coefname => (x -> x .!== "(Intercept)")) | ||||||
# tvals = abs.(r.estimate ./ r.stderror) | ||||||
# return tvals | ||||||
end | ||||||
end | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [JuliaFormatter] reported by reviewdog 🐶
Suggested change
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[JuliaFormatter] reported by reviewdog 🐶