text:
# Tests for the public doctest() function
#
# If the tests are giving you trouble, you can run the tests with
#
#    JULIA_DEBUG=DocTestAPITests julia doctests.jl
#
# TODO: Combine the makedocs calls and stdout files. Also, allow running them one by one.
#
module DocTestAPITests
using Test
using Documenter

# Test the Documenter.doctest function
# ------------------------------------
function run_doctest(f, args...; kwargs...)
    (result, success, backtrace, output) = Documenter.Utilities.withoutput() do
        # Running inside a Task to make sure that the parent testsets do not interfere.
        t = Task(() -> doctest(args...; kwargs...))
        schedule(t)
        # if an exception happens, it gets propagated
        try
            fetch(t)
        catch e
            # Note: in Julia 1.3 fetch no longer throws the exception direction, but instead
            # wraps it in a TaskFailedException (https://github.com/JuliaLang/julia/pull/32814).
            rethrow(t.exception)
        end
    end

    @debug """run_doctest($args;, $kwargs) -> $(success ? "success" : "fail")
    ------------------------------------ output ------------------------------------
    $(output)
    --------------------------------------------------------------------------------
    """ result stacktrace(backtrace)

    f(result, success, backtrace, output)
end

"""
```jldoctest
julia> 2 + 2
4
```
"""
module DocTest1 end

"""
```jldoctest
julia> 2 + 2
5
```
"""
module DocTest2 end

"""
```jldoctest
julia> x
42
```
"""
module DocTest3 end

module DocTest4
    """
    ```jldoctest
    julia> x
    42
    ```
    """
    function foo end
    module Submodule
        """
        ```jldoctest
        julia> x + 1
        43
        ```
        """
        function foo end
    end
end

module DocTest5
    """
    ```jldoctest
    julia> x
    42
    ```
    """
    function foo end
    """
    ```jldoctest
    julia> x
    4200
    ```
    """
    module Submodule
        """
        ```jldoctest
        julia> x + 1
        4201
        ```
        """
        function foo end
    end
end

"""
```jldoctest
julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])
ERROR: syntax: invalid iteration specification
```
```jldoctest
julia> 1.2.3
ERROR: syntax: invalid numeric constant "1.2."
```
```jldoctest
println(9.8.7)
# output
ERROR: syntax: invalid numeric constant "9.8."
```
```jldoctest
julia> Meta.ParseError("foo")
Base.Meta.ParseError("foo")

julia> Meta.ParseError("foo") |> throw
ERROR: Base.Meta.ParseError("foo")
Stacktrace:
[...]
```
"""
module ParseErrorSuccess end

"""
```jldoctest
julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])
ERROR: syntax: invalid iteration specificationX
```
"""
module ParseErrorFail end

"""
```jldoctest
println(9.8.7)
# output
ERROR: syntax: invalid numeric constant "1.2."
```
"""
module ScriptParseErrorFail end

module PR1075
    "x \$(42) y"
    function qux end
    "..."
    function foo end
    @doc @doc(foo) function bar end
    @doc @doc(bar) function baz end
end

@testset "Documenter.doctest" begin
    # DocTest1
    run_doctest(nothing, [DocTest1]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end

    # DocTest2
    run_doctest(nothing, [DocTest2]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end

    # DocTest3
    run_doctest(nothing, [DocTest3]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end
    DocMeta.setdocmeta!(DocTest3, :DocTestSetup, :(x = 42))
    run_doctest(nothing, [DocTest3]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end

    # DocTest4
    run_doctest(nothing, [DocTest4]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end
    DocMeta.setdocmeta!(DocTest4, :DocTestSetup, :(x = 42))
    run_doctest(nothing, [DocTest4]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end
    DocMeta.setdocmeta!(DocTest4, :DocTestSetup, :(x = 42); recursive = true, warn = false)
    run_doctest(nothing, [DocTest4]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end

    # DocTest5
    run_doctest(nothing, [DocTest5]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end
    DocMeta.setdocmeta!(DocTest5, :DocTestSetup, :(x = 42))
    DocMeta.setdocmeta!(DocTest5.Submodule, :DocTestSetup, :(x = 4200))
    run_doctest(nothing, [DocTest5]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end

    # Parse errors in doctests (https://github.com/JuliaDocs/Documenter.jl/issues/1046)
    run_doctest(nothing, [ParseErrorSuccess]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end
    run_doctest(nothing, [ParseErrorFail]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end
    run_doctest(nothing, [ScriptParseErrorFail]) do result, success, backtrace, output
        @test !success
        @test result isa TestSetException
    end

    # PR 1075
    run_doctest(nothing, [PR1075]) do result, success, backtrace, output
        @test success
        @test result isa Test.DefaultTestSet
    end
end

end # module


text:
struct Kosarkasi
    ime::String
    prezime::String
    visina::Int
    pozicija::String
end

function zad42(Kosarkasi,pozicija,visina)
    rez = Array(Kosarkasi)
    for i = 1:length(Kosarkasi)
        if Kosarkasi[i].pozicija == pozicija
            if Kosarkasi[i].visina > visina
                push!(rez,Kosarkasi[i])
            end
        end
    end
    return rez

end

ext: jl


text:
function pprint(io::GarishIO, mime::MIME"text/plain", d::AbstractDict)
    # use default printing if it's the root
    io.state.level == 0 && return show(io, mime, d)
    # heurostics to print Dict in compact form
    if length(d) < 20 && !max_indent_reached(io, length(string(d)))
        pprint_list_like(io, d, "(", ")"; compact=true)
    else
        pprint_list_like(io, d, "(", ")")
    end
end


text:
#=
    --------------------------------------------------------------------------
    Implements functionality for learning a mean diffusion's trajectory during
    mcmc sampling. The main object is `Adaptation`.
    --------------------------------------------------------------------------
=#
import Base.resize!

"""
    Adaptation{TV,T}

Stores the history of imputed paths from which the mean trajectory can be
computed, as well as the scheme according to which the adaptation is supposed
to be performed. `TV` indicates whether any adaptation should be done at all.
`TV` set to `Val{False}` acts as an indicator that no adaptation is to be done.
"""
struct Adaptation{TV,T,ST}
    X::Vector{Vector{Vector{T}}} # history of paths
    λs::Vector{Float64}          # ladder of weights that balance initial
                                 # auxiliary law and the adaptive law based on
                                 # the mean trajectory
    sizes::Vector{Int64}         # ladder indicating number of paths that are to
                                 # be used for computing mean trajectory
    skip::Int64                  # save 1 in every ... many sampled paths
    N::Vector{Int64}             # counter #1-current position on the ladder
                                 # #2-current index of the last saved path
    solver::ST

    """
        Adaptation(::T, λs, sizes_of_path_coll, skip=1)

    Initialise adaptation. `λs` and `sizes_of_path_coll` are ladders that
    are traversed during sampling.
    ...
    # Arguments
    - `::T`: Data type of a diffusion
    - `λs`: ladder of weights that balance between initial choice of auxiliary
            law and the adaptive law based on the mean trajectory
    - `sizes_of_path_coll`: ladder giving the number of paths that are to be
                            used for computing the mean trajectory
    - `skip`: save 1 in every ... many sampled paths
    ...
    """
    function Adaptation(::T, λs, sizes_of_path_coll, skip=1, solver::ST=Vern7()
                        ) where {T,ST}
        TV = Val{true}
        M = maximum(sizes_of_path_coll)
        X = [[zeros(T,0)] for i in 1:M]
        N = [1,1]
        new{TV,T,ST}(X, λs, sizes_of_path_coll, skip, N, solver)
    end

    """
        Adaptation{TV,T}()

    Empty constructor.
    """
    Adaptation{TV,T,ST}() where {TV,T,ST} = new{TV,T,ST}()
end

"""
    NoAdaptation()

Helper function for constructing a flag saying that no adaptation is to be done
"""
NoAdaptation() = Adaptation{Val{false},Nothing,Nothing}()

"""
    resize!(adpt::Adaptation{TV,T}, m, ns::Vector{Int64})

Resize internal containers `X` with paths so that each storage unit consists of
`m` subunits and each of these subunits is a length `ns[i]` vector of type `T`
"""
function resize!(adpt::Adaptation{TV,T}, m, ns::Vector{Int64}) where {TV,T}
    K = length(adpt.X)
    for i in 1:K
        adpt.X[i] = [[zero(T) for _ in 1:ns[i]] for i in 1:m]
    end
end

function adaptation!(ws, adpt::Adaptation, mcmc_iter, ll)
    if still_adapting(adpt) && mcmc_iter % adpt.skip == 0
        add_path!(ws, adpt)
        ll = update!(ws, adpt, ll)
    end
    ll
end

still_adapting(::Adaptation{Val{false}}) = false
still_adapting(adpt::Adaptation{Val{true}}) = adpt.N[1] <= length(adpt.sizes)

function add_path!(ws, adpt::Adaptation)
    m = length(ws.XX)
    for j in 1:m
        adpt.X[adpt.N[2]][j] .= ws.XX[j].yy
    end
end

function update!(ws, adpt::Adaptation, ll)
    if adpt.N[2] == adpt.sizes[adpt.N[1]]
        X_bar = mean_trajectory(adpt)
        m = length(ws.P)
        for j in 1:m
            Pt = recentre(ws.P[j].Pt, ws.XX[j].tt, X_bar[j])
            update_λ!(Pt, adpt.λs[adpt.N[1]])
            ws.P[j] = GuidPropBridge(ws.P[j], Pt)

            Ptᵒ = recentre(ws.Pᵒ[j].Pt, ws.XX[j].tt, X_bar[j])
            update_λ!(Ptᵒ, adpt.λs[adpt.N[1]])
            ws.Pᵒ[j] = GuidPropBridge(ws.Pᵒ[j], Ptᵒ)
        end

        solve_back_rec!(NoBlocking(), adpt.solver, ws.P)
        #solveBackRec!(NoBlocking(), ws.Pᵒ, ST())
        y = ws.XX[1].yy[1]
        z = inv_start_pt(y, ws.x0_prior, ws.P[1])
        set!(ws.z, z)

        for j in 1:m
            inv_solve!(EulerMaruyamaBounded(), ws.XX[j], ws.WW[j], ws.P[j])
        end
        ll = logpdf(ws.x0_prior, y)
        ll += path_log_likhd(obs_scheme(ws), ws.XX, ws.P, 1:m, ws.fpt)
        ll += lobslikelihood(ws.P[1], y)
        adpt.N[2] = 1
        adpt.N[1] += 1
    else
        adpt.N[2] += 1
    end
    ll
end

"""
    mean_trajectory(adpt::Adaptation{Val{true}})

Compute the mean trajectory from the history of accepted paths stored in
`adpt.X`
"""
function mean_trajectory(adpt::Adaptation{Val{true}})
    X = adpt.X
    num_paths = adpt.sizes[adpt.N[1]]
    num_segments = length(X[1])
    for i in 2:num_paths
        for j in 1:num_segments
            num_pts = length(X[i][j])
            for k in 1:num_pts
                X[1][j][k] += X[i][j][k]
            end
        end
    end
    for j in 1:num_segments
        num_pts = length(X[1][j])
        for k in 1:num_pts
            X[1][j][k] /= num_paths
        end
    end
    X[1]
end

"""
    print_adaptation_info(adpt::Adaptation{Val{false}}, ::Any, ::Any, ::Any)

Nothing to print for no adaptation
"""
print_adaptation_info(adpt::Adaptation{Val{false}}, ::Any, ::Any, ::Any) = nothing

"""
    print_adaptation_info(adpt::Adaptation{Val{true}}, acc_imp_counter,
                          acc_updt_counter, i)

Print some information regarding acceptance rate during adaptation to the
console
"""
function print_adaptation_info(adpt::Adaptation{Val{true}}, acc_imp_counter,
                               accUpdtCounter, i)
    if i % adpt.skip == 0 && adpt.N[2] == adpt.sizes[adpt.N[1]]
        print("--------------------------------------------------------\n")
        print(" Adapting...\n")
        print(" Using ", adpt.N[2], " many paths, thinned by ", adpt.skip, "\n")
        print(" Previous imputation acceptance rate: ", acc_imp_counter/i, "\n")
        print(" Previous param update acceptance rate: ", acc_updt_counter./i, "\n")
        print("--------------------------------------------------------\n")
    end
end


text:
using Test
using Arpack: eigs
using ExactDiagonalization.FED: SparseMatrixCSC, GBasis,FockBasis
#using SparseArrays: SparseMatrixCSC
using QuantumLattices
using QuantumLattices.Mathematics.AlgebraOverFields: idtype
using ExactDiagonalization.FEDW: NCBasis,matrix,bitgen,bkron,boplus

@testset "kron" begin
            a=[(1,),(2,3)]
            b=[Tuple{}(),(0,)]
    @test  Base.kron(a,a)==[(1,1),(1,2,3),(2,3,1),(2,3,2,3)]
    @test  Base.kron(a,b)==[(1,),(1,0),(2,3),(2,3,0)]
    @test  Base.kron(b,b)==[Tuple{}(),(0,),(0,),(0,0)]
    @test  bitgen(b[1],UInt)==UInt(0)
    @test  bitgen(b[2],UInt)==UInt(0)
    @test  bitgen(a[1],UInt)==UInt(1)
    @test  bitgen(a[2],UInt)==UInt(1)<<1|UInt(1)<<2
end

@testset "NCBasis" begin
    state=[2,3]
    particle=[[(0,),(1,)],[(1,),(2,3)]]
    basis=NCBasis{UInt}(state,particle)
@test    dimension(basis)==1*3+2*(3+1)
@test    string(bkron(UInt(3),4,UInt(45),6),base=2)=="1011010011"
@test    basis[4]==UInt(14)
@test    searchsortedfirst(basis,UInt(14))==4
    particle2=[[(1,),(2,)],[(0,),(1,2)]]
    state2=[2,2]
@time    basis2=NCBasis{UInt}(state2,particle2)
@time    basis3=bkron(basis,basis2)
@test    basis3.vnstate==[2,3,2,2]
@test    basis3.vnpart==[[(0,),(1,),(1,),(2,)],[(0,),(1,),(0,),(1,2)],[(1,),(2,3),(1,),(2,)],[(1,),(2,3),(0,),(1,2)]]
    #    show(basis)
    #    show(basis2)
    #    show(basis3)
    b5=NCBasis{UInt}([2,3],particle2)
    basis4=boplus(basis,b5)
@test    basis4.vnstate==[2,3]
@test    basis4.vnpart==vcat(particle,particle2)

end

@testset "matrix" begin
lattice=Lattice("L2P",[Point(PID(1),(0.0,)),Point(PID(2),(1.0,))])
config=Config{Fock{:f}}(pid->Fock{:f}(atom=pid.site%2, norbital=1, nspin=2, nnambu=2), lattice.pids)
table=Table(config,usualfockindextotuple)
t=Hopping(:t,1.0,1)
U=Hubbard(:U,1.0)
μ=Onsite(:μ,-0.5)
g=Generator((U,μ,t),Bonds(lattice),config,half=false,table=table)
#basisbra = NCBasis{UInt}([2,2],[[(0,),(2,)],[(2,),(0,)]])
#basisket = NCBasis{UInt}([2,2],[[(1,),(1,)]])
basis=NCBasis{UInt}([2,2],[[(0,1,2),(0,1,2)]])
m=matrix(expand(g),basis,basis,g.table)
@test eigs(m,which=:SR,ritzvec=false)[1][1]≈-2.5615528128088303
end


text:
### A Pluto.jl notebook ###
# v0.17.3

using Markdown
using InteractiveUtils

# ╔═╡ d7b19f60-6348-11ec-11b8-abe5c0a6cee7
md"""
# Day Two: Dive!

**Reference:** [Day 2 (Advent of Code 2021)](https://adventofcode.com/2021/day/2)

**Source:** [ljk233/AdventOfCode2021/days/02/d2.jl](https://github.com/ljk233/AdventOfCode2021/blob/main/days/02/d2.jl)
"""

# ╔═╡ 1a85b479-29dc-4240-ad27-f04002c3f021
"""
	cmds(lines: String[]) -> NamedTuple(:dir, :step)

Return each line in `lines` as a named tuple, keywords **dir, step.**

**Example**
```julia
# line is "forward 7"
(dir="fowards", step=7)
```
"""
cmds(lines) = map(lines) do line
	d, s = split(line)
	return (dir=d, step=parse(Int, s))
end

# ╔═╡ aeba97ec-fd96-4ef4-99b0-726665015217
md"""
## Part 1

Calculate the horizontal position and depth you would have after following the planned course.

**What do you get if you multiply your final horizontal position by your final depth?**
"""

# ╔═╡ 7f03ad5e-bf73-4b16-958b-592ba4b6d923
"""
	main1(f: String) -> Integer
"""
function main1(f)
	lines = readlines(f)
	x, y = 0, 0
	for cmd in cmds(lines)
		if cmd.dir == "down"
	    	y += cmd.step
		elseif cmd.dir == "up"
	    	y -= cmd.step
		else
			x += cmd.step
	    end
	end
	return x*y
end

# ╔═╡ 8cc55754-6815-4c08-8538-b6f4c74d5c28
md"""
**Test #1.**
Expected result = 150.
"""

# ╔═╡ d0d5ecd6-fa56-4fca-a293-fb0a682e4a7b
main1("test.in")

# ╔═╡ 63a48804-1a55-48c6-832f-74f52ac1d583
md"""
**Solution.**
Confirmed output = 2036120.
"""

# ╔═╡ 6c58e558-21fe-4221-b324-1efd90c7911a
main1("data.in")

# ╔═╡ 0e681b8a-82bc-425c-a374-e36d360559d2
md"""
## Part 2

Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course.

**What do you get if you multiply your final horizontal position by your final depth?**
"""

# ╔═╡ 774f7d4b-9d47-41eb-a6d7-e9d0fc579fbb
"""
	main2(f: String) -> Integer
"""
function main2(f)
	lines = readlines(f)
	x, y, aim = 0, 0, 0
	for cmd in cmds(lines)
		if cmd.dir == "down"
	    	aim += cmd.step
		elseif cmd.dir == "up"
	    	aim -= cmd.step
		else
	    	x += cmd.step
	    	y += cmd.step * aim
	    end
	end
	return x*y
end

# ╔═╡ 2e90f5d0-e5ee-4abb-932b-5638afb3a146
md"""
**Test #2.**
Expected result = 900.
"""

# ╔═╡ b5db6a00-eb1d-4cf0-bfad-d04b0d7d9968
main2("test.in")

# ╔═╡ 4d9b89d5-7f30-4031-a619-57fdb5936dc5
md"""
**Solution.**
Confirmed results = 2015547716.
"""

# ╔═╡ 17e05631-6ee0-49f0-b273-c151812220af
main2("data.in")

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
"""

# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised

julia_version = "1.7.0"
manifest_format = "2.0"

[deps]
"""

# ╔═╡ Cell order:
# ╟─d7b19f60-6348-11ec-11b8-abe5c0a6cee7
# ╠═1a85b479-29dc-4240-ad27-f04002c3f021
# ╟─aeba97ec-fd96-4ef4-99b0-726665015217
# ╠═7f03ad5e-bf73-4b16-958b-592ba4b6d923
# ╟─8cc55754-6815-4c08-8538-b6f4c74d5c28
# ╟─d0d5ecd6-fa56-4fca-a293-fb0a682e4a7b
# ╟─63a48804-1a55-48c6-832f-74f52ac1d583
# ╟─6c58e558-21fe-4221-b324-1efd90c7911a
# ╟─0e681b8a-82bc-425c-a374-e36d360559d2
# ╠═774f7d4b-9d47-41eb-a6d7-e9d0fc579fbb
# ╟─2e90f5d0-e5ee-4abb-932b-5638afb3a146
# ╟─b5db6a00-eb1d-4cf0-bfad-d04b0d7d9968
# ╟─4d9b89d5-7f30-4031-a619-57fdb5936dc5
# ╟─17e05631-6ee0-49f0-b273-c151812220af
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
using DelimitedFiles: readdlm
using LinearAlgebra: dot, I

using KalmanFilters.UnscentedKalmanFilter
using KalmanFilters.SigmaPoints

function normalize_angle(α::Float64)::Float64
    m = 2π
    α = α > 0 ? α % m : m + (α % m)
    if α > π
        α -= m
    end
    α
end

function state_residual(
    y::AbstractArray{Float64, 1}, x::AbstractArray{Float64, 1}
)::AbstractArray{Float64, 1}
    r = y - x
    r[3] = normalize_angle(r[3])
    r
end

function state_residual(
    y::AbstractArray{Float64, 2}, x::AbstractArray{Float64, 1}
)::AbstractArray{Float64, 2}
    R = y .- x'
    R[:, 3] .= normalize_angle.(@view(R[:, 3]))
    R
end

function state_add(
    y::AbstractArray{Float64, 1}, x::AbstractArray{Float64, 1}
)::AbstractArray{Float64, 1}
    r = y + x
    r[3] = normalize_angle(r[3])
    r
end

function state_mean(
    Σ::Array{Float64, 2}, m_w::Array{Float64, 1}
)::Array{Float64, 1}
    [
        dot(@view(Σ[:, 1]), m_w),
        dot(@view(Σ[:, 2]), m_w),
        atan(dot(sin.(@view(Σ[:, 3])), m_w), dot(cos.(@view(Σ[:, 3])), m_w)),
    ]
end

hx(;x::AbstractArray{Float64, 1})::AbstractArray{Float64, 1} = x

function fx(
    ;x::Array{Float64, 1}, δt::Float64,
    μ::Array{Float64, 1}, wheelbase::Float64
)::Array{Float64, 1}
    ν, α = μ
    if abs(ν) < 0.3
        return x
    end

    θ = x[3]
    s = ν * δt
    if abs(α) < 0.017
        return x + [s * cos(θ), s * sin(θ), 0.0]
    end

    β = (s / wheelbase) * tan(α)
    r = s / β
    x + [-r * sin(θ) + r * sin(θ + β), r * cos(θ) - r * cos(θ + β), β]
end

load_from_txt(path::String) = readdlm(path, ' ', Float64, '\n')

function main()
    base_path = raw"C:\Users\tonys\projects\carla-dataset\high-quality\recording-2020-05-01-13-52-24-005689"
    positions_time = load_from_txt(joinpath(base_path, "gnss", "timestamp"))
    positions = load_from_txt(joinpath(base_path, "gnss", "enu"))[:, 1:2]

    imu_time = load_from_txt(joinpath(base_path, "imu", "timestamp"))
    compass = load_from_txt(joinpath(base_path, "imu", "compass"))
    speed = load_from_txt(joinpath(base_path, "imu", "speed"))
    steer = load_from_txt(joinpath(base_path, "imu", "steer"))
    # Convert data
    measurement_noise = 1.5
    compass *= π / 180
    steer *= -70.0 * π / 180
    wheelbase = 2.9591
    positions += randn(size(positions)...) * measurement_noise
    println("Loaded data")

    σ_parameters = MerweScaled(n=3, α=1e-3, β=2.0, κ=0.0, residual_x=state_residual)
    ukf = UKFState(
        dim_x=3, dim_z=3, σ_parameters=σ_parameters,
        add_x=state_add,
        mean_x=state_mean, mean_z=state_mean,
        residual_x=state_residual, residual_z=state_residual
    )
    ukf.x .= [positions[1, 1], positions[1, 2], compass[1]]
    ukf.P .*= 0.1

    δt = 1.0 / 50
    μ = zeros(Float64, 2)
    z = zeros(Float64, 3)
    R = Matrix{Float64}(I, 3, 3) * measurement_noise
    Q = Float64[[4e-12 4e-10 2e-8]; [4e-10 4e-8 2e-6]; [2e-8 2e-6 1e-4]]

    track = zeros(Float64, size(imu_time, 1), 2)
    pos_i::Int64 = 1
    can_update::Bool = false

    for (i, t) = enumerate(imu_time)
        μ[1] = speed[i]
        μ[2] = steer[i]
        predict!(ukf=ukf, δt=δt, Q=Q, fx=fx, μ=μ, wheelbase=wheelbase)

        can_update = pos_i < size(positions_time, 1) && (
            abs(t - positions_time[pos_i]) < δt
            || t > positions_time[pos_i]
        )
        if can_update
            z[1:2] = positions[pos_i, :]
            z[3] = compass[i]
            update!(ukf=ukf, z=z, R=R, hx=hx)
            pos_i += 1
        end
        track[i, :] = ukf.x[1:2]
    end

    println(ukf.x)
end

main()

max_stars_repo_name: pxl-th/KalmanFilters

max_issues_repo_name: pxl-th/KalmanFilters

max_forks_repo_name: pxl-th/KalmanFilters


text:
function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    # Base.precompile(Tuple{typeof(which(_turbo_!,(Val{UNROLL},Val{OPS},Val{ARF},Val{AM},Val{LPSYM},Tuple{LB, V},)).generator.gen),Any,Any,Any,Any,Any,Any,Any,Any,Type,Type,Type,Type,Any,Any})   # time: 1.0198073
  # Base.precompile(Tuple{typeof(gespf1),Any,Tuple{Any, VectorizationBase.NullStep}})   # time: 0.1096832
    Base.precompile(avx_body, (LoopSet, Tuple{Bool,Int8,Int8,Int8,Bool,Int,Int,Int,Int,Int,Int,Int,UInt}))
    Base.precompile(lower_and_split_loops, (LoopSet, Int))
    Base.precompile(lower, (LoopSet, Int, Int, Int, Int))
    Base.precompile(Tuple{typeof(turbo_macro),Module,LineNumberNode,Expr})   # time: 0.09183489
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.05469272
    Base.precompile(Tuple{typeof(zerorangestart),UnitRange{Int}})   # time: 0.04291692
    Base.precompile(Tuple{Type{LoopSet},Symbol})   # time: 0.03362425
    Base.precompile(Tuple{typeof(recursive_muladd_search!),Expr,Vector{Any},Nothing,Bool,Bool})   # time: 0.029960306
    Base.precompile(Tuple{typeof(add_constant!),LoopSet,Float64,Vector{Symbol},Symbol,Int})   # time: 0.027501073
    Base.precompile(Tuple{typeof(_turbo_loopset),Any,Any,Any,Any,Core.SimpleVector,Core.SimpleVector,Tuple{Bool, Int8, Int8, Int8, Bool, Int, Int, Int, Int, Int, Int, Int, UInt}})   # time: 0.02345788
    Base.precompile(Tuple{typeof(substitute_broadcast),Expr,Symbol,Bool,Int8,Int8,Int8,Int,Int})   # time: 0.02281322
    Base.precompile(Tuple{typeof(push!),LoopSet,Expr,Int,Int})   # time: 0.022659862
    Base.precompile(Tuple{typeof(add_compute!),LoopSet,Symbol,Expr,Int,Int,Nothing})   # time: 0.02167476
    Base.precompile(Tuple{typeof(checkforoffset!),LoopSet,Symbol,Int,Vector{Operation},Vector{Symbol},Vector{Int8},Vector{Int8},Vector{Bool},Vector{Symbol},Vector{Symbol},Expr,Int})   # time: 0.020454278
    Base.precompile(Tuple{typeof(generate_call),LoopSet,Tuple{Bool, Int8, Int8, Int8},UInt,Bool})   # time: 0.020274462
    Base.precompile(Tuple{typeof(expandbyoffset!),Vector{Tuple{Int, Tuple{Int, Int32, Bool}}},Vector{Any},Vector{Int}})   # time: 0.019860294
    Base.precompile(Tuple{typeof(isscopedname),Symbol,Symbol,Symbol})   # time: 0.016642524
    # Base.precompile(Tuple{typeof(which(vmaterialize!,(Union{Adjoint{T<:Union{Bool, Float32, Float64, Int16, Int32, Int, Int8, UInt16, UInt32, UInt, UInt8, VectorizationBase.Bit}, A<:AbstractArray{T<:Union{Bool, Float32, Float64, Int16, Int32, Int, Int8, UInt16, UInt32, UInt, UInt8, VectorizationBase.Bit}, N}}, Transpose{T<:Union{Bool, Float32, Float64, Int16, Int32, Int, Int8, UInt16, UInt32, UInt, UInt8, VectorizationBase.Bit}, A<:AbstractArray{T<:Union{Bool, Float32, Float64, Int16, Int32, Int, Int8, UInt16, UInt32, UInt, UInt8, VectorizationBase.Bit}, N}}},BC<:Union{Base.Broadcast.Broadcasted, LoopVectorization.Product},Val{Mod},Val{UNROLL},)).generator.gen),Any,Any,Any,Any,Any,Any,Any,Any,Any,Type,Any})   # time: 0.016243948
    Base.precompile(Tuple{typeof(add_compute!),LoopSet,Symbol,Expr,Int,Int,ArrayReferenceMetaPosition})   # time: 0.015863877
    Base.precompile(Tuple{typeof(pushop!),LoopSet,Operation,Symbol})   # time: 0.015437002
    Base.precompile(Tuple{typeof(add_grouped_strided_pointer!),Expr,LoopSet})   # time: 0.014089168
    Base.precompile(Tuple{typeof(should_zerorangestart),LoopSet,Vector{ArrayReferenceMeta},Vector{Vector{Int}},Vector{Bool}})   # time: 0.013730842
    # Base.precompile(Tuple{typeof(normalize_offsets!),LoopSet,Int,Vector{ArrayReferenceMeta},Vector{Int},Vector{Vector{Tuple{Int, Int, Int}}}})   # time: 0.012555225
    Base.precompile(Tuple{Type{Operation},Int,Symbol,Int,Symbol,OperationType,Vector{Symbol},Vector{Symbol},Vector{Operation},ArrayReferenceMeta,Vector{Symbol}})   # time: 0.012369638
    # Base.precompile(Tuple{typeof(which(subsetview,(VectorizationBase.StridedPointer{T, N, C, B, R, X, O},StaticInt{I},Integer,)).generator.gen),Any,Any,Any,Any,Any,Any,Any,Any,Any,Any,Any,Any})   # time: 0.011771905
    # Base.precompile(Tuple{typeof(which(gc_preserve_vmap!,(F,AbstractArray,Val{NonTemporal},Val{Threaded},Vararg{AbstractArray, A},)).generator.gen),Any,Any,Any,Any,Any,Any,Any,Type,Any,Any})   # time: 0.011680721
    Base.precompile(Tuple{typeof(matmul_params)})   # time: 0.011071064
    Base.precompile(Tuple{Type{ArrayRefStruct},LoopSet,ArrayReferenceMeta,Vector{Symbol},Vector{Int}})   # time: 0.009680483
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Bool, 1, 1, 0, (1,), Tuple{StaticInt{1}}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.009625301
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{UInt8, 2, 1, 0, (1, 2), Tuple{StaticInt{1}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.009153917
    Base.precompile(Tuple{typeof(array_reference_meta!),LoopSet,Symbol,SubArray{Any, 1, Vector{Any}, Tuple{UnitRange{Int}}, true},Int,Nothing})   # time: 0.008658403
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 3, 1, 0, (1, 2, 3), Tuple{StaticInt{8}, Int, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.008647886
    Base.precompile(Tuple{typeof(uniquearrayrefs_csesummary),LoopSet})   # time: 0.008355928
    Base.precompile(Tuple{typeof(turbo_macro),Module,LineNumberNode,Expr,Expr,Vararg{Expr}})   # time: 0.007974428
    Base.precompile(Tuple{typeof(tryrefconvert),LoopSet,Expr,Int,Nothing})   # time: 0.007913027
    Base.precompile(Tuple{typeof(turbo_macro),Module,LineNumberNode,Expr,Expr})   # time: 0.007347188
    Base.precompile(Tuple{typeof(show),IOContext{IOBuffer},Operation})   # time: 0.007273663
    Base.precompile(Tuple{typeof(loop_boundaries),LoopSet,Vector{Bool}})   # time: 0.006810827
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{4}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{StaticInt{-1}, StaticInt{-1}, StaticInt{1}, StaticInt{1}}})   # time: 0.006164707
    Base.precompile(Tuple{typeof(add_ci_call!),Expr,Any,Vector{Any},Vector{Symbol},Int,Expr,Symbol})   # time: 0.006148137
    Base.precompile(Tuple{typeof(add_ci_call!),Expr,Any,Vector{Any},Vector{Symbol},Int})   # time: 0.006063301
    Base.precompile(Tuple{typeof(mem_offset),Operation,UnrollArgs,Vector{Bool},Bool,LoopSet,Bool})   # time: 0.005945972
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 3, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{16}, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}, StaticInt{0}}})   # time: 0.005927015
    Base.precompile(Tuple{typeof(sizeofeltypes),Core.SimpleVector})   # time: 0.005828176
    Base.precompile(Tuple{typeof(cse_constant_offsets!),LoopSet,Vector{ArrayReferenceMeta},Int,Vector{Vector{Int}},Vector{Vector{Tuple{Int, Int, Int}}}})   # time: 0.005694307
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{8}, StaticInt{16}, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{StaticInt{1}, VectorizationBase.NullStep, StaticInt{2}, VectorizationBase.NullStep}})   # time: 0.005314204
    Base.precompile(Tuple{typeof(indices_loop!),LoopSet,Expr,Symbol})   # time: 0.005283243
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{0, Tuple{}}, VectorizationBase.NullStep, VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.005256126
    Base.precompile(Tuple{typeof(gesp_const_offsets!),LoopSet,Symbol,Int,Vector{Symbol},Vector{Bool},Vector{Tuple{Int, Symbol}},Int})   # time: 0.005168524
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}, VectorizationBase.NullStep, VectorizationBase.CartesianVIndex{0, Tuple{}}}})   # time: 0.005122315
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}, VectorizationBase.NullStep, VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.005078802
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.005036135
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 2, 0, (3, 1, 4, 2), Tuple{Int, StaticInt{8}, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.004968671
    Base.precompile(Tuple{typeof(subset_vptr!),LoopSet,Symbol,Int,Symbol,Vector{Symbol},Vector{Bool},Int})   # time: 0.004904486
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}, VectorizationBase.NullStep, VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}}})   # time: 0.004722758
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{0, Tuple{}}, Int, VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.004705647
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}, VectorizationBase.NullStep, VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}}})   # time: 0.00464261
    Base.precompile(Tuple{typeof(array_reference_meta!),LoopSet,Symbol,SubArray{Any, 1, Vector{Any}, Tuple{UnitRange{Int}}, true},Int,Symbol})   # time: 0.00460717
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, StaticInt{0}}})   # time: 0.004565251
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{StaticInt{12}}})   # time: 0.004481134
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.004292746
    Base.precompile(Tuple{typeof(add_mref!),Expr,LoopSet,ArrayReferenceMeta,Type{Ptr{Float64}},Int,Int,Vector{Int},Symbol})   # time: 0.004265177
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, Int}})   # time: 0.004203109
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 3, 1, 0, (1, 2, 3), Tuple{StaticInt{8}, Int, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}}})   # time: 0.004096196
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.004048887
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 3, 5), Tuple{StaticInt{8}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}, VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}}})   # time: 0.004037695
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{4}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.004000398
    Base.precompile(Tuple{typeof(vcmpend),Int,UnitRange{Int},StaticInt{32}})   # time: 0.00396612
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{112}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003964044
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 4, 5), Tuple{StaticInt{8}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}, VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.003955696
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{72}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003950459
    Base.precompile(Tuple{typeof(add_operation!),LoopSet,Symbol,Expr,Int,Int})   # time: 0.003884223
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}, VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}}})   # time: 0.003860693
    # Base.precompile(Tuple{typeof(setup_call_inline),LoopSet,Bool,Int8,Int8,Int})   # time: 0.003833778
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{64}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003823736
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{120}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003811805
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{104}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003737383
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, -1, 0, (2, 3, 4, 5), NTuple{4, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{0, Tuple{}}, VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.003715812
    Base.precompile(Tuple{typeof(add_constant!),LoopSet,Int,Int})   # time: 0.003714495
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{88}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003710863
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{48}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003705501
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{128}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.00368231
    Base.precompile(Tuple{typeof(add_reduction_update_parent!),Vector{Operation},Vector{Symbol},Vector{Symbol},LoopSet,Operation,Instruction,Int,Int})   # time: 0.003681644
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{56}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003663781
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{96}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003654243
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{80}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003646013
    Base.precompile(Tuple{typeof(add_pow!),LoopSet,Symbol,Any,Int,Int,Int})   # time: 0.003590707
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}, Int, VectorizationBase.CartesianVIndex{0, Tuple{}}}})   # time: 0.003590253
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{Int, Int}},Tuple{Int, VectorizationBase.NullStep}})   # time: 0.003578008
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{4}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.NullStep, VectorizationBase.NullStep, StaticInt{1}, StaticInt{1}}})   # time: 0.003558228
    Base.precompile(Tuple{typeof(add_pow!),LoopSet,Symbol,Any,Float64,Int,Int})   # time: 0.003542577
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}, Int, VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}}})   # time: 0.003530142
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003522953
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{1}}})   # time: 0.003478515
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}, Int, VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.003474451
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{4}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003459242
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{StaticInt{4}, StaticInt{4}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003453013
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{1}}})   # time: 0.003451803
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{StaticInt{8}, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003370297
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{1, Tuple{StaticInt{1}}}, Int, VectorizationBase.CartesianVIndex{3, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}}}})   # time: 0.003369487
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, -1, 0, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{0}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003363417
    Base.precompile(Tuple{typeof(repeated_index!),LoopSet,Vector{Symbol},Symbol,Int,Int})   # time: 0.003356449
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{StaticInt{292}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003346945
    Base.precompile(Tuple{typeof(pushgespind!),Expr, LoopSet, Symbol, Int, Int, Symbol, Bool, Bool, Bool})   # time: 0.003310727
    Base.precompile(Tuple{typeof(maybeaddref!),LoopSet,Operation})   # time: 0.003291367
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 3, 1, 0, (1, 2, 3), Tuple{StaticInt{8}, StaticInt{16}, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}})   # time: 0.003288427
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{StaticInt{308}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003276252
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 2, 0, (2, 1), Tuple{StaticInt{584}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.00325154
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, StaticInt{0}}})   # time: 0.003241388
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{StaticInt{584}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003234866
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{StaticInt{616}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003233919
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 2, 0, (2, 1), Tuple{StaticInt{292}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003196001
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{584}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003185854
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, StaticInt{292}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003182693
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 3), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.003164367
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, -1, 0, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{0}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003163087
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{StaticInt{276}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003146812
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 3, 2, 0, (3, 1, 4), Tuple{Int, StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}, Int}})   # time: 0.003142811
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{32}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003069923
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{StaticInt{552}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003055035
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{8}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.003049445
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{4}}, Tuple{Int, Int}},Tuple{Int, Int}})   # time: 0.003025853
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.003021861
    Base.precompile(Tuple{typeof(add_reduced_deps!),Operation,Vector{Symbol}})   # time: 0.003020774
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 3), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.003014529
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{584}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.003000713
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.002980572
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002975903
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.002956895
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, -1, 0, (2, 4), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, Int}})   # time: 0.002948314
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{616}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002943787
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 2, 0, (2, 1), Tuple{StaticInt{276}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002935012
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{16}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002934243
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, Int}})   # time: 0.002930976
    # Base.precompile(Tuple{typeof(gespf1),Any,Tuple{Any, Any}})   # time: 0.002917722
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, StaticInt{308}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002916809
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002914504
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, StaticInt{292}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002904719
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{8}}, Tuple{Int, Int}},Tuple{Int, Int}})   # time: 0.002874846
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002871775
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 2, 0, (2, 1), Tuple{StaticInt{552}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002871509
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.00287062
    Base.precompile(Tuple{typeof(determine_eltype),LoopSet,Bool})   # time: 0.002857631
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 2, 0, (2, 1), Tuple{StaticInt{616}, StaticInt{8}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.00284876
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 2, 0, (2, 1), Tuple{StaticInt{308}, StaticInt{4}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002817789
    # Base.precompile(Tuple{typeof(gespf1),Any,Tuple{Any, StaticInt{1}}})   # time: 0.00281579
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002805837
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 2, 0, (2, 1, 4, 3), Tuple{Int, StaticInt{8}, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}}})   # time: 0.002797653
    Base.precompile(Tuple{typeof(add_operation!),LoopSet,Symbol,Expr,ArrayReferenceMetaPosition,Int,Int})   # time: 0.002766816
    Base.precompile(Tuple{typeof(zerorangestart),ArrayInterface.OptionallyStaticStepRange{StaticInt{1}, StaticInt{2}, Int}})   # time: 0.002759321
    Base.precompile(Tuple{typeof(add_affine_index_expr!),LoopSet,Vector{Tuple{Int, Symbol}},Base.RefValue{Int},Int,Expr})   # time: 0.002751373
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 3), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int, Int}})   # time: 0.002712218
    # Base.precompile(Tuple{typeof(which(and_last,(VectorizationBase.VecUnroll{N, W, T, V} where {W, T, V<:Union{Bool, Float32, Float64, Int16, Int32, Int, Int8, UInt16, UInt32, UInt, UInt8, VectorizationBase.Bit, VectorizationBase.AbstractSIMD{W, T}}},Any,)).generator.gen),Any,Any,Any,Any})   # time: 0.002708064
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002685528
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{616}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002673526
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, -1, -1, (1, 2), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.00266138
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, StaticInt{308}}, Tuple{StaticInt{0}, StaticInt{0}}},Tuple{StaticInt{0}, StaticInt{0}}})   # time: 0.002643247
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{Int, Int}},Tuple{Int, VectorizationBase.NullStep}})   # time: 0.002632806
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 3, 2, 0, (2, 1, 4), Tuple{Int, StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}, Int}})   # time: 0.002631182
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 3, 1, 0, (1, 2, 3), Tuple{StaticInt{8}, Int, Int}, Tuple{StaticInt{1}, StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}, Int}})   # time: 0.002629904
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (3, 1), Tuple{Int, StaticInt{8}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002626165
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{1}}},Tuple{Int}})   # time: 0.002618406
    Base.precompile(Tuple{typeof(isscopedname),Expr,Tuple{Symbol, Symbol, Symbol},Symbol})   # time: 0.002615843
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{0}}},Tuple{StaticInt{1}}})   # time: 0.002601953
    Base.precompile(Tuple{typeof(instruction!),LoopSet,Expr})   # time: 0.00246603
    Base.precompile(Tuple{typeof(setdiffv!),Vector{Symbol},Vector{Symbol},Vector{Symbol},SubArray{Symbol, 1, Vector{Symbol}, Tuple{UnitRange{Int}}, true}})   # time: 0.002460923
    Base.precompile(Tuple{typeof(add_constant!),LoopSet,ArrayReferenceMetaPosition,Int})   # time: 0.002440372
    Base.precompile(Tuple{typeof(add_parent!),Vector{Operation},Vector{Symbol},Vector{Symbol},LoopSet,Float64,Int,Int})   # time: 0.002383377
    Base.precompile(Tuple{typeof(expandbyoffset!),Vector{Int},Vector{Any},Vector{Int}})   # time: 0.002380565
    Base.precompile(Tuple{typeof(expandbyoffset!),Vector{Tuple{Int, Float64}},Vector{Any},Vector{Int}})   # time: 0.002357554
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{3}}})   # time: 0.002355627
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002336967
    Base.precompile(Tuple{typeof(muladd_arguments!),Vector{Any},Nothing,Expr})   # time: 0.002320718
    Base.precompile(Tuple{Type{Loop},LoopSet,Expr,Symbol,Type{OptionallyStaticUnitRange{StaticInt{0}, Int}}})   # time: 0.002317385
    Base.precompile(Tuple{typeof(add_reduction!),LoopSet,Symbol,Vector{Symbol},Vector{Symbol},Vector{Operation},Int,Int,Instruction})   # time: 0.00230198
    Base.precompile(Tuple{typeof(expandbyoffset!),Vector{Tuple{Int, NumberType}},Vector{Any},Vector{Int}})   # time: 0.002288319
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{40}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002272713
    Base.precompile(Tuple{typeof(add_store_ref!),LoopSet,Int,Expr,Int})   # time: 0.002250145
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, StaticInt{24}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.002238958
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002226253
    Base.precompile(Tuple{typeof(prepare_rhs_for_storage!),LoopSet,Expr,Symbol,SubArray{Any, 1, Vector{Any}, Tuple{UnitRange{Int}}, true},Int,Int})   # time: 0.002213321
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002195557
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, -1, -1, (2, 3), Tuple{Int, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.002188151
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{8}, StaticInt{16}, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{StaticInt{1}, VectorizationBase.NullStep, StaticInt{1}, VectorizationBase.NullStep}})   # time: 0.002117393
    Base.precompile(Tuple{typeof(zerorangestart),ArrayInterface.OptionallyStaticStepRange{StaticInt{1}, StaticInt{4}, Int}})   # time: 0.002105125
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{1}}})   # time: 0.002098497
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{3}}})   # time: 0.002074802
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{8}}, Tuple{Int, Int}},Tuple{StaticInt{1}}})   # time: 0.002056658
    Base.precompile(Tuple{typeof(misc_loop!),LoopSet,Expr,Symbol,Bool})   # time: 0.002042004
    Base.precompile(Tuple{typeof(add_compute_ifelse!),LoopSet,Symbol,Operation,Operation,Operation,Int})   # time: 0.002028759
    Base.precompile(Tuple{typeof(substitute_ops_all!),LoopSet,Int,Int,Operation,Operation,Vector{ArrayReferenceMeta},Vector{Int},Vector{Vector{Tuple{Int, Int, Int}}}})   # time: 0.002017575
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{0}}})   # time: 0.002004319
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{0}}})   # time: 0.001979018
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{3}}})   # time: 0.00197391
    # Base.precompile(Tuple{typeof(gespf1),StridedBitPointer{1, 1, 0, (1,), Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.001972721
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{3}}})   # time: 0.001924342
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{Int}})   # time: 0.001891342
    # Base.precompile(Tuple{typeof(gespf1),StridedBitPointer{2, 1, 0, (1, 2), Tuple{StaticInt{1}, Int}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.001850312
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{0}, StaticInt{1}}})   # time: 0.001846808
    Base.precompile(Tuple{Type{Loop},LoopSet,Expr,Symbol,Type{UnitRange{Int}}})   # time: 0.001817677
    Base.precompile(Tuple{typeof(matches),Operation,Operation})   # time: 0.001813882
    Base.precompile(Tuple{typeof(register_single_loop!),LoopSet,Expr})   # time: 0.001800988
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 1, 1, 0, (1,), Tuple{StaticInt{4}}, Tuple{StaticInt{1}}},Tuple{StaticInt{2}}})   # time: 0.001792139
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 2, 0, (2, 1), Tuple{Int, StaticInt{4}}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.00176126
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{Int}},Tuple{StaticInt{1}}})   # time: 0.001726697
    Base.precompile(Tuple{typeof(misc_loop!),LoopSet,Symbol,Symbol,Bool})   # time: 0.001717844
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{StaticInt{2}}})   # time: 0.001668273
    Base.precompile(Tuple{typeof(canonicalize_range),Base.OneTo{Int}})   # time: 0.001668198
    Base.precompile(Tuple{typeof(oneto_loop!),LoopSet,Expr,Symbol})   # time: 0.001664069
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{StaticInt{2}}})   # time: 0.001663897
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 5, 1, 0, (1, 2, 3, 4, 5), Tuple{StaticInt{8}, Int, Int, Int, Int}, NTuple{5, StaticInt{1}}},NTuple{5, StaticInt{1}}})   # time: 0.001649866
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 3), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{2, Tuple{StaticInt{1}, StaticInt{1}}}}})   # time: 0.001643936
    Base.precompile(Tuple{typeof(add_store!),LoopSet,ArrayReferenceMetaPosition,Int,Operation})   # time: 0.001619148
    Base.precompile(Tuple{typeof(resize!),LoopOrder,Int})   # time: 0.001618816
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 1, 1, 0, (1,), Tuple{StaticInt{4}}, Tuple{StaticInt{1}}},Tuple{StaticInt{2}}})   # time: 0.001605462
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{VectorizationBase.NullStep, StaticInt{1}}})   # time: 0.001593335
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{Int, Int}},Tuple{Int, Int}})   # time: 0.00159325
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{0}}},Tuple{StaticInt{1}}})   # time: 0.00157471
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{Int, Int}},Tuple{StaticInt{1}}})   # time: 0.001573911
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.00156717
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 1, -1, 0, (2,), Tuple{Int}, Tuple{StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.001561825
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, StaticInt{1}}})   # time: 0.001549125
    # Base.precompile(Tuple{typeof(which(gespf1,(VectorizationBase.StridedPointer{T, N, C, B, R},Tuple{I<:Integer},)).generator.gen),Any,Any,Any,Any,Any,Any,Any,Any,Any})   # time: 0.001528048
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.001527828
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{Int, Int}},Tuple{Int, Int}})   # time: 0.001521008
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int, 1, 1, 0, (1,), Tuple{StaticInt{8}}, Tuple{StaticInt{1}}},Tuple{Int}})   # time: 0.001514603
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Int32, 1, 1, 0, (1,), Tuple{StaticInt{4}}, Tuple{StaticInt{1}}},Tuple{Int}})   # time: 0.001495353
    Base.precompile(Tuple{typeof(_addoffset!),Expr,MaybeKnown,Int,Expr,Int,Bool})   # time: 0.001481168
    Base.precompile(Tuple{typeof(contract!),Expr,Expr,Int,Nothing})   # time: 0.001449395
    Base.precompile(Tuple{typeof(tryrefconvert),LoopSet,Expr,Int,Symbol})   # time: 0.001434435
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int}})   # time: 0.001407814
    Base.precompile(Tuple{typeof(append_update_args),Symbol,Expr})   # time: 0.001406569
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 1, 1, 0, (1,), Tuple{StaticInt{4}}, Tuple{StaticInt{1}}},Tuple{Int}})   # time: 0.001404321
    Base.precompile(Tuple{typeof(symbolind),Symbol,Operation,UnrollArgs,LoopSet})   # time: 0.001402186
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{Int}})   # time: 0.001394523
    Base.precompile(Tuple{typeof(isunrolled_sym),Operation,Symbol,Symbol,Symbol,Tuple{Bool, Bool}})   # time: 0.001386395
    Base.precompile(Tuple{typeof(search_tree_for_ref),LoopSet,Vector{Operation},ArrayReferenceMetaPosition,Symbol})   # time: 0.001383476
    # Base.precompile(Tuple{var"##s450#184",Any,Any,Any,Any,Any})   # time: 0.001382675
    Base.precompile(Tuple{typeof(findindoradd!),Vector{Symbol},Symbol})   # time: 0.001373309
    Base.precompile(Tuple{typeof(muladd_arguments!),Vector{Any},Nothing,Symbol})   # time: 0.001361646
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}}})   # time: 0.001303002
    Base.precompile(Tuple{typeof(isscopedname),Expr,Tuple{Symbol, Symbol},Symbol})   # time: 0.00127083
    Base.precompile(Tuple{typeof(shifted_loopset),LoopSet,Vector{Symbol}})   # time: 0.001262823
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 4, 1, 0, (1, 2, 3, 4), Tuple{StaticInt{8}, Int, Int, Int}, NTuple{4, StaticInt{1}}},Tuple{VectorizationBase.CartesianVIndex{4, NTuple{4, StaticInt{1}}}, VectorizationBase.CartesianVIndex{0, Tuple{}}}})   # time: 0.001229815
    Base.precompile(Tuple{typeof(check_if_empty),LoopSet,Expr})   # time: 0.00120539
    Base.precompile(Tuple{typeof(tuple_expr),typeof(identity),Vector{Tuple{Int, Float64}}})   # time: 0.001184502
    Base.precompile(Tuple{typeof(tuple_expr),typeof(identity),Vector{Tuple{Int, Tuple{Int, Int32, Bool}}}})   # time: 0.001174772
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float32, 2, 1, 0, (1, 2), Tuple{StaticInt{4}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, Int}})   # time: 0.001161233
    Base.precompile(Tuple{typeof(gespf1),StridedPointer{Float64, 2, 1, 0, (1, 2), Tuple{StaticInt{8}, Int}, Tuple{StaticInt{1}, StaticInt{1}}},Tuple{StaticInt{1}, Int}})   # time: 0.001156726
    Base.precompile(Tuple{typeof(loop_boundary!),Expr,LoopSet,Loop,Bool})   # time: 0.001152516
    Base.precompile(Tuple{typeof(maybestatic!),Expr})   # time: 0.001151616
    Base.precompile(Tuple{typeof(tuple_expr),typeof(identity),Vector{Tuple{Int, NumberType}}})   # time: 0.001148223
    Base.precompile(Tuple{typeof(mulexpr),SubArray{Any, 1, Vector{Any}, Tuple{UnitRange{Int}}, true}})   # time: 0.001105523
    Base.precompile(Tuple{typeof(prepend_lnns!),Expr,Vector{LineNumberNode},Val{:block}})   # time: 0.001050358
    Base.precompile(Tuple{typeof(maybe_const_compute!),LoopSet,Symbol,Operation,Int,Int})   # time: 0.001042495
    Base.precompile(Tuple{typeof(add_store_ref!),LoopSet,Float64,Expr,Int})   # time: 0.00104186
    Base.precompile(Tuple{typeof(zerorangestart),OptionallyStaticUnitRange{StaticInt{1}, StaticInt{5}}})   # time: 0.001031162
    Base.precompile(Tuple{typeof(determine_width),LoopSet,Nothing})   # time: 0.001024268
    Base.precompile(Tuple{typeof(choose_order),LoopSet})   # time: 0.001016861
    Base.precompile(Tuple{typeof(capture_a_muladd),Expr,Nothing})   # time: 0.001010088
    Base.precompile(Tuple{typeof(canonicalize_range),CartesianIndices{4, NTuple{4, Base.OneTo{Int}}}})   # time: 0.001000169

  Base.precompile(reduce_expr!, (Expr, LoopSet, Int))
end


text:
using Flux:Dense,Chain
using Flux:destructure,params
using Zygote:Params,Grads
using Zygote:jacobian

### struct for defining the Muller-Brown potential
mutable struct NNModel <: AbstractSinglePotential
  dim::Int64
  pars::Params
  pinfo::Vector{Tuple{Int64, Vararg{Int64, N} where N}}
  nn::Union{Chain,Dense}
  re::Any
  theta::Vector
  f::Vector{Float64}
  function NNModel(dim::Int64,nn::Union{Chain,Dense})
    pars = params(nn)
    pinfo = [size(p_) for p_ in pars]
    th,re = destructure(nn)
    new(dim,pars,pinfo,nn,re,th,zeros(Float64,dim))
  end
end

function getdimensionality(nnm::NNModel)
  return nnm.dim
end

function jacshape(nnm::NNModel)
  return (size(nnm.theta)[1],nnm.dim)
end

function gradshape(nnm::NNModel)
  return size(nnm.theta)[1]
end

"""
Force function with return value
"""
function force(sys::AbstractSystem, nnm::NNModel)
  f::Vector{Float64} = nnm.nn(push!(sys.x,sys.t))
  pop!(sys.x)
  return f
end

"""
Force function with in-place changing
"""
function force!(sys::AbstractSystem, nnm::NNModel)
  nnm.f .= nnm.nn(push!(sys.x,sys.t))
  pop!(sys.x)
end

"""
Jacobian wrt parameters for neural network model
"""
function jacobian!(jac::Array{Float64},sys::AbstractSystem,nnm::NNModel)
  # compute gradients of output wrt parametes
  push!(sys.x,sys.t)
  grads::Grads = jacobian(() -> nnm.nn(sys.x), nnm.pars)
  pop!(sys.x)
  # store gradients into jacobian array
  bcount::Int64 = 1
  for i in 1:length(nnm.pars)
    # TODO replace with reduce function
    ptup::Tuple = nnm.pinfo[i]
    ecount::Int64 = 1
    for j in 1:length(ptup)
      ecount *= ptup[j]
    end
    ecount += (bcount - 1)
    @. @views jac[bcount:ecount,:] .= grads[nnm.pars[i]]'
    bcount = ecount + 1
  end
end

"""
Update parameters for the neural network model
"""
function updateparams!(lr::Float64,dtheta::Vector{Float64},nnm::NNModel)
    # update coefficients for forces
    nnm.theta .+= (lr .* dtheta)
    setparams!(nnm)
end

"""
Set parameters for the neural network model
"""
function setparams!(nnm::NNModel)
    # update coefficients for forces
    nnm.nn = nnm.re(nnm.theta)
    nnm.pars = params(nnm.nn)
end

function setparams!(theta::Vector{Float64},nnm::NNModel)
    # update coefficients for forces
    nnm.theta .= theta
    setparams!(nnm)
end

#"""
#Gradient wrt parameters for neural network model
#"""
#function gradient!(grad::Array{Float64},sys::AbstractSystem,nnm::NNModel)
#  grad = jacobian(() -> model(x), p)
#  pop!(sys.x)
#  val::Float64 = 0.0
#  for i in 1:gm.nx
#    val = exp(-0.5*(sys.x[1]-gm.mux[i])^2/gm.sigx[i])
#    @. @views grad[i,:,:] .= val
#  end
#  for i in 1:gm.ny
#    val = exp(-0.5*(sys.x[2]-gm.muy[i])^2/gm.sigy[i])
#    @. @views grad[:,i,:] .*= val
#  end
#  for i in 1:gm.nt
#    val = exp(-0.5*(sys.t-gm.mut[i])^2/gm.sigt[i])
#    @. @views grad[:,:,i] .*= val
#  end
#end


text:
leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1)

@show leftfactorial.(0:10)
@show ndigits.(leftfactorial.(big.(1000:1000:10_000)))

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
struct Vocab
    w2i::Dict{String,Int}
    i2w::Vector{String}
    unk::Int
    eos::Int
    tokenizer
end

function Vocab(file::String; tokenizer=split, vocabsize=Inf, mincount=1, unk="<unk>", eos="<s>")
    cnt = Dict{String,Int}()
    for line in eachline(file)
        for word in tokenizer(line)
            cnt[word] = 1 + get(cnt, word, 0)
        end
    end
    delete!(cnt, unk); delete!(cnt, eos)
    words = sort!(collect(keys(cnt)); by=(w->cnt[w]), rev=true)
    if mincount > 1; i=findfirst(w -> cnt[w]<mincount, words); i!==nothing && (words=words[1:i-1]); end
    if unk != nothing; pushfirst!(words, unk); end
    if eos != nothing; pushfirst!(words, eos); end
    if length(words) > vocabsize; words = words[1:vocabsize]; end
    vocab = Dict(words[i] => i for i in 1:length(words))
    Vocab(vocab, words, get(vocab,unk,0), get(vocab,eos,0), tokenizer)
end

max_stars_repo_name: denizyuret/research

max_issues_repo_name: denizyuret/research

max_forks_repo_name: denizyuret/research


text:
import ScikitSpatial: Vector

@testset "Vector from two points" begin
    @test Vector([0, 0], [0, 0]) == [0, 0]
    @test Vector([0, 0], [1, 0]) == [1, 0]
    @test Vector([1, 0, 1], [0, 0, 5]) == [-1, 0, 4]
end

@testset "Unit" begin
    for (vector, vector_unit_expected) in [
        ([1, 0], [1, 0])
        ([2, 0], [1, 0])
        ([5, 0], [1, 0])
        ([-5, 0], [-1, 0])
        ([1, 1], √2 / 2 * ones(2))
        ([1, 1, 1], √3 / 3 * ones(3))
    ]
        @test unit(vector) ≈ vector_unit_expected
    end
end

@testset "Centroid of points" begin
    points = [
        0 1;
        0 0;
    ]
    centroid_  = centroid(points)

    # Use type assertion to ensure centroid is a vector (not matrix).
    centroid_::AbstractVector

    @test centroid_ == [0.5, 0]

    points = [
        0 1 2;
        -1 3 5;
    ]
    @test centroid(points) ≈ [1, 7/3]

    points = [
        0 1 2;
        -1 3 5;
        2 5 9;
    ]
    @test centroid(points) ≈ [1, 7/3, 16/3]
end

@testset "Mean center points" begin

    points = [
        1 2 3;
        0 1 2;
    ]
    points_centered_expected = [
        -1 0 1;
        -1 0 1;
    ]

    @test mean_center(points) == points_centered_expected

    points = [
        -2 4;
        0 1;
        2 -3;
        5 2;
    ]
    points_centered_expected = [
        -3 3;
        -0.5 0.5;
        2.5 -2.5;
        1.5 -1.5;
    ]
    @test mean_center(points) == points_centered_expected
end

@testset "To point" begin
    line = Line([0, 0], [1, 0])

    @test to_point(line) == [1, 0]
    @test to_point(line; t=1) == [1, 0]
    @test to_point(line; t=2) == [2, 0]
    @test to_point(line; t=-1) == [-1, 0]

    line = Line([1, 2, 3], [1, 2, 3])

    @test to_point(line) == [2, 4, 6]
    @test to_point(line; t=1) == [2, 4, 6]
    @test to_point(line; t=2) == [3, 6, 9]
    @test to_point(line; t=-1) == [0, 0, 0]
end


text:
struct Pyramid{T} <: GeometryPrimitive{3,T}
    middle::Point{3,T}
    length::T
    width::T
end

function coordinates(p::Pyramid{T}) where {T}
    leftup = Point{3,T}(-p.width, p.width, 0) / 2
    leftdown = Point(-p.width, -p.width, 0) / 2
    tip = Point{3,T}(p.middle + Point{3,T}(0, 0, p.length))
    lu = Point{3,T}(p.middle + leftup)
    ld = Point{3,T}(p.middle + leftdown)
    ru = Point{3,T}(p.middle - leftdown)
    rd = Point{3,T}(p.middle - leftup)
    return Point{3,T}[tip, rd, ru, tip, ru, lu, tip, lu, ld, tip, ld, rd, rd, ru, lu, lu,
                      ld, rd]
end

function faces(::Pyramid)
    return (TriangleFace(triangle) for triangle in TupleView{3}(1:18))
end


text:
using XGBoost

const DATAPATH = joinpath(@__DIR__, "../data")
dtrain = DMatrix(joinpath(DATAPATH, "agaricus.txt.train"))
dtest = DMatrix(joinpath(DATAPATH, "agaricus.txt.test"))
watchlist  = [(dtest,"eval"), (dtrain,"train")]

###
# advanced: start from a initial base prediction
##

print("start running example to start from a initial prediction\n")
param = ["max_depth"=>2, "eta"=>1, "silent"=>1, "objective"=>"binary:logistic"]

bst = xgboost(dtrain, 1, param=param, watchlist=watchlist)
# Note: we need the margin value instead of transformed prediction in set_base_margin
# do predict with output_margin=True, will always give you margin values before logistic transformation

ptrain = predict(bst, dtrain, output_margin=true)
ptest  = predict(bst, dtest, output_margin=true)

# set the base_margin property of dtrain and dtest
# base margin is the base prediction we will boost from

set_info(dtrain, "base_margin", ptrain)
set_info(dtest, "base_margin", ptest)

watchlist  = [(dtest,"eval2"), (dtrain,"train2")]
print("this is result of running from initial prediction\n")

bst = xgboost(dtrain, 1, param=param, watchlist=watchlist)


text:
#Adapated from PyCLES: https://github.com/pressel/pycles
const Pr0 = 0.74
const beta_m = 4.8
const beta_h = 6.5 # beta_h = beta_m / Pr0
const gamma_m = 15.0
const gamma_h = 9.0
# CLIMA microphysics parameters
const rho_cloud_liq = 1e3


text:
struct K_Vector{t,C,T} <: AbstractVector{T}
    a::Vector{C}
    function K_Vector{t,C,T}(x::K_) where {t,C,T}
        a = asarray(x)
        t′ = xt(x)
        if t != t′
            throw(ArgumentError("type mismatch: t=$t, t′=$t′"))
        end
        return new(a)
    end
end
ktypecode(::K_Vector{t,C,T}) where {t,C,T} = t
const K_Chars = K_Vector{C_(10),G_,UInt8}
Base.convert(::Type{String}, x::K_Chars) = String(x.a)
Base.print(io::IO, x::K_Chars) = print(io, String(x))
Base.show(io::IO, x::K_Chars) = print(io, "K(", repr(String(x)), ")")
Base.show(io::IO, ::MIME"text/plain", x::K_Chars) = show(io, x)
Base.serialize(io::AbstractSerializer, x::K_Vector) =
    _serialize(io, x, typeof(x))
function K_Vector(x::K_)
    t = xt(x)
    ti = typeinfo(t)
    K_Vector{t,ti.c_type,ti.jl_type}(x)
end
const KnownLength = Union{Base.HasLength, Base.HasShape}
_vector(t::Integer, n::Integer) = K_Vector(ktn(t, n))
_vector(::Type{T}, n::Integer) where T = _vector(ktypecode(T), n)
_vector(t::Integer, itr, ::KnownLength) =
    (r = _vector(t, Int(length(itr)::Integer));copy!(r, itr);r)
K_Vector{t,C,T}(itr) where {t,C,T} =
    _vector(t, itr, Base.iteratorsize(itr))::K_Vector{t,C,T}
# XXX: Do we need this?
K_Vector(a::Vector) = K_Vector(K(a))

Base.eltype(v::K_Vector{t,C,T}) where {t,C,T} = T
Base.size(v::K_Vector{t,C,T}) where {t,C,T} = size(v.a)
Base.getindex(v::K_Vector{t,C,T}, i::Integer) where {t,C,T} = _cast(T, v.a[i])
# Setting the vector elements
Base.setindex!(v::K_Vector{t,C,T}, el, i::Integer) where {t,C,T} = begin
    v.a[i] = _cast(C, T(el))
    v
end

# See julia.h.
struct jl_array_t
    data   :: Ptr{Void} # (1)  sizeof(Ptr)
    length :: Csize_t   # (2) + sizeof(Ptr)
    flags  :: UInt16    # (3) + 2 bytes
    elsize :: UInt16    # (4) + 2 bytes
    offset :: UInt32    # (5) + 4 bytes
    nrows  :: Csize_t   # (6) = at 2*sizeof(Ptr) + 8
    maxsize:: Csize_t   # (7)
end

const offset_length = fieldoffset(jl_array_t, 2)
const offset_nrows = fieldoffset(jl_array_t, 6)

function resetvector(a::Vector, size::Integer, data::Ptr)
    p = Ptr{jl_array_t}(pointer_from_objref(a))
    # Pre-checks
    d = unsafe_load(p)
    @assert d.data == pointer(a)
    @assert d.length == d.nrows == length(a)
    # replant the data pointer
    unsafe_store!(Ptr{Ptr{Void}}(p), data)
    # update the size
    unsafe_store!(Ptr{Csize_t}(p + offset_length), size)
    unsafe_store!(Ptr{Csize_t}(p + offset_nrows), size)
    # Post-checks
    d = unsafe_load(p)
    @assert d.data == pointer(a)
    @assert d.length == d.nrows == length(a) == size
end

# ⚠ Extending vectors
function Base.push!(x::K_Vector{t,C,T}, y) where {t,C,T}
    n′ = length(x) + 1
    a = _cast(C, T(y))
    p = kpointer(x)
    p′ = ja(Ref{K_}(p), Ref(a))
    resetvector(x.a, n′, p′+16)
    x
end
function Base.append!(x::K_Vector{t,C,T}, y::K_Vector{t,C,T}) where {t,C,T}
    n′ = length(x) + length(y)
    px = kpointer(x)
    py = kpointer(y)
    p′ = jv(Ref{K_}(px), py)
    resetvector(x.a, n′, p′+16)
    x
end
Base.append!(x::K_Vector{t,C,T}, y) where {t,C,T} =
    append!(x, K_Vector{t,C,T}(y))
function Base.empty!(x::K_Vector{t,C,T}) where {t,C,T}
    p = kpointer(x)
    p′ = ktn(t, 0)
    resetvector(x.a, 0, p′+16)
    r0(p)
    x
end


text:
export cost, max_degree, depth, balance

indices(c::ContractCommand) = c.left_idxs, c.right_idxs, c.output_idxs

cost(c::AbstractCommand) = 0

"""
    cost(cmd::ContractCommand)::Number

Function to calculate the cost of the given contraction in FLOPS
"""
function cost(cmd::ContractCommand)::Number
    a, b, c = indices(cmd)
    batched_idxs = intersect(a, b, c)
    a = setdiff(a, batched_idxs)
    b = setdiff(b, batched_idxs)
    c = setdiff(c, batched_idxs)
    common = intersect(a, b)
    remaining = symdiff(a, b)
    1 << (length(common) + length(remaining) + length(batched_idxs))
end

max_degree(c::ContractCommand) = maximum(length.(indices(c)))
cost(n::ComputeNode) = cost(n.op) + sum(cost.(children(n)), init=0)
max_degree(n::ComputeNode) = maximum(max_degree.(children(n)), init=0)
max_degree(n::ComputeNode{ContractCommand}) = maximum([max_degree(n.op), max_degree.(children(n))...])
depth(n::ComputeNode) = 1 + maximum(depth.(children(n)), init=0)
Base.length(n::ComputeNode) = 1 + sum(length.(children(n)), init=0)
balance(n::ComputeNode) = ceil(log2(length(n)))/depth(n)

"""Implement show for compute node to display some useful metrics"""
function Base.show(io::IO, c::ComputeNode{T}) where T
    print(io, "ComputeNode{$(T)}: children: $(length(c)-1), ",
              "depth: $(depth(c)), balance: $(balance(c)), ",
              "max_degree: $(max_degree(c))")
end


text:
#
#  7 ---9--- 8 ---12-- 9
#
#  |         |         |
#  |         |         |
#  |         |         |
#  10   4    11   5    13
#  |         |         |
#  |         |         |
#  |         |         |
#
#  4 ---2--- 5 ---8--- 6
#
#  |         | \   3   |
#  |         |  \      |
#  |         |   \     |
#  3    1    4    6    7
#  |         |     \   |
#  |         |  2   \  |
#  |         |       \ |
#
#  1 ---1--- 2 ---5--- 3
#

                        #1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
cell_to_vertices_data = [1,2,4,5,2,3,5,3,6,5,4,5,7,8,5,6,8,9]
cell_to_vertices_ptrs = [1,      5,    8,    11,     15,    19]

                       #1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
vertex_to_cells_data = [1,1,2,2,3,1,4,1,2,3,4,5,3,5,4,4,5,5]
vertex_to_cells_ptrs = [1,2,  4,  6,  8,        13, 15,16, 18,19]

cell_to_faces_data = [1,2,3,4,5,4,6,7,6,8,2,9,10,11,8,12,11,13]
cell_to_faces_ptrs = [1,5,8,11,15,19]

quad_to_lface_to_lvertices = [[1,2],[3,4],[1,3],[2,4]]

tri_to_lface_to_lvertices = [[1,2],[1,3],[2,3]]

quad_to_lface_to_ftype = [1,1,1,1]
tri_to_lface_to_ftype = [2,2,2]

quad = 1
tri = 2
cell_to_ctype = [quad, tri, tri, quad, quad]

ctype_to_lface_to_lvertices = [
  quad_to_lface_to_lvertices, tri_to_lface_to_lvertices]

ctype_to_lface_to_ftype = [quad_to_lface_to_ftype, tri_to_lface_to_ftype]

face_to_ftype = [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1]

face_to_vertices_data = [1,2,4,5,1,4,2,5,2,3,3,5,3,6,6,5,7,8,4,7,5,8,8,9,6,9]
face_to_vertices_ptrs = [1,3,5,7,9,11,13,15,17,19,21,23,25,27]

face_to_isboundary = Bool[true, false, true, false, true, false, true, false, true, true, false, true, true]

vertex_to_isboundary = Bool[true, true, true, true, false, true, true, true, true]


text:
compactness(ls::Union{LinkStream,DirectedLinkStream})=1.0

function compactness(s::Union{StreamGraph,DirectedStreamGraph})
    throw("Not Yet Implemented...")
end


text:
# Load the shape files
mexicopath = joinpath(testdatapath, "shape_eg_data", "mexico")
states = open_shapefile(joinpath(mexicopath, "states.shp"))
cities = open_shapefile(joinpath(mexicopath, "cities.shp"))
rivers = open_shapefile(joinpath(mexicopath, "rivers.shp"))

# Create plots and test whether they output a Compose.Context (i.e. check if they run)

# Test polygon
canvas1 = plotshape(states)
test1 = (typeof(canvas1) == Compose.Context)

# Test point
canvas2 = plotshape(cities, canvas1, line_width=0.25mm, line_color="red", fill_color=RGB(1,1,0), radius=[0.05cm])
test2 = (typeof(canvas2) == Compose.Context)

# Test polyline
canvas3 = plotshape(rivers, canvas2, line_color=RGB(0.2,0.6,0.8), line_width=0.25mm)
test3 = (typeof(canvas3) == Compose.Context)

# Return
test1 && test2 && test3


text:
@testset "Renewable data misspecification" begin
    # See https://discourse.julialang.org/t/how-to-use-test-warn/15557/5 about testing for warning throwing
    info_message = "The data doesn't include devices of type RenewableDispatch, consider changing the device models"
    device_model = DeviceModel(RenewableDispatch, RenewableFullDispatch)
    c_sys5 = PSB.build_system(PSITestSystems, "c_sys5")
    model = DecisionModel(MockOperationProblem, DCPPowerModel, c_sys5)
    @test_logs (:info, info_message) match_mode = :any mock_construct_device!(
        model,
        device_model,
    )
end

@testset "Renewable DCPLossLess FullDispatch" begin
    device_model = DeviceModel(RenewableDispatch, RenewableFullDispatch)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, DCPPowerModel, c_sys5_re)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 72, 0, 72, 0, 0, false)
    psi_checkobjfun_test(model, GAEVF)
end

@testset "Renewable ACPPower Full Dispatch" begin
    device_model = DeviceModel(RenewableDispatch, RenewableFullDispatch)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, ACPPowerModel, c_sys5_re;)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 144, 0, 144, 72, 0, false)
    psi_checkobjfun_test(model, GAEVF)
end

@testset "Renewable DCPLossLess Constantpower_factor" begin
    device_model = DeviceModel(RenewableDispatch, RenewableConstantPowerFactor)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, DCPPowerModel, c_sys5_re)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 72, 0, 72, 0, 0, false)
    psi_checkobjfun_test(model, GAEVF)
end

@testset "Renewable ACPPower Constantpower_factor" begin
    device_model = DeviceModel(RenewableDispatch, RenewableConstantPowerFactor)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, ACPPowerModel, c_sys5_re;)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 144, 0, 72, 0, 72, false)
    psi_checkobjfun_test(model, GAEVF)
end

@testset "Renewable DCPLossLess FixedOutput" begin
    device_model = DeviceModel(RenewableDispatch, FixedOutput)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, DCPPowerModel, c_sys5_re;)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 0, 0, 0, 0, 0, false)
    psi_checkobjfun_test(model, GAEVF)
end

@testset "Renewable ACPPowerModel FixedOutput" begin
    device_model = DeviceModel(RenewableDispatch, FixedOutput)
    c_sys5_re = PSB.build_system(PSITestSystems, "c_sys5_re")
    model = DecisionModel(MockOperationProblem, ACPPowerModel, c_sys5_re;)
    mock_construct_device!(model, device_model)
    moi_tests(model, false, 0, 0, 0, 0, 0, false)
    psi_checkobjfun_test(model, GAEVF)
end


text:
module CellNumberApplyTests

using Test
using Gridap
using ..CellValuesMocks
using StaticArrays
using TensorValues

l = 10

ax = [1.2, SVector(1.3,2.0), VectorValue(1.3,2.0), VectorValue(1.3,2.0)]
bx = [1, SVector(1.3,2.3), VectorValue(1.1,2.2),1]

for a in ax
  v = TestIterCellValue(a,l)
  w = apply(-,v)
  o = [ -vi for vi in v ]
  test_iter_cell_value(w,o)
end

for (a,b) in zip(ax,bx)
  u = TestIterCellValue(a,l)
  v = TestIterCellValue(b,l)
  w = apply(-,u,v)
  o = [ ui-vi for (ui,vi) in zip(u,v) ]
  test_iter_cell_value(w,o)
end

for a in [[1,2,3], SVector(1.3,2.0), VectorValue(1.3,2.0)]
  v = TestIterCellValue(a,l)
  w = apply(sum,v)
  o = [ sum(vi) for vi in v ]
  test_iter_cell_value(w,o)
end

for a in ax
  v = TestIndexCellValue(a,l)
  w = apply(-,v)
  o = [ -vi for vi in v ]
  test_index_cell_value(w,o)
end

for (a,b) in zip(ax,bx)
  u = TestIndexCellValue(a,l)
  v = TestIndexCellValue(b,l)
  w = apply(-,u,v)
  o = [ ui-vi for (ui,vi) in zip(u,v) ]
  test_index_cell_value(w,o)
end

for a in [[1,2,3], SVector(1.3,2.0), VectorValue(1.3,2.0)]
  v = TestIndexCellValue(a,l)
  w = apply(sum,v)
  o = [ sum(vi) for vi in v ]
  test_index_cell_value(w,o)
end

end # module


text: using DictFiles, HDF5, JLD


text:
### Rules
using Cassette, SparsityDetection
using SparseArrays, Test

using Cassette: tag, untag, Tagged, metadata, hasmetadata, istagged
using SparsityDetection: Path, BranchesPass, SparsityContext, Fixed,
    Input, Output, ProvinanceSet, Tainted, istainted,
    alldone, reset!, HessianSparsityContext
using SparsityDetection: TermCombination

function tester(f, Y, X, args...; sparsity=Sparsity(length(Y), length(X)))

    path = Path()
    ctx = SparsityContext(metadata=(sparsity, path), pass=BranchesPass)
    ctx = Cassette.enabletagging(ctx, f)
    ctx = Cassette.disablehooks(ctx)

    val = nothing
    while true
        val = Cassette.overdub(ctx,
                            f,
                            tag(Y, ctx, Output()),
                            tag(X, ctx, Input()),
                            map(arg -> arg isa Fixed ?
                                arg.value :
                                tag(arg, ctx, ProvinanceSet(())), args)...)
        println("Explored path: ", path)
        alldone(path) && break
        reset!(path)
    end
    return ctx, val
end

testmeta(args...) = tester(args...)[1].metadata
testval(args...) = tester(args...) |> ((ctx,val),) -> untag(val, ctx)
testtag(args...) = tester(args...) |> ((ctx,val),) -> metadata(val, ctx)

function htester(f, X, args...)

    path = Path()
    ctx = HessianSparsityContext(metadata=path, pass=BranchesPass)
    ctx = Cassette.enabletagging(ctx, f)
    ctx = Cassette.disablehooks(ctx)

    val = nothing
    while true
        val = Cassette.overdub(ctx,
                            f,
                            tag(X, ctx, Input()),
                            map(arg -> arg isa Fixed ?
                                arg.value :
                                tag(arg, ctx, one(TermCombination)), args)...)
        println("Explored path: ", path)
        alldone(path) && break
        reset!(path)
    end
    return ctx, val
end
htestmeta(args...) = htester(args...)[1].metadata
htestval(args...)  = htester(args...) |> ((ctx,val),) -> untag(val, ctx)
htesttag(args...)  = htester(args...) |> ((ctx,val),) -> metadata(val, ctx)

using Test

Base.show(io::IO, ::Type{<:Cassette.Context}) = print(io, "ctx")
Base.show(io::IO, ::Type{<:Tagged}) = print(io, "tagged")

import Base.Broadcast: broadcasted, materialize, instantiate, preprocess


text:
#!/usr/bin/env julia

push!(LOAD_PATH, "../src/")

using Documenter
import TreeLas

DocMeta.setdocmeta!(TreeLas, :DocTestSetup, :(import TreeLas);
                    recursive=true, warn=true)

makedocs(
    modules=[TreeLas],
    sitename="TreeLas",
    authors="Elias Kuthe",
    build=get(ENV, "HTML_DIR", "html"),
    clean=true,
    pages=[
        "TreeLas" => "index.md",
        "Tree Solver" => "tree_dp.md",
        "Piecewise-Linear" => "pwl.md",
        "GraphIdx" => "graphidx.index.md",
    ],
    format = Documenter.HTML(
        prettyurls = get(ENV, "CI", nothing) == "true"
    )
)

max_stars_repo_name: EQt/treelas

max_issues_repo_name: EQt/treelas

max_forks_repo_name: EQt/treelas


text:
using SparseArrays
using SparseMatrixVBCs
using LinearAlgebra
using MatrixDepot
using BenchmarkTools
using Cthulhu
using UnicodePlots
using PrettyTables
using ChainPartitioners
using InteractiveUtils

for mtx in [
            #"DIMACS10/chesapeake",
            #"HB/bcsstk04",
            "Boeing/ct20stif",

            #"Simon/raefsky4",
            #"FIDAP/ex11",
            #"Vavasis/av41092",
            #"Goodwin/rim",
            #"GHS_psdef/bmw7st_1",
            #"Williams/cop20k_A",
            #"Boeing/pwtk",
            #"Bova/rma10",
            #"GHS_psdef/s3dkq4m2",
           ]
    A = permutedims(sparse(mdopen(mtx).A))

    println()
    println()
    println(spy(A, maxwidth=50, maxheight=50, title="$mtx"))
    rows = []

    begin
        x = rand(size(A, 1))
        y = rand(size(A, 2))
        z = A' * x
        setup_time = 0.0
        mem = sizeof(A.colptr) + sizeof(A.rowval) + sizeof(A.nzval)
        run_time = time(@benchmark TrSpMV!($y, $A, $x))

        @assert y ≈ z
        push!(rows, ["reference" setup_time mem run_time 0])
    end

    w_max = 8

    limit_width(mdl) = ConstrainedCost(mdl, WidthCost(), w_max)

    mdl_blocks_1D = model_SparseMatrix1DVBC_blocks()
    mdl_memory_1D = model_SparseMatrix1DVBC_memory(eltype(A), Int)
    mdl_time_1D = model_SparseMatrix1DVBC_TrSpMV_time(w_max, eltype(A), Int, Float64)

    mdl_blocks_2D = model_SparseMatrixVBC_blocks()
    mdl_memory_2D = model_SparseMatrixVBC_memory(eltype(A), Int)
    mdl_time_2D = model_SparseMatrixVBC_TrSpMV_time(3, w_max, w_max, eltype(A), Int, Float64)

    function print_model_grid(mdl, U, W)
        R = length(mdl.β_row)
        display([sum(ChainPartitioners.block_component(mdl.β_row[r], u) * ChainPartitioners.block_component(mdl.β_col[r], w) for r = 1:R) for u = 1:U, w = 1:W])
        println()
    end

    for (key, method) in [
        ("strict", StrictChunker(w_max)),
        ("overlap", OverlapChunker(0.9, w_max)),
        ("min blocks", DynamicTotalChunker(limit_width(mdl_blocks_1D))),
        ("min memory", DynamicTotalChunker(limit_width(mdl_memory_1D))),
        ("min time", DynamicTotalChunker(limit_width(mdl_time_1D))),
    ]
        B = SparseMatrix1DVBC{w_max}(A, method)
        setup_time = time(@benchmark SparseMatrix1DVBC{$w_max}($A, $method))

        x = rand(size(A, 1))
        y = rand(size(A, 2))
        z = A' * x

        mem = sizeof(B.Φ) + sizeof(B.pos) + sizeof(B.idx) + sizeof(B.ofs) + sizeof(B.val)

        run_time = time(@benchmark mul!($y, $B', $x, true, false))

        model_time = total_value(A, B.Φ, mdl_time_1D)

        @assert y ≈ z
        push!(rows, [key setup_time mem run_time model_time])
    end

    for (key, method) in [
        ("1D 2D", AlternatingPacker(DynamicTotalChunker(limit_width(mdl_blocks_1D)), EquiChunker(1))),
        ("strict 2D", AlternatingPacker(StrictChunker(w_max), StrictChunker(w_max))),
        ("overlap 2D 0.9", AlternatingPacker(OverlapChunker(0.9, w_max), OverlapChunker(0.9, w_max))),
        ("overlap 2D 0.8", AlternatingPacker(OverlapChunker(0.8, w_max), OverlapChunker(0.8, w_max))),
        ("overlap 2D 0.7", AlternatingPacker(OverlapChunker(0.7, w_max), OverlapChunker(0.7, w_max))),
        ("dynamic blocks 2D", AlternatingPacker(
            DynamicTotalChunker(limit_width(mdl_blocks_1D)),
            DynamicTotalChunker(limit_width(permutedims(mdl_blocks_2D))),
            DynamicTotalChunker(limit_width(mdl_blocks_2D)))),
        ("dynamic memory 2D", AlternatingPacker(
            EquiChunker(1),
            EquiChunker(1),
            DynamicTotalChunker(limit_width(mdl_memory_2D)),
            DynamicTotalChunker(limit_width(permutedims(mdl_memory_2D))),
            DynamicTotalChunker(limit_width(mdl_memory_2D)),
        )),
        ("dynamic time 2D", AlternatingPacker(
            EquiChunker(1),
            EquiChunker(1),
            DynamicTotalChunker(limit_width(mdl_time_2D)),
            DynamicTotalChunker(limit_width(permutedims(mdl_time_2D))),
            DynamicTotalChunker(limit_width(mdl_time_2D)),
        )),
    ]
        B = SparseMatrixVBC{w_max, w_max}(A, method)
        setup_time = time(@benchmark SparseMatrixVBC{$w_max, $w_max}($A, $method))

        x = rand(size(A, 1))
        y = rand(size(A, 2))
        z = A' * x

        mem = sizeof(B.Φ) + sizeof(B.Π) + sizeof(B.pos) + sizeof(B.idx) + sizeof(B.ofs) + sizeof(B.val)

        run_time = time(@benchmark mul!($y, $B', $x, true, false))

        model_time = total_value(A, B.Π, B.Φ, mdl_time_2D) + ChainPartitioners.row_component_value(B.Π, mdl_time_2D)

        @assert y ≈ z
        push!(rows, [key setup_time mem run_time model_time])
    end
    pretty_table(vcat(rows...), ["method", "setuptime", "memory", "runtime", "model"])
end


text:
export CMAES, CMAES_populate, CMAES_generation, populate, evaluate, generation

# CMA-ES implementation based on pycma: https://github.com/CMA-ES/pycma
# To install it: pip install cma

import Cambrian: populate, evaluate, generation
using PyCall

mutable struct CMAES <: Cambrian.AbstractEvolution
    config::NamedTuple
    logger::CambrianLogger
    population::Array{AbstractESIndividual}
    elites::Array{AbstractESIndividual}
    state::Array{Float64}
    fitness::Function
    gen::Int
    pycma::PyObject
end

function CMAES(cfg::NamedTuple, fitness::Function, state::Array{Float64}; T::Type=ESIndividual ,logfile=string("logs/", cfg.id, ".csv"))
    cma = pyimport("cma")
    pycma = cma.CMAEvolutionStrategy(state, cfg.m_rate)
    logger = CambrianLogger(logfile)
    e = CMAES(cfg, logger, [], [], state, fitness, 0, pycma)
    CMAES_populate(e, T)
    e.elites = deepcopy([e.population[i] for i in 1:cfg.n_elite])
    e
end

function CMAES(cfg::NamedTuple, fitness::Function;  T::Type=ESIndividual, logfile=string("logs/", cfg.id, ".csv"))
    logger = CambrianLogger(logfile)
    state = zeros(cfg.n_genes)
    CMAES(cfg, fitness, state; T=T, logfile=logfile)
end

"get next population from pycma and create Cambrian individuals"
function CMAES_populate(e::CMAES, T::Type)
    solutions = e.pycma.ask()
    e.config = merge((n_population=length(solutions), ), e.config)
    e.population=[T(s, -Inf*ones(e.config.d_fitness)) for s in solutions]
end

"get next population from pycma and create Cambrian individuals"
function CMAES_populate(e::CMAES)
    T = typeof(e.population[1])
    CMAES_populate(e, T)
end

"update pycma, called after populate and evaluate"
function CMAES_generation(e::CMAES)
    genes = (i->i.genes).(e.population)
    # Cambrian maximises, pycma minimises, so -1 factor on fitness
    fitnesses = (i->-1*i.fitness[1]).(e.population)

    e.pycma.tell(genes, fitnesses)
    Cambrian.elites_generation(e)
end

populate(e::CMAES) = CMAES_populate(e)
evaluate(e::CMAES) = fitness_evaluate(e, e.fitness)
generation(e::CMAES) = CMAES_generation(e)