text:
using WAV, Plots, Glob, Distributions
using Flux
using IterTools: ncycle
# import Distributions: logpdf
using Flux: throttle, params

include("utils.jl")
using .Utils

dir = "/home/sippycups/Music/2020/"
testdir = "/home/sippycups/Music/2019/"
fns = Glob.glob("*.wav", dir)
testfns = rand(Glob.glob("*.wav", testdir), 1)
fn = fns[1]
n, bs = 100, 64
Dz, Dh = 50, 100

epochs = 1
sr = 44100

xs, ys = Utils.window_multiple(n, sr, fns)
testxs, testys = Utils.window_multiple(n, sr, testfns)

d = Flux.Data.DataLoader(xs, ys; batchsize=bs, shuffle=false)
td = Flux.Data.DataLoader(testxs, testys; batchsize=bs, shuffle=false)
size(d.data[1])

m = Chain(LSTM(n, Dz), LSTM(Dz, Dz), LSTM(Dz, Dz), LSTM(Dz, n)) # basic

A, μ, logσ = Chain(x-> σ.(x),  LSTM(n, Dh)), Dense(Dh, Dz), Dense(Dh, Dz)
g(X) = (h = A(X); (μ(h), logσ(h)))
z(μ, logσ) = μ + exp(logσ) * randn(Float32)
f = Chain(Dense(Dz, Dh, tanh), LSTM(Dh, n), x ->σ.(x))
kl_q_p(μ, logσ) = 0.5f0 * sum(exp.(2f0 .* logσ) + μ.^2 .- 1f0 .- (2 .* logσ))
logpdf(b::Bernoulli, y::Bool) = y * log(b.p + eps(Float32)) + (1f0 - y) * log(1 - b.p + eps(Float32))
logp_x_z(x, z) = sum(logpdf.(Bernoulli.(f(z)), x))
L̄(X) = ((μ̂, logσ̂) = g(X); (logp_x_z(X, z.(μ̂, logσ̂)) - kl_q_p(μ̂, logσ̂)) * 1 // bs)
loss(X) = -L̄(X) + 0.01f0 * sum(x->sum(x.^2), params(f))
modelsample() = rand.(Bernoulli.(f(z.(zeros(Dz), zeros(Dz)))))

evalcb = throttle(() -> @show(-L̄(d.data[1][:, rand(1:n, bs)])), 30)
ps = params(A, μ, logσ, f)

function lxss(x, y)
    @assert size(x) == (n, bs)
    @assert size(y) == (n, bs)
    l = sum(Flux.mse.(m(x), y))
    Flux.reset!(m)
    return l
end

ps = params(m)
opt = ADAM()

function eval_loader(l::Flux.Data.DataLoader)
    for (x, y) in l
        @assert size(x) == (n, bs)
        @assert size(y) == (n, bs)
        ŷ = m(x)

        loss = lxss(x, y)
        return ŷ, loss
    end
end

train_pred = Vector()
test_pred = Vector()
train_losses = Vector()
test_losses = Vector()

global i = 1
cb = function ()
    ŷ, loss = eval_loader(d)
    push!(train_pred, ŷ)
    push!(train_losses, loss)

    test_ŷ, test_loss = eval_loader(td)
    push!(test_pred, test_ŷ)
    push!(test_losses, test_loss)
    println("iter: ", i, ": train_loss:", loss, " test_loss:", test_loss)
    global i += 1
end

for e in 1:epochs
    println("new epoch: ", e)
    Flux.train!(lxss, ps, d, opt, cb=cb)
end

to_write = vcat(train_pred...)
tw = reshape(to_write, 1, :)
size(tw)[2] / sr # seconds

# tw = tw[div(length(tw), 1):end]
test_write = vcat(test_pred...)
testw = reshape(test_write, 1, :)
# testw = testw[div(length(testw), 2):end]
wavwrite(tw', "train_out10.wav", Fs=sr)
wavwrite(testw', "test_out10.wav", Fs=sr)

max_stars_repo_name: anandijain/audio

max_issues_repo_name: anandijain/audio

max_forks_repo_name: anandijain/audio


text:
"""
    module QMatrices

Plain-data matrices and vectors for quantum information.
`z0, z1, I2, X, Y, Z, H, S, T, sqrt_NOT, CX, CCX, CZ, SWAP`
"""
module QMatrices

export z0, z1, I2, H, CH, CCH, S, T,
    sqrt_NOT,
    X, CX, CCX, Y, CY, CCY, Z, CZ, CCZ,
    SWAP, CSWAP, iSWAP,
    Rphi, Rphipi,
    RX, RXpi,
    RY, RYpi,
    RZ, RZpi,
    U, Upi, Ualt, U2,
    R, Rpi,
    magic_basis

include("linalg.jl")
include("construction.jl")
include("parametric.jl")
include("basic_dynamic.jl")
include("constructed.jl")

end # module QMatrices

ext: jl


text:
# Copyright (c) 2017: Miles Lubin and contributors
# Copyright (c) 2017: Google Inc.
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.

function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
    Base.precompile(
        Tuple{
            typeof(MOI.eval_hessian_lagrangian),
            NLPEvaluator,
            SubArray{Float64,1,Vector{Float64},Tuple{UnitRange{Int64}},true},
            Vector{Float64},
            Float64,
            SubArray{Float64,1,Vector{Float64},Tuple{UnitRange{Int64}},true},
        },
    )
    Base.precompile(
        Tuple{
            typeof(MOI.eval_objective_gradient),
            NLPEvaluator,
            Vector{Float64},
            Vector{Float64},
        },
    )
    Base.precompile(Tuple{typeof(MOI.initialize),NLPEvaluator,Vector{Symbol}})
    Base.precompile(Tuple{typeof(MOI.features_available),NLPEvaluator})
    Base.precompile(
        Tuple{
            typeof(MOI.eval_constraint_jacobian),
            NLPEvaluator,
            SubArray{Float64,1,Vector{Float64},Tuple{UnitRange{Int64}},true},
            Vector{Float64},
        },
    )
    Base.precompile(
        Tuple{
            typeof(MOI.eval_constraint),
            NLPEvaluator,
            SubArray{Float64,1,Vector{Float64},Tuple{UnitRange{Int64}},true},
            Vector{Float64},
        },
    )
    Base.precompile(Tuple{typeof(MOI.jacobian_structure),NLPEvaluator})
    Base.precompile(
        Tuple{typeof(MOI.eval_objective),NLPEvaluator,Vector{Float64}},
    )
    return
end

_precompile_()

max_stars_repo_name: JuliaOpt/MathOptInterface

max_issues_repo_name: JuliaOpt/MathOptInterface

max_forks_repo_name: JuliaOpt/MathOptInterface


text:
# constructor

@testset "LinearElastic" begin
    m = LinearElastic(E=200e3, ν=0.3)

    # initial state
    state = initial_material_state(m)

    # constitutive driver
    ε = rand(SymmetricTensor{2,3})
    σ, ∂σ∂ε, temp_state = material_response(m, ε, state)
    @test σ == m.Eᵉ ⊡ ε
    @test ∂σ∂ε == m.Eᵉ

end

function get_LinearElastic_loading()
    loading = range(0.0,  0.02, length=2)
    return [SymmetricTensor{2,3}((ε, ε/10, 0.0, 0.0, 0.0, 0.0)) for ε in loading]
end

@testset "LinearElastic jld2" begin
    m = LinearElastic(E=200e3, ν=0.3)
    loading = get_LinearElastic_loading()
    check_jld2(m, loading, "LinearElastic1")#, OVERWRITE_JLD2=false)
end


text:
#   Copyright (c) 2020-2022 Velexi Corporation
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""
Unit tests for the Pseudoscalar type.
"""

# --- Imports

# Standard library
import InteractiveUtils.subtypes
import LinearAlgebra
using Test
import Random.rand

# GeometricAlgebra.jl
using GeometricAlgebra

# --- File inclusions

# Test utilities
include("test_utils.jl")

# --- Constructor tests

@testset "Pseudoscalar: inner constructor" begin
    #=
      Notes
      -----
      * Test value of constructed instance
    =#

    # --- Pseudoscalar{T}(dim::Integer, value::AbstractFloat)

    test_dim = 10

    # value != 0
    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        for value_type in subtypes(AbstractFloat)
            converted_test_value = value_type(test_value)

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B isa Pseudoscalar{precision_type}
            @test B.dim == test_dim
            @test B.value isa precision_type
            @test B.value == precision_type(converted_test_value)
        end
    end

    # value == 0
    test_value = 0

    for precision_type in subtypes(AbstractFloat)
        for value_type in subtypes(AbstractFloat)
            converted_test_value = value_type(test_value)

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B isa Zero{precision_type}
        end
    end

    # --- Pseudoscalar{T}(dim::Integer, value::Integer)

    test_dim = 10

    # value != 0
    test_value = (rand() > 0.5) ? 10 : -10

    for precision_type in subtypes(AbstractFloat)
        # subtypes(Signed)
        for value_type in subtypes(Signed)
            converted_test_value = value_type(test_value)

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B.dim == test_dim
            @test B.value isa precision_type
            @test B.value == precision_type(converted_test_value)
        end

        # subtypes(Unsigned)
        for value_type in subtypes(Unsigned)
            converted_test_value = value_type(abs(test_value))

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B.dim == test_dim
            @test B.value isa precision_type
            @test B.value == precision_type(converted_test_value)
        end

        # Bool
        B = Pseudoscalar{precision_type}(test_dim, true)
        @test B isa Pseudoscalar{precision_type}
        @test B.dim == test_dim
        @test B.value isa precision_type
        @test B.value == precision_type(1)

        B = Pseudoscalar{precision_type}(test_dim, false)
        @test B isa Zero{precision_type}
    end

    # value == 0
    test_value = 0

    for precision_type in subtypes(AbstractFloat)
        # subtypes(Signed)
        for value_type in subtypes(Signed)
            converted_test_value = value_type(test_value)

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B isa Zero{precision_type}
        end

        # subtypes(Unsigned)
        for value_type in subtypes(Unsigned)
            converted_test_value = value_type(abs(test_value))

            B = Pseudoscalar{precision_type}(test_dim, converted_test_value)
            @test B isa Zero{precision_type}
        end
    end

    # --- Invalid data fields

    for precision_type in subtypes(AbstractFloat)
        # dim == 0
        @test_throws ArgumentError Pseudoscalar{precision_type}(0, 10)

        # dim < 0
        @test_throws ArgumentError Pseudoscalar{precision_type}(-1, 10)
    end
end

@testset "Pseudoscalar: outer constructor - basic constructors" begin
    #=
      Notes
      -----
      * Test type of constructed instances. Correct construction of instances
        is tested by the inner constructor tests.
    =#

    # --- Preparations

    test_dim = 10

    # --- Pseudoscalar(dim::Integer, value::AbstractFloat)

    # value != 0
    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        converted_test_value = precision_type(test_value)
        B = Pseudoscalar(test_dim, converted_test_value)
        @test B isa Pseudoscalar{precision_type}
        @test B.dim == test_dim
        @test B.value == converted_test_value
    end

    # value == 0
    test_value = 0

    for precision_type in subtypes(AbstractFloat)
        converted_test_value = precision_type(test_value)
        B = Pseudoscalar(test_dim, converted_test_value)
        @test B isa Zero{precision_type}
    end

    # --- Pseudoscalar(dim::Integer, value::Integer)

    # value != 0
    test_value = (rand() > 0.5) ? 10 : -10

    # subtypes(Signed)
    for value_type in subtypes(Signed)
        B = Pseudoscalar(test_dim, value_type(test_value))
        @test B isa Pseudoscalar{Float64}
        @test B.dim == test_dim
        @test B.value == value_type(test_value)
    end

    # subtypes(Unsigned)
    for value_type in subtypes(Unsigned)
        B = Pseudoscalar(test_dim, value_type(abs(test_value)))
        @test B isa Pseudoscalar{Float64}
        @test B.dim == test_dim
        @test B.value == value_type(abs(test_value))
    end

    # Bool
    B = Pseudoscalar(test_dim, true)
    @test B isa Pseudoscalar{Float64}
    @test B.dim == test_dim
    @test B.value == 1.0

    B = Pseudoscalar(test_dim, false)
    @test B isa Zero{Float64}

    # value == 0
    test_value = 0

    # subtypes(Signed)
    for value_type in subtypes(Signed)
        B = Pseudoscalar(test_dim, value_type(test_value))
        @test B isa Zero{Float64}
    end

    # subtypes(Unsigned)
    for value_type in subtypes(Unsigned)
        B = Pseudoscalar(test_dim, value_type(abs(test_value)))
        @test B isa Zero{Float64}
    end

    # --- Invalid data fields

    # dim == 0
    @test_throws ArgumentError Pseudoscalar(0, 10)

    # dim < 0
    @test_throws ArgumentError Pseudoscalar(-1, 10)
end

@testset "Pseudoscalar: outer constructor - copy constructor" begin
    #=
      Notes
      -----
      * Test type of constructed instances. Correct construction of instances
        is tested by the inner constructor tests.

      * Test behavior of keyword arguments: `value`.
    =#

    # --- Preparations

    test_dim = 10

    test_value = get_random_value()

    # --- Pseudoscalar(dim::Integer, value::T) where {T<:AbstractFloat}

    for precision_type in subtypes(AbstractFloat)
        # Preparations
        converted_test_value = precision_type(test_value)
        B = Pseudoscalar(test_dim, converted_test_value)

        # Construct a Pseudoscalar representing the same pseudoscalar as `B`
        B_copy = Pseudoscalar(B)
        @test B_copy isa Pseudoscalar{precision_type}
        @test B.dim == test_dim
        @test B.value == precision_type(converted_test_value)

        # Construct a Pseudoscalar representing the same space as `B` with a
        # different value.
        B_copy = Pseudoscalar(B, value=converted_test_value + 1)
        @test B_copy isa Pseudoscalar{precision_type}
        @test B.dim == test_dim
        @test value(B_copy) == converted_test_value + 1
    end
end

# --- Test attribute methods

@testset "Pseudoscalar: AbstractMultivector attribute functions" begin
    # Preparations
    test_dim = 10

    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        # Preparations
        converted_test_value = precision_type(test_value)

        # value > 0
        positive_test_value = converted_test_value > 0 ?
            converted_test_value : -converted_test_value
        B = Pseudoscalar(test_dim, positive_test_value)
        @test dim(B) == test_dim
        @test grades(B) == [test_dim]
        @test blades(B) == [B]
        @test norm(B) isa precision_type
        @test norm(B) == positive_test_value

        @test B[0] == []
        @test B[1] == []
        @test B[test_dim] == [B]

        # value < 0
        negative_test_value = converted_test_value > 0 ?
            -converted_test_value : converted_test_value
        B = Pseudoscalar(test_dim, negative_test_value)
        @test norm(B) isa precision_type
        @test norm(B) == abs(negative_test_value)

        # value = Inf
        B = Pseudoscalar(test_dim, precision_type(Inf))
        @test norm(B) isa precision_type
        @test norm(B) == Inf

        # value = -Inf
        B = Pseudoscalar(test_dim, precision_type(-Inf))
        @test norm(B) isa precision_type
        @test norm(B) == Inf
    end
end

@testset "Pseudoscalar: AbstractBlade attribute functions" begin
    # Preparations
    test_dim = 10

    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        # Preparations
        converted_test_value = precision_type(test_value)

        # value > 0
        positive_test_value = converted_test_value > 0 ?
            converted_test_value : -converted_test_value
        B = Pseudoscalar(test_dim, positive_test_value)
        @test grade(B) == test_dim
        @test basis(B) == LinearAlgebra.I
        @test volume(B) isa precision_type
        @test volume(B) == positive_test_value
        @test sign(B) == 1

        # value < 0
        negative_test_value = converted_test_value > 0 ?
            -converted_test_value : converted_test_value
        B = Pseudoscalar(test_dim, negative_test_value)
        @test volume(B) isa precision_type
        @test volume(B) == negative_test_value
        @test sign(B) == -1

        # value = Inf
        B = Pseudoscalar(test_dim, precision_type(Inf))
        @test volume(B) isa precision_type
        @test volume(B) == precision_type(Inf)
        @test sign(B) == 1

        # value = -Inf
        B = Pseudoscalar(test_dim, precision_type(-Inf))
        @test volume(B) isa precision_type
        @test volume(B) == precision_type(-Inf)
        @test sign(B) == -1
    end
end

@testset "Pseudoscalar: Pseudoscalar attribute functions" begin
    # Preparations
    test_dim = 10

    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        # Preparations
        converted_test_value = precision_type(test_value)

        # value > 0
        positive_test_value = converted_test_value > 0 ?
            converted_test_value : -converted_test_value
        B = Pseudoscalar(test_dim, positive_test_value)
        @test value(B) isa precision_type
        @test value(B) == positive_test_value

        # value < 0
        negative_test_value = converted_test_value > 0 ?
            -converted_test_value : converted_test_value
        B = Pseudoscalar(test_dim, negative_test_value)
        @test value(B) isa precision_type
        @test value(B) == negative_test_value

        # value = Inf
        B = Pseudoscalar(test_dim, precision_type(Inf))
        @test value(B) isa precision_type
        @test value(B) == precision_type(Inf)

        # value = -Inf
        B = Pseudoscalar(test_dim, precision_type(-Inf))
        @test value(B) isa precision_type
        @test value(B) == precision_type(-Inf)
    end
end

# --- Tests for AbstractMultivector interface functions

@testset "Pseudoscalar: -(B)" begin
    # Preparations
    test_dim = 10

    test_value = get_random_value(1)  # add 1 to avoid 0

    # Tests
    for precision_type in subtypes(AbstractFloat)
        B = Pseudoscalar{precision_type}(test_dim, test_value)

        negative_B = -B
        @test negative_B isa Pseudoscalar{precision_type}
        @test negative_B == Pseudoscalar{precision_type}(test_dim, -test_value)
    end
end

@testset "Pseudoscalar: reverse(B)" begin
    # --- Preparations

    test_value = get_random_value(1)  # add 1 to avoid 0

    for precision_type in subtypes(AbstractFloat)
        for test_dim in 5:8
            B = Pseudoscalar(test_dim, test_value)
            reverse_B = reverse(B)
            expected_result = mod(test_dim, 4) < 2 ?
                Pseudoscalar(test_dim, test_value) :
                Pseudoscalar(test_dim, -test_value)
            @test reverse(B) == expected_result

            @test B * reverse(B) ≈ norm(B)^2
        end
    end
end

@testset "Pseudoscalar: dual(B)" begin
    # Preparations
    test_value = get_random_value(1)  # add 1 to avoid 0

    # Tests
    for precision_type in subtypes(AbstractFloat)
        for test_dim in 5:8
            B = Pseudoscalar{precision_type}(test_dim, test_value)

            dual_B = dual(B)
            expected_result = Scalar{precision_type}(precision_type(test_value))
            @test dual_B isa Scalar{precision_type}
            @test dual_B == expected_result

            # Check dual(dual_B) = (-1)^(dim_B * (dim_B - 1) / 2) B
            if mod(dim(B), 4) < 2
                @test dual(dual_B, dim(B)) == B
            else
                @test dual(dual_B, dim(B)) == -B
            end
        end
    end
end

@testset "Pseudoscalar: convert(B)" begin
    # Preparations
    test_dim = 10

    test_value = get_random_value(1)  # add 1 to avoid 0

    # Tests
    for precision_type_converted in subtypes(AbstractFloat)
        for precision_type_src in subtypes(AbstractFloat)
            # Preparations
            converted_test_value = precision_type_src(test_value)
            B = Pseudoscalar{precision_type_src}(test_dim, converted_test_value)

            # Exercise functionality and check results
            B_converted = convert(precision_type_converted, B)

            @test B_converted isa Pseudoscalar{precision_type_converted}

            if precision_type_src == precision_type_converted
                @test B_converted === B
            else
                @test B_converted !== B
                @test B_converted ≈ B
            end
        end
    end
end

# --- Tests for AbstractBlade interface functions

@testset "Pseudoscalar: inv(B)" begin
    # Preparations
    test_value = get_random_value(1)  # add 1 to avoid 0

    # Tests
    for precision_type in subtypes(AbstractFloat)
        converted_value = precision_type(test_value)

        for test_dim = 5:8
            B = Pseudoscalar(test_dim, converted_value)

            inverse_B = inv(B)
            @test inverse_B isa Pseudoscalar{precision_type}

            expected_result = mod(test_dim, 4) < 2 ?
                Pseudoscalar{precision_type}(test_dim, 1 / converted_value) :
                Pseudoscalar{precision_type}(test_dim, -1 / converted_value)
            @test inverse_B == expected_result

            @test B * inverse_B ≈ 1
        end
    end
end


text:
######################################################
#
# Markov-Switching Multifractal (MSM)
#
# Date:   2014-11-19
# Author: Hessel Tuinhof
#
# Function to simulate a MSM process.
#
# Reference:
# - Stein, William: https://raw.githubusercontent.com/sagemath/sagelib/master/sage/finance/markov_multifractal_cython.pyx
#
# Required packages: 	Distributions
#
# Input:
#   num_sim ... number of simulatons, positive integer
#   sim_length ... length of simulation, positive integer
#   m0 ... multiplier, float in [0,2]
#   kbar ... number of frequencies, positive integer
#   sigma ... standard deviation of returns, positve float
#   gamma_kbar ... transition probability, float in [0,1)
#   b ... geometric rate, float in (1,inf)
#
# Output:
#   msm ... simulated log returns
#
# Examples:
#   # Simulation of log returns (1 simulation)
#   plot(MSM(1, 4000, 1.4, 8, 0.55, 0.92, 3))
#
#   # Simulation of log price (10 simulations)
#   plot(cumsum(MSM(10, 4000, 1.4, 8, 0.55, 0.92, 3)))
#
######################################################

#####################   Warning   #####################
# For large simulation purposes the use of the array type
# is not recommendable. Instead one should save the sim-
# ulated returns in an DataFrame or TimeSeries type for
# improved performance.
#####################   Warning   #####################

using Distributions

function MSM(num_sim, sim_length, m0, kbar, sigma, gamma_kbar, b)
	m1 = 2-m0
	gammaone = 1 - exp(log(1-gamma_kbar)/(b^(kbar-1)))
	gamma  = zeros(kbar)
	for i = 1:kbar
		gamma[i] = 1-(1-gammaone)^(b^(i-1))
	end
	markovstatevector = zeros(kbar)
	msm = zeros(sim_length, num_sim)
	for i = 1:num_sim
		for j = 1:kbar
			convert(Bool, rand(Int64) & 1) ? markovstatevector[j] = m0 : markovstatevector[j] = m1
		end
		err = randn(sim_length)
		for j = 1:sim_length
			msm[j,i] = sigma * err[j] * sqrt(prod(markovstatevector))
			for k = 1:kbar
				if rand() <= gamma[k]
					convert(Bool, rand(Int64) & 1) ? markovstatevector[k] = m0 : markovstatevector[k] = m1
				end
			end
		end
	end
	return msm
end

max_stars_repo_name: hesseltuinhof/masterthesis

max_issues_repo_name: hesseltuinhof/masterthesis

max_forks_repo_name: hesseltuinhof/masterthesis


text:
using Test
using NeXLUncertainties
using LaTeXStrings

@testset "Uncertainty" begin

    uv1, uv2, uv3 =
        UncertainValue(1.0, 0.1), UncertainValue(0.8, 0.001), UncertainValue(-0.9, 0.05)

    @testset "Sigma" begin
        @test σ(uv1) == uncertainty(uv1)
        @test σ(1.0) == 0.0
        @test isequal(uv(1.0, 0.1), uv1)
        @test uv(1.0, 0.1) == uv1
        @test σ(uv1) == 0.1
        @test σ(uv2) == 0.001
        @test σ(1.0) == 0.0
        @test variance(uv2) == 0.001^2
        @test variance(1.0) == 0.0
        @test fractional(uv2) == 0.001 / 0.8
        @test fractional(uv3) == abs(0.05 / -0.9)
        @test fractional(0.0) == 0.0
        @test value(uv2) == 0.8
        @test value(uv3) == -0.9
        @test value(1.0) == 1.0

        @test min(uv1, uv2) === uv2
        @test min(uv2, uv3) === uv3
        @test min(uv1, uv3) === uv3
        @test min(uv1, UncertainValue(1.0, 0.05)) === uv1
        @test minimum([uv1, uv2, uv3]) === uv3
        @test minimum((uv1, uv2, uv3)) === uv3

        @test max(uv1, uv2) === uv1
        @test max(uv1, uv2) === uv1
        @test max(uv1, uv3) === uv1
        @test max(uv2, UncertainValue(0.8, 0.0005)) == uv2
        @test maximum([uv1, uv2, uv3]) === uv1
        @test maximum((uv1, uv2, uv3)) === uv1

        @test isless(uv1, uv2) == false
        @test isless(uv2, uv1) == true
        @test isless(uv(1.0, 0.1), uv(1.0, 0.2)) == false
        @test isless(uv(1.0, 0.2), uv(1.0, 0.1)) == true
    end

    @testset "Conversions" begin
        @test convert(UncertainValue, 2.0) == uv(2.0, 0.0)
        @test convert(UncertainValue, 2) == uv(2.0, 0.0)
        @test zero(UncertainValue) == uv(0.0, 0.0)
        @test one(UncertainValue) == uv(1.0, 0.0)

        @test -one(UncertainValue) == uv(-1.0, 0.0)
        @test +one(UncertainValue) == uv(1.0, 0.0)
    end

    @testset "Operations" begin
        # Values are taken from the NIST Uncertainty Machine (Gauss's Formula (GUM's Linear Approximation))
        @test isapprox(3.0 * uv2, uv(2.4, 0.003), atol = 1.0e-10)
        @test isapprox(uv2 * 3.0, uv(2.4, 0.003), atol = 1.0e-10)

        @test isapprox(inv(uv(5.0, 0.2)), uv(0.2, 0.008), atol = 1.0e-5)
        @test isapprox(1.0 / uv(5.0, 0.2), uv(0.2, 0.008), atol = 1.0e-5)

        @test isapprox(uv(2.0, 0.2)^5.0, uv(32.0, 16.0), atol = 1.0e-5)
        @test isapprox(log(uv(2.0, 0.2)), uv(0.693, 0.100), atol = 1.0e-3)
        @test isapprox(exp(uv(2.0, 0.2)), uv(7.39, 1.48), atol = 1.0e-2)
        @test isapprox(sin(uv(2.0, 0.2)), uv(0.909, 0.0832), atol = 1.0e-3)
        @test isapprox(cos(uv(2.0, 0.2)), uv(-0.416, 0.182), atol = 1.0e-3)
        @test isapprox(tan(uv(0.3, 0.1)), uv(0.309, 0.110), atol = 1.0e-3)
        @test isapprox(sqrt(uv(3.5, 0.1)), uv(1.871, 0.0267), atol = 1.0e-3)

        @test equivalent(uv(3.3, 0.2), uv(3.5, 0.1))
        @test !equivalent(uv(3.3, 0.2), uv(3.6, 0.1))

        @test isapprox(
            multiply(uv(2.3, 0.4), uv(3.1, 0.2), 0.3),
            uv(7.13, 1.45),
            atol = 0.01,
        )
        @test isapprox(
            divide(uv(2.3, 0.4), uv(3.1, 0.2), 0.3),
            uv(0.742, 0.123),
            atol = 0.001,
        )

        @test isapprox(
            multiply(uv(2.3, 0.4), uv(3.1, 0.2), -0.2),
            uv(7.13, 1.23),
            atol = 0.01,
        )

        @test isapprox(
            multiply(uv(2.3, 0.4), uv(2.3, 0.4), -1.0),
            uv(2.3*2.3, 0.0),
            atol = 0.001
        )

        @test isapprox(
            multiply(uv(2.3, 0.4), uv(2.3, 0.4), 1.0),
            uv(2.3*2.3, 1.84),
            atol = 0.001
        )

        @test isapprox(
            multiply(uv(2.3, 0.4), uv(2.3, 0.4), 0.0),
            uv(2.3*2.3, 1.301),
            atol = 0.001
        )

        @test isapprox(
            divide(uv(2.3, 0.4), uv(3.1, 0.2), -0.2),
            uv(0.74194, 0.146),
            atol = 0.001,
        )

        @test isapprox(
            divide(uv(2.3, 0.4), uv(2.3, 0.4), 1.0),
            uv(1.0, 0.0),
            atol = 0.001,
        )

        @test isapprox(
            divide(uv(2.3, 0.4), uv(2.3, 0.4), -1.0),
            uv(1.0, 0.348),
            atol = 0.001,
        )

        @test isapprox(
            divide(uv(2.3, 0.4), uv(2.3, 0.4), 0.0),
            uv(1.0, 0.245),
            atol = 0.001,
        )

        @test isapprox(
            add(-3.0, uv(2.3, 0.4), 4.0, uv(3.1, 0.2), -0.2),
            uv(5.5, 1.57),
            atol = 0.01,
        )
        @test isapprox(
            add(3.0, uv(2.3, 0.4), -4.0, uv(3.1, 0.2), 0.3),
            uv(-5.5, 1.23),
            atol = 0.01,
        )

        @test isequal(abs(uv(1.0, 0.2)), uv(1.0, 0.2))
        @test isequal(abs(uv(-1.0, 0.2)), uv(1.0, 0.2))
    end
    @testset "Parse" begin
        @test isequal(parse(UncertainValue, "1.0±0.1"), uv(1.0, 0.1))
        @test isequal(parse(UncertainValue, "2.0 ± 0.3"), uv(2.0, 0.3))
        @test isequal(parse(UncertainValue, "-1.0 ± 0.2"), uv(-1.0, 0.2))
        @test isequal(parse(UncertainValue, "12.3 +- 0.12"), uv(12.3, 0.12))
        @test isequal(parse(UncertainValue, "12.3 -+ 0.12"), uv(12.3, 0.12))
        @test isequal(parse(UncertainValue, repr(uv1)), uv1)
        @test isequal(parse(UncertainValue, repr(uv2)), uv2)
    end
    @testset "LaTeX" begin
        @test isequal(latexstring(uv(1.0,0.033),mode=:normal), L"$1.000 \pm 0.033$")
        @test isequal(latexstring(uv(1.0,0.033),mode=:normal), latexstring(uv(1.0,0.033)))
        @test isequal(latexstring(uv(1.0,0.033),mode=:siunitx), L"$\num{1.000 \pm 0.033}$")
        @test isequal(latexstring(uv(1.0,0.033),fmt = "%0.5f",mode=:normal), L"$1.00000 \pm 0.03300$")
        @test isequal(latexstring(uv(1.0,0.033),fmt = "%0.4f",mode = :siunitx), L"$\num{1.0000 \pm 0.0330}$")
    end
end


text:
import IfElse: ifelse

export Dist, DistBool, prob_equals, infer

"A probability distribution over values of type `T`"
abstract type Dist{T} end

"The global context of a dice program analysis"
abstract type DiceManager end

struct DistBool <: Dist{Bool}
    mgr::DiceManager
    bit
end

DistBool(mgr::DiceManager, b::Bool) =
    DistBool(mgr, constant(mgr, b))

DistBool(mgr::DiceManager, p::Number) =
    DistBool(mgr, new_var(mgr, p))

# display `DistBool` values depending on the manager type
function Base.show(io::IO, x::DistBool)
    # specific to CuddMgr DistBools...
    print(io, typeof(x))
    show(io, x.mgr, x.bit)
end

function biconditional(x::DistBool, y::DistBool)
    @assert x.mgr === y.mgr
    DistBool(x.mgr, biconditional(x.mgr, x.bit, y.bit))
end

function Base.:&(x::DistBool, y::DistBool)
    @assert x.mgr === y.mgr
    DistBool(x.mgr, conjoin(x.mgr, x.bit, y.bit))
end

Base.:&(x::DistBool, y::Bool) =
    x & DistBool(x.mgr, y)

Base.:&(x::Bool, y::DistBool) =
    y & x

function Base.:|(x::DistBool, y::DistBool)
    @assert x.mgr === y.mgr
    DistBool(x.mgr, disjoin(x.mgr, x.bit, y.bit))
end

Base.:|(x::DistBool, y::Bool) =
    x | DistBool(x.mgr, y)

Base.:|(x::Bool, y::DistBool) =
    y | x

negate(x::DistBool) =
    DistBool(x.mgr, negate(x.mgr, x.bit))

Base.:!(x::DistBool) =
    negate(x)

prob_equals(x::DistBool, y::DistBool) =
    biconditional(x,y)

function ifelse(cond::DistBool, then::DistBool, elze::DistBool)
    @assert cond.mgr === then.mgr === elze.mgr
    DistBool(cond.mgr, ite(cond.mgr, cond.bit, then.bit, elze.bit))
end

ifelse(cond::DistBool, x, y) =
    ifelse(cond, DistBool(cond.mgr, x), y)

ifelse(cond::DistBool, x::DistBool, y) =
    ifelse(cond, x, DistBool(cond.mgr, y))

bools(b::DistBool) = [b]

rundice(d::DistBool) =
    rundice(d.mgr, d.bit)

infer(d::DistBool) =
    infer(d.mgr, d.bit)


text:
using FingerTrees
using FunctionalCollections
const FT = FingerTrees
const FC = FunctionalCollections

function fctest(N, n, verbose=true)
    verbose && println("PersistentVector")

    x = PersistentVector(1:n)
    verbose && println("construct")
    @time for i in 1:N
        x = PersistentVector(1:n)
    end
    x = append(x, n+1)
    verbose && println("append")
    @time for i in 2:n
        x = append(x, n+i)
    end
    x = FC.assoc(x, 1, n)
    x = FC.assoc(x, n, 1)
    verbose && println("FC.assoc")
    @time for i in 1:N
        x = FC.assoc(x, n-i, n+i)
        x = FC.assoc(x, n+i, n-i)
    end
    verbose && println("getindex")
    y = 0
    @time for i in 1:N
        y += x[mod1(n+i, 2n)]
    end
    verbose && println("iterator")
    @time for i in x
        y += i
    end
    verbose && println("reduce")
    @time for i in 1:N
        y += reduce(+, x)
    end
    verbose && println("reduce and subset")
    @time for i in 1:N
        y += reduce(+, PersistentVector([x[k] for k in N:n-N]))
    end
    verbose && println(y)

end

function fttest(N, n, verbose=true)
    verbose && println("FingerTree")
    x = FingerTree(1:n)
    verbose && println("construct")
    @time for i in 1:N
        x = FingerTree(1:n)
    end
    x = x |> (n+1)
    verbose && println("append")
    @time for i in 2:n
        x = x |> (n+i)
    end
    x = FT.assoc(x, 1, n)
    x = FT.assoc(x, n, 1)
    verbose && println("assoc")
    @time for i in 1:N
        x = FT.assoc(x, n-i, n+i)
        x = FT.assoc(x, n+i, n-i)
    end
    y = 0
    verbose && println("getindex")
    @time for i in 1:N
        y += x[mod1(n+i, 2n)]
    end
    verbose && println("iterator")
    @time for i in x
        y += i
    end
    verbose && println("reduce")
    @time for i in 1:N
        y += reduce(+, x)
    end
    verbose && println("reduce and subset")
    @time for i in 1:N
        y += reduce(+, x[N:n-N])
    end
    verbose && println(y)

end
fttest(1, 10, false)
fctest(1, 10, false)

fttest(100, 1000)
fctest(100, 1000)


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

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

                     @variable(m, -0.7481803354345802 <= q <= 3.1247048530266452)

                     add_NL_constraint(m, :(sigmoid(0.30283339323429637 + -0.6237495659853991*sigmoid(-0.21938578694289834 + -0.903262746252536*sigmoid(0.9051056598158431 + -0.13053580855908242*$(x[1]) + -0.5492925144525009*$(x[2]) + 0.019096353213378325*$(x[3]) + 0.3378807953855012*$(x[4])) + 0.16468819845671145*sigmoid(0.06066012774712304 + 0.010865522181132903*$(x[1]) + -0.27940603676198705*$(x[2]) + -0.359831046364532*$(x[3]) + -0.7556261576696839*$(x[4]))) + 0.9377177734653888*sigmoid(0.5819650565710264 + -0.47161154460717736*sigmoid(0.9051056598158431 + -0.13053580855908242*$(x[1]) + -0.5492925144525009*$(x[2]) + 0.019096353213378325*$(x[3]) + 0.3378807953855012*$(x[4])) + -0.23723822344605994*sigmoid(0.06066012774712304 + 0.010865522181132903*$(x[1]) + -0.27940603676198705*$(x[2]) + -0.359831046364532*$(x[3]) + -0.7556261576696839*$(x[4])))) + sigmoid(-0.5162811028857681 + 0.4410139812710443*sigmoid(-0.21938578694289834 + -0.903262746252536*sigmoid(0.9051056598158431 + -0.13053580855908242*$(x[1]) + -0.5492925144525009*$(x[2]) + 0.019096353213378325*$(x[3]) + 0.3378807953855012*$(x[4])) + 0.16468819845671145*sigmoid(0.06066012774712304 + 0.010865522181132903*$(x[1]) + -0.27940603676198705*$(x[2]) + -0.359831046364532*$(x[3]) + -0.7556261576696839*$(x[4]))) + 0.2178047619382908*sigmoid(0.5819650565710264 + -0.47161154460717736*sigmoid(0.9051056598158431 + -0.13053580855908242*$(x[1]) + -0.5492925144525009*$(x[2]) + 0.019096353213378325*$(x[3]) + 0.3378807953855012*$(x[4])) + -0.23723822344605994*sigmoid(0.06066012774712304 + 0.010865522181132903*$(x[1]) + -0.27940603676198705*$(x[2]) + -0.359831046364532*$(x[3]) + -0.7556261576696839*$(x[4])))) - $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


text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

@doc raw"""
	configure_cbc(solver_settings_path::String)

Reads user-specified solver settings from cbc\_settings.yml in the directory specified by the string solver\_settings\_path.

Returns a MathOptInterface OptimizerWithAttributes Cbc optimizer instance to be used in the GenX.generate_model() method.

The Cbc optimizer instance is configured with the following default parameters if a user-specified parameter for each respective field is not provided:

 - seconds = 1e-6
 - logLevel = 1e-6
 - maxSolutions = -1
 - maxNodes = -1
 - allowableGap = -1
 - ratioGap = Inf
 - threads = 1

"""
function configure_cbc(solver_settings_path::String)

    solver_settings = YAML.load(open(solver_settings_path))

    # Optional solver parameters ############################################
    seconds = 1e-6
    if (haskey(solver_settings, "TimeLimit"))
        seconds = solver_settings["TimeLimit"]
    end
    loglevel = 1e-6
    if (haskey(solver_settings, "logLevel"))
        loglevel = solver_settings["logLevel"]
    end
    maxSolutions = -1
    if (haskey(solver_settings, "maxSolutions"))
        maxSolutions = solver_settings["maxSolutions"]
    end
    maxNodes = -1
    if (haskey(solver_settings, "maxNodes"))
        maxNodes = solver_settings["maxNodes"]
    end
    allowableGap = -1
    if (haskey(solver_settings, "allowableGap"))
        allowableGap = solver_settings["allowableGap"]
    end
    ratioGap = Inf
    if (haskey(solver_settings, "ratioGap"))
        ratioGap = solver_settings["ratioGap"]
    end
    threads = 1
    if (haskey(solver_settings, "threads"))
        threads = solver_settings["threads"]
    end
    ########################################################################

    OPTIMIZER = optimizer_with_attributes(
        Cbc.Optimizer,
        "seconds" => seconds,
        "logLevel" => loglevel,
        "maxSolutions" => maxSolutions,
        "maxNodes" => maxNodes,
        "allowableGap" => allowableGap,
        "ratioGap" => ratioGap,
        "threads" => threads,
    )

    return OPTIMIZER
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
function gencodebou(filename, f, xdg, udg, odg, wdg, uhg, nlg, tau, uinf, param, time)

opufile = "opu" * filename;
gpufile = "gpu" * filename;

stropu = "template <typename T> void " * opufile;
strgpu = "template <typename T>  __global__  void kernel" * gpufile;

tmp = "(T *f, T *xdg, T *udg, T *odg, T *wdg, T *uhg, T *nlg, T *tau, T *uinf, T *param, T time, int ng, int nc, int ncu, int nd, int ncx, int nco, int ncw)\n";

stropu = stropu * tmp * "{\n";
stropu = stropu *  "\tfor (int i = 0; i <ng; i++) {\n";

strgpu = strgpu * tmp * "{\n";
strgpu = strgpu * "\tint i = threadIdx.x + blockIdx.x * blockDim.x;\n";
strgpu = strgpu * "\twhile (i<ng) {\n";

fstr = string(f[:]);
str = "";
str = varsassign(str, "param", length(param), 0, fstr);
str = varsassign(str, "uinf", length(uinf), 0, fstr);
str = varsassign(str, "tau", length(tau), 0, fstr);
str = varsassign(str, "xdg", length(xdg), 1, fstr);
str = varsassign(str, "udg", length(udg), 1, fstr);
str = varsassign(str, "uhg", length(uhg), 1, fstr);
str = varsassign(str, "odg", length(odg), 1, fstr);
str = varsassign(str, "wdg", length(wdg), 1, fstr);
str = varsassign(str, "nlg", length(nlg), 1, fstr);
str = sympyassign(str, f);
stropu = stropu *  str * "\t}\n" * "}\n\n";

strgpu = strgpu * str * "\t\ti += blockDim.x * gridDim.x;\n";
strgpu = strgpu * "\t}\n" * "}\n\n";

return stropu, strgpu

end

max_stars_repo_name: rloekvh/Exasim

max_issues_repo_name: rloekvh/Exasim

max_forks_repo_name: rloekvh/Exasim


text:
# This file is part of JuliaFMI.
# Licensed under MIT: https://github.com/AnHeuermann/JuliaFMI/blob/master/LICENSE.txt

# This file contains functionalities to show simulation results of a FMU.

using Plots, CSV

function plotTests(csvfile::String)
    if !isfile(csvfile)
        error("File $csvfile does not exist.")
    end

    def = CSV.read(csvfile, delim=",")
    plotdatanames = names(def)
    plotlyjs()
    plt = plot()
    for i in 2:length(plotdatanames)
            plot!(def.time, def[Symbol(plotdatanames[i])], label=plotdatanames[i] )
    end
    gui(plt)
end

max_stars_repo_name: JKRT/JuliaFMI

max_issues_repo_name: JKRT/JuliaFMI

max_forks_repo_name: JKRT/JuliaFMI


text:
"""
    shift_fields!(layer, offset)

Adds `offset` to the `layer` fields.
"""
function shift_fields! end

function shift_fields!(
    layer::Union{Binary,Spin,Potts,Gaussian,ReLU,pReLU,xReLU}, offset::AbstractArray
)
    @assert size(layer) == size(offset)
    layer.θ .+= offset
    return layer
end

function shift_fields!(layer::dReLU, offset::AbstractArray)
    @assert size(layer) == size(offset)
    layer.θp .+= offset
    layer.θn .+= offset
    return layer
end


text:
using Test

import CryptoGroups
import CryptoGroups: generator, order, oncurve, FP, Weierstrass, BinaryCurve, F2PB, F2GNB, @def, specialize, <|, validate, ECPoint, AffinePoint, spec, Specs

const FULL_TEST = false

for C in [:P_192, :P_244, :P_256, :P_384, :P_521]

    spec = getfield(Specs, Symbol("Curve_$C"))

    P = specialize(ECPoint{AffinePoint{Weierstrass, FP}}, spec)

    g = P <| generator(spec)

    @test oncurve(g)
    @test oncurve(g*3)
    @test validate(g)

end

for C in [:B_163_PB, :B_233_PB, :B_283_PB, :B_409_PB, :B_571_PB, :K_163_PB, :K_233_PB, :K_283_PB, :K_409_PB, :K_571_PB]

    spec = getfield(Specs, Symbol("Curve_$C"))

    P = specialize(ECPoint{AffinePoint{BinaryCurve, F2PB}}, spec)

    g = P <| generator(spec)

    @test oncurve(g)
    @test oncurve(g*3)

    if C == :K_163_PB # Too slow to test all
        @test validate(g)
    end

end

for C in [:B_163_GNB, :B_233_GNB, :B_283_GNB, :B_409_GNB, :B_571_GNB, :K_163_GNB, :K_233_GNB, :K_283_GNB, :K_409_GNB, :K_571_GNB]

    spec = getfield(Specs, Symbol("Curve_$C"))

    P = specialize(ECPoint{AffinePoint{BinaryCurve, F2GNB}}, spec)

    g = P <| generator(spec)

    @test oncurve(g)
    @test oncurve(g*3)

end

### macro test

@def P_192 ECPoint{AffinePoint{Weierstrass, FP}} Specs.Curve_P_192

@test oncurve(P_192 <| generator(Specs.Curve_P_192))

@test spec(P_192 <| generator(Specs.Curve_P_192)) == Specs.Curve_P_192


text:
using Cobweb
using Cobweb: h, Page, Node
using Test

n1 = h.div("hi")
n2 = h("div", "hi")

#-----------------------------------------------------------------------------# Creating Nodes
@testset "Node Creation" begin
    for node in [
            h("div"),
            h.div(),
            h("div", "child"),
            h.div("child"),
            h.("p", "c1", "c2"),
            h.p("c1", "c2"),
            h.h1()."class"("c1", "c2")
        ]
        @test node isa Node
    end
    node = h.h1()."class"("c1", "c2")
    @test node.attrs["class"] == "class"
    @test length(node.children) == 2
    @test n1 == n2
end
#-----------------------------------------------------------------------------# HTML
@testset "HTML" begin
    @test repr(n1) == "
hi
"
end
#-----------------------------------------------------------------------------# Javascript
@testset "Javascript" begin
    @test repr("text/javascript", Cobweb.Javascript("x")) == "x"
end
#-----------------------------------------------------------------------------# Page
@testset "Page" begin
    page = Page(n1)
    @test Page(page) == page
    Cobweb.save(page)
    @test isfile(joinpath(Cobweb.DIR, "index.html"))

    Cobweb.save(page, "temp.html")
    @test isfile("temp.html")
    rm("temp.html", force=true)
end
#-----------------------------------------------------------------------------# escaping
@testset "escaping" begin
    chars = ['<', '>', ''', '"']
    for char in chars
        @test char ∉ Cobweb.escape_html(join(chars))
    end
    @test Cobweb.escape_html("&") != "&"
end
#-----------------------------------------------------------------------------# docs
@testset "Docs Build" begin
    include(joinpath(@__DIR__, "..", "docs", "make.jl"))
    @test isfile(joinpath(@__DIR__, "..", "docs", "build", "index.html"))
    rm(joinpath(@__DIR__, "..", "docs", "build"), recursive=true)
end


text:
using Test
using JustSayIt
using JustSayIt.API
using PyCall
import JustSayIt: DEFAULT_MODEL_NAME, TYPE_MODEL_NAME, MODELDIR_PREFIX, DEFAULT_NOISES, COMMAND_RECOGNIZER_ID
import JustSayIt: init_jsi, finalize_jsi, recognizer, noises, reader, start_reading, stop_reading, read_wav, set_default_streamer, reset_all, _are_next

# Test setup
const SAMPLEDIR_CMD     = joinpath("samples", "commands")
const SAMPLEDIR_SILENCE = joinpath("samples", "silence")

commands = Dict("help"      => Help.help,
                "type"      => Keyboard.type,
                "ma"        => Mouse.click_left,
                "select"    => Mouse.press_left,
                "okay"      => Mouse.release_left,
                "middle"    => Mouse.click_middle,
                "right"     => Mouse.click_right,
                "double"    => Mouse.click_double,
                "triple"    => Mouse.click_triple,
                "email"     => Email.email,
                "internet"  => Internet.internet,
                "copy"      => (Key.ctrl, 'c'),
                # "cut"       => (Key.ctrl, 'x'), # NOTE: this is used to test the handling of an unrecognised keyword.
                "paste"     => (Key.ctrl, 'v'),
                "undo"      => (Key.ctrl, 'z'),
                "redo"      => (Key.ctrl, Key.shift, 'z'),
                "page up"   => Key.page_up,
                "page down" => Key.page_down,
                );
modeldirs = Dict(DEFAULT_MODEL_NAME => joinpath(MODELDIR_PREFIX, "vosk-model-small-en-us-0.15"),
                 TYPE_MODEL_NAME    => joinpath(MODELDIR_PREFIX, "vosk-model-small-en-us-0.15"))
init_jsi(commands, modeldirs, DEFAULT_NOISES)

samples = Dict("help"      => read_wav(joinpath(SAMPLEDIR_CMD, "help.wav")),
               "type"      => read_wav(joinpath(SAMPLEDIR_CMD, "type.wav")),
               "ma"        => read_wav(joinpath(SAMPLEDIR_CMD, "ma.wav")),
               "select"    => read_wav(joinpath(SAMPLEDIR_CMD, "select.wav")),
               "okay"      => read_wav(joinpath(SAMPLEDIR_CMD, "okay.wav")),
               "middle"    => read_wav(joinpath(SAMPLEDIR_CMD, "middle.wav")),
               "right"     => read_wav(joinpath(SAMPLEDIR_CMD, "right.wav")),
               "double"    => read_wav(joinpath(SAMPLEDIR_CMD, "double.wav")),
               "triple"    => read_wav(joinpath(SAMPLEDIR_CMD, "triple.wav")),
               "email"     => read_wav(joinpath(SAMPLEDIR_CMD, "email.wav")),
               "internet"  => read_wav(joinpath(SAMPLEDIR_CMD, "internet.wav")),
               "copy"      => read_wav(joinpath(SAMPLEDIR_CMD, "copy.wav")),
               "cut"       => read_wav(joinpath(SAMPLEDIR_CMD, "cut.wav")),
               "paste"     => read_wav(joinpath(SAMPLEDIR_CMD, "paste.wav")),
               "undo"      => read_wav(joinpath(SAMPLEDIR_CMD, "undo.wav")),
               "redo"      => read_wav(joinpath(SAMPLEDIR_CMD, "redo.wav")),
               "page up"   => read_wav(joinpath(SAMPLEDIR_CMD, "page_up.wav")),
               "page down" => read_wav(joinpath(SAMPLEDIR_CMD, "page_down.wav")),
               );
sample_commands = read_wav(joinpath(SAMPLEDIR_CMD, "commands.wav"))
_2  = read_wav(joinpath(SAMPLEDIR_SILENCE, "silence_2001ms.wav"))

@testset "$(basename(@__FILE__))" begin
    @testset "1. print available commands as @info" begin
        id = "commands"
        start_reading([sample_commands; _2]; id=id)
        set_default_streamer(reader, id)
        @test_logs (:info,) Help.help()
        stop_reading(id=id)
    end;
    @testset "2. print specific command help as @info ($cmd)" for cmd in keys(commands)
        sample = samples[cmd]
        id     = cmd
        start_reading([sample; _2]; id=id)
        set_default_streamer(reader, id)
        _are_next(cmd, recognizer(COMMAND_RECOGNIZER_ID), noises(DEFAULT_MODEL_NAME); use_partial_recognitions=false, ignore_unknown=false) # NOTE: this full recognition call is required to have safe reproducable results in the following help call.
        @test_logs (:info,) Help.help()
        stop_reading(id=id)
    end;
    @testset "3. Keyword not recognized @info" begin
        id = "cut"
        start_reading([samples["cut"]; _2]; id=id)
        set_default_streamer(reader, id)
        @test_logs (:info,"Keyword not recognized.") Help.help()
        stop_reading(id=id)
    end;
    recognizer(COMMAND_RECOGNIZER_ID).Reset()
    reset_all(hard=true)
end;

# Test tear down
finalize_jsi()