text:
"""
Provides the [`missingdocs`](@ref), [`footnotes`](@ref) and [`linkcheck`](@ref) functions
for checking docs.
"""
module DocChecks

import ..Documenter:
    Documenter,
    Documents,
    Utilities,
    Utilities.Markdown2

using DocStringExtensions
import Markdown

using Logging
loglevel(doc) = doc.user.strict ? Logging.Error : Logging.Warn

# Missing docstrings.
# -------------------

"""
$(SIGNATURES)

Checks that a [`Documents.Document`](@ref) contains all available docstrings that are
defined in the `modules` keyword passed to [`Documenter.makedocs`](@ref).

Prints out the name of each object that has not had its docs spliced into the document.
"""
function missingdocs(doc::Documents.Document)
    doc.user.checkdocs === :none && return
    @debug "checking for missing docstrings."
    bindings = allbindings(doc.user.checkdocs, doc.blueprint.modules)
    for object in keys(doc.internal.objects)
        # The module references in docs blocks can yield a binding like
        # Docs.Binding(Mod, :SubMod) for a module SubMod, a submodule of Mod. However, the
        # module bindings that come from Docs.meta() always appear to be of the form
        # Docs.Binding(Mod.SubMod, :SubMod) (since Julia 0.7). We therefore "normalize"
        # module bindings before we search in the list returned by allbindings().
        binding = if Documenter.DocSystem.defined(object.binding) && !Documenter.DocSystem.iskeyword(object.binding)
            m = Documenter.DocSystem.resolve(object.binding)
            isa(m, Module) && nameof(object.binding.mod) != object.binding.var ?
                Docs.Binding(m, nameof(m)) : object.binding
        else
            object.binding
        end
        if haskey(bindings, binding)
            signatures = bindings[binding]
            if object.signature ≡ Union{} || length(signatures) ≡ 1
                delete!(bindings, binding)
            elseif object.signature in signatures
                delete!(signatures, object.signature)
            end
        end
    end
    n = reduce(+, map(length, values(bindings)), init=0)
    if n > 0
        b = IOBuffer()
        println(b, "$n docstring$(n ≡ 1 ? "" : "s") potentially missing:\n")
        for (binding, signatures) in bindings
            for sig in signatures
                println(b, "    $binding", sig ≡ Union{} ? "" : " :: $sig")
            end
        end
        push!(doc.internal.errors, :missing_docs)
        @logmsg loglevel(doc) String(take!(b))
    end
end

function allbindings(checkdocs::Symbol, mods)
    out = Dict{Utilities.Binding, Set{Type}}()
    for m in mods
        allbindings(checkdocs, m, out)
    end
    out
end

function allbindings(checkdocs::Symbol, mod::Module, out = Dict{Utilities.Binding, Set{Type}}())
    for (obj, doc) in meta(mod)
        isa(obj, IdDict{Any,Any}) && continue
        name = nameof(obj)
        isexported = Base.isexported(mod, name)
        if checkdocs === :all || (isexported && checkdocs === :exports)
            out[Utilities.Binding(mod, name)] = Set(sigs(doc))
        end
    end
    out
end

meta(m) = Docs.meta(m)

nameof(b::Base.Docs.Binding) = b.var
nameof(x) = Base.nameof(x)

sigs(x::Base.Docs.MultiDoc) = x.order
sigs(::Any) = Type[Union{}]

# Footnote checks.
# ----------------
"""
$(SIGNATURES)

Checks footnote links in a [`Documents.Document`](@ref).
"""
function footnotes(doc::Documents.Document)
    @debug "checking footnote links."
    # A mapping of footnote ids to a tuple counter of how many footnote references and
    # footnote bodies have been found.
    #
    # For all ids the final result should be `(N, 1)` where `N > 1`, i.e. one or more
    # footnote references and a single footnote body.
    footnotes = Dict{Documents.Page, Dict{String, Tuple{Int, Int}}}()
    for (src, page) in doc.blueprint.pages
        empty!(page.globals.meta)
        orphans = Dict{String, Tuple{Int, Int}}()
        for element in page.elements
            Documents.walk(page.globals.meta, page.mapping[element]) do block
                footnote(block, orphans)
            end
        end
        footnotes[page] = orphans
    end
    for (page, orphans) in footnotes
        for (id, (ids, bodies)) in orphans
            # Multiple footnote bodies.
            if bodies > 1
                push!(doc.internal.errors, :footnote)
                @logmsg loglevel(doc) "footnote '$id' has $bodies bodies in $(Utilities.locrepr(page.source))."
            end
            # No footnote references for an id.
            if ids === 0
                push!(doc.internal.errors, :footnote)
                @logmsg loglevel(doc) "unused footnote named '$id' in $(Utilities.locrepr(page.source))."
            end
            # No footnote bodies for an id.
            if bodies === 0
                push!(doc.internal.errors, :footnote)
                @logmsg loglevel(doc) "no footnotes found for '$id' in $(Utilities.locrepr(page.source))."
            end
        end
    end
end

function footnote(fn::Markdown.Footnote, orphans::Dict)
    ids, bodies = get(orphans, fn.id, (0, 0))
    if fn.text === nothing
        # Footnote references: syntax `[^1]`.
        orphans[fn.id] = (ids + 1, bodies)
        return false # No more footnotes inside footnote references.
    else
        # Footnote body: syntax `[^1]:`.
        orphans[fn.id] = (ids, bodies + 1)
        return true # Might be footnotes inside footnote bodies.
    end
end

footnote(other, orphans::Dict) = true

# Link Checks.
# ------------

hascurl() = (try; success(`curl --version`); catch err; false; end)

"""
$(SIGNATURES)

Checks external links using curl.
"""
function linkcheck(doc::Documents.Document)
    if doc.user.linkcheck
        if hascurl()
            for (src, page) in doc.blueprint.pages
                for element in page.elements
                    Documents.walk(page.globals.meta, page.mapping[element]) do block
                        linkcheck(block, doc)
                    end
                end
            end
        else
            push!(doc.internal.errors, :linkcheck)
            @logmsg loglevel(doc) "linkcheck requires `curl`."
        end
    end
    return nothing
end

function linkcheck(link::Markdown.Link, doc::Documents.Document; method::Symbol=:HEAD)

    # first, make sure we're not supposed to ignore this link
    for r in doc.user.linkcheck_ignore
        if linkcheck_ismatch(r, link.url)
            @debug "linkcheck '$(link.url)': ignored."
            return false
        end
    end

    if !haskey(doc.internal.locallinks, link)
        timeout = doc.user.linkcheck_timeout
        null_file = @static Sys.iswindows() ? "nul" : "/dev/null"
        cmd = `curl $(method === :HEAD ? "-sI" : "-s") --proto =http,https,ftp,ftps $(link.url) --max-time $timeout -o $null_file --write-out "%{http_code} %{url_effective} %{redirect_url}"`

        local result
        try
            # interpolating into backticks escapes spaces so constructing a Cmd is necessary
            result = read(cmd, String)
        catch err
            push!(doc.internal.errors, :linkcheck)
            @logmsg loglevel(doc) "$cmd failed:" exception = err
            return false
        end
        STATUS_REGEX = r"^(\d+) (\w+)://(?:\S+) (\S+)?$"m
        matched = match(STATUS_REGEX, result)
        if matched !== nothing
            status, scheme, location = matched.captures
            status = parse(Int, status)
            scheme = uppercase(scheme)
            protocol = startswith(scheme, "HTTP") ? :HTTP :
                startswith(scheme, "FTP") ? :FTP : :UNKNOWN

            if (protocol === :HTTP && (status < 300 || status == 302)) ||
                (protocol === :FTP && (200 <= status < 300 || status == 350))
                if location !== nothing
                    @debug "linkcheck '$(link.url)' status: $(status), redirects to $(location)."
                else
                    @debug "linkcheck '$(link.url)' status: $(status)."
                end
            elseif protocol === :HTTP && status < 400
                if location !== nothing
                    @warn "linkcheck '$(link.url)' status: $(status), redirects to $(location)."
                else
                    @warn "linkcheck '$(link.url)' status: $(status)."
                end
            elseif protocol === :HTTP && status == 405 && method === :HEAD
                # when a server doesn't support HEAD requests, fallback to GET
                @debug "linkcheck '$(link.url)' status: $(status), retrying without `-I`"
                return linkcheck(link, doc; method=:GET)
            else
                push!(doc.internal.errors, :linkcheck)
                @logmsg loglevel(doc) "linkcheck '$(link.url)' status: $(status)."
            end
        else
            push!(doc.internal.errors, :linkcheck)
            @logmsg loglevel(doc) "invalid result returned by $cmd:" result
        end
    end
    return false
end
linkcheck(other, doc::Documents.Document) = true

linkcheck_ismatch(r::String, url) = (url == r)
linkcheck_ismatch(r::Regex, url) = occursin(r, url)

end


text:
using JuMP
using CPLEX
include("instances/exemple-lecture-graphe.jl")
include("exercice1.jl")
# include("exercice2.jl")
# include("exercice3.jl")

global b = 1 # broadband

time_1 = @timed Benders("benders3.txt", b) # exo 1

println("size of instance = ", n)
println(time_1.time, " seconds for exercise 1")

ext: jl

max_stars_repo_name: boumpteryx/MLA

max_issues_repo_name: boumpteryx/MLA

max_forks_repo_name: boumpteryx/MLA


text:
@testset "Py2Ju" begin
    pydict_str = """{
                'format': 'grib',
                'product_type': 'monthly_averaged_reanalysis',
                'variable': 'divergence',
                'pressure_level': '1',
                'year': '2020',
                'month': '06',
                'area': [
                    90, -180, -90,
                    180,
                ],
                'time': '00:00',
            }"""
    julia_dict = Dict("format"=> "grib",
                    "month" => "06",
                    "time" => "00:00",
                    "year" => "2020",
                    "pressure_level" => "1",
                    "area" => Any[90, -180, -90, 180],
                    "product_type" => "monthly_averaged_reanalysis",
                    "variable" => "divergence")
    py2ju_result = py2ju(pydict_str)

    @test typeof(py2ju_result) <: Dict
    @test py2ju_result == julia_dict
end


text:
#!/usr/bin/env julia
# -*- coding: utf-8 -*-
#=
Apply HANTS process on an integer array
=#
cd(dirname(@__FILE__))
include("../HANTS.jl")
using .HANTS, Plots

y = [
     559,  370,  626, 1201, 1782, 2444, 2131, 4946,
    3287, 5617, 3803, 6412, 5324, 8277, 6540, 8166,
    6114, 6615, 3980, 3398, 1139,  867,  586
]

nbase = 365
nfreq = 3
tseries = 1:16:365
validrange = (-10000, 10000)
fet = 0.02
dod = 5
δ = 0.1

A, φ, yrec = hants(
    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=nothing
)
y_reconstruct = reconstruct(A, φ, nbase)

A_Hi, φ_Hi, yrec_Hi = hants(
    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Hi
)
y_reconstruct_Hi = reconstruct(A_Hi, φ_Hi, nbase)

A_Lo, φ_Lo, yrec_Lo = hants(
    y, fet, dod, δ; nbase=nbase, nfreq=nfreq, validrange=validrange, tseries=tseries, outlier=:Lo
)
y_reconstruct_Lo = reconstruct(A_Lo, φ_Lo, nbase)

fig1 = plot(tseries, y, lc=:black, label="Original Data", shape=:circle, mc=:black)
plot!(tseries, yrec, lc=:blue, label="HANTS - None", shape=:circle, mc=:blue)
plot!(tseries, yrec_Hi, lc=:red, label="HANTS - Hi", shape=:circle, mc=:red)
plot!(tseries, yrec_Lo, lc=:green, label="HANTS - Lo", shape=:circle, mc=:green)
title!("Testing HANTS Algorithm")

fig2 = plot(tseries, y, lc=:black, label="Original Data", shape=:circle, mc=:black)
plot!(1:365, y_reconstruct, lc=:blue, label="HANTS - None")
plot!(1:365, y_reconstruct_Hi, lc=:red, label="HANTS - Hi")
plot!(1:365, y_reconstruct_Lo, lc=:green, label="HANTS - Lo")
title!("Testing HANTS Reconstruct")

plot(fig1, fig2; layout=(1, 2), size=(800,300))

max_stars_repo_name: shenrq/JuliaHANTS


text:
# automatically generated by the FlatBuffers compiler, do not modify

MyGame.Example.eval(quote

FlatBuffers.@with_kw mutable struct TypeAliases
    i8::Int8 = 0
    u8::UInt8 = 0
    i16::Int16 = 0
    u16::UInt16 = 0
    i32::Int32 = 0
    u32::UInt32 = 0
    i64::Int64 = 0
    u64::UInt64 = 0
    f32::Float32 = 0.0
    f64::Float64 = 0.0
    v8::Vector{Int8} = []
    vf64::Vector{Float64} = []
end
FlatBuffers.@ALIGN(TypeAliases, 1)
FlatBuffers.slot_offsets(::Type{T}) where {T<:TypeAliases} = [
    0x00000004, 0x00000006, 0x00000008, 0x0000000A,
    0x0000000C, 0x0000000E, 0x00000010, 0x00000012,
    0x00000014, 0x00000016, 0x00000018, 0x0000001A
]

TypeAliases(buf::AbstractVector{UInt8}) = FlatBuffers.read(TypeAliases, buf)
TypeAliases(io::IO) = FlatBuffers.deserialize(io, TypeAliases)

end)

max_stars_repo_name: rjkat/flatbuffers-julia

max_issues_repo_name: rjkat/flatbuffers-julia

max_forks_repo_name: rjkat/flatbuffers-julia


text:
"""
    AbstractSlpOptimizer

Abstract type of SLP solvers
"""
abstract type AbstractSlpOptimizer <: AbstractOptimizer end

function LpData(slp::AbstractSlpOptimizer)
	A = compute_jacobian_matrix(slp)
	return QpData(
        MOI.MIN_SENSE,
        nothing,
		slp.df,
		slp.f,
		A,
		slp.E,
		slp.problem.g_L,
		slp.problem.g_U,
		slp.problem.x_L,
		slp.problem.x_U)
end

function sub_optimize!(slp::AbstractSlpOptimizer, Δ = 1000.0)
    if isnothing(slp.optimizer)
        j_row = Vector{Int}(undef, length(slp.problem.j_str))
        j_col = Vector{Int}(undef, length(slp.problem.j_str))
        for i=1:length(slp.problem.j_str)
            j_row[i] = Int(slp.problem.j_str[i][1]);
            j_col[i] = Int(slp.problem.j_str[i][2]);
        end
        slp.optimizer = QpModel(
            MOI.instantiate(slp.options.external_optimizer),
            LpData(slp),
            j_row,
            j_col
        )
        create_model!(slp.optimizer, slp.x, Δ)
    else
        slp.optimizer.data = LpData(slp)
    end
    return sub_optimize!(
        slp.optimizer,
        slp.x,
        Δ,
        slp.feasibility_restoration
    )
end

"""
    compute_nu!

Compute the penalty parameter for the merit function. This is based on the paper: https://doi.org/10.1016/j.epsr.2018.09.002
"""
function compute_nu!(slp::AbstractSlpOptimizer)
    if slp.iter == 1
        norm_df = ifelse(slp.feasibility_restoration, 1.0, norm(slp.df))
        J = compute_jacobian_matrix(slp)
        for i = 1:slp.problem.m
            slp.ν[i] = max(1.0, norm_df / max(1.0, norm(J[i, :])))
        end
    else
        for i = 1:slp.problem.m
            slp.ν[i] = max(slp.ν[i], abs(slp.lambda[i]))
        end
    end
end

"""
    compute_phi

Evaluate and return the merit function value for a given point x + α * p.

# Arguments
- `slp`: SlpLS structure
- `x`: the current solution point
- `α`: step size taken from `x`
- `p`: direction taken from `x`
"""
function compute_phi(slp::AbstractSlpOptimizer, x::Tv, α::T, p::Tv) where {T,Tv<:AbstractArray{T}}
    ϕ = 0.0
    xp = x + α * p
    E = ifelse(α == 0.0, slp.E, slp.problem.eval_g(xp, zeros(slp.problem.m)))
    if slp.feasibility_restoration
        p_slack = slp.p_slack
        ϕ = slp.prim_infeas
        for (i, v) in p_slack
            ϕ += α * sum(v)
        end
        for i = 1:slp.problem.m
            viol =
                maximum([0.0, slp.E[i] - slp.problem.g_U[i], slp.problem.g_L[i] - slp.E[i]])
            lhs = E[i] - viol
            if slp.problem.g_L[i] > -Inf && slp.problem.g_U[i] < Inf
                lhs += α * (p_slack[i][1] - p_slack[i][2])
            elseif slp.problem.g_L[i] > -Inf
                lhs += α * p_slack[i][1]
            elseif slp.problem.g_U[i] < Inf
                lhs -= α * p_slack[i][1]
            end
            ϕ +=
                slp.ν[i] *
                maximum([0.0, lhs - slp.problem.g_U[i], slp.problem.g_L[i] - lhs])
        end
    else
        ϕ = slp.problem.eval_f(xp)
        for i = 1:slp.problem.m
            if E[i] > slp.problem.g_U[i]
                ϕ += slp.ν[i] * (E[i] - slp.problem.g_U[i])
            elseif E[i] < slp.problem.g_L[i]
                ϕ += slp.ν[i] * (slp.problem.g_L[i] - E[i])
            end
        end
    end
    return ϕ
end

"""
    compute_derivative

Compute the directional derivative at current solution for a given direction.
"""
function compute_derivative(slp::AbstractSlpOptimizer)
    D = 0.0
    if slp.feasibility_restoration
        for (i, v) in slp.p_slack
            D += sum(v)
        end
        for i = 1:slp.problem.m
            viol =
                maximum([0.0, slp.E[i] - slp.problem.g_U[i], slp.problem.g_L[i] - slp.E[i]])
            lhs = slp.E[i] - viol
            D -=
                slp.ν[i] *
                maximum([0.0, lhs - slp.problem.g_U[i], slp.problem.g_L[i] - lhs])
        end
    else
        D = slp.df' * slp.p
        for i = 1:slp.problem.m
            if slp.E[i] > slp.problem.g_U[i]
                D -= slp.ν[i] * (slp.E[i] - slp.problem.g_U[i])
            elseif slp.E[i] < slp.problem.g_L[i]
                D -= slp.ν[i] * (slp.problem.g_L[i] - slp.E[i])
            end
        end
    end
    return D
end

"""
    KT_residuals

Compute Kuhn-Turck residuals
"""
KT_residuals(slp::AbstractSlpOptimizer) = KT_residuals(slp.df, slp.lambda, slp.mult_x_U, slp.mult_x_L, compute_jacobian_matrix(slp))

"""
    norm_complementarity

Compute the normalized complementeraity
"""
norm_complementarity(slp::AbstractSlpOptimizer, p = Inf) = norm_complementarity(
    slp.E, slp.problem.g_L, slp.problem.g_U,
    slp.x, slp.problem.x_L, slp.problem.x_U,
    slp.lambda, slp.mult_x_U, slp.mult_x_L,
    p
)

"""
    norm_violations

Compute the normalized constraint violation
"""

norm_violations(slp::AbstractSlpOptimizer, p = 1) = norm_violations(
    slp.E, slp.problem.g_L, slp.problem.g_U,
    slp.x, slp.problem.x_L, slp.problem.x_U,
    p
)

norm_violations(slp::AbstractSlpOptimizer, x::Tv, p = 1) where {T, Tv<:AbstractArray{T}} = norm_violations(
    slp.problem.eval_g(x, zeros(slp.problem.m)), slp.problem.g_L, slp.problem.g_U,
    slp.x, slp.problem.x_L, slp.problem.x_U,
    p
)

function eval_functions!(slp::AbstractSlpOptimizer)
    slp.f = slp.problem.eval_f(slp.x)
    slp.problem.eval_grad_f(slp.x, slp.df)
    slp.problem.eval_g(slp.x, slp.E)
    slp.problem.eval_jac_g(slp.x, :eval, [], [], slp.dE)
end

compute_jacobian_matrix(slp::AbstractSlpOptimizer) = compute_jacobian_matrix(slp.problem.m, slp.problem.n, slp.problem.j_str, slp.dE)

include("slp_line_search.jl")
include("slp_trust_region.jl")

max_stars_repo_name: exanauts/ActiveSetMethods

max_issues_repo_name: exanauts/ActiveSetMethods

max_forks_repo_name: exanauts/ActiveSetMethods


text:
function time_integration(N,x,y,z)

    dx,dy,dz = 0.,0.,0.         # pre-allocate

    for i = 1:N

        dx = dt*(σ*(y-x))       # RHS
        dy = dt*(x*(ρ-z) - y)
        dz = dt*(x*y - β*z)

        x += dx                 # Euler forward
        y += dy
        z += dz
    end
    x,y,z
end

N = Int(1e8)                    # number of time steps
const dt = 0.01                 # time step

x,y,z = 5.,5.,5.                # initial conditions

const σ = 10.                   # L63 parameters
const ρ = 28.
const β = 8./3.

time_integration(1,x,y,z)       # compile

@time x,y,z = time_integration(N,x,y,z) # RUN

max_stars_repo_name: milankl/misc

max_issues_repo_name: milankl/misc

max_forks_repo_name: milankl/misc


text:
using ChaosTools
using Test
using OrdinaryDiffEq: Tsit5

test_value = (val, vmin, vmax) -> @test vmin <= val <= vmax

println("\nTesting GALI...")

@testset "GALI discrete" begin

    @testset "Chaotic - towel map" begin
        ds = Systems.towel()
        model(x,p)= @. exp(-p[1]*x)
        ls = lyapunovspectrum(ds, 10000)
        threshold = 1e-16
        @testset "k=$k" for k in [2,3]
            ex = sum(ls[1] - ls[j] for j in 2:k)
            g, t = gali(ds, 1000, k; threshold = threshold)
            @test g[end] < threshold
            @test t[end] < 1000
            if k == 3
                fite = -linreg(t, log.(g))[2]
                @test isapprox(fite, ex, rtol=1)
            end
        end
    end

    @testset "Standard Map" begin
        ds = Systems.standardmap()
        k = 2
        @testset "chaotic" begin
            g, t = gali(ds, 1000, k)
            @test g[end] ≤ 1e-12
            @test t[end] < 1000
        end
        @testset "regular" begin
            g, t = ChaosTools.gali(ds, 1000, k; u0 =  [π, rand()])
            @test t[end] == 1000
            @test g[end] > 1/1000^2
        end
    end

    @testset "Coupled Standard Maps" begin
        M = 3; ks = 3ones(M); Γ = 0.1;
        stable = [π, π, π, 0.01, 0, 0] .+ 0.1
        chaotic = rand(2M)

        ds = Systems.coupledstandardmaps(M, stable; ks=ks, Γ = Γ)

        @testset "regular k=$k" for k in [2,3,4, 5, 6]
            g, t = gali(ds, 1000, k; threshold=1e-12)
            @test t[end] == 1000
            @test g[end] > 1e-12
        end

        @testset "chaotic k=$k" for k in [2,3,4, 5, 6]
            g, t = gali(ds, 1000, k; threshold=1e-12, u0 = chaotic)
            @test t[end] < 1000
            @test g[end] ≤ 1e-12
        end

    end
end

@testset "GALI continuous" begin
    @testset "Henon-Helies" begin
        sp = [0, .295456, .407308431, 0] #stable periodic orbit: 1D torus
        qp = [0, .483000, .278980390, 0] #quasiperiodic orbit: 2D torus
        ch = [0, -0.25, 0.42081, 0] # chaotic orbit
        tt = 1000
        ds = Systems.henonheiles()
        diffeq = Dict(:abstol=>1e-9, :reltol=>1e-9, :solver => Tsit5())
        @testset "regular" begin
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = sp)
                @test t[end] ≥ tt
            end
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = qp)
                @test t[end] ≥ tt
            end
        end
        @testset "chaotic" begin
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = ch)
                @test t[end] < tt
                @test g[end] ≤ 1e-12
            end
        end
    end

    # Test henon helies out of place & autodiffed
    function hhoop(u, p, t)
        du1 = u[3]
        du2 = u[4]
        du3 = -u[1] - 2u[1]*u[2]
        du4 = -u[2] - (u[1]^2 - u[2]^2)
        return SVector{4}(du1, du2, du3, du4)
    end
    @testset "Henon-Helies OOP" begin
        sp = [0, .295456, .407308431, 0] #stable periodic orbit: 1D torus
        qp = [0, .483000, .278980390, 0] #quasiperiodic orbit: 2D torus
        ch = [0, -0.25, 0.42081, 0] # chaotic orbit
        tt = 1000
        ds = Systems.ContinuousDynamicalSystem(hhoop, sp, nothing)
        diffeq = Dict(:abstol=>1e-9, :reltol=>1e-9, :solver => Tsit5())
        @testset "regular" begin
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = sp)
                @test t[end] ≥ tt
            end
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = qp)
                @test t[end] ≥ tt
            end
        end
        @testset "chaotic" begin
            for k in [2,4]
                g, t = gali(ds, tt, k; diff_eq_kwargs = diffeq, u0 = ch)
                @test t[end] < tt
                @test g[end] ≤ 1e-12
            end
        end
    end

end


text:
@testset "'MESS' ............................... " begin

  ss = SampleSpace(5:20, 100)

  params = MESS(
      ss, .2, .4, alpha = .05, beta = .2, pess = .4
  )

  @test null(params) == .2

  @test mtoer(params) == .05

  @test samplespace(params) == ss

  @test maxsamplesize(params) == 100

  @test minconditionalpower(params) == 0.0

  @test typeof(params) == MESS{typeof(1.0)}

  params = MESS(
      ss, .2, .4, minconditionalpower = .7
  )
  @test minconditionalpower(params) == 0.7

  design = optimaldesign(10, params, solver)

  @test score(design) < 26.5

end

max_stars_repo_name: kkmann/binaryTwoStageDesigns

max_issues_repo_name: kkmann/binaryTwoStageDesigns

max_forks_repo_name: kkmann/binaryTwoStageDesigns


text:
# IO utilities for vibronic systems.

function Base.read(io::IO, ::Type{System})
    data = JSON.parse(io)

    S = data["number of surfaces"]
    S >= 1 || throw(DomainError(S, "At least 1 surface."))

    M = data["number of modes"]
    M >= 1 || throw(DomainError(M, "At least 1 mode."))

    for key in ["linear coupling", "quadratic coupling"]
        haskey(data, key) && error("System file contains outdated key '$(key)'.")
    end

    energy = zeros(S, S)
    if haskey(data, "energies")
        length(data["energies"]) == size(energy, 1) || error("Bad energy size")
        for (idx1, data1) in enumerate(data["energies"])
            if length(data1) == 1
                energy[idx1, idx1] = data1[1]
            elseif length(data1) == size(energy, 2)
                for (idx2, data2) in enumerate(data1)
                    energy[idx1, idx2] = data2
                end
            else
                error("Bad energy size")
            end
        end
    end
    all(isapprox.(energy, permutedims(energy); rtol=1e-12)) || error("Asymmetric energy")

    freq = zeros(M, S)
    # We repeat the frequency values over the surfaces.
    if haskey(data, "frequencies")
        length(data["frequencies"]) == size(freq, 1) || error("Bad freq size")
        for (idx1, data1) in enumerate(data["frequencies"])
            freq[idx1, :] .= data1
        end
    end
    all(freq .> 0) || error("Nonpositive freq")

    lin = zeros(M, S, S)
    if haskey(data, "linear couplings")
        length(data["linear couplings"]) == size(lin, 1) || error("Bad lin size")
        for (idx1, data1) in enumerate(data["linear couplings"])
            length(data1) == size(lin, 2) || error("Bad lin size")
            for (idx2, data2) in enumerate(data1)
                if length(data2) == 1
                    lin[idx1, idx2, idx2] = data2[1]
                elseif length(data2) == size(lin, 3)
                    for (idx3, data3) in enumerate(data2)
                        lin[idx1, idx2, idx3] = data3
                    end
                else
                    error("Bad lin size")
                end
            end
        end
    end
    all(isapprox.(lin, permutedims(lin, [1, 3, 2]); rtol=1e-12)) || error("Asymmetric lin")

    quad = zeros(M, M, S, S)
    if haskey(data, "quadratic couplings")
        length(data["quadratic couplings"]) == size(quad, 1) || error("Bad quad size")
        for (idx1, data1) in enumerate(data["quadratic couplings"])
            length(data1) == size(quad, 2) || error("Bad quad size")
            for (idx2, data2) in enumerate(data1)
                length(data2) == size(quad, 3) || error("Bad quad size")
                for (idx3, data3) in enumerate(data2)
                    if length(data3) == 1
                        quad[idx1, idx2, idx3, idx3] = data3[1]
                    elseif length(data3) == size(quad, 4)
                        for (idx4, data4) in enumerate(data3)
                            quad[idx1, idx2, idx3, idx4] = data4
                        end
                    else
                        error("Bad quad size")
                    end
                end
            end
        end
    end
    all(isapprox.(quad, permutedims(quad, [1, 2, 4, 3]); rtol=1e-12)) || error("Asymmetric quad")

    energy, freq, lin, quad
end

Base.read(io::IO, ::Type{DenseSystem}) = DenseSystem(read(io, System)...)

Base.read(io::IO, ::Type{DiagonalSystem}) = DiagonalSystem(read(io, System)...)

Base.write(io::IO, sys::System) = JSON.print(io, sys)

function JSON.lower(sys::DenseSystem{S,M}) where {S,M}
    all(sys.freq .== sys.freq[:, 1]) || throw(DomainError(sys.freq, "All surfaces must have the same frequencies."))

    result = Dict()

    result["number of surfaces"] = S
    result["number of modes"] = M

    result["energies"] = permutedims(sys.energy)
    result["frequencies"] = sys.freq[:, 1]
    result["linear couplings"] = permutedims(sys.lin, [3, 2, 1])
    result["quadratic couplings"] = permutedims(sys.quad, [4, 3, 2, 1])

    result
end

function JSON.lower(sys::DiagonalSystem{S,M}) where {S,M}
    all(sys.freq .== sys.freq[:, 1]) || throw(DomainError(sys.freq, "All surfaces must have the same frequencies."))

    result = Dict()

    result["number of surfaces"] = S
    result["number of modes"] = M

    result["energies"] = diag(sys.energy)
    result["frequencies"] = sys.freq[:, 1]
    result["linear couplings"] = permutedims(diag(sys.lin, 2, 3))
    result["quadratic couplings"] = permutedims(diag(sys.quad, 3, 4), [3, 2, 1])

    result
end

function show_tensors(io::IO, sys::System{S,M}) where {S,M}
    if !iszero(sys.energy)
        println(io, "energies:")
        show_matrix(io, sys.energy)
    end
    println(io, "frequencies:")
    for m in 1:M
        println(io, " mode $(m)")
        show_vector(io, sys.freq[m, :])
    end
    if !iszero(sys.lin)
        println(io, "linear couplings:")
        for m in 1:M
            iszero(sys.lin[m, :, :]) && continue
            println(io, " mode $(m)")
            show_matrix(io, sys.lin[m, :, :])
        end
    end
    if !iszero(sys.quad)
        println(io, "quadratic couplings:")
        for m1 in 1:M
            for m2 in 1:M
                iszero(sys.quad[m2, m1, :, :]) && continue
                println(io, " modes $(m1), $(m2)")
                show_matrix(io, sys.quad[m2, m1, :, :])
            end
        end
    end
    nothing
end

function Base.show(io::IO, sys::DenseSystem{S,M}) where {S,M}
    println(io, typeof(sys))
    println(io, "Dense system with $(S) surface$(S == 1 ? "" : "s") and $(M) mode$(M == 1 ? "" : "s").")
    if isdiag(sys)
        println(io, "Does not contain inter-surface coupling.")
    else
        println(io, "Contains inter-surface coupling.")
    end
    show_tensors(io, sys)
    nothing
end

function Base.show(io::IO, sys::DiagonalSystem{S,M}) where {S,M}
    println(io, typeof(sys))
    println(io, "Diagonal system with $(S) surface$(S == 1 ? "" : "s") and $(M) mode$(M == 1 ? "" : "s").")
    show_tensors(io, sys)
    println(io, "energy offsets:")
    show_vector(io, sys.deltas)
    println(io, "position offsets:")
    for m in 1:M
        println(io, " mode $(m)")
        show_vector(io, sys.ds[m, :])
    end
    nothing
end


text:
using DataStructures
lines = readlines() .|> collect
small = [parse(Int, lines[y][x]) for y=1:length(lines), x=1:length(lines[1])]
large = reduce(hcat, [(small .- 1 .+ i) .% 9 .+ 1 for i=0:4])
large = reduce(vcat, [(large .- 1 .+ i) .% 9 .+ 1 for i=0:4])

function solve(field)
    sy, sx = size(field)
    queue = PriorityQueue((1, 1) => 0)
    cost = Dict((1, 1) => 0)
    while !isempty(queue)
        (y, x), prio = dequeue_pair!(queue)
        cost[(y, x)] = prio
        y == sy && x == sx && return prio
        for (y2, x2) in eachrow([-1 0; 1 0; 0 -1; 0 1] .+ [y x])
            if 1 <= y2 <= sy && 1 <= x2 <= sx && (y2, x2) ∉ keys(cost)
                newval, currval = (prio + field[y2, x2]), get(queue, (y2, x2), typemax(Int))
                newval < currval && (queue[(y2, x2)] = newval)
            end
        end
    end
end

println(solve(small))
println(solve(large))

max_stars_repo_name: LiquidFun/adventofcode

max_issues_repo_name: LiquidFun/adventofcode

max_forks_repo_name: LiquidFun/adventofcode