text:
#holds the time-indexed parameters and a pre-allocation for the row-indexed versions
struct VolumePartsDLSq{
    TΠ<:AbstractVector,
    TA<:AbstractMatrix,
    TV₀<:AbstractVector,
    Tts<:AbstractVector,
    Texpand<:NamedTuple,
    elTΠ<:Real} <: AbstractVolumePartsLSq{TΠ, TA, Tts, Texpand, elTΠ}

  Π::TΠ
  A::TA
  V₀::TV₀

  #not to be accessed directly- indices for the expand function
  ts::Tts
  expand::Texpand

  #inner constructor needed to identify elTΠ
  function VolumePartsDLSq(Π::TΠ, A::TA, V₀::TV₀, ts::Tts, expand::Texpand) where {
      TΠ, TA, TV₀, Tts, Texpand}

    @assert (Π == reduce(vcat, [vec(A), vec(V₀)]))

    return new{TΠ, TA, TV₀, Tts, Texpand, eltype(TΠ)}(Π,A,V₀,ts,expand)
  end
end

#pre-allocates for the vpexpand
function VolumePartsDLSq(A::TA, V₀::TV₀, ts::Tts) where {
    TA<:AbstractMatrix,
    TV₀<:AbstractVector,
    Tts<:AbstractVector}

  #create vector versions for the parameter vector
  vecA = vec(A)
  vecV₀ = vec(V₀)

  #this will hold the parameter data
  Π = reduce(vcat, [vecA, vecV₀])
  start=1
  linkedA = less_unsafe_wrap(TA, source=Π, start=start, dims=size(A))
  start+=length(vecA)
  linkedV₀ = less_unsafe_wrap(TV₀, source=Π, start=start, dims=size(V₀))
  start+=length(vecV₀)
  @assert start - 1 == length(Π)

  #final checks on the linked dataframes
  @assert sum(linkedA .== A) + sum(linkedV₀ .== V₀) == length(Π)

  expand = (A = view(linkedA, :, ts),
    LA = view(linkedA, :, ts .- 1),
    V₀ = view(linkedV₀, ts .- 1))

  Θ = VolumePartsDLSq(Π, linkedA, linkedV₀, ts, expand)
  return Θ
end

#basic constructor from dimension arguments
function VolumePartsDLSq(T::Int, K::Int, ts::Vector{Int}, ::Type{Tvp}=PARAM[:opttype],
  ::Type{TV}=PARAM[:optgpu] ? CUDA.CuVector{Tvp} : Vector{Tvp},
  ::Type{TM}=PARAM[:optgpu] ? CUDA.CuMatrix{Tvp} : Matrix{Tvp},
    ) where {Tvp<:Real, TV<:AbstractVector{Tvp}, TM<:AbstractMatrix{Tvp}}

  #note- includes a work-around until Flux.gpu works
  A = TM(abs.(randn(Tvp, K,T)))
  V₀ = TV(abs.(randn(Tvp, T-1)))

  return VolumePartsDLSq(A, V₀, ts)
end

#creates new VolumeParts with copies of the trainable portion and pass-by-reference
# of the non-trainable indices
function copytrainable(Θ::VolumePartsDLSq)
  #copy trainable portions by value
  A  = deepcopy(Θ.A)
  V₀  = deepcopy(Θ.V₀)

  #copy the non-trainable portions by reference
  return VolumePartsDLSq(A, V₀, Θ.ts)
end

#needed due to the segemented array structure
function Base.deepcopy(Θ::VolumePartsDLSq)
  A  = deepcopy(Θ.A)
  V₀  = deepcopy(Θ.V₀)
  ts = deepcopy(Θ.ts)

  return VolumePartsDLSq(A,V₀,ts)
end

function (Θ::VolumePartsDLSq)(X::NamedTuple, ::AbstractVector, ::Val{:level})
  @unpack ws, RLws = X
  #first map each coefficient to its appropriate

  absμₖ = abs.(Θ.expand.A .* ws' .- Θ.expand.LA .* RLws')
  absμ = vec(sum(absμₖ,dims=1)) .+ exp.(Θ.expand.V₀)

  return absμ
end

function (Θ::VolumePartsDLSq)(X::NamedTuple, ::CuVector{T}, ::Val{:level}) where T
  @unpack ws, RLws = X
  @unpack A, LA, V₀ = Θ.expand
  #first map each coefficient to its appropriate

  absμₖ = cudaabsμₖ.(A, LA, ws', RLws')
  absμ = CUDA.vec(CUDA.sum(absμₖ,dims=1)) .+ CUDA.exp.(V₀)

  return absμ
end

function (Θ::VolumePartsDLSq)(X::NamedTuple, ::AbstractVector, ::Val{:levellog})
  @unpack ws, RLws = X
  #first map each coefficient to its appropriate

  absμₖ = abs.((exp).(Θ.expand.A) .* ws' .- (exp).(Θ.expand.LA) .* RLws')
  absμ = vec(sum(absμₖ,dims=1)) .+ exp.(Θ.expand.V₀)

  return absμ
end

Flux.@functor VolumePartsDLSq
Flux.params(Θ::VolumePartsDLSq) = Flux.params(Θ.A, Θ.V₀,)

struct JacobianCache{TVolumeParts<:AbstractVolumeParts,
    TJcolmap<:NamedTuple,
    Tindex<:NamedTuple,
    TbaseJ<:AbstractMatrix}

  Jcolmap::TJcolmap
  index::Tindex
  baseJ::TbaseJ

  #inner constructor captures the type of VolumeParts
  function JacobianCache(::TVolumeParts, Jcolmap::TJcolmap, index::Tindex, baseJ::TbaseJ) where {
      TVolumeParts,TJcolmap, Tindex, TbaseJ}
    return new{TVolumeParts, TJcolmap, Tindex, TbaseJ}(Jcolmap, index, baseJ)
  end
end

function jacobiancolmap(Θ::VolumePartsDLSq)

  #map each entry in the matrix to a corresponding entry in A
  start::Int = 1
  start, Amap = map2linear(start, size(Θ.A))
  start, V₀map = map2linear(start, size(Θ.V₀))

  #checks that should always be true
  @assert start == length(Θ) + 1
  @assert Θ.A == reshape(Θ.Π[vec(Amap)], size(Θ.A))
  @assert Θ.V₀ == Θ.Π[V₀map]

  for (i,Πidx) ∈ enumerate(Amap)
    @assert Θ.A[i] == Θ[Πidx]
  end

  for (i,Πidx) ∈ enumerate(V₀map)
    @assert Θ.V₀[i] == Θ[Πidx]
  end

  return (A=Amap, V₀=V₀map)
end

#NOTE: maybe try a list of cartesian coordinates to speed things up?

#pre-allocates the sparsity array
#a nice feature here is the magnitudes are constant for A, just the signs change
function baseleveljacobian(Θ::VolumePartsDLSq, Jcolmap::NamedTuple, X::NamedTuple,
  ::Ty, ::Type{T}) where {Ty<:AbstractVector, T}
  PARAM[:predictiontype] ∈ [:level, :levellog] || error(
    "PARAM[:predictiontype] $(PARAM[:predictiontype]) not supported for manual jacobians!")
  @unpack ws, RLws = X

  #useful quantities for indexing
  N::Int = size(Θ.A,2)
  K::Int = size(Θ.A,1)
  Nexpand::Int = length(Θ.ts)
  Nnonsparse = 2*Nexpand*K + Nexpand #two expanded A matrices + V0 worth of coefficients

  #stores the sparse matrix vectors in ijv format
  baseJvec = (
    I=Vector{Int}(undef, Nnonsparse),
    J=Vector{Int}(undef, Nnonsparse),
    V=Vector{T}(undef, Nnonsparse))#spzeros(T, Nexpand, length(Θ.Π))

  #coordA is a vector of linear indices that maps, for each k and row i,
  #the relevant output row (i) and input col (j) in the sparse J matrix
  coordA::Matrix{CartesianIndex} = Matrix{CartesianIndex}(undef, Nexpand, K)
  coordLA::Matrix{CartesianIndex} = Matrix{CartesianIndex}(undef, Nexpand, K)
  coordV₀ = Vector{CartesianIndex}(undef, Nexpand)

  #first set the coordinates
  coordctr::Int = 1
  for k ∈ 1:K
    for i ∈ 1:length(Θ.ts)
      t=Θ.ts[i]

      Aj = Jcolmap.A[k,t]
      LAj = Jcolmap.A[k,t-1]

      coordA[i,k] = CartesianIndex(i,Aj)
      coordLA[i,k] = CartesianIndex(i,LAj)

      #baseJ[coordA[i,k]] = ws[i,k]
      #baseJ[coordLA[i,k]] = -RLws[i,k]

      #add the row, column, and value of the Jacobian
      baseJvec.I[coordctr], baseJvec.J[coordctr],  baseJvec.V[coordctr] = i, Aj, ws[i,k]
      coordctr+=1
      baseJvec.I[coordctr], baseJvec.J[coordctr],  baseJvec.V[coordctr] = i, LAj, -RLws[i,k]
      coordctr+=1
    end
  end
  for i ∈ 1:length(Θ.ts)
    t=Θ.ts[i]
    V₀j = Jcolmap.V₀[t-1]
    coordV₀[i] =CartesianIndex(i,V₀j)
    #baseJ[coordV₀[i]] = T(1)

    baseJvec.I[coordctr], baseJvec.J[coordctr],  baseJvec.V[coordctr] = i, V₀j, T(1)
    coordctr+=1
  end

  baseJ = sparse(baseJvec.I, baseJvec.J, baseJvec.V)

  #now find the linear index among values within the sparse array
  nzs = findnz(baseJ)
  coords::Vector{Tuple} = collect(zip(nzs[1],nzs[2]))
  vals::Vector{T} = nzs[3]

  #maps the cartesian coordinates to the value row
  indexA::Matrix{Int} = Matrix{Int}(undef, Nexpand,K)
  indexLA::Matrix{Int} = Matrix{Int}(undef, Nexpand,K)
  indexV₀::Vector{Int} = Vector{Int}(undef, Nexpand)

  coordrow::Dict = Dict(zip(coords, 1:length(coords)))
  findcoord(ci) = coordrow[(ci[1],ci[2])]

  for i ∈ 1:Nexpand
    for k ∈ 1:K
      try
        indexA[i,k] = findcoord(coordA[i,k])
        indexLA[i,k] = findcoord(coordLA[i,k])
      catch err
        @info "i=$i, k=$k, coordA=$(coordA[i,k]), coordLA=$(coordA[i,k]), ws=$(ws[i,k])"
        error(err)
      end
    end
    indexV₀[i] = findcoord(coordV₀[i])
  end

  #verify the values are as expected
  print("Verifying baseJ...")

  @time begin
    for k ∈ 1:K
      @assert ((i,j)->baseJ[i,j]).(1:Nexpand, Jcolmap.A[k, Θ.ts]) == vals[indexA[:,k]]
      @assert ((i,j)->baseJ[i,j]).(1:Nexpand, Jcolmap.A[k, Θ.ts .- 1]) == vals[indexLA[:,k]]
    end
    @assert ws == vals[indexA]
    @assert -1 .* RLws == vals[indexLA]
    @assert ((i,j)->baseJ[i,j]).(1:Nexpand, Jcolmap.V₀[Θ.ts .- 1]) == vals[indexV₀]
  end

  index = (A=indexA, LA=indexLA, V₀=indexV₀)

  return index, baseJ
end

#front-loads and caches some of the computation
function JacobianCache(Θ::VolumePartsDLSq, X::NamedTuple, y::AbstractVector,::Type{T}) where T<:Real
  Jcolmap = jacobiancolmap(Θ)
  index, baseJ = baseleveljacobian(Θ,Jcolmap,X,y,T)

  return JacobianCache(Θ, Jcolmap, index, baseJ)
end

cudasignᵢ(Aᵢ, LAᵢ, wsᵢ, RLwsᵢ) = CUDA.sign(Aᵢ * wsᵢ - LAᵢ * RLwsᵢ)
function jacobian!(J, Jcache::JacobianCache, Θ::VolumePartsDLSq, X::NamedTuple, ::AbstractVector,
    ::Val{:level})::Nothing
  size(J) == (length(Θ.ts), length(Θ)) || error("incorrect dimensions $(size(out)) for J template")
  @unpack ws, RLws = X
  N::Int = size(Θ.A,2)
  K::Int = size(Θ.A,1)
  Nexpand::Int = length(Θ.ts)

  Jvals = nonzeros(J)
  baseJvals = nonzeros(Jcache.baseJ)

  #get the expand versions of all entries
  #A = Θ.expand.A
  #LA = Θ.expand.LA
  #V₀ = (exp).(Θ.expand.V₀)

  #get the signing of each entry
  signs = sign.(Θ.expand.A' .* ws .- Θ.expand.LA' .* RLws)
  Jvals[Jcache.index.A] .= baseJvals[Jcache.index.A] .* signs
  Jvals[Jcache.index.LA] .= baseJvals[Jcache.index.LA] .* signs
  Jvals[Jcache.index.V₀] .= exp.(Θ.expand.V₀)

  return nothing

end

function jacobian!(J, Jcache::JacobianCache, Θ::VolumePartsDLSq, X::NamedTuple, ::AbstractVector,
    ::Val{:levellog})::Nothing
  size(J) == (length(Θ.ts), length(Θ)) || error("incorrect dimensions $(size(out)) for J template")

  @unpack ws, RLws = X
  N::Int = size(Θ.A,2)
  K::Int = size(Θ.A,1)
  Nexpand::Int = length(Θ.ts)

  Jvals = nonzeros(J)
  baseJvals = nonzeros(Jcache.baseJ)

  A = exp.(Θ.expand.A')
  LA = exp.(Θ.expand.LA')

  #get the signing of each entry, and compute the derivitives
  signs = sign.(A .* ws .- LA .* RLws)
  Jvals[Jcache.index.A] .= baseJvals[Jcache.index.A] .* A .* signs
  Jvals[Jcache.index.LA] .= baseJvals[Jcache.index.LA] .* LA .* signs
  Jvals[Jcache.index.V₀] .= exp.(Θ.expand.V₀)

  return nothing

end

#returns an operating function which makes the jacobian, as well as a template of the matrix
function JVolumePartsDLSq(Θ::VolumePartsDLSq, X::NamedTuple, v::AbstractVector,::Type{T},
    PredictionType::Val;
    Jcache = JacobianCache(Θ, X, v, T)) where T<:Real

  #check the expand views
  J = deepcopy(Jcache.baseJ)

  #generate the function to be used
  J!(J, Θ) = jacobian!(J, Jcache, Θ, X, v, PredictionType)

  return J, J!
end

#this is a somewhat lighter weight version of the above for more regular testing
function testjacobian(Θtest::VolumePartsDLSq, Xtest::NamedTuple, vtest::AbstractVector,
  ::Type{T}=PARAM[:fluxtype],
  ::Type{TV}=PARAM[:fluxgpu] ? CUDA.CuVector{T} : Vector{T},
  ::Type{TM}=PARAM[:fluxgpu] ? CUDA.CuMatrix{T} : Matrix{T},
  PredictionType::Val = Val(PARAM[:predictiontype]);
  tol::Float64 = PARAM[:testtol],
  J::Union{AbstractMatrix} = error("J prototype matrix is required]"),
  J! = error("J! is required"),
  dims::NamedTuple = error("dims is required!"),
  )where {
    T<:Real, TV<:AbstractVector{T}, TM<:AbstractMatrix{T}}

  @info "***Verifying Jacobian procedure..."

  if PARAM[:fluxmodel] ≠ :levellsq
    error("PARAM[:fluxmodeltype]≠:levellsq is not coded for use with Jacobian")
    return nothing
  end
  PARAM[:predictiontype] ∈ [:level, :levellog] || error(
    "invalid predictiontype $PredictionType for model type $(PARAM[:fluxmodeltype])")

  CUDA.allowscalar(false)

  #create the verification object
  Xver = (ws=fluxgpu(Xtest.ws,T), RLws=fluxgpu(Xtest.RLws,T))
  vver::TV = fluxgpu(vtest,T)
  Θver = VolumePartsLSq(dims.T, dims.K, Θtest.ts, T)
  Θver .= Θtest

  hatver = Vector{T}(Θver(Xver, vver, PredictionType))
  hattest = Θtest(Xtest, vtest, PredictionType)
  sum(abs.(hatver .- hattest)) < tol || error("prediction deviation (not jacobian) exceeds tolerance")

  @assert Θtest.Π == Θver.Π
  @assert Θtest.A == Θver.A
  @assert Θtest.V₀ == Θver.V₀
  @assert Θtest.expand.A ≈ view(Θver.A, Θver.expand.Aidx...)
  @assert Θtest.expand.LA ≈ view(Θver.A, Θver.expand.LAidx...)
  @assert Θtest.expand.V₀ ≈ view(Θver.V₀, Θver.expand.V₀idx)

  Π=Flux.params(Θver)
  length(Π) == 0 && error("No parameters noticed by Flux!")

  loss(X::NamedTuple,y::AbstractVector) = sum(Θver(Xver, vver, PredictionType))

  #now get the gradient for verification
  ∇Θ! = ∇VolumeParts!(loss, Xver,vver, Θver)
  ∇ver = similar(Θver.Π)
  ∇Θ!(∇ver, Θver)

  J!(J, Θtest)

  ∇test = vec(sum(J, dims=1))

  Δ = sum(abs.(∇test .- ∇ver))
  if Δ > tol
    #@info "∇test: $∇test"
    #@info "∇ver: $∇ver"
    @info "listing differences..."
    ctr::Int = 0
    maxctr::Int = 2
    for i ∈ 1:length(∇test)
      if !(∇test[i] ≈ ∇ver[i]) || (abs(∇test[i] - ∇ver[i]) > tol)
        @info "!: ∇test[$i], ∇ver[$i]=($(∇test[i]), $(∇ver[i])); Δ=$(∇test[i] - ∇ver[i])"
        ctr+=1;
      end
      if ctr ≥ maxctr
        @info "max $ctr reached"
        break
      end
    end
    error("FAILED jacobian test with Δ=$Δ")
  else
    @info "passed jacobian test with Δ=$Δ"
  end

end

function testvolumepartsindicesdirectlsq(::Type{Tvp}=PARAM[:opttype],
  ::Type{TV}=PARAM[:optgpu] ? CUDA.CuVector{Tvp} : Vector{Tvp},
  ::Type{TM}=PARAM[:optgpu] ? CUDA.CuMatrix{Tvp} : Matrix{Tvp}
    ) where {Tvp<:Real, TV<:AbstractVector{Tvp}, TM<:AbstractMatrix{Tvp}}
  Θ = VolumePartsDLSq(200,5, rand(2:200, 10^5))
  Θcopy = deepcopy(Θ)

  #first test getidx
  (Θ.A == reshape(Θ[1:1000], :, 200)) || error("inconsistent getidx dimensions Θ.A")
  (Θ.V₀ == Θ[1001:1199]) || error("inconsistent getidx dimensions Θ.V₀")

  #now test setidx
  testvals = rand(PARAM[:fluxtype], 1199)
  testidx = Random.randperm(1199)

  @assert allunique(testidx)
  Θ[testidx] .= testvals

  testcombined = hcat(testidx, testvals)
  testcombined = testcombined[sortperm(testcombined[:,1]),:]
  orderedtestvals = Vector(vec(testcombined[:,2]))
  @assert sum(orderedtestvals .== Vector(Θ.Π)) == length(Θ.Π)

  Θcopy.A .= TM(reshape(orderedtestvals[1:1000], size(Θcopy.A)))
  Θcopy.V₀ .= TV(orderedtestvals[1001:1199])

  (Θcopy.A ≈ Θ.A) || error("inconsistent setidx! dimensions Θ.A")
  (Θcopy.V₀ ≈ Θ.V₀) || error("inconsistent setidx! dimensions Θ.V₀")

  @info "test vol parts indices completed successfully"
end

#convenience constructor which creates a verificaiton object prior to performing the test
function testprediction(Θtest::VolumePartsDLSq,
  X::NamedTuple, y::AbstractVector,
  PredictionType::Val,
  ::Type{T}=PARAM[:opttype]) where T

  NK, NT = size(Θtest.A)
  Θver = VolumePartsLSq(NT, NK, Θtest.ts, T)
  Θver.Π .= Vector(Θtest.Π)

  yhattest = Θtest(X,y,PredictionType) |> Vector
  yhatver = Θver(X,y,PredictionType) |> Vector
  rmserror = sqrt(mean((yhattest .- yhatver).^2))

  if PARAM[:testmeasure]
    @info "Performance of DLSq objective"
    @btime $Θtest($X,$y,$PredictionType)

    @info "Performance of baseline LSq objective"
    @btime $Θver($X,$y,$PredictionType)
  end

  if yhattest ≈ yhatver
    @info "objective test passed with rmserror=$rmserror"
  else
    error("objective test failed!!! rmserror=$rmserror")
  end

  return nothing
end

#NOTE- test make sure this settup works
function testdlsq(panel::AbstractDataFrame,  ms::MeasureSpec,
    ::Type{T}=PARAM[:opttype],
    ::Type{TV}=PARAM[:optgpu] ? CUDA.CuVector{T} : Vector{T},
    ::Type{TM}=PARAM[:optgpu] ? CUDA.CuMatrix{T} : Matrix{T};
    PredictionType::Val = Val(PARAM[:predictiontype]),
    tol::Float64 = PARAM[:testtol]
    ) where {
      T<:Real, TV<:AbstractVector{T}, TM<:AbstractMatrix{T}}

  if PARAM[:fluxmodel] ≠ :levellsq
    error("PARAM[:fluxmodeltype]≠:levellsq is not coded for use with Jacobian")
  end

  testvolumepartsindicesdirectlsq()

  Fw::Vector{Symbol} = Fweights(ms, :Fw)
  FRLw::Vector{Symbol} = Fweights(ms, :FRLw)
  essentialfields = [Fw; FRLw; ms.Fvol; ]

  #form the data into a more usable format and expand the arrays
  p = modelparts(panel, ms,T, TV, TM,
    weightdata = (Fw=Fw, FRLw=FRLw),
    Fvol=ms.Fvol)
  dims = p.dims
  ws::TM = p.dat[:Fw]
  RLws::TM = p.dat[:FRLw]
  ts::Vector{Int} = p.ts
  Xtest = (ws=ws, RLws=RLws)
  vtest::TV = p.dat[:Fvol]

  Θtest = VolumePartsDLSq(dims.T, dims.K, ts, T)

  if PARAM[:optgpu]
    @info "gpu usage on- derivitives will not work with DLSq+GPU. Skipping Jacobian test"
  else
    J, J! = JVolumePartsDLSq(Θtest, Xtest, vtest, T, PredictionType)
    testjacobian(Θtest, Xtest, vtest, J=J, J! = J!, dims=dims)
  end

  return testprediction(Θtest, Xtest, vtest, PredictionType)
end

max_stars_repo_name: clintonTE/CCA

max_issues_repo_name: clintonTE/CCA

max_forks_repo_name: clintonTE/CCA


text:
@testset "Base extensions" begin

    @testset "sumdropdims" begin
        arr = randn((2,2,2,2,2))

        function test_f(f, arr, dims)
            @test dropdims(sum(f, arr, dims=dims), dims=dims) == sumdropdims(f, arr, dims=dims)
            @test dropdims(sum(arr, dims=dims), dims=dims) == sumdropdims(arr, dims=dims)
        end

        test_f(x -> x^2, arr, (1,2))
        test_f(x -> x^2, arr, (1,3))
        test_f(x -> x^2, arr, (2,4))
        test_f(x -> x^2, arr, (1,2,3,4, 5))
        test_f(x -> x^2, arr, (1,2,3))

        @test ndims(sumdropdims(arr, dims=(1,2,3,4,5))) == 0
    end
end

ext: jl


text:
module TermStructure

using Miletus.DayCounts
using Dates

export YieldTermStructure, VolatilityTermStructure, ConstantYieldCurve,
		compound_factor, discount_factor, implied_rate, discount, forward_rate,
		reference_date, zero_rate, par_rate

#General Interest Rate functionality

compound_factor(r::Real, compounding::Symbol, freq::Symbol,  t::Real) = compound_factor(r, compounding, eval(freq), t)
compound_factor(r::Real, compounding::Symbol,  t::Real) = compound_factor(r, compounding, NoFrequency, t)
compound_factor(r::Real, compounding::Symbol, dc::DayCount, dates::Date...) = compound_factor(r, compounding, NoFrequency, dates...)
compound_factor(r::Real, compounding::Symbol, freq::Symbol, dc::DayCount, dates::Date...) = compound_factor(r, compounding, eval(freq), dates...)
compound_factor(r::Real, compounding::Symbol, freq::Integer, dc::DayCount, dates::Date...) = compound_factor(r,  compounding, freq, yearfraction(dc, dates...))

function compound_factor(r::Real, compounding::Symbol, freq::Integer, t::Real )
	if compounding == :Simple
		return 1 + r * t
	elseif compounding == :Compounded
		@assert(freq != NoFrequency)
		return (1 + r / freq) ^ (freq * t)
	elseif compounding == :Continuous
		return exp(r * t)
	elseif compounding == :SimpleThenCompounded
		@assert(freq != NoFrequency)
		if t < (1 / freq)
            return 1 + r * t
        else
            return (1 + r / freq) ^ (freq * t)
        end
	else
		error("Unknown compounding")
	end
end

discount_factor(x...) = 1/compound_factor(x...)

implied_rate(c::Real, compounding::Symbol, freq::Symbol,  t::Real) = implied_rate(c,compounding, eval(freq), t)
implied_rate(c::Real, compounding::Symbol, freq::Symbol, dc::DayCount, dates::Date...) = implied_rate(c,compounding, eval(freq), dates...)
implied_rate(c::Real, compounding::Symbol, freq::Integer, dc::DayCount, dates::Date...) = implied_rate(c, compounding, freq, yearfraction(dc, dates...))

function implied_rate(c::Real, compounding::Symbol, freq::Integer, t::Real)
	@assert c>0 && t>0
	if compounding == :Simple
		return (c-1) / t
	elseif compounding == :Compounded
		return (c ^ (1/(f*t)) - 1) *f
	elseif compounding == :Continuous
		return log(c)/t
	elseif compounding == :SimpleThenCompounded
		if t < (1 / freq)
            return (c-1) / t
        else
            return (c ^ (1/(f*t)) - 1) *f
        end
	else
		error("Unknown compounding")
	end
end

abstract type TermStuct end

abstract type VolatilityTermStructure <: TermStuct end
abstract type YieldTermStructure <: TermStuct end

#Default values
daycount(::YieldTermStructure) = Actual365()
startdate(::YieldTermStructure) = Dates.today()
compounding(::YieldTermStructure) = :Continuous
frequency(::YieldTermStructure) = NoFrequency

discount(ts::YieldTermStructure, d::Date) = discount(ts, yearfraction(daycount(ts), startdate(ts), d))
Base.getindex(ts::YieldTermStructure, d::Date) = discount(ts, d)
implied_rate(ts::YieldTermStructure, d::Date) = implied_rate(1/ts[d], compounding(ts), frequency(ts), yearfraction(daycount(ts),  startdate(ts), d) )

#Overload this method for each concrete YieldTermStructure
discount(ts::YieldTermStructure, t::Real) = error("Must be implemented by concrete Term Structure")

function forward_rate(ts::YieldTermStructure, d1::Date, d2::Date )
	if d1==d2
		t1 = yearfraction(daycount(ts), startdate(ts), d1)
		t2 = t1+.0001
		c=discount(ts, t1) / discount(ts, t2)
		return implied_rate(c, compounding(ts), frequency(ts), t2-t1)
	elseif d1<d2
		return implied_rate(discount(ts, d1)/discount(ts, d2), compounding(ts), frequency(ts), daycount(ts), d1, d2)
	else
		error("Forward start date must be before forward end dates")
	end
end

function forward_rate(ts::YieldTermStructure, t1::Real, t2::Real )
	if (t2==t1)
		t2=t1+.0001
	end

	compound = discount(ts, t1) / discount(ts, t2)
	return implied_rate(discount(ts, t1) / discount(ts, t2), daycount(ts), t2-t1)
end

zero_rate(ts::YieldTermStructure,  d1::Date) = zero_rate(ts, yearfraction(ts.dc, reference_date(ts), d1))
function zero_rate(ts::YieldTermStructure, t::Real)
	if (t == 0)
		c = 1/discount(ts, .0001)
		return implied_rate(c, ts.compounding, ts.freq, .0001)
	else
		c = 1/discount(ts, t)
		return implied_rate(c, ts.compounding, ts.freq, t)
	end
end

par_rate(ts::YieldTermStructure, dates::AbstractVector{Date}) =
	par_rate(ts, [yearfraction(ts.dc, reference_date(ts), dt) for dt in dates])
function par_rate(ts::YieldTermStructure, tm::AbstractVector)
	s = sum([discount(ts, t) for t in tm])
	r=discount(ts, tm[1])
end

mutable struct ConstantVolatilityCurve <: VolatilityTermStructure

end

struct ConstantContinuousYieldCurve{DC,T} <: YieldTermStructure
    dc::DC
    rate::T
    reference_date::Date
end

daycount(y::ConstantContinuousYieldCurve) = y.dc
startdate(y::ConstantContinuousYieldCurve) = y.reference_date
discount(y::ConstantContinuousYieldCurve, yf::Float64) = exp(-y.rate * yf)

discount(y::ConstantContinuousYieldCurve, d::Date) = discount(y, yearfraction(daycount(y), startdate(y), d))

mutable struct ConstantYieldCurve{T} <: YieldTermStructure
	dc::DayCount
	rate::T
	compounding::Symbol
	freq::Integer
	reference_date::Date
end

ConstantYieldCurve(dc::DayCount, rate::Real, compounding::Symbol, freq::Symbol, reference_date::Date) =
		ConstantYieldCurve(dc, rate, compounding, eval(freq), reference_date)

daycount(y::ConstantYieldCurve) = y.dc
startdate(y::ConstantYieldCurve) = y.reference_date

ConstantYieldCurve(dc::DayCount, rate::Real) = ConstantYieldCurve(dc, rate, :Continuous, :NoFrequency, today())
discount(ts::ConstantYieldCurve, t::Real) = discount_factor(ts.rate, ts.compounding, ts.freq, t)

const NoFrequency       = -1
const Once			 	= 0
const Annual			= 1
const Semiannual		= 2
const EveryFourthMonth  = 3
const Quarterly		 	= 4
const Bimonthly		 	= 6
const Monthly			= 12
const EveryFourthWeek  	= 13
const Biweekly		 	= 26
const Weekly			= 52
const Daily			 	= 365
const OtherFrequency   	= 999

end #Module


text:
# Example of GOKU-net model on the original friction-less pendulum data
# from the  GOKU-net paper (https://github.com/orilinial/GOKU)

using LatentDiffEq
using FileIO
using Parameters: @with_kw
using ProgressMeter: Progress, next!
using Random
using Statistics
using MLDataUtils
using BSON: @save
using Flux.Data: DataLoader
using Flux
using OrdinaryDiffEq
using ModelingToolkit
using DiffEqSensitivity
using Images
using Plots
import GR

include("pendulum.jl")

################################################################################
## Arguments for the train function
@with_kw mutable struct Args
    ## Global model
    model_type = GOKU()

    ## Latent Differential Equations
    diffeq = Pendulum()

    ## Training params
    η = 1e-3                        # learning rate
    decay = 0.0001f0                # decay applied to weights during optimisation
    batch_size = 64                 # minibatch size
    seq_len = 50                    # sequence length for training samples
    epochs = 900                    # number of epochs for training
    seed = 3                        # random seed
    cuda = false                    # GPU usage (not working well yet)
    dt = 0.05                       # timestep for ode solve
    variational = true              # variational or deterministic training

    ## Annealing schedule
    start_β = 0.00001f0             # start value
    end_β = 0.00001f0               # end value
    n_cycle = 3                     # number of annealing cycles
    ratio = 0.9                     # proportion used to increase β (and 1-ratio used to fix β)

    ## Progressive observation training
    progressive_training = false    # progressive training usage
    prog_training_duration = 5      # number of epochs to reach the final seq_len
    start_seq_len = 10              # training sequence length at first step

    ## Visualization
    vis_len = 60                    # number of frames to visualize after each epoch
    save_figure = false             # true: save visualization figure in save_path folder
                                    # false: display image instead of saving it
end

################################################################################
################################################################################
## Training done manualy

function train(; kws...)
    ## Load hyperparameters and GPU config
    args = Args(; kws...)
    @unpack_Args args

    seed > 0 && Random.seed!(seed)

    device = cpu
    @info "Training on CPU"

    ############################################################################
    ## Prepare training data

    root_dir = @__DIR__
    data_path = "$root_dir/data/processed_data.jld2"

    if ~isfile(data_path)
        @info "Downloading pendulum data"
        mkpath("$root_dir/data")
        download("https://ndownloader.figshare.com/files/27986997", data_path)
    end

    data_loaded = load(data_path, "processed_data")
    train_data = data_loaded["train"]

    train_data_norm, min_val, max_val = normalize_to_unit_segment(train_data)
    observations, full_seq_len, h, w = size(train_data_norm)

    train_data = reshape(train_data_norm, observations, full_seq_len, :)
    train_data = permutedims(train_data, [3, 2, 1]) # input_dim, time_size, observations
    train_data = Float32.(train_data)

    train_set, val_set = splitobs(train_data, 0.9)

    loader_train = DataLoader(Array(train_set), batchsize=batch_size, shuffle=true, partial=false)
    loader_val = DataLoader(Array(val_set), batchsize=size(val_set, 3), shuffle=false, partial=false)

    input_dim = size(train_set,1)

    ############################################################################
    # Create model

    encoder_layers, decoder_layers = default_layers(model_type, input_dim, diffeq, device = device)
    model = LatentDiffEqModel(model_type, encoder_layers, decoder_layers)

    # Get parameters
    ps = Flux.params(model)

    ############################################################################
    ## Define optimizer
    opt = ADAM(η)
    # opt = AdaBelief(η)
    # opt = ADAMW(η,(0.9,0.999), decay)

    ############################################################################
    ## Various definitions

    if progressive_training
        prog_seq_lengths = range(start_seq_len, seq_len, step=(seq_len-start_seq_len)/(prog_training_duration-1))
        prog_seq_lengths = Int.(round.(prog_seq_lengths))
    else
        prog_training_duration = 0
    end

    # KL annealing scheduling
    annealing_schedule = frange_cycle_linear(epochs, start_β, end_β, n_cycle, ratio)

    # Preparation for saving best models weights
    mkpath("$root_dir/output")
    best_val_loss = Inf32
    val_loss = 0f0

    # mkpath("$root_dir/output")
    # args = struct2dict(args)
    # @save "$root_dir/output/args.bson" args

    ## Visualization options
    if save_figure
        mkpath("$root_dir/output/visualization")
        GR.inline("pdf")
    end

    ############################################################################
    ## Main train loop
    @info "Start Training of $(typeof(model_type))-net, total $epochs epochs"
    for epoch = 1:epochs

        # Set annealing factor
        β = annealing_schedule[epoch]

        ## Set a sequence length for training samples
        seq_len = epoch ≤ prog_training_duration ? prog_seq_lengths[epoch] : seq_len

        # Model evaluation length
        t = range(0.f0, step=dt, length=seq_len)

        @info "Epoch $epoch .. (Sequence training length $seq_len)"
        progress = Progress(length(loader_train))
        for x in loader_train

            # Use only random sequences of length seq_len for the current minibatch
            x = time_loader(x, full_seq_len, seq_len)

            # Run the model with the current parameters and compute the loss
            loss, back = Flux.pullback(ps) do
                loss_batch(model, x |> device, t, β, variational)
            end

            # Backpropagate and update
            grad = back(1f0)
            Flux.Optimise.update!(opt, ps, grad)

            # Use validation set to get loss and visualisation
            val_set = Flux.unstack(first(loader_val), 2)
            t_val = range(0.f0, step=dt, length=length(val_set))
            val_loss = loss_batch(model, val_set |> device, t_val, β, false)

            # progress meter
            next!(progress; showvalues=[(:loss, loss),(:val_loss, val_loss)])
        end

        if device != gpu
            val_set = first(loader_val)
            # visualize_val_image(model, val_set[:,1:vis_len,:] |> device, t_val, h, w, save_figure)
            visualize_val_image(model, val_set |> device, vis_len, dt, h, w, save_figure)
        end
        if val_loss < best_val_loss
            best_val_loss = deepcopy(val_loss)
            weights = Flux.params(model)
            @save "$root_dir/output/best_model_weights.bson" weights
            @info "Model saved"
        end
    end
end

################################################################################
## Loss definition

function loss_batch(model, x, t, β, variational)

    # Make prediction
    X̂, μ, logσ² = model(x, t, variational)
    x̂, ẑ, l̂ = X̂

    # Compute reconstruction loss
    reconstruction_loss = vector_mse(x, x̂)

    # Compute KL losses from parameter and initial value estimation
    kl_loss = vector_kl(μ, logσ²)

    return reconstruction_loss + β * kl_loss
end

################################################################################
## Visualization function

function visualize_val_image(model, val_set, vis_len, dt, h, w, save_figure)
    j = rand(1:size(val_set,3))
    idxs = rand_time(size(val_set,2), vis_len)
    X_test = val_set[:, idxs, j]

    frames_test = [Gray.(reshape(x,h,w)) for x in eachcol(X_test)]
    X_test = reshape(X_test, Val(3))
    x = Flux.unstack(X_test, 2)
    t_val = range(0.f0, step=dt, length=vis_len)

    X̂, μ, logσ² = model(x, t_val)
    x̂, ẑ, l̂ = X̂
    ẑ₀, θ̂ = l̂

    ẑ = Flux.stack(ẑ, 2)

    plt1 = plot(ẑ[1,:,1], legend = false)
    ylabel!("Angle")
    xlabel!("time")

    x̂ = Flux.stack(x̂, 2)
    frames_pred = [Gray.(reshape(x,h,w)) for x in eachslice(x̂, dims=2)]

    frames_test = frames_test[1:6:end]
    frames_pred = frames_pred[1:6:end]

    plt2 = mosaicview(frames_test..., frames_pred..., nrow=2, rowmajor=true)
    plt2 = plot(plt2, leg = false, ticks = nothing, border = :none)
    plt = plot(plt1, plt2, layout = @layout([a; b]))
    save_figure ? savefig(plt, "output/visualization/fig.pdf") : display(plt)
end

train()


text:
using NumericalMethodsforEngineers

a = [16. 4. 8.; 4. 5. -4.; 8. -4. 22.]
b = [4., 2., 5.]

upper = chol(a)
upper |> display

lower = upper'

y = lower \ b

c = upper \ y


text:
using HCubature

M = 4.5
maxD = 10

f(x) = (2*pi)^(-length(x)/2) * exp(-(1/2)*x'x)

for n in 1:maxD
    a = -M*ones(n)
    b = M*ones(n)
    I,e = hcubature(f, a, b, maxevals = 10^7)
    println("n = $(n), integral = $(I), error (estimate) = $(e)")
end

max_stars_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_issues_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook

max_forks_repo_name: Yoshinobu-Ishizaki/StatsWithJuliaBook


text:
function summaryRanges(nums::Array{Number})
    length(nums) == 0 && return []

    start, endding = nums[1], nums[1]
    result::Array{String} = []

    for i in nums
        i > endding+1 &&
            begin
                start != endding ?
                    push!(result, string(start, "->", endding)) :
                    push!(result, string(start))
                start = i
            end
        endding = i
    end

    start != endding ?
        push!(result, string(start, "->", endding)) :
        push!(result, string(start))

    result
end

using Test
@test summaryRanges([0, 1, 2, 4, 5, 7]) == ["0->2", "4->5", "7"]
@test summaryRanges([0, 2, 3, 4, 6, 8, 9]) == ["0", "2->4", "6", "8->9"]

max_stars_repo_name: ccqpein/Arithmetic-Exercises

max_issues_repo_name: ccqpein/Arithmetic-Exercises

max_forks_repo_name: ccqpein/Arithmetic-Exercises


text:
#=== rec ===#
function wIB(
    fid::IOStream,
    rec::receiver,
    nT::Int64,
    OptCpnt::Array{String})

    CpntDict = Dict("P"=>1,"Vx"=>2,"Vz"=>3,
                "Txx"=>4,"Tzz"=>5,"Txz"=>6,"V"=>23,"Tii"=>45)

    write(fid,rec.nr) # Total Receiver Number
    write(fid,length(OptCpnt))
    for cpnt in OptCpnt
        write(fid,CpntDict[cpnt])
    end
    write(fid,nT) # Total Time Sampling Tn
    write(fid,rec.loc) #physical location
    write(fid,rec.nloc) #discrete location without PML
    write(fid,rec.BDnloc) #discrete location with PML
end

#=== elastic ===#

#=== wavefield ===#
function wIB(
    fid::IOStream,
    model::elmod2d,
    Slices::Union{UnitRange{Int64},StepRange{Int64,Int64},Array{Int64,1},Int64},
    OptCpnt::Array{String})

    CpntDict = Dict("P"=>1,"Vx"=>2,"Vz"=>3,
                "Txx"=>4,"Tzz"=>5,"Txz"=>6,
                "V"=>23,"Tii"=>45)

    write(fid,model.medium.iflag)
    write(fid,length(OptCpnt))
    for cpnt in OptCpnt
        write(fid,CpntDict[cpnt])
    end
    write(fid,model.nwf.BDntpp)
    write(fid,model.medium.ext)
    write(fid,model.medium.dx)
    write(fid,model.medium.dz)
    write(fid,length(Slices))
    write(fid,Slices.*model.medium.dt)

end

#=== acoustic ===#
#=== wavefield ===#
function wIB(
    fid::IOStream,
    model::acmod2d,
    Slices::Union{UnitRange{Int64},StepRange{Int64,Int64},Array{Int64,1},Int64},
    OptCpnt::Array{String})

    CpntDict = Dict("P"=>1,"Vx"=>2,"Vz"=>3,
                "Txx"=>4,"Tzz"=>5,
                "V"=>23,"Tii"=>45)

    write(fid,model.medium.iflag)
    write(fid,length(OptCpnt))
    for cpnt in OptCpnt
        write(fid,CpntDict[cpnt])
    end
    write(fid,model.nwf.BDntpp)
    write(fid,model.medium.ext)
    write(fid,model.medium.dx)
    write(fid,model.medium.dz)
    write(fid,length(Slices))
    write(fid,Slices.*model.medium.dt)

end


text:
@testset "Longest Increasing Subsequence" begin
    @testset "LIS: Dynamic Programming approach!" begin
        @test lis([3, 10, 2, 1, 20], Val(:dp)) == [3, 10, 20]
        # negative elements
        @test lis([-10, -2, -1, -20], Val(:dp)) == [-10, -2, -1]
        # repeated elements
        @test lis([2, 2, 3, 3], Val(:dp)) == [2, 3]
        # one element
        @test lis([2], Val(:dp)) == [2]
        # empty array
        @test lis(Int[], Val(:dp)) == Int[]
        # two possible results:
        @test lis([3, 2], Val(:dp)) in [[2], [3]]
        # two possible results:
        @test lis([50, 3, 10, 7, 40, 80], Val(:dp)) in [[3, 7, 40, 80], [3, 10, 40, 80]]
        # two possible results:
        @test lis([3, 4, -1, 5, 8, 2, 3, 12, 7, 9, 10], Val(:dp)) in
              [[-1, 2, 3, 7, 9, 10], [3, 4, 5, 8, 9, 10]]
    end

    @testset "LIS: Binary Search approach!" begin
        @test lis([3, 10, 2, 1, 20], Val(:bs)) == [3, 10, 20]
        # negative elements
        @test lis([-10, -2, -1, -20], Val(:bs)) == [-10, -2, -1]
        # repeated elements
        @test lis([2, 2, 3, 3], Val(:bs)) == [2, 3]
        # one element
        @test lis([2], Val(:bs)) == [2]
        # empty array
        @test lis(Int[], Val(:bs)) == Int[]
        # two possible results:
        @test lis([3, 2], Val(:bs)) in [[2], [3]]
        # two possible results:
        @test lis([50, 3, 10, 7, 40, 80], Val(:bs)) in [[3, 7, 40, 80], [3, 10, 40, 80]]
        # two possible results:
        @test lis([3, 4, -1, 5, 8, 2, 3, 12, 7, 9, 10], Val(:bs)) in
              [[-1, 2, 3, 7, 9, 10], [3, 4, 5, 8, 9, 10]]
    end
end

max_issues_repo_name: AugustoCL/Julia

max_forks_repo_name: AugustoCL/Julia


text:
export with_options

struct OptionsFactory{T}
	# See https://github.com/JuliaOpt/JuMP.jl/blob/94e2cbb3b1a079b327d2fb9b80bfd3b3afa3415d/src/JuMP.jl#L84-L121
	ObjectType::Type
	args::Tuple
	kwargs::Base.Iterators.Pairs
end

function with_options(object_type, args...; kwargs...)
	OptionsFactory{object_type}(object_type, args, kwargs)
end

function (options_factory::OptionsFactory{T})(args...; kwargs...) where {T}
    return options_factory.ObjectType(args..., options_factory.args...;
									kwargs..., options_factory.kwargs...)
end

"""
	COSMO.Settings{T}(; kwargs) where {T <: AbstractFloat}

Creates a COSMO settings object that is used to pass user settings to the solver.

Argument | Description | Values (default)
--- | :--- | :---
rho | ADMM rho step | 0.1
sigma | ADMM sigma step | 1e-6
alpha | Relaxation parameter | 1.6
eps_abs | Absolute residual tolerance | 1e-4
eps_rel | Relative residual tolerance | 1e-4
eps\\_prim\\_inf | Primal infeasibility tolerance | 1e-6
eps\\_dual\\_inf | Dual infeasibility tolerance | 1e-4
max_iter | Maximum number of iterations | 2500
verbose | Verbose printing | false
verbose_timing | Verbose timing | false
kkt_solver | Linear System solver | `QdldlKKTSolver`
check_termination | Check termination interval | 40
check_infeasibility | Check infeasibility interval | 40
scaling | Number of scaling iterations | 10
adaptive_rho | Automatic adaptation of step size parameter | true
decompose | Activate to decompose chordal psd constraints | true
complete_dual | Activate to complete the dual variable after decomposition | false
merge_strategy | Choose a strategy for clique merging | `CliqueGraphMerge`
compact_transformation | Choose how a decomposed problem is transformed | true
time_limit | Set solver time limit in s | 0
"""
mutable struct Settings{T <: AbstractFloat}
	rho::T
	sigma::T
	alpha::T
	eps_abs::T
	eps_rel::T
	eps_prim_inf::T
	eps_dual_inf::T
	max_iter::Int64
	verbose::Bool
	kkt_solver::Union{Type{<: AbstractKKTSolver}, OptionsFactory{<: AbstractKKTSolver}}
	check_termination::Int64
	check_infeasibility::Int64
	scaling::Int64
	MIN_SCALING::T
	MAX_SCALING::T
	adaptive_rho::Bool
	adaptive_rho_interval::Int64
	adaptive_rho_tolerance::T
	adaptive_rho_fraction::T
	verbose_timing::Bool
	RHO_MIN::T
	RHO_MAX::T
	RHO_TOL::T
	RHO_EQ_OVER_RHO_INEQ::T
	COSMO_INFTY::T
  	decompose::Bool
  	complete_dual::Bool
	time_limit::T
	obj_true::T
	obj_true_tol::T
	merge_strategy::Union{Type{<: AbstractMergeStrategy}, OptionsFactory{<: AbstractMergeStrategy}}
	compact_transformation::Bool
	#constructor
	function Settings{T}(;
		rho::Real=T(0.1),
		sigma::Real=T(1e-6),
		alpha::Real=T(1.6),
		eps_abs::Real=T(1e-4),
		eps_rel::Real=T(1e-4),
		eps_prim_inf::Real=T(1e-6),
		eps_dual_inf::Real=T(1e-4),
		max_iter::Integer=2500,
		verbose::Bool=false,
		kkt_solver=QdldlKKTSolver,
		check_termination::Int64=40,
		check_infeasibility::Int64=40,
		scaling::Integer=10,
		MIN_SCALING::Real = T(1e-4),
		MAX_SCALING::Real = T(1e4),
		adaptive_rho::Bool = true,
		adaptive_rho_interval::Int64 = 40,
		adaptive_rho_tolerance::Int64 = 5,
		adaptive_rho_fraction::Real = T(0.4),
		verbose_timing::Bool = false,
		RHO_MIN::Real = T(1e-6),
		RHO_MAX::Real = T(1e6),
		RHO_TOL::Real = T(1e-4),
		RHO_EQ_OVER_RHO_INEQ::Real = T(1e3),
		COSMO_INFTY::Real = T(1e20),
		decompose::Bool = true,
    	complete_dual::Bool = false,
		time_limit::Real = zero(T),
		obj_true::Real = T(NaN),
		obj_true_tol::Real = T(1e-3),
		merge_strategy = CliqueGraphMerge,
		compact_transformation::Bool = true
		) where {T <: AbstractFloat}
		if !isa(kkt_solver, OptionsFactory)
			kkt_solver = with_options(kkt_solver)
		end

		if !isa(merge_strategy, OptionsFactory)
			merge_strategy = with_options(merge_strategy)
		end
		new(rho, sigma, alpha, eps_abs, eps_rel, eps_prim_inf, eps_dual_inf, max_iter, verbose, kkt_solver, check_termination, check_infeasibility, scaling, MIN_SCALING, MAX_SCALING, adaptive_rho, adaptive_rho_interval, adaptive_rho_tolerance, adaptive_rho_fraction, verbose_timing, RHO_MIN, RHO_MAX, RHO_TOL, RHO_EQ_OVER_RHO_INEQ, COSMO_INFTY, decompose, complete_dual, time_limit, obj_true, obj_true_tol, merge_strategy, compact_transformation)
	end
end

# The default case it to return a Settings{Float64} object
Settings(args...; kwargs...) = Settings{DefaultFloat}(args...; kwargs...)

function Base.show(io::IO, obj::COSMO.Settings{T}) where {T <: AbstractFloat}
	println(io,"A COSMO.Settings{$(T)} object. To list the available options type `?` and `help?>COSMO.Settings`.")
end
eltype(::Type{<:Settings{T}}) where {T} = T


text:
module PkgBugDemo

end # module


text:
using AVLTrees

"""
OneSidedBook is a one-sided book (i.e. :BID or :ASK) of order queues at
varying prices.

OrderQueues are stored in an AVLTree (.book) indexed
either by price (:ASK) or -price (:BID)

The book keeps track of various statistics such as the current best price,
total share and price volume, as well as total contained number of orders.

"""
@kwdef mutable struct OneSidedBook
    side::Symbol
    book::AVLTree{Float32,OrderQueue} = AVLTree{Float32,OrderQueue}()
    total_volume::Int64 = 0 # Total volume available in shares
    num_orders::Int32 = Int32(0) # Number of orders in the book
    best_price::Union{Float32,Nothing} = nothing # best bid or ask
end

Base.isempty(sb::OneSidedBook) = Base.isempty(sb.book)

"Updates the latest best price in a Sidebook (either :BID or :ASK book)."
function _update_next_best_price!(sb::OneSidedBook)
    sb.best_price = isempty(sb.book) ? nothing : first(sb.book)[1]
    return
end

"Retrieve order queue from OneSidedBook at given price"
function _get_price_queue(sb::OneSidedBook,price::Float32)
    pricekey = sb.side == :ASK ? price : -price
    getkey(sb.book,pricekey) # Return the price queue
end

"Delete entire queue associated with given price from OneSidedBook"
function _delete_price_queue!(sb::OneSidedBook,price::Float32)
    pricekey = sb.side == :ASK ? price : -price
    price_queue = pop!(sb.book,pricekey) # delete price queue

    # update book stats
    (price_queue.price == sb.best_price) && _update_next_best_price!(sb) # Update price only if best price was changed
    sb.num_orders -= price_queue.num_orders[]
    sb.total_volume -= price_queue.total_volume[]
end

"Insert new_order into OneSidedBook at given price, create new price queue if needed"
function insert_order!(sb::OneSidedBook,new_order::Order)
    pricekey = (sb.side == :ASK) ? new_order.price : -new_order.price
    # search for order queue at price
    order_queue = getkey(sb.book,pricekey)
    if isnothing(order_queue) # If key not present (price doesnt exist in book)
        new_queue = OrderQueue(price=new_order.price) # Create new price queue
        push!(new_queue,new_order) # Add order to new price queue
        insert!(sb.book,pricekey,new_queue) # add new price queue to OneSidedBook

        # Update new best price depending on bid/ask
        if isnothing(sb.best_price)
            sb.best_price = new_order.price
        elseif sb.side == :BID
            sb.best_price = max(new_order.price,sb.best_price)
        else
            sb.best_price = min(new_order.price,sb.best_price)
        end
    else # If order queue present, retrieve queue and insert new order
        push!(order_queue,new_order)
    end

    # Update Onesidedbook info
    sb.num_orders += 1
    sb.total_volume += new_order.size
end

"Delete order with given price/tick_id from book"
function delete_order!(sb::OneSidedBook,price::Float32,orderid::Int64)
    # Get price queue and delete order from it
    order_queue = _get_price_queue(sb,price)
    vol0 = order_queue.total_volume[] # get stats before deletion
    delete!(order_queue,orderid)
    vol1 = order_queue.total_volume[] # get stats after deletion

    # If order deletion depleted price queue, delete the whole queue
    if isempty(order_queue)
        _delete_price_queue!(sb,price) # note: this function will update price
    end

    # Update Onesidedbook info
    # TODO, Record change in order queue stats
    sb.num_orders -= 1
    sb.total_volume -= (vol0-vol1)

end


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

using Markdown
using InteractiveUtils

# ╔═╡ 3f9f4948-74c3-11ec-2daf-51719517f805
# Import packages
begin
	# Parse HTML
	using Gumbo

	# CSS selector for parsed HTML
	using Cascadia

	# Pluto Notebook utilities
	using PlutoUI

	# Work with tabular data (similar to pandas in Python)
	using DataFrames

	# General purpose linear algebra
	using LinearAlgebra

	# Working with Dates and DateTimes
	using Dates

	# Make plots for data visualization
	using Plots
end

# ╔═╡ 2398b4e5-5920-442e-980b-f75359ba73ae
md"""
# Assignment 1

- Name: Eric Nguyen
- TUID: 915786865
"""

# ╔═╡ 97d595d3-3c44-4112-a7a8-4efe4c1ba943
md"""
# Problem 1

The goal is to provide better data about the top 50 solar flares recorded so far than those shown by [SpaceWeatherLive.com](https://www.spaceweatherlive.com/en/solar-activity/top-50-solar-flares).
Use [this messy NASA data](http://cdaw.gsfc.nasa.gov/CME_list/radio/waves_type2.html) to add more features for the top 50 solar flares.
You need to scrape this information directly from each HTML page.
You can read here more about [Solar Flares](https://en.wikipedia.org/wiki/Solar_flare), [coronal mass ejections](https://www.spaceweatherlive.com/en/help/what-is-a-coronal-mass-ejection-cme), and [the solar flare alphabet soup](http://spaceweather.com/glossary/flareclasses.html).
"""

# ╔═╡ 62ba405d-4d1a-42b7-bacc-1350bf90564e
md"## Part 1: Data scraping and preparation"

# ╔═╡ d6c88a68-c221-417b-bb78-06938fe97407
md"""
### Task 1: Scrape your competitor's data

Scrape data for the top 50 solar flares shown in [SpaceWeatherLive.com](https://www.spaceweatherlive.com/en/solar-activity/top-50-solar-flares).
"""

# ╔═╡ 151282f9-0a35-435c-9cba-e7736efccb3f
swldf() = let
	# Make request to website for HTML data using cookies to gain authorization for web scraping
	data = read(`curl 'https://www.spaceweatherlive.com/en/solar-activity/top-50-solar-flares.html' \
  -H 'authority: www.spaceweatherlive.com' \
  -H 'cache-control: max-age=0' \
  -H 'sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  -H 'upgrade-insecure-requests: 1' \
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36' \
  -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'sec-fetch-site: same-origin' \
  -H 'sec-fetch-mode: navigate' \
  -H 'sec-fetch-user: ?1' \
  -H 'sec-fetch-dest: document' \
  -H 'referer: https://www.spaceweatherlive.com/en/solar-activity/top-50-solar-flares.html' \
  -H 'accept-language: en-US,en;q=0.9' \
  -H 'cookie: CookieScriptConsent={"action":"accept","categories":"[\"targeting\",\"performance\"]","CMP":"CPSyPX3PSyPX3F2ADBENBdCsAP_AAH_AAAAAH6Nf_X__bX9j-_59__t0eY1f9_7_v-wzjhfdt-8N2P_X_L0X42E7PF36pq4KuR4Eu3LBIQNlHOHUTUmw6okVrTPsak2Mr7NKJ7LEmnMZe2dYGHtfn91TuZKY7_78_9fz3_-v_v___9f3r-3_3__59X---_e_V399zLv9_____9nA_YAkw1L4ALsSxwZJo0qhRAhCsJDoBQAUUAwtE1hAwuCnZWAR6ggYAITUBGBECDEFGLAIABAIAkIiAkAPBAIgCIBAACAFSAhAARMAgsALAwCAAUA0LECKAIQJCDI4KjlMCAiRaKCeysASi72NMIQyiwAoFH9FRgIlCCBYGQkLBzGAAAAA.YAAAAAAAAAAA","key":"cd200ab5-5ddb-4df2-8057-ad9de673f1e6"}; _gid=GA1.2.1779020148.1642128786; SPSI=e3d46e0ee55ab21c983b674967abeb21; SPSE=QtZcE7RE5wJ43mJgik/6IiEWjaVvJvUBWREba0C084quUcv8c2WF9rgKyHChd+zcp+4hVlkLs6x5OJPlBXX6HA==; spcsrf=2db0574ff9f3e8b9fbc45b8804c9f061; sp_lit=/BKwhMbFX5iEuAmhsZlBwA==; UTGv2=h47aacd40fcd612bc33976e2edcd25116129; adOtr=643eeedS055; PRLST=ua/Ry/Ai; _ga_25HHLX0QL3=GS1.1.1642218626.6.1.1642219616.0; _ga=GA1.2.737209106.1642128785' \
  --compressed`, String)

	# Parse HTML data using CSS selectors
	page = parsehtml(data)
	table = first(eachmatch(sel".table-responsive-md > table", page.root))
	thead = first(eachmatch(sel"thead", table))
	tbody = first(eachmatch(sel"tbody", table))

	# Use reshape() to convert list of <td> to 1x8-Matrix
	# Vertically concatenate each <td> Matrix to form 50x8 Matrix
	datarows = reduce(vcat, [reshape([Gumbo.text(td.children[1]) for td ∈ tr.children], (1, :)) for tr ∈ eachmatch(sel"tr", tbody)])

	# Put rows of data into DataFrame
	df = DataFrame(datarows, [:rank, :x_class, :date, :region, :start_time, :max_time, :end_time, :movie])
end

# ╔═╡ 8f922beb-d685-4790-a08b-0d24810c417d
md"#### DataFrame for top 50 solar flares from SpaceWeatherLive.com"

# ╔═╡ c93284d7-0cb2-4991-a44e-a30e53c29a93
swldf()

# ╔═╡ 99a21f98-bd1a-4bc4-a619-668e824bb788
md"### Task 2: Tidy the top 50 solar flare data"

# ╔═╡ 6fa4452d-ddcd-4df7-996a-ba75ae21ba6e
tidy_swldf() = let
	df = swldf()

	# Remove '+' from x_class
	df[!,:x_class][last.(df[!,:x_class]) .== '+'] = chop.(df[!,:x_class][last.(df[!,:x_class]) .== '+'])

	# Drop last column of DataFrame
	select!(df, Not(:movie))

	# Set missing values to missing (if they exist)
	allowmissing!(df, :region)
	df[!,:region][df[!,:region] .== "-"] .= missing

	# Convert rank to integer
	df.rank = parse.(Int, df.rank)

	# Convert dates and times to DateTime
	df[!,:date] = Date.(df[:, :date], "yyyy/mm/dd")
	df[!,:start_time] = DateTime.(df[:, :date], Time.(df[:, :start_time]))
	df[!,:max_time] = DateTime.(df[:, :date], Time.(df[:, :max_time]))
	df[!,:end_time] = DateTime.(df[:, :date], Time.(df[:, :end_time]))

	# Drop date columns
	select!(df, Not(:date))

	# Rename columns
	rename!(df, :start_time => :start_datetime)
	rename!(df, :max_time => :max_datetime)
	rename!(df, :end_time => :end_datetime)

	# Reorder columns
	df[!, [:rank, :x_class, :start_datetime, :max_datetime, :end_datetime, :region]]
end

# ╔═╡ e2c62cf7-9c2e-48d7-97a3-0990328e6ec5
md"#### Tidied DataFrame for top 50 solar flares from SpaceWeatherLive.com"

# ╔═╡ ff744877-012a-4edf-bdf9-a9e29744cff3
tidy_swldf()

# ╔═╡ d5bf8c5a-229e-4a2f-bbff-6d1ef6fcf9c6
md"""
### Task 3: Scrape the NASA data

Scrape the [NASA data](http://cdaw.gsfc.nasa.gov/CME_list/radio/waves_type2.html) to get additional features about the solar flares using the [table format description](http://cdaw.gsfc.nasa.gov/CME_list/radio/waves_type2_description.htm).
"""

# ╔═╡ 467168a3-33d0-46e4-acdc-3aea85fd2ff5
nasadf() = let
	# Make request to website for HTML data
	data = read(`curl https://cdaw.gsfc.nasa.gov/CME_list/radio/waves_type2.html`, String)

	# Parse HTML data using CSS selectors
	page = parsehtml(data)
	pre = Gumbo.text(first(eachmatch(sel"pre", page.root)))
	data = reduce(vcat, [reshape(split(row)[1:14], (1,:)) for row ∈ split(pre, '\n')[12:end-1]])

	# Put data into DataFrame
	df = DataFrame(data, [:start_date, :start_time, :end_date, :end_time, :start_frequency, :end_frequency, :flare_location, :flare_region, :flare_classification, :cme_date, :cme_time, :cme_angle, :cme_width, :cme_speed])
end

# ╔═╡ c7e4ee98-8c09-4eb5-aa9d-df7a8e2b51d7
md"#### DataFrame of solar flare data from NASA"

# ╔═╡ 9f986c37-8f68-4348-a587-1cc18f924fee
nasadf()

# ╔═╡ fd3f32e1-29b6-4766-b1a4-60ce09c9e8f9
md"### Task 4: Tidy the NASA table"

# ╔═╡ cc46809e-3436-4748-a29a-2a82cc197d66
tidy_nasadf() = let
	df = nasadf()
	allowmissing!(df)

	# Replace missing data with 'missing'
	df[!,:start_frequency][df[!,:start_frequency] .== "????"] .= missing
	df[!,:end_frequency][df[!,:end_frequency] .== "????"] .= missing
	df[!,:flare_location][df[!,:flare_location] .== "------"] .= missing
	df[!,:flare_region][df[!,:flare_region] .== "-----"] .= missing
	df[!,:flare_classification][df[!,:flare_classification] .== "----"] .= missing
	df[!,:cme_date][df[!,:cme_date] .== "--/--"] .= missing
	df[!,:cme_time][df[!,:cme_time] .== "--:--"] .= missing
	df[!,:cme_angle][df[!,:cme_angle] .== "----"] .= missing
	df[!,:cme_width][df[!,:cme_width] .== "----" .|| df[!,:cme_width] .== "---"] .= missing
	df[!,:cme_speed][df[!,:cme_speed] .== "----"] .= missing

	# Create is_halo column and set Halo angles to missing
	df.is_halo = df[!,:cme_angle] .== "Halo"
	df[!,:cme_angle][coalesce.(df.is_halo, false)] .= missing

	# Indicate lower bound and strip non-numeric parts of width
	df.width_lower_bound = occursin.(">", coalesce.(df[!,:cme_width], ""))
	df[!,:cme_width][df.width_lower_bound] = replace.(df[!,:cme_width][df.width_lower_bound], ">" => "")
	df[!,:cme_width] = replace.(coalesce.(df[!,:cme_width], "-1"), "h" => "")

	# Convert dates and times to DateTime
	df[!,:start_date] = Date.(df[:, :start_date], "yyyy/mm/dd")
	df[!,:end_date] = Date.(string.(year.(df[!,:start_date])) .* "/" .* df[:, :end_date], "yyyy/mm/dd")

	df[!,:start_time] = DateTime.(df[:, :start_date], Time.(df[:, :start_time]))
	df[!,:end_time][df[!,:end_time] .== "24:00"] .= "23:59" # Fix invalid time format
	df[!,:end_time] = DateTime.(df[:, :end_date], Time.(df[:, :end_time]))

	df[!,:cme_date] = Date.(coalesce.(string.(year.(df[!,:start_date])) .* "/" .* df[!,:cme_date], "0"), "yyyy/mm/dd")
	allowmissing!(df, :cme_date)
	df[!,:cme_date][year.(df[!,:cme_date]) .== 0] .= missing

	df[!,:cme_time] = DateTime.(coalesce.(df[:, :cme_date], Date(0)), Time.(coalesce.(df[:, :cme_time], "0")))
	allowmissing!(df, :cme_time)
	df[!,:cme_time][year.(df[!,:cme_time]) .== 0] .= missing

	# Parse int columns
	for col ∈ [:start_frequency, :end_frequency, :cme_angle, :cme_width, :cme_speed]
		df[!,col] .= parse.(Int, coalesce.(df[!,col], "-1"))
		allowmissing!(df, col)
		df[!,col][df[!,col] .== -1] .= missing
	end

	# Drop date columns
	select!(df, Not(:start_date))
	select!(df, Not(:end_date))
	select!(df, Not(:cme_date))

	# Rename columns
	rename!(df, :start_time => :start_datetime)
	rename!(df, :end_time => :end_datetime)
	rename!(df, :cme_time => :cme_datetime)
	rename!(df, :cme_angle => :cpa)
	rename!(df, :cme_width => :width)
	rename!(df, :cme_speed => :speed)

	df
end

# ╔═╡ 8710210a-2dcf-4d63-a274-4ab44445a17f
md"#### Tidied DataFrame of solar flare data from NASA"

# ╔═╡ 12328375-5e07-49c1-83da-bdae88fcc8d4
tidy_nasadf()

# ╔═╡ 1e97263b-5fa9-497b-b610-7f3ad30b5520
md"## Part 2: Analysis"

# ╔═╡ 238002f4-c32b-41bc-8342-ac238828f74a
md"### Task 5: Replication"

# ╔═╡ 3156a7d1-d1a3-414e-8794-c895ed08f3b0
replicate_nasadf() = let
	df = tidy_nasadf()

	# Sort DataFrame by flare classification in descending order
	df = sort(subset(dropmissing(df, :flare_classification), :flare_classification => x -> occursin.('X', x)), order(:flare_classification, by = x -> parse(Float64, x[2:end])), rev=true)

	# Rename columns
	rename!(df, :cme_datetime => :max_datetime)
	rename!(df, :flare_classification => :x_class)
	rename!(df, :flare_region => :region)

	# Truncate regions
	df[!,:region][length.(coalesce.(df[!,:region], "")) .> 4] .= chop.(df[!,:region][length.(coalesce.(df[!,:region], "")) .> 4], head = 1, tail = 0)

	# Remove trailing dots from x_class
	df[!,:x_class][last.(df[!,:x_class]) .== '.'] .= chop.(df[!,:x_class][last.(df[!,:x_class]) .== '.'])

	# Reorder the columns
	df[!, [:x_class, :start_datetime, :max_datetime, :end_datetime, :region]]
end

# ╔═╡ b35a3d34-628e-470d-96b2-076a1e3d5ba5
md"#### DataFrame replication for top 50 solar flares using NASA data"

# ╔═╡ 6048f590-30e0-41ea-bcb9-a283d700668b
replicate_nasadf()[1:50,:]

# ╔═╡ ec522eda-7c21-4691-863e-4b9adf1414b3
md"""
**Task 5 result.** Using the NASA table, I cannot produce an exact replicate due to discrepancies between the tables, e.g., some of the dates/times are different between the tables, and there are some records in the tables that don't exist in the other table.
"""

# ╔═╡ 0509b052-02c7-4cf5-9c1f-fa5cf584360c
md"### Task 6: Integration"

# ╔═╡ 9a30c019-fc18-492c-b147-14c234c8ff12
integrated_nasadf() = let
	df = replicate_nasadf()
	df_t50 = tidy_swldf()

	# Find most similar row from SpaceWeatherLive.com
	similarities = [
		findmin([
			sqrt.(
				# Compare x_class
				(parse.(Float64, chop.(row[:x_class], head = 1, tail = 0)) - parse.(Float64, chop.(t50row[:x_class], head = 1, tail = 0))).^2 +

				# Compare start_datetime
				Dates.value.(Dates.Minute.(row[:start_datetime] - t50row[:start_datetime])).^2 +

				# Compare max_datetime
				Dates.value.(Dates.Minute.(coalesce.(row[:max_datetime], DateTime(0)) - t50row[:max_datetime])).^2 .*

				# Ignore missing max_datetimes
				Dates.value.(Dates.Minute.(coalesce.(row[:max_datetime], DateTime(0)))) +

				# Compare end_datetime
				Dates.value.(Dates.Minute.(row[:end_datetime] - t50row[:end_datetime])).^2 +

				# Compare region
				(parse.(Int, coalesce.(row[:region], "0")) - parse.(Int, t50row[:region])).^2 .*

				# Ignore missing regions
				parse.(Int, coalesce.(row[:region], "0"))
			) for t50row ∈ eachrow(df_t50)]) for row ∈ eachrow(df)
	]

	# Add rank column
	insertcols!(df, 1, :rank => [similarities[x][2] for x ∈ 1:length(similarities)])
	allowmissing!(df, :rank)
	buf = Set()
	min_xclass = minimum(parse.(Float64, chop.(df_t50[!,:x_class], head = 1, tail = 0)))
	for row ∈ eachrow(df)
		if row[:rank] ∈ buf || parse(Float64, chop(row[:x_class], head = 1, tail = 0)) < min_xclass
			row[:rank] = missing
		else
			push!(buf, row[:rank])
		end
	end

	# Remove rows with missing rank
	df = df[(!ismissing).(df[!,:rank]), :]

	# Sort rows by rank
	sort(df)
end

# ╔═╡ 074eb18b-05eb-456e-89c7-39b7b122e14e
md"#### Integrated DataFrame of top 50 solar flares from NASA"

# ╔═╡ 53a2adeb-4d89-41e5-8a38-bb0abb2466eb
integrated_nasadf()

# ╔═╡ f9ac8b88-2383-4ef2-a9b9-01435654ebf8
md"### Task 7: Attributes visualization"

# ╔═╡ e389aaa7-82c8-4569-ace4-d13e2e3fb3ec
dataviz(feature) = let
	df = tidy_nasadf()
	df_t50 = integrated_nasadf()
	t50 = filter(row -> row[:start_datetime] ∈ df_t50[!,:start_datetime], df)
	nott50 = filter(row -> row[:start_datetime] ∉ df_t50[!,:start_datetime], df)
	scatter(nott50[!,:start_datetime], nott50[!,feature], label="Other")
	scatter!(t50[!,:start_datetime], t50[!,feature], label="Top 50", marker=:star, markersize=8)
	xlabel!("Starting DateTime")
end

# ╔═╡ c4311bd3-6cd0-4bf9-8210-8b6555d3175f
let
	dataviz(:start_frequency)
	ylabel!("Starting frequencies (kHz)")
	title!("Starting frequencies over time")
end

# ╔═╡ 8f8db2f8-bf75-4828-862c-2b361eb33692
let
	dataviz(:end_frequency)
	ylabel!("Ending frequencies (kHz)")
	title!("Ending frequencies over time")
end

# ╔═╡ 8e6d61eb-923d-47c3-9306-237529a60672
let
	dataviz(:width)
	ylabel!("CME width in the sky plane (degrees)")
	title!("CME width over time")
end

# ╔═╡ b5eb2437-a13e-4b69-a378-e977ecf0fba7
let
	dataviz(:speed)
	xlabel!("Starting DateTime")
	ylabel!("CME Speed in the sky plane (km/s)")
	title!("CME Speeds over time")
end

# ╔═╡ 55ec5071-e9a5-4acf-9e15-9947cc9be2b5
md"### Task 8: Attributes comparison"

# ╔═╡ 046bd1e5-e6c8-46b4-bace-11fe8ef95b50
let
	df = tidy_nasadf()
	df_t50 = integrated_nasadf()
	t50 = filter(row -> row[:start_datetime] ∈ df_t50[!,:start_datetime], df)
	nott50 = filter(row -> row[:start_datetime] ∉ df_t50[!,:start_datetime], df)
	t50ratio = sum(coalesce.(t50[!,:is_halo], false)) / length(t50[!,:is_halo])
	nott50ratio = sum(coalesce.(nott50[!,:is_halo], false)) / length(nott50[!,:is_halo])
	bar(["Top 50", "Other"], [t50ratio, nott50ratio], color = [theme_palette(:auto)[1], theme_palette(:auto)[2]], legend = false)
	ylabel!("Ratio of Halo CMEs vs. Number of CMEs")
	title!("Comparision of ratios of Halo CMEs between the\n top 50 solar flares and the rest of the solar flares")
end

# ╔═╡ e6c5c88c-1d13-4785-bdea-6048cc905dcc
md"### Task 9: Events distribution"

# ╔═╡ d1ffbd03-3454-4e95-8c8f-3466a0d3ecbc
let
	df = tidy_nasadf()
	df_t50 = integrated_nasadf()
	t50 = filter(row -> row[:start_datetime] ∈ df_t50[!,:start_datetime], df)
	nott50 = filter(row -> row[:start_datetime] ∉ df_t50[!,:start_datetime], df)

	# Plot the number of years instead of months to make it easier to visualize
	numyears = length(df[!,:start_datetime][1]:Year(1):df[!,:start_datetime][end])
	h = histogram(nott50[!,:start_datetime], label="Other", nbins = numyears)
	histogram!(h, t50[!,:start_datetime], label="Top 50", nbins = numyears)
	plot(h, xticks = [df[!,:start_datetime][1], df[!,:start_datetime][end÷2], df[!,:start_datetime][end]], xformatter = x -> Date(Dates.epochms2datetime(x)))
	title!("Number of solar flares per month")
end

# ╔═╡ bd510480-984e-44ef-ac45-2fbfa909eb9e
md"There appears to be a cluster of strong flares between the years 2001-2003 however there are no other clusters apparent in the data."

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Cascadia = "54eefc05-d75b-58de-a785-1a3403f0919f"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
Gumbo = "708ec375-b3d6-5a57-a7ce-8257bf98657a"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"

[compat]
Cascadia = "~1.0.1"
DataFrames = "~1.3.1"
Gumbo = "~0.8.0"
Plots = "~1.25.6"
PlutoUI = "~0.7.29"
"""

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

julia_version = "1.7.1"
manifest_format = "2.0"

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

[[deps.AbstractTrees]]
git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.3.4"

[[deps.Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "af92965fb30777147966f58acb05da51c5616b5f"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.3"

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

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

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

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

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

[[deps.Cascadia]]
deps = ["AbstractTrees", "Gumbo"]
git-tree-sha1 = "95629728197821d21a41778d0e0a49bc2d58ab9b"
uuid = "54eefc05-d75b-58de-a785-1a3403f0919f"
version = "1.0.1"

[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "926870acb6cbcf029396f2f2de030282b6bc1941"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.11.4"

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

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

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

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

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

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

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

[[deps.Crayons]]
git-tree-sha1 = "b618084b49e78985ffa8422f32b9838e397b9fc2"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.1.0"

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

[[deps.DataFrames]]
deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "cfdfef912b7f93e4b848e80b9befdf9e331bc05a"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.3.1"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[[deps.Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"

[[deps.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"

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

[[deps.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 = "aa22e1ee9e722f1da183eb33370df4c1aeb6c2cd"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.63.1+0"

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

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

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

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

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

[[deps.Gumbo]]
deps = ["AbstractTrees", "Gumbo_jll", "Libdl"]
git-tree-sha1 = "e711d08d896018037d6ff0ad4ebe675ca67119d4"
uuid = "708ec375-b3d6-5a57-a7ce-8257bf98657a"
version = "0.8.0"

[[deps.Gumbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "29070dee9df18d9565276d68a596854b1764aa38"
uuid = "528830af-5a63-567c-a44a-034ed33b8444"
version = "0.10.2+0"

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

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

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

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

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

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

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

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

[[deps.InvertedIndices]]
git-tree-sha1 = "bee5f1ef5bf65df56bdd2e40447590b272a5471f"
uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f"
version = "1.1.0"

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

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

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

[[deps.JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "22df5b96feef82434b07327e2d3c770a9b21e023"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.4.0"

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

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

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

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

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

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

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

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

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

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

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

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

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

[[deps.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"

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

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

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

[[deps.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"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"

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

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

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

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

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

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

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

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

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

[[deps.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 = "db7393a80d0e5bef70f2b518990835541917a544"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.25.6"

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

[[deps.PooledArrays]]
deps = ["DataAPI", "Future"]
git-tree-sha1 = "db3a23166af8aebf4db5ef87ac5b00d36eb771e2"
uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720"
version = "1.4.0"

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

[[deps.PrettyTables]]
deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"]
git-tree-sha1 = "dfb54c4e414caa595a1f2ed759b160f5a3ddcba5"
uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d"
version = "1.3.1"

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

[[deps.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"

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

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

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

[[deps.RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"]
git-tree-sha1 = "37c1631cb3cc36a535105e6d5557864c82cd8c2b"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.5.0"

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

[[deps.RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "cdbd3b1338c72ce29d9584fdbe9e9b70eeb5adca"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "0.1.3"

[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"

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

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

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

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

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

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

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

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

[[deps.StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "2ae4fe21e97cd13efd857462c1869b73c9f61be3"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.3.2"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[[deps.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"

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

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

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

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

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

[[deps.Xorg_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"

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

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

[[deps.Xorg_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"

[[deps.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"

[[deps.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"

[[deps.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"

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

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

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

[[deps.Xorg_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"

[[deps.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"

[[deps.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"

[[deps.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"

[[deps.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"

[[deps.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"

[[deps.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"

[[deps.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"

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

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

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

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

[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"

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

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

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

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

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

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

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

[[deps.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:
# ╟─2398b4e5-5920-442e-980b-f75359ba73ae
# ╠═3f9f4948-74c3-11ec-2daf-51719517f805
# ╟─97d595d3-3c44-4112-a7a8-4efe4c1ba943
# ╟─62ba405d-4d1a-42b7-bacc-1350bf90564e
# ╟─d6c88a68-c221-417b-bb78-06938fe97407
# ╠═151282f9-0a35-435c-9cba-e7736efccb3f
# ╟─8f922beb-d685-4790-a08b-0d24810c417d
# ╠═c93284d7-0cb2-4991-a44e-a30e53c29a93
# ╟─99a21f98-bd1a-4bc4-a619-668e824bb788
# ╠═6fa4452d-ddcd-4df7-996a-ba75ae21ba6e
# ╟─e2c62cf7-9c2e-48d7-97a3-0990328e6ec5
# ╠═ff744877-012a-4edf-bdf9-a9e29744cff3
# ╟─d5bf8c5a-229e-4a2f-bbff-6d1ef6fcf9c6
# ╠═467168a3-33d0-46e4-acdc-3aea85fd2ff5
# ╟─c7e4ee98-8c09-4eb5-aa9d-df7a8e2b51d7
# ╠═9f986c37-8f68-4348-a587-1cc18f924fee
# ╟─fd3f32e1-29b6-4766-b1a4-60ce09c9e8f9
# ╠═cc46809e-3436-4748-a29a-2a82cc197d66
# ╟─8710210a-2dcf-4d63-a274-4ab44445a17f
# ╠═12328375-5e07-49c1-83da-bdae88fcc8d4
# ╟─1e97263b-5fa9-497b-b610-7f3ad30b5520
# ╟─238002f4-c32b-41bc-8342-ac238828f74a
# ╠═3156a7d1-d1a3-414e-8794-c895ed08f3b0
# ╟─b35a3d34-628e-470d-96b2-076a1e3d5ba5
# ╠═6048f590-30e0-41ea-bcb9-a283d700668b
# ╟─ec522eda-7c21-4691-863e-4b9adf1414b3
# ╟─0509b052-02c7-4cf5-9c1f-fa5cf584360c
# ╠═9a30c019-fc18-492c-b147-14c234c8ff12
# ╟─074eb18b-05eb-456e-89c7-39b7b122e14e
# ╠═53a2adeb-4d89-41e5-8a38-bb0abb2466eb
# ╟─f9ac8b88-2383-4ef2-a9b9-01435654ebf8
# ╠═e389aaa7-82c8-4569-ace4-d13e2e3fb3ec
# ╠═c4311bd3-6cd0-4bf9-8210-8b6555d3175f
# ╠═8f8db2f8-bf75-4828-862c-2b361eb33692
# ╠═8e6d61eb-923d-47c3-9306-237529a60672
# ╠═b5eb2437-a13e-4b69-a378-e977ecf0fba7
# ╟─55ec5071-e9a5-4acf-9e15-9947cc9be2b5
# ╠═046bd1e5-e6c8-46b4-bace-11fe8ef95b50
# ╟─e6c5c88c-1d13-4785-bdea-6048cc905dcc
# ╠═d1ffbd03-3454-4e95-8c8f-3466a0d3ecbc
# ╟─bd510480-984e-44ef-ac45-2fbfa909eb9e
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
function lookandsay(s::String)
    rst = IOBuffer()
    c = 1
    for i in 1:length(s)
        if i != length(s) && s[i] == s[i+1]
            c += 1
        else
            print(rst, c, s[i])
            c = 1
        end
    end
    String(take!(rst))
end

function lookandsayseq(n::Integer)
    rst = Vector{String}(undef, n)
    rst[1] = "1"
    for i in 2:n
        rst[i] = lookandsay(rst[i-1])
    end
    rst
end

println(lookandsayseq(10))

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode