text:
# ------------------------------------
# Secure the array for explicit and implicit
# ------------------------------------
function common_allocation(cellxmax, cellymax, cellzmax, nval)
    # define at cell center
    Qbase     = zeros(cellxmax, cellymax, cellzmax, nval)        # primitive variables
    Qbase_ave = zeros(cellxmax, cellymax, cellzmax, nval)        # average primitive variables
    volume    = zeros(cellxmax, cellymax, cellzmax)              # volume

    cellcenter = zeros(cellxmax, cellymax, cellzmax, 3)          # cell center

    wally = zeros(cellxmax, cellymax, cellzmax)                  # dis from wall
    yplus =  ones(cellxmax, cellymax, cellzmax) * 1e5            # yplus

    Qcon     = zeros(cellxmax, cellymax, cellzmax, nval)         # conserved variables
    Qcon_hat = zeros(cellxmax, cellymax, cellzmax, nval)         # conserved variables in the general coordinate system

    QbaseU = zeros(cellxmax+1, cellymax, cellzmax, nval)        # Q up
    QbaseD = zeros(cellxmax+1, cellymax, cellzmax, nval)        # Q down
    QbaseL = zeros(cellxmax, cellymax+1, cellzmax, nval)        # Q left
    QbaseR = zeros(cellxmax, cellymax+1, cellzmax, nval)        # Q right
    QbaseF = zeros(cellxmax, cellymax, cellzmax+1, nval)        # Q front
    QbaseB = zeros(cellxmax, cellymax, cellzmax+1, nval)        # Q back

    QconU = zeros(cellxmax+1, cellymax, cellzmax, nval)        # Q up
    QconD = zeros(cellxmax+1, cellymax, cellzmax, nval)        # Q down
    QconL = zeros(cellxmax, cellymax+1, cellzmax, nval)        # Q left
    QconR = zeros(cellxmax, cellymax+1, cellzmax, nval)        # Q right
    QconF = zeros(cellxmax, cellymax, cellzmax+1, nval)        # Q front
    QconB = zeros(cellxmax, cellymax, cellzmax+1, nval)        # Q back

    mu     = zeros(cellxmax, cellymax, cellzmax)                 # viscosity
    lambda = zeros(cellxmax, cellymax, cellzmax)                 # thermal Conductivity
    mut    = zeros(cellxmax, cellymax, cellzmax)                 # turb viscosity
    mut_bd = zeros(cellxmax+1, cellymax+1, cellzmax+1, 3)        # turb viscosity on bd

    RHS = zeros(cellxmax, cellymax, cellzmax, nval)              # right hand side

    E_adv_hat = zeros(cellxmax+1,   cellymax,   cellzmax, nval)    # flux of advection in the x-direction
    F_adv_hat = zeros(  cellxmax, cellymax+1,   cellzmax, nval)    # flux of advection in the y-direction
    G_adv_hat = zeros(  cellxmax,   cellymax, cellzmax+1, nval)    # flux of advection in the z-direction

    E_vis_hat = zeros(cellxmax+1,   cellymax,   cellzmax, nval)    # flux of viscosity in the x-direction
    F_vis_hat = zeros(  cellxmax, cellymax+1,   cellzmax, nval)    # flux of viscosity in the y-direction
    G_vis_hat = zeros(  cellxmax,   cellymax, cellzmax+1, nval)    # flux of viscosity in the z-direction

    return Qbase, Qbase_ave, volume, cellcenter, wally, yplus, Qcon, Qcon_hat, mu, mut, mut_bd, lambda,
            E_adv_hat, F_adv_hat, G_adv_hat, E_vis_hat, F_vis_hat, G_vis_hat, RHS, QbaseU, QbaseD, QbaseL, QbaseR, QbaseF, QbaseB,
            QconU, QconD, QconL, QconR, QconF, QconB

end

function allocation_implicit(cellxmax, cellymax, cellzmax, nval)
    # define at cell center
    Qbasen     = zeros(cellxmax, cellymax, cellzmax, nval)        # primitive variables for inner iteration
    Qconn      = zeros(cellxmax, cellymax, cellzmax, nval)        # conserved variables for inner iteration
    Qconn_hat  = zeros(cellxmax, cellymax, cellzmax, nval)        # conserved variables in general coordinate system for inner iteration
    Qbasem     = zeros(cellxmax, cellymax, cellzmax, nval)        # primitive variables for inner iteration

    dtau         = zeros(cellxmax, cellymax, cellzmax)            # computational time steps

    A_adv_hat_p = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix A+ for one-wave approximation
    A_adv_hat_m = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix A- for one-wave approximation
    B_adv_hat_p = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix B+ for one-wave approximation
    B_adv_hat_m = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix B- for one-wave approximation
    C_adv_hat_p = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix C+ for one-wave approximation
    C_adv_hat_m = zeros(cellxmax, cellymax, cellzmax, nval, nval) # Jacobian matrix C- for one-wave approximation
    A_beta_shig = zeros(cellxmax, cellymax, cellzmax)             # A sigma for one-wave approximation
    B_beta_shig = zeros(cellxmax, cellymax, cellzmax)             # B sigma for one-wave approximation
    C_beta_shig = zeros(cellxmax, cellymax, cellzmax)             # C sigma for one-wave approximation

    jalphaP = zeros(cellxmax, cellymax, cellzmax)                 # Jacobian matrix for viscosity
    jbetaP  = zeros(cellxmax, cellymax, cellzmax)                 # Jacobian matrix for viscosity
    jgammaP = zeros(cellxmax, cellymax, cellzmax)                 # Jacobian matrix for viscosity

    delta_Q      = zeros(cellxmax, cellymax, cellzmax, nval)      # delta Q for lusgs
    delta_Q_temp = zeros(cellxmax, cellymax, cellzmax, nval)      # temporary delta Q for lusgs

    D  = zeros(cellxmax, cellymax, cellzmax)                      # Diagonal of LHS
    Lx = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # lower of LHS
    Ly = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # lower of LHS
    Lz = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # lower of LHS
    Ux = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # upper of LHS
    Uy = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # upper of LHS
    Uz = zeros(cellxmax, cellymax, cellzmax, nval, nval)          # upper of LHS

    LdQ = zeros(cellxmax, cellymax, cellzmax, nval)               # lower of LHS
    UdQ = zeros(cellxmax, cellymax, cellzmax, nval)               # upper of LHS

    RHS_temp = zeros(cellxmax, cellymax, cellzmax, nval)          # temporary RHS
    res = zeros(cellxmax, cellymax, cellzmax, nval)               # residual

    # define at cell boundaries
    lambda_facex = zeros(cellxmax+1, cellymax, cellzmax)          # lambda for computational time steps
    lambda_facey = zeros(cellxmax, cellymax+1, cellzmax)          # lambda for computational time steps
    lambda_facez = zeros(cellxmax, cellymax, cellzmax+1)          # lambda for computational time steps

    # define at cell boundaries
    dx = zeros(cellxmax+1, cellymax, cellzmax)                   # distance from cell center
    dy = zeros(cellxmax, cellymax+1, cellzmax)                   # distance from cell center
    dz = zeros(cellxmax, cellymax, cellzmax+1)                   # distance from cell center

    # misc
    norm2 = zeros(nval)                                 # Residuals by norm-2
    I = zeros(nval, nval)                               # identity matrix
    for l in 1:nval
        I[l,l] = 1.0
    end

    return Qbasen, Qconn, Qconn_hat, Qbasem, dtau, lambda_facex, lambda_facey, lambda_facez, dx, dy, dz,
            A_adv_hat_m, A_adv_hat_p, B_adv_hat_m, B_adv_hat_p, C_adv_hat_p, C_adv_hat_m, A_beta_shig, B_beta_shig, C_beta_shig,
            jalphaP, jbetaP, jgammaP, delta_Q, delta_Q_temp, D, Lx, Ly, Lz, Ux, Uy, Uz, LdQ, UdQ, RHS_temp, res,
            norm2, I
end


text:
using Plots, Test
using RecipesPipeline

@testset "plot" begin
    pl = plot(1:5)
    pl2 = plot(pl, tex_output_standalone = true)
    @test pl[:tex_output_standalone] == false
    @test pl2[:tex_output_standalone] == true
    plot!(pl, tex_output_standalone = true)
    @test pl[:tex_output_standalone] == true
end

@testset "get_axis_limits" begin
    x = [0.1, 5]
    p1 = plot(x, [5, 0.1], yscale = :log10)
    p2 = plot!(identity)
    @test all(RecipesPipeline.get_axis_limits(p1, :x) .== x)
    @test all(RecipesPipeline.get_axis_limits(p2, :x) .== x)
end

@testset "Slicing" begin
    @test plot(1:5, fillrange = 0)[1][1][:fillrange] == 0
    data4 = rand(4, 4)
    mat = reshape(1:8, 2, 4)
    for i in axes(data4, 1)
        for attribute in (:fillrange, :ribbon)
            @test plot(data4; NamedTuple{tuple(attribute)}(0)...)[1][i][attribute] == 0
            @test plot(data4; NamedTuple{tuple(attribute)}(Ref([1, 2]))...)[1][i][attribute] ==
                  [1.0, 2.0]
            @test plot(data4; NamedTuple{tuple(attribute)}(Ref([1 2]))...)[1][i][attribute] ==
                  (iseven(i) ? 2 : 1)
            @test plot(data4; NamedTuple{tuple(attribute)}(Ref(mat))...)[1][i][attribute] ==
                  [2(i - 1) + 1, 2i]
        end
        @test plot(data4, ribbon = (mat, mat))[1][i][:ribbon] ==
              ([2(i - 1) + 1, 2i], [2(i - 1) + 1, 2i])
    end
end

ext: jl


text:
using JuMP
using Combinatorics: permutations

"""Stores and validates the values of a deviation for discrete probabilities `p`.

# Arguments
- `n::Int`: Length of discrete probabilities
- `p::Vector{Float64}`: Vector of discrete probabilities
- `d⁻::Vector{Float64}`: Vector of lower bounds
- `d⁺::Vector{Float64}`: Vector of uppper bounds
- `ϵ::Float64`: Radius of uncertainty

The arguments should satisfy the following conditions:

```julia
n ≥ 1
all(p .≥ 0)
isapprox(sum(p), 1)
length(p) == length(d⁻) == length(d⁺) == n
all(d⁻ .≥ -p)
all(d⁺ .≤ 1.0.-p)
0 ≤ ϵ ≤ 1
```

# Examples
Arguments

```julia
n = 2
p = [0.4, 0.6]
d⁻ = [-0.2, -0.2]
d⁺ = [0.2, 0.2]
ϵ = 0.1
```
"""
struct Deviation
    n::Int
    p::Vector{Float64}
    d⁻::Vector{Float64}
    d⁺::Vector{Float64}
    ϵ::Float64
    function Deviation(n::Int, p::Vector{Float64}, d⁻::Vector{Float64}, d⁺::Vector{Float64}, ϵ::Float64)
        n ≥ 1 || throw(DomainError(""))
        all(p .≥ 0) || throw(DomainError(""))
        isapprox(sum(p), 1) || throw(DomainError(""))
        length(p) == length(d⁻) == length(d⁺) == n || throw(DomainError(""))
        all(d⁻ .≥ -p) || throw(DomainError(""))
        all(d⁺ .≤ 1.0.-p) || throw(DomainError(""))
        0 ≤ ϵ ≤ 1 || throw(DomainError(""))
        new(n, p, d⁻, d⁺, ϵ)
    end
end

"""Constructs a deviation.

Examples
```julia
Deviation(p, d⁻, d⁺, ϵ)
```
"""
function Deviation(p::Vector{Float64}, d⁻::Vector{Float64}, d⁺::Vector{Float64}, ϵ::Float64)
    n = length(p)
    Deviation(n, p, d⁻, d⁺, ϵ)
end

"""Constructs a deviation.

```julia
Deviation(p, d⁻, d⁺)
```
"""
function Deviation(p::Vector{Float64}, d⁻::Vector{Float64}, d⁺::Vector{Float64})
    Deviation(p, d⁻, d⁺, 1.0)
end

"""Constructs a deviation.

```julia
Deviation(p, ϵ)
```
"""
function Deviation(p::Vector{Float64}, ϵ::Float64)
    Deviation(p, -p, 1.0.-p, ϵ)
end

"""Computes the optimal cross-assignment recursively."""
function cross_assignment(l::Int, h::Int, Σ::Float64, d::Vector{Float64}, d⁻::Vector{Float64}, d⁺::Vector{Float64}, ϵ::Float64)
    if (h - l ≤ 0) || (ϵ-Σ ≤ 0)
        return d
    end
    δ_l = d⁺[l] - d[l]
    δ_h = d[h] - d⁻[h]
    δ = min(δ_l, δ_h, ϵ-Σ)
    d[l] += δ
    d[h] -= δ
    if δ_l < δ_h
        return cross_assignment(l+1, h, Σ+δ, d, d⁻, d⁺, ϵ)
    elseif δ_l > δ_h
        return cross_assignment(l, h-1, Σ+δ, d, d⁻, d⁺, ϵ)
    else
        return cross_assignment(l+1, h-1, Σ+δ, d, d⁻, d⁺, ϵ)
    end
end

"""Compute cross-assignment."""
function cross_assignment(k::Int, d⁻::Vector{Float64}, d⁺::Vector{Float64}, ϵ::Float64)
    d = zeros(k)
    cross_assignment(1, k, 0.0, d, d⁻, d⁺, ϵ)
end

"""Computes the optimal cross assignment from deviation.

# Examples
```julia
dev = Deviation(...)
cross_assignment(dev)
```
"""
function cross_assignment(dev::Deviation)
    cross_assignment(dev.n, dev.d⁻, dev.d⁺, dev.ϵ)
end

"""Polyhedral uncertainty"""
function polyhedral_uncertainty(perm::Vector{Int}, dev::Deviation)
    q = copy(dev.p)
    q[perm] += cross_assignment(length(perm), dev.d⁻[perm], dev.d⁺[perm], dev.ϵ)
    return q
end

"""Polyhedral uncertainty set."""
function polyhedral_uncertainty_set(dev::Deviation)::Array{Vector{Float64}}
    p, ϵ = dev.p, dev.ϵ
    if iszero(ϵ)
        return [p]
    else
        i = [i for i in LinearIndices(p) if !iszero(p[i])]
        s = Set(polyhedral_uncertainty(perm, dev) for perm in permutations(i))
        return collect(s)
    end
end

max_stars_repo_name: jaantollander/RobustDecisionProgramming

max_issues_repo_name: jaantollander/RobustDecisionProgramming

max_forks_repo_name: jaantollander/RobustDecisionProgramming


text:
(results_uc, results_ed) = run_test_sim(TEST_RESULT_DIR)

@testset "test filter results" begin
    gen = PG.get_generation_data(results_uc, curtailment = false)
    @test length(gen.data) == 4
    @test length(gen.time) == 48

    gen = PG.get_generation_data(
        results_uc,
        names = [
            :P__ThermalStandard,
            :P__RenewableDispatch,
            :P__max_active_power__RenewableDispatch,
        ],
        initial_time = Dates.DateTime("2024-01-02T02:00:00"),
        len = 3,
    )
    @test length(gen.data) == 3
    @test length(gen.time) == 3

    load = PG.get_load_data(results_ed)
    @test length(load.data) == 2
    @test length(load.time) == 576

    load = PG.get_load_data(
        results_ed,
        names = [:P__max_active_power__PowerLoad],
        initial_time = Dates.DateTime("2024-01-02T02:00:00"),
        len = 3,
    )
    @test length(load.data) == 1
    @test length(load.time) == 3

    srv = PG.get_service_data(results_ed)
    @test length(srv.data) == 0

    srv = PG.get_service_data(
        results_uc,
        names = [:Reserve11__VariableReserve_ReserveUp],
        initial_time = Dates.DateTime("2024-01-02T02:00:00"),
        len = 5,
    )
    @test length(srv.data) == 1
    @test length(srv.time) == 5
end

@testset "test data aggregation" begin
    gen = PG.get_generation_data(results_uc)

    cat = PG.make_fuel_dictionary(results_uc.system)
    @test isempty(symdiff(keys(cat), ["Coal", "Wind", "Hydropower"]))

    fuel = PG.categorize_data(gen.data, cat)
    @test length(fuel) == 4

    fuel_agg = PG.combine_categories(fuel)
    @test size(fuel_agg) == (48, 4)
end

@testset "test html saving" begin
    plot_fuel(
        results_ed,
        set_display = false,
        save = TEST_RESULT_DIR,
        title = "fuel_html_output",
        format = "html",
    )
    @test isfile(joinpath(TEST_RESULT_DIR, "fuel_html_output.html"))
end


text:
module SEML

include("preprocessor3.jl")
include("biosymDecoder.jl")
include("semanticChecking.jl")
include("modelGeneration.jl")
include("JuliaStrategy.jl")
include("Python2Strategy.jl")
include("Python3Strategy.jl")
include("MATLABStrategy.jl")
include("make_model.jl")

# Export the interface function -
export make_model

end # module


text:
"""
    DiagnosticsGroup

Holds a set of diagnostics that share a collection interval, a filename
prefix, and an interpolation.

TODO: will be restructured to be defined as groups of `DiagnosticVariable`s.
"""
mutable struct DiagnosticsGroup
    name::String
    init::Function
    fini::Function
    collect::Function
    interval::String
    out_prefix::String
    writer::AbstractWriter
    interpol::Union{Nothing, InterpolationTopology}
    num::Int

    DiagnosticsGroup(
        name,
        init,
        fini,
        collect,
        interval,
        out_prefix,
        writer,
        interpol,
    ) = new(
        name,
        init,
        fini,
        collect,
        interval,
        out_prefix,
        writer,
        interpol,
        0,
    )
end

function (dgngrp::DiagnosticsGroup)(currtime; init = false, fini = false)
    if init
        dgngrp.init(dgngrp, currtime)
    end
    dgngrp.collect(dgngrp, currtime)
    if fini
        dgngrp.fini(dgngrp, currtime)
    end
    dgngrp.num += 1
end

include("atmos_les_default.jl")
"""
    setup_atmos_default_diagnostics(
        ::AtmosLESConfigType,
        interval::String,
        out_prefix::String;
        writer = NetCDFWriter(),
        interpol = nothing,
    )

Create and return a `DiagnosticsGroup` containing the "AtmosDefault"
diagnostics for LES configurations. All the diagnostics in the group will
run at the specified `interval`, be interpolated to the specified boundaries
and resolution, and will be written to files prefixed by `out_prefix` using
`writer`.
"""
function setup_atmos_default_diagnostics(
    ::AtmosLESConfigType,
    interval::String,
    out_prefix::String;
    writer = NetCDFWriter(),
    interpol = nothing,
)
    return DiagnosticsGroup(
        "AtmosLESDefault",
        Diagnostics.atmos_les_default_init,
        Diagnostics.atmos_les_default_fini,
        Diagnostics.atmos_les_default_collect,
        interval,
        out_prefix,
        writer,
        interpol,
    )
end

include("atmos_gcm_default.jl")
"""
    setup_atmos_default_diagnostics(
        ::AtmosGCMConfigType,
        interval::Int,
        out_prefix::String;
        writer::AbstractWriter,
        interpol = nothing,
    )

Create and return a `DiagnosticsGroup` containing the "AtmosDefault"
diagnostics for GCM configurations. All the diagnostics in the group will run
at the specified `interval`, be interpolated to the specified boundaries and
resolution, and will be written to files prefixed by `out_prefix` using
`writer`.
"""
function setup_atmos_default_diagnostics(
    ::AtmosGCMConfigType,
    interval::String,
    out_prefix::String;
    writer = NetCDFWriter(),
    interpol = nothing,
)
    @assert !isnothing(interpol)

    return DiagnosticsGroup(
        "AtmosGCMDefault",
        Diagnostics.atmos_gcm_default_init,
        Diagnostics.atmos_gcm_default_fini,
        Diagnostics.atmos_gcm_default_collect,
        interval,
        out_prefix,
        writer,
        interpol,
    )
end

include("atmos_les_core.jl")
"""
    setup_atmos_core_diagnostics(
        ::AtmosLESConfigType,
        interval::Int,
        out_prefix::String;
        writer::AbstractWriter,
        interpol = nothing,
    )

Create and return a `DiagnosticsGroup` containing the "AtmosLESCore" diagnostics
for LES configurations. All the diagnostics in the group will run at the
specified `interval`, be interpolated to the specified boundaries and
resolution, and will be written to files prefixed by `out_prefix` using
`writer`.
"""
function setup_atmos_core_diagnostics(
    ::AtmosLESConfigType,
    interval::String,
    out_prefix::String;
    writer = NetCDFWriter(),
    interpol = nothing,
)
    return DiagnosticsGroup(
        "AtmosLESCore",
        Diagnostics.atmos_les_core_init,
        Diagnostics.atmos_les_core_fini,
        Diagnostics.atmos_les_core_collect,
        interval,
        out_prefix,
        writer,
        interpol,
    )
end

include("dump_state_and_aux.jl")
"""
    setup_dump_state_and_aux_diagnostics(
        ::ClimateMachineConfigType,
        interval::String,
        out_prefix::String;
        writer = NetCDFWriter(),
        interpol = nothing,
    )

Create and return a `DiagnosticsGroup` containing a diagnostic that
simply dumps the state and aux variables at the specified `interval`
after being interpolated, into NetCDF files prefixed by `out_prefix`.
"""
function setup_dump_state_and_aux_diagnostics(
    ::ClimateMachineConfigType,
    interval::String,
    out_prefix::String;
    writer = NetCDFWriter(),
    interpol = nothing,
)
    return DiagnosticsGroup(
        "DumpStateAndAux",
        Diagnostics.dump_state_and_aux_init,
        Diagnostics.dump_state_and_aux_fini,
        Diagnostics.dump_state_and_aux_collect,
        interval,
        out_prefix,
        writer,
        interpol,
    )
end

max_stars_repo_name: leios/CLIMA

max_issues_repo_name: leios/CLIMA

max_forks_repo_name: leios/CLIMA


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

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
        el
    end
end

# ╔═╡ 83132240-ba23-11eb-3364-27aa887dc1ed
using WAV, Plots, UnicodePlots, DSP, PlutoUI, SampledSignals

# ╔═╡ ec91d11b-0034-4574-ba6b-14f605916c4b
gr()

# ╔═╡ 32b89ecb-4446-40cb-8190-c49e59c252ea
md"""
# Oscillators
It is the most important component of a synthesizer, it is a component that
that generates a sequence of numbers that repeats after a certain interval.

The most simplest oscillator is one that produces which is generated by
unsurprisingly yet delightfully, the sine function.

https://www.reddit.com/r/Python/comments/lw50ne/making_a_synthesizer_using_python/
https://python.plainenglish.io/making-a-synth-with-python-oscillators-2cb8e68e9c3b
"""

# ╔═╡ 233e8aa5-549a-4c11-83a9-8b015980ecda
md"![](https://i.imgur.com/k2qKXDd.png)"

# ╔═╡ 17e19c4b-f596-47c3-9542-1d86381c3c58
begin    # Example audio
    audio_one_channel = SampleBuf(rand(100000), 10000)
    audio_two_channel = SampleBuf(rand(100000,2), 10000)
    audio_multi_channel = SampleBuf(rand(100000,2), 10000)
end

# ╔═╡ 195cf333-b46e-4510-a960-24f8e835bb5d
typeof(audio_one_channel)

# ╔═╡ 2fa88e96-8be4-46ee-af6f-d8385ea27316
audio_one_channel.data

# ╔═╡ 9b3d1d97-e6b0-4800-bf81-72ae4fcde639
sizeof(audio_one_channel)

# ╔═╡ d078708b-d6c3-40bb-afff-5b5faaacf6b0
size(audio_one_channel)

# ╔═╡ 8a1bcc5e-fd23-4e22-a336-42149f2d1737
audio_two_channel.data

# ╔═╡ 8fbca243-21ae-473f-bdf7-279631736049
audio_two_channel.samplerate

# ╔═╡ 27ec72b8-eb37-4b28-82ad-50041acfaf06
begin

# some examples from WaveForm.jl
squarewave(x::Real) = ifelse(mod2pi(x) < π, 1.0, -1.0)

function squarewave(x::Real, θ::Real)
    0 ≤ θ ≤ 1 || throw(DomainError(θ, "squwarewave(x, θ) is only defined for 0 ≤ θ ≤ 1."))
    ifelse(mod2pi(x) < 2π * θ, 1.0, -1.0)
end

squarewave1(x::Real) = ifelse(mod(x, 1) < 1/2, 1.0, -1.0)

function squarewave1(x::Real, θ::Real)
    0 ≤ θ ≤ 1 || throw(DomainError(θ, "squwarewave1(x, θ) is only defined for 0 ≤ θ ≤ 1."))
    ifelse(mod(x, 1) < θ, 1.0, -1.0)
end

function trianglewave(x::Real)
    modx = mod2pi(x + π/2)
    ifelse(modx < π, 2modx/π - 1, -2modx/π + 3)
end

function trianglewave1(x::Real)
    modx = mod(x + 1/4, 1.0)
    ifelse(modx < 1/2, 4modx - 1, -4modx + 3)
end

sawtoothwave(x::Real) = rem2pi(x, RoundNearest) / π

sawtoothwave1(x::Real) = rem(x, 1.0, RoundNearest) * 2
end

# ╔═╡ 303d7a7a-7f4c-4a0a-9eb3-5bd522ff84f5
lineplot([squarewave], -π/2, 2π)

# ╔═╡ 0bc8c6e5-1178-42fd-936f-f26509d8751d
lineplot([sin], -π/2, 2π)

# ╔═╡ 1165e774-045e-42c4-8644-2894455cd0cc
lineplot([sawtoothwave], -π/2, 2π)

# ╔═╡ c121c2ad-ac4b-469b-9680-80bed77d5a38
lineplot([trianglewave], -π/2, 2π)

# ╔═╡ 796e888f-98b5-43c0-a852-e8beb38f19fc

# ╔═╡ 3b2adbf6-1d51-4571-9939-9c4546214514
@bind A Slider(.1:.1:1,default=.8,show_value=true)

# ╔═╡ 7df42e3f-5bb9-445b-9254-8943b7c9ab5f
@bind phi Slider(0:pi/6:2pi,default=pi/2,show_value=true)

# ╔═╡ dc0a400b-0b94-4f97-882b-e11355afc10a
@bind f0 Slider(0:1000:10000,default=1000,show_value=true)

# ╔═╡ 88a0bc8a-cd2a-46d5-af28-d6d0b1a13ef5
@bind fs Slider(0:1000:50000,default=44100,show_value=true)

# ╔═╡ fb72b61d-a8db-435a-8c23-9f8d3525e845
begin

t = -0.002:1/fs:0.002
y = A*cos.(2*pi*f0*t .+ phi)

#y1 = squarewave.(f1*t1) * 1
#y1 = (sin.(2pi * f1* t1) .*0.1)
#y1 = trianglewave.(f1* t1) * 1
# y1 = (sin.(2pi * f1* t1) .*t1) .+ (sin.(2pi * f1*2* t1 .+pi) .*t1/2)
wavplay(y, fs)
end

# ╔═╡ 59d8f284-7d67-4e23-a660-7d0155bb3711
lineplot(t, y)

# ╔═╡ 6a196ee0-2f8c-46cb-bf32-37873e45a3bd
md"""
## Complex Numbers
```
(a + ib)  a,b: real numbers; i: imaginary unit
```
- Rectangular form: a+ib
- Polar form: A=sqroot(a^2+b^2);phi=a*tan(2(b/a))
"""

# ╔═╡ 2894f290-6d34-4771-a0f0-4772f257fdf9
md"""
## Euler's Formula

Fundamental to understand discrete fourier transform

$$e^{i\phi} = cos(\phi) + isin(\phi)$$

$$cos(\phi) = \frac{e^{i\phi}+ e^{-i\phi}}{2}$$
$$sin(\phi) = \frac{e^{i\phi}- e^{-i\phi}}{2i}$$
"""

# ╔═╡ c52f1841-dba0-442e-ad2d-32bdd73db167
md"""
![](https://i.imgur.com/HkbIUh8.png)

We plot the complex wave  in a 2d graph by plotting real and imaginary parts separately
"""

# ╔═╡ c809174c-db19-4fc8-ad06-6ec3134e66c7
md"""
## Scalar(Dot Product of sequences)
$$x=[1,2,3] , y = [1,2,3]$$
$$dot = 1*1 + 2*2 + 3*3 = 14$$

Scalar product of two orthogonal sequences is 0.

$$x = [2,2], y = [2,-2]$$
$$dot = 2*2 + 2*-2 = 0$$

"""

# ╔═╡ dbb861f7-8852-4aa6-8401-8cfc4e897718
md"""
![](https://i.imgur.com/iixirS3.png)
![](https://i.imgur.com/F4T7PiO.png)
"""

# ╔═╡ 6875e4b2-5ca9-436b-b982-1756592f9fca
@bind A1 Slider(.1:.1:1,default=.8,show_value=true)

# ╔═╡ 5aee7e72-113d-45c7-ad9b-ab474aa7de4a
@bind A2 Slider(.1:.1:1,default=.8,show_value=true)

# ╔═╡ 330cc960-8a01-4e3a-9856-cc945516db77
@bind phi1 Slider(0:pi/6:2pi,default=pi/2,show_value=true)

# ╔═╡ 554edb90-70e1-408d-971e-f3d756a8b8d4
@bind phi2 Slider(0:pi/6:2pi,default=pi/2,show_value=true)

# ╔═╡ b70f11f9-1eeb-4cc0-95a3-11a39936336a
@bind f01 Slider(0:1000:10000,default=1000,show_value=true)

# ╔═╡ 787c8243-7267-472e-9d15-4d664b56f577
@bind f02 Slider(0:1000:10000,default=1000,show_value=true)

# ╔═╡ aeaaa336-cb57-4b55-a350-0dc01adbaf5a
@bind fst Slider(0:1000:50000,default=44100,show_value=true)

# ╔═╡ 74688ae9-8021-4ba8-bc03-5db34a90ee04
begin
#tr = -1:1/fst:1	 #use this if want to hear something and comment next line
tr = -0.002:1/fs:0.002
y1 = A1*sin.(2*pi*f01*tr .+ phi1)
y2 = A2*cos.(2*pi*f02*tr .+ phi2)
addresult =y1 .+ y2
subresult =y1 .- y2
mulresult =y1 .* y2
divresult =y1 ./ y2
wavplay(subresult, fst)
end

# ╔═╡ c87b000d-0c4a-4a4c-8ab8-c7e3b762ec4b
lineplot(tr, y1)

# ╔═╡ 7956a1fc-9bd8-418c-bf22-370e2a426090
lineplot(tr, y2)

# ╔═╡ c817eafc-8ebe-49a6-a53d-13b325d51012
lineplot(tr, addresult)

# ╔═╡ e8e9adcb-3a14-4785-a162-c1aafc03f516
lineplot(tr, subresult)

# ╔═╡ 45f25de9-06ac-49de-b5e2-523927650d22
lineplot(tr, mulresult)

# ╔═╡ 422d7aa0-3e09-424d-8eb1-63d9eeaf13c8
lineplot(tr, divresult)

# ╔═╡ 1636782b-4327-438e-afab-375c52ca0912
begin
wave1, fs1 = wavread("piano-phrase.wav")
wavplay(wave1, fs1)
end

# ╔═╡ a4498719-ebbc-4917-aa8b-3753a4bb49db
begin
plot(0:1/fs1:(length(wave1)-1)/fs1, wave1)
# xlabel("Time [s]")
end

# ╔═╡ 30d4a5c1-cd1b-4acf-b8cc-eee54ccda363
@bind Az Slider(.1:.1:1,default=.8,show_value=true)

# ╔═╡ 3d505342-61c2-4b09-a9aa-f3b64041efa8
@bind phiz Slider(0:pi/6:2pi,default=pi/2,show_value=true)

# ╔═╡ 405bf0ef-f935-4a5b-a59d-9b1dd9ff4ca2
@bind fsd Slider(0:1000:50000,default=44100,show_value=true)

# ╔═╡ 641b2f68-a2c9-49cb-adbc-3ddee4e04cab
begin
f0z = 880

tz = 1:1/fsd:11
wavez = Az./tz.*sin.(2*pi*f0z*tz .+ phiz)

#y1 = squarewave.(f1*t1) * 1
#y1 = (sin.(2pi * f1* t1) .*0.1)
#y1 = trianglewave.(f1* t1) * 1
# y1 = (sin.(2pi * f1* t1) .*t1) .+ (sin.(2pi * f1*2* t1 .+pi) .*t1/2)
wavplay(wavez, fsd)
end

# ╔═╡ 9fd1b730-6d2c-4955-9de2-3ea76996f3df
lineplot(tz,wavez)

# ╔═╡ 4ca03162-c38c-4f32-bee3-984d9509f657
@bind f1 Slider(0:10:1000,default=200,show_value=true)

# ╔═╡ 69fdc3d1-e75a-4479-ab9c-67982e5e6038
@bind f2 Slider(0:10:1000,default=400,show_value=true)

# ╔═╡ 7d597e41-1e88-421f-9f38-758523ec9bc9
@bind f3 Slider(0:10:1000,default=600,show_value=true)

# ╔═╡ 0dc9f30c-0852-47e2-b20b-30bb05f1978d
@bind f4 Slider(0:10:1000,default=800,show_value=true)

# ╔═╡ 2028733e-ef1d-4ee2-bc54-6f9c4286fe5b
@bind f5 Slider(0:10:1000,default=1000,show_value=true)

# ╔═╡ f7e817ac-2e94-4311-91db-d2b29c25dbc3
begin
ta = -0.005:1/fsd:0.005
harmonic1 = A*sin.(2*pi*f1*ta .+ phi)
harmonic2 = A*sin.(2*pi*f2*ta .+ phi)
harmonic3 = A*sin.(2*pi*f3*ta .+ phi)
harmonic4 = A*sin.(2*pi*f4*ta .+ phi)
harmonic5 = A*sin.(2*pi*f5*ta .+ phi)
end

# ╔═╡ 036ffade-4b41-4aea-9176-49b15e520cfd
wavplay(harmonic5, fsd)

# ╔═╡ a0350ced-095f-4c44-b298-faf2a34a178e
composite = harmonic1 .+ harmonic2 .+ harmonic3 .+ harmonic4 .+harmonic5

# ╔═╡ 2040daae-ce2f-44db-800a-be306efe916c
lineplot(ta,composite)

# ╔═╡ eb0a1090-8ace-4d2f-8bf4-a206c0c43cca
lineplot(ta,composite)

# ╔═╡ c834ef7b-816d-49d5-ab9b-93b0504fa9e9
wavplay(composite, fsd)

# ╔═╡ 88411f35-2332-43f3-acd8-24169a03083e
md"""
Important Resources:

- https://ccrma.stanford.edu/~jos/mdft/
- https://github.com/MTG/sms-tools

"""

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
DSP = "717857b8-e6f2-59f4-9121-6e50c889abd2"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
SampledSignals = "bd7594eb-a658-542f-9e75-4c4d8908c167"
UnicodePlots = "b8865327-cd53-5732-bb35-84acbb429228"
WAV = "8149f6b0-98f6-5db9-b78f-408fbbb8ef88"

[compat]
DSP = "~0.6.10"
Plots = "~1.25.4"
PlutoUI = "~0.7.27"
SampledSignals = "~2.1.2"
UnicodePlots = "~2.5.1"
WAV = "~1.2.0"
"""

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

[[AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "485ee0867925449198280d4af84bdb46a2a404d0"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.0.1"

[[AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"

[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "9faf218ea18c51fcccaf956c8d39614c9d30fe8b"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.2"

[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"

[[ArrayInterface]]
deps = ["Compat", "IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"]
git-tree-sha1 = "265b06e2b1f6a216e0e8f183d28e4d354eab3220"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "3.2.1"

[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"

[[Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"

[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "d711603452231bad418bd5e0c91f1abd650cba71"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.11.3"

[[ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "bf98fa45a0a4cee295de98d4c1462be26345b9a1"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.2"

[[ColorSchemes]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "a851fec56cb73cfdf43762999ec72eff5b86882a"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.15.0"

[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"

[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"

[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "44c37b4636bc54afac5c574d2d02b625349d6582"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.41.0"

[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"

[[ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.3.0"

[[Contour]]
deps = ["StaticArrays"]
git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.5.7"

[[Crayons]]
git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.0.4"

[[DSP]]
deps = ["FFTW", "IterTools", "LinearAlgebra", "Polynomials", "Random", "Reexport", "SpecialFunctions", "Statistics"]
git-tree-sha1 = "2a63cb5fc0e8c1f0f139475ef94228c7441dc7d0"
uuid = "717857b8-e6f2-59f4-9121-6e50c889abd2"
version = "0.6.10"

[[DataAPI]]
git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.9.0"

[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "3daef5523dd2e769dad2365274f760ff5f282c7d"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.11"

[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"

[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"

[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"

[[DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.8.6"

[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"

[[EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.3+0"

[[EllipsisNotation]]
deps = ["ArrayInterface"]
git-tree-sha1 = "3fe985505b4b667e1ae303c9ca64d181f09d5c05"
uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949"
version = "1.1.3"

[[Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b3bfd02e98aedfa5cf885665493c5598c350cd2f"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.2.10+0"

[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"

[[FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"

[[FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.0+0"

[[FFTW]]
deps = ["AbstractFFTs", "FFTW_jll", "LinearAlgebra", "MKL_jll", "Preferences", "Reexport"]
git-tree-sha1 = "463cb335fa22c4ebacfd1faba5fde14edb80d96c"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "1.4.5"

[[FFTW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c6033cc3892d0ef5bb9cd29b7f2f0331ea5184ea"
uuid = "f5851436-0d7a-5f13-b9de-f02708fd171a"
version = "3.3.10+0"

[[FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "2db648b6712831ecb333eae76dbfd1c156ca13bb"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.11.2"

[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"

[[Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.93+0"

[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"

[[FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.10.4+0"

[[FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"

[[GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "0c603255764a1fa0b61752d2bec14cfbd18f7fe8"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.5+1"

[[GR]]
deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "Serialization", "Sockets", "Test", "UUIDs"]
git-tree-sha1 = "b9a93bcdf34618031891ee56aad94cfff0843753"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.63.0"

[[GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "f97acd98255568c3c9b416c5a3cf246c1315771b"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.63.0+0"

[[GeometryBasics]]
deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.1"

[[Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"

[[Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "a32d672ac2c967f3deb8a81d828afc739c838a06"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.68.3+2"

[[Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"

[[Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"

[[HTTP]]
deps = ["Base64", "Dates", "IniFile", "Logging", "MbedTLS", "NetworkOptions", "Sockets", "URIs"]
git-tree-sha1 = "0fa77022fe4b511826b39c894c90daf5fce3334a"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "0.9.17"

[[HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+1"

[[Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"

[[HypertextLiteral]]
git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.3"

[[IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"

[[IfElse]]
git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1"
uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173"
version = "0.1.1"

[[IniFile]]
deps = ["Test"]
git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8"
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
version = "0.5.0"

[[InlineStrings]]
deps = ["Parsers"]
git-tree-sha1 = "8d70835a3759cdd75881426fced1508bb7b7e1b6"
uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48"
version = "1.1.1"

[[IntelOpenMP_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d979e54b71da82f3a65b62553da4fc3d18c9004c"
uuid = "1d5cc7b8-4909-519e-a0f8-d0f5ad9712d0"
version = "2018.0.3+2"

[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[IntervalSets]]
deps = ["Dates", "EllipsisNotation", "Statistics"]
git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758"
uuid = "8197267c-284f-5f27-9208-e0e47529a953"
version = "0.5.3"

[[Intervals]]
deps = ["Dates", "Printf", "RecipesBase", "Serialization", "TimeZones"]
git-tree-sha1 = "323a38ed1952d30586d0fe03412cde9399d3618b"
uuid = "d8418881-c3e1-53bb-8760-2df7ec849ed5"
version = "1.5.0"

[[InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.2"

[[IrrationalConstants]]
git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.1"

[[IterTools]]
git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.4.0"

[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"

[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"

[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"

[[JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d735490ac75c5cb9f1b00d8b5509c11984dc6943"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "2.1.0+0"

[[LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.1+0"

[[LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.1+0"

[[LaTeXStrings]]
git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.0"

[[Latexify]]
deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"]
git-tree-sha1 = "a8f4f279b6fa3c3c4f1adadd78a621b13a506bce"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.15.9"

[[LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"

[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"

[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"

[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"

[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"

[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"

[[Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+1"

[[Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"

[[Libglvnd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"]
git-tree-sha1 = "7739f837d6447403596a75d19ed01fd08d6f56bf"
uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29"
version = "1.3.0+3"

[[Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"

[[Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+1"

[[Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.35.0+0"

[[Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.3.0+0"

[[Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.36.0+0"

[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[LogExpFunctions]]
deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "e5718a00af0ab9756305a0392832c8952c7426c1"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.6"

[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"

[[MKL_jll]]
deps = ["Artifacts", "IntelOpenMP_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "Pkg"]
git-tree-sha1 = "5455aef09b40e5020e1520f551fa3135040d4ed0"
uuid = "856f044c-d86e-5d09-b602-aeab76dc8ba7"
version = "2021.1.1+2"

[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.9"

[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "Random", "Sockets"]
git-tree-sha1 = "1c38e51c3d08ef2278062ebceade0e46cefc96fe"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.0.3"

[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"

[[Measures]]
git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.1"

[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.2"

[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[Mocking]]
deps = ["Compat", "ExprTools"]
git-tree-sha1 = "29714d0a7a8083bba8427a4fbfb00a540c681ce7"
uuid = "78c3b35d-d492-501b-9361-3d52fe80e533"
version = "0.7.3"

[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"

[[NaNMath]]
git-tree-sha1 = "f755f36b19a5116bb580de457cda0c140153f283"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "0.3.6"

[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"

[[OffsetArrays]]
deps = ["Adapt"]
git-tree-sha1 = "043017e0bdeff61cfbb7afeb558ab29536bbb5ed"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.10.8"

[[Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+0"

[[OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"

[[OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "15003dcb7d8db3c6c857fda14891a539a8f2705a"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.10+0"

[[OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"

[[Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"

[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"

[[PCRE_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488"
uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc"
version = "8.44.0+0"

[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "d7fa6237da8004be601e19bd6666083056649918"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.1.3"

[[Pixman_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.40.1+0"

[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"

[[PlotThemes]]
deps = ["PlotUtils", "Requires", "Statistics"]
git-tree-sha1 = "a3a964ce9dc7898193536002a6dd892b1b5a6f1d"
uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
version = "2.0.1"

[[PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "68604313ed59f0408313228ba09e79252e4b2da8"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.1.2"

[[Plots]]
deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "GeometryBasics", "JSON", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "PlotThemes", "PlotUtils", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs", "UnicodeFun", "Unzip"]
git-tree-sha1 = "71d65e9242935132e71c4fbf084451579491166a"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.25.4"

[[PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "fed057115644d04fba7f4d768faeeeff6ad11a60"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.27"

[[Polynomials]]
deps = ["Intervals", "LinearAlgebra", "OffsetArrays", "RecipesBase"]
git-tree-sha1 = "0b15f3597b01eb76764dd03c3c23d6679a3c32c8"
uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45"
version = "1.2.1"

[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "2cf929d64681236a2e074ffafb8d568733d2e6af"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.3"

[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[Qt5Base_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "xkbcommon_jll"]
git-tree-sha1 = "ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8"
uuid = "ea2cea3b-5b76-57ae-a6ef-0a8af62496e1"
version = "5.15.3+0"

[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"

[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[RecipesBase]]
git-tree-sha1 = "6bf3f380ff52ce0832ddd3a2a7b9538ed1bcca7d"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.2.1"

[[RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"]
git-tree-sha1 = "7ad0dfa8d03b7bcf8c597f59f5292801730c55b8"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.4.1"

[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"

[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "8f82019e525f4d5c669692772a6f4b0a58b06a6a"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.2.0"

[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[SampledSignals]]
deps = ["Base64", "Compat", "DSP", "FFTW", "FixedPointNumbers", "IntervalSets", "LinearAlgebra", "Random", "TreeViews", "Unitful"]
git-tree-sha1 = "4b7e413f20fa56fa47b8433c96f96a1acfe372a6"
uuid = "bd7594eb-a658-542f-9e75-4c4d8908c167"
version = "2.1.2"

[[Scratch]]
deps = ["Dates"]
git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.0"

[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"

[[Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"

[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"

[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "f0bccf98e16759818ffc5d97ac3ebf87eb950150"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.8.1"

[[Static]]
deps = ["IfElse"]
git-tree-sha1 = "7f5a513baec6f122401abfc8e9c074fdac54f6c1"
uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3"
version = "0.4.1"

[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3c76dde64d03699e074ac02eb2e8ba8254d428da"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.13"

[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[StatsAPI]]
git-tree-sha1 = "d88665adc9bcf45903013af0982e2fd05ae3d0a6"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.2.0"

[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "51383f2d367eb3b444c961d485c565e4c0cf4ba0"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.14"

[[StructArrays]]
deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"]
git-tree-sha1 = "2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.3"

[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"

[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "bb1064c9a84c52e277f1096cf41434b675cd368b"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.6.1"

[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"

[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[TimeZones]]
deps = ["Dates", "Downloads", "InlineStrings", "LazyArtifacts", "Mocking", "Printf", "RecipesBase", "Serialization", "Unicode"]
git-tree-sha1 = "ce5aab0b0146b81efefae52f13002e19c2af57ac"
uuid = "f269a46b-ccf7-5d73-abea-4c690281aa53"
version = "1.7.0"

[[TreeViews]]
deps = ["Test"]
git-tree-sha1 = "8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6"
uuid = "a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7"
version = "0.3.0"

[[URIs]]
git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.3.0"

[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"

[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"

[[UnicodeFun]]
deps = ["REPL"]
git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf"
uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1"
version = "0.4.1"

[[UnicodePlots]]
deps = ["Crayons", "Dates", "SparseArrays", "StatsBase"]
git-tree-sha1 = "3cb994143aba28cfe66615702505b2d294cebd3e"
uuid = "b8865327-cd53-5732-bb35-84acbb429228"
version = "2.5.1"

[[Unitful]]
deps = ["ConstructionBase", "Dates", "LinearAlgebra", "Random"]
git-tree-sha1 = "09b3c3eb6767521346b3716e461ddfb3ebe88293"
uuid = "1986cc42-f94f-5a68-af5c-568840ba703d"
version = "1.10.0"

[[Unzip]]
git-tree-sha1 = "34db80951901073501137bdbc3d5a8e7bbd06670"
uuid = "41fe7b60-77ed-43a1-b4f0-825fd5a5650d"
version = "0.1.2"

[[WAV]]
deps = ["Base64", "FileIO", "Libdl", "Logging"]
git-tree-sha1 = "7e7e1b4686995aaf4ecaaf52f6cd824fa6bd6aa5"
uuid = "8149f6b0-98f6-5db9-b78f-408fbbb8ef88"
version = "1.2.0"

[[Wayland_jll]]
deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23"
uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89"
version = "1.19.0+0"

[[Wayland_protocols_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "66d72dc6fcc86352f01676e8f0f698562e60510f"
uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91"
version = "1.23.0+0"

[[XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.9.12+0"

[[XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"

[[Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.6.9+4"

[[Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.9+4"

[[Xorg_libXcursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd"
uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724"
version = "1.2.0+4"

[[Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.3+4"

[[Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.4+4"

[[Xorg_libXfixes_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4"
uuid = "d091e8ba-531a-589c-9de9-94069b037ed8"
version = "5.0.3+4"

[[Xorg_libXi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"]
git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246"
uuid = "a51aa0fd-4e3c-5386-b890-e753decda492"
version = "1.7.10+4"

[[Xorg_libXinerama_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"]
git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123"
uuid = "d1454406-59df-5ea1-beac-c340f2130bc3"
version = "1.1.4+4"

[[Xorg_libXrandr_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631"
uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484"
version = "1.5.2+4"

[[Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.10+4"

[[Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.0+3"

[[Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.13.0+3"

[[Xorg_libxkbfile_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "926af861744212db0eb001d9e40b5d16292080b2"
uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a"
version = "1.1.0+4"

[[Xorg_xcb_util_image_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97"
uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b"
version = "0.4.0+1"

[[Xorg_xcb_util_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"]
git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1"
uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5"
version = "0.4.0+1"

[[Xorg_xcb_util_keysyms_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00"
uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7"
version = "0.4.0+1"

[[Xorg_xcb_util_renderutil_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e"
uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e"
version = "0.3.9+1"

[[Xorg_xcb_util_wm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67"
uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361"
version = "0.4.1+1"

[[Xorg_xkbcomp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxkbfile_jll"]
git-tree-sha1 = "4bcbf660f6c2e714f87e960a171b119d06ee163b"
uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4"
version = "1.4.2+4"

[[Xorg_xkeyboard_config_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xkbcomp_jll"]
git-tree-sha1 = "5c8424f8a67c3f2209646d4425f3d415fee5931d"
uuid = "33bec58e-1273-512f-9401-5d533626f822"
version = "2.27.0+4"

[[Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.4.0+3"

[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"

[[Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"

[[libass_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47"
uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0"
version = "0.15.1+0"

[[libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "2.0.2+0"

[[libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.38+0"

[[libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "c45f4e40e7aafe9d086379e5578947ec8b95a8fb"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+0"

[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"

[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"

[[x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2021.5.5+0"

[[x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.5.0+0"

[[xkbcommon_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"]
git-tree-sha1 = "ece2350174195bb31de1a63bea3a41ae1aa593b6"
uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd"
version = "0.9.1+5"
"""

# ╔═╡ Cell order:
# ╠═83132240-ba23-11eb-3364-27aa887dc1ed
# ╠═ec91d11b-0034-4574-ba6b-14f605916c4b
# ╟─32b89ecb-4446-40cb-8190-c49e59c252ea
# ╟─233e8aa5-549a-4c11-83a9-8b015980ecda
# ╠═17e19c4b-f596-47c3-9542-1d86381c3c58
# ╠═195cf333-b46e-4510-a960-24f8e835bb5d
# ╠═2fa88e96-8be4-46ee-af6f-d8385ea27316
# ╠═9b3d1d97-e6b0-4800-bf81-72ae4fcde639
# ╠═d078708b-d6c3-40bb-afff-5b5faaacf6b0
# ╠═8a1bcc5e-fd23-4e22-a336-42149f2d1737
# ╠═8fbca243-21ae-473f-bdf7-279631736049
# ╠═27ec72b8-eb37-4b28-82ad-50041acfaf06
# ╠═303d7a7a-7f4c-4a0a-9eb3-5bd522ff84f5
# ╠═0bc8c6e5-1178-42fd-936f-f26509d8751d
# ╠═1165e774-045e-42c4-8644-2894455cd0cc
# ╠═c121c2ad-ac4b-469b-9680-80bed77d5a38
# ╠═796e888f-98b5-43c0-a852-e8beb38f19fc
# ╠═3b2adbf6-1d51-4571-9939-9c4546214514
# ╠═7df42e3f-5bb9-445b-9254-8943b7c9ab5f
# ╠═dc0a400b-0b94-4f97-882b-e11355afc10a
# ╠═88a0bc8a-cd2a-46d5-af28-d6d0b1a13ef5
# ╠═fb72b61d-a8db-435a-8c23-9f8d3525e845
# ╠═59d8f284-7d67-4e23-a660-7d0155bb3711
# ╟─6a196ee0-2f8c-46cb-bf32-37873e45a3bd
# ╟─2894f290-6d34-4771-a0f0-4772f257fdf9
# ╟─c52f1841-dba0-442e-ad2d-32bdd73db167
# ╟─c809174c-db19-4fc8-ad06-6ec3134e66c7
# ╠═dbb861f7-8852-4aa6-8401-8cfc4e897718
# ╠═6875e4b2-5ca9-436b-b982-1756592f9fca
# ╠═5aee7e72-113d-45c7-ad9b-ab474aa7de4a
# ╠═330cc960-8a01-4e3a-9856-cc945516db77
# ╠═554edb90-70e1-408d-971e-f3d756a8b8d4
# ╠═b70f11f9-1eeb-4cc0-95a3-11a39936336a
# ╠═787c8243-7267-472e-9d15-4d664b56f577
# ╠═aeaaa336-cb57-4b55-a350-0dc01adbaf5a
# ╠═74688ae9-8021-4ba8-bc03-5db34a90ee04
# ╠═c87b000d-0c4a-4a4c-8ab8-c7e3b762ec4b
# ╠═7956a1fc-9bd8-418c-bf22-370e2a426090
# ╠═c817eafc-8ebe-49a6-a53d-13b325d51012
# ╠═e8e9adcb-3a14-4785-a162-c1aafc03f516
# ╠═45f25de9-06ac-49de-b5e2-523927650d22
# ╠═422d7aa0-3e09-424d-8eb1-63d9eeaf13c8
# ╠═1636782b-4327-438e-afab-375c52ca0912
# ╠═a4498719-ebbc-4917-aa8b-3753a4bb49db
# ╠═30d4a5c1-cd1b-4acf-b8cc-eee54ccda363
# ╠═3d505342-61c2-4b09-a9aa-f3b64041efa8
# ╠═405bf0ef-f935-4a5b-a59d-9b1dd9ff4ca2
# ╠═641b2f68-a2c9-49cb-adbc-3ddee4e04cab
# ╠═9fd1b730-6d2c-4955-9de2-3ea76996f3df
# ╠═4ca03162-c38c-4f32-bee3-984d9509f657
# ╠═69fdc3d1-e75a-4479-ab9c-67982e5e6038
# ╠═7d597e41-1e88-421f-9f38-758523ec9bc9
# ╠═0dc9f30c-0852-47e2-b20b-30bb05f1978d
# ╠═2028733e-ef1d-4ee2-bc54-6f9c4286fe5b
# ╠═f7e817ac-2e94-4311-91db-d2b29c25dbc3
# ╠═036ffade-4b41-4aea-9176-49b15e520cfd
# ╠═a0350ced-095f-4c44-b298-faf2a34a178e
# ╠═2040daae-ce2f-44db-800a-be306efe916c
# ╠═eb0a1090-8ace-4d2f-8bf4-a206c0c43cca
# ╠═c834ef7b-816d-49d5-ab9b-93b0504fa9e9
# ╟─88411f35-2332-43f3-acd8-24169a03083e
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002

max_stars_repo_name: ashwani-rathee/Sardor

max_issues_repo_name: ashwani-rathee/Sardor

max_forks_repo_name: ashwani-rathee/Sardor


text:
module TestIterators

using Phylo
using Test

@testset "$TreeType" for TreeType in [Nonultrametric, Ultrametric]
    ntip = 10
    nur = rand(TreeType(ntip))

    nni = nodenameiter(nur)
    @test Base.IteratorEltype(nni) == Base.HasEltype()
    @test eltype(nni) == nodenametype(typeof(nur))
    @test Base.IteratorSize(nni) == Base.HasLength()
    @test length(nni) == 2 * ntip - 1

    ni = nodeiter(nur)
    @test Base.IteratorEltype(ni) == Base.HasEltype()
    @test eltype(ni) == nodetype(typeof(nur))
    @test Base.IteratorSize(ni) == Base.HasLength()
    @test length(ni) == 2 * ntip - 1
    @test Set(ni) == Set(map(n -> getnode(nur, n), nni))

    bni = branchnameiter(nur)
    @test Base.IteratorEltype(bni) == Base.HasEltype()
    @test eltype(bni) == branchnametype(typeof(nur))
    @test Base.IteratorSize(bni) == Base.HasLength()
    @test length(bni) == ntip * 2 - 2

    bi = branchiter(nur)
    @test Base.IteratorEltype(bi) == Base.HasEltype()
    @test eltype(bi) == branchtype(typeof(nur))
    @test Base.IteratorSize(bi) == Base.HasLength()
    @test length(bi) == 2 * ntip - 2
    @test Set(bi) == Set(map(b -> getbranch(nur, b), bni))
end

@testset "$TreeType with filter" for TreeType in [Nonultrametric, Ultrametric]
    ntip = 10
    nur = rand(TreeType(ntip))

    nni = nodenamefilter(isleaf, nur)
    @test Base.IteratorEltype(nni) == Base.HasEltype()
    @test eltype(nni) == nodenametype(typeof(nur))
    @test Base.IteratorSize(nni) == Base.HasLength()
    @test length(nni) == ntip
    leaves = collect(nni)
    @test Set(leaves) == Set(getleafnames(nur))

    ni = nodefilter(isleaf, nur)
    @test Base.IteratorEltype(ni) == Base.HasEltype()
    @test eltype(ni) == nodetype(typeof(nur))
    @test Base.IteratorSize(ni) == Base.HasLength()
    @test length(ni) == ntip
    @test all(n -> isleaf(nur, n), collect(ni))

    bni = branchnamefilter(nur) do tree, branch
        return isleaf(tree, dst(tree, branch))
    end
    @test Base.IteratorEltype(bni) == Base.HasEltype()
    @test eltype(bni) == branchnametype(typeof(nur))
    @test Base.IteratorSize(bni) == Base.HasLength()
    @test length(bni) == ntip

    bi = branchfilter(nur) do tree, branch
        return isleaf(tree, dst(tree, branch))
    end
    @test Base.IteratorEltype(bi) == Base.HasEltype()
    @test eltype(bi) == branchtype(typeof(nur))
    @test Base.IteratorSize(bi) == Base.HasLength()
    @test length(bi) == ntip
    bileaves = map(b -> dst(bi.tree, b), bi)
    @test Set(bileaves) == Set(getnode.(nur, leaves))
end

end


text:
export capacity, sample, SumTree

import StatsBase: sample

"""
    SumTree(capacity::Int)
Efficiently sample and update weights.
For more detals, see the post at [here](https://jaromiru.com/2016/11/07/lets-make-a-dqn-double-learning-and-prioritized-experience-replay/).
Here we use a vector to represent the binary tree.
Suppose we will have `capacity` leaves at most.
Every time we `push!` new node into the tree, only the recent `capacity` node and their sum will be updated!
[------------Parent nodes------------][--------leaves--------]
[size: 2^ceil(Int, log2(capacity))-1 ][     size: capacity   ]
# Example
```julia
julia> t = SumTree(8)
0-element SumTree
julia> for i in 1:16
       push!(t, i)
       end
julia> t
8-element SumTree:
  9.0
 10.0
 11.0
 12.0
 13.0
 14.0
 15.0
 16.0
julia> sample(t)
(2, 10.0)
julia> sample(t)
(1, 9.0)
julia> inds, ps = sample(t,100000)
([8, 4, 8, 1, 5, 2, 2, 7, 6, 6  …  1, 1, 7, 1, 6, 1, 5, 7, 2, 7], [16.0, 12.0, 16.0, 9.0, 13.0, 10.0, 10.0, 15.0, 14.0, 14.0  …  9.0, 9.0, 15.0, 9.0, 14.0, 9.0, 13.0, 15.0, 10.0, 15.0])
julia> countmap(inds)
Dict{Int64,Int64} with 8 entries:
  7 => 14991
  4 => 12019
  2 => 10003
  3 => 11027
  5 => 12971
  8 => 16052
  6 => 13952
  1 => 8985
julia> countmap(ps)
Dict{Float64,Int64} with 8 entries:
  9.0  => 8985
  13.0 => 12971
  10.0 => 10003
  14.0 => 13952
  16.0 => 16052
  11.0 => 11027
  15.0 => 14991
  12.0 => 12019
```
"""
mutable struct SumTree{T} <: AbstractArray{Int,1}
    capacity::Int
    first::Int
    length::Int
    nparents::Int
    tree::Vector{T}
    SumTree(capacity::Int) = SumTree(Float64, capacity)
    function SumTree(T, capacity)
        nparents = 2^ceil(Int, log2(capacity)) - 1
        new{T}(capacity, 1, 0, nparents, zeros(T, nparents + capacity))
    end
end

capacity(t::SumTree) = t.capacity
Base.length(t::SumTree) = t.length
Base.size(t::SumTree) = (length(t),)

function _index(t::SumTree, i::Int)
    ind = i + t.first - 1
    if ind > t.capacity
        ind -= t.capacity
    end
    ind
end

_tree_index(t::SumTree, i) = t.nparents + _index(t, i)

Base.getindex(t::SumTree, i::Int) = t.tree[_tree_index(t, i)]

function Base.setindex!(t::SumTree, p, i)
    tree_ind = _tree_index(t, i)
    change = p - t.tree[tree_ind]
    t.tree[tree_ind] = p
    while tree_ind != 1
        tree_ind = tree_ind ÷ 2
        t.tree[tree_ind] += change
    end
end

function Base.push!(t::SumTree, p)
    if t.length == t.capacity
        t.first = (t.first == t.capacity ? 1 : t.first + 1)
    else
        t.length += 1
    end
    t[t.length] = p
end

function Base.empty!(t::SumTree)
    t.length = 0.0
    fill!(t.tree, 0.0)
    # yes, no need to reset `t.first`
    # so, don't rely on that `t.first` is always 1 after `empty!`
    t
end

"!!! this is unsafe, always check the `real_ind`, or you may get bound error in some extreme cases."
function get(t::SumTree, v)
    parent_ind = 1
    leaf_ind = parent_ind
    while true
        left_child_ind = parent_ind * 2
        right_child_ind = left_child_ind + 1
        if left_child_ind > length(t.tree)
            leaf_ind = parent_ind
            break
        else
            if v ≤ t.tree[left_child_ind]
                parent_ind = left_child_ind
            else
                v -= t.tree[left_child_ind]
                parent_ind = right_child_ind
            end
        end
    end
    p = t.tree[leaf_ind]
    ind = leaf_ind - t.nparents
    real_ind = ind >= t.first ? ind - t.first + 1 : ind + t.capacity - t.first + 1
    real_ind, p
end

sample(t::SumTree{T}) where {T} = get(t, rand(T) * t.tree[1])

function sample(t::SumTree, n::Int)
    inds, priorities = Vector{Int}(undef, n), Vector{Float64}(undef, n)
    for i = 1:n
        ind, p = sample(t)
        inds[i] = ind
        priorities[i] = p
    end
    inds, priorities
end


text:
# Autogenerated wrapper script for VideoCaptureWrap_jll for armv7l-linux-gnueabihf-cxx11
export libvideocapture

using libcxxwrap_julia_jll
using OpenCVQt_jll
JLLWrappers.@generate_wrapper_header("VideoCaptureWrap")
JLLWrappers.@declare_library_product(libvideocapture, "libvideocapture.so")
function __init__()
    JLLWrappers.@generate_init_header(libcxxwrap_julia_jll, OpenCVQt_jll)
    JLLWrappers.@init_library_product(
        libvideocapture,
        "lib/libvideocapture.so",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
# function read_issue(refid::String)
#     rrfile = _rr_srcfile(refid)
#     if !isfile(rrfile)
#         error("No report found!!!")
#     end
#     return read(rrfile, RBDoc)
# end


text:
#=
preprocessing and initial point finding functions for interior point algorithms
=#

MatrixyAG = Union{AbstractMatrix, UniformScaling}

# delete later, affects qr. see https://github.com/JuliaLang/julia/pull/40623
if VERSION < v"1.7.0-DEV.1188"
    const ColumnNorm = Val{true}
end

# rescale the rows and columns of the conic data to get an equivalent conic problem
function rescale_data(solver::Solver{T}) where {T <: Real}
    solver.rescale || return false
    model = solver.model
    (c, A, b, G, h) = (model.c, model.A, model.b, model.G, model.h)
    (isa(A, MatrixyAG) && isa(G, MatrixyAG)) || return false

    minval = sqrt(eps(T))
    maxabsmin(v::AbstractVecOrMat) = mapreduce(abs, max, v; init = minval)
    maxabsmincol(v::UniformScaling, ::Int) = max(abs(v.λ), minval)
    maxabsmincol(v::AbstractMatrix, j::Int) = maxabsmin(view(v, :, j))
    maxabsminrow(v::UniformScaling, ::Int) = max(abs(v.λ), minval)
    maxabsminrow(v::AbstractMatrix, i::Int) = maxabsmin(view(v, i, :))
    maxabsminrows(v::UniformScaling, ::UnitRange{Int}) = max(abs(v.λ), minval)
    maxabsminrows(v::AbstractMatrix, rows::UnitRange{Int}) =
        maxabsmin(view(v, rows, :))

    @inbounds solver.c_scale = c_scale = T[sqrt(max(abs(c[j]),
        maxabsmincol(A, j), maxabsmincol(G, j))) for j in eachindex(c)]
    @inbounds solver.b_scale = b_scale = T[sqrt(max(abs(b[i]),
        maxabsminrow(A, i))) for i in eachindex(b)]

    h_scale = solver.h_scale = ones(T, model.q)
    for (k, cone) in enumerate(model.cones)
        idxs = model.cone_idxs[k]
        if cone isa Cones.Nonnegative
            for i in idxs
                @inbounds h_scale[i] = sqrt(max(abs(h[i]), maxabsminrow(G, i)))
            end
        else
            # TODO store single scale value only?
            @inbounds @views h_scale[idxs] .= sqrt(
                max(maxabsmin(h[idxs]), maxabsminrows(G, idxs)))
        end
    end

    c_diag = Diagonal(c_scale)
    model.c = c_diag \ c
    model.A = A / c_diag
    model.G = G / c_diag
    b_diag = Diagonal(b_scale)
    model.b = b_diag \ b
    ldiv!(b_diag, model.A)
    h_diag = Diagonal(h_scale)
    model.h = h_diag \ h
    ldiv!(h_diag, model.G)

    return true
end

# optionally preprocess dual equalities and solve for x as least squares
# solution to Ax = b, Gx = h - s
function find_initial_x(
    solver::Solver{T},
    init_s::Vector{T},
    ) where {T <: Real}
    if solver.status != SolveCalled
        return zeros(T, 0)
    end
    model = solver.model
    n = model.n
    if iszero(n) # x is empty (no primal variables)
        solver.x_keep_idxs = Int[]
        return zeros(T, 0)
    end
    p = model.p
    q = model.q
    A = model.A
    G = model.G
    solver.x_keep_idxs = 1:n

    rhs = vcat(model.b, model.h - init_s)

    # indirect method
    if solver.init_use_indirect || !isa(A, MatrixyAG) || !isa(G, MatrixyAG)
        # TODO pick lsqr or lsmr
        if iszero(p)
            AG = G
        else
            linmap(M::UniformScaling) = LinearMaps.LinearMap(M, n)
            linmap(M) = LinearMaps.LinearMap(M)
            AG = vcat(linmap(A), linmap(G))
        end
        init_x = IterativeSolvers.lsqr(AG, rhs)
        return init_x
    end

    # direct method
    if iszero(p)
        # A is empty
        if issparse(G)
            AG = G
        elseif G isa Matrix{T}
            AG = copy(G)
        else
            AG = Matrix(G)
        end
    else
        AG = vcat(A, G)
    end
    if issparse(AG)
        if !(T <: Float64)
            @warn("using dense factorization of [A; G] in preprocessing and " *
                "initial point finding because sparse factorization for number " *
                "type $T is not supported by SuiteSparse packages")
            AG_fact = qr!(Matrix(AG), ColumnNorm())
        else
            AG_fact = qr(AG, tol = solver.init_tol_qr)
        end
    else
        AG_fact = qr!(AG, ColumnNorm())
    end
    AG_rank = get_rank_est(AG_fact, solver.init_tol_qr)

    if !solver.preprocess || (AG_rank == n)
        if AG_rank < n
            @warn("some dual equalities appear to be dependent " *
            "(possibly inconsistent); try using preprocess = true")
        end
        init_x = AG_fact \ rhs
        return init_x
    end

    # preprocess dual equalities
    col_piv = (AG_fact isa QRPivoted{T, Matrix{T}}) ? AG_fact.p : AG_fact.pcol
    x_keep_idxs = col_piv[1:AG_rank]
    AG_R = UpperTriangular(AG_fact.R[1:AG_rank, 1:AG_rank])

    c_sub = model.c[x_keep_idxs]
    # yz_sub = AG_fact.Q * vcat((AG_R' \ c_sub), zeros(p + q - AG_rank))
    yz_sub = zeros(T, p + q)
    yz_sub1 = view(yz_sub, 1:AG_rank)
    copyto!(yz_sub1, c_sub)
    ldiv!(AG_R', yz_sub1)
    lmul!(AG_fact.Q, yz_sub)
    if !(AG_fact isa QRPivoted{T, Matrix{T}})
        yz_sub = yz_sub[AG_fact.rpivinv]
    end
    @views residual = norm(A' * yz_sub[1:p] + G' *
        yz_sub[(p + 1):end] - model.c, Inf)
    if residual > solver.init_tol_qr
        if solver.verbose
            println("some dual equality constraints are inconsistent " *
            "(residual $residual, tolerance $(solver.init_tol_qr))")
        end
        solver.status = DualInconsistent
        return zeros(T, 0)
    end
    if solver.verbose
        println("$(n - AG_rank) of $n dual equality constraints are dependent")
    end

    # modify solver.model to remove/reorder some primal variables x
    model.c = c_sub
    model.A = A[:, x_keep_idxs]
    model.G = G[:, x_keep_idxs]
    model.n = AG_rank
    solver.x_keep_idxs = x_keep_idxs

    # init_x = AG_R \ ((AG_fact.Q' * vcat(b, h - point.s))[1:AG_rank])
    temp = vcat(model.b, model.h - init_s)
    lmul!(AG_fact.Q', temp)
    init_x = temp[1:model.n]
    ldiv!(AG_R, init_x)

    return init_x
end

# optionally preprocess primal equalities and solve for y as least squares
# solution to A'y = -c - G'z
function find_initial_y(
    solver::Solver{T},
    init_z::Vector{T},
    reduce::Bool,
    ) where {T <: Real}
    if solver.status != SolveCalled
        return zeros(T, 0)
    end
    model = solver.model
    p = model.p
    if iszero(p) # y is empty (no primal variables)
        solver.y_keep_idxs = Int[]
        solver.Ap_R = UpperTriangular(zeros(T, 0, 0))
        solver.Ap_Q = I
        return zeros(T, 0)
    end
    n = model.n
    q = model.q
    A = model.A
    solver.y_keep_idxs = 1:p

    if !reduce || !isa(A, MatrixyAG)
        # rhs = -c - G' * point.z
        rhs = copy(model.c)
        mul!(rhs, model.G', init_z, -1, -1)

        # indirect method
        if solver.init_use_indirect
            # TODO pick lsqr or lsmr
            init_y = IterativeSolvers.lsqr(A', rhs)
            return init_y
        end
    end

    # factorize A'
    if issparse(A)
        if !(T <: Float64)
            @warn("using dense factorization of A' in preprocessing and initial " *
                "point finding because sparse factorization for number type $T " *
                "is not supported by SuiteSparse packages")
            Ap_fact = qr!(Matrix(A'), ColumnNorm())
        else
            Ap_fact = qr(sparse(A'), tol = solver.init_tol_qr)
        end
    else
        Ap_fact = qr!(Matrix(A'), ColumnNorm())
    end
    Ap_rank = get_rank_est(Ap_fact, solver.init_tol_qr)

    if !reduce && !solver.preprocess
        if Ap_rank < p
            @warn("some primal equalities appear to be dependent " *
            "(possibly inconsistent); try using preprocess = true")
        end
        init_y = Ap_fact \ rhs
        return init_y
    end

    # preprocess dual equalities
    Ap_R = UpperTriangular(Ap_fact.R[1:Ap_rank, 1:Ap_rank])
    col_piv = (Ap_fact isa QRPivoted{T, Matrix{T}}) ? Ap_fact.p : Ap_fact.pcol
    y_keep_idxs = col_piv[1:Ap_rank]
    Ap_Q = Ap_fact.Q

    b_sub = model.b[y_keep_idxs]
    if Ap_rank < p
        # some dependent primal equalities, so check if they are consistent
        # x_sub = Ap_Q * vcat((Ap_R' \ b_sub), zeros(n - Ap_rank))
        x_sub = zeros(T, n)
        x_sub1 = view(x_sub, 1:Ap_rank)
        copyto!(x_sub1, b_sub)
        ldiv!(Ap_R', x_sub1)
        lmul!(Ap_Q, x_sub)

        if !(Ap_fact isa QRPivoted{T, Matrix{T}})
            x_sub = x_sub[Ap_fact.rpivinv]
        end
        residual = norm(A * x_sub - model.b, Inf)
        if residual > solver.init_tol_qr
            if solver.verbose
                println("some primal equality constraints are inconsistent " *
                "(residual $residual, tolerance $(solver.init_tol_qr))")
            end
            solver.status = PrimalInconsistent
            return zeros(T, 0)
        end
        if solver.verbose
            println("$(p - Ap_rank) of $p primal equality constraints " *
                "are dependent")
        end
    end

    if reduce && isa(model.G, MatrixyAG)
        # remove all primal equalities by making A and b empty with
        # n = n0 - p0 and p = 0
        # TODO improve efficiency
        # TODO avoid calculating GQ1 explicitly if possible
        # recover original-space solution using:
        # x0 = Q * [(R' \ b0), x]
        # y0 = R \ (-cQ1' - GQ1' * z0)
        if !(Ap_fact isa QRPivoted{T, Matrix{T}})
            row_piv = Ap_fact.prow
            model.c = model.c[row_piv]
            model.G = model.G[:, row_piv]
            solver.reduce_row_piv_inv = Ap_fact.rpivinv
        else
            solver.reduce_row_piv_inv = Int[]
        end

        Q1_idxs = 1:Ap_rank
        Q2_idxs = (Ap_rank + 1):n

        # [cQ1 cQ2] = c0' * Q
        cQ = model.c' * Ap_Q
        cQ1 = solver.reduce_cQ1 = cQ[Q1_idxs]
        cQ2 = cQ[Q2_idxs]
        # c = cQ2
        model.c = cQ2
        model.n = length(model.c)
        # offset = offset0 + cQ1 * (R' \ b0)
        Rpib0 = solver.reduce_Rpib0 = ldiv!(Ap_R', b_sub)
        # solver.Rpib0 = Rpib0 # TODO
        model.obj_offset += dot(cQ1, Rpib0)

        # [GQ1 GQ2] = G0 * Q
        # very inefficient method used for sparse G * QRSparseQ
        # see https://github.com/JuliaLang/julia/issues/31124#issuecomment-501540818
        if model.G isa UniformScaling
            side = size(Ap_Q, 1)
            G_mul = Matrix{T}(model.G, side, side)
        elseif !isa(model.G, Matrix)
            G_mul = Matrix{T}(model.G)
        else
            G_mul = model.G
        end
        GQ = G_mul * Ap_Q
        GQ1 = solver.reduce_GQ1 = GQ[:, Q1_idxs]
        GQ2 = GQ[:, Q2_idxs]
        # h = h0 - GQ1 * (R' \ b0)
        mul!(model.h, GQ1, Rpib0, -1, true)

        # G = GQ2
        model.G = GQ2

        # A and b empty
        model.p = 0
        model.A = zeros(T, 0, model.n)
        model.b = zeros(T, 0)
        solver.reduce_Ap_R = Ap_R
        solver.reduce_Ap_Q = Ap_Q

        solver.reduce_y_keep_idxs = y_keep_idxs
        solver.Ap_R = UpperTriangular(zeros(T, 0, 0))
        solver.Ap_Q = I

        return zeros(T, 0)
    end

    # init_y = Ap_R \ ((Ap_fact.Q' * (-c - G' * point.z))[1:Ap_rank])
    temp = copy(model.c)
    mul!(temp, model.G', init_z, true, true)
    lmul!(Ap_fact.Q', temp)
    init_y = temp[1:Ap_rank]
    init_y .*= -1
    ldiv!(Ap_R, init_y)

    # modify solver.model to remove/reorder some dual variables y
    if !(Ap_fact isa QRPivoted{T, Matrix{T}})
        row_piv = Ap_fact.prow
        model.A = A[y_keep_idxs, row_piv]
        model.c = model.c[row_piv]
        model.G = model.G[:, row_piv]
        solver.x_keep_idxs = solver.x_keep_idxs[row_piv]
    else
        model.A = A[y_keep_idxs, :]
    end
    model.b = b_sub
    model.p = Ap_rank
    solver.y_keep_idxs = y_keep_idxs
    solver.Ap_R = Ap_R
    solver.Ap_Q = Ap_Q

    return init_y
end

# (pivoted) QR factorizations are usually rank-revealing but may be unreliable
# see http://www.math.sjsu.edu/~foster/rankrevealingcode.html
# TODO could replace this with rank(qr_fact) when available for both dense and sparse
get_rank_est(qr_fact::SuiteSparse.SPQR.QRSparse, init_tol_qr::Real) =
    rank(qr_fact)

function get_rank_est(qr_fact::QRPivoted, init_tol_qr::Real)
    factors = qr_fact.factors
    rank_est = 0
    for i in diagind(factors)
        if abs(factors[i]) > init_tol_qr
            rank_est += 1
        end
    end
    return rank_est
end

# postprocess the interior point and save in result point
function postprocess(solver::Solver{T}) where {T <: Real}
    point = solver.point
    result = solver.result
    if in(solver.status, (PrimalInfeasible, DualInfeasible))
        tau = true
    else
        tau = point.tau[]
        if tau <= 0
            result.vec .= NaN
            return
        end
    end

    # finalize s,z
    @. result.s = point.s / tau
    @. result.z = point.z / tau

    # finalize x
    if solver.preprocess && !iszero(solver.orig_model.n) && !any(isnan, point.x)
        # unpreprocess solver's solution
        if solver.reduce && !iszero(solver.orig_model.p)
            # unreduce solver's solution
            # x = Q * [(R' \ b0), x]
            xa = zeros(T, solver.orig_model.n - length(solver.reduce_Rpib0))
            @. @views xa[solver.x_keep_idxs] = point.x / tau
            if in(solver.status, (PrimalInfeasible, DualInfeasible))
                Rpib0 = zeros(T, length(solver.reduce_Rpib0))
            else
                Rpib0 = solver.reduce_Rpib0
            end
            xb = vcat(Rpib0, xa)
            lmul!(solver.reduce_Ap_Q, xb)
            if isempty(solver.reduce_row_piv_inv)
                result.x .= xb
            else
                @. @views result.x = xb[solver.reduce_row_piv_inv]
            end
        else
            @. @views result.x[solver.x_keep_idxs] = point.x / tau
        end
    else
        @. result.x = point.x / tau
    end

    # finalize y
    if solver.preprocess && !iszero(solver.orig_model.p) && !any(isnan, point.y)
        # unpreprocess solver's solution
        if solver.reduce
            # unreduce solver's solution
            # y = R \ (-cQ1' - GQ1' * z)
            ya = solver.reduce_GQ1' * result.z
            if !in(solver.status, (PrimalInfeasible, DualInfeasible))
                ya .+= solver.reduce_cQ1
            end
            @views ldiv!(solver.reduce_Ap_R,
                ya[1:length(solver.reduce_y_keep_idxs)])
            @. @views result.y[solver.reduce_y_keep_idxs] = -ya
        else
            @. @views result.y[solver.y_keep_idxs] = point.y / tau
        end
    else
        @. result.y = point.y / tau
    end

    if solver.used_rescaling
        # unscale result
        result.s .*= solver.h_scale
        result.z ./= solver.h_scale
        result.y ./= solver.b_scale
        result.x ./= solver.c_scale
    end

    return
end


text:
using DataFrames, CSV

using GLMNet, Distributions, Random
using SubsetSelection
using SubsetSelectionCIO
include("data_construction.jl") #Functions to generate data
include("cv.jl")    #Utilities to conduct cross-validation
include("oa/oa_cv.jl")

EXPERIMENTS = DataFrame(prefix=["ML"], snr = [1e8], ρ = [.3])

## Choose loss function for sparse classication -- See SubsetSelection.jl documentation
ℓ = SubsetSelection.L1SVM()
#ℓ = SubsetSelection.LogReg()

do_lasso = false #Indicates whether to compute the Lasso solution
do_enet = false #Indicates whether to compute the Enet solution
do_saddle = true #Indicates whether to use the Boolean relaxation as warmstart to CIOF
do_cio = true #Indicates whether to compute the CIO solution

savedir = "results/"
mkpath(savedir)

iter_run = 1 #Number of the iteration (for averaging)
n = 500 #Number of observations
p = 1000 #Number of features
k = 30 #Size of the support

prefix= "ML" #prefix for result files
snr = 1e8 #signal-to-noise ratio
ρ = 0.3 #correlation in the Toeplitz correlation matrix

#Dataframes to save results
LASSO = DataFrame(run = Int[], n=Int[], r=Int[], SNR=Real[], rho= Real[], k=Int[],
                time=Real[], A=Real[], AUC=Real[], MR=Real[])
ENET = DataFrame(run = Int[], n=Int[], r=Int[], SNR=Real[], rho= Real[], k=Int[],
                alpha=Real[], time=Real[], A=Real[], AUC=Real[], MR=Real[])
SADDLE = DataFrame(run = Int[], n=Int[], r=Int[], SNR=Real[], rho= Real[], k=Int[],
                gamma=Real[], factor=[], time=Real[], cuts=Real[], A=Real[], AUC=Real[], MR=Real[])
CIO = DataFrame(run = Int[], n=Int[], r=Int[], SNR=Real[], rho= Real[], k=Int[],
                gamma=Real[], factor=[], time=Real[], Gap=Real[], cuts=Real[], A=Real[], AUC=Real[], MR=Real[])

Random.seed!(n+536*iter_run)

println("***********************")
println("BUILDING DATA")
println("***********************")
X, Y, indices_true, w_true = data_construction(SubsetSelection.L1SVM(), n+200, k, p, snr, ρ)

normalization = sqrt.(sum(X.^2,dims=1))/sqrt.(size(X,1))
X = X./normalization

train = 1:n
val = (n+1):(n+200)

println("***********************")
println("Samples = ", n)
println("Features = ", p)
println("Sparsity = ", k)
println("SNR = ", snr)
println("ρ = ", ρ)
println("***********************")

println("***********************")
println("Julia-LASSO")
println("***********************")
Y_transf = [(Y[train].<0) (Y[train].>0)]

t0 = time_ns()
l1 = glmnet(X[train,:], convert(Matrix{Float64}, Y_transf), GLMNet.Binomial(), intercept=false)
Δt_lasso = (time_ns() - t0)*(1e-9)

if do_lasso
    col = size(l1.betas, 2)
    while length(findall(s->abs(s)>1e-8, l1.betas[:, col]))>k && col>=1
        col = col - 1
    end

    indices_lasso = findall(s->abs(s)>1e-8, l1.betas[:, col])
    w_lasso = l1.betas[:, col][indices_lasso]

    accuracy_lasso = length(intersect(indices_true, indices_lasso))/k*100
    auc_lasso = 1-error(ℓ, Y[val], X[val,:], indices_lasso, w_lasso)
    mr_lasso = error2(ℓ, Y[val], X[val,:], indices_lasso, w_lasso)
    push!(LASSO, [iter_run, n, p, snr, ρ, k, Δt_lasso, accuracy_lasso, auc_lasso, mr_lasso])
    filename = string(prefix, "LassoFix", array_num, ".csv")
    CSV.write(savedir*filename, LASSO)
end

println("***********************")
println("Julia-ENET")
println("***********************")
if do_enet
    for α in 0.1:.1:1
        t0 =time_ns()
        enet = glmnet(X[train,:], convert(Matrix{Float64}, Y_transf), GLMNet.Binomial(), intercept=false, alpha=α)
        Δt_enet = (time_ns() - t0)*(1e-9)

        col = size(enet.betas, 2)
        while length(findall(s->abs(s)>1e-8, enet.betas[:, col]))>k && col>=1
            col = col - 1
        end

        indices_enet = findall(s->abs(s)>1e-8, enet.betas[:, col])
        w_enet = enet.betas[:, col][indices_enet]

        accuracy_enet = length(intersect(indices_true, indices_enet))/k*100
        auc_enet = 1-error(ℓ, Y[val], X[val,:], indices_enet, w_enet)
        mr_enet = error2(ℓ, Y[val], X[val,:], indices_enet, w_enet)
        push!(ENET, [iter_run, n, p, snr, ρ, k, α, Δt_enet/Δt_lasso, accuracy_enet, auc_enet, mr_enet])
        filename = string(prefix, "EnetFix", array_num, ".csv")
        CSV.write(savedir*filename, ENET)
    end
end

println("***********************")
println("Julia - SADDLE POINT RELAXATION and CUTTING PLANES")
println("***********************")
if do_saddle||do_cio
  # Regularization
  subsetSelection(ℓ, Constraint(10), Y[1:10], X[1:10,:], maxIter=10)

  γ0 = 1. *p / k / (maximum(sum(X[train,:].^2,dims=2))*n)
  factor = 1000.

  indicesRelax=findall(x-> x< k/size(X,2), rand(size(X,2)))
  stop = false;

  for inner_epoch in 1:10

      if !stop
        γ = factor*γ0
        println("***********************")
        println("Sparsity k = ", k)
        println("Regularization γ = ", γ)
        println("***********************")

        #Initialization for CIO: Either Boolean relaxation or GLMNet
        if do_saddle
            maxCut = 100
            t0=time_ns()
            result_saddle = subsetSelection(SubsetSelection.L1SVM(), Constraint(k), Y[train], X[train,:],
                                            intercept=false, numberRestarts=1, maxIter=maxCut)
            Δt_saddle = (time_ns() - t0)*(1e-9)
            indices_saddle = result_saddle.indices[:]
            w_saddle = result_saddle.w

            accuracy_saddle = length(intersect(indices_true, indices_saddle))/k*100
            auc_saddle = 1-error(SubsetSelection.L1SVM(), Y[val], X[val,:], indices_saddle, w_saddle)
            mr_saddle = error2(SubsetSelection.L1SVM(), Y[val], X[val,:], indices_saddle, w_saddle)

            push!(SADDLE, [iter_run, n, p, snr, ρ, k,
                γ, factor, Δt_saddle/Δt_lasso, maxCut, accuracy_saddle, auc_saddle, mr_saddle])
            filename = string(prefix, "SaddleFix", array_num, ".csv")
            CSV.write(savedir*filename, SADDLE)

            indicesRelax = result_saddle.indices[:]
        else
            l1 = glmnet(X[train,:], convert(Matrix{Float64}, Y_transf), GLMNet.Binomial(), dfmax=k, intercept=false)
            col = size(l1.betas, 2)
            while length(findall(s->abs(s)>1e-8, l1.betas[:, col]))>k && col>=1
                col = col - 1
            end
            indicesRelax = findall(s->abs(s)>1e-8, l1.betas[:, col])
        end

        indices_cio, w_cio, Δt_cio, status, Gap, cutCount = oa_formulation(ℓ, Y[train], X[train,:], k, γ,
              indices0=indicesRelax,
              solver=:Gurobi, ΔT_max=180., verbose=false, rootnode=true, rootCuts=100, stochastic=true)

        accuracy_cio = length(intersect(indices_true, indices_cio))/k*100
        auc_cio = 1-error(ℓ, Y[val], X[val,:], indices_cio, w_cio)
        mr_cio = error2(ℓ, Y[val], X[val,:], indices_cio, w_cio)

        push!(CIO, [iter_run, n, p, snr, ρ, k,
            γ, factor, Δt_cio, Gap, cutCount, accuracy_cio, auc_cio, mr_cio])
        filename = string(prefix, "CIOFix", array_num, "_StochasticWS.csv")
        CSV.write(savedir*filename, CIO)

        g_old = norm(grad_primal(ℓ, Y[train], X[train, indices_cio], zeros(length(indices_cio)), 2*γ))
        g_new = norm(grad_primal(ℓ, Y[train], X[train, indices_cio], w_cio, 2*γ))
        stop = (g_new / g_old < 1e-2)

        factor *=2
      end
  end
end


text:
using MathMLRepr
using Test

@testset "MathMLRepr.jl" begin
    # Write your tests here.
end