text:
using Test
using Dash
using JSON2
@testset "dev" begin
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

styles = (
    pre = (
        border = "thin lightgrey solid",
        overflowX = "scroll"
    ),
)

app = dash("Dash Layout", external_stylesheets=external_stylesheets)
app.layout = html_div() do
        dcc_graph(
            id = "basic-interactions",
            figure = (
                data = [
                    (
                        x = [1,2,3,4],
                        y = [4,1,3,5],
                        text = ["a", "b", "c", "d"],
                        customdata = ["c.a", "c.b", "c.c", "c.d"],
                        name = "Trace 1",
                        mode = "markers",
                        marker = (size = 12,)
                    ),
                    (
                        x = [1,2,3,4],
                        y = [9,4,1,4],
                        text = ["w", "x", "y", "z"],
                        customdata = ["c.w", "c.x", "c.y", "c.z"],
                        name = "Trace 2",
                        mode = "markers",
                        marker = (size = 12,)
                    )
                ],
                layout = (clickmode = "event+select",)
            )
        ),
        html_div(className="three columns") do
            dcc_markdown() do
                """**Hover Data**
                Mouse over values in the graph."""
            end,
            html_pre(id="hover-data", style=styles.pre)
        end,
        html_div(className="three columns") do
            dcc_markdown() do
                """**Click Data**
                Click on points in the graph."""
            end,
            html_pre(id="click-data", style=styles.pre)
        end,
        html_div(className="three columns") do
            dcc_markdown() do
                """**Selection Data**
                Choose the lasso or rectangle tool in the graph's menu
                bar and then select points in the graph.
                Note that if `layout.clickmode = 'event+select'`, selection data also
                accumulates (or un-accumulates) selected data if you hold down the shift
                button while clicking."""
            end,
            html_pre(id="selected-data", style=styles.pre)
        end,
        html_div(className="three columns") do
            dcc_markdown() do
                """**Zoom and Relayout Data**
                Click and drag on the graph to zoom or click on the zoom
                buttons in the graph's menu bar.
                Clicking on legend items will also fire
                this event."""
            end,
            html_pre(id="relayout-data", style=styles.pre)
        end
    end

function pretty_json(t)
    io = IOBuffer()
    JSON2.pretty(io, JSON2.write(t), offset = 2)
    return String(take!(io))
end

callback!(app, callid"""basic-interactions.hoverData => hover-data.children""") do hover_data
    pretty_json(hover_data)
end
callback!(app, callid"""basic-interactions.clickData => click-data.children""") do click_data
    pretty_json(click_data)
end
callback!(app, callid"""basic-interactions.selectedData => selected-data.children""") do selected_data
    pretty_json(selected_data)
end
callback!(app, callid"""basic-interactions.relayoutData => relayout-data.children""") do relayout_data
    pretty_json(relayout_data)
end

run_server(app, "0.0.0.0", 8080; debug=true)
end


text:
#
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons, Josef Kircher
# Licensed under the MIT license. See LICENSE file in the project root for details.
#

################################## INSTALLATION ###############################################
# (1) Enter Package Manager via     ]
# (2) Install FMI via               add FMI     or    add "https://github.com/ThummeTo/FMI.jl"
################################ END INSTALLATION #############################################

using FMI
import FMIZoo

# we use a FMU from the FMIZoo.jl
pathToFMU = FMIZoo.get_model_filename("SpringFrictionPendulum1D", "Dymola", "2022x")

# this is how you can quickly simulate a FMU
myFMU = fmiLoad(pathToFMU)
simData = fmiSimulate(myFMU, 0.0, 10.0; recordValues=["mass.s"])

# ... and plot it
using Plots
fmiPlot(simData)

fmiUnload(myFMU)

# this is how you can simulate a FMU with more possibilities
myFMU = fmiLoad(pathToFMU)
fmuComp = fmiInstantiate!(myFMU)
fmiSetupExperiment(fmuComp, 0.0, 10.0)
fmiEnterInitializationMode(fmuComp)
fmiExitInitializationMode(fmuComp)
dt = 0.1
ts = 0.0:dt:(10.0-dt)
for t in ts
    # set model inputs
    # ...

    fmiDoStep(fmuComp, dt)

    # get model outputs
    # ...
end
fmiTerminate(fmuComp)
fmiFreeInstance!(fmuComp)
fmiUnload(myFMU)

ext: jl


text:
using DelayDiffEq, Calculus, ForwardDiff
using LinearAlgebra, Test

# Hutchinson's equation
function f(du, u, h, p, t)
  du[1] = p[1] * u[1] * (1 - h(p, t - p[2])[1] / p[3])
  nothing
end

h(p, t) = [p[4]]

@testset "Gradient" begin
  function test(p)
    prob = DDEProblem(f, [p[5]], h, eltype(p).((0.0, 20.0)), copy(p);
                      constant_lags = [p[2]])
    sol = solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14)
    diff = @. sol[1, :] - 10 * exp(-sol.t)
    dot(diff, diff)
  end

  p = [1.0, 1.0, 1.0, 0.0, 1.0]
  findiff = Calculus.finite_difference(test, p)
  fordiff = @test_logs (:warn, r"^dt <= dtmin") ForwardDiff.gradient(test, p)

  @test_broken findiff ≈ fordiff
end

@testset "Jacobian" begin
  function test(p)
    prob = DDEProblem(f, [p[5]], h, eltype(p).((0.0, 20.0)), copy(p);
                      constant_lags = [p[2]])
    solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14).u[end]
  end

  p = [1.0, 1.0, 1.0, 0.0, 1.0]
  findiff = Calculus.finite_difference_jacobian(test, p)
  fordiff = @test_logs (:warn, r"^dt <= dtmin") ForwardDiff.jacobian(test, p)

  @test_broken findiff ≈ fordiff
end

@testset "Hessian" begin
  function test(p)
    prob = DDEProblem(f, [p[5]], h, eltype(p).((0.0, 20.0)), copy(p);
                      constant_lags = [p[2]])
    sol = solve(prob, MethodOfSteps(Tsit5()); abstol = 1e-14, reltol = 1e-14)
    diff = @. sol[1, :] - 10 * exp(-sol.t)
    dot(diff, diff)
  end

  p = [1.0, 1.0, 1.0, 0.0, 1.0]
  findiff = Calculus.finite_difference_hessian(test, p)
  fordiff = @test_logs (:warn, r"^dt <= dtmin") ForwardDiff.hessian(test, p)

  @test_broken findiff ≈ fordiff
end


text:
# ---
# title: 595. Big Countries
# id: problem595
# author: Tian Jun
# date: 2020-10-31
# difficulty: Easy
# categories:
# link: <https://leetcode.com/problems/big-countries/description/>
# hidden: true
# ---
#
# There is a table `World`
#
#
#
#     +-----------------+------------+------------+--------------+---------------+
#     | name            | continent  | area       | population   | gdp           |
#     +-----------------+------------+------------+--------------+---------------+
#     | Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
#     | Albania         | Europe     | 28748      | 2831741      | 12960000      |
#     | Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
#     | Andorra         | Europe     | 468        | 78115        | 3712000       |
#     | Angola          | Africa     | 1246700    | 20609294     | 100990000     |
#     +-----------------+------------+------------+--------------+---------------+
#
#
# A country is big if it has an area of bigger than 3 million square km or a
# population of more than 25 million.
#
# Write a SQL solution to output big countries' name, population and area.
#
# For example, according to the above table, we should output:
#
#
#
#     +--------------+-------------+--------------+
#     | name         | population  | area         |
#     +--------------+-------------+--------------+
#     | Afghanistan  | 25500100    | 652230       |
#     | Algeria      | 37100000    | 2381741      |
#     +--------------+-------------+--------------+
#
#
#
#
#
## @lc code=start
using LeetCode

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


text:
########################### Thermal Generation Models ######################################

abstract type AbstractThermalFormulation <: AbstractDeviceFormulation end

abstract type AbstractThermalDispatchFormulation <: AbstractThermalFormulation end

abstract type AbstractThermalUnitCommitment <: AbstractThermalFormulation end

struct ThermalBasicUnitCommitment <: AbstractThermalUnitCommitment end

struct ThermalStandardUnitCommitment <: AbstractThermalUnitCommitment end

struct ThermalDispatch <: AbstractThermalDispatchFormulation end

struct ThermalRampLimited <: AbstractThermalDispatchFormulation end

struct ThermalDispatchNoMin <: AbstractThermalDispatchFormulation end

########################### Active Dispatch Variables ######################################

"""
This function add the variables for power generation output to the model
"""
function activepower_variables!(canonical::Canonical,
                           devices::IS.FlattenIteratorWrapper{T}) where {T<:PSY.ThermalGen}

    add_variable(canonical,
                 devices,
                 Symbol("P_$(T)"),
                 false,
                 :nodal_balance_active;
                 ub_value = d -> d.tech.activepowerlimits.max,
                 lb_value = d -> d.tech.activepowerlimits.min,
                 init_value = d -> PSY.get_activepower(PSY.get_tech(d)))

    return

end

"""
This function add the variables for power generation output to the model
"""
function reactivepower_variables!(canonical::Canonical,
                           devices::IS.FlattenIteratorWrapper{T}) where {T<:PSY.ThermalGen}

    add_variable(canonical,
                 devices,
                 Symbol("Q_$(T)"),
                 false,
                 :nodal_balance_reactive;
                 ub_value = d -> d.tech.reactivepowerlimits.max,
                 lb_value = d -> d.tech.reactivepowerlimits.min,
                 init_value = d -> d.tech.reactivepower)

    return

end

"""
This function add the variables for power generation commitment to the model
"""
function commitment_variables!(canonical::Canonical,
                           devices::IS.FlattenIteratorWrapper{T}) where {T<:PSY.ThermalGen}

    time_steps = model_time_steps(canonical)
    var_names = [Symbol("ON_$(T)"), Symbol("START_$(T)"), Symbol("STOP_$(T)")]

    for v in var_names
        add_variable(canonical, devices, v, true)
    end

    return

end

"""
This function adds the active power limits of generators when there are no CommitmentVariables
"""
function activepower_constraints!(canonical::Canonical,
                                 devices::IS.FlattenIteratorWrapper{T},
                                 device_formulation::Type{D},
                                 system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                     D<:AbstractThermalDispatchFormulation,
                                                                     S<:PM.AbstractPowerModel}

    range_data = [(PSY.get_name(g),  PSY.get_activepowerlimits(PSY.get_tech(g))) for g in devices]

    device_range(canonical,
                 range_data,
                 Symbol("activerange_$(T)"),
                 Symbol("P_$(T)"))
    return

end

"""
This function adds the active power limits of generators when there are CommitmentVariables
"""
function activepower_constraints!(canonical::Canonical,
                                 devices::IS.FlattenIteratorWrapper{T},
                                 device_formulation::Type{D},
                                 system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                      D<:AbstractThermalFormulation,
                                                                      S<:PM.AbstractPowerModel}

    range_data = [(PSY.get_name(g),  PSY.get_activepowerlimits(PSY.get_tech(g))) for g in devices]
    device_semicontinuousrange(canonical,
                               range_data,
                               Symbol("activerange_$(T)"),
                               Symbol("P_$(T)"),
                               Symbol("ON_$(T)"))

    return

end

"""
This function adds the active power limits of generators when there are
    no CommitmentVariables
"""
function activepower_constraints!(canonical::Canonical,
                                  devices::IS.FlattenIteratorWrapper{T},
                                  device_formulation::Type{ThermalDispatchNoMin},
                                  system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                     S<:PM.AbstractPowerModel}

    range_data = [(PSY.get_name(g), (min = 0.0, max=( PSY.get_activepowerlimits(PSY.get_tech(g))).max)) for g in devices]
    var_key = Symbol("P_$(T)")
    variable = get_variable(canonical, var_key)

    # If the variable was a lower bound != 0, not removing the LB can cause infeasibilities
    for v in variable
        if JuMP.has_lower_bound(v)
            JuMP.set_lower_bound(v, 0.0)
        end
    end

    device_range(canonical,
                range_data,
                Symbol("activerange_$(T)"),
                Symbol("P_$(T)")
                )

    return

end

"""
This function adds the reactive  power limits of generators when there are CommitmentVariables
"""
function reactivepower_constraints!(canonical::Canonical,
                                   devices::IS.FlattenIteratorWrapper{T},
                                   device_formulation::Type{D},
                                   system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                       D<:AbstractThermalDispatchFormulation,
                                                                       S<:PM.AbstractPowerModel}

    range_data = [(PSY.get_name(g),  PSY.get_reactivepowerlimits(PSY.get_tech(g))) for g in devices]

    device_range(canonical,
                 range_data ,
                 Symbol("reactiverange_$(T)"),
                 Symbol("Q_$(T)"))

    return

end

"""
This function adds the reactive power limits of generators when there CommitmentVariables
"""
function reactivepower_constraints!(canonical::Canonical,
                                   devices::IS.FlattenIteratorWrapper{T},
                                   device_formulation::Type{D},
                                   system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                        D<:AbstractThermalFormulation,
                                                                        S<:PM.AbstractPowerModel}

    range_data = [(PSY.get_name(g),  PSY.get_reactivepowerlimits(PSY.get_tech(g))) for g in devices]

    device_semicontinuousrange(canonical,
                               range_data,
                               Symbol("reactiverange_$(T)"),
                               Symbol("Q_$(T)"),
                               Symbol("ON_$(T)"))

    return

end

### Constraints for Thermal Generation without commitment variables ####
"""
This function adds the Commitment Status constraint when there are CommitmentVariables
"""
function commitment_constraints!(canonical::Canonical,
                                 devices::IS.FlattenIteratorWrapper{T},
                                 device_formulation::Type{D},
                                 system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                                     D<:AbstractThermalFormulation,
                                                                     S<:PM.AbstractPowerModel}

    key = ICKey(DeviceStatus, T)

    if !(key in keys(canonical.initial_conditions))
        error("Initial status conditions not provided. This can lead to unwanted results")
    end

    device_commitment(canonical,
                     canonical.initial_conditions[key],
                     Symbol("commitment_$(T)"),
                     (Symbol("START_$(T)"),
                      Symbol("STOP_$(T)"),
                      Symbol("ON_$(T)"))
                      )

    return

end

########################## Make initial Conditions for a Model #############################
function initial_conditions!(canonical::Canonical,
                            devices::IS.FlattenIteratorWrapper{T},
                            device_formulation::Type{D}) where {T<:PSY.ThermalGen,
                                                                D<:AbstractThermalFormulation}

    status_init(canonical, devices)
    output_init(canonical, devices)
    duration_init(canonical, devices)

    return

end

function initial_conditions!(canonical::Canonical,
                            devices::IS.FlattenIteratorWrapper{T},
                            device_formulation::Type{D}) where {T<:PSY.ThermalGen,
                                                                D<:AbstractThermalDispatchFormulation}

    output_init(canonical, devices)

    return

end

########################### Ramp/Rate of Change constraints ################################
"""
This function gets the data for the generators
"""
function _get_data_for_rocc(initial_conditions::Vector{InitialCondition},
                            resolution::Dates.Period)

    if resolution > Dates.Minute(1)
        minutes_per_period = Dates.value(Dates.Minute(resolution))
    else
        minutes_per_period = Dates.value(Dates.Second(resolution))/60
    end

    lenght_devices = length(initial_conditions)
    ini_conds = Vector{InitialCondition}(undef, lenght_devices)
    ramp_params = Vector{UpDown}(undef, lenght_devices)
    minmax_params = Vector{MinMax}(undef, lenght_devices)

    idx = 0
    for ic in initial_conditions
        g = ic.device
        gen_tech = PSY.get_tech(g)
        name = PSY.get_name(g)
        non_binding_up = false
        non_binding_down = false
        ramplimits =  PSY.get_ramplimits(gen_tech)
        rating = PSY.get_rating(gen_tech)
        if !isnothing(ramplimits)
            p_lims = PSY.get_activepowerlimits(gen_tech)
            max_rate = abs(p_lims.min - p_lims.max)/minutes_per_period
            if (ramplimits.up*rating >= max_rate) & (ramplimits.down*rating >= max_rate)
                @info "Generator $(name) has a nonbinding ramp limits. Constraints Skipped"
                continue
            else
                idx += 1
            end
            ini_conds[idx] = ic
            ramp_params[idx] = (up = ramplimits.up*rating*minutes_per_period,
                                down = ramplimits.down*rating*minutes_per_period)
            minmax_params[idx] = p_lims
        end
    end

    if idx < lenght_devices
        deleteat!(ini_conds, idx+1:lenght_devices)
        deleteat!(ramp_params, idx+1:lenght_devices)
        deleteat!(minmax_params, idx+1:lenght_devices)
    end

    return ini_conds, ramp_params, minmax_params

end

"""
This function adds the ramping limits of generators when there are CommitmentVariables
"""
function ramp_constraints!(canonical::Canonical,
                           devices::IS.FlattenIteratorWrapper{T},
                           device_formulation::Type{D},
                           system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                    D<:AbstractThermalFormulation,
                                                    S<:PM.AbstractPowerModel}
    key = ICKey(DevicePower, T)

    if !(key in keys(canonical.initial_conditions))
        error("Initial Conditions for $(T) Rate of Change Constraints not in the model")
    end

    time_steps = model_time_steps(canonical)
    resolution = model_resolution(canonical)
    initial_conditions = get_initial_conditions(canonical, key)
    rate_data = _get_data_for_rocc(initial_conditions, resolution)
    ini_conds, ramp_params, minmax_params = _get_data_for_rocc(initial_conditions, resolution)

    if !isempty(ini_conds)
        # Here goes the reactive power ramp limits when versions for AC and DC are added
        device_mixedinteger_rateofchange(canonical,
                                         (ramp_params, minmax_params),
                                         ini_conds,
                                         Symbol("ramp_$(T)"),
                                        (Symbol("P_$(T)"),
                                         Symbol("START_$(T)"),
                                         Symbol("STOP_$(T)"))
                                        )
    else
        @warn "Data doesn't contain generators with ramp limits, consider adjusting your formulation"
    end

    return

end

function ramp_constraints!(canonical::Canonical,
                          devices::IS.FlattenIteratorWrapper{T},
                          device_formulation::Type{D},
                          system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                   D<:AbstractThermalDispatchFormulation,
                                                   S<:PM.AbstractPowerModel}

    key = ICKey(DevicePower, T)

    if !(key in keys(canonical.initial_conditions))
        error("Initial Conditions for $(T) Rate of Change Constraints not in the model")
    end

    time_steps = model_time_steps(canonical)
    resolution = model_resolution(canonical)
    initial_conditions = get_initial_conditions(canonical, key)
    rate_data = _get_data_for_rocc(initial_conditions, resolution)
    ini_conds, ramp_params, minmax_params = _get_data_for_rocc(initial_conditions, resolution)

    if !isempty(ini_conds)
        # Here goes the reactive power ramp limits when versions for AC and DC are added
        device_linear_rateofchange(canonical,
                                  ramp_params,
                                  ini_conds,
                                   Symbol("ramp_$(T)"),
                                   Symbol("P_$(T)"))
    else
        @warn "Data doesn't contain generators with ramp limits, consider adjusting your formulation"
    end

    return

end

########################### time duration constraints ######################################
"""
If the fraction of hours that a generator has a duration constraint is less than
the fraction of hours that a single time_step represents then it is not binding.
"""
function _get_data_for_tdc(initial_conditions_on::Vector{InitialCondition},
                           initial_conditions_off::Vector{InitialCondition},
                           resolution::Dates.Period)

    steps_per_hour = 60/Dates.value(Dates.Minute(resolution))
    fraction_of_hour = 1/steps_per_hour
    lenght_devices_on = length(initial_conditions_on)
    lenght_devices_off = length(initial_conditions_off)
    @assert lenght_devices_off == lenght_devices_on
    time_params = Vector{UpDown}(undef, lenght_devices_on)
    ini_conds = Matrix{InitialCondition}(undef, lenght_devices_on, 2)

    idx = 0
    for (ix, ic) in enumerate(initial_conditions_on)
        g = ic.device
        @assert g == initial_conditions_off[ix].device
        tech = PSY.get_tech(g)
        non_binding_up = false
        non_binding_down = false
        timelimits =  PSY.get_timelimits(tech)
        name = PSY.get_name(g)
        if !isnothing(timelimits)
            if (timelimits.up <= fraction_of_hour) & (timelimits.down <= fraction_of_hour)
                @info "Generator $(name) has a nonbinding time limits. Constraints Skipped"
            else
                idx += 1
            end
            ini_conds[idx, 1] = ic
            ini_conds[idx, 2] = initial_conditions_off[ix]
            up_val = round(timelimits.up * steps_per_hour, RoundUp)
            down_val = round(timelimits.down * steps_per_hour, RoundUp)
            time_params[idx] = time_params[idx] = (up = up_val, down = down_val)
        end
    end

    if idx < lenght_devices_on
        ini_conds = ini_conds[1:idx,:]
        deleteat!(time_params, idx+1:lenght_devices_on)
    end

    return ini_conds, time_params

end

function time_constraints!(canonical::Canonical,
                          devices::IS.FlattenIteratorWrapper{T},
                          device_formulation::Type{D},
                          system_formulation::Type{S}) where {T<:PSY.ThermalGen,
                                                   D<:AbstractThermalFormulation,
                                                   S<:PM.AbstractPowerModel}

    ic_keys = [ICKey(TimeDurationON, T), ICKey(TimeDurationOFF, T)]
    for key in ic_keys
        if !(key in keys(canonical.initial_conditions))
            error("Initial Conditions for $(T) Time Constraint not in the model")
        end
    end

    parameters = model_has_parameters(canonical)
    resolution = model_resolution(canonical)
    initial_conditions_on  = get_initial_conditions(canonical, ic_keys[1])
    initial_conditions_off = get_initial_conditions(canonical, ic_keys[2])
    ini_conds, time_params = _get_data_for_tdc(initial_conditions_on,
                                               initial_conditions_off,
                                               resolution)

    if !(isempty(ini_conds))
       if parameters
            device_duration_parameters(canonical,
                                time_params,
                                ini_conds,
                                Symbol("duration_$(T)"),
                                (Symbol("ON_$(T)"),
                                Symbol("START_$(T)"),
                                Symbol("STOP_$(T)"))
                                      )
        else
            device_duration_retrospective(canonical,
                                        time_params,
                                        ini_conds,
                                        Symbol("duration_$(T)"),
                                        (Symbol("ON_$(T)"),
                                        Symbol("START_$(T)"),
                                        Symbol("STOP_$(T)"))
                                        )
        end
    else
        @warn "Data doesn't contain generators with time-up/down limits, consider adjusting your formulation"
    end

    return

end

########################### Cost Function Calls#############################################

function cost_function(canonical::Canonical,
                       devices::IS.FlattenIteratorWrapper{T},
                       ::Type{D},
                       ::Type{S}) where {T<:PSY.ThermalGen,
                                         D<:AbstractThermalDispatchFormulation,
                                         S<:PM.AbstractPowerModel}

    add_to_cost(canonical,
                devices,
                Symbol("P_$(T)"),
                :variable)

    return

end

function cost_function(canonical::Canonical,
                       devices::IS.FlattenIteratorWrapper{T},
                       ::Type{D},
                       ::Type{S}) where {T<:PSY.ThermalGen,
                                         D<:AbstractThermalFormulation,
                                         S<:PM.AbstractPowerModel}

    #Variable Cost component
    add_to_cost(canonical, devices, Symbol("P_$(T)"), :variable)

    #Commitment Cost Components
    add_to_cost(canonical, devices, Symbol("START_$(T)"), :startup)
    add_to_cost(canonical, devices, Symbol("STOP_$(T)"), :shutdn)
    add_to_cost(canonical, devices, Symbol("ON_$(T)"), :fixed)

    return

end


text:
include("ImageData.jl")
include("Nifti.jl")
include("Shutter.jl")
include("ErrorMeasures.jl")
include("CoilSensitivity.jl")
include("Regridding.jl")


text:
abstract type AbstractNode{T} end

struct EmptyNode{T} <: AbstractNode{T} end
mutable struct Node{T} <: AbstractNode{T}
    value::T
    pred::AbstractNode{T}
    succ::AbstractNode{T}
end

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
import RecipesBase
function recipetest(lib::Polyhedra.Library)
    @testset "Error for 3D polyhedron" begin
        err = ErrorException("Plotting 3-dimensional polyhedron with Plots is not supported, use Makie or MeshCat.")
        v = convexhull(ones(3), zeros(3))
        p = polyhedron(v, lib)
        @test_throws err RecipesBase.apply_recipe(Dict{Symbol, Any}(), p)
    end
    @testset "Error for 1D polyhedron" begin
        err = ErrorException("Plotting 1-dimensional polyhedron with Plots is not supported.")
        h = HalfSpace([1], 1) ∩ HalfSpace([-1], 1)
        p = polyhedron(h, lib)
        @test_throws err RecipesBase.apply_recipe(Dict{Symbol, Any}(), p)
    end
    v = convexhull([0.0, 0.0], [1.0, 0.0], [0.0, 1.0])
    p = polyhedron(v)
    @test RecipesBase.apply_recipe(Dict{Symbol, Any}(), p)[1].args == ([0.0, 0.0, 1.0, 0.0],
                                                                       [0.0, 1.0, 0.0, 0.0])
    @testset "Error for unbounded polyhedron" begin
        err = ErrorException("Rays not supported yet in the 2D plotting recipe.")
        vr = convexhull(v, Ray([1.0, 1.0]))
        pr = polyhedron(vr, lib)
        @test_throws err RecipesBase.apply_recipe(Dict{Symbol, Any}(), pr)
        vl = convexhull(v, Line([1.0, 1.0]))
        pl = polyhedron(vl, lib)
        @test_throws err RecipesBase.apply_recipe(Dict{Symbol, Any}(), pl)
    end
    @testset "Error for empty polyhedron" begin
        err = ErrorException("Plotting empty polyhedron is not supported.")
        h = HalfSpace([1, 1], 0) ∩ HyperPlane([1, 1], 1)
        p = polyhedron(h, lib)
        @test_throws err RecipesBase.apply_recipe(Dict{Symbol, Any}(), p)
    end
end


text:
using StatsPlots

"""
    psp_slices(
        model,
        p_fun,
        parm_names,
        bounds,
        v_parm;
        v_range,
        sample,
        name_fun = x -> x,
        opt_set = (),
        kwargs...
    )

Returns a grid of scatter plots which represent slices of the parameter space at values of
a third value `v_parm`. The expected signiture for `model` is

    function model(parms::ComponentVector; p1=.3, p2=.2, kwargs...)
        main_model(; p1, p2, parms..., kwargs...)
    end

    function main_model(;p1, p2, p3, p4)
        return main_model(p1, p1, p2, p4)
    end

    function main_model(p1, p1, p2, p4)
        ...
    end

# Arguments

- `model`: a model function that returns predictions given a vector of parameters
- `p_fun`: a function that that evaluates the qualitative data pattern
- `parm_names`: a vector of symbols corresponding to parameter names
- `bounds`: a vector of tuples representing (lowerbound, upperbound) for each dimension in
the parameter space

# Keywords

- `v_parm`: the name (symbol) of the parameter which is varied to generate subplots
- `v_range`: the range of values over which `v_parm` is varied
- `name_fun x -> x`: a function that processes/formats the patterns. The default function is the
identiy function
- `sample`: a function in the form of `sample(bounds, parm_names)` which samples an initial point
- `opt_set=()`: a `NamedTuple` of settings to be based to `Options`
- `kwargs...`: optional keyword arguments for `model` and `p_fun`

"""
function psp_slices(
    model,
    p_fun,
    parm_names,
    bounds,
    v_parm;
    v_range,
    sample,
    name_fun = x->x,
    opt_set = (),
    kwargs...
    )
    plots = map(
        x -> psp_slice(
            model,
            p_fun,
            parm_names,
            bounds,
            v_parm,
            x;
            sample,
            name_fun,
            opt_set,
            kwargs...
        ),
        v_range
    )
    return plot(plots...)
end

function psp_slice(
    model,
    p_fun,
    parm_names,
    bounds,
    v_parm,
    v_val;
    sample,
    name_fun = x->x,
    opt_set = (),
    kwargs...
    )

    init_parms = map(_ -> sample(bounds, parm_names), 1:1)

    options = Options(;
        radius = .10,
        bounds,
        n_iters = 5_000,
        init_parms,
        opt_set...
    )

    results = find_partitions(
        model,
        p_fun,
        options;
        kwargs...,
        v_parm => v_val
    )

    df = DataFrame(results)

    transform!(
        df,
        :parms => identity => parm_names
    )

    transform!(df, :pattern => name_fun => :pattern_var)

    p = @df df scatter(
        cols(parm_names[1]),
        cols(parm_names[2]),
        group = :pattern_var,
        grid = false,
        legend = :outertopright,
        xaxis = string(parm_names[1]),
        yaxis = string(parm_names[2]),
        title = string(v_parm, " = ", round(v_val, digits=3)),
        titlefontsize = 10,
    )
    return p
end

max_stars_repo_name: itsdfish/ParameterSpacePartitions

max_forks_repo_name: itsdfish/ParameterSpacePartitions


text:
using SuffixArrays
using Base.Test

function test_suffix(args)
    for file in args
        T = open(readall,file)
        tic()
        SA = suffixsort(T)
        t = toq()
        println("Sorting '$file' took: $t")
        @test sufcheck(T,SA.index) == 0
    end
end

function sufcheck(T,SA)
    n = length(T)
    n == 0 && (println("Done."); return 0)
    n < 0 && (println("Invalid length $n"); return -1)
    C = zeros(Int,256)
    for i = 1:n
        if SA[i] < 0 || n <= SA[i]
            println("Out of range $n")
            println("SA[$i] = $(SA[i])")
            return -2
        end
    end
    for i = 2:n
        if T[SA[i-1]+1] > T[SA[i]+1]
            println("Suffixes in wrong order")
            println("T[SA[$(i-1)]+1] = $(T[SA[(i-1)]+1])")
            println("T[SA[$i]+1] = $(T[SA[i]+1])")
            return -3
        end
    end
    for i = 1:n
        C[T[i]+1] += 1
    end
    p = 0
    for i = 1:256
        t = C[i]
        C[i] = p
        p += t
    end
    q = C[T[n]+1]
    C[T[n]+1] += 1
    for i = 1:n
        p = SA[i]
        if 0 < p
            p -= 1
            c = T[p+1]
            t = C[c+1]
        else
            p = n-1
            c = T[p+1]
            t = q
        end
        if t < 0 || p != SA[t+1]
            println("Suffixes in wrong position")
            return -4
        end
        if t != q
            C[c+1] += 1
            if n <= C[c+1] || T[SA[C[c+1]+1]+1] != c
                C[c+1] = -1
            end
        end
    end
    println("Done.")
    return 0
end

function walkdir(dir,files)
    t = readdir(dir)
    for f in t
        f == ".git" && continue
        j = joinpath(dir,f)
        if isdir(j)
            append!(files,walkdir(j,files))
        else
            push!(files,j)
        end
    end
    return unique(files)
end

files = walkdir(Pkg.dir("SuffixArrays"),{})
test_suffix(files)


text:
@testset "mapobs" begin
    data = 1:10
    mdata = mapobs(-, data)
    @test getobs(mdata, 8) == -8

    mdata2 = mapobs((-, x -> 2x), data)
    @test getobs(mdata2, 8) == (-8, 16)

    nameddata = mapobs((x = sqrt, y = log), data)
    @test getobs(nameddata, 10) == (x = sqrt(10), y = log(10))
    @test getobs(nameddata.x, 10) == sqrt(10)
end

@testset "filterobs" begin
    data = 1:10
    fdata = filterobs(>(5), data)
    @test numobs(fdata) == 5
end

@testset "groupobs" begin
    data = -10:10
    datas = groupobs(>(0), data)
    @test length(datas) == 2
end

@testset "joinobs" begin
    data1, data2 = 1:10, 11:20
    jdata = joinobs(data1, data2)
    @test getobs(jdata, 15) == 15
end

@testset "shuffleobs" begin
    @test_throws DimensionMismatch shuffleobs((X, rand(149)))

    @testset "typestability" begin
        for var in vars
            @test typeof(@inferred(shuffleobs(var))) <: SubArray
        end
        for tup in tuples
            @test typeof(@inferred(shuffleobs(tup))) <: Tuple
        end
    end

    @testset "Array and SubArray" begin
        for var in vars
            @test size(shuffleobs(var)) == size(var)
        end
        # tests if all obs are still present and none duplicated
        @test sum(shuffleobs(Y1)) == 120
    end

    @testset "Tuple of Array and SubArray" begin
        for var in ((X,yv), (Xv,y), tuples...)
            @test_throws MethodError shuffleobs(var...)
            @test typeof(shuffleobs(var)) <: Tuple
            @test all(map(x->(typeof(x)<:SubArray), shuffleobs(var)))
            @test all(map(x->(numobs(x)===15), shuffleobs(var)))
        end
        # tests if all obs are still present and none duplicated
        # also tests that both paramter are shuffled identically
        x1, y1, z1 = shuffleobs((X1,Y1,X1))
        @test vec(sum(x1,dims=2)) == fill(120,10)
        @test vec(sum(z1,dims=2)) == fill(120,10)
        @test sum(y1) == 120
        @test all(x1' .== y1)
        @test all(z1' .== y1)
    end

    @testset "SparseArray" begin
        for var in (Xs, ys)
            @test typeof(shuffleobs(var)) <: SubArray
            @test numobs(shuffleobs(var)) == numobs(var)
        end
        # tests if all obs are still present and none duplicated
        @test vec(sum(getobs(shuffleobs(sparse(X1))),dims=2)) == fill(120,10)
        @test sum(getobs(shuffleobs(sparse(Y1)))) == 120
    end

    @testset "Tuple of SparseArray" begin
        for var in ((Xs,ys), (X,ys), (Xs,y), (Xs,Xs), (XX,X,ys))
            @test_throws MethodError shuffleobs(var...)
            @test typeof(shuffleobs(var)) <: Tuple
            @test numobs(shuffleobs(var)) == numobs(var)
        end
        # tests if all obs are still present and none duplicated
        # also tests that both paramter are shuffled identically
        x1, y1 = getobs(shuffleobs((sparse(X1),sparse(Y1))))
        @test vec(sum(x1,dims=2)) == fill(120,10)
        @test sum(y1) == 120
        @test all(x1' .== y1)
    end

    @testset "RNG" begin
        # tests reproducibility
        explicit_shuffle = shuffleobs(MersenneTwister(42), (X, y))
        @test explicit_shuffle == shuffleobs(MersenneTwister(42), (X, y))
    end

end


text:
# see readme file in tests/ for description of tests
# Claudia July 2015
# modified to using PhyloNetworks always, all test files have commented out
# the include(...) or the using PhyloNetworks part
# Claudia May 2016

using Test
using PhyloNetworks
using CSV # for reading files
using DataFrames
using Distributed # parallel in test_correctLik.jl and test_bootstrap.jl
using GLM # for coef, nobs, residuals etc.
using LinearAlgebra: norm, diag, logdet # LinearAlgebra.rotate! not brought into scope
using Random
using StaticArrays # for rate substitution matrices
using Statistics
using StatsBase # for aic etc., stderr
using BioSymbols

PhyloNetworks.setCHECKNET(true)

    ## readTopology
    getIndexEdge = PhyloNetworks.getIndexEdge
    getIndexNode = PhyloNetworks.getIndexNode
    Edge = PhyloNetworks.Edge
    Node = PhyloNetworks.Node
    setNode! = PhyloNetworks.setNode!
    ## calculateExpCF
    approxEq = PhyloNetworks.approxEq
    Quartet = PhyloNetworks.Quartet
    extractQuartet! = PhyloNetworks.extractQuartet!
    identifyQuartet! = PhyloNetworks.identifyQuartet!
    eliminateHybridization! = PhyloNetworks.eliminateHybridization!
    updateSplit! = PhyloNetworks.updateSplit!
    updateFormula! = PhyloNetworks.updateFormula!
    calculateExpCF! = PhyloNetworks.calculateExpCF!
    parameters! = PhyloNetworks.parameters!
    searchHybridNode = PhyloNetworks.searchHybridNode
    updateInCycle! = PhyloNetworks.updateInCycle!
    updateContainRoot! = PhyloNetworks.updateContainRoot!
    updateGammaz! = PhyloNetworks.updateGammaz!
    ## correctLik
    calculateExpCFAll! = PhyloNetworks.calculateExpCFAll!
    logPseudoLik = PhyloNetworks.logPseudoLik
    optTopRun1! = PhyloNetworks.optTopRun1!
    ## partition
    addHybridizationUpdate! = PhyloNetworks.addHybridizationUpdate!
    deleteHybridizationUpdate! = PhyloNetworks.deleteHybridizationUpdate!
    ## partition2
    writeTopologyLevel1 = PhyloNetworks.writeTopologyLevel1
    printPartitions = PhyloNetworks.printPartitions
    cleanBL! = PhyloNetworks.cleanBL!
    cleanAfterRead! = PhyloNetworks.cleanAfterRead!
    identifyInCycle = PhyloNetworks.identifyInCycle
    updatePartition! = PhyloNetworks.updatePartition!
    ## deleteHybridizationUpdate
    checkNet = PhyloNetworks.checkNet
    ## add2hyb
    hybridEdges = PhyloNetworks.hybridEdges
    ## optBLparts
    update! = PhyloNetworks.update!
    ## orderings_plot
    RootMismatch = PhyloNetworks.RootMismatch
    fuseedgesat! = PhyloNetworks.fuseedgesat!
    ## compareNetworks
    deletehybridedge! = PhyloNetworks.deletehybridedge!
    displayedNetworks! = PhyloNetworks.displayedNetworks!
    ## perfect data
    writeExpCF = PhyloNetworks.writeExpCF
    optBL! = PhyloNetworks.optBL!
    ## traitLikDiscrete
    P = PhyloNetworks.P
    P! = PhyloNetworks.P!

tests = [
    "test_auxillary.jl",
    "test_generatetopology.jl",
    "test_addHybrid.jl",
    "test_5taxon_readTopology.jl",
    "test_calculateExpCF.jl", "test_calculateExpCF2.jl",
    "test_hasEdge.jl", "test_parameters.jl", "test_correctLik.jl",
    "test_partition.jl", "test_partition2.jl", "test_deleteHybridizationUpdate.jl", "test_add2hyb.jl", "test_optBLparts.jl", "test_undirectedOtherNetworks.jl",
    "test_graph_components.jl",
    "test_manipulateNet.jl", "test_compareNetworks.jl",
    "test_badDiamII.jl",
    "test_multipleAlleles.jl",
    "test_bootstrap.jl",
    "test_perfectData.jl", # "test_readme.jl"
    "test_moves_semidirected.jl",
    "test_lm.jl", "test_lm_tree.jl", "test_traits.jl", "test_simulate.jl", "test_simulate_mbd.jl",
    "test_lm_withinspecies.jl",
    "test_parsimony.jl",
    "test_calibratePairwise.jl", "test_relaxed_reading.jl",
    "test_isMajor.jl", "test_interop.jl",
    "test_traitLikDiscrete.jl",
    "test_phyLiNCoptimization.jl",
    "test_readInputData.jl",
    "test_nj.jl",
]

@show PhyloNetworks.CHECKNET

anyerrors = false

for t in tests
    global anyerrors
    try
        @info "starting $t"
        include(t)
        println("\033[1m\033[32mPASSED\033[0m: $t")
    catch
        anyerrors = true
        println("\033[1m\033[31mFAILED\033[0m: $t")
    end
end
println("-------------------------------------")

if anyerrors
    throw("Tests failed")
else
    println("\033[1m\033[32mTests passed")
end


text:
# read the ECCOv4r4 lat-lon-cap (LLC) grid, return grid in γ

using Revise
using ECCOtour, MeshArrays, MITgcmTools

# other useful packages in Reemergence project
# using Statistics, PyPlot, Distributions, FFTW, LinearAlgebra, StatsBase

workdir = pwd()
push!(LOAD_PATH, workdir)
cd(workdir)

pth="../inputs/GRID_LLC90/"

http="https://github.com/gaelforget/GRID_LLC90"
!isdir(pth) ? run(`git clone $http $pth`) : nothing;

γ=GridSpec("LatLonCap",pth)

D=γ.read(γ.path*"Depth.data",MeshArray(γ,Float64))
tmp1=write(D); tmp2=read(tmp1,D)
show(D)

LAT=γ.read(γ.path*"YC.data",MeshArray(γ,Float64))
tmp1=write(LAT); tmp2=read(tmp1,LAT)
show(LAT)

LON=γ.read(γ.path*"XC.data",MeshArray(γ,Float64))
tmp1=write(LON); tmp2=read(tmp1,LON)
show(LON)


text:
# axis_attr_list = []
# for a in (Axis3D,)
#     attr = keys(default_theme(nothing, a))
#     push!(axis_attr_list, attr...)
# end
# axis_attr_list = string.(sort!(unique(axis_attr_list)))

# dict = default_theme(nothing, Axis3D)
# print_rec(STDOUT, dict)

const Axis3D_attr_desc = Dict(
    :frame => "See the detailed descriptions for `frame` attributes.",
    :names => "See the detailed descriptions for `names` attributes.",
    :scale => "NTuple{3,Float}. Specifies the scaling for the axes.",
    :showaxis => "NTuple{3,Bool}. Specifies whether to show the axes.",
    :showgrid => "NTuple{3,Bool}. Specifies whether to show the axis grids.",
    :showticks => "NTuple{3,Bool}. Specifies whether to show the axis ticks.",
    :ticks => "See the detailed descriptions for `ticks` attributes."
)

# frame
const Axis3D_attr_frame = Dict(
    :axiscolor => "Symbol or Colorant. Specifies the color of the axes. Can be a color symbol/string like :red, or a Colorant.",
    :linewidth => "Number. Width of the axes grid lines.",
    :linecolor => "Symbol or Colorant. Specifies the color of the grid lines. Can be a color symbol/string like :red, or a Colorant."
)

# names
const Axis3D_attr_names = Dict(
    :align => "`NTuple{3,(:pos, :pos)}`. Specify the text alignment for the axis labels, where `:pos` can be `:left`, `:center`, or `:right`.",
    :axisnames => "NTuple{3,String}. Specifies the axis labels.",
    :font => "NTuple{3,String}. Specifies the font for the axis labels, and can choose any font available on the system.",
    :gap => "Number. Specifies the gap (in pixels) between the axis labels and the axes themselves.",
    :rotation => "NTuple{3,Quaternion{Float32}}. Specifies the rotations for each axis's label, in radians.",
    :textcolor => "NTuple{3,Symbol or Colorant}. Specifies the color of the axes labels. Can be a color symbol/string like :red, or a Colorant.",
    :textsize => "NTuple{3,Int}. Font pointsize for axes labels."
)

# ticks
const Axis3D_attr_ticks = Dict(
    :align => "`NTuple{3,(:pos, :pos)}`. Specify the text alignment for the axis ticks, where `:pos` can be `:left`, `:center`, or `:right`.",
    :font => "NTuple{3,String}. Specifies the font for the axis ticks, and can choose any font available on the system.",
    :gap => "Number. Specifies the gap (in pixels) between the axis ticks and the axes themselves.",
    :rotation => "NTuple{3,Quaternion{Float32}}. Specifies the rotations for each axis's ticks, in radians.",
    :textcolor => "NTuple{3,Symbol or Colorant}. Specifies the color of the axes ticks. Can be a color symbol/string like :red, or a Colorant.",
    :textsize => "Integer. Font pointsize for text."
)

const Axis3D_attr_groups = Dict(
    :frame => Axis3D_attr_frame,
    :names => Axis3D_attr_names,
    :ticks => Axis3D_attr_ticks
)


text:
# This file was generated, do not modify it. # hide
mce = cross_entropy(ŷ, y[test]) |> mean
round(mce, digits=4)


text:
struct TreeNode
    action::Union{Tuple,Nothing}
    parent::Union{TreeNode,Nothing}
    pathcost::Integer
    state::Matrix
end

import Base.==
function ==(x::TreeNode, y::TreeNode)
    x.state == y.state
end

function addnode(action, parent, state)
    cost = parent.pathcost + 1
    newnode = TreeNode(action, parent, cost, state)
    return newnode
end

function createtree(state)
    newnode = TreeNode(nothing, nothing, 0, state)
    return newnode
end

function iscycle(node, cynum)
    count = 0
    previous = node

    while (count < cynum) && !isnothing(previous.parent)
        count += 1
        previous = previous.rparent

        if node.state == previous.state
            return true
        end
    end
    return false
end

function displaysolution(solvenode)
    while !isnothing(solvenode)
        println("Step $(solvenode.pathcost):")
        println("\t$(solvenode.state[1,:])")
        println("\t$(solvenode.state[2,:])")
        println("\t$(solvenode.state[3,:])")
        println("\tAction: $(solvenode.action)")
        solvenode = solvenode.parent
    end
    print(to)
end

max_stars_repo_name: brice-allen/npuz

max_issues_repo_name: brice-allen/npuz

max_forks_repo_name: brice-allen/npuz


text:
function sum_mesh(point1::Float64,point2::Float64)
    return point1 + point2
end

abstract type Mesh end

struct NoMesh <:Mesh end

struct UniformMesh <:Mesh
    num_cells::Int64
    simulation_length::Float64
    cell_length::Float64
    V_cell::Float64
    mesh_index::Array{Array{Int64,1}}
    function UniformMesh(box::Array{Float64,1},Lcell::Float64)
        num_cells=convert(Int64,div(box[1],Lcell))
        real_Lcell=box[1]/num_cells
        simulation_length=box[1]
        V_cell=real_Lcell*real_Lcell*real_Lcell
        mesh_index=Array{Array{Int64,1},1}(undef,0)
        for icell=0:num_cells-2
            for jcell=0:num_cells-2
                for kcell=0:num_cells-2
                    push!(mesh_index,[icell,jcell,kcell])
                end
            end
        end

        @info "Create UniformMesh with $(num_cells) Cells, Real Cell Length: $(real_Lcell)"
        new(num_cells::Int64,
            simulation_length::Float64,
            real_Lcell::Float64,
            V_cell::Float64,
            mesh_index::Array{Array{Int64,1}}
            )
    end
end

abstract type Field end

Base.broadcastable(x::Field) = Ref(x)

struct NoField <:Field end

struct CanonicalField <:Field

    χ::Array{Float64,2}
    κ::Float64
    τ::Int64
    Lcell::Float64
    mesh::Mesh
    local_field::Array{Array{Float64,1},1}
    global_field::Array{Array{Float64,1},1}
    field_gradient::Array{Array{Float64,1},1}
    particle2cell::Array{Array{Float64,1},1}
    cellindex::Array{Array{Int64,2},1}

    function CanonicalField(;χ::Array{Float64,2}=zeros(0,0),
                             κ::Float64=0.0,
                             τ::Int64=1,
                             Lcell::Float64=0.0,
                             mesh::Mesh=NoMesh())

        local_field=Array{Array{Float64,1},1}(undef,0)
        global_field=Array{Array{Float64,1},1}(undef,0)
        field_gradient=Array{Array{Float64,1},1}(undef,0)

        particle2cell=Array{Array{Float64,1},1}(undef,0)
        cellindex=Array{Array{Int64,2},1}(undef,0)

        new(χ::Array{Float64,2},
            κ::Float64,
            τ::Int64,
            Lcell::Float64,
            mesh::Mesh,
            local_field::Array{Array{Float64,1},1},
            global_field::Array{Array{Float64,1},1},
            field_gradient::Array{Array{Float64,1},1},
            particle2cell::Array{Array{Float64,1},1},
            cellindex::Array{Array{Int64,2},1})
    end
end

function init(::CanonicalField,input::Dict,configuration::Configuration)
    num_atomtypes=length(keys(input["Canonical field"]["χ"]))
    chi=zeros(num_atomtypes,num_atomtypes)
    for atomi in 1:num_atomtypes
        chi_i=convert(Array{Float64,1},input["Canonical field"]["χ"][string(atomi)])
        for atomj in 1:num_atomtypes
            chi[atomi,atomj]=chi_i[atomj]
        end
    end

    if "uniform mesh" in keys(input["Canonical field"])
        mesh=UniformMesh(configuration.box,input["Canonical field"]["Lcell"])
    end

    field=CanonicalField(χ=chi,
                         κ=input["Canonical field"]["κ"],
                         τ=input["Canonical field"]["update"],
                         Lcell=input["Canonical field"]["Lcell"],
                         mesh=mesh)

    for i in 1:num_atomtypes
        push!(field.local_field,zeros(mesh.num_cells*mesh.num_cells*mesh.num_cells))
        push!(field.global_field,zeros(mesh.num_cells*mesh.num_cells*mesh.num_cells))
        push!(field.field_gradient,zeros(mesh.num_cells*mesh.num_cells*mesh.num_cells*3))
    end
    return field
end


text:
using Glob
using WAV
using Plots
using SignalAnalysis
datalist = glob("**/*.wav", "./mini_speech_commands")

for i in datalist
    println(i)
    y, fs = wavread(i)
    test1 = tfd(y[:], SignalAnalysis.Spectrogram())
    splited = split(i, "/")
    label = splited[end-1]
    label2 = splited[end]
    # println(label*"#"*label2)
    # splitedag = split(label*"#"*label2, "#")
    # println(splitedag)
    png(
        plot(test1, legend = :none, ticks=false, xaxis =false, yaxis=false, margins = -1.0Plots.cm, size=(28,28)),
        "./datasetspectro/"* label * "#" * label2,
    )
    # break
end

max_stars_repo_name: ashwani-rathee/Sardor

max_issues_repo_name: ashwani-rathee/Sardor

max_forks_repo_name: ashwani-rathee/Sardor


text:
#####
##### Generic API
#####

export is_function_basis, dimension, domain, basis_at, linear_combination,
    InteriorGrid, EndpointGrid, grid, collocation_matrix

"""
$(TYPEDEF)

Abstract type for function families.

Not part of the API, just used internally for dispatch. See [`is_function_basis`](@ref).
"""
abstract type FunctionBasis end

Broadcast.broadcastable(basis::FunctionBasis) = Ref(basis)

"""
`$(FUNCTIONNAME)(F)`

`$(FUNCTIONNAME)(f::F)`

Test if the argument is a *function basis*, supporting the following interface:

- [`domain`](@ref) for querying the domain,

- [`dimension`](@ref) for the dimension,

- [`basis_at`](@ref) for function evaluation,

- [`grid`](@ref) to obtain collocation points.

[`linear_combination`](@ref) and [`collocation_matrix`](@ref) are also supported, building
on the above.

Can be used on both types (preferred) and values (for convenience).
"""
is_function_basis(T::Type) = false

is_function_basis(::Type{<:FunctionBasis}) = true

is_function_basis(f) = is_function_basis(typeof(f))

"""
`$(FUNCTIONNAME)(basis)`

The domain of a function basis. A tuple of numbers (of arbitrary type, but usually
`Float64`), or a tuple the latter.
"""
function domain end

"""
`$(FUNCTIONNAME)(basis)`

Return the dimension of `basis`, a positive `Int`.
"""
function dimension end

"""
`$(FUNCTIONNAME)(basis, x)`

Return an iterable with known element type and length (`Base.HasEltype()`,
`Base.HasLength()`) of basis functions in `basis` evaluated at `x`.

Methods are type stable.

!!! note
    Consequences are undefined when evaluating outside the domain.
"""
function basis_at end

"""
$(SIGNATURES)

Evaluate the linear combination of ``∑ θₖ⋅fₖ(x)`` of function basis ``f₁, …`` at `x`, for
the given order.

The length of `θ` should equal `dimension(θ)`.
"""
function linear_combination(basis, θ, x)
    mapreduce(*, +, θ, basis_at(basis, x))
end

# FIXME define a nice Base.show method
struct LinearCombination{B,T}
    basis::B
    θ::T
end

(l::LinearCombination)(x) = linear_combination(l.basis, l.θ, x)

"""
$(SIGNATURES)

Return a callable that calculates `linear_combination(basis, θ, x)` when called with `x`.
"""
linear_combination(basis, θ) = LinearCombination(basis, θ)

"""
$(TYPEDEF)

Abstract type for all grid specifications.
"""
abstract type AbstractGrid end

"""
$(TYPEDEF)

Grid with interior points (eg Gauss-Chebyshev).
"""
struct InteriorGrid <: AbstractGrid end

Base.show(io::IO, ::InteriorGrid) = print(io, "interior grid")

"""
$(TYPEDEF)

Grid that includes endpoints (eg Gauss-Lobatto).
"""
struct EndpointGrid <: AbstractGrid end

Base.show(io::IO, ::EndpointGrid) = print(io, "grid w/ endpoints")

"""
$(SIGNATURES)

Return a gridpoint for collocation, with `1 ≤ i ≤ dimension(basis)`.

`T` is used *as a hint* for the element type of grid coordinates, and defaults to `Float64`.
The actual type can be broadened as required. Methods are type stable.

!!! note
    Not all grids have this method defined, especially if it is impractical. See
    [`grid`](@ref), which is part of the API, this function isn't.
"""
gridpoint(basis, i) = gridpoint(Float64, basis, i)

"""
`$(FUNCTIONNAME)([T], basis)`

Return a grid recommended for collocation, with `dimension(basis)` elements.

`T` is used *as a hint* for the element type of grid coordinates, and defaults to `Float64`.
The actual type can be broadened as required. Methods are type stable.
"""
grid(basis) = grid(Float64, basis)

function grid(::Type{T}, basis) where {T<:Real}
    map(i -> gridpoint(T, basis, i), 1:dimension(basis))
end

"""
$(SIGNATURES)

Convenience function to obtain a collocation matrix at gridpoints `x`, which is assumed to
have a concrete `eltype`.

Methods are type stable.
"""
function collocation_matrix(basis, x)
    @argcheck isconcretetype(eltype(x))
    N = dimension(basis)
    C = Matrix{eltype(basis_at(basis, first(x)))}(undef, N, N)
    for i in 1:N
        foreach(((j, f),) -> C[i, j] = f, enumerate(basis_at(basis, x[i])))
    end
    C
end


text:
using Roots

f(x) = x^3 - x - 1
@show fzeros(f)
println()

@show fzero(f, [-2,2])
println()

@show fzero(f, 1.0)
println()

f(x) = exp(x) - x^4
fp(x) = exp(x) - 4x^3
fpp(x) = exp(x) - 12x^2
newton(f, fp, 8)        # 8.613169456441398
newton(f, 8)
halley(f, fp, fpp, 8)
halley(f, 8)
secant_method(f, 8, 8.5)


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

using Markdown
using InteractiveUtils

# ╔═╡ e0573e4e-0710-11eb-0c38-f54ceea8c90b
using Pkg, DrWatson

# ╔═╡ 9060d3be-0710-11eb-1686-196534333f23
begin
	@quickactivate "StatisticalRethinkingTuring"
	using Turing
	using StatisticalRethinking
end

# ╔═╡ 8d881ea4-0710-11eb-1eb7-2337f465fcff
md"## Clip-04-50-63t.jl"

# ╔═╡ 8fd7b794-0710-11eb-2b61-fd8f3fa5951f
begin
	df = CSV.read(sr_datadir("Howell1.csv"), DataFrame)
	df = df[df.age .>= 18, :]
	x̄ = mean(df.weight)
	x = range(minimum(df.weight), maximum(df.weight), length = 100)     # either
end;

# ╔═╡ b639f15a-0725-11eb-3b15-c35097e6acd5
@model function m4_3(weights, heights)
    a ~ Normal(178, 20)
    b ~ LogNormal(0, 1)
    σ ~ Uniform(0, 50)
    μ = a .+ b .* (weights .- x̄)
    heights ~ MvNormal(μ, σ)
end

# ╔═╡ dab57768-0778-11eb-3d4b-43d2eff46c65
begin
	m4_3t = m4_3(df.weight, df.height)
	Text(precis(m4_3t; io=String))
end

# ╔═╡ 183d7c0c-0779-11eb-087b-59e6cb72a2a2
begin
	quap4_3t = quap(m4_3t)
	Text(precis(quap4_3t; io=String))
end

# ╔═╡ 8f6a472e-0710-11eb-143d-6dfc45f27694
md"### snippets 4.50 - 4.52"

# ╔═╡ d463b7e4-070f-11eb-3b02-6f0bf21b511b
begin
	post = DataFrame(rand(quap4_3t.distr, 1_000)', quap4_3t.params)
	mu_at_50 = post.a + post.b * (50 - x̄)
end;

# ╔═╡ bb0877a2-0724-11eb-0ab5-3b1e14ee69ec
density(mu_at_50)

# ╔═╡ bb08bb74-0724-11eb-0e0e-fd511a507191
quantile(mu_at_50, (0.1, 0.9))

# ╔═╡ bb093fe6-0724-11eb-2a6a-2fc93e608313
md"### snippet 4.53 - 4.55"

# ╔═╡ 0613f12c-0725-11eb-15c7-abaa84650f38
begin
	weight_seq = 25:70

	# It's a little unfortunate that you have to write out the formula you have already put
	# into the model. I don't have a better way at the moment though.
	mu = post.a' .+ post.b' .* (weight_seq .- x̄)

	scatter(weight_seq, mu[:, 1:100], legend = false, c = 1, alpha = 0.1)

	# %% 4.56, 4.57
	mu_m = mean.(eachrow(mu))
	mu_lower = quantile.(eachrow(mu), 0.055)
	mu_upper = quantile.(eachrow(mu), 0.945)

	scatter(df.weight, df.height, ms = 3)
	plot!(weight_seq, mu_m, ribbon = (mu_m .- mu_lower, mu_upper .- mu_m))

	# or
	#mu = meanlowerupper(mu)
	#scatter(df.weight, df.height, ms = 3)
	#plot!(weight_seq, mu.mean, ribbon = (mu.mean .- mu.lower, mu.upper .- mu.mean))

end

# ╔═╡ 06146c9c-0725-11eb-078b-b7b2c199795a
md"### snippets 4.59 - 4.61"

# ╔═╡ bb1a7ca4-0724-11eb-2259-c34225bb22f3
begin
	mu1 = meanlowerupper(mu)
	# This isn't really pretty either. I'm not sure how to put this into a function since
	# there isn't a way to know how to create `predict_model` from `height`.
	chn = Chains(Array(post), ["a", "b", "σ"])
	predict_model = m4_3(weight_seq, missing)
	sim1 = predict(predict_model, chn)
	sim1 = meanlowerupper(Array(sim1)')

	scatter(df.weight, df.height, ms = 3, legend = false)
	plot!(weight_seq, mu1.mean, ribbon = (mu1.mean .- mu1.lower, mu1.upper .- mu1.mean))
	plot!(weight_seq, sim1.lower, fillrange = sim1.upper, alpha = 0.3, linealpha = 0.0, c = 2)
end

# ╔═╡ bb1b2adc-0724-11eb-3b86-e972178eee8a
md"### snippet 4.62"

# ╔═╡ bb293b7c-0724-11eb-0a07-3f2bb565e951
begin
	sim2 = predict(predict_model, Chains(rand(quap4_3t.distr, 10_000)', ["a", "b", "σ"])) |> Array
	sim2 = meanlowerupper(sim2')

	scatter(df.weight, df.height, ms = 3, legend = false)
	plot!(weight_seq, mu1.mean, ribbon = (mu1.mean .- mu1.lower, mu1.upper .- mu1.mean))
	plot!(weight_seq, sim2.lower, fillrange = sim2.upper, alpha = 0.3, linealpha = 0.0, c = 2)

	# %% 4.63
	post2 = DataFrame(rand(quap4_3t.distr, 1_000)', quap4_3t.params)
	#weight_seq = 25:70
	normals = Normal.(post2.a' .+ post2.b' .* (weight_seq .- x̄), post2.σ')
	sim3 = rand.(normals)
	sim3 = meanlowerupper(sim3)

	scatter(df.weight, df.height, ms = 3, legend = false)
	plot!(weight_seq, mu1.mean, ribbon = (mu1.mean .- mu1.lower, mu1.upper .- mu1.mean))
	plot!(weight_seq, sim3.lower, fillrange = sim3.upper, alpha = 0.3, linealpha = 0.0, c = 2)
end

# ╔═╡ a0eead00-0724-11eb-0bda-2fce139eebef
md"## End of clip-04-50-63t.jl"

# ╔═╡ Cell order:
# ╠═8d881ea4-0710-11eb-1eb7-2337f465fcff
# ╠═e0573e4e-0710-11eb-0c38-f54ceea8c90b
# ╠═9060d3be-0710-11eb-1686-196534333f23
# ╠═8fd7b794-0710-11eb-2b61-fd8f3fa5951f
# ╠═b639f15a-0725-11eb-3b15-c35097e6acd5
# ╠═dab57768-0778-11eb-3d4b-43d2eff46c65
# ╠═183d7c0c-0779-11eb-087b-59e6cb72a2a2
# ╟─8f6a472e-0710-11eb-143d-6dfc45f27694
# ╠═d463b7e4-070f-11eb-3b02-6f0bf21b511b
# ╠═bb0877a2-0724-11eb-0ab5-3b1e14ee69ec
# ╠═bb08bb74-0724-11eb-0e0e-fd511a507191
# ╟─bb093fe6-0724-11eb-2a6a-2fc93e608313
# ╠═0613f12c-0725-11eb-15c7-abaa84650f38
# ╟─06146c9c-0725-11eb-078b-b7b2c199795a
# ╠═bb1a7ca4-0724-11eb-2259-c34225bb22f3
# ╟─bb1b2adc-0724-11eb-3b86-e972178eee8a
# ╠═bb293b7c-0724-11eb-0a07-3f2bb565e951
# ╟─a0eead00-0724-11eb-0bda-2fce139eebef


text:
# Input/output

function Base.show(io::IO, ::MIME"text/plain", r::T) where {T<:SeisRequest}
    print(io, T, ":\n  ")
    println(io, join(["$f = $(repr(getfield(r, f)))" for f in fieldnames(T)], "\n  "))
end

function Base.show(io::IO, r::T) where {T<:SeisRequest}
    print(io, T, "(")
    print(io, join(["$f=$(repr(getfield(r, f)))"
                    for f in fieldnames(T) if getfield(r, f) !== missing], ", "))
    print(io, ")")
end


text:
function factorial(x)
  if x ≤ 1
    return 1
  else
    return x * factorial(x - 1)
  end
end

v = factorial(big(9000))
s = string(v)

for c in s
  println(c)
end

max_stars_repo_name: catseye/Dipple

max_issues_repo_name: catseye/Dipple

max_forks_repo_name: catseye/Dipple


text:
#
# Copyright (c) 2021 Tobias Thummerer, Lars Mikelsons, Josef Kircher
# Licensed under the MIT license. See LICENSE file in the project root for details.
#

t_start = 0.0
t_stop = 8.0

# case 1: ME-FMU with state events

pathToFMU = joinpath(dirname(@__FILE__), "..", "model", ENV["EXPORTINGTOOL"], "SpringFrictionPendulum1D.fmu")

myFMU = fmiLoad(pathToFMU)

comp = fmiInstantiate!(myFMU; loggingOn=false)
@test comp != 0

# choose FMU or FMUComponent
fmuStruct = nothing
envFMUSTRUCT = ENV["FMUSTRUCT"]
if envFMUSTRUCT == "FMU"
    fmuStruct = myFMU
elseif envFMUSTRUCT == "FMUCOMPONENT"
    fmuStruct = comp
end
@assert fmuStruct != nothing "Unknown fmuStruct, environment variable `FMUSTRUCT` = `$envFMUSTRUCT`"

solution, _ = fmiSimulateME(fmuStruct, t_start, t_stop)
@test length(solution.u) > 0
@test length(solution.t) > 0

@test solution.t[1] == t_start
@test solution.t[end] == t_stop

# reference values from Simulation in Dymola2020x (Dassl)
@test solution.u[1] == [0.5, 0.0]
@test sum(abs.(solution.u[end] - [1.06736, -1.03552e-10])) < 0.1
fmiUnload(myFMU)

# case 2: ME-FMU with state and time events

if ENV["EXPORTINGTOOL"] == "Dymola/2020x"
    pathToFMU = joinpath(dirname(@__FILE__), "..", "model", ENV["EXPORTINGTOOL"], "SpringTimeFrictionPendulum1D.fmu")

    myFMU = fmiLoad(pathToFMU)

    comp = fmiInstantiate!(myFMU; loggingOn=false)
    @test comp != 0

    # choose FMU or FMUComponent
    fmuStruct = nothing
    envFMUSTRUCT = ENV["FMUSTRUCT"]
    if envFMUSTRUCT == "FMU"
        fmuStruct = myFMU
    elseif envFMUSTRUCT == "FMUCOMPONENT"
        fmuStruct = comp
    end
    @assert fmuStruct != nothing "Unknown fmuStruct, environment variable `FMUSTRUCT` = `$envFMUSTRUCT`"

    ### test without recording values

    solution, _ = fmiSimulateME(fmuStruct, t_start, t_stop)
    @test length(solution.u) > 0
    @test length(solution.t) > 0

    @test solution.t[1] == t_start
    @test solution.t[end] == t_stop

    # reference values from Simulation in Dymola2020x (Dassl)
    @test solution.u[1] == [0.5, 0.0]
    @test sum(abs.(solution.u[end] - [1.05444, 1e-10])) < 0.01

    ### test with recording values (variable step record values)

    solution, savedValues = fmiSimulateME(fmuStruct, t_start, t_stop; recordValues="mass.f")
    dataLength = length(solution.u)
    @test dataLength > 0
    @test length(solution.t) == dataLength
    @test length(savedValues.saveval) == dataLength
    @test length(savedValues.t) == dataLength

    @test solution.t[1] == t_start
    @test solution.t[end] == t_stop
    @test savedValues.t[1] == t_start
    @test savedValues.t[end] == t_stop

    # reference values from Simulation in Dymola2020x (Dassl)
    @test sum(abs.(solution.u[1] - [0.5, 0.0])) < 1e-4
    @test sum(abs.(solution.u[end] - [1.05444, 1e-10])) < 0.01
    @test abs(savedValues.saveval[1][1] - 0.75) < 1e-4
    @test sum(abs.(savedValues.saveval[end][1] - -0.54435 )) < 0.015

    ### test with recording values (fixed step record values)

    tData = t_start:0.1:t_stop
    solution, savedValues = fmiSimulateME(fmuStruct, t_start, t_stop; recordValues="mass.f", saveat=tData)
    @test length(solution.u) == length(tData)
    @test length(solution.t) == length(tData)
    @test length(savedValues.saveval) == length(tData)
    @test length(savedValues.t) == length(tData)

    @test solution.t[1] == t_start
    @test solution.t[end] == t_stop
    @test savedValues.t[1] == t_start
    @test savedValues.t[end] == t_stop

    # reference values from Simulation in Dymola2020x (Dassl)
    @test sum(abs.(solution.u[1] - [0.5, 0.0])) < 1e-4
    @test sum(abs.(solution.u[end] - [1.05444, 1e-10])) < 0.01
    @test abs(savedValues.saveval[1][1] - 0.75) < 1e-4
    @test sum(abs.(savedValues.saveval[end][1] - -0.54435 )) < 0.015

    fmiUnload(myFMU)
end

# case 3: ME-FMU without events, but with input signal

function extForce(t)
    [sin(t)]
end

if ENV["EXPORTINGTOOL"] == "Dymola/2020x"
    pathToFMU = joinpath(dirname(@__FILE__), "..", "model", ENV["EXPORTINGTOOL"], "SpringPendulumExtForce1D.fmu")

    myFMU = fmiLoad(pathToFMU)

    comp = fmiInstantiate!(myFMU; loggingOn=false)
    @test comp != 0

    # choose FMU or FMUComponent
    fmuStruct = nothing
    envFMUSTRUCT = ENV["FMUSTRUCT"]
    if envFMUSTRUCT == "FMU"
        fmuStruct = myFMU
    elseif envFMUSTRUCT == "FMUCOMPONENT"
        fmuStruct = comp
    end
    @assert fmuStruct != nothing "Unknown fmuStruct, environment variable `FMUSTRUCT` = `$envFMUSTRUCT`"

    solution = fmiSimulateME(fmuStruct, t_start, t_stop; inputValues=["extForce"], inputFunction=extForce, dtmax=0.001)
    @test length(solution.u) > 0
    @test length(solution.t) > 0

    @test solution.t[1] == t_start
    @test solution.t[end] == t_stop

    # reference values from Simulation in Dymola2020x (Dassl)
    @test solution.u[1] == [0.5, 0.0]
    @test sum(abs.(solution.u[end] - [0.613371, 0.188633])) < 0.01
    fmiUnload(myFMU)
end


text:
"""
---
Generate a time domain signal for a given multicarrier waveform. Input are the Time-Frequency matrix qamMat and the Waveform structure.
# --- Syntax
sigId	= genSig(qamMat,struc::Waveform)
# --- Input parameters
- qamMat  : Time frequency complex QAM matrix [Array{Complex{Float64}}]
- struc	  : Waveform structure
# --- Output parameters
- sigId	  : Time domain signal
# ---
# v 1.0 - Robin Gerzaguet.
"""
function genSig(qamMat,struc::StrucOFDM)
	return ofdmSigGen(qamMat,struc);
end
function genSig(qamMat,struc::StrucSCFDMA)
	return scfdmaSigGen(qamMat,struc);
end
function genSig(qamMat,struc::StrucUFOFDM)
	return ufofdmSigGen(qamMat,struc);
end
function genSig(qamMat,struc::StrucBFOFDM)
	return bfofdmSigGen(qamMat,struc);
end
function genSig(qamMat,struc::StrucWOLA)
	return wolaSigGen(qamMat,struc);
end
function genSig(qamMat,struc::StrucFBMC)
	return fbmcSigGen(qamMat,struc);
end

"""

Decode a time domain signal for a given multicarrier waveform and returns a T/F QAM constellation. Input are the compelx baseband signal  and the Waveform structure.
# --- Syntax
	qamDec	= decodeSig(signal,struc);
# --- Input parameters
- signal  : Time domain signal
- struc	  : Waveform structure
# --- Output parameters
- qamDec  : Time frequency complex QAM matrix [Array{Complex{Float64}}]
# ---
# v 1.0 - Robin Gerzaguet.
"""
function decodeSig(signal,struc::StrucOFDM)
	return ofdmSigDecode(signal,struc);
end
function decodeSig(signal,struc::StrucSCFDMA)
	return scfdmaSigDecode(signal,struc);
end
function decodeSig(signal,struc::StrucUFOFDM)
	return ufofdmSigDecode(signal,struc);
end
function decodeSig(signal,struc::StrucBFOFDM)
	return bfofdmSigDecode(signal,struc);
end
function decodeSig(signal,struc::StrucWOLA)
	return wolaSigDecode(signal,struc);
end
function decodeSig(signal,struc::StrucFBMC)
	return fbmcSigDecode(signal,struc);
end

"""
---
Returns the waveform name based on input type structure
# --- Syntax
 name = getWaveformName(struc)
# --- Input parameters
- struc	  : Waveform structure [Waveform]
# --- Output parameters
- name	  : String associated to waveform name
# ---
# v 1.0 - Robin Gerzaguet.
"""
function getWaveformName(s::Waveform)
	if typeof(s) == StrucOFDM
		name = "OFDM";
	elseif typeof(s) == StrucSCFDMA
		name = "SCFDMA";
	elseif typeof(s) == StrucUFOFDM
		name = "UFOFDM";
	elseif typeof(s) == StrucWOLA
		name = "WOLA";
	elseif typeof(s) == StrucFBMC
		name = "FBMC";
	elseif typeof(s) == StrucBFOFDM
		name = "BFOFDM";
	end
end

"""
---
Create a dictionnary of waveform configurations. To compare and use the same script for different waveform configuration, we propose to add a dictionnary to have a container that contains all waveform configuraton. The function is called with every desired waveform structure. The dictionnary as a key associated to the waveform name, and a field associated to the waveform structure. If the waveform is present several times (several configuration with same waveform type, for instance FBMC with different overlapping factor values), a counter index is added to the waveform key.
# --- Syntax
	dWav  = initWaveforms(x1,x2,...)
# --- Input parameters
- x		: Waveform structure [Waveform]
# --- Output parameters
- dWav	: Dictionnary of waveforms.
# ---
# v 1.0 - Robin Gerzaguet.
"""
function initWaveforms(x...)
	# --- Init dictionnary
	waveformDict = Dict{String,Waveform}();
	nbElem		 = nfields(x);
	#@show nbElem
	# --- Iterative extraction of waveform configuration
	for i = 1 : 1 : nbElem
		cnt = 1;
		# --- Getting name of configuration
		charW	= getWaveformName(x[i]);
		# --- Iterative earch of other config of same waveform
		tC	= charW;
		al  = collect(keys(waveformDict));
		for iN = 1 : 1 : length(waveformDict)
			# ---
			if al[iN] == tC
				tC = "$charW-$cnt";
				cnt+=1;
			end
		end
		# --- Pushing the configuration in the dictionnary
		waveformDict[tC] = x[i];
	end
	return waveformDict;
end

"""
---
Create a signal based on a waveform dictionnary and a desired configuration (i.e the key)
# --- Syntax
sigId	= genSig(qamMat,dWav,key)
# --- Input parameters
- qamMat  : Time frequency complex QAM matrix [Array{Complex{Float64}}]
- dWav	  : Waveform dictionnary (see initWaveforms)
- key	  : Desired waveform configuration
# --- Output parameters
- sigId	  : Time domain signal
# ---
# v 1.0 - Robin Gerzaguet.
"""
function genSig(qamMat::Array{Complex{Float64}},dict::Dict{String,Waveform},mod::String)
	return genSig(qamMat,dict[mod]);
end

"""
---
Create a signal based on a waveform dictionnary and a desired configuration (i.e the key)
# --- Syntax
sigId	= decodeSig(qamMat,dWav,key)
# --- Input parameters
- signal	  : Time domain signal
- qamMat  : Time frequency complex QAM matrix [Array{Complex{Float64}}]
- dWav	  : Waveform dictionnary (see initWaveforms)
- key	  : Desired waveform configuration
# --- Output parameters
# ---
# v 1.0 - Robin Gerzaguet.
"""
function decodeSig(signal,dict::Dict{String,Waveform},mod::String)
	return decodeSig(signal,dict[mod]);
end


text:
import Base.@kwdef
include("../src/Jus.jl")
include("../samples/src/example1.jl")
using .Jus
using .Jus: local_server, output, input
using HTTP
using Logging
using JSON3

test_equal(expc, actual) = expc == actual
test_equal(expc::Union{AbstractDict, NamedTuple}, actual::Union{AbstractDict, NamedTuple}) =
    test_equal_parts(expc, actual)
test_equal(expc::AbstractArray, actual::AbstractArray) = test_equal_parts(expc, actual)
test_equal(expc::Union{AbstractString, Symbol}, actual::Union{AbstractString, Symbol}) =
    string(expc) == string(actual)

str_keys(d) = Dict(map(k-> string(k) => k, [keys(d)...]))

function str_keys(a, b)
    k1 = str_keys(a)
    k2 = str_keys(b)
    keys(k1) != keys(k2) && return nothing
    Dict(k => [k1[k], k2[k]] for k in keys(k1))
end

function test_equal_parts(expc, actual)
    if Set(keys(expc)) != Set(keys(actual))
        @debug "DIFFERENT KEYS, $(keys(expc)) != $(keys(actual))"
        @debug "DIFFERENT KEYS for $(expc) and $(actual)"
    end
    strk = str_keys(expc, actual)
    strk === nothing && @debug "DIFFERENT KEYS"
    strk === nothing && return false
    for k in keys(strk)
        !test_equal(expc[strk[k][1]], actual[strk[k][2]]) && @debug "DIFFERENT VALUES"
        !test_equal(expc[strk[k][1]], actual[strk[k][2]]) && return false
    end
    true
end

expect(ws; expc...) = expect(ws, (; expc...)) do input
    @debug "COMPARING $(typeof((;expc...))) AND $(typeof(input))"
    result = test_equal((;expc...), input)
    if !result
        @debug "COMPARING $(repr((;expc...))) with $(repr(input))"
        @debug "ABSTRACT DICTS: $((;expc...) isa AbstractDict) $(input isa AbstractDict)"
        @debug "JSON: $(JSON3.write((;expc...))) == $(JSON3.write(input))"
    end
    result
end

expect(ws, command, result) = expect(ws; command, result)

expect(ws, command, result, update) = expect(ws; command, result, update)

function expect(test::Function, ws, expc)
    @debug "@@@ EXPECTING $(repr(expc))"
    result = input(ws)
    #@debug "@@@ @@@ TESTING $(repr(result))"
    if !test(result)
        throw(join(["Error, expected <", JSON3.write(expc), "> but got <", JSON3.write(result), ">\n"]))
    else
        @debug "- - @@ - -> GOT EXPECTED RESULT <$(expc)>"
    end
end

function assert_equal(expc, result)
    if !test_equal(expc, result)
        throw(join(["Error, expected <", JSON3.write(expc), "> but got <", JSON3.write(result), ">\n"]))
    else
        @debug "- - @@ - -> GOT EXPECTED RESULT <$(expc)>"
    end
end

assert_type(var::Var, type) = assert_type(var.value, type)
function assert_type(value, type)
    assert(value isa type, "Expected $(value) to be a $(type) but it is a $(typeof(value))")
end

assert(condition::Bool, msg, success = "") = assert(condition, ()-> msg, ()-> success)
function assert(condition::Bool, msg::Function, success::Function = ()-> "")
    if !condition
        throw(msg())
    else
        s = success()
        s != "" && @debug s
    end
end

function test1()
    config, task, ws = local_server("TEST")
    var(n) = config[ID("TEST", n)]
    output(ws, ["set", "-c", "@/0:create=PersonApp", "true"])
    expect(ws, :set, ["@/1"])
    assert_type(var(1), PersonApp)
    app = var(1).value
    output(ws, ["observe", "@/1"])
    expect(ws, :observe, [],
           (; Symbol("@/1") => (;
                                  set = (; ref = 1),
                                  metadata = (;
                                              type = "Main.PersonApp",
                                              create = :PersonApp,
                                              )
                                  ),
              ))
    output(ws, ["set", "-c", "@/1 new_person:path=new_person(),access=action", "true"])
    expect(ws, :set, ["@/2"],
           (;
              Symbol("@/2") =>
                  (;
                   set = "true",
                   metadata = (;
                               path = "new_person()",
                               access = "action",
                               type = "Core.String"
                               ),
                   )))
    output(ws, ["set", "-c", "@/1 namefield:path=namefield()", "true"])
    expect(ws, :set, ["@/3"],
           (;
            Symbol("@/3") =>
                (;
                 set = "",
                 metadata =
                     (;
                      path = "namefield()",
                      type = "Core.String",
                      ),
                 )))
    output(ws, ["set", "@/3", ""])
    expect(ws, :set, [],
           (;
            Symbol("@/3") =>
                (;
                 set = "",
                 ),
            ))
    output(ws, ["set", "-c", "@/1 address:path=addressfield", "true"])
    expect(ws, :set, ["@/4"],
           (;
            Symbol("@/4") =>
                (;
                 set = "",
                 metadata =
                     (;
                      path = "addressfield",
                      type = "Core.String",
                      ),
                 ),
            ))
    output(ws, ["set", "@/4", "1234 Elm St"])
    expect(ws, :set, [],
           (;
            Symbol("@/4") =>
                (;
                 set = "1234 Elm St",
                 ),
            ))
    output(ws, ["set", "@/3", "fred"])
    expect(ws, :set, [],
           (;
            Symbol("@/3") =>
                (;
                 set = "fred",
                 ),
            ))
    output(ws, ["set", "-c", "@/1 people:path=people,access=r", "true"])
    expect(ws, :set, ["@/5"],
           (;
            Symbol("@/5") =>
                (;
                 set = [],
                 metadata = (;
                             path = "people",
                             access = "r",
                             type = "Core.Vector{Person}"
                             ),
                 )))
    # make a person
    output(ws, ["set", "@/2", "true"])
    expect(ws, :set, [],
           (;
            Symbol("@/5") =>
                (;
                 set = [(;ref = 2)],)
            ))
    output(ws, ["set", "@/3", "joe"])
    expect(ws, :set, [],
           (;
            Symbol("@/3") =>
                (;
                 set = "joe",
                 ),
            ))
    output(ws, ["set", "@/4", "1234 Elm St"])
    expect(ws, :set, [],
           (;
            Symbol("@/4") =>
                (;
                 set = "1234 Elm St",
                 ),
            ))
    # make a person
    output(ws, ["set", "@/2", "true"])
    expect(ws, :set, [],
           (;
            Symbol("@/5") =>
                (;
                 set = [(;ref = 2), (;ref = 3)],
                 ),
            ))
    try
        close(ws)
    catch err
        !(err isa HTTP.WebSockets.WebSocketError && lowercase(err.message) == "closed") && rethrow(err)
    end
    fetch(task)
end

function run_tests(func...)
    io = IOBuffer()
    with_logger(ConsoleLogger(stderr)) do
        for f in [test1]
            try
                f()
                print(".")
            catch err
                print("E")
                @error join(["$(err)", stacktrace(catch_backtrace())...], "\n")
            end
        end
    end
    println()
    err = String(take!(io))
    isempty(err) && @debug "SUCCESS"
    isempty(err) && exit(0)
    while !isempty(err)
        println(err)
        err = String(take!(io))
    end
    exit(1)
end

run_tests(test1)


text:
export basemeasure

import MeasureTheory

function MeasureTheory.basemeasure(c::ModelClosure{M,A}, x=NamedTuple()) where {M,A}
    _basemeasure(M, model(c), argvals(c), observations(c), x)
end

export sourceBasemeasure

sourceBasemeasure(m::AbstractModel) = sourceBasemeasure()(model(m))

function sourceBasemeasure()
    function(_m::DAGModel)
        proc(_m, st :: Assign)     = :($(st.x) = $(st.rhs))
        proc(_m, st :: Return)     = nothing
        proc(_m, st :: LineNumber) = nothing
        function proc(_m, st :: Sample)
            x = st.x
            xname = QuoteNode(x)
            rhs = st.rhs
            @q begin
                _bm = merge(_bm, NamedTuple{($xname,)}((basemeasure($rhs),)))
                $x = Tilde.testvalue($rhs)
            end
        end

        wrap(kernel) = @q begin
            _bm = (;)
            $kernel
            return Tilde.productmeasure(_bm)
        end

        buildSource(_m, proc, wrap) |> MacroTools.flatten
    end
end

@gg function _basemeasure(M::Type{<:TypeLevel}, _m::DAGModel, _args, _data, _pars)
    body = type2model(_m) |> sourceBasemeasure() |> loadvals(_args, _data, _pars)
    @under_global from_type(_unwrap_type(M)) @q let M
        $body
    end
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct VirtualMachineScaleSetVMProperties <: SwaggerModel
    latestModelApplied::Any # spec type: Union{ Nothing, Bool } # spec name: latestModelApplied
    vmId::Any # spec type: Union{ Nothing, String } # spec name: vmId
    instanceView::Any # spec type: Union{ Nothing, VirtualMachineScaleSetVMInstanceView } # spec name: instanceView
    hardwareProfile::Any # spec type: Union{ Nothing, HardwareProfile } # spec name: hardwareProfile
    storageProfile::Any # spec type: Union{ Nothing, StorageProfile } # spec name: storageProfile
    additionalCapabilities::Any # spec type: Union{ Nothing, AdditionalCapabilities } # spec name: additionalCapabilities
    osProfile::Any # spec type: Union{ Nothing, OSProfile } # spec name: osProfile
    securityProfile::Any # spec type: Union{ Nothing, SecurityProfile } # spec name: securityProfile
    networkProfile::Any # spec type: Union{ Nothing, NetworkProfile } # spec name: networkProfile
    networkProfileConfiguration::Any # spec type: Union{ Nothing, VirtualMachineScaleSetVMNetworkProfileConfiguration } # spec name: networkProfileConfiguration
    diagnosticsProfile::Any # spec type: Union{ Nothing, DiagnosticsProfile } # spec name: diagnosticsProfile
    availabilitySet::Any # spec type: Union{ Nothing, SubResource } # spec name: availabilitySet
    provisioningState::Any # spec type: Union{ Nothing, String } # spec name: provisioningState
    licenseType::Any # spec type: Union{ Nothing, String } # spec name: licenseType
    modelDefinitionApplied::Any # spec type: Union{ Nothing, String } # spec name: modelDefinitionApplied
    protectionPolicy::Any # spec type: Union{ Nothing, VirtualMachineScaleSetVMProtectionPolicy } # spec name: protectionPolicy

    function VirtualMachineScaleSetVMProperties(;latestModelApplied=nothing, vmId=nothing, instanceView=nothing, hardwareProfile=nothing, storageProfile=nothing, additionalCapabilities=nothing, osProfile=nothing, securityProfile=nothing, networkProfile=nothing, networkProfileConfiguration=nothing, diagnosticsProfile=nothing, availabilitySet=nothing, provisioningState=nothing, licenseType=nothing, modelDefinitionApplied=nothing, protectionPolicy=nothing)
        o = new()
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("latestModelApplied"), latestModelApplied)
        setfield!(o, Symbol("latestModelApplied"), latestModelApplied)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("vmId"), vmId)
        setfield!(o, Symbol("vmId"), vmId)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("instanceView"), instanceView)
        setfield!(o, Symbol("instanceView"), instanceView)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("hardwareProfile"), hardwareProfile)
        setfield!(o, Symbol("hardwareProfile"), hardwareProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("storageProfile"), storageProfile)
        setfield!(o, Symbol("storageProfile"), storageProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("additionalCapabilities"), additionalCapabilities)
        setfield!(o, Symbol("additionalCapabilities"), additionalCapabilities)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("osProfile"), osProfile)
        setfield!(o, Symbol("osProfile"), osProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("securityProfile"), securityProfile)
        setfield!(o, Symbol("securityProfile"), securityProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("networkProfile"), networkProfile)
        setfield!(o, Symbol("networkProfile"), networkProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("networkProfileConfiguration"), networkProfileConfiguration)
        setfield!(o, Symbol("networkProfileConfiguration"), networkProfileConfiguration)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("diagnosticsProfile"), diagnosticsProfile)
        setfield!(o, Symbol("diagnosticsProfile"), diagnosticsProfile)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("availabilitySet"), availabilitySet)
        setfield!(o, Symbol("availabilitySet"), availabilitySet)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("licenseType"), licenseType)
        setfield!(o, Symbol("licenseType"), licenseType)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("modelDefinitionApplied"), modelDefinitionApplied)
        setfield!(o, Symbol("modelDefinitionApplied"), modelDefinitionApplied)
        validate_property(VirtualMachineScaleSetVMProperties, Symbol("protectionPolicy"), protectionPolicy)
        setfield!(o, Symbol("protectionPolicy"), protectionPolicy)
        o
    end
end # type VirtualMachineScaleSetVMProperties

const _property_map_VirtualMachineScaleSetVMProperties = Dict{Symbol,Symbol}(Symbol("latestModelApplied")=>Symbol("latestModelApplied"), Symbol("vmId")=>Symbol("vmId"), Symbol("instanceView")=>Symbol("instanceView"), Symbol("hardwareProfile")=>Symbol("hardwareProfile"), Symbol("storageProfile")=>Symbol("storageProfile"), Symbol("additionalCapabilities")=>Symbol("additionalCapabilities"), Symbol("osProfile")=>Symbol("osProfile"), Symbol("securityProfile")=>Symbol("securityProfile"), Symbol("networkProfile")=>Symbol("networkProfile"), Symbol("networkProfileConfiguration")=>Symbol("networkProfileConfiguration"), Symbol("diagnosticsProfile")=>Symbol("diagnosticsProfile"), Symbol("availabilitySet")=>Symbol("availabilitySet"), Symbol("provisioningState")=>Symbol("provisioningState"), Symbol("licenseType")=>Symbol("licenseType"), Symbol("modelDefinitionApplied")=>Symbol("modelDefinitionApplied"), Symbol("protectionPolicy")=>Symbol("protectionPolicy"))
const _property_types_VirtualMachineScaleSetVMProperties = Dict{Symbol,String}(Symbol("latestModelApplied")=>"Bool", Symbol("vmId")=>"String", Symbol("instanceView")=>"VirtualMachineScaleSetVMInstanceView", Symbol("hardwareProfile")=>"HardwareProfile", Symbol("storageProfile")=>"StorageProfile", Symbol("additionalCapabilities")=>"AdditionalCapabilities", Symbol("osProfile")=>"OSProfile", Symbol("securityProfile")=>"SecurityProfile", Symbol("networkProfile")=>"NetworkProfile", Symbol("networkProfileConfiguration")=>"VirtualMachineScaleSetVMNetworkProfileConfiguration", Symbol("diagnosticsProfile")=>"DiagnosticsProfile", Symbol("availabilitySet")=>"SubResource", Symbol("provisioningState")=>"String", Symbol("licenseType")=>"String", Symbol("modelDefinitionApplied")=>"String", Symbol("protectionPolicy")=>"VirtualMachineScaleSetVMProtectionPolicy")
Base.propertynames(::Type{ VirtualMachineScaleSetVMProperties }) = collect(keys(_property_map_VirtualMachineScaleSetVMProperties))
Swagger.property_type(::Type{ VirtualMachineScaleSetVMProperties }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_VirtualMachineScaleSetVMProperties[name]))}
Swagger.field_name(::Type{ VirtualMachineScaleSetVMProperties }, property_name::Symbol) =  _property_map_VirtualMachineScaleSetVMProperties[property_name]

function check_required(o::VirtualMachineScaleSetVMProperties)
    true
end

function validate_property(::Type{ VirtualMachineScaleSetVMProperties }, name::Symbol, val)
end