licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
docs
553
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased ## v2.0.0 - `callback` now receives the gradient as an argument `βˆ‚`. - No other (breaking) changes, but tagging major release to be safe. ## v1.0.0 - Contrastive divergence algorithm for training Restricted Boltzmann Machines. - Compatiblity with with RestrictedBoltzmannMachines v3.
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
2.1.1
a9327ceb1e062f3b080ac368e7ce86c15a3499d0
docs
290
# ContrastiveDivergenceRBM Julia package Contrastive divergence (CD) training of RBMs, in Julia. ## Installation This package is registered. Install with: ```julia import Pkg Pkg.add("ContrastiveDivergenceRBM") ``` ## Related * https://github.com/cossio/RestrictedBoltzmannMachines.jl
ContrastiveDivergenceRBM
https://github.com/cossio/ContrastiveDivergenceRBM.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
6667
using BenchmarkTools using Pkg using StableRNGs using ResumableFunctions const SUITE = BenchmarkGroup() const rng = StableRNG(42) const n = 93 Manifest = Pkg.Operations.Context().env.manifest V = Manifest[findfirst(v -> v.name == "ResumableFunctions", Manifest)].version ## Benchmarks hardcoded for various types const hardcoded_types = [Int, BigInt] S_hc = SUITE["hardcoded types"] = BenchmarkGroup(["hardcoded types"]) for N in hardcoded_types # define a separate submodule for each hardcoded type @eval module $(Symbol("Test", N)) using BenchmarkTools using ResumableFunctions using ..Main: S_hc, rng, V const n = $n const N = $N str = string(N) S = S_hc[str] = BenchmarkGroup([str]) # the functions to be benchmarked function direct(a::N, b::N) b, a+b end function test_direct(n::Int) a, b = zero(N), one(N) for _ in 1:n-1 a, b = direct(a, b) end a end @resumable function fibonacci_resumable(n::Int) a, b = zero(N), one(N) for _ in 1:n @yield a a, b = b, a + b end end @noinline function test_resumable(n::Int) a = 0 for v in fibonacci_resumable(n) a = v end a end function fibonacci_channel(n::Int, ch::Channel) a, b = zero(N), one(N) for _ in 1:n put!(ch, a) a, b = b, a + b end end @noinline function test_channel(n::Int, csize::Int) fib_channel = Channel(c -> fibonacci_channel(n, c); ctype=N, csize=csize) a = 0 for v in fib_channel a = v end a end struct Generator callee :: Task function Generator(f::Function, args...; kwargs...) ct = current_task() new(@task begin task_local_storage(:caller, ct); f(args...; kwargs...); yield(ct) end) end end function Base.iterate(gen::Generator, state=nothing) ret = yieldto(gen.callee) if ret === nothing return nothing end ret, nothing end function consume(gen::Generator, val=nothing) yieldto(gen.callee, val) end function produce(val=nothing) t = task_local_storage(:caller) yieldto(t, val) end function fibonacci_task(n::Int) a,b = zero(N), one(N) for _ in 1:n produce(a) a, b = b, a+b end end @noinline function test_task(n::Int) a = 0 for v in Generator(fibonacci_task, n) a = v end a end function fibonacci_closure() a, b = zero(N), one(N) function() tmp = a a, b = b, a + b tmp end end @noinline function test_closure(n::Int) fib_closure = fibonacci_closure() a = 0 for _ in 1:n a = fib_closure() end a end function fibonacci_closure_opt() a = Ref(zero(N)) b = Ref(one(N)) function() tmp = a[] a[], b[] = b[], a[] + b[] tmp end end @noinline function test_closure_opt(n::Int) fib_closure = fibonacci_closure_opt() a = 0 for _ in 1:n a = fib_closure() end a end function fibonacci_closure_stm(n::Int) _state = Ref(0x00) a = Ref{N}() b = Ref{N}() _iterstate_1 = Ref{Int}() _iterator_1 = Ref{UnitRange{Int}}() function(_arg::Any=nothing) _state[] === 0x00 && @goto _STATE_0 _state[] === 0x01 && @goto _STATE_1 error("@resumable function has stopped!") @label _STATE_0 _state[] = 0xff _arg isa Exception && throw(_arg) a[], b[] = zero(Int), one(Int) _iterator_1[] = 1:n _iteratornext_1 = iterate(_iterator_1[]) while _iteratornext_1 !== nothing (_, _iterstate_1[]) = _iteratornext_1 _state[] = 0x01 return a[] @label _STATE_1 _state[] = 0xff _arg isa Exception && throw(_arg) (a[], b[]) = (b[], a[] + b[]) _iteratornext_1 = iterate(_iterator_1[], _iterstate_1[]) end end end const FibClosure = typeof(fibonacci_closure_stm(n)) function Base.iterate(f::FibClosure, state=nothing) a = f() f._state[] === 0xff && return nothing a, nothing end @noinline function test_closure_stm(n::Int) fib_closure = fibonacci_closure_stm(n) a = 0 for v in fibonacci_closure_stm(n) a = v end a end struct FibN n::Int end function Base.iterate(f::FibN, state::Tuple{N, N, Int}=(zero(N), one(N), 1)) a, b, iters = state iters > f.n && return nothing a, (b, a + b, iters + 1) end @noinline function test_iteration_protocol(n::Int) a = 0 for v in FibN(n) a = v end a end # define the benchmarks S["Direct"] = @benchmarkable test_direct(_n) setup=(_n=n) S["ResumableFunctions"] = @benchmarkable test_resumable(_n) setup=(_n=n) S["Channels csize=0"] = @benchmarkable test_channel(_n, 0) setup=(_n=n) S["Channels csize=1"] = @benchmarkable test_channel(_n, 1) setup=(_n=n) S["Channels csize=20"] = @benchmarkable test_channel(_n, 20) setup=(_n=n) S["Channels csize=100"] = @benchmarkable test_channel(_n, 100) setup=(_n=n) S["Task scheduling"] = @benchmarkable test_task(_n) setup=(_n=n) S["Closure"] = @benchmarkable test_closure(_n) setup=(_n=n) S["Closure optimized"] = @benchmarkable test_closure_opt(_n) setup=(_n=n) S["Closure statemachine"] = @benchmarkable test_closure_stm(_n) setup=(_n=n) S["Iteration protocol"] = @benchmarkable test_iteration_protocol(_n) setup=(_n=n) end # module end # for N in [Int, BigInt] ## # run as `julia --project=. benchmark/benchmarks.jl` const T = Int # pick a type to test for (from hardcoded_types) isinteractive() || get(ENV,"CI","false") =="true" || begin println("\n\nTesting with $T\n") eval( :(import .$(Symbol("Test",T)): test_direct, test_resumable, test_channel, test_task, test_closure, test_closure_opt, test_closure_stm, test_iteration_protocol) ) println("Direct: ") @btime test_direct($n) @assert test_direct(n) == 7540113804746346429 println("ResumableFunctions: ") @btime test_resumable($n) @assert test_resumable(n) == 7540113804746346429 println("Channels csize=0: ") @btime test_channel($n, $0) @assert test_channel(n, 0) == 7540113804746346429 println("Channels csize=1: ") @btime test_channel($n, $1) @assert test_channel(n, 1) == 7540113804746346429 println("Channels csize=20: ") @btime test_channel($n, $20) @assert test_channel(n, 20) == 7540113804746346429 println("Channels csize=100: ") @btime test_channel($n, $100) @assert test_channel(n, 100) == 7540113804746346429 println("Task scheduling") @btime test_task($n) @assert test_task(n) == 7540113804746346429 println("Closure: ") @btime test_closure($n) @assert test_closure(n) == 7540113804746346429 println("Closure optimised: ") @btime test_closure_opt($n) @assert test_closure_opt(n) == 7540113804746346429 println("Closure statemachine: ") @btime test_closure_stm($n) @assert test_closure_stm(n) == 7540113804746346429 println("Iteration protocol: ") @btime test_iteration_protocol($n) @assert test_iteration_protocol(n) == 7540113804746346429 end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
378
using Documenter using ResumableFunctions makedocs( sitename = "ResumableFunctions", authors = "Ben Lauwens and volunteers from JuliaDynamics and QuantumSavory", pages = [ "Home" => "index.md", "Manual" => "manual.md", "Internals" => "internals.md", "Library" => "library.md" ] ) deploydocs( repo = "github.com/JuliaDynamics/ResumableFunctions.jl" )
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1892
#= The Computer Language Benchmarks Game https://salsa.debian.org/benchmarksgame-team/benchmarksgame/ contributed by Ben Lauwens derived from the Chapel version by Tom Hildebrandt, Brad Chamberlain, and Lydia Duncan and inspired by the Julia version of Luiz M. Faria =# using ResumableFunctions using Base.GMP.MPZ: add_ui!, mul_ui!, add!, tdiv_q! const mpz_t = Ref{BigInt} addmul_ui!(x::BigInt,a::BigInt,b::UInt64) = ccall((:__gmpz_addmul_ui,"libgmp"), Cvoid, (mpz_t,mpz_t,Culong), x, a, b) submul_ui!(x::BigInt,a::BigInt,b::UInt64) = ccall((:__gmpz_submul_ui,"libgmp"), Cvoid, (mpz_t,mpz_t,Culong), x, a, b) get_ui(x::BigInt) = ccall((:__gmpz_get_ui,"libgmp"), Culong, (mpz_t,), x) @resumable function pidigits() k = one(UInt64) d = zero(UInt64) numer = BigInt(1) denom = BigInt(1) accum = BigInt(0) tmp1 = BigInt(0) tmp2 = BigInt(0) tmp3 = BigInt(0) while true k2 = 2k + one(UInt64) addmul_ui!(accum, numer, UInt64(2)) mul_ui!(accum, k2) mul_ui!(denom, k2) mul_ui!(numer, k) k += one(UInt64) if numer <= accum mul_ui!(tmp1, numer, UInt64(3)) add!(tmp1, accum) tdiv_q!(tmp2, tmp1, denom) mul_ui!(tmp1, numer, UInt64(4)) add!(tmp1, accum) tdiv_q!(tmp3, tmp1, denom) if tmp2 == tmp3 d = get_ui(tmp2) @yield d submul_ui!(accum, denom, d) mul_ui!(accum, UInt64(10)) mul_ui!(numer, UInt64(10)) end end end end function main(n = parse(Int64, ARGS[1])) i = 0 pid = pidigits() for i in 1:n d = pid() print(d) if i % 10 === 0 println("\t:", i) end end if i % 10 !== 0 println(" "^(10 - (i % 10)), "\t:", n) end end main(100)
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
468
""" Main module for ResumableFunctions.jl – C# style generators a.k.a. semi-coroutines for Julia """ module ResumableFunctions using MacroTools using MacroTools: combinedef, combinearg, flatten, postwalk export @resumable, @yield, @nosave, @yieldfrom function __init__() STDERR_HAS_COLOR[] = get(stderr, :color, false) end include("safe_logging.jl") include("types.jl") include("transforms.jl") include("utils.jl") include("macro.jl") end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
8147
""" Macro if used in a `@resumable function` that returns the `expr` otherwise throws an error. """ macro yield(expr=nothing) error("@yield macro outside a @resumable function!") end """ Macro if used in a `@resumable function` that delegates to `expr` otherwise throws an error. """ macro yieldfrom(expr=nothing) error("@yieldfrom macro outside a @resumable function!") end """ Macro if used in a `@resumable function` that creates a not saved variable otherwise throws an error. """ macro nosave(expr=nothing) error("@nosave macro outside a @resumable function!") end """ Macro that transforms a function definition in a finite-state machine: - Defines a new `mutable struct` that implements the iterator interface and is used to store the internal state. - Makes this new type callable having following characteristics: - implementents the statements from the initial function definition but; - returns at a `@yield` statement and; - continues after the `@yield` statement when called again. - Defines a constructor function that respects the calling conventions of the initial function definition and returns an object of the new type. If the element type and length is known, the resulting iterator can be made more efficient as follows: - Use `length=ex` to specify the length (if known) of the iterator, like: @resumable length=ex function f(x); body; end Here `ex` can be any expression containing the arguments of `f`. - Use `function f(x)::T` to specify the element type of the iterator. # Extended ```julia julia> @resumable length=n^2 function f(n)::Int for i in 1:n^2 @yield i end end f (generic function with 2 methods) julia> collect(f(3)) 9-element Vector{Int64}: 1 2 3 4 5 6 7 8 9 ``` """ macro resumable(ex::Expr...) length(ex) >= 3 && error("Too many arguments") for i in 1:length(ex)-1 a = ex[i] if !(a isa Expr && a.head === :(=) && a.args[1] in [:length]) error("only keyword argument 'length' allowed") end end expr = ex[end] expr.head !== :function && error("Expression is not a function definition!") # The function that executes a step of the finite state machine func_def = splitdef(expr) rtype = :rtype in keys(func_def) ? func_def[:rtype] : Any args, kwargs, arg_dict = get_args(func_def) params = ((get_param_name(param) for param in func_def[:whereparams])...,) # Initial preparation of the function stepping through the finite state machine and extraction of local variables and their types ui8 = BoxedUInt8(zero(UInt8)) func_def[:body] = postwalk(transform_arg_yieldfrom, func_def[:body]) func_def[:body] = postwalk(transform_yieldfrom, func_def[:body]) func_def[:body] = postwalk(x->transform_for(x, ui8), func_def[:body]) inferfn, slots = get_slots(copy(func_def), arg_dict, __module__) # check if the resumable function is a callable struct instance (a functional) that is referencing itself isfunctional = @capture(func_def[:name], functional_::T_) && inexpr(func_def[:body], functional) if isfunctional slots[functional] = T push!(args, functional) end # The finite state machine structure definition type_name = gensym(Symbol(func_def[:name], :_FSMI)) constr_def = copy(func_def) slot_T = [gensym(s) for s in keys(slots)] slot_T_sub = [:($k <: $v) for (k, v) in zip(slot_T, values(slots))] struct_name = :($type_name{$(func_def[:whereparams]...), $(slot_T_sub...)} <: ResumableFunctions.FiniteStateMachineIterator{$rtype}) constr_def[:whereparams] = (func_def[:whereparams]..., slot_T_sub...) # if there are no where or slot type parameters, we need to use the bare type if isempty(params) && isempty(slot_T) constr_def[:name] = :($type_name) else constr_def[:name] = :($type_name{$(params...), $(slot_T...)}) end constr_def[:args] = tuple() constr_def[:kwargs] = tuple() constr_def[:rtype] = nothing constr_def[:body] = quote fsmi = new() fsmi._state = 0x00 fsmi end # the bare/fallback version of the constructor supplies default slot type parameters # we only need to define this if there there are actually slot defaults to be filled if !isempty(slot_T) bareconstr_def = copy(constr_def) if isempty(params) bareconstr_def[:name] = :($type_name) else bareconstr_def[:name] = :($type_name{$(params...)}) end bareconstr_def[:whereparams] = func_def[:whereparams] bareconstr_def[:body] = :($(bareconstr_def[:name]){$(values(slots)...)}()) bareconst_expr = combinedef(bareconstr_def) |> flatten else bareconst_expr = nothing end constr_expr = combinedef(constr_def) |> flatten type_expr = :( mutable struct $struct_name _state :: UInt8 $((:($slotname :: $slottype) for (slotname, slottype) in zip(keys(slots), slot_T))...) $(constr_expr) $(bareconst_expr) end ) @debug type_expr|>MacroTools.striplines # The "original" function that now is simply a wrapper around the construction of the finite state machine call_def = copy(func_def) call_def[:rtype] = nothing if isempty(params) fsmi_name = type_name else fsmi_name = :($type_name{$(params...)}) end fwd_args, fwd_kwargs = forward_args(call_def) isfunctional && push!(fwd_args, functional) call_def[:body] = quote fsmi = ResumableFunctions.typed_fsmi($fsmi_name, $inferfn, $(fwd_args...), $(fwd_kwargs...)) $((arg !== Symbol("_") ? :(fsmi.$arg = $arg) : nothing for arg in args)...) $((:(fsmi.$arg = $arg) for arg in kwargs)...) fsmi end call_expr = combinedef(call_def) |> flatten @debug call_expr|>MacroTools.striplines # Finalizing the function stepping through the finite state machine if isempty(params) func_def[:name] = :((_fsmi::$type_name)) else func_def[:name] = :((_fsmi::$type_name{$(params...)})) end func_def[:rtype] = nothing func_def[:body] = postwalk(x->transform_slots(x, keys(slots)), func_def[:body]) # Capture the length=... interface_defs = [] for i in 1:length(ex)-1 a = ex[i] if !(a isa Expr && a.head === :(=) && a.args[1] in [:length]) error("only keyword argument 'length' allowed") end if a.args[1] === :length push!(interface_defs, quote Base.IteratorSize(::Type{<: $type_name}) = Base.HasLength() end) func_def2 = copy(func_def) func_def2[:body] = a.args[2] new_body = postwalk(x->transform_slots(x, keys(slots)), a.args[2]) push!(interface_defs, quote Base.length(_fsmi::$type_name) = begin $new_body end end) end end func_def[:body] = postwalk(transform_arg, func_def[:body]) func_def[:body] = postwalk(transform_exc, func_def[:body]) |> flatten ui8 = BoxedUInt8(zero(UInt8)) func_def[:body] = postwalk(x->transform_try(x, ui8), func_def[:body]) ui8 = BoxedUInt8(zero(UInt8)) func_def[:body] = postwalk(x->transform_yield(x, ui8), func_def[:body]) func_def[:body] = postwalk(x->transform_nosave(x, Set{Symbol}()), func_def[:body]) func_def[:body] = quote _fsmi._state === 0x00 && @goto $(Symbol("_STATE_0")) $((:(_fsmi._state === $i && @goto $(Symbol("_STATE_",:($i)))) for i in 0x01:ui8.n)...) error("@resumable function has stopped!") @label $(Symbol("_STATE_0")) _fsmi._state = 0xff _arg isa Exception && throw(_arg) $(func_def[:body]) end func_def[:args] = [Expr(:kw, :(_arg::Any), nothing)] func_def[:kwargs] = [] func_expr = combinedef(func_def) |> flatten if inexpr(func_def[:body], call_def[:name]) || isfunctional @debug "recursion or self-reference is present in a resumable function definition: falling back to no inference" call_expr = postwalk(x->x==:(ResumableFunctions.typed_fsmi) ? :(ResumableFunctions.typed_fsmi_fallback) : x, call_expr) end @debug func_expr|>MacroTools.striplines # The final expression: # - the finite state machine struct # - the function stepping through the states # - the "original" function which now is a simple wrapper around the construction of the finite state machine esc(quote $type_expr $func_expr $(interface_defs...) Base.@__doc__($call_expr) end) end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1183
# safe logging, copied from GPUCompiler using Logging const STDERR_HAS_COLOR = Ref{Bool}(false) # Prevent invalidation when packages define custom loggers # Using invoke in combination with @nospecialize eliminates backedges to these methods function _invoked_min_enabled_level(@nospecialize(logger)) return invoke(Logging.min_enabled_level, Tuple{typeof(logger)}, logger)::LogLevel end # define safe loggers for use in generated functions (where task switches are not allowed) for level in [:debug, :info, :warn, :error] @eval begin macro $(Symbol("safe_$level"))(ex...) macrocall = :(@placeholder $(ex...)) # NOTE: `@placeholder` in order to avoid hard-coding @__LINE__ etc macrocall.args[1] = Symbol($"@$level") quote old_logger = global_logger() io = IOContext(Core.stderr, :color=>STDERR_HAS_COLOR[]) min_level = _invoked_min_enabled_level(old_logger) global_logger(Logging.ConsoleLogger(io, min_level)) ret = $(esc(macrocall)) global_logger(old_logger) ret end end end end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
7367
""" Function that replaces a variable """ function transform_nosave(expr, nosaves::Set{Symbol}) @capture(expr, @nosave var_ = body_) || return expr push!(nosaves, var) :($var = $body) end """ Function that replaces a `@yieldfrom iter` statement with ```julia _other_ = iter... _ret_ = generate(_other_, nothing) while !(_ret_ isa IteratorReturn) _value_, _state_ = _ret_ _newvalue_ = @yield _value_ _ret_ = generate(_other_, _newvalue_, _state_) end _ ``` """ function transform_yieldfrom(expr) _is_yieldfrom(expr) || return expr iter = expr.args[3:end] quote _other_ = $(iter...) _ret_ = $generate(_other_, nothing) while !(_ret_ isa $IteratorReturn) _value_, _state_ = _ret_ _newvalue_ = @yield _value_ _ret_ = $generate(_other_, _newvalue_, _state_) end end end """ Function that replaces an `arg = @yieldfrom iter` statement by ```julia @yieldfrom iter arg = _ret_.value ``` """ function transform_arg_yieldfrom(expr) @capture(expr, arg_ = ex_) || return expr _is_yieldfrom(ex) || return expr iter = ex.args[3:end] quote @yieldfrom $(iter...) $arg = _ret_.value end end """ Function returning whether an expression is a `@yieldfrom` macro """ _is_yieldfrom(ex) = false function _is_yieldfrom(ex::Expr) is_ = ex.head === :macrocall && ex.args[1] === Symbol("@yieldfrom") if is_ && length(ex.args) < 3 error("@yieldfrom without arguments!") end return is_ end """ Function that replaces a `for` loop by a corresponding `while` loop saving explicitly the *iterator* and its *state*. """ function transform_for(expr, ui8::BoxedUInt8) @capture(expr, for element_ in iterator_ body_ end) || return expr ui8.n += one(UInt8) next = Symbol("_iteratornext_", ui8.n) state = Symbol("_iterstate_", ui8.n) iterator_value = Symbol("_iterator_", ui8.n) label = Symbol("_iteratorlabel_", ui8.n) body = postwalk(x->transform_continue(x, label), :(begin $(body) end)) quote $iterator_value = $iterator @nosave $next = iterate($iterator_value) while $next !== nothing ($element, $state) = $next $body @label $label $next = iterate($iterator_value, $state) end end end """ Function that replaces a `continue` statement by a corresponding `@goto` with as label the correct location for the next iteration. """ function transform_continue(expr, label::Symbol) @capture(expr, continue) || return expr :(@goto $label) end """ Function that replaces a variable `x` in an expression by `_fsmi.x` where `x` is a known slot. """ function transform_slots(expr, symbols) expr isa Expr || return expr expr.head === :let && return transform_slots_let(expr, symbols) for i in 1:length(expr.args) expr.head === :kw && i === 1 && continue expr.head === Symbol("quote") && continue expr.args[i] = expr.args[i] isa Symbol && expr.args[i] in symbols ? :(_fsmi.$(expr.args[i])) : expr.args[i] end expr end """ Function that handles `let` block """ function transform_slots_let(expr::Expr, symbols) @capture(expr, let vars_; body_ end) locals = Set{Symbol}() (isa(vars, Expr) && vars.head==:(=)) || error("@resumable currently supports only single variable declarations in let blocks, i.e. only let blocks exactly of the form `let i=j; ...; end`. If you need multiple variables, please submit an issue on the issue tracker and consider contributing a patch.") sym = vars.args[1].args[2].value push!(locals, sym) vars.args[1] = sym body = postwalk(x->transform_let(x, locals), :(begin $(body) end)) :(let $vars; $body end) end """ Function that replaces a variable `_fsmi.x` in an expression by `x` where `x` is a variable declared in a `let` block. """ function transform_let(expr, symbols::Set{Symbol}) expr isa Expr || return expr expr.head === :. || return expr expr = expr.args[2].value in symbols ? :($(expr.args[2].value)) : expr end """ Function that replaces a `arg = @yield ret` statement by ```julia @yield ret; arg = arg_ ``` where `arg_` is the argument of the function containing the expression. """ function transform_arg(expr) @capture(expr, arg_ = ex_) || return expr _is_yield(ex) || return expr ret = length(ex.args) > 2 ? ex.args[3:end] : [nothing] quote @yield $(ret...) $arg = _arg end end """ Function that replaces a `@yield ret` or `@yield` statement by ```julia @yield ret _arg isa Exception && throw(_arg) ``` to allow that an `Exception` can be thrown into a `@resumable function`. """ function transform_exc(expr) _is_yield(expr) || return expr ret = length(expr.args) > 2 ? expr.args[3:end] : [nothing] quote @yield $(ret...) _arg isa Exception && throw(_arg) end end """ Function that replaces a `try`-`catch`-`finally`-`end` expression having a top level `@yield` statement in the `try` part ```julia try before_statements... @yield ret after_statements... catch exc catch_statements... finally finally_statements... end ``` with a sequence of `try`-`catch`-`end` expressions: ```julia try before_statements... catch catch_statements... @goto _TRY_n end @yield ret try after_statements... catch catch_statements... end @label _TRY_n finally_statements... ``` """ function transform_try(expr, ui8::BoxedUInt8) @capture(expr, (try body_ catch exc_; handling_ end) | (try body_ catch exc_; handling_ finally always_ end)) || return expr ui8.n += one(UInt8) new_body = [] segment = [] for ex in body.args if _is_yield(ex) ret = length(ex.args) > 2 ? ex.args[3:end] : [nothing] exc === nothing ? push!(new_body, :(try $(segment...) catch; $(handling); @goto $(Symbol("_TRY_", :($(ui8.n)))) end)) : push!(new_body, :(try $(segment...) catch $exc; $(handling) ; @goto $(Symbol("_TRY_", :($(ui8.n)))) end)) push!(new_body, quote @yield $(ret...) end) segment = [] else push!(segment, ex) end end if segment != [] exc === nothing ? push!(new_body, :(try $(segment...) catch; $(handling) end)) : push!(new_body, :(try $(segment...) catch $exc; $(handling) end)) end push!(new_body, :(@label $(Symbol("_TRY_", :($(ui8.n)))))) always === nothing || push!(new_body, quote $(always) end) quote $(new_body...) end end """ Function that replaces a `@yield ret` or `@yield` statement with ```julia _fsmi._state = n return ret @label _STATE_n _fsmi._state = 0xff ``` """ function transform_yield(expr, ui8::BoxedUInt8) _is_yield(expr) || return expr ret = length(expr.args) > 2 ? expr.args[3:end] : [nothing] ui8.n += one(UInt8) quote _fsmi._state = $(ui8.n) return $(ret...) @label $(Symbol("_STATE_", :($(ui8.n)))) _fsmi._state = 0xff end end """ Function that replaces a `@yield ret` or `@yield` statement with ```julia Base.inferencebarrier(ret) ``` This version is used for inference only. It makes sure that `val = @yield ret` is inferred as `Any` rather than `typeof(ret)`. """ function transform_yield(expr) _is_yield(expr) || return expr ret = length(expr.args) > 2 ? expr.args[3:end] : [nothing] quote Base.inferencebarrier($(ret...)) end end """ Function returning whether an expression is a `@yield` macro """ _is_yield(ex) = false function _is_yield(ex::Expr) ex.head === :macrocall && ex.args[1] === Symbol("@yield") end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
799
""" Abstract type used as base type for the type created by the `@resumable` macro. """ abstract type FiniteStateMachineIterator{R} end """ Mutable struct that contains a single `UInt8`. """ mutable struct BoxedUInt8 n :: UInt8 end """ Implements the `iteratorsize` method of the *iterator* interface for a subtype of `FiniteStateMachineIterator`. """ Base.IteratorSize(::Type{T}) where T<:FiniteStateMachineIterator = Base.SizeUnknown() """ Implements the `eltype` method of the *iterator* interface for a subtype of `FiniteStateMachineIterator`. """ Base.eltype(::Type{T}) where T<:FiniteStateMachineIterator{R} where R = R function Base.iterate(fsm_iter::FiniteStateMachineIterator, state=nothing) result = fsm_iter() fsm_iter._state === 0xff && return nothing result, nothing end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
7749
""" Function returning the name of a where parameter """ function get_param_name(expr) :: Symbol @capture(expr, arg_<:arg_type_) && return arg @capture(expr, arg_) && return arg end """ Function returning the arguments of a function definition """ function get_args(func_def::Dict) arg_dict = Dict{Symbol, Any}() arg_list = Vector{Symbol}() kwarg_list = Vector{Symbol}() for arg in (func_def[:args]...,) arg_def = splitarg(arg) if arg_def[1] != nothing push!(arg_list, arg_def[1]) arg_dict[arg_def[1]] = arg_def[3] ? Any : arg_dict[arg_def[1]] = arg_def[2] end end for arg in (func_def[:kwargs]...,) arg_def = splitarg(arg) push!(kwarg_list, arg_def[1]) arg_dict[arg_def[1]] = arg_def[3] ? Any : arg_dict[arg_def[1]] = arg_def[2] end arg_list, kwarg_list, arg_dict end """ Takes a function definition and returns the expressions needed to forward the arguments to an inner function. For example `function foo(a, ::Int, c...; x, y=1, z...)` will 1. modify the function to `gensym()` nameless arguments 2. return `(:a, gensym(), :(c...)), (:x, :y, :(z...)))` """ function forward_args(func_def) args = [] map!(func_def[:args], func_def[:args]) do arg name, type, splat, default = splitarg(arg) name = something(name, gensym()) if splat push!(args, :($name...)) else push!(args, name) end combinearg(name, type, splat, default) end kwargs = [] for arg in func_def[:kwargs] name, type, splat, default = splitarg(arg) if splat push!(kwargs, :($name...)) else push!(kwargs, name) end end args, kwargs end const unused = (Symbol("#temp#"), Symbol("_"), Symbol(""), Symbol("#unused#"), Symbol("#self#")) """ Function returning the slots of a function definition """ function get_slots(func_def::Dict, args::Dict{Symbol, Any}, mod::Module) slots = Dict{Symbol, Any}() func_def[:name] = gensym() func_def[:args] = (func_def[:args]..., func_def[:kwargs]...) func_def[:kwargs] = [] # replace yield with inference barrier func_def[:body] = postwalk(transform_yield, func_def[:body]) # collect items to skip nosaves = Set{Symbol}() func_def[:body] = postwalk(x->transform_nosave(x, nosaves), func_def[:body]) # eval function func_expr = combinedef(func_def) |> flatten @eval(mod, @noinline $func_expr) # get typed code codeinfos = @eval(mod, code_typed($(func_def[:name]), Tuple; optimize=false)) # extract slot names and types for codeinfo in codeinfos for (name, type) in collect(zip(codeinfo.first.slotnames, codeinfo.first.slottypes)) name βˆ‰ nosaves && name βˆ‰ unused && (slots[name] = Union{type, get(slots, name, Union{})}) end end # remove `catch exc` statements postwalk(x->remove_catch_exc(x, slots), func_def[:body]) # set error branches to Any for (key, val) in slots if val === Union{} slots[key] = Any end end return func_def[:name], slots end """ Function removing the `exc` symbol of a `catch exc` statement of a list of slots. """ function remove_catch_exc(expr, slots::Dict{Symbol, Any}) @capture(expr, (try body__ catch exc_; handling__ end) | (try body__ catch exc_; handling__ finally always__ end)) && delete!(slots, exc) expr end struct IteratorReturn{T} value :: T IteratorReturn(value) = new{typeof(value)}(value) end @inline function generate(fsm_iter::FiniteStateMachineIterator, send, state=nothing) #fsm_iter._state = state result = fsm_iter(send) fsm_iter._state === 0xff && return IteratorReturn(result) result, nothing end @inline function generate(iter, _) ret = iterate(iter) isnothing(ret) && return IteratorReturn(nothing) ret end @inline function generate(iter, _, state) ret = iterate(iter, state) isnothing(ret) && return IteratorReturn(nothing) ret end # this is similar to code_typed but it considers the world age function code_typed_by_type(@nospecialize(tt::Type); optimize::Bool=true, world::UInt=Base.get_world_counter(), interp::Core.Compiler.AbstractInterpreter=Core.Compiler.NativeInterpreter(world)) tt = Base.to_tuple_type(tt) # look up the method match, valid_worlds = Core.Compiler.findsup(tt, Core.Compiler.InternalMethodTable(world)) # run inference, normally not allowed in generated functions frame = Core.Compiler.typeinf_frame(interp, match.method, match.spec_types, match.sparams, optimize) frame === nothing && error("inference failed") valid_worlds = Core.Compiler.intersect(valid_worlds, frame.valid_worlds) return frame.linfo, frame.src, valid_worlds end function fsmi_generator(world::UInt, source::LineNumberNode, passtype, fsmitype::Type{Type{T}}, fargtypes) where T @nospecialize # get typed code of the inference function evaluated in get_slots # but this time with concrete argument types tt = Base.to_tuple_type(fargtypes) mi, ci, valid_worlds = try code_typed_by_type(tt; world, optimize=false) catch err # inference failed, return generic type @safe_warn "Inference of a @resumable function failed -- a slower fallback will be used and everything will still work, however please consider reporting this to the developers of ResumableFunctions.jl so that we can debug and increase performance" @safe_warn "The error was $err" slots = fieldtypes(T)[2:end] stub = Core.GeneratedFunctionStub(identity, Core.svec(:pass, :fsmi, :fargs), Core.svec()) if isempty(slots) return stub(world, source, :(return $T())) else return stub(world, source, :(return $T{$(slots...)}())) end end min_world = valid_worlds.min_world max_world = valid_worlds.max_world # extract slot types cislots = Dict{Symbol, Any}() for (name, type) in collect(zip(ci.slotnames, ci.slottypes)) # take care to widen types that are unstable or Const type = Core.Compiler.widenconst(type) cislots[name] = Union{type, get(cislots, name, Union{})} end slots = map(slot->get(cislots, slot, Any), fieldnames(T)[2:end]) # generate code to instantiate the concrete type stub = Core.GeneratedFunctionStub(identity, Core.svec(:pass, :fsmi, :fargs), Core.svec()) if isempty(slots) exprs = stub(world, source, :(return $T())) else exprs = stub(world, source, :(return $T{$(slots...)}())) end # lower codeinfo to pass world age and invalidation edges ci = ccall(:jl_expand_and_resolve, Any, (Any, Any, Any), exprs, passtype.name.module, Core.svec()) ci.min_world = min_world ci.max_world = max_world ci.edges = Core.MethodInstance[mi] if isdefined(Base, :__has_internal_change) && Base.__has_internal_change(v"1.12-alpha", :codeinfonargs) # due to julia#54341 ci.nargs = 3 ci.isva = true end return ci end # JuliaLang/julia#48611: world age is exposed to generated functions, and should be used if VERSION >= v"1.10.0-DEV.873" # This is like @generated, but it receives the world age of the caller # which we need to do inference safely and correctly @eval function typed_fsmi(fsmi, fargs...) $(Expr(:meta, :generated_only)) $(Expr(:meta, :generated, fsmi_generator)) end else # runtime fallback function that uses the fallback constructor with generic slot types function typed_fsmi(fsmi::Type{T}, fargs...)::T where T return typed_fsmi_fallback(fsmi, fargs...) end end # a fallback function that uses the fallback constructor with generic slot types -- useful for older versions of Julia or for situations where our current custom inference struggles function typed_fsmi_fallback(fsmi::Type{T}, fargs...)::T where T return T() end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
881
using ResumableFunctions using Test using SafeTestsets function doset(descr) if length(ARGS) == 0 return true end for a in ARGS if occursin(lowercase(a), lowercase(descr)) return true end end return false end macro doset(descr) quote if doset($descr) @safetestset $descr begin include("test_"*$descr*".jl") end end end end println("Starting tests with $(Threads.nthreads()) threads out of `Sys.CPU_THREADS = $(Sys.CPU_THREADS)`...") @doset "main" @doset "yieldfrom" @doset "typeparams" @doset "repeated_variable" @doset "inference_recursive_calls" @doset "selfreferencing_functional" @doset "coverage_preservation" @doset "performance" VERSION >= v"1.8" && @doset "doctests" VERSION >= v"1.8" && @doset "aqua" get(ENV,"JET_TEST","")=="true" && @doset "jet"
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
71
using Aqua using ResumableFunctions Aqua.test_all(ResumableFunctions)
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
872
using ResumableFunctions using Test using MacroTools: postwalk before = :(function f(arg, arg2::Int) @yield arg for i in 1:10 let i=i @yield arg2 arg2 = arg2 + i end end while true try @yield arg2 arg2 = arg2 + 1 catch e @yield e arg2 = arg2 + 1 end break end arg2+arg @yield arg2 end ) after = eval(quote @macroexpand @resumable $before end) function get_all_linenodes(expr) nodes = Set() postwalk(expr) do x if x isa LineNumberNode push!(nodes, x) end x end return nodes end @testset "all line numbers are preserved" begin @test get_all_linenodes(before) βŠ† get_all_linenodes(after) end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
209
using Documenter using ResumableFunctions @testset "Doctests" begin DocMeta.setdocmeta!(ResumableFunctions, :DocTestSetup, :(using ResumableFunctions); recursive=true) doctest(ResumableFunctions) end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1252
using Test using ResumableFunctions ## @resumable function rec1(a::Int)::Int @yield a if a > 0 for i in rec1(a-1) @yield i end end end @test collect(rec1(4)) isa Vector{Int} @test collect(rec1(4)) == 4:-1:0 ## @resumable function rec2(a::Int)::Any @yield a if a > 0 for i in rec2(a-1) @yield i end end end @test collect(rec2(4)) isa Vector{Any} @test collect(rec2(4)) == 4:-1:0 ## @resumable function rec3(a) @yield a if a > 0 for i in rec3(a-1) @yield i end end end @test collect(rec3(4)) isa Vector{Any} @test collect(rec3(4)) == 4:-1:0 ## # From issue #80 @resumable function rf!(a::Vector{Int}, i::Integer, n::Integer)::Vector{Int} if i > n @yield a return end a[i] = 0 for _ in rf!(a, i+1, n) @yield a end for k = i+1:n a[i] = k a[k] = i for _ in rf!(a, i+1, k-1) for _ in rf!(a, k+1, n) @yield a end end end end const n = 3 const a = zeros(Int, n) collect(rf!(a, 1, n)) == [[3, 0, 1], [3, 0, 1], [3, 0, 1], [3, 0, 1]]
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1001
using ResumableFunctions using JET using Test using JET: ReportPass, BasicPass, InferenceErrorReport, UncaughtExceptionReport # Custom report pass that ignores `UncaughtExceptionReport` # Too coarse currently, but it serves to ignore the various # "may throw" messages for runtime errors we raise on purpose # (mostly on malformed user input) struct MayThrowIsOk <: ReportPass end # ignores `UncaughtExceptionReport` analyzed by `JETAnalyzer` (::MayThrowIsOk)(::Type{UncaughtExceptionReport}, @nospecialize(_...)) = return # forward to `BasicPass` for everything else function (::MayThrowIsOk)(report_type::Type{<:InferenceErrorReport}, @nospecialize(args...)) BasicPass()(report_type, args...) end @testset "JET checks" begin rep = report_package("ResumableFunctions"; report_pass=MayThrowIsOk(), ignored_modules=( Core.Compiler, ) ) @show rep @test length(JET.get_reports(rep)) <= 6 @test_broken length(JET.get_reports(rep)) == 0 end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
5269
using ResumableFunctions using Test @resumable function test_for(a::Int=0; b::Int=a+1) :: Int for i in 1:10 @yield a a, b = b, a+b end end @testset "test_for" begin @test collect(test_for(4)) == [4, 5, 9, 14, 23, 37, 60, 97, 157, 254] end @resumable function test_try(io) try a = 1 @yield a a = 2 c = @yield a println(io,c) catch except println(io,except) finally println(io,"Always") end end struct SpecialException <: Exception end @testset "test_try" begin io = IOBuffer() try_me = test_try(io) try_me() try_me(SpecialException()) @test endswith(String(take!(copy(io))), "SpecialException()\nAlways\n") io = IOBuffer() try_me = test_try(io) try_me() try_me() try_me("Hello") @test String(take!(copy(io))) == "Hello\nAlways\n" io = IOBuffer() try_me = test_try(io) try_me() try_me() try_me(SpecialException()) @test_throws ErrorException try_me() @test endswith(String(take!(copy(io))), "SpecialException()\nAlways\n") end @resumable function (test_where1(a::N) :: N) where {N<:Number} b = a + one(N) for i in 1:10 @yield a a, b = b, a+b end end @resumable function (test_where2(a::N=4; b::N=a + one(N)) :: N) where N for i in 1:10 @yield a a, b = b, a+b end end @testset "test_where" begin @test collect(test_where1(4.0)) == [4.0, 5.0, 9.0, 14.0, 23.0, 37.0, 60.0, 97.0, 157.0, 254.0] @test collect(test_where2(4)) == [4, 5, 9, 14, 23, 37, 60, 97, 157, 254] end @resumable function test_varargs(a...) for (i, e) in enumerate(a) @yield e end end @testset "test_varargs" begin @test collect(test_varargs(1, 2, 3)) == [1, 2, 3] end @resumable function test_let() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i=i val = [a[i] for a in u] end @yield val end end end @testset "test_let" begin @test collect(test_let()) == [[1,3],[2,4],[5,7],[6,8]] end if VERSION >= v"1.8" q_test_let2 = quote @resumable function test_let2() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i=i, j=i val = [(a[i],a[j]) for a in u] end @yield val end end end end @testset "test_let2" begin #@test collect(test_let2()) == ... @test_throws "@resumable currently supports only single" eval(q_test_let2) @test_broken false # the test above throws an error when it should not -- it happens because we do not support variables without assignments in let blocks -- see issues #69 and #70 end q_test_let_noassignment = quote @resumable function test_let_noassignment() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i val = [a[1] for a in u] end @yield val end end end end @testset "test_let_noassignment" begin #@test collect(test_let_noassignment()) == ... @test_throws "@resumable currently supports only single" eval(q_test_let_noassignment) @test_broken false # the test above throws an error when it should not -- it happens because we do not support variables without assignments in let blocks -- see issues #69 and #70 end q_test_let_multipleargs = quote @resumable function test_let_multipleargs() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i=i, j val = [a[i] for a in u] end @yield val end end end end @testset "test_let_multipleargs" begin #@test collect(test_let_multipleargs()) == ... @test_throws "@resumable currently supports only single" eval(q_test_let_noassignment) @test_broken false # the test above throws an error when it should not -- it happens because we do not support variables without assignments in let blocks -- see issues #69 and #70 end end # VERSION >= v"1.8" @resumable function test_nosave() for i in 65:74 @nosave tmp = Char(i) @yield tmp end end @testset "test_nosave" begin @test collect(test_nosave()) == ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] end @resumable function test_return_value() return 1 end @testset "test_return_value" begin @test collect(test_return_value()) == [] end @resumable function test_continue() for i in 1:10 if i === 2 continue end @yield i end end @resumable function test_continue_double() for i in 1:3 if i === 2 continue end for j in 1:3 if j === 2 continue end @yield j end end end @testset "test_continue" begin @test collect(test_continue()) == [1, 3, 4, 5, 6, 7, 8, 9, 10] @test collect(test_continue_double()) == [1, 3, 1, 3] end """docstring""" @resumable function fwithdoc() @yield 1 end """docstring""" function gwithdoc() return 1 end @testset "test_docstring" begin @test (@doc fwithdoc) == (@doc gwithdoc) end @resumable function test_unstable(a::Int) for i in 1:a a = "number $i" @yield a end end @testset "test_unstable" begin @test collect(test_unstable(3)) == ["number 1", "number 2", "number 3"] end # test length @testset "test_length" begin @resumable length=n^2*m^2 function test_length(n, m) for i in 1:n^2 for j in 1:m^2 @yield i + j end end end @test length(test_length(10, 20)) === 10^2 * 20^2 @test length(collect(test_length(10, 20))) === 10^2 * 20^2 @test Base.IteratorSize(typeof(test_length(1, 1))) == Base.HasLength() end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
630
using ResumableFunctions using Test @resumable function fibonacci_resumable(n::Int) a, b = zero(Int), one(Int) for _ in 1:n @yield a a, b = b, a + b end end @noinline function test_resumable(n::Int) a = 0 for v in fibonacci_resumable(n) a = v end a end @test (@allocated test_resumable(80))==0 @resumable function cumsum(iter) acc = zero(eltype(iter)) for i in iter acc += i @yield acc end end # versions that support generating inferred code if VERSION >= v"1.10.0-DEV.873" cs = cumsum(1:1000) @allocated cs() # shake out the compilation overhead @test (@allocated cs())==0 end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
981
using Test using ResumableFunctions # From issue #86 ## @resumable function singleton()::String @yield "anything" end # 1. must be defined before combined! @resumable function _empty(x)::String end @resumable function combined()::String for s in singleton() @yield s # fails "here" because s is determined to be of type Nothing because of the second loop end # 2. must reuse of variable for s in _empty(1) # dummy argument needed to illustrate point 1. @yield s end end @test collect(combined()) == ["anything"] @test collect(combined()) isa Vector{String} ## @resumable function singletonF()::String @yield "anything" end @resumable function _emptyF()::String end @resumable function combinedF()::String # @yieldfrom also uses the same variable names for each generated loop @yieldfrom singletonF() @yieldfrom _emptyF() end @test collect(combinedF()) == ["anything"] @test collect(combinedF()) isa Vector{String}
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
197
using Test using ResumableFunctions struct A a::Int end; @resumable function (fa::A)(b::Int) @yield b+fa.a end @test collect(A(1)(2)) == [3] @test_broken collect(A(1)(2)) isa Vector{Int}
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1311
using ResumableFunctions using Test @resumable function test_type_parameters(::Type{Int}, start::Int) for i in start:start+3 @yield i end end @resumable function test_type_parameters(::Type{Float64}, start::Int) for i in start:start+3 @yield float(i) end end @testset "test_type_parameters" begin @test collect(test_type_parameters(Int, 1)) == [1, 2, 3, 4] @test collect(test_type_parameters(Float64, 1)) == [1.0, 2.0, 3.0, 4.0] end @resumable function test_type_parameters_order(start::Int, ::Type{T})::T where {T} for i in start:start+3 @yield T(i) end end @testset "test_type_parameters_order" begin @test collect(test_type_parameters_order(1, Int)) == [1, 2, 3, 4] @test collect(test_type_parameters_order(1, Float64)) == [1.0, 2.0, 3.0, 4.0] @test typeof(first(test_type_parameters_order(1, ComplexF32))) == ComplexF32 end @resumable function test_type_parameters_optional(start::Int; t::Type{T}=Type{Int})::T where {T} for i in start:start+3 @yield T(i) end end @testset "test_type_parameters_optional" begin @test collect(test_type_parameters_optional(1, t=Int)) == [1, 2, 3, 4] @test collect(test_type_parameters_optional(1, t=Float64)) == [1.0, 2.0, 3.0, 4.0] @test typeof(first(test_type_parameters_optional(1, t=ComplexF32))) == ComplexF32 end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
code
1045
using Test using ResumableFunctions @resumable function test_yieldfrom_inner(n) for i in 1:n @yield i^2 end 42, n end @resumable function test_yieldfrom(n) @yieldfrom [42, 314] m, n = @yieldfrom test_yieldfrom_inner(n) @test m == 42 @yield n @yieldfrom test_yieldfrom_inner(n+1) end @testset "test_yieldfrom" begin @test collect(test_yieldfrom(4)) == [42, 314, 1, 4, 9, 16, 4, 1, 4, 9, 16, 25] end @resumable function test_echo() x = 0 while true x = @yield x end return "Done" end @resumable function test_forward() ret = @yieldfrom test_echo() @test ret == "Done" @yieldfrom test_echo() end @testset "test_yieldfrom_twoway" begin forward = test_forward() @test forward() == 0 for i in 1:5 @test forward(i) == i end end @testset "test_yieldfrom_nonresumable" begin @test_throws LoadError eval(:(@yieldfrom [1,2,3])) end @testset "test_yieldfrom_noargs" begin test_f = :(@resumable function test_yieldfrom_noargs() @yieldfrom end) @test_throws LoadError eval(test_f) end
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
3280
# News ## v0.6.10 - 2024-09-08 - Add `length` support by allowing `@resumable length=ex function [...]` - Adjust to an internal changes in Julia 1.12 (see julia#54341). ## v0.6.9 - 2024-02-13 - Self-referencing functionals (callable structs) are now supported as resumable functions, e.g. `@resumable (f::A)() @yield f.property end`. ## v0.6.8 - 2024-02-11 - Redeploy the improved performance from v0.6.6 without the issues that caused them to be reverted in v0.6.7. The issue stemmed from lack of support for recursive resumable functions in the v0.6.6 improvements. - Significant additions to the CI and testing of the package to avoid such issues in the future. ## v0.6.7 - 2024-01-02 - Fix stack overflow errors by reverting the changes introduced in v0.6.6. ## v0.6.6 - 2023-10-08 - Significantly improved performance on Julia 1.10 and newer by more precise inference of slot types. ## v0.6.5 - 2023-09-06 - Fix to a performance regression originally introduced by `@yieldfrom`. ## v0.6.4 - 2023-08-08 - Docstrings now work with `@resumable` functions. - Generated types in `@resumable` functions have clearer names for better debugging. - Line-number nodes are preserved in `@resumable` functions for better debugging and code coverage. ## Changelog before moving to JuliaDynamics * 2023: v0.6.3 * Julia 1.6 or newer is required * introduction of `@yieldfrom` to delegate to another resumable function or iterator (similar to [Python's `yield from`](https://peps.python.org/pep-0380/)) * resumable functions are now allowed to return values, so that `r = @yieldfrom f` also stores the return value of `f` in `r` * 2023: v0.6.2 * Julia v1.10 compatibility fix * resumable functions can now dispatch on types * 2021: v0.6.1 * `continue` in loop works * 2021: v0.6.0 * introduction of `@nosave` to keep a variable out of the saved structure. * optimized `for` loop. * 2020: v0.5.2 is Julia v1.6 compatible. * 2019: v0.5.1 * inference problem solved: force iterator next value to be of type `Union` of `Tuple` and `Nothing`. * 2019: v0.5.0 is Julia v1.2 compatible. * 2018: v0.4.2 prepare for Julia v1.1 * better inference caused a problem;). * iterator with a specified `rtype` is fixed. * 2018: v0.4.0 is Julia v1.0 compatible. * 2018: v0.3.1 uses the new iteration protocol. * the new iteration protocol is used for a `@resumable function` based iterator. * the `for` loop transformation implements also the new iteration protocol. * 2018: v0.3 is Julia v0.7 compatible. * introduction of `let` block to allow variables not te be persisted between `@resumable function` calls (EXPERIMENTAL). * the `eltype` of a `@resumable function` based iterator is its return type if specified, otherwise `Any`. * 2018: v0.2 the iterator now behaves as a Python generator: only values that are explicitly yielded are generated; the return value is ignored and a warning is generated. * 2017: v0.1 initial release that is Julia v0.6 compatible: * Introduction of the `@resumable` and the `@yield` macros. * A `@resumable function` generates a type that implements the [iterator](https://docs.julialang.org/en/stable/manual/interfaces/#man-interface-iteration-1) interface. * Parametric `@resumable functions` are supported.
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
5503
# ResumableFunctions <table> <tr> <td>Documentation</td> <td> <a href="https://juliadynamics.github.io/ResumableFunctions.jl/stable"><img src="https://img.shields.io/badge/docs-stable-blue.svg" alt="Documentation of latest stable version"></a> <a href="https://juliadynamics.github.io/ResumableFunctions.jl/dev"><img src="https://img.shields.io/badge/docs-dev-blue.svg" alt="Documentation of dev version"></a> </td> </tr><tr></tr> <tr> <td>Continuous integration</td> <td> <a href="https://github.com/JuliaDynamics/ResumableFunctions.jl/actions?query=workflow%3ACI+branch%3Amaster"><img src="https://img.shields.io/github/actions/workflow/status/JuliaDynamics/ResumableFunctions.jl/ci.yml?branch=master" alt="GitHub Workflow Status"></a> </td> </tr><tr></tr> <tr> <td>Code coverage</td> <td> <a href="https://codecov.io/gh/JuliaDynamics/ResumableFunctions.jl"><img src="https://img.shields.io/codecov/c/gh/JuliaDynamics/ResumableFunctions.jl?label=codecov" alt="Test coverage from codecov"></a> </td> </tr><tr></tr> <tr> <td>Static analysis with</td> <td> <a href="https://github.com/aviatesk/JET.jl"><img src="https://img.shields.io/badge/%F0%9F%9B%A9%EF%B8%8F_tested_with-JET.jl-233f9a" alt="JET static analysis"></a> <a href="https://github.com/JuliaTesting/Aqua.jl"><img src="https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg" alt="Aqua QA"></a> </td> </tr> </table> [![status](http://joss.theoj.org/papers/889b2faed426b978ee705689c8f8440b/status.svg)](http://joss.theoj.org/papers/889b2faed426b978ee705689c8f8440b) [![DOI](https://zenodo.org/badge/100050892.svg)](https://zenodo.org/badge/latestdoi/100050892) [C#](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/) has a convenient way to create iterators using the `yield return` statement. The package `ResumableFunctions` provides the same functionality for the [Julia language](https://julialang.org) by introducing the `@resumable` and the `@yield` macros. These macros can be used to replace the `Task` switching functions `produce` and `consume` which were deprecated in Julia v0.6. `Channels` are the preferred way for inter-task communication in julia v0.6+, but their performance is subpar for iterator applications. See [the benchmarks section below](#Benchmarks). ## Installation `ResumableFunctions` is a [registered package](http://pkg.julialang.org) and can be installed by running: ```julia using Pkg Pkg.add("ResumableFunctions") ``` ## Example ```julia using ResumableFunctions @resumable function fibonacci(n::Int) :: Int a = 0 b = 1 for i in 1:n @yield a a, b = b, a+b end end for fib in fibonacci(10) println(fib) end # Example with specifies the length using ResumableFunctions @resumable length=n^2 function fibonacci(n::Int) :: Int a = 0 b = 1 for i in 1:n^2 @yield a a, b = b, a+b end end for fib in fibonacci(5) println(fib) end ``` ## Benchmarks The following block is the result of running `julia --project=. benchmark/benchmarks.jl` on a Macbook Pro with following processor: `Intel Core i9 2.4 GHz 8-Core`. Julia version 1.5.3 was used. Fibonacci with `Int` values: ``` Direct: 27.184 ns (0 allocations: 0 bytes) ResumableFunctions: 27.503 ns (0 allocations: 0 bytes) Channels csize=0: 2.438 ms (101 allocations: 3.08 KiB) Channels csize=1: 2.546 ms (23 allocations: 1.88 KiB) Channels csize=20: 138.681 ΞΌs (26 allocations: 2.36 KiB) Channels csize=100: 35.071 ΞΌs (28 allocations: 3.95 KiB) Task scheduling 17.726 ΞΌs (86 allocations: 3.31 KiB) Closure: 1.948 ΞΌs (82 allocations: 1.28 KiB) Closure optimised: 25.910 ns (0 allocations: 0 bytes) Closure statemachine: 28.048 ns (0 allocations: 0 bytes) Iteration protocol: 41.143 ns (0 allocations: 0 bytes) ``` Fibonacci with `BigInt` values: ``` Direct: 5.747 ΞΌs (188 allocations: 4.39 KiB) ResumableFunctions: 5.984 ΞΌs (191 allocations: 4.50 KiB) Channels csize=0: 2.508 ms (306 allocations: 7.75 KiB) Channels csize=1: 2.629 ms (306 allocations: 7.77 KiB) Channels csize=20: 150.274 ΞΌs (309 allocations: 8.25 KiB) Channels csize=100: 44.592 ΞΌs (311 allocations: 9.84 KiB) Task scheduling 24.802 ΞΌs (198 allocations: 6.61 KiB) Closure: 7.064 ΞΌs (192 allocations: 4.47 KiB) Closure optimised: 5.809 ΞΌs (190 allocations: 4.44 KiB) Closure statemachine: 5.826 ΞΌs (190 allocations: 4.44 KiB) Iteration protocol: 5.822 ΞΌs (190 allocations: 4.44 KiB) ``` ## Authors * Ben Lauwens, [Royal Military Academy](http://www.rma.ac.be), Brussels, Belgium. * JuliaDynamics and QuantumSavory volunteers. ## Contributing * To discuss problems or feature requests, file an issue. For bugs, please include as much information as possible, including operating system, julia version, and version of [MacroTools](https://github.com/MikeInnes/MacroTools.jl.git). * To contribute, make a pull request. Contributions should include tests for any new features/bug fixes. ## Release Notes A [detailed change log is kept](https://github.com/JuliaDynamics/ResumableFunctions.jl/blob/master/CHANGELOG.md). ## Caveats * In a `try` block only top level `@yield` statements are allowed. * In a `finally` block a `@yield` statement is not allowed. * An anonymous function can not contain a `@yield` statement. * Many more restrictions.
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
1101
# ResumableFunctions C# style generators a.k.a. semi-coroutines for Julia. C# has a convenient way to create iterators using the `yield return` statement. The package `ResumableFunctions` provides the same functionality for the Julia language by introducing the `@resumable` and the `@yield` macros. These macros can be used to replace the `Task` switching functions `produce` and `consume` which were deprecated in Julia v0.6. `Channels` are the preferred way for inter-task communication in julia v0.6+, but their performance is subpar for iterator applications. ## Example ```jldoctest using ResumableFunctions @resumable function fibonacci(n::Int) a = 0 b = 1 for i in 1:n @yield a a, b = b, a+b end end for val in fibonacci(10) println(val) end # output 0 1 1 2 3 5 8 13 21 34 ``` ## Installation `ResumableFunctions` is a registered package and can be installed by running: ```julia Pkg.add("ResumableFunctions") ``` ## Authors * Ben Lauwens, Royal Military Academy, Brussels, Belgium. ## License `ResumableFunctions` is licensed under the MIT "Expat" License.
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
6092
# Internals The macro `@resumable` transform a function definition into a finite state-machine, i.e. a callable type holding the state and references to the internal variables of the function and a constructor for this new type respecting the method signature of the original function definition. When calling the new type a modified version of the body of the original function definition is executed: - a dispatch mechanism is inserted at the start to allow a non local jump to a label inside the body; - the `@yield` statement is replaced by a `return` statement and a label placeholder as endpoint of a non local jump; - `for` loops are transformed in `while` loops and - `try`-`catch`-`finally`-`end` expressions are converted in a sequence of `try`-`catch`-`end` expressions with at the end of the `catch` part a non local jump to a label that marks the beginning of the expressions in the `finally` part. The two last transformations are needed to overcome the limitations of the non local jump macros `@goto` and `@label`. The complete procedure is explained using the following example: ```julia @resumable function fibonacci(n::Int) a = 0 b = 1 for i in 1:n-1 @yield a a, b = b, a + b end a end ``` ## Split the definition The function definition is split by `MacroTools.splitdef` in different parts, eg. `:name`, `:body`, `:args`, ... ## For loops `for` loops in the body of the function definition are transformed in equivalent while loops: ```julia begin a = 0 b = 1 _iter = 1:n-1 _iterstate = start(_iter) while !done(_iter, _iterstate) i, _iterstate = next(_iter, _iterstate) @yield a a, b = b, a + b end a end ``` ## Slots The slots and their types in the function definition are recovered by running the `code_typed` function for the locally evaluated function definition: ```julia n :: Int64 a :: Int64 b :: Int64 _iter :: UnitRange{Int64} _iterstate :: Int64 i :: Int64 ``` ## Type definition A `mutable struct` is defined containing the state and the slots: ```julia mutable struct ##123 <: ResumableFunctions.FiniteStateMachineIterator _state :: UInt8 n :: Int64 a :: Int64 b :: Int64 _iter :: UnitRange{Int64} _iterstate :: Int64 i :: Int64 function ##123() fsmi = new() fsmi._state = 0x00 fsmi end end ``` ## Call definition A call function is constructed that creates the previously defined composite type. This function satisfy the calling convention of the original function definition and is returned from the macro: ```julia function fibonacci(n::Int) fsmi = ##123(n) fsmi.n = n fsmi end ``` ## Transformation of the body In 6 steps the body of the function definition is transformed into a finite state-machine. ### Renaming of slots The slots are replaced by references to the fields of the composite type: ```julia begin _fsmi.a = 0 _fsmi.b = 1 _fsmi._iter = 1:n-1 _fsmi._iterstate = start(_fsmi._iter) while !done(_fsmi._iter, _fsmi._iterstate) _fsmi.i, _fsmi._iterstate = next(_fsmi._iter, _fsmi._iterstate) @yield _fsmi.a _fsmi.a, _fsmi.b = _fsmi.b, _fsmi.a + _fsmi.b end _fsmi.a end ``` ### Two-way communication All expressions of the form `_fsmi.arg = @yield` are transformed into: ```julia @yield _fsmi.arg = _arg ``` ### Exception handling Exception handling is added to `@yield`: ```julia begin _fsmi.a = 0 _fsmi.b = 1 _fsmi._iter = 1:n-1 _fsmi._iterstate = start(_fsmi._iter) while !done(_fsmi._iter, _fsmi._iterstate) _fsmi.i, _fsmi._iterstate = next(_fsmi._iter, _fsmi._iterstate) @yield _fsmi.a _arg isa Exception && throw(_arg) _fsmi.a, _fsmi.b = _fsmi.b, _fsmi.a + _fsmi.b end _fsmi.a end ``` ### Try catch finally end block handling `try`-`catch`-`finally`-`end` expressions are converted in a sequence of `try`-`catch`-`end` expressions with at the end of the `catch` part a non local jump to a label that marks the beginning of the expressions in the `finally` part. ### Yield transformation The `@yield` statement is replaced by a `return` statement and a label placeholder as endpoint of a non local jump: ```julia begin _fsmi.a = 0 _fsmi.b = 1 _fsmi._iter = 1:n-1 _fsmi._iterstate = start(_fsmi._iter) while !done(_fsmi._iter, _fsmi._iterstate) _fsmi.i, _fsmi._iterstate = next(_fsmi._iter, _fsmi._iterstate) _fsmi._state = 0x01 return _fsmi.a @label _STATE_1 _fsmi._state = 0xff _arg isa Exception && throw(_arg) _fsmi.a, _fsmi.b = _fsmi.b, _fsmi.a + _fsmi.b end _fsmi.a end ``` ### Dispatch mechanism A dispatch mechanism is inserted at the start of the body to allow a non local jump to a label inside the body: ```julia begin _fsmi_state == 0x00 && @goto _STATE_0 _fsmi_state == 0x01 && @goto _STATE_1 error("@resumable function has stopped!") @label _STATE_0 _fsmi._state = 0xff _arg isa Exception && throw(_arg) _fsmi.a = 0 _fsmi.b = 1 _fsmi._iter = 1:n-1 _fsmi._iterstate = start(_fsmi._iter) while !done(_fsmi._iter, _fsmi._iterstate) _fsmi.i, _fsmi._iterstate = next(_fsmi._iter, _fsmi._iterstate) _fsmi._state = 0x01 return _fsmi.a @label _STATE_1 _fsmi._state = 0xff _arg isa Exception && throw(_arg) _fsmi.a, _fsmi.b = _fsmi.b, _fsmi.a + _fsmi.b end _fsmi.a end ``` ## Making the type callable A function is defined with one argument `_arg`: ```julia function (_fsmi::##123)(_arg::Any=nothing) _fsmi_state == 0x00 && @goto _STATE_0 _fsmi_state == 0x01 && @goto _STATE_1 error("@resumable function has stopped!") @label _STATE_0 _fsmi._state = 0xff _arg isa Exception && throw(_arg) _fsmi.a = 0 _fsmi.b = 1 _fsmi._iter = 1:n-1 _fsmi._iterstate = start(_fsmi._iter) while !done(_fsmi._iter, _fsmi._iterstate) _fsmi.i, _fsmi._iterstate = next(_fsmi._iter, _fsmi._iterstate) _fsmi._state = 0x01 return _fsmi.a @label _STATE_1 _fsmi._state = 0xff _arg isa Exception && throw(_arg) _fsmi.a, _fsmi.b = _fsmi.b, _fsmi.a + _fsmi.b end _fsmi.a end ```
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
173
# Library ## Public interface ```@autodocs Modules = [ResumableFunctions] Private = false ``` ## Internals ```@autodocs Modules = [ResumableFunctions] Public = false ```
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
6055
# Manual ## Basic usage When a `@resumable function` is called, it continues where it left during the previous invocation: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function basic_example() @yield "Initial call" @yield "Second call" "Final call" end end ``` ```julia @resumable function basic_example() @yield "Initial call" @yield "Second call" "Final call" end ``` ```jldoctest julia> basic_iterator = basic_example(); julia> basic_iterator() "Initial call" julia> basic_iterator() "Second call" julia> basic_iterator() "Final call" ``` ```@meta DocTestSetup = nothing ``` The `@yield` can also be used without a return argument: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function basic_example() @yield "Initial call" @yield "Final call" end end ``` ```julia @resumable function basic_example() @yield "Initial call" @yield "Final call" end ``` ```jldoctest julia> basic_iterator = basic_example(); julia> basic_iterator() "Initial call" julia> basic_iterator() julia> basic_iterator() "Final call" ``` ```@meta DocTestSetup = nothing ``` The famous fibonacci sequence can easily be generated: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function fibonacci() a = 0 b = 1 while true @yield a a, b = b, a + b end end end ``` ```julia @resumable function fibonacci() a = 0 b = 1 while true @yield a a, b = b, a + b end end ``` ```jldoctest julia> fib_iterator = fibonacci(); julia> fib_iterator() 0 julia> fib_iterator() 1 julia> fib_iterator() 1 julia> fib_iterator() 2 julia> fib_iterator() 3 julia> fib_iterator() 5 julia> fib_iterator() 8 ``` ```@meta DocTestSetup = nothing ``` The `@resumable function` can take arguments and the type of the return value can be specified: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function fibonacci(n) :: Int a = 0 b = 1 for i in 1:n @yield a a, b = b, a + b end end end ``` ```julia @resumable function fibonacci(n) :: Int a = 0 b = 1 for i in 1:n @yield a a, b = b, a + b end end ``` ```jldoctest julia> fib_iterator = fibonacci(4); julia> fib_iterator() 0 julia> fib_iterator() 1 julia> fib_iterator() 1 julia> fib_iterator() 2 julia> fib_iterator() julia> fib_iterator() ERROR: @resumable function has stopped! ``` ```@meta DocTestSetup = nothing ``` When the `@resumable function` returns normally an error will be thrown if called again. ## Two-way communication The caller can transmit a variable to the `@resumable function` by assigning a `@yield` statement to a variable: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function two_way() name = @yield "Who are you?" "Hello, " * name * "!" end end ``` ```julia @resumable function two_way() name = @yield "Who are you?" "Hello, " * name * "!" end ``` ```jldoctest julia> hello = two_way(); julia> hello() "Who are you?" julia> hello("Ben") "Hello, Ben!" ``` ```@meta DocTestSetup = nothing ``` When an `Exception` is passed to the `@resumable function`, it is thrown at the resume point: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function mouse() try @yield "Here I am!" catch exc return "You got me!" end end struct Cat <: Exception end end ``` ```julia @resumable function mouse() try @yield "Here I am!" catch exc return "You got me!" end end struct Cat <: Exception end ``` ```jldoctest julia> catch_me = mouse(); julia> catch_me() "Here I am!" julia> catch_me(Cat()) "You got me!" ``` ```@meta DocTestSetup = nothing ``` ## Iterator interface The iterator interface is implemented for a `@resumable function`: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function fibonacci(n) :: Int a = 0 b = 1 for i in 1:n @yield a a, b = b, a + b end end end ``` ```julia @resumable function fibonacci(n) :: Int a = 0 b = 1 for i in 1:n @yield a a, b = b, a + b end end ``` ```jldoctest julia> for val in fibonacci(10) println(val) end 0 1 1 2 3 5 8 13 21 34 ``` ```@meta DocTestSetup = nothing ``` ## Parametric `@resumable` functions Type parameters can be specified with a `where` clause: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function fibonacci(a::N, b::N=a+one(N)) :: N where {N<:Number} for i in 1:10 @yield a a, b = b, a + b end end end ``` ```julia @resumable function fibonacci(a::N, b::N=a+one(N)) :: N where {N<:Number} for i in 1:10 @yield a a, b = b, a + b end end ``` ```jldoctest julia> for val in fibonacci(0.0) println(val) end 0.0 1.0 1.0 2.0 3.0 5.0 8.0 13.0 21.0 34.0 ``` ```@meta DocTestSetup = nothing ``` ## Let block A `let` block allows a variable not to be saved in between calls to a `@resumable function`: ```@meta DocTestSetup = quote using ResumableFunctions @resumable function arrays_of_tuples() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i=i val = [a[i] for a in u] end @yield val end end end end ``` ```julia @resumable function arrays_of_tuples() for u in [[(1,2),(3,4)], [(5,6),(7,8)]] for i in 1:2 let i=i val = [a[i] for a in u] end @yield val end end end ``` ```jldoctest julia> for array in arrays_of_tuples() println(array) end [1, 3] [2, 4] [5, 7] [6, 8] ``` ```@meta DocTestSetup = nothing ``` ## Caveats - In a `try` block only top level `@yield` statements are allowed. - In a `catch` or a `finally` block a `@yield` statement is not allowed. - An anonymous function can not contain a `@yield` statement. - If a `FiniteStateMachineIterator` object is used in more than one `for` loop, only the `state` variable is reinitialised. A `@resumable function` that alters its arguments will use the modified values as initial parameters.
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.6.10
910fb2b8f0dd33649f606266c392f639bb939b10
docs
2702
--- title: 'ResumableFunctions: C# sharp style generators for Julia.' tags: - semi-coroutine - finite-state-machine - julia - iterator - stackless authors: - name: Ben Lauwens orcid: 0000-0003-0761-6265 affiliation: 1 affiliations: - name: Royal Military Academy, Brussels, Belgium index: 1 date: September 2017 bibliography: paper.bib --- # Summary C# has a convenient way to create iterators [@CsharpIterators] using the `yield return` statement. The package [@ResumableFunctions] provides the same functionality for the Julia language [@Julia] by introducing the `@resumable` and the `@yield` macros. These macros can be used to replace the `Task` switching functions `produce` and `consume` which were deprecated in Julia v0.6. `Channels` are the preferred way for inter-task communication in julia v0.6+, but their performance is subpar for iterator applications. The macro `@resumable` transform a function definition into a finite state-machine, i.e. a callable type holding the state and references to the internal variables of the function and a constructor for this new type respecting the method signature of the original function definition. When calling the new type a modified version of the body of the original function definition is executed: - a dispatch mechanism is inserted at the start to allow a non local jump to a label inside the body; - the `@yield` statement is replaced by a `return` statement and a label placeholder as endpoint of a non local jump; - `for` loops are transformed in `while` loops and - `try`-`catch`-`finally`-`end` expressions are converted in a sequence of `try`-`catch`-`end` expressions with at the end of the `catch` part a non local jump to a label that marks the beginning of the expressions in the `finally` part. The two last transformations are needed to overcome the limitations of the non local jump macros `@goto` and `@label`. Straightforward two-way communication between the caller and the callable type is possible by calling the callable type with an extra argument. The value of this argument is passed to the left side of an `arg = @yield ret` expression. The `iterator` interface is implemented so that a `@resumable function` can be used transparently. Benchmarks show that this macro based implementation of semi-coroutines is an order of magnitude faster than both the original `Task` switching with `produce` and `consume` and the newer `Channel` based approach for inter-task communication. A context switch is more expensive than a function call. The next generation of process-driven simulations in the discrete-event simulation framework [@SimJulia] is based on this package. # References
ResumableFunctions
https://github.com/JuliaDynamics/ResumableFunctions.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3188
using BenchmarkTools using Random using StableRNGs using UnfoldSim using Unfold using DataFrames using CategoricalArrays using MixedModels using BSplineKit #const SUITE = BenchmarkGroup() Random.seed!(3) #--- sfreq = 100 data, evts = UnfoldSim.predef_2x2(StableRNG(1); n_subjects = 20, signalsize = sfreq) data_epochs, evts_epochs = UnfoldSim.predef_2x2( StableRNG(1); n_subjects = 20, signalsize = sfreq, return_epoched = true, ) data = data[:] data_epochs = reshape(data_epochs, size(data_epochs, 1), :) transform!(evts, :subject => categorical => :subject) transform!(evts, :item => categorical => :item) evts.type = rand(StableRNG(1), [0, 1], nrow(evts)) for (ix, k) in enumerate([:continuousA, :continuousB, :continuousC, :continuousD, :continuousE]) evts[!, k] = rand(StableRNG(ix), size(evts, 1)) evts_epochs[!, k] = rand(StableRNG(ix), size(evts_epochs, 1)) end ba1 = firbasis(Ο„ = (0, 1), sfreq = sfreq) ba2 = firbasis(Ο„ = (0, 1), sfreq = sfreq) f1_lmm = @formula 0 ~ 1 + A + (1 + A | subject) f2_lmm = @formula 0 ~ 1 + A + (1 + A | item) f1 = @formula 0 ~ 1 + A f1_spl = @formula 0 ~ 1 + A + spl(continuousA, 5) + spl(continuousB, 5) + spl(continuousC, 5) + spl(continuousD, 5) + spl(continuousE, 5) f2 = @formula 0 ~ 1 + B dict_lin = Dict(0 => (f1, ba1), 1 => (f2, ba2)) dict_spl = Dict(0 => (f1_spl, ba1), 1 => (f1_spl, ba2)) dict_lmm = Dict(0 => (f1_lmm, ba1), 1 => (f2_lmm, ba2)) times = 1:size(data_epochs, 1) #--- m_epoch_lin_f1 = fit(UnfoldModel, f1, evts_epochs, data_epochs, times) m_epoch_lin_f1_spl = fit(UnfoldModel, f1_spl, evts_epochs, data_epochs, times) m_lin_f1 = fit(UnfoldModel, dict_lin, evts, data, eventcolumn = "type") m_lin_f1_spl = fit(UnfoldModel, dict_spl, evts, data, eventcolumn = "type") if 1 == 0 m_lin_f1_spl_ch = fit(UnfoldModel, dict_spl, evts, repeat(data, 1, 100)', eventcolumn = "type") end #--- ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) SUITE = BenchmarkGroup() SUITE["designmat"] = BenchmarkGroup(["designmat"]) SUITE["fit"] = BenchmarkGroup(["fit"]) SUITE["effects"] = BenchmarkGroup(["effects"]) # designmatrix generation SUITE["designmat"]["lin"] = @benchmarkable designmatrix(UnfoldLinearModelContinuousTime, $f1, $evts, $ba1) SUITE["designmat"]["lmm"] = @benchmarkable designmatrix( ext.UnfoldLinearMixedModelContinuousTime, $f1_lmm, $evts, $ba1, ) # Model Fit SUITE["fit"]["lin"] = @benchmarkable fit(UnfoldModel, $f1, $evts_epochs, $data_epochs, $times) SUITE["fit"]["lmm"] = @benchmarkable fit(UnfoldModel, $f1_lmm, $evts_epochs, $data_epochs, $times) SUITE["fit"]["lin_deconv"] = @benchmarkable fit(UnfoldModel, $dict_lin, $evts, $data, eventcolumn = "type"); #SUITE["fit"]["lmm_deconv"] = # @benchmarkable fit(UnfoldModel, $dict_lmm, $evts, $data, eventcolumn = "type"); SUITE["effects"]["lin"] = @benchmarkable effects($(Dict(:A => ["a_small", "a_big"])), $m_lin_f1) SUITE["effects"]["lin_spl"] = @benchmarkable effects( $(Dict(:continuousA => collect(range(0.1, 0.9, length = 15)))), $m_lin_f1_spl, ) #SUITE["fit"]["debugging"] = @benchmarkable read(run(`git diff Project.toml`))
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
720
using UnfoldSim using Unfold using BSplineKit using Krylov, CUDA data, evts = UnfoldSim.predef_eeg() data = repeat(data, 1, 30)' data = data .+ rand(size(data)...) bf = firbasis([-1, 1], 100) evts.continuousB .= rand(size(evts, 1)) f = @formula(0 ~ 1 + condition + spl(continuous, 5) + spl(continuousB, 20)) # 1.3s vs 0.3s in matlab Oo @time uf = designmatrix!(UnfoldLinearModelContinuousTime(Dict(Any => (f, bf))), evts); @time fit(UnfoldModel, Dict(Any => (f, bf)), evts, data; solver = (x, y) -> return nothing); @time fit(UnfoldModel, Dict(Any => (f, bf)), evts, data); @time fit( UnfoldModel, Dict(Any => (f, bf)), evts, data; solver = (x, y) -> Unfold.solver_krylov(x, y; GPU = true), );
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2067
using UnfoldSim using Krylov, CUDA using Unfold using Random using DataFrames using StableRNGs using BSplineKit #--- Generate Data sfreq = 100 data, evts = UnfoldSim.predef_eeg(StableRNG(1); n_repeats = 200, sfreq = sfreq) evts = evts[1:end-2, :] data = reshape(data, 1, :) evts.type = rand(StableRNG(1), [0, 1], nrow(evts)) ba1 = firbasis(Ο„ = (0, 1), sfreq = sfreq, name = "evts1") ba2 = firbasis(Ο„ = (0, 1), sfreq = sfreq, name = "evts2") f1 = @formula 0 ~ 1 + spl(continuous, 5) + condition f2 = @formula 0 ~ 1 + spl(continuous, 5) + condition dict_lin = Dict(0 => (f1, ba1), 1 => (f2, ba2)) uf = fit(UnfoldModel, dict_lin, evts, data, eventcolumn = "type", solver = (x, y) -> nothing); #---- X = modelmatrix(uf) data_one = data[1:1, 1:size(X, 1)] # cute the data to have same length data20 = repeat(data_one, 50) data20 .= data20 .+ rand(StableRNG(1), size(data20)...) #--- y = data_one y = data20 @time Unfold.solver_default(X, y; multithreading = false); @time Unfold.solver_default(X, y; multithreading = true); @time Unfold.solver_krylov(X, y; multithreading = false); @time Unfold.solver_krylov(X, y); @time Unfold.solver_krylov(X, y; GPU = true); #---- #using SuiteSparseGraphBLAS #@time b7 = solver_gb(X,y); # function solver_gb( # X, # data::AbstractArray{T,2}; # stderror = false, # ) where {T<:Union{Missing,<:Number}} # minfo = [] # sizehint!(minfo, size(data,1)) # beta = zeros(size(data,1),size(X,2)) # had issues with undef # X_l = GBMatrix(disallowmissing(X)) # for ch = 1:size(data, 1) # # use the previous channel as a starting point # #ch == 1 || copyto!(view(beta, ch, :), view(beta, ch-1, :)) # beta[ch,:],h = lsmr!(@view(beta[ch, :]), X_l, @view(data[ch, ix]),log=true) # push!(minfo, h) # end # if stderror # stderror = calculate_stderror(X, data, beta) # modelfit = Unfold.LinearModelFit(beta, ["lsmr",minfo], stderror) # else # modelfit = Unfold.LinearModelFit(beta, ["lsmr",minfo]) # end # return modelfit # end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3773
# Calling Matlab from Julia and comparing to Unfold.jl ENV["MATLAB_ROOT"] = "/opt/common/apps/matlab/r2021a/" using MATLAB using BSplineKit, Unfold, UnfoldSim using Random mat"addpath('/store/users/skukies/unfold_duration_backup/lib/eeglab')" # Add EEGLAB? mat"addpath('/store/users/skukies/unfold_duration_backup/lib/unfold')" #" Add Unfold? mat"init_unfold" # Matlab function for comparison function calc_matlab(datajl, eventsjl) mat" EEG = eeg_emptyset(); EEG.data = $datajl; EEG.srate = 100; " mat_events = mxarray( Dict( "continuous" => eventsjl.continuous, "condition" => eventsjl.condition, "latency" => eventsjl.latency, ), ) mat" for e = 1:length($mat_events.latency) EEG.event(end+1).latency = $mat_events.latency(e); EEG.event(end).condition = $mat_events.condition{e}; EEG.event(end).continuous= $mat_events.continuous(e); EEG.event(end).continuousB= rand(1); EEG.event(end).type = 'fixation'; end " mat"EEG = eeg_checkset(EEG)" mat" cfgDesign = []; cfgDesign.eventtypes = {'fixation'}; cfgDesign.formula = 'y ~ 1+ cat(condition)+spl(continuous,5)'; tic EEG = uf_designmat(EEG,cfgDesign); EEG = uf_timeexpandDesignmat(EEG,'timelimits',[-1,1]); t_design = toc EEG = uf_glmfit(EEG); t_fit = toc " end #" Setting up data # data, events = UnfoldSim.predef_eeg() design = SingleSubjectDesign(; conditions = Dict( :condition => ["car", "face"], :continuous => range(-5, 5, length = 10), ), ) |> x -> RepeatDesign(x, 50); p1 = LinearModelComponent(; basis = p100(), formula = @formula(0 ~ 1), Ξ² = [5]); n1 = LinearModelComponent(; basis = n170(), formula = @formula(0 ~ 1 + condition), Ξ² = [5, -3], ); p3 = LinearModelComponent(; basis = p300(), formula = @formula(0 ~ 1 + continuous), Ξ² = [5, 1], ); components = [p1, n1, p3] data, events = UnfoldSim.simulate( MersenneTwister(1), design, components, UniformOnset(; width = 50, offset = 20), PinkNoise(), ); # Run fit two times; once for compilation and once for actual timing for k = 1:2 @time m = fit( UnfoldModel, [ Any => ( @formula(0 ~ 1 + condition + spl(continuous, 5)), firbasis(Ο„ = [-1, 1], sfreq = 100, name = "basis"), ), ], events, data, ) end ## Matlab part calc_matlab(data, events) @mget(t_fit) # Above tested 2023/11/22; Julia: 0.12 sec ; Matlab: 0.15sec # Above tested 2024/04/18: Julia: 0.4 ; Matlab: 0.24s ## Multichannel w/ headmodel c = LinearModelComponent(; basis = p100(), formula = @formula(0 ~ 1 + condition), Ξ² = [5, 1], ); c2 = LinearModelComponent(; basis = p300(), formula = @formula(0 ~ 1 + continuous), Ξ² = [5, -3], ); hart = headmodel(type = "hartmut") mc = UnfoldSim.MultichannelComponent(c, hart => "Left Postcentral Gyrus") mc2 = UnfoldSim.MultichannelComponent(c2, hart => "Right Occipital Pole") onset = UniformOnset(; width = 50, offset = 20); data_mc, events_mc = UnfoldSim.simulate(MersenneTwister(1), design, [mc, mc2], onset, PinkNoise()) # Fit Unfold.jl @time m = fit( UnfoldModel, [ Any => ( @formula(0 ~ 1 + condition + spl(continuous, 5)), firbasis(Ο„ = [-1, 1], sfreq = 100), ), ], events_mc, data_mc, ); # Fit Matlab calc_matlab(data_mc, events_mc) # Above tested 2023/11/22; Julia: ca.8.9 sec ; Matlab: ca. 10.5sec # Above tested 2024/04/18: Julia: ca. 4s ; Matlab: ca. 66s
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2519
using Documenter using Unfold using AlgebraOfGraphics # can be removed with UnfoldMakie 0.3.0 using DocStringExtensions using Literate using Glob GENERATED = joinpath(@__DIR__, "src", "generated") SOURCE = joinpath(@__DIR__, "literate") for subfolder ∈ ["explanations", "HowTo", "tutorials"] local SOURCE_FILES = Glob.glob(subfolder * "/*.jl", SOURCE) foreach(fn -> Literate.markdown(fn, GENERATED * "/" * subfolder), SOURCE_FILES) end makedocs( sitename = "Unfold.jl Timeseries Analysis & Deconvolution", #root = joinpath(dirname(pathof(Unfold)), "..", "docs"), #prettyurls = get(ENV, "CI", nothing) == "true", repo = Documenter.Remotes.GitHub("unfoldtoolbox", "Unfold.jl"), pages = [ "index.md", "Installing Julia + Unfold.jl" => "installation.md", "Tutorials" => [ "Mass univariate LM" => "tutorials/lm_mu.md", "LM overlap correction" => "tutorials/lm_overlap.md", "Mass univariate Mixed Model" => "tutorials/lmm_mu.md", "LMM + overlap correction" => "tutorials/lmm_overlap.md", ], "HowTo" => [ "Overlap: Multiple events" => "HowTo/multiple_events.md", "Import EEG with 🐍 PyMNE.jl" => "HowTo/pymne.md", "Standard errors" => "HowTo/standarderrors.md", "Alternative Solvers (Robust, GPU, B2B)" => "HowTo/custom_solvers.md", "🐍 Calling Unfold.jl directly from Python" => "generated/HowTo/juliacall_unfold.md", "P-values for mixedModels" => "HowTo/lmm_pvalues.md", "Marginal effects (focus on non-linear predictors)" => "generated/HowTo/effects.md", #"Time domain basis functions"=>"generated/HowTo/timesplines.md", "Save and load Unfold models" => "generated/HowTo/unfold_io.md", ], "Explanations" => [ "About basisfunctions" => "./explanations/basisfunctions.md", "Non-Linear effects" => "./generated/explanations/nonlinear_effects.md", "Window Length Effect" => "./generated/explanations/window_length.md", ], "Reference" => [ "Overview of package extensions" => "references/extensions.md", "Development environment" => "explanations/development.md", "API: Types" => "references/types.md", "API: Functions" => "references/functions.md", ], ], ) deploydocs(; repo = "github.com/unfoldtoolbox/Unfold.jl", push_preview = true, devbranch = "main", )
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
5719
### A Pluto.jl notebook ### # v0.19.2 using Markdown using InteractiveUtils # ╔═║ 25d21156-d006-11eb-3655-61be76e7db93 begin import Pkg Pkg.activate("../../../") end # ╔═║ 34aefa9a-e034-4293-b53d-cc1dc349ecc7 let using Revise using Unfold using DataFramesMeta end # ╔═║ c73bf3ed-4af3-4e5a-997e-6399c9b85bbe using StatsModels, PlutoUI, DataFrames, StatsPlots # ╔═║ d1e1de70-7e37-46a4-8ce2-3ca591bb84cf include(pathof(Unfold) * "../../../test/test_utilities.jl") # ╔═║ 2e9ec6e0-03c6-41f6-bd3b-a44eaed5b553 data, evts = loadtestdata("test_case_4a"); # ╔═║ 0b27e0bb-7aee-4672-8501-6096539c7ad7 evts.continuousA = rand(size(evts, 1)) # ╔═║ 97443eb8-ac67-4f8e-9e8a-eb09176c8516 # ╔═║ 2a5d5493-b88d-473f-8d81-9e9240b3ffe0 #f = @formula 0~1+conditionA+continuousA # 1 f = @formula 0 ~ 1 + continuousA # 1 # ╔═║ 5d23b74c-988d-48bc-9c30-c2af0dbabdb4 # ╔═║ 3f2b7a92-a064-4be6-8a39-cabaa2453777 basisfunction = Unfold.splinebasis(Ο„ = (-1, 1), sfreq = 20, nsplines = 10, name = "basisA") # ╔═║ 8f32dbf3-8958-4e67-8e25-5f24d48058e1 Unfold.splinebasis # ╔═║ 7ef24e5a-63df-4e99-a021-7119d7e8d3bf fir = firbasis(Ο„ = (-1, 1), sfreq = 20, name = "basisB") # ╔═║ 12c617c1-1994-4efe-b8bc-23fd2325c2ca fir.kernel(2) # ╔═║ 6f7bc2f6-28de-40a5-83ee-c15cd6f74f6c basisfunction.kernel(1) # ╔═║ e3d7ac15-e7a2-490b-abbc-aea3d7b4f4c7 size(Unfold.times(basisfunction)) # ╔═║ 73022b4d-4edd-44e2-8cfa-26ded44a8921 size(Unfold.colnames(basisfunction)) # ╔═║ d38f9cc9-409f-4c52-b0d2-d09312cc695a size(basisfunction.colnames) # ╔═║ 786d0114-e10e-4e29-b6d7-bbe635c55f08 evts # ╔═║ c4227637-81b4-4ea7-a7b7-741860fef8c3 m = fit( UnfoldModel, Dict("eventA" => (f, fir), "eventB" => (f, basisfunction)), evts, data, eventcolumn = "type", ); # ╔═║ cd19784c-686e-41c5-bd32-cdf793cecf03 res = coeftable(m) # ╔═║ 29e875d3-45b9-4a6a-aaa6-c6eaf35244c5 @df res plot(:time, :estimate, group = (:basisname, :coefname)) # ╔═║ b669f55b-9121-4d66-9c82-f89bbfe0b2df Unfold.coef(m) # ╔═║ 64cf7e78-2677-4551-9491-82c9f560ed61 res # ╔═║ 02b8ff44-c514-492e-bf94-0cbf44431097 x = [1] # ╔═║ d964a5ca-7e63-41d5-bf97-526772d259e9 #[kernel(formTerm.basisfunction)(0) for formTerm in getfield.(designmatrix(m).formulas,:rhs)] # ╔═║ 1ee404e1-3039-410d-99de-ce713e751280 let basisnames = Unfold.get_basis_name(m) betaOut = [] for (k, b) in enumerate(unique(basisnames)) ix = basisnames .== b betaOut = vcat( betaOut, designmatrix(m).formulas[k].rhs.basisfunction.kernel(0) * m.modelfit.estimate[:, ix]', ) end plot(Float64.(betaOut)) end # ╔═║ 5466ec0b-d28a-4be7-b686-cb5ad7fea92b let basisnames = Unfold.get_basis_name(m) k = 2 b = unique(basisnames)[k] bf = designmatrix(m).formulas[k].rhs.basisfunction ix = basisnames .== b hcat(bf.kernel.([0, 0])...) * m.modelfit.estimate[:, ix]' end # ╔═║ 033cf2e0-a3ca-40e3-8f27-e88e017ca8de size(Unfold.times(basisfunction)) # ╔═║ a8238bd7-0198-45d2-89bd-d1434c537b2a designmatrix(m).formulas[2].rhs.basisfunction.kernel(0) # ╔═║ fe5a826f-aede-4e91-b6cd-ee7fca33ce31 zeros() # ╔═║ 8b9d8e32-d2ca-49db-986f-851ffabc3a3e function undoBasis(d, m) bname = unique(d.basisname) # the current coefficient basename @assert(length(bname) == 1) @assert(length(unique(d.channel)) == 1) bnames = unique(Unfold.get_basis_name(m)) # all model basenames # find out which formula / basisfunction we have k = findfirst(bname .== bnames) bf = designmatrix(m).formulas[k].rhs.basisfunction estimate = bf.kernel.(0) * d.estimate @show size(bf.kernel.(0)) @show size(Unfold.times(bf)) return DataFrame(:time => Unfold.times(bf), :estimate => estimate) end # ╔═║ 350a7f4b-f019-4bf6-8878-2cbb0cf82005 begin gd = groupby(res, [:basisname, :channel, :group, :coefname]) a = combine(gd) do d return undoBasis(d, m) end a end # ╔═║ a876f554-a034-461e-9522-490ca4bab5f8 @df a plot(:time, :estimate, group = (:basisname, :coefname)) # ╔═║ 1d5b8b05-cdc6-4058-9bc1-bd52e6e3b444 Unfold.get_basis_name(m) # ╔═║ 111189ec-be04-4687-91ff-53b540a7b4db Unfold.get_basis_name(m) # ╔═║ 4b572283-14cd-4a75-9ff2-f5a18f40228d res # ╔═║ Cell order: # ╠═25d21156-d006-11eb-3655-61be76e7db93 # ╠═34aefa9a-e034-4293-b53d-cc1dc349ecc7 # ╠═c73bf3ed-4af3-4e5a-997e-6399c9b85bbe # ╠═d1e1de70-7e37-46a4-8ce2-3ca591bb84cf # ╠═2e9ec6e0-03c6-41f6-bd3b-a44eaed5b553 # ╠═0b27e0bb-7aee-4672-8501-6096539c7ad7 # ╠═97443eb8-ac67-4f8e-9e8a-eb09176c8516 # ╠═2a5d5493-b88d-473f-8d81-9e9240b3ffe0 # ╠═5d23b74c-988d-48bc-9c30-c2af0dbabdb4 # ╠═3f2b7a92-a064-4be6-8a39-cabaa2453777 # ╠═8f32dbf3-8958-4e67-8e25-5f24d48058e1 # ╠═7ef24e5a-63df-4e99-a021-7119d7e8d3bf # ╠═12c617c1-1994-4efe-b8bc-23fd2325c2ca # ╠═6f7bc2f6-28de-40a5-83ee-c15cd6f74f6c # ╠═e3d7ac15-e7a2-490b-abbc-aea3d7b4f4c7 # ╠═73022b4d-4edd-44e2-8cfa-26ded44a8921 # ╠═d38f9cc9-409f-4c52-b0d2-d09312cc695a # ╠═786d0114-e10e-4e29-b6d7-bbe635c55f08 # ╠═c4227637-81b4-4ea7-a7b7-741860fef8c3 # ╠═cd19784c-686e-41c5-bd32-cdf793cecf03 # ╠═29e875d3-45b9-4a6a-aaa6-c6eaf35244c5 # ╠═b669f55b-9121-4d66-9c82-f89bbfe0b2df # ╠═64cf7e78-2677-4551-9491-82c9f560ed61 # ╠═02b8ff44-c514-492e-bf94-0cbf44431097 # ╠═d964a5ca-7e63-41d5-bf97-526772d259e9 # ╠═1ee404e1-3039-410d-99de-ce713e751280 # ╠═5466ec0b-d28a-4be7-b686-cb5ad7fea92b # ╠═033cf2e0-a3ca-40e3-8f27-e88e017ca8de # ╠═a8238bd7-0198-45d2-89bd-d1434c537b2a # ╠═350a7f4b-f019-4bf6-8878-2cbb0cf82005 # ╠═a876f554-a034-461e-9522-490ca4bab5f8 # ╠═fe5a826f-aede-4e91-b6cd-ee7fca33ce31 # ╠═8b9d8e32-d2ca-49db-986f-851ffabc3a3e # ╠═1d5b8b05-cdc6-4058-9bc1-bd52e6e3b444 # ╠═111189ec-be04-4687-91ff-53b540a7b4db # ╠═4b572283-14cd-4a75-9ff2-f5a18f40228d
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3552
### A Pluto.jl notebook ### # v0.19.2 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId( Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes", )].Bonds.initial_value catch b -> missing end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═║ 360367c3-a17d-4c04-b8eb-e2f0366baa86 import Pkg; # ╔═║ a69bf247-acbc-4b4d-889d-3f52ff046ef4 Pkg.activate("/store/users/ehinger/unfoldjl_dev/") # ╔═║ cf3dcd54-cfa0-11eb-2e99-756f9df71a4d using Revise, Unfold, Plots, BSplines # ╔═║ a9e6971f-8a50-4564-ace5-1fabe65b1522 import PlutoUI # ╔═║ 8a62a281-d91d-4e70-b301-4ebafdd58b38 # ╔═║ 539da607-f382-4eaa-93ad-31c906aa67ee # ╔═║ 17943406-ac61-49bd-bc8d-7d3f62441b8e # ╔═║ 89eace50-c0f5-4951-821f-cf010cdb9726 @bind nsplines PlutoUI.Slider(2:10; default = 8, show_value = true) # ╔═║ cb62fb85-364d-4142-b28b-c8b0871b4ccc @bind srate PlutoUI.Slider(1:50; default = 10, show_value = true) # ╔═║ 8496a69b-20bc-45c2-92cb-179d0ad7127c @bind Ο„1 PlutoUI.Slider(-5:0.1:2; default = -0.5, show_value = true) # ╔═║ c8285ed7-bffb-4047-89ff-22a664c19a78 @bind Ο„2 PlutoUI.Slider(-2:0.1:5; default = 2, show_value = true) # ╔═║ 9df0d50d-2a1a-4431-9725-12178c824d62 Ο„ = [Ο„1, Ο„2] # ╔═║ 94a258ea-febd-4793-89c4-d3755e82c48c begin function splinebasis(Ο„, sfreq, nsplines, name::String) Ο„ = Unfold.round_times(Ο„, sfreq) times = range(Ο„[1], stop = Ο„[2], step = 1 ./ sfreq) kernel = e -> splinekernel(e, times, nsplines) type = "splinebasis" shiftOnset = Int64(floor(Ο„[1] * sfreq)) return Unfold.BasisFunction(kernel, times, times, type, name, shiftOnset) end function spl_breakpoints(times, nsplines) # calculate the breakpoints, evenly spaced return collect(range(minimum(times), stop = maximum(times), length = nsplines)) end function splinekernel(e, times, nsplines) breakpoints = spl_breakpoints(times, nsplines) basis = BSplineBasis(4, breakpoints) # 4= cubic return Unfold.splFunction(times, basis) end spl = splinebasis(Ο„, srate, nsplines, "test") end # ╔═║ 3f612e26-aba8-46ed-af19-67cd1be672fa plot(spl.times, spl.kernel(0)) # ╔═║ d375b64c-0e64-4b39-8c3f-5a14d365877d # ╔═║ 7086e800-d51a-4fe3-b33f-309acd676ae7 # ╔═║ 4d6fc512-205e-4e25-b3b5-b7981d9dec75 # ╔═║ ba9bafc2-9733-43d0-80cd-75b2637ba4a7 # ╔═║ Cell order: # ╠═360367c3-a17d-4c04-b8eb-e2f0366baa86 # ╠═a9e6971f-8a50-4564-ace5-1fabe65b1522 # ╠═a69bf247-acbc-4b4d-889d-3f52ff046ef4 # ╠═8a62a281-d91d-4e70-b301-4ebafdd58b38 # ╠═539da607-f382-4eaa-93ad-31c906aa67ee # ╠═17943406-ac61-49bd-bc8d-7d3f62441b8e # ╠═94a258ea-febd-4793-89c4-d3755e82c48c # ╠═3f612e26-aba8-46ed-af19-67cd1be672fa # ╠═89eace50-c0f5-4951-821f-cf010cdb9726 # ╠═cb62fb85-364d-4142-b28b-c8b0871b4ccc # ╠═8496a69b-20bc-45c2-92cb-179d0ad7127c # ╠═c8285ed7-bffb-4047-89ff-22a664c19a78 # ╠═9df0d50d-2a1a-4431-9725-12178c824d62 # ╠═d375b64c-0e64-4b39-8c3f-5a14d365877d # ╠═cf3dcd54-cfa0-11eb-2e99-756f9df71a4d # ╠═7086e800-d51a-4fe3-b33f-309acd676ae7 # ╠═4d6fc512-205e-4e25-b3b5-b7981d9dec75 # ╠═ba9bafc2-9733-43d0-80cd-75b2637ba4a7
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4166
### A Pluto.jl notebook ### # v0.14.8 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing el end end # ╔═║ 65edde2e-d03e-11eb-300b-897bdc66d875 begin using Unfold using PlutoUI using StatsPlots using DataFrames using StatsModels end # ╔═║ 0a821c04-1aff-4fca-aab8-07a4d450838c begin using Random end # ╔═║ bec07615-8ca3-4251-9e44-bf5044828274 include("../test/test_utilities.jl"); # ╔═║ 72bffaed-d3d9-44d8-9a74-0e0a0d3b0882 md"""# Simple Unfold.jl Example with overlap correction""" # ╔═║ ee305b1e-0c62-4a9f-ab80-d937b1401347 md""" ### Setup Setup might take a while because the libraries are very large. It might be better to install some of the packages to your julia-environment prior to starting Pluto """ # ╔═║ 2ec25bc8-1154-4850-ba02-62ed634cb558 md"""### Loading Data & Setting up Unfold""" # ╔═║ 76afd758-ac50-4f3c-a484-7f268ab059ef data, evts = loadtestdata("test_case_3b"); # ╔═║ c7fb216e-d177-4623-a135-db4cd856d4ad f = @formula 0 ~ 1 + conditionA + continuousA # ╔═║ a55058c9-3b56-447b-8f1a-f7319a29f478 md"""### Fitting the models""" # ╔═║ 8bfb1b5c-1c6a-472c-9087-dd03b0884922 md"""### Plotting the results""" # ╔═║ 9a4c715a-7a51-411d-a354-f79ec2369cb7 let md"""change window size Ο„ = (-0.3, $(@bind Ο„2 Slider(0:0.1:5,default=2, show_value=true))) """ end # ╔═║ ba2f0c48-f5f8-40eb-a45b-441b8134ffb1 Ο„ = (-0.3, Ο„2) # ╔═║ f99efde3-bd34-46e2-ad1c-1a97ad866b79 fir = firbasis(Ο„ = Ο„, sfreq = 20, name = "basisA"); # ╔═║ dcbdef13-675e-47f7-b484-d340f0e55934 f_dict = Dict("eventA" => (f, fir)) # combine eventname, formula & basis # ╔═║ ed61f099-343c-47d4-9af4-c4486c93fd4a let md"""change noise: Οƒ = $(@bind Οƒ Slider(0:0.1:5,default=0, show_value=true)) """ end # ╔═║ 09705728-c6e5-41a5-9859-2c7e28828d5b # add some noise data_noise = data .+ Οƒ .* randn(size(data)); # ╔═║ b31a80a5-cca2-4c69-82f5-2b477f5b62be begin plot(data_noise[1:600], title = "Simulated Data with overlap") vline!(evts.latency[1:20], legend = false) end # ╔═║ 3f4dd059-e275-483d-af42-a09a2795fca4 data_e, times = Unfold.epoch(data = data_noise, tbl = evts, Ο„ = Ο„, sfreq = 10); # ╔═║ 9aa42667-2629-48e1-b7fe-979dabc28f96 # non-overlapping (mass univariate) m_e, res_e = fit(UnfoldLinearModel, f, evts, data_e, times); # ╔═║ bce42119-33d7-4e10-ac5e-b37028381b09 # overlap-corrected m, res = fit(UnfoldLinearModel, f_dict, evts, data_noise, eventcolumn = "type"); # ╔═║ de267143-c029-4103-9fd7-ada153588ab6 begin p1 = @df res_e plot( :colname_basis, :estimate, group = :coefname, title = "Without ...", ylims = (-3, 5), legend = false, xlims = (-0.3, 3), ) p2 = @df res plot( :colname_basis, :estimate, group = :coefname, title = "... with overlap correction", ylims = (-3, 5), xlims = (-0.3, 3), legend = :bottomright, ) plot(p1, p2, layout = (1, 2)) end # ╔═║ Cell order: # β•Ÿβ”€72bffaed-d3d9-44d8-9a74-0e0a0d3b0882 # β•Ÿβ”€ee305b1e-0c62-4a9f-ab80-d937b1401347 # ╠═65edde2e-d03e-11eb-300b-897bdc66d875 # ╠═0a821c04-1aff-4fca-aab8-07a4d450838c # ╠═bec07615-8ca3-4251-9e44-bf5044828274 # β•Ÿβ”€2ec25bc8-1154-4850-ba02-62ed634cb558 # ╠═76afd758-ac50-4f3c-a484-7f268ab059ef # ╠═09705728-c6e5-41a5-9859-2c7e28828d5b # ╠═b31a80a5-cca2-4c69-82f5-2b477f5b62be # ╠═3f4dd059-e275-483d-af42-a09a2795fca4 # ╠═c7fb216e-d177-4623-a135-db4cd856d4ad # ╠═f99efde3-bd34-46e2-ad1c-1a97ad866b79 # ╠═dcbdef13-675e-47f7-b484-d340f0e55934 # β•Ÿβ”€a55058c9-3b56-447b-8f1a-f7319a29f478 # ╠═bce42119-33d7-4e10-ac5e-b37028381b09 # ╠═9aa42667-2629-48e1-b7fe-979dabc28f96 # β•Ÿβ”€8bfb1b5c-1c6a-472c-9087-dd03b0884922 # ╠═ba2f0c48-f5f8-40eb-a45b-441b8134ffb1 # β•Ÿβ”€9a4c715a-7a51-411d-a354-f79ec2369cb7 # β•Ÿβ”€ed61f099-343c-47d4-9af4-c4486c93fd4a # ╠═de267143-c029-4103-9fd7-ada153588ab6
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4954
### A Pluto.jl notebook ### # v0.14.8 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing el end end # ╔═║ 65edde2e-d03e-11eb-300b-897bdc66d875 begin import Pkg Pkg.activate(mktempdir()) Pkg.add(url = "https://github.com/unfoldtoolbox/Unfold.jl") Pkg.add("PlutoUI") Pkg.add("StatsPlots") Pkg.add("DataFrames") Pkg.add("StatsModels") Pkg.add("DSP") end # ╔═║ 0a821c04-1aff-4fca-aab8-07a4d450838c let using Revise using Unfold using StatsModels, PlutoUI, StatsPlots, DataFrames, Random using DSP end # ╔═║ bec07615-8ca3-4251-9e44-bf5044828274 include("../test/test_utilities.jl"); # ╔═║ 72bffaed-d3d9-44d8-9a74-0e0a0d3b0882 md"""# Simple Unfold.jl Example with overlap correction""" # ╔═║ ee305b1e-0c62-4a9f-ab80-d937b1401347 md""" ### Setup Setup might take a while because the libraries are very large. It might be better to install some of the packages to your julia-environment prior to starting Pluto """ # ╔═║ 2ec25bc8-1154-4850-ba02-62ed634cb558 md"""### Loading Data & Setting up Unfold""" # ╔═║ 76afd758-ac50-4f3c-a484-7f268ab059ef data, evts = loadtestdata("test_case_3b"); # ╔═║ c7fb216e-d177-4623-a135-db4cd856d4ad f = @formula 0 ~ 1 + conditionA + continuousA # ╔═║ a55058c9-3b56-447b-8f1a-f7319a29f478 md"""### Fitting the models""" # ╔═║ 8bfb1b5c-1c6a-472c-9087-dd03b0884922 md"""### Plotting the results""" # ╔═║ 9a4c715a-7a51-411d-a354-f79ec2369cb7 let md"""change window size Ο„ = (-0.3, $(@bind Ο„2 Slider(0:0.1:5,default=2, show_value=true))) """ end # ╔═║ ba2f0c48-f5f8-40eb-a45b-441b8134ffb1 Ο„ = (-0.3, Ο„2) # ╔═║ f99efde3-bd34-46e2-ad1c-1a97ad866b79 fir_basis = firbasis(Ο„ = Ο„, sfreq = 20, name = "basisA"); # ╔═║ dcbdef13-675e-47f7-b484-d340f0e55934 f_dict = Dict("eventA" => (f, fir_basis)) # combine eventname, formula & basis # ╔═║ ed61f099-343c-47d4-9af4-c4486c93fd4a let md"""change noise: Οƒ = $(@bind Οƒ Slider(0:0.1:5,default=0, show_value=true)) """ end # ╔═║ 09705728-c6e5-41a5-9859-2c7e28828d5b # add some noise #data_noise = data .+ Οƒ .* randn(size(data)); data_noise = data .+ Οƒ .* rand(PinkGaussian(size(data, 1))); # ╔═║ 1f3419f0-02e3-4346-8ac4-026cb76fa0fe md"""filter: $(@bind low_cutoff Slider(0.01:0.01:2,default=0.01, show_value=true)) """ # ╔═║ 3e6f413d-f0b3-434f-a2bd-e002592247f8 hpf = fir(501, low_cutoff; fs = 20); # ╔═║ b2893e0a-5712-4af2-923d-e80078f7277c data_filter = filtfilt(hpf, data_noise); # ╔═║ b31a80a5-cca2-4c69-82f5-2b477f5b62be begin plot(data_filter[1:400], title = "Simulated Data with overlap") plot!(data_noise[1:400], title = "Simulated Data with overlap") vline!(evts.latency[1:10], legend = false) end # ╔═║ 3f4dd059-e275-483d-af42-a09a2795fca4 data_e, times = Unfold.epoch(data = data_filter, tbl = evts, Ο„ = Ο„, sfreq = 20); # ╔═║ 9aa42667-2629-48e1-b7fe-979dabc28f96 # non-overlapping (mass univariate) m_e, res_e = fit(UnfoldLinearModel, f, evts, data_e, times); # ╔═║ bce42119-33d7-4e10-ac5e-b37028381b09 # overlap-corrected m, res = fit(UnfoldLinearModel, f_dict, evts, data_filter, eventcolumn = "type"); # ╔═║ de267143-c029-4103-9fd7-ada153588ab6 begin p1 = @df res_e plot( :colname_basis, :estimate, group = :coefname, title = "Without ...", ylims = (-3, 5), legend = false, xlims = (-0.3, 5), ) p2 = @df res plot( :colname_basis, :estimate, group = :coefname, title = "... with overlap correction", ylims = (-3, 5), xlims = (-0.3, 5), legend = :bottomright, ) plot(p1, p2, layout = (1, 2)) end # ╔═║ Cell order: # β•Ÿβ”€72bffaed-d3d9-44d8-9a74-0e0a0d3b0882 # β•Ÿβ”€ee305b1e-0c62-4a9f-ab80-d937b1401347 # ╠═65edde2e-d03e-11eb-300b-897bdc66d875 # ╠═0a821c04-1aff-4fca-aab8-07a4d450838c # ╠═bec07615-8ca3-4251-9e44-bf5044828274 # β•Ÿβ”€2ec25bc8-1154-4850-ba02-62ed634cb558 # ╠═76afd758-ac50-4f3c-a484-7f268ab059ef # ╠═09705728-c6e5-41a5-9859-2c7e28828d5b # ╠═3e6f413d-f0b3-434f-a2bd-e002592247f8 # ╠═b2893e0a-5712-4af2-923d-e80078f7277c # ╠═b31a80a5-cca2-4c69-82f5-2b477f5b62be # ╠═3f4dd059-e275-483d-af42-a09a2795fca4 # ╠═c7fb216e-d177-4623-a135-db4cd856d4ad # ╠═f99efde3-bd34-46e2-ad1c-1a97ad866b79 # ╠═dcbdef13-675e-47f7-b484-d340f0e55934 # β•Ÿβ”€a55058c9-3b56-447b-8f1a-f7319a29f478 # ╠═bce42119-33d7-4e10-ac5e-b37028381b09 # ╠═9aa42667-2629-48e1-b7fe-979dabc28f96 # β•Ÿβ”€8bfb1b5c-1c6a-472c-9087-dd03b0884922 # ╠═ba2f0c48-f5f8-40eb-a45b-441b8134ffb1 # β•Ÿβ”€9a4c715a-7a51-411d-a354-f79ec2369cb7 # β•Ÿβ”€ed61f099-343c-47d4-9af4-c4486c93fd4a # β•Ÿβ”€1f3419f0-02e3-4346-8ac4-026cb76fa0fe # ╠═de267143-c029-4103-9fd7-ada153588ab6
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
228
using LiveServer dr = filter(isdir, readdir(joinpath("src", "generated"), join = true)) push!(dr, "./build") servedocs( skip_dirs = dr, literate_dir = joinpath("literate"), foldername = ".", host = "0.0.0.0", )
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3762
# # [Marginal effects](@id effects) # [Marginal effect plots](https://library.virginia.edu/data/articles/a-beginners-guide-to-marginal-effects) are useful for understanding model fits. # If you are an EEG researcher, you can think of the coefficients as the 'difference waves' and the (marginal) effects as the 'modelled ERP evaluated at a certain predictor value combination'. # In some way, we are fitting a model with coefficients, receiving intercepts and slopes, and then try to recover the 'classical' ERPs in their "data-domain", typically with some effect adjustment, overlap removal, or similar. # # Setup things # Setup some packages using Unfold using DataFrames using Random using CSV using UnfoldMakie using UnfoldSim using UnfoldMakie using DisplayAs # hide # Generate data and fit a model with a 2-level categorical predictor and a continuous predictor without interaction. data, evts = UnfoldSim.predef_eeg(; noiselevel = 8) basisfunction = firbasis(Ο„ = (-0.1, 0.5), sfreq = 100; interpolate = false) f = @formula 0 ~ 1 + condition + continuous # 1 m = fit(UnfoldModel, [Any => (f, basisfunction)], evts, data, eventcolumn = "type") m |> DisplayAs.withcontext(:is_pluto => true) # hide # Plot the results plot_erp(coeftable(m)) #= The coefficients are represented by three lines on a figure: - the intercept showing the reference category for a typical p1/n1/p3 ERP components; - the slope of continuous variables with 1Β΅V range; - the effect of categorical variabe with 3Β΅V range. =# # ### Effects function # In order to better understand the actual predicted ERP curves, often researchers had to do manual contrasts. Remember that a linear model is `y = X * b`, which allows (after `b` was estimated) to input a so-called `contrast` vector for X. You might know this in the form of `[1, 0, -1, 1]` or similar form. However, for larger models, this method can be prone to errors. # The `effects` function is a convenient way to specify contrast vectors by providing the actual levels of the experimental design. It can be used to calculate all possible combinations of multiple variables. # If a predictor-variable is not specified here, the function will automatically set it to its typical value. This value is usually the `mean`, but for categorical variables, it could be something else. The R package `emmeans` has a lot of discussion on this topic. eff = effects(Dict(:condition => ["car", "face"]), m) plot_erp(eff; mapping = (; color = :condition,)) # We can also generate continuous predictions: eff = effects(Dict(:continuous => -5:0.5:5), m) plot_erp( eff; mapping = (; color = :continuous, group = :continuous => nonnumeric), categorical_color = false, categorical_group = false, ) # Or we can split our marginal effects by condition and calculate all combinations "automagically". eff = effects(Dict(:condition => ["car", "face"], :continuous => -5:2:5), m) plot_erp(eff; mapping = (; color = :condition, col = :continuous)) # ## What is typical anyway? # The `effects` function includes an argument called `typical`, which specifies the function applied to the marginalized covariates/factors. The default value is `mean`, which is usually sufficient for analysis. # # However, for skewed distributions, it may be more appropriate to use the `mode`, while for outliers, the `median` or `winsor` mean may be more appropriate. # # To illustrate, we will use the `maximum` function on the `continuous` predictor. eff_max = effects(Dict(:condition => ["car", "face"]), m; typical = maximum) eff_max.typical .= :maximum eff = effects(Dict(:condition => ["car", "face"]), m) eff.typical .= :mean # mean is the default plot_erp(vcat(eff, eff_max); mapping = (; color = :condition, col = :typical))
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3824
# # Using Unfold.jl from Python # it is straight forward to call Unfold from Python using `JuliaCall`. # ## Quick start # Create a Python environment and install JuliaCall. # ```bash # pip install juliacall # ``` # Create a Julia environment and install Unfold # ```python # # Import the Julia package manager # from juliacall import Pkg as jlPkg # # Activate the environment in the current folder # jlPkg.activate(".") # # Install Unfold (in the activated environment) # jlPkg.add("Unfold") # ``` # Import Julia's main module and Unfold # ```python # # Import Julia's Main module # from juliacall import Main as jl # # Import Unfold # # The function seval() can be used to evaluate a piece of Julia code given as a string # jl.seval("using Unfold") # Unfold = jl.Unfold # simplify name # ``` # Now you can use all Unfold functions as for example # ```python # dummy_model = Unfold.UnfoldLinearModel(jl.Dict()) # ``` # ## Example: Unfold model fitting from Python # In this [notebook](https://github.com/unfoldtoolbox/Unfold.jl/blob/main/docs/src/HowTo/juliacall_unfold.ipynb), you can find a more detailed example of how to use Unfold from Python to load data, fit an Unfold model and visualise the results in Python. # ## Important limitations # Python doesnt not offer the full expressions that are available in Julia. So there are some things you need to give special attention: # # **`@formula`**: we havent found a way to call macros yet, even though we think it should be possible. For now please use `f = jl.seval("@formula(0~1+my+cool+design)")`. Later versions might support something like `f = @formula("0~1+my+cool+design)"` directly # # **Specifying the design**: Since Unfold 0.7 we officially switched to the # ```julia # ["eventtypeA"=>(formula,basisfunction), # "eventtypeB"=>(otherformula,otherbasisfunction)] # ``` # Array-based syntax, from a Dict-based syntax. Unfortunately, `=>` (a pair) is not supported in Python and one needs to do some rewriting: # ```python # jl.convert(jl.Pair,(formula,basisfunction)) # ``` # which makes the code less readable. We are thinking of ways to remedy this - but right now there is now way around. For now, it is also possible to use the old syntax e.g. in python # ```python # {"eventtypeA"=>(formula,basisfunction),"eventtypeB"=>(otherformula,otherbasisfunction)} # ``` # which is clearly easier to read :) # # **`UnfoldSim.design`**: we need a `Dict` with a `Symbol` , one has to do something like `condition_dict_jl = {convert(jl.Symbol,"condA"):["car", "face"]}` to do so. We will [try to allow strings}(https://github.com/unfoldtoolbox/UnfoldSim.jl/issues/96) here as well, removing this constraint. # # When preprocessing your raw data through MNE Python, take the following into consideration: # The [Raw object](https://mne.tools/stable/generated/mne.io.Raw.html) contains the [first_samp](https://mne.tools/stable/documentation/glossary.html#term-first_samp) attribute which is an integer representing the number of time samples that passed between the onset of the hardware acquisition system and the time when data recording started. # The Raw data doesn't include these time samples, meaning that the first sample is the beginning of the data aquisition. # From the Raw object you can obtain an events array from the annotations through [mne.events_from_annotations()](https://mne.tools/stable/generated/mne.events_from_annotations.html). # The events array, however, does include first_samp, meaning that the annotated events in events array don't match the Raw object anymore. # Alternatively, it might be easier to convert the annotations to a pandas dataframe directly (`to_data_frame()`), or even better, load the "*_events.tsv" from a BIDS dataset. In the latter case, all columns will be preserved, which MNE's read_annotation drops.
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1411
# # [Save and load Unfold models](@id unfold_io) # Unfold.jl allows storing Unfold models in a memory-efficient way using (compressed) .jld2 files. # ## Simulate EEG data and fit an Unfold model # ```@raw html # <details> # <summary>Click to expand</summary> # ``` # ### Simulate some example data using UnfoldSim.jl using UnfoldSim data, events = UnfoldSim.predef_eeg(; n_repeats = 10) first(events, 5) # ### Fit an Unfold model using Unfold basisfunction = firbasis(Ο„ = (-0.5, 1.0), sfreq = 100, name = "stimulus") f = @formula 0 ~ 1 + condition + continuous bfDict = Dict(Any => (f, basisfunction)) m = fit(UnfoldModel, bfDict, events, data); # ```@raw html # </details > # ``` # ## Save and load the fitted Unfold model # The following code saves the model in a compressed .jld2 file. The default option of the `save` function is `compress=false`. # For memory efficiency the designmatrix is set to missing. If needed, it can be reconstructed when loading the model. save_path = mktempdir(; cleanup = false) # create a temporary directory for the example save(joinpath(save_path, "m_compressed.jld2"), m; compress = true); # The `load` function allows to retrieve the model again. # By default, the designmatrix is reconstructed. If it is not needed set `generate_Xs=false`` which improves time-efficiency. m_loaded = load(joinpath(save_path, "m_compressed.jld2"), UnfoldModel, generate_Xs = true);
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4289
# # [Non-linear effects]](@id nonlinear) using BSplineKit, Unfold using CairoMakie using DataFrames using Random using Colors using Missings # ## Generating a non-linear signal # We start with generating data variables rng = MersenneTwister(2) # make repeatable n = 20 # number of datapoints evts = DataFrame(:x => rand(rng, n)) signal = -(3 * (evts.x .- 0.5)) .^ 2 .+ 0.5 .* rand(rng, n) plot(evts.x, signal) # # Looks perfectly non-linear. Great! # # # Compare linear & non-linear fit # First, we have to reshape `signal` data to a 3d array, so it will fit to Unfold format: 1 channel x 1 timepoint x 20 datapoints. signal = reshape(signal, length(signal), 1, 1) signal = permutedims(signal, [3, 2, 1]) size(signal) # Next we define three different models: **linear**, **4 splines** and **10 splines**. # Note difference in formulas: one `x`, the other `spl(x, 4)`. design_linear = [Any => (@formula(0 ~ 1 + x), [0])]; design_spl3 = [Any => (@formula(0 ~ 1 + spl(x, 4)), [0])]; design_spl10 = [Any => (@formula(0 ~ 1 + spl(x, 10)), [0])]; # Next, fit the parameters. uf_linear = fit(UnfoldModel, design_linear, evts, signal); uf_spl3 = fit(UnfoldModel, design_spl3, evts, signal); uf_spl10 = fit(UnfoldModel, design_spl10, evts, signal); #hide # Extract the fitted values using Unfold.effects. p_linear = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_linear); p_spl3 = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_spl3); p_spl10 = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_spl10); first(p_linear, 5) # Plot them. pl = plot(evts.x, signal[1, 1, :]) lines!(p_linear.x, p_linear.yhat) lines!(p_spl3.x, coalesce.(p_spl3.yhat, NaN)) lines!(p_spl10.x, coalesce.(p_spl10.yhat, NaN)) pl # We see here, that the linear effect (blue line) underfits the data, the yellow `spl(x, 10)` overfits it, but the green `spl(x, 4)` fits it perfectly. # ## Looking under the hood # Let's have a brief look how the splines manage what they are managing. # # The most important bit to understand is, that we are replacing `x` by a set of coefficients `spl(x)`. # These new coefficients each tile the range of `x` (in our case, from [0-1]) in overlapping areas, while each will be fit by one coefficient. # Because the ranges are overlapping, we get a smooth function. # # Maybe this becomes clear after looking at a `basisfunction`: term_spl = Unfold.formulas(uf_spl10)[1].rhs.terms[2] # This is the spline term. Note, this is a special type available in the BSplineKit.jl extension in Unfold.jl. It's abstract type is `AbstractSplineTerm` defined in Unfold.jl typeof(term_spl) # const splFunction = Base.get_extension(Unfold, :UnfoldBSplineKitExt).splFunction splFunction([0.2], term_spl) # Each column of this 1-row matrix is a coefficient for our regression model. lines(disallowmissing(splFunction([0.2], term_spl))[1, :]) # Note: We have to use `disallowmissing`, because our splines return a `missing` whenever we ask it to return a value outside its defined range, e.g.: splFunction([-0.2], term_spl) # Because it never has seen any data outside and can't extrapolate! # Back to our main issue. Let's plot the whole basis set basisSet = splFunction(0.0:0.01:1, term_spl) basisSet = disallowmissing(basisSet[.!any(ismissing.(basisSet), dims = 2)[:, 1], :]) # remove missings ax = Axis(Figure()[1, 1]) [lines!(ax, basisSet[:, k]) for k = 1:size(basisSet, 2)] current_figure() # Notice how we flipped the plot around, i.e. now on the x-axis we do not plot the coefficients, but the `x`-values. # Now each line is one basis-function of the spline. # # Unfold returns us one coefficient per basis-function Ξ² = coef(uf_spl10)[1, 1, :] Ξ² = Float64.(disallowmissing(Ξ²)) # But because we used an intercept, we have to do some remodelling in the `basisSet`. X = hcat(ones(size(basisSet, 1)), basisSet[:, 1:5], basisSet[:, 7:end]) # Now we can weight the spline by the `basisfunction`. weighted = (Ξ² .* X') # Plotting them creates a nice looking plot! ax = Axis(Figure()[1, 1]) [lines!(weighted[k, :]) for k = 1:10] current_figure() # Now sum them up. lines(sum(weighted, dims = 1)[1, :]) plot!(X * Ξ², color = "gray") #(same as matrixproduct X*Ξ² directly!) current_figure() # And this is how you can think about splines.
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
5379
# # Window length effects using Unfold, UnfoldSim using CairoMakie, AlgebraOfGraphics, MakieThemes using Random using DataFrames, DataFramesMeta using ColorSchemes, Colors # !!! important # For analyzing real-world EEG data we recommend that researchers should β€” a priori β€” make an educated guess about the length of the underlying EEG activity and select this as their EW. This also suggests to use event windows with different sizes between events (as is possible with Unfold). # Further, as can be seen below, when choosing longer time-windows the overfit is only of moderate size, thus we additionally recommend to generally err on the longer side, to not miss any important activity. \ # For a more in depth explanation on this, you can read our 2023 CCN paper: [Skukies & Ehinger, 2023](https://www.biorxiv.org/content/10.1101/2023.06.05.543689v1) set_theme!(theme_ggthemr(:fresh)) # As opposed to classical averaged ERPs overlap corrected regression ERPs can be influenced by the chosen window length: # Long estimation windows might capture all relevant event-related activity, but might introduce artifacts due to overfit, # short estimation windows might not overfit, but also might not capture all (overlapping) activity, and thereby introduce bias. # # Thus a common question we get is, how to specify the length of the estimation windows. # # Init functions # First we need a function that simulates some continous data; conviently we can use UnfoldSim for this function gen_data(rng, noiselevel, sfreq) noise = PinkNoise(; noiselevel = noiselevel) dat, evts = UnfoldSim.predef_eeg( rng; sfreq = sfreq, p1 = (p100(; sfreq = sfreq), @formula(0 ~ 1 + condition), [5, 0], Dict()), n1 = (n170(; sfreq = sfreq), @formula(0 ~ 1 + condition), [5, 0], Dict()), p3 = (p300(; sfreq = sfreq), @formula(0 ~ 1 + continuous), [5, 0], Dict()), n_repeats = 20, noise = noise, ) return dat, evts end; # Next a convience function to calculate the estimates function calc_time_models(evts, dat, tWinList, sfreq) mList = [] for twindow in tWinList m = fit( UnfoldModel, [Any => (@formula(0 ~ 1), firbasis(twindow, sfreq))], evts, dat, ) res = coeftable(m) res.tWin .= string.(Ref(twindow[2])) push!(mList, res) end return vcat(mList...) end; # # Init variables tWinList = [(-0.1, x) for x in [3, 2.5, 2, 1.5, 1, 0.5]] noiselevel = 8.5 sfreq = 250; # # Generate data and calculate estimates dat, evts = gen_data(MersenneTwister(2), noiselevel, sfreq); res = calc_time_models(evts, dat, tWinList, sfreq); # We also append some additional information to the results dataframe # For comparison lets also generate the ground truth of our data; this is a bit cumbersome and you don't have to care (too much) about it dat_gt, evts_gt = UnfoldSim.predef_eeg(; p1 = (p100(; sfreq = sfreq), @formula(0 ~ 1), [5], Dict()), sfreq = sfreq, n1 = (n170(; sfreq = sfreq), @formula(0 ~ 1), [5], Dict()), p3 = (p300(; sfreq = sfreq), @formula(0 ~ 1), [5], Dict()), n_repeats = 1, noiselevel = 0, return_epoched = true, ); time_gt = range(0, length = length(dat_gt[:, 1]), step = 1 / sfreq) unique_event = unique(res.tWin) df_gt = DataFrame( tWin = reduce(vcat, fill.(unique_event, length(dat_gt[:, 1]))), eventname = Any, channel = repeat([1], length(dat_gt[:, 1]) * length(unique_event)), coefname = reduce( vcat, fill("GroundTruth", length(dat_gt[:, 1]) * length(unique_event)), ), estimate = repeat(dat_gt[:, 1], length(unique_event)), group = reduce(vcat, fill(nothing, length(dat_gt[:, 1]) * length(unique_event))), stderror = reduce(vcat, fill(nothing, length(dat_gt[:, 1]) * length(unique_event))), time = repeat(time_gt, length(unique_event)), ); # And append ground truth to our results df res_gt = vcat(res, df_gt); # # Plot results # Choose which data to plot h_t = AlgebraOfGraphics.data(res) * mapping( :time, :estimate, color = :tWin, group = (:tWin, :coefname) => (x, y) -> string(x[2]) * y, ); # We use the following to plot some length indicator lines untWin = unique(res_gt.tWin) segDF = DataFrame( :x => hcat(repeat([-0.1], length(untWin)), parse.(Float64, untWin))[:], :y => repeat(reverse(1:length(untWin)), outer = 2), ) segDF.tWin .= "0.0" segDF.tWin .= segDF.x[reverse(segDF.y .+ 6)] segDF.y = segDF.y .* 0.2 .+ 6; # Layer for indicator lines h_l = AlgebraOfGraphics.data(@subset(segDF, :tWin .!= "3.0")) * mapping(:x, :y, color = :tWin, group = :tWin => x -> string.(x)); # Ground truth Layer h_gt = AlgebraOfGraphics.data(df_gt) * mapping(:time, :estimate, group = (:tWin, :coefname) => (x, y) -> string(x) * y) * visual(Lines, linewidth = 5, color = Colors.Gray(0.6)); # Add all visuals together and draw h1 = h_gt + visual(Lines, colormap = get(ColorSchemes.Blues, 0.3:0.01:1.2)) * (h_l + h_t) |> x -> draw(x, axis = (; xlabel = "time [s]", ylabel = "estimate [a.u.]")); # Add zero grid lines h1 = hlines!(current_axis(), [0], color = Colors.Gray(0.8)); h2 = vlines!(current_axis(), [0], color = Colors.Gray(0.8)); translate!(h1, 0, 0, -1); translate!(h2, 0, 0, -1); # Plot figure current_figure()
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
52689
### A Pluto.jl notebook ### # v0.19.11 using Markdown using InteractiveUtils # ╔═║ 1eec25bc-8040-11ec-024c-c54939c335ac begin using CairoMakie using DataFrames using Random using Unfold using Colors end # ╔═║ f926f2a9-d188-4c65-80c7-0e500d9c3b9a begin rng = MersenneTwister(2) n = 20 evts = DataFrame(:x => rand(rng, n)) signal = -(3 * (evts.x .- 0.5)) .^ 2 .+ 0.5 .* rand(rng, n) signal = reshape(signal, length(signal), 1, 1) signal = permutedims(signal, [3, 2, 1]) end; # ╔═║ 248e07ea-bf5b-4c88-97c6-e29d0576bdaa begin design_spl3 = Dict(Any => (@formula(0 ~ 1 + spl(x, 3)), [0])) uf_spl3 = fit(UnfoldModel, design_spl3, evts, signal) end; # ╔═║ fea2e408-baa5-426c-a125-6ef68953abce begin design_lin = Dict(Any => (@formula(0 ~ 1 + x), [0])) uf_lin = fit(UnfoldModel, design_lin, evts, signal) end; # ╔═║ f30a9476-b884-44e4-b2e9-b6ca722e52da begin design_spl10 = Dict(Any => (@formula(0 ~ 1 + spl(x, 10)), [0])) uf_spl10 = fit(UnfoldModel, design_spl10, evts, signal) end; # ╔═║ 144b86fc-b860-4f12-9250-0d7926e68cc5 begin p_3 = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_spl3) p_10 = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_spl10) p_l = Unfold.effects(Dict(:x => range(0, stop = 1, length = 100)), uf_lin) end; # ╔═║ 8633dc2f-cde4-45ca-8378-d4703804d02f begin pl = plot(evts.x, signal[1, 1, :]) lines!(p_l.x, p_l.yhat) lines!(p_3.x, p_3.yhat) lines!(p_10.x, p_10.yhat) pl end # ╔═║ 71e73918-f6c5-4f48-adf2-74875c32833c # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" Colors = "5ae59095-9a9b-59fe-a467-6f913c188581" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Unfold = "181c99d8-e21b-4ff3-b70b-c233eddec679" [compat] CairoMakie = "~0.7.1" Colors = "~0.12.8" DataFrames = "~1.3.2" Unfold = "~0.3.6" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.8.0" manifest_format = "2.0" project_hash = "6b897082068de46dde2708b3814731ba252fe9b7" [[deps.AbstractFFTs]] deps = ["ChainRulesCore", "LinearAlgebra"] git-tree-sha1 = "6f1d9bc1c08f9f4a8fa92e3ea3cb50153a1b40d4" uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" version = "1.1.0" [[deps.AbstractTrees]] git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5" uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" version = "0.3.4" [[deps.Adapt]] deps = ["LinearAlgebra"] git-tree-sha1 = "af92965fb30777147966f58acb05da51c5616b5f" uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" version = "3.3.3" [[deps.Animations]] deps = ["Colors"] git-tree-sha1 = "e81c509d2c8e49592413bfb0bb3b08150056c79d" uuid = "27a7e980-b3e6-11e9-2bcd-0b925532e340" version = "0.4.1" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.ArrayInterface]] deps = ["Compat", "IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"] git-tree-sha1 = "ffc6588e17bcfcaa79dfa5b4f417025e755f83fc" uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9" version = "4.0.1" [[deps.Arrow]] deps = ["ArrowTypes", "BitIntegers", "CodecLz4", "CodecZstd", "DataAPI", "Dates", "Mmap", "PooledArrays", "SentinelArrays", "Tables", "TimeZones", "UUIDs"] git-tree-sha1 = "d4a35c773dd7b07ddeeba36f3520aefe517a70f2" uuid = "69666777-d1a9-59fb-9406-91d4454c9d45" version = "2.2.0" [[deps.ArrowTypes]] deps = ["UUIDs"] git-tree-sha1 = "a0633b6d6efabf3f76dacd6eb1b3ec6c42ab0552" uuid = "31f734f8-188a-4ce0-8406-c8a06bd891cd" version = "1.2.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Automa]] deps = ["Printf", "ScanByte", "TranscodingStreams"] git-tree-sha1 = "d50976f217489ce799e366d9561d56a98a30d7fe" uuid = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b" version = "0.8.2" [[deps.AxisAlgorithms]] deps = ["LinearAlgebra", "Random", "SparseArrays", "WoodburyMatrices"] git-tree-sha1 = "66771c8d21c8ff5e3a93379480a2307ac36863f7" uuid = "13072b0f-2c55-5437-9ae7-d433b7a33950" version = "1.0.1" [[deps.BSplines]] deps = ["LinearAlgebra", "OffsetArrays", "RecipesBase"] git-tree-sha1 = "54308218333f6b8967311c76f2cf89ab495542d6" uuid = "488c2830-172b-11e9-1591-253b8a7df96d" version = "0.3.2" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.BenchmarkTools]] deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"] git-tree-sha1 = "940001114a0147b6e4d10624276d56d531dd9b49" uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" version = "1.2.2" [[deps.BitIntegers]] deps = ["Random"] git-tree-sha1 = "5a814467bda636f3dde5c4ef83c30dd0a19928e0" uuid = "c3b6d118-76ef-56ca-8cc7-ebb389d030a1" version = "0.2.6" [[deps.BlockDiagonals]] deps = ["ChainRulesCore", "FillArrays", "FiniteDifferences", "LinearAlgebra"] git-tree-sha1 = "c42e91f6ef89386413f5803423b106a32850987c" uuid = "0a1fb500-61f7-11e9-3c65-f5ef3456f9f0" version = "0.1.25" [[deps.Bzip2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2" uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" version = "1.0.8+0" [[deps.CEnum]] git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9" uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" version = "0.4.1" [[deps.Cairo]] deps = ["Cairo_jll", "Colors", "Glib_jll", "Graphics", "Libdl", "Pango_jll"] git-tree-sha1 = "d0b3f8b4ad16cb0a2988c6788646a5e6a17b6b1b" uuid = "159f3aea-2a34-519c-b102-8c37f9878175" version = "1.0.5" [[deps.CairoMakie]] deps = ["Base64", "Cairo", "Colors", "FFTW", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "SHA", "StaticArrays"] git-tree-sha1 = "c5c1397a0df375fda6fc20a54c5610c96ad71cf5" uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" version = "0.7.1" [[deps.Cairo_jll]] deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2" uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a" version = "1.16.1+1" [[deps.CategoricalArrays]] deps = ["DataAPI", "Future", "Missings", "Printf", "Requires", "Statistics", "Unicode"] git-tree-sha1 = "c308f209870fdbd84cb20332b6dfaf14bf3387f8" uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597" version = "0.10.2" [[deps.ChainRulesCore]] deps = ["Compat", "LinearAlgebra", "SparseArrays"] git-tree-sha1 = "54fc4400de6e5c3e27be6047da2ef6ba355511f8" uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" version = "1.11.6" [[deps.ChangesOfVariables]] deps = ["ChainRulesCore", "LinearAlgebra", "Test"] git-tree-sha1 = "bf98fa45a0a4cee295de98d4c1462be26345b9a1" uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" version = "0.1.2" [[deps.CodecBzip2]] deps = ["Bzip2_jll", "Libdl", "TranscodingStreams"] git-tree-sha1 = "2e62a725210ce3c3c2e1a3080190e7ca491f18d7" uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd" version = "0.7.2" [[deps.CodecLz4]] deps = ["Lz4_jll", "TranscodingStreams"] git-tree-sha1 = "59fe0cb37784288d6b9f1baebddbf75457395d40" uuid = "5ba52731-8f18-5e0d-9241-30f10d1ec561" version = "0.4.0" [[deps.CodecZlib]] deps = ["TranscodingStreams", "Zlib_jll"] git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da" uuid = "944b1d66-785c-5afd-91f1-9de20f533193" version = "0.7.0" [[deps.CodecZstd]] deps = ["CEnum", "TranscodingStreams", "Zstd_jll"] git-tree-sha1 = "849470b337d0fa8449c21061de922386f32949d9" uuid = "6b39b394-51ab-5f42-8807-6242bab2b4c2" version = "0.7.2" [[deps.ColorBrewer]] deps = ["Colors", "JSON", "Test"] git-tree-sha1 = "61c5334f33d91e570e1d0c3eb5465835242582c4" uuid = "a2cac450-b92f-5266-8821-25eda20663c8" version = "0.4.0" [[deps.ColorSchemes]] deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"] git-tree-sha1 = "6b6f04f93710c71550ec7e16b650c1b9a612d0b6" uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" version = "3.16.0" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.0" [[deps.ColorVectorSpace]] deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"] git-tree-sha1 = "3f1f500312161f1ae067abe07d13b40f78f32e07" uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" version = "0.9.8" [[deps.Colors]] deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40" uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" version = "0.12.8" [[deps.Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "44c37b4636bc54afac5c574d2d02b625349d6582" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.41.0" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" version = "0.5.2+0" [[deps.Conda]] deps = ["Downloads", "JSON", "VersionParsing"] git-tree-sha1 = "6cdc8832ba11c7695f494c9d9a1c31e90959ce0f" uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" version = "1.6.0" [[deps.Contour]] deps = ["StaticArrays"] git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7" uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" version = "0.5.7" [[deps.Crayons]] git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15" uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" version = "4.1.1" [[deps.DSP]] deps = ["Compat", "FFTW", "IterTools", "LinearAlgebra", "Polynomials", "Random", "Reexport", "SpecialFunctions", "Statistics"] git-tree-sha1 = "fe2287966e085df821c0694df32d32b6311c6f4c" uuid = "717857b8-e6f2-59f4-9121-6e50c889abd2" version = "0.7.4" [[deps.DataAPI]] git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8" uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" version = "1.9.0" [[deps.DataFrames]] deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] git-tree-sha1 = "ae02104e835f219b8930c7664b8012c93475c340" uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" version = "1.3.2" [[deps.DataStructures]] deps = ["Compat", "InteractiveUtils", "OrderedCollections"] git-tree-sha1 = "3daef5523dd2e769dad2365274f760ff5f282c7d" uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" version = "0.18.11" [[deps.DataValueInterfaces]] git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" version = "1.0.0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DelimitedFiles]] deps = ["Mmap"] uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" [[deps.DensityInterface]] deps = ["InverseFunctions", "Test"] git-tree-sha1 = "80c3e8639e3353e5d2912fb3a1916b8455e2494b" uuid = "b429d917-457f-4dbc-8f4c-0cc954292b1d" version = "0.4.0" [[deps.Distributed]] deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[deps.Distributions]] deps = ["ChainRulesCore", "DensityInterface", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "Test"] git-tree-sha1 = "5863b0b10512ed4add2b5ec07e335dc6121065a5" uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" version = "0.25.41" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.8.6" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.EarCut_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d" uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" version = "2.2.3+0" [[deps.Effects]] deps = ["DataFrames", "LinearAlgebra", "Statistics", "StatsBase", "StatsModels", "Tables"] git-tree-sha1 = "f99ed3dd68cf67f9b3c78ea30a7ab15a527eafc7" uuid = "8f03c58b-bd97-4933-a826-f71b64d2cca2" version = "0.1.5" [[deps.EllipsisNotation]] deps = ["ArrayInterface"] git-tree-sha1 = "d7ab55febfd0907b285fbf8dc0c73c0825d9d6aa" uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949" version = "1.3.0" [[deps.Expat_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b3bfd02e98aedfa5cf885665493c5598c350cd2f" uuid = "2e619515-83b5-522b-bb60-26c02a35a201" version = "2.2.10+0" [[deps.ExprTools]] git-tree-sha1 = "56559bbef6ca5ea0c0818fa5c90320398a6fbf8d" uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" version = "0.1.8" [[deps.FFMPEG]] deps = ["FFMPEG_jll"] git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8" uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a" version = "0.4.1" [[deps.FFMPEG_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"] git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f" uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5" version = "4.4.0+0" [[deps.FFTW]] deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"] git-tree-sha1 = "463cb335fa22c4ebacfd1faba5fde14edb80d96c" uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" version = "1.4.5" [[deps.FFTW_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea" uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a" version = "3.3.10+0" [[deps.FileIO]] deps = ["Pkg", "Requires", "UUIDs"] git-tree-sha1 = "67551df041955cc6ee2ed098718c8fcd7fc7aebe" uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" version = "1.12.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FillArrays]] deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"] git-tree-sha1 = "8756f9935b7ccc9064c6eef0bff0ad643df733a3" uuid = "1a297f60-69ca-5386-bcde-b61e274b549b" version = "0.12.7" [[deps.FiniteDifferences]] deps = ["ChainRulesCore", "LinearAlgebra", "Printf", "Random", "Richardson", "StaticArrays"] git-tree-sha1 = "ebebaefe1f42864f26e50ea1fa54a8e4cadb5992" uuid = "26cc04aa-876d-5657-8c51-4c34ba976000" version = "0.12.20" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [[deps.Fontconfig_jll]] deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03" uuid = "a3f928ae-7b40-5064-980b-68af3947d34b" version = "2.13.93+0" [[deps.Formatting]] deps = ["Printf"] git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8" uuid = "59287772-0a20-5a39-b81b-1366585eb4c0" version = "0.4.2" [[deps.FreeType]] deps = ["CEnum", "FreeType2_jll"] git-tree-sha1 = "cabd77ab6a6fdff49bfd24af2ebe76e6e018a2b4" uuid = "b38be410-82b0-50bf-ab77-7b57e271db43" version = "4.0.0" [[deps.FreeType2_jll]] deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9" uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7" version = "2.10.4+0" [[deps.FreeTypeAbstraction]] deps = ["ColorVectorSpace", "Colors", "FreeType", "GeometryBasics", "StaticArrays"] git-tree-sha1 = "770050893e7bc8a34915b4b9298604a3236de834" uuid = "663a7486-cb36-511b-a19d-713bb74d65c9" version = "0.9.5" [[deps.FriBidi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91" uuid = "559328eb-81f9-559d-9380-de523a88c83c" version = "1.0.10+0" [[deps.Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[deps.GLM]] deps = ["Distributions", "LinearAlgebra", "Printf", "Reexport", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "StatsModels"] git-tree-sha1 = "fb764dacfa30f948d52a6a4269ae293a479bbc62" uuid = "38e38edf-8417-5370-95a0-9cbb8c7f171a" version = "1.6.1" [[deps.GeometryBasics]] deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"] git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c" uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326" version = "0.4.1" [[deps.Gettext_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"] git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046" uuid = "78b55507-aeef-58d4-861c-77aaff3498b1" version = "0.21.0+0" [[deps.Glib_jll]] deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "a32d672ac2c967f3deb8a81d828afc739c838a06" uuid = "7746bdde-850d-59dc-9ae8-88ece973131d" version = "2.68.3+2" [[deps.Graphics]] deps = ["Colors", "LinearAlgebra", "NaNMath"] git-tree-sha1 = "1c5a84319923bea76fa145d49e93aa4394c73fc2" uuid = "a2bd30eb-e257-5431-a919-1863eab51364" version = "1.1.1" [[deps.Graphite2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011" uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472" version = "1.3.14+0" [[deps.GridLayoutBase]] deps = ["GeometryBasics", "InteractiveUtils", "Observables"] git-tree-sha1 = "70938436e2720e6cb8a7f2ca9f1bbdbf40d7f5d0" uuid = "3955a311-db13-416c-9275-1d80ed98e5e9" version = "0.6.4" [[deps.Grisu]] git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2" uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe" version = "1.0.2" [[deps.HarfBuzz_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"] git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3" uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566" version = "2.8.1+1" [[deps.IfElse]] git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1" uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173" version = "0.1.1" [[deps.ImageCore]] deps = ["AbstractFFTs", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Graphics", "MappedArrays", "MosaicViews", "OffsetArrays", "PaddedViews", "Reexport"] git-tree-sha1 = "9a5c62f231e5bba35695a20988fc7cd6de7eeb5a" uuid = "a09fc81d-aa75-5fe9-8630-4744c3626534" version = "0.9.3" [[deps.ImageIO]] deps = ["FileIO", "Netpbm", "OpenEXR", "PNGFiles", "QOI", "Sixel", "TiffImages", "UUIDs"] git-tree-sha1 = "816fc866edd8307a6e79a575e6585bfab8cef27f" uuid = "82e4d734-157c-48bb-816b-45c225c6df19" version = "0.6.0" [[deps.Imath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "87f7662e03a649cffa2e05bf19c303e168732d3e" uuid = "905a6f67-0a94-5f89-b386-d35d92009cd1" version = "3.1.2+0" [[deps.IncompleteLU]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "a22b92ffedeb499383720dfedcd473deb9608b62" uuid = "40713840-3770-5561-ab4c-a76e7d0d7895" version = "0.2.0" [[deps.IndirectArrays]] git-tree-sha1 = "012e604e1c7458645cb8b436f8fba789a51b257f" uuid = "9b13fd28-a010-5f03-acff-a1bbcff69959" version = "1.0.0" [[deps.Inflate]] git-tree-sha1 = "f5fc07d4e706b84f72d54eedcc1c13d92fb0871c" uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9" version = "0.1.2" [[deps.InlineStrings]] deps = ["Parsers"] git-tree-sha1 = "8d70835a3759cdd75881426fced1508bb7b7e1b6" uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" version = "1.1.1" [[deps.IntelOpenMP_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c" uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0" version = "2018.0.3+2" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.Interpolations]] deps = ["AxisAlgorithms", "ChainRulesCore", "LinearAlgebra", "OffsetArrays", "Random", "Ratios", "Requires", "SharedArrays", "SparseArrays", "StaticArrays", "WoodburyMatrices"] git-tree-sha1 = "b15fc0a95c564ca2e0a7ae12c1f095ca848ceb31" uuid = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59" version = "0.13.5" [[deps.IntervalSets]] deps = ["Dates", "EllipsisNotation", "Statistics"] git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758" uuid = "8197267c-284f-5f27-9208-e0e47529a953" version = "0.5.3" [[deps.Intervals]] deps = ["Dates", "Printf", "RecipesBase", "Serialization", "TimeZones"] git-tree-sha1 = "323a38ed1952d30586d0fe03412cde9399d3618b" uuid = "d8418881-c3e1-53bb-8760-2df7ec849ed5" version = "1.5.0" [[deps.InverseFunctions]] deps = ["Test"] git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65" uuid = "3587e190-3f89-42d0-90ee-14403ec27112" version = "0.1.2" [[deps.InvertedIndices]] git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f" uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" version = "1.1.0" [[deps.IrrationalConstants]] git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151" uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" version = "0.1.1" [[deps.Isoband]] deps = ["isoband_jll"] git-tree-sha1 = "f9b6d97355599074dc867318950adaa6f9946137" uuid = "f1662d9f-8043-43de-a69a-05efc1cc6ff4" version = "0.1.1" [[deps.IterTools]] git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5" uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e" version = "1.4.0" [[deps.IterativeSolvers]] deps = ["LinearAlgebra", "Printf", "Random", "RecipesBase", "SparseArrays"] git-tree-sha1 = "1169632f425f79429f245113b775a0e3d121457c" uuid = "42fd0dbc-a981-5370-80f2-aaf504508153" version = "0.9.2" [[deps.IteratorInterfaceExtensions]] git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" uuid = "82899510-4779-5014-852e-03e436cf321d" version = "1.0.0" [[deps.JLLWrappers]] deps = ["Preferences"] git-tree-sha1 = "22df5b96feef82434b07327e2d3c770a9b21e023" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.4.0" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.2" [[deps.JSON3]] deps = ["Dates", "Mmap", "Parsers", "StructTypes", "UUIDs"] git-tree-sha1 = "7d58534ffb62cd947950b3aa9b993e63307a6125" uuid = "0f8b85d8-7281-11e9-16c2-39a750bddbf1" version = "1.9.2" [[deps.KernelDensity]] deps = ["Distributions", "DocStringExtensions", "FFTW", "Interpolations", "StatsBase"] git-tree-sha1 = "591e8dc09ad18386189610acafb970032c519707" uuid = "5ab0869b-81aa-558d-bb23-cbf5423bbe9b" version = "0.6.3" [[deps.LAME_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c" uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d" version = "3.100.1+0" [[deps.LZO_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6" uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac" version = "2.10.1+0" [[deps.LaTeXStrings]] git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996" uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" version = "1.3.0" [[deps.LazyArtifacts]] deps = ["Artifacts", "Pkg"] uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" [[deps.LeftChildRightSiblingTrees]] deps = ["AbstractTrees"] git-tree-sha1 = "b864cb409e8e445688bc478ef87c0afe4f6d1f8d" uuid = "1d6d02ad-be62-4b6b-8a6d-2f90e265016e" version = "0.1.3" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.3" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "7.84.0+0" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.10.2+0" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Libffi_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290" uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490" version = "3.2.2+1" [[deps.Libgcrypt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"] git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae" uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4" version = "1.8.7+0" [[deps.Libgpg_error_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9" uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8" version = "1.42.0+0" [[deps.Libiconv_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778" uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" version = "1.16.1+1" [[deps.Libmount_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73" uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9" version = "2.35.0+0" [[deps.Libuuid_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066" uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700" version = "2.36.0+0" [[deps.LinearAlgebra]] deps = ["Libdl", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.LogExpFunctions]] deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"] git-tree-sha1 = "e5718a00af0ab9756305a0392832c8952c7426c1" uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" version = "0.3.6" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.Lz4_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "5d494bc6e85c4c9b626ee0cab05daa4085486ab1" uuid = "5ced341a-0733-55b8-9ab6-a4889d929147" version = "1.9.3+0" [[deps.MKL_jll]] deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"] git-tree-sha1 = "5455aef09b40e5020e1520f551fa3135040d4ed0" uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7" version = "2021.1.1+2" [[deps.MLBase]] deps = ["IterTools", "Random", "Reexport", "StatsBase"] git-tree-sha1 = "3bd9fd4baf19dfc1edf344bc578da7f565da2e18" uuid = "f0e99cf1-93fa-52ec-9ecc-5026115318e0" version = "0.9.0" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.9" [[deps.Makie]] deps = ["Animations", "Base64", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "Contour", "Distributions", "DocStringExtensions", "FFMPEG", "FileIO", "FixedPointNumbers", "Formatting", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageIO", "IntervalSets", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MakieCore", "Markdown", "Match", "MathTeXEngine", "Observables", "OffsetArrays", "Packing", "PlotUtils", "PolygonOps", "Printf", "Random", "RelocatableFolders", "Serialization", "Showoff", "SignedDistanceFields", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "UnicodeFun"] git-tree-sha1 = "8222fe4310820801c6590256b0df7f83bfa78c1a" uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" version = "0.16.2" [[deps.MakieCore]] deps = ["Observables"] git-tree-sha1 = "c5fb1bfac781db766f9e4aef96adc19a729bc9b2" uuid = "20f20a25-4f0e-4fdf-b5d1-57303727442b" version = "0.2.1" [[deps.MappedArrays]] git-tree-sha1 = "e8b359ef06ec72e8c030463fe02efe5527ee5142" uuid = "dbb5928d-eab1-5f90-85c2-b9b0edb7c900" version = "0.4.1" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.Match]] git-tree-sha1 = "1d9bc5c1a6e7ee24effb93f175c9342f9154d97f" uuid = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf" version = "1.2.0" [[deps.MathOptInterface]] deps = ["BenchmarkTools", "CodecBzip2", "CodecZlib", "JSON", "LinearAlgebra", "MutableArithmetics", "OrderedCollections", "Printf", "SparseArrays", "Test", "Unicode"] git-tree-sha1 = "38062215a56109442d4ec25a0a2970cbfef55bbc" uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" version = "0.10.7" [[deps.MathProgBase]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "9abbe463a1e9fc507f12a69e7f29346c2cdc472c" uuid = "fdba3010-5040-5b88-9595-932c9decdf73" version = "0.7.8" [[deps.MathTeXEngine]] deps = ["AbstractTrees", "Automa", "DataStructures", "FreeTypeAbstraction", "GeometryBasics", "LaTeXStrings", "REPL", "RelocatableFolders", "Test"] git-tree-sha1 = "70e733037bbf02d691e78f95171a1fa08cdc6332" uuid = "0a4f8689-d25c-4efe-a92b-7142dfc1aa53" version = "0.2.1" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.0+0" [[deps.Missings]] deps = ["DataAPI"] git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f" uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" version = "1.0.2" [[deps.MixedModels]] deps = ["Arrow", "DataAPI", "Distributions", "GLM", "JSON3", "LazyArtifacts", "LinearAlgebra", "Markdown", "NLopt", "PooledArrays", "ProgressMeter", "Random", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsFuns", "StatsModels", "StructTypes", "Tables"] git-tree-sha1 = "173c9a62d9a5a29ba7db37fd12d60bf0aab6757a" uuid = "ff71e718-51f3-5ec2-a782-8ffcbfa3c316" version = "4.6.0" [[deps.MixedModelsPermutations]] deps = ["BlockDiagonals", "LinearAlgebra", "MixedModels", "Random", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsModels", "Tables"] git-tree-sha1 = "841e53d597f79846e99e3d9923452c6d14219ed7" uuid = "647c4018-d7ef-4d03-a0cc-8889a722319e" version = "0.1.3" [[deps.MixedModelsSim]] deps = ["LinearAlgebra", "MixedModels", "PooledArrays", "PrettyTables", "Random", "Statistics", "Tables"] git-tree-sha1 = "96ce9a3dd9499fd679a4ffd494d339d50248da0e" uuid = "d5ae56c5-23ca-4a1f-b505-9fc4796fc1fe" version = "0.2.6" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.Mocking]] deps = ["Compat", "ExprTools"] git-tree-sha1 = "29714d0a7a8083bba8427a4fbfb00a540c681ce7" uuid = "78c3b35d-d492-501b-9361-3d52fe80e533" version = "0.7.3" [[deps.MosaicViews]] deps = ["MappedArrays", "OffsetArrays", "PaddedViews", "StackViews"] git-tree-sha1 = "b34e3bc3ca7c94914418637cb10cc4d1d80d877d" uuid = "e94cdb99-869f-56ef-bcf0-1ae2bcbe0389" version = "0.3.3" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2022.2.1" [[deps.MutableArithmetics]] deps = ["LinearAlgebra", "SparseArrays", "Test"] git-tree-sha1 = "73deac2cbae0820f43971fad6c08f6c4f2784ff2" uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" version = "0.3.2" [[deps.NLopt]] deps = ["MathOptInterface", "MathProgBase", "NLopt_jll"] git-tree-sha1 = "f115030b9325ca09ef1619ba0617b2a64101ce84" uuid = "76087f3c-5699-56af-9a33-bf431cd00edd" version = "0.6.4" [[deps.NLopt_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9b1f15a08f9d00cdb2761dcfa6f453f5d0d6f973" uuid = "079eb43e-fd8e-5478-9966-2cf3e3edb778" version = "2.7.1+0" [[deps.NaNMath]] git-tree-sha1 = "f755f36b19a5116bb580de457cda0c140153f283" uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" version = "0.3.6" [[deps.Netpbm]] deps = ["FileIO", "ImageCore"] git-tree-sha1 = "18efc06f6ec36a8b801b23f076e3c6ac7c3bf153" uuid = "f09324ee-3d7c-5217-9330-fc30815ba969" version = "1.0.2" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.Observables]] git-tree-sha1 = "fe29afdef3d0c4a8286128d4e45cc50621b1e43d" uuid = "510215fc-4207-5dde-b226-833fc4488ee2" version = "0.4.0" [[deps.OffsetArrays]] deps = ["Adapt"] git-tree-sha1 = "043017e0bdeff61cfbb7afeb558ab29536bbb5ed" uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881" version = "1.10.8" [[deps.Ogg_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "887579a3eb005446d514ab7aeac5d1d027658b8f" uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051" version = "1.3.5+1" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" version = "0.3.20+0" [[deps.OpenEXR]] deps = ["Colors", "FileIO", "OpenEXR_jll"] git-tree-sha1 = "327f53360fdb54df7ecd01e96ef1983536d1e633" uuid = "52e1d378-f018-4a11-a4be-720524705ac7" version = "0.3.2" [[deps.OpenEXR_jll]] deps = ["Artifacts", "Imath_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "923319661e9a22712f24596ce81c54fc0366f304" uuid = "18a262bb-aa17-5467-a713-aee519bc75cb" version = "3.1.1+0" [[deps.OpenLibm_jll]] deps = ["Artifacts", "Libdl"] uuid = "05823500-19ac-5b8b-9628-191a04bc5112" version = "0.8.1+0" [[deps.OpenSSL_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "648107615c15d4e09f7eca16307bc821c1f718d8" uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" version = "1.1.13+0" [[deps.OpenSpecFun_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1" uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" version = "0.5.5+0" [[deps.Opus_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720" uuid = "91d4177d-7536-5919-b921-800302f37372" version = "1.3.2+0" [[deps.OrderedCollections]] git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.4.1" [[deps.PCRE_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488" uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc" version = "8.44.0+0" [[deps.PDMats]] deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"] git-tree-sha1 = "ee26b350276c51697c9c2d88a072b339f9f03d73" uuid = "90014a1f-27ba-587c-ab20-58faa44d9150" version = "0.11.5" [[deps.PNGFiles]] deps = ["Base64", "CEnum", "ImageCore", "IndirectArrays", "OffsetArrays", "libpng_jll"] git-tree-sha1 = "6d105d40e30b635cfed9d52ec29cf456e27d38f8" uuid = "f57f5aa1-a3ce-4bc8-8ab9-96f992907883" version = "0.3.12" [[deps.Packing]] deps = ["GeometryBasics"] git-tree-sha1 = "1155f6f937fa2b94104162f01fa400e192e4272f" uuid = "19eb6ba3-879d-56ad-ad62-d5c202156566" version = "0.4.2" [[deps.PaddedViews]] deps = ["OffsetArrays"] git-tree-sha1 = "03a7a85b76381a3d04c7a1656039197e70eda03d" uuid = "5432bcbf-9aad-5242-b902-cca2824c8663" version = "0.5.11" [[deps.Pango_jll]] deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "FriBidi_jll", "Glib_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "9bc1871464b12ed19297fbc56c4fb4ba84988b0d" uuid = "36c8627f-9965-5494-a995-c6b170f724f3" version = "1.47.0+0" [[deps.Parsers]] deps = ["Dates"] git-tree-sha1 = "92f91ba9e5941fc781fecf5494ac1da87bdac775" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.2.0" [[deps.Pixman_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29" uuid = "30392449-352a-5448-841d-b1acce4e97dc" version = "0.40.1+0" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.8.0" [[deps.PkgBenchmark]] deps = ["BenchmarkTools", "Dates", "InteractiveUtils", "JSON", "LibGit2", "Logging", "Pkg", "Printf", "TerminalLoggers", "UUIDs"] git-tree-sha1 = "e4a10b7cdb7ec836850e43a4cee196f4e7b02756" uuid = "32113eaa-f34f-5b0d-bd6c-c81e245fc73d" version = "0.2.12" [[deps.PkgVersion]] deps = ["Pkg"] git-tree-sha1 = "a7a7e1a88853564e551e4eba8650f8c38df79b37" uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688" version = "0.1.1" [[deps.PlotUtils]] deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"] git-tree-sha1 = "6f1b25e8ea06279b5689263cc538f51331d7ca17" uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043" version = "1.1.3" [[deps.PolygonOps]] git-tree-sha1 = "77b3d3605fc1cd0b42d95eba87dfcd2bf67d5ff6" uuid = "647866c9-e3ac-4575-94e7-e3d426903924" version = "0.1.2" [[deps.Polynomials]] deps = ["Intervals", "LinearAlgebra", "MutableArithmetics", "RecipesBase"] git-tree-sha1 = "f184bc53e9add8c737e50fa82885bc3f7d70f628" uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45" version = "2.0.24" [[deps.PooledArrays]] deps = ["DataAPI", "Future"] git-tree-sha1 = "db3a23166af8aebf4db5ef87ac5b00d36eb771e2" uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" version = "1.4.0" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "2cf929d64681236a2e074ffafb8d568733d2e6af" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.2.3" [[deps.PrettyTables]] deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"] git-tree-sha1 = "dfb54c4e414caa595a1f2ed759b160f5a3ddcba5" uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" version = "1.3.1" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.Profile]] deps = ["Printf"] uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" [[deps.ProgressLogging]] deps = ["Logging", "SHA", "UUIDs"] git-tree-sha1 = "80d919dee55b9c50e8d9e2da5eeafff3fe58b539" uuid = "33c8b6b6-d38a-422a-b730-caa89a2f386c" version = "0.1.4" [[deps.ProgressMeter]] deps = ["Distributed", "Printf"] git-tree-sha1 = "afadeba63d90ff223a6a48d2009434ecee2ec9e8" uuid = "92933f4c-e287-5a05-a399-4b506db050ca" version = "1.7.1" [[deps.PyCall]] deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"] git-tree-sha1 = "71fd4022ecd0c6d20180e23ff1b3e05a143959c2" uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0" version = "1.93.0" [[deps.PyMNE]] deps = ["PyCall"] git-tree-sha1 = "b3caa6ea95490974465487d54fc1e62a094bad8e" uuid = "6c5003b2-cbe8-491c-a0d1-70088e6a0fd6" version = "0.1.2" [[deps.QOI]] deps = ["ColorTypes", "FileIO", "FixedPointNumbers"] git-tree-sha1 = "18e8f4d1426e965c7b532ddd260599e1510d26ce" uuid = "4b34888f-f399-49d4-9bb3-47ed5cae4e65" version = "1.0.0" [[deps.QuadGK]] deps = ["DataStructures", "LinearAlgebra"] git-tree-sha1 = "78aadffb3efd2155af139781b8a8df1ef279ea39" uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc" version = "2.4.2" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA", "Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Ratios]] deps = ["Requires"] git-tree-sha1 = "01d341f502250e81f6fec0afe662aa861392a3aa" uuid = "c84ed2f1-dad5-54f0-aa8e-dbefe2724439" version = "0.4.2" [[deps.RecipesBase]] git-tree-sha1 = "6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d" uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" version = "1.2.1" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.RelocatableFolders]] deps = ["SHA", "Scratch"] git-tree-sha1 = "cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca" uuid = "05181044-ff0b-4ac5-8273-598c1e38db00" version = "0.1.3" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.3.0" [[deps.Richardson]] deps = ["LinearAlgebra"] git-tree-sha1 = "e03ca566bec93f8a3aeb059c8ef102f268a38949" uuid = "708f8203-808e-40c0-ba2d-98a6953ed40d" version = "1.4.0" [[deps.Rmath]] deps = ["Random", "Rmath_jll"] git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f" uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" version = "0.7.0" [[deps.Rmath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7" uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" version = "0.3.0+0" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.SIMD]] git-tree-sha1 = "39e3df417a0dd0c4e1f89891a281f82f5373ea3b" uuid = "fdea26ae-647d-5447-a871-4b548cad5224" version = "3.4.0" [[deps.ScanByte]] deps = ["Libdl", "SIMD"] git-tree-sha1 = "9cc2955f2a254b18be655a4ee70bc4031b2b189e" uuid = "7b38b023-a4d7-4c5e-8d43-3f3097f304eb" version = "0.3.0" [[deps.Scratch]] deps = ["Dates"] git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda" uuid = "6c6a2e73-6563-6170-7368-637461726353" version = "1.1.0" [[deps.SentinelArrays]] deps = ["Dates", "Random"] git-tree-sha1 = "15dfe6b103c2a993be24404124b8791a09460983" uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" version = "1.3.11" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[deps.ShiftedArrays]] git-tree-sha1 = "22395afdcf37d6709a5a0766cc4a5ca52cb85ea0" uuid = "1277b4bf-5013-50f5-be3d-901d8477a67a" version = "1.0.0" [[deps.Showoff]] deps = ["Dates", "Grisu"] git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de" uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f" version = "1.0.3" [[deps.SignedDistanceFields]] deps = ["Random", "Statistics", "Test"] git-tree-sha1 = "d263a08ec505853a5ff1c1ebde2070419e3f28e9" uuid = "73760f76-fbc4-59ce-8f25-708e95d2df96" version = "0.4.0" [[deps.Sixel]] deps = ["Dates", "FileIO", "ImageCore", "IndirectArrays", "OffsetArrays", "REPL", "libsixel_jll"] git-tree-sha1 = "8fb59825be681d451c246a795117f317ecbcaa28" uuid = "45858cf5-a6b0-47a3-bbea-62219f50df47" version = "0.1.2" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SortingAlgorithms]] deps = ["DataStructures"] git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508" uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" version = "1.0.1" [[deps.SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[deps.SpecialFunctions]] deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] git-tree-sha1 = "e08890d19787ec25029113e88c34ec20cac1c91e" uuid = "276daf66-3868-5448-9aa4-cd146d93841b" version = "2.0.0" [[deps.StackViews]] deps = ["OffsetArrays"] git-tree-sha1 = "46e589465204cd0c08b4bd97385e4fa79a0c770c" uuid = "cae243ae-269e-4f55-b966-ac2d0dc13c15" version = "0.1.1" [[deps.Static]] deps = ["IfElse"] git-tree-sha1 = "b4912cd034cdf968e06ca5f943bb54b17b97793a" uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3" version = "0.5.1" [[deps.StaticArrays]] deps = ["LinearAlgebra", "Random", "Statistics"] git-tree-sha1 = "2884859916598f974858ff01df7dfc6c708dd895" uuid = "90137ffa-7385-5640-81b9-e52037218182" version = "1.3.3" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[deps.StatsAPI]] git-tree-sha1 = "d88665adc9bcf45903013af0982e2fd05ae3d0a6" uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" version = "1.2.0" [[deps.StatsBase]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "51383f2d367eb3b444c961d485c565e4c0cf4ba0" uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" version = "0.33.14" [[deps.StatsFuns]] deps = ["ChainRulesCore", "InverseFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"] git-tree-sha1 = "f35e1879a71cca95f4826a14cdbf0b9e253ed918" uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" version = "0.9.15" [[deps.StatsModels]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Printf", "REPL", "ShiftedArrays", "SparseArrays", "StatsBase", "StatsFuns", "Tables"] git-tree-sha1 = "677488c295051568b0b79a77a8c44aa86e78b359" uuid = "3eaba693-59b7-5ba5-a881-562e759f1c8d" version = "0.6.28" [[deps.StructArrays]] deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"] git-tree-sha1 = "d21f2c564b21a202f4677c0fba5b5ee431058544" uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a" version = "0.6.4" [[deps.StructTypes]] deps = ["Dates", "UUIDs"] git-tree-sha1 = "d24a825a95a6d98c385001212dc9020d609f2d4f" uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" version = "1.8.1" [[deps.SuiteSparse]] deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.0" [[deps.TableTraits]] deps = ["IteratorInterfaceExtensions"] git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" version = "1.0.1" [[deps.Tables]] deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"] git-tree-sha1 = "bb1064c9a84c52e277f1096cf41434b675cd368b" uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" version = "1.6.1" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.TensorCore]] deps = ["LinearAlgebra"] git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" version = "0.1.1" [[deps.TerminalLoggers]] deps = ["LeftChildRightSiblingTrees", "Logging", "Markdown", "Printf", "ProgressLogging", "UUIDs"] git-tree-sha1 = "62846a48a6cd70e63aa29944b8c4ef704360d72f" uuid = "5d786b92-1e48-4d6f-9151-6b4477ca9bed" version = "0.1.5" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.TiffImages]] deps = ["ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "OffsetArrays", "PkgVersion", "ProgressMeter", "UUIDs"] git-tree-sha1 = "991d34bbff0d9125d93ba15887d6594e8e84b305" uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" version = "0.5.3" [[deps.TimeZones]] deps = ["Dates", "Downloads", "InlineStrings", "LazyArtifacts", "Mocking", "Printf", "RecipesBase", "Serialization", "Unicode"] git-tree-sha1 = "0f1017f68dc25f1a0cb99f4988f78fe4f2e7955f" uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53" version = "1.7.1" [[deps.TimerOutputs]] deps = ["ExprTools", "Printf"] git-tree-sha1 = "97e999be94a7147d0609d0b9fc9feca4bf24d76b" uuid = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f" version = "0.5.15" [[deps.TranscodingStreams]] deps = ["Random", "Test"] git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c" uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" version = "0.9.6" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unfold]] deps = ["BSplines", "CategoricalArrays", "DSP", "DataFrames", "Distributions", "DocStringExtensions", "Effects", "GLM", "IncompleteLU", "IterativeSolvers", "LinearAlgebra", "MLBase", "Missings", "MixedModels", "MixedModelsPermutations", "MixedModelsSim", "PkgBenchmark", "ProgressMeter", "PyMNE", "Random", "SparseArrays", "StaticArrays", "Statistics", "StatsBase", "StatsModels", "Tables", "Test", "TimerOutputs"] git-tree-sha1 = "6ed61fa9736d2f214231f28608b13bac2b4d6620" uuid = "181c99d8-e21b-4ff3-b70b-c233eddec679" version = "0.3.6" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.UnicodeFun]] deps = ["REPL"] git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf" uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1" version = "0.4.1" [[deps.VersionParsing]] git-tree-sha1 = "58d6e80b4ee071f5efd07fda82cb9fbe17200868" uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" version = "1.3.0" [[deps.WoodburyMatrices]] deps = ["LinearAlgebra", "SparseArrays"] git-tree-sha1 = "de67fa59e33ad156a590055375a30b23c40299d3" uuid = "efce3f68-66dc-5838-9240-27a6d6f5f9b6" version = "0.5.5" [[deps.XML2_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"] git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a" uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" version = "2.9.12+0" [[deps.XSLT_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"] git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a" uuid = "aed1982a-8fda-507f-9586-7b0439959a61" version = "1.1.34+0" [[deps.Xorg_libX11_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"] git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527" uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc" version = "1.6.9+4" [[deps.Xorg_libXau_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e" uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec" version = "1.0.9+4" [[deps.Xorg_libXdmcp_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4" uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05" version = "1.1.3+4" [[deps.Xorg_libXext_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3" uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3" version = "1.3.4+4" [[deps.Xorg_libXrender_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"] git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96" uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa" version = "0.9.10+4" [[deps.Xorg_libpthread_stubs_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb" uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74" version = "0.1.0+3" [[deps.Xorg_libxcb_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"] git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6" uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b" version = "1.13.0+3" [[deps.Xorg_xtrans_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845" uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10" version = "1.4.0+3" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.12+3" [[deps.Zstd_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6" uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" version = "1.5.0+0" [[deps.isoband_jll]] deps = ["Libdl", "Pkg"] git-tree-sha1 = "a1ac99674715995a536bbce674b068ec1b7d893d" uuid = "9a68df92-36a6-505f-a73e-abb412b6bfb4" version = "0.2.2+0" [[deps.libass_jll]] deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47" uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0" version = "0.15.1+0" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl", "OpenBLAS_jll"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" version = "5.1.1+0" [[deps.libfdk_aac_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55" uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280" version = "2.0.2+0" [[deps.libpng_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"] git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c" uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f" version = "1.6.38+0" [[deps.libsixel_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "78736dab31ae7a53540a6b752efc61f77b304c5b" uuid = "075b6546-f08a-558a-be8f-8157d0f608a5" version = "1.8.6+1" [[deps.libvorbis_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"] git-tree-sha1 = "b910cb81ef3fe6e78bf6acee440bda86fd6ae00c" uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a" version = "1.3.7+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.48.0+0" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+0" [[deps.x264_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2" uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a" version = "2021.5.5+0" [[deps.x265_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9" uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76" version = "3.5.0+0" """ # ╔═║ Cell order: # ╠═1eec25bc-8040-11ec-024c-c54939c335ac # ╠═f926f2a9-d188-4c65-80c7-0e500d9c3b9a # ╠═248e07ea-bf5b-4c88-97c6-e29d0576bdaa # ╠═fea2e408-baa5-426c-a125-6ef68953abce # ╠═f30a9476-b884-44e4-b2e9-b6ca722e52da # ╠═144b86fc-b860-4f12-9250-0d7926e68cc5 # ╠═8633dc2f-cde4-45ca-8378-d4703804d02f # ╠═71e73918-f6c5-4f48-adf2-74875c32833c # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2199
module UnfoldKrylovExt import Krylov using CUDA, CUDA.CUSPARSE, SparseArrays using Unfold using Missings using ProgressMeter """ Alternative implementation of LSMR using Krylov.jl The fastest solver (x30 in some cases) with GPU = true To activate you have to do: > using Krylov,CUDA Difference to solver_default: No suport for per-channel missings. If one sample is missing in any channel, whole channel is removed due a lack of support for Missings in Krylov. """ function solver_krylov( X, data::AbstractArray{T,2}; GPU = false, history = true, multithreading = GPU ? false : true, show_progress = true, stderror = false, ) where {T<:Union{Missing,<:Number}} @assert !(multithreading && GPU) "currently no support for both GPU and multi-threading" minfo = Array{Any,1}(undef, size(data, 1)) ix = any(@. !ismissing(data); dims = 1)[1, :] X_loop = disallowmissing(X[ix, :]) data = disallowmissing(view(data, :, ix)) if GPU X_loop = CuSparseMatrixCSC(X_loop) lsmr_solver = Krylov.LsmrSolver(size(X_loop)..., CuVector{Float64}) data = CuArray(data) else lsmr_solver = Krylov.LsmrSolver(size(X_loop)..., Vector{Float64}) end p = Progress(size(data, 1); enabled = show_progress) beta = zeros(T, size(data, 1), size(X, 2)) # had issues with undef Unfold.@maybe_threads multithreading for ch = 1:size(data, 1) @debug ch data_loop = view(data, ch, :) # use the previous channel as a starting point #ch == 1 || Krylov.warm_start!(lsmr_solver,beta[ch-1,:])#copyto!(view(beta, ch, :), view(beta, ch-1, :)) Krylov.solve!(lsmr_solver, X_loop, data_loop; history = history) beta[ch, :] = Vector(lsmr_solver.x) #beta[ch,:],h = Krylov.lsmr(X_loop,data_loop,history=history) minfo[ch] = deepcopy(lsmr_solver.stats) next!(p) end finish!(p) if stderror stderror = Unfold.calculate_stderror(X, data, beta) modelfit = Unfold.LinearModelFit(beta, ["krylov_lsmr", minfo], stderror) else modelfit = Unfold.LinearModelFit(beta, ["krylov_lsmr", minfo]) end return modelfit end end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1609
module UnfoldRobustModelsExt using Unfold using RobustModels using ProgressMeter using Missings function solver_robust( X, data::AbstractArray{T,3}; estimator = MEstimator{TukeyLoss}(), rlmOptions = (initial_scale = :mad,), ) where {T<:Union{Missing,<:Number}} #beta = zeros(Union{Missing,Number},size(data, 1), size(data, 2), size(X, 2)) beta = zeros(T, size(data, 1), size(data, 2), size(X, 2)) @showprogress 0.1 for ch = 1:size(data, 1) for t = 1:size(data, 2) #@debug("$(ndims(data,)),$t,$ch") dd = view(data, ch, t, :) ix = @. !ismissing(dd) # init beta #if ch == 1 && t==1 #elseif ch > 1 && t == 1 # copyto!(view(beta, ch, 1,:), view(beta, ch-1, 1,:)) #else # copyto!(view(beta, ch,t, :), view(beta, ch,t-1, :)) #end X_local = disallowmissing((X[ix, :])) # view crashes robust model here. XXX follow up once # https://github.com/JuliaStats/GLM.jl/issues/470 received a satisfying result y_local = disallowmissing(@view(data[ch, t, ix])) # if not specified otherwise # this results in strange regularizing effects #if :initial_coef βˆ‰ keys(rlmOptions) # rlmOptions = merge(rlmOptions,(initial_coef=@view(beta[ch,t,:]),)) #end m = rlm(X_local, y_local, estimator; rlmOptions...) beta[ch, t, :] .= coef(m) end end modelfit = Unfold.LinearModelFit(beta, ["solver_robust"]) return modelfit end end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
733
module UnfoldBSplineKitExt using Unfold using BSplineKit using StatsModels import StatsModels: termvars, width, coefnames, modelcols, apply_schema import Base: show using Statistics using DataFrames using Effects using SparseArrays import Unfold: AbstractSplineTerm include("basisfunctions.jl") include("splinepredictors.jl") ## Effects Effects._trmequal(t1::AbstractSplineTerm, t2::AbstractTerm) = Effects._symequal(t1.term, t2) Effects._trmequal(t1::AbstractSplineTerm, t2::AbstractSplineTerm) = Effects._symequal(t1.term, t2.term) Effects._trmequal(t1::AbstractTerm, t2::AbstractSplineTerm) = Effects._symequal(t1, t2.term) Effects._symequal(t1::AbstractTerm, t2::AbstractSplineTerm) = Effects._symequal(t1, t2.term) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
972
splinebasis(; Ο„, sfreq, nsplines, name) = Unfold.splinebasis(Ο„, sfreq, nsplines, name) splinebasis(Ο„, sfreq, nsplines) = Unfold.splinebasis(Ο„, sfreq, nsplines, "basis_" * string(rand(1:10000))) function splinebasis(Ο„, sfreq, nsplines, name::String) Ο„ = Unfold.round_times(Ο„, sfreq) times = range(Ο„[1], stop = Ο„[2], step = 1 ./ sfreq) kernel = e -> splinekernel(e, times, nsplines - 2) shift_onset = Int64(floor(Ο„[1] * sfreq)) colnames = spl_breakpoints(times, nsplines) return SplineBasis(kernel, colnames, times, name, shift_onset) end function spl_breakpoints(times, nsplines) # calculate the breakpoints, evenly spaced return collect(range(minimum(times), stop = maximum(times), length = nsplines)) end function splinekernel(e, times, nsplines) breakpoints = spl_breakpoints(times, nsplines) basis = BSplineKit.BSplineBasis(BSplineOrder(4), breakpoints) # 4= cubic return sparse(splFunction(times, basis)) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
6896
const bsPLINE_CONTEXT = Any mutable struct BSplineTerm{T,D} <: AbstractSplineTerm term::T df::D order::Int breakpoints::Vector end mutable struct PeriodicBSplineTerm{T,D} <: AbstractSplineTerm term::T df::D order::Int low::Real high::Real breakpoints::Vector end """ generate a cubic spline basis function set, with df-1 breakpoints fixed to the quantiles of x minus one due to the intercept. Note: that due to the boundary condition (`natural`) spline, we repeat the boundary knots to each side `order` times, enforcing smoothness there - this is done within BSplineKit """ function genSpl_breakpoints(p::AbstractSplineTerm, x) p = range(0.0, length = p.df - 2, stop = 1.0) breakpoints = quantile(x, p) return breakpoints end """ In the circular case, we do not use quantiles, (circular quantiles are difficult) """ function genSpl_breakpoints(p::PeriodicBSplineTerm, x) # periodic case - return range(p.low, p.high, length = p.df + 2) end """ function that fills in an Matrix `large` according to the evaluated values in `x` with the designmatrix values for the spline. Two separate functions are needed here, as the periodicBSplineBasis implemented in BSplineKits is a bit weird, that it requires to evalute "negative" knots + knots above the top-boundary and fold them down """ function spl_fillMat!(bs::PeriodicBSplineBasis, large::Matrix, x::AbstractVector) # wrap values around the boundaries bnds = boundaries(bs) x = deepcopy(x) x = mod.(x .- bnds[1], period(bs)) .+ bnds[1] for k = -1:length(bs)+2 ix = basis_to_array_index(bs, axes(large, 2), k) large[:, ix] .+= bs[k](x) end return large end function spl_fillMat!(bs::BSplineBasis, large::AbstractMatrix, x::AbstractVector) for k = 1:length(bs) large[:, k] .+= bs[k](x) end bnds = boundaries(bs) ix = x .< bnds[1] .|| x .> bnds[2] if sum(ix) != 0 @warn( "spline prediction outside of possible range putting those values to missing.\n `findfirst(Out-Of-Bound-value)` is x=$(x[findfirst(ix)]), with bounds: $bnds" ) large = allowmissing(large) large[ix, :] .= missing end return large end """ splFunction(x::AbstractVector,bs::AbstractBSplineTerm) _splFunction(x::AbstractVector,bs::AbstractBSplineTerm) evaluate a spline basisset `basis` at `x`. Automatically promotes `x` to Float64 if not AbstractFloat returns `Missing` if x is outside of the basis set """ function _splFunction(x::AbstractVector{T}, bs) where {T<:AbstractFloat} @debug "spl" typeof(x) # init array large = zeros(T, length(x), length(bs)) # fill it with spline values large = spl_fillMat!(bs, large, x) return large end _splFunction(x::AbstractVector, bs) = _splFunction(Float64.(x), bs) splFunction(x, bs) = _splFunction(x, bs) function splFunction(x::AbstractVector, spl::PeriodicBSplineTerm) basis = PeriodicBSplineBasis(BSplineOrder(spl.order), deepcopy(spl.breakpoints)) _splFunction(x, basis) end function splFunction(x::AbstractVector, spl::BSplineTerm) basis = BSplineKit.BSplineBasis(BSplineOrder(spl.order), deepcopy(spl.breakpoints)) _splFunction(x, basis) end #spl(x,df) = Splines2.bs(x,df=df,intercept=true) # assumes intercept Unfold.spl(x, df) = 0 # fallback # make a nice call if the function is called via REPL Unfold.spl(t::Symbol, d::Int) = BSplineTerm(term(t), d, 4, []) Unfold.circspl(t::Symbol, d::Int, low, high) = PeriodicBSplineTerm(term(t), term(d), 4, low, high) """ Construct a BSplineTerm, if breakpoints/basis are not defined yet, put to `nothing` """ function BSplineTerm(term, df, order = 4) @assert df > 3 "Minimal degrees of freedom has to be 4" BSplineTerm(term, df, order, []) end function BSplineTerm(term, df::ConstantTerm, order = 4) BSplineTerm(term, df.n, order, []) end function PeriodicBSplineTerm(term, df, low, high) PeriodicBSplineTerm(term, df, 4, low, high) end function PeriodicBSplineTerm( term::AbstractTerm, df::ConstantTerm, order, low::ConstantTerm, high::ConstantTerm, breakvec, ) PeriodicBSplineTerm(term, df.n, order, low.n, high.n, breakvec) end function PeriodicBSplineTerm(term, df, order, low, high) PeriodicBSplineTerm(term, df, order, low, high, []) end Base.show(io::IO, p::BSplineTerm) = print(io, "spl($(p.term), $(p.df))") Base.show(io::IO, p::PeriodicBSplineTerm) = print(io, "circspl($(p.term), $(p.df),$(p.low):$(p.high))") function StatsModels.apply_schema( t::FunctionTerm{typeof(Unfold.spl)}, sch::StatsModels.Schema, Mod::Type{<:bsPLINE_CONTEXT}, ) @debug "BSpline spl Schema" ar = nothing try ar = t.args catch ar = t.args_parsed # statsmodels < 0.7 end apply_schema(BSplineTerm(ar...), sch, Mod) end function StatsModels.apply_schema( t::FunctionTerm{typeof(Unfold.circspl)}, sch::StatsModels.Schema, Mod::Type{<:bsPLINE_CONTEXT}, ) ar = nothing try ar = t.args catch ar = t.args_parsed # statsmodels < 0.7 end apply_schema(PeriodicBSplineTerm(ar...), sch, Mod) end function StatsModels.apply_schema( t::AbstractSplineTerm, sch::StatsModels.Schema, Mod::Type{<:bsPLINE_CONTEXT}, ) @debug "BSpline Inner schema" term = apply_schema(t.term, sch, Mod) isa(term, ContinuousTerm) || throw(ArgumentError("BSplineTerm only works with continuous terms (got $term)")) if isa(t.df, ConstantTerm) try # in case of ConstantTerm of Èffects.jl`` t.df.n catch throw(ArgumentError("BSplineTerm df must be a number (got $(t.df))")) end end return construct_spline(t, term) end construct_spline(t::BSplineTerm, term) = BSplineTerm(term, t.df, t.order) construct_spline(t::PeriodicBSplineTerm, term) = PeriodicBSplineTerm(term, t.df, t.order, t.low, t.high) function StatsModels.modelcols(p::AbstractSplineTerm, d::NamedTuple) col = modelcols(p.term, d) if isempty(p.breakpoints) p.breakpoints = genSpl_breakpoints(p, col) end #basis = genSpl_basis(pp.breakpoints,p.order)#Splines2.bs_(col,df=p.df+1,intercept=true) #X = Splines2.bs(col, df=p.df+1,intercept=true) X = splFunction(col, p) # remove middle X to negate intercept = true, generating a pseudo effect code return X[:, Not(Int(ceil(end / 2)))] end #StatsModels.terms(p::BSplineTerm) = terms(p.term) StatsModels.termvars(p::AbstractSplineTerm) = StatsModels.termvars(p.term) StatsModels.width(p::AbstractSplineTerm) = p.df - 1 StatsModels.coefnames(p::BSplineTerm) = "spl(" .* coefnames(p.term) .* "," .* string.(1:p.df-1) .* ")" StatsModels.coefnames(p::PeriodicBSplineTerm) = "circspl(" .* coefnames(p.term) .* "," .* string.(1:p.df-1) .* ",$(p.low):$(p.high))"
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
791
module UnfoldMixedModelsExt using Unfold import Unfold: isa_lmm_formula, make_estimate, modelmatrices using MixedModels #import MixedModels.FeMat # extended for sparse femats, type piracy => issue on MixedModels.jl github using StaticArrays # for MixedModels extraction of parametrs (inherited from MixedModels.jl, not strictly needed ) import MixedModels: likelihoodratiotest, ranef using StatsModels import StatsModels: fit!, coef, coefnames, modelcols, modelmatrix using SparseArrays using DocStringExtensions using LinearAlgebra # LowerTriangular using DataFrames using ProgressMeter using SimpleTraits include("typedefinitions.jl") include("condense.jl") include("designmatrix.jl") include("fit.jl") include("statistics.jl") include("timeexpandedterm.jl") include("effects.jl") end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
5157
function MixedModels.tidyσs( m::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) # using MixedModels: AbstractReTerm t = MixedModels.tidyσs(modelfit(m)) reorder_tidyσs(t, Unfold.formulas(m)) end MixedModels.tidyβ(m::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}) = MixedModels.tidyβ(modelfit(m)) """ random_effect_groupings(t::MixedModels.AbstractReTerm) Returns the random effect grouping term (rhs), similar to coefnames, which returns the left hand sides """ random_effect_groupings(t::AbstractTerm) = repeat([nothing], length(t.terms)) random_effect_groupings(t::Unfold.TimeExpandedTerm) = repeat(random_effect_groupings(t.term), length(Unfold.colnames(t.basisfunction))) random_effect_groupings(t::MixedModels.AbstractReTerm) = repeat([t.rhs.sym], length(t.lhs.terms)) random_effect_groupings(f::FormulaTerm) = vcat(random_effect_groupings.(f.rhs)...) random_effect_groupings(t::Vector) = vcat(random_effect_groupings.(t)...) """ reorder_tidyσs(t, f) This function reorders a MixedModels.tidyσs output, according to the formula and not according to the largest RandomGrouping. """ function reorder_tidyσs(t, f) #@debug typeof(f) # get the order from the formula, this is the target f_order = random_effect_groupings(f) # formula order #@debug f_order f_order = vcat(f_order...) #@debug f_order # find the fixefs fixef_ix = isnothing.(f_order) f_order = string.(f_order[.!fixef_ix]) f_name = vcat(coefnames(f)...)[.!fixef_ix] # get order from tidy object t_order = [string(i.group) for i in t if i.iter == 1] t_name = [string(i.column) for i in t if i.iter == 1] # combine for formula and tidy output the group + the coefname #@debug f_order #@debug f_name f_comb = f_order .* f_name t_comb = t_order .* t_name # find for each formula output, the fitting tidy permutation reorder_ix = Int[] for f_coef in f_comb ix = findall(t_comb .== f_coef) # @debug t_comb, f_coef @assert length(ix) == 1 "error in reordering of MixedModels - please file a bugreport!" push!(reorder_ix, ix[1]) end @assert length(reorder_ix) == length(t_comb) #@debug reorder_ix # repeat and build the index for all timepoints reorder_ix_all = repeat(reorder_ix, length(t) ÷ length(reorder_ix)) for k = 1:length(reorder_ix):length(t) reorder_ix_all[k:k+length(reorder_ix)-1] .+= (k - 1) end return t[reorder_ix_all] end """ Unfold.make_estimate(m::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) extracts betas (and sigma's for mixed models) with string grouping indicator returns as a ch x beta, or ch x time x beta (for mass univariate) """ function Unfold.make_estimate( m::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) coefs = coef(m) estimate = cat(coefs, ranef(m), dims = ndims(coefs)) ranef_group = [x.group for x in MixedModels.tidyσs(m)] if ndims(coefs) == 3 group_f = repeat([nothing], size(coefs, 1), size(coefs, 2), size(coefs, ndims(coefs))) # reshape to pred x time x chan and then invert to chan x time x pred ranef_group = permutedims(reshape(ranef_group, :, size(coefs, 2), size(coefs, 1)), [3 2 1]) stderror_fixef = Unfold.stderror(m) stderror_ranef = fill(nothing, size(ranef(m))) stderror = cat(stderror_fixef, stderror_ranef, dims = 3) else group_f = repeat([nothing], size(coefs, 1), size(coefs, 2)) # reshape to time x channel ranef_group = reshape(ranef_group, :, size(coefs, 1)) # permute to channel x time ranef_group = permutedims(ranef_group, [2, 1]) #@debug size(ranef_group) # #ranef_group = repeat(["ranef"], size(coefs, 1), size(ranef(m), 2)) #@debug size(ranef_group) stderror = fill(nothing, size(estimate)) end group = cat(group_f, ranef_group, dims = ndims(coefs)) |> Unfold.poolArray return Float64.(estimate), stderror, group end function Unfold.stderror( m::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) return permutedims( reshape(vcat([[b.se...] for b in modelfit(m).fits]...), reverse(size(coef(m)))), [3, 2, 1], ) end function Unfold.get_coefnames(uf::UnfoldLinearMixedModelContinuousTime) # special case here, because we have to reorder the random effects to the end, else labels get messed up as we concat (coefs,ranefs) # coefnames = Unfold.coefnames(formula(uf)) # coefnames(formula(uf)[1].rhs[1]) formulas = Unfold.formulas(uf) if !isa(formulas, AbstractArray) # in case we have only a single basisfunction formulas = [formulas] end fe_coefnames = vcat([coefnames(f.rhs[1]) for f in formulas]...) re_coefnames = vcat([coefnames(f.rhs[2:end]) for f in formulas]...) return vcat(fe_coefnames, re_coefnames) end Unfold.modelfit(uf::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}) = uf.modelfit.collection
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
8465
function StatsModels.coefnames(term::RandomEffectsTerm) coefnames(term.lhs) end check_groupsorting(r::MatrixTerm) = check_groupsorting(r.terms) function check_groupsorting(r::Tuple) @debug "checking group sorting" ix = findall(isa.(r, MixedModels.AbstractReTerm)) rhs(x::RandomEffectsTerm) = x.rhs rhs(x::MixedModels.ZeroCorr) = rhs(x.term) groupvars = [map(x -> rhs(x).sym, r[ix])...] @assert groupvars == sort(groupvars) "random effects have to be alphabetically ordered. e.g. (1+a|X) + (1+a|A) is not allowed. Please reorder" end function Unfold.unfold_apply_schema( type::Type{<:Union{<:UnfoldLinearMixedModel,<:UnfoldLinearMixedModelContinuousTime}}, f, schema, ) @debug "LMM apply schema" f_new = apply_schema(f, schema, MixedModels.LinearMixedModel) check_groupsorting(f_new.rhs) return f_new end function StatsModels.coefnames(term::MixedModels.ZeroCorr) coefnames(term.term) end function lmm_combine_modelmatrices!(Xcomb, X1, X2) # we have random effects # combine REMats in single-eventtpe formulas ala y ~ (1|x) + (a|x) modelmatrix1 = MixedModels._amalgamate([X1.modelmatrix[2:end]...], Float64) modelmatrix2 = MixedModels._amalgamate([X2.modelmatrix[2:end]...], Float64) Xcomb = (Xcomb, modelmatrix1..., modelmatrix2...) # Next we make the ranefs all equal size equalize_ReMat_lengths!(Xcomb[2:end]) # check if ranefs can be amalgamated. If this fails, then MixedModels tried to amalgamate over different eventtypes and we should throw the warning # if it success, we have to check if the size before and after is identical. If it is not, it tried to amalgamize over different eventtypes which were of the same length try reterms = MixedModels._amalgamate([Xcomb[2:end]...], Float64) if length(reterms) != length(Xcomb[2:end]) throw("IncompatibleRandomGroupings") end catch e @error "Error, you seem to have two different eventtypes with the same random-effect grouping variable. \n This is not allowed, you have to rename one. Example:\n eventA: y~1+(1|item) \n eventB: y~1+(1|item) \n This leads to this error. Rename the later one\n eventB: y~1+(1|itemB) " throw("IncompatibleRandomGroupings") end return Xcomb end function change_ReMat_size!(remat::MixedModels.AbstractReMat, m::Integer) n = m - length(remat.refs) # missing elements if n < 0 deleteat!(remat.refs, range(m + 1, stop = length(remat.refs))) remat.adjA = remat.adjA[:, 1:(m+1)] remat.wtz = remat.wtz[:, 1:(m+1)] remat.z = remat.z[:, 1:(m+1)] elseif n > 0 append!(remat.refs, repeat([remat.refs[end]], n)) remat.adjA = [remat.adjA sparse(repeat([0], size(remat.adjA)[1], n))] remat.wtz = [remat.wtz zeros((size(remat.wtz)[1], n))] remat.z = [remat.z zeros((size(remat.z)[1], n))] end #ReMat{T,S}(remat.trm, refs, levels, cnames, z, wtz, Ξ», inds, adjA, scratch) end """ $(SIGNATURES) Get the timeranges where the random grouping variable was applied """ function get_timeexpanded_random_grouping(tbl_group, tbl_latencies, basisfunction) ranges = Unfold.get_timeexpanded_time_range.(tbl_latencies, Ref(basisfunction)) end function equalize_ReMat_lengths!(remats::NTuple{A,MixedModels.AbstractReMat}) where {A} # find max length m = maximum([x[1] for x in size.(remats)]) @debug "combining lengths: $m" # for each reMat for k in range(1, length = length(remats)) remat = remats[k] if size(remat)[1] == m continue end # prolong if necessary change_ReMat_size!(remat, m) end end mutable struct SparseReMat{T,S} <: MixedModels.AbstractReMat{T} trm::Any refs::Vector{Int32} levels::Any cnames::Vector{String} z::SparseMatrixCSC{T} wtz::SparseMatrixCSC{T} Ξ»::LowerTriangular{T,Matrix{T}} inds::Vector{Int} adjA::SparseMatrixCSC{T,Int32} scratch::Matrix{T} end """ $(SIGNATURES) This function timeexpands the random effects and generates a ReMat object """ function StatsModels.modelcols( term::Unfold.TimeExpandedTerm{ <:Union{<:RandomEffectsTerm,<:MixedModels.AbstractReTerm}, }, tbl, ) # exchange this to get ZeroCorr to work tbl = DataFrame(tbl) # get the non-timeexpanded reMat reMat = modelcols(term.term, tbl) # Timeexpand the designmatrix z = transpose(Unfold.time_expand(transpose(reMat.z), term, tbl)) z = disallowmissing(z) # can't have missing in here # First we check if there is overlap in the timeexpanded term. If so, we cannot continue. Later implementations will remedy that #println(dump(term,)) if hasfield(typeof(term.term), :rhs) rhs = term.term.rhs elseif hasfield(typeof(term.term.term), :rhs) # we probably have something like zerocorr, which does not need to show a .rhs necessarily rhs = term.term.term.rhs else println("term.term: $(dump(term.term))") error("unknown RE structure, has no field .rhs:$(typeof(term.term))") end group = tbl[!, rhs.sym] time = tbl[!, term.eventfields[1]] # get the from-to onsets of the grouping varibales onsets = get_timeexpanded_random_grouping(group, time, term.basisfunction) #print(size(reMat.z)) refs = zeros(size(z)[2]) .+ 1 for (i, o) in enumerate(onsets[2:end]) # check for overlap if (minimum(o) <= maximum(onsets[i+1])) & (maximum(o) <= minimum(onsets[i+1])) error("overlap in random effects structure detected, not currently supported") end end # From now we can assume no overlap # We want to fnd which subject is active when refs = zeros(size(z)[2]) .+ 1 uGroup = unique(group) for (i, g) in enumerate(uGroup[1:end]) ix_start = findfirst(g .== group) ix_end = findlast(g .== group) if i == 1 time_start = 1 else time_start = time[ix_start] # XXX Replace this functionality by shift_onset? time_start = time_start - sum(Unfold.times(term.basisfunction) .<= 0) end if i == length(uGroup) time_stop = size(refs, 1) else time_stop = time[ix_end] time_stop = time_stop + sum(Unfold.times(term.basisfunction) .> 0) end if time_start < 0 time_start = 1 end if time_stop > size(refs, 1) time_stop = size(refs, 1) end #println("$g,$time_start,$time_stop") refs[Int64(time_start):Int64(time_stop)] .= i end # Other variables with implementaions taken from the LinerMixedModel function wtz = z trm = term S = size(z, 1) T = eltype(z) Ξ» = LowerTriangular(Matrix{T}(I, S, S)) inds = MixedModels.sizehint!(Int[], (S * (S + 1)) >> 1) # double trouble? can this line go? m = reshape(1:abs2(S), (S, S)) inds = sizehint!(Int[], (S * (S + 1)) >> 1) for j = 1:S for i = j:S # We currently restrict to diagonal entries # Once mixedmodels#293 is pushed, we can relax this and use zerocorr() if !(typeof(term.term) <: MixedModels.ZeroCorr) || (i == j) # for diagonal push!(inds, m[i, j]) end end end levels = reMat.levels refs = refs # reMat.levels doesnt change cnames = coefnames(term) #print(refs) adjA = MixedModels.adjA(refs, z) scratch = Matrix{T}(undef, (S, length(uGroup))) # Once MixedModels.jl supports it, can be replaced with: SparseReMat ReMat{T,S}(rhs, refs, levels, cnames, z, wtz, Ξ», inds, adjA, scratch) end function change_modelmatrix_size!(m, fe::AbstractSparseMatrix, remats) change_ReMat_size!.(remats, Ref(m)) @debug "changemodelmatrix" typeof(fe) fe = SparseMatrixCSC(m, fe.n, fe.colptr, fe.rowval, fe.nzval) return (fe, remats...) end function change_modelmatrix_size!(m, fe::AbstractMatrix, remats) change_ReMat_size!.(remats, Ref(m)) fe = fe[1:m, :] return (fe, remats...) end """ modelmatrices(modelmatrix::Tuple) in the case of a Tuple (MixedModels - FeMat/ReMat Tuple), returns only the FeMat part """ Unfold.modelmatrices(modelmatrix::Tuple) = modelmatrix[1] #modelcols(rhs::MatrixTerm, tbl) = modelcols.(rhs, Ref(tbl))
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
211
function StatsModels.modelmatrix(model::UnfoldLinearMixedModel, bool) @assert bool == false "time continuous model matrix is not implemented for a `UnfoldLinearMixedModel`" return modelmatrix(model) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
8012
StatsModels.modelmatrix( uf::Union{UnfoldLinearMixedModelContinuousTime,<:UnfoldLinearMixedModel}, ) = modelmatrix(designmatrix(uf)) function StatsModels.modelmatrix( Xs::Vector{ <:Union{DesignMatrixLinearMixedModel,<:DesignMatrixLinearMixedModelContinuousTime}, }, ) @debug "modelmatrix" typeof(Xs) #X_vec = getfield.(designmatrix(uf), :modelmatrix) Xcomb = Xs[1] for k = 2:length(Xs) @debug typeof(Xcomb) typeof(Xs[k]) modelmatrix1 = Unfold.modelmatrices(Xcomb) modelmatrix2 = Unfold.modelmatrices(Xs[k]) @debug typeof(modelmatrix1), typeof(modelmatrix2) Xcomb_temp = Unfold.extend_to_larger(modelmatrix1, modelmatrix2) @debug "tmp" typeof(Xcomb_temp) Xcomb = lmm_combine_modelmatrices!(Xcomb_temp, Xcomb, Xs[k]) @debug "Xcomb" typeof(Xcomb) end Xs = length(Xs) > 1 ? Xcomb : [Xs[1].modelmatrix] return Xs end """ fit!(uf::UnfoldModel,data::Union{<:AbstractArray{T,2},<:AbstractArray{T,3}}) where {T<:Union{Missing, <:Number}} Fit a DesignMatrix against a 2D/3D Array data along its last dimension Data is typically interpreted as channel x time (with basisfunctions) or channel x time x epoch (for mass univariate) - `show_progress` (default:true), deactivate the progressmeter Returns an UnfoldModel object # Examples ```julia-repl ``` """ function StatsModels.fit!( uf::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, data::AbstractArray{T}; show_progress = true, kwargs..., ) where {T} #@assert length(first(values(design(uf)))[2]) if uf isa UnfoldLinearMixedModel if ~isempty(Unfold.design(uf)) @assert length(Unfold.times(Unfold.design(uf))[1]) == size(data, length(size(data)) - 1) "Times Vector does not match second last dimension of input data - forgot to epoch, or misspecified 'time' vector?" end end # function content partially taken from MixedModels.jl bootstrap.jl df = Array{NamedTuple,1}() dataDim = length(size(data)) # surely there is a nicer way to get this but I dont know it @debug typeof(uf) #Xs = modelmatrix(uf) # If we have3 dimension, we have a massive univariate linear mixed model for each timepoint if dataDim == 3 firstData = data[1, 1, :] ntime = size(data, 2) else # with only 2 dimension, we run a single time-expanded linear mixed model per channel/voxel firstData = data[1, :] ntime = 1 end nchan = size(data, 1) Xs = prepare_modelmatrix(uf) _, data = Unfold.equalize_size(Xs[1], data) # get a un-fitted mixed model object #Xs = (Matrix(Xs[1]),Xs[2:end]...) @debug "firstdata" size(firstData) mm = LinearMixedModel_wrapper(Unfold.formulas(uf), firstData, Xs) # prepare some variables to be used βsc, θsc = similar(MixedModels.coef(mm)), similar(mm.θ) # pre allocate p, k = length(βsc), length(θsc) #β_names = (Symbol.(fixefnames(mm))..., ) β_names = (Symbol.(vcat(fixefnames(mm)...))...,) β_names = (unique(β_names)...,) @assert( length(β_names) == length(βsc), "Beta-Names & coefficient length do not match. Did you provide two identical basis functions?" ) #@debug println("beta_names $β_names") #@debug println("uniquelength: $(length(unique(β_names))) / $(length(β_names))") # for each channel prog = Progress(nchan * ntime, 0.1) #@showprogress .1 for ch in range(1, stop = nchan) # for each time for t in range(1, stop = ntime) #@debug "ch:$ch/$nchan, t:$t/$ntime" #@debug "data-size: $(size(data))" #@debug println("mixedModel: $(mm.feterms)") if ndims(data) == 3 @debug typeof(mm) MixedModels.refit!(mm, data[ch, t, :]; progress = false) else #@debug size(mm.y) MixedModels.refit!(mm, data[ch, :]; progress = false) end #@debug println(MixedModels.fixef!(βsc,mm)) β = NamedTuple{β_names}(MixedModels.fixef!(βsc, mm)) out = ( objective = mm.objective, σ = mm.σ, β = NamedTuple{β_names}(MixedModels.fixef!(βsc, mm)), se = SVector{p,Float64}(MixedModels.stderror!(βsc, mm)), #SVector not necessary afaik, took over from MixedModels.jl θ = SVector{k,Float64}(MixedModels.getθ!(θsc, mm)), channel = ch, timeIX = ifelse(dataDim == 2, NaN, t), ) push!(df, out) if show_progress ProgressMeter.next!(prog; showvalues = [(:channel, ch), (:time, t)]) end end end uf.modelfit = UnfoldLinearMixedModelFit{T,ndims(data)}( LinearMixedModelFitCollection{T}( df, deepcopy(mm.λ), getfield.(mm.reterms, :inds), copy(mm.optsum.lowerbd), NamedTuple{Symbol.(fnames(mm))}(map(t -> (t.cnames...,), mm.reterms)), ), ) return uf end function prepare_modelmatrix(uf) Xs = modelmatrix(uf) if isa(Xs, Vector) if length(Xs) > 1 @warn "multi-event LMM currently not supported" end Xs = Xs[1] end Xs = (Unfold.extend_to_larger(Xs[1]), Xs[2:end]...)#(Unfold.extend_to_larger(Xs[1]), Xs[2:end]...) Xs = (disallowmissing(Xs[1]), Xs[2:end]...) return Xs end function StatsModels.coef( uf::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) beta = [x.β for x in MixedModels.tidyβ(uf)] return reshape_lmm(uf, beta) end function MixedModels.ranef( uf::Union{UnfoldLinearMixedModel,UnfoldLinearMixedModelContinuousTime}, ) sigma = [x.σ for x in MixedModels.tidyσs(uf)] return reshape_lmm(uf, sigma) end function reshape_lmm(uf::UnfoldLinearMixedModel, est) ntime = length(Unfold.times(uf)[1]) @debug ntime nchan = modelfit(uf).fits[end].channel return permutedims(reshape(est, :, ntime, nchan), [3 2 1]) end function reshape_lmm(uf::UnfoldLinearMixedModelContinuousTime, est) nchan = modelfit(uf).fits[end].channel return reshape(est, :, nchan)' end LinearMixedModel_wrapper( form, data::AbstractArray{<:Union{TData},1}, Xs; wts = [], ) where {TData<:Union{Missing,Number}} = @error("currently no support for missing values in MixedModels.jl") """ $(SIGNATURES) Wrapper to generate a LinearMixedModel. Code taken from MixedModels.jl and slightly adapted. """ function LinearMixedModel_wrapper( form, data::AbstractArray{<:Union{TData},1}, Xs; wts = [], ) where {TData<:Number} # function LinearMixedModel_wrapper(form,data::Array{<:Union{Missing,TData},1},Xs;wts = []) where {TData<:Number} @debug "LMM wrapper, $(typeof(Xs))" Xs = (Unfold.extend_to_larger(Xs[1]), Xs[2:end]...) # XXX Push this to utilities equalize_size # Make sure X & y are the same size @assert isa(Xs[1], AbstractMatrix) & isa(Xs[2], ReMat) "Xs[1] was a $(typeof(Xs[1])), should be a AbstractMatrix, and Xs[2] was a $(typeof(Xs[2])) should be a ReMat" m = size(Xs[1])[1] if m != size(data)[1] fe, data = Unfold.equalize_size(Xs[1], data) Xs = change_modelmatrix_size!(size(data)[1], fe, Xs[2:end]) end #y = (reshape(float(data), (:, 1))) y = data MixedModels.LinearMixedModel(y, Xs, form, wts) end function MixedModels.LinearMixedModel(y, Xs, form::Array, wts) form_combined = form[1] for f in form[2:end] form_combined = form_combined.lhs ~ MatrixTerm(form_combined.rhs[1] + f.rhs[1]) + form_combined.rhs[2:end] + f.rhs[2:end] end #@debug typeof(form_combined) @debug typeof(y), typeof(Xs), typeof(wts) MixedModels.LinearMixedModel(y, Xs, form_combined, wts) end isa_lmm_formula(f::typeof(MixedModels.zerocorr)) = true
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2371
""" $(SIGNATURES) Returns a partial LMM model (non-functional due to lacking data) to be used in likelihoodratiotests. `k` to selcet which of the modelfit's to fake """ function fake_lmm(m::UnfoldLinearMixedModel, k::Int) mm = modelmatrix(m) @assert length(mm) == 1 "LRT is currently not implemented for fitting multiple events at the same time" feterm = mm[1][1] #reterm = mm[2:end] fakeY = zeros(size(feterm, 1)) lmm = LinearMixedModel_wrapper(Unfold.formulas(m), fakeY, mm[1]) fcoll = Unfold.modelfit(m) #lmm.optsum.feval .= 1 #lmm.optsum.fmin .= 1 lmm.optsum.sigma = fcoll.fits[k].Οƒ lmm.optsum.optimizer = :unfold lmm.optsum.returnvalue = :success setΞΈ!(lmm, fcoll.fits[k].ΞΈ) return lmm end fake_lmm(m::UnfoldLinearMixedModel) = fake_lmm.(m, 1:length(modelfit(m).fits)) """ $(SIGNATURES) Calculate likelihoodratiotest """ function MixedModels.likelihoodratiotest(m::UnfoldLinearMixedModel...) #@info lrtest(fake_lmm.(m,1)...) n = length(Unfold.modelfit(m[1]).fits) lrt = Array{MixedModels.LikelihoodRatioTest}(undef, n) sizehint!(lrt, n) for k = 1:n ms = fake_lmm.(m, k) #@info objective.(ms) lrt[k] = MixedModels.likelihoodratiotest(ms...) end return lrt end """ $(SIGNATURES) Unfold-Method: return pvalues of likelihoodratiotests, typically calculated: # Examples julia> pvalues(likelihoodratiotest(m1,m2)) where m1/m2 are UnfoldLinearMixedModel's Tipp: if you only compare two models you can easily get a vector of p-values: julia> vcat(pvalues(likelihoodratiotest(m1,m2))...) Multiple channels are returned linearized at the moment, as we do not have access to the amount of channels after the LRT, you can do: julia> reshape(vcat(pvalues(likelihoodratiotest(m1,m2))...),ntimes,nchan)' """ function pvalues(lrtvec::Vector{MixedModels.LikelihoodRatioTest}) [lrt.pvalues for lrt in lrtvec] end function MixedModels.rePCA(m::UnfoldLinearMixedModel) oneresult = MixedModels.rePCA(fake_lmm(m, 1)) emptyPCA = (;) for s in keys(oneresult) res = hcat( [ a[s] for a in MixedModels.rePCA.(fake_lmm.(Ref(m), 1:length(modelfit(m).fits))) ]..., ) newPCA = NamedTuple{(s,)}([res]) emptyPCA = merge(emptyPCA, newPCA) end return emptyPCA end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
298
function Unfold.TimeExpandedTerm( term::NTuple{N,Union{<:AbstractTerm,<:MixedModels.RandomEffectsTerm}}, basisfunction, eventfields::Array{Symbol,1}, ) where {N} # for mixed models, apply it to each Term Unfold.TimeExpandedTerm.(term, Ref(basisfunction), Ref(eventfields)) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3398
struct DesignMatrixLinearMixedModel{T} <: AbstractDesignMatrix{T} formula::FormulaTerm modelmatrix::Tuple events::DataFrame end struct DesignMatrixLinearMixedModelContinuousTime{T} <: AbstractDesignMatrix{T} formula::FormulaTerm modelmatrix::Tuple events::DataFrame end DesignMatrixLinearMixedModel{T}() where {T} = DesignMatrixLinearMixedModel{T}(FormulaTerm(:empty, :empty), (), DataFrame()) DesignMatrixLinearMixedModelContinuousTime{T}() where {T} = DesignMatrixLinearMixedModelContinuousTime{T}( FormulaTerm(:empty, :empty), (), DataFrame(), ) struct LinearMixedModelFitCollection{T} <: MixedModels.MixedModelFitCollection{T} fits::Vector Ξ»::Vector inds::Vector{Vector{Int}} lowerbd::Vector{T} fcnames::NamedTuple end LinearMixedModelFitCollection{T}() where {T} = LinearMixedModelFitCollection{T}([], [], Vector{Int}[], T[], (;)) struct UnfoldLinearMixedModelFit{T<:AbstractFloat,N} <: AbstractModelFit{T,N} collection::LinearMixedModelFitCollection{T} end UnfoldLinearMixedModelFit{T,N}() where {T,N} = UnfoldLinearMixedModelFit{T,N}(LinearMixedModelFitCollection{T}()) """ Concrete type to implement an Mass-Univariate LinearMixedModel. `.design` contains the formula + times dict `.designmatrix` contains a `DesignMatrix` `modelfit` is a `Any` container for the model results """ mutable struct UnfoldLinearMixedModel{T} <: UnfoldModel{T} design::Vector{<:Pair} designmatrix::Vector{<:DesignMatrixLinearMixedModel{T}} modelfit::UnfoldLinearMixedModelFit{T,3} # optional info on the modelfit end UnfoldLinearMixedModel(args...; kwargs...) = UnfoldLinearMixedModel{Float64}(args...; kwargs...) UnfoldLinearMixedModel{T}() where {T} = UnfoldLinearMixedModel{T}(Pair[]) UnfoldLinearMixedModel{T}(d::Vector) where {T} = UnfoldLinearMixedModel{T}( d, [DesignMatrixLinearMixedModel{T}()], UnfoldLinearMixedModelFit{T,3}(), ) UnfoldLinearMixedModel{T}(d::Vector, X::Vector{<:AbstractDesignMatrix}) where {T} = UnfoldLinearMixedModel{T}(deepcopy(d), X, DataFrame()) """ Concrete type to implement an deconvolution LinearMixedModel. **Warning** This is to be treated with care, not much testing went into it. `.design` contains the formula + times dict `.designmatrix` contains a `DesignMatrix` `.modelfit` is a `Any` container for the model results """ mutable struct UnfoldLinearMixedModelContinuousTime{T} <: UnfoldModel{T} design::Vector{<:Pair} designmatrix::Vector{<:DesignMatrixLinearMixedModelContinuousTime{T}} modelfit::UnfoldLinearMixedModelFit{T,2} end UnfoldLinearMixedModelContinuousTime(args...; kwargs...) = UnfoldLinearMixedModelContinuousTime{Float64}(args...; kwargs...) UnfoldLinearMixedModelContinuousTime{T}() where {T} = UnfoldLinearMixedModelContinuousTime{T}(Pair[]) UnfoldLinearMixedModelContinuousTime{T}(d::Vector) where {T} = UnfoldLinearMixedModelContinuousTime{T}( d, [DesignMatrixLinearMixedModelContinuousTime{T}()], UnfoldLinearMixedModelFit{T,2}(), ) # empty modelfit UnfoldLinearMixedModelContinuousTime{T}( d::Vector{<:Pair}, X::Vector{<:AbstractDesignMatrix{T}}, ) where {T} = UnfoldLinearMixedModelContinuousTime{T}( deepcopy(d), X, UnfoldLinearMixedModelFit{T,2}(), ) @traitimpl Unfold.ContinuousTimeTrait{UnfoldLinearMixedModelContinuousTime}
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
6510
module Unfold using SimpleTraits using SparseArrays using StatsModels using StatsBase using IterativeSolvers using DataFrames #using MixedModels using Missings using StatsBase using LinearAlgebra using Tables # not sure we need it using GLM # not sure we need it using TimerOutputs # debugging fitting times etc. not strictly needed #using DSP using StatsModels using ProgressMeter using DocStringExtensions # for Docu using MLBase # for crossVal import Term # prettiert output using OrderedCollections # for Base.Show import Term: vstack, Panel, tprint import Term: Tree # to display Dicts using PooledArrays using TypedTables # DataFrames loose the pooled array, so we have to do it differently for now... #using Tullio #using BSplineKit # for spline predictors #using RobustModels # for robust modelling #using CategoricalArrays import StatsBase: fit import StatsBase: coef import StatsBase: fit! import StatsBase: coefnames import StatsBase: modelmatrix import StatsBase: predict import StatsModels: width import StatsModels: terms import StatsBase.quantile import Base.show import Base.(+) # overwrite for DesignMatrices using Distributions: Gamma, pdf # TODO replace this with direct implementation (used in basisfunction.jl) include("typedefinitions.jl") include("basisfunctions.jl") include("timeexpandedterm.jl") include("designmatrix.jl") include("fit.jl") include("utilities.jl") include("condense.jl") include("solver.jl") include("predict.jl") include("splinepredictors.jl") include("effects.jl") include("statistics.jl") include("io.jl") include("show.jl") # pretty printing #include("plot.jl") # don't include for now export fit, fit!, designmatrix! export firbasis, hrfbasis export AbstractDesignMatrix, AbstractModelFit, UnfoldModel export UnfoldLinearModel, UnfoldLinearMixedModel, UnfoldLinearMixedModelContinuousTime, UnfoldLinearModelContinuousTime export FIRBasis, HRFBasis, SplineBasis export modelmatrix, modelmatrices export formulas, design, designmatrix, coef export coeftable, predicttable export modelfit export predict, residuals if !isdefined(Base, :get_extension) ## Extension Compatabality with julia pre 1.9 include("../ext/UnfoldRobustModelsExt.jl") solver_robust = UnfoldRobustModelsExt.solver_robust include("../ext/UnfoldMixedModelsExt/UnfoldMixedModelsExt.jl") pvalues = UnfoldMixedModelsExt.pvalues using MixedModels rePCA = MixedModels.rePCA lmm_combine_modelmatrices! = UnfoldMixedModelsExt.lmm_combine_modelmatrices! likelihoodratiotest = UnfoldMixedModelsExt.likelihoodratiotest check_groupsorting = UnfoldMixedModelsExt.check_groupsorting spl() = error("dummy / undefined") circspl() = error("dummy / undefined") include("../ext/UnfoldBSplineKitExt/UnfoldBSplineKitExt.jl") splinebasis = UnfoldBSplineKitExt.splinebasis # need this definition unfortunatly #circspl = UnfoldBSplineKitExt.circspl #spl = UnfoldBSplineKitExt.spl include("../ext/UnfoldKrylovExt.jl") solver_krylov = UnfoldKrylovExt.solver_krylov else # Jl 1.9+: we need dummy functions, in case the extension was not activated to warn the user if they try to use a functionality that is not yet defined checkFun(sym) = Base.get_extension(@__MODULE__(), sym) function solver_robust(args...; kwargs...) ext = checkFun(:UnfoldRobustModelsExt) msg = "RobustModels not loaded. Please use ]add RobustModels, using RobustModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.solver_robust(args...; kwargs...) end function pvalues(args...; kwargs...) ext = checkFun(:UnfoldMixedModelsExt) msg = "MixedModels not loaded. Please use ]add MixedModels, using MixedModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.pvalues(args...; kwargs...) end function likelihoodratiotest(args...; kwargs...) ext = checkFun(:UnfoldMixedModelsExt) msg = "MixedModels not loaded. Please use ]add MixedModels, using MixedModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.likelihoodratiotest(args...; kwargs...) end function rePCA(args...; kwargs...) ext = checkFun(:UnfoldMixedModelsExt) msg = "MixedModels not loaded. Please use ]add MixedModels, using MixedModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.rePCA(args...; kwargs...) end function check_groupsorting(args...; kwargs...) ext = checkFun(:UnfoldMixedModelsExt) msg = "MixedModels not loaded. Please use ]add MixedModels, using MixedModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.check_groupsorting(args...; kwargs...) end function lmm_combine_modelmatrices!(args...; kwargs...) ext = checkFun(:UnfoldMixedModelsExt) msg = "MixedModels not loaded. Please use ]add MixedModels, using MixedModels to install it prior to using" isnothing(ext) ? throw(msg) : ext.lmm_combine_modelmatrices!(args...; kwargs...) end function splinebasis(args...; kwargs...) ext = checkFun(:UnfoldBSplineKitExt) msg = "BSplineKit not loaded. Please use `]add BSplineKit, using BSplineKit` to install/load it, if you want to use splines" isnothing(ext) ? throw(msg) : ext.splinebasis(args...; kwargs...) end function spl(args...; kwargs...) ext = checkFun(:UnfoldBSplineKitExt) msg = "BSplineKit not loaded. Please use `]add BSplineKit, using BSplineKit` to install/load it, if you want to use splines" isnothing(ext) ? throw(msg) : ext.spl(args...; kwargs...) end function circspl(args...; kwargs...) ext = checkFun(:UnfoldBSplineKitExt) msg = "BSplineKit not loaded. Please use `]add BSplineKit, using BSplineKit` to install/load it, if you want to use splines" isnothing(ext) ? throw(msg) : ext.circspl(args...; kwargs...) end function solver_krylov(args...; kwargs...) ext = checkFun(:UnfoldKrylovExt) msg = "Krylov or CUDA not loaded. Please use `]add Krylov,CUDA, using Krylov,CUDA` to install/load it, if you want to use GPU-fitting" isnothing(ext) ? throw(msg) : ext.solver_krylov(args...; kwargs...) end end export spl, circspl export likelihoodratiotest # statistics.jl export pvalues # statistics.jl export effects # effects.jl import StatsModels.@formula # for exporting export @formula export save export load end # module
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
9968
""" See FIRBasis for an examples a BasisFunction should implement: - kernel() # kernel(b::BasisFunction,sample) => returns the designmatrix for that event - height() # number of samples in continuous time - width() # number of coefficient columns (e.g. HRF 1 to 3, FIR=height(),except if interpolate=true ) - colnames() # unique names of expanded columns - times() # vector of times along expanded columns, length = height() - name() # name of basisfunction - collabel() [default "colname_basis"] # name for coeftable - shift_onset() [default 0] """ abstract type BasisFunction end """ Defines a FIRBasisfunction which can be called for each event, defining the time-expanded basis kernel $(TYPEDEF) $(TYPEDSIGNATURES) $(FIELDS) (tipp: most users would you want to call firbasis, not generate it manually) # Examples ```julia-repl julia> b = FIRBasis(range(0,1,length=10),"basisA",-1) ``` """ mutable struct FIRBasis <: BasisFunction "vector of times along rows of kernel-output (in seconds)" times::Vector "name of the event, should be the actual eventName in `eventcolumn` of the dataframes later" name::Any "by how many samples do we need to shift the event onsets? This number is determined by how many 'negative' timepoints the basisfunction defines" shift_onset::Int64 "should we linearly interpolate events not on full samples?" interpolate::Bool end # default dont interpolate FIRBasis(times, name, shift_onset) = FIRBasis(times, name, shift_onset, false) @deprecate FIRBasis(kernel::Function, times, name, shift_onset) FIRBasis( times, name, shift_onset, ) collabel(basis::FIRBasis) = :time colnames(basis::FIRBasis) = basis.interpolate ? basis.times[1:end-1] : basis.times[1:end] mutable struct SplineBasis <: BasisFunction kernel::Function "vector of names along columns of kernel-output" colnames::AbstractVector " vector of times along rows of kernel-output (in seconds)" times::Vector "name of the event, random 1:1000 if unspecified" name::String "by how many samples do we need to shift the event onsets? This number is determined by how many 'negative' timepoints the basisfunction defines" shift_onset::Int64 end mutable struct HRFBasis <: BasisFunction kernel::Function "vector of names along columns of kernel-output" colnames::AbstractVector " vector of times along rows of kernel-output (in seconds)" times::Vector "name of the event, random 1:1000 if unspecified" name::String end """ $(SIGNATURES) Generate a sparse FIR basis around the *Ο„* timevector at sampling rate *sfreq*. This is useful if you cannot make any assumptions on the shape of the event responses. If unrounded events are supplied, they are split between samples. E.g. event-latency = 1.2 will result in a "0.8" and a "0.2" entry. # keyword arguments `interpolate` (Bool, default false): if true, interpolates events between samples linearly. This results in `predict` functions to return a trailling 0 # Examples Generate a FIR basis function from -0.1s to 0.3s at 100Hz ```julia-repl julia> f = firbasis([-0.1,0.3],100) ``` Evaluate at an event occuring at sample 103.3 ```julia-repl julia> f(103.3) ``` """ function firbasis(Ο„, sfreq, name = ""; interpolate = false) Ο„ = round_times(Ο„, sfreq) if interpolate # stop + 1 step, because we support fractional event-timings Ο„ = (Ο„[1], Ο„[2] + 1 ./ sfreq) end times = range(Ο„[1], stop = Ο„[2], step = 1 ./ sfreq) shift_onset = Int64(floor(Ο„[1] * sfreq)) return FIRBasis(times, name, shift_onset, interpolate) end # cant multiple dispatch on optional arguments #firbasis(;Ο„,sfreq) = firbasis(Ο„,sfreq) firbasis(; Ο„, sfreq, name = "", kwargs...) = firbasis(Ο„, sfreq, name; kwargs...) """ $(SIGNATURES) Calculate a sparse firbasis # Examples ```julia-repl julia> f = firkernel(103.3,range(-0.1,step=0.01,stop=0.31)) ``` """ function firkernel(e, times; interpolate = false) @assert ndims(e) <= 1 #either single onset or a row vector where we will take the first one :) if size(e, 1) > 1 # XXX we will soon assume that the second entry would be the duration e = Float64(e[1]) end ksize = length(times) # kernelsize if interpolate eboth = [1 .- (e .% 1) e .% 1] eboth[isapprox.(eboth, 0, atol = 1e-15)] .= 0 return spdiagm( ksize + 1, ksize, 0 => repeat([eboth[1]], ksize), -1 => repeat([eboth[2]], ksize), ) else #eboth = Int(round(e)) return spdiagm(ksize, ksize, 0 => repeat([1], ksize)) end end """ $(SIGNATURES) Generate a Hemodynamic-Response-Functio (HRF) basis with inverse-samplingrate "TR" (=1/FS) Optional Parameters p: defaults {seconds} p(1) - delay of response (relative to onset) 6 p(2) - delay of undershoot (relative to onset) 16 p(3) - dispersion of response 1 p(4) - dispersion of undershoot 1 p(5) - ratio of response to undershoot 6 p(6) - onset {seconds} 0 p(7) - length of kernel {seconds} 32 # Examples Generate a HRF basis function object with Sampling rate 1/TR. And evaluate it at an event occuring at TR 103.3 with duration of 4.1 TRs ```julia-repl julia> f = hrfbasis(2.3) julia> f(103.3,4.1) ``` """ function hrfbasis(TR::Float64; parameters = [6.0 16.0 1.0 1.0 6.0 0.0 32.0], name = "") # Haemodynamic response function adapted from SPM12b "spm_hrf.m" # Parameters: # defaults # {seconds} # p(1) - delay of response (relative to onset) 6 # p(2) - delay of undershoot (relative to onset) 16 # p(3) - dispersion of response 1 # p(4) - dispersion of undershoot 1 # p(5) - ratio of response to undershoot 6 # p(6) - onset {seconds} 0 # p(7) - length of kernel {seconds} 32 kernel = e -> hrfkernel(e, TR, parameters) return HRFBasis( kernel, ["f(x)"], range(0, (length(kernel([0, 1])) - 1) * TR, step = TR), name, ) end shift_onset(basis::HRFBasis) = 0 collabel(basis::HRFBasis) = :derivative collabel(basis::SplineBasis) = :splineTerm collabel(uf::UnfoldModel) = collabel(formulas(uf)) collabel(form::FormulaTerm) = collabel(form.rhs) collabel(t::Tuple) = collabel(t[1]) # MixedModels has Fixef+ReEf collabel(term::Array{<:AbstractTerm}) = collabel(term[1].rhs) # in case of combined formulas #collabel(form::MatrixTerm) = collabel(form[1].rhs) # typical defaults shift_onset(basis::BasisFunction) = basis.shift_onset colnames(basis::BasisFunction) = basis.colnames kernel(basis::BasisFunction, e) = basis.kernel(e) @deprecate kernel(basis::BasisFunction) basis.kernel basisname(fs::Vector{<:FormulaTerm}) = [name(f.rhs.basisfunction) for f in fs] basisname(uf::UnfoldModel) = basisname(formulas(uf)) basisname(uf::UnfoldLinearModel) = first.(design(uf)) # for linear models we dont save it in the formula kernel(basis::FIRBasis, e) = basis.interpolate ? firkernel(e, basis.times[1:end-1]; interpolate = true) : firkernel(e, basis.times; interpolate = false) times(basis::BasisFunction) = basis.times name(basis::BasisFunction) = basis.name StatsModels.width(basis::BasisFunction) = height(basis) StatsModels.width(basis::FIRBasis) = basis.interpolate ? height(basis) - 1 : height(basis) height(basis::FIRBasis) = length(times(basis)) StatsModels.width(basis::HRFBasis) = 1 times(basis::HRFBasis) = NaN """ $(SIGNATURES) Calculate a HRF kernel. Input e can be [onset duration] # Examples ```julia-repl julia> f = hrfkernel(103.3,2.3,[6. 16. 1. 1. 6. 0. 32.]) ``` """ function hrfkernel(e, TR, p) @assert ndims(e) <= 1 #either single onset or a row vector where we will take the first one :) # code adapted from SPM12b mt = 32 dt = TR / mt firstElem = Int(round((1 - (e[1] % 1)) .* mt)) if size(e, 1) == 2 && e[2] > 0.0 duration = e[2] else duration = 1.0 / mt end duration_mt = Int(ceil(duration .* mt)) box_mt = [zeros(firstElem)' ones(duration_mt)']' #box_mt = box_mt ./ (sum(box_mt)) # u = [0:ceil(p(7)/dt)] - p(6)/dt; u = range(0, stop = ceil((p[7] + duration) / dt)) .- p[6] / dt #hrf = spm_Gpdf(u,p(1)/p(3),dt/p(3)) # Note the inverted scale parameter compared to SPM12. g1 = Gamma(p[1] ./ p[3], p[3] ./ dt) #spm_Gpdf(u,p(2)/p(4),dt/p(4)) g2 = Gamma(p[2] ./ p[4], p[4] ./ dt) # g1 - g2/p(5); hrf = pdf.(g1, u) .- pdf.(g2, u) ./ p[5] # hrf = hrf([0:floor(p(7)/RT)]*fMRI_T + 1); hrf = hrf ./ sum(hrf) hrf = conv1D(box_mt, hrf)' #println(box_mt) hrf = hrf[((range(0, stop = Int(floor(p[7] ./ TR + duration)))*mt)).+1] return (SparseMatrixCSC(sparse(hrf))) end # taken from https://codereview.stackexchange.com/questions/284537/implementing-a-1d-convolution-simd-friendly-in-julia # to replace the DSP.conv function function conv1D!(vO::Array{T,1}, vA::Array{T,1}, vB::Array{T,1})::Array{T,1} where {T<:Real} lenA = length(vA) lenB = length(vB) fill!(vO, zero(T)) for idxB = 1:lenB for idxA = 1:lenA @inbounds vO[idxA+idxB-1] += vA[idxA] * vB[idxB] end end return vO end function conv1D(vA::Array{T,1}, vB::Array{T,1})::Array{T,1} where {T<:Real} lenA = length(vA) lenB = length(vB) vO = Array{T,1}(undef, lenA + lenB - 1) return conv1D!(vO, vA, vB) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
9366
function extract_coef_info(coefs, ix) # 1 = eventname, 2 = coefname, 3 = colname return [c[ix] for c in split.(coefs, " : ")] end function get_coefnames(uf::Union{<:UnfoldModel,<:AbstractDesignMatrix}) coefnames = Unfold.coefnames(formulas(uf)) coefnames = vcat(coefnames...) # gets rid of an empty Any() XXX not sure where it comes from, only in MixedModel Timexpanded case end modelfit(uf::UnfoldModel) = uf.modelfit StatsModels.coef(uf::UnfoldModel) = coef(modelfit(uf)) StatsModels.coef(mf::LinearModelFit) = mf.estimate #= function coeftable2(uf) coefs = coef(uf) ix = get_basis_indices.(Ref(uf), eventnames(uf)) # XXX stderror, group, coefname coefs_views = [@view(coefs[:, i]) for i in ix] XXX = DataFrame() # specify the coefficient dataframe somehow?! result_to_table(uf, coefs_views, XXX) end =# @traitfn function StatsModels.coeftable( uf::T, ) where {T <: UnfoldModel; ContinuousTimeTrait{T}} coefsRaw = get_coefnames(uf) |> poolArray coefs = extract_coef_info(coefsRaw, 2) |> poolArray #colnames_basis_raw = get_basis_colnames(formulas(uf))# this is unconverted basisfunction basis, colnames_basis = extract_coef_info(coefsRaw, 3) |> poolArray # this is converted to strings! basisnames = extract_coef_info(coefsRaw, 1) |> poolArray nchan = size(coef(uf), 1) coefs_rep = permutedims(repeat(coefs, 1, nchan), [2, 1]) if length(colnames_basis) == 1 colnames_basis = [colnames_basis] end colnames_basis_rep = permutedims(repeat(colnames_basis, 1, nchan), [2, 1]) try colnames_basis_rep = parse.(Float64, colnames_basis_rep) catch #do nothing end chan_rep = repeat((1:nchan) |> poolArray, 1, size(colnames_basis_rep, 2)) designkeys = collect(first.(design(uf))) if design(uf) != [:empty => ()] basiskeys = [string(b.name) for b in last.(last.(design(uf)))] eventnames = Array{Union{eltype(designkeys),eltype(basiskeys)}}(undef, length(basisnames)) for (b, d) in zip(basiskeys, designkeys) eventnames[basisnames.==b] .= d end else @warn "No design found, falling back to basisnames instead of eventnames" eventnames = basisnames end eventnames_rep = permutedims(repeat(eventnames |> poolArray, 1, nchan), [2, 1]) @debug typeof(coefs_rep) coefs_rep[1] return make_long_df( uf, coefs_rep, chan_rep, colnames_basis_rep, eventnames_rep, collabel(uf), ) end @traitfn function StatsModels.coeftable( uf::T, ) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} # Mass Univariate Case coefnames = get_coefnames(uf) colnames_basis = collect(last.(last.(design(uf)[1]))) @debug "coefs: $(size(coefnames)),colnames_basis:$(size(colnames_basis)))" @debug "coefs: $coefnames,colnames_basis:$colnames_basis" nchan = size(coef(uf), 1) ncols = length(colnames_basis) ncoefs = length(coefnames) # replicate coefs_rep = permutedims(repeat(coefnames, outer = [1, nchan, ncols]), [2, 3, 1]) colnames_basis_rep = permutedims(repeat(colnames_basis, 1, nchan, ncoefs), [2 1 3]) chan_rep = repeat(1:nchan, 1, ncols, ncoefs) designkeys = collect(first.(design(uf))) if length(designkeys) == 1 # in case of 1 event, repeat it by ncoefs eventnames = repeat([designkeys[1]], ncoefs) else eventnames = String[] for (ix, evt) in enumerate(designkeys) push!(eventnames, repeat([evt], size(modelmatrix(uf)[ix], 2))...) end end eventnames_rep = permutedims(repeat(eventnames, 1, nchan, ncols), [2, 3, 1]) # results = make_long_df(uf, coefs_rep, chan_rep, colnames_basis_rep, eventnames_rep, :time) return results end #--- # Returns a long df given the already matched function make_long_df(m, coefs, chans, colnames, eventnames, collabel) @assert all(size(coefs) .== size(chans)) "coefs, chans and colnames need to have the same size at this point, $(size(coefs)),$(size(chans)),$(size(colnames)), should be $(size(coef(m))))" @assert all(size(coefs) .== size(colnames)) "coefs, chans and colnames need to have the same size at this point" estimate, stderror, group = make_estimate(m) return DataFrame( Dict( :coefname => String.(linearize(coefs)) |> poolArray, :channel => linearize(chans), :eventname => linearize(eventnames), collabel => linearize(colnames), :estimate => linearize(estimate), :stderror => linearize(stderror), :group => linearize(group), ), ) end #--------- stderror(m::UnfoldModel) = stderror(modelfit(m)) function stderror(m::LinearModelFit) if isempty(m.standarderror) stderror = fill(nothing, size(coef(m))) else stderror = Float64.(m.standarderror) end end function make_estimate(uf::UnfoldModel) return Float64.(coef(uf)), stderror(uf), fill(nothing, size(coef(uf))) |> poolArray end # Return the column names of the basis functions. function get_basis_colnames(formula::FormulaTerm) return get_basis_colnames(formula.rhs) end function get_basis_colnames(rhs::Tuple) return colnames(rhs[1].basisfunction) end function get_basis_colnames(rhs::AbstractTerm) return colnames(rhs.basisfunction) end """ get_basisnames(model::UnfoldModel) Return the basisnames for all predictor terms as a vector. The returned vector contains the name of the event type/basis, repeated by their actual coefficient number (after StatsModels.apply_schema / timeexpansion). If a model has more than one event type (e.g. stimulus and fixation), the vectors are concatenated. """ @traitfn function get_basis_names(m::T) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} # Extract the event names from the design design_keys = first.((Unfold.design(m))) # Create a list of the basis names corresponding to each model term basisnames = String[] for (ix, event) in enumerate(design_keys) push!(basisnames, repeat([event], size(modelmatrix(m)[ix], 2))...) end return basisnames end @traitfn get_basis_names(m::T) where {T <: UnfoldModel; ContinuousTimeTrait{T}} = get_basis_names.(formulas(m)) function get_basis_names(m::FormulaTerm) bf = m.rhs.basisfunction # @debug bf return repeat([name(bf)] |> poolArray, width(m.rhs)) end """ get_basis_colnames(m) get_basis_colnames(formulas) returns list of colnames - e.g. times for firbasis. """ get_basis_colnames(formulas::AbstractArray{<:FormulaTerm}) = get_basis_colnames.(formula) """ result_to_table(model<:UnfoldModel, eff::AbstractArray, events::Vector{<:DataFrame}) result_to_table( eff::AbstractArray, events::Vector{<:DataFrame}, times::Vector{<:Vector{<:Number}}, eventnames::Vector) Converts an array-result (prediction or coefficient) together with the events, to a tidy dataframe """ result_to_table(model, eff, events::Vector{<:DataFrame}) = result_to_table(eff, events, times(model), eventnames(model)) # Array directly without in Vector function result_to_table( eff::AbstractArray{<:Union{Number,Missing}}, events::Vector, times::Vector, eventnames, ) 1 == length(times) == length(events) result_to_table([eff], events, times, eventnames) end function result_to_table( eff::Vector{<:AbstractArray}, events::Vector{<:DataFrame}, times::Vector, eventnames::Vector, ) @assert length(eventnames) == length(events) == length(times) times_vecs = repeat.(poolArray.(times), size.(events, 1)) # times_vecs = map((x, n) -> repeat(x, outer = n), poolArray.(times), size.(events, 1)) # init the meta dataframe @debug typeof(times_vecs) size(times_vecs) data_list = [] for (single_events, single_eff, single_times, single_eventname) in zip(events, eff, times_vecs, eventnames) @debug "sizes" size(single_events) size(single_eff) size(single_times) @debug "sizes2" size.(events) size.(times) ntimes = size(single_eff, 2) evts_tbl = repeat(Table(single_events), inner = (ntimes)) time_event = Table( time = single_times |> poolArray, eventname = repeat([single_eventname] |> poolArray, length(single_times)), ) @debug size(time_event) size(evts_tbl) @assert size(evts_tbl) == size(time_event) metadata = Table(evts_tbl, time_event) @debug "metadata" size(metadata) single_data = Table( yhat = single_eff[:],#vec(reshape(single_eff, :, 1)), channel = repeat( (1:size(single_eff, 1)) |> poolArray, outer = size(single_eff, 2) * size(single_eff, 3), ), ) # single_data = hcat(single_data, repeat(metadata, size(single_eff, 1))) @debug size(metadata) size(single_eff) size(single_data) @debug repeat(metadata, inner = size(single_eff, 1))[end] @debug single_data[end] single_data_comb = map(merge, single_data, repeat(metadata, inner = size(single_eff, 1))) push!(data_list, single_data_comb) end return reduce(vcat, data_list) |> t -> DataFrame(columns(t)) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
23394
""" $(SIGNATURES) Combine two UnfoldDesignmatrices. This allows combination of multiple events. This also allows to define events with different lengths. Not supported for models without timebasis, as it is not needed there (one can simply run multiple models) # Examples ```julia-repl julia> basisfunction1 = firbasis(Ο„=(0,1),sfreq = 10,name="basis1") julia> basisfunction2 = firbasis(Ο„=(0,0.5),sfreq = 10,name="basis2") julia> Xdc1 = designmatrix(UnfoldLinearModelContinuousTime([Any=>(@formula 0~1,basisfunction1)],tbl_1) julia> Xdc2 = designmatrix(UnfoldLinearModelContinuousTime([Any=>(@formula 0~1,basisfunction2)],tbl_2) julia> Xdc = Xdc1+Xdc2 ``` """ Base.:+(X1::Vector{T}, X2::T) where {T<:AbstractDesignMatrix} = [X1..., X2] Base.:+(X1::T, X2::T) where {T<:AbstractDesignMatrix} = [X1, X2] Base.:+(X1::Nothing, X2::AbstractDesignMatrix) = [X2] # helper to get the fixef of lmm but the normal matrix elsewhere modelmatrices(modelmatrix::AbstractMatrix) = modelmatrix """ modelmatrices(X::AbstractDesignMatrix) modelmatrices(X::Vector{<:AbstractDesignMatrix}) modelmatrices(modelmatrix::AbstractMatrix) Returns the modelmatrices (also called designmatrices) separately for the events. This is similar to `StatsModels.modelcols`, but merely access the precomputed designmatrix. If the designmatrix needs to be computed, please use `modelcols` Compare to `modelmatrix` which further concatenates the designmatrices (in the ContinuousTime case). """ modelmatrices(X::AbstractDesignMatrix) = modelmatrices(X.modelmatrix) modelmatrices(X::Vector{<:AbstractDesignMatrix}) = modelmatrices.(X) """ $(SIGNATURES) designmatrix(type, f, tbl; kwargs...) Return a *DesignMatrix* used to fit the models. # Arguments - type::UnfoldModel - f::FormulaTerm: Formula to be used in this designmatrix - tbl: Events (usually a data frame) to be modelled - basisfunction::BasisFunction: basisfunction to be used in modeling (if specified) - contrasts::Dict: (optional) contrast to be applied to formula - eventfields::Array: (optional) Array of symbols which are passed to basisfunction event-wise. First field of array always defines eventonset in samples. Default is [:latency] # Examples ```julia-repl julia> designmatrix(UnfoldLinearModelContinuousTime,Dict(Any=>(f,basisfunction1),tbl) ``` """ function designmatrix( unfoldmodeltype::Type{<:UnfoldModel}, f::Union{Tuple,FormulaTerm}, tbl, basisfunction; contrasts = Dict{Symbol,Any}(), eventname = Any, kwargs..., ) @debug("generating DesignMatrix") # check for missings-columns - currently missings not really supported in StatsModels s_tmp = schema(f, tbl, contrasts) # temporary scheme to get necessary terms neededCols = [v.sym for v in values(s_tmp.schema)] tbl_nomissing = DataFrame(tbl) # tbl might be a SubDataFrame due to a view - but we can't modify a subdataframe, can we? try disallowmissing!(tbl_nomissing, neededCols) # if this fails, it means we have a missing value in a column we need. We do not support this catch e if e isa ArgumentError error( e.msg * "\n we tried to get rid of a event-column declared as type Union{Missing,T}. But there seems to be some actual missing values in there. You have to replace them yourself (e.g. replace(tbl.colWithMissingValue,missing=>0)) or impute them otherwise.", ) else rethrow() end end @debug "applying schema $unfoldmodeltype" form = unfold_apply_schema(unfoldmodeltype, f, schema(f, tbl_nomissing, contrasts)) form = apply_basisfunction( form, basisfunction, get(Dict(kwargs), :eventfields, nothing), eventname, ) # Evaluate the designmatrix X = modelcols(form.rhs, tbl_nomissing) designmatrixtype = typeof(designmatrix(unfoldmodeltype())[1]) #return X return designmatrixtype(form, X, tbl) end """ designmatrix(type, f, tbl; kwargs...) call without basis function, continue with basisfunction = `nothing` """ function designmatrix(type, f, tbl; kwargs...) return designmatrix(type, f, tbl, nothing; kwargs...) end """ wrapper to make apply_schema mixed models as extension possible Note: type is not necessary here, but for LMM it is for multiple dispatch reasons! """ unfold_apply_schema(type, f, schema) = apply_schema(f, schema, UnfoldModel) # specify for abstract interface designmatrix(uf::UnfoldModel) = uf.designmatrix """ designmatrix( uf::UnfoldModel, tbl; eventcolumn = :event, contrasts = Dict{Symbol,Any}(), kwargs..., Main function, generates the designmatrix, returns a list of `<:AbstractDesignMatrix` """ function designmatrix( uf::UnfoldModel, tbl; eventcolumn = :event, contrasts = Dict{Symbol,Any}(), kwargs..., ) X = nothing fDict = design(uf) for (eventname, f) in fDict @debug "Eventname, X:", eventname, X if eventname == Any eventTbl = tbl else if !((eventcolumn ∈ names(tbl)) | (eventcolumn ∈ propertynames(tbl))) error( "Couldnt find columnName: " * string(eventcolumn) * " in event-table. Maybe need to specify eventcolumn=:correctColumnName (default is ':event') \n names(tbl) = " * join(names(tbl), ","), ) end eventTbl = @view tbl[tbl[:, eventcolumn].==eventname, :] # we need a view so we can remap later if needed end if isempty(eventTbl) error( "eventTable empty after subsetting. Couldnt find event '" * string(eventname) * "'{" * string(typeof(eventname)) * "}, in field tbl[:,:" * string(eventcolumn) * "].? - maybe you need to specify it as a string instead of a symbol?", ) end fIx = collect(typeof.(f) .<: FormulaTerm) bIx = collect(typeof.(f) .<: BasisFunction) if any(bIx) # timeContinuos way # TODO there should be a julian way to do this distinction X = X + designmatrix( typeof(uf), f[fIx], eventTbl, collect(f[bIx])[1]; contrasts = contrasts, eventname = eventname, kwargs..., ) else # normal way @debug f X = X + designmatrix( typeof(uf), f[fIx], eventTbl; contrasts = contrasts, eventname = eventname, kwargs..., ) end end return X end import Base.isempty Base.isempty(d::AbstractDesignMatrix) = isempty(modelmatrices(d)) """ $(SIGNATURES) timeexpand the rhs-term of the formula with the basisfunction """ function apply_basisfunction(form, basisfunction::BasisFunction, eventfields, eventname) @debug "apply_basisfunction" basisfunction.name eventname if basisfunction.name == "" basisfunction.name = eventname elseif basisfunction.name != eventname && eventname != Any error( "since unfold 0.7 basisfunction names need to be equivalent to the event.name (or = \"\" for autofilling).", ) end return FormulaTerm(form.lhs, TimeExpandedTerm(form.rhs, basisfunction, eventfields)) end function apply_basisfunction(form, basisfunction::Nothing, eventfields, eventname) # in case of no basisfunctin, do nothing return form end function designmatrix!(uf::UnfoldModel{T}, evts; kwargs...) where {T} X = designmatrix(uf, evts; kwargs...) uf.designmatrix = X return uf end """ modelmatrix(uf::UnfoldLinearModel) returns the modelmatrix of the model. Concatenates them, except in the MassUnivariate cases, where a vector of modelmatrices is return Compare with `modelmatrices` which returns a vector of modelmatrices, one per event """ function StatsModels.modelmatrix(uf::UnfoldLinearModel, basisfunction) if basisfunction @warn("basisfunction not defined for this kind of model") else return modelmatrix(uf) end end # catch all case extend_to_larger(modelmatrix::AbstractMatrix) = modelmatrix # UnfoldLinearMixedModelContinuousTime case extend_to_larger(modelmatrix::Tuple) = (extend_to_larger(modelmatrix[1]), modelmatrix[2:end]...) # UnfoldLinearModel - they have to be equal already extend_to_larger(modelmatrix::Vector{<:AbstractMatrix}) = modelmatrix #UnfoldLinearModelContinuousTime extend_to_larger(modelmatrix::Vector{<:SparseMatrixCSC}) = extend_to_larger(modelmatrix...) extend_to_larger(modelmatrix1::SparseMatrixCSC, modelmatrix2::SparseMatrixCSC, args...) = extend_to_larger(extend_to_larger(modelmatrix1, modelmatrix2), args...) function extend_to_larger(modelmatrix1::SparseMatrixCSC, modelmatrix2::SparseMatrixCSC) sX1 = size(modelmatrix1, 1) sX2 = size(modelmatrix2, 1) # append 0 to the shorter designmat if sX1 < sX2 modelmatrix1 = SparseMatrixCSC( sX2, modelmatrix1.n, modelmatrix1.colptr, modelmatrix1.rowval, modelmatrix1.nzval, ) elseif sX2 < sX1 modelmatrix2 = SparseMatrixCSC( sX1, modelmatrix2.n, modelmatrix2.colptr, modelmatrix2.rowval, modelmatrix2.nzval, ) end return hcat(modelmatrix1, modelmatrix2) end function StatsModels.modelmatrix(uf::UnfoldLinearModelContinuousTime, basisfunction = true) if basisfunction return modelmatrix(designmatrix(uf)) #return hcat(modelmatrix(designmatrix(uf))...) else # replace basisfunction with non-timeexpanded one f = formulas(uf) # probably a more julian way to do this... #if isa(f, AbstractArray) return modelcols_nobasis.(f, events(uf)) #else # return modelcols_nobasis(f, events(uf)) #end end end modelcols_nobasis(f::FormulaTerm, tbl::AbstractDataFrame) = modelcols(f.rhs.term, tbl) StatsModels.modelmatrix(uf::UnfoldModel) = modelmatrix(designmatrix(uf))#modelmatrix(uf.design,uf.designmatrix.events) StatsModels.modelmatrix(d::AbstractDesignMatrix) = modelmatrices(d) StatsModels.modelmatrix(d::Vector{<:AbstractDesignMatrix}) = extend_to_larger(modelmatrices.(d)) """ formulas(design::Vector{<:Pair}) returns vector of formulas, no schema has been applied (those formulas never saw the data). Also no timeexpansion has been applied (in the case of timecontinuous models) """ formulas(design::Vector{<:Pair}) = formulas.(design) formulas(design::Pair{<:Any,<:Tuple}) = last(design)[1] """ formulas(uf::UnfoldModel) formulas(d::Vector{<:AbstractDesignMatrix}) returns vector of formulas, **after** timeexpansion / apply_schema has been used. """ formulas(uf::UnfoldModel) = formulas(designmatrix(uf)) formulas(d::AbstractDesignMatrix) = d.formula formulas(d::Vector{<:AbstractDesignMatrix}) = formulas.(d) events(uf::UnfoldModel) = events(designmatrix(uf)) events(d::AbstractDesignMatrix) = d.events events(d::Vector{<:AbstractDesignMatrix}) = events.(d) design(uf::UnfoldModel) = uf.design function formulas(d::Dict) #TODO Specify Dict better if length(values(d)) == 1 return [c[1] for c in collect(values(d))][1] else return [c[1] for c in collect(values(d))] end end """ $(SIGNATURES) calculates in which rows the individual event-basisfunctions should go in Xdc timeexpand_rows timeexpand_vals """ function timeexpand_rows(onsets, bases, shift, ncolsX) # generate rowindices rows = copy(rowvals.(bases)) # this shift is necessary as some basisfunction time-points can be negative. But a matrix is always from 1:Ο„. Thus we have to shift it backwards in time. # The onsets are onsets-1 XXX not sure why. for r in eachindex(rows) rows[r] .+= floor(onsets[r] - 1) .+ shift end rows_red = reduce(vcat, rows) rows_red = repeat(rows_red, ncolsX) return rows_red end """ $(SIGNATURES) calculates the actual designmatrix for a timeexpandedterm. Multiple dispatch on StatsModels.modelcols """ function StatsModels.modelcols(term::TimeExpandedTerm, tbl) X = modelcols(term.term, tbl) time_expand(X, term, tbl) end # helper function to get the ranges from where to where the basisfunction is added function get_timeexpanded_time_range(onset, basisfunction) npos = sum(times(basisfunction) .>= 0) nneg = sum(times(basisfunction) .< 0) #basis = kernel(basisfunction)(onset) fromRowIx = floor(onset) - nneg toRowIx = floor(onset) + npos range(fromRowIx, stop = toRowIx) end function timeexpand_cols_allsamecols(bases, ncolsBasis::Int, ncolsX) repeatEach = length(nzrange(bases[1], 1)) cols_r = UnitRange{Int64}[ ((1:ncolsBasis) .+ ix * ncolsBasis) for ix in (0:ncolsX-1) for b = 1:length(bases) ] cols = reduce(vcat, cols_r) cols = repeat(cols, inner = repeatEach) return cols end """ $(SIGNATURES) calculates in which rows the individual event-basisfunctions should go in Xdc see also timeexpand_rows timeexpand_vals """ function timeexpand_cols(basisfunction, bases, ncolsBasis, ncolsX) # we can generate the columns much faster, if all bases output the same number of columns fastpath = time_expand_allBasesSameCols(basisfunction, bases, ncolsBasis) if fastpath return timeexpand_cols_allsamecols(bases, ncolsBasis, ncolsX) else return timeexpand_cols_generic(bases, ncolsBasis, ncolsX) end end function timeexpand_cols_generic(bases, ncolsBasis, ncolsX) # it could happen, e.g. for bases that are duration modulated, that each event has different amount of columns # in that case, we have to go the slow route cols = Vector{Int64}[] for Xcol = 1:ncolsX for b = 1:length(bases) coloffset = (Xcol - 1) * ncolsBasis for c = 1:ncolsBasis push!(cols, repeat([c + coloffset], length(nzrange(bases[b], c)))) end end end return reduce(vcat, cols) end function timeexpand_vals(bases, X, nTotal, ncolsX) # generate values #vals = [] vals = Array{Union{Missing,Float64}}(undef, nTotal) ix = 1 for Xcol = 1:ncolsX for (i, b) in enumerate(bases) b_nz = nonzeros(b) l = length(b_nz) vals[ix:ix+l-1] .= b_nz .* @view X[i, Xcol] ix = ix + l #push!(vals, ) end end return vals end """ $(SIGNATURES) performs the actual time-expansion in a sparse way. - Get the non-timeexpanded designmatrix X from StatsModels. - evaluate the basisfunction kernel at each event - calculate the necessary rows, cols and values for the sparse matrix Returns SparseMatrixCSC """ function time_expand(Xorg::AbstractArray, term::TimeExpandedTerm, tbl) tbl = DataFrame(tbl) # this extracts the predefined eventfield, usually "latency" onsets = tbl[!, term.eventfields] time_expand(Xorg, term.basisfunction, onsets) end function time_expand(Xorg::AbstractArray, basisfunction::FIRBasis, onsets) if basisfunction.interpolate # code doubling, but I dont know how to do the multiple dispatch otherwise # this is the "old" way, pre 0.7.1 #bases = kernel.(Ref(basisfunction), eachrow(onsets)) if size(onsets, 2) != 1 @error "not implemented" end bases = kernel.(Ref(basisfunction), onsets[!, 1]) return time_expand(Xorg, basisfunction, onsets[!, 1], bases) else # fast way return time_expand_firdiag(Xorg, basisfunction, onsets) end end function time_expand_firdiag(Xorg::AbstractMatrix{T}, basisfunction, onsets) where {T} # @debug "Xorg eltype" T @assert width(basisfunction) == height(basisfunction) w = width(basisfunction) adjusted_onsets = Int.(floor.(onsets[!, 1] .+ shift_onset(basisfunction))) @assert (minimum(onsets[!, 1]) + shift_onset(basisfunction) .- 1 + w) > 0 neg_fix = sum(adjusted_onsets[adjusted_onsets.<1] .- 1) ncoeffs = w * size(Xorg, 1) * size(Xorg, 2) .+ neg_fix * size(Xorg, 2) I = Vector{Int}(undef, ncoeffs) colptr = Vector{Int}(undef, w * size(Xorg, 2) + 1) #V = Vector{T}(undef, ncoeffs) V = similar(Xorg, ncoeffs) for ix_X = 1:size(Xorg, 2) #I, J, V, m, n = spdiagm_diag(w, (.-onsets[!, 1] .=> Xorg[:, Xcol])...) #ix = (1+size(Xorg, 1)*(ix_X-1)):size(Xorg, 1)*ix_X ol = w * size(Xorg, 1) + neg_fix #ix = 1:ol ix = 1+(ix_X-1)*ol:ix_X*ol ix_col = (1+(ix_X-1)*w):ix_X*w+1 #@debug ix, ix_col size(I) size(colptr) size(V) w @views spdiagm_diag_colwise!( I[ix], colptr[ix_col], V[ix], w, adjusted_onsets, Xorg[:, ix_X]; colptr_offset = (ix_X - 1) * (w * size(Xorg, 1) + neg_fix), ) end colptr[end] = length(V) + 1 m = adjusted_onsets[end, 1] + w - 1 n = w * size(Xorg, 2) SparseArrays._goodbuffers(Int(m), Int(n), colptr, I, V) || throw( ArgumentError( "Invalid buffers for SparseMatrixCSC construction n=$n, colptr=$(summary(colptr)), rowval=$(summary(rowval)), nzval=$(summary(nzval))", ), ) Ti = promote_type(eltype(colptr), eltype(I)) SparseArrays.sparse_check_Ti(m, n, Ti) SparseArrays.sparse_check(n, colptr, I, V) # silently shorten rowval and nzval to usable index positions. maxlen = abs(widemul(m, n)) isbitstype(Ti) && (maxlen = min(maxlen, typemax(Ti) - 1)) return SparseMatrixCSC(m, n, colptr, I, V) #return reduce(hcat, Xdc_list) end """ Even more speed improved version of spdiagm, takes a single float value instead of a vector, like a version of spdiagm that takes in a UniformScaling. This directly constructs the CSC required fields, thus it is possible to do SparseMatrixCSC(spdiagm_diag_colwise(...)). Use at your own discretion!! e.g. > sz = 5 > ix = [1,3,10] > vals = [4,1,2] > spdiagm_diag(sz,ix,vals) """ function spdiagm_diag_colwise!( I, colptr, V, diagsz, onsets, values::AbstractVector{T}; colptr_offset = 0, ) where {T} #ncoeffs = diagsz * length(onsets) # @debug size(I) size(colptr) size(V) size(onsets) size(values) #colptr .= colptr_offset .+ (1:sum(>(0),onsets):ncoeffs+1) r = 1 _c = 1 for c = 1:diagsz colptr[c] = _c + colptr_offset c_add = 0 for (i, o) in enumerate(onsets) # @debug i, r row_val = o + c - 1 if row_val < 1 continue end I[r] = row_val V[r] = values[i] r = r + 1 c_add = c_add + 1 end _c = _c + c_add end return (onsets[end] + diagsz, diagsz, colptr, I, V) end function spdiagm_diag_colwise(diagsz, onsets, values::AbstractVector{T}) where {T} ncoeffs = diagsz * length(onsets) I = Vector{Int}(undef, ncoeffs) #J = Vector{Int}(undef, ncoeffs) colptr = 1:length(onsets):ncoeffs+1 |> collect V = Vector{T}(undef, ncoeffs) r = 1 for c = 1:diagsz for (i, o) in enumerate(onsets) v = values[i] I[r] = o + c #J[r] = c V[r] = v r = r + 1 end end return (onsets[end] + diagsz, diagsz, colptr, I, V) end """ Speed improved version of spdiagm, takes a single float value instead of a vector, like a version of spdiagm that takes in a UniformScaling e.g. > sz = 5 > ix = [1,3,10] > spdiagm_diag(sz,(.-ix.=>1)...) """ function spdiagm_diag(diagsz, kv::Pair{<:Integer,T}...) where {T} ncoeffs = diagsz * length(kv) I = Vector{Int}(undef, ncoeffs) J = Vector{Int}(undef, ncoeffs) V = Vector{T}(undef, ncoeffs) i = 0 m = 0 n = 0 for p in kv k = p.first # e.g. -1 v = p.second # e.g. [1,2,3,4,5] if k < 0 row = -k col = 0 elseif k > 0 row = 0 col = k else row = 0 col = 0 end r = 1+i:diagsz+i I[r], J[r] = (row+1:row+diagsz, col+1:col+diagsz) #copyto!(view(V, r), v) view(V, r) .= v m = max(m, row + diagsz) n = max(n, col + diagsz) i += diagsz end return I, J, V, m, n end function time_expand(Xorg::AbstractArray, basisfunction::BasisFunction, onsets) bases = kernel.(Ref(basisfunction), eachrow(onsets)) return time_expand(Xorg, basisfunction, onsets, bases) end function time_expand(Xorg, basisfunction::BasisFunction, onsets, bases) ncolsBasis = size(kernel(basisfunction, 0), 2)::Int64 X = reshape(Xorg, size(Xorg, 1), :) # why is this necessary? ncolsX = size(X)[2]::Int64 rows = timeexpand_rows(onsets, bases, shift_onset(basisfunction), ncolsX) cols = timeexpand_cols(basisfunction, bases, ncolsBasis, ncolsX) vals = timeexpand_vals(bases, X, size(cols), ncolsX) #vals = vcat(vals...) ix = rows .> 0 #.&& vals .!= 0. A = @views sparse(rows[ix], cols[ix], vals[ix]) dropzeros!(A) return A end """ Helper function to decide whether all bases have the same number of columns per event """ time_expand_allBasesSameCols(b::FIRBasis, bases, ncolBasis) = true # FIRBasis is always fast! function time_expand_allBasesSameCols(basisfunction, bases, ncolsBasis) fastpath = true for b in eachindex(bases) if length(unique(length.(nzrange.(Ref(bases[b]), 1:ncolsBasis)))) != 1 return false end end return true end """ $(SIGNATURES) coefnames of a TimeExpandedTerm concatenates the basis-function name with the kronecker product of the term name and the basis-function colnames. Separator is ' : ' Some examples for a firbasis: basis_313 : (Intercept) : 0.1 basis_313 : (Intercept) : 0.2 basis_313 : (Intercept) : 0.3 ... """ function StatsModels.coefnames(term::TimeExpandedTerm) terms = coefnames(term.term) colnames = Unfold.colnames(term.basisfunction) name = Unfold.name(term.basisfunction) if typeof(terms) == String terms = [terms] end return string(name) .* " : " .* kron(terms .* " : ", string.(colnames)) end function StatsModels.termnames(term::TimeExpandedTerm) terms = coefnames(term.term) colnames = Unfold.colnames(term.basisfunction) if typeof(terms) == String terms = [terms] end return vcat(repeat.([[t] for t in terms], length(colnames))...) end function colname_basis(term::TimeExpandedTerm) terms = coefnames(term.term) colnames = Unfold.colnames(term.basisfunction) if typeof(terms) == String terms = [terms] end return repeat(colnames, length(terms)) end function StatsModels.coefnames(terms::AbstractArray{<:FormulaTerm}) return coefnames.(Base.getproperty.(terms, :rhs)) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4426
import Effects: effects import Effects: expand_grid import Effects: typify import Effects.typify import Effects: _symequal import StatsModels.collect_matrix_terms import Base.getproperty using Effects """ effects(design::AbstractDict, model::UnfoldModel; typical = mean) Calculates marginal effects for all term combinations in `design`. Implementation based on Effects.jl package; likely could repackage in UnfoldEffects.jl; somebody wants to do it? This would make it easier to cross-maintain it to changes/bug fixes in the Effects.jl package. `design` is a dictionary containing those predictors (as keys) with levels (as values), that you want to evaluate. The `typical` refers to the value, which other predictors that are not specified in the dictionary, should take on. For MixedModels, the returned effects are based on the "typical" subject, i.e. all random effects are put to 0. # Example ```julia-repl julia> f = @formula 0 ~ categoricalA + continuousA + continuousB julia> uf = fit(UnfoldModel, (Any => (f, times)), data, events) julia> d = Dict(:categorical => ["levelA", "levelB"], :continuous => [-2, 0, 2]) julia> effects(d, uf) ``` will result in 6 predicted values: A/-2, A/0, A/2, B/-2, B/0, B/2. """ function effects(design::AbstractDict, model::T; typical = mean) where {T<:UnfoldModel} if isempty(design) return effects(Dict(:dummy => [:dummy]), model; typical) end reference_grid = expand_grid(design) form = Unfold.formulas(model) # get formula # replace non-specified fields with "constants" m = Unfold.modelmatrix(model, false) # get the modelmatrix without timeexpansion #@debug "type form[1]", typeof(form[1]) form_typical = _typify(T, reference_grid, form, m, typical) @debug typeof(form_typical) typeof(form_typical[1]) #form_typical = vec(form_typical) reference_grids = repeat([reference_grid], length(form_typical)) eff = predict(model, form_typical, reference_grids; overlap = false) if :latency ∈ unique(vcat(names.(reference_grids)...)) reference_grids = select.(reference_grids, Ref(DataFrames.Not(:latency))) end @debug "effects" size(eff[1]) reference_grid size(times(model)[1]) eventnames(model) return result_to_table(eff, reference_grids, times(model), eventnames(model)) end Effects.typify(reference_grid, form::AbstractArray, X; kwargs...) = typify.(Ref(reference_grid), form, Ref(X); kwargs...) # cast single form to a vector _typify( reference_grid, form::FormulaTerm{<:InterceptTerm,<:Unfold.TimeExpandedTerm}, m, typical, ) = _typify(reference_grid, [form], [m], typical) @traitfn function _typify( ::Type{UF}, reference_grid, form::Vector{T}, m::Vector, typical, ) where {T<:FormulaTerm,UF<:UnfoldModel;ContinuousTimeTrait{UF}} @debug "_typify - stripping away timeexpandedterm" form_typical = Array{FormulaTerm}(undef, length(form)) for f = 1:length(form) # strip of basisfunction and put it on afterwards again tmpf = deepcopy(form[f]) # create a Formula without Timeexpansion tmpf = FormulaTerm(tmpf.lhs, tmpf.rhs.term) # typify that tmpf = typify(reference_grid, tmpf, m[f]; typical = typical) # regenerate TimeExpansion tmpf = Unfold.TimeExpandedTerm( tmpf, form[f].rhs.basisfunction; eventfields = form[f].rhs.eventfields, ) form_typical[f] = FormulaTerm(form[f].lhs, tmpf) end return form_typical end function _typify(reference_grid, form::FormulaTerm, m, typical) return [typify(reference_grid, form, m; typical = typical)] end @traitfn function _typify( ::Type{UF}, reference_grid, form::AbstractArray{T}, m::Vector, typical, ) where {T<:FormulaTerm,UF<:UnfoldModel;!ContinuousTimeTrait{UF}} # Mass Univariate with multiple effects @debug "_typify going the mass univariate route - $(typeof(form))" @debug length(form), length(m), typeof(m) out = FormulaTerm[] for k = 1:length(form) tmpf = typify(reference_grid, form[k], m[k]; typical = typical) push!(out, FormulaTerm(form[k].lhs, tmpf)) end @debug :_typify typeof(form) return out end # mixedModels case - just use the FixEff, ignore the ranefs Effects.typify(reference_grid, form, m::Tuple; typical) = typify(reference_grid, form, m[1]; typical)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2092
# helper scripts for event handlung """ copy field-info from source to closest target `match_fun` can be "closest", "s before t" (eq. "t after s") or "t before s" (eq. "s after t") ## Example julia> # copy reaction time values from button press to closest stimulus immediately before button press julia> copy_eventinfo!(evts,"button"=>"stimulus",:reaction_time;match_fun="s after t") """ function copy_eventinfo!(evts, fromTo, field; match_fun = "closest") source = fromTo.first target = fromTo.second if isa(field, Pair) source_field = field.first target_field = field.second else source_field = field target_field = field end source_ix = findall(isequal(source), evts.trial_type) target_ix = findall(isequal(target), evts.trial_type) isempty(source_ix) && error("couldnt find source entries ($source) in evts.trial_type") isempty(target_ix) && error("couldnt find target entries ($target) in evts.trial_type") # for some matching functions we want to find the minimum, but no negative number filter_greaterzero = x -> x >= 0 ? x : Inf if match_fun == "closest" match_fun = (a, b) -> argmin(abs.(a .- b)) # find closest before or after elseif match_fun == "s after t" || match_fun == "t before s" match_fun = (s, t) -> argmin(filter_greaterzero.(s .- t)) # source after target elseif match_fun == "s before t" || match_fun == "t after s" match_fun = (s, t) -> argmin(filter_greaterzero.(t .- s)) # source before target elseif !callable(match_fun) error("bad match_fun input") end ix = [match_fun(evts[s, :latency], evts[target_ix, :latency]) for s in source_ix] ix = target_ix[ix] payload = evts[source_ix, source_field] # if targetfield does not exist, create one with Union(missing,target_field_datatype) if !any(names(evts) .== target_field) evts[!, target_field] = Array{Union{Missing,typeof(payload[1])}}(missing, nrow(evts)) end # fill it in evts[ix, target_field] .= payload return evts end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
8487
""" fit(type::UnfoldModel,d::Vector{Pair},tbl::AbstractDataFrame,data::Array) fit(type::UnfoldModel,f::FormulaTerm,tbl::AbstractDataFrame,data::Array{T,3},times) fit(type::UnfoldModel,f::FormulaTerm,tbl::AbstractDataFrame,data::Array{T,2},basisfunction::BasisFunction) Generates Designmatrix & fits model, either mass-univariate (one model per epoched-timepoint) or time-expanded (modeling linear overlap). - `eventcolumn` (Symbol/String, default :event) - the column in `tbl::AbstractDataFrame` to differentiate the basisfunctions as defined in `d::Vector{Pair}` - `show_progress` (Bool, default true) - show Progress via ProgressMeter If a `Vector[Pairs]` is provided, it has to have one of the following structures: `[:A=>(f,basisfunction), :B=>(f2,bf2)]` - for deconvolutin analyses (use `Any=>(f,bf)` to match all rows of `tbl` in one basis functins) `[:A=>(f,timesvector), :B=>(f2,timesvector)]` - for mass univariate analyses. If multiple rERPs are calculated at the same time, the timesvectors must be the same ## Notes - The `type` can be specified directly as well e.g. `fit(type::UnfoldLinearModel)` instead of inferred - The data is reshaped if it is missing one dimension to have the first dimesion then `1` "Channel". ## Examples Mass Univariate Linear ```julia-repl julia> data,evts = loadtestdata("testCase1") julia> data_r = reshape(data,(1,:)) julia> data_e,times = Unfold.epoch(data=data_r,tbl=evts,Ο„=(-1.,1.9),sfreq=10) # cut the data into epochs. data_e is now ch x times x epoch julia> f = @formula 0~1+continuousA+continuousB # 1 julia> model = fit(UnfoldModel,f,evts,data_e,times) ``` Timexpanded Univariate Linear ```julia-repl julia> basisfunction = firbasis(Ο„=(-1,1),sfreq=10,name="A") julia> model = fit(UnfoldModel,[Any=>(f,basisfunction],evts,data_r) ``` """ function StatsModels.fit( UnfoldModelType::Type{T}, f::FormulaTerm, tbl::AbstractDataFrame, data::AbstractArray, basisOrTimes::Union{BasisFunction,AbstractArray}; kwargs..., ) where {T<:UnfoldModel} # old input format, sometimes convenient.Convert to list-based one fit(UnfoldModelType, [Any => (f, basisOrTimes)], tbl, data; kwargs...) end # deprecated Dict call function StatsModels.fit(uf::Type{UnfoldModel}, design::Dict, args...; kwargs...) #@debug keys(design) .=> Tuple.(values(design)) @warn "using `Dict(:A=>(@formula,times/basisfunction))` is deprecated, please use `[:A=>(@formula,times/basisfunction)]` from now on" fit(uf, collect(pairs(design)), args...; kwargs...) end function StatsModels.fit( UnfoldModelType::Type{<:UnfoldModel}, design::Vector, tbl::AbstractDataFrame, data::AbstractArray{T}; kwargs..., ) where {T} for k = 1:length(design) d_first = design[k] d_tuple = last(d_first) @assert typeof(first(d_tuple)) <: FormulaTerm "InputError in design(uf) - :key=>(FORMULA,basis/times), formula not found. Maybe formula wasn't at the first place?" end if UnfoldModelType == UnfoldModel @debug "autodetecting UnfoldModelType" UnfoldModelType = design_to_modeltype(design) end for k = 1:length(design) d_first = design[k] d_tuple = last(d_first) @assert (typeof(last(d_tuple)) <: AbstractVector) ⊻ (SimpleTraits.istrait(Unfold.ContinuousTimeTrait{UnfoldModelType})) "InputError: Either a basis function was declared, but a UnfoldLinearModel was built, or a times-vector (and no basis function) was given, but a UnfoldLinearModelContinuousTime was asked for." end @debug "Check Data + Applying UnfoldModelType: $UnfoldModelType {$T}" data_r = check_data(UnfoldModelType, data) fit(UnfoldModelType{T}(design), tbl, data_r; kwargs...) end function StatsModels.fit( uf::UnfoldModel, tbl::AbstractDataFrame, data::AbstractArray; kwargs..., ) @debug "adding desigmatrix!" designmatrix!(uf, tbl; kwargs...) fit!(uf, data; kwargs...) return uf end # special case where designmatrix and data are provided directly without a design function StatsModels.fit( UnfoldModelType::Type{UF}, X::Vector{<:AbstractDesignMatrix{T}}, data::AbstractArray; kwargs..., ) where {UF<:UnfoldModel,T} if UnfoldModelType == UnfoldModel error( "Can't infer model automatically, specify with e.g. fit(UnfoldLinearModel...) instead of fit(UnfoldModel...)", ) end uf = UnfoldModelType{T}([:empty => ()], X) fit!(uf, data; kwargs...) return uf end # main fitting function function StatsModels.fit!( uf::UnfoldModel{T}, data::AbstractArray{T}; solver = (x, y) -> solver_default(x, y), kwargs..., ) where {T} @debug "fit!: $T, datasize: $(size(data))" @assert ~isempty(designmatrix(uf)) if isa(uf, UnfoldLinearModel) @assert length(times(uf)[1]) == size(data, length(size(data)) - 1) "Times Vector does not match second last dimension of input data - forgot to cut into epochs?" end X = modelmatrix(uf) if isa(uf, UnfoldLinearModel) d = designmatrix(uf) # mass univariate with multiple events fitted at the same time coefs = [] for m = 1:length(X) # the main issue is, that the designmatrices are subsets of the event table - we have # to do the same for the data, but data and designmatrix dont know much about each other. # Thus we use parentindices() to get the original indices of the @view events[...] from desigmatrix.jl @debug typeof(X) typeof(events(d)[m]) push!(coefs, solver(X[m], @view data[:, :, parentindices(events(d)[m])[1]])) end @debug [size(c.estimate) for c in coefs] uf.modelfit = LinearModelFit{T,3}( cat([c.estimate for c in coefs]..., dims = 3), [c.info for c in coefs], cat([c.standarderror for c in coefs]..., dims = 3), ) return # we are done here # elseif isa(d.events, SubDataFrame) # in case the user specified an event to subset (and not any) we have to use the view from now on # data = @view data[:, :, parentindices(d.events)[1]] # end end X, data = equalize_size(X, data) # @debug typeof(uf.modelfit), typeof(T), typeof(X), typeof(data) uf.modelfit = solver(X, data) return uf end @traitfn function check_data( uf::Type{UF}, data::AbstractArray{T,2}, ) where {T,UF<:UnfoldModel;!ContinuousTimeTrait{UF}} @debug(" !ContinuousTimeTrait: data array is size (X,Y), reshaping to (1,X,Y)") data_r = reshape(data, 1, size(data)...) return data_r end @traitfn check_data( uf::Type{UF}, data::AbstractArray{T,2}, ) where {T,UF<:UnfoldModel;ContinuousTimeTrait{UF}} = data function check_data(uf::Type{<:UnfoldModel}, data::AbstractVector) @debug("data array is size (X,), reshaping to (1,X)") data = reshape(data, 1, :) end check_data(uf::Type{<:UnfoldModel}, data) = data isa_lmm_formula(f::FormulaTerm) = isa_lmm_formula(f.rhs) isa_lmm_formula(f::Tuple) = any(isa_lmm_formula.(f)) isa_lmm_formula(f::InteractionTerm) = false isa_lmm_formula(f::ConstantTerm) = false isa_lmm_formula(f::StatsModels.Term) = false #isa_lmm_formula(f::FunctionTerm) = false function isa_lmm_formula(f::FunctionTerm) try isa_lmm_formula(f.f) catch isa_lmm_formula(f.forig) # StatsMoels <0.7 end end isa_lmm_formula(f::Function) = false # catch all isa_lmm_formula(f::typeof(|)) = true function design_to_modeltype(design) #@debug design # autoDetect tmp = last(design[1]) f = tmp[1] # formula t = tmp[2] # Vector or BasisFunction isMixedModel = isa_lmm_formula(f) if isMixedModel ext = Base.get_extension(@__MODULE__, :UnfoldMixedModelsExt) if isnothing(ext) throw( "MixedModels is not loaded. Please use `]add MixedModels` and `using MixedModels` to install it prior to using", ) end end if typeof(t) <: BasisFunction if isMixedModel UnfoldModelType = ext.UnfoldLinearMixedModelContinuousTime else UnfoldModelType = UnfoldLinearModelContinuousTime end else if isMixedModel UnfoldModelType = ext.UnfoldLinearMixedModel else UnfoldModelType = UnfoldLinearModel end end return UnfoldModelType end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3038
using FileIO using JLD2 using StatsModels using Unfold """ _modelcols(forms::Vector,events::Vector) A wrapper around StatsModels.modelcols that is only needed for easy multiple dispatch """ function _modelcols(forms::Vector, events::Vector) @assert length(forms) == length(events) return _modelcols.(forms, events) end """ _modelcols(form::FormulaTerm, events) """ _modelcols(form::FormulaTerm, events) = modelcols(form.rhs, events) """ FileIO.save(file, uf::T; compress=false) where {T<:UnfoldModel} Save UnfoldModel in a (by default uncompressed) .jld2 file. For memory efficiency the designmatrix is set to missing. If needed, it can be reconstructed when loading the model. """ function FileIO.save(file, uf::T; compress = false) where {T<:UnfoldModel} jldopen(file, "w"; compress = compress) do f f["uf"] = T( design(uf), [ typeof(uf.designmatrix[k])( Unfold.formulas(uf)[k], empty_modelmatrix(designmatrix(uf)[k]), Unfold.events(uf)[k], ) for k = 1:length(uf.designmatrix) ], uf.modelfit, ) end end function empty_modelmatrix(d::AbstractDesignMatrix) return typeof(d)().modelmatrix end """ FileIO.load(file, ::Type{<:UnfoldModel}; generate_Xs=true) Load UnfoldModel from a .jld2 file. By default, the designmatrix is reconstructed. If it is not needed set `generate_Xs=false` which improves time-efficiency. """ function FileIO.load(file, ::Type{<:UnfoldModel}; generate_Xs = true) f = jldopen(file, "r") uf = f["uf"] close(f) form = formulas(designmatrix(uf)) events = Unfold.events(designmatrix(uf)) @debug typeof.(form) typeof.(events) size(form) size(events) # potentially don't generate Xs, but always generate it for LinearModels as it is small + cheap + we actually need it for many functions if generate_Xs || uf isa UnfoldLinearModel X = _modelcols(form, events) else #nd = length(size(modelmatrix(designmatrix(uf)[1]))) #@debug typeof.(designmatrix(uf)) #X = [sparse(Array{eltype(uf)}(undef, repeat([0], nd)...)) for k = 1:length(form)] X = [empty_modelmatrix(designmatrix(uf)[k]) for k = 1:length(form)] end modelfit = if isa(uf.modelfit, JLD2.ReconstructedMutable{Symbol("Unfold.LinearModelFit")}) @warn "old Unfold Model detected, trying to 'upgrade' uf.modelfit" mf = uf.modelfit T = typeof(mf.estimate) if isempty(mf.standarderror) LinearModelFit(mf.estimate, mf.info) else LinearModelFit(mf.estimate, mf.info, T(mf.standarderror)) end else uf.modelfit end @debug typeof(uf) typeof(form) typeof(X) typeof(events) size(form) size(X) size(events) # reintegrate the designmatrix return typeof(uf)(uf.design, typeof(designmatrix(uf)[1]).(form, X, events), modelfit) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
16664
#using DocStringExtensions: format # opt-in # Most important function ;-) #predict(X::AbstractMatrix, coefs::AbstractMatrix) = coefs * X' predict(X::AbstractMatrix, coefs::AbstractMatrix) = (X * coefs')' # MassUnivariate Model, we have to extract the coefficients per designmatrix function predict(X::Vector{<:AbstractMatrix}, coefs::AbstractArray{T,3}) where {T} len = size.(X, 2) @assert length(unique(len)) == 1 "all designmatrices need to be the same size in this case" coefs_views = [@view(coefs[:, :, (i-1)*len[1]+1:i*len[1]]) for i = 1:length(len)] predict.(X, coefs_views) end # 3D-case function predict( X::AbstractMatrix{Tx}, coef::AbstractArray{Tc,3}, ) where {Tx<:Union{Missing,<:Number},Tc<:Union{Missing,<:Number}} yhat = Array{Union{Tc,Tx}}(undef, size(coef, 1), size(X, 1), size(coef, 2)) for ch = 1:size(coef, 1) yhat[ch, :, :] .= X * permutedims(coef[ch, :, :], (2, 1)) end return permutedims(yhat, (1, 3, 2)) # esults in: ch x time x pred end function predict( X::AbstractMatrix{Tcoef}, coefs::AbstractMatrix{TX}, onsets::Vector, timewindow::NTuple{2,Int}, ) where {Tcoef,TX} # Create an empty array for the residuals # Note there is a +1 because start and stop indices are both included in the interval yhat = Array{Union{TX,Tcoef}}( undef, size(coefs, 1), timewindow[2] - timewindow[1] + 1, length(onsets), ) for event in eachindex(onsets) event_range_temp = onsets[event]+timewindow[1]:onsets[event]+timewindow[2] # Clip indices that are outside of the design matrix (i.e. before the start or after the end) #indices_inside_data = 0 .< event_range_temp .< size(data, 2) indices_inside_data = 0 .< event_range_temp .< size(X, 1) event_range = event_range_temp[indices_inside_data] # Calculate residuals yhat[:, indices_inside_data, event] .= predict(@view(X[event_range, :]), coefs) end return yhat end function _residuals( yhat::AbstractArray{Tyhat,3}, y::AbstractMatrix{Ty}, onsets::Vector, timewindow::NTuple{2,Int}, ) where {Ty,Tyhat} resid = missings( Union{Ty,Tyhat}, size(y, 1), timewindow[2] - timewindow[1] + 1, length(onsets), ) for event in eachindex(onsets) event_range_temp = onsets[event]+timewindow[1]:onsets[event]+timewindow[2] # Clip indices that are outside of the design matrix (i.e. before the start or after the end) indices_inside_data = 0 .< event_range_temp .< size(y, 2) event_range = event_range_temp[indices_inside_data] !isempty(event_range) || @warn "event_range is empty for $event $(onsets[event])" # Calculate residuals #@debug "_residuals" size(y) size(yhat) size(event_range) #@debug event event_range[[1, end]] @views resid[:, indices_inside_data, event] .= y[:, event_range] .- yhat[:, indices_inside_data, event] # if !all(indices_inside_data) # @views resid[:, .!indices_inside_data, event] .= # y[:, event_range_temp[.!indices_inside_data]] #end end return resid end @traitfn residuals( uf::T, data::AbstractArray, ) where {T <: UnfoldModel; ContinuousTimeTrait{T}} = _residuals(T, predict(uf), check_data(T, data)) @traitfn function residuals( uf::T, data::AbstractArray, ) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} pred = predict(uf) @assert length(pred) == 1 "residuals currently not supported for multi-event MassUnivariateModels. It is not hard to implement, but I ran out of time. Write an issue if you need this functionality" _residuals(T, pred[1], check_data(T, data)) end _split_data(y::AbstractMatrix, n) = return @view(y[:, 1:n]), @view(y[:, n+1:end]) _split_data(y::AbstractArray, n) = return @view(y[:, 1:n, :]), @view(y[:, n+1:end, :]) #@traitfn function _residuals(::Type{T}, yhat, y) where {T<:UnfoldModel}#; ContinuousTimeTrait{T}} #_split_data(y::AbstractVector, n) = return @view(y[1:n]), @view(y[n+1:end]) n_yhat = size(yhat, 2) n_y = size(y, 2) @debug n_yhat n_y if n_yhat >= n_y @debug "n_yhat > n_y" size(y) size.(_split_data(yhat, n_y)) return y .- _split_data(yhat, n_y)[1] else @debug "n_y < n_yhat" yA, yB = _split_data(y, n_yhat) @debug size(yA) size(yB) res = yA .- n_y return cat(res, yB; dims = 2) end end predict(uf::UnfoldModel, f::FormulaTerm, args...; kwargs...) = predict(uf, [f], args...; kwargs...) predict(uf::UnfoldModel, f::Vector, evts::DataFrame; kwargs...) = predict(uf, f, repeat([evts], length(f)); kwargs...) predict(uf::UnfoldModel; kwargs...) = predict(uf, formulas(uf), events(uf); kwargs...) predict(uf::UnfoldModel, f::Vector{<:FormulaTerm}; kwargs...) = predict(uf, f, events(uf); kwargs...) predict(uf::UnfoldModel, evts::Vector{<:DataFrame}; overlap = false, kwargs...) = predict(uf, Unfold.formulas(uf), evts; overlap, kwargs...) predict(uf::UnfoldModel, evts::DataFrame; overlap = false, kwargs...) = predict( uf, Unfold.formulas(uf), repeat([evts], length(Unfold.formulas(uf))); overlap, kwargs..., ) """ function predict( uf, f::Vector{<:FormulaTerm}, evts::Vector{<:DataFrame}; overlap = true, kwargs... ) Returns a predicted ("y_hat = X*b") `Array`. - `uf` is an `<:UnfoldModel` - `f` is a (vector of) formulas, typically `Unfold.formulas(uf)`, but formulas can be modified e.g. by `effects`. - `evts` is a (vector of) events, can be `Unfold.events(uf)` to return the (possibly continuous-time) predictions of the model. Can be a custom even ## kwargs: if `overlap = true` (default), overlap based on the `latency` column of 'evts` will be simulated, or in the case of `!ContinuousTimeTrait` just X*coef is returned. if `overlap = false`, returns predictions without overlap (models with `ContinuousTimeTrait` (=> with basisfunction / deconvolution) only), via `predict_no_overlap` if `keep_basis` or `exclude_basis` is defined, then `predict_partial_overlap` is called, which allows to selective introduce overlap based on specified (or excluded respective) events/basisfunctions `epoch_to` and `epoch_timewindow` currently only defined for partial_overlap, calculated (partial) overlap controlled predictions, but returns them at the specified `epoch_at` event, with the times `epoch_timewindow` in samples. `eventcolumn` can be specified as well if different from the default `event` Hint: all vectors can be "single" types, and will be containered in a vector ## Output - If `overlap=false`, returns a 3D-Array - If `overlap=true` and `epoch_to=nothing` (default), returns a 2D-array - If `overlap=true` and `epoch_to!=nothing`, returns a 3D array """ function predict( uf, f::Vector{<:FormulaTerm}, evts::Vector{<:DataFrame}; overlap = true, keep_basis = [], exclude_basis = [], epoch_to = nothing, epoch_timewindow = nothing, kwargs..., #eventcolumn = :event, ) @assert !( (!isempty(keep_basis) || !isempty(exclude_basis)) && (length(formulas(uf)) == 1) ) "No way to calculate partial overlap if basisnames is Any; please revise model " @assert !(!isempty(keep_basis) & !isempty(exclude_basis)) "choose either to keep events, or to exclude, but not both" coefs = coef(uf) if overlap if isempty(keep_basis) & isempty(exclude_basis) @debug "full-overlap" if events(uf) == evts @debug "original design predict" # off-the-shelf standard continuous predict, as you'd expect return predict(modelmatrix(uf), coef(uf)) else @debug "new dataframe predict" # predict of new data-table with a latency column. First generate new designmatrix, then off-the-shelf X*b predict @assert length(f) == length(evts) "please provide the same amount of formulas (currently $(length(f)) as event-dataframes (currently $(length(evts)))" X_new = modelcols.(f, evts) |> Unfold.extend_to_larger @debug typeof(X_new) typeof(modelcols.(f, evts)) return predict(X_new, coefs) end else return predict_partial_overlap( uf, coefs, evts; keep_basis, exclude_basis, epoch_to, epoch_timewindow, kwargs..., ) end else @debug "no overlap predict2" # no overlap, the "ideal response". We predict each event row independently. user could concatenate if they really want to :) return predict_no_overlap(uf, coefs, f, evts) end end @traitfn predict_partial_overlap( uf::T, args; kwargs..., ) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} = error("can't have partial overlap without Timecontinuous model") @traitfn function predict_partial_overlap( uf::T, coefs, evts; keep_basis = [], exclude_basis = [], epoch_to = nothing, epoch_timewindow = nothing, eventcolumn = :event, ) where {T <: UnfoldModel; ContinuousTimeTrait{T}} @assert !(!isempty(keep_basis) & !isempty(exclude_basis)) "can't have no overlap & specify keep/exclude at the same time. decide for either case" # Partial overlap! we reconstruct with some basisfunctions deactivated if !isempty(keep_basis) if !isa(keep_basis, Vector) # Check if keep_basis is a vector basisnames = [keep_basis] else basisnames = keep_basis end @assert !isempty(intersect(basisname(Unfold.formulas(uf)), basisnames)) "Couldn't find (any of) $keep_basis in the models basisnames; you can check which basisnames are available in your model using Unfold.basisname(Unfold.formulas(uf))" else basisnames = basisname(Unfold.formulas(uf)) basisnames = setdiff(basisnames, exclude_basis) end # @debug basisname X_view = matrix_by_basisname(modelmatrix(uf), uf, basisnames) coefs_view = matrix_by_basisname(coefs, uf, basisnames) if isnothing(epoch_to) return predict(X_view, coefs_view) else # @debug typeof(evts) timewindow = isnothing(epoch_timewindow) ? calc_epoch_timewindow(uf, epoch_to) : epoch_timewindow find_lat = x -> x[ epoch_to == Any ? (1:size(x, 1)) : x[:, eventcolumn] .== epoch_to, :latency, ] latencies = vcat(find_lat.(evts)...) #ix_event = vcat(evts...)[:, eventcolumn] .== epoch_to #latencies = evts[ix_event].latency #@debug latencies[end] size(X_view) timewindow return predict(X_view, coefs_view, latencies, (timewindow[1], timewindow[end]);) end end @traitfn function predict_no_overlap( uf::T, coefs, f::Vector, evts::Vector, ) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} @debug "Not ContinuousTime yhat, Array" X = _modelcols.(f, evts) @debug typeof(X) # figure out which coefficients belong to which event Xsizes = size.(X, Ref(2)) Xsizes_cumsum = vcat(0, cumsum(Xsizes)) indexes = [(Xsizes_cumsum[ix]+1):Xsizes_cumsum[ix+1] for ix = 1:length(f)] # split up the coefs accordingly coArray = [@view coefs[:, :, ix] for ix in indexes] @debug typeof(collect(X[1])), typeof(collect(coArray[1])) size(X) size(coArray) return predict.(X, coArray) end @traitfn function predict_no_overlap( uf::T, coefs, f::Vector, evts::Vector, ) where {T <: UnfoldModel; ContinuousTimeTrait{T}} has_missings = false yhat = Array{eltype(coefs)}[] @debug eltype(coefs) typeof(yhat) for (fi, e) in zip(f, deepcopy(evts)) # put latency to 1 in case no basis shift e.latency .= -fi.rhs.basisfunction.shift_onset + 1 #sum(times(fi) .<= 0) #e.latency .= 1 X_singles = map(x -> _modelcols(fi, DataFrame(x)), eachrow(e)) coefs_view = matrix_by_basisname(coefs, (uf), (basisname([fi]))) yhat_single = similar( coefs_view, size(coefs_view, 1), size(X_singles[1], 1), length(X_singles), ) for ev = 1:length(X_singles) p = predict(X_singles[ev], coefs_view) if has_missings || isa(p, AbstractArray{<:Union{<:Missing,<:Number}}) # if outside range predictions happen for spline predictors, we have to allow missings # @debug "yeah, missings..." has_missings = true yhat_single = allowmissing(yhat_single) end yhat_single[:, :, ev] .= p end yhat = combine_yhat!(yhat, yhat_single) end @debug typeof(yhat) typeof.(yhat) @debug typeof(vcat(yhat)) return yhat end """ combine_yhat(list,single) combines single into list, if either list or single contains missing, automatically casts the respective counter-part to allow missings as well """ function combine_yhat!(yhat::Vector{<:Array{T}}, yhat_single::Array{T}) where {T} @debug typeof(yhat) typeof.(yhat) typeof(yhat_single) push!(yhat, yhat_single) end combine_yhat!(yhat::Vector{Array{Union{Missing,<:Number}}}, yhat_single) = push!(yhat, allowmissing(yhat_single)) function combine_yhat!( yhat::Vector{<:Array{<:Number}}, yhat_single::Array{T}, ) where {T<:Union{Missing,<:Number}} @debug "new yhat" yhat_new = Array{T}[] combine_yhat!.(Ref(yhat_new), yhat) combine_yhat!(yhat_new, yhat_single) end """ Returns a view of the Matrix `y`, according to the indices of the timeexpanded `basisname` """ function matrix_by_basisname(y::AbstractMatrix, uf, basisnames::Vector) ix = get_basis_indices(uf, basisnames) return @view(y[:, ix]) end """ returns an integer range with the samples around `epoch_event` as defined in the corresponding basisfunction """ function calc_epoch_timewindow(uf, epoch_event) basis_ix = findfirst(Unfold.basisname(formulas(uf)) .== epoch_event) basisfunction = formulas(uf)[basis_ix].rhs.basisfunction return (1:Unfold.height(basisfunction)) .- 1 .+ Unfold.shift_onset(basisfunction) # start at 0 end """ get_basis_indices(uf, basisnames::Vector) returns a boolean vector with length spanning all coefficients, which coefficient is defined by `basisnames` (vector of names) """ get_basis_indices(uf, basisnames::Vector) = reduce(vcat, Unfold.get_basis_names(uf)) .∈ Ref(basisnames) get_basis_indices(uf, basisnames) = get_basis_indices(uf, [basisnames]) """ predicttable(model<:UnfoldModel,events=Unfold.events(model),args...;kwargs...) Shortcut to call efficiently call (pseudocode) `result_to_table(predict(...))`. Returns a tidy DataFrame with the predicted results. Loops all input to `predict`, but really only makes sense to use if you specify either: `overlap = false` (the default) or `epoch_to = "eventname"`. """ function predicttable( model::UnfoldModel, events::Vector = Unfold.events(model), args...; overlap = false, kwargs..., ) p = predict( model, Unfold.formulas(model), events, args...; overlap = overlap, kwargs..., ) return result_to_table(model, p, events) end predicttable(model, events::DataFrame) = predicttable(model, [events]) eventnames(model::UnfoldModel) = first.(design(model)) """ times(model<:UnfoldModel) returns arrays of time-vectors, one for each basisfunction / parallel-fitted-model (MassUnivarite case) """ @traitfn times(model::T) where {T <: UnfoldModel; !ContinuousTimeTrait{T}} = times(design(model)) @traitfn times(model::T) where {T <: UnfoldModel; ContinuousTimeTrait{T}} = times(formulas(model)) times(d::Vector) = times.(d) times(d::FormulaTerm) = times(d.rhs) times(d::MatrixTerm) = times(d.term) times(d::TimeExpandedTerm) = times(d.basisfunction) function times( d::Vector{ <:Pair{ <:Union{<:DataType,<:AbstractString,<:Symbol}, <:Tuple{<:AbstractTerm,<:AbstractVector}, }, }, ) all_times = last.(last.(d)) #[k[2] for k in values(d)] # probably going for steprange would be better # @debug all_times length(all_times) length.(all_times) @assert all(all_times .== all_times[1:1]) "all times need to be equal in a mass univariate model" return all_times end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4748
# pluto compatability of plotting function Base.show( io::IO, ::MIME"text/html", obj::T, ) where { T<:Union{ <:TimeExpandedTerm, <:Vector{<:FormulaTerm}, <:FormulaTerm, <:BasisFunction, <:UnfoldModel, <:Vector{<:AbstractDesignMatrix}, <:Vector{<:Pair{<:Any,<:Tuple}}, }, } #show(IOContext(io, :highlight => false, "text/plain", obj)) is_pluto = get(io, :is_pluto, false) if is_pluto show(Base.stdout, "text/plain", obj) else show(io, "text/plain", obj) end end #----- TimeExpandedTerm function Base.show(io::IO, p::TimeExpandedTerm) t = times(p.basisfunction) tPlot = show_shorten_vector(t) tprint( io, Term.highlight("$(p.basisfunction.name)", :operator) * Term.highlight(": timeexpand($(p.term)) for times $(tPlot)"), ) end function Base.show(io::IO, f::FormulaTerm{<:Union{<:InterceptTerm,TimeExpandedTerm}}) tprint(io, f.rhs) end function Base.show(io::IO, f::Vector{<:FormulaTerm}; eventnames = repeat([""], length(f))) for k = 1:length(f) Term.tprintln( io, "{bold blue_light} $(eventnames[k]){/bold blue_light}", "=>", f[k], ) end end function show_shorten_vector(t) if length(t) > 3 t = (round.(t[[1, 2, end]]; sigdigits = 4)) tPlot = "[" * string(t[1]) * ", " * string(t[2]) * " ... " * string(t[3]) * "]" else tPlot = string(t) end return tPlot end function Base.show(io::IO, obj::BasisFunction) print(io, renderable(obj)) end function renderable(obj::BasisFunction; title = "::BasisFunction") d = OrderedDict( :name => name(obj), :kerneltype => typeof(obj), :width => width(obj), :height => height(obj), :colnames => colnames(obj) |> show_shorten_vector, :times => times(obj) |> show_shorten_vector, :collabel => collabel(obj), :shift_onset => shift_onset(obj), )# |> x -> Tree(x; title = title) str = "{bold blue}::BasisFunction{/bold blue}\n" for (key, val) in d str = str * "{bold blue_light}$key: {/bold blue_light}" * Term.highlight("$val", :number) * "\n" end io = IOBuffer() show( IOContext(io, :limit => true, :displaysize => (40, 40)), "text/plain", kernel(obj, 0), ) s = String(take!(io)) return Panel(str) * s end #---- UnfoldModel function Base.show(io::IO, ::MIME"text/plain", obj::T) where {T<:UnfoldModel} Term.tprintln(io, "Unfold-Type: ::$(typeof(obj)){{$(typeof(obj).parameters[1])}}") keys = first.(design(obj)) forms = formulas(obj) empty_uf = T() is_not_fit = modelfit(obj) == modelfit(empty_uf) #@debug typeof(formulas(obj)) Base.show(io, formulas(obj); eventnames = keys) println(io) Term.tprintln( io, is_not_fit ? "{red}❌{/red]} model not fit" : "{bold green}βœ”{/bold green} model is fit. {blue_light} size(coefs) $(size(coef(obj))){/blue_light}", ) #println(io, "Design: $(design(obj))") println(io) tprint( io, "{gray}Useful functions:{/gray} `design(uf)`, `designmatrix(uf)`, `coef(uf)`, `coeftable(uf)`", ) end ``` print design in a beautiful way ``` function Base.show(io::IO, design::Vector{<:Pair{<:Any,<:Tuple}}) basisList = [] for (first, second) in design push!( basisList, Panel(string(first) * "=>" * "($(second[1]),$(second[2]))", fit = false), ) end print(io, Term.grid(basisList)) end function Base.show(io::IO, ::MIME"text/plain", d::Vector{<:AbstractDesignMatrix}) Term.tprintln(io, "Vector of length $(length(d)), $(unique(typeof.(d)))") Term.tprintln(io, "$(formulas(d))") Term.tprintln( io, "\nuseful functions: `formulas(d)`, `modelmatrix(d)/modelmatrices(d)`, `events(d)`", ) end function Base.show(io::IO, d::AbstractDesignMatrix) Term.tprintln(io, "::$(typeof(d))") Term.tprintln(io, "@formula: $(formulas(d))") sz_evts = isa(d.events, Vector) ? size.(d.events) : size(d.events) sz_modelmatrix = (isa(d.modelmatrix, Vector) | isa(d.modelmatrix, Tuple)) ? size.(d.modelmatrix) : size(d.modelmatrix) Term.tprintln(io, "") Term.tprintln(io, "- modelmatrix (time/trials x predictors): $sz_modelmatrix") Term.tprintln(io, "- $(sz_evts[1]) events with $(sz_evts[2]) columns") Term.tprintln( io, "\nuseful functions: `formulas(d)`, `modelmatrix(d)/modelmatrices(d)`, `events(d)`", ) Term.tprintln(io, "Fields: `.formula`, `.modelmatrix`, `.events`") end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4448
using StatsBase: var function _lsmr!(beta, X::SparseMatrixCSC, data::AbstractArray{<:Number}, ch) _, h = lsmr!(@view(beta[ch, :]), X, @view(data[ch, :]); log = true) return h end function _lsmr!( beta, X::SparseMatrixCSC, data::AbstractArray{<:Union{<:Number,Missing}}, ch, ) dd = view(data, ch, :) ix = @. !ismissing(dd) _, h = lsmr!(@view(beta[ch, :]), (X[ix, :]), @view(data[ch, ix]); log = true) return h end function solver_default( X, data::AbstractArray{T,2}; stderror = false, multithreading = true, show_progress = true, ) where {T<:Union{Missing,<:Number}} minfo = Array{IterativeSolvers.ConvergenceHistory,1}(undef, size(data, 1)) beta = zeros(T, size(data, 1), size(X, 2)) # had issues with undef p = Progress(size(data, 1); enabled = show_progress) X = SparseMatrixCSC(X) # X s often a SubArray, lsmr really doesnt like indexing into subarrays, one copy needed. @maybe_threads multithreading for ch = 1:size(data, 1) # use the previous channel as a starting point ch == 1 || copyto!(view(beta, ch, :), view(beta, ch - 1, :)) h = _lsmr!(beta, X, data, ch) minfo[ch] = h next!(p) end finish!(p) if stderror stderror = calculate_stderror(X, data, beta) modelfit = Unfold.LinearModelFit(beta, ["lsmr", minfo], stderror) else modelfit = Unfold.LinearModelFit(beta, ["lsmr", minfo]) end return modelfit end function solver_default( X, data::AbstractArray{T,3}; stderror = true, multithreading = true, show_progress = true, ) where {T<:Union{Missing,<:Number}} #beta = Array{Union{Missing,Number}}(undef, size(data, 1), size(data, 2), size(X, 2)) beta = zeros(T, size(data, 1), size(data, 2), size(X, 2)) p = Progress(size(data, 1); enabled = show_progress) @maybe_threads multithreading for ch = 1:size(data, 1) for t = 1:size(data, 2) # @debug("$(ndims(data,)),$t,$ch") dd = view(data, ch, t, :) ix = @. !ismissing(dd) beta[ch, t, :] = @view(X[ix, :]) \ @view(data[ch, t, ix]) # qr(X) was slower on Februar 2022 end next!(p) end finish!(p) if stderror stderror = calculate_stderror(X, data, beta) modelfit = LinearModelFit(beta, ["solver_default"], stderror) else modelfit = LinearModelFit(beta, ["solver_default"]) end return modelfit end function calculate_stderror( Xdc, data::AbstractMatrix, beta::AbstractArray{T}, ) where {T<:Union{Missing,<:Number}} # remove missings ix = any(.!ismissing.(data), dims = 1)[1, :] if length(ix) != size(data, 2) @warn( "Limitation: Missing data are calculated over all channels for standard error" ) end data = data[:, ix] Xdc = Xdc[ix, :] # Hat matrix only once hat_prime = inv(disallowmissing(Matrix(Xdc' * Xdc))) # Calculate residual variance @warn( "Autocorrelation was NOT taken into account. Therefore SE are UNRELIABLE. Use at your own discretion" ) se = Array{T}(undef, size(data, 1), size(Xdc, 2)) for ch = 1:size(data, 1) residualVar = var(data[ch, :] .- Xdc * beta[ch, :]) @assert(!isnan(residualVar), "residual Variance was NaN") hat = hat_prime .* residualVar #se = sqrt(diag(cfg.contrast(:,:)*hat*cfg.contrast(:,:)')); se[ch, :] = sqrt.(diag(hat)) end return se end function calculate_stderror( X, data::AbstractArray{T1,3}, beta::AbstractArray{T2}, ) where {T1<:Union{Missing,<:Number},T2<:Union{Missing,<:Number}} #function calculate_stderror(Xdc,data::AbstractArray{T,2},beta) where {T<:Union{Missing, <:Number}} X = disallowmissing(X) # Hat matrix hat_prime = inv(Matrix(X' * X)) se = Array{T2}(undef, size(data, 1), size(data, 2), size(X, 2)) for ch = 1:size(data, 1) for t = 1:size(data, 2) ix = .!ismissing.(data[ch, t, :]) # Calculate residual variance residualVar = var(data[ch, t, ix] .- X[ix, :] * beta[ch, t, :]) @assert(!isnan(residualVar), "residual Variance was NaN") hat = hat_prime .* residualVar #se = sqrt(diag(cfg.contrast(:,:)*hat*cfg.contrast(:,:)')); se[ch, t, :] = sqrt.(diag(hat)) end end return se end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1484
""" Object with a *term* and an applicable *BasisFunction* and a eventfield that are later passed to the basisfunction. $(TYPEDEF) $(TYPEDSIGNATURES) $(FIELDS) # Examples ```julia-repl julia> b = TimeExpandedTerm(term,kernel,[:latencyTR,:durationTR]) ``` """ struct TimeExpandedTerm{T<:AbstractTerm} <: AbstractTerm "Term that the basis function is applied to. This is regularly called in other functions to get e.g. term-coefnames and timeexpand those" term::T "Kernel that determines what should happen to the designmatrix of the term" basisfunction::BasisFunction "Which fields of the event-table should be passed to the basisfunction.Important: The first entry has to be the event-latency in samples!" eventfields::Array{Symbol} end function TimeExpandedTerm(term, basisfunction, eventfields::Nothing) # if the eventfield is nothing, call default TimeExpandedTerm(term, basisfunction) end function TimeExpandedTerm(term, basisfunction, eventfields::Symbol) # call with symbol, convert to array of symbol TimeExpandedTerm(term, basisfunction, [eventfields]) end function TimeExpandedTerm(term, basisfunction; eventfields = [:latency]) # default call, use latency TimeExpandedTerm(term, basisfunction, eventfields) end collabel(term::TimeExpandedTerm) = collabel(term.basisfunction) StatsModels.width(term::TimeExpandedTerm) = width(term.basisfunction) * width(term.term) StatsModels.terms(t::TimeExpandedTerm) = terms(t.term)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
5650
""" using Base: @deprecate_binding The main abstract model-type of the toolbox. E.g. `UnfoldLinearModel` is a concrete type of this """ abstract type UnfoldModel{T} end """ Abstract Type to report modelresults """ abstract type AbstractModelFit{T,N} end abstract type AbstractDesignMatrix{T} end """ DesignMatrix Type that keeps an Array of `formulas`, designmatrices `modelmatrix` (Array or Array of Arrays in case of MixedModel) and `events`-dataframe """ struct DesignMatrixLinearModel{T} <: AbstractDesignMatrix{T} formula::FormulaTerm # "Array of formulas" modelmatrix::Array{T,2} #"A concatenated designmatric. In case of Mixed Models an array, where the first one is a FeMat, later ones ReMats. " events::Union{<:SubDataFrame,<:DataFrame} #"Event table with all events" end struct DesignMatrixLinearModelContinuousTime{T} <: AbstractDesignMatrix{T} formula::FormulaTerm # "Array of formulas" modelmatrix::SparseMatrixCSC{T} #"A concatenated designmatric. In case of Mixed Models an array, where the first one is a FeMat, later ones ReMats. " events::DataFrame #"Event table with all events" end """ in case a single FormulaTerm is inputted, this is wrapped into a vector """ # DesignMatrixLinearModel(f::FormulaTerm, modelmatrix, events) = # DesignMatrixLinearModel([f], modelmatrix, events) # DesignMatrixLinearModel(f, modelmatrix, events::DataFrame) = DesignMatrixLinearModel(f, modelmatrix, [events]) DesignMatrixLinearModel(args...) = DesignMatrixLinearModel{Float64}() DesignMatrixLinearModel{T}() where {T} = DesignMatrixLinearModel{T}( FormulaTerm(:empty, :empty), Array{T,2}(undef, 0, 0), DataFrame(), ) DesignMatrixLinearModelContinuousTime(args...) = DesignMatrixLinearModelContinuousTime{Float64}() DesignMatrixLinearModelContinuousTime{T}() where {T} = DesignMatrixLinearModelContinuousTime{T}( FormulaTerm(:empty, :empty), SparseMatrixCSC(Array{T,2}(undef, 0, 0)), DataFrame(), ) # DesignMatrixLinearModelContinuousTime(f, modelmatrix, events::DataFrame) = # DesignMatrixLinearModelContinuousTime(f, modelmatrix, [events]) # DesignMatrixLinearModelContinuousTime(f, modelmatrix::SparseMatrixCSC, events) = # DesignMatrixLinearModelContinuousTime(f, [modelmatrix], events) """ Contains the results of linearmodels (continuous and not) """ struct LinearModelFit{T,N} <: AbstractModelFit{T,N} estimate::Array{T,N} info::Any standarderror::Array{T,N} end LinearModelFit() = LinearModelFit(Float64[], [], Float64[]) LinearModelFit(estimate) = LinearModelFit(estimate, []) LinearModelFit(estimate::Array{T,2}, info) where {T} = LinearModelFit(estimate, info, similar(Array{T}, 0, 0)) LinearModelFit(estimate::Array{T,3}, info) where {T} = LinearModelFit(estimate, info, similar(Array{T}, 0, 0, 0)) """ Concrete type to implement an Mass-Univariate LinearModel. `.design` contains the formula + times dict `.designmatrix` contains a `DesignMatrix` `modelfit` is a `Any` container for the model results """ mutable struct UnfoldLinearModel{T} <: UnfoldModel{T} design::Vector{<:Pair{<:Any,<:Tuple}} designmatrix::Vector{<:DesignMatrixLinearModel{T}} modelfit::LinearModelFit{T,3} end # empty model UnfoldLinearModel(args...) = UnfoldLinearModel{Float64}(args...) UnfoldLinearModel{T}() where {T} = UnfoldLinearModel{T}([:empty => ()]) # backward compatible with dict UnfoldLinearModel{T}(d::Dict, args...) where {T} = UnfoldLinearModel(collect(pairs(d)), args...) # only design specified UnfoldLinearModel{T}(d::Vector{<:Pair}) where {T} = UnfoldLinearModel{T}(d, [DesignMatrixLinearModel{T}()]) # matrix not a vector of matrix UnfoldLinearModel{T}(d::Vector{<:Pair}, X::AbstractDesignMatrix) where {T} = UnfoldLinearModel{T}(d, [X]) # no modelfit UnfoldLinearModel{T}(d::Vector{<:Pair}, X::Vector{<:AbstractDesignMatrix{T}}) where {T} = UnfoldLinearModel{T}(deepcopy(d), X, LinearModelFit(Array{T,3}(undef, 0, 0, 0))) """ Concrete type to implement an deconvolution LinearModel. `.design` contains the formula + times dict `.designmatrix` contains a `DesignMatrix` `modelfit` is a `Any` container for the model results """ mutable struct UnfoldLinearModelContinuousTime{T} <: UnfoldModel{T} design::Vector{<:Pair{<:Any,<:Tuple}} designmatrix::Vector{<:DesignMatrixLinearModelContinuousTime{T}} modelfit::LinearModelFit{T,2} end # empty model UnfoldLinearModelContinuousTime(args...) = UnfoldLinearModelContinuousTime{Float64}(args...) UnfoldLinearModelContinuousTime{T}() where {T} = UnfoldLinearModelContinuousTime{T}([:empty => ()]) # backward compatible with dict UnfoldLinearModelContinuousTime{T}(d::Dict, args...) where {T} = UnfoldLinearModelContinuousTime{T}(keys(d) .=> values(d), args...) # only design specified UnfoldLinearModelContinuousTime{T}(d::Vector{<:Pair}) where {T} = UnfoldLinearModelContinuousTime{T}(d, Unfold.DesignMatrixLinearModelContinuousTime{T}()) # matrix not a vector of matrix UnfoldLinearModelContinuousTime{T}(d::Vector{<:Pair}, X::AbstractDesignMatrix) where {T} = UnfoldLinearModelContinuousTime{T}(d, [X]) # no modelfit UnfoldLinearModelContinuousTime{T}( d::Vector{<:Pair}, X::Vector{<:AbstractDesignMatrix{T}}, ) where {T} = UnfoldLinearModelContinuousTime{T}( deepcopy(d), X, LinearModelFit(Array{T,2}(undef, 0, 0)), ) #---- # Traits definitions @traitdef ContinuousTimeTrait{X} @traitimpl ContinuousTimeTrait{UnfoldLinearModelContinuousTime} #--- """ Abstract non-linear spline term. Implemented in `UnfoldBSplineKitExt` """ abstract type AbstractSplineTerm <: AbstractTerm end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
5380
# misc functions function epoch(; data, evts = nothing, tbl = nothing, Ο„, sfreq, kwargs...) @assert (isnothing(evts) | isnothing(tbl)) evts = isnothing(evts) ? tbl : evts @show isnothing(evts), isnothing(tbl) epoch(data, evts, Ο„, sfreq; kwargs...) end """ epoch(data::Array{T,1},evts::DataFrame,Ο„::Tuple/Vector,sfreq;kwargs..., Basic function to epoch data; all input also available as kwargs. Additional kwarg: `eventtime`=:latency, which defines the column in `evts` that is used to cut the data (in samples). For uneven sample-times we use `round()`` """ function epoch(data::Array{T,1}, evts, Ο„, sfreq; kwargs...) where {T<:Union{Missing,Number}} data_r = reshape(data, (1, :)) epoch(data_r, evts, Ο„, sfreq; kwargs...) end function epoch(data::Matrix, evts::DataFrame, Ο„::Vector, sfreq; kwargs...) return epoch(data, evts, (Ο„[1], Ο„[2]), sfreq; kwargs...) end function epoch( data::Matrix, evts::DataFrame, Ο„::Tuple{Number,Number}, sfreq; eventtime::String = "latency", ) return epoch(data, evts, Ο„, sfreq; eventtime = Symbol(eventtime)) end function epoch( data::Array{T,2}, evts::DataFrame, Ο„::Tuple{Number,Number}, sfreq; eventtime::Symbol = :latency, ) where {T<:Union{Missing,Number}} # data: channels x times # partial taken from EEG.jl numEpochs = size(evts, 1) Ο„ = round_times(Ο„, sfreq) times = range(Ο„[1], stop = Ο„[2], step = 1 ./ sfreq) lenEpochs = length(times) numChans = size(data, 1) epochs = Array{Union{Missing,Float64}}( missing, Int(numChans), Int(lenEpochs), Int(numEpochs), ) # User feedback @debug "Creating epochs: $numChans x $lenEpochs x $numEpochs" for si = 1:size(evts, 1) #eventonset = evts[si,eventtime] # in samples #d_start = eventonset d_start = Int(round(evts[si, eventtime]) + times[1] .* sfreq) d_end = Int(round(evts[si, eventtime]) + times[end] .* sfreq) e_start = 1 e_end = lenEpochs #println("d: $(size(data)),e: $(size(epochs)) | $d_start,$d_end,$e_start,$e_end | $(evts[si,eventtime])") if d_start < 1 e_start = e_start + (-d_start + 1) d_start = 1 end if d_end > size(data, 2) e_end = e_end - (d_end - size(data, 2)) d_end = size(data, 2) end #println("d: $(size(data)),e: $(size(epochs)) | $d_start,$d_end,$e_start,$e_end | $(evts[si,eventtime])") epochs[:, e_start:e_end, si] = data[:, d_start:d_end] end return (epochs, times) end function round_times(Ο„, sfreq) # function to round Ο„ to sfreq samples. This specifies the epoch length. # its a function to be the same for epoch & timeexpanded analyses return round.(Ο„ .* sfreq) ./ sfreq end """ [X,y] = drop_missing_epochs(X, y::Array) Helper function to remove epochs of `y` that contain missings. Drops them from both `X` and `y`. Often used in combination with `Unfold.epoch` X can be anything that has two dimensions (Matrix, DataFrame etc) """ function drop_missing_epochs(X, y::AbstractArray{T,3}) where {T} @assert length(size(X)) == 2 missingIx = .!any(ismissing.(y), dims = (1, 2)) goodIx = dropdims(missingIx, dims = (1, 2)) return X[goodIx, :], Array{Float64}(y[:, :, goodIx]) end """ $(SIGNATURES) Flatten a 1D array from of a 2D/3D array. Also drops the empty dimension """ function linearize(x::AbstractArray{T,N}) where {T,N} # used in condense_long to generate the long format return x[:] #dropdims(reshape(x, :, 1), dims = 2)::AbstractArray{T,1} end function linearize(x::String) return x end """ $(SIGNATURES) Equates the length of data and designmatrix by cutting the shorter one The reason we need this is because when generating the designmatrix, we do not know how long the data actually are. We only assume that event-latencies are synchronized with the data """ function equalize_size( X::AbstractMatrix, data::AbstractArray{T,2}, ) where {T<:Union{Missing,<:Number}} @debug("2d equalize_size") if size(X, 1) > size(data, 2) X = @view X[1:size(data, 2), :] else data = @view data[:, 1:size(X, 1)] end return X, data end function equalize_size( X::AbstractMatrix, data::AbstractVector{T}, ) where {T<:Union{Missing,<:Number}} @debug("1d equalize_size") if size(X, 1) > length(data) X = @view X[1:length(data), :] else data = @view data[1:size(X, 1)] end return X, data end function equalize_size( X::AbstractMatrix, data::AbstractArray{T,3}, ) where {T<:Union{Missing,<:Number}} @debug("3d equalize_size") @assert size(X, 1) == size(data, 3) "Your events are not of the same size as your last dimension of data" return X, data end function clean_data( data::AbstractArray{T,2}, winrej::AbstractArray{<:Number,2}, ) where {T<:Union{Float64,Missing}} data = Array{Union{Float64,Missing}}(data) for row = 1:size(winrej, 1) data[:, Int.(winrej[row, 1]:winrej[row, 2])] .= missing end return data end macro maybe_threads(multithreading, code) return esc(:( if multithreading Threads.@threads($code) else $code end )) end poolArray(x) = PooledArray(x; compress = true)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1604
@testset "FIR" begin firbase = firbasis((-1, 1), 10) # test optional call @test Unfold.kernel(firbase, 1) == Unfold.kernel(firbasis((-1, 1), 10), 1) @test typeof(Unfold.name(firbase)) <: String # test basics of basisfunction @test length(collect(Unfold.colnames(firbase))) == 21 @test unique(Unfold.kernel(firbase, 1)) == [1.0, 0.0] # test length consistency @test length(Unfold.colnames(firbase)) == size(Unfold.kernel(firbase, 3.1))[2] @test length(Unfold.times(firbase)) == size(Unfold.kernel(firbase, 3.1))[1] # testing the non-sampling rate samples # test the interpolate / true false firbase_off = firbasis((-1, 1), 10; interpolate = false) firbase_on = firbasis((-1, 1), 10; interpolate = true) @test Unfold.kernel(firbase_off, 0.5)[1:3, 1:3] == [1 0 0; 0 1 0; 0 0 1] @test Unfold.kernel(firbase_on, 0.5)[1:3, 1:3] == [0.5 0.0 0.0; 0.5 0.5 0.0; 0.0 0.5 0.5] end @testset "BOLD" begin boldbase = hrfbasis(2.0, name = "test") @test Unfold.name(boldbase) == "test" @test Unfold.kernel(boldbase, 0) == Unfold.kernel(boldbase, 1) @test Unfold.kernel(boldbase, 0.1) != Unfold.kernel(boldbase, 1) # testing fractional kernel generation @test findmax(Unfold.kernel(boldbase, 0.3))[2][1] == 4 end @testset "timespline" begin splinebase = Unfold.splinebasis(Ο„ = (-1, 1), sfreq = 20, nsplines = 10, name = "basisA") @test length(Unfold.colnames(splinebase)) == size(Unfold.kernel(splinebase, 3.1))[2] @test length(Unfold.times(splinebase)) == size(Unfold.kernel(splinebase, 3.1))[1] end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
2156
using Test using MixedModelsSim using Random using DSP include("test_utilities.jl") Ο„ = 1.5 fs = 18 evt, epoch_dat = simulate_lmm( MersenneTwister(1), Ο„, fs, Ξ² = [0.0, -1.0], Οƒs = [1, 1, 1], Οƒ = 1, n_sub = 20, n_item = 30, noise_type = "AR-exponential", ); #mres,res = fit(UnfoldLinearMixedModel,f,evt,dat[chIx:chIx,:,:].*1e6 ,times,contrasts=Dict(:category => EffectsCoding(), :condition => EffectsCoding())); times = range(0, stop = Ο„ - 1 / fs, step = 1 / fs) f2 = @formula 0 ~ 1 + stimType + (1 + stimType | subj) + (1 | item) mres, res = fit(UnfoldLinearMixedModel, f2, evt, epoch_dat, times) p_df = cluster_permutation_test(mres, epoch_dat, times, 2) @test p_df[1, :pval] == 0.036 #--- Testing cluster_permutation call tRange = 1:length(times) nPerm = 10 permDat = cluster_permutation(mres, epoch_dat, tRange, 2, nPerm) @test size(permDat, 2) == nPerm @test size(permDat, 1) == length(tRange) tRange = 5:length(times)-5 permDat = cluster_permutation(mres, epoch_dat, tRange, 2, nPerm) @test size(permDat, 1) == length(tRange) #------ testing pymne_cluster z_obs = [ m.z for m in coefpvalues(mres.modelinfo) if String(m.coefname) == coefnames(mres.X.formulas)[2][coeffOfInterest] ] #-- clusterpermutation obs_cluster = pymne_cluster(z_obs, 4) @test all(abs.(obs_cluster[2]) .> 4) # clusters have to be larger 4 @test obs_cluster[1][1][1].start == 13 # start of cluster @test obs_cluster[1][1][1].stop == 14 # end of cluster obs_cluster = pymne_cluster(z_obs, 0.1) @test all(abs.(obs_cluster[2]) .> 0.1) # all clusters have to be larger 0.1 @test length(obs_cluster[2]) == 12 # if nothing changed, 12 clusters should be found #-- tfce clusterFormingThreshold = Dict(:start => 0, :step => 0.2) obs_cluster = pymne_cluster(z_obs, clusterFormingThreshold) @test all(obs_cluster[2] .>= 0) # TFCE is always positive @test findmax(obs_cluster[2])[2] == findmax(abs.(z_obs))[2] # tfce should not move maximum #gen_han(Ο„,fs,3) if 1 == 0 # plot some design bits map = mapping(:subj, :dv, color = :stimType)#,linestyle=:channel) AlgebraOfGraphics.data(evt) * visual(Scatter) * map |> draw end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
954
#using Unfold using MAT using DataFrames using DelimitedFiles function import_eeglab(filename) file = MAT.matopen(filename) # open file EEG = read(file, "EEG") function parse_struct(s::Dict) return DataFrame(map(x -> dropdims(x, dims = 1), values(s)), collect(keys(s))) end evts_df = parse_struct(EEG["event"]) chanlocs_df = parse_struct(EEG["chanlocs"]) # epoch_df = parse_struct(EEG["epochs"]) srate = EEG["srate"] if typeof(EEG["data"]) == String datapath = joinpath(splitdir(filename)[1], EEG["data"]) data = Array{Float32,3}( undef, Int(EEG["nbchan"]), Int(EEG["pnts"]), Int(EEG["trials"]), ) read!(datapath, data) else data = EEG["data"] end if (ndims(data) == 3) & (size(data, 3) == 1) data = dropdims(data, dims = 3) end return data, srate, evts_df, chanlocs_df, EEG end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
10219
##--- tbl = DataFrame([1 4]', [:latency]) X = ones(size(tbl)) shouldBeNeg = zeros(4, 4) shouldBeNeg[1, :] = [1, 0, 0, 1] shouldBeNeg[2, :] = [0, 1, 0, 0] shouldBeNeg[3, :] = [0, 0, 1, 0] shouldBeNeg[4, :] = [0, 0, 0, 1] shouldBePos = zeros(4, 4) shouldBePos[1, :] = [0, 0, 0, 0] shouldBePos[2, :] = [1, 0, 0, 0] shouldBePos[3, :] = [0, 1, 0, 0] shouldBePos[4, :] = [0, 0, 1, 0] ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) #--- @testset "basic designmat" begin ## test negative basisfunction = firbasis(Ο„ = (-3, 0), sfreq = 1, name = "testing") timeexpandterm = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction, :latency) Xdc = Unfold.time_expand(X, timeexpandterm, tbl) @test all(isapprox.(Matrix(Xdc)[1:4, 1:4], shouldBeNeg, atol = 1e-15)) ## Test Positive only basisfunction = firbasis(Ο„ = (1, 4), sfreq = 1, name = "testing") timeexpandterm = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction, :latency) Xdc = Unfold.time_expand(X, timeexpandterm, tbl) @test all(isapprox.(Matrix(Xdc)[1:4, 1:4], shouldBePos, atol = 1e-15)) end @testset "basic designmat interpolated yes/no" begin ## test negative basisfunction = firbasis(Ο„ = (-3, 0), sfreq = 1, name = "testing") timeexpandterm = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction, :latency) Xdc = Unfold.time_expand(X, timeexpandterm, tbl) @test length(Unfold.times(timeexpandterm)) == 4 @test size(Xdc) == (4, 4) @test Unfold.width(basisfunction) == 4 @test Unfold.height(basisfunction) == 4 basisfunction = firbasis(Ο„ = (-3, 0), sfreq = 1, name = "testing", interpolate = true) timeexpandterm = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction, :latency) Xdc = Unfold.time_expand(X, timeexpandterm, tbl) @test length(Unfold.times(timeexpandterm)) == 5 @test Unfold.width(basisfunction) == 4 @test Unfold.height(basisfunction) == 5 @test size(Xdc) == (5, 4) end @testset "customized eventfields" begin tbl2 = tbl = DataFrame([1 4]', [:onset]) timeexpandterm_latency = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction) timeexpandterm_onset = Unfold.TimeExpandedTerm( FormulaTerm(Term, Term), basisfunction, eventfields = [:onset], ) Xdc = Unfold.time_expand(X, timeexpandterm_onset, tbl) @test_throws ArgumentError Unfold.time_expand(X, timeexpandterm_latency, tbl) end @testset "combining designmatrices" begin tbl = DataFrame([1 4]', [:latency]) X = ones(size(tbl)) basisfunction1 = firbasis(Ο„ = (0, 1), sfreq = 10, name = "basis1") basisfunction2 = firbasis(Ο„ = (0, 0.5), sfreq = 10, name = "basis2") f = @formula 0 ~ 1 Xdc1 = designmatrix(UnfoldLinearModelContinuousTime, f, tbl, basisfunction1) Xdc2 = designmatrix(UnfoldLinearModelContinuousTime, f, tbl .+ 1, basisfunction2) Xdc = Xdc1 + Xdc2 @test size(modelmatrix(Xdc), 2) == size(modelmatrix(Xdc1), 2) + size(modelmatrix(Xdc2), 2) @test length(Unfold.events(Xdc)) == 2 Xdc_3 = Xdc1 + Xdc2 + Xdc2 @test size(modelmatrix(Xdc_3), 2) == size(modelmatrix(Xdc1), 2) + 2 * size(modelmatrix(Xdc2), 2) @test length(Unfold.events(Xdc_3)) == 3 end @testset "combining MixedModel Designmatrices" begin basisfunction1 = firbasis(Ο„ = (0, 1), sfreq = 10, name = "basis1") basisfunction2 = firbasis(Ο„ = (0, 0.5), sfreq = 10, name = "basis2") tbl = DataFrame( [1 4 10 15 20 22 31 37; 1 1 1 2 2 2 3 3; 1 2 3 1 2 3 1 2]', [:latency, :subject, :item], ) tbl2 = DataFrame( [2 3 12 18 19 25 40 43; 1 1 1 2 2 2 3 3; 1 2 3 1 2 3 1 2]', [:latency, :subject, :itemB], ) y = Float64.([collect(range(1, stop = 100))...])' transform!(tbl, :subject => categorical => :subject) transform!(tbl2, :itemB => categorical => :itemB) transform!(tbl, :item => categorical => :item) #tbl.itemB = tbl.item f3 = @formula 0 ~ 1 + (1 | item) + (1 | subject) f4 = @formula 0 ~ 1 + (1 | itemB) f4_wrong = @formula 0 ~ 1 + (1 | item) ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) Xdc3 = designmatrix(ext.UnfoldLinearMixedModel, f3, tbl, basisfunction1) Xdc4 = designmatrix(ext.UnfoldLinearMixedModel, f4, tbl2, basisfunction2) Xdc4_wrong = designmatrix(ext.UnfoldLinearMixedModel, f4_wrong, tbl, basisfunction2) Xdc = Xdc3 + Xdc4 @test typeof(modelmatrix(Xdc)[1]) <: SparseArrays.SparseMatrixCSC @test length(modelmatrix(Xdc)) == 4 # one FeMat + 3 ReMat @test_throws String modelmatrix(Xdc3 + Xdc4_wrong) end @testset "equalizeReMatLengths" begin bf1 = firbasis(Ο„ = (0, 1), sfreq = 10, name = "basis1") bf2 = firbasis(Ο„ = (0, 0.5), sfreq = 10, name = "basis2") tbl1 = DataFrame( [1 4 10 15 20 22 31 37; 1 1 1 2 2 2 3 3; 1 2 3 1 2 3 1 2]', [:latency, :subject, :item], ) tbl2 = DataFrame( [2 3 12 18 19 25 40 43; 1 1 1 2 2 2 3 3; 1 2 3 1 2 3 1 2]', [:latency, :subject, :itemB], ) transform!(tbl1, :subject => categorical => :subject) transform!(tbl1, :item => categorical => :item) transform!(tbl2, :itemB => categorical => :itemB) #tbl.itemB = tbl.item f1 = @formula 0 ~ 1 + (1 | item) + (1 | subject) f2 = @formula 0 ~ 1 + (1 | itemB) form = apply_schema(f1, schema(f1, tbl1), MixedModels.LinearMixedModel) form = Unfold.apply_basisfunction(form, bf1, nothing, Any) X1 = modelcols.(form.rhs, Ref(tbl1)) form = apply_schema(f2, schema(f2, tbl2), MixedModels.LinearMixedModel) form = Unfold.apply_basisfunction(form, bf2, nothing, Any) X2 = modelcols.(form.rhs, Ref(tbl2)) # no missmatch, shouldnt change anything then X = deepcopy(X1[2:end]) if !isdefined(Base, :get_extension) include("../ext/UnfoldMixedModelsExt/UnfoldMixedModelsExt.jl") ext = UnfoldMixedModelsExt else ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) end ext.equalize_ReMat_lengths!(X) @test all([x[1] for x in size.(X)] .== 47) X = (deepcopy(X1[2:end])..., deepcopy(X2[2:end])...) @test !all([x[1] for x in size.(X)] .== 48) # not alllenghts the same ext.equalize_ReMat_lengths!(X) @test all([x[1] for x in size.(X)] .== 48) # now all lengths the same :-) X = deepcopy(X2[2]) @test size(X)[1] == 48 ext.change_ReMat_size!(X, 52) @test size(X)[1] == 52 X = deepcopy(X2[2]) @test size(X)[1] == 48 ext.change_ReMat_size!(X, 40) @test size(X)[1] == 40 X = (deepcopy(X1)..., deepcopy(X2[2:end])...) @test size(X[1])[1] == 47 @test size(X[2])[1] == 47 @test size(X[3])[1] == 47 @test size(X[4])[1] == 48 XA, XB = ext.change_modelmatrix_size!(52, X[1], X[2:end]) @test size(XA)[1] == 52 @test size(XB)[1] == 52 XA, XB = ext.change_modelmatrix_size!(40, X[1], X[2:end]) @test size(XA)[1] == 40 @test size(XB)[1] == 40 XA, XB = ext.change_modelmatrix_size!(30, Matrix(X[1]), X[2:end]) @test size(XA)[1] == 30 @test size(XB)[1] == 30 end @testset "Some LinearMixedModel tests" begin data, evts = loadtestdata("testCase3", dataPath = (@__DIR__) * "/data") # evts.subject = categorical(evts.subject) f_zc = @formula 0 ~ 1 + condA + condB + zerocorr(1 + condA + condB | subject) basisfunction = firbasis(Ο„ = (-0.1, 0.1), sfreq = 10, name = "ABC") Xdc_zc = designmatrix(ext.UnfoldLinearMixedModel, f_zc, evts, basisfunction) @test length(Xdc_zc.modelmatrix[2].inds) == 9 f = @formula 0 ~ 1 + condA + condB + (1 + condA + condB | subject) Xdc = designmatrix(ext.UnfoldLinearMixedModel, f, evts, basisfunction) @test length(Xdc.modelmatrix[2].inds) == (9 * 9 + 9) / 2 # test bug with not sequential subjects evts_nonseq = copy(evts) evts_nonseq = evts_nonseq[.!(evts_nonseq.subject .== 2), :] Xdc_nonseq = designmatrix(ext.UnfoldLinearMixedModel, f_zc, evts_nonseq, basisfunction) end #basisfunction2 = firbasis(Ο„ = (0, 0.5), sfreq = 10, name = "basis2") @testset "Missings in Events" begin tbl = DataFrame( :a => [1.0, 2, 3, 4, 5, 6, 7, 8], :b => [1.0, 1, 1, 2, 2, 2, 3, missing], :c => [1.0, 2, 3, 4, 5, 6, 7, missing], :d => ["1", "2", "3", "4", "5", "6", "7", "8"], :e => ["1", "2", "3", "4", "5", "6", "7", missing], :event => [1, 1, 1, 1, 2, 2, 2, 2], :latency => [10, 20, 30, 40, 50, 60, 70, 80], ) tbl.event = string.(tbl.event) designmatrix(UnfoldLinearModel, @formula(0 ~ a), tbl) @test_throws ErrorException designmatrix(UnfoldLinearModel, @formula(0 ~ a + b), tbl) @test_throws ErrorException designmatrix(UnfoldLinearModel, @formula(0 ~ e), tbl) # including an actual missing doesnt work design = [ "1" => (@formula(0 ~ a + b + c + d + e), firbasis((0, 1), 1)), "2" => (@formula(0 ~ a + b + c + d + e), firbasis((0, 1), 1)), ] uf = UnfoldLinearModelContinuousTime(design) @test_throws ErrorException designmatrix(uf, tbl) # but if the missing is in another event, no problem design = [ "1" => (@formula(0 ~ a + b + c + d + e), firbasis((0, 1), 1)), "2" => (@formula(0 ~ a + d), firbasis((0, 1), 1)), ] uf = UnfoldLinearModelContinuousTime(design) designmatrix(uf, tbl) # prior to the Missing disallow sanity check, this gave an error design = [ "1" => (@formula(0 ~ spl(a, 4) + spl(b, 4) + d + e), firbasis((0, 1), 1)), "2" => (@formula(0 ~ a + d), firbasis((0, 1), 1)), ] uf = UnfoldLinearModelContinuousTime(design) designmatrix(uf, tbl) end @testset "Integer Covariate Splines" begin tbl = DataFrame( :a => [1.0, 2, 3, 4, 5, 6, 7, 8], :event => [1, 1, 1, 1, 2, 2, 2, 2], :latency => [10, 20, 30, 40, 50, 60, 70, 80], ) tbl.event = string.(tbl.event) designmatrix(UnfoldLinearModel, @formula(0 ~ a), tbl) # prior to the Missing disallow sanity check, this gave an error design = ["1" => (@formula(0 ~ spl(a, 4)), firbasis((0, 1), 1))] uf = UnfoldLinearModelContinuousTime(design) designmatrix(uf, tbl) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1303
using Unfold using UnfoldSim using CairoMakie using DataFrames using UnfoldMakie data, evts = UnfoldSim.predef_eeg(; n_repeats = 5, noiselevel = 0.8) uf = fit( UnfoldModel, [ "car" => (@formula(0 ~ 1 + spl(continuous, 4)), firbasis((-0.1, 1), 100)), "face" => (@formula(0 ~ 1 + continuous^2), firbasis((-0.2, 0.4), 100)), ], evts, data; eventcolumn = "condition", show_progress = false, ) #---- ix = 500 lines(predict(uf)[1, 1:ix]) # predict(m,overlap=false) #--- f = Figure() heatmap( f[1, 1], predict(uf; keep_basis = ["car"], epoch_to = "car", eventcolumn = :condition)[1, :, :], ) heatmap( f[1, 2], predict(uf; keep_basis = ["car"], epoch_to = "face", eventcolumn = :condition)[1, :, :], ) heatmap( f[2, 2], predict(uf; keep_basis = ["face"], epoch_to = "face", eventcolumn = :condition)[ 1, :, :, ], ) heatmap( f[2, 1], predict(uf; keep_basis = ["face"], epoch_to = "car", eventcolumn = :condition)[1, :, :], ) f #--- predict( uf, DataFrame(:continuous => [1, 5], :condition => ["car", "face"], :latency => [1, 40]), )[1][ 1, :, :, ]' |> series #--- eff = effects(Dict(:continuous => [0, 1, 2]), uf) plot_erp(eff; mapping = (; color = :continuous, col = :eventname))
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1983
## using Test, StatsModels using DataFrames import Logging using Unfold include("test_utilities.jl") Logging.global_logger(Logging.SimpleLogger(stdout, Logging.Debug)) data, evts = loadtestdata("testCase3") # append!(data, zeros(1000)) data = reshape(data, 1, :) data = vcat(data, data) data = data .+ 1 * randn(size(data)) # we have to add minimal noise, else mixed models crashes. data_missing = Array{Union{Missing,Number}}(undef, size(data)) data_missing .= data data_missing[4500:4600] .= missing categorical!(evts, :subject) f = @formula 0 ~ 1 + condA + condB + (1 + condA + condB | subject) #f = @formula 0~1 + (1|subject) # cut the data into epochs # TODO This ignores subject bounds data_e, times = Unfold.epoch(data = data, tbl = evts, Ο„ = (-1.0, 1.9), sfreq = 10) evts_e, data_e = Unfold.drop_missing_epochs(evts, data_e) ## basisfunction = firbasis(Ο„ = (-0.1, 0.3), sfreq = 10) f = @formula 0 ~ 1 + condA + condB # 1 Xs = designmatrix(UnfoldLinearModel, f, evts_e) ufModel_A = unfoldfit(UnfoldLinearModel, Xs, data_e) basisfunction = firbasis(Ο„ = (-0.1, 0.3), sfreq = 10) Xs = designmatrix(UnfoldLinearModel, f, evts, basisfunction) basisfunction = firbasis(Ο„ = (-0.1, 0.5), sfreq = 10) Xs2 = designmatrix(UnfoldLinearModel, f, evts, basisfunction) Xs = Xs + Xs2 ufModel_B = unfoldfit(UnfoldLinearModel, Xs, data) f = @formula 0 ~ 1 + condA + condB + (1 + condA | subject) Xs = designmatrix(UnfoldLinearMixedModel, f, evts_e) ufModel_C = unfoldfit(UnfoldLinearMixedModel, Xs, data_e) basisfunction = firbasis(Ο„ = (-0.1, 0.3), sfreq = 10) Xs = designmatrix(UnfoldLinearMixedModel, f, evts, basisfunction) ufModel_D = unfoldfit(UnfoldLinearMixedModel, Xs, data) ufA = condense_long(ufModel_A, times) ufB = condense_long(ufModel_B) ufC = condense_long(ufModel_C, times) ufD = condense_long(ufModel_D) plot(ufA.colname_basis, ufA.estimate) plot(ufC.colname_basis, ufC.estimate) plot(ufB.colname_basis, ufB.estimate) plot(ufD.colname_basis, ufD.estimate)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
10399
data, evts = loadtestdata("test_case_3a") # data_r = reshape(data, (1, :)) data_e, times = Unfold.epoch(data = data_r, tbl = evts, Ο„ = (0, 0.05), sfreq = 10) # cut the data into epochs f = @formula 0 ~ 1 + conditionA + continuousA # 1 m_mul = fit(Unfold.UnfoldModel, [Any => (f, times)], evts, data_e) ##--- @testset "Mass Univariate, all specified" begin # test simple case eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [0]), m_mul) @test size(eff, 1) == 2 # we specified 2 levels @ 1 time point @test eff.conditionA β‰ˆ [0.0, 1.0] # we want to different levels @test eff.yhat β‰ˆ [2.0, 5.0] # these are the perfect predicted values # combination 2 levels / 6 values eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [-2, 0, 2]), m_mul) @test size(eff, 1) == 6 # we want 6 values @test eff.conditionA β‰ˆ [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] @test eff.continuousA β‰ˆ [-2, 0, 2, -2, 0, 2.0] end @testset "Mass Univariate, typified" begin # testing typical value eff_man = Unfold.effects( Dict(:conditionA => [0, 1], :continuousA => [mean(evts.continuousA)]), m_mul, ) eff_typ = Unfold.effects(Dict(:conditionA => [0, 1]), m_mul) @test eff_man.yhat β‰ˆ eff_typ.yhat end ## Testing Splines f_spl = @formula 0 ~ 1 + conditionA + spl(continuousA, 4) # 1 m_mul_spl = fit(UnfoldModel, f_spl, evts, data_e, times) @testset "Mass Univariate, splines" begin eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [0]), m_mul_spl) @test size(eff, 1) == 2 # we specified 2 levels @ 1 time point @test eff.conditionA β‰ˆ [0.0, 1.0] # we want to different levels @test eff.yhat β‰ˆ [2.0, 5.0] # these are the perfect predicted values # combination 2 levels / 6 values eff = Unfold.effects( Dict(:conditionA => [0, 1], :continuousA => [-0.5, 0, 0.5]), m_mul_spl, ) @test size(eff, 1) == 6 # we want 6 values @test eff.conditionA β‰ˆ [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] @test eff.continuousA β‰ˆ [-0.5, 0, 0.5, -0.5, 0, 0.5] @test eff.yhat β‰ˆ [0, 2, 4, 3, 5, 7] # testing for safe predictions eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [2]), m_mul_spl) @test all(ismissing.(eff.yhat)) end ## Timeexpansion data, evts = loadtestdata("test_case_3a") # f = @formula 0 ~ 1 + conditionA + continuousA # 1 @testset "Time Expansion, one event" begin uf = fit(Unfold.UnfoldModel, Dict(Any => (f, firbasis([0, 0.1], 10))), evts, data) eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [0]), uf) @test nrow(eff) == 4 @test eff.yhat β‰ˆ [2.0, 2.0, 5.0, 5.0] @test eff.conditionA β‰ˆ [0.0, 0.0, 1.0, 1.0] @test eff.continuousA β‰ˆ [0.0, 0.0, 0.0, 0.0] end data, evts = loadtestdata("test_case_4a") # b1 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20, name = "eventA") b2 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20, name = "eventB") b3 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20, name = "eventC") f = @formula 0 ~ 1 # 1 m_tul = fit( UnfoldModel, Dict("eventA" => (f, b1), "eventB" => (f, b2)), evts, data, eventcolumn = "type", ) @testset "Time Expansion, two events" begin eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [0]), m_tul) @test unique(eff.eventname) == ["eventA", "eventB"] @test unique(eff.yhat) β‰ˆ [2, 3] @test size(eff, 1) == 2 * 2 * 20 # 2 basisfunctions, 2x conditionA, 1s a 20Hz eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [-1, 0, 1]), m_tul) @test size(eff, 1) == 2 * 6 * 20 end @testset "Time Expansion, three events" begin evts_3 = deepcopy(evts) evts_3.type[1:50] .= "eventC" evts_3.type[50:100] .= "eventD" m_tul_3 = fit( UnfoldModel, Dict("eventA" => (f, b1), "eventB" => (f, b2), "eventC" => (f, b3)), evts_3, data, eventcolumn = "type", ) eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [0]), m_tul_3) @test size(eff, 1) == 3 * 2 * 20 # 2 basisfunctions, 2x conditionA, 1s a 20Hz end @testset "Time Expansion, two events different size + different formulas" begin ## Different sized events + different Formulas data, evts = loadtestdata("test_case_4a") # evts[!, :continuousA] = rand(MersenneTwister(42), nrow(evts)) b1 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20, name = "eventA") b2 = firbasis(Ο„ = (0.0, 0.5), sfreq = 20, name = "eventB") f1 = @formula 0 ~ 1 # 1 f2 = @formula 0 ~ 1 + continuousA # 1 m_tul = fit( UnfoldModel, Dict("eventA" => (f1, b1), "eventB" => (f2, b2)), evts, data, eventcolumn = "type", ) eff = Unfold.effects(Dict(:conditionA => [0, 1], :continuousA => [-1, 0, 1]), m_tul) @test nrow(eff) == (length(Unfold.times(b1)) + length(Unfold.times(b2))) * 6 @test sum(eff.eventname .== "eventA") == 120 @test sum(eff.eventname .== "eventB") == 66 end ## Test two channels data, evts = loadtestdata("test_case_3a") # data_r = repeat(reshape(data, (1, :)), 3, 1) data_r[2, :] = data_r[2, :] .* 2 data_e, times = Unfold.epoch(data = data_r, tbl = evts, Ο„ = (0, 0.05), sfreq = 10) # cut the data into epochs # f = @formula 0 ~ 1 + conditionA + continuousA # 1 m_mul = fit(Unfold.UnfoldModel, Dict(Any => (f, times)), evts, data_e) m_tul = fit(Unfold.UnfoldModel, Dict(Any => (f, firbasis([0, 0.05], 10))), evts, data_r) @testset "Two channels" begin # test simple case eff_m = Unfold.effects(Dict(:conditionA => [0, 1, 0, 1], :continuousA => [0]), m_mul) eff_t = Unfold.effects(Dict(:conditionA => [0, 1, 0, 1], :continuousA => [0]), m_tul) @test eff_m.yhat β‰ˆ eff_t.yhat @test length(unique(eff_m.channel)) == 3 @test eff_m[eff_m.channel.==1, :yhat] β‰ˆ eff_m[eff_m.channel.==2, :yhat] ./ 2 @test eff_m[eff_m.channel.==1, :yhat] β‰ˆ [2, 5, 2, 5.0] # these are the perfect predicted values - note that we requested them twice end @testset "Timeexpansion, two events, typified" begin data, evts = loadtestdata("test_case_4a") # evts[!, :continuousA] = rand(MersenneTwister(42), nrow(evts)) evts[!, :continuousB] = rand(MersenneTwister(43), nrow(evts)) ixA = evts.type .== "eventA" evts.continuousB[ixA] = evts.continuousB[ixA] .- mean(evts.continuousB[ixA]) .- 5 evts.continuousB[.!ixA] = evts.continuousB[.!ixA] .- mean(evts.continuousB[.!ixA]) .+ 0.5 b1 = firbasis(Ο„ = (0.0, 0.02), sfreq = 20, name = "eventA") b2 = firbasis(Ο„ = (1.0, 1.02), sfreq = 20, name = "eventB") f1 = @formula 0 ~ 1 + continuousA # 1 f2 = @formula 0 ~ 1 + continuousB # 1 m_tul = fit( UnfoldModel, Dict("eventA" => (f1, b1), "eventB" => (f2, b2)), evts, data, eventcolumn = "type", ) m_tul.modelfit.estimate .= [0 -1 0 6] eff = Unfold.effects(Dict(:continuousA => [0, 1]), m_tul) eff = Unfold.effects(Dict(:continuousA => [0, 1], :continuousB => [0.5]), m_tul) @test eff.yhat[3] == eff.yhat[4] @test eff.yhat[1] == 0.0 @test eff.yhat[2] == -1.0 @test eff.yhat[3] == 3 end @testset "timeexpansion, Interactions, two events" begin data, evts = loadtestdata("test_case_4a") # evts[!, :continuousA] = rand(MersenneTwister(42), nrow(evts)) evts[!, :continuousB] = ["m", "x"][Int.(1 .+ round.(rand(MersenneTwister(43), nrow(evts))))] b1 = firbasis(Ο„ = (0.0, 0.02), sfreq = 20, name = "eventA") b2 = firbasis(Ο„ = (1.0, 1.02), sfreq = 20, name = "eventB") f1 = @formula 0 ~ 1 + continuousA * continuousB # 1 f2 = @formula 0 ~ 1 + continuousB # 1 m_tul = fit( UnfoldModel, ["eventA" => (f1, b1), "eventB" => (f2, b2)], evts, data, eventcolumn = "type", ) m_tul.modelfit.estimate .= [0, -1, 0, 2.0, 0.0, 0.0]' eff = Unfold.effects(Dict(:continuousA => [0, 1]), m_tul) @test size(eff, 1) == 4 @test all(eff.eventname[1:2] .== "eventA") @test all(eff.eventname[4:end] .== "eventB") @test eff.yhat β‰ˆ [ 0.0, mean(evts.continuousB[evts.type.=="eventA"] .== "x") * coef(m_tul)[4] + 1 * coef(m_tul)[2], 0.0, 0.0, ] eff = Unfold.effects(Dict(:continuousB => ["m", "x"]), m_tul) @test eff.yhat[1] == -eff.yhat[2] @test all(eff.yhat[3:4] .β‰ˆ 0.0) eff = Unfold.effects(Dict(:continuousA => [0, 1], :continuousB => ["m", "x"]), m_tul) @test eff.yhat[3:4] == [-1, 1] @test all(eff.yhat[1:2, 5:end] .== 0) end @testset "splinesMissings" begin @testset "Missings in Events" begin tbl = DataFrame( :a => [1, 2, 3, 4, 5, 6, 7, 8], :b => [1, 1, 1, 2, 2, 2, 3, missing], :c => [1, 2, 3, 4, 5, 6, 7, missing], :d => ["1", "2", "3", "4", "5", "6", "7", "8"], :e => ["1", "2", "3", "4", "5", "6", "7", missing], :event => [1, 1, 1, 1, 2, 2, 2, 2], :latency => [10, 20, 30, 40, 50, 60, 70, 80], ) data = rand(120) tbl.event = string.(tbl.event) # prior to the Missing disallow sanity check, this gave an error design = Dict( "1" => (@formula(0 ~ spl(a, 4) + spl(b, 4) + d + e), firbasis((0, 2), 1)), "2" => (@formula(0 ~ a + d), firbasis((0, 1), 1)), ) m = fit(UnfoldModel, design, tbl, data) effects(Dict(:a => [1, 2, 3], :b => [1, 1.5]), m) end end @testset "MixedModel" begin data, evts = UnfoldSim.predef_eeg(10; return_epoched = true) data = reshape(data, size(data, 1), :) m = fit( UnfoldModel, @formula(0 ~ 1 + condition + (1 + condition | subject)), evts, data, 1:size(data, 1), ) eff = effects(Dict(:condition => ["car", "face"]), m) end @testset "MixedModelContinuousTime" begin data, evts = UnfoldSim.predef_eeg(10; sfreq = 10, return_epoched = false) data = data[:] subj_idx = [parse(Int, split(string(s), 'S')[2]) for s in evts.subject] evts.latency .+= size(data, 1) .* (subj_idx .- 1) m = fit( UnfoldModel, [ Any => ( @formula(0 ~ 1 + condition + zerocorr(1 + condition | subject)), firbasis([0.0, 1], 10; interpolate = false), ), ], evts, data, ) @test_broken eff = effects(Dict(:condition => ["car", "face"]), m) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
10020
data, evts = loadtestdata("test_case_3a") # f = @formula 0 ~ 1 + conditionA + continuousA # 1 # prepare data data_r = reshape(data, (1, :)) data_r = vcat(data_r, data_r)#add second channel #--------------------------# # Mass Univariate Linear ## #--------------------------# data_e, times = Unfold.epoch(data = data_r, tbl = evts, Ο„ = (-1.0, 1.9), sfreq = 20) # cut the data into epochs @testset "Float32" begin evts_nomiss, dat_nomiss = Unfold.drop_missing_epochs(evts, data_e) uf = fit(UnfoldModel, f, evts_nomiss, Float32.((dat_nomiss)), times) @test typeof(uf) == UnfoldLinearModel{Float32} @test eltype(coef(uf)) == Float32 uf = fit(UnfoldModel, f, evts_nomiss, Float16.((dat_nomiss)), times) @test eltype(coef(uf)) == Float16 # continuos case basisfunction = firbasis(Ο„ = (-1, 1), sfreq = 20) uf = fit(UnfoldModel, [Any => (f, basisfunction)], evts_nomiss, Float32.(data_r)) @test typeof(uf) == UnfoldLinearModelContinuousTime{Float32} @test eltype(coef(uf)) == Float32 end #--- @testset "test manual pathway" begin uf = UnfoldLinearModel{Union{Float64,Missing}}([Any => (f, times)]) designmatrix!(uf, evts; eventcolumn = "type") fit!(uf, data_e) @test typeof(uf.modelfit) == Unfold.LinearModelFit{Union{Missing,Float64},3} @test !isempty(coef(uf.modelfit)) end @testset "epoched auto multi-event" begin evts_local = deepcopy(evts) evts_local.type .= repeat(["A", "B"], nrow(evts) Γ· 2) uf = fit(UnfoldModel, ["A" => (f, times)], evts_local, data_e; eventcolumn = "type") @test size(coef(uf)) == (2, 59, 3) uf_2events = fit( UnfoldModel, ["A" => (f, times), "B" => (@formula(0 ~ 1), times)], evts_local, data_e; eventcolumn = "type", ) @test size(coef(uf_2events)) == (2, 59, 4) c = coeftable(uf) c2 = coeftable(uf_2events) @test c2[c2.eventname.=="A", :] == c e_uf = effects(Dict(:condtionA => [0, 1]), uf) e_uf2 = effects(Dict(:condtionA => [0, 1]), uf_2events) end @testset "test Autodetection" begin @test Unfold.design_to_modeltype([Any => (@formula(0 ~ 1), 0:10)]) == UnfoldLinearModel @test Unfold.design_to_modeltype([Any => (@formula(0 ~ 1 + A), 0:10)]) == UnfoldLinearModel @test Unfold.design_to_modeltype([ Any => (@formula(0 ~ 1 + A), firbasis(Ο„ = (-1, 1), sfreq = 20)), ],) == UnfoldLinearModelContinuousTime ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) @test Unfold.design_to_modeltype([Any => (@formula(0 ~ 1 + (1 | test)), 0:10)]) == ext.UnfoldLinearMixedModel @test Unfold.design_to_modeltype([ Any => (@formula(0 ~ 1 + (1 | test)), firbasis(Ο„ = (-1, 1), sfreq = 20)), ],) == ext.UnfoldLinearMixedModelContinuousTime end @testset "Bad Input" begin # check that if UnfoldLinearModel or UnfoldLinearModelContinuousTime is defined, that the design is appropriate basisfunction = firbasis(Ο„ = (-1, 1), sfreq = 20) @test_throws "AssertionError" fit( UnfoldLinearModel, [Any => (@formula(0 ~ 1), basisfunction)], evts, data_r, ) @test_throws "AssertionError" fit( UnfoldLinearModel, [Any => (@formula(0 ~ 1), basisfunction)], evts, data_e, ) @test_throws "AssertionError" fit( UnfoldLinearModelContinuousTime, [Any => (@formula(0 ~ 1), 0:0.1:1)], evts, data_r, ) end @testset "automatic, non-vector call" begin times = -1.0:0.05:1.9 m_mul = coeftable(fit(UnfoldLinearModel, f, evts, data_e, times)) @test m_mul[(m_mul.channel.==1).&(m_mul.time.==0.1), :estimate] β‰ˆ [2, 3, 4] data_e_noreshape, times = Unfold.epoch(data = data, tbl = evts, Ο„ = (-1.0, 1.9), sfreq = 20) # cut the data into epochs m_mul_noreshape = coeftable(fit(UnfoldLinearModel, f, evts, data_e_noreshape, times)) @test m_mul_noreshape[ (m_mul_noreshape.channel.==1).&(m_mul_noreshape.time.==0.1), :estimate, ] β‰ˆ [2, 3, 4] @test size(m_mul_noreshape)[1] == size(m_mul)[1] / 2 # test 2D call for UnfoldLinearModel m_mul_autoreshape = coeftable(fit(UnfoldLinearModel, f, evts, data_e_noreshape[1, :, :], times)) m_mul_autoreshape == m_mul_noreshape # Add Missing in Data data_e_missing = deepcopy(data_e) data_e_missing[1, 25, end-5:end] .= missing m_mul_missing = coeftable(Unfold.fit(UnfoldLinearModel, f, evts, data_e_missing, times)) @test m_mul_missing.estimate β‰ˆ m_mul.estimate # Special solver solver_lsmr_se with Standard Error se_solver = solver = (x, y) -> Unfold.solver_default(x, y, stderror = true) m_mul_se = coeftable(Unfold.fit(UnfoldModel, f, evts, data_e, times; solver = se_solver)) @test all(m_mul_se.estimate .β‰ˆ m_mul.estimate) @test !all(isnothing.(m_mul_se.stderror)) # robust solver #ext = Base.get_extension(Unfold, :UnfoldRobustModelsExt) rob_solver = (x, y) -> Unfold.solver_robust(x, y)#,rlmOptions=(initial_coef=zeros(3 *length(times)),)) data_outlier = copy(data_e) data_outlier[:, 31, 1] .= 1000 m_mul_rob = coeftable( Unfold.fit(UnfoldModel, f, evts, data_outlier, times, solver = rob_solver), ) ix = findall(m_mul_rob.time .β‰ˆ 0.5) @test all(m_mul_rob.estimate[ix] .β‰ˆ m_mul.estimate[ix]) m_mul_outlier = coeftable(Unfold.fit(UnfoldModel, f, evts, data_outlier, times)) end @testset "standard-errors solver" begin data, evts = UnfoldSim.predef_eeg(; noiselevel = 10, return_epoched = true) data = reshape(data, 1, size(data)...) f = @formula 0 ~ 1 + condition + continuous # generate ModelStruct se_solver = (x, y) -> Unfold.solver_default(x, y, stderror = true) fit( UnfoldModel, (Dict(Any => (f, range(0, length = size(data, 2), step = 1 / 100)))), evts, data; solver = se_solver, ) end #---------------------------------# ## Timexpanded Univariate Linear ## #---------------------------------# basisfunction = firbasis(Ο„ = (-1, 1), sfreq = 20) @testset "timeexpanded univariate linear+missings" begin m_tul = coeftable(fit(UnfoldModel, f, evts, data_r, basisfunction)) @test isapprox( m_tul[(m_tul.channel.==1).&(m_tul.time.==0.1), :estimate], [2, 3, 4], atol = 0.01, ) # test without reshape, i.e. 1 channel vector e.g. size(data) = (1200,) m_tul_noreshape = coeftable(fit(UnfoldModel, f, evts, data, basisfunction)) @test size(m_tul_noreshape)[1] == size(m_tul)[1] / 2 # Test under missing data data_missing = Array{Union{Missing,Number}}(undef, size(data_r)) data_missing .= deepcopy(data_r) data_missing[4500:4600] .= missing m_tul_missing = coeftable(fit(UnfoldModel, f, evts, data_missing, basisfunction)) @test isapprox(m_tul_missing.estimate, m_tul.estimate, atol = 1e-4) # higher tol because we remove stuff ## Test multiple basisfunctions b1 = firbasis(Ο„ = (-1, 1), sfreq = 20) b2 = firbasis(Ο„ = (-1, 1), sfreq = 20) f1 = @formula 0 ~ 1 + continuousA # 1 f2 = @formula 0 ~ 1 + continuousA # 1 # Fast-lane new implementation res = coeftable( fit( UnfoldModel, [0 => (f1, b1), 1 => (f2, b2)], evts, data_r, eventcolumn = "conditionA", ), ) # slow manual X1 = designmatrix( UnfoldLinearModelContinuousTime, f1, filter(x -> (x.conditionA == 0), evts), b1, ) X2 = designmatrix( UnfoldLinearModelContinuousTime, f2, filter(x -> (x.conditionA == 1), evts), b2, ) uf = UnfoldLinearModelContinuousTime(Dict(0 => (f1, b1), 1 => (f2, b2)), X1 + X2) @time fit!(uf, data_r) tmp = coeftable(uf) # test fast way & slow way to be identical @test all(tmp.estimate .== res.estimate) end @testset "runtime tests" begin # runntime tests - does something explode? for k = 1:4 local f if k == 1 f = @formula 0 ~ 1 elseif k == 2 f = @formula 0 ~ 1 + conditionA elseif k == 3 f = @formula 0 ~ 0 + conditionA elseif k == 4 f = @formula 0 ~ 1 + continuousA end fit(UnfoldModel, f, evts, data_e, times) fit(UnfoldModel, f, evts, data, basisfunction) end end @testset "automatic, non-dictionary call" begin m_mul = coeftable(fit(UnfoldLinearModel, f, evts, data_e, times)) @test m_mul[(m_mul.channel.==1).&(m_mul.time.==0.1), :estimate] β‰ˆ [2, 3, 4] end @testset "Special solver solver_lsmr_se with Standard Error" begin se_solver = solver = (x, y) -> Unfold.solver_default(x, y, stderror = true) m_tul_se = coeftable(fit(UnfoldModel, f, evts, data_r, basisfunction, solver = se_solver)) #with m_tul = coeftable(fit(UnfoldModel, f, evts, data_r, basisfunction)) #without @test all(m_tul_se.estimate .== m_tul.estimate) @test !all(isnothing.(m_tul_se.stderror)) #m_mul_se,m_mul_se = fit(UnfoldLinearModel,f,evts,data_e.+randn(size(data_e)).*5,times,solver=se_solver) #plot(m_mul_se[m_mul_se.channel.==1,:],se=true) #m_tul_se,m_tul_se = fit(UnfoldLinearModel,f,evts,data_r.+randn(size(data_r)).*5,basisfunction,solver=se_solver) #plot(m_tul_se[m_tul_se.channel.==1,:],se=true) end @testset "non-integer fir no interpolation #200" begin data, evts = UnfoldSim.predef_eeg() evts.latency .= evts.latency + rand(length(evts.latency)) f = @formula 0 ~ 1 + condition + continuous # generate ModelStruct m = fit(UnfoldModel, [Any => (f, firbasis([-0.111, 0.2312], 100))], evts, data;) end @testset "missing data modelfit" begin data, evts = UnfoldSim.predef_eeg() data = allowmissing(data) data[500:600] .= missing f = @formula 0 ~ 1 + condition + continuous # generate ModelStruct m = fit(UnfoldModel, [Any => (f, firbasis([-0.111, 0.2312], 100))], evts, data;) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
7203
@testset "lmm tests" begin ############################### ## Mixed Model tests ############################### data, evts = loadtestdata("testCase3", dataPath = (@__DIR__) * "/data") # append!(data, zeros(1000)) data = reshape(data, 1, :) data = vcat(data, data) data = data .+ 1 * randn(size(data)) # we have to add minimal noise, else mixed models crashes. data_missing = Array{Union{Missing,Number}}(undef, size(data)) data_missing .= deepcopy(data) data_missing[4500:4600] .= missing transform!(evts, :subject => categorical => :subject) f = @formula 0 ~ 1 + condA + condB + (1 + condA + condB | subject) #f = @formula 0~1 + (1|subject) # cut the data into epochs # TODO This ignores subject bounds data_e, times = Unfold.epoch(data = data, tbl = evts, Ο„ = (-1.0, 1.9), sfreq = 10) data_missing_e, times = Unfold.epoch(data = data_missing, tbl = evts, Ο„ = (-1.0, 1.9), sfreq = 10) evts_e, data_e = Unfold.drop_missing_epochs(copy(evts), data_e) evts_missing_e, data_missing_e = Unfold.drop_missing_epochs(copy(evts), data_missing_e) ###################### ## Mass Univariate Mixed @time m_mum = fit( UnfoldModel, f, evts_e, data_e, times, contrasts = Dict(:condA => EffectsCoding(), :condB => EffectsCoding()), show_progress = false, ) df = Unfold.coeftable(m_mum) @test isapprox( df[(df.channel.==1).&(df.coefname.=="condA: 1").&(df.time.==0.0), :estimate], [5.618, 9.175], rtol = 0.1, ) # with missing @time m_mum = fit( UnfoldModel, f, evts_missing_e, data_missing_e, times, contrasts = Dict(:condA => EffectsCoding(), :condB => EffectsCoding()), show_progress = false, ) df = coeftable(m_mum) @test isapprox( df[(df.channel.==1).&(df.coefname.=="condA: 1").&(df.time.==0.0), :estimate], [5.618, 9.175], rtol = 0.1, ) # Timexpanded Univariate Mixed f = @formula 0 ~ 1 + condA + condB + (1 + condA | subject) basisfunction = firbasis(Ο„ = (-0.2, 0.3), sfreq = 10) @time m_tum = fit( UnfoldModel, f, evts, data, basisfunction, contrasts = Dict(:condA => EffectsCoding(), :condB => EffectsCoding()), show_progress = false, ) df = coeftable(m_tum) @test isapprox( df[(df.channel.==1).&(df.coefname.=="condA: 1").&(df.time.==0.0), :estimate], [5.618, 9.175], rtol = 0.1, ) # missing data in LMMs # not yet implemented Test.@test_broken m_tum = fit( UnfoldModel, f, evts, data_missing, basisfunction, contrasts = Dict(:condA => EffectsCoding(), :condB => EffectsCoding()), ) evts.subjectB = evts.subject evts1 = evts[evts.condA.==0, :] evts2 = evts[evts.condA.==1, :] f0_lmm = @formula 0 ~ 1 + condB + (1 | subject) + (1 | subjectB) @time m_tum = coeftable( fit(UnfoldModel, f0_lmm, evts, data, basisfunction; show_progress = false), ) f1_lmm = @formula 0 ~ 1 + condB + (1 | subject) f2_lmm = @formula 0 ~ 1 + condB + (1 | subjectB) b1 = firbasis(Ο„ = (-0.2, 0.3), sfreq = 10, name = 0) b2 = firbasis(Ο„ = (-0.1, 0.3), sfreq = 10, name = 1) ext = Base.get_extension(Unfold, :UnfoldMixedModelsExt) X1_lmm = designmatrix(ext.UnfoldLinearMixedModelContinuousTime, f1_lmm, evts1, b1) X2_lmm = designmatrix(ext.UnfoldLinearMixedModelContinuousTime, f2_lmm, evts2, b2) r = fit( ext.UnfoldLinearMixedModelContinuousTime, X1_lmm + X2_lmm, data; show_progress = false, ) df = coeftable(r) @test isapprox( df[(df.channel.==1).&(df.coefname.=="condB").&(df.time.==0.0), :estimate], [18.21, 17.69], rtol = 0.1, ) # Fast-lane new implementation m = coeftable( fit( UnfoldModel, [0 => (f1_lmm, b1), 1 => (f2_lmm, b2)], evts, data, eventcolumn = "condA", ), ) end ## Condense check for multi channel, multi @testset "LMM multi channel, multi basisfunction" begin data, evts = loadtestdata("testCase3", dataPath = (@__DIR__) * "/data") transform!(evts, :subject => categorical => :subject) data = vcat(data', data') bA0 = firbasis(Ο„ = (-0.0, 0.1), sfreq = 10, name = 0) bA1 = firbasis(Ο„ = (0.1, 0.2), sfreq = 10, name = 1) evts.subject2 = evts.subject fA0 = @formula 0 ~ 1 + condB + zerocorr(1 | subject) fA1 = @formula 0 ~ 1 + condB + zerocorr(1 | subject2) m = fit( UnfoldModel, Dict(0 => (fA0, bA0), 1 => (fA1, bA1)), evts, data; eventcolumn = "condA", show_progress = false, ) res = coeftable(m) @test all(last(.!isnothing.(res.group), 8)) @test all(last(res.coefname, 8) .== "(Intercept)") end @testset "LMM bug reorder #115" begin data, evts = UnfoldSim.predef_2x2(; return_epoched = true, n_subjects = 10, noiselevel = 1, onset = NoOnset(), ) data = reshape(data, size(data, 1), :) designList = [ [ Any => ( @formula( 0 ~ 1 + A + B + zerocorr(1 + B + A | subject) + zerocorr(1 + B | item) ), range(0, 1, length = size(data, 1)), ), ], [ Any => ( @formula( 0 ~ 1 + A + B + zerocorr(1 + A + B | subject) + zerocorr(1 + B | item) ), range(0, 1, length = size(data, 1)), ), ], [ Any => ( @formula(0 ~ 1 + zerocorr(1 + A + B | subject) + zerocorr(1 | item)), range(0, 1, length = size(data, 1)), ), ], ] #des = designList[1] #des = designList[2] for des in designList @test_throws AssertionError fit(UnfoldModel, des, evts, data) # end #counter check des = [ Any => ( @formula(0 ~ 1 + zerocorr(1 | item) + zerocorr(1 + A + B | subject)), range(0, 1, length = size(data, 1)), ), ] #= fails but not in the repl...? uf = fit(UnfoldModel, des, evts, data; show_progress = false) @test 3 == unique( @subset( coeftable(uf), @byrow(:group == Symbol("subject")), @byrow :time == 0.0 ).coefname, ) |> length =# end @testset "LMM bug reshape #110" begin data, evts = UnfoldSim.predef_2x2(; return_epoched = true, n_subjects = 10, noiselevel = 1) data = reshape(data, size(data, 1), :) des = [ Any => ( @formula( 0 ~ 1 + A + B + zerocorr(1 + B + A | item) + zerocorr(1 + B | subject) ), range(0, 1, length = size(data, 1)), ), ] uf = fit(UnfoldModel, des, evts, data; show_progress = false) @test size(coef(uf)) == (1, 100, 3) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4993
using UnfoldSim using DataFrames save_path = mktempdir(; cleanup = false)#tempdir() ## 1. Test data set: # - Generate a P1/N1/P3 complex for one subject (using UnfoldSim) # - Use a Continuous Time Unfold model with two event types # - Use splines to model the continuous predictor variable data1, evts1 = UnfoldSim.predef_eeg(; n_repeats = 100, noiselevel = 0.8); # Assume that the data is from two different events evts1[!, :type] = repeat(["event_A", "event_B"], nrow(evts1) Γ· 2); bf1_A = firbasis(Ο„ = [-0.1, 1], sfreq = 100, name = "event_A"); bf1_B = firbasis(Ο„ = [-0.1, 1], sfreq = 100, name = "event_B"); f1_A = @formula 0 ~ 1; f1_B = @formula 0 ~ 1 + condition + spl(continuous, 4); bfDict1 = ["event_A" => (f1_A, bf1_A), "event_B" => (f1_B, bf1_B)]; data1_e, times = Unfold.epoch(data1, evts1, [-0.1, 1], 100) bfDict1_e = ["event_A" => (f1_A, times), "event_B" => (f1_B, times)]; for deconv in [false, true] if deconv m1 = Unfold.fit(UnfoldModel, bfDict1, evts1, data1, eventcolumn = "type") else m1 = Unfold.fit(UnfoldLinearModel, bfDict1_e, evts1, data1_e; eventcolumn = "type") end @testset "SingleSubjectDesign with two event types and splines" begin # save the model to a compressed .jld2 file and load it again save(joinpath(save_path, "m1_compressed2.jld2"), m1; compress = true) m1_loaded = load( joinpath(save_path, "m1_compressed2.jld2"), UnfoldModel, generate_Xs = true, ) @test isempty(Unfold.modelmatrices(designmatrix(m1_loaded))[1]) == false @test typeof(m1) == typeof(m1_loaded) @test coeftable(m1) == coeftable(m1_loaded) @test m1.modelfit.estimate == m1_loaded.modelfit.estimate @test m1.designmatrix[end].events == m1_loaded.designmatrix[end].events # In the loaded version one gets two matrices instead of one. # The dimensions do also not match. # Probably the designmatrix reconstruction in the load function needs to be changed. @test m1.designmatrix[end].modelmatrix == m1_loaded.designmatrix[end].modelmatrix # Test whether the effects function works with the loaded model # and the results match the ones of the original model eff1 = effects(Dict(:condition => ["car", "face"], :continuous => -5:1), m1) eff1_loaded = effects(Dict(:condition => ["car", "face"], :continuous => -5:1), m1_loaded) @test eff1 == eff1_loaded # load the model without reconstructing the designmatrix m1_loaded_without_dm = load( joinpath(save_path, "m1_compressed2.jld2"), UnfoldModel, generate_Xs = false, ) # ismissing should only be true fr the deconv case @test isempty(modelmatrix(designmatrix(m1_loaded_without_dm)[2])) == (deconv == true) end end #---- ## 2. Test data set: # - Generate a 2x2 design with Hanning window for multiple subjects (using UnfoldSim) # - Use a Mixed-effects Unfold model data2, evts2 = UnfoldSim.predef_2x2(; n_subjects = 5, return_epoched = true); data2 = reshape(data2, size(data2, 1), :) # Define a model formula with interaction term and random effects for subjects f2 = @formula(0 ~ 1 + A * B + (1 | subject)); Ο„2 = [-0.1, 1]; sfreq2 = 100; times2 = range(Ο„2[1], length = size(data2, 1), step = 1 ./ sfreq2); m2 = Unfold.fit( UnfoldModel, Dict(Any => (f2, times2)), evts2, reshape(data2, 1, size(data2)...), ); save(joinpath(save_path, "m2_compressed2.jld2"), m2; compress = true) m2_loaded = load(joinpath(save_path, "m2_compressed2.jld2"), UnfoldModel, generate_Xs = true) @testset "2x2 MultiSubjectDesign Mixed-effects model" begin # save the model to a compressed .jld2 file and load it again save(joinpath(save_path, "m2_compressed2.jld2"), m2; compress = true) m2_loaded = load(joinpath(save_path, "m2_compressed2.jld2"), UnfoldModel, generate_Xs = true) @test isempty(Unfold.modelmatrices(designmatrix(m2_loaded))[1]) == false @test typeof(m2) == typeof(m2_loaded) @test coeftable(m2) == coeftable(m2_loaded) @test modelfit(m2).fits == modelfit(m2_loaded).fits @test Unfold.events(m2) == Unfold.events(m2_loaded) @test modelmatrix(m2) == modelmatrix(m2_loaded) # Test whether the effects function works with the loaded models # and the results match the ones of the original model conditions = Dict(:A => levels(evts2.A), :B => levels(evts2.B)) # The effects function is currently not defined for UnfoldLinearMixedModel #eff2 = effects(conditions, m2) #eff2_loaded = effects(conditions, m2_loaded) @test_broken eff2 == eff2_loaded # load the model without reconstructing the designmatrix m2_loaded_without_dm = load(joinpath(save_path, "m2_compressed2.jld2"), UnfoldModel, generate_Xs = false) @test isempty(modelmatrix(designmatrix(m2_loaded_without_dm))[1]) == true end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
515
# This is not included in the testset because we cant use GPU on github action :( @testset "krylov with missings" begin using Krylov, CUDA data, evts = UnfoldSim.predef_eeg() data = allowmissing(data) data[500:600] .= missing f = @formula 0 ~ 1 + condition + continuous # generate ModelStruct m = fit( UnfoldModel, [Any => (f, firbasis([-0.111, 0.2312], 100))], evts, data; solver = (x, y) -> Unfold.solver_krylov(x, y; GPU = false), ) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
4303
data, evts = loadtestdata("test_case_3a") # data_r = reshape(data, (1, :)) data_e, times = Unfold.epoch(data = data_r, evts = evts, Ο„ = (0.0, 0.95), sfreq = 20) # cut the data into epochs basisfunction = firbasis(Ο„ = (0.0, 0.95), sfreq = 20) f = @formula 0 ~ 1 # 1 m_mul = fit(UnfoldModel, f, evts, data_e, times) m_tul = fit(UnfoldModel, f, evts, data_r, basisfunction) m_mul_results = coeftable(m_mul) m_tul_results = coeftable(m_tul) conditionA = [0, 1.0] continuousA = [-1.0, 0, 1.0] tmp = reshape( [[x, y] for x in conditionA, y in continuousA], length(conditionA) * length(continuousA), ) evts_grid = DataFrame(collect(hcat(tmp...)'), ["conditionA", "continuousA"]) yhat_mul = predict(m_mul, evts_grid) yhat_tul = predict(m_tul, evts_grid) @test yhat_mul β‰ˆ yhat_tul Unfold.result_to_table(m_mul, yhat_mul, [evts_grid]) @test all(yhat_mul[1][:] .β‰ˆ mean(data[data.!=0])) @test all(yhat_tul[1][:] .β‰ˆ mean(data[data.!=0])) ## Case with multiple formulas f = @formula 0 ~ 1 + conditionA + continuousA# 1 m_tul = fit(UnfoldModel, f, evts, data_r, basisfunction) m_mul = fit(UnfoldModel, f, evts, data_e, times) m_mul_results = coeftable(m_mul) m_tul_results = coeftable(m_tul) yhat_tul = predict(m_tul, evts_grid) yhat_mul = predict(m_mul, evts_grid) #@test predict(m_mul,evts).yhat β‰ˆ yhat.yhat @test isapprox(sum(coef(m_tul)[[5, 25, 45]]), yhat_tul[1][end-3], atol = 0.001) @test isapprox(yhat_tul[1], yhat_mul[1], atol = 0.001) @test isapprox(yhat_tul[1][1, 5, :], [-2, 1, 2, 5, 6, 9.0], atol = 0.0001) ## two events data, evts = loadtestdata("test_case_4a") # data_e, times = Unfold.epoch(data = data, evts = evts, Ο„ = (0.0, 0.95), sfreq = 20) # cut the data into epochs b1 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20) b2 = firbasis(Ο„ = (0.0, 0.95), sfreq = 20) f = @formula 0 ~ 1 # 1 m_tul = fit( UnfoldModel, ["eventA" => (f, b1), "eventB" => (f, b2)], evts, data, eventcolumn = "type", ) p = predict(m_tul, DataFrame(:Cond => [1])) @test length(p) == 2 @test size(p[1], 2) == size(p[2], 2) == 20 ## two events mass-univariate m_mul = fit( UnfoldModel, ["eventA" => (f, times), "eventB" => (f, times)], evts, data_e, eventcolumn = "type", ) p = predict(m_mul, DataFrame(:Cond => [1, 2, 3])) @test length(p) == 2 @test size(p[2]) == (1, 20, 3) ## result_to_table data, evts = UnfoldSim.predef_eeg(; n_repeats = 5, noiselevel = 0.8) m = fit( UnfoldModel, [ "car" => (@formula(0 ~ 1 + spl(continuous, 4)), firbasis((-0.1, 1), 100)), "face" => (@formula(0 ~ 1 + continuous^2), firbasis((-0.2, 0.4), 100)), ], evts, repeat(data, 1, 3)'; eventcolumn = "condition", show_progress = false, ) p = predict(m; overlap = false) pt = Unfold.result_to_table(m, p, repeat([evts], 2)) @show pt[[1, 2, 3], :yhat] @test all(isapprox.(pt[[1, 2, 3], :yhat], 0.293292035997; atol = 0.01)) @test all(pt[[1, 2, 3], :channel] .== [1, 2, 3]) @test all(pt[[1, 2, 3], :channel] .== [1, 2, 3]) @test all( pt[[1, 6 * 112 + 1, 3 * 112 + 1], :continuous] .β‰ˆ [5, 1.6666666667, -2.7777777778], ) @testset "residuals" begin data, evts = UnfoldSim.predef_eeg(; n_repeats = 5, noiselevel = 0.8) # time expanded m = fit(UnfoldModel, [Any => (@formula(0 ~ 1), firbasis((-0.1, 1), 100))], evts, data;) @test size(Unfold.residuals(m, data)) == (1, 6170) # time expanded + multichannel m = fit( UnfoldModel, [Any => (@formula(0 ~ 1), firbasis((-0.1, 1), 100))], evts, repeat(data, 1, 3)'; ) @test size(Unfold.residuals(m, data)) == (3, 6170) # time expanded, data longer m = fit( UnfoldModel, [Any => (@formula(0 ~ 1), firbasis((-0.1, 0.1), 100))], evts, repeat(data, 1, 3)'; ) resids = Unfold.residuals(m, repeat(data, 1, 3)') @test size(resids) == (3, 6170) @test all(resids[1, end-2:end] .β‰ˆ data[end-2:end]) # data_e, evts = UnfoldSim.predef_eeg(; n_repeats = 5, noiselevel = 0.8, return_epoched = true) times = 1:size(data_e, 1) m_mul = fit(UnfoldModel, f, evts, data_e, times) resids_e = Unfold.residuals(m_mul, data_e) @test size(resids_e)[2:3] == size(data_e) @test maximum(abs.(data_e .- (resids_e.+predict(m_mul)[1])[1, :, :])) < 0.0000001 end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
767
using Unfold include("setup.jl") # sanity checks, auto-quality control #using Aqua #Aqua.test_all(Unfold) @testset "BasisFunctions" begin include("basisfunctions.jl") end @testset "Fitting" begin include("fit.jl") end @testset "fit LMMs" begin include("fit_LMM.jl") end @testset "Designmatrix" begin include("designmatrix.jl") end @testset "Splines" begin include("splines.jl") end @testset "Predict" begin include("predict.jl") end @testset "Effects" begin include("effects.jl") end @testset "Statistics" begin include("statistics.jl") end @testset "Utilities" begin include("utilities.jl") end @testset "IO" begin include("io.jl") end #@testset "ClusterPermutation" begin #include("clusterpermutation.jl") #end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
283
using Test using StatsModels using DataFrames using DataFramesMeta using Statistics using Random using CategoricalArrays using StatsBase using Missings using MixedModels, RobustModels, BSplineKit # extensionTriggers using SparseArrays using UnfoldSim include("test_utilities.jl")
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3199
using Unfold: predicttable data, evts = loadtestdata("test_case_3a") # ## f_spl = @formula 0 ~ 1 + conditionA + spl(continuousA, 4) # 1 f = @formula 0 ~ 1 + conditionA + continuousA # 1 data_r = reshape(data, (1, :)) data_e, times = Unfold.epoch(data = data_r, tbl = evts, Ο„ = (-1.0, 1.0), sfreq = 10) # cut the data into epochs m_mul = coeftable(fit(UnfoldModel, f, evts, data_e, times)) m_mul_spl = coeftable(fit(UnfoldModel, f_spl, evts, data_e, times)) # asking for 4 splines should generate 4 splines @test length(unique(m_mul_spl.coefname)) == 5 s = Unfold.formulas(fit(UnfoldModel, f_spl, evts, data_e, times))[1].rhs.terms[3] @test Unfold.width(s) == 3 @test length(coefnames(s)) == 3 @test s.df == 4 @testset "outside bounds" begin # test safe prediction m = fit(UnfoldModel, f_spl, evts, data_e, times) r = Unfold.predicttable(m, DataFrame(conditionA = [0, 0], continuousA = [0.9, 1.9])) @test all(ismissing.(r.yhat[r.continuousA.==1.9])) @test !any(ismissing.(r.yhat[r.continuousA.==0.9])) end basisfunction = firbasis(Ο„ = (-1, 1), sfreq = 10, name = "A") @testset "timeexpanded" begin # test time expanded m_tul = coeftable(fit(UnfoldModel, f, evts, data_r, basisfunction)) m_tul_spl = coeftable(fit(UnfoldModel, f_spl, evts, data_r, basisfunction)) end @testset "safe prediction outside bounds" begin # test safe predict m = fit(UnfoldModel, f_spl, evts, data_r, basisfunction) p = predicttable(m, DataFrame(conditionA = [0, 0, 0], continuousA = [0.9, 0.9, 1.9])) @test all(ismissing.(p[p.continuousA.==1.9, :yhat])) end #@test_broken all(ismissing.) #evts_grid = gridexpand() # results from timeexpanded and non should be equal #yhat_tul = predict(m_tul_spl,evts_grid) #yhat_mul = predict(m_mul_spl,evts_grid) if 1 == 0 using AlgebraOfGraphics yhat_mul.conditionA = categorical(yhat_mul.conditionA) yhat_mul.continuousA = categorical(yhat_mul.continuousA) m = mapping(:times, :yhat, color = :continuousA, linestyle = :conditionA) df = yhat_mul AlgebraOfGraphics.data(df) * visual(Lines) * m |> draw end @testset "many splines" begin # test much higher number of splines f_spl_many = @formula 0 ~ 1 + spl(continuousA, 131) # 1 m_mul_spl_many = coeftable(fit(UnfoldModel, f_spl_many, evts, data_e, times)) @test length(unique(m_mul_spl_many.coefname)) == 131 end @testset "PeriodicSplines" begin f_circspl = @formula 0 ~ 1 + circspl(continuousA, 10, -1, 1) # 1 m = fit(UnfoldModel, f_circspl, evts, data_e, times) f_evaluated = Unfold.formulas(m) effValues = [-1, -0.99, 0, 0.99, 1] effValues = range(-1.1, 1.1, step = 0.1) effSingle = effects(Dict(:continuousA => effValues), m) tmp = subset(effSingle, :time => x -> x .== -1.0) @test tmp.yhat[tmp.continuousA.==-1.1] β‰ˆ tmp.yhat[tmp.continuousA.==0.9] @test tmp.yhat[tmp.continuousA.==-1.0] β‰ˆ tmp.yhat[tmp.continuousA.==1] @test tmp.yhat[tmp.continuousA.==-0.9] β‰ˆ tmp.yhat[tmp.continuousA.==1.1] end @testset "minimal number of splines" begin f_spl = @formula 0 ~ 1 + conditionA + spl(continuousA, 3) # 1 @test_throws AssertionError fit(UnfoldModel, f_spl, evts, data_e, times) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
921
@testset "LMM LRT" begin data, evts = UnfoldSim.predef_eeg(10; n_items = 20, sfreq = 10, return_epoched = true) data = reshape(data, 1, size(data, 1), size(data, 2) * size(data, 3)) # add second channel data = vcat(data, data) times = range(0, 1, size(data, 2)) f0 = @formula 0 ~ 1 + condition + (1 | subject) f1 = @formula 0 ~ 1 + condition + continuous + (1 | subject) m0 = fit(UnfoldModel, Dict(Any => (f0, times)), evts, data) m1 = fit(UnfoldModel, Dict(Any => (f1, times)), evts, data) tix = 4 evts[!, :y] = data[1, tix, :] f0 = @formula y ~ 1 + condition + (1 | subject) f1 = @formula y ~ 1 + condition + continuous + (1 | subject) lmm0 = fit(MixedModel, f0, evts) lmm1 = fit(MixedModel, f1, evts) uf_lrt = likelihoodratiotest(m0, m1) mm_lrt = MixedModels.likelihoodratiotest(lmm0, lmm1) @test mm_lrt.pvalues β‰ˆ uf_lrt[tix].pvalues end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
3839
using CSV using DelimitedFiles using DSP using Random using LinearAlgebra using DataFrames function loadtestdata( testCase::String; dataPath::String = (@__DIR__) * "/data_new_testcases", ) #println(pwd()) # to debug github action data = readdlm(joinpath(dataPath, "$(testCase)_data.csv"), ',', Float64, '\n') data = dropdims(data, dims = 1) # convert to vector evts = CSV.read(joinpath(dataPath, "$(testCase)_events.csv"), DataFrame) return data, evts end function gridexpand(conditionA = [0, 1.0], continuousA = [-1.0, 0, 1.0]) tmp = reshape( [[x, y] for x in conditionA, y in continuousA], length(conditionA) * length(continuousA), ) evts_grid = DataFrame(hcat(tmp...)') rename!(evts_grid, ["conditionA", "continuousA"]) return evts_grid end simulate_lmm(args...; kwargs...) = simulate_lmm(Random.GLOBAL_RNG, args...; kwargs...) function simulate_lmm( rng::AbstractRNG, Ο„ = 1.5, fs = 12; Ξ² = [0.0, -1.0], Οƒs = [1, 1, 1], Οƒ = 1, n_sub = 20, n_item = 30, noise_type = "AR-exponential", ) rng_copy = deepcopy(rng) subj_btwn = item_btwn = both_win = nothing #subj_btwn = Dict("age" => ["O", "Y"]) # there are no between-item factors in this design so you can omit it or set it to nothing item_btwn = Dict("stimType" => ["I", "II"]) # put within-subject/item factors in a Dict #both_win = Dict("condition" => ["A", "B"]) # simulate data evt = DataFrame( simdat_crossed( n_sub, n_item, subj_btwn = subj_btwn, item_btwn = item_btwn, both_win = both_win, ), ) # f1 = @formula dv ~ 1 + age * condition + (1+condition|item) + (1+condition|subj); f1 = @formula dv ~ 1 + stimType + (1 + stimType | subj) + (1 | item) m = MixedModels.fit(MixedModel, f1, evt) # set the random effects #gen_han(Ο„,fs,1) basis = gen_han(Ο„, fs, 2) epoch_dat = zeros(Int(Ο„ * fs), size(evt, 1)) #MixedModels doesnt really support Οƒ==0 because all Ranef are scaled residual variance Οƒ_lmm = 0.0001 Οƒs = Οƒs ./ Οƒ_lmm for t = 1:size(epoch_dat, 1) b = basis[t] MixedModelsSim.update!(m, create_re(b .* Οƒs[1], b .* Οƒs[2]), create_re(b .* Οƒs[3])) simulate!(deepcopy(rng_copy), m, Ξ² = [b .* Ξ²[1], b .* Ξ²[2]], Οƒ = Οƒ_lmm) epoch_dat[t, :] = m.y end epoch_dat = reshape(epoch_dat, (1, size(epoch_dat)...)) # add some noise if noise_type == "normal" epoch_dat = epoch_dat .+ randn(rng, size(epoch_dat)) .* Οƒ elseif noise_type == "AR-exponential" epoch_dat = epoch_dat .+ gen_noise_exp(rng, size(epoch_dat)) .* Οƒ end return evt, epoch_dat end function gen_han(Ο„, fs, peak) hanLen = Int(Ο„ * fs / 3) han = hanning(hanLen, zerophase = false) sig = zeros(Int(Ο„ * fs)) sig[1+hanLen*(peak-1):hanLen*peak] .= han return sig end function circulant(x) # Author: Jaromil Frossard # returns a symmetric matrix where X was circ-shifted. lx = length(x) ids = [1:1:(lx-1);] a = Array{Float64,2}(undef, lx, lx) for i = 1:length(x) if i == 1 a[i, :] = x else a[i, :] = vcat(x[i], a[i-1, ids]) end end return Symmetric(a) end function exponentialCorrelation(x; nu = 1, length_ratio = 1) # Author: Jaromil Frossard # generate exponential function R = length(x) * length_ratio return exp.(-3 * (x / R) .^ nu) end function noise_exp(rng, n_t) Ξ£ = circulant(exponentialCorrelation([0:1:(n_t-1);], nu = 1.5)) Ut = LinearAlgebra.cholesky(Ξ£).U' return (randn(rng, n_t)'*Ut')[1, :] end function gen_noise_exp(rng, si) n = hcat(map(x -> noise_exp(rng, si[2]), 1:si[3])...) return reshape(n, si) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
1054
tbl = DataFrame([collect(1:4:1000)], [:latency]) X = ones(size(tbl)) basisfunction = firbasis(Ο„ = (-3, 0), sfreq = 1, name = "testing") term = Unfold.TimeExpandedTerm(FormulaTerm(Term, Term), basisfunction, :latency); Xdc = Unfold.time_expand(X, term, tbl) kernel = Unfold.kernel ncolsBasis = size(kernel(term.basisfunction)(0.0), 2) X = reshape(X, size(X, 1), :) ncolsX = size(X)[2] nrowsX = size(X)[1] ncolsXdc = ncolsBasis * ncolsX onsets = tbl[!, term.eventfields[1]] if typeof(term.eventfields) <: Array && length(term.eventfields) == 1 bases = kernel(term.basisfunction).(tbl[!, term.eventfields[1]]) else bases = kernel(term.basisfunction).(eachrow(tbl[!, term.eventfields])) end rows = Unfold.timeexpand_rows(onsets, bases, Unfold.shift_onset(term.basisfunction), ncolsX) cols = Unfold.timeexpand_cols(term, bases, ncolsBasis, ncolsX) vals = Unfold.timeexpand_vals(bases, X, size(cols), ncolsX) @test Unfold.timeexpand_cols_allsamecols(bases, ncolsBasis, ncolsX) == Unfold.timeexpand_cols_generic(bases, ncolsBasis, ncolsX)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
code
959
@testset "epoch" begin d = collect(1:100) evt = DataFrame(:latency => (50)) ep = Ο„ -> Unfold.epoch(d, evt, Ο„, 1)[1][1, :, 1] # check time delays @test ep((0, 10.0)) β‰ˆ collect(50:60.0) @test ep((-10, 10.0)) β‰ˆ collect(40:60.0) @test ep((-10, 0.0)) β‰ˆ collect(40:50.0) @test ep((5, 15)) β‰ˆ collect(55:65.0) @test ep((-15, -5)) β‰ˆ collect(35:45.0) # check corner cases (sample doesnt end on sampling rate) @test ep((0.6, 2)) β‰ˆ collect(51:52.0) @test ep((0.2, 2)) β‰ˆ collect(50:52.0) # test sampling frequencies ep = Ο„ -> Unfold.epoch(d, evt, Ο„, 2)[1][1, :, 1] @test ep((-1.0, 2)) β‰ˆ collect(48:54.0) ep = Ο„ -> Unfold.epoch(d, evt, Ο„, 0.5)[1][1, :, 1] @test ep((-4.0, 8)) β‰ˆ collect(48:54.0) # rounding bug when latency was .5 -> bug #78 d = zeros((1, 1270528)) evt = DataFrame(:latency => (181603.5)) ep = Ο„ -> Unfold.epoch(d, evt, Ο„, 256.0)[1][1, :, 1] ep((-0.1, 0.8)) end
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
11968
# [![Unfold.jl EEG toolbox](https://github.com/unfoldtoolbox/Unfold.jl/assets/10183650/3cbe57c1-e1a7-4150-817a-ce3dcc844485)](https://github.com/unfoldtoolbox/Unfold.jl) [![Docs][Doc-img]][Doc-url] ![semver][semver-img] [![Build Status][build-img]][build-url] [Doc-img]: https://img.shields.io/badge/docs-main-blue.svg [Doc-url]: https://unfoldtoolbox.github.io/Unfold.jl/dev [semver-img]: https://img.shields.io/badge/semantic-versioning-green [build-img]: https://github.com/unfoldtoolbox/UnfoldSim.jl/workflows/CI/badge.svg [build-url]: https://github.com/unfoldtoolbox/UnfoldSim.jl/workflows/CI.yml |Estimation|Visualisation|Simulation|BIDS pipeline|Decoding|Statistics| |---|---|---|---|---|---| | <a href="https://github.com/unfoldtoolbox/Unfold.jl/tree/main"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277623787-757575d0-aeb9-4d94-a5f8-832f13dcd2dd.png"></a> | <a href="https://github.com/unfoldtoolbox/UnfoldMakie.jl"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277623793-37af35a0-c99c-4374-827b-40fc37de7c2b.png"></a>|<a href="https://github.com/unfoldtoolbox/UnfoldSim.jl"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277623795-328a4ccd-8860-4b13-9fb6-64d3df9e2091.png"></a>|<a href="https://github.com/unfoldtoolbox/UnfoldBIDS.jl"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277622460-2956ca20-9c48-4066-9e50-c5d25c50f0d1.png"></a>|<a href="https://github.com/unfoldtoolbox/UnfoldDecode.jl"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277622487-802002c0-a1f2-4236-9123-562684d39dcf.png"></a>|<a href="https://github.com/unfoldtoolbox/UnfoldStats.jl"><img src="https://github-production-user-asset-6210df.s3.amazonaws.com/10183650/277623799-4c8f2b5a-ea84-4ee3-82f9-01ef05b4f4c6.png"></a>| Toolbox to perform linear / GAM / hierarchical / deconvolution regression on biological signals. This kind of modelling is also known as encoding modeling, linear deconvolution, Temporal Response Functions (TRFs), linear system identification, and probably under other names. fMRI models with HRF-basis functions and pupil-dilation bases are also supported. ## Getting started ### 🐍Python User? We clearly recommend Julia πŸ˜‰ - but [Python users can use juliacall/Unfold directly from python!](https://unfoldtoolbox.github.io/Unfold.jl/dev/generated/HowTo/juliacall_unfold/) ### Julia installation <details> <summary>Click to expand</summary> The recommended way to install julia is [juliaup](https://github.com/JuliaLang/juliaup). It allows you to, e.g., easily update Julia at a later point, but also test out alpha/beta versions etc. TL:DR; If you dont want to read the explicit instructions, just copy the following command #### Windows AppStore -> JuliaUp, or `winget install julia -s msstore` in CMD #### Mac & Linux `curl -fsSL https://install.julialang.org | sh` in any shell </details> ### Unfold.jl installation ```julia using Pkg Pkg.add("Unfold") ``` ## Usage Please check out [the documentation](https://unfoldtoolbox.github.io/Unfold.jl/dev) for extensive tutorials, explanations and more! Here is a quick overview on what to expect. ### What you need ```julia using Unfold events::DataFrame # formula with or without random effects f = @formula 0~1+condA fLMM = @formula 0~1+condA+(1|subject) + (1|item) # in case of [overlap-correction] we need continuous data plus per-eventtype one basisfunction (typically firbasis) data::Array{Float64,2} basis = firbasis(Ο„=(-0.3,0.5),srate=250) # for "timeexpansion" / deconvolution # in case of [mass univariate] we need to epoch the data into trials, and a accompanying time vector epochs::Array{Float64,3} # channel x time x epochs (n-epochs == nrows(events)) times = range(0,length=size(epochs,3),step=1/sampling_rate) ``` To fit any of the models, Unfold.jl offers a unified syntax: | Overlap-Correction | Mixed Modelling | julia syntax | |:---:|:---:|---| | | | `fit(UnfoldModel,[Any=>(f,times)),evts,data_epoch]` | | x | | `fit(UnfoldModel,[Any=>(f,basis)),evts,data]` | | | x | `fit(UnfoldModel,[Any=>(fLMM,times)),evts,data_epoch]` | | x | x | `fit(UnfoldModel,[Any=>(fLMM,basis)),evts,data]` | ## Comparison to Unfold (matlab) <details> <summary>Click to expand</summary> The matlab version is still maintained, but active development happens in Julia. | Feature | Unfold | unmixed (defunct) | Unfold.jl | |-------------------------|--------|---------|-----------| | overlap correction | x | x | x | | non-linear splines | x | x | x | | speed | | 🐌 | ⚑ 2-100x | | GPU support | | | πŸš€| | plotting tools | x | | [UnfoldMakie.jl](https://unfoldtoolbox.github.io/UnfoldMakie.jl/dev/) | | Interactive plotting | | | stay tuned - coming soon! | | simulation tools | x | | [UnfoldSim.jl](https://unfoldtoolbox.github.io/UnfoldSim.jl) | | BIDS support | x | | alpha: [UnfoldBIDS.jl](https://github.com/ReneSkukies/UnfoldBIDS.jl/)) | | sanity checks | x | | x | | tutorials | x | | x | | unittests | x | | x | | Alternative bases e.g. HRF (fMRI) | | | x | | mix different basisfunctions | | | x | | different timewindows per event | | | x | | mixed models | | x | x | | item & subject effects | | (x) | x | | decoding | | | UnfoldDecode.jl | | outlier-robust fits | | | [many options (but slower)](https://unfoldtoolbox.github.io/Unfold.jl/dev/HowTo/custom_solvers/#Robust-Solvers) | | 🐍Python support | | | [via juliacall](https://unfoldtoolbox.github.io/Unfold.jl/dev/generated/HowTo/pyjulia_unfold/)| </details> ## Contributions Contributions are very welcome. These could be typos, bugreports, feature-requests, speed-optimization, new solvers, better code, better documentation. ### How-to Contribute You are very welcome to raise issues and start pull requests! ### Adding Documentation 1. We recommend to write a Literate.jl document and place it in `docs/literate/FOLDER/FILENAME.jl` with `FOLDER` being `HowTo`, `Explanation`, `Tutorial` or `Reference` ([recommended reading on the 4 categories](https://documentation.divio.com/)). 2. Literate.jl converts the `.jl` file to a `.md` automatically and places it in `docs/src/generated/FOLDER/FILENAME.md`. 3. Edit [make.jl](https://github.com/unfoldtoolbox/Unfold.jl/blob/main/docs/make.jl) with a reference to `docs/src/generated/FOLDER/FILENAME.md`. ## Contributors <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> <table> <tbody> <tr> <td align="center" valign="top" width="14.28%"><a href="https://github.com/jschepers"><img src="https://avatars.githubusercontent.com/u/22366977?v=4?s=100" width="100px;" alt="Judith Schepers"/><br /><sub><b>Judith Schepers</b></sub></a><br /><a href="#bug-jschepers" title="Bug reports">πŸ›</a> <a href="#code-jschepers" title="Code">πŸ’»</a> <a href="#doc-jschepers" title="Documentation">πŸ“–</a> <a href="#tutorial-jschepers" title="Tutorials">βœ…</a> <a href="#ideas-jschepers" title="Ideas, Planning, & Feedback">πŸ€”</a> <a href="#test-jschepers" title="Tests">⚠️</a></td> <td align="center" valign="top" width="14.28%"><a href="http://www.benediktehinger.de"><img src="https://avatars.githubusercontent.com/u/10183650?v=4?s=100" width="100px;" alt="Benedikt Ehinger"/><br /><sub><b>Benedikt Ehinger</b></sub></a><br /><a href="#bug-behinger" title="Bug reports">πŸ›</a> <a href="#code-behinger" title="Code">πŸ’»</a> <a href="#doc-behinger" title="Documentation">πŸ“–</a> <a href="#tutorial-behinger" title="Tutorials">βœ…</a> <a href="#ideas-behinger" title="Ideas, Planning, & Feedback">πŸ€”</a> <a href="#test-behinger" title="Tests">⚠️</a> <a href="#infra-behinger" title="Infrastructure (Hosting, Build-Tools, etc)">πŸš‡</a> <a href="#test-behinger" title="Tests">⚠️</a> <a href="#maintenance-behinger" title="Maintenance">🚧</a> <a href="#review-behinger" title="Reviewed Pull Requests">πŸ‘€</a> <a href="#question-behinger" title="Answering Questions">πŸ’¬</a></td> <td align="center" valign="top" width="14.28%"><a href="https://reneskukies.de/"><img src="https://avatars.githubusercontent.com/u/57703446?v=4?s=100" width="100px;" alt="RenΓ© Skukies"/><br /><sub><b>RenΓ© Skukies</b></sub></a><br /><a href="#bug-ReneSkukies" title="Bug reports">πŸ›</a> <a href="#doc-ReneSkukies" title="Documentation">πŸ“–</a> <a href="#tutorial-ReneSkukies" title="Tutorials">βœ…</a></td> <td align="center" valign="top" width="14.28%"><a href="https://reboreexplore.github.io/"><img src="https://avatars.githubusercontent.com/u/43548330?v=4?s=100" width="100px;" alt="Manpa Barman"/><br /><sub><b>Manpa Barman</b></sub></a><br /><a href="#infra-ReboreExplore" title="Infrastructure (Hosting, Build-Tools, etc)">πŸš‡</a></td> <td align="center" valign="top" width="14.28%"><a href="https://www.phillipalday.com"><img src="https://avatars.githubusercontent.com/u/1677783?v=4?s=100" width="100px;" alt="Phillip Alday"/><br /><sub><b>Phillip Alday</b></sub></a><br /><a href="#code-palday" title="Code">πŸ’»</a> <a href="#infra-palday" title="Infrastructure (Hosting, Build-Tools, etc)">πŸš‡</a></td> <td align="center" valign="top" width="14.28%"><a href="http://davekleinschmidt.com"><img src="https://avatars.githubusercontent.com/u/135920?v=4?s=100" width="100px;" alt="Dave Kleinschmidt"/><br /><sub><b>Dave Kleinschmidt</b></sub></a><br /><a href="#doc-kleinschmidt" title="Documentation">πŸ“–</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/ssaket"><img src="https://avatars.githubusercontent.com/u/27828189?v=4?s=100" width="100px;" alt="Saket Saurabh"/><br /><sub><b>Saket Saurabh</b></sub></a><br /><a href="#bug-ssaket" title="Bug reports">πŸ›</a></td> </tr> <tr> <td align="center" valign="top" width="14.28%"><a href="https://github.com/suddha-bpn"><img src="https://avatars.githubusercontent.com/u/7974144?v=4?s=100" width="100px;" alt="suddha-bpn"/><br /><sub><b>suddha-bpn</b></sub></a><br /><a href="#bug-suddha-bpn" title="Bug reports">πŸ›</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/vladdez"><img src="https://avatars.githubusercontent.com/u/33777074?v=4?s=100" width="100px;" alt="Vladimir Mikheev"/><br /><sub><b>Vladimir Mikheev</b></sub></a><br /><a href="#bug-vladdez" title="Bug reports">πŸ›</a> <a href="#doc-vladdez" title="Documentation">πŸ“–</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/carmenamme"><img src="https://avatars.githubusercontent.com/u/100191854?v=4?s=100" width="100px;" alt="carmenamme"/><br /><sub><b>carmenamme</b></sub></a><br /><a href="#doc-carmenamme" title="Documentation">πŸ“–</a></td> </tr> </tbody> </table> <!-- markdownlint-restore --> <!-- prettier-ignore-end --> <!-- ALL-CONTRIBUTORS-LIST:END --> This project follows the [all-contributors](https://allcontributors.org/docs/en/specification) specification. Contributions of any kind welcome! ## Citation For now, please cite [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.6423476.svg)](https://doi.org/10.5281/zenodo.6423476) or [Ehinger & Dimigen](https://peerj.com/articles/7838/) ## Acknowledgements This work was initially supported by the Center for Interdisciplinary Research, Bielefeld (ZiF) Cooperation Group "Statistical models for psychological and linguistic data". Funded by Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) under GermanyΒ΄s Excellence Strategy – EXC 2075 – 390740016
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1003
# Emoji Key and Contribution Types for Unfold.jl toolbox πŸ” Emoji/Type | Represents | Comments :---: | :---: | :---: πŸ› <br /> `bug` | Bug reports | Links to issues reported by the user on this project πŸ’» <br /> `code` | Code | Links to commits by the user on this project πŸ“– <br /> `doc` | Documentation | Links to commits by the user on this project, Wiki, or other source of documentation πŸ€” <br /> `ideas` | Ideas & Planning | New ideas to make the toolbox better πŸš‡ <br /> `infra` | Infrastructure | Hosting, Build-Tools, etc. Links to source file (like `travis.yml`) in repo, if applicable 🚧 <br /> `maintenance` | Maintenance | People who help in maintaining the repo, links to commits by the user on this project πŸ’¬ <br /> `question` | Answering Questions | Answering Questions in Issues, Stack Overflow, Gitter, Slack, etc. πŸ‘€ <br /> `review` | Reviewed Pull Requests | | ⚠️ <br /> `test` | Tests | Links to commits by the user on this project βœ… <br /> `tutorial` | Tutorials | Links to the tutorial
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1445
# Unfold Documentation If you want to follow the **tutorials**, best to start with the [mass-univariate approach](@ref lm_massunivariate), which should be familiar to you if you did ERPs before. Then the [overlap-correction tutorial](@ref lm_overlap), [mixed mass univariate](@ref lmm_massunivariate), [mixed overlap (tricky!)](@ref lmm_overlap). If you are then not satisfied, check out more advanced topics: [effects-interface (aka what to do after fitting)](@ref effects), or non-linear effects. In case you want to understand the tools better, check out our **explanations**. Once you are familiar with the tools, check out further **how-to guides** for specific applications. In case you want to understand the toolbox better, we plan to offer **technical references**. This includes Benchmarks & Explorations. ## Quick start There are four main model types 1. Timeexpansion **No**, Mixed **No** : `fit(UnfoldModel, [Any=>(f, -0.1:0.01:0.5)], evts, data_epoch)` 1. Timeexpansion **Yes**, Mixed **No** : `fit(UnfoldModel, [Any=>(f, basisfunction)], evts, data)` 1. Timeexpansion **No**, Mixed **Yes** : `fit(UnfoldModel, [Any=>(fLMM, -0.1:0.01:0.5)], evts, data_epoch)` 1. Timeexpansion **Yes**, Mixed **Yes**: `fit(UnfoldModel, [Any=>(fLMM, basisfunction)], evts, data)` ```julia f = @formula 0 ~ 1 + condition fLMM = @formula 0 ~ 1 + condition + (1|subject) + (1|item) basisfunction = firbasis(Ο„ = (-0.1,0.5), sfreq = 100)) ```
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1056
# [Installation](@id install_instruct) ## Installing Julia The easiest way to install julia is using [`juliaup`](https://github.com/JuliaLang/juliaup) TLDR; - Windows: `winget install julia -s msstore` - Mac/Linux: `curl -fsSL https://install.julialang.org | sh` We further recommend to use VSCode. Make sure to install the Julia-Plugin, and install Revise.jl - [a tutorial with screenshots can be found here](http://www.simtech-summerschool.de/installation/julia.html) ## Installing Unfold.jl You can enter the package manager (similar to conda) using `]` in the REPL ("julia-commandline"). This should result in `(currentFolder) pkg>` (with `currentFolder` being the project you currently work in) !!! hint if you see `(@v1.9) pkg>` instead, you still have to activate your environment. This can be done using: `cd("/path/to/your/project")` and `]activate .` or alternatively `]activate /path/to/your/project/` Now you can do `pkg> add Unfold` and after some installation: `julia> using Unfold` in the REPL
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1970
# [Alternative Solvers](@id custom_solvers) A solver takes an Unfold-specified DesignMatrix and the data, and typically solves the equation system `y = Xb` (in the case of Linear Models). There are many different ways how one can approach this problem, depending if the matrix is sparse, if it is 2D or 3D, if one wants to use GPU etc. ### Setup some data ```@Example main using Unfold using UnfoldMakie, CairoMakie using UnfoldSim dat, evts = UnfoldSim.predef_eeg(; noiselevel = 10, return_epoched = true) f = @formula 0 ~ 1 + condition + continuous designDict = Dict(Any => (f, range(0, 1, length = size(dat, 1)))) ``` ### GPU Solvers GPU solvers can significantly speed up your model fitting, with observed improvements of up to a factor of 30! ```julia using Krylov, CUDA # necessary to load the right package extension gpu_solver =(x, y) -> Unfold.solver_krylov(x, y; GPU = true) m = Unfold.fit(UnfoldModel, designDict, evts, dat, solver = gpu_solver) ``` To test it, you will need to run it yourself as we cannot run it on the docs. If you require a different graphicscard vendor than NVIDA/CUDA, please create an issue. Currently, we are unable to test it due to lack of hardware. ### Robust Solvers Robust solvers automatically adjust for outlier trials, but they come at a significant computational cost. ```@Example main using RobustModels # necessary to load the Unfold package extension se_solver = (x, y) -> Unfold.solver_robust(x, y) m = Unfold.fit(UnfoldModel, designDict, evts, dat, solver = se_solver) results = coeftable(m) plot_erp(results; stderror = true) ``` ### Back2Back regression ```@Example main b2b_solver = (x, y) -> Unfold.solver_b2b(x, y; ross_val_reps = 5) dat_3d = permutedims(repeat(dat, 1, 1, 20), [3 1 2]) m = Unfold.fit(UnfoldModel, designDict, evts, dat_3d; solver = b2b_solver) results = coeftable(m) plot_erp(results) ``` These are the decoding results for `conditionA` while considering `conditionB`, and vice versa.
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
3486
## [How To get P-Values for Mass-Univariate LMM](@id lmm_pvalues) There are currently two ways to obtain p-values for LMMs: Wald's t-test and likelihood ratio tests (mass univariate only). #### Setup ```@example Main using MixedModels, Unfold # we require to load MixedModels to load the PackageExtension using DataFrames using UnfoldSim using CairoMakie using DisplayAs # hide data_epoch, evts = UnfoldSim.predef_2x2(; n_items = 52, n_subjects = 40, return_epoched = true) data_epoch = reshape(data_epoch, size(data_epoch, 1), :) # times = range(0, 1, length = size(data_epoch, 1)) ``` #### Define f0 & f1 and fit! ```@example Main f0 = @formula 0 ~ 1 + A + (1 + A | subject); f1 = @formula 0 ~ 1 + A + B + (1 + A | subject); # could also differ in random effects m0 = fit(UnfoldModel,[Any=>(f0,times)],evts,data_epoch); m1 = fit(UnfoldModel,[Any=>(f1,times)],evts,data_epoch); m1|> DisplayAs.withcontext(:is_pluto=>true) # hide ``` ## Likelihood ratio ```@example Main uf_lrt = likelihoodratiotest(m0, m1) uf_lrt[1] ``` As you can see, we have some likelihood ratio outcomes, exciting! #### Extract p-values ```@example Main pvalues(uf_lrt) ``` We have extracted the p-values and now need to make them usable. The solution can be found in the documentation under `?pvalues`. ```@example Main pvals_lrt = vcat(pvalues(uf_lrt)...) nchan = 1 ntime = length(times) reshape(pvals_lrt, ntime, nchan)' # note the last transpose via ' ! ``` Perfecto, these are the LRT p-values of a model `condA` vs. `condA+condB` with same random effect structure. ## Walds T-Test This method is easier to calculate but has limitations in accuracy and scope. It may also be less accurate due to the liberal estimation of degrees of freedom. Testing is limited in this case, as random effects cannot be tested and only single predictors can be used, which may not be appropriate for spline effects. It is important to note that this discussion is beyond the scope of this LMM package. ```@example Main res = coeftable(m1) # only fixed effects: what is not in a ranef group is a fixef. res = res[isnothing.(res.group), :] # calculate t-value res[:, :tvalue] = res.estimate ./ res.stderror ``` We obtained Walds t, but how to translate them to a p-value? Determining the necessary degrees of freedom for the t-distribution is a complex issue with much debate surrounding it. One approach is to use the number of subjects as an upper bound for the p-value (your df will be between $n_{subject}$ and $\sum{n_{trials}}$). ```@example Main df = length(unique(evts.subject)) ``` Plug it into the t-distribution. ```@example Main using Distributions res.pvalue = pdf.(TDist(df),res.tvalue) ``` ## Comparison of methods Cool! Let's compare both methods of p-value calculation! ```@example Main df = DataFrame(:walds => res[res.coefname.=="B: b_tiny", :pvalue], :lrt => pvals_lrt) f = Figure() scatter(f[1,1],times,res[res.coefname .== "B: b_tiny",:estimate],axis=(;xlabel="time",title="coef: B:b_tiny")) scatter(f[1,2],df.walds,df.lrt,axis=(;title="walds-t pvalue",ylabel="LRT pvalue")) scatter(f[2,1],times,df.walds,axis=(;title="walds-t pvalue",xlabel="time")) scatter(f[2,2],times,df.lrt,axis=(;title="lrt pvalue",xlabel="time")) f ``` Look pretty similar! Note that the Walds-T is typically too liberal (LRT also, but to a lesser exted). Best is to use the forthcoming MixedModelsPermutations.jl or go the route via R and use KenwardRoger (data not yet published)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1589
# How to model multiple events When dealing with overlapping data, it is often necessary to model multiple eventtypes (e.g. fixations, stimuli, responses). ### Load Example Data ```@example main using Unfold using UnfoldMakie, CairoMakie using DataFrames using StatsModels using MixedModels using DisplayAs # hide include(joinpath(dirname(pathof(Unfold)), "../test/test_utilities.jl")) # to load data dat, evts = loadtestdata("test_case_4b"); evts[1:5,:] ``` The `type` column of table `evts` contains two conditions: `eventA`` and `eventB` (if your eventstypes are specified in a different column, you need to define the keywordargument `eventcolumn` in the `fit` command below) ### Specify formulas and basisfunctions ```@example main bf1 = firbasis(Ο„ = (-0.4, 0.8), sfreq = 50) bf2 = firbasis(Ο„ = (-0.2, 1.2), sfreq = 50) bf2|> DisplayAs.withcontext(:is_pluto=>true) # hide ``` For each event, a basis function and formula must be specified. The same basis and formulas may be used. ```@example main f = @formula 0 ~ 1 ``` For each event, we must specify the formula and basis function to be used. ```@example main bfDict = [ "eventA" => (f, bf1), "eventB" => (f, bf2) ] bfDict |> DisplayAs.withcontext(:is_pluto=>true) # hide ``` Finally, fitting & plotting works the same way as always ```@example main m = Unfold.fit( UnfoldModel, bfDict, evts, dat, solver = (x, y) -> Unfold.solver_default(x, y; stderror = true), eventcolumn = "type", ) results = coeftable(m) plot_erp(results; stderror = true, mapping = (; col = :eventname)) ```
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git
[ "MIT" ]
0.7.6
14faed094d3728f4e549b6fbc4b38b9b8c6a4a99
docs
1805
# Loading Data into Unfold Unfold is generally agnostic to how you load your data. You only require a Matrix (channel x time) or 3D-Array(channel x time x epochs) and an event-dataframe. ### Setup ```@Example main using Unfold using UnfoldMakie,CairoMakie using PyMNE using DataFrames ``` ### MNE Demo Dataset The easiest way to showcase this is to simply use a demo-dataset from MNE. ```@Example main limo_epochs = PyMNE.datasets.limo.load_data(subject=1,path="~/MNE/DATA",update_path=false) limo_epochs ``` Now we can fit a simple `Unfold` model to it. First extract the data & convert it to Julia/Unfold requirements ```@Example main data = limo_epochs.get_data(picks="B11") data = permutedims(data,[2,3,1]) # get into ch x times x epochs function convert_pandas(df_pd) df= DataFrame() for col in df_pd.columns df[!, col] = getproperty(df_pd, col).values end return df end events = convert_pandas(limo_epochs.metadata) rename!(events,2=>:coherence) # negative signs in formulas are not good ;) events.face = string.(events.face) # ugly names, but fast ``` Next fit an Unfold Model ```@Example main uf = fit(UnfoldModel,[Any=>(@formula(0~face+coherence),Float64.(limo_epochs.times))],events,data) results = coeftable(uf) ``` ```@Example main plot_results(results) ``` ### Read some of your own data We can make use of all PyMNE importer functions to load the data. Try it for your own data! Get starting with Unfold in no-time! ```@Example main #eeglabdata = PyMNE.io.read_raw_eeglab("pathToEEGLabSet.set") ``` ### Contribute? Some extra conversions are needed to import the data from PyMNE to Unfold (as shown above). We could try putting these in a wrapper function - do you want to tackle this challenge? Would be a great first contribution to the toolbox :-)
Unfold
https://github.com/unfoldtoolbox/Unfold.jl.git