text:
__precompile__()

module ExpFunctions

struct FunctionSet
   setmodel!::Function
   initstate!::Function
   setcontrol!::Function
   observe!::Function
   reward::Function
   evaluate::Function
end
export FunctionSet

using Common: makesavedir, save
using mjWrap: save_traj
using Policy: save_pol
using LearningStrategies
import LearningStrategies: setup!, hook, cleanup!
export setup!, hook, cleanup!

#export FunctionSet
export PolicyExp
export ControlExp

# Policy Gradient experiment specific things
mutable struct PolicyExp <: LearningStrategy
   prefix::String
   expfile::String
   expname::String
   meshfile::String
   dir::String
   statefile::String
   policyfile::String
   expresults::String

   function PolicyExp(prefix::String, expfile::String,
                      expname::String, meshfile::String)
      return new(prefix, expfile, expname, meshfile, "", "", "", "")
   end
end

function setup!(s::PolicyExp, model)
   info("SETTING UP NPG EXPERIMENT")

   poltype = Base.datatype_name(typeof(model.policy))
   dir = "$(s.prefix)/$(s.expname)_$poltype"
   expdir = makesavedir(dir, s.expfile, model.mjsys.name, s.meshfile)
   s.dir        = "$(expdir)"
   s.statefile  = "$(expdir)/data.jld"
   s.policyfile = "$(expdir)/policy.jld"
   s.expresults = "$(expdir)/expmt.jld"
end

function hook(s::PolicyExp, model, i)
   if i==1 || model.trace[:stocR][i] >= maximum(model.trace[:stocR][1:i-1])
      info("\tSaving traj for experiment ", s.dir)
      save_traj(model.mjsys, model.samples, s.statefile)
      save_pol(model.policy,
               model.mjsys.skip,
               basename(model.mjsys.name),
               s.policyfile) # needs skip and model for policy playback (FIX LATER)
      save(s.expresults, model.trace)
   end
end

function cleanup!(s::PolicyExp, model)
   save(s.expresults, model.trace)
   info("Saved Experiment to ", s.dir)
   # email myself when done
   #run(`bash ./plot2html.sh $(scores[end]) $(expfile)`)
   #if cluster == 1
   #   println(workers())
   #   for w in workers()
   #      rmprocs(w)
   #   end
   #end
end

##### Control Experiment Functions
mutable struct ControlExp <: LearningStrategy
   prefix::String
   expfile::String
   expname::String
   meshfile::String
   dir::String
   statefile::String
   #policyfile::String
   expresults::String

   function ControlExp(prefix::String, expfile::String,
                       expname::String, meshfile::String)
      return new(prefix, expfile, expname, meshfile, "", "", "")
   end
end

function setup!(s::ControlExp, model)
   info("SETTING UP NPG EXPERIMENT")

   dir          = "$(s.prefix)/$(s.expname)_MPPI"
   expdir       = makesavedir(dir, s.expfile, model.mjsys.name, s.meshfile)
   s.dir        = "$(expdir)"
   s.statefile  = "$(expdir)/data.jld"
   s.expresults = "$(expdir)/expmt.jld"
end

#function hook(s::ControlExp, model, i)
#   if i==1 || model.stocR[i] >= maximum(model.stocR[1:i-1])
#      info("\tSaving traj for experiment ", s.dir)
#      save_traj(model.mjsys, model.traj, s.statefile)
#      save(s.expresults, Dict(:stocR => model.stocR[1:i],
#                              :meanR => model.meanR[1:i],
#                              :evals => model.evalscore[1:i]))
#   end
#end
#
function cleanup!(s::ControlExp, model)
   save_traj(model.mjsys, model.traj, s.statefile) # save result of MPC anyway
   save(s.expresults, model.trace)
   info("Saved Experiment to ", s.dir)

   # email myself when done
   #run(`bash ./plot2html.sh $(scores[end]) $(expfile)`)
   #if cluster == 1
   #   println(workers())
   #   for w in workers()
   #      rmprocs(w)
   #   end
   #end
end

end


text:
plt = Observable{Any}(plot_seq(seq;darkmode))
ui = dom"div"(plt)
map!(p->plot_seq(p;darkmode), plt, seq_obs)
content!(w, "div#content", ui)

ext: jl


text:
function treshold_array_length_up(array, treshold)
    return size(array, 1) > treshold
end

function treshold_array_length_down(array, treshold)
    return size(array, 1) < treshold
end

function treshold_clique_nv_up(merge_kwargs)
    return merge_kwargs_2 -> treshold_array_length_up(merge_kwargs_2["clique"], merge_kwargs["treshold_percent"] * get_nv(merge_kwargs["clique"]))
end

function treshold_cliquetree_nv_up(merge_kwargs)
    return merge_kwargs_2 -> treshold_array_length_up(merge_kwargs_2["clique"], merge_kwargs["treshold_percent"] * get_nv(merge_kwargs["cliquetree"]))
end

function treshold_clique_ne_up(merge_kwargs)
    return merge_kwargs_2 -> treshold_array_length_up(merge_kwargs_2["clique"], merge_kwargs["treshold_percent"] * get_ne(merge_kwargs["clique"]))
end

function treshold_cliquetree_ne_up(merge_kwargs)
    return merge_kwargs_2 -> treshold_array_length_up(merge_kwargs_2["clique"], merge_kwargs["treshold_percent"] * get_ne(merge_kwargs["cliquetree"]))
end

function treshold_nb_lc_nv_up(merge_kwargs)
    return merge_kwargs_2 -> merge_kwargs_2["nb_lc"] > merge_kwargs["treshold_percent"] * get_nv(merge_kwargs["clique"])
end

function treshold_nb_lc_ne_up(merge_kwargs)
    return merge_kwargs_2 -> merge_kwargs_2["nb_lc"] > merge_kwargs["treshold_percent"] * get_ne(merge_kwargs["clique"])
end

const treshold_functions = Dict(
    "clique_nv_up" => treshold_clique_nv_up,
    "cliquetree_nv_up" => treshold_cliquetree_nv_up,
    "clique_ne_up" => treshold_clique_ne_up,
    "cliquetree_ne_up" => treshold_cliquetree_ne_up,
    "nb_lc_nv_up" => treshold_nb_lc_nv_up,
    "nb_lc_ne_up" => treshold_nb_lc_ne_up
)

max_stars_repo_name: charlyalizadeh/PowerFlowNetworks

max_issues_repo_name: charlyalizadeh/PowerFlowNetworks

max_forks_repo_name: charlyalizadeh/PowerFlowNetworks


text:
module TestExamples1D

using Test
using Trixi

include("test_trixi.jl")

# Start with a clean environment: remove Trixi output directory if it exists
outdir = "out"
isdir(outdir) && rm(outdir, recursive=true)

# pathof(Trixi) returns /path/to/Trixi/src/Trixi.jl, dirname gives the parent directory
const EXAMPLES_DIR = joinpath(pathof(Trixi) |> dirname |> dirname, "examples", "1d")

# Run basic tests
@testset "Examples 1D" begin
  @testset "parameters.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters.toml"),
            l2   = [5.581321238071356e-6],
            linf = [3.270561745361e-5])
  end
  @testset "parameters_amr.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_amr.toml"),
            l2   = [0.3540209654959832],
            linf = [0.9999905446337742])
  end
  @testset "parameters_amr_nonperiodic.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_amr_nonperiodic.toml"),
            l2   = [4.323673749626657e-6],
            linf = [3.239622040581043e-5])
  end
  @testset "parameters_nonperiodic.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_nonperiodic.toml"),
            l2   = [3.8103398423084437e-6, 1.6765350427819571e-6, 7.733123446821975e-6],
            linf = [1.2975101617795914e-5, 9.274867029507305e-6, 3.093686036947929e-5])
  end
  @testset "parameters_blast_wave_shockcapturing.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_blast_wave_shockcapturing.toml"),
            l2   = [0.21530530948120738, 0.2805965425286348, 0.5591770920395336],
            linf = [1.508388610723991, 1.5622010377944118, 2.035149673163788],
            n_steps_max=30)
  end
  @testset "parameters_ec.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_ec.toml"),
            l2   = [0.11948926375393912, 0.15554606230413676, 0.4466895989733186],
            linf = [0.2956500342985863, 0.28341906267346123, 1.0655211913235232])
  end
  @testset "parameters_ec.toml with extra_analysis_quantities" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_ec.toml"),
            l2   = [0.11948926375393912, 0.15554606230413676, 0.4466895989733186],
            linf = [0.2956500342985863, 0.28341906267346123, 1.0655211913235232],
            extra_analysis_quantities = ["l2_error_primitive", "linf_error_primitive", "conservation_error",
                                        "entropy", "energy_total", "energy_kinetic", "energy_internal", "residual"],
            save_analysis = true)
  end
  @testset "parameters_ec.toml with flux_shima_etal" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_ec.toml"),
            l2   = [0.06423364669980625, 0.08503530800170918, 0.2407844935006154],
            linf = [0.3212150514022287, 0.3070502221852398, 1.1446658347785068],
            n_steps_max=10,
            surface_flux = "flux_shima_etal",
            volume_flux = "flux_shima_etal")
  end
  @testset "parameters_ec.toml with flux_ranocha" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_ec.toml"),
            l2   = [0.06424564531300972, 0.08500942143178748, 0.2407606831620822],
            linf = [0.3215742010701772, 0.30592054370082256, 1.1453122141121064],
            n_steps_max=10,
            surface_flux = "flux_ranocha",
            volume_flux = "flux_ranocha")
  end
  @testset "parameters_ec.toml with flux_hll" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_ec.toml"),
            l2   = [0.0575654253650954, 0.0748264642646861, 0.21532027367350406],
            linf = [0.17289848639699257, 0.22023865765090028, 0.6349097763679086],
            n_steps_max=10,
            surface_flux = "flux_hll",
            volume_flux = "flux_hll")
  end
  @testset "parameters_sedov_blast_wave_shockcapturing.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_sedov_blast_wave_shockcapturing.toml"),
            l2   = [1.2500050612446159, 0.06878411345533555, 0.9447942342833009],
            linf = [2.9791692123401017, 0.1683336841958163, 2.665578807135144])
  end
  @testset "parameters_sedov_blast_wave_shockcapturing.toml with pressure" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_sedov_blast_wave_shockcapturing.toml"),
            l2   = [1.2974912081242604, 0.07965704393481755, 0.9453618260835944],
            linf = [3.1823155476320926, 0.21380426507857242, 2.6650734792251995],
            shock_indicator_variable = "pressure")
  end
  @testset "parameters_sedov_blast_wave_shockcapturing.toml with density" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_sedov_blast_wave_shockcapturing.toml"),
            l2   = [1.2797014548135697, 0.07077838776630381, 0.9457917493772532],
            linf = [3.117424382044245, 0.17775688760995997, 2.666854886766347],
            shock_indicator_variable = "density")
  end
  @testset "parameters_weak_blast_wave_shockcapturing.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_weak_blast_wave_shockcapturing.toml"),
            l2   = [0.1166063015913971, 0.15097998823740955, 0.4348178492249418],
            linf = [0.1872570975062362, 0.245999816865685, 0.7037939282238272])
  end
  @testset "parameters_source_terms.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_source_terms.toml"),
            l2   = [2.243591980786875e-8, 1.8007794300157155e-8, 7.701353735993148e-8],
            linf = [1.6169171668245497e-7, 1.4838378192827406e-7, 5.407841152660353e-7])
  end
  @testset "parameters_density_wave.toml" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_density_wave.toml"),
            l2   = [0.0011482554828446659, 0.00011482554838682677, 5.741277410494742e-6],
            linf = [0.004090978306810378, 0.0004090978313616156, 2.045489169688608e-5])
  end
  @testset "parameters_density_wave.toml with initial_conditions_density_pulse" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_density_wave.toml"),
            l2   = [0.003724642049410045, 0.0037246420494099837, 0.0018623210247047657],
            linf = [0.018538787219922304, 0.018538787219903874, 0.009269393609915078],
            initial_conditions = "initial_conditions_density_pulse")
  end
  @testset "parameters_density_wave.toml with initial_conditions_constant" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters_density_wave.toml"),
            l2   = [7.058654266604569e-16, 1.9703187362332313e-14, 7.286819681608443e-15],
            linf = [3.774758283725532e-15, 6.733502644351574e-14, 2.4868995751603507e-14],
            initial_conditions = "initial_conditions_constant")
  end
end

# Coverage test for all initial conditions
@testset "Tests for initial conditions" begin
  # Linear scalar advection
  @testset "parameters.toml with initial_conditions_sin" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters.toml"),
            l2   = [9.506162481381351e-5],
            linf = [0.00017492510098227054],
            n_steps_max = 1,
            initial_conditions = "initial_conditions_sin")
  end
  @testset "parameters.toml with initial_conditions_constant" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters.toml"),
            l2   = [6.120436421866528e-16],
            linf = [1.3322676295501878e-15],
            n_steps_max = 1,
            initial_conditions = "initial_conditions_constant")
  end
  @testset "parameters.toml with initial_conditions_linear_x" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters.toml"),
            l2   = [7.602419413667044e-17],
            linf = [2.220446049250313e-16],
            n_steps_max = 1,
            initial_conditions = "initial_conditions_linear_x",
            boundary_conditions = "boundary_conditions_linear_x",
            periodicity=false)
  end
  @testset "parameters.toml with initial_conditions_convergence_test" begin
    test_trixi_run(joinpath(EXAMPLES_DIR, "parameters.toml"),
            l2   = [2.9989673704826656e-6],
            linf = [5.841215237722963e-6],
            n_steps_max = 1,
            initial_conditions = "initial_conditions_convergence_test",
            boundary_conditions = "boundary_conditions_convergence_test",
            periodicity=false)
  end
end

# Clean up afterwards: delete Trixi output directory
@test_nowarn rm(outdir, recursive=true)

end #module


text:
# WARNING: This file was generated from fasta-parser.rl using ragel. Do not edit!
const fastaparser_start  = 6
const fastaparser_first_final  = 6
const fastaparser_error  = 0
const fastaparser_en_main  = 6
const _fastaparser_nfa_targs = Int8[ 0, 0 ,  ]
const _fastaparser_nfa_offsets = Int8[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,  ]
const _fastaparser_nfa_push_actions = Int8[ 0, 0 ,  ]
const _fastaparser_nfa_pop_trans = Int8[ 0, 0 ,  ]
Ragel.@generate_read!_function(
"fastaparser",
FASTAReader,
SeqRecord,
begin
begin
if ( p == pe  )
	@goto _test_eof

end
if ( cs  == 6 )
	@goto st_case_6
elseif ( cs  == 0 )
	@goto st_case_0
elseif ( cs  == 1 )
	@goto st_case_1
elseif ( cs  == 2 )
	@goto st_case_2
elseif ( cs  == 3 )
	@goto st_case_3
elseif ( cs  == 4 )
	@goto st_case_4
elseif ( cs  == 7 )
	@goto st_case_7
elseif ( cs  == 8 )
	@goto st_case_8
elseif ( cs  == 5 )
	@goto st_case_5
end
@goto st_out
@label ctr13
begin
state.linenum += 1
end
@goto st6
@label st6
p+= 1;
if 	( p == pe  )
	@goto _test_eof6

end
@label st_case_6
if ( (data[1+(p )]) == 10 )
	begin
	@goto ctr13

end
elseif 	( (data[1+(p )]) == 32 )
	begin
	@goto st6

end
elseif 	( (data[1+(p )]) == 62 )
	begin
	@goto st1

end
end
if 	( 9 <= (data[1+(p )])&& (data[1+(p )])<= 13  )
	begin
	@goto st6

end

end
begin
	@goto st0

end
@label st_case_0
@label st0
cs = 0;
@goto _out
@label ctr17
begin
if seqtype(typeof(output)) == ReferenceSequence
		output.seq = ReferenceSequence(input.seqbuf.buffer, 1, length(input.seqbuf))
		elseif seqtype(typeof(output)) == BioSequence
		ET = predict(input.seqbuf.buffer, 1, length(input.seqbuf))
		if 	ET == typeof(output.seq)
	resize!(output.seq, length(input.seqbuf))
	encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
else
	output.seq = ET(input.seqbuf.buffer, 1, length(input.seqbuf))
end
else
			resize!(output.seq, length(input.seqbuf))
	encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
end
empty!(input.seqbuf)
Ragel.@yield 1
end
@goto st1
@label ctr21
begin
	Ragel.@append_from_anchor!(input.seqbuf)
end
begin
if seqtype(typeof(output)) == ReferenceSequence
		output.seq = ReferenceSequence(input.seqbuf.buffer, 1, length(input.seqbuf))
		elseif seqtype(typeof(output)) == BioSequence
		ET = predict(input.seqbuf.buffer, 1, length(input.seqbuf))
		if 	ET == typeof(output.seq)
	resize!(output.seq, length(input.seqbuf))
	encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
else
	output.seq = ET(input.seqbuf.buffer, 1, length(input.seqbuf))
end
else
			resize!(output.seq, length(input.seqbuf))
	encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
end
empty!(input.seqbuf)
Ragel.@yield 1
end
@goto st1
@label st1
p+= 1;
if 	( p == pe  )
	@goto _test_eof1

end
@label st_case_1
if ( (data[1+(p )])== 32  )
	begin
	@goto st0

end

end
if 	( 9 <= (data[1+(p )])&& (data[1+(p )])<= 13  )
	begin
	@goto st0

end

end
begin
	@goto ctr0

end
@label ctr0
begin
Ragel.@anchor!
end
@goto st2
@label st2
p+= 1;
if ( p == pe  )
@goto _test_eof2

end
@label st_case_2
if ( (data[1+(p )]) == 10 )
begin
@goto ctr4

end
elseif ( (data[1+(p )]) == 12 )
begin
@goto st0

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr5

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto ctr3

end
end
if ( 9 <= (data[1+(p )])&& (data[1+(p )])<= 11  )
begin
@goto ctr3

end

end
begin
@goto st2

end
@label ctr3
begin
Ragel.@copy_from_anchor!(output.name)
end
@goto st3
@label st3
p+= 1;
if ( p == pe  )
@goto _test_eof3

end
@label st_case_3
if ( (data[1+(p )]) == 9 )
begin
@goto st3

end
elseif ( (data[1+(p )]) == 11 )
begin
@goto st3

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st3

end
end
begin
@goto ctr6

end
@label ctr6
begin
Ragel.@anchor!
end
@goto st4
@label st4
p+= 1;
if ( p == pe  )
@goto _test_eof4

end
@label st_case_4
if ( (data[1+(p )]) == 10 )
begin
@goto ctr9

end
elseif ( (data[1+(p )]) == 13 )
begin
@goto ctr10

end
end
begin
@goto st4

end
@label ctr4
begin
Ragel.@copy_from_anchor!(output.name)
end
begin
state.linenum += 1
end
@goto st7
@label ctr9
begin
Ragel.@copy_from_anchor!(output.metadata.description)
end
begin
state.linenum += 1
end
@goto st7
@label ctr11
begin
state.linenum += 1
end
@goto st7
@label ctr19
begin
Ragel.@append_from_anchor!(input.seqbuf)
end
@goto st7
@label ctr20
begin
Ragel.@append_from_anchor!(input.seqbuf)
end
begin
state.linenum += 1
end
@goto st7
@label st7
p+= 1;
if ( p == pe  )
@goto _test_eof7

end
@label st_case_7
if ( (data[1+(p )]) == 10 )
begin
@goto ctr11

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto st7

end
elseif ( (data[1+(p )]) == 62 )
begin
@goto ctr17

end
end
if ( 9 <= (data[1+(p )])&& (data[1+(p )])<= 13  )
begin
@goto st7

end

end
begin
@goto ctr15

end
@label ctr15
begin
Ragel.@anchor!
end
@goto st8
@label st8
p+= 1;
if ( p == pe  )
@goto _test_eof8

end
@label st_case_8
if ( (data[1+(p )]) == 10 )
begin
@goto ctr20

end
elseif ( (data[1+(p )]) == 32 )
begin
@goto ctr19

end
elseif ( (data[1+(p )]) == 62 )
begin
@goto ctr21

end
end
if ( 9 <= (data[1+(p )])&& (data[1+(p )])<= 13  )
begin
@goto ctr19

end

end
begin
@goto st8

end
@label ctr5
begin
Ragel.@copy_from_anchor!(output.name)
end
@goto st5
@label ctr10
begin
Ragel.@copy_from_anchor!(output.metadata.description)
end
@goto st5
@label st5
p+= 1;
if ( p == pe  )
@goto _test_eof5

end
@label st_case_5
if ( (data[1+(p )])== 10  )
begin
@goto ctr11

end

end
begin
@goto st0

end
@label st_out
@label _test_eof6
cs = 6;
@goto _test_eof
@label _test_eof1
cs = 1;
@goto _test_eof
@label _test_eof2
cs = 2;
@goto _test_eof
@label _test_eof3
cs = 3;
@goto _test_eof
@label _test_eof4
cs = 4;
@goto _test_eof
@label _test_eof7
cs = 7;
@goto _test_eof
@label _test_eof8
cs = 8;
@goto _test_eof
@label _test_eof5
cs = 5;
@goto _test_eof
@label _test_eof
begin

end
if ( p == eof  )
begin
if ( cs  == 7 )
begin
if seqtype(typeof(output)) == ReferenceSequence
output.seq = ReferenceSequence(input.seqbuf.buffer, 1, length(input.seqbuf))
elseif seqtype(typeof(output)) == BioSequence
ET = predict(input.seqbuf.buffer, 1, length(input.seqbuf))
if ET == typeof(output.seq)
resize!(output.seq, length(input.seqbuf))
encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
else
output.seq = ET(input.seqbuf.buffer, 1, length(input.seqbuf))
end
else
resize!(output.seq, length(input.seqbuf))
encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
end
empty!(input.seqbuf)
Ragel.@yield 0
end

break;
elseif ( cs  == 8 )
begin
Ragel.@append_from_anchor!(input.seqbuf)
end
begin
if seqtype(typeof(output)) == ReferenceSequence
output.seq = ReferenceSequence(input.seqbuf.buffer, 1, length(input.seqbuf))
elseif seqtype(typeof(output)) == BioSequence
ET = predict(input.seqbuf.buffer, 1, length(input.seqbuf))
if ET == typeof(output.seq)
resize!(output.seq, length(input.seqbuf))
encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
else
output.seq = ET(input.seqbuf.buffer, 1, length(input.seqbuf))
end
else
resize!(output.seq, length(input.seqbuf))
encode_copy!(output.seq, 1, input.seqbuf.buffer, 1, length(input.seqbuf))
end
empty!(input.seqbuf)
Ragel.@yield 0
end

break;
end

end

end
@label _out
begin

end

end
end)


text:
using Documenter, DiffEqOperators

makedocs(
    sitename="DiffEqOperators.jl",
    authors="Chris Rackauckas et al.",
    clean=true,
    doctest=false,
    modules=[DiffEqOperators],

    format=Documenter.HTML(assets=["assets/favicon.ico"],
                           canonical="https://diffeqoperators.sciml.ai/stable/"),

    pages=[
        "DiffEqOperators.jl: Linear operators for Scientific Machine Learning" => "index.md",
        "Examples" => "examples.md"
    ]
)

deploydocs(
    repo="github.com/SciML/DiffEqOperators.jl";
    push_preview=true
)


text:
using Logging
using Printf
using ArgParse

using Oceananigans
using Oceananigans.Units
using Oceananigans.Operators
using SeawaterPolynomials.TEOS10

using CUDA: @allowscalar
using Dates: Date, DateTime, Second, Millisecond, now, format
using Oceananigans: Center # Not sure why I need this.
using Oceananigans.Architectures: array_type
using Oceananigans.BuoyancyModels: BuoyancyField
using RealisticLESbrary: ∂z, ∂t

Logging.global_logger(OceananigansLogger())

# We want to time how long simulation setup takes.
t0 = time_ns()

# Remove this fix once https://github.com/CliMA/Oceananigans.jl/pull/1642
# makes it into a tagged release.

import Adapt
using Oceananigans.Forcings: DiscreteForcing

Adapt.adapt_structure(to, forcing::DiscreteForcing) =
    DiscreteForcing(Adapt.adapt(to, forcing.func),
                    Adapt.adapt(to, forcing.parameters))

include("load_sose_data.jl")
include("interpolate_sose_data.jl")
include("make_plots_and_movies.jl")
include("mixed_layer_depth.jl")

function parse_command_line_arguments()
    settings = ArgParseSettings()

    @add_arg_table! settings begin
        "--architecture"
            help = "Architecture to run on: CPU (default) or GPU"
            default = "CPU"
            arg_type = String

        "--size"
            help = "The number of grid points in x, y, and z."
            nargs = 3
            arg_type = Int

        "--extent"
            help = "The length of the x, y, and z dimensions."
            nargs = 3
            arg_type = Float64

        "--latitude"
            help = "Site latitude in degrees North (°N). Note that the SOSE dataset only goes up to -30°N."
            arg_type = Float64

        "--longitude"
            help = "Site longitude in degrees East (°E) between 0°E and 360°E."
            arg_type = Float64

        "--start"
            help = "Start date (format YYYY-mm-dd) between 2013-01-01 and 2018-01-01."
            arg_type = String

        "--end"
            help = "End date (format YYYY-mm-dd) between 2013-01-01 and 2018-01-01. Must be after the start date."
            arg_type = String

        "--sose-dir"
            help = "Directory containing the SOSE datasets."
            arg_type = String

        "--output-dir"
            help = "Directory to write output to. Defaults to the current working directory."
            default = pwd()
            arg_type = String

        "--no-surface-forcing"
            help = "Disable surface forcing of momentum, temperature, and salinity."
            action = :store_true

        "--no-background-state"
            help = "Disable the geostrophic background state and relaxation of temperature and salinity."
            action = :store_true

        "--no-animate"
            help = "Do not produce plots and animations after the simulation has finished."
            action = :store_true
    end

    return parse_args(settings)
end

@info "Parsing command line arguments..."

args = parse_command_line_arguments()

Nx, Ny, Nz = args["size"]
Lx, Ly, Lz = args["extent"]
lat = args["latitude"]
lon = args["longitude"]

start_date = Date(args["start"])
end_date = Date(args["end"])
validate_sose_dates(start_date, end_date)
day_offset, n_days = dates_to_offset(start_date, end_date)

arch_str2type = Dict("CPU" => CPU(), "GPU" => GPU())
arch = arch_str2type[args["architecture"]]

sose_dir = args["sose-dir"]
output_dir = abspath(args["output-dir"])
mkpath(output_dir)

apply_surface_forcing = !args["no-surface-forcing"]
apply_background_state = !args["no-background-state"]
make_animation = !args["no-animate"]

@info "Mapping grid..."

topology = (Periodic, Periodic, Bounded)
grid = RegularRectilinearGrid(topology=topology, size=(Nx, Ny, Nz), x=(0.0, Lx), y=(0.0, Ly), z=(-Lz, 0.0), halo=(3, 3, 3))

@info "Spinning up a tangent plane..."

coriolis = FPlane(latitude=lat)

@info "Surfacing a buoyancy model..."

buoyancy = SeawaterBuoyancy(equation_of_state=TEOS10EquationOfState())

@info "Summoning SOSE data and diagnosing geostrophic background state..."

# Don't pass an array_type to keep this data on the CPU until we interpolate it.
sose_datetimes, sose_grid, sose_surface_forcings, sose_profiles =
    load_sose_data(sose_dir, lat, lon, day_offset, n_days, grid, buoyancy, coriolis)

dates = convert.(Date, sose_datetimes)
start_date = dates[day_offset]
stop_date = dates[day_offset + n_days]
@info "Simulation start date: $start_date, stop date: $stop_date"

@info "Interpolating SOSE data..."

times = day * (0:n_days)
interpolated_surface_forcings = interpolate_surface_forcings(sose_surface_forcings, times, array_type=array_type(arch))
interpolated_profiles = interpolate_profiles(sose_profiles, sose_grid, grid, times, array_type=array_type(arch))

# We need a CPU version for set! and output writing (to avoid CUDA scalar operations).
interpolated_surface_forcings_cpu = interpolate_surface_forcings(sose_surface_forcings, times)
interpolated_profiles_cpu = interpolate_profiles(sose_profiles, sose_grid, grid, times)

@info "Plotting initial state for inspection..."

plot_initial_args = (sose_profiles, sose_grid, interpolated_profiles, grid, lat, lon, start_date)
@allowscalar plot_initial_state(plot_initial_args..., z_bottom=-Lz, filepath=joinpath(output_dir, "initial_state.png"))
@allowscalar plot_initial_state(plot_initial_args..., z_bottom=max(-10Lz, minimum(sose_grid.zF)), filepath=joinpath(output_dir, "initial_state_deep.png"))

@info "Forcing mean-flow interactions and relaxing tracers..."

## Set up forcing forcings to
##   1. include mean flow interactions in the momentum equation, and
##   2. weakly relax tracer fields to the base state.

# Fu′ = - w′∂z(U) - U∂x(u′) - V∂y(u′)
# FIXME? Do we need to use the flux form operator ∇·(Uũ′) instead of ũ′·∇U ?
@inline Fu′(i, j, k, grid, t, u′, v′, w′, p) =
    @inbounds - w′[i, j, k] * ∂z(p.ℑU, grid.zC[k], t) - p.ℑU(grid.zC[k], t) * ∂xᶜᵃᵃ(i, j, k, grid, u′) - p.ℑV(grid.zC[k], t) * ∂yᵃᶜᵃ(i, j, k, grid, u′)

# Fv′ = - w′∂z(V) - U∂x(v′) - V∂y(v′)
@inline Fv′(i, j, k, grid, t, u′, v′, w′, p) =
    @inbounds - w′[i, j, k] * ∂z(p.ℑV, grid.zC[k], t) - p.ℑU(grid.zC[k], t) * ∂xᶜᵃᵃ(i, j, k, grid, v′) - p.ℑV(grid.zC[k], t) * ∂yᵃᶜᵃ(i, j, k, grid, v′)

# Fw′ = - U∂x(w′) - V∂y(w′)
@inline Fw′(i, j, k, grid, t, u′, v′, w′, p) =
    @inbounds - p.ℑU(grid.zC[k], t) * ∂xᶜᵃᵃ(i, j, k, grid, u′) - p.ℑV(grid.zC[k], t) * ∂yᵃᶜᵃ(i, j, k, grid, v′)

# Fθ′ = - ∂t(Θ) - U∂x(θ′) - V∂y(θ′) - w′∂z(Θ)
# FIXME? Do we need to include the ∂t(Θ) terms?
@inline Fθ′(i, j, k, grid, t, u′, v′, w′, T′, p) =
    @inbounds - p.ℑU(grid.zC[k], t) * ∂xᶠᵃᵃ(i, j, k, grid, T′) - p.ℑV(grid.zC[k], t) * ∂yᵃᶜᵃ(i, j, k, grid, T′) - w′[i, j, k] * ∂z(p.ℑΘ, grid.zC[k], t)

# Fs′ = - ∂t(S) - U∂x(s′) - V∂y(s′) - w′∂z(S)
@inline Fs′(i, j, k, grid, t, u′, v′, w′, S′, p) =
    @inbounds - p.ℑU(grid.zC[k], t) * ∂xᶠᵃᵃ(i, j, k, grid, S′) - p.ℑV(grid.zC[k], t) * ∂yᵃᶜᵃ(i, j, k, grid, S′) - w′[i, j, k] * ∂z(p.ℑS, grid.zC[k], t)

# Timescale for relaxation to large-scale solution.
week = 7days
μ = (T=1/week, S=1/week)

# FIXME: Should be μ(C - c̅) so I need to add horizontal averages to parameters.
@inline Fθ_μ(i, j, k, grid, t, T′, p) = @inbounds p.μ.T * (p.ℑΘ(grid.zC[k], t) - T′[i, j, k])
@inline FS_μ(i, j, k, grid, t, S′, p) = @inbounds p.μ.S * (p.ℑS(grid.zC[k], t) - S′[i, j, k])

@inline u_forcing_wrapper(i, j, k, grid, clock, fields, params) = Fu′(i, j, k, grid, clock.time, fields.u, fields.v, fields.w, params)
@inline v_forcing_wrapper(i, j, k, grid, clock, fields, params) = Fv′(i, j, k, grid, clock.time, fields.u, fields.v, fields.w, params)
@inline w_forcing_wrapper(i, j, k, grid, clock, fields, params) = Fw′(i, j, k, grid, clock.time, fields.u, fields.v, fields.w, params)
@inline T_forcing_wrapper(i, j, k, grid, clock, fields, params) = Fθ′(i, j, k, grid, clock.time, fields.u, fields.v, fields.w, fields.T, params) + Fθ_μ(i, j, k, grid, clock.time, fields.T, params)
@inline S_forcing_wrapper(i, j, k, grid, clock, fields, params) = Fs′(i, j, k, grid, clock.time, fields.u, fields.v, fields.w, fields.S, params) + FS_μ(i, j, k, grid, clock.time, fields.S, params)

ℑτx = interpolated_surface_forcings.τx
ℑτy = interpolated_surface_forcings.τy
ℑQθ = interpolated_surface_forcings.Qθ
ℑQs = interpolated_surface_forcings.Qs
 ℑU = interpolated_profiles.Ugeo
 ℑV = interpolated_profiles.Vgeo
 ℑΘ = interpolated_profiles.Θ
 ℑS = interpolated_profiles.S

# Only give each forcing function the parameters it needs to avoid an
# ERROR: CUDA error: a PTX JIT compilation failed
# due to kernel arguments taking up too much parameter space on the GPU.

forcings = (
    u = Forcing(u_forcing_wrapper, discrete_form=true, parameters=(; ℑU, ℑV)),
    v = Forcing(v_forcing_wrapper, discrete_form=true, parameters=(; ℑU, ℑV)),
    w = Forcing(w_forcing_wrapper, discrete_form=true, parameters=(; ℑU, ℑV)),
    T = Forcing(T_forcing_wrapper, discrete_form=true, parameters=(; ℑU, ℑV, ℑΘ, μ)),
    S = Forcing(S_forcing_wrapper, discrete_form=true, parameters=(; ℑU, ℑV, ℑS, μ))
)

@info "Enforcing boundary conditions..."

## Set up boundary conditions to
##   1. impose wind stresses at the ocean surface, and
##   2. impose heat and salt fluxes at the ocean surface.

# Physical constants.
const ρ₀ = 1027.0  # Density of seawater [kg/m³]
const cₚ = 4000.0  # Specific heat capacity of seawater at constant pressure [J/(kg·K)]

@inline wind_stress_x(x, y, t, p) =   p.ℑτx(t) / ρ₀
@inline wind_stress_y(x, y, t, p) =   p.ℑτy(t) / ρ₀
@inline     heat_flux(x, y, t, p) = - p.ℑQθ(t) / ρ₀ / cₚ
@inline     salt_flux(x, y, t, p) =   p.ℑQs(t) / ρ₀

u′_bcs = UVelocityBoundaryConditions(grid, top=FluxBoundaryCondition(wind_stress_x, parameters=(; ℑτx)))
v′_bcs = VVelocityBoundaryConditions(grid, top=FluxBoundaryCondition(wind_stress_y, parameters=(; ℑτy)))
θ′_bcs =    TracerBoundaryConditions(grid, top=FluxBoundaryCondition(heat_flux, parameters=(; ℑQθ)))
s′_bcs =    TracerBoundaryConditions(grid, top=FluxBoundaryCondition(salt_flux, parameters=(; ℑQs)))

boundary_conditions = (u=u′_bcs, v=v′_bcs, T=θ′_bcs, S=s′_bcs)

@info "Framing the model..."

model = IncompressibleModel(
           architecture = arch,
                   grid = grid,
            timestepper = :RungeKutta3,
              advection = arch isa CPU ? UpwindBiasedThirdOrder() : WENO5(),
                tracers = (:T, :S),
               buoyancy = buoyancy,
               coriolis = coriolis,
                closure = AnisotropicMinimumDissipation(),
    boundary_conditions = apply_surface_forcing ? boundary_conditions : NamedTuple(),
                forcing = apply_background_state ? forcings : NamedTuple()
)

@info "Initializing conditions..."

ε(μ) = μ * randn() # noise

U₀(x, y, z) = 0
V₀(x, y, z) = 0
W₀(x, y, z) = ε(1e-10)
Θ₀(x, y, z) = interpolated_profiles_cpu.Θ(z, 0)
S₀(x, y, z) = interpolated_profiles_cpu.S(z, 0)

Oceananigans.set!(model, u=U₀, v=V₀, w=W₀, T=Θ₀, S=S₀)

@info "Summoning the time step wizard..."

wizard = TimeStepWizard(
           cfl = 0.5,
            Δt = 1second,
    max_change = 1.1,
        min_Δt = 0.001second,
        max_Δt = 1minute
)

# CFL utilities for reporting stability criterions.
cfl = AdvectiveCFL(wizard)
dcfl = DiffusiveCFL(wizard)

@info "Saddling up progress messenger..."

mutable struct ProgressTicker
    interval_start_time :: Float64
end

function (ticker::ProgressTicker)(simulation)
    model = simulation.model
    p = simulation.parameters

    # Compute simulation progress
    i, t = model.clock.iteration, model.clock.time
    simulation_date_time = DateTime(p.start_date) + Millisecond(round(Int, 1000t))

    wall_time = (time_ns() - ticker.interval_start_time) * 1e-9
    progress = model.clock.time / simulation.stop_time
    ETA = (1 - progress) / progress * simulation.run_time
    ETA_datetime = now() + Second(round(Int, ETA))

    # Find maximum velocities.
    umax = maximum(abs, model.velocities.u)
    vmax = maximum(abs, model.velocities.v)
    wmax = maximum(abs, model.velocities.w)

    # Find tracer extrema
    Tmin = minimum(model.tracers.T)
    Tmax = maximum(model.tracers.T)
    Smin = minimum(model.tracers.S)
    Smax = maximum(model.tracers.S)

    # Find maximum ν and κ.
     νmax = maximum(model.diffusivities.νₑ)
    κTmax = maximum(model.diffusivities.κₑ.T)
    κSmax = maximum(model.diffusivities.κₑ.S)

    mld = p.mixed_layer_depth(model)

    @info @sprintf("[%06.2f%%] iteration: %d, simulation time: %s, mixed layer depth: %.2f m, CFL: %.2e, νCFL: %.2e, next Δt: %s",
                   100 * progress, i, simulation_date_time, mld, cfl(model), dcfl(model), prettytime(simulation.Δt.Δt))

    @info @sprintf("          ├── u⃗_max: (%.2e, %.2e, %.2e) m/s, T: (min=%.2f, max=%.2f) °C, S: (min=%.2f, max=%.2f) psu, νκ_max: (ν=%.2e, κT=%.2e, κS=%.2e)",
                   umax, vmax, wmax, Tmin, Tmax, Smin, Smax, νmax, κTmax, κSmax)

    @info @sprintf("          └── ETA: %s (%s), Δ(wall time): %s / iteration",
                   format(ETA_datetime, "yyyy-mm-dd HH:MM:SS"), prettytime(ETA), prettytime(wall_time / simulation.iteration_interval))

    ticker.interval_start_time = time_ns()

    return nothing
end

@info "Conjuring the simulation..."

simulation = Simulation(model,
                    Δt = wizard,
             stop_time = n_days * days,
    iteration_interval = 10,
              progress = ProgressTicker(time_ns()),
            parameters = (; start_date, end_date, mixed_layer_depth)
)

@info "Garnishing output writers..."

filepath_prefix = joinpath(output_dir, "lesbrary_latitude$(lat)_longitude$(lon)_$(start_date)_to_$(stop_date)")

global_attributes = Dict(
    "latitude" => lat,
    "longitude" => lon,
    "start_date" => string(start_date),
    "end_date" => string(end_date)
)

u, v, w, T, S = fields(model)
b = BuoyancyField(model)
fields_to_output = (; u, v, w, T, S, b)

simulation.output_writers[:fields] =
    NetCDFOutputWriter(model, fields_to_output, global_attributes = global_attributes,
                       schedule = TimeInterval(6hours),
                       filepath = filepath_prefix * "_fields.nc",
                           mode = "c")

simulation.output_writers[:surface] =
    NetCDFOutputWriter(model, fields_to_output, global_attributes = global_attributes,
                            schedule = TimeInterval(5minutes),
                            filepath = filepath_prefix * "_surface.nc",
                                mode = "c",
                        field_slicer = FieldSlicer(k=grid.Nz))

simulation.output_writers[:slice] =
    NetCDFOutputWriter(model, fields_to_output, global_attributes = global_attributes,
                            schedule = TimeInterval(5minutes),
                            filepath = filepath_prefix * "_slice.nc",
                                mode = "c",
                        field_slicer = FieldSlicer(i=1))

@info "Squeezing out statistics..."

profiles = (
    U = AveragedField(u, dims=(1, 2)),
    V = AveragedField(v, dims=(1, 2)),
    T = AveragedField(T, dims=(1, 2)),
    S = AveragedField(S, dims=(1, 2)),
    B = AveragedField(b, dims=(1, 2))
)

simulation.output_writers[:profiles] =
    NetCDFOutputWriter(model, profiles, global_attributes = global_attributes,
                       schedule = TimeInterval(5minutes),
                       filepath = filepath_prefix * "_profiles.nc",
                           mode = "c")

@info "Inscribing background state..."

large_scale_outputs = Dict(
    "τx" => model -> interpolated_surface_forcings_cpu.τx.(model.clock.time),
    "τy" => model -> interpolated_surface_forcings_cpu.τy.(model.clock.time),
    "QT" => model -> interpolated_surface_forcings_cpu.Qθ.(model.clock.time),
    "QS" => model -> interpolated_surface_forcings_cpu.Qs.(model.clock.time),
     "u" => model -> interpolated_profiles_cpu.U.(znodes(Center, model.grid)[:], model.clock.time),
     "v" => model -> interpolated_profiles_cpu.V.(znodes(Center, model.grid)[:], model.clock.time),
     "T" => model -> interpolated_profiles_cpu.Θ.(znodes(Center, model.grid)[:], model.clock.time),
     "S" => model -> interpolated_profiles_cpu.S.(znodes(Center, model.grid)[:], model.clock.time),
  "Ugeo" => model -> interpolated_profiles_cpu.Ugeo.(znodes(Center, model.grid)[:], model.clock.time),
  "Vgeo" => model -> interpolated_profiles_cpu.Vgeo.(znodes(Center, model.grid)[:], model.clock.time),
  "mld_SOSE" => model -> interpolated_surface_forcings_cpu.mld.(model.clock.time),
  "mld_LES"  => mixed_layer_depth
)

large_scale_dims = Dict(
      "τx" => (),
      "τy" => (),
      "QT" => (),
      "QS" => (),
       "u" => ("zC",),
       "v" => ("zC",),
       "T" => ("zC",),
       "S" => ("zC",),
    "∂ρ∂z" => ("zF",),
    "Ugeo" => ("zC",),
    "Vgeo" => ("zC",),
    "mld_SOSE" => (),
    "mld_LES"  => ()
)

simulation.output_writers[:large_scale] =
    NetCDFOutputWriter(model, large_scale_outputs, global_attributes = global_attributes,
                         schedule = TimeInterval(5minutes),
                         filepath = filepath_prefix * "_large_scale.nc",
                       dimensions = large_scale_dims,
                             mode = "c")

wave = raw"""
           _.====.._
         ,:._       ~-_
             `\        ~-_
               |          `.
             ,/             ~-_
..__-..__..-''                 ~~--..__...----... LESbrary.jl ..__..--
"""

fish = raw"""
o                      o                    o
  o                     o                   o
 o                     o                    o
o   .''''.            o   .''''.            o   .''''.
 o /O)    './|         o /O)    './|         o /O)    './|
   > ) \| .'\|           > ) \| .'\|           > ) \| .'\|
    `....`                `....`                `....`
      ` `                   ` `                   ` `

             o                      o                   o
            o                      o                    o
            o   .''''.            o   .''''.             o  .''''.
             o /O)    './|         o /O)    './|         o /O)    './|
               > ) \| .'\|           > ) \| .'\|           > ) \| .'\|
                `....`                `....`                `....`
                  ` `                   ` `                   ` `
"""

print(wave)
println()

@printf("                    arch : %s                       \n", typeof(arch))
@printf("                       N : %d, %d, %d               \n", grid.Nx, grid.Ny, grid.Nz)
@printf("                       L : %.3g, %.3g, %.3g (meters)\n", grid.Lx, grid.Ly, grid.Lz)
@printf("                       Δ : %.3g, %.3g, %.3g (meters)\n", grid.Δx, grid.Δy, grid.Δz)
@printf("                    φ, λ : %.2f°N, %.2f°E           \n", lat, lon)
@printf("                   start : %s                       \n", start_date)
@printf("                     end : %s                       \n", end_date)

println()

@printf("              output dir : %s\n", output_dir)
@printf("   apply surface forcing : %s\n", apply_surface_forcing)
@printf("  apply background state : %s\n", apply_background_state)
@printf("         make animations : %s\n", make_animation)

println()
print(fish)

t1 = time_ns()
t_setup = prettytime((t1 - t0) * 1e-9)
@info "Simulation setup took $t_setup."

@info "Teaching the simulation to run!..."

run!(simulation)

@info "Plotting stuff and making movies..."

if make_animation
    plot_surface_forcings(filepath_prefix)
    animate_fields(lat, lon, start_date, filepath_prefix)
    animate_profiles(lat, lon, start_date, filepath_prefix)
end


text:
# ---
# title: 1497. Check If Array Pairs Are Divisible by k
# id: problem1497
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Array, Math, Greedy
# link: <https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/description/>
# hidden: true
# ---
#
# Given an array of integers `arr` of even length `n` and an integer `k`.
#
# We want to divide the array into exactly `n / 2` pairs such that the sum of
# each pair is divisible by `k`.
#
# Return _True_ If you can find a way to do that or _False_ otherwise.
#
#
#
# **Example 1:**
#
#
#
#     Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
#     Output: true
#     Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
#
#
# **Example 2:**
#
#
#
#     Input: arr = [1,2,3,4,5,6], k = 7
#     Output: true
#     Explanation: Pairs are (1,6),(2,5) and(3,4).
#
#
# **Example 3:**
#
#
#
#     Input: arr = [1,2,3,4,5,6], k = 10
#     Output: false
#     Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
#
#
# **Example 4:**
#
#
#
#     Input: arr = [-10,10], k = 2
#     Output: true
#
#
# **Example 5:**
#
#
#
#     Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
#     Output: true
#
#
#
#
# **Constraints:**
#
#   * `arr.length == n`
#   * `1 <= n <= 10^5`
#   * `n` is even.
#   * `-10^9 <= arr[i] <= 10^9`
#   * `1 <= k <= 10^5`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
struct CircularVector{T}
    v::Vector{T}
    l::Int
    CircularVector{T}(l::Integer) where T = new(zeros(T, l), l)
end

function Base.getindex(V::CircularVector{T}, i::Int) where T
    return V.v[mod1(i, V.l)]
end

function Base.setindex!(V::CircularVector{T}, val::T, i::Int) where T
    V.v[mod1(i, V.l)] = val
end

Base.@kwdef mutable struct Options

    # Printing options
    log_verbose::Bool = false
    log_freq::Int = 100
    timer_verbose::Bool = false
    timer_file::Bool = false

    # time options
    time_limit::Float64 = 3600_00. #100 hours

    # Default tolerances
    tol_primal::Float64 = 1e-3
    tol_dual::Float64 = 1e-3
    tol_psd::Float64 = 1e-6
    tol_soc::Float64 = 1e-6

    # Bounds on beta (dual_step / primal_step) [larger bounds may lead to numerical inaccuracy]
    min_beta::Float64 = 1e-5
    max_beta::Float64 = 1e+5
    initial_beta::Float64 = 1.

    # Adaptive primal-dual steps parameters [adapt_decay above .7 may lead to slower convergence]
    initial_adapt_level::Float64 = .9
    adapt_decay::Float64 = .8
    adapt_window::Int64 = 50

    # PDHG parameters
    convergence_window::Int = 200
    convergence_check::Int = 50
    max_iter::Int = Int(1e+5)

    # Linesearch parameters
    max_linsearch_steps::Int = 2000
    delta::Float64 = .999
    initial_theta::Float64 = 1.
    linsearch_decay::Float64 = .9

    # Spectral decomposition parameters
    full_eig_decomp::Bool = false
    max_target_rank_krylov_eigs::Int = 16
    min_size_krylov_eigs::Int = 100
    warm_start_eig::Bool = true

    # Reduce rank [warning: heuristics]
    reduce_rank::Bool = false
    rank_slack::Int = 3

    # equilibration parameters
    equilibration::Bool = false
    equilibration_iters::Int = 100
    equilibration_lb::Float64 = -10.0
    equilibration_ub::Float64 = +10.0
    equilibration_limit::Float64 = 0.8
    equilibration_force::Bool = false

    # spectral norm [using exact norm via svds may result in nondeterministic behavior]
    approx_norm::Bool = true
end

function Options(args)
    options = Options()
    parse_args!(options, args)
    return options
end

function parse_args!(options, args)
    for i in args
        parse_arg!(options, i)
    end
    return nothing
end

function parse_arg!(options::Options, arg)
    fields = fieldnames(Options)
    name = arg[1]
    value = arg[2]
    if name in fields
        setfield!(options, name, value)
    end
    return nothing
end

mutable struct AffineSets
    n::Int  # Size of primal variables
    p::Int  # Number of linear equalities
    m::Int  # Number of linear inequalities
    extra::Int  # Number of adition linear equalities (for disjoint cones)
    A::SparseMatrixCSC{Float64,Int64}
    G::SparseMatrixCSC{Float64,Int64}
    b::Vector{Float64}
    h::Vector{Float64}
    c::Vector{Float64}
end

mutable struct SDPSet
    vec_i::Vector{Int}
    mat_i::Vector{Int}
    tri_len::Int
    sq_len::Int
    sq_side::Int
end

mutable struct SOCSet
    idx::Vector{Int}
    len::Int
end

mutable struct ConicSets
    sdpcone::Vector{SDPSet}
    socone::Vector{SOCSet}
end

struct CPResult
    status::Int
    status_string::String
    primal::Vector{Float64}
    dual_eq::Vector{Float64}
    dual_in::Vector{Float64}
    slack_eq::Vector{Float64}
    slack_in::Vector{Float64}
    primal_residual::Float64
    dual_residual::Float64
    objval::Float64
    dual_objval::Float64
    gap::Float64
    time::Float64
    final_rank::Int
end

mutable struct PrimalDual
    x::Vector{Float64}
    x_old::Vector{Float64}
    y::Vector{Float64}
    y_old::Vector{Float64}

    PrimalDual(aff::AffineSets) = new(
        zeros(aff.n), zeros(aff.n), zeros(aff.m+aff.p), zeros(aff.m+aff.p)
    )
end

mutable struct WarmStart
    x::Vector{Float64}
    y_eq::Vector{Float64}
    y_in::Vector{Float64}
end

mutable struct Residuals
    dual_gap::Float64
    prim_obj::Float64
    dual_obj::Float64
    equa_feasibility::Float64
    ineq_feasibility::Float64
    feasibility::Float64
    primal_residual::CircularVector{Float64}
    dual_residual::CircularVector{Float64}
    comb_residual::CircularVector{Float64}

    Residuals(window::Int) = new(
        .0, .0, .0, .0, .0, .0,
        CircularVector{Float64}(2*window),
        CircularVector{Float64}(2*window),
        CircularVector{Float64}(2*window)
    )
end

const ViewVector = SubArray#{Float64, 1, Vector{Float64}, Tuple{UnitRange{Int}}, true}
const ViewScalar = SubArray#{Float64, 1, Vector{Float64}, Tuple{Int}, true}

mutable struct AuxiliaryData
    m::Vector{Symmetric{Float64,Matrix{Float64}}}

    Mty::Vector{Float64}
    Mty_old::Vector{Float64}

    Mx::Vector{Float64}
    Mx_old::Vector{Float64}
    residual::Vector{Float64}

    y_half::Vector{Float64}
    y_temp::Vector{Float64}

    soc_v::Vector{ViewVector}
    soc_s::Vector{ViewScalar}

    function AuxiliaryData(aff::AffineSets, cones::ConicSets)
        Mx_old = zeros(aff.p+aff.m)
    new(
        [Symmetric(zeros(sdp.sq_side, sdp.sq_side), :U) for sdp in cones.sdpcone],
        zeros(aff.n), zeros(aff.n),
        zeros(aff.p+aff.m), Mx_old, zeros(aff.p+aff.m),
        zeros(aff.p+aff.m), zeros(aff.p+aff.m),
        ViewVector[], ViewScalar[]
)
    end
end

mutable struct Matrices
    M::SparseMatrixCSC{Float64,Int64}
    Mt::SparseMatrixCSC{Float64,Int64}
    c::Vector{Float64}

    Matrices(M, Mt, c) = new(M, Mt, c)
end

mutable struct Params
    current_rank::Vector{Int}
    target_rank::Vector{Int}
    rank_update::Int
    update_cont::Int
    min_eig::Vector{Float64}
    iter::Int
    stop_reason::Int
    stop_reason_string::String
    iteration::Int
    primal_step::Float64
    primal_step_old::Float64
    dual_step::Float64
    theta::Float64
    beta::Float64
    adapt_level::Float64
    window::Int
    time0::Float64
    norm_c::Float64
    norm_b::Float64
    norm_h::Float64
    sqrt2::Float64

    Params() = new()
end


text:
##################################################################################
# This file is part of StateSpaceEcon.jl
# BSD 3-Clause License
# Copyright (c) 2020-2022, Bank of Canada
# All rights reserved.
##################################################################################

using StateSpaceEcon
using TimeSeriesEcon
using ModelBaseEcon

@info "Loading Model examples. Might take some time to pre-compile."
@using_example E1
@using_example E2
@using_example E3
@using_example E3nl
@using_example E6
@using_example E7
@using_example E7A

using Test
using Suppressor

@testset "1dsolvers" begin
    # f(x) = (x-2)*(x-3) = a x^2 + b x + c with vals = [a, x, b, c]
    let f(v) = v[1] * v[2]^2 + v[3] * v[2] + v[4],
        fdf(v) = (f(v), [v[2]^2, v[1] * v[2] * 2 + v[3], v[2], 1.0]),
        vals = [1.0, NaN, -5.0, 6.0]

        vals[2] = 0.0
        @test StateSpaceEcon.SteadyStateSolver.newton1!(fdf, vals, 2; tol = eps(), maxiter = 8)
        @test vals ≈ [1.0, 2.0, -5.0, 6.0] atol = 1e3 * eps()

        vals[2] = 6.0
        @test StateSpaceEcon.SteadyStateSolver.newton1!(fdf, vals, 2; tol = eps(), maxiter = 8)
        @test vals ≈ [1.0, 3.0, -5.0, 6.0] atol = 1e3 * eps()

        vals[2] = 0.0
        @test StateSpaceEcon.SteadyStateSolver.bisect!(f, vals, 2, fdf(vals)[2][2]; tol = eps())
        @test vals ≈ [1.0, 2.0, -5.0, 6.0] atol = 1e3 * eps()

        vals[2] = 6.0
        @test StateSpaceEcon.SteadyStateSolver.bisect!(f, vals, 2, fdf(vals)[2][2]; tol = eps())
        @test vals ≈ [1.0, 3.0, -5.0, 6.0] atol = 1e3 * eps()
    end
end

@testset "Plans" begin
    m = E1.model
    p = Plan(m, 1:3)
    @test first(p.range) == 0U
    @test last(p.range) == 4U
    out = @capture_out print(p)
    @test length(split(out, '\n')) == 2
    @test p[1] == [:y_shk]
    @test p[1U] == [:y_shk]
    endogenize!(p, :y_shk, 1U)
    @test isempty(p[1U])
    endogenize!(p, :y_shk, 1U:3U)
    exogenize!(p, :y, 2U)
    exogenize!(p, :y, 4U)
    # make sure indexing with integers works as well
    @test p[0U] == p[1] == [:y_shk]
    @test p[1U] == p[2] == []
    @test p[2U] == p[3] == [:y]
    @test p[3U] == p[4] == []
    @test p[4U] == p[5] == [:y, :y_shk]
    out = @capture_out print(p)
    @test length(split(out, '\n')) == 6
    out = @capture_out print(IOContext(stdout, :displaysize => (7, 80)), p)
    @test length(split(out, '\n')) == 4
    @test length(split(out, '⋮')) == 2
    let p = Plan(m, 2000Q1:2020Q4)
        endogenize!(p, shocks(m), 2000Q1:2002Q4)
        @test isempty(p[2000Q1])
        out = @capture_out print(p)
        length(split(out, "\n")) == 4
    end
    let p = Plan(2000Q1:2010Q4, (a = 1, b = 2, c = 3), falses(44, 3))
        exogenize!(p, :a, p.range)
        exogenize!(p, :b, 2001Q1:2006Q1)
        exogenize!(p, :c, 2006Q1:2009Q4)

        pio = IOBuffer()
        exportplan(pio, p)
        seek(pio, 0)
        q = importplan(pio)
        @test p == q
    end

end

# include("simdatatests.jl")
include("sstests.jl")

@testset "misc" begin
    m = E3.model
    sim = m.maxlag .+ (1:10)
    p = Plan(m, sim)

    # random data
    d1 = zeroworkspace(m, p)
    d = zeroworkspace(m, p)
    for v in keys(d1)
        @test d[v] == d1[v]
    end
    for v in values(d)
        v .= rand(Float64, size(v))
    end

    @test workspace2array(d1, m.allvars) == zeroarray(m, p)
    @test workspace2array(d1, m.allvars) == rawdata(zerodata(m, p))

    @test size(workspace2array(d, [:pinf, :ygap])) == (length(p.range), 2)
    @test size(workspace2array(d, ["pinf", "ygap"])) == (length(p.range), 2)
    @test size(workspace2array(d, m.variables)) == (length(p.range), 3)
    a = workspace2array(d, m.allvars)
    @test size(a) == (length(p.range), 6)
    @test a == hcat((d[v] for v in m.allvars)...)

    # error variable missing from dictionary
    @test_throws KeyError workspace2array(d, [:pinf, :ygap, :nosuchvar])
    # error out of range
    @test_throws BoundsError workspace2array(d, [:pinf, :ygap], 10U:20U)

    # warning variables with different ranges
    d.wrong_var = TSeries(3U, rand(10))
    b = workspace2array(d, [:pinf, :wrong_var])
    @test size(b) == (10, 2)
    @test b[:, 1] == d.pinf[3U:12U].values
    @test b[:, 2] == d.wrong_var[3U:12U].values

    s = workspace2data(d, m.allvars)
    @test all(s .== a)

    sa = data2array(s)  # copy=false, so s and sa point to the same matrix
    @test all(sa .== s)
    s.pinf[3U:5U] = 3:5
    @test all(sa .== s)

    sd = data2workspace(s)
    @test Set(keys(sd)) == Set(colnames(s))

    as = array2data(a, m.allvars, p.range)
    @test all(as .== a)
    a[1, 2] = 2.5
    @test all(as .== a)
    as = array2data(a, m.allvars, first(p.range), copy = true)
    @test all(as .== a)
    a[1, 2] = 3.0
    @test !all(as .== a)
    as[1, 2] = 3.0
    @test all(as .== a)

    ad = array2workspace(a, m.allvars, first(p.range))
    @test length(ad) == size(a, 2)
    @test all(ad[v].values == a[:, i] for (i, v) in enumerate(m.allvars))
end

@testset "overlay" begin
    t1 = overlay(TSeries(3U, 3ones(2)), TSeries(1U, ones(6)))
    @test t1 == TSeries(1U, [1, 1, 3, 3, 1, 1])
    t1 = overlay(TSeries(4U, 5ones(5)), t1)
    @test t1 == TSeries(1U, [1, 1, 3, 5, 5, 5, 5, 5])
end

include("simtests.jl")
include("logsimtests.jl")

# include("shockdecomp.jl")

@testset "misc" begin
    io = IOBuffer()
    printmatrix(io, rand(3, 4))
    seekstart(io)
    @test length(readlines(io)) == 3
end


text:
using DFTK
using Test

include("testcases.jl")

@testset "Kernels" begin
    Ecut=2
    kgrid = [2, 2, 2]
    testcase = silicon
    ε = 1e-8

    spec = ElementPsp(testcase.atnum, psp=load_psp(testcase.psp))
    model = Model(testcase.lattice; atoms=[spec => testcase.positions],
                  terms=[PowerNonlinearity(1.2, 2.0),
                         Xc(:lda_xc_teter93),
                         Hartree()])
    basis = PlaneWaveBasis(model, Ecut; kgrid=kgrid)

    ρ0 = guess_density(basis)
    dρ = randn(size(ρ0.real))

    for term in basis.terms
        ρ_minus = from_real(basis, ρ0.real - ε * dρ)
        pot_minus = ene_ops(term, nothing, nothing; ρ=ρ_minus).ops[1].potential
        ρ_plus = from_real(basis, ρ0.real .+ ε * dρ)
        pot_plus = ene_ops(term, nothing, nothing; ρ=ρ_plus).ops[1].potential
        dV = (pot_plus - pot_minus) / (2ε)

        dV_apply = DFTK.apply_kernel(term, dρ; ρ=ρ0)
        ker = DFTK.compute_kernel(term; ρ=ρ0)
        dV_compute = reshape(ker * vec(dρ), size(dρ))
        @test norm(dV - dV_apply)   < 100ε
        @test norm(dV - dV_compute) < 100ε
    end
end


text:
##########
##########
# Set equations to track biomass in each population
##########
##########
# AUTHOR: Cole B. Brookson
# DATE OF CREATION: 2021-06-21
##########
##########

# set up =======================================================================

using DifferentialEquations, DelimitedFiles
include("./src/eqn_component_functions.jl")

all_species_lists = readdlm("./data/intermediate-files/species_lists_for_simulations.csv", ',', Any)
all_networks = readdlm("./data/intermediate-files/all_networks_for_simulations.csv", ',', Any)

organism_id_pos = 1
organism_type_pos = 2
body_size_pos = 3
lower_prey_limit_pos = 4
upper_prey_limit_pos = 5
habitat_midpoint_pos = 6
habitat_lower_limit_pos = 7
habitat_upper_limit_pos = 8
nutritional_value_pos = 9
biomass_pos = 10

# quick test
species_list = all_species_lists[all_species_lists[:,11] .== 1, 1:10]
network = all_networks[all_networks[:, 1] .== 1, 2:end]

x0 = Float64[]
for i in 1:size(species_list, 1)
    append!(x0, species_list[i, biomass_pos])
end

dx = zeros(50)
function biomass!(dx, x, p, t)
    for i in 1:size(species_list, 1)
        dx[i] = growth_rate(i, species_list, x) +
                biomass_gain(species_list, network, x, 2, i) -
                biomass_loss(species_list, network, x, 2, i) -
                mortality_change(i, x)
    end
end
first2 = [1,5000]
trans = collect(5001:5500)
long_term = collect(5501:100:15000)
times = append!([1, 5000], collect(5001:5500), collect(5501:100:15000))
tspan = (0.0, 9.9)
prob = ODEProblem(biomass!, x0, tspan)
sol2 = solve(prob)
plot(sol2)

x0 = Float64[]
x0 = x0[1:10]
function biomass!(dx, x, p, t)
    for i in 1:10
        dx[i] = x[i]*0.008290132474132671 +
                x[i]*0 -
                x[i]*1.1841009394500528e-5 -
                x[i]*0.0027366885494656884
    end
end

max_stars_repo_name: colebrookson/trait-based-rewiring

max_issues_repo_name: colebrookson/trait-based-rewiring

max_forks_repo_name: colebrookson/trait-based-rewiring


text:
module Switches

export Switch, Unknown, Optional

import Base: @pure, broadcast, promote_op

include("Switch.jl")
include("Optional.jl")

end # module


text:
"""
    struct Name
        particle::String
        last::String
        junior::String
        first::String
        middle::String
    end
Store a name with no ambiguities. For additional parts to define a name, please fill an issue or make a pull request.
"""
# Name type
struct Name
    particle::String
    last::String
    junior::String
    first::String
    middle::String
end
const Names = Vector{Name}

"""
    Name(str::String)
Decompose without ambiguities a name as `particle` (optional) `last`, `junior` (optional), `first` `middle` (optional) based on BibTeX possible input. As for BibTeX, the decomposition of a name in the form of `first` `last` is also possible, but ambiguities can occur.
"""
function Name(str)
    @assert !isempty(strip(str)) "Name must not be empty or consist of only whitespace"

    # split along commas, then along spaces
    subnames = map(split(str, ","; keepempty=false)) do aux
        return split(aux, r"[\n\r ]+"; keepempty=false)
    end

    # subnames containers
    first = ""
    middle = ""
    particle = ""
    last = ""
    junior = ""

    # mark for string parsing
    mark_in = 1
    mark_out = 0

    # BibTeX form 1: First Second von Last
    if length(subnames) == 1
        aux = subnames[1]
        mark_out = length(aux) - 1
        last = aux[end]
        if length(aux) > 1 && isuppercase(aux[1][1])
            first = aux[1]
            mark_in += 1
            for s in aux[2:(end - 1)]
                mark_in += 1
                islowercase(s[1]) && break
                middle *= " $s"
            end
            for s in reverse(aux[mark_in:mark_out])
                islowercase(s[1]) && break
                mark_out -= 1
                last = "$s " * last
            end
            particle = join(aux[mark_in:mark_out], " ")
        end

        # BibTeX form 2: von Last, First Second
    elseif length(subnames) == 2
        aux = subnames[1] # von Last
        mark_out = length(aux) - 1
        last = aux[end]
        for s in reverse(aux[1:mark_out])
            islowercase(s[1]) && break
            mark_out -= 1
            last = "$s " * last
        end
        particle = join(aux[1:mark_out], " ")
        aux = subnames[end]  # First Second
        first = aux[1]
        middle = join(aux[2:end], " ")

        # BibTeX form 3: von Last, Junior, First Second
    elseif length(subnames) == 3
        aux = subnames[1] # von Last
        mark_out = length(aux) - 1
        last = aux[end]
        for s in reverse(aux[1:mark_out])
            islowercase(s[1]) && break
            mark_out -= 1
            last = "$s " * last
        end
        particle = join(aux[1:mark_out], " ")
        aux = subnames[2]
        @assert length(aux) == 1 "malformed junior subname"
        junior = aux[1]
        aux = subnames[end]  # First Second
        first = aux[1]
        middle = join(aux[2:end], " ")

    else
        # TODO: become more strict here in the future? but beware, right
        # now this function sometimes gets called with an empty string
        #error("too many commas in name '$(str)'")
    end

    return Name(particle, last, junior, first, middle)
end

"""
    names(str::String)
Decompose into parts a list of names in BibTeX compatible format. That is names separated by `and`.
"""
names(str) = map(Name, split(strip(str), r"\s+and\s+"; keepempty=false))

"""
    struct Access
        doi::String
        howpublished::String
        url::String
    end
Store the online access of an entry as a String. Handles the fields `doi` and `url` and the `arXiv` entries. For additional fields or entries, please fill an issue or make a pull request.
"""
struct Access
    doi::String
    howpublished::String
    url::String
end

"""
    Access(fields::Fields)
Construct the online access information based on the entry fields.
"""
function Access(fields)
    doi = get_delete!(fields, "doi")
    howpublished = get_delete!(fields, "howpublished")
    url = fields["_type"] == "eprint" ? arxive_url(fields) : get_delete!(fields, "url")
    return Access(doi, howpublished, url)
end

"""
    struct Date
        day::String
        month::String
        year::String
    end
Store the date information as `day`, `month`, and `year`.
"""
struct Date
    day::String
    month::String
    year::String
end

"""
    Date(fields::Fields)
Construct the date information based on the entry fields.
"""
function Date(fields)
    day = get_delete!(fields, "day")
    month = get_delete!(fields, "month")
    year = get_delete!(fields, "year")
    return Date(day, month, year)
end

"""
    struct Eprint
        archive_prefix::String
        eprint::String
        primary_class::String
    end
Store the information related to arXiv eprint format.
"""
struct Eprint
    archive_prefix::String
    eprint::String
    primary_class::String
end

"""
    Eprint(fields::Fields)
Construct the eprint arXiv information based on the entry fields. Handle old and current arXiv format.
"""
function Eprint(fields)
    archive_prefix = get_delete!(fields, "archiveprefix")
    eprint = get_delete!(fields, "eprint")
    primary_class = get_delete!(fields, "primaryclass")
    return Eprint(archive_prefix, eprint, primary_class)
end

"""
    struct In
        address::String
        chapter::String
        edition::String
        institution::String
        journal::String
        number::String
        organization::String
        pages::String
        publisher::String
        school::String
        series::String
        volume::String
    end
Store all the information related to how an entry was published.
"""
struct In
    address::String
    chapter::String
    edition::String
    institution::String
    journal::String
    number::String
    organization::String
    pages::String
    publisher::String
    school::String
    series::String
    volume::String
end

"""
    In(fields::Fields)
Construct the information of how an entry was published based on its fields
"""
function In(fields)
    address = get_delete!(fields, "address")
    chapter = get_delete!(fields, "chapter")
    edition = get_delete!(fields, "edition")
    institution = get_delete!(fields, "institution")
    journal = get_delete!(fields, "journal")
    number = get_delete!(fields, "number")
    organization = get_delete!(fields, "organization")
    pages = get_delete!(fields, "pages")
    publisher = get_delete!(fields, "publisher")
    school = get_delete!(fields, "school")
    series = get_delete!(fields, "series")
    volume = get_delete!(fields, "volume")
    return In(
        address,
        chapter,
        edition,
        institution,
        journal,
        number,
        organization,
        pages,
        publisher,
        school,
        series,
        volume,
    )
end

"""
    struct Entry <: AbstractEntry
        access::Access
        authors::Names
        booktitle::String
        date::Date
        editors::Names
        eprint::Eprint
        id::String
        in::In
        fields::Dict{String,String}
        title::String
        type::String
    end
Generic Entry type. If some construction rules are required, it should be done beforehand. Check `bibtex.jl` as the example of rules implementation for BibTeX format.
"""
struct Entry <: AbstractEntry
    access::Access
    authors::Names
    booktitle::String
    date::Date
    editors::Names
    eprint::Eprint
    id::String
    in::In
    fields::Dict{String,String}
    title::String
    type::String
end

"""
    Entry(id::String, fields::Fields)
Construct an entry with a unique id and a list of `Fields`.
"""
function Entry(id, fields)
    # foreach((name, field) -> fields[name] = erase_spaces(field), fields)
    access = Access(fields)
    authors = names(get_delete!(fields, "author"))
    booktitle = get_delete!(fields, "booktitle")
    date = Date(fields)
    editors = names(get_delete!(fields, "editor"))
    eprint = Eprint(fields)
    in_ = In(fields)
    title = get_delete!(fields, "title")
    type = get_delete!(fields, "_type")
    return Entry(
        access, authors, booktitle, date, editors, eprint, id, in_, fields, title, type
    )
end

"""
    Base.isless(a::BibInternal.Date,b::BibInternal.Date)::Bool

Function to check for `a < b` on `BibInternal.Date` data types.

This function will throw an `ArgumentError` if the `year` can not parsed into
`Int`. If it is not possible to parse `month` or `day` to `Int` those entries
will be silently ignored for comparison.
This function will not check if the date fields are given in a correct format
all fields are parsed into and compared as `Int` (no checking if date format
is correct or valid!).
!!! danger "Note:"
    The silent ignoring of not parseable `month` or `day` fields will lead to
    misbehaviour if using comparators like `==` or `!==`!
"""
function Base.isless(a::BibInternal.Date, b::BibInternal.Date)
    numbers = "0123456789" # TODO: use a regexp

    empty_year = isempty(a.year) || isempty(b.year)
    year_format = !issubset(a.year, numbers) || !issubset(b.year, numbers)
    not_valid_year = empty_year || year_format
    not_valid_year && throw(ArgumentError("Unsupported year format!"))

    a_y = parse(Int, a.year)
    b_y = parse(Int, b.year)

    empty_month = isempty(a.month) || isempty(b.month)
    month_format = !issubset(a.month, numbers) || !issubset(b.month, numbers)
    not_valid_month = empty_month || month_format

    if !not_valid_month
        a_m = parse(Int, a.month)
        b_m = parse(Int, b.month)
    end

    empty_day = isempty(a.day) || isempty(b.day)
    day_format = !issubset(a.day, numbers) || !issubset(b.day, numbers)
    not_valid_day = empty_day || day_format

    if !not_valid_day
        a_d = parse(Int, a.day)
        b_d = parse(Int, b.day)
    end

    if a_y == b_y
        if not_valid_month
            return false
        else
            return a_m == b_m ? !not_valid_day && a_d < b_d : a_m < b_m
        end
    end

    return a_y < b_y
end

"""
    Base.isless(a::BibInternal.Name,b::BibInternal.Name)::Bool

Function to check for `a < b` on `BibInternal.Name` data types.

This function will check the fields `last`, `first` and `middle` in this order
of priority. The other fields are ignored for now.
The field comparison is done by string comparison no advanced alphabetizing
rules are used for now.
!!! danger "Note:"
    The silent ignoring of the other fields might lead to misbehaviour if using
    comparators like `==` or `!==`!
"""
function Base.isless(a::BibInternal.Name, b::BibInternal.Name)
    if a.last == b.last
        if a.first == b.first
            return a.middle == b.middle ? false : a.middle < b.middle
        else
            return a.first < b.first
        end
    end

    return a.last < b.last
end


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:3] <= 1)

                     @variable(m, -65.76627584345755 <= q <= 59.26265199263469)

                     add_NL_constraint(m, :(log(1 + exp(-0.4079491356153899 + -0.18134844314194787*log(1 + exp(0.2817697329190594 + 0.989386077401103*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.6068435500303653*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.8530798012021474*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.8376755183348754*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.6594644406874322*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.2976334456396539*log(1 + exp(-0.4984715860832294 + -0.6460783499544172*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.0952691245496573*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.5434919689873383*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.2400778955734424*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.904210133814042*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.11940205422195982*log(1 + exp(-0.9402956128299329 + 0.19522910845028774*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.5236489579886725*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.09802794343243137*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.5359271533353085*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.5362141752531211*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.6350558501595733*log(1 + exp(-0.842982128122256 + 0.6833459994096582*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.15560340828874075*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.5368387122163134*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.6086259049043772*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.5403730914454505*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.4683577877900529*log(1 + exp(0.6067063734003204 + 0.8661978259504042*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.06088102390312189*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.9836506901320718*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.7952476421961925*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.6703006410599177*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))))) + log(1 + exp(0.9379679817528435 + -0.4660824895766815*log(1 + exp(0.2817697329190594 + 0.989386077401103*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.6068435500303653*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.8530798012021474*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.8376755183348754*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.6594644406874322*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.32761179552569075*log(1 + exp(-0.4984715860832294 + -0.6460783499544172*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.0952691245496573*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.5434919689873383*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.2400778955734424*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.904210133814042*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.6880683972685175*log(1 + exp(-0.9402956128299329 + 0.19522910845028774*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.5236489579886725*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.09802794343243137*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.5359271533353085*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.5362141752531211*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.5888723964207281*log(1 + exp(-0.842982128122256 + 0.6833459994096582*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.15560340828874075*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.5368387122163134*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.6086259049043772*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.5403730914454505*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.05595383404471299*log(1 + exp(0.6067063734003204 + 0.8661978259504042*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.06088102390312189*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.9836506901320718*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.7952476421961925*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.6703006410599177*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))))) + log(1 + exp(-0.3048668135843893 + -0.3680078347752045*log(1 + exp(0.2817697329190594 + 0.989386077401103*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.6068435500303653*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.8530798012021474*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.8376755183348754*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.6594644406874322*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.09989706667818732*log(1 + exp(-0.4984715860832294 + -0.6460783499544172*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.0952691245496573*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.5434919689873383*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.2400778955734424*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.904210133814042*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.6733365176188579*log(1 + exp(-0.9402956128299329 + 0.19522910845028774*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.5236489579886725*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.09802794343243137*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.5359271533353085*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.5362141752531211*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.7967060490111804*log(1 + exp(-0.842982128122256 + 0.6833459994096582*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.15560340828874075*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.5368387122163134*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.6086259049043772*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.5403730914454505*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.8483184805894783*log(1 + exp(0.6067063734003204 + 0.8661978259504042*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.06088102390312189*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.9836506901320718*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.7952476421961925*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.6703006410599177*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))))) + log(1 + exp(-0.8260325513973243 + 0.9282935832138137*log(1 + exp(0.2817697329190594 + 0.989386077401103*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.6068435500303653*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.8530798012021474*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.8376755183348754*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.6594644406874322*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.5968467249691596*log(1 + exp(-0.4984715860832294 + -0.6460783499544172*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.0952691245496573*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.5434919689873383*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.2400778955734424*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.904210133814042*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.003449906971975558*log(1 + exp(-0.9402956128299329 + 0.19522910845028774*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.5236489579886725*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.09802794343243137*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.5359271533353085*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.5362141752531211*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.5427745947324003*log(1 + exp(-0.842982128122256 + 0.6833459994096582*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.15560340828874075*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.5368387122163134*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.6086259049043772*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.5403730914454505*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.4794292841893828*log(1 + exp(0.6067063734003204 + 0.8661978259504042*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.06088102390312189*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.9836506901320718*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.7952476421961925*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.6703006410599177*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))))) + log(1 + exp(-0.3442450542855955 + 0.3679171232252214*log(1 + exp(0.2817697329190594 + 0.989386077401103*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.6068435500303653*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.8530798012021474*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.8376755183348754*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.6594644406874322*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.4969759600474797*log(1 + exp(-0.4984715860832294 + -0.6460783499544172*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.0952691245496573*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.5434919689873383*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.2400778955734424*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.904210133814042*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.17345395101703964*log(1 + exp(-0.9402956128299329 + 0.19522910845028774*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.5236489579886725*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + -0.09802794343243137*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.5359271533353085*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + 0.5362141752531211*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + -0.24637355767613478*log(1 + exp(-0.842982128122256 + 0.6833459994096582*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + 0.15560340828874075*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.5368387122163134*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + -0.6086259049043772*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.5403730914454505*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))) + 0.4183638306902213*log(1 + exp(0.6067063734003204 + 0.8661978259504042*log(1 + exp(-0.7838782818766057 + 0.6083304932652234*$(x[1]) + 0.4982278286707449*$(x[2]) + -0.2123905230276213*$(x[3]))) + -0.06088102390312189*log(1 + exp(-0.6220948510874038 + -0.22981743777707297*$(x[1]) + 0.33188126395442463*$(x[2]) + -0.8264122617752747*$(x[3]))) + 0.9836506901320718*log(1 + exp(0.5453301275165048 + -0.2798145416678528*$(x[1]) + -0.9787415760841154*$(x[2]) + 0.5329097417839521*$(x[3]))) + 0.7952476421961925*log(1 + exp(-0.31934053056836653 + 0.3102265855539219*$(x[1]) + -0.9236015463563882*$(x[2]) + -0.5629164596540628*$(x[3]))) + -0.6703006410599177*log(1 + exp(0.17795541107351465 + 0.6245951080916892*$(x[1]) + -0.14381738742917527*$(x[2]) + 0.44898943772247746*$(x[3]))))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions